Skip to content

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

refator: splitting big files based on responsibility

Luigi Agosti97c4a39a3804
diff --git a/cmd/pinchtab/cli_palette.go b/cmd/pinchtab/cli_palette.go
new file mode 100644
index 00000000..f7d29d62
--- /dev/null
+++ b/cmd/pinchtab/cli_palette.go
@@ -0,0 +1,47 @@
+package main
+
+import (
+ "os"
+
+ "github.com/charmbracelet/lipgloss"
+ "github.com/pinchtab/pinchtab/internal/cliui"
+)
+
+var (
+ pinchtabColorBorder = cliui.ColorBorder
+ pinchtabColorTextPrimary = cliui.ColorTextPrimary
+ pinchtabColorTextMuted = cliui.ColorTextMuted
+ pinchtabColorAccent = cliui.ColorAccent
+ pinchtabColorAccentLight = cliui.ColorAccentLight
+ pinchtabColorSuccess = cliui.ColorSuccess
+ pinchtabColorWarning = cliui.ColorWarning
+ pinchtabColorDanger = cliui.ColorDanger
+)
+
+var (
+ cliHeadingStyle = cliui.HeadingStyle
+ cliCommandStyle = cliui.CommandStyle
+ cliMutedStyle = cliui.MutedStyle
+ cliSuccessStyle = cliui.SuccessStyle
+ cliWarningStyle = cliui.WarningStyle
+ cliErrorStyle = cliui.ErrorStyle
+ cliValueStyle = cliui.ValueStyle
+)
+
+func renderToWriter(w *os.File, style lipgloss.Style, text string) string {
+ if w == os.Stdout {
+ return cliui.RenderStdout(style, text)
+ }
+ if w == os.Stderr {
+ return cliui.RenderStderr(style, text)
+ }
+ return style.Render(text)
+}
+
+func styleStdout(style lipgloss.Style, text string) string {
+ return renderToWriter(os.Stdout, style, text)
+}
+
+func styleStderr(style lipgloss.Style, text string) string {
+ return renderToWriter(os.Stderr, style, text)
+}
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 66a18215..398d0f9b 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -14,21 +14,314 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
)
+var quickCmd = &cobra.Command{
+ Use: "quick <url>",
+ Short: "Navigate + analyze page (beginner-friendly)",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliQuick(client, base, token, args)
+ })
+ },
+}
+
+var navCmd = &cobra.Command{
+ Use: "nav <url>",
+ Short: "Navigate to URL",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliNavigate(client, base, token, args)
+ })
+ },
+}
+
+var snapCmd = &cobra.Command{
+ Use: "snap",
+ Short: "Snapshot accessibility tree",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliSnapshot(client, base, token, args)
+ })
+ },
+}
+
+var clickCmd = &cobra.Command{
+ Use: "click <ref>",
+ Short: "Click element",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliTabOperation(client, base, token, "click", args)
+ })
+ },
+}
+
+var typeCmd = &cobra.Command{
+ Use: "type <ref> <text>",
+ Short: "Type into element",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliTabOperation(client, base, token, "type", args)
+ })
+ },
+}
+
+var screenshotCmd = &cobra.Command{
+ Use: "screenshot",
+ Short: "Take a screenshot",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliScreenshot(client, base, token, args)
+ })
+ },
+}
+
+var tabsCmd = &cobra.Command{
+ Use: "tabs",
+ Short: "List or manage tabs",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliTabs(client, base, token, args)
+ })
+ },
+}
+
+var instancesCmd = &cobra.Command{
+ Use: "instances",
+ Short: "List or manage instances",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliInstances(client, base, token)
+ })
+ },
+}
+
+var healthCmd = &cobra.Command{
+ Use: "health",
+ Short: "Check server health",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliHealth(client, base, token)
+ })
+ },
+}
+
+var pressCmd = &cobra.Command{
+ Use: "press <key>",
+ Short: "Press key (Enter, Tab, Escape...)",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliAction(client, base, token, "press", args)
+ })
+ },
+}
+
+var fillCmd = &cobra.Command{
+ Use: "fill <ref|selector> <text>",
+ Short: "Fill input directly",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliAction(client, base, token, "fill", args)
+ })
+ },
+}
+
+var hoverCmd = &cobra.Command{
+ Use: "hover <ref>",
+ Short: "Hover element",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliAction(client, base, token, "hover", args)
+ })
+ },
+}
+
+var scrollCmd = &cobra.Command{
+ Use: "scroll <ref|pixels>",
+ Short: "Scroll to element or by pixels",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliAction(client, base, token, "scroll", args)
+ })
+ },
+}
+
+var evalCmd = &cobra.Command{
+ Use: "eval <expression>",
+ Short: "Evaluate JavaScript",
+ Args: cobra.MinimumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliEvaluate(client, base, token, args)
+ })
+ },
+}
+
+var pdfCmd = &cobra.Command{
+ Use: "pdf",
+ Short: "Export the current page as PDF",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliPDF(client, base, token, args)
+ })
+ },
+}
+
+var textCmd = &cobra.Command{
+ Use: "text",
+ Short: "Extract page text",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliText(client, base, token, args)
+ })
+ },
+}
+
+var profilesCmd = &cobra.Command{
+ Use: "profiles",
+ Short: "List browser profiles",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliProfiles(client, base, token)
+ })
+ },
+}
+
+var instanceCmd = &cobra.Command{
+ Use: "instance",
+ Short: "Manage browser instances",
+}
+
+func init() {
+ rootCmd.AddCommand(quickCmd)
+ rootCmd.AddCommand(navCmd)
+ rootCmd.AddCommand(snapCmd)
+ rootCmd.AddCommand(clickCmd)
+ rootCmd.AddCommand(typeCmd)
+ rootCmd.AddCommand(screenshotCmd)
+ rootCmd.AddCommand(tabsCmd)
+ rootCmd.AddCommand(instancesCmd)
+ rootCmd.AddCommand(healthCmd)
+ rootCmd.AddCommand(pressCmd)
+ rootCmd.AddCommand(fillCmd)
+ rootCmd.AddCommand(hoverCmd)
+ rootCmd.AddCommand(scrollCmd)
+ rootCmd.AddCommand(evalCmd)
+ rootCmd.AddCommand(pdfCmd)
+ rootCmd.AddCommand(textCmd)
+ rootCmd.AddCommand(profilesCmd)
+
+ instanceCmd.AddCommand(&cobra.Command{
+ Use: "start <name>",
+ Short: "Start a browser instance",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliInstanceStart(client, base, token, args)
+ })
+ },
+ })
+ instanceCmd.AddCommand(&cobra.Command{
+ Use: "navigate <id> <url>",
+ Short: "Navigate an instance to a URL",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliInstanceNavigate(client, base, token, args)
+ })
+ },
+ })
+ instanceCmd.AddCommand(&cobra.Command{
+ Use: "stop <id>",
+ Short: "Stop a browser instance",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliInstanceStop(client, base, token, args)
+ })
+ },
+ })
+ instanceCmd.AddCommand(&cobra.Command{
+ Use: "logs <id>",
+ Short: "Get instance logs",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ cliInstanceLogs(client, base, token, args)
+ })
+ },
+ })
+ rootCmd.AddCommand(instanceCmd)
+}
+
+func runCLIWith(cfg *config.RuntimeConfig, fn func(client *http.Client, base, token string)) {
+ client := &http.Client{Timeout: 60 * time.Second}
+ dashPort := cfg.Port
+ if dashPort == "" {
+ dashPort = "9870"
+ }
+ base := fmt.Sprintf("http://localhost:%s", dashPort)
+ token := cfg.Token
+
+ fn(client, base, token)
+}
+
func printHelp() {
fmt.Printf(`pinchtab %s - Browser control for AI agents
-MODES:
- pinchtab Start full server (default)
+Usage:
+ pinchtab [command] [flags]
+
+Primary commands (most users start here):
+ pinchtab Start the full server (default: headed or headless via env)
+ -> Launches Chrome instances + HTTP API on http://localhost:9867
+ pinchtab onboard Guided interactive setup (recommended first run)
+ -> Configures profiles, daemon, stealth, and security defaults
+
+OTHER COMMANDS:
pinchtab server Start full server explicitly
pinchtab bridge Start single-instance bridge-only server
+<<<<<<< HEAD
pinchtab mcp Start MCP (Model Context Protocol) server on stdio
+=======
+ pinchtab daemon Manage the background service
+>>>>>>> 97fee9e (refator: splitting big files based on responsibility)
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)
+ pinchtab onboard --install-daemon Guided setup + install a user daemon
CLI COMMANDS:
pinchtab nav <url> Navigate to URL
@@ -435,9 +728,9 @@ func cliTabs(client *http.Client, base, token string, args []string) {
// Check if any instances are running
instances := getInstances(client, base, token)
if len(instances) == 0 {
- fmt.Fprintf(os.Stderr, "πŸ“ No instances running, launching default...\n")
+ fmt.Fprintln(os.Stderr, styleStderr(cliWarningStyle, "No instances running, launching default..."))
launchInstance(client, base, token, "default")
- fmt.Fprintf(os.Stderr, "βœ… Instance launched\n")
+ fmt.Fprintln(os.Stderr, styleStderr(cliSuccessStyle, "Instance launched"))
}
body := map[string]any{"action": "new"}
@@ -539,7 +832,7 @@ func cliTabOperation(client *http.Client, base, token string, op string, args []
}
if data != nil {
if err := os.WriteFile(outFile, data, 0600); err == nil {
- fmt.Printf("Saved %s (%d bytes)\n", outFile, len(data))
+ fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
}
@@ -761,7 +1054,7 @@ func cliScreenshot(client *http.Client, base, token string, args []string) {
if err := os.WriteFile(outFile, data, 0600); err != nil {
fatal("Write failed: %v", err)
}
- fmt.Printf("Saved %s (%d bytes)\n", outFile, len(data))
+ fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
// --- evaluate ---
@@ -890,7 +1183,7 @@ func cliPDF(client *http.Client, base, token string, args []string) {
if err := os.WriteFile(outFile, data, 0600); err != nil {
fatal("Write failed: %v", err)
}
- fmt.Printf("Saved %s (%d bytes)\n", outFile, len(data))
+ fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
// --- quick command ---
@@ -900,7 +1193,7 @@ func cliQuick(client *http.Client, base, token string, args []string) {
fatal("Usage: pinchtab quick <url>")
}
- fmt.Println("πŸ¦€ Navigating to", args[0], "...")
+ fmt.Println(styleStdout(cliHeadingStyle, fmt.Sprintf("Navigating to %s...", args[0])))
// Navigate
navBody := map[string]any{"url": args[0]}
@@ -909,7 +1202,8 @@ func cliQuick(client *http.Client, base, token string, args []string) {
// Small delay for page to stabilize
time.Sleep(1 * time.Second)
- fmt.Println("\nπŸ“‹ Page structure:")
+ fmt.Println()
+ fmt.Println(styleStdout(cliHeadingStyle, "Page structure"))
// Snapshot with interactive filter
snapParams := url.Values{}
@@ -919,17 +1213,19 @@ func cliQuick(client *http.Client, base, token string, args []string) {
// Extract info from navigation result
if title, ok := navResult["title"].(string); ok {
- fmt.Printf("\nπŸ“Œ Title: %s\n", title)
+ fmt.Println()
+ fmt.Printf("%s %s\n", styleStdout(cliMutedStyle, "Title:"), styleStdout(cliValueStyle, title))
}
if urlStr, ok := navResult["url"].(string); ok {
- fmt.Printf("πŸ”— URL: %s\n", urlStr)
+ fmt.Printf("%s %s\n", styleStdout(cliMutedStyle, "URL:"), styleStdout(cliValueStyle, urlStr))
}
- fmt.Println("\nπŸ’‘ Quick actions:")
- fmt.Println(" pinchtab click <ref> # Click an element (use refs from above)")
- fmt.Println(" pinchtab type <ref> <text> # Type into input field")
- fmt.Println(" pinchtab screenshot # Take a screenshot")
- fmt.Println(" pinchtab pdf --tab <id> -o output.pdf # Save tab as PDF")
+ fmt.Println()
+ fmt.Println(styleStdout(cliHeadingStyle, "Quick actions"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab click <ref>"), styleStdout(cliMutedStyle, "# Click an element (use refs from above)"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab type <ref> <text>"), styleStdout(cliMutedStyle, "# Type into input field"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab screenshot"), styleStdout(cliMutedStyle, "# Take a screenshot"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), styleStdout(cliMutedStyle, "# Save tab as PDF"))
}
// --- health ---
@@ -1138,7 +1434,7 @@ func doGet(client *http.Client, base, token, path string, params url.Values) map
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
- fmt.Fprintf(os.Stderr, "Error %d: %s\n", resp.StatusCode, string(body))
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(body))))
os.Exit(1)
}
@@ -1175,7 +1471,7 @@ func doGetRaw(client *http.Client, base, token, path string, params url.Values)
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
- fmt.Fprintf(os.Stderr, "Error %d: %s\n", resp.StatusCode, string(body))
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(body))))
os.Exit(1)
}
return body
@@ -1196,7 +1492,7 @@ func doPost(client *http.Client, base, token, path string, body map[string]any)
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
- fmt.Fprintf(os.Stderr, "Error %d: %s\n", resp.StatusCode, string(respBody))
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(respBody))))
os.Exit(1)
}
@@ -1225,34 +1521,33 @@ func checkServerAndGuide(client *http.Client, base, token string) bool {
resp, err := client.Do(req)
if err != nil {
if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial tcp") {
- fmt.Fprintf(os.Stderr, `❌ Pinchtab server is not running on %s
-
-To start the server:
- pinchtab # Run in foreground (recommended for beginners)
- pinchtab & # Run in background
- PINCHTAB_PORT=9868 pinchtab # Use different port
-
-Then try your command again:
- %s
-
-Learn more: https://github.com/pinchtab/pinchtab#quick-start
-`, base, strings.Join(os.Args, " "))
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Pinchtab server is not running on %s", base)))
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "To start the server"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab"), styleStderr(cliMutedStyle, "# Run in foreground (recommended for beginners)"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab &"), styleStderr(cliMutedStyle, "# Run in background"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "PINCHTAB_PORT=9868 pinchtab"), styleStderr(cliMutedStyle, "# Use different port"))
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "Then try your command again"))
+ fmt.Fprintf(os.Stderr, " %s\n", styleStderr(cliCommandStyle, strings.Join(os.Args, " ")))
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintf(os.Stderr, "%s %s\n", styleStderr(cliMutedStyle, "Learn more:"), styleStderr(cliCommandStyle, "https://github.com/pinchtab/pinchtab#quick-start"))
return false
}
// Other connection errors
- fmt.Fprintf(os.Stderr, "❌ Cannot connect to Pinchtab server: %v\n", err)
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Cannot connect to Pinchtab server: %v", err)))
return false
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == 401 {
- fmt.Fprintf(os.Stderr, "❌ Authentication required. Set PINCHTAB_TOKEN.\n")
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, "Authentication required. Set PINCHTAB_TOKEN."))
return false
}
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
- fmt.Fprintf(os.Stderr, "❌ Server error %d: %s\n", resp.StatusCode, string(body))
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Server error %d: %s", resp.StatusCode, string(body))))
return false
}
@@ -1263,31 +1558,34 @@ Learn more: https://github.com/pinchtab/pinchtab#quick-start
func suggestNextAction(cmd string, result map[string]any) {
switch cmd {
case "nav", "navigate":
- fmt.Fprintf(os.Stderr, "\nπŸ’‘ Next steps:\n")
- fmt.Fprintf(os.Stderr, " pinchtab snap # See page structure\n")
- fmt.Fprintf(os.Stderr, " pinchtab screenshot # Capture visual\n")
- fmt.Fprintf(os.Stderr, " pinchtab click <ref> # Click an element\n")
- fmt.Fprintf(os.Stderr, " pinchtab pdf --tab <id> -o output.pdf # Save tab as PDF\n")
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "Next steps"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab snap"), styleStderr(cliMutedStyle, "# See page structure"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab screenshot"), styleStderr(cliMutedStyle, "# Capture visual"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab click <ref>"), styleStderr(cliMutedStyle, "# Click an element"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), styleStderr(cliMutedStyle, "# Save tab as PDF"))
case "snap", "snapshot":
refs := extractRefs(result)
if len(refs) > 0 {
- fmt.Fprintf(os.Stderr, "\nπŸ’‘ Found %d interactive elements. Try:\n", len(refs))
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, fmt.Sprintf("Found %d interactive elements", len(refs))))
for i, ref := range refs[:min(3, len(refs))] {
- fmt.Fprintf(os.Stderr, " pinchtab click %s # %s\n", ref.id, ref.desc)
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, fmt.Sprintf("pinchtab click %s", ref.id)), styleStderr(cliMutedStyle, "# "+ref.desc))
if i >= 2 {
break
}
}
if len(refs) > 3 {
- fmt.Fprintf(os.Stderr, " ... and %d more\n", len(refs)-3)
+ fmt.Fprintf(os.Stderr, " %s\n", styleStderr(cliMutedStyle, fmt.Sprintf("... and %d more", len(refs)-3)))
}
}
case "click", "type", "fill":
- fmt.Fprintf(os.Stderr, "\nπŸ’‘ Action completed. To see results:\n")
- fmt.Fprintf(os.Stderr, " pinchtab snap # See updated page\n")
- fmt.Fprintf(os.Stderr, " pinchtab screenshot # Visual confirmation\n")
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "Action completed"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab snap"), styleStderr(cliMutedStyle, "# See updated page"))
+ fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab screenshot"), styleStderr(cliMutedStyle, "# Visual confirmation"))
}
}
@@ -1352,6 +1650,6 @@ func resolveInstanceBase(orchBase, token, instanceID, bind string) string {
}
func fatal(format string, args ...any) {
- fmt.Fprintf(os.Stderr, format+"\n", args...)
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf(format, args...)))
os.Exit(1)
}
diff --git a/cmd/pinchtab/cmd_connect.go b/cmd/pinchtab/cmd_connect.go
index 5651cb0a..04d0e9b1 100644
--- a/cmd/pinchtab/cmd_connect.go
+++ b/cmd/pinchtab/cmd_connect.go
@@ -9,6 +9,7 @@ import (
"os"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
)
type profileInstanceStatus struct {
@@ -20,37 +21,34 @@ type profileInstanceStatus struct {
Error string `json:"error"`
}
-func handleConnectCommand(cfg *config.RuntimeConfig) {
- profile := ""
- dashboardURL := os.Getenv("PINCHTAB_DASHBOARD_URL")
- jsonOut := false
+var connectCmd = &cobra.Command{
+ Use: "connect <profile>",
+ Short: "Get URL for a running profile",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ jsonOut, _ := cmd.Flags().GetBool("json")
+ dashboardURL, _ := cmd.Flags().GetString("dashboard")
+ handleConnectCommand(cfg, args[0], dashboardURL, jsonOut)
+ },
+}
- args := os.Args[2:]
- for i := 0; i < len(args); i++ {
- arg := args[i]
- switch arg {
- case "--json":
- jsonOut = true
- case "--dashboard":
- if i+1 >= len(args) {
- fmt.Fprintln(os.Stderr, "missing value for --dashboard")
- os.Exit(2)
- }
- i++
- dashboardURL = args[i]
- default:
- if profile == "" {
- profile = arg
- }
- }
- }
+func init() {
+ connectCmd.Flags().Bool("json", false, "Output as JSON")
+ connectCmd.Flags().String("dashboard", "", "Dashboard URL (e.g. http://localhost:9867)")
+ rootCmd.AddCommand(connectCmd)
+}
- if profile == "" {
- fmt.Fprintln(os.Stderr, "Usage: pinchtab connect <profile> [--dashboard http://localhost:9867] [--json]")
- os.Exit(2)
+func handleConnectCommand(cfg *config.RuntimeConfig, profile, dashboardURL string, jsonOut bool) {
+ if dashboardURL == "" {
+ dashboardURL = os.Getenv("PINCHTAB_DASHBOARD_URL")
}
if dashboardURL == "" {
- dashboardURL = "http://localhost:" + cfg.Port
+ dashPort := cfg.Port
+ if dashPort == "" {
+ dashPort = "9870"
+ }
+ dashboardURL = "http://localhost:" + dashPort
}
reqURL := stringsTrimRightSlash(dashboardURL) + "/profiles/" + url.PathEscape(profile) + "/instance"
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 03ac855c..8408c90c 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -22,6 +22,7 @@ import (
"github.com/pinchtab/pinchtab/internal/scheduler"
"github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
+ "github.com/spf13/cobra"
// Register strategies via init().
_ "github.com/pinchtab/pinchtab/internal/strategy/alwayson"
@@ -30,6 +31,29 @@ import (
_ "github.com/pinchtab/pinchtab/internal/strategy/simple"
)
+var serverCmd = &cobra.Command{
+ Use: "server",
+ Short: "Start full server explicitly",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runDashboard(cfg)
+ },
+}
+
+var bridgeCmd = &cobra.Command{
+ Use: "bridge",
+ Short: "Start single-instance bridge-only server",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runBridgeServer(cfg)
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(serverCmd)
+ rootCmd.AddCommand(bridgeCmd)
+}
+
// runDashboard starts a lightweight dashboard server β€” no Chrome, no bridge.
// It manages PinchTab instances via the orchestrator and serves the dashboard UI.
func runDashboard(cfg *config.RuntimeConfig) {
@@ -38,12 +62,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
dashPort = "9870"
}
startedAt := time.Now()
- 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 {
@@ -86,6 +104,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
// instance management and shorthand route registration. Otherwise fall back
// to the default manual route setup for backward compatibility.
var activeStrategy strategy.Strategy
+ stratName := "manual"
if cfg.Strategy != "" {
strat, err := strategy.New(cfg.Strategy)
if err != nil {
@@ -100,10 +119,32 @@ func runDashboard(cfg *config.RuntimeConfig) {
}
strat.RegisterRoutes(mux)
activeStrategy = strat
- slog.Info("strategy activated", "strategy", strat.Name())
+ stratName = strat.Name()
}
}
+ allocPolicy := cfg.AllocationPolicy
+ if allocPolicy == "" {
+ allocPolicy = "none"
+ }
+
+ printStartupBanner(cfg, startupBannerOptions{
+ Mode: "server",
+ ListenAddr: cfg.Bind + ":" + dashPort,
+ PublicURL: fmt.Sprintf("http://localhost:%s", dashPort),
+ Strategy: stratName,
+ Allocation: allocPolicy,
+ })
+
+ if IsDaemonRunning() && checkPinchTabRunning(dashPort, cfg.Token) {
+ fmt.Println(styleStdout(cliWarningStyle, fmt.Sprintf(" pinchtab already running as a daemon on port %s", dashPort)))
+ fmt.Println(styleStdout(cliMutedStyle, " Stop the daemon first with `pinchtab daemon stop` to run in the foreground."))
+ fmt.Println()
+ os.Exit(0)
+ }
+
+ slog.Info("orchestration", "strategy", stratName, "allocation", allocPolicy)
+
// If no strategy handled route registration, register default routes.
if activeStrategy == nil {
orch.RegisterHandlers(mux)
@@ -162,9 +203,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
IdleTimeout: 120 * time.Second,
}
- // Start strategy lifecycle if active. For strategies like simple-autorestart,
- // Start() launches the initial instance and begins crash monitoring.
- // When a strategy handles auto-launch, skip the manual auto-launch below.
+ // Start strategy lifecycle if active.
strategyHandlesLaunch := false
if activeStrategy != nil {
if err := activeStrategy.Start(context.Background()); err != nil {
@@ -185,8 +224,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
go func() {
time.Sleep(500 * time.Millisecond)
profileToLaunch := defaultProfile
- // If profile is not explicitly configured, prefer an existing profile.
- // Only synthesize "default" when nothing exists yet.
if !defaultProfileExplicit {
list, err := profMgr.List()
if err != nil {
@@ -252,49 +289,26 @@ func runDashboard(cfg *config.RuntimeConfig) {
os.Exit(130)
}()
- // Periodic health check: log tabs and Chrome process info every 30 seconds
- go periodicHealthCheck(orch)
-
+ slog.Info("dashboard started", "port", dashPort)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
slog.Error("server", "err", err)
os.Exit(1)
}
}
-// periodicHealthCheck logs instance and Chrome process status every 30 seconds
-func periodicHealthCheck(orch *orchestrator.Orchestrator) {
- ticker := time.NewTicker(30 * time.Second)
- defer ticker.Stop()
-
- for range ticker.C {
- // Get instance information
- instances := orch.List()
- if len(instances) == 0 {
- continue // No instances running, skip logging
- }
-
- // Count instances by headedness
- headedCount := 0
- headlessCount := 0
-
- for _, inst := range instances {
- if inst.Headless {
- headlessCount++
- } else {
- headedCount++
- }
- }
-
- // Get tabs across all instances
- allTabs := orch.AllTabs()
-
- slog.Info("health check",
- "instances", len(instances),
- "headed", headedCount,
- "headless", headlessCount,
- "total_tabs", len(allTabs),
- )
+func checkPinchTabRunning(port, token string) bool {
+ client := &http.Client{Timeout: 500 * time.Millisecond}
+ url := fmt.Sprintf("http://localhost:%s/health", port)
+ req, _ := http.NewRequest("GET", url, nil)
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return false
}
+ defer resp.Body.Close()
+ return resp.StatusCode == 200
}
// registerDefaultProxyRoutes adds the default shorthand proxy routes
diff --git a/cmd/pinchtab/cmd_onboard.go b/cmd/pinchtab/cmd_onboard.go
new file mode 100644
index 00000000..7ae6bbd7
--- /dev/null
+++ b/cmd/pinchtab/cmd_onboard.go
@@ -0,0 +1,1220 @@
+package main
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "os/user"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+
+ "github.com/charmbracelet/huh"
+ "github.com/charmbracelet/lipgloss"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
+)
+
+const (
+ pinchtabDaemonUnitName = "pinchtab.service"
+ pinchtabLaunchdLabel = "com.pinchtab.pinchtab"
+)
+
+type onboardOptions struct {
+ force bool
+ installDaemon bool
+}
+
+type onboardConfigStatus string
+
+const (
+ onboardConfigCreated onboardConfigStatus = "created"
+ onboardConfigRecovered onboardConfigStatus = "recovered"
+ onboardConfigVerified onboardConfigStatus = "verified"
+)
+
+type commandRunner interface {
+ CombinedOutput(name string, args ...string) ([]byte, error)
+}
+
+type osCommandRunner struct{}
+
+func (osCommandRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
+ return exec.Command(name, args...).CombinedOutput()
+}
+
+type daemonEnvironment struct {
+ execPath string
+ homeDir string
+ osName string
+ userID string
+ xdgConfigHome string
+}
+
+type daemonManager interface {
+ Install(execPath, configPath string) (string, error)
+ ServicePath() string
+ Start() (string, error)
+ Restart() (string, error)
+ Status() (string, error)
+ Stop() (string, error)
+ Uninstall() (string, error)
+ ManualInstructions() string
+ Pid() (string, error)
+ Logs(n int) (string, error)
+}
+
+type systemdUserManager struct {
+ env daemonEnvironment
+ runner commandRunner
+}
+
+type launchdManager struct {
+ env daemonEnvironment
+ runner commandRunner
+}
+
+var onboardCmd = &cobra.Command{
+ Use: "onboard",
+ Short: "Guided interactive setup (recommended first run)",
+ Long: "Step-by-step setup to configure your profiles, security defaults, and background service.",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ force, _ := cmd.Flags().GetBool("force")
+ installDaemonOpt, _ := cmd.Flags().GetBool("install-daemon")
+ handleOnboardCommand(cfg, force, installDaemonOpt)
+ },
+}
+
+var daemonCmd = &cobra.Command{
+ Use: "daemon [action]",
+ Short: "Manage the background service",
+ Long: "Start, stop, install, or check the status of the PinchTab background service.",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ sub := ""
+ if len(args) > 0 {
+ sub = args[0]
+ }
+ handleDaemonCommand(cfg, sub)
+ },
+}
+
+func init() {
+ onboardCmd.Flags().Bool("install-daemon", false, "Install and start a user-level background service")
+ onboardCmd.Flags().Bool("force", false, "Replace the existing config with fresh secure defaults")
+ rootCmd.AddCommand(onboardCmd)
+ rootCmd.AddCommand(daemonCmd)
+}
+
+func handleOnboardCommand(_ *config.RuntimeConfig, force bool, installDaemonOpt bool) {
+ configPath, effectiveCfg, configStatus, err := ensureOnboardConfig(force)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "onboard failed: %v\n", err)
+ os.Exit(1)
+ }
+
+ if isInteractiveTerminal() {
+ if err := runInteractiveOnboard(configPath, effectiveCfg, configStatus, installDaemonOpt); err != nil {
+ fmt.Fprintf(os.Stderr, "onboard failed: %v\n", err)
+ os.Exit(1)
+ }
+ return
+ }
+
+ if installDaemonOpt {
+ if _, err := installDaemon(configPath); err != nil {
+ fmt.Fprintf(os.Stderr, "daemon install failed: %v\n", err)
+ os.Exit(1)
+ }
+ }
+
+ fmt.Print(renderOnboardGuide(configPath, effectiveCfg, configStatus, installDaemonOpt))
+}
+
+func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
+ if subcommand == "" || subcommand == "help" || subcommand == "--help" || subcommand == "-h" {
+ printDaemonStatusSummary()
+
+ if subcommand == "" && isInteractiveTerminal() {
+ var picked string
+ err := huh.NewSelect[string]().
+ Title("Daemon Actions").
+ Options(
+ huh.NewOption("Start service", "start"),
+ huh.NewOption("Stop service", "stop"),
+ huh.NewOption("Restart service", "restart"),
+ huh.NewOption("Install service", "install"),
+ huh.NewOption("Uninstall service", "uninstall"),
+ huh.NewOption("Exit", "exit"),
+ ).
+ Value(&picked).
+ WithTheme(pinchtabOnboardTheme()).
+ Run()
+
+ if err != nil || picked == "exit" || picked == "" {
+ os.Exit(0)
+ }
+ subcommand = picked
+ } else {
+ daemonUsage()
+ if subcommand == "" {
+ os.Exit(0)
+ }
+ return
+ }
+ }
+
+ manager, err := currentDaemonManager()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+
+ switch subcommand {
+ case "install":
+ configPath, _, _, err := ensureOnboardConfig(false)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ os.Exit(1)
+ }
+ message, err := manager.Install(managerEnvironment(manager).execPath, configPath)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ fmt.Println()
+ fmt.Println(manager.ManualInstructions())
+ os.Exit(1)
+ }
+ fmt.Println(styleStdout(cliSuccessStyle, " [ok] ") + message)
+ printDaemonFollowUp()
+ case "start":
+ printDaemonManagerResult(manager.Start())
+ case "restart":
+ printDaemonManagerResult(manager.Restart())
+ case "stop":
+ printDaemonManagerResult(manager.Stop())
+ case "uninstall":
+ message, err := manager.Uninstall()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, err.Error()))
+ fmt.Println()
+ fmt.Println(manager.ManualInstructions())
+ os.Exit(1)
+ }
+ fmt.Println(styleStdout(cliSuccessStyle, " [ok] ") + message)
+ default:
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))
+ daemonUsage()
+ os.Exit(2)
+ }
+}
+
+func daemonUsage() {
+ fmt.Println(styleStdout(cliHeadingStyle, "Usage:") + " " + styleStdout(cliCommandStyle, "pinchtab daemon <install|start|restart|stop|uninstall>"))
+ fmt.Println()
+ fmt.Println(styleStdout(cliMutedStyle, "Manage the PinchTab user-level background service."))
+ fmt.Println()
+}
+
+func printDaemonStatusSummary() {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ fmt.Println(styleStdout(cliErrorStyle, " Error: ")+err.Error())
+ return
+ }
+
+ installed := IsDaemonInstalled()
+ running := IsDaemonRunning()
+
+ fmt.Println(styleStdout(cliHeadingStyle, "Daemon status:"))
+
+ status := styleStdout(cliWarningStyle, "not installed")
+ if installed {
+ status = styleStdout(cliSuccessStyle, "installed")
+ }
+ fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "Service:"), status)
+
+ state := styleStdout(cliMutedStyle, "stopped")
+ if running {
+ state = styleStdout(cliSuccessStyle, "active (running)")
+ }
+ fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "State:"), state)
+
+ if running {
+ pid, _ := manager.Pid()
+ if pid != "" {
+ fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "PID:"), styleStdout(cliValueStyle, pid))
+ }
+ }
+
+ if installed {
+ fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "Path:"), styleStdout(cliValueStyle, manager.ServicePath()))
+ }
+
+ if installed {
+ logs, err := manager.Logs(5)
+ if err == nil && strings.TrimSpace(logs) != "" {
+ fmt.Println()
+ fmt.Println(styleStdout(cliHeadingStyle, "Recent logs:"))
+ lines := strings.Split(logs, "\n")
+ for _, line := range lines {
+ if strings.TrimSpace(line) != "" {
+ fmt.Printf(" %s\n", styleStdout(cliMutedStyle, line))
+ }
+ }
+ }
+ }
+ fmt.Println()
+}
+
+func printDaemonManagerResult(message string, err error) {
+ if err != nil {
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+ if strings.HasPrefix(message, "Installed") || strings.HasPrefix(message, "Pinchtab daemon") {
+ fmt.Println(styleStdout(cliSuccessStyle, " [ok] ") + message)
+ } else {
+ // For status, it might be a block of text
+ fmt.Println(message)
+ }
+}
+
+func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConfigStatus, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return "", nil, "", err
+ }
+
+ exists := fileExists(configPath)
+ status := onboardConfigVerified
+ if !exists || force {
+ defaults := config.DefaultFileConfig()
+ token, err := config.GenerateAuthToken()
+ if err != nil {
+ return "", nil, "", err
+ }
+ defaults.Server.Token = token
+ if err := config.SaveFileConfig(&defaults, configPath); err != nil {
+ return "", nil, "", err
+ }
+ status = onboardConfigCreated
+ } else {
+ before := securityDefaultsSnapshot(fc)
+ applyRecommendedSecurityDefaults(fc)
+ after := securityDefaultsSnapshot(fc)
+ if !reflect.DeepEqual(before, after) {
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return "", nil, "", err
+ }
+ status = onboardConfigRecovered
+ }
+ }
+
+ effectiveCfg := config.Load()
+ return configPath, effectiveCfg, status, nil
+}
+
+func renderOnboardGuide(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemon bool) string {
+ var out bytes.Buffer
+ totalSteps := 6
+ if installDaemon {
+ totalSteps = 7
+ }
+
+ fmt.Fprintf(&out, "%s\n\n", renderOnboardTitle())
+ out.WriteString(renderOnboardConfigStep(1, totalSteps, configPath, configStatus))
+ out.WriteString(renderOnboardAPIAccessStep(2, totalSteps, cfg))
+ out.WriteString(renderOnboardSensitiveStep(3, totalSteps, cfg))
+ out.WriteString(renderOnboardAttachStep(4, totalSteps, cfg))
+ out.WriteString(renderOnboardIDPIStep(5, totalSteps, cfg))
+
+ if installDaemon {
+ out.WriteString(renderOnboardDaemonStep(6, totalSteps, true))
+ out.WriteString(renderOnboardNextStep(7, totalSteps, true))
+ return out.String()
+ }
+ out.WriteString(renderOnboardNextStep(6, totalSteps, false))
+ return out.String()
+}
+
+func writeSecurityToggle(out *bytes.Buffer, key string, enabled bool, description string) {
+ writeOnboardKV(out, key, fmt.Sprintf("%t", enabled))
+ if enabled {
+ writeOnboardWarning(out, "Enabled: this exposes %s to any authenticated caller.", description)
+ return
+ }
+ writeOnboardMessage(out, true, "Disabled by default: this keeps %s off until you intentionally opt in.", description)
+}
+
+func summarizeToken(token string) string {
+ token = strings.TrimSpace(token)
+ if token == "" {
+ return "<empty>"
+ }
+ if len(token) <= 8 {
+ return "<set>"
+ }
+ return token[:4] + "..." + token[len(token)-4:]
+}
+
+func formatStringSlice(values []string) string {
+ if len(values) == 0 {
+ return "<empty>"
+ }
+ return strings.Join(values, ", ")
+}
+
+func installDaemon(configPath string) (daemonManager, error) {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ return nil, err
+ }
+ message, err := manager.Install(managerEnvironment(manager).execPath, configPath)
+ if err != nil {
+ return nil, err
+ }
+ fmt.Println(message)
+ printDaemonFollowUp()
+ return manager, nil
+}
+
+func runInteractiveOnboard(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemonRequested bool) error {
+ totalSteps := 6
+ if installDaemonRequested {
+ totalSteps = 7
+ }
+
+ installDaemonChoice := installDaemonRequested
+ runtimeMode := "manual"
+ if installDaemonChoice {
+ runtimeMode = "daemon"
+ }
+ selectedSensitiveCaps := enabledSensitiveCapabilityKeys(cfg)
+
+ groups := []*huh.Group{
+ huh.NewGroup(
+ huh.NewNote().
+ Title("Config").
+ Description(onboardConfigSummary(configPath, configStatus)).
+ Next(true).
+ NextLabel("Continue"),
+ ).Title(fmt.Sprintf("Step 1/%d", totalSteps)).Description("Config and recovery"),
+ huh.NewGroup(
+ huh.NewNote().
+ Title("API access").
+ Description(onboardAPIAccessSummary(cfg)).
+ Next(true).
+ NextLabel("Continue"),
+ ).Title(fmt.Sprintf("Step 2/%d", totalSteps)).Description("Bind and token"),
+ huh.NewGroup(
+ huh.NewMultiSelect[string]().
+ Title("Opt in sensitive capabilities").
+ Description("Leave everything unselected for the recommended default. Select only what you intentionally want to expose.").
+ Options(
+ huh.NewOption("evaluate", "evaluate").Selected(cfg.AllowEvaluate),
+ huh.NewOption("macro", "macro").Selected(cfg.AllowMacro),
+ huh.NewOption("screencast", "screencast").Selected(cfg.AllowScreencast),
+ huh.NewOption("download", "download").Selected(cfg.AllowDownload),
+ huh.NewOption("upload", "upload").Selected(cfg.AllowUpload),
+ ).
+ Value(&selectedSensitiveCaps).
+ Filtering(false).
+ Height(8),
+ huh.NewNote().
+ Description("These are high-risk endpoint families. If enabled, any authenticated caller can use them.").
+ Next(true).
+ NextLabel("Continue"),
+ ).Title(fmt.Sprintf("Step 3/%d", totalSteps)).Description("High-risk endpoint families"),
+ huh.NewGroup(
+ huh.NewNote().
+ Title("Attach policy").
+ Description(onboardAttachSummary(cfg)).
+ Next(true).
+ NextLabel("Continue"),
+ ).Title(fmt.Sprintf("Step 4/%d", totalSteps)).Description("External Chrome attach controls"),
+ huh.NewGroup(
+ huh.NewNote().
+ Title("IDPI protections").
+ Description(onboardIDPISummary(cfg)).
+ Next(true).
+ NextLabel("Continue"),
+ ).Title(fmt.Sprintf("Step 5/%d", totalSteps)).Description("Indirect prompt-injection defense"),
+ }
+
+ modeStep := 6
+
+ modeOptions := []huh.Option[string]{
+ huh.NewOption("Install background service (recommended)", "daemon"),
+ huh.NewOption("Start it manually when needed", "manual"),
+ }
+ groups = append(groups, huh.NewGroup(
+ huh.NewSelect[string]().
+ Title("How should PinchTab run?").
+ Description("Choose whether onboarding should install a persistent user-level service.").
+ Options(modeOptions...).
+ Value(&runtimeMode),
+ huh.NewNote().
+ Title("Background service").
+ Description("Daemon mode installs PinchTab once and gives you `pinchtab daemon status/start/restart/stop/uninstall`. Manual mode leaves startup under your control.").
+ Next(true).
+ NextLabel("Finish wizard"),
+ ).Title(fmt.Sprintf("Step %d/%d", modeStep, totalSteps)).Description("Runtime mode"))
+
+ form := huh.NewForm(groups...).WithTheme(pinchtabOnboardTheme()).WithWidth(68)
+ if err := form.Run(); err != nil {
+ if errors.Is(err, huh.ErrUserAborted) {
+ fmt.Println("Onboarding stopped at your request.")
+ return nil
+ }
+ return err
+ }
+
+ if err := saveSelectedSensitiveCapabilities(configPath, selectedSensitiveCaps); err != nil {
+ return err
+ }
+
+ installDaemonChoice = runtimeMode == "daemon"
+ if installDaemonChoice {
+ if _, err := installDaemon(configPath); err != nil {
+ return err
+ }
+ fmt.Println()
+ fmt.Print(renderOnboardDaemonStep(modeStep, totalSteps, true))
+ fmt.Print(renderOnboardNextStep(0, 0, true))
+ return nil
+ }
+
+ fmt.Println()
+ fmt.Print(renderOnboardNextStep(0, 0, false))
+ return nil
+}
+
+func onboardConfigSummary(configPath string, configStatus onboardConfigStatus) string {
+ lines := []string{}
+ switch configStatus {
+ case onboardConfigCreated:
+ lines = append(lines, "Created secure default config.")
+ case onboardConfigRecovered:
+ lines = append(lines, "Recovered secure baseline.")
+ lines = append(lines, "Preserved browser, profile, port, and timeout settings.")
+ default:
+ lines = append(lines, "Secure defaults already in place.")
+ }
+ lines = append(lines, "")
+ lines = append(lines, fmt.Sprintf("Path %s", configPath))
+ lines = append(lines, "Override `PINCHTAB_CONFIG`")
+ return strings.Join(lines, "\n")
+}
+
+func onboardAPIAccessSummary(cfg *config.RuntimeConfig) string {
+ return strings.Join([]string{
+ onboardFact("server.bind", cfg.Bind, "local-only API access when set to 127.0.0.1"),
+ "",
+ onboardFact("server.token", summarizeToken(cfg.Token), "required for API and CLI auth"),
+ }, "\n")
+}
+
+func onboardSensitiveSummary(cfg *config.RuntimeConfig) string {
+ lines := []string{
+ onboardToggleSummary("security.allowEvaluate", cfg.AllowEvaluate, "JavaScript execution in the page context"),
+ onboardToggleSummary("security.allowMacro", cfg.AllowMacro, "higher-level macro automation routes"),
+ onboardToggleSummary("security.allowScreencast", cfg.AllowScreencast, "live page streaming output"),
+ onboardToggleSummary("security.allowDownload", cfg.AllowDownload, "server-side download endpoints"),
+ onboardToggleSummary("security.allowUpload", cfg.AllowUpload, "uploading local files through browser flows"),
+ }
+ return strings.Join(lines, "\n\n")
+}
+
+func enabledSensitiveCapabilityKeys(cfg *config.RuntimeConfig) []string {
+ if cfg == nil {
+ return nil
+ }
+ keys := make([]string, 0, 5)
+ if cfg.AllowEvaluate {
+ keys = append(keys, "evaluate")
+ }
+ if cfg.AllowMacro {
+ keys = append(keys, "macro")
+ }
+ if cfg.AllowScreencast {
+ keys = append(keys, "screencast")
+ }
+ if cfg.AllowDownload {
+ keys = append(keys, "download")
+ }
+ if cfg.AllowUpload {
+ keys = append(keys, "upload")
+ }
+ return keys
+}
+
+func saveSelectedSensitiveCapabilities(configPath string, selected []string) error {
+ fc, _, err := config.LoadFileConfig()
+ if err != nil {
+ return err
+ }
+
+ has := make(map[string]bool, len(selected))
+ for _, item := range selected {
+ has[item] = true
+ }
+
+ fc.Security.AllowEvaluate = boolPtr(has["evaluate"])
+ fc.Security.AllowMacro = boolPtr(has["macro"])
+ fc.Security.AllowScreencast = boolPtr(has["screencast"])
+ fc.Security.AllowDownload = boolPtr(has["download"])
+ fc.Security.AllowUpload = boolPtr(has["upload"])
+
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return err
+ }
+ return nil
+}
+
+func boolPtr(v bool) *bool {
+ return &v
+}
+
+func onboardAttachSummary(cfg *config.RuntimeConfig) string {
+ return strings.Join([]string{
+ onboardFact("attach.enabled", fmt.Sprintf("%t", cfg.AttachEnabled), "keep off unless external Chrome attach is intentional"),
+ "",
+ onboardFact("attach.hosts", strings.Join(cfg.AttachAllowHosts, ", "), "limits attach targets to trusted hosts"),
+ "",
+ onboardFact("attach.schemes", strings.Join(cfg.AttachAllowSchemes, ", "), "websocket-only transport"),
+ }, "\n")
+}
+
+func onboardIDPISummary(cfg *config.RuntimeConfig) string {
+ return strings.Join([]string{
+ onboardFact("idpi.enabled", fmt.Sprintf("%t", cfg.IDPI.Enabled), "turns on indirect prompt-injection defense"),
+ "",
+ onboardFact("idpi.domains", formatStringSlice(cfg.IDPI.AllowedDomains), "trusted domains for the local-default setup"),
+ "",
+ onboardFact("idpi.strictMode", fmt.Sprintf("%t", cfg.IDPI.StrictMode), "blocks suspicious content instead of warning only"),
+ "",
+ onboardFact("idpi.scanContent", fmt.Sprintf("%t", cfg.IDPI.ScanContent), "scans /text and /snapshot output"),
+ "",
+ onboardFact("idpi.wrapContent", fmt.Sprintf("%t", cfg.IDPI.WrapContent), "marks extracted content as untrusted data"),
+ }, "\n")
+}
+
+func onboardToggleSummary(key string, enabled bool, description string) string {
+ if enabled {
+ return onboardFact(key, "true", "exposes "+description+" to any authenticated caller")
+ }
+ return onboardFact(key, "false", "disabled by default until you explicitly opt in")
+}
+
+func onboardFact(key, value, detail string) string {
+ return fmt.Sprintf("%-18s %s\n - %s", key, value, detail)
+}
+
+func IsDaemonInstalled() bool {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ return false
+ }
+ _, err = os.Stat(manager.ServicePath())
+ return err == nil
+}
+
+func IsDaemonRunning() bool {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ return false
+ }
+ status, err := manager.Status()
+ if err != nil {
+ return false
+ }
+ // Simple string checks for common "running" indicators
+ return strings.Contains(status, "state = running") || // launchd
+ strings.Contains(status, "Active: active (running)") // systemd
+}
+
+func pinchtabOnboardTheme() *huh.Theme {
+ t := huh.ThemeBase()
+
+ textPrimary := pinchtabColorTextPrimary
+ textSecondary := lipgloss.Color("#94a3b8")
+ textMuted := pinchtabColorTextMuted
+ accent := pinchtabColorAccent
+ accentLight := pinchtabColorAccentLight
+ success := pinchtabColorSuccess
+ warning := pinchtabColorWarning
+ destructive := pinchtabColorDanger
+
+ t.Form.Base = lipgloss.NewStyle().
+ Foreground(textPrimary).
+ Padding(0, 0)
+
+ t.Group.Base = lipgloss.NewStyle().Foreground(textPrimary)
+ t.Group.Title = lipgloss.NewStyle().
+ Foreground(accent).
+ Bold(true)
+ t.Group.Description = lipgloss.NewStyle().
+ Foreground(textMuted)
+
+ t.FieldSeparator = lipgloss.NewStyle().SetString("\n")
+
+ t.Focused.Base = lipgloss.NewStyle().
+ BorderStyle(lipgloss.NormalBorder()).
+ BorderForeground(pinchtabColorBorder).
+ BorderLeft(true).
+ PaddingLeft(1)
+ t.Focused.Card = t.Focused.Base
+ t.Focused.Title = lipgloss.NewStyle().Foreground(accent).Bold(true)
+ t.Focused.NoteTitle = lipgloss.NewStyle().
+ Foreground(accentLight).
+ Bold(true)
+ t.Focused.Description = lipgloss.NewStyle().Foreground(textPrimary)
+ t.Focused.ErrorIndicator = lipgloss.NewStyle().Foreground(destructive)
+ t.Focused.ErrorMessage = lipgloss.NewStyle().Foreground(destructive)
+ t.Focused.SelectSelector = lipgloss.NewStyle().Foreground(accentLight).SetString("> ")
+ t.Focused.Option = lipgloss.NewStyle().Foreground(textPrimary)
+ t.Focused.SelectedOption = lipgloss.NewStyle().Foreground(success).Bold(true)
+ t.Focused.SelectedPrefix = lipgloss.NewStyle().Foreground(success).SetString("βœ“ ")
+ t.Focused.UnselectedOption = lipgloss.NewStyle().Foreground(textSecondary)
+ t.Focused.UnselectedPrefix = lipgloss.NewStyle().Foreground(textMuted).SetString("β€’ ")
+ t.Focused.NextIndicator = lipgloss.NewStyle().Foreground(accentLight).SetString("β†’")
+ t.Focused.PrevIndicator = lipgloss.NewStyle().Foreground(accentLight).SetString("←")
+ t.Focused.FocusedButton = lipgloss.NewStyle().
+ Foreground(accentLight).
+ Bold(true).
+ Underline(true)
+ t.Focused.BlurredButton = lipgloss.NewStyle().
+ Foreground(textSecondary).
+ Padding(0, 0)
+ t.Focused.Next = lipgloss.NewStyle().
+ Foreground(accentLight).
+ Bold(true).
+ Underline(true)
+ t.Focused.TextInput.Cursor = lipgloss.NewStyle().Foreground(accentLight)
+ t.Focused.TextInput.CursorText = lipgloss.NewStyle().Foreground(textPrimary)
+ t.Focused.TextInput.Placeholder = lipgloss.NewStyle().Foreground(textMuted)
+ t.Focused.TextInput.Prompt = lipgloss.NewStyle().Foreground(accentLight)
+ t.Focused.TextInput.Text = lipgloss.NewStyle().Foreground(textPrimary)
+
+ t.Blurred = t.Focused
+ t.Blurred.Base = lipgloss.NewStyle().
+ BorderStyle(lipgloss.HiddenBorder()).
+ PaddingLeft(1)
+ t.Blurred.Card = t.Blurred.Base
+ t.Blurred.Title = lipgloss.NewStyle().Foreground(textSecondary)
+ t.Blurred.NoteTitle = lipgloss.NewStyle().Foreground(textSecondary).Bold(true)
+ t.Blurred.Description = lipgloss.NewStyle().Foreground(textSecondary)
+ t.Blurred.Option = lipgloss.NewStyle().Foreground(textSecondary)
+ t.Blurred.SelectedOption = lipgloss.NewStyle().Foreground(success)
+ t.Blurred.UnselectedOption = lipgloss.NewStyle().Foreground(textMuted)
+ t.Blurred.NextIndicator = lipgloss.NewStyle().Foreground(warning)
+ t.Blurred.PrevIndicator = lipgloss.NewStyle().Foreground(warning)
+
+ return t
+}
+
+func renderOnboardConfigStep(step, total int, configPath string, configStatus onboardConfigStatus) string {
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Config"))
+ switch configStatus {
+ case onboardConfigCreated:
+ writeOnboardMessage(&out, true, "Wrote a default config to %s.", configPath)
+ case onboardConfigRecovered:
+ writeOnboardWarning(&out, "Recovered the secure baseline in %s.", configPath)
+ writeOnboardNote(&out, "Existing browser, profile, port, and timeout settings were preserved.")
+ default:
+ writeOnboardMessage(&out, true, "Verified the existing config at %s.", configPath)
+ writeOnboardNote(&out, "Recovery defaults were already in place.")
+ }
+ writeOnboardNote(&out, "PinchTab will read this file unless `PINCHTAB_CONFIG` overrides it.")
+ out.WriteString("\n")
+ return out.String()
+}
+
+func renderOnboardAPIAccessStep(step, total int, cfg *config.RuntimeConfig) string {
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "API access"))
+ writeOnboardKV(&out, "server.bind", cfg.Bind)
+ writeOnboardNote(&out, "Keeps the API local to this machine when set to 127.0.0.1.")
+ writeOnboardKV(&out, "server.token", summarizeToken(cfg.Token))
+ writeOnboardNote(&out, "A bearer token gates every API request and CLI call that reaches the server.")
+ out.WriteString("\n")
+ return out.String()
+}
+
+func renderOnboardSensitiveStep(step, total int, cfg *config.RuntimeConfig) string {
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Sensitive capabilities"))
+ writeSecurityToggle(&out, "security.allowEvaluate", cfg.AllowEvaluate, "JavaScript execution in the page context")
+ writeSecurityToggle(&out, "security.allowMacro", cfg.AllowMacro, "higher-level macro automation routes")
+ writeSecurityToggle(&out, "security.allowScreencast", cfg.AllowScreencast, "live page streaming output")
+ writeSecurityToggle(&out, "security.allowDownload", cfg.AllowDownload, "server-side download endpoints")
+ writeSecurityToggle(&out, "security.allowUpload", cfg.AllowUpload, "uploading local files through browser flows")
+ out.WriteString("\n")
+ return out.String()
+}
+
+func renderOnboardAttachStep(step, total int, cfg *config.RuntimeConfig) string {
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Attach policy"))
+ writeOnboardKV(&out, "security.attach.enabled", fmt.Sprintf("%t", cfg.AttachEnabled))
+ writeOnboardNote(&out, "Leave this off unless you intentionally attach to an externally managed Chrome.")
+ writeOnboardKV(&out, "security.attach.allowHosts", strings.Join(cfg.AttachAllowHosts, ", "))
+ writeOnboardNote(&out, "Keeps attach targets scoped to trusted hosts.")
+ writeOnboardKV(&out, "security.attach.allowSchemes", strings.Join(cfg.AttachAllowSchemes, ", "))
+ writeOnboardNote(&out, "Restricts attach URLs to websocket transport.")
+ out.WriteString("\n")
+ return out.String()
+}
+
+func renderOnboardIDPIStep(step, total int, cfg *config.RuntimeConfig) string {
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "IDPI protections"))
+ writeOnboardKV(&out, "security.idpi.enabled", fmt.Sprintf("%t", cfg.IDPI.Enabled))
+ writeOnboardNote(&out, "Enables indirect prompt-injection defenses for navigation and extracted content.")
+ writeOnboardKV(&out, "security.idpi.allowedDomains", formatStringSlice(cfg.IDPI.AllowedDomains))
+ writeOnboardNote(&out, "Whitelists which sites are considered trusted enough for the local-default setup.")
+ writeOnboardKV(&out, "security.idpi.strictMode", fmt.Sprintf("%t", cfg.IDPI.StrictMode))
+ writeOnboardNote(&out, "Blocks disallowed domains or suspicious content instead of only warning.")
+ writeOnboardKV(&out, "security.idpi.scanContent", fmt.Sprintf("%t", cfg.IDPI.ScanContent))
+ writeOnboardNote(&out, "Scans `/text` and `/snapshot` output for prompt-injection patterns.")
+ writeOnboardKV(&out, "security.idpi.wrapContent", fmt.Sprintf("%t", cfg.IDPI.WrapContent))
+ writeOnboardNote(&out, "Wraps extracted content so downstream agents can treat it as untrusted data.")
+ out.WriteString("\n")
+ return out.String()
+}
+
+func renderOnboardDaemonStep(step, total int, installed bool) string {
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Background service"))
+ if installed {
+ writeOnboardMessage(&out, true, "Installed and started a user-level daemon for PinchTab.")
+ writeOnboardNote(&out, "Use `pinchtab daemon`, `start`, `restart`, `stop`, or `uninstall` to manage it.")
+ out.WriteString("\n")
+ return out.String()
+ }
+ writeOnboardWarning(&out, "This step installs a user-level background service and starts PinchTab automatically.")
+ writeOnboardNote(&out, "After install you can use `pinchtab daemon`, `start`, `restart`, `stop`, and `uninstall`.")
+ out.WriteString("\n")
+ return out.String()
+}
+
+func renderOnboardNextStep(step, total int, installDaemon bool) string {
+ var out bytes.Buffer
+ if step > 0 && total > 0 {
+ fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Next commands"))
+ } else {
+ fmt.Fprintf(&out, "%s\n", styleValue("Next commands"))
+ }
+ if installDaemon {
+ writeOnboardCommand(&out, "pinchtab daemon")
+ writeOnboardCommand(&out, "pinchtab health")
+ writeOnboardCommand(&out, "pinchtab security")
+ } else {
+ writeOnboardCommand(&out, "pinchtab server")
+ writeOnboardCommand(&out, "pinchtab health")
+ writeOnboardCommand(&out, "pinchtab security")
+ }
+ writeOnboardCommand(&out, "pinchtab quick https://example.com")
+ return out.String()
+}
+
+func renderOnboardTitle() string {
+ return styleLogo("PinchTab") + " " + styleMode("onboarding")
+}
+
+func styleOnboardStep(step, total int, title string) string {
+ prefix := styleStdout(cliHeadingStyle, fmt.Sprintf("Step %d/%d", step, total))
+ return prefix + " " + styleValue(title)
+}
+
+func writeOnboardKV(out *bytes.Buffer, key, value string) {
+ fmt.Fprintf(out, " %s %s\n", styleLabel(key), styleValue(value))
+}
+
+func writeOnboardNote(out *bytes.Buffer, message string, args ...any) {
+ fmt.Fprintf(out, " %s %s\n", styleStdout(cliMutedStyle, ">"), styleStdout(cliMutedStyle, fmt.Sprintf(message, args...)))
+}
+
+func writeOnboardMessage(out *bytes.Buffer, ok bool, message string, args ...any) {
+ fmt.Fprintf(out, " [%s] %s\n", styleMarker(ok), fmt.Sprintf(message, args...))
+}
+
+func writeOnboardWarning(out *bytes.Buffer, message string, args ...any) {
+ fmt.Fprintf(out, " [%s] %s\n", styleMarker(false), fmt.Sprintf(message, args...))
+}
+
+func writeOnboardCommand(out *bytes.Buffer, command string) {
+ fmt.Fprintf(out, " %s %s\n", styleStdout(cliMutedStyle, "$"), styleValue(command))
+}
+
+func printDaemonFollowUp() {
+ fmt.Println()
+ fmt.Println(styleStdout(cliHeadingStyle, "Follow-up commands:"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon"), styleStdout(cliMutedStyle, "# Check service health and logs"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon restart"), styleStdout(cliMutedStyle, "# Apply config changes"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon stop"), styleStdout(cliMutedStyle, "# Stop background service"))
+ fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon uninstall"), styleStdout(cliMutedStyle, "# Remove service file"))
+}
+
+func currentDaemonManager() (daemonManager, error) {
+ env, err := currentDaemonEnvironment()
+ if err != nil {
+ return nil, err
+ }
+ return newDaemonManager(env, osCommandRunner{})
+}
+
+func currentDaemonEnvironment() (daemonEnvironment, error) {
+ execPath, err := os.Executable()
+ if err != nil {
+ return daemonEnvironment{}, fmt.Errorf("resolve executable path: %w", err)
+ }
+ homeDir, err := os.UserHomeDir()
+ if err != nil {
+ return daemonEnvironment{}, fmt.Errorf("resolve home directory: %w", err)
+ }
+ currentUser, err := user.Current()
+ if err != nil {
+ return daemonEnvironment{}, fmt.Errorf("resolve current user: %w", err)
+ }
+
+ return daemonEnvironment{
+ execPath: execPath,
+ homeDir: homeDir,
+ osName: runtime.GOOS,
+ userID: currentUser.Uid,
+ xdgConfigHome: os.Getenv("XDG_CONFIG_HOME"),
+ }, nil
+}
+
+func newDaemonManager(env daemonEnvironment, runner commandRunner) (daemonManager, error) {
+ switch env.osName {
+ case "linux":
+ return &systemdUserManager{env: env, runner: runner}, nil
+ case "darwin":
+ return &launchdManager{env: env, runner: runner}, nil
+ default:
+ return nil, fmt.Errorf("pinchtab daemon is supported on macOS and Linux; current OS is %s", env.osName)
+ }
+}
+
+func managerEnvironment(manager daemonManager) daemonEnvironment {
+ switch m := manager.(type) {
+ case *systemdUserManager:
+ return m.env
+ case *launchdManager:
+ return m.env
+ default:
+ return daemonEnvironment{}
+ }
+}
+
+func (m *systemdUserManager) ServicePath() string {
+ return filepath.Join(systemdUserConfigHome(m.env), "systemd", "user", pinchtabDaemonUnitName)
+}
+
+func (m *systemdUserManager) Install(execPath, configPath string) (string, error) {
+ if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
+ return "", fmt.Errorf("create systemd user directory: %w", err)
+ }
+ if err := os.WriteFile(m.ServicePath(), []byte(renderSystemdUnit(execPath, configPath)), 0644); err != nil {
+ return "", fmt.Errorf("write systemd unit: %w", err)
+ }
+ if _, err := runCommand(m.runner, "systemctl", "--user", "daemon-reload"); err != nil {
+ return "", err
+ }
+ if _, err := runCommand(m.runner, "systemctl", "--user", "enable", "--now", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("Installed systemd user service at %s", m.ServicePath()), nil
+}
+
+func (m *systemdUserManager) Start() (string, error) {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "start", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon started.", nil
+}
+
+func (m *systemdUserManager) Restart() (string, error) {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "restart", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon restarted.", nil
+}
+
+func (m *systemdUserManager) Stop() (string, error) {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "stop", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon stopped.", nil
+}
+
+func (m *systemdUserManager) Status() (string, error) {
+ output, err := runCommand(m.runner, "systemctl", "--user", "status", pinchtabDaemonUnitName, "--no-pager")
+ if err != nil {
+ return "", err
+ }
+ if strings.TrimSpace(output) == "" {
+ return "Pinchtab daemon status returned no output.", nil
+ }
+ return output, nil
+}
+
+func (m *systemdUserManager) Uninstall() (string, error) {
+ var errs []error
+ if _, err := runCommand(m.runner, "systemctl", "--user", "disable", "--now", pinchtabDaemonUnitName); err != nil {
+ errs = append(errs, err)
+ }
+ if err := os.Remove(m.ServicePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
+ errs = append(errs, fmt.Errorf("remove unit file: %w", err))
+ }
+ if _, err := runCommand(m.runner, "systemctl", "--user", "daemon-reload"); err != nil {
+ errs = append(errs, err)
+ }
+ if len(errs) > 0 {
+ return "", errors.Join(errs...)
+ }
+ return "Pinchtab daemon uninstalled.", nil
+}
+
+func (m *systemdUserManager) Pid() (string, error) {
+ output, err := runCommand(m.runner, "systemctl", "--user", "show", pinchtabDaemonUnitName, "--property", "MainPID")
+ if err != nil {
+ return "", err
+ }
+ // Output is typically MainPID=1234
+ if parts := strings.Split(output, "="); len(parts) == 2 {
+ pid := strings.TrimSpace(parts[1])
+ if pid == "0" {
+ return "", nil // Not running
+ }
+ return pid, nil
+ }
+ return "", nil
+}
+
+func (m *systemdUserManager) Logs(n int) (string, error) {
+ return runCommand(m.runner, "journalctl", "--user", "-u", pinchtabDaemonUnitName, "-n", fmt.Sprintf("%d", n), "--no-pager")
+}
+
+func (m *systemdUserManager) ManualInstructions() string {
+ path := m.ServicePath()
+ var b strings.Builder
+ fmt.Fprintln(&b, styleStdout(cliHeadingStyle, "Manual instructions (Linux/systemd):"))
+ fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To install manually:"))
+ fmt.Fprintf(&b, " 1. Create %s\n", styleStdout(cliValueStyle, path))
+ fmt.Fprintln(&b, " 2. Run: "+styleStdout(cliCommandStyle, "systemctl --user daemon-reload"))
+ fmt.Fprintln(&b, " 3. Run: "+styleStdout(cliCommandStyle, "systemctl --user enable --now pinchtab.service"))
+ fmt.Fprintln(&b)
+ fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To uninstall manually:"))
+ fmt.Fprintln(&b, " 1. Run: "+styleStdout(cliCommandStyle, "systemctl --user disable --now pinchtab.service"))
+ fmt.Fprintf(&b, " 2. Remove: %s\n", styleStdout(cliValueStyle, path))
+ fmt.Fprintln(&b, " 3. Run: "+styleStdout(cliCommandStyle, "systemctl --user daemon-reload"))
+ return b.String()
+}
+
+func renderSystemdUnit(execPath, configPath string) string {
+ return fmt.Sprintf(`[Unit]
+Description=Pinchtab Browser Service
+After=network.target
+
+[Service]
+Type=simple
+ExecStart="%s" server
+Environment="PINCHTAB_CONFIG=%s"
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=default.target
+`, execPath, configPath)
+}
+
+func (m *launchdManager) ServicePath() string {
+ return filepath.Join(m.env.homeDir, "Library", "LaunchAgents", pinchtabLaunchdLabel+".plist")
+}
+
+func (m *launchdManager) Install(execPath, configPath string) (string, error) {
+ if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
+ return "", fmt.Errorf("create LaunchAgents directory: %w", err)
+ }
+ if err := os.WriteFile(m.ServicePath(), []byte(renderLaunchdPlist(execPath, configPath)), 0644); err != nil {
+ return "", fmt.Errorf("write launchd plist: %w", err)
+ }
+ _, _ = runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
+ if _, err := runCommand(m.runner, "launchctl", "bootstrap", launchdDomainTarget(m.env), m.ServicePath()); err != nil {
+ return "", err
+ }
+ if _, err := runCommand(m.runner, "launchctl", "kickstart", "-k", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("Installed launchd agent at %s", m.ServicePath()), nil
+}
+
+func (m *launchdManager) Start() (string, error) {
+ if _, err := runCommand(m.runner, "launchctl", "bootstrap", launchdDomainTarget(m.env), m.ServicePath()); err != nil && !strings.Contains(err.Error(), "already bootstrapped") {
+ return "", err
+ }
+ if _, err := runCommand(m.runner, "launchctl", "kickstart", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon started.", nil
+}
+
+func (m *launchdManager) Restart() (string, error) {
+ if _, err := runCommand(m.runner, "launchctl", "kickstart", "-k", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon restarted.", nil
+}
+
+func (m *launchdManager) Stop() (string, error) {
+ _, err := runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
+ if err != nil && !isLaunchdIgnorableError(err) {
+ return "", err
+ }
+ return "Pinchtab daemon stopped.", nil
+}
+
+func (m *launchdManager) Status() (string, error) {
+ output, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel)
+ if err != nil {
+ return "", err
+ }
+ if strings.TrimSpace(output) == "" {
+ return "Pinchtab daemon status returned no output.", nil
+ }
+ return output, nil
+}
+
+func (m *launchdManager) Uninstall() (string, error) {
+ var errs []error
+ _, err := runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
+ if err != nil && !isLaunchdIgnorableError(err) {
+ errs = append(errs, err)
+ }
+ if err := os.Remove(m.ServicePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
+ errs = append(errs, fmt.Errorf("remove launchd plist: %w", err))
+ }
+ if len(errs) > 0 {
+ return "", errors.Join(errs...)
+ }
+ return "Pinchtab daemon uninstalled.", nil
+}
+
+func (m *launchdManager) Pid() (string, error) {
+ output, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel)
+ if err != nil {
+ return "", err
+ }
+ // Try to find pid = 1234
+ lines := strings.Split(output, "\n")
+ for _, line := range lines {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "pid = ") {
+ return strings.TrimPrefix(trimmed, "pid = "), nil
+ }
+ }
+ return "", nil
+}
+
+func (m *launchdManager) Logs(n int) (string, error) {
+ // macOS log paths we added to plist
+ logPath := "/tmp/pinchtab.err.log"
+ if _, err := os.Stat(logPath); err != nil {
+ return "No logs found at " + logPath, nil
+ }
+ return runCommand(m.runner, "tail", "-n", fmt.Sprintf("%d", n), logPath)
+}
+
+func (m *launchdManager) ManualInstructions() string {
+ path := m.ServicePath()
+ target := launchdDomainTarget(m.env)
+ var b strings.Builder
+ fmt.Fprintln(&b, styleStdout(cliHeadingStyle, "Manual instructions (macOS/launchd):"))
+ fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To install manually:"))
+ fmt.Fprintf(&b, " 1. Create %s\n", styleStdout(cliValueStyle, path))
+ fmt.Fprintln(&b, " 2. Run: "+styleStdout(cliCommandStyle, fmt.Sprintf("launchctl bootstrap %s %s", target, path)))
+ fmt.Fprintln(&b)
+ fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To uninstall manually:"))
+ fmt.Fprintln(&b, " 1. Run: "+styleStdout(cliCommandStyle, fmt.Sprintf("launchctl bootout %s %s", target, path)))
+ fmt.Fprintf(&b, " 2. Remove: %s\n", styleStdout(cliValueStyle, path))
+ return b.String()
+}
+
+func isLaunchdIgnorableError(err error) bool {
+ if err == nil {
+ return true
+ }
+ msg := err.Error()
+ // Exit status 5 often means already booted out or path not found in domain
+ // "No such process" (status 3) or "No such file or directory" (status 2) or "Operation not permitted" (sometimes)
+ return strings.Contains(msg, "exit status 5") ||
+ strings.Contains(msg, "No such process") ||
+ strings.Contains(msg, "not found") ||
+ strings.Contains(msg, "already bootstrapped")
+}
+
+func renderLaunchdPlist(execPath, configPath string) string {
+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>%s</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>%s</string>
+ <string>server</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PINCHTAB_CONFIG</key>
+ <string>%s</string>
+ </dict>
+ <key>StandardOutPath</key>
+ <string>/tmp/pinchtab.out.log</string>
+ <key>StandardErrorPath</key>
+ <string>/tmp/pinchtab.err.log</string>
+</dict>
+</plist>
+`, pinchtabLaunchdLabel, execPath, configPath)
+}
+
+func runCommand(runner commandRunner, name string, args ...string) (string, error) {
+ output, err := runner.CombinedOutput(name, args...)
+ trimmed := strings.TrimSpace(string(output))
+ if err == nil {
+ return trimmed, nil
+ }
+ if trimmed == "" {
+ return "", fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
+ }
+ return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, trimmed)
+}
+
+func launchdDomainTarget(env daemonEnvironment) string {
+ return "gui/" + env.userID
+}
+
+func systemdUserConfigHome(env daemonEnvironment) string {
+ if strings.TrimSpace(env.xdgConfigHome) != "" {
+ return env.xdgConfigHome
+ }
+ return filepath.Join(env.homeDir, ".config")
+}
+
+func fileExists(path string) bool {
+ _, err := os.Stat(path)
+ return err == nil
+}
diff --git a/cmd/pinchtab/cmd_onboard_test.go b/cmd/pinchtab/cmd_onboard_test.go
new file mode 100644
index 00000000..eb0845c9
--- /dev/null
+++ b/cmd/pinchtab/cmd_onboard_test.go
@@ -0,0 +1,281 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type fakeCommandRunner struct {
+ calls []string
+ outputs map[string]string
+ errors map[string]error
+}
+
+func (f *fakeCommandRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
+ call := name + " " + strings.Join(args, " ")
+ f.calls = append(f.calls, call)
+ if out, ok := f.outputs[call]; ok {
+ return []byte(out), f.errors[call]
+ }
+ return nil, f.errors[call]
+}
+
+func TestEnsureOnboardConfigCreatesDefaultConfig(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+ t.Setenv("PINCHTAB_BIND", "")
+
+ gotPath, cfg, status, err := ensureOnboardConfig(false)
+ if err != nil {
+ t.Fatalf("ensureOnboardConfig returned error: %v", err)
+ }
+ if status != onboardConfigCreated {
+ t.Fatalf("status = %q, want %q", status, onboardConfigCreated)
+ }
+ 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 strings.TrimSpace(cfg.Token) == "" {
+ t.Fatal("expected generated token to be set")
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("reading config file: %v", err)
+ }
+ content := string(data)
+ if !strings.Contains(content, `"bind": "127.0.0.1"`) {
+ t.Fatalf("expected config file to include bind, got %s", content)
+ }
+ if !strings.Contains(content, `"token": "`) {
+ t.Fatalf("expected config file to include token, got %s", content)
+ }
+}
+
+func TestEnsureOnboardConfigRecoversExistingSecuritySettings(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ input := `{
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9999",
+ "token": ""
+ },
+ "browser": {
+ "binary": "/custom/chrome"
+ },
+ "security": {
+ "allowEvaluate": true
+ }
+}
+`
+ if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ t.Fatalf("creating config dir: %v", err)
+ }
+ if err := os.WriteFile(configPath, []byte(input), 0644); err != nil {
+ t.Fatalf("writing config file: %v", err)
+ }
+
+ _, cfg, status, err := ensureOnboardConfig(false)
+ if err != nil {
+ t.Fatalf("ensureOnboardConfig returned error: %v", err)
+ }
+ if status != onboardConfigRecovered {
+ t.Fatalf("status = %q, want %q", status, onboardConfigRecovered)
+ }
+ if cfg.Bind != "127.0.0.1" {
+ t.Fatalf("bind = %q, want 127.0.0.1", cfg.Bind)
+ }
+ if cfg.Port != "9999" {
+ t.Fatalf("port = %q, want 9999", cfg.Port)
+ }
+ if cfg.ChromeBinary != "/custom/chrome" {
+ t.Fatalf("chrome binary = %q, want /custom/chrome", cfg.ChromeBinary)
+ }
+ if cfg.AllowEvaluate {
+ t.Fatal("expected allowEvaluate to be reset to false")
+ }
+ if strings.TrimSpace(cfg.Token) == "" {
+ t.Fatal("expected recovery to generate a token")
+ }
+}
+
+func TestSaveSelectedSensitiveCapabilities(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ token := "test-token"
+ fc.Server.Token = token
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig returned error: %v", err)
+ }
+
+ if err := saveSelectedSensitiveCapabilities(configPath, []string{"evaluate", "download"}); err != nil {
+ t.Fatalf("saveSelectedSensitiveCapabilities returned error: %v", err)
+ }
+
+ got, _, err := config.LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig returned error: %v", err)
+ }
+
+ if got.Security.AllowEvaluate == nil || !*got.Security.AllowEvaluate {
+ t.Fatal("expected allowEvaluate to be true")
+ }
+ if got.Security.AllowDownload == nil || !*got.Security.AllowDownload {
+ t.Fatal("expected allowDownload to be true")
+ }
+ if got.Security.AllowMacro == nil || *got.Security.AllowMacro {
+ t.Fatal("expected allowMacro to be false")
+ }
+ if got.Security.AllowScreencast == nil || *got.Security.AllowScreencast {
+ t.Fatal("expected allowScreencast to be false")
+ }
+ if got.Security.AllowUpload == nil || *got.Security.AllowUpload {
+ t.Fatal("expected allowUpload to be false")
+ }
+}
+
+func TestRenderOnboardGuideIncludesSecurityValues(t *testing.T) {
+ cfg := testRuntimeConfig()
+ output := renderOnboardGuide("/tmp/pinchtab/config.json", cfg, onboardConfigCreated, true)
+
+ required := []string{
+ "Step 2/7 API access",
+ "server.bind 127.0.0.1",
+ "security.allowEvaluate false",
+ "security.attach.enabled false",
+ "security.idpi.strictMode true",
+ "pinchtab daemon status",
+ }
+ for _, needle := range required {
+ if !strings.Contains(output, needle) {
+ t.Fatalf("expected onboarding guide to contain %q\n%s", needle, output)
+ }
+ }
+}
+
+func TestSystemdUserManagerInstallWritesUnitAndEnablesService(t *testing.T) {
+ root := t.TempDir()
+ runner := &fakeCommandRunner{}
+ manager := &systemdUserManager{
+ env: daemonEnvironment{
+ homeDir: root,
+ osName: "linux",
+ execPath: "/usr/local/bin/pinchtab",
+ xdgConfigHome: filepath.Join(root, ".config"),
+ },
+ runner: runner,
+ }
+
+ message, err := manager.Install("/usr/local/bin/pinchtab", "/tmp/pinchtab/config.json")
+ if err != nil {
+ t.Fatalf("Install returned error: %v", err)
+ }
+ if !strings.Contains(message, manager.ServicePath()) {
+ t.Fatalf("install message = %q, want path %q", message, manager.ServicePath())
+ }
+
+ data, err := os.ReadFile(manager.ServicePath())
+ if err != nil {
+ t.Fatalf("reading service file: %v", err)
+ }
+ content := string(data)
+ if !strings.Contains(content, `ExecStart="/usr/local/bin/pinchtab" server`) {
+ t.Fatalf("unexpected unit content: %s", content)
+ }
+ if !strings.Contains(content, `Environment="PINCHTAB_CONFIG=/tmp/pinchtab/config.json"`) {
+ t.Fatalf("expected config env in unit content: %s", content)
+ }
+
+ expectedCalls := []string{
+ "systemctl --user daemon-reload",
+ "systemctl --user enable --now pinchtab.service",
+ }
+ if strings.Join(runner.calls, "\n") != strings.Join(expectedCalls, "\n") {
+ t.Fatalf("systemd calls = %v, want %v", runner.calls, expectedCalls)
+ }
+}
+
+func TestLaunchdManagerInstallWritesPlistAndBootstrapsAgent(t *testing.T) {
+ root := t.TempDir()
+ runner := &fakeCommandRunner{}
+ manager := &launchdManager{
+ env: daemonEnvironment{
+ homeDir: root,
+ osName: "darwin",
+ execPath: "/Applications/Pinchtab.app/Contents/MacOS/pinchtab",
+ userID: "501",
+ },
+ runner: runner,
+ }
+
+ message, err := manager.Install("/Applications/Pinchtab.app/Contents/MacOS/pinchtab", "/tmp/pinchtab/config.json")
+ if err != nil {
+ t.Fatalf("Install returned error: %v", err)
+ }
+ if !strings.Contains(message, manager.ServicePath()) {
+ t.Fatalf("install message = %q, want path %q", message, manager.ServicePath())
+ }
+
+ data, err := os.ReadFile(manager.ServicePath())
+ if err != nil {
+ t.Fatalf("reading launchd plist: %v", err)
+ }
+ content := string(data)
+ if !strings.Contains(content, "<string>com.pinchtab.pinchtab</string>") {
+ t.Fatalf("expected launchd label in plist: %s", content)
+ }
+ if !strings.Contains(content, "<string>/Applications/Pinchtab.app/Contents/MacOS/pinchtab</string>") {
+ t.Fatalf("expected executable path in plist: %s", content)
+ }
+ if !strings.Contains(content, "<string>/tmp/pinchtab/config.json</string>") {
+ t.Fatalf("expected config path in plist: %s", content)
+ }
+
+ expectedCalls := []string{
+ "launchctl bootout gui/501 " + manager.ServicePath(),
+ "launchctl bootstrap gui/501 " + manager.ServicePath(),
+ "launchctl kickstart -k gui/501/com.pinchtab.pinchtab",
+ }
+ if strings.Join(runner.calls, "\n") != strings.Join(expectedCalls, "\n") {
+ t.Fatalf("launchctl calls = %v, want %v", runner.calls, expectedCalls)
+ }
+}
+
+func TestNewDaemonManagerRejectsUnsupportedOS(t *testing.T) {
+ _, err := newDaemonManager(daemonEnvironment{osName: "windows"}, &fakeCommandRunner{})
+ if err == nil {
+ t.Fatal("expected unsupported OS error")
+ }
+}
+
+func testRuntimeConfig() *config.RuntimeConfig {
+ return &config.RuntimeConfig{
+ Bind: "127.0.0.1",
+ Token: "abcd1234efgh5678",
+ AllowEvaluate: false,
+ AllowMacro: false,
+ AllowScreencast: false,
+ AllowDownload: false,
+ AllowUpload: false,
+ AttachEnabled: false,
+ 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,
+ },
+ }
+}
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index 9bf53aa9..f79c101d 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -8,73 +8,88 @@ import (
"strings"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
)
+var securityCmd = &cobra.Command{
+ Use: "security",
+ Short: "Review runtime security posture",
+ Long: "Shows runtime security posture and offers to restore recommended security defaults.",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ handleSecurityCommand(cfg)
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(securityCmd)
+}
+
func handleSecurityCommand(cfg *config.RuntimeConfig) {
warnings := assessSecurityWarnings(cfg)
recommended := recommendedSecurityDefaultLines(cfg)
- fmt.Println("Security posture:")
+ fmt.Println(styleStdout(cliHeadingStyle, "Security posture"))
fmt.Println()
printSecuritySummary(os.Stdout, cfg, " ")
if len(warnings) == 0 {
- fmt.Println("Warnings:")
+ fmt.Println(styleStdout(cliHeadingStyle, "Warnings"))
fmt.Println()
- fmt.Println(" none")
+ fmt.Println(" " + styleStdout(cliMutedStyle, "none"))
} else {
- fmt.Println("Warnings:")
+ fmt.Println(styleStdout(cliHeadingStyle, "Warnings"))
fmt.Println()
for _, warning := range warnings {
- fmt.Printf(" - %s\n", warning.Message)
+ fmt.Printf(" - %s\n", styleStdout(cliWarningStyle, 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]))
+ fmt.Printf(" %s: %s\n", styleStdout(cliMutedStyle, key), styleStdout(cliValueStyle, 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.Printf(" %s: %s\n", styleStdout(cliMutedStyle, "hint"), styleStdout(cliValueStyle, formatSecurityValue(warning.Attrs[i+1])))
}
}
}
}
fmt.Println()
- fmt.Println("Recommended security defaults:")
+ fmt.Println(styleStdout(cliHeadingStyle, "Recommended security defaults"))
fmt.Println()
if len(recommended) == 0 {
- fmt.Println(" none")
+ fmt.Println(" " + styleStdout(cliMutedStyle, "none"))
} else {
printRecommendedSecurityDefaults(recommended)
}
fmt.Println()
if !isInteractiveTerminal() {
- fmt.Println("Interactive restore skipped because stdin/stdout is not a terminal.")
+ fmt.Println(styleStdout(cliMutedStyle, "Interactive restore skipped because stdin/stdout is not a terminal."))
return
}
if !promptRestoreDefaults() {
- fmt.Println("No changes made.")
+ fmt.Println(styleStdout(cliMutedStyle, "No changes made."))
return
}
configPath, changed, err := restoreSecurityDefaults()
if err != nil {
- fmt.Printf("Error restoring defaults: %v\n", err)
+ fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error restoring defaults: %v", err)))
os.Exit(1)
}
if !changed {
- fmt.Printf("Security defaults already match %s\n", configPath)
+ fmt.Println(styleStdout(cliMutedStyle, fmt.Sprintf("Security defaults already match %s", configPath)))
return
}
- fmt.Printf("Security defaults restored in %s\n", configPath)
- fmt.Println("Restart PinchTab to apply file-based changes.")
+ fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Security defaults restored in %s", configPath)))
+ fmt.Println(styleStdout(cliMutedStyle, "Restart PinchTab to apply file-based changes."))
}
func formatSecurityValue(value any) string {
@@ -86,15 +101,9 @@ func formatSecurityValue(value any) string {
}
}
-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)
+ fmt.Printf(" - %s\n", styleStdout(cliValueStyle, line))
}
}
@@ -157,7 +166,7 @@ func recommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
}
func promptRestoreDefaults() bool {
- fmt.Print("Restore recommended security defaults in config? (y/N): ")
+ fmt.Print(styleStdout(cliHeadingStyle, "Restore recommended security defaults in config?") + " " + styleStdout(cliMutedStyle, "(y/N): "))
reader := bufio.NewReader(os.Stdin)
response, err := reader.ReadString('\n')
if err != nil && strings.TrimSpace(response) == "" {
diff --git a/cmd/pinchtab/main.go b/cmd/pinchtab/main.go
index f2b06d6b..736ef310 100644
--- a/cmd/pinchtab/main.go
+++ b/cmd/pinchtab/main.go
@@ -1,83 +1,5 @@
package main
-import (
- "fmt"
- "os"
-
- "github.com/pinchtab/pinchtab/internal/config"
-)
-
-var version = "dev"
-
-func startupMode(args []string) (string, bool) {
- if len(args) <= 1 {
- return "server", true
- }
- switch args[1] {
- case "server":
- return "server", true
- case "bridge":
- return "bridge", true
- }
- return "", false
-}
-
func main() {
- cfg := config.Load()
-
- if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-v") {
- fmt.Printf("pinchtab %s\n", version)
- os.Exit(0)
- }
-
- if len(os.Args) > 1 && (os.Args[1] == "help" || os.Args[1] == "--help" || os.Args[1] == "-h") {
- printHelp()
- os.Exit(0)
- }
-
- if len(os.Args) > 1 && os.Args[1] == "config" {
- config.HandleConfigCommand(cfg)
- os.Exit(0)
- }
-
- if len(os.Args) > 1 && os.Args[1] == "connect" {
- handleConnectCommand(cfg)
- 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)
- }
-
- if len(os.Args) > 1 && os.Args[1] == "mcp" {
- runMCP(cfg)
- return
- }
-
- // CLI commands
- if len(os.Args) > 1 && isCLICommand(os.Args[1]) {
- runCLI(cfg)
- return
- }
-
- mode, ok := startupMode(os.Args)
- if !ok {
- fmt.Fprintf(os.Stderr, "unknown command: %s\n\n", os.Args[1])
- printHelp()
- os.Exit(1)
- }
-
- switch mode {
- case "bridge":
- runBridgeServer(cfg)
- case "server":
- runDashboard(cfg)
- default:
- runDashboard(cfg)
- }
+ Execute()
}
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
new file mode 100644
index 00000000..5e9f767b
--- /dev/null
+++ b/cmd/pinchtab/root.go
@@ -0,0 +1,36 @@
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
+)
+
+var version = "dev"
+
+var rootCmd = &cobra.Command{
+ Use: "pinchtab",
+ Short: "PinchTab - Browser control for AI agents",
+ Long: `PinchTab provides a lightweight, API-driven way for AI agents to control
+browsers, manage tabs, and perform interactive tasks.`,
+ Run: func(cmd *cobra.Command, args []string) {
+ // Default action: start the server
+ cfg := config.Load()
+ runDashboard(cfg)
+ },
+}
+
+func Execute() {
+ if err := rootCmd.Execute(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func init() {
+ rootCmd.Version = version
+ rootCmd.SetVersionTemplate("pinchtab {{.Version}}\n")
+ rootCmd.AddCommand(config.ConfigCmd)
+}
diff --git a/cmd/pinchtab/startup_output.go b/cmd/pinchtab/startup_output.go
index 74a9fba0..e1de04ad 100644
--- a/cmd/pinchtab/startup_output.go
+++ b/cmd/pinchtab/startup_output.go
@@ -6,6 +6,8 @@ import (
"os"
"strings"
+ "github.com/charmbracelet/lipgloss"
+ "github.com/pinchtab/pinchtab/internal/cliui"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -14,6 +16,7 @@ type startupBannerOptions struct {
ListenAddr string
PublicURL string
Strategy string
+ Allocation string
ProfileDir string
}
@@ -23,9 +26,16 @@ func printStartupBanner(cfg *config.RuntimeConfig, opts startupBannerOptions) {
if opts.PublicURL != "" {
writeBannerf(" %s %s\n", styleLabel("url"), styleValue(opts.PublicURL))
}
- if opts.Strategy != "" {
- writeBannerf(" %s %s\n", styleLabel("strategy"), styleValue(opts.Strategy))
+ strat := blankIfEmpty(opts.Strategy, "manual")
+ alloc := blankIfEmpty(opts.Allocation, "none")
+ writeBannerf(" %s %s\n", styleLabel("str,plc"), styleValue(fmt.Sprintf("%s,%s", strat, alloc)))
+
+ daemonStatus := styleStdout(cliWarningStyle, "not installed")
+ if IsDaemonInstalled() {
+ daemonStatus = styleStdout(cliSuccessStyle, "ok")
}
+ writeBannerf(" %s %s\n", styleLabel("daemon"), daemonStatus)
+
if opts.ProfileDir != "" {
writeBannerf(" %s %s\n", styleLabel("profile"), styleValue(opts.ProfileDir))
}
@@ -97,93 +107,64 @@ func writeSummaryf(w io.Writer, format string, args ...any) {
}
func styleLogo(text string) string {
- return applyStyle(text, ansiBold, ansiCyan)
+ return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorAccent).Bold(true))
}
func styleMode(text string) string {
- return applyStyle(text, ansiDim)
+ return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorTextMuted))
}
func styleLabel(text string) string {
- return applyStyle(fmt.Sprintf("%-8s", text), ansiDim)
+ return applyStyle(fmt.Sprintf("%-8s", text), lipgloss.NewStyle().Foreground(cliui.ColorTextMuted))
}
func styleValue(text string) string {
- return applyStyle(text, ansiBold)
+ return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorTextPrimary).Bold(true))
}
func styleCheckLabel(text string) string {
- return applyStyle(fmt.Sprintf("%-20s", text), ansiDim)
+ return applyStyle(fmt.Sprintf("%-20s", text), lipgloss.NewStyle().Foreground(cliui.ColorTextMuted))
}
func styleCheckDetail(passed bool, text string) string {
if passed {
- return applyStyle(text, ansiGreen)
+ return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorSuccess))
}
- return applyStyle(text, ansiYellow)
+ return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorWarning))
}
func styleMarker(passed bool) string {
if passed {
- return applyStyle("ok", ansiBold, ansiGreen)
+ return applyStyle("ok", lipgloss.NewStyle().Foreground(cliui.ColorSuccess).Bold(true))
}
- return applyStyle("!!", ansiBold, ansiRed)
+ return applyStyle("!!", lipgloss.NewStyle().Foreground(cliui.ColorDanger).Bold(true))
}
func styleSecurityLevel(level string) string {
- return applyStyle(level, ansiBold, securityLevelColor(level))
+ return applyStyle(level, lipgloss.NewStyle().Foreground(lipgloss.Color(securityLevelColor(level))).Bold(true))
}
func styleSecurityBar(level, bar string) string {
- return applyStyle(bar, ansiBold, securityLevelColor(level))
+ return applyStyle(bar, lipgloss.NewStyle().Foreground(lipgloss.Color(securityLevelColor(level))).Bold(true))
}
func securityLevelColor(level string) string {
switch level {
case "LOCKED":
- return ansiGreen
+ return string(cliui.ColorSuccess)
case "GUARDED":
- return ansiYellow
+ return string(cliui.ColorWarning)
case "ELEVATED":
- return ansiRed
+ return string(cliui.ColorDanger)
default:
- return ansiRed
+ return string(cliui.ColorDanger)
}
}
-func applyStyle(text string, codes ...string) string {
- if !shouldColorizeOutput() || len(codes) == 0 {
- return text
- }
- return "\x1b[" + strings.Join(codes, ";") + "m" + text + "\x1b[0m"
+func applyStyle(text string, style lipgloss.Style) string {
+ return cliui.RenderStdout(style, text)
}
-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
index 50a16c27..ace06161 100644
--- a/cmd/pinchtab/startup_output_test.go
+++ b/cmd/pinchtab/startup_output_test.go
@@ -1,17 +1,21 @@
package main
-import "testing"
+import (
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/cliui"
+)
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},
+ {level: "LOCKED", want: string(cliui.ColorSuccess)},
+ {level: "GUARDED", want: string(cliui.ColorWarning)},
+ {level: "ELEVATED", want: string(cliui.ColorDanger)},
+ {level: "EXPOSED", want: string(cliui.ColorDanger)},
+ {level: "UNKNOWN", want: string(cliui.ColorDanger)},
}
for _, tt := range tests {
diff --git a/cmd/promptdemo/main.go b/cmd/promptdemo/main.go
new file mode 100644
index 00000000..c04aabc5
--- /dev/null
+++ b/cmd/promptdemo/main.go
@@ -0,0 +1,96 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var demoRefs = []prompt.Suggest{
+ {Text: "e12", Description: "button Login"},
+ {Text: "e18", Description: "input Email"},
+ {Text: "e24", Description: "link Forgot password"},
+}
+
+var rootSuggestions = []prompt.Suggest{
+ {Text: "help", Description: "Show the available commands"},
+ {Text: "nav", Description: "Navigate to a URL"},
+ {Text: "snap", Description: "Capture a page snapshot"},
+ {Text: "click", Description: "Click an element from the last snapshot"},
+ {Text: "type", Description: "Type into an element from the last snapshot"},
+ {Text: "pdf", Description: "Export the current page as PDF"},
+ {Text: "exit", Description: "Quit the demo"},
+}
+
+func main() {
+ fmt.Println("PinchTab prompt demo")
+ fmt.Println("Tab completes commands and a few cached refs from a fake snapshot.")
+ fmt.Println("Try: nav https://example.com, snap -i, click e12, type e18 hello")
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix("pinchtab> "),
+ prompt.OptionTitle("PinchTab Prompt Demo"),
+ )
+ p.Run()
+}
+
+func executor(in string) {
+ line := strings.TrimSpace(in)
+ if line == "" {
+ return
+ }
+
+ switch {
+ case line == "exit" || line == "quit":
+ fmt.Println("bye")
+ os.Exit(0)
+ case line == "help":
+ fmt.Println("commands: nav, snap, click, type, pdf, exit")
+ case strings.HasPrefix(line, "nav "):
+ fmt.Printf("navigate -> %s\n", strings.TrimSpace(strings.TrimPrefix(line, "nav ")))
+ case strings.HasPrefix(line, "snap"):
+ fmt.Println("snapshot -> cached refs: e12(Login), e18(Email), e24(Forgot password)")
+ case strings.HasPrefix(line, "click "):
+ fmt.Printf("click -> %s\n", strings.TrimSpace(strings.TrimPrefix(line, "click ")))
+ case strings.HasPrefix(line, "type "):
+ fmt.Printf("type -> %s\n", strings.TrimSpace(strings.TrimPrefix(line, "type ")))
+ case strings.HasPrefix(line, "pdf"):
+ fmt.Println("pdf -> /tmp/example.pdf")
+ default:
+ fmt.Printf("unknown command: %s\n", line)
+ }
+}
+
+func completer(d prompt.Document) []prompt.Suggest {
+ words := strings.Fields(d.TextBeforeCursor())
+ if len(words) == 0 {
+ return prompt.FilterHasPrefix(rootSuggestions, d.GetWordBeforeCursor(), true)
+ }
+
+ switch words[0] {
+ case "nav":
+ return prompt.FilterHasPrefix([]prompt.Suggest{
+ {Text: "https://example.com", Description: "demo URL"},
+ {Text: "https://pinchtab.com", Description: "PinchTab website"},
+ }, d.GetWordBeforeCursor(), true)
+ case "snap":
+ return prompt.FilterHasPrefix([]prompt.Suggest{
+ {Text: "-i", Description: "interactive elements only"},
+ {Text: "-c", Description: "compact format"},
+ {Text: "--diff", Description: "only changes since last snapshot"},
+ }, d.GetWordBeforeCursor(), true)
+ case "click", "type":
+ return prompt.FilterHasPrefix(demoRefs, d.GetWordBeforeCursor(), true)
+ case "pdf":
+ return prompt.FilterHasPrefix([]prompt.Suggest{
+ {Text: "-o", Description: "output file"},
+ {Text: "--tab", Description: "target tab"},
+ }, d.GetWordBeforeCursor(), true)
+ default:
+ return prompt.FilterHasPrefix(rootSuggestions, d.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/docs/guides/daemon.md b/docs/guides/daemon.md
new file mode 100644
index 00000000..f4d4766c
--- /dev/null
+++ b/docs/guides/daemon.md
@@ -0,0 +1,69 @@
+# Background Service (Daemon)
+
+PinchTab can run as a user-level background service (daemon) on both macOS (`launchd`) and Linux (`systemd`). This ensures that the PinchTab server is always available to your agents without needing an open terminal window.
+
+![Daemon Status & Picker](../media/daemon-status.png)
+
+## Quick Start
+
+The easiest way to set up the daemon is through the interactive onboarding:
+
+```bash
+pinchtab onboard --install-daemon
+```
+
+If you already have PinchTab configured, you can manage the service directly:
+
+```bash
+pinchtab daemon
+```
+
+When run without arguments in an interactive terminal, this command shows the current status and opens a picker for common actions.
+
+## Daemon Commands
+
+| Command | Description |
+|---------|-------------|
+| `pinchtab daemon` | Show status summary, recent logs, and open interactive picker. |
+| `pinchtab daemon install` | Create and enable the background service file. |
+| `pinchtab daemon start` | Start the background service if it is stopped. |
+| `pinchtab daemon stop` | Stop the background service. |
+| `pinchtab daemon restart` | Restart the service (useful after config changes). |
+| `pinchtab daemon uninstall` | Disable and remove the background service file. |
+
+## Status & Diagnostics
+
+The `pinchtab daemon` command provides a comprehensive overview of the service:
+
+- **Service Status**: Shows if the `.plist` (macOS) or `.service` (Linux) file is installed.
+- **State**: Indicates if the process is `active (running)` or `stopped`.
+- **PID**: The Process ID of the running server.
+- **Path**: The exact location of the service configuration file on your system.
+- **Recent Logs**: The last few lines of output from the server to help diagnose issues.
+
+## Manual Installation
+
+If the automated commands fail due to permission issues or system restrictions, PinchTab provides manual instructions tailored to your OS.
+
+### macOS (launchd)
+Service file: `~/Library/LaunchAgents/com.pinchtab.pinchtab.plist`
+
+1. Create the plist file (PinchTab will provide the content on error).
+2. Register and start:
+ ```bash
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pinchtab.pinchtab.plist
+ ```
+
+### Linux (systemd)
+Service file: `~/.config/systemd/user/pinchtab.service`
+
+1. Create the unit file.
+2. Reload and enable:
+ ```bash
+ systemctl --user daemon-reload
+ systemctl --user enable --now pinchtab.service
+ ```
+
+## Conflict Detection
+
+If you try to start a PinchTab server in the foreground (`pinchtab server`) while the daemon is already running on the same port, PinchTab will detect the conflict, warn you, and exit to prevent port binding errors.
diff --git a/go.mod b/go.mod
index 8072c13d..297f8885 100644
--- a/go.mod
+++ b/go.mod
@@ -3,36 +3,69 @@ module github.com/pinchtab/pinchtab
go 1.25.0
require (
+ github.com/c-bata/go-prompt v0.2.6
+ github.com/charmbracelet/huh v1.0.0
+ github.com/charmbracelet/lipgloss v1.1.0
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d
github.com/chromedp/chromedp v0.14.2
github.com/gobwas/ws v1.4.0
github.com/gost-dom/browser v0.11.0
github.com/mark3labs/mcp-go v0.45.0
github.com/shirou/gopsutil/v4 v4.26.2
+ github.com/spf13/cobra v1.10.2
golang.org/x/net v0.47.0
gopkg.in/yaml.v3 v3.0.1
)
require (
+ github.com/atotto/clipboard v0.1.4 // indirect
+ github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
+ github.com/catppuccin/go v0.3.0 // indirect
+ github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect
+ github.com/charmbracelet/bubbletea v1.3.6 // indirect
+ github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
+ github.com/charmbracelet/x/ansi v0.9.3 // indirect
+ github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
+ github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
+ github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
+ github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.0 // indirect
+ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gost-dom/css v0.1.0 // indirect
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/invopop/jsonschema v0.13.0 // indirect
+ github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
+ github.com/mattn/go-colorable v0.1.7 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-localereader v0.0.1 // indirect
+ github.com/mattn/go-runewidth v0.0.16 // indirect
+ github.com/mattn/go-tty v0.0.3 // indirect
+ github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
+ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
+ github.com/muesli/cancelreader v0.2.2 // indirect
+ github.com/muesli/termenv v0.16.0 // indirect
+ github.com/pkg/term v1.2.0-beta.2 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
+ github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/cast v1.7.1 // indirect
+ github.com/spf13/pflag v1.0.9 // indirect
github.com/tklauser/go-sysconf v0.3.16 // indirect
github.com/tklauser/numcpus v0.11.0 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
+ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
+ golang.org/x/sync v0.18.0 // indirect
golang.org/x/sys v0.41.0 // indirect
+ golang.org/x/text v0.31.0 // indirect
)
diff --git a/go.sum b/go.sum
index 635e4934..12af3a29 100644
--- a/go.sum
+++ b/go.sum
@@ -1,17 +1,64 @@
+github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
+github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
+github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
+github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
+github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
+github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=
+github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
+github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI=
+github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY=
+github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
+github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
+github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws=
+github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7/go.mod h1:ISC1gtLcVilLOf23wvTfoQuYbW2q0JevFxPfUzZ9Ybw=
+github.com/charmbracelet/bubbletea v1.3.6 h1:VkHIxPJQeDt0aFJIsVxw8BQdh/F/L2KKZGsK6et5taU=
+github.com/charmbracelet/bubbletea v1.3.6/go.mod h1:oQD9VCRQFF8KplacJLo28/jofOI2ToOfGYeFgBBxHOc=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
+github.com/charmbracelet/huh v1.0.0 h1:wOnedH8G4qzJbmhftTqrpppyqHakl/zbbNdXIWJyIxw=
+github.com/charmbracelet/huh v1.0.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4=
+github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
+github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
+github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh6GXd0=
+github.com/charmbracelet/x/ansi v0.9.3/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
+github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=
+github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
+github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U=
+github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ=
+github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
+github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
+github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
+github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
+github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
+github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
+github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
+github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
+github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI=
+github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d h1:ZtA1sedVbEW7EW80Iz2GR3Ye6PwbJAJXjv7D74xG6HU=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
@@ -35,6 +82,8 @@ github.com/gost-dom/css v0.1.0 h1:O4aXjnYonQH1EDwKysXCQOgGVLwCWd/+HJeGO15sDIE=
github.com/gost-dom/css v0.1.0/go.mod h1:BYfl+dr6Dzl6RoKn4op6TynJ7GmFqP0kFCM44NEVgNs=
github.com/gost-dom/fixture v0.1.0 h1:7PnEpkuww1QBOh4gyoR8updPfyosHJfxmFRY+2t05+w=
github.com/gost-dom/fixture v0.1.0/go.mod h1:7mSGaBhOfi/NO+YiD426CQ1DTkko62vYxoSVRmveqqY=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E=
github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
@@ -44,26 +93,62 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
+github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
+github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mark3labs/mcp-go v0.45.0 h1:s0S8qR/9fWaQ3pHxz7pm1uQ0DrswoSnRIxKIjbiQtkc=
github.com/mark3labs/mcp-go v0.45.0/go.mod h1:YnJfOL382MIWDx1kMY+2zsRHU/q78dBg9aFb8W6Thdw=
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
+github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
+github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
+github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
+github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
+github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
+github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
+github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A=
github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
+github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=
github.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=
@@ -72,19 +157,34 @@ github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9R
github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
+golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
diff --git a/internal/cliui/styles.go b/internal/cliui/styles.go
new file mode 100644
index 00000000..224bde09
--- /dev/null
+++ b/internal/cliui/styles.go
@@ -0,0 +1,64 @@
+package cliui
+
+import (
+ "os"
+ "strings"
+
+ "github.com/charmbracelet/lipgloss"
+)
+
+var (
+ ColorBorder = lipgloss.Color("#2b3345")
+ ColorTextPrimary = lipgloss.Color("#e2e8f0")
+ ColorTextMuted = lipgloss.Color("#64748b")
+ ColorAccent = lipgloss.Color("#60a5fa")
+ ColorAccentLight = lipgloss.Color("#93c5fd")
+ ColorSuccess = lipgloss.Color("#22c55e")
+ ColorWarning = lipgloss.Color("#fbbf24")
+ ColorDanger = lipgloss.Color("#ef4444")
+)
+
+var (
+ HeadingStyle = lipgloss.NewStyle().Foreground(ColorAccent).Bold(true)
+ CommandStyle = lipgloss.NewStyle().Foreground(ColorAccentLight)
+ MutedStyle = lipgloss.NewStyle().Foreground(ColorTextMuted)
+ SuccessStyle = lipgloss.NewStyle().Foreground(ColorSuccess).Bold(true)
+ WarningStyle = lipgloss.NewStyle().Foreground(ColorWarning).Bold(true)
+ ErrorStyle = lipgloss.NewStyle().Foreground(ColorDanger).Bold(true)
+ ValueStyle = lipgloss.NewStyle().Foreground(ColorTextPrimary)
+)
+
+func RenderStdout(style lipgloss.Style, text string) string {
+ return renderToWriter(os.Stdout, style, text)
+}
+
+func RenderStderr(style lipgloss.Style, text string) string {
+ return renderToWriter(os.Stderr, style, text)
+}
+
+func renderToWriter(w *os.File, style lipgloss.Style, text string) string {
+ if !shouldColorizeFile(w) {
+ return text
+ }
+ return style.Render(text)
+}
+
+func shouldColorizeFile(file *os.File) bool {
+ if file == nil {
+ return false
+ }
+ 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 := file.Stat()
+ if err != nil {
+ return false
+ }
+ return (info.Mode() & os.ModeCharDevice) != 0
+}
diff --git a/internal/config/config.go b/internal/config/config.go
deleted file mode 100644
index cb9304c0..00000000
--- a/internal/config/config.go
+++ /dev/null
@@ -1,1324 +0,0 @@
-package config
-
-import (
- "crypto/rand"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
-)
-
-// RuntimeConfig holds all runtime settings used throughout the application.
-// This is the single source of truth for configuration at runtime.
-type RuntimeConfig struct {
- // Server settings
- Bind string
- Port string
- InstancePortStart int // Starting port for instances (default 9868)
- InstancePortEnd int // Ending port for instances (default 9968)
- Token string
- StateDir string
-
- // Security settings
- AllowEvaluate bool
- AllowMacro bool
- AllowScreencast bool
- AllowDownload bool
- AllowUpload bool
- MaxRedirects int // Max HTTP redirects (-1=unlimited, 0=none, default=-1)
-
- // Browser/instance settings
- Headless bool
- NoRestore bool
- ProfileDir string
- ProfilesBaseDir string
- DefaultProfile string
- ChromeVersion string
- Timezone string
- BlockImages bool
- BlockMedia bool
- BlockAds bool
- MaxTabs int
- MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU
- ChromeBinary string
- ChromeExtraFlags string
- ExtensionPaths []string
- UserAgent string
- NoAnimations bool
- StealthLevel string
- TabEvictionPolicy string // "close_lru" (default), "reject", "close_oldest"
-
- // Timeout settings
- ActionTimeout time.Duration
- NavigateTimeout time.Duration
- ShutdownTimeout time.Duration
- WaitNavDelay time.Duration
-
- // Orchestrator settings (dashboard mode only)
- Strategy string // "always-on" (default), "simple", "explicit", or "simple-autorestart"
- AllocationPolicy string // "fcfs" (default), "round_robin", "random"
- RestartMaxRestarts int // Max restart attempts for restart-managed strategies (-1 = unlimited, 0 = strategy default)
- RestartInitBackoff time.Duration // Initial restart backoff (0 = strategy default)
- RestartMaxBackoff time.Duration // Maximum restart backoff cap (0 = strategy default)
- RestartStableAfter time.Duration // Stable runtime window that resets the restart counter (0 = strategy default)
-
- // Attach settings
- AttachEnabled bool
- AttachAllowHosts []string
- AttachAllowSchemes []string
-
- // IDPI (Indirect Prompt Injection defense) settings
- IDPI IDPIConfig
-
- // Engine mode: "chrome" (default), "lite", or "auto"
- Engine string
-
- // Scheduler settings (dashboard mode only)
- Scheduler SchedulerConfig
-}
-
-// EnabledSensitiveEndpoints returns the names of sensitive endpoint families
-// that are currently enabled in the runtime configuration.
-func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {
- if cfg == nil {
- return nil
- }
-
- enabled := make([]string, 0, 5)
- if cfg.AllowEvaluate {
- enabled = append(enabled, "evaluate")
- }
- if cfg.AllowMacro {
- enabled = append(enabled, "macro")
- }
- if cfg.AllowScreencast {
- enabled = append(enabled, "screencast")
- }
- if cfg.AllowDownload {
- enabled = append(enabled, "download")
- }
- if cfg.AllowUpload {
- enabled = append(enabled, "upload")
- }
- return enabled
-}
-
-// SchedulerConfig holds task scheduler settings.
-type SchedulerConfig struct {
- Enabled bool `json:"enabled,omitempty"`
- Strategy string `json:"strategy,omitempty"`
- MaxQueueSize int `json:"maxQueueSize,omitempty"`
- MaxPerAgent int `json:"maxPerAgent,omitempty"`
- MaxInflight int `json:"maxInflight,omitempty"`
- MaxPerAgentFlight int `json:"maxPerAgentInflight,omitempty"`
- ResultTTLSec int `json:"resultTTLSec,omitempty"`
- WorkerCount int `json:"workerCount,omitempty"`
-}
-
-// --- Nested FileConfig structure (PR #91 model) ---
-
-// FileConfig is the persistent configuration written to disk.
-// Uses nested sections that match actual runtime ownership.
-type FileConfig struct {
- Server ServerConfig `json:"server,omitempty"`
- Browser BrowserConfig `json:"browser,omitempty"`
- InstanceDefaults InstanceDefaultsConfig `json:"instanceDefaults,omitempty"`
- Security SecurityConfig `json:"security,omitempty"`
- Profiles ProfilesConfig `json:"profiles,omitempty"`
- MultiInstance MultiInstanceConfig `json:"multiInstance,omitempty"`
- Timeouts TimeoutsConfig `json:"timeouts,omitempty"`
- Scheduler SchedulerFileConfig `json:"scheduler,omitempty"`
-}
-
-// ServerConfig holds server/network settings.
-type ServerConfig struct {
- Port string `json:"port,omitempty"`
- Bind string `json:"bind,omitempty"`
- Token string `json:"token,omitempty"`
- StateDir string `json:"stateDir,omitempty"`
- Engine string `json:"engine,omitempty"`
-}
-
-// BrowserConfig holds Chrome executable/runtime wiring.
-type BrowserConfig struct {
- ChromeVersion string `json:"version,omitempty"`
- ChromeBinary string `json:"binary,omitempty"`
- ChromeExtraFlags string `json:"extraFlags,omitempty"`
- ExtensionPaths []string `json:"extensionPaths,omitempty"`
-}
-
-// InstanceDefaultsConfig holds the default behavior for a launched browser instance.
-type InstanceDefaultsConfig struct {
- Mode string `json:"mode,omitempty"`
- NoRestore *bool `json:"noRestore,omitempty"`
- Timezone string `json:"timezone,omitempty"`
- BlockImages *bool `json:"blockImages,omitempty"`
- BlockMedia *bool `json:"blockMedia,omitempty"`
- BlockAds *bool `json:"blockAds,omitempty"`
- MaxTabs *int `json:"maxTabs,omitempty"`
- MaxParallelTabs *int `json:"maxParallelTabs,omitempty"`
- UserAgent string `json:"userAgent,omitempty"`
- NoAnimations *bool `json:"noAnimations,omitempty"`
- StealthLevel string `json:"stealthLevel,omitempty"`
- TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"`
-}
-
-// ProfilesConfig holds profile storage defaults.
-type ProfilesConfig struct {
- BaseDir string `json:"baseDir,omitempty"`
- DefaultProfile string `json:"defaultProfile,omitempty"`
-}
-
-// 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"`
- MaxRedirects *int `json:"maxRedirects,omitempty"` // Max HTTP redirects per navigation (-1=unlimited, 0=none, default=-1)
- Attach AttachConfig `json:"attach,omitempty"`
- IDPI IDPIConfig `json:"idpi,omitempty"`
-}
-
-// IDPIConfig holds the configuration for the Indirect Prompt Injection (IDPI)
-// defense layer. All fields default to zero/false, making the feature fully
-// opt-in with no change to existing behaviour when Enabled is false.
-type IDPIConfig struct {
- // Enabled is the master switch. No IDPI checks are performed when false.
- Enabled bool `json:"enabled,omitempty"`
-
- // AllowedDomains is a whitelist of permitted navigation targets.
- // An empty list means all domains are allowed (no restriction).
- // 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.
- // true β†’ block the request (HTTP 403 for navigation; scan refuses response).
- // false β†’ allow the request but emit an X-IDPI-Warning response header.
- StrictMode bool `json:"strictMode,omitempty"`
-
- // ScanContent enables keyword-pattern scanning on page content returned by
- // /snapshot and /text. When a known injection phrase is detected the
- // response is annotated (warn mode) or refused (strict mode).
- ScanContent bool `json:"scanContent,omitempty"`
-
- // WrapContent wraps plain-text output from /text in
- // <untrusted_web_content> XML delimiters and prepends a safety advisory
- // so downstream LLMs treat the content as data, not as instructions.
- WrapContent bool `json:"wrapContent,omitempty"`
-
- // CustomPatterns is a user-extensible list of additional injection-detection
- // phrases. Matched case-insensitively, same as the built-in patterns.
- CustomPatterns []string `json:"customPatterns,omitempty"`
-
- // ScanTimeoutSec is the maximum number of seconds the CDP page-text fetch
- // (body.innerText) may take during content scanning. Capped to prevent the
- // IDPI scan from consuming the full action-timeout budget.
- // Defaults to 5. A value ≀ 0 is treated as the default.
- ScanTimeoutSec int `json:"scanTimeoutSec,omitempty"`
-}
-
-var defaultLocalAllowedDomains = []string{"127.0.0.1", "localhost", "::1"}
-
-// MultiInstanceConfig holds multi-instance orchestration settings.
-type MultiInstanceConfig struct {
- Strategy string `json:"strategy,omitempty"`
- AllocationPolicy string `json:"allocationPolicy,omitempty"`
- InstancePortStart *int `json:"instancePortStart,omitempty"`
- InstancePortEnd *int `json:"instancePortEnd,omitempty"`
- Restart MultiInstanceRestartConfig `json:"restart,omitempty"`
-}
-
-// MultiInstanceRestartConfig controls restart-managed strategy recovery behavior.
-type MultiInstanceRestartConfig struct {
- MaxRestarts *int `json:"maxRestarts,omitempty"`
- InitBackoffSec *int `json:"initBackoffSec,omitempty"`
- MaxBackoffSec *int `json:"maxBackoffSec,omitempty"`
- StableAfterSec *int `json:"stableAfterSec,omitempty"`
-}
-
-// AttachConfig holds policy for attaching to externally managed Chrome instances.
-type AttachConfig struct {
- Enabled *bool `json:"enabled,omitempty"`
- AllowHosts []string `json:"allowHosts,omitempty"`
- AllowSchemes []string `json:"allowSchemes,omitempty"`
-}
-
-// TimeoutsConfig holds timeout settings.
-type TimeoutsConfig struct {
- ActionSec int `json:"actionSec,omitempty"`
- NavigateSec int `json:"navigateSec,omitempty"`
- ShutdownSec int `json:"shutdownSec,omitempty"`
- WaitNavMs int `json:"waitNavMs,omitempty"`
-}
-
-// SchedulerFileConfig holds scheduler settings in the config file.
-type SchedulerFileConfig struct {
- Enabled *bool `json:"enabled,omitempty"`
- Strategy string `json:"strategy,omitempty"`
- MaxQueueSize *int `json:"maxQueueSize,omitempty"`
- MaxPerAgent *int `json:"maxPerAgent,omitempty"`
- MaxInflight *int `json:"maxInflight,omitempty"`
- MaxPerAgentFlight *int `json:"maxPerAgentInflight,omitempty"`
- ResultTTLSec *int `json:"resultTTLSec,omitempty"`
- WorkerCount *int `json:"workerCount,omitempty"`
-}
-
-// --- Legacy flat FileConfig for backward compatibility ---
-
-// legacyFileConfig is the old flat structure for backward compatibility.
-type legacyFileConfig struct {
- Port string `json:"port"`
- InstancePortStart *int `json:"instancePortStart,omitempty"`
- InstancePortEnd *int `json:"instancePortEnd,omitempty"`
- Token string `json:"token,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"`
- StateDir string `json:"stateDir"`
- ProfileDir string `json:"profileDir"`
- Headless *bool `json:"headless,omitempty"`
- NoRestore bool `json:"noRestore"`
- MaxTabs *int `json:"maxTabs,omitempty"`
- TimeoutSec int `json:"timeoutSec,omitempty"`
- NavigateSec int `json:"navigateSec,omitempty"`
-}
-
-// convertLegacyConfig converts flat config to nested structure.
-func convertLegacyConfig(lc *legacyFileConfig) *FileConfig {
- fc := &FileConfig{}
-
- // Server
- fc.Server.Port = lc.Port
- fc.Server.Token = lc.Token
- fc.Server.StateDir = lc.StateDir
-
- // Browser / instance defaults
- if lc.Headless != nil {
- if *lc.Headless {
- fc.InstanceDefaults.Mode = "headless"
- } else {
- fc.InstanceDefaults.Mode = "headed"
- }
- }
- fc.InstanceDefaults.MaxTabs = lc.MaxTabs
- if lc.NoRestore {
- b := true
- fc.InstanceDefaults.NoRestore = &b
- }
-
- // Profiles
- if lc.ProfileDir != "" {
- fc.Profiles.BaseDir = filepath.Dir(lc.ProfileDir)
- fc.Profiles.DefaultProfile = filepath.Base(lc.ProfileDir)
- }
-
- // Security
- fc.Security.AllowEvaluate = lc.AllowEvaluate
- fc.Security.AllowMacro = lc.AllowMacro
- fc.Security.AllowScreencast = lc.AllowScreencast
- fc.Security.AllowDownload = lc.AllowDownload
- fc.Security.AllowUpload = lc.AllowUpload
-
- // Timeouts
- fc.Timeouts.ActionSec = lc.TimeoutSec
- fc.Timeouts.NavigateSec = lc.NavigateSec
-
- // Multi-instance
- fc.MultiInstance.InstancePortStart = lc.InstancePortStart
- fc.MultiInstance.InstancePortEnd = lc.InstancePortEnd
-
- return fc
-}
-
-// isLegacyConfig detects if JSON is flat (legacy) or nested (new).
-// Returns true if it looks like legacy format.
-func isLegacyConfig(data []byte) bool {
- var probe map[string]json.RawMessage
- if err := json.Unmarshal(data, &probe); err != nil {
- return false
- }
-
- // If any new nested keys exist, it's new format
- if _, hasServer := probe["server"]; hasServer {
- return false
- }
- if _, hasBrowser := probe["browser"]; hasBrowser {
- return false
- }
- if _, hasInstanceDefaults := probe["instanceDefaults"]; hasInstanceDefaults {
- return false
- }
- if _, hasProfiles := probe["profiles"]; hasProfiles {
- return false
- }
- if _, hasMultiInstance := probe["multiInstance"]; hasMultiInstance {
- return false
- }
- if _, hasSecurity := probe["security"]; hasSecurity {
- return false
- }
- if _, hasAttach := probe["attach"]; hasAttach {
- return false
- }
- if _, hasTimeouts := probe["timeouts"]; hasTimeouts {
- return false
- }
-
- // If "port" or "headless" exist at top level, it's legacy
- if _, hasPort := probe["port"]; hasPort {
- return true
- }
- if _, hasHeadless := probe["headless"]; hasHeadless {
- return true
- }
-
- // Default to new format for empty/unknown
- return false
-}
-
-// --- Environment variable helpers ---
-
-func envOr(key, fallback string) string {
- if v := os.Getenv(key); v != "" {
- return v
- }
- return fallback
-}
-
-func envIntOr(key string, fallback int) int {
- v := os.Getenv(key)
- if v == "" {
- return fallback
- }
- n, err := strconv.Atoi(v)
- if err != nil || n < 0 {
- return fallback
- }
- return n
-}
-
-// homeDir returns the user's home directory, checking $HOME first for container compatibility
-func homeDir() string {
- if home := os.Getenv("HOME"); home != "" {
- return home
- }
- h, _ := os.UserHomeDir()
- return h
-}
-
-// userConfigDir returns the OS-appropriate app config directory:
-// - macOS: ~/Library/Application Support/pinchtab
-// - Linux: ~/.config/pinchtab (or $XDG_CONFIG_HOME/pinchtab)
-// - Windows: %APPDATA%\pinchtab
-//
-// For backwards compatibility:
-// 1. If ~/.pinchtab/config.json exists (and new location doesn't) β†’ use legacy
-// 2. If ~/.pinchtab dir exists (and new dir doesn't) β†’ use legacy (for init)
-// 3. Otherwise β†’ use new XDG path
-func userConfigDir() string {
- home := homeDir()
- legacyPath := filepath.Join(home, ".pinchtab")
-
- // Try to get OS-appropriate config directory
- configDir, err := os.UserConfigDir()
- if err != nil {
- // Fallback to legacy location if UserConfigDir fails
- return legacyPath
- }
-
- newPath := filepath.Join(configDir, "pinchtab")
-
- // Priority 1: Check for config FILE (handles case where both dirs exist
- // but only legacy has config.json β€” the issue #224 scenario)
- legacyConfig := filepath.Join(legacyPath, "config.json")
- newConfig := filepath.Join(newPath, "config.json")
-
- if fileExists(legacyConfig) && !fileExists(newConfig) {
- return legacyPath
- }
-
- // Priority 2: Check for DIRECTORY (handles init scenario where
- // legacy dir exists from npm install but no config yet)
- if dirExists(legacyPath) && !dirExists(newPath) {
- return legacyPath
- }
-
- return newPath
-}
-
-// dirExists checks if a directory exists
-func dirExists(path string) bool {
- info, err := os.Stat(path)
- if err != nil {
- return false
- }
- return info.IsDir()
-}
-
-// fileExists checks if a file exists (not a directory)
-func fileExists(path string) bool {
- info, err := os.Stat(path)
- if err != nil {
- return false
- }
- return !info.IsDir()
-}
-
-func (c *RuntimeConfig) ListenAddr() string {
- return c.Bind + ":" + c.Port
-}
-
-func modeToHeadless(mode string, fallback bool) bool {
- switch strings.ToLower(strings.TrimSpace(mode)) {
- case "":
- return fallback
- case "headless":
- return true
- case "headed":
- return false
- default:
- return fallback
- }
-}
-
-func finalizeProfileConfig(cfg *RuntimeConfig) {
- if cfg.DefaultProfile == "" {
- cfg.DefaultProfile = "default"
- }
- if cfg.ProfilesBaseDir == "" {
- cfg.ProfilesBaseDir = filepath.Join(cfg.StateDir, "profiles")
- }
- if cfg.ProfileDir == "" {
- cfg.ProfileDir = filepath.Join(cfg.ProfilesBaseDir, cfg.DefaultProfile)
- }
-}
-
-// 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{
- // Server defaults + selected env vars
- Bind: envOr("PINCHTAB_BIND", "127.0.0.1"),
- Port: envOr("PINCHTAB_PORT", "9867"),
- InstancePortStart: 9868,
- InstancePortEnd: 9968,
- Token: os.Getenv("PINCHTAB_TOKEN"),
- StateDir: userConfigDir(),
-
- // Security defaults
- AllowEvaluate: false,
- AllowMacro: false,
- AllowScreencast: false,
- AllowDownload: false,
- AllowUpload: false,
- MaxRedirects: -1, // Unlimited by default; set to N to limit redirect hops
-
- // Browser / instance defaults
- Headless: true,
- NoRestore: false,
- ProfileDir: "",
- ProfilesBaseDir: "",
- DefaultProfile: "default",
- ChromeVersion: "144.0.7559.133",
- Timezone: "",
- BlockImages: false,
- BlockMedia: false,
- BlockAds: false,
- MaxTabs: 20,
- MaxParallelTabs: 0,
- ChromeBinary: "", // Set via config.json only; env var CHROME_BIN removed
- ChromeExtraFlags: "",
- ExtensionPaths: nil,
- UserAgent: "",
- NoAnimations: false,
- StealthLevel: "light",
- TabEvictionPolicy: "close_lru",
-
- // Timeout defaults
- ActionTimeout: 30 * time.Second,
- NavigateTimeout: 60 * time.Second,
- ShutdownTimeout: 10 * time.Second,
- WaitNavDelay: 1 * time.Second,
-
- // Orchestrator defaults
- Strategy: "always-on",
- AllocationPolicy: "fcfs",
- RestartMaxRestarts: 20,
- RestartInitBackoff: 2 * time.Second,
- RestartMaxBackoff: 60 * time.Second,
- RestartStableAfter: 5 * time.Minute,
-
- // Attach defaults
- 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,
- ScanTimeoutSec: 5,
- },
-
- // Engine default
- Engine: envOr("PINCHTAB_ENGINE", "chrome"),
- }
- finalizeProfileConfig(cfg)
-
- // Load config file (supports both legacy flat and new nested format)
- configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- if !os.IsNotExist(err) {
- slog.Warn("failed to read config file", "path", configPath, "error", err)
- }
- return cfg
- }
-
- slog.Debug("loading config file", "path", configPath)
-
- var fc *FileConfig
-
- if isLegacyConfig(data) {
- var lc legacyFileConfig
- if err := json.Unmarshal(data, &lc); err != nil {
- slog.Warn("failed to parse legacy config", "path", configPath, "error", err)
- return cfg
- }
- fc = convertLegacyConfig(&lc)
- slog.Info("loaded legacy flat config, consider migrating to nested format", "path", configPath)
- } else {
- fc = &FileConfig{}
- if err := json.Unmarshal(data, fc); err != nil {
- slog.Warn("failed to parse config", "path", configPath, "error", err)
- return cfg
- }
- }
-
- // Validate file config and log warnings
- if errs := ValidateFileConfig(fc); len(errs) > 0 {
- for _, e := range errs {
- slog.Warn("config validation error", "path", configPath, "error", e)
- }
- }
-
- // Apply file config (only if env var NOT set)
- applyFileConfig(cfg, fc)
- finalizeProfileConfig(cfg)
-
- return cfg
-}
-
-// applyFileConfig merges FileConfig values into RuntimeConfig.
-// Only applies values where the corresponding env var is NOT set.
-func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
- // Server
- if fc.Server.Port != "" && os.Getenv("PINCHTAB_PORT") == "" {
- cfg.Port = fc.Server.Port
- }
- if fc.Server.Bind != "" && os.Getenv("PINCHTAB_BIND") == "" {
- cfg.Bind = fc.Server.Bind
- }
- if fc.Server.Token != "" && os.Getenv("PINCHTAB_TOKEN") == "" {
- cfg.Token = fc.Server.Token
- }
- if fc.Server.StateDir != "" {
- cfg.StateDir = fc.Server.StateDir
- }
- if fc.Server.Engine != "" && os.Getenv("PINCHTAB_ENGINE") == "" {
- cfg.Engine = fc.Server.Engine
- }
- // Security
- if fc.Security.AllowEvaluate != nil {
- cfg.AllowEvaluate = *fc.Security.AllowEvaluate
- }
- if fc.Security.AllowMacro != nil {
- cfg.AllowMacro = *fc.Security.AllowMacro
- }
- if fc.Security.AllowScreencast != nil {
- cfg.AllowScreencast = *fc.Security.AllowScreencast
- }
- if fc.Security.AllowDownload != nil {
- cfg.AllowDownload = *fc.Security.AllowDownload
- }
- if fc.Security.AllowUpload != nil {
- cfg.AllowUpload = *fc.Security.AllowUpload
- }
- if fc.Security.MaxRedirects != nil {
- cfg.MaxRedirects = *fc.Security.MaxRedirects
- }
- // IDPI – copy the whole struct; individual fields have safe zero-value defaults.
- cfg.IDPI = fc.Security.IDPI
-
- // Browser
- if fc.Browser.ChromeVersion != "" {
- cfg.ChromeVersion = fc.Browser.ChromeVersion
- }
- if fc.Browser.ChromeBinary != "" {
- cfg.ChromeBinary = fc.Browser.ChromeBinary
- }
- if fc.Browser.ChromeExtraFlags != "" {
- cfg.ChromeExtraFlags = fc.Browser.ChromeExtraFlags
- }
- if len(fc.Browser.ExtensionPaths) > 0 {
- cfg.ExtensionPaths = fc.Browser.ExtensionPaths
- }
-
- // Instance defaults
- if fc.InstanceDefaults.Mode != "" {
- cfg.Headless = modeToHeadless(fc.InstanceDefaults.Mode, cfg.Headless)
- }
- if fc.InstanceDefaults.NoRestore != nil {
- cfg.NoRestore = *fc.InstanceDefaults.NoRestore
- }
- if fc.InstanceDefaults.Timezone != "" {
- cfg.Timezone = fc.InstanceDefaults.Timezone
- }
- if fc.InstanceDefaults.BlockImages != nil {
- cfg.BlockImages = *fc.InstanceDefaults.BlockImages
- }
- if fc.InstanceDefaults.BlockMedia != nil {
- cfg.BlockMedia = *fc.InstanceDefaults.BlockMedia
- }
- if fc.InstanceDefaults.BlockAds != nil {
- cfg.BlockAds = *fc.InstanceDefaults.BlockAds
- }
- if fc.InstanceDefaults.MaxTabs != nil {
- cfg.MaxTabs = *fc.InstanceDefaults.MaxTabs
- }
- if fc.InstanceDefaults.MaxParallelTabs != nil {
- cfg.MaxParallelTabs = *fc.InstanceDefaults.MaxParallelTabs
- }
- if fc.InstanceDefaults.UserAgent != "" {
- cfg.UserAgent = fc.InstanceDefaults.UserAgent
- }
- if fc.InstanceDefaults.NoAnimations != nil {
- cfg.NoAnimations = *fc.InstanceDefaults.NoAnimations
- }
- if fc.InstanceDefaults.StealthLevel != "" {
- cfg.StealthLevel = fc.InstanceDefaults.StealthLevel
- }
- if fc.InstanceDefaults.TabEvictionPolicy != "" {
- cfg.TabEvictionPolicy = fc.InstanceDefaults.TabEvictionPolicy
- }
-
- // Profiles
- if fc.Profiles.BaseDir != "" {
- cfg.ProfilesBaseDir = fc.Profiles.BaseDir
- }
- if fc.Profiles.DefaultProfile != "" {
- cfg.DefaultProfile = fc.Profiles.DefaultProfile
- }
- cfg.ProfileDir = ""
-
- // Multi-instance
- if fc.MultiInstance.Strategy != "" {
- cfg.Strategy = fc.MultiInstance.Strategy
- }
- if fc.MultiInstance.AllocationPolicy != "" {
- cfg.AllocationPolicy = fc.MultiInstance.AllocationPolicy
- }
- if fc.MultiInstance.InstancePortStart != nil {
- cfg.InstancePortStart = *fc.MultiInstance.InstancePortStart
- }
- if fc.MultiInstance.InstancePortEnd != nil {
- cfg.InstancePortEnd = *fc.MultiInstance.InstancePortEnd
- }
- if fc.MultiInstance.Restart.MaxRestarts != nil {
- cfg.RestartMaxRestarts = *fc.MultiInstance.Restart.MaxRestarts
- }
- if fc.MultiInstance.Restart.InitBackoffSec != nil {
- cfg.RestartInitBackoff = time.Duration(*fc.MultiInstance.Restart.InitBackoffSec) * time.Second
- }
- if fc.MultiInstance.Restart.MaxBackoffSec != nil {
- cfg.RestartMaxBackoff = time.Duration(*fc.MultiInstance.Restart.MaxBackoffSec) * time.Second
- }
- if fc.MultiInstance.Restart.StableAfterSec != nil {
- cfg.RestartStableAfter = time.Duration(*fc.MultiInstance.Restart.StableAfterSec) * time.Second
- }
-
- // Attach
- if fc.Security.Attach.Enabled != nil {
- cfg.AttachEnabled = *fc.Security.Attach.Enabled
- }
- if len(fc.Security.Attach.AllowHosts) > 0 {
- cfg.AttachAllowHosts = append([]string(nil), fc.Security.Attach.AllowHosts...)
- }
- if len(fc.Security.Attach.AllowSchemes) > 0 {
- cfg.AttachAllowSchemes = append([]string(nil), fc.Security.Attach.AllowSchemes...)
- }
-
- // Timeouts
- if fc.Timeouts.ActionSec > 0 {
- cfg.ActionTimeout = time.Duration(fc.Timeouts.ActionSec) * time.Second
- }
- if fc.Timeouts.NavigateSec > 0 {
- cfg.NavigateTimeout = time.Duration(fc.Timeouts.NavigateSec) * time.Second
- }
- if fc.Timeouts.ShutdownSec > 0 {
- cfg.ShutdownTimeout = time.Duration(fc.Timeouts.ShutdownSec) * time.Second
- }
- if fc.Timeouts.WaitNavMs > 0 {
- cfg.WaitNavDelay = time.Duration(fc.Timeouts.WaitNavMs) * time.Millisecond
- }
-
- // Scheduler
- if fc.Scheduler.Enabled != nil {
- cfg.Scheduler.Enabled = *fc.Scheduler.Enabled
- }
- if fc.Scheduler.Strategy != "" {
- cfg.Scheduler.Strategy = fc.Scheduler.Strategy
- }
- if fc.Scheduler.MaxQueueSize != nil {
- cfg.Scheduler.MaxQueueSize = *fc.Scheduler.MaxQueueSize
- }
- if fc.Scheduler.MaxPerAgent != nil {
- cfg.Scheduler.MaxPerAgent = *fc.Scheduler.MaxPerAgent
- }
- if fc.Scheduler.MaxInflight != nil {
- cfg.Scheduler.MaxInflight = *fc.Scheduler.MaxInflight
- }
- if fc.Scheduler.MaxPerAgentFlight != nil {
- cfg.Scheduler.MaxPerAgentFlight = *fc.Scheduler.MaxPerAgentFlight
- }
- if fc.Scheduler.ResultTTLSec != nil {
- cfg.Scheduler.ResultTTLSec = *fc.Scheduler.ResultTTLSec
- }
- if fc.Scheduler.WorkerCount != nil {
- cfg.Scheduler.WorkerCount = *fc.Scheduler.WorkerCount
- }
-}
-
-// ApplyFileConfigToRuntime merges file configuration into an existing runtime
-// config and refreshes derived profile paths for long-running processes.
-func ApplyFileConfigToRuntime(cfg *RuntimeConfig, fc *FileConfig) {
- if cfg == nil || fc == nil {
- return
- }
-
- applyFileConfig(cfg, fc)
- finalizeProfileConfig(cfg)
-}
-
-// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).
-func DefaultFileConfig() FileConfig {
- start := 9868
- end := 9968
- restartMaxRestarts := 20
- restartInitBackoffSec := 2
- restartMaxBackoffSec := 60
- restartStableAfterSec := 300
- maxTabs := 20
- allowEvaluate := false
- allowMacro := false
- allowScreencast := false
- allowDownload := false
- allowUpload := false
- maxRedirects := -1
- return FileConfig{
- Server: ServerConfig{
- Port: "9867",
- Bind: "127.0.0.1",
- StateDir: userConfigDir(),
- },
- Browser: BrowserConfig{
- ChromeVersion: "144.0.7559.133",
- },
- InstanceDefaults: InstanceDefaultsConfig{
- Mode: "headless",
- MaxTabs: &maxTabs,
- StealthLevel: "light",
- TabEvictionPolicy: "close_lru",
- },
- Security: SecurityConfig{
- AllowEvaluate: &allowEvaluate,
- AllowMacro: &allowMacro,
- AllowScreencast: &allowScreencast,
- AllowDownload: &allowDownload,
- AllowUpload: &allowUpload,
- MaxRedirects: &maxRedirects,
- 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,
- ScanTimeoutSec: 5,
- },
- },
- Profiles: ProfilesConfig{
- BaseDir: filepath.Join(userConfigDir(), "profiles"),
- DefaultProfile: "default",
- },
- MultiInstance: MultiInstanceConfig{
- Strategy: "always-on",
- AllocationPolicy: "fcfs",
- InstancePortStart: &start,
- InstancePortEnd: &end,
- Restart: MultiInstanceRestartConfig{
- MaxRestarts: &restartMaxRestarts,
- InitBackoffSec: &restartInitBackoffSec,
- MaxBackoffSec: &restartMaxBackoffSec,
- StableAfterSec: &restartStableAfterSec,
- },
- },
- Timeouts: TimeoutsConfig{
- ActionSec: 30,
- NavigateSec: 60,
- ShutdownSec: 10,
- WaitNavMs: 1000,
- },
- }
-}
-
-// FileConfigFromRuntime converts the effective runtime configuration back into a
-// nested file configuration shape. This is primarily used when orchestrator-launched
-// child instances need a generated config file.
-func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
- if cfg == nil {
- return DefaultFileConfig()
- }
-
- noRestore := cfg.NoRestore
- blockImages := cfg.BlockImages
- blockMedia := cfg.BlockMedia
- blockAds := cfg.BlockAds
- maxTabs := cfg.MaxTabs
- maxParallelTabs := cfg.MaxParallelTabs
- noAnimations := cfg.NoAnimations
- allowEvaluate := cfg.AllowEvaluate
- allowMacro := cfg.AllowMacro
- allowScreencast := cfg.AllowScreencast
- allowDownload := cfg.AllowDownload
- allowUpload := cfg.AllowUpload
- maxRedirects := cfg.MaxRedirects
- attachEnabled := cfg.AttachEnabled
- start := cfg.InstancePortStart
- end := cfg.InstancePortEnd
- restartMaxRestarts := cfg.RestartMaxRestarts
- restartInitBackoffSec := int(cfg.RestartInitBackoff / time.Second)
- restartMaxBackoffSec := int(cfg.RestartMaxBackoff / time.Second)
- restartStableAfterSec := int(cfg.RestartStableAfter / time.Second)
-
- mode := "headless"
- if !cfg.Headless {
- mode = "headed"
- }
-
- fc := FileConfig{
- Server: ServerConfig{
- Port: cfg.Port,
- Bind: cfg.Bind,
- Token: cfg.Token,
- StateDir: cfg.StateDir,
- Engine: cfg.Engine,
- },
- Browser: BrowserConfig{
- ChromeVersion: cfg.ChromeVersion,
- ChromeBinary: cfg.ChromeBinary,
- ChromeExtraFlags: cfg.ChromeExtraFlags,
- ExtensionPaths: append([]string(nil), cfg.ExtensionPaths...),
- },
- InstanceDefaults: InstanceDefaultsConfig{
- Mode: mode,
- NoRestore: &noRestore,
- Timezone: cfg.Timezone,
- BlockImages: &blockImages,
- BlockMedia: &blockMedia,
- BlockAds: &blockAds,
- MaxTabs: &maxTabs,
- MaxParallelTabs: &maxParallelTabs,
- UserAgent: cfg.UserAgent,
- NoAnimations: &noAnimations,
- StealthLevel: cfg.StealthLevel,
- TabEvictionPolicy: cfg.TabEvictionPolicy,
- },
- Security: SecurityConfig{
- AllowEvaluate: &allowEvaluate,
- AllowMacro: &allowMacro,
- AllowScreencast: &allowScreencast,
- AllowDownload: &allowDownload,
- AllowUpload: &allowUpload,
- MaxRedirects: &maxRedirects,
- Attach: AttachConfig{
- Enabled: &attachEnabled,
- AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
- AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
- },
- IDPI: cfg.IDPI,
- },
- Profiles: ProfilesConfig{
- BaseDir: cfg.ProfilesBaseDir,
- DefaultProfile: cfg.DefaultProfile,
- },
- MultiInstance: MultiInstanceConfig{
- Strategy: cfg.Strategy,
- AllocationPolicy: cfg.AllocationPolicy,
- InstancePortStart: &start,
- InstancePortEnd: &end,
- Restart: MultiInstanceRestartConfig{
- MaxRestarts: &restartMaxRestarts,
- InitBackoffSec: &restartInitBackoffSec,
- MaxBackoffSec: &restartMaxBackoffSec,
- StableAfterSec: &restartStableAfterSec,
- },
- },
- Timeouts: TimeoutsConfig{
- ActionSec: int(cfg.ActionTimeout / time.Second),
- NavigateSec: int(cfg.NavigateTimeout / time.Second),
- ShutdownSec: int(cfg.ShutdownTimeout / time.Second),
- WaitNavMs: int(cfg.WaitNavDelay / time.Millisecond),
- },
- }
-
- return fc
-}
-
-// HandleConfigCommand handles `pinchtab config <subcommand>`.
-func HandleConfigCommand(cfg *RuntimeConfig) {
- if len(os.Args) < 3 {
- printConfigUsage()
- return
- }
-
- switch os.Args[2] {
- case "init":
- handleConfigInit()
- case "show":
- handleConfigShow(cfg)
- case "path":
- handleConfigPath()
- case "validate":
- handleConfigValidate()
- case "get":
- handleConfigGet()
- case "set":
- handleConfigSet()
- case "patch":
- handleConfigPatch()
- default:
- fmt.Printf("Unknown command: %s\n", os.Args[2])
- printConfigUsage()
- os.Exit(1)
- }
-}
-
-func printConfigUsage() {
- fmt.Println("Usage: pinchtab config <command>")
- fmt.Println()
- fmt.Println("Commands:")
- fmt.Println(" init Create default config file")
- fmt.Println(" show Show current configuration")
- fmt.Println(" path Show config file path")
- fmt.Println(" validate Validate config file")
- fmt.Println(" get <path> Get a config value (e.g., server.port)")
- fmt.Println(" set <path> <val> Set a config value (e.g., server.port 8080)")
- fmt.Println(" patch <json> Merge JSON into config")
-}
-
-func handleConfigGet() {
- if len(os.Args) < 4 {
- fmt.Println("Usage: pinchtab config get <path>")
- fmt.Println()
- fmt.Println("Examples:")
- fmt.Println(" pinchtab config get server.port")
- fmt.Println(" pinchtab config get instanceDefaults.mode")
- fmt.Println(" pinchtab config get security.attach.allowHosts")
- fmt.Println()
- fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts")
- os.Exit(1)
- }
-
- path := os.Args[3]
-
- fc, _, err := LoadFileConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- value, err := GetConfigValue(fc, path)
- if err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Println(value)
-}
-
-func handleConfigInit() {
- configPath := filepath.Join(userConfigDir(), "config.json")
-
- if _, err := os.Stat(configPath); err == nil {
- fmt.Printf("Config file already exists at %s\n", configPath)
- fmt.Print("Overwrite? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
- }
- }
-
- if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
- fmt.Printf("Error creating directory: %v\n", err)
- os.Exit(1)
- }
-
- 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)
- os.Exit(1)
- }
-
- fmt.Printf("Config file created at %s\n", configPath)
- fmt.Println()
- fmt.Println("Example with auth token:")
- fmt.Println(`{
- "server": {
- "port": "9867",
- "token": "your-secret-token"
- },
- "instanceDefaults": {
- "mode": "headless",
- "maxTabs": 20
- },
- "profiles": {
- "defaultProfile": "default"
- }
-}`)
-}
-
-func handleConfigShow(cfg *RuntimeConfig) {
- fmt.Println("Current configuration (env > file > defaults):")
- fmt.Println()
- fmt.Println("Server:")
- fmt.Printf(" Port: %s\n", cfg.Port)
- fmt.Printf(" Bind: %s\n", cfg.Bind)
- fmt.Printf(" Token: %s\n", MaskToken(cfg.Token))
- fmt.Printf(" State Dir: %s\n", cfg.StateDir)
- fmt.Printf(" Instance Ports: %d-%d\n", cfg.InstancePortStart, cfg.InstancePortEnd)
- fmt.Println()
- fmt.Println("Security:")
- fmt.Printf(" Evaluate: %v\n", cfg.AllowEvaluate)
- fmt.Printf(" Macro: %v\n", cfg.AllowMacro)
- fmt.Printf(" Screencast: %v\n", cfg.AllowScreencast)
- fmt.Printf(" Download: %v\n", cfg.AllowDownload)
- fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
- fmt.Println()
- fmt.Println("Browser / Instance Defaults:")
- fmt.Printf(" Headless: %v\n", cfg.Headless)
- fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
- fmt.Printf(" Profile Dir: %s\n", cfg.ProfileDir)
- fmt.Printf(" Profiles Dir: %s\n", cfg.ProfilesBaseDir)
- fmt.Printf(" Default Profile: %s\n", cfg.DefaultProfile)
- fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)
- fmt.Printf(" Stealth: %s\n", cfg.StealthLevel)
- fmt.Printf(" Tab Eviction: %s\n", cfg.TabEvictionPolicy)
- fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)
- fmt.Println()
- fmt.Println("Multi-Instance:")
- fmt.Printf(" Strategy: %s\n", cfg.Strategy)
- fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
- fmt.Printf(" Max Restarts: %d\n", cfg.RestartMaxRestarts)
- fmt.Printf(" Init Backoff: %v\n", cfg.RestartInitBackoff)
- fmt.Printf(" Max Backoff: %v\n", cfg.RestartMaxBackoff)
- fmt.Printf(" Stable After: %v\n", cfg.RestartStableAfter)
- fmt.Println()
- fmt.Println("Attach:")
- fmt.Printf(" Enabled: %v\n", cfg.AttachEnabled)
- fmt.Printf(" Allow Hosts: %v\n", cfg.AttachAllowHosts)
- fmt.Printf(" Allow Schemes: %v\n", cfg.AttachAllowSchemes)
- fmt.Println()
- fmt.Println("Timeouts:")
- fmt.Printf(" Action: %v\n", cfg.ActionTimeout)
- fmt.Printf(" Navigate: %v\n", cfg.NavigateTimeout)
- fmt.Printf(" Shutdown: %v\n", cfg.ShutdownTimeout)
-}
-
-func handleConfigPath() {
- configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
- fmt.Println(configPath)
-}
-
-func handleConfigSet() {
- if len(os.Args) < 5 {
- fmt.Println("Usage: pinchtab config set <path> <value>")
- fmt.Println()
- fmt.Println("Examples:")
- 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, timeouts")
- os.Exit(1)
- }
-
- path := os.Args[3]
- value := os.Args[4]
-
- fc, configPath, err := LoadFileConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- if err := SetConfigValue(fc, path, value); err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
-
- // Validate before saving
- if errs := ValidateFileConfig(fc); len(errs) > 0 {
- fmt.Printf("Warning: new value causes validation error(s):\n")
- for _, e := range errs {
- fmt.Printf(" - %v\n", e)
- }
- fmt.Print("Save anyway? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- fmt.Println("Aborted.")
- return
- }
- }
-
- if err := SaveFileConfig(fc, configPath); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Printf("βœ“ Set %s = %s\n", path, value)
-}
-
-func handleConfigPatch() {
- if len(os.Args) < 4 {
- fmt.Println("Usage: pinchtab config patch '<json>'")
- fmt.Println()
- fmt.Println("Examples:")
- fmt.Println(` pinchtab config patch '{"server": {"port": "8080"}}'`)
- fmt.Println(` pinchtab config patch '{"instanceDefaults": {"mode": "headed", "maxTabs": 50}}'`)
- os.Exit(1)
- }
-
- jsonPatch := os.Args[3]
-
- fc, configPath, err := LoadFileConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- if err := PatchConfigJSON(fc, jsonPatch); err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
-
- // Validate before saving
- if errs := ValidateFileConfig(fc); len(errs) > 0 {
- fmt.Printf("Warning: patch causes validation error(s):\n")
- for _, e := range errs {
- fmt.Printf(" - %v\n", e)
- }
- fmt.Print("Save anyway? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- fmt.Println("Aborted.")
- return
- }
- }
-
- if err := SaveFileConfig(fc, configPath); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Println("βœ“ Config patched successfully")
-}
-
-func handleConfigValidate() {
- configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- fmt.Printf("Error reading config file: %v\n", err)
- os.Exit(1)
- }
-
- var fc *FileConfig
-
- if isLegacyConfig(data) {
- var lc legacyFileConfig
- if err := json.Unmarshal(data, &lc); err != nil {
- fmt.Printf("Error parsing config file: %v\n", err)
- os.Exit(1)
- }
- fc = convertLegacyConfig(&lc)
- fmt.Println("Note: Config file uses legacy flat format. Consider migrating to nested format.")
- fmt.Println()
- } else {
- fc = &FileConfig{}
- if err := json.Unmarshal(data, fc); err != nil {
- fmt.Printf("Error parsing config file: %v\n", err)
- os.Exit(1)
- }
- }
-
- errs := ValidateFileConfig(fc)
- if len(errs) == 0 {
- fmt.Printf("βœ“ Config file is valid: %s\n", configPath)
- return
- }
-
- fmt.Printf("βœ— Config file has %d error(s):\n", len(errs))
- for _, e := range errs {
- fmt.Printf(" - %v\n", e)
- }
- os.Exit(1)
-}
-
-// MaskToken masks a token for display (shows first/last 4 chars).
-func MaskToken(t string) string {
- if t == "" {
- return "(none)"
- }
- if len(t) <= 8 {
- return "***"
- }
- return t[:4] + "..." + t[len(t)-4:]
-}
diff --git a/internal/config/config_cmd.go b/internal/config/config_cmd.go
new file mode 100644
index 00000000..c70158c5
--- /dev/null
+++ b/internal/config/config_cmd.go
@@ -0,0 +1,275 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/spf13/cobra"
+)
+
+// ConfigCmd is the root command for configuration management.
+var ConfigCmd = &cobra.Command{
+ Use: "config",
+ Short: "Manage configuration",
+}
+
+func init() {
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "show",
+ Short: "Display current configuration",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := Load()
+ handleConfigShow(cfg)
+ },
+ })
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "init",
+ Short: "Initialize a new config file",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigInit()
+ },
+ })
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "path",
+ Short: "Show config file path",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigPath()
+ },
+ })
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "validate",
+ Short: "Validate config file",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigValidate()
+ },
+ })
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "get <path>",
+ Short: "Get a config value (e.g., server.port)",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigGet(args[0])
+ },
+ })
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "set <path> <val>",
+ Short: "Set a config value (e.g., server.port 8080)",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigSet(args[0], args[1])
+ },
+ })
+ ConfigCmd.AddCommand(&cobra.Command{
+ Use: "patch <json>",
+ Short: "Merge JSON into config",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigPatch(args[0])
+ },
+ })
+}
+
+func handleConfigShow(cfg *RuntimeConfig) {
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Current configuration (env > file > defaults):"))
+ fmt.Println()
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Server"))
+ fmt.Printf(" Port: %s\n", cfg.Port)
+ fmt.Printf(" Bind: %s\n", cfg.Bind)
+ fmt.Printf(" Token: %s\n", MaskToken(cfg.Token))
+ fmt.Printf(" State Dir: %s\n", cfg.StateDir)
+ fmt.Printf(" Instance Ports: %d-%d\n", cfg.InstancePortStart, cfg.InstancePortEnd)
+ fmt.Println()
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Security"))
+ fmt.Printf(" Evaluate: %v\n", cfg.AllowEvaluate)
+ fmt.Printf(" Macro: %v\n", cfg.AllowMacro)
+ fmt.Printf(" Screencast: %v\n", cfg.AllowScreencast)
+ fmt.Printf(" Download: %v\n", cfg.AllowDownload)
+ fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
+ fmt.Println()
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Browser / Instance Defaults"))
+ fmt.Printf(" Headless: %v\n", cfg.Headless)
+ fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
+ fmt.Printf(" Profile Dir: %s\n", cfg.ProfileDir)
+ fmt.Printf(" Profiles Dir: %s\n", cfg.ProfilesBaseDir)
+ fmt.Printf(" Default Profile: %s\n", cfg.DefaultProfile)
+ fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)
+ fmt.Printf(" Stealth: %s\n", cfg.StealthLevel)
+ fmt.Printf(" Tab Eviction: %s\n", cfg.TabEvictionPolicy)
+ fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)
+ fmt.Println()
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Multi-Instance"))
+ fmt.Printf(" Strategy: %s\n", cfg.Strategy)
+ fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
+ fmt.Printf(" Max Restarts: %d\n", cfg.RestartMaxRestarts)
+ fmt.Printf(" Init Backoff: %v\n", cfg.RestartInitBackoff)
+ fmt.Printf(" Max Backoff: %v\n", cfg.RestartMaxBackoff)
+ fmt.Printf(" Stable After: %v\n", cfg.RestartStableAfter)
+ fmt.Println()
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Attach"))
+ fmt.Printf(" Enabled: %v\n", cfg.AttachEnabled)
+ fmt.Printf(" Allow Hosts: %v\n", cfg.AttachAllowHosts)
+ fmt.Printf(" Allow Schemes: %v\n", cfg.AttachAllowSchemes)
+ fmt.Println()
+ fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Timeouts"))
+ fmt.Printf(" Action: %v\n", cfg.ActionTimeout)
+ fmt.Printf(" Navigate: %v\n", cfg.NavigateTimeout)
+ fmt.Printf(" Shutdown: %v\n", cfg.ShutdownTimeout)
+}
+
+func handleConfigInit() {
+ configPath := filepath.Join(userConfigDir(), "config.json")
+
+ if _, err := os.Stat(configPath); err == nil {
+ fmt.Printf("Config file already exists at %s\n", configPath)
+ fmt.Print("Overwrite? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
+ }
+ }
+
+ if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ fmt.Printf("Error creating directory: %v\n", err)
+ os.Exit(1)
+ }
+
+ 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)
+ os.Exit(1)
+ }
+
+ fmt.Printf("Config file created at %s\n", configPath)
+}
+
+func handleConfigPath() {
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+ fmt.Println(configPath)
+}
+
+func handleConfigGet(path string) {
+ fc, _, err := LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ value, err := GetConfigValue(fc, path)
+ if err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Println(value)
+}
+
+func handleConfigSet(path, value string) {
+ fc, configPath, err := LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := SetConfigValue(fc, path, value); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ if errs := ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Warning: new value causes validation error(s):\n")
+ for _, e := range errs {
+ fmt.Printf(" - %v\n", e)
+ }
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
+ }
+ }
+
+ if err := SaveFileConfig(fc, configPath); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("βœ“ Set %s = %s\n", path, value)
+}
+
+func handleConfigPatch(jsonPatch string) {
+ fc, configPath, err := LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := PatchConfigJSON(fc, jsonPatch); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ if errs := ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Warning: patch causes validation error(s):\n")
+ for _, e := range errs {
+ fmt.Printf(" - %v\n", e)
+ }
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
+ }
+ }
+
+ if err := SaveFileConfig(fc, configPath); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Println("βœ“ Config patched successfully")
+}
+
+func handleConfigValidate() {
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ fmt.Printf("Error reading config file: %v\n", err)
+ os.Exit(1)
+ }
+
+ var fc *FileConfig
+ if isLegacyConfig(data) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ fmt.Printf("Error parsing legacy config: %v\n", err)
+ os.Exit(1)
+ }
+ fc = convertLegacyConfig(&lc)
+ } else {
+ fc = &FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ fmt.Printf("Error parsing config: %v\n", err)
+ os.Exit(1)
+ }
+ }
+
+ if errs := ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("βœ— Config file has %d error(s):\n", len(errs))
+ for _, e := range errs {
+ fmt.Printf(" - %v\n", e)
+ }
+ os.Exit(1)
+ }
+ fmt.Printf("βœ“ Config file is valid: %s\n", configPath)
+}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
new file mode 100644
index 00000000..98d2564f
--- /dev/null
+++ b/internal/config/config_file.go
@@ -0,0 +1,291 @@
+package config
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).
+func DefaultFileConfig() FileConfig {
+ start := 9868
+ end := 9968
+ restartMaxRestarts := 20
+ restartInitBackoffSec := 2
+ restartMaxBackoffSec := 60
+ restartStableAfterSec := 300
+ maxTabs := 20
+ allowEvaluate := false
+ allowMacro := false
+ allowScreencast := false
+ allowDownload := false
+ allowUpload := false
+ maxRedirects := -1
+ return FileConfig{
+ Server: ServerConfig{
+ Port: "9867",
+ Bind: "127.0.0.1",
+ StateDir: userConfigDir(),
+ },
+ Browser: BrowserConfig{
+ ChromeVersion: "144.0.7559.133",
+ },
+ InstanceDefaults: InstanceDefaultsConfig{
+ Mode: "headless",
+ MaxTabs: &maxTabs,
+ StealthLevel: "light",
+ TabEvictionPolicy: "close_lru",
+ },
+ Security: SecurityConfig{
+ AllowEvaluate: &allowEvaluate,
+ AllowMacro: &allowMacro,
+ AllowScreencast: &allowScreencast,
+ AllowDownload: &allowDownload,
+ AllowUpload: &allowUpload,
+ MaxRedirects: &maxRedirects,
+ 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,
+ ScanTimeoutSec: 5,
+ },
+ },
+ Profiles: ProfilesConfig{
+ BaseDir: filepath.Join(userConfigDir(), "profiles"),
+ DefaultProfile: "default",
+ },
+ MultiInstance: MultiInstanceConfig{
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+ InstancePortStart: &start,
+ InstancePortEnd: &end,
+ Restart: MultiInstanceRestartConfig{
+ MaxRestarts: &restartMaxRestarts,
+ InitBackoffSec: &restartInitBackoffSec,
+ MaxBackoffSec: &restartMaxBackoffSec,
+ StableAfterSec: &restartStableAfterSec,
+ },
+ },
+ Timeouts: TimeoutsConfig{
+ ActionSec: 30,
+ NavigateSec: 60,
+ ShutdownSec: 10,
+ WaitNavMs: 1000,
+ },
+ }
+}
+
+// FileConfigFromRuntime converts the effective runtime configuration back into a
+// nested file configuration shape.
+func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
+ if cfg == nil {
+ return DefaultFileConfig()
+ }
+
+ noRestore := cfg.NoRestore
+ blockImages := cfg.BlockImages
+ blockMedia := cfg.BlockMedia
+ blockAds := cfg.BlockAds
+ maxTabs := cfg.MaxTabs
+ maxParallelTabs := cfg.MaxParallelTabs
+ noAnimations := cfg.NoAnimations
+ allowEvaluate := cfg.AllowEvaluate
+ allowMacro := cfg.AllowMacro
+ allowScreencast := cfg.AllowScreencast
+ allowDownload := cfg.AllowDownload
+ allowUpload := cfg.AllowUpload
+ maxRedirects := cfg.MaxRedirects
+ attachEnabled := cfg.AttachEnabled
+ start := cfg.InstancePortStart
+ end := cfg.InstancePortEnd
+ restartMaxRestarts := cfg.RestartMaxRestarts
+ restartInitBackoffSec := int(cfg.RestartInitBackoff / time.Second)
+ restartMaxBackoffSec := int(cfg.RestartMaxBackoff / time.Second)
+ restartStableAfterSec := int(cfg.RestartStableAfter / time.Second)
+
+ mode := "headless"
+ if !cfg.Headless {
+ mode = "headed"
+ }
+
+ fc := FileConfig{
+ Server: ServerConfig{
+ Port: cfg.Port,
+ Bind: cfg.Bind,
+ Token: cfg.Token,
+ StateDir: cfg.StateDir,
+ Engine: cfg.Engine,
+ },
+ Browser: BrowserConfig{
+ ChromeVersion: cfg.ChromeVersion,
+ ChromeBinary: cfg.ChromeBinary,
+ ChromeExtraFlags: cfg.ChromeExtraFlags,
+ ExtensionPaths: append([]string(nil), cfg.ExtensionPaths...),
+ },
+ InstanceDefaults: InstanceDefaultsConfig{
+ Mode: mode,
+ NoRestore: &noRestore,
+ Timezone: cfg.Timezone,
+ BlockImages: &blockImages,
+ BlockMedia: &blockMedia,
+ BlockAds: &blockAds,
+ MaxTabs: &maxTabs,
+ MaxParallelTabs: &maxParallelTabs,
+ UserAgent: cfg.UserAgent,
+ NoAnimations: &noAnimations,
+ StealthLevel: cfg.StealthLevel,
+ TabEvictionPolicy: cfg.TabEvictionPolicy,
+ },
+ Security: SecurityConfig{
+ AllowEvaluate: &allowEvaluate,
+ AllowMacro: &allowMacro,
+ AllowScreencast: &allowScreencast,
+ AllowDownload: &allowDownload,
+ AllowUpload: &allowUpload,
+ MaxRedirects: &maxRedirects,
+ Attach: AttachConfig{
+ Enabled: &attachEnabled,
+ AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
+ AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
+ },
+ IDPI: cfg.IDPI,
+ },
+ Profiles: ProfilesConfig{
+ BaseDir: cfg.ProfilesBaseDir,
+ DefaultProfile: cfg.DefaultProfile,
+ },
+ MultiInstance: MultiInstanceConfig{
+ Strategy: cfg.Strategy,
+ AllocationPolicy: cfg.AllocationPolicy,
+ InstancePortStart: &start,
+ InstancePortEnd: &end,
+ Restart: MultiInstanceRestartConfig{
+ MaxRestarts: &restartMaxRestarts,
+ InitBackoffSec: &restartInitBackoffSec,
+ MaxBackoffSec: &restartMaxBackoffSec,
+ StableAfterSec: &restartStableAfterSec,
+ },
+ },
+ Timeouts: TimeoutsConfig{
+ ActionSec: int(cfg.ActionTimeout / time.Second),
+ NavigateSec: int(cfg.NavigateTimeout / time.Second),
+ ShutdownSec: int(cfg.ShutdownTimeout / time.Second),
+ WaitNavMs: int(cfg.WaitNavDelay / time.Millisecond),
+ },
+ }
+
+ return fc
+}
+
+// legacyFileConfig is the old flat structure for backward compatibility.
+type legacyFileConfig struct {
+ Port string `json:"port"`
+ InstancePortStart *int `json:"instancePortStart,omitempty"`
+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+ Token string `json:"token,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"`
+ StateDir string `json:"stateDir"`
+ ProfileDir string `json:"profileDir"`
+ Headless *bool `json:"headless,omitempty"`
+ NoRestore bool `json:"noRestore"`
+ MaxTabs *int `json:"maxTabs,omitempty"`
+ TimeoutSec int `json:"timeoutSec,omitempty"`
+ NavigateSec int `json:"navigateSec,omitempty"`
+}
+
+// convertLegacyConfig converts flat config to nested structure.
+func convertLegacyConfig(lc *legacyFileConfig) *FileConfig {
+ fc := &FileConfig{}
+
+ // Server
+ fc.Server.Port = lc.Port
+ fc.Server.Token = lc.Token
+ fc.Server.StateDir = lc.StateDir
+
+ // Browser / instance defaults
+ if lc.Headless != nil {
+ if *lc.Headless {
+ fc.InstanceDefaults.Mode = "headless"
+ } else {
+ fc.InstanceDefaults.Mode = "headed"
+ }
+ }
+ fc.InstanceDefaults.MaxTabs = lc.MaxTabs
+ if lc.NoRestore {
+ b := true
+ fc.InstanceDefaults.NoRestore = &b
+ }
+
+ // Profiles
+ if lc.ProfileDir != "" {
+ fc.Profiles.BaseDir = filepath.Dir(lc.ProfileDir)
+ fc.Profiles.DefaultProfile = filepath.Base(lc.ProfileDir)
+ }
+
+ // Security
+ fc.Security.AllowEvaluate = lc.AllowEvaluate
+ fc.Security.AllowMacro = lc.AllowMacro
+ fc.Security.AllowScreencast = lc.AllowScreencast
+ fc.Security.AllowDownload = lc.AllowDownload
+ fc.Security.AllowUpload = lc.AllowUpload
+
+ // Timeouts
+ fc.Timeouts.ActionSec = lc.TimeoutSec
+ fc.Timeouts.NavigateSec = lc.NavigateSec
+
+ // Multi-instance
+ fc.MultiInstance.InstancePortStart = lc.InstancePortStart
+ fc.MultiInstance.InstancePortEnd = lc.InstancePortEnd
+
+ return fc
+}
+
+// isLegacyConfig detects if JSON is flat (legacy) or nested (new).
+func isLegacyConfig(data []byte) bool {
+ var probe map[string]json.RawMessage
+ if err := json.Unmarshal(data, &probe); err != nil {
+ return false
+ }
+
+ // If any new nested keys exist, it's new format
+ newKeys := []string{"server", "browser", "instanceDefaults", "profiles", "multiInstance", "security", "attach", "timeouts"}
+ for _, key := range newKeys {
+ if _, has := probe[key]; has {
+ return false
+ }
+ }
+
+ // If "port" or "headless" exist at top level, it's legacy
+ if _, hasPort := probe["port"]; hasPort {
+ return true
+ }
+ if _, hasHeadless := probe["headless"]; hasHeadless {
+ return true
+ }
+
+ return false
+}
+
+func modeToHeadless(mode string, fallback bool) bool {
+ switch strings.ToLower(strings.TrimSpace(mode)) {
+ case "":
+ return fallback
+ case "headless":
+ return true
+ case "headed":
+ return false
+ default:
+ return fallback
+ }
+}
diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.go
new file mode 100644
index 00000000..e2f852d4
--- /dev/null
+++ b/internal/config/config_file_test.go
@@ -0,0 +1,200 @@
+package config
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestDefaultFileConfig(t *testing.T) {
+ fc := DefaultFileConfig()
+ if fc.Server.Port != "9867" {
+ t.Errorf("DefaultFileConfig.Server.Port = %v, want 9867", fc.Server.Port)
+ }
+ if fc.Server.Bind != "127.0.0.1" {
+ t.Errorf("DefaultFileConfig.Server.Bind = %v, want 127.0.0.1", fc.Server.Bind)
+ }
+ if fc.InstanceDefaults.Mode != "headless" {
+ t.Errorf("DefaultFileConfig.InstanceDefaults.Mode = %v, want headless", fc.InstanceDefaults.Mode)
+ }
+ if fc.MultiInstance.Strategy != "simple" {
+ t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want simple", fc.MultiInstance.Strategy)
+ }
+ 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))
+ }
+ if fc.Security.AllowMacro == nil || *fc.Security.AllowMacro {
+ t.Errorf("DefaultFileConfig.Security.AllowMacro = %v, want explicit false", formatBoolPtr(fc.Security.AllowMacro))
+ }
+ if fc.Security.AllowScreencast == nil || *fc.Security.AllowScreencast {
+ t.Errorf("DefaultFileConfig.Security.AllowScreencast = %v, want explicit false", formatBoolPtr(fc.Security.AllowScreencast))
+ }
+ if fc.Security.AllowDownload == nil || *fc.Security.AllowDownload {
+ t.Errorf("DefaultFileConfig.Security.AllowDownload = %v, want explicit false", formatBoolPtr(fc.Security.AllowDownload))
+ }
+ if fc.Security.AllowUpload == nil || *fc.Security.AllowUpload {
+ t.Errorf("DefaultFileConfig.Security.AllowUpload = %v, want explicit false", formatBoolPtr(fc.Security.AllowUpload))
+ }
+ 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)
+ }
+}
+
+// TestIsLegacyConfig tests the format detection logic.
+func TestIsLegacyConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ json string
+ isLegacy bool
+ }{
+ {
+ name: "nested format with server",
+ json: `{"server": {"port": "9867"}}`,
+ isLegacy: false,
+ },
+ {
+ name: "nested format with instanceDefaults",
+ json: `{"instanceDefaults": {"mode": "headless"}}`,
+ isLegacy: false,
+ },
+ {
+ name: "nested format with security.attach",
+ json: `{"security": {"attach": {"enabled": true}}}`,
+ isLegacy: false,
+ },
+ {
+ name: "legacy format with port",
+ json: `{"port": "9867"}`,
+ isLegacy: true,
+ },
+ {
+ name: "legacy format with headless",
+ json: `{"headless": true}`,
+ isLegacy: true,
+ },
+ {
+ name: "empty object",
+ json: `{}`,
+ isLegacy: false,
+ },
+ {
+ name: "mixed - nested wins",
+ json: `{"server": {"port": "8888"}, "port": "7777"}`,
+ isLegacy: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := isLegacyConfig([]byte(tt.json))
+ if got != tt.isLegacy {
+ t.Errorf("isLegacyConfig(%s) = %v, want %v", tt.json, got, tt.isLegacy)
+ }
+ })
+ }
+}
+
+// TestConvertLegacyConfig tests the legacy to nested conversion.
+func TestConvertLegacyConfig(t *testing.T) {
+ h := false
+ maxTabs := 25
+ lc := &legacyFileConfig{
+ Port: "7777",
+ Headless: &h,
+ MaxTabs: &maxTabs,
+ AllowEvaluate: boolPtr(true),
+ TimeoutSec: 45,
+ NavigateSec: 90,
+ }
+
+ fc := convertLegacyConfig(lc)
+
+ if fc.Server.Port != "7777" {
+ t.Errorf("converted Server.Port = %v, want 7777", fc.Server.Port)
+ }
+ if fc.InstanceDefaults.Mode != "headed" {
+ t.Errorf("converted InstanceDefaults.Mode = %v, want headed", fc.InstanceDefaults.Mode)
+ }
+ if *fc.InstanceDefaults.MaxTabs != 25 {
+ t.Errorf("converted InstanceDefaults.MaxTabs = %v, want 25", *fc.InstanceDefaults.MaxTabs)
+ }
+ if *fc.Security.AllowEvaluate != true {
+ t.Errorf("converted Security.AllowEvaluate = %v, want true", *fc.Security.AllowEvaluate)
+ }
+ if fc.Timeouts.ActionSec != 45 {
+ t.Errorf("converted Timeouts.ActionSec = %v, want 45", fc.Timeouts.ActionSec)
+ }
+ if fc.Timeouts.NavigateSec != 90 {
+ t.Errorf("converted Timeouts.NavigateSec = %v, want 90", fc.Timeouts.NavigateSec)
+ }
+}
+
+// TestDefaultFileConfigJSON tests that DefaultFileConfig serializes correctly.
+func TestDefaultFileConfigJSON(t *testing.T) {
+ fc := DefaultFileConfig()
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ t.Fatalf("failed to marshal DefaultFileConfig: %v", err)
+ }
+
+ // Verify it can be parsed back
+ var parsed FileConfig
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ t.Fatalf("failed to unmarshal DefaultFileConfig output: %v", err)
+ }
+
+ if parsed.Server.Port != "9867" {
+ t.Errorf("round-trip Server.Port = %v, want 9867", parsed.Server.Port)
+ }
+ if parsed.InstanceDefaults.Mode != "headless" {
+ t.Errorf("round-trip InstanceDefaults.Mode = %v, want headless", parsed.InstanceDefaults.Mode)
+ }
+ if parsed.Security.AllowEvaluate == nil || *parsed.Security.AllowEvaluate {
+ t.Errorf("round-trip Security.AllowEvaluate = %v, want explicit false", formatBoolPtr(parsed.Security.AllowEvaluate))
+ }
+ if parsed.Security.AllowMacro == nil || *parsed.Security.AllowMacro {
+ t.Errorf("round-trip Security.AllowMacro = %v, want explicit false", formatBoolPtr(parsed.Security.AllowMacro))
+ }
+ if parsed.Security.AllowScreencast == nil || *parsed.Security.AllowScreencast {
+ t.Errorf("round-trip Security.AllowScreencast = %v, want explicit false", formatBoolPtr(parsed.Security.AllowScreencast))
+ }
+ if parsed.Security.AllowDownload == nil || *parsed.Security.AllowDownload {
+ t.Errorf("round-trip Security.AllowDownload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowDownload))
+ }
+ if parsed.Security.AllowUpload == nil || *parsed.Security.AllowUpload {
+ t.Errorf("round-trip Security.AllowUpload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowUpload))
+ }
+ 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 boolPtr(b bool) *bool {
+ return &b
+}
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
new file mode 100644
index 00000000..bf0d8412
--- /dev/null
+++ b/internal/config/config_load.go
@@ -0,0 +1,350 @@
+package config
+
+import (
+ "encoding/json"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strconv"
+ "time"
+)
+
+// Load returns the RuntimeConfig with precedence: env vars > config file > defaults.
+func Load() *RuntimeConfig {
+ cfg := &RuntimeConfig{
+ // Server defaults + selected env vars
+ Bind: envOr("PINCHTAB_BIND", "127.0.0.1"),
+ Port: envOr("PINCHTAB_PORT", "9867"),
+ InstancePortStart: 9868,
+ InstancePortEnd: 9968,
+ Token: os.Getenv("PINCHTAB_TOKEN"),
+ StateDir: userConfigDir(),
+
+ // Security defaults
+ AllowEvaluate: false,
+ AllowMacro: false,
+ AllowScreencast: false,
+ AllowDownload: false,
+ AllowUpload: false,
+ MaxRedirects: -1, // Unlimited by default; set to N to limit redirect hops
+
+ // Browser / instance defaults
+ Headless: true,
+ NoRestore: false,
+ ProfileDir: "",
+ ProfilesBaseDir: "",
+ DefaultProfile: "default",
+ ChromeVersion: "144.0.7559.133",
+ Timezone: "",
+ BlockImages: false,
+ BlockMedia: false,
+ BlockAds: false,
+ MaxTabs: 20,
+ MaxParallelTabs: 0,
+ ChromeBinary: "", // Set via config.json only; env var CHROME_BIN removed
+ ChromeExtraFlags: "",
+ ExtensionPaths: nil,
+ UserAgent: "",
+ NoAnimations: false,
+ StealthLevel: "light",
+ TabEvictionPolicy: "close_lru",
+
+ // Timeout defaults
+ ActionTimeout: 30 * time.Second,
+ NavigateTimeout: 60 * time.Second,
+ ShutdownTimeout: 10 * time.Second,
+ WaitNavDelay: 1 * time.Second,
+
+ // Orchestrator defaults
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+ RestartMaxRestarts: 20,
+ RestartInitBackoff: 2 * time.Second,
+ RestartMaxBackoff: 60 * time.Second,
+ RestartStableAfter: 5 * time.Minute,
+
+ // Attach defaults
+ 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,
+ ScanTimeoutSec: 5,
+ },
+
+ // Engine default
+ Engine: envOr("PINCHTAB_ENGINE", "chrome"),
+ }
+ finalizeProfileConfig(cfg)
+
+ // Load config file (supports both legacy flat and new nested format)
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ slog.Warn("failed to read config file", "path", configPath, "error", err)
+ }
+ return cfg
+ }
+
+ slog.Debug("loading config file", "path", configPath)
+
+ var fc *FileConfig
+
+ if isLegacyConfig(data) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ slog.Warn("failed to parse legacy config", "path", configPath, "error", err)
+ return cfg
+ }
+ fc = convertLegacyConfig(&lc)
+ slog.Info("loaded legacy flat config, consider migrating to nested format", "path", configPath)
+ } else {
+ fc = &FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ slog.Warn("failed to parse config", "path", configPath, "error", err)
+ return cfg
+ }
+ }
+
+ // Validate file config and log warnings
+ if errs := ValidateFileConfig(fc); len(errs) > 0 {
+ for _, e := range errs {
+ slog.Warn("config validation error", "path", configPath, "error", e)
+ }
+ }
+
+ // Apply file config (only if env var NOT set)
+ applyFileConfig(cfg, fc)
+ finalizeProfileConfig(cfg)
+
+ return cfg
+}
+
+func envOr(key, fallback string) string {
+ if v := os.Getenv(key); v != "" {
+ return v
+ }
+ return fallback
+}
+
+func envIntOr(key string, fallback int) int {
+ v := os.Getenv(key)
+ if v == "" {
+ return fallback
+ }
+ n, err := strconv.Atoi(v)
+ if err != nil || n < 0 {
+ return fallback
+ }
+ return n
+}
+
+func finalizeProfileConfig(cfg *RuntimeConfig) {
+ if cfg.DefaultProfile == "" {
+ cfg.DefaultProfile = "default"
+ }
+ if cfg.ProfilesBaseDir == "" {
+ cfg.ProfilesBaseDir = filepath.Join(cfg.StateDir, "profiles")
+ }
+ if cfg.ProfileDir == "" {
+ cfg.ProfileDir = filepath.Join(cfg.ProfilesBaseDir, cfg.DefaultProfile)
+ }
+}
+
+func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
+ // Server
+ if fc.Server.Port != "" && os.Getenv("PINCHTAB_PORT") == "" {
+ cfg.Port = fc.Server.Port
+ }
+ if fc.Server.Bind != "" && os.Getenv("PINCHTAB_BIND") == "" {
+ cfg.Bind = fc.Server.Bind
+ }
+ if fc.Server.Token != "" && os.Getenv("PINCHTAB_TOKEN") == "" {
+ cfg.Token = fc.Server.Token
+ }
+ if fc.Server.StateDir != "" {
+ cfg.StateDir = fc.Server.StateDir
+ }
+ if fc.Server.Engine != "" && os.Getenv("PINCHTAB_ENGINE") == "" {
+ cfg.Engine = fc.Server.Engine
+ }
+ // Security
+ if fc.Security.AllowEvaluate != nil {
+ cfg.AllowEvaluate = *fc.Security.AllowEvaluate
+ }
+ if fc.Security.AllowMacro != nil {
+ cfg.AllowMacro = *fc.Security.AllowMacro
+ }
+ if fc.Security.AllowScreencast != nil {
+ cfg.AllowScreencast = *fc.Security.AllowScreencast
+ }
+ if fc.Security.AllowDownload != nil {
+ cfg.AllowDownload = *fc.Security.AllowDownload
+ }
+ if fc.Security.AllowUpload != nil {
+ cfg.AllowUpload = *fc.Security.AllowUpload
+ }
+ if fc.Security.MaxRedirects != nil {
+ cfg.MaxRedirects = *fc.Security.MaxRedirects
+ }
+ // IDPI – copy the whole struct; individual fields have safe zero-value defaults.
+ cfg.IDPI = fc.Security.IDPI
+
+ // Browser
+ if fc.Browser.ChromeVersion != "" {
+ cfg.ChromeVersion = fc.Browser.ChromeVersion
+ }
+ if fc.Browser.ChromeBinary != "" {
+ cfg.ChromeBinary = fc.Browser.ChromeBinary
+ }
+ if fc.Browser.ChromeExtraFlags != "" {
+ cfg.ChromeExtraFlags = fc.Browser.ChromeExtraFlags
+ }
+ if len(fc.Browser.ExtensionPaths) > 0 {
+ cfg.ExtensionPaths = fc.Browser.ExtensionPaths
+ }
+
+ // Instance defaults
+ if fc.InstanceDefaults.Mode != "" {
+ cfg.Headless = modeToHeadless(fc.InstanceDefaults.Mode, cfg.Headless)
+ }
+ if fc.InstanceDefaults.NoRestore != nil {
+ cfg.NoRestore = *fc.InstanceDefaults.NoRestore
+ }
+ if fc.InstanceDefaults.Timezone != "" {
+ cfg.Timezone = fc.InstanceDefaults.Timezone
+ }
+ if fc.InstanceDefaults.BlockImages != nil {
+ cfg.BlockImages = *fc.InstanceDefaults.BlockImages
+ }
+ if fc.InstanceDefaults.BlockMedia != nil {
+ cfg.BlockMedia = *fc.InstanceDefaults.BlockMedia
+ }
+ if fc.InstanceDefaults.BlockAds != nil {
+ cfg.BlockAds = *fc.InstanceDefaults.BlockAds
+ }
+ if fc.InstanceDefaults.MaxTabs != nil {
+ cfg.MaxTabs = *fc.InstanceDefaults.MaxTabs
+ }
+ if fc.InstanceDefaults.MaxParallelTabs != nil {
+ cfg.MaxParallelTabs = *fc.InstanceDefaults.MaxParallelTabs
+ }
+ if fc.InstanceDefaults.UserAgent != "" {
+ cfg.UserAgent = fc.InstanceDefaults.UserAgent
+ }
+ if fc.InstanceDefaults.NoAnimations != nil {
+ cfg.NoAnimations = *fc.InstanceDefaults.NoAnimations
+ }
+ if fc.InstanceDefaults.StealthLevel != "" {
+ cfg.StealthLevel = fc.InstanceDefaults.StealthLevel
+ }
+ if fc.InstanceDefaults.TabEvictionPolicy != "" {
+ cfg.TabEvictionPolicy = fc.InstanceDefaults.TabEvictionPolicy
+ }
+
+ // Profiles
+ if fc.Profiles.BaseDir != "" {
+ cfg.ProfilesBaseDir = fc.Profiles.BaseDir
+ }
+ if fc.Profiles.DefaultProfile != "" {
+ cfg.DefaultProfile = fc.Profiles.DefaultProfile
+ }
+ cfg.ProfileDir = ""
+
+ // Multi-instance
+ if fc.MultiInstance.Strategy != "" {
+ cfg.Strategy = fc.MultiInstance.Strategy
+ }
+ if fc.MultiInstance.AllocationPolicy != "" {
+ cfg.AllocationPolicy = fc.MultiInstance.AllocationPolicy
+ }
+ if fc.MultiInstance.InstancePortStart != nil {
+ cfg.InstancePortStart = *fc.MultiInstance.InstancePortStart
+ }
+ if fc.MultiInstance.InstancePortEnd != nil {
+ cfg.InstancePortEnd = *fc.MultiInstance.InstancePortEnd
+ }
+ // Restart
+ if fc.MultiInstance.Restart.MaxRestarts != nil {
+ cfg.RestartMaxRestarts = *fc.MultiInstance.Restart.MaxRestarts
+ }
+ if fc.MultiInstance.Restart.InitBackoffSec != nil {
+ cfg.RestartInitBackoff = time.Duration(*fc.MultiInstance.Restart.InitBackoffSec) * time.Second
+ }
+ if fc.MultiInstance.Restart.MaxBackoffSec != nil {
+ cfg.RestartMaxBackoff = time.Duration(*fc.MultiInstance.Restart.MaxBackoffSec) * time.Second
+ }
+ if fc.MultiInstance.Restart.StableAfterSec != nil {
+ cfg.RestartStableAfter = time.Duration(*fc.MultiInstance.Restart.StableAfterSec) * time.Second
+ }
+
+ // Attach
+ if fc.Security.Attach.Enabled != nil {
+ cfg.AttachEnabled = *fc.Security.Attach.Enabled
+ }
+ if len(fc.Security.Attach.AllowHosts) > 0 {
+ cfg.AttachAllowHosts = append([]string(nil), fc.Security.Attach.AllowHosts...)
+ }
+ if len(fc.Security.Attach.AllowSchemes) > 0 {
+ cfg.AttachAllowSchemes = append([]string(nil), fc.Security.Attach.AllowSchemes...)
+ }
+
+ // Timeouts
+ if fc.Timeouts.ActionSec > 0 {
+ cfg.ActionTimeout = time.Duration(fc.Timeouts.ActionSec) * time.Second
+ }
+ if fc.Timeouts.NavigateSec > 0 {
+ cfg.NavigateTimeout = time.Duration(fc.Timeouts.NavigateSec) * time.Second
+ }
+ if fc.Timeouts.ShutdownSec > 0 {
+ cfg.ShutdownTimeout = time.Duration(fc.Timeouts.ShutdownSec) * time.Second
+ }
+ if fc.Timeouts.WaitNavMs > 0 {
+ cfg.WaitNavDelay = time.Duration(fc.Timeouts.WaitNavMs) * time.Millisecond
+ }
+
+ // Scheduler
+ if fc.Scheduler.Enabled != nil {
+ cfg.Scheduler.Enabled = *fc.Scheduler.Enabled
+ }
+ if fc.Scheduler.Strategy != "" {
+ cfg.Scheduler.Strategy = fc.Scheduler.Strategy
+ }
+ if fc.Scheduler.MaxQueueSize != nil {
+ cfg.Scheduler.MaxQueueSize = *fc.Scheduler.MaxQueueSize
+ }
+ if fc.Scheduler.MaxPerAgent != nil {
+ cfg.Scheduler.MaxPerAgent = *fc.Scheduler.MaxPerAgent
+ }
+ if fc.Scheduler.MaxInflight != nil {
+ cfg.Scheduler.MaxInflight = *fc.Scheduler.MaxInflight
+ }
+ if fc.Scheduler.MaxPerAgentFlight != nil {
+ cfg.Scheduler.MaxPerAgentFlight = *fc.Scheduler.MaxPerAgentFlight
+ }
+ if fc.Scheduler.ResultTTLSec != nil {
+ cfg.Scheduler.ResultTTLSec = *fc.Scheduler.ResultTTLSec
+ }
+ if fc.Scheduler.WorkerCount != nil {
+ cfg.Scheduler.WorkerCount = *fc.Scheduler.WorkerCount
+ }
+}
+
+// ApplyFileConfigToRuntime merges file configuration into an existing runtime
+// config and refreshes derived profile paths for long-running processes.
+func ApplyFileConfigToRuntime(cfg *RuntimeConfig, fc *FileConfig) {
+ if cfg == nil || fc == nil {
+ return
+ }
+
+ applyFileConfig(cfg, fc)
+ finalizeProfileConfig(cfg)
+}
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
new file mode 100644
index 00000000..701c77d1
--- /dev/null
+++ b/internal/config/config_load_test.go
@@ -0,0 +1,227 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestEnvOr(t *testing.T) {
+ key := "PINCHTAB_TEST_ENV"
+ fallback := "default"
+
+ _ = os.Unsetenv(key)
+ if got := envOr(key, fallback); got != fallback {
+ t.Errorf("envOr() = %v, want %v", got, fallback)
+ }
+
+ val := "set"
+ _ = os.Setenv(key, val)
+ defer func() { _ = os.Unsetenv(key) }()
+ if got := envOr(key, fallback); got != val {
+ t.Errorf("envOr() = %v, want %v", got, val)
+ }
+}
+
+func TestEnvIntOr(t *testing.T) {
+ key := "PINCHTAB_TEST_INT"
+ fallback := 42
+
+ _ = os.Unsetenv(key)
+ if got := envIntOr(key, fallback); got != fallback {
+ t.Errorf("envIntOr() = %v, want %v", got, fallback)
+ }
+
+ _ = os.Setenv(key, "100")
+ if got := envIntOr(key, fallback); got != 100 {
+ t.Errorf("envIntOr() = %v, want %v", got, 100)
+ }
+
+ _ = os.Setenv(key, "invalid")
+ if got := envIntOr(key, fallback); got != fallback {
+ t.Errorf("envIntOr() = %v, want %v", got, fallback)
+ }
+}
+
+func TestLoadConfigDefaults(t *testing.T) {
+ clearConfigEnvVars(t)
+ // Point to non-existent config to test pure defaults
+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
+
+ cfg := Load()
+ if cfg.Port != "9867" {
+ t.Errorf("default Port = %v, want 9867", cfg.Port)
+ }
+ if cfg.Bind != "127.0.0.1" {
+ t.Errorf("default Bind = %v, want 127.0.0.1", cfg.Bind)
+ }
+ if cfg.AllowEvaluate {
+ t.Errorf("default AllowEvaluate = %v, want false", cfg.AllowEvaluate)
+ }
+ if cfg.Strategy != "simple" {
+ t.Errorf("default Strategy = %v, want simple", cfg.Strategy)
+ }
+ if cfg.AllocationPolicy != "fcfs" {
+ t.Errorf("default AllocationPolicy = %v, want fcfs", cfg.AllocationPolicy)
+ }
+ if cfg.TabEvictionPolicy != "close_lru" {
+ t.Errorf("default TabEvictionPolicy = %v, want close_lru", cfg.TabEvictionPolicy)
+ }
+ if cfg.AttachEnabled {
+ t.Errorf("default AttachEnabled = %v, want false", cfg.AttachEnabled)
+ }
+ 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) {
+ clearConfigEnvVars(t)
+ // Point to non-existent config to isolate env var testing
+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
+ _ = os.Setenv("PINCHTAB_PORT", "1234")
+ _ = os.Setenv("PINCHTAB_BIND", "0.0.0.0")
+ _ = os.Setenv("PINCHTAB_TOKEN", "secret")
+ defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
+ _ = os.Unsetenv("PINCHTAB_PORT")
+ _ = os.Unsetenv("PINCHTAB_BIND")
+ _ = os.Unsetenv("PINCHTAB_TOKEN")
+ }()
+
+ cfg := Load()
+ if cfg.Port != "1234" {
+ t.Errorf("env Port = %v, want 1234", cfg.Port)
+ }
+ if cfg.Bind != "0.0.0.0" {
+ t.Errorf("env Bind = %v, want 0.0.0.0", cfg.Bind)
+ }
+ if cfg.Token != "secret" {
+ t.Errorf("env Token = %v, want secret", cfg.Token)
+ }
+}
+
+func TestPinchtabEnvTakesPrecedence(t *testing.T) {
+ clearConfigEnvVars(t)
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ _ = os.Setenv("PINCHTAB_PORT", "7777")
+ defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
+ _ = os.Unsetenv("PINCHTAB_PORT")
+ }()
+
+ if err := os.WriteFile(configPath, []byte(`{"server":{"port":"8888"}}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+ if cfg.Port != "7777" {
+ t.Errorf("precedence Port = %v, want 7777", cfg.Port)
+ }
+}
+
+func TestEnvOverridesNestedConfig(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ _ = os.Setenv("PINCHTAB_PORT", "9999")
+ defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
+ _ = os.Unsetenv("PINCHTAB_PORT")
+ }()
+
+ // Config file says port 8888 and strategy explicit
+ nestedConfig := `{
+ "server": {
+ "port": "8888"
+ },
+ "multiInstance": {
+ "strategy": "explicit"
+ }
+ }`
+ if err := os.WriteFile(configPath, []byte(nestedConfig), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+
+ // Env var should win
+ if cfg.Port != "9999" {
+ t.Errorf("env should override file: Port = %v, want 9999", cfg.Port)
+ }
+ if cfg.Strategy != "explicit" {
+ t.Errorf("file should supply Strategy = %v, want explicit", cfg.Strategy)
+ }
+}
+
+func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T) {
+ cfg := &RuntimeConfig{
+ AllowEvaluate: true,
+ AllowMacro: true,
+ AllowScreencast: true,
+ AllowDownload: true,
+ AllowUpload: true,
+ IDPI: IDPIConfig{
+ Enabled: false,
+ },
+ }
+
+ fc := DefaultFileConfig()
+ ApplyFileConfigToRuntime(cfg, &fc)
+
+ if cfg.AllowEvaluate {
+ t.Errorf("ApplyFileConfigToRuntime AllowEvaluate = %v, want false", cfg.AllowEvaluate)
+ }
+ if cfg.AllowMacro {
+ t.Errorf("ApplyFileConfigToRuntime AllowMacro = %v, want false", cfg.AllowMacro)
+ }
+ if cfg.AllowScreencast {
+ t.Errorf("ApplyFileConfigToRuntime AllowScreencast = %v, want false", cfg.AllowScreencast)
+ }
+ if cfg.AllowDownload {
+ t.Errorf("ApplyFileConfigToRuntime AllowDownload = %v, want false", cfg.AllowDownload)
+ }
+ if cfg.AllowUpload {
+ t.Errorf("ApplyFileConfigToRuntime AllowUpload = %v, want false", cfg.AllowUpload)
+ }
+ 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)
+ }
+}
+
+// clearConfigEnvVars unsets all config-related env vars for clean tests.
+func clearConfigEnvVars(t *testing.T) {
+ t.Helper()
+ envVars := []string{
+ "PINCHTAB_PORT", "PINCHTAB_BIND", "PINCHTAB_TOKEN", "PINCHTAB_CONFIG", "PINCHTAB_ENGINE",
+ }
+ for _, v := range envVars {
+ _ = os.Unsetenv(v)
+ }
+}
diff --git a/internal/config/config_methods.go b/internal/config/config_methods.go
new file mode 100644
index 00000000..54e1fe13
--- /dev/null
+++ b/internal/config/config_methods.go
@@ -0,0 +1,27 @@
+package config
+
+// EnabledSensitiveEndpoints returns the names of sensitive endpoint families
+// that are currently enabled in the runtime configuration.
+func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {
+ if cfg == nil {
+ return nil
+ }
+
+ enabled := make([]string, 0, 5)
+ if cfg.AllowEvaluate {
+ enabled = append(enabled, "evaluate")
+ }
+ if cfg.AllowMacro {
+ enabled = append(enabled, "macro")
+ }
+ if cfg.AllowScreencast {
+ enabled = append(enabled, "screencast")
+ }
+ if cfg.AllowDownload {
+ enabled = append(enabled, "download")
+ }
+ if cfg.AllowUpload {
+ enabled = append(enabled, "upload")
+ }
+ return enabled
+}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
deleted file mode 100644
index 64823618..00000000
--- a/internal/config/config_test.go
+++ /dev/null
@@ -1,738 +0,0 @@
-package config
-
-import (
- "encoding/json"
- "os"
- "path/filepath"
- "testing"
- "time"
-)
-
-func TestEnvOr(t *testing.T) {
- key := "PINCHTAB_TEST_ENV"
- fallback := "default"
-
- _ = os.Unsetenv(key)
- if got := envOr(key, fallback); got != fallback {
- t.Errorf("envOr() = %v, want %v", got, fallback)
- }
-
- val := "set"
- _ = os.Setenv(key, val)
- defer func() { _ = os.Unsetenv(key) }()
- if got := envOr(key, fallback); got != val {
- t.Errorf("envOr() = %v, want %v", got, val)
- }
-}
-
-func TestEnvIntOr(t *testing.T) {
- key := "PINCHTAB_TEST_INT"
- fallback := 42
-
- _ = os.Unsetenv(key)
- if got := envIntOr(key, fallback); got != fallback {
- t.Errorf("envIntOr() = %v, want %v", got, fallback)
- }
-
- _ = os.Setenv(key, "100")
- if got := envIntOr(key, fallback); got != 100 {
- t.Errorf("envIntOr() = %v, want %v", got, 100)
- }
-
- _ = os.Setenv(key, "invalid")
- if got := envIntOr(key, fallback); got != fallback {
- t.Errorf("envIntOr() = %v, want %v", got, fallback)
- }
-}
-
-func TestMaskToken(t *testing.T) {
- tests := []struct {
- token string
- want string
- }{
- {"", "(none)"},
- {"short", "***"},
- {"very-long-token-secret", "very...cret"},
- }
-
- for _, tt := range tests {
- if got := MaskToken(tt.token); got != tt.want {
- t.Errorf("MaskToken(%q) = %v, want %v", tt.token, 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))
- }
- 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
- _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
- defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
-
- cfg := Load()
- if cfg.Port != "9867" {
- t.Errorf("default Port = %v, want 9867", cfg.Port)
- }
- if cfg.Bind != "127.0.0.1" {
- t.Errorf("default Bind = %v, want 127.0.0.1", cfg.Bind)
- }
- if cfg.AllowEvaluate {
- t.Errorf("default AllowEvaluate = %v, want false", cfg.AllowEvaluate)
- }
- if cfg.Strategy != "always-on" {
- t.Errorf("default Strategy = %v, want always-on", cfg.Strategy)
- }
- if cfg.AllocationPolicy != "fcfs" {
- t.Errorf("default AllocationPolicy = %v, want fcfs", cfg.AllocationPolicy)
- }
- if cfg.RestartMaxRestarts != 20 {
- t.Errorf("default RestartMaxRestarts = %v, want 20", cfg.RestartMaxRestarts)
- }
- if cfg.RestartInitBackoff != 2*time.Second {
- t.Errorf("default RestartInitBackoff = %v, want 2s", cfg.RestartInitBackoff)
- }
- if cfg.TabEvictionPolicy != "close_lru" {
- t.Errorf("default TabEvictionPolicy = %v, want close_lru", cfg.TabEvictionPolicy)
- }
- if cfg.AttachEnabled {
- t.Errorf("default AttachEnabled = %v, want false", cfg.AttachEnabled)
- }
- 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) {
- clearConfigEnvVars(t)
- // Point to non-existent config to isolate env var testing
- _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
- _ = os.Setenv("PINCHTAB_PORT", "1234")
- _ = os.Setenv("PINCHTAB_BIND", "0.0.0.0")
- _ = os.Setenv("PINCHTAB_TOKEN", "secret")
- defer func() {
- _ = os.Unsetenv("PINCHTAB_CONFIG")
- _ = os.Unsetenv("PINCHTAB_PORT")
- _ = os.Unsetenv("PINCHTAB_BIND")
- _ = os.Unsetenv("PINCHTAB_TOKEN")
- }()
-
- cfg := Load()
- if cfg.Port != "1234" {
- t.Errorf("env Port = %v, want 1234", cfg.Port)
- }
- if cfg.Bind != "0.0.0.0" {
- t.Errorf("env Bind = %v, want 0.0.0.0", cfg.Bind)
- }
- if cfg.Token != "secret" {
- t.Errorf("env Token = %v, want secret", cfg.Token)
- }
- // ChromeBinary is config-only, no longer available as env var
-}
-
-func TestPinchtabEnvTakesPrecedence(t *testing.T) {
- clearConfigEnvVars(t)
- tmpDir := t.TempDir()
- configPath := filepath.Join(tmpDir, "config.json")
- _ = os.Setenv("PINCHTAB_CONFIG", configPath)
- _ = os.Setenv("PINCHTAB_PORT", "7777")
- defer func() {
- _ = os.Unsetenv("PINCHTAB_CONFIG")
- _ = os.Unsetenv("PINCHTAB_PORT")
- }()
-
- if err := os.WriteFile(configPath, []byte(`{"server":{"port":"8888"}}`), 0644); err != nil {
- t.Fatal(err)
- }
-
- cfg := Load()
- if cfg.Port != "7777" {
- t.Errorf("precedence Port = %v, want 7777", cfg.Port)
- }
-}
-
-func TestDefaultFileConfig(t *testing.T) {
- fc := DefaultFileConfig()
- if fc.Server.Port != "9867" {
- t.Errorf("DefaultFileConfig.Server.Port = %v, want 9867", fc.Server.Port)
- }
- if fc.Server.Bind != "127.0.0.1" {
- t.Errorf("DefaultFileConfig.Server.Bind = %v, want 127.0.0.1", fc.Server.Bind)
- }
- if fc.InstanceDefaults.Mode != "headless" {
- t.Errorf("DefaultFileConfig.InstanceDefaults.Mode = %v, want headless", fc.InstanceDefaults.Mode)
- }
- if fc.MultiInstance.Strategy != "always-on" {
- t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want always-on", fc.MultiInstance.Strategy)
- }
- if fc.MultiInstance.Restart.MaxRestarts == nil || *fc.MultiInstance.Restart.MaxRestarts != 20 {
- t.Errorf("DefaultFileConfig.MultiInstance.Restart.MaxRestarts = %v, want 20", formatIntPtr(fc.MultiInstance.Restart.MaxRestarts))
- }
- 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))
- }
- if fc.Security.AllowMacro == nil || *fc.Security.AllowMacro {
- t.Errorf("DefaultFileConfig.Security.AllowMacro = %v, want explicit false", formatBoolPtr(fc.Security.AllowMacro))
- }
- if fc.Security.AllowScreencast == nil || *fc.Security.AllowScreencast {
- t.Errorf("DefaultFileConfig.Security.AllowScreencast = %v, want explicit false", formatBoolPtr(fc.Security.AllowScreencast))
- }
- if fc.Security.AllowDownload == nil || *fc.Security.AllowDownload {
- t.Errorf("DefaultFileConfig.Security.AllowDownload = %v, want explicit false", formatBoolPtr(fc.Security.AllowDownload))
- }
- if fc.Security.AllowUpload == nil || *fc.Security.AllowUpload {
- t.Errorf("DefaultFileConfig.Security.AllowUpload = %v, want explicit false", formatBoolPtr(fc.Security.AllowUpload))
- }
- 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.
-func TestLoadNestedConfig(t *testing.T) {
- clearConfigEnvVars(t)
-
- tmpDir := t.TempDir()
- configPath := filepath.Join(tmpDir, "config.json")
- _ = os.Setenv("PINCHTAB_CONFIG", configPath)
- defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
-
- // Create nested config file
- nestedConfig := `{
- "server": {
- "port": "8888",
- "bind": "0.0.0.0",
- "token": "secret123"
- },
- "instanceDefaults": {
- "mode": "headed",
- "maxTabs": 50,
- "stealthLevel": "full",
- "tabEvictionPolicy": "close_oldest"
- },
- "security": {
- "allowEvaluate": true,
- "attach": {
- "enabled": true,
- "allowHosts": ["localhost", "chrome.internal"],
- "allowSchemes": ["wss"]
- }
- },
- "multiInstance": {
- "strategy": "explicit",
- "allocationPolicy": "round_robin",
- "restart": {
- "maxRestarts": 7,
- "initBackoffSec": 4,
- "maxBackoffSec": 90,
- "stableAfterSec": 420
- }
- },
- "timeouts": {
- "actionSec": 60,
- "navigateSec": 120
- }
- }`
- if err := os.WriteFile(configPath, []byte(nestedConfig), 0644); err != nil {
- t.Fatal(err)
- }
-
- cfg := Load()
-
- // Server
- if cfg.Port != "8888" {
- t.Errorf("nested Port = %v, want 8888", cfg.Port)
- }
- if cfg.Bind != "0.0.0.0" {
- t.Errorf("nested Bind = %v, want 0.0.0.0", cfg.Bind)
- }
- if cfg.Token != "secret123" {
- t.Errorf("nested Token = %v, want secret123", cfg.Token)
- }
-
- // Instance defaults
- if cfg.Headless != false {
- t.Errorf("nested Headless = %v, want false", cfg.Headless)
- }
- if cfg.MaxTabs != 50 {
- t.Errorf("nested MaxTabs = %v, want 50", cfg.MaxTabs)
- }
- if cfg.StealthLevel != "full" {
- t.Errorf("nested StealthLevel = %v, want full", cfg.StealthLevel)
- }
- if cfg.TabEvictionPolicy != "close_oldest" {
- t.Errorf("nested TabEvictionPolicy = %v, want close_oldest", cfg.TabEvictionPolicy)
- }
-
- // Security
- if cfg.AllowEvaluate != true {
- t.Errorf("nested AllowEvaluate = %v, want true", cfg.AllowEvaluate)
- }
-
- // Multi-instance
- if cfg.Strategy != "explicit" {
- t.Errorf("nested Strategy = %v, want explicit", cfg.Strategy)
- }
- if cfg.AllocationPolicy != "round_robin" {
- t.Errorf("nested AllocationPolicy = %v, want round_robin", cfg.AllocationPolicy)
- }
- if cfg.RestartMaxRestarts != 7 {
- t.Errorf("nested RestartMaxRestarts = %v, want 7", cfg.RestartMaxRestarts)
- }
- if cfg.RestartInitBackoff != 4*time.Second {
- t.Errorf("nested RestartInitBackoff = %v, want 4s", cfg.RestartInitBackoff)
- }
- if cfg.RestartMaxBackoff != 90*time.Second {
- t.Errorf("nested RestartMaxBackoff = %v, want 90s", cfg.RestartMaxBackoff)
- }
- if cfg.RestartStableAfter != 420*time.Second {
- t.Errorf("nested RestartStableAfter = %v, want 420s", cfg.RestartStableAfter)
- }
- if cfg.AttachEnabled != true {
- t.Errorf("nested AttachEnabled = %v, want true", cfg.AttachEnabled)
- }
- if len(cfg.AttachAllowHosts) != 2 || cfg.AttachAllowHosts[1] != "chrome.internal" {
- t.Errorf("nested AttachAllowHosts = %v, want [localhost chrome.internal]", cfg.AttachAllowHosts)
- }
- if len(cfg.AttachAllowSchemes) != 1 || cfg.AttachAllowSchemes[0] != "wss" {
- t.Errorf("nested AttachAllowSchemes = %v, want [wss]", cfg.AttachAllowSchemes)
- }
-
- // Timeouts
- if cfg.ActionTimeout != 60*time.Second {
- t.Errorf("nested ActionTimeout = %v, want 60s", cfg.ActionTimeout)
- }
- if cfg.NavigateTimeout != 120*time.Second {
- t.Errorf("nested NavigateTimeout = %v, want 120s", cfg.NavigateTimeout)
- }
-}
-
-// TestLoadLegacyFlatConfig tests backward compatibility with flat config files.
-func TestLoadLegacyFlatConfig(t *testing.T) {
- clearConfigEnvVars(t)
-
- tmpDir := t.TempDir()
- configPath := filepath.Join(tmpDir, "config.json")
- _ = os.Setenv("PINCHTAB_CONFIG", configPath)
- defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
-
- // Create legacy flat config file (old format)
- legacyConfig := `{
- "port": "7777",
- "headless": false,
- "maxTabs": 30,
- "allowEvaluate": true,
- "timeoutSec": 45,
- "navigateSec": 90
- }`
- if err := os.WriteFile(configPath, []byte(legacyConfig), 0644); err != nil {
- t.Fatal(err)
- }
-
- cfg := Load()
-
- if cfg.Port != "7777" {
- t.Errorf("legacy flat Port = %v, want 7777", cfg.Port)
- }
- if cfg.Headless != false {
- t.Errorf("legacy flat Headless = %v, want false", cfg.Headless)
- }
- if cfg.MaxTabs != 30 {
- t.Errorf("legacy flat MaxTabs = %v, want 30", cfg.MaxTabs)
- }
- if cfg.AllowEvaluate != true {
- t.Errorf("legacy flat AllowEvaluate = %v, want true", cfg.AllowEvaluate)
- }
- if cfg.ActionTimeout != 45*time.Second {
- t.Errorf("legacy flat ActionTimeout = %v, want 45s", cfg.ActionTimeout)
- }
- if cfg.NavigateTimeout != 90*time.Second {
- t.Errorf("legacy flat NavigateTimeout = %v, want 90s", cfg.NavigateTimeout)
- }
-}
-
-// TestEnvOverridesNestedConfig verifies env vars take precedence over nested config.
-func TestEnvOverridesNestedConfig(t *testing.T) {
- clearConfigEnvVars(t)
-
- tmpDir := t.TempDir()
- configPath := filepath.Join(tmpDir, "config.json")
- _ = os.Setenv("PINCHTAB_CONFIG", configPath)
- _ = os.Setenv("PINCHTAB_PORT", "9999")
- defer func() {
- _ = os.Unsetenv("PINCHTAB_CONFIG")
- _ = os.Unsetenv("PINCHTAB_PORT")
- }()
-
- // Config file says port 8888 and strategy explicit
- nestedConfig := `{
- "server": {
- "port": "8888"
- },
- "multiInstance": {
- "strategy": "explicit"
- }
- }`
- if err := os.WriteFile(configPath, []byte(nestedConfig), 0644); err != nil {
- t.Fatal(err)
- }
-
- cfg := Load()
-
- // Env var should win
- if cfg.Port != "9999" {
- t.Errorf("env should override file: Port = %v, want 9999", cfg.Port)
- }
- if cfg.Strategy != "explicit" {
- t.Errorf("file should supply Strategy = %v, want explicit", cfg.Strategy)
- }
-}
-
-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)
- }
-
- 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)
- }
-}
-
-// TestIsLegacyConfig tests the format detection logic.
-func TestIsLegacyConfig(t *testing.T) {
- tests := []struct {
- name string
- json string
- isLegacy bool
- }{
- {
- name: "nested format with server",
- json: `{"server": {"port": "9867"}}`,
- isLegacy: false,
- },
- {
- name: "nested format with instanceDefaults",
- json: `{"instanceDefaults": {"mode": "headless"}}`,
- isLegacy: false,
- },
- {
- name: "nested format with security.attach",
- json: `{"security": {"attach": {"enabled": true}}}`,
- isLegacy: false,
- },
- {
- name: "legacy format with port",
- json: `{"port": "9867"}`,
- isLegacy: true,
- },
- {
- name: "legacy format with headless",
- json: `{"headless": true}`,
- isLegacy: true,
- },
- {
- name: "empty object",
- json: `{}`,
- isLegacy: false,
- },
- {
- name: "mixed - nested wins",
- json: `{"server": {"port": "8888"}, "port": "7777"}`,
- isLegacy: false,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := isLegacyConfig([]byte(tt.json))
- if got != tt.isLegacy {
- t.Errorf("isLegacyConfig(%s) = %v, want %v", tt.json, got, tt.isLegacy)
- }
- })
- }
-}
-
-// TestConvertLegacyConfig tests the legacy to nested conversion.
-func TestConvertLegacyConfig(t *testing.T) {
- h := false
- maxTabs := 25
- lc := &legacyFileConfig{
- Port: "7777",
- Headless: &h,
- MaxTabs: &maxTabs,
- AllowEvaluate: boolPtr(true),
- TimeoutSec: 45,
- NavigateSec: 90,
- }
-
- fc := convertLegacyConfig(lc)
-
- if fc.Server.Port != "7777" {
- t.Errorf("converted Server.Port = %v, want 7777", fc.Server.Port)
- }
- if fc.InstanceDefaults.Mode != "headed" {
- t.Errorf("converted InstanceDefaults.Mode = %v, want headed", fc.InstanceDefaults.Mode)
- }
- if *fc.InstanceDefaults.MaxTabs != 25 {
- t.Errorf("converted InstanceDefaults.MaxTabs = %v, want 25", *fc.InstanceDefaults.MaxTabs)
- }
- if *fc.Security.AllowEvaluate != true {
- t.Errorf("converted Security.AllowEvaluate = %v, want true", *fc.Security.AllowEvaluate)
- }
- if fc.Timeouts.ActionSec != 45 {
- t.Errorf("converted Timeouts.ActionSec = %v, want 45", fc.Timeouts.ActionSec)
- }
- if fc.Timeouts.NavigateSec != 90 {
- t.Errorf("converted Timeouts.NavigateSec = %v, want 90", fc.Timeouts.NavigateSec)
- }
-}
-
-// TestDefaultFileConfigJSON tests that DefaultFileConfig serializes correctly.
-func TestDefaultFileConfigJSON(t *testing.T) {
- fc := DefaultFileConfig()
- data, err := json.MarshalIndent(fc, "", " ")
- if err != nil {
- t.Fatalf("failed to marshal DefaultFileConfig: %v", err)
- }
-
- // Verify it can be parsed back
- var parsed FileConfig
- if err := json.Unmarshal(data, &parsed); err != nil {
- t.Fatalf("failed to unmarshal DefaultFileConfig output: %v", err)
- }
-
- if parsed.Server.Port != "9867" {
- t.Errorf("round-trip Server.Port = %v, want 9867", parsed.Server.Port)
- }
- if parsed.InstanceDefaults.Mode != "headless" {
- t.Errorf("round-trip InstanceDefaults.Mode = %v, want headless", parsed.InstanceDefaults.Mode)
- }
- if parsed.Security.AllowEvaluate == nil || *parsed.Security.AllowEvaluate {
- t.Errorf("round-trip Security.AllowEvaluate = %v, want explicit false", formatBoolPtr(parsed.Security.AllowEvaluate))
- }
- if parsed.Security.AllowMacro == nil || *parsed.Security.AllowMacro {
- t.Errorf("round-trip Security.AllowMacro = %v, want explicit false", formatBoolPtr(parsed.Security.AllowMacro))
- }
- if parsed.Security.AllowScreencast == nil || *parsed.Security.AllowScreencast {
- t.Errorf("round-trip Security.AllowScreencast = %v, want explicit false", formatBoolPtr(parsed.Security.AllowScreencast))
- }
- if parsed.Security.AllowDownload == nil || *parsed.Security.AllowDownload {
- t.Errorf("round-trip Security.AllowDownload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowDownload))
- }
- if parsed.Security.AllowUpload == nil || *parsed.Security.AllowUpload {
- t.Errorf("round-trip Security.AllowUpload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowUpload))
- }
- 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) {
- cfg := &RuntimeConfig{
- AllowEvaluate: true,
- AllowMacro: true,
- AllowScreencast: true,
- AllowDownload: true,
- AllowUpload: true,
- IDPI: IDPIConfig{
- Enabled: false,
- },
- }
-
- fc := DefaultFileConfig()
- ApplyFileConfigToRuntime(cfg, &fc)
-
- if cfg.AllowEvaluate {
- t.Errorf("ApplyFileConfigToRuntime AllowEvaluate = %v, want false", cfg.AllowEvaluate)
- }
- if cfg.AllowMacro {
- t.Errorf("ApplyFileConfigToRuntime AllowMacro = %v, want false", cfg.AllowMacro)
- }
- if cfg.AllowScreencast {
- t.Errorf("ApplyFileConfigToRuntime AllowScreencast = %v, want false", cfg.AllowScreencast)
- }
- if cfg.AllowDownload {
- t.Errorf("ApplyFileConfigToRuntime AllowDownload = %v, want false", cfg.AllowDownload)
- }
- if cfg.AllowUpload {
- t.Errorf("ApplyFileConfigToRuntime AllowUpload = %v, want false", cfg.AllowUpload)
- }
- 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
-
-func boolPtr(b bool) *bool {
- return &b
-}
-
-// clearConfigEnvVars unsets all config-related env vars for clean tests.
-func clearConfigEnvVars(t *testing.T) {
- t.Helper()
- envVars := []string{
- "PINCHTAB_PORT", "PINCHTAB_BIND", "PINCHTAB_TOKEN", "PINCHTAB_CONFIG",
- }
- for _, v := range envVars {
- _ = os.Unsetenv(v)
- }
-}
-
-func TestFileExists(t *testing.T) {
- // Create a temp directory
- tmpDir, err := os.MkdirTemp("", "pinchtab-test-*")
- if err != nil {
- t.Fatalf("Failed to create temp dir: %v", err)
- }
- defer func() { _ = os.RemoveAll(tmpDir) }()
-
- // Test non-existent file
- if fileExists(filepath.Join(tmpDir, "nonexistent.json")) {
- t.Error("fileExists() returned true for non-existent file")
- }
-
- // Test existing file
- testFile := filepath.Join(tmpDir, "test.json")
- if err := os.WriteFile(testFile, []byte("{}"), 0644); err != nil {
- t.Fatalf("Failed to create test file: %v", err)
- }
- if !fileExists(testFile) {
- t.Error("fileExists() returned false for existing file")
- }
-
- // Test directory (should return false)
- subDir := filepath.Join(tmpDir, "subdir")
- if err := os.Mkdir(subDir, 0755); err != nil {
- t.Fatalf("Failed to create subdir: %v", err)
- }
- if fileExists(subDir) {
- t.Error("fileExists() returned true for directory")
- }
-}
-
-// TestUserConfigDirLegacyConfigFilePriority tests that when legacy config FILE exists
-// but new directory exists (without config), the legacy path is used (issue #224)
-func TestUserConfigDirLegacyConfigFilePriority(t *testing.T) {
- // This test verifies the fix for GitHub issue #224:
- // When ~/.pinchtab/config.json exists and ~/.config/pinchtab/ exists (but without config.json),
- // the legacy path should be used because the config FILE exists there.
-
- // Skip if we can't manipulate HOME directory
- origHome := os.Getenv("HOME")
- if origHome == "" {
- t.Skip("HOME not set, skipping test")
- }
-
- // Create a temp directory to simulate home
- tmpHome, err := os.MkdirTemp("", "pinchtab-home-*")
- if err != nil {
- t.Fatalf("Failed to create temp home: %v", err)
- }
- defer func() { _ = os.RemoveAll(tmpHome) }()
-
- // Setup directory structure that mimics the bug scenario:
- // ~/.pinchtab/config.json exists
- // ~/.config/pinchtab/ exists (e.g., for profiles) but NO config.json
- legacyDir := filepath.Join(tmpHome, ".pinchtab")
- newConfigBase := filepath.Join(tmpHome, ".config")
- newDir := filepath.Join(newConfigBase, "pinchtab")
-
- if err := os.MkdirAll(legacyDir, 0755); err != nil {
- t.Fatalf("Failed to create legacy dir: %v", err)
- }
- if err := os.MkdirAll(newDir, 0755); err != nil {
- t.Fatalf("Failed to create new dir: %v", err)
- }
-
- // Create config.json in legacy location only
- legacyConfig := filepath.Join(legacyDir, "config.json")
- if err := os.WriteFile(legacyConfig, []byte(`{"server":{"port":"9876"}}`), 0644); err != nil {
- t.Fatalf("Failed to create legacy config: %v", err)
- }
-
- // Verify file exists helper works
- if !fileExists(legacyConfig) {
- t.Fatal("fileExists() should return true for legacy config")
- }
- newConfig := filepath.Join(newDir, "config.json")
- if fileExists(newConfig) {
- t.Fatal("fileExists() should return false for non-existent new config")
- }
-
- // The key assertion: with legacy config file present and new config file absent,
- // the code should prefer legacy even when both DIRECTORIES exist
- t.Logf("Legacy dir: %s (has config.json: %v)", legacyDir, fileExists(legacyConfig))
- t.Logf("New dir: %s (has config.json: %v)", newDir, fileExists(newConfig))
- t.Logf("Both directories exist: legacy=%v, new=%v", dirExists(legacyDir), dirExists(newDir))
-
- // Note: We can't easily test userConfigDir() directly because it uses os.UserConfigDir()
- // which we can't override. But we've verified the fileExists logic works correctly,
- // and the userConfigDir implementation now uses fileExists instead of dirExists.
-}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
new file mode 100644
index 00000000..fd8e821a
--- /dev/null
+++ b/internal/config/config_types.go
@@ -0,0 +1,194 @@
+package config
+
+import "time"
+
+// RuntimeConfig holds all runtime settings used throughout the application.
+// This is the single source of truth for configuration at runtime.
+type RuntimeConfig struct {
+ // Server settings
+ Bind string
+ Port string
+ InstancePortStart int // Starting port for instances (default 9868)
+ InstancePortEnd int // Ending port for instances (default 9968)
+ Token string
+ StateDir string
+
+ // Security settings
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ AllowUpload bool
+ MaxRedirects int // Max HTTP redirects (-1=unlimited, 0=none, default=-1)
+
+ // Browser/instance settings
+ Headless bool
+ NoRestore bool
+ ProfileDir string
+ ProfilesBaseDir string
+ DefaultProfile string
+ ChromeVersion string
+ Timezone string
+ BlockImages bool
+ BlockMedia bool
+ BlockAds bool
+ MaxTabs int
+ MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU
+ ChromeBinary string
+ ChromeExtraFlags string
+ ExtensionPaths []string
+ UserAgent string
+ NoAnimations bool
+ StealthLevel string
+ TabEvictionPolicy string // "close_lru" (default), "reject", "close_oldest"
+
+ // Timeout settings
+ ActionTimeout time.Duration
+ NavigateTimeout time.Duration
+ ShutdownTimeout time.Duration
+ WaitNavDelay time.Duration
+
+ // Orchestrator settings (dashboard mode only)
+ Strategy string // "simple" (default), "explicit", or "simple-autorestart"
+ AllocationPolicy string // "fcfs" (default), "round_robin", "random"
+ RestartMaxRestarts int // Max restart attempts for restart-managed strategies (-1 = unlimited, 0 = strategy default)
+ RestartInitBackoff time.Duration // Initial restart backoff (0 = strategy default)
+ RestartMaxBackoff time.Duration // Maximum restart backoff cap (0 = strategy default)
+ RestartStableAfter time.Duration // Stable runtime window that resets the restart counter (0 = strategy default)
+
+ // Attach settings
+ AttachEnabled bool
+ AttachAllowHosts []string
+ AttachAllowSchemes []string
+
+ // IDPI (Indirect Prompt Injection defense) settings
+ IDPI IDPIConfig
+
+ // Engine mode: "chrome" (default), "lite", or "auto"
+ Engine string
+
+ // Scheduler settings (dashboard mode only)
+ Scheduler SchedulerConfig
+}
+
+// IDPIConfig holds the configuration for the Indirect Prompt Injection (IDPI)
+// defense layer.
+type IDPIConfig struct {
+ Enabled bool `json:"enabled,omitempty"`
+ AllowedDomains []string `json:"allowedDomains,omitempty"`
+ StrictMode bool `json:"strictMode,omitempty"`
+ ScanContent bool `json:"scanContent,omitempty"`
+ WrapContent bool `json:"wrapContent,omitempty"`
+ CustomPatterns []string `json:"customPatterns,omitempty"`
+ ScanTimeoutSec int `json:"scanTimeoutSec,omitempty"`
+}
+
+// SchedulerConfig holds task scheduler settings.
+type SchedulerConfig struct {
+ Enabled bool `json:"enabled,omitempty"`
+ Strategy string `json:"strategy,omitempty"`
+ MaxQueueSize int `json:"maxQueueSize,omitempty"`
+ MaxPerAgent int `json:"maxPerAgent,omitempty"`
+ MaxInflight int `json:"maxInflight,omitempty"`
+ MaxPerAgentFlight int `json:"maxPerAgentInflight,omitempty"`
+ ResultTTLSec int `json:"resultTTLSec,omitempty"`
+ WorkerCount int `json:"workerCount,omitempty"`
+}
+
+// FileConfig is the persistent configuration written to disk.
+type FileConfig struct {
+ Server ServerConfig `json:"server,omitempty"`
+ Browser BrowserConfig `json:"browser,omitempty"`
+ InstanceDefaults InstanceDefaultsConfig `json:"instanceDefaults,omitempty"`
+ Security SecurityConfig `json:"security,omitempty"`
+ Profiles ProfilesConfig `json:"profiles,omitempty"`
+ MultiInstance MultiInstanceConfig `json:"multiInstance,omitempty"`
+ Timeouts TimeoutsConfig `json:"timeouts,omitempty"`
+ Scheduler SchedulerFileConfig `json:"scheduler,omitempty"`
+}
+
+type ServerConfig struct {
+ Port string `json:"port,omitempty"`
+ Bind string `json:"bind,omitempty"`
+ Token string `json:"token,omitempty"`
+ StateDir string `json:"stateDir,omitempty"`
+ Engine string `json:"engine,omitempty"`
+}
+
+type BrowserConfig struct {
+ ChromeVersion string `json:"version,omitempty"`
+ ChromeBinary string `json:"binary,omitempty"`
+ ChromeExtraFlags string `json:"extraFlags,omitempty"`
+ ExtensionPaths []string `json:"extensionPaths,omitempty"`
+}
+
+type InstanceDefaultsConfig struct {
+ Mode string `json:"mode,omitempty"`
+ NoRestore *bool `json:"noRestore,omitempty"`
+ Timezone string `json:"timezone,omitempty"`
+ BlockImages *bool `json:"blockImages,omitempty"`
+ BlockMedia *bool `json:"blockMedia,omitempty"`
+ BlockAds *bool `json:"blockAds,omitempty"`
+ MaxTabs *int `json:"maxTabs,omitempty"`
+ MaxParallelTabs *int `json:"maxParallelTabs,omitempty"`
+ UserAgent string `json:"userAgent,omitempty"`
+ NoAnimations *bool `json:"noAnimations,omitempty"`
+ StealthLevel string `json:"stealthLevel,omitempty"`
+ TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"`
+}
+
+type ProfilesConfig struct {
+ BaseDir string `json:"baseDir,omitempty"`
+ DefaultProfile string `json:"defaultProfile,omitempty"`
+}
+
+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"`
+ MaxRedirects *int `json:"maxRedirects,omitempty"`
+ Attach AttachConfig `json:"attach,omitempty"`
+ IDPI IDPIConfig `json:"idpi,omitempty"`
+}
+
+type MultiInstanceConfig struct {
+ Strategy string `json:"strategy,omitempty"`
+ AllocationPolicy string `json:"allocationPolicy,omitempty"`
+ InstancePortStart *int `json:"instancePortStart,omitempty"`
+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+ Restart MultiInstanceRestartConfig `json:"restart,omitempty"`
+}
+
+// MultiInstanceRestartConfig controls restart-managed strategy recovery behavior.
+type MultiInstanceRestartConfig struct {
+ MaxRestarts *int `json:"maxRestarts,omitempty"`
+ InitBackoffSec *int `json:"initBackoffSec,omitempty"`
+ MaxBackoffSec *int `json:"maxBackoffSec,omitempty"`
+ StableAfterSec *int `json:"stableAfterSec,omitempty"`
+}
+
+type AttachConfig struct {
+ Enabled *bool `json:"enabled,omitempty"`
+ AllowHosts []string `json:"allowHosts,omitempty"`
+ AllowSchemes []string `json:"allowSchemes,omitempty"`
+}
+
+type TimeoutsConfig struct {
+ ActionSec int `json:"actionSec,omitempty"`
+ NavigateSec int `json:"navigateSec,omitempty"`
+ ShutdownSec int `json:"shutdownSec,omitempty"`
+ WaitNavMs int `json:"waitNavMs,omitempty"`
+}
+
+type SchedulerFileConfig struct {
+ Enabled *bool `json:"enabled,omitempty"`
+ Strategy string `json:"strategy,omitempty"`
+ MaxQueueSize *int `json:"maxQueueSize,omitempty"`
+ MaxPerAgent *int `json:"maxPerAgent,omitempty"`
+ MaxInflight *int `json:"maxInflight,omitempty"`
+ MaxPerAgentFlight *int `json:"maxPerAgentInflight,omitempty"`
+ ResultTTLSec *int `json:"resultTTLSec,omitempty"`
+ WorkerCount *int `json:"workerCount,omitempty"`
+}
diff --git a/internal/config/config_utils.go b/internal/config/config_utils.go
new file mode 100644
index 00000000..3e88cf4d
--- /dev/null
+++ b/internal/config/config_utils.go
@@ -0,0 +1,70 @@
+package config
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+var defaultLocalAllowedDomains = []string{"127.0.0.1", "localhost", "::1"}
+
+func homeDir() string {
+ if home := os.Getenv("HOME"); home != "" {
+ return home
+ }
+ h, _ := os.UserHomeDir()
+ return h
+}
+
+func userConfigDir() string {
+ home := homeDir()
+ legacyPath := filepath.Join(home, ".pinchtab")
+
+ configDir, err := os.UserConfigDir()
+ if err != nil {
+ return legacyPath
+ }
+
+ newPath := filepath.Join(configDir, "pinchtab")
+
+ legacyExists := dirExists(legacyPath)
+ newExists := dirExists(newPath)
+
+ if legacyExists && !newExists {
+ return legacyPath
+ }
+
+ return newPath
+}
+
+func dirExists(path string) bool {
+ info, err := os.Stat(path)
+ if err != nil {
+ return false
+ }
+ return info.IsDir()
+}
+
+func (c *RuntimeConfig) ListenAddr() string {
+ return c.Bind + ":" + c.Port
+}
+
+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
+}
+
+func MaskToken(t string) string {
+ if t == "" {
+ return "(none)"
+ }
+ if len(t) <= 8 {
+ return "***"
+ }
+ return t[:4] + "..." + t[len(t)-4:]
+}
diff --git a/internal/config/config_utils_test.go b/internal/config/config_utils_test.go
new file mode 100644
index 00000000..55b4ff61
--- /dev/null
+++ b/internal/config/config_utils_test.go
@@ -0,0 +1,52 @@
+package config
+
+import (
+ "testing"
+)
+
+func TestMaskToken(t *testing.T) {
+ tests := []struct {
+ token string
+ want string
+ }{
+ {"", "(none)"},
+ {"short", "***"},
+ {"very-long-token-secret", "very...cret"},
+ }
+
+ for _, tt := range tests {
+ if got := MaskToken(tt.token); got != tt.want {
+ t.Errorf("MaskToken(%q) = %v, want %v", tt.token, 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))
+ }
+ 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 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)
+ }
+
+ 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)
+ }
+}
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 5ba9ee3d..b4e6fcbb 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -250,17 +250,14 @@ func isValidAttachScheme(scheme string) bool {
}
}
-// ValidStealthLevels returns all valid stealth level values.
func ValidStealthLevels() []string {
return []string{"light", "medium", "full"}
}
-// ValidEvictionPolicies returns all valid tab eviction policy values.
func ValidEvictionPolicies() []string {
return []string{"reject", "close_oldest", "close_lru"}
}
-// ValidStrategies returns all valid strategy values.
func ValidStrategies() []string {
return []string{"simple", "explicit", "simple-autorestart", "always-on"}
}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 2baf87d9..b421b9fb 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -105,7 +105,7 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator
if err := installStableBinary(exe, stableBin); err != nil {
slog.Warn("failed to install pinchtab binary", "path", stableBin, "err", err)
} else {
- slog.Info("installed pinchtab binary", "path", stableBin)
+ slog.Debug("installed pinchtab binary", "path", stableBin)
}
}
@@ -159,7 +159,6 @@ func (o *Orchestrator) SetAllocationPolicy(name string) error {
return err
}
o.instanceMgr.Allocator.SetPolicy(p)
- slog.Info("allocation policy changed", "policy", name)
return nil
}