Skip to content

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

feat: improve CLI server lifecycle and security status

Luigi Agosti992189e983bf
diff --git a/Dockerfile b/Dockerfile
index fbb3162a..a73c69f6 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -67,4 +67,4 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD /bin/sh -lc 'pinchtab health >/dev/null' || exit 1
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
-CMD ["/usr/local/bin/docker-entrypoint.sh", "pinchtab"]
+CMD ["/usr/local/bin/docker-entrypoint.sh", "pinchtab", "server"]
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.go
index c066bb28..34b5ca56 100644
--- a/cmd/pinchtab/cmd_config.go
+++ b/cmd/pinchtab/cmd_config.go
@@ -21,7 +21,7 @@ var configCmd = &cobra.Command{
Use: "config",
Short: "Manage configuration",
Run: func(cmd *cobra.Command, args []string) {
- handleConfigOverview(loadLocalConfig())
+ printConfigOverview(loadLocalConfig())
},
}
@@ -86,9 +86,11 @@ func init() {
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])
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return handleConfigSet(args[0], args[1])
},
+ SilenceUsage: true,
+ SilenceErrors: true,
}
// Allow values like "--no-sandbox --disable-gpu" after the config path.
configSetCmd.Flags().SetInterspersed(false)
@@ -97,15 +99,17 @@ func init() {
Use: "patch <json>",
Short: "Merge JSON into config",
Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigPatch(args[0])
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return handleConfigPatch(args[0])
},
+ SilenceUsage: true,
+ SilenceErrors: true,
})
rootCmd.AddCommand(configCmd)
}
-func handleConfigOverview(cfg *config.RuntimeConfig) {
+func printConfigOverview(cfg *config.RuntimeConfig) {
_, configPath, err := config.LoadFileConfig()
if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("Error loading config path: %v", err)))
@@ -116,33 +120,30 @@ func handleConfigOverview(cfg *config.RuntimeConfig) {
dashboardURL := fmt.Sprintf("http://localhost:%s", dashPort)
running := server.CheckPinchTabRunning(dashPort, cfg.Token)
- for {
- fmt.Print(renderConfigOverview(cfg, configPath, dashboardURL, running))
-
- if !isInteractiveTerminal() {
- return
- }
-
- nextCfg, changed, done, err := promptConfigEdit(cfg)
- if err != nil {
- fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
- fmt.Println()
- continue
- }
- if done {
- return
- }
- if !changed {
- fmt.Println()
- continue
- }
-
- cfg = nextCfg
- dashPort = cfg.Port
- dashboardURL = fmt.Sprintf("http://localhost:%s", dashPort)
- running = server.CheckPinchTabRunning(dashPort, cfg.Token)
- fmt.Println()
+ out := os.Stdout
+ _, _ = fmt.Fprintln(out, cli.StyleStdout(cli.HeadingStyle, "Config"))
+ _, _ = fmt.Fprintln(out)
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "strategy", cli.StyleStdout(cli.ValueStyle, cfg.Strategy))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "allocation policy", cli.StyleStdout(cli.ValueStyle, cfg.AllocationPolicy))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "stealth level", cli.StyleStdout(cli.ValueStyle, cfg.StealthLevel))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "tab eviction", cli.StyleStdout(cli.ValueStyle, cfg.TabEvictionPolicy))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "tab lifecycle", cli.StyleStdout(cli.ValueStyle, formatTabLifecycle(cfg)))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "file", cli.StyleStdout(cli.ValueStyle, configPath))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "token", cli.StyleStdout(cli.ValueStyle, config.MaskToken(cfg.Token)))
+ if running {
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "dashboard", cli.StyleStdout(cli.ValueStyle, dashboardURL))
+ } else {
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "dashboard", cli.StyleStdout(cli.MutedStyle, "not running"))
}
+ _, _ = fmt.Fprintln(out)
+
+ _, _ = fmt.Fprintln(out, cli.StyleStdout(cli.HeadingStyle, "Change config:"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config get <path>"), cli.StyleStdout(cli.MutedStyle, "# read a value (e.g. server.port)"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config set <path> <value>"), cli.StyleStdout(cli.MutedStyle, "# update a value"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config show"), cli.StyleStdout(cli.MutedStyle, "# print labelled config summary"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config token"), cli.StyleStdout(cli.MutedStyle, "# copy API token to clipboard"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab security"), cli.StyleStdout(cli.MutedStyle, "# review security posture"))
+ _, _ = fmt.Fprintf(out, " %s %s\n", cli.StyleStdout(cli.MutedStyle, "Or edit the file directly:"), cli.StyleStdout(cli.ValueStyle, configPath))
}
func formatTabLifecycle(cfg *config.RuntimeConfig) string {
@@ -156,98 +157,6 @@ func formatTabLifecycle(cfg *config.RuntimeConfig) string {
return policy
}
-func renderConfigOverview(cfg *config.RuntimeConfig, configPath, dashboardURL string, running bool) string {
- out := ""
- out += cli.StyleStdout(cli.HeadingStyle, "Config") + "\n\n"
- out += fmt.Sprintf(" 1. %-18s %s\n", "Strategy", cli.StyleStdout(cli.ValueStyle, cfg.Strategy))
- out += fmt.Sprintf(" 2. %-18s %s\n", "Allocation policy", cli.StyleStdout(cli.ValueStyle, cfg.AllocationPolicy))
- out += fmt.Sprintf(" 3. %-18s %s\n", "Stealth level", cli.StyleStdout(cli.ValueStyle, cfg.StealthLevel))
- out += fmt.Sprintf(" 4. %-18s %s\n", "Tab eviction", cli.StyleStdout(cli.ValueStyle, cfg.TabEvictionPolicy))
- out += fmt.Sprintf(" 5. %-18s %s\n", "Tab lifecycle", cli.StyleStdout(cli.ValueStyle, formatTabLifecycle(cfg)))
- out += fmt.Sprintf(" 6. %-18s %s\n", "Copy token", cli.StyleStdout(cli.MutedStyle, "clipboard"))
- out += "\n"
- out += cli.StyleStdout(cli.HeadingStyle, "More") + "\n\n"
- out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "File:"), cli.StyleStdout(cli.ValueStyle, configPath))
- out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Token:"), cli.StyleStdout(cli.ValueStyle, config.MaskToken(cfg.Token)))
- if running {
- out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Dashboard:"), cli.StyleStdout(cli.ValueStyle, dashboardURL))
- } else {
- out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Dashboard:"), cli.StyleStdout(cli.MutedStyle, "not running"))
- }
- if isInteractiveTerminal() {
- out += "\n"
- out += cli.StyleStdout(cli.MutedStyle, "Edit item (1-6, blank to exit):") + " "
- }
- out += "\n"
- return out
-}
-
-func promptConfigEdit(cfg *config.RuntimeConfig) (*config.RuntimeConfig, bool, bool, error) {
- choice, err := promptInput("", "")
- if err != nil {
- return nil, false, false, err
- }
- choice = strings.TrimSpace(choice)
- if choice == "" {
- return nil, false, true, nil
- }
-
- switch choice {
- case "1":
- nextCfg, changed, err := editConfigSelection("Instance strategy", "multiInstance.strategy", cfg.Strategy, config.ValidStrategies())
- return nextCfg, changed, false, err
- case "2":
- nextCfg, changed, err := editConfigSelection("Allocation policy", "multiInstance.allocationPolicy", cfg.AllocationPolicy, config.ValidAllocationPolicies())
- return nextCfg, changed, false, err
- case "3":
- nextCfg, changed, err := editConfigSelection("Default stealth level", "instanceDefaults.stealthLevel", cfg.StealthLevel, config.ValidStealthLevels())
- return nextCfg, changed, false, err
- case "4":
- nextCfg, changed, err := editConfigSelection("Default tab eviction", "instanceDefaults.tabEvictionPolicy", cfg.TabEvictionPolicy, config.ValidEvictionPolicies())
- return nextCfg, changed, false, err
- case "5":
- nextCfg, changed, err := editConfigSelection("Default tab lifecycle", "instanceDefaults.tabPolicy.lifecycle", cfg.TabLifecyclePolicy, config.ValidLifecyclePolicies())
- return nextCfg, changed, false, err
- case "6":
- if err := copyConfigToken(cfg.Token); err != nil {
- return nil, false, false, err
- }
- return nil, false, false, nil
- default:
- return nil, false, false, fmt.Errorf("invalid selection %q", choice)
- }
-}
-
-func editConfigSelection(title, path, current string, values []string) (*config.RuntimeConfig, bool, error) {
- options := make([]menuOption, 0, len(values)+1)
- for _, value := range values {
- label := value
- if value == current {
- label += " (current)"
- }
- options = append(options, menuOption{label: label, value: value})
- }
- options = append(options, menuOption{label: "Cancel", value: "cancel"})
-
- picked, err := promptSelect(title, options)
- if err != nil {
- return nil, false, err
- }
- if picked == "" || picked == "cancel" {
- return nil, false, nil
- }
-
- nextCfg, changed, err := workflow.UpdateValue(path, picked)
- if err != nil {
- return nil, false, err
- }
- if changed {
- fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Updated %s to %s", path, picked)))
- fmt.Println(cli.StyleStdout(cli.MutedStyle, "Restart PinchTab to apply file-based changes."))
- }
- return nextCfg, changed, nil
-}
-
func copyConfigToken(token string) error {
if strings.TrimSpace(token) == "" {
return fmt.Errorf("server token is empty")
@@ -346,39 +255,47 @@ func handleConfigPath() {
func handleConfigGet(path string) {
value, err := workflow.GetValue(path)
if err != nil {
- fmt.Printf("Error: %v\n", err)
+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println(displayConfigValue(path, value))
}
-func handleConfigSet(path, value string) {
+func handleConfigSet(path, value string) error {
change, err := workflow.PrepareSetValue(path, value)
if err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
+ return err
}
if errs := change.ValidationErrors; len(errs) > 0 {
- fmt.Printf("Warning: new value causes validation error(s):\n")
+ fmt.Fprintf(os.Stderr, "Warning: new value causes validation error(s):\n")
for _, err := range errs {
- fmt.Printf(" - %v\n", err)
+ fmt.Fprintf(os.Stderr, " - %v\n", err)
}
- fmt.Print("Save anyway? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
+ if !confirmSaveAnyway() {
+ return fmt.Errorf("aborted: value not saved")
}
}
if err := workflow.SavePreparedChange(change); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
+ return fmt.Errorf("save config: %w", err)
}
fmt.Printf("Set %s = %s\n", path, displayConfigValue(path, value))
+ return nil
+}
+
+// confirmSaveAnyway prompts on a TTY; on non-TTY (agent / pipe) it returns
+// false so the validation warning blocks the save by default.
+func confirmSaveAnyway() bool {
+ if !isInteractiveTerminal() {
+ return false
+ }
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ return response == "y" || response == "Y"
}
func displayConfigValue(path, value string) string {
@@ -388,32 +305,28 @@ func displayConfigValue(path, value string) string {
return value
}
-func handleConfigPatch(jsonPatch string) {
+func handleConfigPatch(jsonPatch string) error {
change, err := workflow.PreparePatch(jsonPatch)
if err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
+ return err
}
if errs := change.ValidationErrors; len(errs) > 0 {
- fmt.Printf("Warning: patch causes validation error(s):\n")
+ fmt.Fprintf(os.Stderr, "Warning: patch causes validation error(s):\n")
for _, err := range errs {
- fmt.Printf(" - %v\n", err)
+ fmt.Fprintf(os.Stderr, " - %v\n", err)
}
- fmt.Print("Save anyway? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
+ if !confirmSaveAnyway() {
+ return fmt.Errorf("aborted: patch not saved")
}
}
if err := workflow.SavePreparedChange(change); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
+ return fmt.Errorf("save config: %w", err)
}
fmt.Println("Config patched successfully")
+ return nil
}
func handleConfigValidate() {
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.go
index 115b5b3d..4fa527bf 100644
--- a/cmd/pinchtab/cmd_config_test.go
+++ b/cmd/pinchtab/cmd_config_test.go
@@ -10,28 +10,34 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
-func TestRenderConfigOverview(t *testing.T) {
- cfg := &config.RuntimeConfig{
- Port: "9867",
- Strategy: "simple",
- AllocationPolicy: "fcfs",
- StealthLevel: "light",
- TabEvictionPolicy: "close_lru",
- Token: "very-long-token-secret",
+func TestPrintConfigOverview(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "very-long-token-secret"
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
}
- output := renderConfigOverview(cfg, "/tmp/pinchtab/config.json", "http://localhost:9867", false)
+
+ cfg := config.Load()
+ output := captureStdout(t, func() {
+ printConfigOverview(cfg)
+ })
required := []string{
"Config",
- "Strategy",
- "Allocation policy",
- "Stealth level",
- "Tab eviction",
- "Copy token",
- "More",
- "/tmp/pinchtab/config.json",
+ "strategy",
+ "allocation policy",
+ "stealth level",
+ "tab eviction",
+ "file",
+ "token",
+ "dashboard",
+ configPath,
"very...cret",
- "Dashboard:",
+ "Change config:",
+ "pinchtab config set",
}
for _, needle := range required {
if !strings.Contains(output, needle) {
@@ -115,15 +121,17 @@ func TestConfigSetRejectsUnsafeChromeExtraFlags(t *testing.T) {
rootCmd.SetArgs(nil)
})
- output := captureStdout(t, func() {
+ var execErr error
+ stderr := captureStderr(t, func() {
rootCmd.SetArgs([]string{"config", "set", "browser.extraFlags", "--no-sandbox --disable-gpu"})
- if err := rootCmd.Execute(); err != nil {
- t.Fatalf("Execute() error = %v", err)
- }
+ execErr = rootCmd.Execute()
})
- if !strings.Contains(output, "browser.extraFlags") || !strings.Contains(output, "runtime compatibility") {
- t.Fatalf("expected unsafe flag warning, got %q", output)
+ if execErr == nil {
+ t.Fatalf("expected Execute() to return error for declined unsafe save")
+ }
+ if !strings.Contains(stderr, "browser.extraFlags") || !strings.Contains(stderr, "runtime compatibility") {
+ t.Fatalf("expected unsafe flag warning on stderr, got %q", stderr)
}
saved, _, err := config.LoadFileConfig()
diff --git a/cmd/pinchtab/cmd_daemon.go b/cmd/pinchtab/cmd_daemon.go
index 2a4ec945..ee6226e9 100644
--- a/cmd/pinchtab/cmd_daemon.go
+++ b/cmd/pinchtab/cmd_daemon.go
@@ -1,6 +1,7 @@
package main
import (
+ "encoding/json"
"fmt"
"os"
"strings"
@@ -16,36 +17,29 @@ var daemonCmd = &cobra.Command{
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) {
+ jsonOut, _ := cmd.Flags().GetBool("json")
sub := ""
if len(args) > 0 {
sub = args[0]
}
- handleDaemonCommand(sub)
+ handleDaemonCommand(sub, jsonOut)
},
}
func init() {
daemonCmd.GroupID = "primary"
+ daemonCmd.Flags().Bool("json", false, "Print daemon status as JSON (status only, no actions)")
rootCmd.AddCommand(daemonCmd)
}
-func handleDaemonCommand(subcommand string) {
+func handleDaemonCommand(subcommand string, jsonOut bool) {
if subcommand == "" || subcommand == "help" || subcommand == "--help" || subcommand == "-h" {
- printDaemonStatusSummary()
-
- if subcommand == "" && isInteractiveTerminal() {
- picked, err := promptSelect("Daemon Actions", daemonMenuOptions(daemon.IsInstalled(), daemon.IsRunning()))
- if err != nil || picked == "exit" || picked == "" {
- os.Exit(0)
- }
- subcommand = picked
- } else {
- daemonUsage()
- if subcommand == "" {
- os.Exit(0)
- }
+ if jsonOut {
+ printDaemonStatusJSON()
return
}
+ printDaemonOverview()
+ return
}
manager, err := daemon.CurrentManager()
@@ -95,91 +89,123 @@ func handleDaemonCommand(subcommand string) {
fmt.Println(cli.StyleStdout(cli.SuccessStyle, " [ok] ") + message)
default:
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))
- daemonUsage()
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.MutedStyle, "Usage: pinchtab daemon <install|start|restart|stop|uninstall>"))
os.Exit(2)
}
}
-func daemonUsage() {
- fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Usage:") + " " + cli.StyleStdout(cli.CommandStyle, "pinchtab daemon <install|start|restart|stop|uninstall>"))
- fmt.Println()
- fmt.Println(cli.StyleStdout(cli.MutedStyle, "Manage the PinchTab user-level background service."))
- fmt.Println()
+type daemonStatus struct {
+ Installed bool `json:"installed"`
+ Running bool `json:"running"`
+ PID string `json:"pid,omitempty"`
+ ServicePath string `json:"servicePath,omitempty"`
+ PreflightError string `json:"preflightError,omitempty"`
+ ManagerError string `json:"managerError,omitempty"`
}
-func daemonMenuOptions(installed, running bool) []menuOption {
- options := make([]menuOption, 0, 4)
- switch {
- case !installed:
- options = append(options, menuOption{label: "Install service", value: "install"})
- case running:
- options = append(options,
- menuOption{label: "Stop service", value: "stop"},
- menuOption{label: "Restart service", value: "restart"},
- menuOption{label: "Uninstall service", value: "uninstall"},
- )
- default:
- options = append(options,
- menuOption{label: "Start service", value: "start"},
- menuOption{label: "Uninstall service", value: "uninstall"},
- )
+func collectDaemonStatus() daemonStatus {
+ st := daemonStatus{
+ Installed: daemon.IsInstalled(),
+ Running: daemon.IsRunning(),
}
- options = append(options, menuOption{label: "Exit", value: "exit"})
- return options
-}
-
-func printDaemonStatusSummary() {
manager, err := daemon.CurrentManager()
if err != nil {
- fmt.Println(cli.StyleStdout(cli.ErrorStyle, " Error: ") + err.Error())
- return
+ st.ManagerError = err.Error()
+ return st
+ }
+ if st.Running {
+ if pid, err := manager.Pid(); err == nil {
+ st.PID = pid
+ }
}
+ if st.Installed {
+ st.ServicePath = manager.ServicePath()
+ }
+ if err := manager.Preflight(); err != nil {
+ st.PreflightError = err.Error()
+ }
+ return st
+}
- installed := daemon.IsInstalled()
- running := daemon.IsRunning()
+func printDaemonStatusJSON() {
+ st := collectDaemonStatus()
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetIndent("", " ")
+ _ = enc.Encode(st)
+}
- fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Daemon status:"))
+func printDaemonOverview() {
+ st := collectDaemonStatus()
- status := cli.StyleStdout(cli.WarningStyle, "not installed")
- if installed {
- status = cli.StyleStdout(cli.SuccessStyle, "installed")
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Daemon"))
+ fmt.Println()
+
+ if st.ManagerError != "" {
+ fmt.Printf(" %-20s %s\n", "manager", cli.StyleStdout(cli.ErrorStyle, st.ManagerError))
+ fmt.Println()
+ return
}
- fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "Service:"), status)
- state := cli.StyleStdout(cli.MutedStyle, "stopped")
- if running {
- state = cli.StyleStdout(cli.SuccessStyle, "active (running)")
+ serviceVal, serviceStyle := "not installed", cli.WarningStyle
+ if st.Installed {
+ serviceVal, serviceStyle = "installed", cli.SuccessStyle
}
- fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "State:"), state)
+ fmt.Printf(" %-20s %s\n", "service", cli.StyleStdout(serviceStyle, serviceVal))
- if running {
- pid, _ := manager.Pid()
- if pid != "" {
- fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "PID:"), cli.StyleStdout(cli.ValueStyle, pid))
- }
+ stateVal, stateStyle := "stopped", cli.WarningStyle
+ if st.Running {
+ stateVal, stateStyle = "running", cli.SuccessStyle
}
+ fmt.Printf(" %-20s %s\n", "state", cli.StyleStdout(stateStyle, stateVal))
- if installed {
- fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "Path:"), cli.StyleStdout(cli.ValueStyle, manager.ServicePath()))
+ if st.PID != "" {
+ fmt.Printf(" %-20s %s\n", "pid", cli.StyleStdout(cli.ValueStyle, st.PID))
}
- if err := manager.Preflight(); err != nil {
- fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "Environment:"), cli.StyleStdout(cli.WarningStyle, err.Error()))
+ if st.ServicePath != "" {
+ fmt.Printf(" %-20s %s\n", "path", cli.StyleStdout(cli.ValueStyle, st.ServicePath))
+ }
+ if st.PreflightError != "" {
+ fmt.Printf(" %-20s %s\n", "environment", cli.StyleStdout(cli.WarningStyle, st.PreflightError))
+ }
+ fmt.Println()
+
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Manage daemon:"))
+ switch {
+ case !st.Installed:
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon install"), cli.StyleStdout(cli.MutedStyle, "# install background service"))
+ case st.Running:
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon stop"), cli.StyleStdout(cli.MutedStyle, "# stop the service"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon restart"), cli.StyleStdout(cli.MutedStyle, "# restart (apply config changes)"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon uninstall"), cli.StyleStdout(cli.MutedStyle, "# remove service file"))
+ default:
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon start"), cli.StyleStdout(cli.MutedStyle, "# start the service"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon uninstall"), cli.StyleStdout(cli.MutedStyle, "# remove service file"))
}
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon --json"), cli.StyleStdout(cli.MutedStyle, "# status as JSON"))
- if installed {
- logs, err := manager.Logs(5)
- if err == nil && strings.TrimSpace(logs) != "" {
+ if st.Installed {
+ if logs := tailDaemonLogs(); logs != "" {
fmt.Println()
fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Recent logs:"))
- lines := strings.Split(logs, "\n")
- for _, line := range lines {
+ for _, line := range strings.Split(logs, "\n") {
if strings.TrimSpace(line) != "" {
fmt.Printf(" %s\n", cli.StyleStdout(cli.MutedStyle, line))
}
}
}
}
- fmt.Println()
+}
+
+func tailDaemonLogs() string {
+ manager, err := daemon.CurrentManager()
+ if err != nil {
+ return ""
+ }
+ logs, err := manager.Logs(5)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(logs)
}
func printDaemonManagerResult(message string, err error) {
diff --git a/cmd/pinchtab/cmd_daemon_test.go b/cmd/pinchtab/cmd_daemon_test.go
index d54078b7..6863f3e1 100644
--- a/cmd/pinchtab/cmd_daemon_test.go
+++ b/cmd/pinchtab/cmd_daemon_test.go
@@ -1,45 +1,41 @@
package main
-import "testing"
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
-func TestDaemonMenuOptions(t *testing.T) {
- tests := []struct {
- name string
- installed bool
- running bool
- want []string
- }{
- {
- name: "not installed",
- installed: false,
- running: false,
- want: []string{"install", "exit"},
- },
- {
- name: "installed stopped",
- installed: true,
- running: false,
- want: []string{"start", "uninstall", "exit"},
- },
- {
- name: "installed running",
- installed: true,
- running: true,
- want: []string{"stop", "restart", "uninstall", "exit"},
- },
+func TestPrintDaemonStatusJSONShape(t *testing.T) {
+ output := captureStdout(t, func() {
+ printDaemonStatusJSON()
+ })
+
+ var got map[string]any
+ if err := json.Unmarshal([]byte(output), &got); err != nil {
+ t.Fatalf("output is not valid JSON: %v\n%s", err, output)
+ }
+ for _, key := range []string{"installed", "running"} {
+ if _, ok := got[key]; !ok {
+ t.Fatalf("expected key %q in JSON output, got %s", key, output)
+ }
}
+}
+
+func TestPrintDaemonOverviewIncludesStatusAndHints(t *testing.T) {
+ output := captureStdout(t, func() {
+ printDaemonOverview()
+ })
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := daemonMenuOptions(tt.installed, tt.running)
- if len(got) != len(tt.want) {
- t.Fatalf("len(daemonMenuOptions()) = %d, want %d", len(got), len(tt.want))
- }
- for i, want := range tt.want {
- if got[i].value != want {
- t.Fatalf("daemonMenuOptions()[%d] = %q, want %q", i, got[i].value, want)
- }
- }
- })
+ for _, needle := range []string{
+ "Daemon",
+ "service",
+ "state",
+ "Manage daemon:",
+ "pinchtab daemon --json",
+ } {
+ if !strings.Contains(output, needle) {
+ t.Fatalf("expected output to contain %q\n%s", needle, output)
+ }
}
}
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index c9cd31ce..0ec669cf 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -3,7 +3,6 @@ package main
import (
"fmt"
"os"
- "strings"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
@@ -14,10 +13,9 @@ import (
var securityCmd = &cobra.Command{
Use: "security",
Short: "Review runtime security posture",
- Long: "Shows runtime security posture and offers to restore recommended security defaults.",
+ Long: "Shows runtime security posture and recommended defaults.",
Run: func(cmd *cobra.Command, args []string) {
- cfg := loadLocalConfig()
- handleSecurityCommand(cfg)
+ printSecurityOverview(loadLocalConfig())
},
}
@@ -44,263 +42,40 @@ func init() {
rootCmd.AddCommand(securityCmd)
}
-func handleSecurityCommand(cfg *config.RuntimeConfig) {
- interactive := isInteractiveTerminal()
+func printSecurityOverview(cfg *config.RuntimeConfig) {
+ posture := cli.AssessSecurityPosture(cfg)
+ recommended := cli.RecommendedSecurityDefaultLines(cfg)
+ warnings := cli.AssessSecurityWarnings(cfg)
- for {
- posture := cli.AssessSecurityPosture(cfg)
- warnings := cli.AssessSecurityWarnings(cfg)
- recommended := cli.RecommendedSecurityDefaultLines(cfg)
-
- printSecuritySummary(posture, interactive)
-
- if len(warnings) > 0 {
- fmt.Println()
- fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Warnings"))
- fmt.Println()
- for _, warning := range warnings {
- fmt.Printf(" - %s\n", cli.StyleStdout(cli.WarningStyle, 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", cli.StyleStdout(cli.MutedStyle, key), cli.StyleStdout(cli.ValueStyle, 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(" %s: %s\n", cli.StyleStdout(cli.MutedStyle, "hint"), cli.StyleStdout(cli.ValueStyle, formatSecurityValue(warning.Attrs[i+1])))
- }
- }
- }
- }
-
- if len(recommended) == 0 && len(warnings) == 0 {
- fmt.Println()
- fmt.Println(" " + cli.StyleStdout(cli.SuccessStyle, "All recommended security defaults are active."))
- } else if len(recommended) > 0 {
- fmt.Println()
- fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Recommended defaults"))
- fmt.Println()
- printRecommendedSecurityDefaults(recommended)
- }
-
- if !interactive {
- if len(recommended) > 0 {
- fmt.Println()
- fmt.Println(cli.StyleStdout(cli.MutedStyle, "Interactive editing skipped because stdin/stdout is not a terminal."))
- }
- return
- }
-
- nextCfg, changed, done, err := promptSecurityEdit(cfg, posture, len(recommended) > 0)
- if err != nil {
- fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
- os.Exit(1)
- }
- if done {
- return
- }
- if !changed {
- fmt.Println()
- fmt.Println(cli.StyleStdout(cli.MutedStyle, "No changes made."))
- return
- }
- cfg = nextCfg
- fmt.Println()
- }
-}
-
-func formatSecurityValue(value any) string {
- switch v := value.(type) {
- case []string:
- return strings.Join(v, ", ")
- default:
- return fmt.Sprint(v)
- }
-}
-
-func printRecommendedSecurityDefaults(lines []string) {
- for _, line := range lines {
- fmt.Printf(" - %s\n", cli.StyleStdout(cli.ValueStyle, line))
- }
-}
-
-func printSecuritySummary(posture cli.SecurityPosture, interactive bool) {
fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Security"))
fmt.Println()
- fmt.Printf(" %s %s\n", posture.Bar, cli.StyleStdout(cli.ValueStyle, posture.Level))
- for i, check := range posture.Checks {
- indicator := cli.StyleStdout(cli.WarningStyle, "!!")
- if check.Passed {
- indicator = cli.StyleStdout(cli.SuccessStyle, "ok")
- }
- if interactive {
- fmt.Printf(" %d. %s %-20s %s\n", i+1, indicator, check.Label, check.Detail)
- continue
+ for _, check := range posture.Checks {
+ style := cli.ValueStyle
+ if !check.Passed {
+ style = cli.WarningStyle
}
- fmt.Printf(" %s %-20s %s\n", indicator, check.Label, check.Detail)
+ fmt.Printf(" %-20s %s\n", check.Label, cli.StyleStdout(style, check.Detail))
}
-}
-
-func promptSecurityEdit(cfg *config.RuntimeConfig, posture cli.SecurityPosture, canRestoreDefaults bool) (*config.RuntimeConfig, bool, bool, error) {
fmt.Println()
- prompt := "Edit item (1-8"
- if canRestoreDefaults {
- prompt += ", u = security up"
- }
- prompt += ", d = security down, blank to exit):"
-
- choice, err := promptInput(cli.StyleStdout(cli.HeadingStyle, prompt), "")
- if err != nil {
- return nil, false, false, err
- }
- choice = strings.ToLower(strings.TrimSpace(choice))
- if choice == "" {
- return nil, false, true, nil
- }
-
- if (choice == "u" || choice == "up") && canRestoreDefaults {
- nextCfg, changed, err := applySecurityUp()
- return nextCfg, changed, false, err
- }
- if choice == "d" || choice == "down" {
- nextCfg, changed, err := applySecurityDown()
- return nextCfg, changed, false, err
- }
-
- index := strings.TrimSpace(choice)
- for i, check := range posture.Checks {
- if index == fmt.Sprint(i+1) {
- nextCfg, changed, err := editSecurityCheck(cfg, check)
- return nextCfg, changed, false, err
+ if len(recommended) == 0 && len(warnings) == 0 {
+ fmt.Println(" " + cli.StyleStdout(cli.SuccessStyle, "All recommended security defaults are active."))
+ } else {
+ label := fmt.Sprintf("%d setting(s) differ from recommended defaults —", len(recommended))
+ if len(recommended) == 0 {
+ label = fmt.Sprintf("%d security warning(s) detected —", len(warnings))
}
+ fmt.Printf(" %s %s\n",
+ cli.StyleStdout(cli.MutedStyle, label),
+ cli.StyleStdout(cli.CommandStyle, "pinchtab security up"))
}
+ fmt.Println()
- return nil, false, false, fmt.Errorf("invalid selection %q", choice)
-}
-
-func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck) (*config.RuntimeConfig, bool, error) {
- switch check.ID {
- case "bind_loopback":
- value, err := promptInput("Set server.bind (127.0.0.1 keeps it local):", cfg.Bind)
- if err != nil {
- return nil, false, err
- }
- if !isLoopbackBindValue(value) {
- fmt.Println()
- fmt.Println(" " + cli.StyleStdout(cli.WarningStyle, "Warning: server.bind is non-loopback"))
- fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "effect") + ": " + cli.StyleStdout(cli.ValueStyle, "may expose the server beyond the local machine unless an outer network boundary still restricts access"))
- fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "scope") + ": " + cli.StyleStdout(cli.ValueStyle, "documented, non-default, security-reducing override"))
- fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "hint") + ": " + cli.StyleStdout(cli.ValueStyle, "keep a token set and review reverse proxy or port-publishing behavior explicitly"))
- }
- return workflow.UpdateValue("server.bind", value)
- case "api_auth_enabled":
- picked, err := promptSelect("API authentication", []menuOption{
- {label: "Generate new token (Recommended)", value: "generate"},
- {label: "Set custom token", value: "custom"},
- {label: "Disable token", value: "disable"},
- {label: "Cancel", value: "cancel"},
- })
- if err != nil || picked == "" || picked == "cancel" {
- return cfg, false, nil
- }
- switch picked {
- case "generate":
- token, err := config.GenerateAuthToken()
- if err != nil {
- return nil, false, err
- }
- return workflow.UpdateValue("server.token", token)
- case "custom":
- token, err := promptInputHiddenDefault("Set server.token:", cfg.Token)
- if err != nil {
- return nil, false, err
- }
- return workflow.UpdateValue("server.token", token)
- case "disable":
- return workflow.UpdateValue("server.token", "")
- }
- case "sensitive_endpoints_disabled":
- current := strings.Join(cfg.EnabledSensitiveEndpoints(), ",")
- value, err := promptInput("Enable sensitive endpoints (evaluate,macro,screencast,download,upload; blank = disable all):", current)
- if err != nil {
- return nil, false, err
- }
- return workflow.UpdateSensitiveEndpoints(value)
- case "attach_disabled":
- picked, err := promptSelect("Attach endpoint", []menuOption{
- {label: "Disable (Recommended)", value: "disable"},
- {label: "Enable", value: "enable"},
- {label: "Cancel", value: "cancel"},
- })
- if err != nil || picked == "" || picked == "cancel" {
- return cfg, false, nil
- }
- return workflow.UpdateValue("security.attach.enabled", fmt.Sprintf("%t", picked == "enable"))
- case "attach_local_only":
- value, err := promptInput("Set security.attach.allowHosts (comma-separated; '*' disables host allowlisting):", strings.Join(cfg.AttachAllowHosts, ","))
- if err != nil {
- return nil, false, err
- }
- if attachHostsContainsWildcard(value) {
- fmt.Println()
- fmt.Println(" " + cli.StyleStdout(cli.WarningStyle, "Warning: security.attach.allowHosts includes '*'"))
- fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "effect") + ": " + cli.StyleStdout(cli.ValueStyle, "disables host allowlisting and allows any reachable attach host with an allowed scheme"))
- fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "scope") + ": " + cli.StyleStdout(cli.ValueStyle, "documented, non-default, security-reducing override"))
- fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "hint") + ": " + cli.StyleStdout(cli.ValueStyle, "use only on isolated, operator-controlled networks"))
- }
- return workflow.UpdateValue("security.attach.allowHosts", value)
- case "idpi_whitelist_scoped":
- value, err := promptInput("Set security.allowedDomains (comma-separated):", strings.Join(cfg.AllowedDomains, ","))
- if err != nil {
- return nil, false, err
- }
- return workflow.UpdateValue("security.allowedDomains", value)
- case "idpi_strict_mode":
- picked, err := promptSelect("IDPI strict mode", []menuOption{
- {label: "Enforce (Recommended)", value: "true"},
- {label: "Warn only", value: "false"},
- {label: "Cancel", value: "cancel"},
- })
- if err != nil || picked == "" || picked == "cancel" {
- return cfg, false, nil
- }
- return workflow.UpdateValue("security.idpi.strictMode", picked)
- case "idpi_content_protection":
- picked, err := promptSelect("IDPI content guard", []menuOption{
- {label: "Active: scan + wrap (Recommended)", value: "both"},
- {label: "Scan only", value: "scan"},
- {label: "Wrap only", value: "wrap"},
- {label: "Disable", value: "off"},
- {label: "Cancel", value: "cancel"},
- })
- if err != nil || picked == "" || picked == "cancel" {
- return cfg, false, nil
- }
- return workflow.UpdateContentGuard(picked)
- }
- return cfg, false, nil
-}
-
-func attachHostsContainsWildcard(value string) bool {
- for _, part := range strings.Split(value, ",") {
- if strings.TrimSpace(part) == "*" {
- return true
- }
- }
- return false
-}
-
-func isLoopbackBindValue(value string) bool {
- switch strings.TrimSpace(strings.ToLower(value)) {
- case "", "127.0.0.1", "localhost", "::1":
- return true
- default:
- return false
- }
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Change security:"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab security up"), cli.StyleStdout(cli.MutedStyle, "# restore recommended defaults"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab security down"), cli.StyleStdout(cli.MutedStyle, "# apply guards-down preset (persistent)"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab server -y"), cli.StyleStdout(cli.MutedStyle, "# guards down for one run only (in-memory)"))
+ fmt.Printf(" %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config set <path> <value>"), cli.StyleStdout(cli.MutedStyle, "# tune individual security flags"))
}
func applySecurityUp() (*config.RuntimeConfig, bool, error) {
diff --git a/cmd/pinchtab/cmd_security_test.go b/cmd/pinchtab/cmd_security_test.go
index b32d19cf..cf555b66 100644
--- a/cmd/pinchtab/cmd_security_test.go
+++ b/cmd/pinchtab/cmd_security_test.go
@@ -15,7 +15,7 @@ func TestHandleSecurityCommandDefaultConfigSkipsEmptySections(t *testing.T) {
cfg := testRuntimeConfig()
output := captureStdout(t, func() {
- handleSecurityCommand(cfg)
+ printSecurityOverview(cfg)
})
required := []string{
@@ -43,6 +43,22 @@ func TestHandleSecurityCommandDefaultConfigSkipsEmptySections(t *testing.T) {
}
}
+func TestPrintSecurityOverviewDoesNotCallAuthDisabledSafe(t *testing.T) {
+ cfg := testRuntimeConfig()
+ cfg.Token = ""
+
+ output := captureStdout(t, func() {
+ printSecurityOverview(cfg)
+ })
+
+ if strings.Contains(output, "All recommended security defaults are active.") {
+ t.Fatalf("auth-disabled config should not be reported as fully recommended\n%s", output)
+ }
+ if !strings.Contains(output, "security warning") {
+ t.Fatalf("expected security warning summary for auth-disabled config\n%s", output)
+ }
+}
+
func TestApplySecurityDownPrintsExplicitRiskFraming(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
t.Setenv("PINCHTAB_CONFIG", configPath)
@@ -83,14 +99,22 @@ func TestApplySecurityDownPrintsExplicitRiskFraming(t *testing.T) {
}
func captureStdout(t *testing.T, fn func()) string {
+ return captureStream(t, &os.Stdout, fn)
+}
+
+func captureStderr(t *testing.T, fn func()) string {
+ return captureStream(t, &os.Stderr, fn)
+}
+
+func captureStream(t *testing.T, target **os.File, fn func()) string {
t.Helper()
- orig := os.Stdout
+ orig := *target
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("os.Pipe() error = %v", err)
}
- os.Stdout = w
+ *target = w
var buf bytes.Buffer
done := make(chan error, 1)
@@ -101,7 +125,7 @@ func captureStdout(t *testing.T, fn func()) string {
}()
defer func() {
- os.Stdout = orig
+ *target = orig
}()
fn()
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.go
index bf755f3f..da142a5f 100644
--- a/cmd/pinchtab/cmd_server.go
+++ b/cmd/pinchtab/cmd_server.go
@@ -5,6 +5,7 @@ import (
"os"
"github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/config/workflow"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
@@ -16,25 +17,49 @@ var serverCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
maybeRunWizard()
- if yolo, _ := cmd.Flags().GetBool("yolo"); yolo {
- if _, _, _, err := workflow.ApplyGuardsDownPreset(); err != nil {
+ cfg := loadConfig()
+ backgroundMarker, _ := cmd.Flags().GetString("background-child")
+ cfg.BackgroundMarker = backgroundMarker
+
+ yolo, _ := cmd.Flags().GetBool("yolo")
+ if yolo {
+ fc, _, err := config.LoadFileConfig()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("--yolo: load config: %v", err)))
+ os.Exit(1)
+ }
+ if _, err := workflow.BuildGuardsDownConfig(fc); err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("--yolo: %v", err)))
os.Exit(1)
}
- fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, "YOLO mode: guards down"))
+ config.ApplyFileConfigToRuntime(cfg, fc)
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, "YOLO mode: guards down for this run only (config file unchanged)"))
}
- cfg := loadConfig()
-
- if headed, _ := cmd.Flags().GetBool("headed"); headed {
+ headed, _ := cmd.Flags().GetBool("headed")
+ if headed {
cfg.Headless = false
cfg.HeadlessSet = true
}
- if exts, _ := cmd.Flags().GetStringArray("extension"); len(exts) > 0 {
+ exts, _ := cmd.Flags().GetStringArray("extension")
+ if len(exts) > 0 {
cfg.ExtensionPaths = append(cfg.ExtensionPaths, exts...)
}
verbose, _ := cmd.Flags().GetBool("verbose")
cfg.VerboseStartup = verbose
+
+ if background, _ := cmd.Flags().GetBool("background"); background {
+ if err := runServerBackground(cfg, serverBackgroundOptions{
+ Yolo: yolo,
+ Headed: headed,
+ Verbose: verbose,
+ Extensions: append([]string(nil), exts...),
+ }); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+ return
+ }
server.RunDashboard(cfg, version)
},
}
@@ -45,5 +70,9 @@ func init() {
serverCmd.Flags().BoolP("headed", "H", false, "Start default instance in headed mode")
serverCmd.Flags().BoolP("yolo", "y", false, "Apply guards down preset (enables evaluate, macro, download)")
serverCmd.Flags().BoolP("verbose", "v", false, "Show full startup banner and logs")
+ serverCmd.Flags().BoolP("background", "b", false, "Spawn the server detached and return JSON with pid/url/token")
+ serverCmd.Flags().String("background-child", "", "Internal marker for background server ownership")
+ _ = serverCmd.Flags().MarkHidden("background-child")
+ serverCmd.AddCommand(serverStopCmd)
rootCmd.AddCommand(serverCmd)
}
diff --git a/cmd/pinchtab/cmd_server_background.go b/cmd/pinchtab/cmd_server_background.go
new file mode 100644
index 00000000..6757d439
--- /dev/null
+++ b/cmd/pinchtab/cmd_server_background.go
@@ -0,0 +1,325 @@
+package main
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
+)
+
+const backgroundStartTimeout = 30 * time.Second
+const backgroundMarkerBytes = 16
+const backgroundHealthProbeHeader = "PinchTab-Background-Marker"
+
+type serverPIDInfo struct {
+ PID int `json:"pid"`
+ Executable string `json:"executable"`
+ Args []string `json:"args"`
+ URL string `json:"url"`
+ Marker string `json:"marker"`
+ StartedAt string `json:"startedAt"`
+}
+
+type serverBackgroundOptions struct {
+ Yolo bool
+ Headed bool
+ Verbose bool
+ Extensions []string
+}
+
+var readProcessCommand = defaultReadProcessCommand
+
+var serverStopCmd = &cobra.Command{
+ Use: "stop",
+ Short: "Stop a background server started with `pinchtab server --background`",
+ Run: func(cmd *cobra.Command, args []string) {
+ if err := runServerStop(); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+ },
+}
+
+func runtimeStateDir() string {
+ return filepath.Dir(config.DefaultConfigPath())
+}
+
+func serverPIDFilePath() string {
+ return filepath.Join(runtimeStateDir(), "server.pid")
+}
+
+func serverLogFilePath() string {
+ return filepath.Join(runtimeStateDir(), "server.log")
+}
+
+func runServerBackground(cfg *config.RuntimeConfig, opts serverBackgroundOptions) error {
+ if info, ok := readServerPID(); ok {
+ if processAlive(info.PID) {
+ if err := verifyServerPIDInfo(info); err == nil {
+ return fmt.Errorf("server already running (pid %d); stop with: pinchtab server stop", info.PID)
+ } else {
+ return fmt.Errorf("background PID file at %s points to a live process that cannot be verified: %w", serverPIDFilePath(), err)
+ }
+ }
+ _ = os.Remove(serverPIDFilePath())
+ }
+
+ baseURL := fmt.Sprintf("http://127.0.0.1:%s", cfg.Port)
+ if isUnauthenticatedPinchTabServerReady(baseURL) {
+ return fmt.Errorf("server already running at %s; stop it before starting a background server", baseURL)
+ }
+ if portIsListening(baseURL) {
+ return fmt.Errorf("port already in use at %s, but it is not a healthy PinchTab server for this config", baseURL)
+ }
+
+ binary, err := os.Executable()
+ if err != nil {
+ return fmt.Errorf("resolve executable: %w", err)
+ }
+ marker, err := newBackgroundMarker()
+ if err != nil {
+ return fmt.Errorf("generate background marker: %w", err)
+ }
+
+ if err := os.MkdirAll(runtimeStateDir(), 0o755); err != nil {
+ return fmt.Errorf("create state dir: %w", err)
+ }
+ logF, err := os.OpenFile(serverLogFilePath(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+ if err != nil {
+ return fmt.Errorf("open log file: %w", err)
+ }
+
+ args := backgroundServerArgs(marker, opts)
+ c := exec.Command(binary, args...) // #nosec G204 -- binary is our own executable
+ c.Stdin = nil
+ c.Stdout = logF
+ c.Stderr = logF
+ detachProcess(c)
+
+ if err := c.Start(); err != nil {
+ _ = logF.Close()
+ return fmt.Errorf("spawn server: %w", err)
+ }
+ pid := c.Process.Pid
+ if err := c.Process.Release(); err != nil {
+ // non-fatal
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.MutedStyle, fmt.Sprintf("warn: release child: %v", err)))
+ }
+ _ = logF.Close()
+
+ if err := writeServerPID(serverPIDInfo{
+ PID: pid,
+ Executable: binary,
+ Args: append([]string(nil), args...),
+ URL: baseURL,
+ Marker: marker,
+ StartedAt: time.Now().UTC().Format(time.RFC3339Nano),
+ }); err != nil {
+ return fmt.Errorf("write pid file: %w", err)
+ }
+
+ if !waitForServerWith(baseURL, marker, backgroundStartTimeout, isBackgroundServerReady) {
+ if !processAlive(pid) {
+ _ = os.Remove(serverPIDFilePath())
+ }
+ return fmt.Errorf("server did not become healthy within %s; check logs at %s", backgroundStartTimeout, serverLogFilePath())
+ }
+
+ out := map[string]any{
+ "pid": pid,
+ "url": baseURL,
+ "token": cfg.Token,
+ "logFile": serverLogFilePath(),
+ "pidFile": serverPIDFilePath(),
+ }
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetIndent("", " ")
+ return enc.Encode(out)
+}
+
+func backgroundServerArgs(marker string, opts serverBackgroundOptions) []string {
+ args := []string{"server", "--background-child", marker}
+ if opts.Yolo {
+ args = append(args, "-y")
+ }
+ if opts.Headed {
+ args = append(args, "-H")
+ }
+ if opts.Verbose {
+ args = append(args, "-v")
+ }
+ for _, ext := range opts.Extensions {
+ args = append(args, "-e", ext)
+ }
+ return args
+}
+
+func isBackgroundServerReady(baseURL, marker string) bool {
+ marker = strings.TrimSpace(marker)
+ if marker == "" {
+ return false
+ }
+ return isPinchTabHealthReady(baseURL+"/health/background", marker)
+}
+
+func isUnauthenticatedPinchTabServerReady(baseURL string) bool {
+ return isPinchTabHealthReady(baseURL+"/health", "")
+}
+
+func isPinchTabHealthReady(url, marker string) bool {
+ client := &http.Client{Timeout: 3 * time.Second}
+ req, err := http.NewRequest(http.MethodGet, url, nil)
+ if err != nil {
+ return false
+ }
+ if marker != "" {
+ req.Header.Set(backgroundHealthProbeHeader, marker)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return false
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusOK {
+ return false
+ }
+
+ var health struct {
+ Status string `json:"status"`
+ Mode string `json:"mode"`
+ Version string `json:"version"`
+ Marker string `json:"marker"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
+ return false
+ }
+ if health.Status != "ok" || health.Mode != "dashboard" || strings.TrimSpace(health.Version) == "" {
+ return false
+ }
+ return marker == "" || health.Marker == marker
+}
+
+func runServerStop() error {
+ info, ok := readServerPID()
+ if !ok {
+ return fmt.Errorf("no background server PID file at %s", serverPIDFilePath())
+ }
+ pid := info.PID
+ if !processAlive(pid) {
+ _ = os.Remove(serverPIDFilePath())
+ return fmt.Errorf("background server (pid %d) is not running; cleaned up stale pid file", pid)
+ }
+ if err := verifyServerPIDInfo(info); err != nil {
+ return err
+ }
+ if err := stopProcess(pid); err != nil {
+ return fmt.Errorf("stop pid %d: %w", pid, err)
+ }
+
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if !processAlive(pid) {
+ break
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ if processAlive(pid) {
+ return fmt.Errorf("background server (pid %d) did not exit within 5s; leaving pid file at %s", pid, serverPIDFilePath())
+ }
+ _ = os.Remove(serverPIDFilePath())
+ fmt.Printf("Stopped background server (pid %d)\n", pid)
+ return nil
+}
+
+func newBackgroundMarker() (string, error) {
+ var b [backgroundMarkerBytes]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b[:]), nil
+}
+
+func writeServerPID(info serverPIDInfo) error {
+ if err := os.MkdirAll(runtimeStateDir(), 0o755); err != nil {
+ return fmt.Errorf("create state dir: %w", err)
+ }
+ data, err := json.MarshalIndent(info, "", " ")
+ if err != nil {
+ return fmt.Errorf("marshal pid info: %w", err)
+ }
+ data = append(data, '\n')
+ return os.WriteFile(serverPIDFilePath(), data, 0o600)
+}
+
+func readServerPID() (serverPIDInfo, bool) {
+ data, err := os.ReadFile(serverPIDFilePath())
+ if err != nil {
+ return serverPIDInfo{}, false
+ }
+ var info serverPIDInfo
+ if err := json.Unmarshal(data, &info); err == nil && info.PID > 0 {
+ return info, true
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
+ if err != nil || pid <= 0 {
+ return serverPIDInfo{}, false
+ }
+ return serverPIDInfo{PID: pid}, true
+}
+
+func verifyServerPIDInfo(info serverPIDInfo) error {
+ if info.PID <= 0 {
+ return fmt.Errorf("invalid pid file: missing pid")
+ }
+ if strings.TrimSpace(info.Executable) == "" || strings.TrimSpace(info.Marker) == "" {
+ return fmt.Errorf("pid file lacks verifiable background metadata; refusing to stop pid %d", info.PID)
+ }
+ command, err := readProcessCommand(info.PID)
+ if err != nil {
+ return fmt.Errorf("read process command for pid %d: %w", info.PID, err)
+ }
+ if !serverPIDCommandMatches(command, info) {
+ return fmt.Errorf("pid %d does not match background server metadata; refusing to stop", info.PID)
+ }
+ return nil
+}
+
+func serverPIDCommandMatches(command string, info serverPIDInfo) bool {
+ command = strings.TrimSpace(command)
+ executable := strings.TrimSpace(info.Executable)
+ if command == "" || executable == "" || info.Marker == "" {
+ return false
+ }
+ if command != executable && !strings.HasPrefix(command, executable+" ") {
+ return false
+ }
+ rest := strings.TrimSpace(strings.TrimPrefix(command, executable))
+ fields := strings.Fields(rest)
+ if len(fields) == 0 || fields[0] != "server" {
+ return false
+ }
+ return strings.Contains(command, info.Marker)
+}
+
+func defaultReadProcessCommand(pid int) (string, error) {
+ if data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)); err == nil && len(data) > 0 {
+ parts := strings.Split(strings.TrimRight(string(data), "\x00"), "\x00")
+ return strings.TrimSpace(strings.Join(parts, " ")), nil
+ }
+ out, err := exec.Command("ps", "-p", strconv.Itoa(pid), "-o", "command=").Output()
+ if err != nil {
+ return "", err
+ }
+ return strings.TrimSpace(string(out)), nil
+}
diff --git a/cmd/pinchtab/cmd_server_background_test.go b/cmd/pinchtab/cmd_server_background_test.go
new file mode 100644
index 00000000..3edd2977
--- /dev/null
+++ b/cmd/pinchtab/cmd_server_background_test.go
@@ -0,0 +1,160 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestIsBackgroundServerReadyRequiresValidPinchTabHealth(t *testing.T) {
+ tests := []struct {
+ name string
+ status int
+ body string
+ want bool
+ }{
+ {
+ name: "pinchtab health",
+ status: http.StatusOK,
+ body: `{"status":"ok","mode":"dashboard","version":"dev","marker":"marker-123"}`,
+ want: true,
+ },
+ {
+ name: "unauthorized pinchtab health",
+ status: http.StatusUnauthorized,
+ body: `{"code":"bad_token","message":"unauthorized"}`,
+ want: false,
+ },
+ {
+ name: "plain ok from other service",
+ status: http.StatusOK,
+ body: `ok`,
+ want: false,
+ },
+ {
+ name: "partial json from other service",
+ status: http.StatusOK,
+ body: `{"status":"ok"}`,
+ want: false,
+ },
+ {
+ name: "valid health with wrong marker",
+ status: http.StatusOK,
+ body: `{"status":"ok","mode":"dashboard","version":"dev","marker":"other"}`,
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/health/background" {
+ t.Fatalf("path = %q, want /health/background", r.URL.Path)
+ }
+ w.WriteHeader(tt.status)
+ _, _ = w.Write([]byte(tt.body))
+ }))
+ defer srv.Close()
+
+ if got := isBackgroundServerReady(srv.URL, "marker-123"); got != tt.want {
+ t.Fatalf("isBackgroundServerReady() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestIsBackgroundServerReadyDoesNotSendBearerToken(t *testing.T) {
+ var gotAuth string
+ var gotMarker string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotAuth = r.Header.Get("Authorization")
+ gotMarker = r.Header.Get(backgroundHealthProbeHeader)
+ _, _ = w.Write([]byte(`{"status":"ok","mode":"dashboard","version":"dev","marker":"marker-123"}`))
+ }))
+ defer srv.Close()
+
+ if !isBackgroundServerReady(srv.URL, "marker-123") {
+ t.Fatal("expected background health probe to succeed")
+ }
+ if gotAuth != "" {
+ t.Fatalf("Authorization = %q, want empty", gotAuth)
+ }
+ if gotMarker != "marker-123" {
+ t.Fatalf("%s = %q, want marker", backgroundHealthProbeHeader, gotMarker)
+ }
+}
+
+func TestBackgroundServerArgsForwardsForegroundFlags(t *testing.T) {
+ got := backgroundServerArgs("marker-123", serverBackgroundOptions{
+ Yolo: true,
+ Headed: true,
+ Verbose: true,
+ Extensions: []string{"./ext-one", "/tmp/ext two"},
+ })
+ want := []string{
+ "server", "--background-child", "marker-123",
+ "-y",
+ "-H",
+ "-v",
+ "-e", "./ext-one",
+ "-e", "/tmp/ext two",
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("backgroundServerArgs() = %#v, want %#v", got, want)
+ }
+}
+
+func TestServerPIDCommandMatchesRequiresExpectedMetadata(t *testing.T) {
+ info := serverPIDInfo{
+ Executable: "/tmp/pinchtab",
+ Marker: "marker-123",
+ }
+
+ tests := []struct {
+ name string
+ command string
+ want bool
+ }{
+ {name: "match", command: "/tmp/pinchtab server --background-child marker-123 -y", want: true},
+ {name: "wrong marker", command: "/tmp/pinchtab server --background-child other", want: false},
+ {name: "wrong subcommand", command: "/tmp/pinchtab bridge --background-child marker-123", want: false},
+ {name: "wrong executable", command: "/tmp/other server --background-child marker-123", want: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := serverPIDCommandMatches(tt.command, info); got != tt.want {
+ t.Fatalf("serverPIDCommandMatches() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestVerifyServerPIDInfoRefusesLegacyPID(t *testing.T) {
+ err := verifyServerPIDInfo(serverPIDInfo{PID: os.Getpid()})
+ if err == nil || !strings.Contains(err.Error(), "lacks verifiable background metadata") {
+ t.Fatalf("verifyServerPIDInfo() error = %v, want missing metadata error", err)
+ }
+}
+
+func TestVerifyServerPIDInfoChecksProcessCommand(t *testing.T) {
+ orig := readProcessCommand
+ readProcessCommand = func(pid int) (string, error) {
+ return "/tmp/pinchtab server --background-child marker-123", nil
+ }
+ defer func() {
+ readProcessCommand = orig
+ }()
+
+ err := verifyServerPIDInfo(serverPIDInfo{
+ PID: os.Getpid(),
+ Executable: "/tmp/pinchtab",
+ Marker: "marker-123",
+ })
+ if err != nil {
+ t.Fatalf("verifyServerPIDInfo() error = %v", err)
+ }
+}
diff --git a/cmd/pinchtab/cmd_server_background_unix.go b/cmd/pinchtab/cmd_server_background_unix.go
new file mode 100644
index 00000000..384dc6b4
--- /dev/null
+++ b/cmd/pinchtab/cmd_server_background_unix.go
@@ -0,0 +1,13 @@
+//go:build !windows
+
+package main
+
+import "syscall"
+
+func processAlive(pid int) bool {
+ return syscall.Kill(pid, 0) == nil
+}
+
+func stopProcess(pid int) error {
+ return syscall.Kill(pid, syscall.SIGTERM)
+}
diff --git a/cmd/pinchtab/cmd_server_background_windows.go b/cmd/pinchtab/cmd_server_background_windows.go
new file mode 100644
index 00000000..2d631639
--- /dev/null
+++ b/cmd/pinchtab/cmd_server_background_windows.go
@@ -0,0 +1,22 @@
+//go:build windows
+
+package main
+
+import "os"
+
+func processAlive(pid int) bool {
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ return false
+ }
+ _ = proc.Release()
+ return true
+}
+
+func stopProcess(pid int) error {
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ return err
+ }
+ return proc.Kill()
+}
diff --git a/cmd/pinchtab/cmd_server_ensure.go b/cmd/pinchtab/cmd_server_ensure.go
index b94f998b..0672d097 100644
--- a/cmd/pinchtab/cmd_server_ensure.go
+++ b/cmd/pinchtab/cmd_server_ensure.go
@@ -6,6 +6,7 @@ import (
"net/http"
"os"
"os/exec"
+ "strings"
"time"
"github.com/pinchtab/pinchtab/internal/config"
@@ -69,8 +70,13 @@ func autoStartServer() error {
if err != nil {
return fmt.Errorf("resolve executable: %w", err)
}
+ marker, err := newBackgroundMarker()
+ if err != nil {
+ return fmt.Errorf("generate background marker: %w", err)
+ }
- cmd := exec.Command(binary, autoStartServerArgs()...) // #nosec G204 -- binary is our own executable from os.Executable(), args are hardcoded subcommands
+ args := autoStartServerArgs(marker)
+ cmd := exec.Command(binary, args...) // #nosec G204 -- binary is our own executable from os.Executable(), args are hardcoded subcommands
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
@@ -80,15 +86,32 @@ func autoStartServer() error {
return fmt.Errorf("spawn server: %w", err)
}
+ pid := cmd.Process.Pid
if err := cmd.Process.Release(); err != nil {
slog.Warn("failed to release server process", "err", err)
}
+ // Track the auto-started server's PID so `pinchtab server stop` can reap
+ // it. Best-effort: failing to write the PID file is logged but not fatal.
+ if err := writeServerPID(serverPIDInfo{
+ PID: pid,
+ Executable: binary,
+ Args: append([]string(nil), args...),
+ Marker: marker,
+ StartedAt: time.Now().UTC().Format(time.RFC3339Nano),
+ }); err != nil {
+ slog.Warn("failed to write server pid file", "err", err)
+ }
+
return nil
}
-func autoStartServerArgs() []string {
- return []string{"server"}
+func autoStartServerArgs(marker ...string) []string {
+ args := []string{"server"}
+ if len(marker) > 0 && strings.TrimSpace(marker[0]) != "" {
+ args = append(args, "--background-child", marker[0])
+ }
+ return args
}
func waitForServer(baseURL, token string, timeout time.Duration) bool {
diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.go
index 2074c150..0b360829 100644
--- a/cmd/pinchtab/cmd_session.go
+++ b/cmd/pinchtab/cmd_session.go
@@ -12,8 +12,9 @@ import (
func init() {
sessionCmd := &cobra.Command{
- Use: "session",
- Short: "Agent session management",
+ Use: "session",
+ Short: "Agent session management",
+ GroupID: "primary",
}
infoCmd := &cobra.Command{
diff --git a/cmd/pinchtab/prompt.go b/cmd/pinchtab/prompt.go
index f65af4ae..4e142e49 100644
--- a/cmd/pinchtab/prompt.go
+++ b/cmd/pinchtab/prompt.go
@@ -53,28 +53,6 @@ func promptSelect(title string, options []menuOption) (string, error) {
return "", fmt.Errorf("invalid selection %q", choice)
}
-func promptInput(prompt, defaultValue string) (string, error) {
- if prompt == "" {
- // The caller already rendered the prompt.
- } else if defaultValue != "" {
- fmt.Printf("%s %s ", prompt, cli.StyleStdout(cli.MutedStyle, "["+defaultValue+"]"))
- } else {
- fmt.Print(prompt + " ")
- }
-
- reader := bufio.NewReader(os.Stdin)
- input, err := reader.ReadString('\n')
- if err != nil && strings.TrimSpace(input) == "" {
- return "", err
- }
-
- value := strings.TrimSpace(input)
- if value == "" {
- return defaultValue, nil
- }
- return value, nil
-}
-
func promptInputHiddenDefault(prompt, defaultValue string) (string, error) {
if prompt != "" {
fmt.Print(prompt + " ")
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
index 8acb2000..411bc9c6 100644
--- a/cmd/pinchtab/root.go
+++ b/cmd/pinchtab/root.go
@@ -1,13 +1,16 @@
package main
import (
+ "encoding/json"
"fmt"
+ "net/http"
"os"
+ "strings"
+ "time"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/safelog"
- "github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
@@ -21,51 +24,8 @@ browsers, manage tabs, and perform interactive tasks.`,
Example: ` pinchtab server
pinchtab nav https://pinchtab.com`,
Run: func(cmd *cobra.Command, args []string) {
- // Check if security wizard needs to run
maybeRunWizard()
- if isInteractiveTerminal() {
- cfg := loadLocalConfig()
- cli.PrintStartupBanner(cfg, cli.StartupBannerOptions{
- Mode: "menu",
- ListenStatus: menuListenStatus(cfg),
- })
-
- picked, err := promptSelect("Main Menu", []menuOption{
- {label: "Start server", value: "server"},
- {label: "Daemon", value: "daemon"},
- {label: "Start bridge", value: "bridge"},
- {label: "Start MCP server", value: "mcp"},
- {label: "Config", value: "config"},
- {label: "Security", value: "security"},
- {label: "Help", value: "help"},
- {label: "Exit", value: "exit"},
- })
-
- if err != nil || picked == "exit" || picked == "" {
- return
- }
-
- switch picked {
- case "server":
- server.RunDashboard(loadConfig(), version)
- case "daemon":
- handleDaemonCommand("")
- case "bridge":
- server.RunBridgeServer(loadConfig(), version)
- case "mcp":
- runMCP(loadConfig())
- case "config":
- handleConfigOverview(cfg)
- case "security":
- handleSecurityCommand(cfg)
- case "help":
- _ = cmd.Help()
- }
- return
- }
-
- // Fallback for non-interactive: start the server
- server.RunDashboard(loadConfig(), version)
+ printAgentHints(loadLocalConfig())
},
}
@@ -84,12 +44,141 @@ func maybeRunWizard() {
runSecurityWizard(fileCfg, configPath, isNew)
}
-func menuListenStatus(cfg *config.RuntimeConfig) string {
- dashPort := cfg.Port
- if server.CheckPinchTabRunning(dashPort, cfg.Token) {
- return "running"
+type healthSnapshot struct {
+ Status string `json:"status"`
+ Mode string `json:"mode"`
+ Version string `json:"version"`
+ Security *struct {
+ Level string `json:"level"`
+ AllowedDomains []string `json:"allowedDomains"`
+ IDPIEnabled bool `json:"idpiEnabled"`
+ EnabledSensitiveEndpoints []string `json:"enabledSensitiveEndpoints"`
+ GuardsDown bool `json:"guardsDown"`
+ } `json:"security"`
+}
+
+type healthSnapshotState string
+
+const (
+ healthSnapshotStopped healthSnapshotState = "stopped"
+ healthSnapshotRunning healthSnapshotState = "running"
+ healthSnapshotProtected healthSnapshotState = "protected listener"
+ healthSnapshotUnhealthy healthSnapshotState = "unhealthy"
+ healthSnapshotInvalid healthSnapshotState = "invalid health response"
+)
+
+func formatAllowedDomains(domains []string) string {
+ if len(domains) == 0 {
+ return "all"
+ }
+ for _, d := range domains {
+ if strings.TrimSpace(d) == "*" {
+ return "all"
+ }
+ }
+ return strings.Join(domains, ", ")
+}
+
+func fetchHealthSnapshot(port string) (*healthSnapshot, healthSnapshotState) {
+ client := &http.Client{Timeout: 500 * time.Millisecond}
+ req, _ := http.NewRequest("GET", fmt.Sprintf("http://localhost:%s/health", port), nil)
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, healthSnapshotStopped
+ }
+ defer func() { _ = resp.Body.Close() }()
+ switch resp.StatusCode {
+ case http.StatusOK:
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil, healthSnapshotProtected
+ default:
+ return nil, healthSnapshotUnhealthy
+ }
+ var snap healthSnapshot
+ if err := json.NewDecoder(resp.Body).Decode(&snap); err != nil {
+ return nil, healthSnapshotInvalid
}
- return "stopped"
+ if snap.Status != "ok" || snap.Mode != "dashboard" || strings.TrimSpace(snap.Version) == "" {
+ return nil, healthSnapshotInvalid
+ }
+ return &snap, healthSnapshotRunning
+}
+
+func printAgentHints(cfg *config.RuntimeConfig) {
+ snap, healthState := fetchHealthSnapshot(cfg.Port)
+ running := healthState == healthSnapshotRunning
+ out := os.Stdout
+
+ _, _ = fmt.Fprintln(out, cli.StyleStdout(cli.HeadingStyle, "PinchTab")+" "+cli.StyleStdout(cli.MutedStyle, version))
+ _, _ = fmt.Fprintln(out)
+
+ if running {
+ serverStatus := "running"
+ serverStyle := cli.SuccessStyle
+ if snap != nil && snap.Security != nil && snap.Security.GuardsDown {
+ serverStatus = "running (YOLO — guards down for this run)"
+ serverStyle = cli.WarningStyle
+ }
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "server", cli.StyleStdout(serverStyle, serverStatus))
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "listen", cli.StyleStdout(cli.ValueStyle, cfg.ListenAddr()))
+ if snap != nil && snap.Security != nil {
+ if eps := snap.Security.EnabledSensitiveEndpoints; len(eps) > 0 {
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "sensitive", cli.StyleStdout(cli.WarningStyle, strings.Join(eps, ", ")))
+ }
+ }
+ } else {
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "server", cli.StyleStdout(cli.WarningStyle, string(healthState)))
+ }
+
+ var domains []string
+ idpiEnabled := cfg.IDPI.Enabled
+ if running && snap != nil && snap.Security != nil {
+ domains = snap.Security.AllowedDomains
+ idpiEnabled = snap.Security.IDPIEnabled
+ } else {
+ domains = cfg.AllowedDomains
+ }
+ formatted := formatAllowedDomains(domains)
+ domStyle := cli.ValueStyle
+ if formatted == "all" {
+ domStyle = cli.WarningStyle
+ }
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "allowedDomains", cli.StyleStdout(domStyle, formatted))
+
+ idpiStatus := "disabled"
+ idpiStyle := cli.WarningStyle
+ if idpiEnabled {
+ idpiStatus = "enabled"
+ idpiStyle = cli.SuccessStyle
+ }
+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "idpi", cli.StyleStdout(idpiStyle, idpiStatus))
+ _, _ = fmt.Fprintln(out)
+
+ _, _ = fmt.Fprintln(out, cli.StyleStdout(cli.HeadingStyle, "Next steps:"))
+ switch healthState {
+ case healthSnapshotRunning:
+ _, _ = fmt.Fprintf(out, " %-64s %s\n", cli.StyleStdout(cli.CommandStyle, "export PINCHTAB_SESSION=$(pinchtab session create --agent-id <id>)"), cli.StyleStdout(cli.MutedStyle, "# start a dedicated session"))
+ _, _ = fmt.Fprintf(out, " %-64s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab nav <url>"), cli.StyleStdout(cli.MutedStyle, "# open a page in the current tab"))
+ _, _ = fmt.Fprintf(out, " %-64s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab snap"), cli.StyleStdout(cli.MutedStyle, "# inspect interactive elements"))
+ case healthSnapshotProtected:
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config token"), cli.StyleStdout(cli.MutedStyle, "# copy configured API token"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab health --json"), cli.StyleStdout(cli.MutedStyle, "# retry health with the current token"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config show"), cli.StyleStdout(cli.MutedStyle, "# inspect configured port and token"))
+ case healthSnapshotInvalid, healthSnapshotUnhealthy:
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab health --json"), cli.StyleStdout(cli.MutedStyle, "# inspect the current listener"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config show"), cli.StyleStdout(cli.MutedStyle, "# verify configured port/token"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab server"), cli.StyleStdout(cli.MutedStyle, "# start after freeing the port"))
+ default:
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab server"), cli.StyleStdout(cli.MutedStyle, "# start the server (foreground)"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab server -y"), cli.StyleStdout(cli.MutedStyle, "# start with guards down (this run only)"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon install"), cli.StyleStdout(cli.MutedStyle, "# install background service"))
+ }
+ _, _ = fmt.Fprintln(out)
+
+ _, _ = fmt.Fprintln(out, cli.StyleStdout(cli.HeadingStyle, "Configure:"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab config show"), cli.StyleStdout(cli.MutedStyle, "# view current config"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab security"), cli.StyleStdout(cli.MutedStyle, "# review security posture"))
+ _, _ = fmt.Fprintf(out, " %-44s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab --help"), cli.StyleStdout(cli.MutedStyle, "# full command list"))
}
func Execute() {
diff --git a/cmd/pinchtab/root_test.go b/cmd/pinchtab/root_test.go
new file mode 100644
index 00000000..7f0e4a1c
--- /dev/null
+++ b/cmd/pinchtab/root_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestFetchHealthSnapshotClassifiesOnlyValidDashboardHealthAsRunning(t *testing.T) {
+ tests := []struct {
+ name string
+ status int
+ body string
+ want healthSnapshotState
+ }{
+ {
+ name: "valid dashboard health",
+ status: http.StatusOK,
+ body: `{"status":"ok","mode":"dashboard","version":"dev","security":{"allowedDomains":["localhost"],"idpiEnabled":true}}`,
+ want: healthSnapshotRunning,
+ },
+ {
+ name: "valid dashboard health without security block",
+ status: http.StatusOK,
+ body: `{"status":"ok","mode":"dashboard","version":"dev"}`,
+ want: healthSnapshotRunning,
+ },
+ {
+ name: "protected listener",
+ status: http.StatusUnauthorized,
+ body: `{"code":"missing_token","message":"unauthorized"}`,
+ want: healthSnapshotProtected,
+ },
+ {
+ name: "foreign json",
+ status: http.StatusOK,
+ body: `{"status":"ok"}`,
+ want: healthSnapshotInvalid,
+ },
+ {
+ name: "foreign text",
+ status: http.StatusOK,
+ body: `ok`,
+ want: healthSnapshotInvalid,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ srv := newLocalhostHealthServer(t, tt.status, tt.body)
+ defer srv.Close()
+
+ _, port, err := net.SplitHostPort(srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatalf("SplitHostPort() error = %v", err)
+ }
+ _, got := fetchHealthSnapshot(port)
+ if got != tt.want {
+ t.Fatalf("fetchHealthSnapshot() state = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestPrintAgentHintsDoesNotTreatAuthFailureAsRunning(t *testing.T) {
+ srv := newLocalhostHealthServer(t, http.StatusUnauthorized, `{"code":"missing_token","message":"unauthorized"}`)
+ defer srv.Close()
+
+ _, port, err := net.SplitHostPort(srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatalf("SplitHostPort() error = %v", err)
+ }
+ cfg := testRuntimeConfig()
+ cfg.Port = port
+ cfg.Token = "wrong-token"
+
+ output := captureStdout(t, func() {
+ printAgentHints(cfg)
+ })
+ if !strings.Contains(output, "protected listener") {
+ t.Fatalf("expected protected listener status, got\n%s", output)
+ }
+ if strings.Contains(output, "pinchtab nav <url>") {
+ t.Fatalf("protected listener should not show running-server next steps\n%s", output)
+ }
+}
+
+func TestFetchHealthSnapshotDoesNotSendBearerToken(t *testing.T) {
+ var gotAuth string
+ srv := newLocalhostHealthServerWithHandler(t, func(w http.ResponseWriter, r *http.Request) {
+ gotAuth = r.Header.Get("Authorization")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = io.WriteString(w, `{"code":"missing_token","message":"unauthorized"}`)
+ })
+ defer srv.Close()
+
+ _, port, err := net.SplitHostPort(srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatalf("SplitHostPort() error = %v", err)
+ }
+ _, got := fetchHealthSnapshot(port)
+ if got != healthSnapshotProtected {
+ t.Fatalf("fetchHealthSnapshot() state = %q, want %q", got, healthSnapshotProtected)
+ }
+ if gotAuth != "" {
+ t.Fatalf("Authorization = %q, want empty", gotAuth)
+ }
+}
+
+func newLocalhostHealthServer(t *testing.T, status int, body string) *httptest.Server {
+ t.Helper()
+
+ return newLocalhostHealthServerWithHandler(t, func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ _, _ = io.WriteString(w, body)
+ })
+}
+
+func newLocalhostHealthServerWithHandler(t *testing.T, handler http.HandlerFunc) *httptest.Server {
+ t.Helper()
+
+ listener, err := net.Listen("tcp", "localhost:0")
+ if err != nil {
+ t.Fatalf("Listen() error = %v", err)
+ }
+ srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/health" {
+ t.Fatalf("path = %q, want /health", r.URL.Path)
+ }
+ handler(w, r)
+ }))
+ srv.Listener = listener
+ srv.Start()
+ return srv
+}
diff --git a/internal/cli/actions/actions_system.go b/internal/cli/actions/actions_system.go
index dbe81813..3639ee37 100644
--- a/internal/cli/actions/actions_system.go
+++ b/internal/cli/actions/actions_system.go
@@ -20,24 +20,40 @@ func Health(client *http.Client, base, token string, cmd *cobra.Command) {
return
}
- // Terse: "ok" or "degraded: <reason>"
body := apiclient.DoGetRaw(client, base, token, "/health", nil)
var result map[string]any
if err := json.Unmarshal(body, &result); err != nil {
output.Value("ok")
+ printHealthHints(true)
return
}
status, _ := result["status"].(string)
if status == "ok" {
output.Value("ok")
+ printHealthHints(true)
+ return
+ }
+ reason, _ := result["reason"].(string)
+ if reason != "" {
+ output.Value("degraded: " + reason)
} else {
- reason, _ := result["reason"].(string)
- if reason != "" {
- output.Value("degraded: " + reason)
- } else {
- output.Value(status)
- }
+ output.Value(status)
+ }
+ printHealthHints(false)
+}
+
+func printHealthHints(ok bool) {
+ _, _ = fmt.Fprintln(os.Stdout)
+ _, _ = fmt.Fprintln(os.Stdout, "Next steps:")
+ if ok {
+ _, _ = fmt.Fprintf(os.Stdout, " %-64s %s\n", "export PINCHTAB_SESSION=$(pinchtab session create --agent-id <id>)", "# start a dedicated session")
+ _, _ = fmt.Fprintf(os.Stdout, " %-64s %s\n", "pinchtab nav <url>", "# open a page in the current tab")
+ _, _ = fmt.Fprintf(os.Stdout, " %-64s %s\n", "pinchtab snap", "# inspect interactive elements")
+ return
}
+ _, _ = fmt.Fprintf(os.Stdout, " %-44s %s\n", "pinchtab daemon", "# check service status and logs")
+ _, _ = fmt.Fprintf(os.Stdout, " %-44s %s\n", "pinchtab security", "# review security posture")
+ _, _ = fmt.Fprintf(os.Stdout, " %-44s %s\n", "pinchtab health --json", "# full health payload")
}
func Instances(client *http.Client, base, token string, cmd *cobra.Command) {
diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.go
index b5b42adc..95e3d701 100644
--- a/internal/cli/apiclient/client.go
+++ b/internal/cli/apiclient/client.go
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io"
- "log"
"net/http"
"net/url"
"os"
@@ -127,9 +126,9 @@ func doPostQuietWithStatus(client *http.Client, base, token, path string, body m
var result map[string]any
if resp.StatusCode < 400 {
- if err := json.Unmarshal(respBody, &result); err != nil {
- log.Printf("warning: error unmarshaling response: %v", err)
- }
+ // Object responses populate result; array/scalar responses leave it nil.
+ // Callers that need a map should branch on result == nil.
+ _ = json.Unmarshal(respBody, &result)
}
return resp.StatusCode, respBody, result
}
@@ -222,13 +221,16 @@ func printAndDecode(body []byte) map[string]any {
} else {
fmt.Println(string(body))
}
+ if !isJSON {
+ return nil
+ }
var result map[string]any
- if isJSON {
- if err := json.Unmarshal(body, &result); err != nil {
- log.Printf("warning: error unmarshaling response: %v", err)
- }
+ if err := json.Unmarshal(body, &result); err == nil {
+ return result
}
- return result
+ // Body is valid JSON but not an object (array, string, number, etc.).
+ // That's fine — many endpoints return arrays. Don't warn.
+ return nil
}
// ResolveInstanceBase fetches the named instance from the orchestrator and returns
diff --git a/internal/cli/report/security.go b/internal/cli/report/security.go
index 94bc8a38..34d3bf4e 100644
--- a/internal/cli/report/security.go
+++ b/internal/cli/report/security.go
@@ -25,7 +25,6 @@ type SecurityPosture struct {
Passed int
Total int
Level string
- Bar string
}
func AssessSecurityPosture(cfg *config.RuntimeConfig) SecurityPosture {
@@ -90,7 +89,6 @@ func AssessSecurityPosture(cfg *config.RuntimeConfig) SecurityPosture {
Passed: passed,
Total: len(checks),
Level: securityPostureLevel(passed, len(checks)),
- Bar: securityPostureBar(passed, len(checks)),
}
}
@@ -98,20 +96,6 @@ func assessSecurityPosture(cfg *config.RuntimeConfig) SecurityPosture {
return AssessSecurityPosture(cfg)
}
-func securityPostureBar(passed, total int) string {
- if total == 0 {
- return "[ ]"
- }
- const width = 10
- pct := float64(passed) / float64(total)
- filled := int(pct * width)
- if filled > width {
- filled = width
- }
- bar := "[" + strings.Repeat("■", filled) + strings.Repeat(" ", width-filled) + "]"
- return bar
-}
-
func AssessSecurityWarnings(cfg *config.RuntimeConfig) []SecurityWarning {
if cfg == nil {
return nil
diff --git a/internal/cli/report/startup.go b/internal/cli/report/startup.go
index 2c23365c..bdccc751 100644
--- a/internal/cli/report/startup.go
+++ b/internal/cli/report/startup.go
@@ -34,7 +34,7 @@ func PrintStartupBanner(cfg *config.RuntimeConfig, opts StartupBannerOptions) {
}
}
- writeBannerLine(renderStartupLogo(blankIfEmpty(opts.Mode, "server")))
+ writeBannerLine(renderStartupHeading(blankIfEmpty(opts.Mode, "server")))
writeBannerf(" %s %s\n", styleLabel("listen"), formatListenValue(blankIfEmpty(opts.ListenAddr, cfg.ListenAddr()), defaultListenStatus(opts.Mode, opts.ListenStatus)))
if opts.PublicURL != "" {
writeBannerf(" %s %s\n", styleLabel("url"), styleValue(opts.PublicURL))
@@ -50,7 +50,7 @@ func PrintStartupBanner(cfg *config.RuntimeConfig, opts StartupBannerOptions) {
writeBannerf(" %s %s\n", styleLabel("daemon"), daemonStatus)
posture := AssessSecurityPosture(cfg)
- writeBannerf(" %s %s %s\n", styleLabel("security"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
+ writeBannerf(" %s %s\n", styleLabel("security"), styleSecurityLevel(posture.Level))
if opts.ProfileDir != "" {
writeBannerf(" %s %s\n", styleLabel("profile"), styleValue(opts.ProfileDir))
@@ -61,12 +61,12 @@ func PrintStartupBanner(cfg *config.RuntimeConfig, opts StartupBannerOptions) {
func PrintSecuritySummary(w io.Writer, cfg *config.RuntimeConfig, prefix string, detailed bool) {
posture := AssessSecurityPosture(cfg)
if detailed {
- writeSummaryf(w, "%s%s %s %s\n", prefix, styleHeading("Security"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
+ writeSummaryf(w, "%s%s %s\n", prefix, styleHeading("Security"), styleSecurityLevel(posture.Level))
for _, check := range posture.Checks {
writeSummaryf(w, "%s %s %s %s\n", prefix, styleMarker(check.Passed), styleCheckLabel(check.Label), styleCheckDetail(check.Passed, check.Detail))
}
} else {
- writeSummaryf(w, "%s%s %s %s\n", prefix, styleLabel("security"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
+ writeSummaryf(w, "%s%s %s\n", prefix, styleLabel("security"), styleSecurityLevel(posture.Level))
}
}
@@ -77,11 +77,12 @@ func blankIfEmpty(value, fallback string) string {
return value
}
-func renderStartupLogo(mode string) string {
+func renderStartupHeading(mode string) string {
+ heading := styleHeading("PinchTab")
if mode == "menu" || mode == "" {
- return styleLogo(startupLogo)
+ return heading
}
- return styleLogo(startupLogo) + " " + styleMode(mode)
+ return heading + " " + styleMode(mode)
}
func writeBannerLine(line string) {
@@ -100,10 +101,6 @@ func styleHeading(text string) string {
return applyStyle(text, headingStyle)
}
-func styleLogo(text string) string {
- return applyStyle(text, headingStyle)
-}
-
func styleMode(text string) string {
return applyStyle(text, commandStyle)
}
@@ -151,10 +148,6 @@ func styleSecurityLevel(level string) string {
return applyStyle(level, termstyle.NewStyle().Foreground(termstyle.Color(SecurityLevelColor(level))).Bold(true))
}
-func styleSecurityBar(level, bar string) string {
- return applyStyle(bar, termstyle.NewStyle().Foreground(termstyle.Color(SecurityLevelColor(level))).Bold(true))
-}
-
func SecurityLevelColor(level string) string {
switch level {
case "LOCKED":
@@ -193,9 +186,3 @@ func defaultListenStatus(mode, explicit string) string {
return ""
}
}
-
-const startupLogo = ` ____ _ _ _____ _
- | _ \(_)_ __ ___| |__ |_ _|_ _| |__
- | |_) | | '_ \ / __| '_ \ | |/ _ | '_ \
- | __/| | | | | (__| | | | | | (_| | |_) |
- |_| |_|_| |_|\___|_| |_| |_|\__,_|_.__/`
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 1855e7b5..56934111 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -17,6 +17,7 @@ type RuntimeConfig struct {
TrustProxyHeaders bool // Only trust X-Forwarded-*/Forwarded headers when behind a trusted reverse proxy
CookieSecure *bool // Nil = auto-detect based on request scheme/host for backward compatibility
VerboseStartup bool // Show full banner and slog output on server start
+ BackgroundMarker string
// Security settings
AllowEvaluate bool
diff --git a/internal/config/workflow/security.go b/internal/config/workflow/security.go
index b08260fe..9d15f443 100644
--- a/internal/config/workflow/security.go
+++ b/internal/config/workflow/security.go
@@ -98,27 +98,28 @@ func UpdateContentGuard(mode string) (*config.RuntimeConfig, bool, error) {
return config.Load(), true, nil
}
-func ApplyGuardsDownPreset() (*config.RuntimeConfig, string, bool, error) {
- fc, configPath, err := config.LoadFileConfig()
- if err != nil {
- return nil, "", false, fmt.Errorf("load config: %w", err)
+// BuildGuardsDownConfig mutates fc in memory to apply the guards-down preset.
+// It does not persist anything. Returns whether fc was modified.
+func BuildGuardsDownConfig(fc *config.FileConfig) (bool, error) {
+ if fc == nil {
+ return false, fmt.Errorf("nil file config")
}
originalJSON, err := formatFileConfigJSON(fc)
if err != nil {
- return nil, "", false, err
+ return false, err
}
original, err := config.GetConfigValue(fc, "server.token")
if err != nil {
- return nil, "", false, fmt.Errorf("read server.token: %w", err)
+ return false, fmt.Errorf("read server.token: %w", err)
}
if strings.TrimSpace(original) == "" {
token, err := config.GenerateAuthToken()
if err != nil {
- return nil, "", false, fmt.Errorf("generate token: %w", err)
+ return false, fmt.Errorf("generate token: %w", err)
}
if err := config.SetConfigValue(fc, "server.token", token); err != nil {
- return nil, "", false, fmt.Errorf("set server.token: %w", err)
+ return false, fmt.Errorf("set server.token: %w", err)
}
}
@@ -142,23 +143,33 @@ func ApplyGuardsDownPreset() (*config.RuntimeConfig, string, bool, error) {
{path: "security.idpi.wrapContent", value: "false"},
} {
if err := config.SetConfigValue(fc, item.path, item.value); err != nil {
- return nil, "", false, fmt.Errorf("set %s: %w", item.path, err)
+ return false, fmt.Errorf("set %s: %w", item.path, err)
}
}
if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
- return nil, "", false, errs[0]
+ return false, errs[0]
}
nextJSON, err := formatFileConfigJSON(fc)
+ if err != nil {
+ return false, err
+ }
+ return originalJSON != nextJSON, nil
+}
+
+func ApplyGuardsDownPreset() (*config.RuntimeConfig, string, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return nil, "", false, fmt.Errorf("load config: %w", err)
+ }
+ changed, err := BuildGuardsDownConfig(fc)
if err != nil {
return nil, "", false, err
}
- changed := originalJSON != nextJSON
if !changed {
return config.Load(), configPath, false, nil
}
-
if err := config.SaveFileConfig(fc, configPath); err != nil {
return nil, "", false, fmt.Errorf("save config: %w", err)
}
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index f402c6a6..447821f0 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -12,6 +12,7 @@ import (
"github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/browsersession"
+ "github.com/pinchtab/pinchtab/internal/cli/report"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
)
@@ -54,6 +55,15 @@ type healthInstanceInfo struct {
Status string `json:"status"`
}
+type healthSecurityInfo struct {
+ Level string `json:"level"`
+ Bind string `json:"bind"`
+ AllowedDomains []string `json:"allowedDomains"`
+ IDPIEnabled bool `json:"idpiEnabled"`
+ EnabledSensitiveEndpoints []string `json:"enabledSensitiveEndpoints"`
+ GuardsDown bool `json:"guardsDown"`
+}
+
type healthEnvelope struct {
Status string `json:"status"`
Mode string `json:"mode"`
@@ -66,6 +76,7 @@ type healthEnvelope struct {
Agents int `json:"agents"`
RestartRequired bool `json:"restartRequired"`
RestartReasons []string `json:"restartReasons,omitempty"`
+ Security *healthSecurityInfo `json:"security,omitempty"`
}
func NewConfigAPI(
@@ -108,7 +119,7 @@ func (c *ConfigAPI) RegisterHandlers(mux *http.ServeMux) {
}
func (c *ConfigAPI) HandleHealth(w http.ResponseWriter, r *http.Request) {
- info, err := c.healthInfo()
+ info, err := c.healthInfo(healthSecurityVisibleTo(r))
if err != nil {
httpx.Error(w, 500, err)
return
@@ -194,7 +205,7 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, c.configEnvelopeFor(normalized, path, restartReasons))
}
-func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {
+func (c *ConfigAPI) healthInfo(includeSecurity bool) (healthEnvelope, error) {
_, _, restartReasons, err := c.currentConfig()
if err != nil {
return healthEnvelope{}, err
@@ -224,7 +235,7 @@ func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {
if c.agents != nil {
agentCount = c.agents.AgentCount()
}
- return healthEnvelope{
+ out := healthEnvelope{
Status: "ok",
Mode: "dashboard",
Version: c.version,
@@ -236,7 +247,54 @@ func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {
Agents: agentCount,
RestartRequired: len(restartReasons) > 0,
RestartReasons: restartReasons,
- }, nil
+ }
+ if includeSecurity {
+ security := runtimeSecurityInfo(c.runtime)
+ out.Security = &security
+ }
+ return out, nil
+}
+
+func healthSecurityVisibleTo(r *http.Request) bool {
+ switch authn.CredentialsFromRequest(r).Method {
+ case authn.MethodHeader, authn.MethodCookie:
+ return true
+ default:
+ return false
+ }
+}
+
+func runtimeSecurityInfo(cfg *config.RuntimeConfig) healthSecurityInfo {
+ if cfg == nil {
+ return healthSecurityInfo{Level: "UNKNOWN"}
+ }
+ posture := report.AssessSecurityPosture(cfg)
+ enabled := append([]string(nil), cfg.EnabledSensitiveEndpoints()...)
+ domains := append([]string(nil), cfg.AllowedDomains...)
+ return healthSecurityInfo{
+ Level: posture.Level,
+ Bind: cfg.Bind,
+ AllowedDomains: domains,
+ IDPIEnabled: cfg.IDPI.Enabled,
+ EnabledSensitiveEndpoints: enabled,
+ GuardsDown: isGuardsDownPosture(cfg),
+ }
+}
+
+// isGuardsDownPosture reports whether the runtime config matches the
+// guards-down preset signature (all sensitive endpoints + attach + IDPI off).
+func isGuardsDownPosture(cfg *config.RuntimeConfig) bool {
+ if cfg == nil {
+ return false
+ }
+ return cfg.AllowEvaluate &&
+ cfg.AllowMacro &&
+ cfg.AllowScreencast &&
+ cfg.AllowDownload &&
+ cfg.AllowUpload &&
+ cfg.AllowNetworkIntercept &&
+ cfg.AttachEnabled &&
+ !cfg.IDPI.Enabled
}
func (c *ConfigAPI) currentConfig() (config.FileConfig, string, []string, error) {
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
index d77c5f5e..daf47f8d 100644
--- a/internal/dashboard/config_api_test.go
+++ b/internal/dashboard/config_api_test.go
@@ -13,6 +13,7 @@ import (
"testing"
"time"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -316,6 +317,48 @@ func TestHandleHealthIncludesAgentCount(t *testing.T) {
}
}
+func TestHandleHealthSecurityVisibilityByAuthMethod(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ api := newConfigAPITestAPI(t, fc)
+
+ tests := []struct {
+ name string
+ authHeader string
+ cookie bool
+ wantSecurity bool
+ }{
+ {name: "bearer", authHeader: "Bearer secret-token", wantSecurity: true},
+ {name: "dashboard cookie", cookie: true, wantSecurity: true},
+ {name: "agent session", authHeader: "Session ses_test", wantSecurity: false},
+ {name: "no auth context", wantSecurity: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ if tt.authHeader != "" {
+ req.Header.Set("Authorization", tt.authHeader)
+ }
+ if tt.cookie {
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: "dashboard-session"})
+ }
+ w := httptest.NewRecorder()
+ api.HandleHealth(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("HandleHealth() status = %d, want %d", w.Code, http.StatusOK)
+ }
+ var health healthEnvelope
+ if err := json.NewDecoder(w.Body).Decode(&health); err != nil {
+ t.Fatalf("Decode() error = %v", err)
+ }
+ if got := health.Security != nil; got != tt.wantSecurity {
+ t.Fatalf("health.Security present = %v, want %v", got, tt.wantSecurity)
+ }
+ })
+ }
+}
+
func newConfigAPITestAPI(t *testing.T, fc config.FileConfig) *ConfigAPI {
t.Helper()
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index d4cc3212..020931a6 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -29,6 +29,8 @@ var (
const (
defaultCSP = "default-src 'self'; base-uri 'self'; frame-ancestors 'none'; object-src 'none'; form-action 'self'; img-src 'self' data: blob:; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:"
strictTransportSecurity = "max-age=31536000"
+ backgroundHealthPath = "/health/background"
+ backgroundHealthHeader = "PinchTab-Background-Marker"
)
func LoggingMiddleware(next http.Handler) http.Handler {
@@ -83,6 +85,10 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess
next.ServeHTTP(w, r)
return
}
+ if backgroundHealthProbeAllowed(cfg, r) {
+ next.ServeHTTP(w, r)
+ return
+ }
token := strings.TrimSpace(cfg.Token)
if token == "" {
httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)
@@ -168,6 +174,18 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess
})
}
+func backgroundHealthProbeAllowed(cfg *config.RuntimeConfig, r *http.Request) bool {
+ if cfg == nil || r.Method != http.MethodGet || r.URL.Path != backgroundHealthPath {
+ return false
+ }
+ marker := strings.TrimSpace(cfg.BackgroundMarker)
+ got := strings.TrimSpace(r.Header.Get(backgroundHealthHeader))
+ if marker == "" || got == "" {
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(got), []byte(marker)) == 1
+}
+
// StripInternalHeadersMiddleware removes any X-PinchTab-* headers that arrived
// from the public network. These headers are reserved for trusted internal
// propagation (orchestrator → instance) after auth, and accepting them from
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index 69ee158d..0c535f05 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -133,6 +133,50 @@ func TestAuthMiddleware_ValidToken(t *testing.T) {
}
}
+func TestAuthMiddleware_AllowsBackgroundHealthProbeMarker(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123", BackgroundMarker: "marker-123"}
+
+ called := false
+ handler := StripInternalHeadersMiddleware(AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ })))
+
+ req := httptest.NewRequest(http.MethodGet, backgroundHealthPath, nil)
+ req.Header.Set(backgroundHealthHeader, "marker-123")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ if !called {
+ t.Fatal("handler should have been called with the background marker")
+ }
+}
+
+func TestAuthMiddleware_RejectsWrongBackgroundHealthProbeMarker(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123", BackgroundMarker: "marker-123"}
+
+ called := false
+ handler := StripInternalHeadersMiddleware(AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ })))
+
+ req := httptest.NewRequest(http.MethodGet, backgroundHealthPath, nil)
+ req.Header.Set(backgroundHealthHeader, "other")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401", w.Code)
+ }
+ if called {
+ t.Fatal("handler should not have been called with the wrong background marker")
+ }
+}
+
func TestAuthMiddleware_InvalidToken(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret123"}
diff --git a/internal/server/server.go b/internal/server/server.go
index f78c895b..bffac32f 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -288,6 +288,14 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
}
mux.HandleFunc("GET /health", configAPI.HandleHealth)
+ mux.HandleFunc("GET /health/background", func(w http.ResponseWriter, r *http.Request) {
+ httpx.JSON(w, http.StatusOK, map[string]string{
+ "status": "ok",
+ "mode": "dashboard",
+ "version": version,
+ "marker": cfg.BackgroundMarker,
+ })
+ })
handler := handlers.StripInternalHeadersMiddleware(
handlers.RequestIDMiddleware(
diff --git a/internal/strategy/autorestart/handlers.go b/internal/strategy/autorestart/handlers.go
index 192a75f2..32bc5121 100644
--- a/internal/strategy/autorestart/handlers.go
+++ b/internal/strategy/autorestart/handlers.go
@@ -3,12 +3,19 @@ package autorestart
import (
"fmt"
"net/http"
+ "time"
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/strategy"
)
+// instanceReadyWait is the longest a proxied request will block waiting for
+// the managed instance to come up. Covers the first request after server
+// start (when launchInitial is still spinning up Chrome) without hanging
+// indefinitely on a genuinely broken instance.
+const instanceReadyWait = 10 * time.Second
+
// RegisterRoutes adds shorthand endpoints that proxy to the managed instance.
func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
s.orch.RegisterHandlers(mux)
@@ -29,7 +36,8 @@ func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
s.orch.ProxyToTarget(w, r, target+r.URL.Path)
}
-// ensureRunning returns the URL of the managed instance if running.
+// ensureRunning returns the URL of the managed instance, waiting briefly for
+// the initial launch / a restart to finish before giving up.
func (s *Strategy) ensureRunning() (string, error) {
if s.orch == nil {
return "", fmt.Errorf("no orchestrator configured")
@@ -37,7 +45,14 @@ func (s *Strategy) ensureRunning() (string, error) {
if target := s.orch.FirstRunningURL(); target != "" {
return target, nil
}
- return "", fmt.Errorf("instance not ready (may be restarting)")
+ deadline := time.Now().Add(instanceReadyWait)
+ for time.Now().Before(deadline) {
+ time.Sleep(200 * time.Millisecond)
+ if target := s.orch.FirstRunningURL(); target != "" {
+ return target, nil
+ }
+ }
+ return "", fmt.Errorf("instance not ready after %s (may be restarting)", instanceReadyWait)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
diff --git a/tests/e2e/docker-compose-multi.yml b/tests/e2e/docker-compose-multi.yml
index d91db0c4..20667ff7 100644
--- a/tests/e2e/docker-compose-multi.yml
+++ b/tests/e2e/docker-compose-multi.yml
@@ -25,7 +25,7 @@ services:
- ./config/pinchtab.json:/fixture-config/pinchtab.json:ro
- ./fixtures/test-extension:/extensions/test-extension
- ./fixtures/test-extension-api:/extensions/test-extension-api
- command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab server"]
ports:
- "127.0.0.1:9999:9999"
healthcheck: *pinchtab-healthcheck
@@ -36,7 +36,7 @@ services:
PINCHTAB_CONFIG: /data/e2e-config/pinchtab-secure.json
volumes:
- ./config/pinchtab-secure.json:/fixture-config/pinchtab-secure.json:ro
- command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-secure.json /data/e2e-config/pinchtab-secure.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-secure.json /data/e2e-config/pinchtab-secure.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab server"]
ports:
- "127.0.0.1:9998:9999"
healthcheck: *pinchtab-healthcheck
@@ -48,7 +48,7 @@ services:
volumes:
- ./config/pinchtab-autoclose.json:/fixture-config/pinchtab-autoclose.json:ro
- ./fixtures/test-extension:/extensions/test-extension
- command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-autoclose.json /data/e2e-config/pinchtab-autoclose.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-autoclose.json /data/e2e-config/pinchtab-autoclose.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab server"]
healthcheck: *pinchtab-healthcheck
pinchtab-medium:
@@ -58,7 +58,7 @@ services:
volumes:
- ./config/pinchtab-medium-permissive.json:/fixture-config/pinchtab-medium-permissive.json:ro
- ./fixtures/test-extension:/extensions/test-extension
- command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-medium-permissive.json /data/e2e-config/pinchtab-medium-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-medium-permissive.json /data/e2e-config/pinchtab-medium-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab server"]
ports:
- "127.0.0.1:9994:9999"
healthcheck: *pinchtab-healthcheck
@@ -70,7 +70,7 @@ services:
volumes:
- ./config/pinchtab-full-permissive.json:/fixture-config/pinchtab-full-permissive.json:ro
- ./fixtures/test-extension:/extensions/test-extension
- command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-full-permissive.json /data/e2e-config/pinchtab-full-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-full-permissive.json /data/e2e-config/pinchtab-full-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab server"]
ports:
- "127.0.0.1:9995:9999"
healthcheck: *pinchtab-healthcheck
diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml
index f92251cf..894a4bee 100644
--- a/tests/e2e/docker-compose.yml
+++ b/tests/e2e/docker-compose.yml
@@ -9,7 +9,7 @@ services:
- ./config/pinchtab.json:/fixture-config/pinchtab.json:ro
- ./fixtures/test-extension:/extensions/test-extension:ro
- ./fixtures/test-extension-api:/extensions/test-extension-api:ro
- command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab server"]
ports:
- "127.0.0.1:9999:9999"
shm_size: '2gb'
diff --git a/tests/e2e/scenarios/cli/files-extended.sh b/tests/e2e/scenarios/cli/files-extended.sh
index 80a39052..16e2d486 100644
--- a/tests/e2e/scenarios/cli/files-extended.sh
+++ b/tests/e2e/scenarios/cli/files-extended.sh
@@ -4,11 +4,33 @@
GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${GROUP_DIR}/../../helpers/cli.sh"
+open_capture_tab() {
+ CAPTURE_TAB_ID=""
+ pt_ok nav --new-tab "${FIXTURES_URL}/index.html"
+ CAPTURE_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')
+ if [ -n "$CAPTURE_TAB_ID" ]; then
+ pt_ok tab "$CAPTURE_TAB_ID"
+ pt_ok wait "body" --tab "$CAPTURE_TAB_ID" --timeout 5000
+ else
+ fail_assert "capture tab id available"
+ fi
+}
+
+close_capture_tab() {
+ if [ -n "${CAPTURE_TAB_ID:-}" ]; then
+ pt tab close "$CAPTURE_TAB_ID" > /dev/null 2>&1 || true
+ CAPTURE_TAB_ID=""
+ fi
+}
+
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab screenshot -o custom.jpg"
-pt_ok nav "${FIXTURES_URL}/index.html"
-pt_ok screenshot -o /tmp/e2e-custom-screenshot.jpg
+rm -f /tmp/e2e-custom-screenshot.jpg
+open_capture_tab
+if [ -n "${CAPTURE_TAB_ID:-}" ]; then
+ pt_ok screenshot --tab "$CAPTURE_TAB_ID" -o /tmp/e2e-custom-screenshot.jpg
+fi
if [ -f /tmp/e2e-custom-screenshot.jpg ]; then
echo -e " ${GREEN}✓${NC} file created"
@@ -18,15 +40,21 @@ else
echo -e " ${RED}✗${NC} file not created"
((ASSERTIONS_FAILED++)) || true
fi
+close_capture_tab
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab screenshot -q 10"
-pt_ok nav "${FIXTURES_URL}/index.html"
-pt_ok screenshot -q 10 -o /tmp/e2e-lowq.jpg
rm -f /tmp/e2e-lowq.jpg
+open_capture_tab
+if [ -n "${CAPTURE_TAB_ID:-}" ]; then
+ pt_ok screenshot --tab "$CAPTURE_TAB_ID" -q 10 -o /tmp/e2e-lowq.jpg
+fi
+assert_file_exists /tmp/e2e-lowq.jpg "low quality screenshot file created"
+rm -f /tmp/e2e-lowq.jpg
+close_capture_tab
end_test
diff --git a/tests/exploration/agent-cli-test.md b/tests/exploration/agent-cli-test.md
new file mode 100644
index 00000000..c4169b69
--- /dev/null
+++ b/tests/exploration/agent-cli-test.md
@@ -0,0 +1,147 @@
+# Agent CLI Test Blueprint — Setup/Server/Config
+
+Reusable test plan for validating the agent-facing UX of the setup, server,
+and configuration commands. Run by spawning a fresh general-purpose agent
+with only the skill (`./skills/pinchtab/SKILL.md`) and the built binary
+(`./pinchtab`) — no other context.
+
+The agent should execute each scenario, capture output, and report:
+- What worked.
+- What failed (exact command + error).
+- What was confusing or required guesswork beyond the skill.
+- Suggestions to make commands more agent-friendly.
+
+## Preconditions
+
+- `./pinchtab` exists and is executable.
+- `./skills/pinchtab/SKILL.md` is readable.
+- No pinchtab server currently running on the configured port.
+
+## Scenarios (run in order)
+
+### Phase 1 — Read-only inspection (no side effects)
+
+1. `./pinchtab` (bare) — expect a hint screen showing `server stopped`,
+ `allowedDomains`, `idpi`, plus "Next steps" / "Configure" hints.
+2. `./pinchtab --help` — confirm command list is discoverable.
+3. `./pinchtab config` — expect a Config overview + "Change config:" hints.
+4. `./pinchtab security` — expect Security checks + recommended-defaults
+ summary + "Change security:" hints.
+5. `./pinchtab daemon` — expect Daemon overview + "Manage daemon:" hints.
+6. `./pinchtab daemon --json` — expect parseable JSON with `installed`,
+ `running` keys.
+7. `./pinchtab config get server.port` — expect plain value on stdout.
+8. `./pinchtab config show` — expect structured config output.
+
+### Phase 2 — Background server lifecycle
+
+9. `./pinchtab server --background` — expect JSON on stdout with
+ `pid`, `url`, `token`, `logFile`, `pidFile`. Capture all four.
+10. `./pinchtab` (bare again) — expect `protected listener`; bare status
+ must not send the API token to identify the listener.
+11. `./pinchtab health` — expect first line `ok`, then "Next steps" hints.
+12. `PINCHTAB_SESSION= ./pinchtab health --json` — expect JSON; verify it
+ contains a `security` block with `level`, `allowedDomains`, `idpiEnabled`
+ when using the full configured API token rather than an agent session.
+
+### Phase 3 — Sessions + browse end-to-end
+
+13. `./pinchtab session create --agent-id testbot` — capture the session
+ token from stdout (must be a single line, just the token). Stderr
+ must be empty (no hints).
+14. `export PINCHTAB_SESSION=<token>` then
+ `./pinchtab nav https://example.com --snap` — expect snapshot.
+15. `./pinchtab text` — expect page text from example.com.
+
+### Phase 4 — Stop and verify
+
+16. `./pinchtab server stop` — expect "Stopped background server (pid …)".
+17. `./pinchtab` — expect `server stopped` again, matching the Phase 1 baseline.
+
+### Phase 5 — Config introspection & safe mutations
+
+Server can be stopped or running; if you need it for these checks, restart
+with `./pinchtab server --background`.
+
+18. `./pinchtab config path` — expect a single line with the config file
+ path.
+19. `./pinchtab config validate` — expect a "valid" message and exit 0.
+20. `./pinchtab config get nonexistent.path` — expect a clear error and
+ non-zero exit.
+21. `printf 'n\n' | ./pinchtab config set server.port abc` — expect a
+ validation warning on stderr, the message `aborted: value not saved`,
+ and exit code 1. Verify port is unchanged afterwards.
+22. Round-trip a safe value:
+ - Read original: `./pinchtab config get instanceDefaults.maxTabs` (record value).
+ - Set new: `./pinchtab config set instanceDefaults.maxTabs 25`.
+ - Verify: `./pinchtab config get instanceDefaults.maxTabs`.
+ - Restore: `./pinchtab config set instanceDefaults.maxTabs <original>`.
+ - Verify again.
+23. `./pinchtab config schema` — expect a URL.
+24. `./pinchtab config schema --print` — expect JSON Schema output (truncate to first 5 lines).
+
+### Phase 6 — Session lifecycle
+
+Server must be running.
+
+25. `./pinchtab session create --agent-id agentA` — capture token A.
+26. `./pinchtab session create --agent-id agentB --label "second"` — capture token B.
+27. `./pinchtab session list` — expect both sessions visible.
+28. `PINCHTAB_SESSION=<tokenA> ./pinchtab session info` — expect agent ID `agentA`.
+29. Revoke session B: extract its session ID from `session list` and
+ run `./pinchtab session revoke <id>`. Verify with `session list` it's
+ gone (or marked revoked).
+
+### Phase 7 — Error cases & edge cases
+
+30. With server stopped: `./pinchtab health` — should fail clearly, not hang.
+31. With server stopped: `./pinchtab nav https://example.com` — should
+ auto-start the server, wait for the browser instance to come up, and
+ return success with a tab id on stdout. Exit code 0.
+32. With no PID file: `./pinchtab server stop` — expect a clear
+ "no PID file" error, non-zero exit.
+33. Start once: `./pinchtab server --background`. Then immediately
+ try `./pinchtab server --background` again — expect a "server already
+ running (pid X); stop with: pinchtab server stop" error.
+34. Stop the server, then run `./pinchtab daemon --json` — verify
+ JSON shape and that `running` is false.
+
+### Phase 8 — YOLO background flow
+
+35. Stop any running server first.
+36. `./pinchtab server --background -y` — expect JSON same shape as
+ scenario 9; the "YOLO" message goes to stderr.
+37. `./pinchtab` (bare) — expect `protected listener`; bare status must not
+ send the API token to discover guards-down state.
+38. `PINCHTAB_SESSION= ./pinchtab health --json | jq '.security.guardsDown'`
+ (or grep) — expect `true` when using the full configured API token rather
+ than an agent session.
+39. `./pinchtab server stop` — clean up.
+
+## Things to deliberately NOT do
+
+- Do not run `security up`, `security down`, `config set`, `config patch`,
+ `config init`, `daemon install`, `daemon uninstall`, or anything else
+ that mutates the user's persistent config or system.
+- Do not delete `~/.pinchtab/` or any of its contents.
+- If a step fails, do NOT try to "fix" the user's environment — log the
+ failure and continue to the next scenario.
+
+## Report format
+
+For each scenario, report:
+
+```
+### Scenario N — <name>
+Command: <exact command>
+Exit code: <int>
+Stdout (verbatim, trimmed):
+ <output>
+Stderr (verbatim, trimmed):
+ <output>
+Verdict: pass | fail | confusing
+Notes: <one or two sentences about what was unclear or unexpected>
+```
+
+End with a "Top issues" section listing the three biggest agent-friendliness
+gaps you hit, in priority order.