Skip to content

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

refactor: CLI separation, package restructuring, session auth (#322)

luigiagent29f745d86dd6
diff --git a/SECURITY.md b/SECURITY.md
index 38036552..105f69ff 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -1,14 +1,34 @@
# Security Policy
+For the user-facing security guide, see
+[docs/guides/security.md](./docs/guides/security.md).
+
## Supported Versions
We currently support the following versions of Pinchtab with security updates:
| Version | Supported |
| ------- | ------------------ |
-| v0.7.x | :white_check_mark: |
-| v0.6.x | :white_check_mark: |
-| < v0.6 | :x: |
+| v0.8.4 | :white_check_mark: |
+| < v0.8.3 | :x: |
+
+## Current Posture
+
+The current codebase has the following security controls in place:
+
+- query-string token auth has been removed
+- browser dashboard auth uses a server-side `HttpOnly` session cookie instead
+ of raw-token URL or browser-storage flows
+- cookie-authenticated browser requests are same-origin enforced
+- sensitive dashboard actions use elevation rather than normal browser session
+ auth alone
+- login attempts are rate-limited and important auth/admin actions are audited
+- current-tab domain policy is enforced after load, not only at initial
+ navigation time
+- popup/opener abuse is hardened in the browser runtime
+- safer default Chrome flags are used than in the earlier posture
+- scheduler callback destinations are validated before use
+- attach is disabled by default
## Reporting a Vulnerability
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.go
index 175d528a..3249fa07 100644
--- a/cmd/pinchtab/cmd_bridge.go
+++ b/cmd/pinchtab/cmd_bridge.go
@@ -4,7 +4,6 @@ import (
"fmt"
"strings"
- "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
@@ -15,7 +14,7 @@ var bridgeCmd = &cobra.Command{
Use: "bridge",
Short: "Start single-instance bridge-only server",
RunE: func(cmd *cobra.Command, args []string) error {
- cfg := config.Load()
+ cfg := loadConfig()
engineMode, err := resolveBridgeEngine(bridgeEngine, cfg.Engine)
if err != nil {
return err
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 298e3a6e..25d79f4e 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -2,14 +2,9 @@ package main
import (
"fmt"
- "net/http"
- "os"
"strings"
- "time"
- browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
- "github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/urlutil"
+ "github.com/pinchtab/pinchtab/internal/urls"
"github.com/spf13/cobra"
)
@@ -18,807 +13,5 @@ func normalizeRequiredURL(raw string) string {
if trimmed == "" {
cobra.CheckErr(fmt.Errorf("empty URL"))
}
- return urlutil.Normalize(trimmed)
-}
-
-var quickCmd = &cobra.Command{
- Use: "quick <url>",
- Short: "Navigate + analyze page",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- args[0] = normalizeRequiredURL(args[0])
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Quick(client, base, token, args)
- })
- },
-}
-
-var navCmd = &cobra.Command{
- Use: "nav <url>",
- Aliases: []string{"goto", "navigate", "open"},
- Short: "Navigate to URL",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- url := normalizeRequiredURL(args[0])
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Navigate(client, base, token, url, cmd)
- })
- },
-}
-
-var backCmd = &cobra.Command{
- Use: "back",
- Short: "Go back in browser history",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Back(client, base, token, cmd)
- })
- },
-}
-
-var forwardCmd = &cobra.Command{
- Use: "forward",
- Short: "Go forward in browser history",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Forward(client, base, token, cmd)
- })
- },
-}
-
-var reloadCmd = &cobra.Command{
- Use: "reload",
- Short: "Reload current page",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Reload(client, base, token, cmd)
- })
- },
-}
-
-var snapCmd = &cobra.Command{
- Use: "snap",
- Short: "Snapshot accessibility tree",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Snapshot(client, base, token, cmd)
- })
- },
-}
-
-var clickCmd = &cobra.Command{
- Use: "click <ref>",
- Short: "Click element",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- ref := ""
- if len(args) > 0 {
- ref = args[0]
- }
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "click", ref, cmd)
- })
- },
-}
-
-var dblclickCmd = &cobra.Command{
- Use: "dblclick <ref>",
- Short: "Double-click element",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- ref := ""
- if len(args) > 0 {
- ref = args[0]
- }
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "dblclick", ref, cmd)
- })
- },
-}
-
-var typeCmd = &cobra.Command{
- Use: "type <ref> <text>",
- Short: "Type into element",
- Args: cobra.MinimumNArgs(2),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "type", args, cmd)
- })
- },
-}
-
-var screenshotCmd = &cobra.Command{
- Use: "screenshot",
- Short: "Take a screenshot",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Screenshot(client, base, token, cmd)
- })
- },
-}
-
-var tabsCmd = &cobra.Command{
- Use: "tab [id]",
- Aliases: []string{"tabs"},
- Short: "List tabs, or focus a tab by ID",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- if len(args) == 0 {
- browseractions.TabList(client, base, token)
- } else {
- browseractions.TabFocus(client, base, token, args[0])
- }
- })
- },
-}
-
-var instancesCmd = &cobra.Command{
- Use: "instances",
- Short: "List or manage instances",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Instances(client, base, token)
- })
- },
-}
-
-var healthCmd = &cobra.Command{
- Use: "health",
- Short: "Check server health",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Health(client, base, token)
- })
- },
-}
-
-var pressCmd = &cobra.Command{
- Use: "press <key>",
- Short: "Press key (Enter, Tab, Escape...)",
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "press", args, cmd)
- })
- },
-}
-
-var fillCmd = &cobra.Command{
- Use: "fill <ref|selector> <text>",
- Short: "Fill input directly",
- Args: cobra.MinimumNArgs(2),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "fill", args, cmd)
- })
- },
-}
-
-var hoverCmd = &cobra.Command{
- Use: "hover <ref>",
- Short: "Hover element",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- ref := ""
- if len(args) > 0 {
- ref = args[0]
- }
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "hover", ref, cmd)
- })
- },
-}
-
-var focusCmd = &cobra.Command{
- Use: "focus <ref>",
- Short: "Focus element",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- ref := ""
- if len(args) > 0 {
- ref = args[0]
- }
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "focus", ref, cmd)
- })
- },
-}
-
-var scrollCmd = &cobra.Command{
- Use: "scroll <ref|pixels>",
- Short: "Scroll to element or by pixels",
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "scroll", args, cmd)
- })
- },
-}
-
-var evalCmd = &cobra.Command{
- Use: "eval <expression>",
- Short: "Evaluate JavaScript",
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Evaluate(client, base, token, args, cmd)
- })
- },
-}
-
-var pdfCmd = &cobra.Command{
- Use: "pdf",
- Short: "Export the current page as PDF",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.PDF(client, base, token, cmd)
- })
- },
-}
-
-var textCmd = &cobra.Command{
- Use: "text",
- Short: "Extract page text",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Text(client, base, token, cmd)
- })
- },
-}
-
-var downloadCmd = &cobra.Command{
- Use: "download <url>",
- Short: "Download a file via browser session",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- args[0] = normalizeRequiredURL(args[0])
- output, _ := cmd.Flags().GetString("output")
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Download(client, base, token, args, output)
- })
- },
-}
-
-var uploadCmd = &cobra.Command{
- Use: "upload <file-path>",
- Short: "Upload a file to a file input element",
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- selector, _ := cmd.Flags().GetString("selector")
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Upload(client, base, token, args, selector)
- })
- },
-}
-
-var profilesCmd = &cobra.Command{
- Use: "profiles",
- Short: "List browser profiles",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Profiles(client, base, token)
- })
- },
-}
-
-var activityCmd = &cobra.Command{
- Use: "activity",
- Short: "List recorded activity events",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Activity(client, base, token, cmd)
- })
- },
-}
-
-var instanceCmd = &cobra.Command{
- Use: "instance",
- Short: "Manage browser instances",
-}
-
-var findCmd = &cobra.Command{
- Use: "find <query>",
- Short: "Find elements by natural language query",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Find(client, base, token, args[0], cmd)
- })
- },
-}
-
-var waitCmd = &cobra.Command{
- Use: "wait [selector|ms]",
- Short: "Wait for element, text, URL, network idle, JS expression, or fixed duration",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Wait(client, base, token, args, cmd)
- })
- },
-}
-
-var dialogCmd = &cobra.Command{
- Use: "dialog",
- Short: "Handle JavaScript dialogs (alert, confirm, prompt)",
-}
-
-var dialogAcceptCmd = &cobra.Command{
- Use: "accept [text]",
- Short: "Accept (OK) the current dialog",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- text := ""
- if len(args) > 0 {
- text = args[0]
- }
- tabID, _ := cmd.Flags().GetString("tab")
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Dialog(client, base, token, "accept", text, tabID)
- })
- },
-}
-
-var dialogDismissCmd = &cobra.Command{
- Use: "dismiss",
- Short: "Dismiss (Cancel) the current dialog",
- Run: func(cmd *cobra.Command, args []string) {
- tabID, _ := cmd.Flags().GetString("tab")
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Dialog(client, base, token, "dismiss", "", tabID)
- })
- },
-}
-
-var selectCmd = &cobra.Command{
- Use: "select <ref> <value>",
- Short: "Select option in dropdown",
- Args: cobra.MinimumNArgs(2),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "select", args, cmd)
- })
- },
-}
-
-var checkCmd = &cobra.Command{
- Use: "check <selector>",
- Short: "Check a checkbox or radio",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "check", args[0], cmd)
- })
- },
-}
-
-var networkCmd = &cobra.Command{
- Use: "network [requestId]",
- Short: "List or inspect network requests",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Network(client, base, token, cmd, args)
- })
- },
-}
-
-var uncheckCmd = &cobra.Command{
- Use: "uncheck <selector>",
- Short: "Uncheck a checkbox or radio",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "uncheck", args[0], cmd)
- })
- },
-}
-
-var keyboardCmd = &cobra.Command{
- Use: "keyboard",
- Short: "Keyboard commands (type, inserttext)",
-}
-
-var keyboardTypeCmd = &cobra.Command{
- Use: "type <text>",
- Short: "Type text at current focus via keystroke events",
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "keyboard-type", args, cmd)
- })
- },
-}
-
-var keyboardInsertTextCmd = &cobra.Command{
- Use: "inserttext <text>",
- Short: "Insert text at current focus (paste-like, no key events)",
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "keyboard-inserttext", args, cmd)
- })
- },
-}
-
-var keydownCmd = &cobra.Command{
- Use: "keydown <key>",
- Short: "Hold a key down",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "keydown", args, cmd)
- })
- },
-}
-
-var keyupCmd = &cobra.Command{
- Use: "keyup <key>",
- Short: "Release a key",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActionSimple(client, base, token, "keyup", args, cmd)
- })
- },
-}
-
-var scrollintoviewCmd = &cobra.Command{
- Use: "scrollintoview <selector>",
- Short: "Scroll element into view and return bounding box",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- ref := ""
- if len(args) > 0 {
- ref = args[0]
- }
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.Action(client, base, token, "scrollintoview", ref, cmd)
- })
- },
-}
-
-func init() {
- quickCmd.GroupID = "browser"
- navCmd.GroupID = "browser"
- backCmd.GroupID = "browser"
- forwardCmd.GroupID = "browser"
- reloadCmd.GroupID = "browser"
- snapCmd.GroupID = "browser"
- clickCmd.GroupID = "browser"
- typeCmd.GroupID = "browser"
- screenshotCmd.GroupID = "browser"
- tabsCmd.GroupID = "browser"
- instancesCmd.GroupID = "management"
- healthCmd.GroupID = "management"
- pressCmd.GroupID = "browser"
- fillCmd.GroupID = "browser"
- hoverCmd.GroupID = "browser"
- focusCmd.GroupID = "browser"
- scrollCmd.GroupID = "browser"
- evalCmd.GroupID = "browser"
- pdfCmd.GroupID = "browser"
- textCmd.GroupID = "browser"
- profilesCmd.GroupID = "management"
- activityCmd.GroupID = "management"
- downloadCmd.GroupID = "browser"
- uploadCmd.GroupID = "browser"
- findCmd.GroupID = "browser"
- selectCmd.GroupID = "browser"
- checkCmd.GroupID = "browser"
- uncheckCmd.GroupID = "browser"
- networkCmd.GroupID = "browser"
- dialogCmd.GroupID = "browser"
- waitCmd.GroupID = "browser"
- keyboardCmd.GroupID = "browser"
- keydownCmd.GroupID = "browser"
- keyupCmd.GroupID = "browser"
- scrollintoviewCmd.GroupID = "browser"
-
- tabsCmd.AddCommand(&cobra.Command{
- Use: "new [url]",
- Short: "Open a new tab",
- Args: cobra.MaximumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- body := map[string]any{"action": "new"}
- if len(args) > 0 {
- body["url"] = normalizeRequiredURL(args[0])
- }
- browseractions.TabNew(client, base, token, body)
- })
- },
- })
- tabsCmd.AddCommand(&cobra.Command{
- Use: "close <id>",
- Short: "Close a tab by ID",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.TabClose(client, base, token, args[0])
- })
- },
- })
-
- uploadCmd.Flags().StringP("selector", "s", "", "CSS selector for file input")
- downloadCmd.Flags().StringP("output", "o", "", "Save downloaded file to path")
-
- clickCmd.Flags().String("css", "", "CSS selector instead of ref")
- clickCmd.Flags().Float64("x", 0, "X coordinate for click")
- clickCmd.Flags().Float64("y", 0, "Y coordinate for click")
- clickCmd.Flags().Bool("wait-nav", false, "Wait for navigation after click")
- dblclickCmd.Flags().String("css", "", "CSS selector instead of ref")
- dblclickCmd.Flags().Float64("x", 0, "X coordinate for dblclick")
- dblclickCmd.Flags().Float64("y", 0, "Y coordinate for dblclick")
- hoverCmd.Flags().String("css", "", "CSS selector instead of ref")
- hoverCmd.Flags().Float64("x", 0, "X coordinate for hover")
- hoverCmd.Flags().Float64("y", 0, "Y coordinate for hover")
- focusCmd.Flags().String("css", "", "CSS selector instead of ref")
-
- snapCmd.Flags().BoolP("interactive", "i", false, "Filter interactive elements only")
- snapCmd.Flags().BoolP("compact", "c", false, "Compact output format")
- snapCmd.Flags().Bool("text", false, "Text output format")
- snapCmd.Flags().BoolP("diff", "d", false, "Show diff from previous snapshot")
- snapCmd.Flags().StringP("selector", "s", "", "CSS selector to scope snapshot")
- snapCmd.Flags().String("max-tokens", "", "Maximum token budget")
- snapCmd.Flags().String("depth", "", "Tree depth limit")
- snapCmd.Flags().String("tab", "", "Tab ID")
-
- screenshotCmd.Flags().StringP("output", "o", "", "Save screenshot to file path")
- screenshotCmd.Flags().StringP("quality", "q", "", "JPEG quality (0-100)")
- screenshotCmd.Flags().String("tab", "", "Tab ID")
-
- pdfCmd.Flags().StringP("output", "o", "", "Save PDF to file path")
- pdfCmd.Flags().String("tab", "", "Tab ID")
- pdfCmd.Flags().Bool("landscape", false, "Landscape orientation")
- pdfCmd.Flags().String("scale", "", "Page scale (e.g. 0.5)")
- pdfCmd.Flags().String("paper-width", "", "Paper width (inches)")
- pdfCmd.Flags().String("paper-height", "", "Paper height (inches)")
- pdfCmd.Flags().String("margin-top", "", "Top margin")
- pdfCmd.Flags().String("margin-bottom", "", "Bottom margin")
- pdfCmd.Flags().String("margin-left", "", "Left margin")
- pdfCmd.Flags().String("margin-right", "", "Right margin")
- pdfCmd.Flags().String("page-ranges", "", "Page ranges (e.g. 1-3)")
- pdfCmd.Flags().Bool("prefer-css-page-size", false, "Use CSS page size")
- pdfCmd.Flags().Bool("display-header-footer", false, "Show header/footer")
- pdfCmd.Flags().String("header-template", "", "Header HTML template")
- pdfCmd.Flags().String("footer-template", "", "Footer HTML template")
- pdfCmd.Flags().Bool("generate-tagged-pdf", false, "Generate tagged PDF")
- pdfCmd.Flags().Bool("generate-document-outline", false, "Generate document outline")
- pdfCmd.Flags().Bool("file-output", false, "Use server-side file output")
- pdfCmd.Flags().String("path", "", "Server-side output path")
-
- findCmd.Flags().String("tab", "", "Tab ID")
- findCmd.Flags().String("threshold", "", "Minimum similarity score (0-1)")
- findCmd.Flags().Bool("explain", false, "Show score breakdown")
- findCmd.Flags().Bool("ref-only", false, "Output just the element ref")
-
- textCmd.Flags().Bool("raw", false, "Raw extraction mode")
- textCmd.Flags().String("tab", "", "Tab ID")
-
- navCmd.Flags().Bool("new-tab", false, "Open in new tab")
- navCmd.Flags().Bool("block-images", false, "Block image loading")
- navCmd.Flags().Bool("block-ads", false, "Block ads")
- navCmd.Flags().String("tab", "", "Tab ID")
- backCmd.Flags().String("tab", "", "Tab ID")
- forwardCmd.Flags().String("tab", "", "Tab ID")
- reloadCmd.Flags().String("tab", "", "Tab ID")
-
- clickCmd.Flags().String("tab", "", "Tab ID")
- dblclickCmd.Flags().String("tab", "", "Tab ID")
- hoverCmd.Flags().String("tab", "", "Tab ID")
- focusCmd.Flags().String("tab", "", "Tab ID")
- typeCmd.Flags().String("tab", "", "Tab ID")
- pressCmd.Flags().String("tab", "", "Tab ID")
- fillCmd.Flags().String("tab", "", "Tab ID")
- scrollCmd.Flags().String("tab", "", "Tab ID")
- selectCmd.Flags().String("tab", "", "Tab ID")
- evalCmd.Flags().String("tab", "", "Tab ID")
- checkCmd.Flags().String("tab", "", "Tab ID")
- uncheckCmd.Flags().String("tab", "", "Tab ID")
- keyboardTypeCmd.Flags().String("tab", "", "Tab ID")
- keyboardInsertTextCmd.Flags().String("tab", "", "Tab ID")
- keydownCmd.Flags().String("tab", "", "Tab ID")
- keyupCmd.Flags().String("tab", "", "Tab ID")
-
- scrollintoviewCmd.Flags().String("css", "", "CSS selector instead of ref")
- scrollintoviewCmd.Flags().String("tab", "", "Tab ID")
-
- rootCmd.AddCommand(quickCmd)
- rootCmd.AddCommand(navCmd)
- rootCmd.AddCommand(backCmd)
- rootCmd.AddCommand(forwardCmd)
- rootCmd.AddCommand(reloadCmd)
- rootCmd.AddCommand(snapCmd)
- rootCmd.AddCommand(clickCmd)
- rootCmd.AddCommand(dblclickCmd)
- rootCmd.AddCommand(typeCmd)
- rootCmd.AddCommand(screenshotCmd)
- rootCmd.AddCommand(tabsCmd)
- rootCmd.AddCommand(instancesCmd)
- rootCmd.AddCommand(healthCmd)
- rootCmd.AddCommand(pressCmd)
- rootCmd.AddCommand(fillCmd)
- rootCmd.AddCommand(hoverCmd)
- rootCmd.AddCommand(focusCmd)
- rootCmd.AddCommand(scrollCmd)
- rootCmd.AddCommand(evalCmd)
- rootCmd.AddCommand(pdfCmd)
- rootCmd.AddCommand(textCmd)
- rootCmd.AddCommand(profilesCmd)
- rootCmd.AddCommand(activityCmd)
- rootCmd.AddCommand(downloadCmd)
- rootCmd.AddCommand(uploadCmd)
- rootCmd.AddCommand(findCmd)
- rootCmd.AddCommand(selectCmd)
- rootCmd.AddCommand(checkCmd)
- rootCmd.AddCommand(uncheckCmd)
- rootCmd.AddCommand(networkCmd)
- rootCmd.AddCommand(waitCmd)
- rootCmd.AddCommand(keyboardCmd)
- rootCmd.AddCommand(keydownCmd)
- rootCmd.AddCommand(keyupCmd)
- rootCmd.AddCommand(scrollintoviewCmd)
-
- keyboardCmd.AddCommand(keyboardTypeCmd)
- keyboardCmd.AddCommand(keyboardInsertTextCmd)
-
- networkCmd.Flags().String("tab", "", "Tab ID")
- networkCmd.Flags().String("filter", "", "URL pattern filter")
- networkCmd.Flags().String("method", "", "HTTP method filter (GET, POST, etc)")
- networkCmd.Flags().String("status", "", "Status code range (e.g. 4xx, 5xx, 200)")
- networkCmd.Flags().String("type", "", "Resource type filter (xhr, fetch, document, etc)")
- networkCmd.Flags().String("limit", "", "Maximum entries to return")
- networkCmd.Flags().Bool("body", false, "Include response body (with requestId)")
- networkCmd.Flags().Bool("clear", false, "Clear captured network data")
- networkCmd.Flags().String("buffer-size", "", "Per-tab network buffer size (default 100)")
- networkCmd.Flags().Bool("stream", false, "Stream network entries in real-time (like tail -f)")
-
- waitCmd.Flags().String("text", "", "Wait for text on page")
- waitCmd.Flags().String("url", "", "Wait for URL glob match")
- waitCmd.Flags().String("load", "", "Wait for load state (networkidle)")
- waitCmd.Flags().String("fn", "", "Wait for JS expression to be truthy")
- waitCmd.Flags().String("state", "", "Element state: visible (default) or hidden")
- waitCmd.Flags().Int("timeout", 0, "Timeout in milliseconds (default 10000, max 30000)")
- waitCmd.Flags().String("tab", "", "Tab ID")
-
- dialogAcceptCmd.Flags().String("tab", "", "Tab ID")
- dialogDismissCmd.Flags().String("tab", "", "Tab ID")
- dialogCmd.AddCommand(dialogAcceptCmd)
- dialogCmd.AddCommand(dialogDismissCmd)
- rootCmd.AddCommand(dialogCmd)
-
- instanceCmd.GroupID = "management"
-
- startInstanceCmd := &cobra.Command{
- Use: "start",
- Short: "Start a browser instance",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.InstanceStart(client, base, token, cmd)
- })
- },
- }
- startInstanceCmd.Flags().String("profile", "", "Profile to use")
- startInstanceCmd.Flags().String("mode", "", "Instance mode")
- startInstanceCmd.Flags().String("port", "", "Port number")
- startInstanceCmd.Flags().StringArray("extension", nil, "Load browser extension (repeatable)")
- instanceCmd.AddCommand(startInstanceCmd)
-
- instanceCmd.AddCommand(&cobra.Command{
- Use: "navigate <id> <url>",
- Short: "Navigate an instance to a URL",
- Args: cobra.ExactArgs(2),
- Run: func(cmd *cobra.Command, args []string) {
- args[1] = normalizeRequiredURL(args[1])
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.InstanceNavigate(client, base, token, args)
- })
- },
- })
- instanceCmd.AddCommand(&cobra.Command{
- Use: "stop <id>",
- Short: "Stop a browser instance",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.InstanceStop(client, base, token, args)
- })
- },
- })
- instanceCmd.AddCommand(&cobra.Command{
- Use: "logs <id>",
- Short: "Get instance logs",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.InstanceLogs(client, base, token, args)
- })
- },
- })
- rootCmd.AddCommand(instanceCmd)
-
- activityCmd.AddCommand(&cobra.Command{
- Use: "tab <id>",
- Short: "List recorded activity events for a tab",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runCLIWith(cfg, func(client *http.Client, base, token string) {
- browseractions.ActivityTab(client, base, token, args[0], cmd)
- })
- },
- })
-
- activityCmd.PersistentFlags().Int("limit", 200, "Maximum number of events to return")
- activityCmd.PersistentFlags().Int("age-sec", 0, "Only include events from the last N seconds")
-}
-
-func runCLIWith(cfg *config.RuntimeConfig, fn func(client *http.Client, base, token string)) {
- client := &http.Client{Timeout: 60 * time.Second}
-
- // Default: http://127.0.0.1:{port}
- port := cfg.Port
- if port == "" {
- port = "9867"
- }
- base := fmt.Sprintf("http://127.0.0.1:%s", port)
-
- // --server flag overrides
- if serverURL != "" {
- base = strings.TrimRight(serverURL, "/")
- }
-
- // Token from config, env var overrides
- token := cfg.Token
- if envToken := os.Getenv("PINCHTAB_TOKEN"); envToken != "" {
- token = envToken
- }
-
- fn(client, base, token)
+ return urls.Normalize(trimmed)
}
diff --git a/cmd/pinchtab/cmd_cli_browser_actions.go b/cmd/pinchtab/cmd_cli_browser_actions.go
new file mode 100644
index 00000000..6185485c
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_browser_actions.go
@@ -0,0 +1,108 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+func newOptionalRefActionCmd(use, short, action string) *cobra.Command {
+ return &cobra.Command{
+ Use: use,
+ Short: short,
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Action(rt.client, rt.base, rt.token, action, optionalArg(args), cmd)
+ })
+ },
+ }
+}
+
+func newSimpleActionCmd(use, short, action string, argsValidator cobra.PositionalArgs) *cobra.Command {
+ return &cobra.Command{
+ Use: use,
+ Short: short,
+ Args: argsValidator,
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.ActionSimple(rt.client, rt.base, rt.token, action, args, cmd)
+ })
+ },
+ }
+}
+
+func newRequiredRefActionCmd(use, short, action string) *cobra.Command {
+ return &cobra.Command{
+ Use: use,
+ Short: short,
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Action(rt.client, rt.base, rt.token, action, args[0], cmd)
+ })
+ },
+ }
+}
+
+var clickCmd = newOptionalRefActionCmd("click <ref>", "Click element", "click")
+
+var dblclickCmd = newOptionalRefActionCmd("dblclick <ref>", "Double-click element", "dblclick")
+
+var typeCmd = newSimpleActionCmd("type <ref> <text>", "Type into element", "type", cobra.MinimumNArgs(2))
+
+var pressCmd = newSimpleActionCmd("press <key>", "Press key (Enter, Tab, Escape...)", "press", cobra.MinimumNArgs(1))
+
+var fillCmd = newSimpleActionCmd("fill <ref|selector> <text>", "Fill input directly", "fill", cobra.MinimumNArgs(2))
+
+var hoverCmd = newOptionalRefActionCmd("hover <ref>", "Hover element", "hover")
+
+var focusCmd = newOptionalRefActionCmd("focus <ref>", "Focus element", "focus")
+
+var scrollCmd = newSimpleActionCmd("scroll <ref|pixels>", "Scroll to element or by pixels", "scroll", cobra.MinimumNArgs(1))
+
+var selectCmd = newSimpleActionCmd("select <ref> <value>", "Select option in dropdown", "select", cobra.MinimumNArgs(2))
+
+var checkCmd = newRequiredRefActionCmd("check <selector>", "Check a checkbox or radio", "check")
+
+var uncheckCmd = newRequiredRefActionCmd("uncheck <selector>", "Uncheck a checkbox or radio", "uncheck")
+
+var keyboardCmd = &cobra.Command{
+ Use: "keyboard",
+ Short: "Keyboard commands (type, inserttext)",
+}
+
+var keyboardTypeCmd = newSimpleActionCmd("type <text>", "Type text at current focus via keystroke events", "keyboard-type", cobra.MinimumNArgs(1))
+
+var keyboardInsertTextCmd = newSimpleActionCmd("inserttext <text>", "Insert text at current focus (paste-like, no key events)", "keyboard-inserttext", cobra.MinimumNArgs(1))
+
+var keydownCmd = newSimpleActionCmd("keydown <key>", "Hold a key down", "keydown", cobra.ExactArgs(1))
+
+var keyupCmd = newSimpleActionCmd("keyup <key>", "Release a key", "keyup", cobra.ExactArgs(1))
+
+var scrollintoviewCmd = newOptionalRefActionCmd("scrollintoview <selector>", "Scroll element into view and return bounding box", "scrollintoview")
+
+var dialogCmd = &cobra.Command{
+ Use: "dialog",
+ Short: "Handle JavaScript dialogs (alert, confirm, prompt)",
+}
+
+var dialogAcceptCmd = &cobra.Command{
+ Use: "accept [text]",
+ Short: "Accept (OK) the current dialog",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Dialog(rt.client, rt.base, rt.token, "accept", optionalArg(args), stringFlag(cmd, "tab"))
+ })
+ },
+}
+
+var dialogDismissCmd = &cobra.Command{
+ Use: "dismiss",
+ Short: "Dismiss (Cancel) the current dialog",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Dialog(rt.client, rt.base, rt.token, "dismiss", "", stringFlag(cmd, "tab"))
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_browser_inspect.go b/cmd/pinchtab/cmd_cli_browser_inspect.go
new file mode 100644
index 00000000..3ae5b771
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_browser_inspect.go
@@ -0,0 +1,114 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/pinchtab/pinchtab/internal/urls"
+ "github.com/spf13/cobra"
+)
+
+var snapCmd = &cobra.Command{
+ Use: "snap",
+ Short: "Snapshot accessibility tree",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Snapshot(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var screenshotCmd = &cobra.Command{
+ Use: "screenshot",
+ Short: "Take a screenshot",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Screenshot(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var evalCmd = &cobra.Command{
+ Use: "eval <expression>",
+ Short: "Evaluate JavaScript",
+ Args: cobra.MinimumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Evaluate(rt.client, rt.base, rt.token, args, cmd)
+ })
+ },
+}
+
+var pdfCmd = &cobra.Command{
+ Use: "pdf",
+ Short: "Export the current page as PDF",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.PDF(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var textCmd = &cobra.Command{
+ Use: "text",
+ Short: "Extract page text",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Text(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var downloadCmd = &cobra.Command{
+ Use: "download <url>",
+ Short: "Download a file via browser session",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ args[0] = urls.Normalize(args[0])
+ runCLI(func(rt cliRuntime) {
+ browseractions.Download(rt.client, rt.base, rt.token, args, stringFlag(cmd, "output"))
+ })
+ },
+}
+
+var uploadCmd = &cobra.Command{
+ Use: "upload <file-path>",
+ Short: "Upload a file to a file input element",
+ Args: cobra.MinimumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Upload(rt.client, rt.base, rt.token, args, stringFlag(cmd, "selector"))
+ })
+ },
+}
+
+var findCmd = &cobra.Command{
+ Use: "find <query>",
+ Short: "Find elements by natural language query",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Find(rt.client, rt.base, rt.token, args[0], cmd)
+ })
+ },
+}
+
+var waitCmd = &cobra.Command{
+ Use: "wait [selector|ms]",
+ Short: "Wait for element, text, URL, network idle, JS expression, or fixed duration",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Wait(rt.client, rt.base, rt.token, args, cmd)
+ })
+ },
+}
+
+var networkCmd = &cobra.Command{
+ Use: "network [requestId]",
+ Short: "List or inspect network requests",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Network(rt.client, rt.base, rt.token, cmd, args)
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_browser_nav.go b/cmd/pinchtab/cmd_cli_browser_nav.go
new file mode 100644
index 00000000..61a10953
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_browser_nav.go
@@ -0,0 +1,104 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/pinchtab/pinchtab/internal/urls"
+ "github.com/spf13/cobra"
+)
+
+var quickCmd = &cobra.Command{
+ Use: "quick <url>",
+ Short: "Navigate + analyze page",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ args[0] = urls.Normalize(args[0])
+ runCLI(func(rt cliRuntime) {
+ browseractions.Quick(rt.client, rt.base, rt.token, args)
+ })
+ },
+}
+
+var navCmd = &cobra.Command{
+ Use: "nav <url>",
+ Aliases: []string{"goto", "navigate", "open"},
+ Short: "Navigate to URL",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ url := urls.Normalize(args[0])
+ runCLI(func(rt cliRuntime) {
+ browseractions.Navigate(rt.client, rt.base, rt.token, url, cmd)
+ })
+ },
+}
+
+var backCmd = &cobra.Command{
+ Use: "back",
+ Short: "Go back in browser history",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Back(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var forwardCmd = &cobra.Command{
+ Use: "forward",
+ Short: "Go forward in browser history",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Forward(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var reloadCmd = &cobra.Command{
+ Use: "reload",
+ Short: "Reload current page",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Reload(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var tabsCmd = &cobra.Command{
+ Use: "tab [id]",
+ Aliases: []string{"tabs"},
+ Short: "List tabs, or focus a tab by ID",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ if len(args) == 0 {
+ browseractions.TabList(rt.client, rt.base, rt.token)
+ return
+ }
+ browseractions.TabFocus(rt.client, rt.base, rt.token, args[0])
+ })
+ },
+}
+
+var tabNewCmd = &cobra.Command{
+ Use: "new [url]",
+ Short: "Open a new tab",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ body := map[string]any{"action": "new"}
+ if len(args) > 0 {
+ body["url"] = urls.Normalize(args[0])
+ }
+ browseractions.TabNew(rt.client, rt.base, rt.token, body)
+ })
+ },
+}
+
+var tabCloseCmd = &cobra.Command{
+ Use: "close <id>",
+ Short: "Close a tab by ID",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.TabClose(rt.client, rt.base, rt.token, args[0])
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_management.go b/cmd/pinchtab/cmd_cli_management.go
new file mode 100644
index 00000000..83becede
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_management.go
@@ -0,0 +1,107 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/pinchtab/pinchtab/internal/urls"
+ "github.com/spf13/cobra"
+)
+
+var instancesCmd = &cobra.Command{
+ Use: "instances",
+ Short: "List or manage instances",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Instances(rt.client, rt.base, rt.token)
+ })
+ },
+}
+
+var healthCmd = &cobra.Command{
+ Use: "health",
+ Short: "Check server health",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Health(rt.client, rt.base, rt.token)
+ })
+ },
+}
+
+var profilesCmd = &cobra.Command{
+ Use: "profiles",
+ Short: "List browser profiles",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Profiles(rt.client, rt.base, rt.token)
+ })
+ },
+}
+
+var activityCmd = &cobra.Command{
+ Use: "activity",
+ Short: "List recorded activity events",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Activity(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var activityTabCmd = &cobra.Command{
+ Use: "tab <id>",
+ Short: "List recorded activity events for a tab",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.ActivityTab(rt.client, rt.base, rt.token, args[0], cmd)
+ })
+ },
+}
+
+var instanceCmd = &cobra.Command{
+ Use: "instance",
+ Short: "Manage browser instances",
+}
+
+var startInstanceCmd = &cobra.Command{
+ Use: "start",
+ Short: "Start a browser instance",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.InstanceStart(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var instanceNavigateCmd = &cobra.Command{
+ Use: "navigate <id> <url>",
+ Short: "Navigate an instance to a URL",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ args[1] = urls.Normalize(args[1])
+ runCLI(func(rt cliRuntime) {
+ browseractions.InstanceNavigate(rt.client, rt.base, rt.token, args)
+ })
+ },
+}
+
+var instanceStopCmd = &cobra.Command{
+ Use: "stop <id>",
+ Short: "Stop a browser instance",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.InstanceStop(rt.client, rt.base, rt.token, args)
+ })
+ },
+}
+
+var instanceLogsCmd = &cobra.Command{
+ Use: "logs <id>",
+ Short: "Get instance logs",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.InstanceLogs(rt.client, rt.base, rt.token, args)
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
new file mode 100644
index 00000000..27b2c387
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -0,0 +1,237 @@
+package main
+
+import "github.com/spf13/cobra"
+
+func init() {
+ registerBrowserCommands()
+ registerManagementCommands()
+}
+
+func registerBrowserCommands() {
+ setCommandGroup("browser",
+ quickCmd,
+ navCmd,
+ backCmd,
+ forwardCmd,
+ reloadCmd,
+ snapCmd,
+ clickCmd,
+ dblclickCmd,
+ typeCmd,
+ screenshotCmd,
+ tabsCmd,
+ pressCmd,
+ fillCmd,
+ hoverCmd,
+ focusCmd,
+ scrollCmd,
+ evalCmd,
+ pdfCmd,
+ textCmd,
+ downloadCmd,
+ uploadCmd,
+ findCmd,
+ selectCmd,
+ checkCmd,
+ uncheckCmd,
+ networkCmd,
+ waitCmd,
+ keyboardCmd,
+ keydownCmd,
+ keyupCmd,
+ scrollintoviewCmd,
+ dialogCmd,
+ )
+
+ tabsCmd.AddCommand(tabNewCmd, tabCloseCmd)
+ keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)
+ dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)
+
+ configureBrowserFlags()
+
+ addRootCommands(
+ quickCmd,
+ navCmd,
+ backCmd,
+ forwardCmd,
+ reloadCmd,
+ snapCmd,
+ clickCmd,
+ dblclickCmd,
+ typeCmd,
+ screenshotCmd,
+ tabsCmd,
+ pressCmd,
+ fillCmd,
+ hoverCmd,
+ focusCmd,
+ scrollCmd,
+ evalCmd,
+ pdfCmd,
+ textCmd,
+ downloadCmd,
+ uploadCmd,
+ findCmd,
+ selectCmd,
+ checkCmd,
+ uncheckCmd,
+ networkCmd,
+ waitCmd,
+ keyboardCmd,
+ keydownCmd,
+ keyupCmd,
+ scrollintoviewCmd,
+ dialogCmd,
+ )
+}
+
+func registerManagementCommands() {
+ setCommandGroup("management", instancesCmd, healthCmd, profilesCmd, activityCmd, instanceCmd)
+
+ instanceCmd.AddCommand(startInstanceCmd, instanceNavigateCmd, instanceStopCmd, instanceLogsCmd)
+ activityCmd.AddCommand(activityTabCmd)
+
+ configureManagementFlags()
+
+ addRootCommands(instancesCmd, healthCmd, profilesCmd, activityCmd, instanceCmd)
+}
+
+func configureBrowserFlags() {
+ uploadCmd.Flags().StringP("selector", "s", "", "CSS selector for file input")
+ downloadCmd.Flags().StringP("output", "o", "", "Save downloaded file to path")
+
+ clickCmd.Flags().String("css", "", "CSS selector instead of ref")
+ addPointFlags(clickCmd, "click")
+ clickCmd.Flags().Bool("wait-nav", false, "Wait for navigation after click")
+
+ dblclickCmd.Flags().String("css", "", "CSS selector instead of ref")
+ addPointFlags(dblclickCmd, "dblclick")
+
+ hoverCmd.Flags().String("css", "", "CSS selector instead of ref")
+ addPointFlags(hoverCmd, "hover")
+
+ focusCmd.Flags().String("css", "", "CSS selector instead of ref")
+
+ snapCmd.Flags().BoolP("interactive", "i", false, "Filter interactive elements only")
+ snapCmd.Flags().BoolP("compact", "c", false, "Compact output format")
+ snapCmd.Flags().Bool("text", false, "Text output format")
+ snapCmd.Flags().BoolP("diff", "d", false, "Show diff from previous snapshot")
+ snapCmd.Flags().StringP("selector", "s", "", "CSS selector to scope snapshot")
+ snapCmd.Flags().String("max-tokens", "", "Maximum token budget")
+ snapCmd.Flags().String("depth", "", "Tree depth limit")
+
+ screenshotCmd.Flags().StringP("output", "o", "", "Save screenshot to file path")
+ screenshotCmd.Flags().StringP("quality", "q", "", "JPEG quality (0-100)")
+
+ pdfCmd.Flags().StringP("output", "o", "", "Save PDF to file path")
+ pdfCmd.Flags().Bool("landscape", false, "Landscape orientation")
+ pdfCmd.Flags().String("scale", "", "Page scale (e.g. 0.5)")
+ pdfCmd.Flags().String("paper-width", "", "Paper width (inches)")
+ pdfCmd.Flags().String("paper-height", "", "Paper height (inches)")
+ pdfCmd.Flags().String("margin-top", "", "Top margin")
+ pdfCmd.Flags().String("margin-bottom", "", "Bottom margin")
+ pdfCmd.Flags().String("margin-left", "", "Left margin")
+ pdfCmd.Flags().String("margin-right", "", "Right margin")
+ pdfCmd.Flags().String("page-ranges", "", "Page ranges (e.g. 1-3)")
+ pdfCmd.Flags().Bool("prefer-css-page-size", false, "Use CSS page size")
+ pdfCmd.Flags().Bool("display-header-footer", false, "Show header/footer")
+ pdfCmd.Flags().String("header-template", "", "Header HTML template")
+ pdfCmd.Flags().String("footer-template", "", "Footer HTML template")
+ pdfCmd.Flags().Bool("generate-tagged-pdf", false, "Generate tagged PDF")
+ pdfCmd.Flags().Bool("generate-document-outline", false, "Generate document outline")
+ pdfCmd.Flags().Bool("file-output", false, "Use server-side file output")
+ pdfCmd.Flags().String("path", "", "Server-side output path")
+
+ findCmd.Flags().String("threshold", "", "Minimum similarity score (0-1)")
+ findCmd.Flags().Bool("explain", false, "Show score breakdown")
+ findCmd.Flags().Bool("ref-only", false, "Output just the element ref")
+
+ textCmd.Flags().Bool("raw", false, "Raw extraction mode")
+
+ navCmd.Flags().Bool("new-tab", false, "Open in new tab")
+ navCmd.Flags().Bool("block-images", false, "Block image loading")
+ navCmd.Flags().Bool("block-ads", false, "Block ads")
+
+ addTabFlag(
+ navCmd,
+ backCmd,
+ forwardCmd,
+ reloadCmd,
+ snapCmd,
+ screenshotCmd,
+ pdfCmd,
+ findCmd,
+ textCmd,
+ clickCmd,
+ dblclickCmd,
+ hoverCmd,
+ focusCmd,
+ typeCmd,
+ pressCmd,
+ fillCmd,
+ scrollCmd,
+ selectCmd,
+ evalCmd,
+ checkCmd,
+ uncheckCmd,
+ keyboardTypeCmd,
+ keyboardInsertTextCmd,
+ keydownCmd,
+ keyupCmd,
+ scrollintoviewCmd,
+ networkCmd,
+ waitCmd,
+ dialogAcceptCmd,
+ dialogDismissCmd,
+ )
+
+ scrollintoviewCmd.Flags().String("css", "", "CSS selector instead of ref")
+
+ networkCmd.Flags().String("filter", "", "URL pattern filter")
+ networkCmd.Flags().String("method", "", "HTTP method filter (GET, POST, etc)")
+ networkCmd.Flags().String("status", "", "Status code range (e.g. 4xx, 5xx, 200)")
+ networkCmd.Flags().String("type", "", "Resource type filter (xhr, fetch, document, etc)")
+ networkCmd.Flags().String("limit", "", "Maximum entries to return")
+ networkCmd.Flags().Bool("body", false, "Include response body (with requestId)")
+ networkCmd.Flags().Bool("clear", false, "Clear captured network data")
+ networkCmd.Flags().String("buffer-size", "", "Per-tab network buffer size (default 100)")
+ networkCmd.Flags().Bool("stream", false, "Stream network entries in real-time (like tail -f)")
+
+ waitCmd.Flags().String("text", "", "Wait for text on page")
+ waitCmd.Flags().String("url", "", "Wait for URL glob match")
+ waitCmd.Flags().String("load", "", "Wait for load state (networkidle)")
+ waitCmd.Flags().String("fn", "", "Wait for JS expression to be truthy")
+ waitCmd.Flags().String("state", "", "Element state: visible (default) or hidden")
+ waitCmd.Flags().Int("timeout", 0, "Timeout in milliseconds (default 10000, max 30000)")
+}
+
+func configureManagementFlags() {
+ startInstanceCmd.Flags().String("profile", "", "Profile to use")
+ startInstanceCmd.Flags().String("mode", "", "Instance mode")
+ startInstanceCmd.Flags().String("port", "", "Port number")
+ startInstanceCmd.Flags().StringArray("extension", nil, "Load browser extension (repeatable)")
+
+ activityCmd.PersistentFlags().Int("limit", 200, "Maximum number of events to return")
+ activityCmd.PersistentFlags().Int("age-sec", 0, "Only include events from the last N seconds")
+}
+
+func setCommandGroup(groupID string, cmds ...*cobra.Command) {
+ for _, cmd := range cmds {
+ cmd.GroupID = groupID
+ }
+}
+
+func addRootCommands(cmds ...*cobra.Command) {
+ rootCmd.AddCommand(cmds...)
+}
+
+func addTabFlag(cmds ...*cobra.Command) {
+ for _, cmd := range cmds {
+ cmd.Flags().String("tab", "", "Tab ID")
+ }
+}
+
+func addPointFlags(cmd *cobra.Command, action string) {
+ cmd.Flags().Float64("x", 0, "X coordinate for "+action)
+ cmd.Flags().Float64("y", 0, "Y coordinate for "+action)
+}
diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.go
new file mode 100644
index 00000000..093592c4
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_runtime.go
@@ -0,0 +1,62 @@
+package main
+
+import (
+ "fmt"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
+)
+
+type cliRuntime struct {
+ client *http.Client
+ base string
+ token string
+}
+
+func runCLI(fn func(cliRuntime)) {
+ runCLIWith(loadConfig(), fn)
+}
+
+func runCLIWith(cfg *config.RuntimeConfig, fn func(cliRuntime)) {
+ fn(cliRuntime{
+ client: &http.Client{Timeout: 60 * time.Second},
+ base: resolveCLIBase(cfg),
+ token: resolveCLIToken(cfg),
+ })
+}
+
+func resolveCLIBase(cfg *config.RuntimeConfig) string {
+ port := cfg.Port
+ if port == "" {
+ port = "9867"
+ }
+ base := fmt.Sprintf("http://127.0.0.1:%s", port)
+ if serverURL != "" {
+ base = strings.TrimRight(serverURL, "/")
+ }
+ return base
+}
+
+func resolveCLIToken(cfg *config.RuntimeConfig) string {
+ token := cfg.Token
+ if envToken := os.Getenv("PINCHTAB_TOKEN"); envToken != "" {
+ token = envToken
+ }
+ return token
+}
+
+func optionalArg(args []string) string {
+ if len(args) == 0 {
+ return ""
+ }
+ return args[0]
+}
+
+func stringFlag(cmd *cobra.Command, name string) string {
+ value, _ := cmd.Flags().GetString(name)
+ return value
+}
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.go
index ebdc51fa..b11c8aba 100644
--- a/cmd/pinchtab/cmd_config.go
+++ b/cmd/pinchtab/cmd_config.go
@@ -1,16 +1,15 @@
package main
import (
- "encoding/json"
"fmt"
"os"
"os/exec"
- "path/filepath"
"runtime"
"strings"
"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"
)
@@ -21,7 +20,7 @@ var configCmd = &cobra.Command{
Use: "config",
Short: "Manage configuration",
Run: func(cmd *cobra.Command, args []string) {
- handleConfigOverview(loadConfig())
+ handleConfigOverview(loadLocalConfig())
},
}
@@ -31,7 +30,7 @@ func init() {
Use: "show",
Short: "Display current configuration",
Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
+ cfg := loadLocalConfig()
cli.HandleConfigShow(cfg)
},
})
@@ -210,7 +209,7 @@ func editConfigSelection(title, path, current string, values []string) (*config.
return nil, false, nil
}
- nextCfg, changed, err := updateConfigValue(path, picked)
+ nextCfg, changed, err := workflow.UpdateValue(path, picked)
if err != nil {
return nil, false, err
}
@@ -285,10 +284,7 @@ func clipboardCommands() []clipboardCommand {
}
func handleConfigInit() {
- configPath := os.Getenv("PINCHTAB_CONFIG")
- if configPath == "" {
- configPath = config.DefaultConfigPath()
- }
+ configPath := workflow.CurrentConfigPath()
if _, err := os.Stat(configPath); err == nil {
fmt.Printf("Config file already exists at %s\n", configPath)
@@ -300,20 +296,7 @@ func handleConfigInit() {
}
}
- if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
- fmt.Printf("Error creating directory: %v\n", err)
- os.Exit(1)
- }
-
- fc := config.DefaultFileConfig()
- token, err := config.GenerateAuthToken()
- if err != nil {
- fmt.Printf("Error generating auth token: %v\n", err)
- os.Exit(1)
- }
- fc.Server.Token = token
-
- if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ if err := workflow.InitDefaultConfig(configPath); err != nil {
fmt.Printf("Error writing config: %v\n", err)
os.Exit(1)
}
@@ -322,21 +305,11 @@ func handleConfigInit() {
}
func handleConfigPath() {
- configPath := os.Getenv("PINCHTAB_CONFIG")
- if configPath == "" {
- configPath = config.DefaultConfigPath()
- }
- fmt.Println(configPath)
+ fmt.Println(workflow.CurrentConfigPath())
}
func handleConfigGet(path string) {
- fc, _, err := config.LoadFileConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- value, err := config.GetConfigValue(fc, path)
+ value, err := workflow.GetValue(path)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
@@ -346,18 +319,13 @@ func handleConfigGet(path string) {
}
func handleConfigSet(path, value string) {
- fc, configPath, err := config.LoadFileConfig()
+ change, err := workflow.PrepareSetValue(path, value)
if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- if err := config.SetConfigValue(fc, path, value); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ if errs := change.ValidationErrors; len(errs) > 0 {
fmt.Printf("Warning: new value causes validation error(s):\n")
for _, err := range errs {
fmt.Printf(" - %v\n", err)
@@ -370,7 +338,7 @@ func handleConfigSet(path, value string) {
}
}
- if err := config.SaveFileConfig(fc, configPath); err != nil {
+ if err := workflow.SavePreparedChange(change); err != nil {
fmt.Printf("Error saving config: %v\n", err)
os.Exit(1)
}
@@ -379,18 +347,13 @@ func handleConfigSet(path, value string) {
}
func handleConfigPatch(jsonPatch string) {
- fc, configPath, err := config.LoadFileConfig()
+ change, err := workflow.PreparePatch(jsonPatch)
if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- if err := config.PatchConfigJSON(fc, jsonPatch); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ if errs := change.ValidationErrors; len(errs) > 0 {
fmt.Printf("Warning: patch causes validation error(s):\n")
for _, err := range errs {
fmt.Printf(" - %v\n", err)
@@ -403,7 +366,7 @@ func handleConfigPatch(jsonPatch string) {
}
}
- if err := config.SaveFileConfig(fc, configPath); err != nil {
+ if err := workflow.SavePreparedChange(change); err != nil {
fmt.Printf("Error saving config: %v\n", err)
os.Exit(1)
}
@@ -412,23 +375,13 @@ func handleConfigPatch(jsonPatch string) {
}
func handleConfigValidate() {
- configPath := os.Getenv("PINCHTAB_CONFIG")
- if configPath == "" {
- configPath = config.DefaultConfigPath()
- }
- data, err := os.ReadFile(configPath)
+ configPath, errs, err := workflow.ValidateCurrentFile()
if err != nil {
- fmt.Printf("Error reading config file: %v\n", err)
- os.Exit(1)
- }
-
- fc := &config.FileConfig{}
- if err := json.Unmarshal(data, fc); err != nil {
- fmt.Printf("Error parsing config: %v\n", err)
+ fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ if len(errs) > 0 {
fmt.Printf("Config file has %d error(s):\n", len(errs))
for _, err := range errs {
fmt.Printf(" - %v\n", err)
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.go
index 397e1e16..7ceacbfe 100644
--- a/cmd/pinchtab/cmd_config_test.go
+++ b/cmd/pinchtab/cmd_config_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "os"
"path/filepath"
"strings"
"testing"
@@ -82,3 +83,35 @@ func TestConfigSetAllowsDashPrefixedValue(t *testing.T) {
t.Fatalf("ChromeExtraFlags = %q, want %q", saved.Browser.ChromeExtraFlags, "--no-sandbox --disable-gpu")
}
}
+
+func TestConfigShowLoadsLegacyFlatConfigWithoutToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+
+ if err := os.WriteFile(configPath, []byte(`{
+ "port": "8765",
+ "headless": true,
+ "maxTabs": 30
+}`), 0600); err != nil {
+ t.Fatalf("WriteFile() error = %v", err)
+ }
+
+ t.Cleanup(func() {
+ rootCmd.SetArgs(nil)
+ })
+
+ output := captureStdout(t, func() {
+ rootCmd.SetArgs([]string{"config", "show"})
+ if err := rootCmd.Execute(); err != nil {
+ t.Fatalf("Execute() error = %v", err)
+ }
+ })
+
+ if !strings.Contains(output, "8765") {
+ t.Fatalf("expected config show output to contain legacy port, got %q", output)
+ }
+ if !strings.Contains(output, "Current configuration") {
+ t.Fatalf("expected config show header, got %q", output)
+ }
+}
diff --git a/cmd/pinchtab/cmd_daemon.go b/cmd/pinchtab/cmd_daemon.go
index dd1a81c2..2a4ec945 100644
--- a/cmd/pinchtab/cmd_daemon.go
+++ b/cmd/pinchtab/cmd_daemon.go
@@ -1,36 +1,26 @@
package main
import (
- "errors"
"fmt"
"os"
- "os/exec"
- "os/user"
- "path/filepath"
- "runtime"
"strings"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/daemon"
"github.com/spf13/cobra"
)
-const (
- pinchtabDaemonUnitName = "pinchtab.service"
- pinchtabLaunchdLabel = "com.pinchtab.pinchtab"
-)
-
var daemonCmd = &cobra.Command{
Use: "daemon [action]",
Short: "Manage the background service",
Long: "Start, stop, install, or check the status of the PinchTab background service.",
Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
sub := ""
if len(args) > 0 {
sub = args[0]
}
- handleDaemonCommand(cfg, sub)
+ handleDaemonCommand(sub)
},
}
@@ -39,12 +29,12 @@ func init() {
rootCmd.AddCommand(daemonCmd)
}
-func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
+func handleDaemonCommand(subcommand string) {
if subcommand == "" || subcommand == "help" || subcommand == "--help" || subcommand == "-h" {
printDaemonStatusSummary()
if subcommand == "" && isInteractiveTerminal() {
- picked, err := promptSelect("Daemon Actions", daemonMenuOptions(cli.IsDaemonInstalled(), cli.IsDaemonRunning()))
+ picked, err := promptSelect("Daemon Actions", daemonMenuOptions(daemon.IsInstalled(), daemon.IsRunning()))
if err != nil || picked == "exit" || picked == "" {
os.Exit(0)
}
@@ -58,7 +48,7 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
}
}
- manager, err := currentDaemonManager()
+ manager, err := daemon.CurrentManager()
if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
os.Exit(1)
@@ -66,12 +56,11 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
switch subcommand {
case "install":
- configPath, fileCfg, _, err := ensureDaemonConfig(false)
+ configPath, fileCfg, _, err := daemon.EnsureConfig(false)
if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
os.Exit(1)
}
- // Run wizard if needed (first install or version upgrade)
if config.NeedsWizard(fileCfg) {
isNew := config.IsFirstRun(fileCfg)
runSecurityWizard(fileCfg, configPath, isNew)
@@ -80,7 +69,7 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install unavailable: %v", err)))
os.Exit(1)
}
- message, err := manager.Install(managerEnvironment(manager).execPath, configPath)
+ message, err := manager.Install(configPath)
if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
fmt.Println()
@@ -140,14 +129,14 @@ func daemonMenuOptions(installed, running bool) []menuOption {
}
func printDaemonStatusSummary() {
- manager, err := currentDaemonManager()
+ manager, err := daemon.CurrentManager()
if err != nil {
fmt.Println(cli.StyleStdout(cli.ErrorStyle, " Error: ") + err.Error())
return
}
- installed := cli.IsDaemonInstalled()
- running := cli.IsDaemonRunning()
+ installed := daemon.IsInstalled()
+ running := daemon.IsRunning()
fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Daemon status:"))
@@ -200,105 +189,9 @@ func printDaemonManagerResult(message string, err error) {
}
if strings.HasPrefix(message, "Installed") || strings.HasPrefix(message, "Pinchtab daemon") {
fmt.Println(cli.StyleStdout(cli.SuccessStyle, " [ok] ") + message)
- } else {
- // For status, it might be a block of text
- fmt.Println(message)
- }
-}
-
-func ensureDaemonConfig(force bool) (string, *config.FileConfig, configBootstrapStatus, error) {
- _, configPath, err := config.LoadFileConfig()
- if err != nil {
- return "", nil, "", err
- }
-
- exists := fileExists(configPath)
- if !exists || force {
- defaults := config.DefaultFileConfig()
- defaults.ConfigVersion = "" // Leave empty so wizard triggers on first install
- token, err := config.GenerateAuthToken()
- if err != nil {
- return "", nil, "", err
- }
- defaults.Server.Token = token
- if err := config.SaveFileConfig(&defaults, configPath); err != nil {
- return "", nil, "", err
- }
- status := configCreated
- if exists {
- status = configRecovered
- }
- return configPath, &defaults, status, nil
- }
-
- // File exists — load it as-is, don't overwrite security settings.
- // Security recovery is now handled by the wizard or `pinchtab security up`.
- fileCfg, _, _ := config.LoadFileConfig()
- if fileCfg == nil {
- return configPath, nil, "", fmt.Errorf("failed to load existing config at %s", configPath)
- }
-
- // Only generate a token if one is missing (security essential)
- if strings.TrimSpace(fileCfg.Server.Token) == "" {
- token, err := config.GenerateAuthToken()
- if err == nil {
- fileCfg.Server.Token = token
- _ = config.SaveFileConfig(fileCfg, configPath)
- return configPath, fileCfg, configRecovered, nil
- }
+ return
}
-
- return configPath, fileCfg, configVerified, nil
-}
-
-type configBootstrapStatus string
-
-const (
- configCreated configBootstrapStatus = "created"
- configRecovered configBootstrapStatus = "recovered"
- configVerified configBootstrapStatus = "verified"
-)
-
-type commandRunner interface {
- CombinedOutput(name string, arg ...string) ([]byte, error)
-}
-
-type osCommandRunner struct{}
-
-func (r osCommandRunner) CombinedOutput(name string, arg ...string) ([]byte, error) {
- return exec.Command(name, arg...).CombinedOutput() // #nosec G204 -- args are daemon manager controlled, not user input
-}
-
-type daemonEnvironment struct {
- execPath string
- homeDir string
- osName string
- userID string
- xdgConfigHome string
-}
-
-type daemonManager interface {
- Preflight() error
- Install(execPath, configPath string) (string, error)
- ServicePath() string
- Start() (string, error)
- Restart() (string, error)
- Status() (string, error)
- Stop() (string, error)
- Uninstall() (string, error)
- ManualInstructions() string
- Pid() (string, error)
- Logs(n int) (string, error)
-}
-
-type systemdUserManager struct {
- env daemonEnvironment
- runner commandRunner
-}
-
-type launchdManager struct {
- env daemonEnvironment
- runner commandRunner
+ fmt.Println(message)
}
func printDaemonFollowUp() {
@@ -309,392 +202,3 @@ func printDaemonFollowUp() {
fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon stop"), cli.StyleStdout(cli.MutedStyle, "# Stop background service"))
fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon uninstall"), cli.StyleStdout(cli.MutedStyle, "# Remove service file"))
}
-
-func currentDaemonManager() (daemonManager, error) {
- env, err := currentDaemonEnvironment()
- if err != nil {
- return nil, err
- }
- return newDaemonManager(env, osCommandRunner{})
-}
-
-func currentDaemonEnvironment() (daemonEnvironment, error) {
- execPath, err := os.Executable()
- if err != nil {
- return daemonEnvironment{}, fmt.Errorf("resolve executable path: %w", err)
- }
- homeDir, err := os.UserHomeDir()
- if err != nil {
- return daemonEnvironment{}, fmt.Errorf("resolve home directory: %w", err)
- }
- currentUser, err := user.Current()
- if err != nil {
- return daemonEnvironment{}, fmt.Errorf("resolve current user: %w", err)
- }
-
- return daemonEnvironment{
- execPath: execPath,
- homeDir: homeDir,
- osName: runtime.GOOS,
- userID: currentUser.Uid,
- xdgConfigHome: os.Getenv("XDG_CONFIG_HOME"),
- }, nil
-}
-
-func newDaemonManager(env daemonEnvironment, runner commandRunner) (daemonManager, error) {
- switch env.osName {
- case "linux":
- return &systemdUserManager{env: env, runner: runner}, nil
- case "darwin":
- return &launchdManager{env: env, runner: runner}, nil
- default:
- return nil, fmt.Errorf("pinchtab daemon is supported on macOS and Linux; current OS is %s", env.osName)
- }
-}
-
-func managerEnvironment(manager daemonManager) daemonEnvironment {
- switch m := manager.(type) {
- case *systemdUserManager:
- return m.env
- case *launchdManager:
- return m.env
- default:
- return daemonEnvironment{}
- }
-}
-
-func (m *systemdUserManager) ServicePath() string {
- return filepath.Join(systemdUserConfigHome(m.env), "systemd", "user", pinchtabDaemonUnitName)
-}
-
-func (m *systemdUserManager) Preflight() error {
- if _, err := runCommand(m.runner, "systemctl", "--user", "show-environment"); err != nil {
- return fmt.Errorf("linux daemon install requires a working user systemd session (`systemctl --user`): %w", err)
- }
- return nil
-}
-
-func (m *systemdUserManager) Install(execPath, configPath string) (string, error) {
- if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
- return "", fmt.Errorf("create systemd user directory: %w", err)
- }
- if err := os.WriteFile(m.ServicePath(), []byte(renderSystemdUnit(execPath, configPath)), 0644); err != nil {
- return "", fmt.Errorf("write systemd unit: %w", err)
- }
- if _, err := runCommand(m.runner, "systemctl", "--user", "daemon-reload"); err != nil {
- return "", err
- }
- if _, err := runCommand(m.runner, "systemctl", "--user", "enable", "--now", pinchtabDaemonUnitName); err != nil {
- return "", err
- }
- return fmt.Sprintf("Installed systemd user service at %s", m.ServicePath()), nil
-}
-
-func (m *systemdUserManager) Start() (string, error) {
- if _, err := runCommand(m.runner, "systemctl", "--user", "start", pinchtabDaemonUnitName); err != nil {
- return "", err
- }
- return "Pinchtab daemon started.", nil
-}
-
-func (m *systemdUserManager) Restart() (string, error) {
- if _, err := runCommand(m.runner, "systemctl", "--user", "restart", pinchtabDaemonUnitName); err != nil {
- return "", err
- }
- return "Pinchtab daemon restarted.", nil
-}
-
-func (m *systemdUserManager) Stop() (string, error) {
- if _, err := runCommand(m.runner, "systemctl", "--user", "stop", pinchtabDaemonUnitName); err != nil {
- return "", err
- }
- return "Pinchtab daemon stopped.", nil
-}
-
-func (m *systemdUserManager) Status() (string, error) {
- output, err := runCommand(m.runner, "systemctl", "--user", "status", pinchtabDaemonUnitName, "--no-pager")
- if err != nil {
- return "", err
- }
- if strings.TrimSpace(output) == "" {
- return "Pinchtab daemon status returned no output.", nil
- }
- return output, nil
-}
-
-func (m *systemdUserManager) Uninstall() (string, error) {
- var errs []error
- if _, err := runCommand(m.runner, "systemctl", "--user", "disable", "--now", pinchtabDaemonUnitName); err != nil {
- errs = append(errs, err)
- }
- if err := os.Remove(m.ServicePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
- errs = append(errs, fmt.Errorf("remove unit file: %w", err))
- }
- if _, err := runCommand(m.runner, "systemctl", "--user", "daemon-reload"); err != nil {
- errs = append(errs, err)
- }
- if len(errs) > 0 {
- return "", errors.Join(errs...)
- }
- return "Pinchtab daemon uninstalled.", nil
-}
-
-func (m *systemdUserManager) Pid() (string, error) {
- output, err := runCommand(m.runner, "systemctl", "--user", "show", pinchtabDaemonUnitName, "--property", "MainPID")
- if err != nil {
- return "", err
- }
- // Output is typically MainPID=1234
- if parts := strings.Split(output, "="); len(parts) == 2 {
- pid := strings.TrimSpace(parts[1])
- if pid == "0" {
- return "", nil // Not running
- }
- return pid, nil
- }
- return "", nil
-}
-
-func (m *systemdUserManager) Logs(n int) (string, error) {
- return runCommand(m.runner, "journalctl", "--user", "-u", pinchtabDaemonUnitName, "-n", fmt.Sprintf("%d", n), "--no-pager")
-}
-
-func (m *systemdUserManager) ManualInstructions() string {
- path := m.ServicePath()
- var b strings.Builder
- fmt.Fprintln(&b, cli.StyleStdout(cli.HeadingStyle, "Manual instructions (Linux/systemd):"))
- fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To install manually:"))
- fmt.Fprintf(&b, " 1. Create %s\n", cli.StyleStdout(cli.ValueStyle, path))
- fmt.Fprintln(&b, " 2. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user daemon-reload"))
- fmt.Fprintln(&b, " 3. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user enable --now pinchtab.service"))
- fmt.Fprintln(&b)
- fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To uninstall manually:"))
- fmt.Fprintln(&b, " 1. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user disable --now pinchtab.service"))
- fmt.Fprintf(&b, " 2. Remove: %s\n", cli.StyleStdout(cli.ValueStyle, path))
- fmt.Fprintln(&b, " 3. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user daemon-reload"))
- return b.String()
-}
-
-func renderSystemdUnit(execPath, configPath string) string {
- return fmt.Sprintf(`[Unit]
-Description=Pinchtab Browser Service
-After=network.target
-
-[Service]
-Type=simple
-ExecStart="%s" server
-Environment="PINCHTAB_CONFIG=%s"
-Restart=always
-RestartSec=5
-
-[Install]
-WantedBy=default.target
-`, execPath, configPath)
-}
-
-func (m *launchdManager) ServicePath() string {
- return filepath.Join(m.env.homeDir, "Library", "LaunchAgents", pinchtabLaunchdLabel+".plist")
-}
-
-func (m *launchdManager) Preflight() error {
- if strings.TrimSpace(m.env.userID) == "" {
- return fmt.Errorf("macOS daemon install requires a logged-in user session with a launchd GUI domain")
- }
- if _, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)); err != nil {
- return fmt.Errorf("macOS daemon install requires an active launchd GUI session: %w", err)
- }
- return nil
-}
-
-func (m *launchdManager) Install(execPath, configPath string) (string, error) {
- if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
- return "", fmt.Errorf("create LaunchAgents directory: %w", err)
- }
- if err := os.WriteFile(m.ServicePath(), []byte(renderLaunchdPlist(execPath, configPath)), 0644); err != nil {
- return "", fmt.Errorf("write launchd plist: %w", err)
- }
- _, _ = runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
- if _, err := runCommand(m.runner, "launchctl", "bootstrap", launchdDomainTarget(m.env), m.ServicePath()); err != nil {
- return "", err
- }
- if _, err := runCommand(m.runner, "launchctl", "kickstart", "-k", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
- return "", err
- }
- return fmt.Sprintf("Installed launchd agent at %s", m.ServicePath()), nil
-}
-
-func (m *launchdManager) Start() (string, error) {
- if _, err := runCommand(m.runner, "launchctl", "bootstrap", launchdDomainTarget(m.env), m.ServicePath()); err != nil && !strings.Contains(err.Error(), "already bootstrapped") {
- return "", err
- }
- if _, err := runCommand(m.runner, "launchctl", "kickstart", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
- return "", err
- }
- return "Pinchtab daemon started.", nil
-}
-
-func (m *launchdManager) Restart() (string, error) {
- if _, err := runCommand(m.runner, "launchctl", "kickstart", "-k", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
- return "", err
- }
- return "Pinchtab daemon restarted.", nil
-}
-
-func (m *launchdManager) Stop() (string, error) {
- _, err := runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
- if err != nil && !isLaunchdIgnorableError(err) {
- return "", err
- }
- return "Pinchtab daemon stopped.", nil
-}
-
-func (m *launchdManager) Status() (string, error) {
- output, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel)
- if err != nil {
- return "", err
- }
- if strings.TrimSpace(output) == "" {
- return "Pinchtab daemon status returned no output.", nil
- }
- return output, nil
-}
-
-func (m *launchdManager) Uninstall() (string, error) {
- var errs []error
- _, err := runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
- if err != nil && !isLaunchdIgnorableError(err) {
- errs = append(errs, err)
- }
- if err := os.Remove(m.ServicePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
- errs = append(errs, fmt.Errorf("remove launchd plist: %w", err))
- }
- if len(errs) > 0 {
- return "", errors.Join(errs...)
- }
- return "Pinchtab daemon uninstalled.", nil
-}
-
-func (m *launchdManager) Pid() (string, error) {
- output, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel)
- if err != nil {
- return "", err
- }
- // Try to find pid = 1234
- lines := strings.Split(output, "\n")
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if strings.HasPrefix(trimmed, "pid = ") {
- return strings.TrimPrefix(trimmed, "pid = "), nil
- }
- }
- return "", nil
-}
-
-func (m *launchdManager) Logs(n int) (string, error) {
- // macOS log paths we added to plist
- logPath := "/tmp/pinchtab.err.log"
- if _, err := os.Stat(logPath); err != nil {
- return "No logs found at " + logPath, nil
- }
- return runCommand(m.runner, "tail", "-n", fmt.Sprintf("%d", n), logPath)
-}
-
-func (m *launchdManager) ManualInstructions() string {
- path := m.ServicePath()
- target := launchdDomainTarget(m.env)
- var b strings.Builder
- fmt.Fprintln(&b, cli.StyleStdout(cli.HeadingStyle, "Manual instructions (macOS/launchd):"))
- fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To install manually:"))
- fmt.Fprintf(&b, " 1. Create %s\n", cli.StyleStdout(cli.ValueStyle, path))
- fmt.Fprintln(&b, " 2. Run: "+cli.StyleStdout(cli.CommandStyle, fmt.Sprintf("launchctl bootstrap %s %s", target, path)))
- fmt.Fprintln(&b)
- fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To uninstall manually:"))
- fmt.Fprintln(&b, " 1. Run: "+cli.StyleStdout(cli.CommandStyle, fmt.Sprintf("launchctl bootout %s %s", target, path)))
- fmt.Fprintf(&b, " 2. Remove: %s\n", cli.StyleStdout(cli.ValueStyle, path))
- return b.String()
-}
-
-func isLaunchdIgnorableError(err error) bool {
- if err == nil {
- return true
- }
- msg := err.Error()
- // Exit status 5 often means already booted out or path not found in domain
- // "No such process" (status 3) or "No such file or directory" (status 2) or "Operation not permitted" (sometimes)
- return strings.Contains(msg, "exit status 5") ||
- strings.Contains(msg, "No such process") ||
- strings.Contains(msg, "not found") ||
- strings.Contains(msg, "already bootstrapped")
-}
-
-func renderLaunchdPlist(execPath, configPath string) string {
- return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>Label</key>
- <string>%s</string>
- <key>ProgramArguments</key>
- <array>
- <string>%s</string>
- <string>server</string>
- </array>
- <key>RunAtLoad</key>
- <true/>
- <key>KeepAlive</key>
- <true/>
- <key>ExitTimeOut</key>
- <integer>10</integer>
- <key>EnvironmentVariables</key>
- <dict>
- <key>PINCHTAB_CONFIG</key>
- <string>%s</string>
- </dict>
- <key>StandardOutPath</key>
- <string>/tmp/pinchtab.out.log</string>
- <key>StandardErrorPath</key>
- <string>/tmp/pinchtab.err.log</string>
-</dict>
-</plist>
-`, pinchtabLaunchdLabel, execPath, configPath)
-}
-
-func runCommand(runner commandRunner, name string, args ...string) (string, error) {
- output, err := runner.CombinedOutput(name, args...)
- trimmed := strings.TrimSpace(string(output))
- if err == nil {
- return trimmed, nil
- }
- if trimmed == "" {
- return "", fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
- }
- return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, trimmed)
-}
-
-func launchdDomainTarget(env daemonEnvironment) string {
- return "gui/" + env.userID
-}
-
-func systemdUserConfigHome(env daemonEnvironment) string {
- if strings.TrimSpace(env.xdgConfigHome) != "" {
- return env.xdgConfigHome
- }
- return filepath.Join(env.homeDir, ".config")
-}
-
-func fileExists(path string) bool {
- _, err := os.Stat(path)
- return err == nil
-}
-
-func isInteractiveTerminal() bool {
- in, err := os.Stdin.Stat()
- if err != nil || (in.Mode()&os.ModeCharDevice) == 0 {
- return false
- }
- out, err := os.Stdout.Stat()
- if err != nil || (out.Mode()&os.ModeCharDevice) == 0 {
- return false
- }
- return true
-}
diff --git a/cmd/pinchtab/cmd_daemon_test.go b/cmd/pinchtab/cmd_daemon_test.go
index 0c89bed6..d54078b7 100644
--- a/cmd/pinchtab/cmd_daemon_test.go
+++ b/cmd/pinchtab/cmd_daemon_test.go
@@ -1,249 +1,6 @@
package main
-import (
- "errors"
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-type fakeCommandRunner struct {
- calls []string
- outputs map[string]string
- errors map[string]error
-}
-
-func (f *fakeCommandRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
- call := name + " " + strings.Join(args, " ")
- f.calls = append(f.calls, call)
- if out, ok := f.outputs[call]; ok {
- return []byte(out), f.errors[call]
- }
- return nil, f.errors[call]
-}
-
-func TestEnsureOnboardConfigCreatesDefaultConfig(t *testing.T) {
- configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
- t.Setenv("PINCHTAB_CONFIG", configPath)
- t.Setenv("PINCHTAB_TOKEN", "")
- t.Setenv("PINCHTAB_BIND", "")
-
- gotPath, cfg, status, err := ensureDaemonConfig(false)
- if err != nil {
- t.Fatalf("ensureDaemonConfig returned error: %v", err)
- }
- if status != configCreated {
- t.Fatalf("status = %q, want %q", status, configCreated)
- }
- if gotPath != configPath {
- t.Fatalf("config path = %q, want %q", gotPath, configPath)
- }
- if cfg.Server.Bind != "127.0.0.1" {
- t.Fatalf("bind = %q, want 127.0.0.1", cfg.Server.Bind)
- }
- if strings.TrimSpace(cfg.Server.Token) == "" {
- t.Fatal("expected generated token to be set")
- }
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatalf("reading config file: %v", err)
- }
- content := string(data)
- if !strings.Contains(content, `"bind": "127.0.0.1"`) {
- t.Fatalf("expected config file to include bind, got %s", content)
- }
- if !strings.Contains(content, `"token": "`) {
- t.Fatalf("expected config file to include token, got %s", content)
- }
-}
-
-func TestEnsureOnboardConfigRecoversExistingSecuritySettings(t *testing.T) {
- configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
- t.Setenv("PINCHTAB_CONFIG", configPath)
- input := `{
- "server": {
- "bind": "0.0.0.0",
- "port": "9999",
- "token": ""
- },
- "browser": {
- "binary": "/custom/chrome"
- },
- "security": {
- "allowEvaluate": true
- }
-}
-`
- if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
- t.Fatalf("creating config dir: %v", err)
- }
- if err := os.WriteFile(configPath, []byte(input), 0644); err != nil {
- t.Fatalf("writing config file: %v", err)
- }
-
- _, cfg, status, err := ensureDaemonConfig(false)
- if err != nil {
- t.Fatalf("ensureDaemonConfig returned error: %v", err)
- }
- // Only token recovery happens now — security settings are preserved for wizard
- if status != configRecovered {
- t.Fatalf("status = %q, want %q", status, configRecovered)
- }
- // Bind is preserved as-is (wizard handles security changes, not daemon config)
- if cfg.Server.Bind != "0.0.0.0" {
- t.Fatalf("bind = %q, want 0.0.0.0 (preserved)", cfg.Server.Bind)
- }
- if cfg.Server.Port != "9999" {
- t.Fatalf("port = %q, want 9999", cfg.Server.Port)
- }
- if cfg.Browser.ChromeBinary != "/custom/chrome" {
- t.Fatalf("chrome binary = %q, want /custom/chrome", cfg.Browser.ChromeBinary)
- }
- // Security settings preserved — not overwritten
- if !boolPtrValue(cfg.Security.AllowEvaluate) {
- t.Fatal("expected allowEvaluate to be preserved as true")
- }
- // Token should be generated (was empty)
- if strings.TrimSpace(cfg.Server.Token) == "" {
- t.Fatal("expected recovery to generate a token")
- }
-}
-
-func TestSystemdUserManagerInstallWritesUnitAndEnablesService(t *testing.T) {
- root := t.TempDir()
- runner := &fakeCommandRunner{}
- manager := &systemdUserManager{
- env: daemonEnvironment{
- homeDir: root,
- osName: "linux",
- execPath: "/usr/local/bin/pinchtab",
- xdgConfigHome: filepath.Join(root, ".config"),
- },
- runner: runner,
- }
-
- message, err := manager.Install("/usr/local/bin/pinchtab", "/tmp/pinchtab/config.json")
- if err != nil {
- t.Fatalf("Install returned error: %v", err)
- }
- if !strings.Contains(message, manager.ServicePath()) {
- t.Fatalf("install message = %q, want path %q", message, manager.ServicePath())
- }
-
- data, err := os.ReadFile(manager.ServicePath())
- if err != nil {
- t.Fatalf("reading service file: %v", err)
- }
- content := string(data)
- if !strings.Contains(content, `ExecStart="/usr/local/bin/pinchtab" server`) {
- t.Fatalf("unexpected unit content: %s", content)
- }
- if !strings.Contains(content, `Environment="PINCHTAB_CONFIG=/tmp/pinchtab/config.json"`) {
- t.Fatalf("expected config env in unit content: %s", content)
- }
-
- expectedCalls := []string{
- "systemctl --user daemon-reload",
- "systemctl --user enable --now pinchtab.service",
- }
- if strings.Join(runner.calls, "\n") != strings.Join(expectedCalls, "\n") {
- t.Fatalf("systemd calls = %v, want %v", runner.calls, expectedCalls)
- }
-}
-
-func TestLaunchdManagerInstallWritesPlistAndBootstrapsAgent(t *testing.T) {
- root := t.TempDir()
- runner := &fakeCommandRunner{}
- manager := &launchdManager{
- env: daemonEnvironment{
- homeDir: root,
- osName: "darwin",
- execPath: "/Applications/Pinchtab.app/Contents/MacOS/pinchtab",
- userID: "501",
- },
- runner: runner,
- }
-
- message, err := manager.Install("/Applications/Pinchtab.app/Contents/MacOS/pinchtab", "/tmp/pinchtab/config.json")
- if err != nil {
- t.Fatalf("Install returned error: %v", err)
- }
- if !strings.Contains(message, manager.ServicePath()) {
- t.Fatalf("install message = %q, want path %q", message, manager.ServicePath())
- }
-
- data, err := os.ReadFile(manager.ServicePath())
- if err != nil {
- t.Fatalf("reading launchd plist: %v", err)
- }
- content := string(data)
- if !strings.Contains(content, "<string>com.pinchtab.pinchtab</string>") {
- t.Fatalf("expected launchd label in plist: %s", content)
- }
- if !strings.Contains(content, "<string>/Applications/Pinchtab.app/Contents/MacOS/pinchtab</string>") {
- t.Fatalf("expected executable path in plist: %s", content)
- }
- if !strings.Contains(content, "<string>/tmp/pinchtab/config.json</string>") {
- t.Fatalf("expected config path in plist: %s", content)
- }
-
- expectedCalls := []string{
- "launchctl bootout gui/501 " + manager.ServicePath(),
- "launchctl bootstrap gui/501 " + manager.ServicePath(),
- "launchctl kickstart -k gui/501/com.pinchtab.pinchtab",
- }
- if strings.Join(runner.calls, "\n") != strings.Join(expectedCalls, "\n") {
- t.Fatalf("launchctl calls = %v, want %v", runner.calls, expectedCalls)
- }
-}
-
-func TestSystemdUserManagerPreflightRequiresUserSession(t *testing.T) {
- runner := &fakeCommandRunner{
- errors: map[string]error{
- "systemctl --user show-environment": errors.New("exit status 1"),
- },
- }
- manager := &systemdUserManager{
- env: daemonEnvironment{osName: "linux"},
- runner: runner,
- }
-
- err := manager.Preflight()
- if err == nil {
- t.Fatal("expected preflight error")
- }
- if !strings.Contains(err.Error(), "working user systemd session") {
- t.Fatalf("unexpected error: %v", err)
- }
-}
-
-func TestLaunchdManagerPreflightRequiresGUIDomain(t *testing.T) {
- runner := &fakeCommandRunner{
- errors: map[string]error{
- "launchctl print gui/501": errors.New("exit status 113"),
- },
- }
- manager := &launchdManager{
- env: daemonEnvironment{osName: "darwin", userID: "501"},
- runner: runner,
- }
-
- err := manager.Preflight()
- if err == nil {
- t.Fatal("expected preflight error")
- }
- if !strings.Contains(err.Error(), "active launchd GUI session") {
- t.Fatalf("unexpected error: %v", err)
- }
-}
-
-func TestNewDaemonManagerRejectsUnsupportedOS(t *testing.T) {
- _, err := newDaemonManager(daemonEnvironment{osName: "windows"}, &fakeCommandRunner{})
- if err == nil {
- t.Fatal("expected unsupported OS error")
- }
-}
+import "testing"
func TestDaemonMenuOptions(t *testing.T) {
tests := []struct {
diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.go
index 1c33ce9b..0bd1b25d 100644
--- a/cmd/pinchtab/cmd_mcp.go
+++ b/cmd/pinchtab/cmd_mcp.go
@@ -15,7 +15,7 @@ var mcpCmd = &cobra.Command{
Short: "Start the MCP stdio server",
Long: "Start the Model Context Protocol stdio server and proxy browser actions to a running PinchTab instance.",
Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
+ cfg := loadConfig()
runMCP(cfg)
},
}
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index 71e5989e..8e6b67ed 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -1,14 +1,13 @@
package main
import (
- "encoding/json"
"fmt"
"os"
- "slices"
"strings"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/config/workflow"
"github.com/spf13/cobra"
)
@@ -17,7 +16,7 @@ var securityCmd = &cobra.Command{
Short: "Review runtime security posture",
Long: "Shows runtime security posture and offers to restore recommended security defaults.",
Run: func(cmd *cobra.Command, args []string) {
- cfg := loadConfig()
+ cfg := loadLocalConfig()
handleSecurityCommand(cfg)
},
}
@@ -186,7 +185,7 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
if err != nil {
return nil, false, err
}
- return updateConfigValue("server.bind", value)
+ return workflow.UpdateValue("server.bind", value)
case "api_auth_enabled":
picked, err := promptSelect("API authentication", []menuOption{
{label: "Generate new token (Recommended)", value: "generate"},
@@ -203,15 +202,15 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
if err != nil {
return nil, false, err
}
- return updateConfigValue("server.token", token)
+ return workflow.UpdateValue("server.token", token)
case "custom":
token, err := promptInput("Set server.token:", cfg.Token)
if err != nil {
return nil, false, err
}
- return updateConfigValue("server.token", token)
+ return workflow.UpdateValue("server.token", token)
case "disable":
- return updateConfigValue("server.token", "")
+ return workflow.UpdateValue("server.token", "")
}
case "sensitive_endpoints_disabled":
current := strings.Join(cfg.EnabledSensitiveEndpoints(), ",")
@@ -219,7 +218,7 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
if err != nil {
return nil, false, err
}
- return updateSensitiveEndpoints(value)
+ return workflow.UpdateSensitiveEndpoints(value)
case "attach_disabled":
picked, err := promptSelect("Attach endpoint", []menuOption{
{label: "Disable (Recommended)", value: "disable"},
@@ -229,19 +228,19 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
if err != nil || picked == "" || picked == "cancel" {
return cfg, false, nil
}
- return updateConfigValue("security.attach.enabled", fmt.Sprintf("%t", picked == "enable"))
+ return workflow.UpdateValue("security.attach.enabled", fmt.Sprintf("%t", picked == "enable"))
case "attach_local_only":
value, err := promptInput("Set security.attach.allowHosts (comma-separated):", strings.Join(cfg.AttachAllowHosts, ","))
if err != nil {
return nil, false, err
}
- return updateConfigValue("security.attach.allowHosts", value)
+ return workflow.UpdateValue("security.attach.allowHosts", value)
case "idpi_whitelist_scoped":
value, err := promptInput("Set security.idpi.allowedDomains (comma-separated):", strings.Join(cfg.IDPI.AllowedDomains, ","))
if err != nil {
return nil, false, err
}
- return updateConfigValue("security.idpi.allowedDomains", value)
+ return workflow.UpdateValue("security.idpi.allowedDomains", value)
case "idpi_strict_mode":
picked, err := promptSelect("IDPI strict mode", []menuOption{
{label: "Enforce (Recommended)", value: "true"},
@@ -251,7 +250,7 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
if err != nil || picked == "" || picked == "cancel" {
return cfg, false, nil
}
- return updateConfigValue("security.idpi.strictMode", picked)
+ 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"},
@@ -263,155 +262,13 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
if err != nil || picked == "" || picked == "cancel" {
return cfg, false, nil
}
- return updateContentGuard(picked)
+ return workflow.UpdateContentGuard(picked)
}
return cfg, false, nil
}
-func updateConfigValue(path, value string) (*config.RuntimeConfig, bool, error) {
- fc, configPath, err := config.LoadFileConfig()
- if err != nil {
- return nil, false, fmt.Errorf("load config: %w", err)
- }
- if err := config.SetConfigValue(fc, path, value); err != nil {
- return nil, false, fmt.Errorf("set %s: %w", path, err)
- }
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
- return nil, false, errs[0]
- }
- if err := config.SaveFileConfig(fc, configPath); err != nil {
- return nil, false, fmt.Errorf("save config: %w", err)
- }
- return config.Load(), true, nil
-}
-
-func updateSensitiveEndpoints(value string) (*config.RuntimeConfig, bool, error) {
- fc, configPath, err := config.LoadFileConfig()
- if err != nil {
- return nil, false, fmt.Errorf("load config: %w", err)
- }
-
- selected := map[string]bool{}
- for _, item := range splitCommaList(value) {
- selected[item] = true
- }
- for endpoint, path := range map[string]string{
- "evaluate": "security.allowEvaluate",
- "macro": "security.allowMacro",
- "screencast": "security.allowScreencast",
- "download": "security.allowDownload",
- "upload": "security.allowUpload",
- } {
- enabled := selected[endpoint]
- if err := config.SetConfigValue(fc, path, fmt.Sprintf("%t", enabled)); err != nil {
- return nil, false, fmt.Errorf("set %s: %w", endpoint, err)
- }
- }
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
- return nil, false, errs[0]
- }
- if err := config.SaveFileConfig(fc, configPath); err != nil {
- return nil, false, fmt.Errorf("save config: %w", err)
- }
- return config.Load(), true, nil
-}
-
-func updateContentGuard(mode string) (*config.RuntimeConfig, bool, error) {
- fc, configPath, err := config.LoadFileConfig()
- if err != nil {
- return nil, false, fmt.Errorf("load config: %w", err)
- }
-
- scan := mode == "both" || mode == "scan"
- wrap := mode == "both" || mode == "wrap"
- for _, item := range []struct {
- path string
- value bool
- }{
- {path: "security.idpi.scanContent", value: scan},
- {path: "security.idpi.wrapContent", value: wrap},
- } {
- if err := config.SetConfigValue(fc, item.path, fmt.Sprintf("%t", item.value)); err != nil {
- return nil, false, fmt.Errorf("set %s: %w", item.path, err)
- }
- }
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
- return nil, false, errs[0]
- }
- if err := config.SaveFileConfig(fc, configPath); err != nil {
- return nil, false, fmt.Errorf("save config: %w", err)
- }
- 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)
- }
- originalJSON, err := formatFileConfigJSON(fc)
- if err != nil {
- return nil, "", false, err
- }
-
- original, err := config.GetConfigValue(fc, "server.token")
- if err != nil {
- return nil, "", 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)
- }
- if err := config.SetConfigValue(fc, "server.token", token); err != nil {
- return nil, "", false, fmt.Errorf("set server.token: %w", err)
- }
- }
-
- for _, item := range []struct {
- path string
- value string
- }{
- {path: "server.bind", value: "127.0.0.1"},
- {path: "security.allowEvaluate", value: "true"},
- {path: "security.allowMacro", value: "true"},
- {path: "security.allowScreencast", value: "true"},
- {path: "security.allowDownload", value: "true"},
- {path: "security.allowUpload", value: "true"},
- {path: "security.attach.enabled", value: "true"},
- {path: "security.attach.allowHosts", value: "127.0.0.1,localhost,::1"},
- {path: "security.attach.allowSchemes", value: "ws,wss"},
- {path: "security.idpi.enabled", value: "false"},
- {path: "security.idpi.strictMode", value: "false"},
- {path: "security.idpi.scanContent", value: "false"},
- {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)
- }
- }
-
- if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
- return nil, "", false, errs[0]
- }
-
- nextJSON, err := formatFileConfigJSON(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)
- }
- return config.Load(), configPath, true, nil
-}
-
func applySecurityUp() (*config.RuntimeConfig, bool, error) {
- configPath, changed, err := cli.RestoreSecurityDefaults()
+ configPath, changed, err := workflow.RestoreSecurityDefaults()
if err != nil {
return nil, false, fmt.Errorf("restore defaults: %w", err)
}
@@ -425,7 +282,7 @@ func applySecurityUp() (*config.RuntimeConfig, bool, error) {
}
func applySecurityDown() (*config.RuntimeConfig, bool, error) {
- nextCfg, configPath, changed, err := applyGuardsDownPreset()
+ nextCfg, configPath, changed, err := workflow.ApplyGuardsDownPreset()
if err != nil {
return nil, false, fmt.Errorf("guards down: %w", err)
}
@@ -451,24 +308,3 @@ func handleSecurityDownCommand() {
os.Exit(1)
}
}
-
-func formatFileConfigJSON(fc *config.FileConfig) (string, error) {
- data, err := json.Marshal(fc)
- if err != nil {
- return "", fmt.Errorf("marshal config: %w", err)
- }
- return string(data), nil
-}
-
-func splitCommaList(value string) []string {
- parts := strings.Split(value, ",")
- items := make([]string, 0, len(parts))
- for _, part := range parts {
- trimmed := strings.TrimSpace(strings.ToLower(part))
- if trimmed != "" {
- items = append(items, trimmed)
- }
- }
- slices.Sort(items)
- return slices.Compact(items)
-}
diff --git a/cmd/pinchtab/cmd_security_test.go b/cmd/pinchtab/cmd_security_test.go
index 9a2fd8ea..d34ae11b 100644
--- a/cmd/pinchtab/cmd_security_test.go
+++ b/cmd/pinchtab/cmd_security_test.go
@@ -3,7 +3,6 @@ package main
import (
"io"
"os"
- "path/filepath"
"strings"
"testing"
@@ -70,53 +69,6 @@ func captureStdout(t *testing.T, fn func()) string {
return string(data)
}
-func TestApplyGuardsDownPreset(t *testing.T) {
- configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
- t.Setenv("PINCHTAB_CONFIG", configPath)
-
- fc := config.DefaultFileConfig()
- fc.Server.Token = "guarded-token"
- if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
- t.Fatalf("MkdirAll() error = %v", err)
- }
- if err := config.SaveFileConfig(&fc, configPath); err != nil {
- t.Fatalf("SaveFileConfig() error = %v", err)
- }
-
- cfg, gotPath, changed, err := applyGuardsDownPreset()
- if err != nil {
- t.Fatalf("applyGuardsDownPreset() error = %v", err)
- }
- if !changed {
- t.Fatal("expected guards down preset to change config")
- }
- if gotPath != configPath {
- t.Fatalf("config path = %q, want %q", gotPath, configPath)
- }
-
- if cfg.Bind != "127.0.0.1" {
- t.Fatalf("Bind = %q, want 127.0.0.1", cfg.Bind)
- }
- if cfg.Token != "guarded-token" {
- t.Fatalf("Token = %q, want existing token to remain", cfg.Token)
- }
- if !cfg.AllowEvaluate || !cfg.AllowMacro || !cfg.AllowScreencast || !cfg.AllowDownload || !cfg.AllowUpload {
- t.Fatalf("expected sensitive endpoints enabled, got %+v", cfg)
- }
- if !cfg.AttachEnabled {
- t.Fatal("expected attach endpoint enabled")
- }
- if got := strings.Join(cfg.AttachAllowHosts, ","); got != "127.0.0.1,localhost,::1" {
- t.Fatalf("AttachAllowHosts = %q", got)
- }
- if got := strings.Join(cfg.AttachAllowSchemes, ","); got != "ws,wss" {
- t.Fatalf("AttachAllowSchemes = %q", got)
- }
- if cfg.IDPI.Enabled || cfg.IDPI.StrictMode || cfg.IDPI.ScanContent || cfg.IDPI.WrapContent {
- t.Fatalf("expected IDPI protections disabled, got %+v", cfg.IDPI)
- }
-}
-
func testRuntimeConfig() *config.RuntimeConfig {
return &config.RuntimeConfig{
Bind: "127.0.0.1",
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.go
index 2ee00b57..9c569108 100644
--- a/cmd/pinchtab/cmd_server.go
+++ b/cmd/pinchtab/cmd_server.go
@@ -1,7 +1,6 @@
package main
import (
- "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
@@ -11,7 +10,7 @@ var serverCmd = &cobra.Command{
Short: "Start server",
Run: func(cmd *cobra.Command, args []string) {
maybeRunWizard()
- cfg := config.Load()
+ cfg := loadConfig()
if exts, _ := cmd.Flags().GetStringArray("extension"); len(exts) > 0 {
cfg.ExtensionPaths = append(cfg.ExtensionPaths, exts...)
}
diff --git a/cmd/pinchtab/cmd_terminal.go b/cmd/pinchtab/cmd_terminal.go
new file mode 100644
index 00000000..190143ca
--- /dev/null
+++ b/cmd/pinchtab/cmd_terminal.go
@@ -0,0 +1,15 @@
+package main
+
+import "os"
+
+func isInteractiveTerminal() bool {
+ in, err := os.Stdin.Stat()
+ if err != nil || (in.Mode()&os.ModeCharDevice) == 0 {
+ return false
+ }
+ out, err := os.Stdout.Stat()
+ if err != nil || (out.Mode()&os.ModeCharDevice) == 0 {
+ return false
+ }
+ return true
+}
diff --git a/cmd/pinchtab/cmd_wizard.go b/cmd/pinchtab/cmd_wizard.go
index 42adc7ec..32ad90e7 100644
--- a/cmd/pinchtab/cmd_wizard.go
+++ b/cmd/pinchtab/cmd_wizard.go
@@ -14,6 +14,10 @@ import (
// Returns true if the user completed setup, false if they cancelled.
func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) bool {
interactive := isInteractiveTerminal()
+ if _, err := config.EnsureFileToken(cfg); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("failed to generate auth token: %v", err)))
+ return false
+ }
if !interactive {
return runNonInteractiveSetup(cfg, configPath, isNew)
@@ -201,21 +205,10 @@ func printSetting(name, value string) {
fmt.Printf(" %-12s %s\n", name+":", value)
}
-func boolPtrValue(p *bool) bool {
- if p == nil {
- return false
- }
- return *p
-}
-
func dashboardURL(cfg *config.FileConfig, path string) string {
host := orDefault(cfg.Server.Bind, "127.0.0.1")
port := orDefault(cfg.Server.Port, "9867")
- url := fmt.Sprintf("http://%s:%s%s", host, port, path)
- if cfg.Server.Token != "" {
- url += "?token=" + cfg.Server.Token
- }
- return url
+ return fmt.Sprintf("http://%s:%s%s", host, port, path)
}
func orDefault(val, fallback string) string {
diff --git a/cmd/pinchtab/config_load.go b/cmd/pinchtab/config_load.go
index c7fb79d4..f35f6733 100644
--- a/cmd/pinchtab/config_load.go
+++ b/cmd/pinchtab/config_load.go
@@ -1,7 +1,67 @@
package main
-import "github.com/pinchtab/pinchtab/internal/config"
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
func loadConfig() *config.RuntimeConfig {
+ cfg, err := loadConfigWithMandatoryToken()
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)
+ os.Exit(1)
+ }
+ return cfg
+}
+
+func loadLocalConfig() *config.RuntimeConfig {
return config.Load()
}
+
+func loadConfigWithMandatoryToken() (*config.RuntimeConfig, error) {
+ if err := ensureMandatoryToken(); err != nil {
+ return nil, err
+ }
+ return config.Load(), nil
+}
+
+func ensureMandatoryToken() error {
+ if strings.TrimSpace(os.Getenv("PINCHTAB_TOKEN")) != "" {
+ return nil
+ }
+
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return fmt.Errorf("load config file: %w", err)
+ }
+ if fc == nil {
+ fc = &config.FileConfig{}
+ }
+ if strings.TrimSpace(fc.Server.Token) != "" {
+ return nil
+ }
+
+ if strings.TrimSpace(os.Getenv("PINCHTAB_CONFIG")) != "" {
+ if _, statErr := os.Stat(configPath); statErr == nil {
+ return fmt.Errorf("server token is required in %s when PINCHTAB_CONFIG is set; add server.token or set PINCHTAB_TOKEN", configPath)
+ } else if !os.IsNotExist(statErr) {
+ return fmt.Errorf("stat config file: %w", statErr)
+ }
+ }
+
+ changed, err := config.EnsureFileToken(fc)
+ if err != nil {
+ return fmt.Errorf("ensure server token: %w", err)
+ }
+ if !changed {
+ return nil
+ }
+
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return fmt.Errorf("save config file: %w", err)
+ }
+ return nil
+}
diff --git a/cmd/pinchtab/config_load_test.go b/cmd/pinchtab/config_load_test.go
new file mode 100644
index 00000000..0f2bb3e7
--- /dev/null
+++ b/cmd/pinchtab/config_load_test.go
@@ -0,0 +1,93 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestLoadConfigWithMandatoryToken_GeneratesAndPersistsToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+
+ cfg, err := loadConfigWithMandatoryToken()
+ if err != nil {
+ t.Fatalf("loadConfigWithMandatoryToken() error = %v", err)
+ }
+ if cfg.Token == "" {
+ t.Fatal("expected generated runtime token")
+ }
+
+ saved, _, err := config.LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if saved.Server.Token == "" {
+ t.Fatal("expected generated token to be persisted")
+ }
+ if saved.Server.Token != cfg.Token {
+ t.Fatalf("saved token = %q, runtime token = %q", saved.Server.Token, cfg.Token)
+ }
+}
+
+func TestLoadConfigWithMandatoryToken_UsesEnvTokenWithoutPersisting(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "env-token")
+
+ cfg, err := loadConfigWithMandatoryToken()
+ if err != nil {
+ t.Fatalf("loadConfigWithMandatoryToken() error = %v", err)
+ }
+ if cfg.Token != "env-token" {
+ t.Fatalf("runtime token = %q, want env-token", cfg.Token)
+ }
+ if _, err := os.Stat(configPath); !os.IsNotExist(err) {
+ t.Fatalf("expected config file to remain absent, stat err = %v", err)
+ }
+}
+
+func TestLoadConfigWithMandatoryToken_PreservesExistingToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "existing-token"
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ cfg, err := loadConfigWithMandatoryToken()
+ if err != nil {
+ t.Fatalf("loadConfigWithMandatoryToken() error = %v", err)
+ }
+ if cfg.Token != "existing-token" {
+ t.Fatalf("runtime token = %q, want existing-token", cfg.Token)
+ }
+}
+
+func TestLoadConfigWithMandatoryToken_ExplicitConfigRequiresToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+
+ fc := config.DefaultFileConfig()
+ fc.ConfigVersion = config.CurrentConfigVersion
+ fc.Server.Token = ""
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ _, err := loadConfigWithMandatoryToken()
+ if err == nil {
+ t.Fatal("expected explicit config without token to fail")
+ }
+ if !strings.Contains(err.Error(), "server token is required") {
+ t.Fatalf("error = %q, want explicit token requirement", err)
+ }
+}
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
index 5a979531..b04f6c41 100644
--- a/cmd/pinchtab/root.go
+++ b/cmd/pinchtab/root.go
@@ -20,12 +20,10 @@ browsers, manage tabs, and perform interactive tasks.`,
Example: ` pinchtab server
pinchtab nav https://pinchtab.com`,
Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
-
// Check if security wizard needs to run
maybeRunWizard()
-
if isInteractiveTerminal() {
+ cfg := loadLocalConfig()
cli.PrintStartupBanner(cfg, cli.StartupBannerOptions{
Mode: "menu",
ListenStatus: menuListenStatus(cfg),
@@ -48,13 +46,13 @@ browsers, manage tabs, and perform interactive tasks.`,
switch picked {
case "server":
- server.RunDashboard(cfg, version)
+ server.RunDashboard(loadConfig(), version)
case "daemon":
- handleDaemonCommand(cfg, "")
+ handleDaemonCommand("")
case "bridge":
- server.RunBridgeServer(cfg)
+ server.RunBridgeServer(loadConfig())
case "mcp":
- runMCP(cfg)
+ runMCP(loadConfig())
case "config":
handleConfigOverview(cfg)
case "security":
@@ -66,7 +64,7 @@ browsers, manage tabs, and perform interactive tasks.`,
}
// Fallback for non-interactive: start the server
- server.RunDashboard(cfg, version)
+ server.RunDashboard(loadConfig(), version)
},
}
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 8e2ef36d..2e7b5610 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -1,23 +1,18 @@
import { useEffect, useState } from "react";
import {
BrowserRouter,
- Routes,
- Route,
Navigate,
+ Route,
+ Routes,
useLocation,
useNavigate,
} from "react-router-dom";
import { ActivityPage } from "./activities";
-import { useAppStore } from "./stores/useAppStore";
import { NavBar } from "./components/molecules";
import { LoginPage, MonitoringPage, ProfilesPage, SettingsPage } from "./pages";
import * as api from "./services/api";
-import {
- AUTH_REQUIRED_EVENT,
- clearStoredAuthToken,
- getStoredAuthToken,
- setStoredAuthToken,
-} from "./services/auth";
+import { AUTH_REQUIRED_EVENT, AUTH_STATE_CHANGED_EVENT } from "./services/auth";
+import { useAppStore } from "./stores/useAppStore";
type AuthMode = "probing" | "required" | "open" | "unreachable";
const AUTH_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000] as const;
@@ -34,40 +29,22 @@ function AppContent() {
const location = useLocation();
const navigate = useNavigate();
const memoryMetricsEnabled = settings.monitoring?.memoryMetrics ?? false;
- // Auto-login from ?token= query parameter (e.g. from wizard URL)
- useEffect(() => {
- const params = new URLSearchParams(window.location.search);
- const urlToken = params.get("token");
- if (urlToken) {
- setStoredAuthToken(urlToken);
- const clean = new URL(window.location.href);
- clean.searchParams.delete("token");
- window.history.replaceState({}, "", clean.pathname + clean.hash);
- window.location.reload();
- }
- }, []);
-
- const authToken = getStoredAuthToken();
- const hasStoredToken = authToken !== "";
- const [authMode, setAuthMode] = useState<AuthMode>(
- hasStoredToken ? "required" : "probing",
- );
+ const [authMode, setAuthMode] = useState<AuthMode>("probing");
+ const [authProtected, setAuthProtected] = useState(false);
const [authRetryCount, setAuthRetryCount] = useState(0);
- const dashboardAccessible = hasStoredToken || authMode === "open";
- const loginRequired = !hasStoredToken && authMode === "required";
+ const dashboardAccessible = authMode === "open";
+ const loginRequired = authMode === "required";
useEffect(() => {
document.documentElement.setAttribute("data-site-mode", "agent");
}, []);
useEffect(() => {
- if (hasStoredToken) {
- setAuthMode("required");
- setAuthRetryCount(0);
- return;
- }
-
- if (authMode === "open" || authMode === "unreachable") {
+ if (
+ authMode === "open" ||
+ authMode === "required" ||
+ authMode === "unreachable"
+ ) {
return;
}
@@ -78,7 +55,8 @@ function AppContent() {
if (cancelled) {
return;
}
- setAuthMode(result.requiresAuth ? "required" : "open");
+ setAuthProtected(result.mode !== "open");
+ setAuthMode(result.mode === "required" ? "required" : "open");
setAuthRetryCount(0);
if (result.health) {
setServerInfo(result.health);
@@ -95,11 +73,10 @@ function AppContent() {
return () => {
cancelled = true;
};
- }, [authMode, hasStoredToken, setServerInfo]);
+ }, [authMode, setServerInfo]);
useEffect(() => {
if (
- hasStoredToken ||
authMode !== "unreachable" ||
authRetryCount >= AUTH_RETRY_DELAYS_MS.length
) {
@@ -114,11 +91,11 @@ function AppContent() {
return () => {
window.clearTimeout(timer);
};
- }, [authMode, authRetryCount, hasStoredToken]);
+ }, [authMode, authRetryCount]);
useEffect(() => {
const handleAuthRequired = () => {
- clearStoredAuthToken();
+ setAuthProtected(true);
setAuthMode("required");
setAuthRetryCount(0);
navigate("/login", {
@@ -126,9 +103,20 @@ function AppContent() {
state: { from: location.pathname },
});
};
+ const handleAuthStateChanged = () => {
+ setAuthMode("probing");
+ setAuthRetryCount(0);
+ };
+
window.addEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
- return () =>
+ window.addEventListener(AUTH_STATE_CHANGED_EVENT, handleAuthStateChanged);
+ return () => {
window.removeEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
+ window.removeEventListener(
+ AUTH_STATE_CHANGED_EVENT,
+ handleAuthStateChanged,
+ );
+ };
}, [location.pathname, navigate]);
useEffect(() => {
@@ -140,7 +128,12 @@ function AppContent() {
}
}, [location.pathname, loginRequired, navigate]);
- // Initial load
+ useEffect(() => {
+ if (dashboardAccessible && location.pathname === "/login") {
+ navigate("/dashboard/monitoring", { replace: true });
+ }
+ }, [dashboardAccessible, location.pathname, navigate]);
+
useEffect(() => {
if (!dashboardAccessible) {
return;
@@ -159,10 +152,9 @@ function AppContent() {
console.error("Failed to load initial data", e);
}
};
- load();
+ void load();
}, [dashboardAccessible, setInstances, setProfiles, setServerInfo]);
- // Subscribe to SSE events
useEffect(() => {
if (!dashboardAccessible) {
return;
@@ -193,11 +185,9 @@ function AppContent() {
applyMonitoringSnapshot,
memoryMetricsEnabled,
setAgents,
- setInstances,
- setProfiles,
]);
- if (!hasStoredToken && authMode === "probing") {
+ if (authMode === "probing") {
return (
<div className="flex min-h-screen items-center justify-center bg-bg-app px-4">
<div className="rounded-sm border border-border-subtle bg-black/10 px-4 py-3 text-sm text-text-muted">
@@ -207,7 +197,7 @@ function AppContent() {
);
}
- if (!hasStoredToken && authMode === "unreachable") {
+ if (authMode === "unreachable") {
const nextRetryDelay =
authRetryCount < AUTH_RETRY_DELAYS_MS.length
? AUTH_RETRY_DELAYS_MS[authRetryCount]
@@ -259,7 +249,7 @@ function AppContent() {
return (
<div className="dashboard-shell flex h-screen flex-col bg-bg-app">
- <NavBar />
+ <NavBar showLogout={authProtected} />
<main className="dashboard-grid flex-1 overflow-hidden">
<Routes>
<Route
diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsx
index 5927d6cb..c73f29ef 100644
--- a/dashboard/src/components/molecules/NavBar.tsx
+++ b/dashboard/src/components/molecules/NavBar.tsx
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { NavLink, useLocation, useNavigate } from "react-router-dom";
+import * as api from "../../services/api";
+import { dispatchAuthRequired } from "../../services/auth";
import { useAppStore } from "../../stores/useAppStore";
-import { clearStoredAuthToken, getStoredAuthToken } from "../../services/auth";
import "./NavBar.css";
interface Tab {
@@ -19,16 +20,16 @@ const tabs: Tab[] = [
interface NavBarProps {
onRefresh?: () => void;
+ showLogout?: boolean;
}
-export default function NavBar({ onRefresh }: NavBarProps) {
+export default function NavBar({ onRefresh, showLogout = false }: NavBarProps) {
const { serverInfo } = useAppStore();
const [refreshing, setRefreshing] = useState(false);
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const tabsRef = useRef<HTMLElement>(null);
const location = useLocation();
const navigate = useNavigate();
- const hasStoredToken = getStoredAuthToken() !== "";
// Close mobile menu on route change
useEffect(() => {
@@ -42,11 +43,15 @@ export default function NavBar({ onRefresh }: NavBarProps) {
setTimeout(() => setRefreshing(false), 800);
}, [onRefresh, refreshing]);
- const handleLogout = useCallback(() => {
- clearStoredAuthToken();
- setMobileMenuOpen(false);
- navigate("/login", { replace: true });
- }, [navigate]);
+ const handleLogout = useCallback(async () => {
+ try {
+ await api.logout();
+ setMobileMenuOpen(false);
+ dispatchAuthRequired("logout");
+ } catch (error) {
+ console.error("Logout failed", error);
+ }
+ }, []);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
@@ -123,11 +128,13 @@ export default function NavBar({ onRefresh }: NavBarProps) {
</span>
</div>
)}
- {hasStoredToken && (
+ {showLogout && (
<button
type="button"
className="mr-2 rounded-sm border border-transparent px-3 py-1.5 text-xs font-medium uppercase tracking-[0.08em] text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30"
- onClick={handleLogout}
+ onClick={() => {
+ void handleLogout();
+ }}
>
Logout
</button>
@@ -172,11 +179,13 @@ export default function NavBar({ onRefresh }: NavBarProps) {
{tab.label}
</NavLink>
))}
- {hasStoredToken && (
+ {showLogout && (
<button
type="button"
className="border-t border-border-subtle px-4 py-3 text-left text-sm font-medium text-text-secondary transition-colors duration-150 hover:bg-bg-elevated hover:text-text-primary"
- onClick={handleLogout}
+ onClick={() => {
+ void handleLogout();
+ }}
>
Logout
</button>
diff --git a/dashboard/src/components/screencast/ScreencastTile.test.tsx b/dashboard/src/components/screencast/ScreencastTile.test.tsx
index e6347eb1..836dd556 100644
--- a/dashboard/src/components/screencast/ScreencastTile.test.tsx
+++ b/dashboard/src/components/screencast/ScreencastTile.test.tsx
@@ -25,7 +25,6 @@ describe("ScreencastTile", () => {
"location",
new URL("https://pinchtab.com/dashboard/profiles"),
);
- window.localStorage.setItem("pinchtab.auth.token", "secret-token");
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
drawImage: vi.fn(),
} as unknown as CanvasRenderingContext2D);
@@ -44,7 +43,6 @@ describe("ScreencastTile", () => {
afterEach(() => {
vi.useRealTimers();
- window.localStorage.clear();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
@@ -62,7 +60,7 @@ describe("ScreencastTile", () => {
await waitFor(() => expect(webSocketMock).toHaveBeenCalledTimes(1));
expect(webSocketMock).toHaveBeenCalledWith(
- "wss://pinchtab.com/instances/inst_123/proxy/screencast?tabId=tab_456&quality=30&maxWidth=800&fps=1&token=secret-token",
+ "wss://pinchtab.com/instances/inst_123/proxy/screencast?tabId=tab_456&quality=30&maxWidth=800&fps=1",
);
});
diff --git a/dashboard/src/components/screencast/ScreencastTile.tsx b/dashboard/src/components/screencast/ScreencastTile.tsx
index 3aa78ee6..9b473f85 100644
--- a/dashboard/src/components/screencast/ScreencastTile.tsx
+++ b/dashboard/src/components/screencast/ScreencastTile.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { addTokenToUrl } from "../../services/auth";
+import { sameOriginUrl } from "../../services/auth";
import * as api from "../../services/api";
import ScreencastStatusBar, {
type ScreencastStatus,
@@ -147,7 +147,7 @@ export default function ScreencastTile({
maxWidth: String(maxWidth),
fps: String(localFps),
});
- const path = addTokenToUrl(
+ const path = sameOriginUrl(
`/instances/${encodeURIComponent(instanceId)}/proxy/screencast?${params.toString()}`,
);
const wsUrl = new URL(path, window.location.origin);
@@ -213,12 +213,14 @@ export default function ScreencastTile({
socket.onerror = () => {
if (!disposed) {
setStatus("error");
+ void api.handleRealtimeAuthFailure();
}
};
socket.onclose = () => {
if (!disposed) {
setStatus("error");
+ void api.handleRealtimeAuthFailure();
}
};
diff --git a/dashboard/src/pages/LoginPage.tsx b/dashboard/src/pages/LoginPage.tsx
index f76f8b8d..382b4f4a 100644
--- a/dashboard/src/pages/LoginPage.tsx
+++ b/dashboard/src/pages/LoginPage.tsx
@@ -3,7 +3,11 @@ import type { ComponentProps } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Button, Card } from "../components/atoms";
import * as api from "../services/api";
-import { setStoredAuthToken } from "../services/auth";
+import {
+ credentialUsername,
+ dispatchAuthStateChanged,
+ storeTokenCredential,
+} from "../services/auth";
export default function LoginPage() {
const navigate = useNavigate();
@@ -11,6 +15,7 @@ export default function LoginPage() {
const [token, setToken] = useState("");
const [error, setError] = useState("");
const [submitting, setSubmitting] = useState(false);
+ const savedCredentialUsername = credentialUsername();
const from =
(location.state as { from?: string } | null)?.from ||
@@ -23,8 +28,9 @@ export default function LoginPage() {
setSubmitting(true);
setError("");
try {
- await api.verifyBackendToken(token);
- setStoredAuthToken(token);
+ await api.login(token);
+ void storeTokenCredential(token);
+ dispatchAuthStateChanged();
navigate(from, { replace: true });
} catch (e) {
setError(e instanceof Error ? e.message : "Authentication failed");
@@ -47,14 +53,28 @@ export default function LoginPage() {
</p>
</div>
- <form className="space-y-4" onSubmit={handleSubmit}>
+ <form className="space-y-4" autoComplete="on" onSubmit={handleSubmit}>
+ <input
+ type="text"
+ name="username"
+ autoComplete="username"
+ value={savedCredentialUsername}
+ readOnly
+ tabIndex={-1}
+ aria-hidden="true"
+ className="sr-only"
+ />
<input
type="password"
autoFocus
+ name="password"
+ autoComplete="current-password"
value={token}
onChange={(e) => setToken(e.target.value)}
className="w-full rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
placeholder="Paste bearer token"
+ spellCheck={false}
+ autoCapitalize="none"
/>
{error && (
<div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs leading-5 text-destructive">
diff --git a/dashboard/src/pages/SettingsPage.test.tsx b/dashboard/src/pages/SettingsPage.test.tsx
new file mode 100644
index 00000000..54a2cc4e
--- /dev/null
+++ b/dashboard/src/pages/SettingsPage.test.tsx
@@ -0,0 +1,68 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter } from "react-router-dom";
+import SettingsPage from "./SettingsPage";
+import { useAppStore } from "../stores/useAppStore";
+import { defaultBackendConfig, type BackendConfigState } from "../types";
+
+vi.mock("../services/api", () => ({
+ fetchBackendConfig: vi.fn(),
+ fetchHealth: vi.fn(),
+ saveBackendConfig: vi.fn(),
+ elevate: vi.fn(),
+ isApiError: vi.fn(() => false),
+}));
+
+function renderSettingsPage() {
+ return render(
+ <MemoryRouter>
+ <SettingsPage />
+ </MemoryRouter>,
+ );
+}
+
+function makeConfigState(): BackendConfigState {
+ return {
+ config: structuredClone(defaultBackendConfig),
+ configPath: "/tmp/config.json",
+ tokenConfigured: true,
+ restartRequired: false,
+ restartReasons: [],
+ };
+}
+
+describe("SettingsPage", () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ const api = await import("../services/api");
+ const configState = makeConfigState();
+ vi.mocked(api.fetchBackendConfig).mockResolvedValue(configState);
+ vi.mocked(api.fetchHealth).mockRejectedValue(new Error("skip health"));
+ vi.mocked(api.saveBackendConfig).mockResolvedValue(configState);
+
+ useAppStore.setState({
+ settings: useAppStore.getState().settings,
+ serverInfo: null,
+ });
+ });
+
+ it("shows token status without exposing token management controls", async () => {
+ renderSettingsPage();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: /Network & Attach/i }),
+ );
+
+ expect(
+ screen.getByText(
+ "Token configured. Manage rotation through the CLI or config file; the current value is never returned by the server.",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByLabelText("API token")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Generate" }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText(/No API token is set/i)).not.toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index e387a367..dfbf2cdc 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -1,7 +1,9 @@
+import type { FormEvent } from "react";
import { useEffect, useMemo, useState } from "react";
import { useAppStore } from "../stores/useAppStore";
-import { Button, Card } from "../components/atoms";
+import { Button, Card, Input, Modal } from "../components/atoms";
import * as api from "../services/api";
+import { credentialUsername, storeTokenCredential } from "../services/auth";
import type {
BackendConfig,
BackendConfigState,
@@ -21,6 +23,8 @@ type SectionId =
| "browser"
| "timeouts";
+type PendingElevatedAction = "save" | null;
+
const sections: Array<{
id: SectionId;
label: string;
@@ -76,6 +80,13 @@ const sections: Array<{
const fieldClass =
"w-full rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20";
+function backendSaveNotice(state: BackendConfigState | null): string {
+ if (state?.restartRequired) {
+ return "Backend config saved. Dynamic changes were applied where possible. Restart advised for server-level changes.";
+ }
+ return "Backend config saved. Dynamic changes were applied where possible.";
+}
+
const selectClass =
"rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20";
@@ -179,9 +190,14 @@ export default function SettingsPage() {
);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
- const [generatingToken, setGeneratingToken] = useState(false);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
+ const [pendingElevatedAction, setPendingElevatedAction] =
+ useState<PendingElevatedAction>(null);
+ const [elevationToken, setElevationToken] = useState("");
+ const [elevationError, setElevationError] = useState("");
+ const [elevating, setElevating] = useState(false);
+ const savedCredentialUsername = useMemo(() => credentialUsername(), []);
useEffect(() => {
setLocalSettings(settings);
@@ -217,7 +233,7 @@ export default function SettingsPage() {
[localSettings, settings],
);
- const hasBackendChanges = useMemo(
+ const hasBackendConfigChanges = useMemo(
() =>
Boolean(
backendConfig &&
@@ -226,6 +242,7 @@ export default function SettingsPage() {
),
[backendConfig, backendState],
);
+ const hasBackendChanges = hasBackendConfigChanges;
const hasChanges = hasDashboardChanges || hasBackendChanges;
const restartRequired =
@@ -241,9 +258,7 @@ export default function SettingsPage() {
backendConfig.security.allowUpload,
].some(Boolean)
: false;
- const apiTokenMissing = backendConfig
- ? backendConfig.server.token.trim() === ""
- : false;
+ const apiTokenMissing = !backendState?.tokenConfigured;
const idpiEnabled = backendConfig
? backendConfig.security.idpi.enabled
: false;
@@ -276,26 +291,6 @@ export default function SettingsPage() {
setNotice("");
};
- const handleGenerateToken = async () => {
- if (!backendConfig) {
- return;
- }
- setGeneratingToken(true);
- setError("");
- setNotice("");
- try {
- const token = await api.generateBackendToken();
- updateBackendSection("server", { token });
- setNotice("Generated a new API token. Save changes to persist it.");
- } catch (e) {
- const message =
- e instanceof Error ? e.message : "Failed to generate API token";
- setError(message);
- } finally {
- setGeneratingToken(false);
- }
- };
-
const handleSave = async () => {
if (!hasChanges || !backendConfig) return;
@@ -304,19 +299,21 @@ export default function SettingsPage() {
setNotice("");
try {
+ let latestBackendState = backendState;
+
if (hasDashboardChanges) {
setSettings(localSettings);
}
- if (hasBackendChanges) {
+ if (hasBackendConfigChanges) {
const saved = await api.saveBackendConfig(backendConfig);
+ latestBackendState = saved;
setBackendState(saved);
setBackendConfig(saved.config);
- setNotice(
- saved.restartRequired
- ? "Backend config saved. Dynamic changes were applied where possible. Restart advised for server-level changes."
- : "Backend config saved. Dynamic changes were applied where possible.",
- );
+ }
+
+ if (hasBackendChanges) {
+ setNotice(backendSaveNotice(latestBackendState));
}
const health = await api.fetchHealth().catch(() => null);
@@ -328,6 +325,12 @@ export default function SettingsPage() {
setNotice("Dashboard preferences saved in this browser.");
}
} catch (e) {
+ if (api.isApiError(e) && e.code === "elevation_required") {
+ setElevationToken("");
+ setElevationError("");
+ setPendingElevatedAction("save");
+ return;
+ }
const message =
e instanceof Error ? e.message : "Failed to save settings";
setError(message);
@@ -336,6 +339,43 @@ export default function SettingsPage() {
}
};
+ const closeElevationPrompt = () => {
+ if (elevating) {
+ return;
+ }
+ setPendingElevatedAction(null);
+ setElevationToken("");
+ setElevationError("");
+ };
+
+ const handleElevationSubmit = async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ if (!pendingElevatedAction) {
+ return;
+ }
+
+ const action = pendingElevatedAction;
+ setElevating(true);
+ setElevationError("");
+
+ try {
+ await api.elevate(elevationToken);
+ void storeTokenCredential(elevationToken);
+ setPendingElevatedAction(null);
+ setElevationToken("");
+
+ if (action === "save") {
+ await handleSave();
+ }
+ } catch (e) {
+ const message =
+ e instanceof Error ? e.message : "Failed to verify API token";
+ setElevationError(message);
+ } finally {
+ setElevating(false);
+ }
+ };
+
return (
<div className="flex h-full flex-col overflow-hidden">
<div className="sticky top-0 z-10 border-b border-border-subtle bg-bg-surface/95 px-4 py-3 backdrop-blur">
@@ -387,6 +427,70 @@ export default function SettingsPage() {
</div>
)}
</div>
+ <Modal
+ open={pendingElevatedAction !== null}
+ onClose={closeElevationPrompt}
+ title="Confirm admin action"
+ actions={
+ <>
+ <Button
+ variant="secondary"
+ onClick={closeElevationPrompt}
+ disabled={elevating}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ type="submit"
+ form="settings-elevation-form"
+ disabled={elevating || elevationToken.trim() === ""}
+ >
+ {elevating ? "Verifying..." : "Continue"}
+ </Button>
+ </>
+ }
+ >
+ <form
+ id="settings-elevation-form"
+ className="space-y-4"
+ autoComplete="on"
+ onSubmit={handleElevationSubmit}
+ >
+ <p className="leading-6 text-text-muted">
+ Re-enter the API token to save backend configuration changes. The
+ elevated session stays active briefly so you do not need to repeat
+ this for every admin action.
+ </p>
+ <input
+ type="text"
+ name="username"
+ autoComplete="username"
+ value={savedCredentialUsername}
+ readOnly
+ tabIndex={-1}
+ aria-hidden="true"
+ className="sr-only"
+ />
+ <Input
+ type="password"
+ name="password"
+ autoComplete="current-password"
+ label="API token"
+ placeholder="Paste API token"
+ value={elevationToken}
+ onChange={(e) => setElevationToken(e.target.value)}
+ autoFocus
+ spellCheck={false}
+ autoCapitalize="none"
+ />
+ {elevationError && (
+ <div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs leading-5 text-destructive">
+ {elevationError}
+ </div>
+ )}
+ </form>
+ </Modal>
<div className="flex flex-1 flex-col gap-6 overflow-hidden p-4 lg:flex-row lg:p-6">
<aside className="flex w-full shrink-0 flex-col gap-4 overflow-y-auto lg:w-72">
@@ -1137,7 +1241,7 @@ export default function SettingsPage() {
{activeSection === "network" && (
<SectionCard
title="Network & Attach"
- description="Port and bind changes require a restart. Token changes update request auth immediately because middleware reads runtime config live."
+ description="Port and bind changes require a restart. API token management is handled outside the dashboard."
>
<SettingRow
label="Server port"
@@ -1165,34 +1269,21 @@ export default function SettingsPage() {
</SettingRow>
<SettingRow
label="API token"
- description="Bearer token required by authenticated requests when set. Leaving this empty means reachable clients are unauthenticated."
+ description="Bearer token required by authenticated requests when set. The dashboard never returns it and does not manage it."
>
<div className="space-y-2">
- <div className="flex gap-2">
- <input
- value={backendConfig.server.token}
- onChange={(e) =>
- updateBackendSection("server", {
- token: e.target.value,
- })
- }
- className={fieldClass}
- />
- <Button
- type="button"
- variant="secondary"
- onClick={handleGenerateToken}
- disabled={generatingToken}
- >
- {generatingToken ? "Generating..." : "Generate"}
- </Button>
+ <div className="text-xs leading-5 text-text-muted">
+ {backendState?.tokenConfigured
+ ? "Token configured. Manage rotation through the CLI or config file; the current value is never returned by the server."
+ : "No token configured. Set one through the CLI or config file."}
</div>
{apiTokenMissing && (
<div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs leading-5 text-destructive">
No API token is set. Anyone who can reach this server
can access exposed endpoints. Keep it on trusted local
- networks only, or set a strong token. You are
- responsible for protecting access.
+ networks only, or configure a strong token through the
+ CLI or config file. You are responsible for protecting
+ access.
</div>
)}
</div>
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index db811f74..56ecfb61 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -24,45 +24,63 @@ import {
normalizeDashboardServerInfo,
normalizeMonitoringSnapshot,
} from "../types";
-import {
- addTokenToUrl,
- dispatchAuthRequired,
- getStoredAuthToken,
-} from "./auth";
+import { dispatchAuthRequired, sameOriginUrl } from "./auth";
const BASE = ""; // Uses proxy in dev
type RequestMeta = {
- authToken?: string;
suppressAuthRedirect?: boolean;
};
+export class ApiError extends Error {
+ status: number;
+ code?: string;
+
+ constructor(message: string, status: number, code?: string) {
+ super(message);
+ this.name = "ApiError";
+ this.status = status;
+ this.code = code;
+ }
+}
+
+export function isApiError(error: unknown): error is ApiError {
+ return error instanceof ApiError;
+}
+
+async function parseError(
+ res: Response,
+): Promise<{ code?: string; error?: string }> {
+ return (await res
+ .json()
+ .catch(() => ({ code: "", error: res.statusText }))) as {
+ code?: string;
+ error?: string;
+ };
+}
+
+function handleUnauthorized(meta?: RequestMeta, reason?: string): void {
+ if (meta?.suppressAuthRedirect || typeof window === "undefined") {
+ return;
+ }
+ dispatchAuthRequired(reason || "unauthorized");
+}
+
async function request<T>(
url: string,
options?: RequestInit,
meta?: RequestMeta,
): Promise<T> {
- const headers = new Headers(options?.headers ?? {});
- const token = meta?.authToken?.trim() || getStoredAuthToken();
- if (token) {
- headers.set("Authorization", `Bearer ${token}`);
- }
-
const res = await fetch(BASE + url, {
...options,
- headers,
+ credentials: "same-origin",
});
if (!res.ok) {
- const err = await res.json().catch(() => ({ error: res.statusText }));
- if (
- res.status === 401 &&
- !meta?.suppressAuthRedirect &&
- typeof window !== "undefined"
- ) {
- window.localStorage.removeItem("pinchtab.auth.token");
- dispatchAuthRequired(err.code || "unauthorized");
+ const err = await parseError(res);
+ if (res.status === 401) {
+ handleUnauthorized(meta, err.code);
}
- throw new Error(err.error || "Request failed");
+ throw new ApiError(err.error || "Request failed", res.status, err.code);
}
return res.json();
}
@@ -72,27 +90,16 @@ async function requestText(
options?: RequestInit,
meta?: RequestMeta,
): Promise<string> {
- const headers = new Headers(options?.headers ?? {});
- const token = meta?.authToken?.trim() || getStoredAuthToken();
- if (token) {
- headers.set("Authorization", `Bearer ${token}`);
- }
-
const res = await fetch(BASE + url, {
...options,
- headers,
+ credentials: "same-origin",
});
if (!res.ok) {
- const err = await res.json().catch(() => ({ error: res.statusText }));
- if (
- res.status === 401 &&
- !meta?.suppressAuthRedirect &&
- typeof window !== "undefined"
- ) {
- window.localStorage.removeItem("pinchtab.auth.token");
- dispatchAuthRequired(err.code || "unauthorized");
+ const err = await parseError(res);
+ if (res.status === 401) {
+ handleUnauthorized(meta, err.code);
}
- throw new Error(err.error || "Request failed");
+ throw new ApiError(err.error || "Request failed", res.status, err.code);
}
return res.text();
}
@@ -102,27 +109,16 @@ async function requestBlob(
options?: RequestInit,
meta?: RequestMeta,
): Promise<Blob> {
- const headers = new Headers(options?.headers ?? {});
- const token = meta?.authToken?.trim() || getStoredAuthToken();
- if (token) {
- headers.set("Authorization", `Bearer ${token}`);
- }
-
const res = await fetch(BASE + url, {
...options,
- headers,
+ credentials: "same-origin",
});
if (!res.ok) {
- const err = await res.json().catch(() => ({ error: res.statusText }));
- if (
- res.status === 401 &&
- !meta?.suppressAuthRedirect &&
- typeof window !== "undefined"
- ) {
- window.localStorage.removeItem("pinchtab.auth.token");
- dispatchAuthRequired(err.code || "unauthorized");
+ const err = await parseError(res);
+ if (res.status === 401) {
+ handleUnauthorized(meta, err.code);
}
- throw new Error(err.error || "Request failed");
+ throw new ApiError(err.error || "Request failed", res.status, err.code);
}
return res.blob();
}
@@ -242,7 +238,7 @@ export function subscribeToInstanceLogs(
id: string,
handlers: { onLogs?: (logs: string) => void },
): () => void {
- const url = addTokenToUrl(`/instances/${encodeURIComponent(id)}/logs/stream`);
+ const url = sameOriginUrl(`/instances/${encodeURIComponent(id)}/logs/stream`);
const es = new EventSource(url);
es.addEventListener("log", (e) => {
@@ -255,9 +251,7 @@ export function subscribeToInstanceLogs(
});
es.onerror = () => {
- if (!getStoredAuthToken()) {
- dispatchAuthRequired("missing_token");
- }
+ void handleRealtimeAuthFailure();
};
const cleanup = () => es.close();
@@ -306,45 +300,72 @@ export async function fetchActivity(
}
export async function probeBackendAuth(): Promise<{
- requiresAuth: boolean;
+ mode: "open" | "authenticated" | "required";
health?: DashboardServerInfo;
}> {
- const res = await fetch(BASE + "/health");
+ const res = await fetch(BASE + "/health", {
+ credentials: "same-origin",
+ });
if (res.ok) {
+ const health = normalizeDashboardServerInfo(
+ (await res.json()) as DashboardServerInfo,
+ );
return {
- requiresAuth: false,
- health: normalizeDashboardServerInfo(
- (await res.json()) as DashboardServerInfo,
- ),
+ mode: health.authRequired ? "authenticated" : "open",
+ health,
};
}
- const err = (await res
- .json()
- .catch(() => ({ code: "", error: res.statusText }))) as {
- code?: string;
- error?: string;
- };
+ const err = await parseError(res);
if (
res.status === 401 &&
(err.code === "missing_token" ||
err.code === "bad_token" ||
err.error === "unauthorized")
) {
- return { requiresAuth: true };
+ return { mode: "required" };
}
throw new Error(err.error || "Request failed");
}
-export async function verifyBackendToken(
- token: string,
-): Promise<DashboardServerInfo> {
- return normalizeDashboardServerInfo(
- await request<DashboardServerInfo>("/health", undefined, {
- authToken: token,
+export async function login(token: string): Promise<void> {
+ await request<{ status: string }>(
+ "/api/auth/login",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ },
+ {
suppressAuthRedirect: true,
- }),
+ },
+ );
+}
+
+export async function logout(): Promise<void> {
+ await request<{ status: string }>(
+ "/api/auth/logout",
+ {
+ method: "POST",
+ },
+ {
+ suppressAuthRedirect: true,
+ },
+ );
+}
+
+export async function elevate(token: string): Promise<void> {
+ await request<{ status: string }>(
+ "/api/auth/elevate",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ },
+ {
+ suppressAuthRedirect: true,
+ },
);
}
@@ -366,13 +387,6 @@ export async function saveBackendConfig(
);
}
-export async function generateBackendToken(): Promise<string> {
- const res = await request<{ token: string }>("/api/config/generate-token", {
- method: "POST",
- });
- return res.token;
-}
-
// SSE Events — endpoint is /api/events
export interface SystemEvent {
type: "instance.started" | "instance.stopped" | "instance.error";
@@ -397,7 +411,7 @@ export function subscribeToEvents(
handlers: EventHandler,
options?: { includeMemory?: boolean },
): () => void {
- const url = addTokenToUrl(
+ const url = sameOriginUrl(
options?.includeMemory ? "/api/events?memory=1" : "/api/events",
);
const es = new EventSource(url);
@@ -442,9 +456,7 @@ export function subscribeToEvents(
// Suppress connection errors (expected on page reload/navigation)
es.onerror = () => {
- if (!getStoredAuthToken()) {
- dispatchAuthRequired("missing_token");
- }
+ void handleRealtimeAuthFailure();
};
// Clean up on page unload to prevent ERR_INCOMPLETE_CHUNKED_ENCODING
@@ -456,3 +468,14 @@ export function subscribeToEvents(
es.close();
};
}
+
+export async function handleRealtimeAuthFailure(): Promise<void> {
+ try {
+ const result = await probeBackendAuth();
+ if (result.mode === "required") {
+ dispatchAuthRequired("missing_token");
+ }
+ } catch {
+ // ignore transient network failures
+ }
+}
diff --git a/dashboard/src/services/auth.test.ts b/dashboard/src/services/auth.test.ts
new file mode 100644
index 00000000..f18777af
--- /dev/null
+++ b/dashboard/src/services/auth.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ AUTH_REQUIRED_EVENT,
+ AUTH_STATE_CHANGED_EVENT,
+ credentialUsername,
+ dispatchAuthRequired,
+ dispatchAuthStateChanged,
+ sameOriginUrl,
+} from "./auth";
+
+describe("auth helpers", () => {
+ it("dispatches the auth-required event with a reason", () => {
+ const handler = vi.fn();
+ window.addEventListener(AUTH_REQUIRED_EVENT, handler);
+
+ dispatchAuthRequired("missing_token");
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ const event = handler.mock.calls[0]?.[0] as CustomEvent<{ reason: string }>;
+ expect(event.detail.reason).toBe("missing_token");
+ window.removeEventListener(AUTH_REQUIRED_EVENT, handler);
+ });
+
+ it("dispatches the auth-state-changed event", () => {
+ const handler = vi.fn();
+ window.addEventListener(AUTH_STATE_CHANGED_EVENT, handler);
+
+ dispatchAuthStateChanged();
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ window.removeEventListener(AUTH_STATE_CHANGED_EVENT, handler);
+ });
+
+ it("keeps dashboard URLs same-origin without appending auth state", () => {
+ vi.stubGlobal("location", new URL("https://pinchtab.com/dashboard"));
+
+ expect(sameOriginUrl("/api/events?memory=1")).toBe("/api/events?memory=1");
+
+ vi.unstubAllGlobals();
+ });
+
+ it("builds a stable credential username for password managers", () => {
+ vi.stubGlobal("location", new URL("https://pinchtab.example/dashboard"));
+
+ expect(credentialUsername()).toBe("[email protected]");
+
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/dashboard/src/services/auth.ts b/dashboard/src/services/auth.ts
index 04ab3ddc..47239c1e 100644
--- a/dashboard/src/services/auth.ts
+++ b/dashboard/src/services/auth.ts
@@ -1,17 +1,6 @@
-const AUTH_TOKEN_KEY = "pinchtab.auth.token";
const AUTH_REQUIRED_EVENT = "pinchtab-auth-required";
-
-export function getStoredAuthToken(): string {
- return window.localStorage.getItem(AUTH_TOKEN_KEY)?.trim() ?? "";
-}
-
-export function setStoredAuthToken(token: string): void {
- window.localStorage.setItem(AUTH_TOKEN_KEY, token.trim());
-}
-
-export function clearStoredAuthToken(): void {
- window.localStorage.removeItem(AUTH_TOKEN_KEY);
-}
+const AUTH_STATE_CHANGED_EVENT = "pinchtab-auth-state-changed";
+const CREDENTIAL_USERNAME_PREFIX = "pinchtab";
export function dispatchAuthRequired(reason: string): void {
window.dispatchEvent(
@@ -21,15 +10,55 @@ export function dispatchAuthRequired(reason: string): void {
);
}
-export function addTokenToUrl(url: string, token?: string): string {
- const authToken = (token ?? getStoredAuthToken()).trim();
- if (!authToken) {
- return url;
- }
+export function dispatchAuthStateChanged(): void {
+ window.dispatchEvent(new Event(AUTH_STATE_CHANGED_EVENT));
+}
+export function sameOriginUrl(url: string): string {
const absolute = new URL(url, window.location.origin);
- absolute.searchParams.set("token", authToken);
return absolute.pathname + absolute.search;
}
-export { AUTH_REQUIRED_EVENT };
+export function credentialUsername(): string {
+ if (typeof window === "undefined") {
+ return CREDENTIAL_USERNAME_PREFIX;
+ }
+ return `${CREDENTIAL_USERNAME_PREFIX}@${window.location.host}`;
+}
+
+type PasswordCredentialConstructor = new (data: {
+ id: string;
+ password: string;
+ name?: string;
+}) => Credential;
+
+export async function storeTokenCredential(token: string): Promise<void> {
+ const trimmed = token.trim();
+ if (
+ trimmed === "" ||
+ typeof window === "undefined" ||
+ navigator.credentials?.store === undefined
+ ) {
+ return;
+ }
+
+ const PasswordCredentialImpl = (
+ window as Window & { PasswordCredential?: PasswordCredentialConstructor }
+ ).PasswordCredential;
+ if (!PasswordCredentialImpl) {
+ return;
+ }
+
+ try {
+ const credential = new PasswordCredentialImpl({
+ id: credentialUsername(),
+ password: trimmed,
+ name: `PinchTab ${window.location.host}`,
+ });
+ await navigator.credentials.store(credential);
+ } catch {
+ // Ignore password-manager failures and continue with the session flow.
+ }
+}
+
+export { AUTH_REQUIRED_EVENT, AUTH_STATE_CHANGED_EVENT };
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 2f25456f..09b00ab7 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -31,6 +31,7 @@ export interface DashboardServerInfo {
mode: string;
version: string;
uptime: number;
+ authRequired?: boolean;
profiles: number;
instances: number;
agents: number;
@@ -146,6 +147,7 @@ export interface BackendConfig {
export interface BackendConfigState {
config: BackendConfig;
configPath: string;
+ tokenConfigured: boolean;
restartRequired: boolean;
restartReasons: string[];
}
@@ -285,6 +287,7 @@ export function normalizeBackendConfigState(
return {
config: normalizeBackendConfig(input.config),
configPath: input.configPath ?? "",
+ tokenConfigured: input.tokenConfigured ?? false,
restartRequired: input.restartRequired ?? false,
restartReasons: input.restartReasons ?? [],
};
@@ -295,6 +298,7 @@ export function normalizeDashboardServerInfo(
): DashboardServerInfo {
return {
...input,
+ authRequired: input.authRequired ?? false,
restartRequired: input.restartRequired ?? false,
restartReasons: input.restartReasons ?? [],
};
diff --git a/docs/endpoints.md b/docs/endpoints.md
index d9ad2413..f1f1abb9 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -194,5 +194,6 @@ Task body: `{"agentId": "...", "action": "snapshot", "tabId": "..."}`
```
GET /api/config # Get current configuration
PUT /api/config # Update configuration
-POST /api/config/generate-token # Generate new auth token
```
+
+`server.token` is write-only and managed outside the dashboard API via CLI or config file updates.
diff --git a/docs/guides/security.md b/docs/guides/security.md
index f77661af..18f61a25 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -42,12 +42,21 @@ Binding to loopback reduces who can reach the API. Tokens reduce who can use it
## API Token
-`server.token` is the bearer token expected by the server. When it is set, requests must send:
+`server.token` is the master API token.
+
+For non-browser clients, requests should send:
```http
Authorization: Bearer <token>
```
+The browser dashboard uses a different flow:
+
+1. the user enters the token once on the login page
+2. the server exchanges it for a same-origin `HttpOnly` session cookie
+3. sensitive dashboard actions can require token re-entry for short-lived
+ elevation
+
Why this matters:
- without a token, any process that can reach the server can call the API
diff --git a/internal/activity/api.go b/internal/activity/api.go
index 704c1a45..c21076d0 100644
--- a/internal/activity/api.go
+++ b/internal/activity/api.go
@@ -7,7 +7,7 @@ import (
"time"
apiTypes "github.com/pinchtab/pinchtab/internal/api/types"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func RegisterHandlers(mux *http.ServeMux, rec Recorder) {
@@ -18,13 +18,13 @@ func RegisterHandlers(mux *http.ServeMux, rec Recorder) {
mux.HandleFunc("GET /api/activity", func(w http.ResponseWriter, r *http.Request) {
filter, err := filterFromRequest(r)
if err != nil {
- web.ErrorCode(w, http.StatusBadRequest, "bad_filter", err.Error(), false, nil)
+ httpx.ErrorCode(w, http.StatusBadRequest, "bad_filter", err.Error(), false, nil)
return
}
events, err := rec.Query(filter)
if err != nil {
- web.Error(w, http.StatusInternalServerError, err)
+ httpx.Error(w, http.StatusInternalServerError, err)
return
}
@@ -56,7 +56,7 @@ func RegisterHandlers(mux *http.ServeMux, rec Recorder) {
})
}
- web.JSON(w, http.StatusOK, resp)
+ httpx.JSON(w, http.StatusOK, resp)
})
}
diff --git a/internal/activity/context.go b/internal/activity/context.go
index f5f8d9bb..be030b28 100644
--- a/internal/activity/context.go
+++ b/internal/activity/context.go
@@ -2,13 +2,13 @@ package activity
import (
"context"
- "net"
"net/http"
"strings"
"sync"
"time"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
const (
@@ -52,7 +52,7 @@ func Middleware(rec Recorder, source string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
- sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
+ sw := &httpx.StatusWriter{ResponseWriter: w, Code: 200}
state := &requestState{
event: Event{
Timestamp: start.UTC(),
@@ -201,16 +201,7 @@ func actorIDFor(r *http.Request) string {
if actorID := strings.TrimSpace(r.Header.Get(HeaderPTActorID)); actorID != "" {
return actorID
}
- token := strings.TrimSpace(r.URL.Query().Get("token"))
- if token == "" {
- auth := strings.TrimSpace(r.Header.Get("Authorization"))
- if strings.HasPrefix(strings.ToLower(auth), "bearer ") {
- token = strings.TrimSpace(auth[7:])
- } else {
- token = auth
- }
- }
- return FingerprintToken(token)
+ return FingerprintToken(authn.TokenFromRequest(r))
}
func agentIDFor(r *http.Request) string {
@@ -223,14 +214,7 @@ func agentIDFor(r *http.Request) string {
}
func remoteAddrFor(r *http.Request) string {
- if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {
- return strings.TrimSpace(strings.Split(xff, ",")[0])
- }
- host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
- if err == nil && host != "" {
- return host
- }
- return strings.TrimSpace(r.RemoteAddr)
+ return authn.ClientIP(r)
}
func (s *requestState) snapshot() Event {
diff --git a/internal/authn/audit.go b/internal/authn/audit.go
new file mode 100644
index 00000000..3d4d4603
--- /dev/null
+++ b/internal/authn/audit.go
@@ -0,0 +1,38 @@
+package authn
+
+import (
+ "log/slog"
+ "net/http"
+ "strings"
+)
+
+// AuditLog records security-sensitive actions without logging raw credentials
+// or session identifiers.
+func AuditLog(r *http.Request, event string, attrs ...any) {
+ slog.Info("audit", append(auditAttrs(r, event), attrs...)...)
+}
+
+// AuditWarn records denied or suspicious security-relevant actions.
+func AuditWarn(r *http.Request, event string, attrs ...any) {
+ slog.Warn("audit", append(auditAttrs(r, event), attrs...)...)
+}
+
+func auditAttrs(r *http.Request, event string) []any {
+ attrs := []any{"event", strings.TrimSpace(event)}
+ if r == nil {
+ return attrs
+ }
+ attrs = append(attrs,
+ "requestId", strings.TrimSpace(r.Header.Get("X-Request-Id")),
+ "method", r.Method,
+ "path", r.URL.Path,
+ "clientIP", ClientIP(r),
+ )
+ if creds := CredentialsFromRequest(r); creds.Method != MethodNone {
+ attrs = append(attrs, "authMethod", string(creds.Method))
+ }
+ if origin := strings.TrimSpace(r.Header.Get("Origin")); origin != "" {
+ attrs = append(attrs, "origin", origin)
+ }
+ return attrs
+}
diff --git a/internal/authn/cookie.go b/internal/authn/cookie.go
new file mode 100644
index 00000000..0cfab314
--- /dev/null
+++ b/internal/authn/cookie.go
@@ -0,0 +1,41 @@
+package authn
+
+import (
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// SetSessionCookie stores the opaque dashboard session id in an HttpOnly
+// same-site cookie so browser APIs can authenticate without exposing the
+// underlying bearer token to JavaScript.
+func SetSessionCookie(w http.ResponseWriter, _ *http.Request, sessionID string, maxLifetime time.Duration) {
+ if maxLifetime <= 0 {
+ maxLifetime = DefaultSessionMaxLifetime
+ }
+ http.SetCookie(w, &http.Cookie{
+ Name: CookieName,
+ Value: url.QueryEscape(strings.TrimSpace(sessionID)),
+ Path: "/",
+ HttpOnly: true,
+ Secure: true,
+ SameSite: http.SameSiteStrictMode,
+ MaxAge: int(maxLifetime.Seconds()),
+ Expires: time.Now().Add(maxLifetime),
+ })
+}
+
+// ClearSessionCookie expires the dashboard auth cookie.
+func ClearSessionCookie(w http.ResponseWriter, _ *http.Request) {
+ http.SetCookie(w, &http.Cookie{
+ Name: CookieName,
+ Value: "",
+ Path: "/",
+ HttpOnly: true,
+ Secure: true,
+ SameSite: http.SameSiteStrictMode,
+ MaxAge: -1,
+ Expires: time.Unix(0, 0),
+ })
+}
diff --git a/internal/authn/rate_limit.go b/internal/authn/rate_limit.go
new file mode 100644
index 00000000..044bd510
--- /dev/null
+++ b/internal/authn/rate_limit.go
@@ -0,0 +1,132 @@
+package authn
+
+import (
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ DefaultLoginRateLimitWindow = 10 * time.Minute
+ DefaultLoginRateLimitMaxAttempt = 10
+)
+
+type AttemptLimiterConfig struct {
+ Window time.Duration
+ MaxAttempts int
+}
+
+type AttemptLimiter struct {
+ mu sync.Mutex
+ window time.Duration
+ maxAttempts int
+ attempts map[string][]time.Time
+ now func() time.Time
+}
+
+func NewAttemptLimiter(cfg AttemptLimiterConfig) *AttemptLimiter {
+ window := cfg.Window
+ if window <= 0 {
+ window = DefaultLoginRateLimitWindow
+ }
+ maxAttempts := cfg.MaxAttempts
+ if maxAttempts <= 0 {
+ maxAttempts = DefaultLoginRateLimitMaxAttempt
+ }
+ return &AttemptLimiter{
+ window: window,
+ maxAttempts: maxAttempts,
+ attempts: make(map[string][]time.Time),
+ now: time.Now,
+ }
+}
+
+func (l *AttemptLimiter) Allow(key string) (bool, time.Duration) {
+ if l == nil {
+ return true, 0
+ }
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return true, 0
+ }
+
+ now := l.now()
+
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ filtered := l.pruneLocked(key, now)
+ if len(filtered) < l.maxAttempts {
+ return true, 0
+ }
+
+ retryAfter := l.window - now.Sub(filtered[0])
+ if retryAfter < 0 {
+ retryAfter = 0
+ }
+ return false, retryAfter
+}
+
+func (l *AttemptLimiter) RecordFailure(key string) {
+ if l == nil {
+ return
+ }
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return
+ }
+
+ now := l.now()
+
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ filtered := l.pruneLocked(key, now)
+ l.attempts[key] = append(filtered, now)
+}
+
+func (l *AttemptLimiter) Reset(key string) {
+ if l == nil {
+ return
+ }
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return
+ }
+ l.mu.Lock()
+ delete(l.attempts, key)
+ l.mu.Unlock()
+}
+
+func (l *AttemptLimiter) Window() time.Duration {
+ if l == nil {
+ return DefaultLoginRateLimitWindow
+ }
+ return l.window
+}
+
+func (l *AttemptLimiter) MaxAttempts() int {
+ if l == nil {
+ return DefaultLoginRateLimitMaxAttempt
+ }
+ return l.maxAttempts
+}
+
+func (l *AttemptLimiter) pruneLocked(key string, now time.Time) []time.Time {
+ hits := l.attempts[key]
+ if len(hits) == 0 {
+ return nil
+ }
+ filtered := hits[:0]
+ for _, ts := range hits {
+ if now.Sub(ts) < l.window {
+ filtered = append(filtered, ts)
+ }
+ }
+ if len(filtered) == 0 {
+ delete(l.attempts, key)
+ return nil
+ }
+ l.attempts[key] = filtered
+ return filtered
+}
diff --git a/internal/authn/rate_limit_test.go b/internal/authn/rate_limit_test.go
new file mode 100644
index 00000000..5e87bcdf
--- /dev/null
+++ b/internal/authn/rate_limit_test.go
@@ -0,0 +1,55 @@
+package authn
+
+import (
+ "testing"
+ "time"
+)
+
+func TestAttemptLimiterBlocksAfterMaxFailures(t *testing.T) {
+ limiter := NewAttemptLimiter(AttemptLimiterConfig{
+ Window: time.Minute,
+ MaxAttempts: 2,
+ })
+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
+ limiter.now = func() time.Time { return now }
+
+ if allowed, _ := limiter.Allow("127.0.0.1"); !allowed {
+ t.Fatal("expected first check to be allowed")
+ }
+
+ limiter.RecordFailure("127.0.0.1")
+ limiter.RecordFailure("127.0.0.1")
+
+ allowed, retryAfter := limiter.Allow("127.0.0.1")
+ if allowed {
+ t.Fatal("expected limiter to block after max failures")
+ }
+ if retryAfter <= 0 {
+ t.Fatalf("retryAfter = %v, want > 0", retryAfter)
+ }
+}
+
+func TestAttemptLimiterResetsAndExpires(t *testing.T) {
+ limiter := NewAttemptLimiter(AttemptLimiterConfig{
+ Window: time.Minute,
+ MaxAttempts: 1,
+ })
+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
+ limiter.now = func() time.Time { return now }
+
+ limiter.RecordFailure("127.0.0.1")
+ if allowed, _ := limiter.Allow("127.0.0.1"); allowed {
+ t.Fatal("expected limiter to block after recorded failure")
+ }
+
+ limiter.Reset("127.0.0.1")
+ if allowed, _ := limiter.Allow("127.0.0.1"); !allowed {
+ t.Fatal("expected reset to clear failures")
+ }
+
+ limiter.RecordFailure("127.0.0.1")
+ now = now.Add(2 * time.Minute)
+ if allowed, _ := limiter.Allow("127.0.0.1"); !allowed {
+ t.Fatal("expected failures to expire after the window")
+ }
+}
diff --git a/internal/authn/request.go b/internal/authn/request.go
new file mode 100644
index 00000000..2a1cc389
--- /dev/null
+++ b/internal/authn/request.go
@@ -0,0 +1,82 @@
+package authn
+
+import (
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+type Method string
+
+const (
+ MethodNone Method = ""
+ MethodHeader Method = "header"
+ MethodCookie Method = "cookie"
+)
+
+type Credentials struct {
+ Value string
+ Method Method
+}
+
+// CookieName is the dashboard auth cookie used for browser APIs that cannot
+// attach Authorization headers directly, such as EventSource and WebSocket.
+const CookieName = "pinchtab_auth_token"
+
+// CredentialsFromRequest extracts the auth token and the mechanism it arrived on.
+// Authorization headers take precedence over the dashboard auth cookie.
+func CredentialsFromRequest(r *http.Request) Credentials {
+ if r == nil {
+ return Credentials{}
+ }
+
+ if token := tokenFromAuthorizationHeader(r.Header.Get("Authorization")); token != "" {
+ return Credentials{Value: token, Method: MethodHeader}
+ }
+
+ cookie, err := r.Cookie(CookieName)
+ if err != nil {
+ return Credentials{}
+ }
+
+ value := strings.TrimSpace(cookie.Value)
+ if value == "" {
+ return Credentials{}
+ }
+ if decoded, err := url.QueryUnescape(value); err == nil {
+ return Credentials{Value: strings.TrimSpace(decoded), Method: MethodCookie}
+ }
+ return Credentials{Value: value, Method: MethodCookie}
+}
+
+// TokenFromRequest extracts the bearer token from the request.
+// Authorization headers take precedence over the dashboard auth cookie.
+func TokenFromRequest(r *http.Request) string {
+ return CredentialsFromRequest(r).Value
+}
+
+// ClientIP returns the immediate peer IP address for audit and rate-limiting
+// decisions. Reverse proxy headers are ignored unless a trusted-proxy model is
+// added explicitly.
+func ClientIP(r *http.Request) string {
+ if r == nil {
+ return ""
+ }
+ host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
+ if err == nil && host != "" {
+ return host
+ }
+ return strings.TrimSpace(r.RemoteAddr)
+}
+
+func tokenFromAuthorizationHeader(auth string) string {
+ auth = strings.TrimSpace(auth)
+ if auth == "" {
+ return ""
+ }
+ if strings.HasPrefix(strings.ToLower(auth), "bearer ") {
+ return strings.TrimSpace(auth[7:])
+ }
+ return auth
+}
diff --git a/internal/authn/request_test.go b/internal/authn/request_test.go
new file mode 100644
index 00000000..09059cab
--- /dev/null
+++ b/internal/authn/request_test.go
@@ -0,0 +1,61 @@
+package authn
+
+import (
+ "net/http/httptest"
+ "net/url"
+ "testing"
+)
+
+func TestTokenFromRequest_HeaderWins(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Authorization", "Bearer header-token")
+ req.Header.Set("Cookie", CookieName+"="+url.QueryEscape("cookie-token"))
+
+ if got := TokenFromRequest(req); got != "header-token" {
+ t.Fatalf("TokenFromRequest() = %q, want %q", got, "header-token")
+ }
+ if creds := CredentialsFromRequest(req); creds.Method != MethodHeader {
+ t.Fatalf("CredentialsFromRequest().Method = %q, want %q", creds.Method, MethodHeader)
+ }
+}
+
+func TestTokenFromRequest_CookieFallback(t *testing.T) {
+ const want = "cookie token/+"
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Cookie", CookieName+"="+url.QueryEscape(want))
+
+ if got := TokenFromRequest(req); got != want {
+ t.Fatalf("TokenFromRequest() = %q, want %q", got, want)
+ }
+ if creds := CredentialsFromRequest(req); creds.Method != MethodCookie {
+ t.Fatalf("CredentialsFromRequest().Method = %q, want %q", creds.Method, MethodCookie)
+ }
+}
+
+func TestTokenFromRequest_NoToken(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+
+ if got := TokenFromRequest(req); got != "" {
+ t.Fatalf("TokenFromRequest() = %q, want empty", got)
+ }
+}
+
+func TestClientIP_IgnoresForwardedHeaders(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = "198.51.100.10:43123"
+ req.Header.Set("X-Forwarded-For", "203.0.113.9")
+ req.Header.Set("X-Real-Ip", "203.0.113.8")
+
+ if got := ClientIP(req); got != "198.51.100.10" {
+ t.Fatalf("ClientIP() = %q, want %q", got, "198.51.100.10")
+ }
+}
+
+func TestClientIP_FallsBackToRawRemoteAddr(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = "198.51.100.10"
+
+ if got := ClientIP(req); got != "198.51.100.10" {
+ t.Fatalf("ClientIP() = %q, want %q", got, "198.51.100.10")
+ }
+}
diff --git a/internal/authn/session.go b/internal/authn/session.go
new file mode 100644
index 00000000..96d3027b
--- /dev/null
+++ b/internal/authn/session.go
@@ -0,0 +1,207 @@
+package authn
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ DefaultSessionIdleTimeout = 12 * time.Hour
+ DefaultSessionMaxLifetime = 7 * 24 * time.Hour
+ DefaultSessionElevationWindow = 15 * time.Minute
+)
+
+type SessionConfig struct {
+ IdleTimeout time.Duration
+ MaxLifetime time.Duration
+ ElevationWindow time.Duration
+}
+
+type SessionManager struct {
+ mu sync.Mutex
+ sessions map[string]sessionState
+ idleTimeout time.Duration
+ maxLifetime time.Duration
+ elevationWindow time.Duration
+ now func() time.Time
+}
+
+type sessionState struct {
+ CreatedAt time.Time
+ LastSeen time.Time
+ ElevatedUntil time.Time
+ TokenHash [32]byte
+}
+
+func NewSessionManager(cfg SessionConfig) *SessionManager {
+ idle := cfg.IdleTimeout
+ if idle <= 0 {
+ idle = DefaultSessionIdleTimeout
+ }
+ maxLifetime := cfg.MaxLifetime
+ if maxLifetime <= 0 {
+ maxLifetime = DefaultSessionMaxLifetime
+ }
+ elevationWindow := cfg.ElevationWindow
+ if elevationWindow <= 0 {
+ elevationWindow = DefaultSessionElevationWindow
+ }
+ return &SessionManager{
+ sessions: make(map[string]sessionState),
+ idleTimeout: idle,
+ maxLifetime: maxLifetime,
+ elevationWindow: elevationWindow,
+ now: time.Now,
+ }
+}
+
+func (m *SessionManager) Create(token string) (string, error) {
+ if m == nil {
+ return "", nil
+ }
+ id, err := randomSessionID()
+ if err != nil {
+ return "", err
+ }
+ now := m.now()
+ m.mu.Lock()
+ m.sessions[id] = sessionState{
+ CreatedAt: now,
+ LastSeen: now,
+ TokenHash: hashToken(token),
+ }
+ m.mu.Unlock()
+ return id, nil
+}
+
+func (m *SessionManager) Validate(sessionID, token string) bool {
+ if m == nil {
+ return false
+ }
+ sessionID = strings.TrimSpace(sessionID)
+ if sessionID == "" {
+ return false
+ }
+
+ now := m.now()
+ expected := hashToken(token)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ state, ok := m.sessions[sessionID]
+ if !ok {
+ return false
+ }
+ if !m.sessionValid(state, now, expected) {
+ delete(m.sessions, sessionID)
+ return false
+ }
+ state.LastSeen = now
+ m.sessions[sessionID] = state
+ return true
+}
+
+func (m *SessionManager) Elevate(sessionID, token string) bool {
+ if m == nil {
+ return false
+ }
+ sessionID = strings.TrimSpace(sessionID)
+ if sessionID == "" {
+ return false
+ }
+
+ now := m.now()
+ expected := hashToken(token)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ state, ok := m.sessions[sessionID]
+ if !ok {
+ return false
+ }
+ if !m.sessionValid(state, now, expected) {
+ delete(m.sessions, sessionID)
+ return false
+ }
+ state.LastSeen = now
+ state.ElevatedUntil = now.Add(m.elevationWindow)
+ m.sessions[sessionID] = state
+ return true
+}
+
+func (m *SessionManager) IsElevated(sessionID, token string) bool {
+ if m == nil {
+ return false
+ }
+ sessionID = strings.TrimSpace(sessionID)
+ if sessionID == "" {
+ return false
+ }
+
+ now := m.now()
+ expected := hashToken(token)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ state, ok := m.sessions[sessionID]
+ if !ok {
+ return false
+ }
+ if !m.sessionValid(state, now, expected) {
+ delete(m.sessions, sessionID)
+ return false
+ }
+ return !state.ElevatedUntil.IsZero() && !now.After(state.ElevatedUntil)
+}
+
+func (m *SessionManager) Revoke(sessionID string) {
+ if m == nil {
+ return
+ }
+ sessionID = strings.TrimSpace(sessionID)
+ if sessionID == "" {
+ return
+ }
+ m.mu.Lock()
+ delete(m.sessions, sessionID)
+ m.mu.Unlock()
+}
+
+func (m *SessionManager) MaxLifetime() time.Duration {
+ if m == nil {
+ return DefaultSessionMaxLifetime
+ }
+ return m.maxLifetime
+}
+
+func (m *SessionManager) ElevationWindow() time.Duration {
+ if m == nil {
+ return DefaultSessionElevationWindow
+ }
+ return m.elevationWindow
+}
+
+func (m *SessionManager) sessionValid(state sessionState, now time.Time, expected [32]byte) bool {
+ return now.Sub(state.LastSeen) <= m.idleTimeout &&
+ now.Sub(state.CreatedAt) <= m.maxLifetime &&
+ state.TokenHash == expected
+}
+
+func randomSessionID() (string, error) {
+ buf := make([]byte, 32)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(buf), nil
+}
+
+func hashToken(token string) [32]byte {
+ return sha256.Sum256([]byte(strings.TrimSpace(token)))
+}
diff --git a/internal/authn/session_test.go b/internal/authn/session_test.go
new file mode 100644
index 00000000..fd64331d
--- /dev/null
+++ b/internal/authn/session_test.go
@@ -0,0 +1,74 @@
+package authn
+
+import (
+ "testing"
+ "time"
+)
+
+func TestSessionManagerValidateAndExpiry(t *testing.T) {
+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
+ mgr := NewSessionManager(SessionConfig{
+ IdleTimeout: time.Hour,
+ MaxLifetime: 24 * time.Hour,
+ })
+ mgr.now = func() time.Time { return now }
+
+ sessionID, err := mgr.Create("secret")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ if !mgr.Validate(sessionID, "secret") {
+ t.Fatal("Validate() = false, want true")
+ }
+
+ now = now.Add(30 * time.Minute)
+ if !mgr.Validate(sessionID, "secret") {
+ t.Fatal("Validate() after activity = false, want true")
+ }
+
+ now = now.Add(61 * time.Minute)
+ if mgr.Validate(sessionID, "secret") {
+ t.Fatal("Validate() after idle expiry = true, want false")
+ }
+}
+
+func TestSessionManagerInvalidatesOnTokenChange(t *testing.T) {
+ mgr := NewSessionManager(SessionConfig{})
+ sessionID, err := mgr.Create("secret")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ if mgr.Validate(sessionID, "rotated-token") {
+ t.Fatal("Validate() with rotated token = true, want false")
+ }
+}
+
+func TestSessionManagerElevationWindow(t *testing.T) {
+ now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
+ mgr := NewSessionManager(SessionConfig{
+ IdleTimeout: time.Hour,
+ MaxLifetime: 24 * time.Hour,
+ ElevationWindow: 15 * time.Minute,
+ })
+ mgr.now = func() time.Time { return now }
+
+ sessionID, err := mgr.Create("secret")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ if mgr.IsElevated(sessionID, "secret") {
+ t.Fatal("IsElevated() before elevation = true, want false")
+ }
+ if !mgr.Elevate(sessionID, "secret") {
+ t.Fatal("Elevate() = false, want true")
+ }
+ if !mgr.IsElevated(sessionID, "secret") {
+ t.Fatal("IsElevated() after elevation = false, want true")
+ }
+
+ now = now.Add(16 * time.Minute)
+ if mgr.IsElevated(sessionID, "secret") {
+ t.Fatal("IsElevated() after elevation expiry = true, want false")
+ }
+}
diff --git a/internal/bridge/action_common.go b/internal/bridge/action_common.go
new file mode 100644
index 00000000..e8f4a4e5
--- /dev/null
+++ b/internal/bridge/action_common.go
@@ -0,0 +1,30 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/chromedp"
+)
+
+func firstNodeBySelector(ctx context.Context, selector string) (*cdp.Node, error) {
+ var nodes []*cdp.Node
+ if err := chromedp.Run(ctx,
+ chromedp.Nodes(selector, &nodes, chromedp.ByQuery),
+ ); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, fmt.Errorf("element not found: %s", selector)
+ }
+ return nodes[0], nil
+}
+
+func focusBackendNode(ctx context.Context, nodeID int64) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ )
+}
diff --git a/internal/bridge/action_form.go b/internal/bridge/action_form.go
new file mode 100644
index 00000000..1679cc5d
--- /dev/null
+++ b/internal/bridge/action_form.go
@@ -0,0 +1,168 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/chromedp/chromedp"
+)
+
+func (b *Bridge) actionFocus(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Selector != "" {
+ return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery))
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"focused": true}, focusBackendNode(ctx, req.NodeID)
+ }
+ return map[string]any{"focused": true}, nil
+}
+
+func (b *Bridge) actionSelect(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ val := req.Value
+ if val == "" {
+ val = req.Text
+ }
+ if val == "" {
+ return nil, fmt.Errorf("value required for select")
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"selected": val}, SelectByNodeID(ctx, req.NodeID, val)
+ }
+ if req.Selector != "" {
+ return map[string]any{"selected": val}, chromedp.Run(ctx,
+ chromedp.SetValue(req.Selector, val, chromedp.ByQuery),
+ )
+ }
+ return nil, fmt.Errorf("need selector or ref")
+}
+
+func (b *Bridge) actionCheck(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ return checkUncheck(ctx, req, true)
+}
+
+func (b *Bridge) actionUncheck(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ return checkUncheck(ctx, req, false)
+}
+
+// checkUncheck implements both check and uncheck actions.
+// If wantChecked is true, it ensures the element is checked; if false, unchecked.
+// It only clicks if the current state differs from the desired state.
+func checkUncheck(ctx context.Context, req ActionRequest, wantChecked bool) (map[string]any, error) {
+ // Resolve the element to an objectId via backendNodeId or CSS selector.
+ var resolveJS string
+ if req.NodeID > 0 {
+ // Resolve via backendNodeId using DOM.resolveNode (done below).
+ } else if req.Selector != "" {
+ resolveJS = req.Selector
+ } else {
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+ }
+
+ var objectID string
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ if req.NodeID > 0 {
+ var result json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": req.NodeID,
+ }, &result); err != nil {
+ return err
+ }
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(result, &resolved); err != nil {
+ return err
+ }
+ objectID = resolved.Object.ObjectID
+ return nil
+ }
+ // CSS selector path
+ var evalResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": fmt.Sprintf(`document.querySelector(%q)`, resolveJS),
+ "returnByValue": false,
+ }, &evalResult); err != nil {
+ return err
+ }
+ var er struct {
+ Result struct {
+ ObjectID string `json:"objectId"`
+ Type string `json:"type"`
+ Subtype string `json:"subtype"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(evalResult, &er); err != nil {
+ return err
+ }
+ if er.Result.ObjectID == "" || er.Result.Subtype == "null" {
+ return fmt.Errorf("element not found: %s", resolveJS)
+ }
+ objectID = er.Result.ObjectID
+ return nil
+ }))
+ if err != nil {
+ return nil, err
+ }
+
+ // Validate element is a checkbox or radio, and read current checked state.
+ var isChecked bool
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ js := `function() {
+ var tag = this.tagName ? this.tagName.toLowerCase() : "";
+ var type = (this.type || "").toLowerCase();
+ if (tag !== "input" || (type !== "checkbox" && type !== "radio")) {
+ return {error: "element is not a checkbox or radio input (got " + tag + "[type=" + type + "])"};
+ }
+ return {checked: this.checked};
+ }`
+ var callResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": js,
+ "objectId": objectID,
+ "returnByValue": true,
+ }, &callResult); err != nil {
+ return err
+ }
+ var cr struct {
+ Result struct {
+ Value json.RawMessage `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &cr); err != nil {
+ return err
+ }
+ var val struct {
+ Error string `json:"error"`
+ Checked bool `json:"checked"`
+ }
+ if err := json.Unmarshal(cr.Result.Value, &val); err != nil {
+ return err
+ }
+ if val.Error != "" {
+ return fmt.Errorf("%s", val.Error)
+ }
+ isChecked = val.Checked
+ return nil
+ }))
+ if err != nil {
+ return nil, err
+ }
+
+ // Click only if state needs to change.
+ if isChecked != wantChecked {
+ if req.NodeID > 0 {
+ if err := ClickByNodeID(ctx, req.NodeID); err != nil {
+ return nil, err
+ }
+ } else {
+ if err := chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery)); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ return map[string]any{"checked": wantChecked}, nil
+}
diff --git a/internal/bridge/action_pointer.go b/internal/bridge/action_pointer.go
new file mode 100644
index 00000000..db5ad741
--- /dev/null
+++ b/internal/bridge/action_pointer.go
@@ -0,0 +1,135 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/chromedp"
+)
+
+func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ var err error
+ if req.Selector != "" {
+ err = chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery))
+ } else if req.NodeID > 0 {
+ err = ClickByNodeID(ctx, req.NodeID)
+ } else if req.HasXY {
+ err = ClickByCoordinate(ctx, req.X, req.Y)
+ } else {
+ return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")
+ }
+ if err != nil {
+ return nil, err
+ }
+ if req.WaitNav {
+ _ = chromedp.Run(ctx, chromedp.Sleep(b.Config.WaitNavDelay))
+ }
+ return map[string]any{"clicked": true}, nil
+}
+
+func (b *Bridge) actionDoubleClick(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ var err error
+ if req.Selector != "" {
+ err = chromedp.Run(ctx, chromedp.DoubleClick(req.Selector, chromedp.ByQuery))
+ } else if req.NodeID > 0 {
+ err = DoubleClickByNodeID(ctx, req.NodeID)
+ } else if req.HasXY {
+ err = DoubleClickByCoordinate(ctx, req.X, req.Y)
+ } else {
+ return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")
+ }
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"doubleclicked": true}, nil
+}
+
+func (b *Bridge) actionHover(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ return map[string]any{"hovered": true}, HoverByNodeID(ctx, req.NodeID)
+ }
+ if req.Selector != "" {
+ return map[string]any{"hovered": true}, chromedp.Run(ctx,
+ chromedp.Evaluate(fmt.Sprintf(`document.querySelector(%q)?.dispatchEvent(new MouseEvent('mouseover', {bubbles:true}))`, req.Selector), nil),
+ )
+ }
+ if req.HasXY {
+ return map[string]any{"hovered": true}, HoverByCoordinate(ctx, req.X, req.Y)
+ }
+ return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")
+}
+
+func (b *Bridge) actionScroll(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ return map[string]any{"scrolled": true}, ScrollByNodeID(ctx, req.NodeID)
+ }
+ if req.ScrollX != 0 || req.ScrollY != 0 {
+ js := fmt.Sprintf("window.scrollBy(%d, %d)", req.ScrollX, req.ScrollY)
+ return map[string]any{"scrolled": true, "x": req.ScrollX, "y": req.ScrollY},
+ chromedp.Run(ctx, chromedp.Evaluate(js, nil))
+ }
+ return map[string]any{"scrolled": true, "y": 800},
+ chromedp.Run(ctx, chromedp.Evaluate("window.scrollBy(0, 800)", nil))
+}
+
+func (b *Bridge) actionDrag(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.DragX == 0 && req.DragY == 0 {
+ return nil, fmt.Errorf("dragX or dragY required for drag")
+ }
+ if req.NodeID > 0 {
+ err := DragByNodeID(ctx, req.NodeID, req.DragX, req.DragY)
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"dragged": true, "dragX": req.DragX, "dragY": req.DragY}, nil
+ }
+ if req.Selector != "" {
+ node, err := firstNodeBySelector(ctx, req.Selector)
+ if err != nil {
+ return nil, err
+ }
+ err = DragByNodeID(ctx, int64(node.BackendNodeID), req.DragX, req.DragY)
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"dragged": true, "dragX": req.DragX, "dragY": req.DragY}, nil
+ }
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+}
+
+func (b *Bridge) actionHumanClick(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ // req.NodeID is a backendDOMNodeId from the accessibility tree
+ if err := ClickElement(ctx, cdp.BackendNodeID(req.NodeID)); err != nil {
+ return nil, err
+ }
+ return map[string]any{"clicked": true, "human": true}, nil
+ }
+ if req.Selector != "" {
+ node, err := firstNodeBySelector(ctx, req.Selector)
+ if err != nil {
+ return nil, err
+ }
+ // Use BackendNodeID from the DOM node
+ if err := ClickElement(ctx, node.BackendNodeID); err != nil {
+ return nil, err
+ }
+ return map[string]any{"clicked": true, "human": true}, nil
+ }
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+}
+
+func (b *Bridge) actionScrollIntoView(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ return ScrollIntoViewAndGetBox(ctx, req.NodeID)
+ }
+ if req.Selector != "" {
+ nid, err := ResolveCSSToNodeID(ctx, req.Selector)
+ if err != nil {
+ return nil, err
+ }
+ return ScrollIntoViewAndGetBox(ctx, nid)
+ }
+ return nil, fmt.Errorf("need selector or ref")
+}
diff --git a/internal/bridge/action_registry.go b/internal/bridge/action_registry.go
new file mode 100644
index 00000000..18cfaf6b
--- /dev/null
+++ b/internal/bridge/action_registry.go
@@ -0,0 +1,47 @@
+package bridge
+
+const (
+ ActionClick = "click"
+ ActionDoubleClick = "dblclick"
+ ActionType = "type"
+ ActionFill = "fill"
+ ActionPress = "press"
+ ActionFocus = "focus"
+ ActionHover = "hover"
+ ActionSelect = "select"
+ ActionScroll = "scroll"
+ ActionDrag = "drag"
+ ActionHumanClick = "humanClick"
+ ActionHumanType = "humanType"
+ ActionCheck = "check"
+ ActionUncheck = "uncheck"
+ ActionKeyboardType = "keyboard-type"
+ ActionKeyboardInsert = "keyboard-inserttext"
+ ActionKeyDown = "keydown"
+ ActionKeyUp = "keyup"
+ ActionScrollIntoView = "scrollintoview"
+)
+
+func (b *Bridge) InitActionRegistry() {
+ b.Actions = map[string]ActionFunc{
+ ActionClick: b.actionClick,
+ ActionDoubleClick: b.actionDoubleClick,
+ ActionType: b.actionType,
+ ActionFill: b.actionFill,
+ ActionPress: b.actionPress,
+ ActionFocus: b.actionFocus,
+ ActionHover: b.actionHover,
+ ActionSelect: b.actionSelect,
+ ActionScroll: b.actionScroll,
+ ActionDrag: b.actionDrag,
+ ActionHumanClick: b.actionHumanClick,
+ ActionHumanType: b.actionHumanType,
+ ActionCheck: b.actionCheck,
+ ActionUncheck: b.actionUncheck,
+ ActionKeyboardType: b.actionKeyboardType,
+ ActionKeyboardInsert: b.actionKeyboardInsert,
+ ActionKeyDown: b.actionKeyDown,
+ ActionKeyUp: b.actionKeyUp,
+ ActionScrollIntoView: b.actionScrollIntoView,
+ }
+}
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.go
new file mode 100644
index 00000000..2c26d019
--- /dev/null
+++ b/internal/bridge/action_resolve.go
@@ -0,0 +1,288 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/selector"
+)
+
+// ResolveXPathToNodeID resolves an XPath expression to a backend node ID
+// using CDP's DOM.performSearch + DOM.getSearchResults.
+func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {
+ var backendNodeID int64
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ // Use DOM.getDocument first to ensure the DOM is available.
+ var docResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getDocument", map[string]any{"depth": 0}, &docResult); err != nil {
+ return fmt.Errorf("get document: %w", err)
+ }
+
+ // Perform XPath search.
+ var searchResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.performSearch", map[string]any{
+ "query": xpath,
+ }, &searchResult); err != nil {
+ return fmt.Errorf("xpath search: %w", err)
+ }
+
+ var sr struct {
+ SearchID string `json:"searchId"`
+ ResultCount int `json:"resultCount"`
+ }
+ if err := json.Unmarshal(searchResult, &sr); err != nil {
+ return err
+ }
+ if sr.ResultCount == 0 {
+ return fmt.Errorf("xpath %q: no elements found", xpath)
+ }
+
+ // Get the first result.
+ var getResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getSearchResults", map[string]any{
+ "searchId": sr.SearchID,
+ "fromIndex": 0,
+ "toIndex": 1,
+ }, &getResult); err != nil {
+ return fmt.Errorf("get search results: %w", err)
+ }
+
+ var gr struct {
+ NodeIDs []int64 `json:"nodeIds"`
+ }
+ if err := json.Unmarshal(getResult, &gr); err != nil {
+ return err
+ }
+ if len(gr.NodeIDs) == 0 {
+ return fmt.Errorf("xpath %q: no node IDs returned", xpath)
+ }
+
+ // Convert DOM NodeID → BackendNodeID.
+ var descResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
+ "nodeId": gr.NodeIDs[0],
+ }, &descResult); err != nil {
+ return fmt.Errorf("describe node: %w", err)
+ }
+
+ var desc struct {
+ Node struct {
+ BackendNodeID int64 `json:"backendNodeId"`
+ } `json:"node"`
+ }
+ if err := json.Unmarshal(descResult, &desc); err != nil {
+ return err
+ }
+ backendNodeID = desc.Node.BackendNodeID
+
+ // Clean up the search.
+ _ = chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.discardSearchResults", map[string]any{
+ "searchId": sr.SearchID,
+ }, nil)
+
+ return nil
+ }))
+ return backendNodeID, err
+}
+
+// ResolveTextToNodeID finds the first element whose visible text content
+// contains the given string and returns its backend node ID.
+func ResolveTextToNodeID(ctx context.Context, text string) (int64, error) {
+ var backendNodeID int64
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var docResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": "document",
+ "returnByValue": false,
+ }, &docResult); err != nil {
+ return fmt.Errorf("resolve document: %w", err)
+ }
+
+ var doc struct {
+ Result struct {
+ ObjectID string `json:"objectId"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(docResult, &doc); err != nil {
+ return err
+ }
+ if doc.Result.ObjectID == "" {
+ return fmt.Errorf("document object not found")
+ }
+
+ const findTextFn = `function(needle) {
+ const root = this.body || this.documentElement;
+ if (!root) {
+ return null;
+ }
+ const elements = root.querySelectorAll("*");
+ for (const el of elements) {
+ const text = el.innerText || "";
+ if (!text.includes(needle)) {
+ continue;
+ }
+ let childContainsText = false;
+ for (const child of el.children) {
+ if ((child.innerText || "").includes(needle)) {
+ childContainsText = true;
+ break;
+ }
+ }
+ if (!childContainsText) {
+ return el;
+ }
+ }
+ return null;
+ }`
+
+ var callResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": findTextFn,
+ "objectId": doc.Result.ObjectID,
+ "arguments": []map[string]any{{"value": text}},
+ "returnByValue": false,
+ }, &callResult); err != nil {
+ return fmt.Errorf("find text node: %w", err)
+ }
+
+ var call struct {
+ Result struct {
+ ObjectID string `json:"objectId"`
+ Subtype string `json:"subtype"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &call); err != nil {
+ return err
+ }
+ if call.Result.ObjectID == "" || call.Result.Subtype == "null" {
+ return fmt.Errorf("text %q not found", text)
+ }
+
+ var nodeResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.requestNode", map[string]any{
+ "objectId": call.Result.ObjectID,
+ }, &nodeResult); err != nil {
+ return fmt.Errorf("request node: %w", err)
+ }
+
+ var node struct {
+ NodeID int64 `json:"nodeId"`
+ }
+ if err := json.Unmarshal(nodeResult, &node); err != nil {
+ return err
+ }
+ if node.NodeID == 0 {
+ return fmt.Errorf("text %q resolved to an invalid node", text)
+ }
+
+ var descResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
+ "nodeId": node.NodeID,
+ }, &descResult); err != nil {
+ return fmt.Errorf("describe node: %w", err)
+ }
+
+ var desc struct {
+ Node struct {
+ BackendNodeID int64 `json:"backendNodeId"`
+ } `json:"node"`
+ }
+ if err := json.Unmarshal(descResult, &desc); err != nil {
+ return err
+ }
+ if desc.Node.BackendNodeID == 0 {
+ return fmt.Errorf("text %q resolved to an invalid backend node", text)
+ }
+
+ backendNodeID = desc.Node.BackendNodeID
+ return nil
+ }))
+ return backendNodeID, err
+}
+
+// ResolveCSSToNodeID resolves a CSS selector to a backend node ID.
+func ResolveCSSToNodeID(ctx context.Context, css string) (int64, error) {
+ var backendNodeID int64
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var docResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getDocument", map[string]any{"depth": 0}, &docResult); err != nil {
+ return fmt.Errorf("get document: %w", err)
+ }
+ var doc struct {
+ Root struct {
+ NodeID int64 `json:"nodeId"`
+ } `json:"root"`
+ }
+ if err := json.Unmarshal(docResult, &doc); err != nil {
+ return err
+ }
+
+ var qResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.querySelector", map[string]any{
+ "nodeId": doc.Root.NodeID,
+ "selector": css,
+ }, &qResult); err != nil {
+ return fmt.Errorf("querySelector: %w", err)
+ }
+ var qr struct {
+ NodeID int64 `json:"nodeId"`
+ }
+ if err := json.Unmarshal(qResult, &qr); err != nil {
+ return err
+ }
+ if qr.NodeID == 0 {
+ return fmt.Errorf("css %q: no element found", css)
+ }
+
+ var descResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
+ "nodeId": qr.NodeID,
+ }, &descResult); err != nil {
+ return fmt.Errorf("describe node: %w", err)
+ }
+ var desc struct {
+ Node struct {
+ BackendNodeID int64 `json:"backendNodeId"`
+ } `json:"node"`
+ }
+ if err := json.Unmarshal(descResult, &desc); err != nil {
+ return err
+ }
+ backendNodeID = desc.Node.BackendNodeID
+ return nil
+ }))
+ return backendNodeID, err
+}
+
+// ResolveUnifiedSelector resolves a parsed selector to a backend node ID.
+// For ref selectors, the refCache is consulted. For CSS, XPath, and text
+// selectors, CDP is used directly. Semantic selectors are not resolved here
+// (they require the semantic matcher at a higher layer).
+func ResolveUnifiedSelector(ctx context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {
+ switch sel.Kind {
+ case selector.KindRef:
+ if refCache != nil {
+ if nid, ok := refCache.Refs[sel.Value]; ok {
+ return nid, nil
+ }
+ }
+ return 0, fmt.Errorf("ref %s not found in snapshot cache", sel.Value)
+
+ case selector.KindCSS:
+ return ResolveCSSToNodeID(ctx, sel.Value)
+
+ case selector.KindXPath:
+ return ResolveXPathToNodeID(ctx, sel.Value)
+
+ case selector.KindText:
+ return ResolveTextToNodeID(ctx, sel.Value)
+
+ case selector.KindSemantic:
+ return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")
+
+ default:
+ return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)
+ }
+}
diff --git a/internal/bridge/action_text.go b/internal/bridge/action_text.go
new file mode 100644
index 00000000..07313a15
--- /dev/null
+++ b/internal/bridge/action_text.go
@@ -0,0 +1,159 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chromedp/chromedp"
+)
+
+func (b *Bridge) actionType(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Text == "" {
+ return nil, fmt.Errorf("text required for type")
+ }
+ if req.Selector != "" {
+ return map[string]any{"typed": req.Text}, chromedp.Run(ctx,
+ chromedp.Click(req.Selector, chromedp.ByQuery),
+ chromedp.SendKeys(req.Selector, req.Text, chromedp.ByQuery),
+ )
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"typed": req.Text}, TypeByNodeID(ctx, req.NodeID, req.Text)
+ }
+ return nil, fmt.Errorf("need selector or ref")
+}
+
+func (b *Bridge) actionFill(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Selector != "" {
+ return map[string]any{"filled": req.Text}, chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"filled": req.Text}, FillByNodeID(ctx, req.NodeID, req.Text)
+ }
+ return nil, fmt.Errorf("need selector or ref")
+}
+
+func (b *Bridge) actionPress(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Key == "" {
+ return nil, fmt.Errorf("key required for press")
+ }
+ return map[string]any{"pressed": req.Key}, DispatchNamedKey(ctx, req.Key)
+}
+
+func (b *Bridge) actionHumanType(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Text == "" {
+ return nil, fmt.Errorf("text required for humanType")
+ }
+
+ if req.Selector != "" {
+ if err := chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery)); err != nil {
+ return nil, err
+ }
+ } else if req.NodeID > 0 {
+ // req.NodeID is a BackendNodeID from the accessibility tree (same as humanClick).
+ // Must use DOM.focus with backendNodeId, not dom.Focus().WithNodeID() which
+ // expects a DOM NodeID — a different ID space. Using the wrong type causes
+ // "Could not find node with given id (-32000)". See issue #226.
+ if err := focusBackendNode(ctx, req.NodeID); err != nil {
+ return nil, err
+ }
+ } else {
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+ }
+
+ actions := Type(req.Text, req.Fast)
+ if err := chromedp.Run(ctx, actions...); err != nil {
+ return nil, err
+ }
+
+ return map[string]any{"typed": req.Text, "human": true}, nil
+}
+
+func (b *Bridge) actionKeyboardType(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Text == "" {
+ return nil, fmt.Errorf("text required for keyboard-type")
+ }
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ for _, ch := range req.Text {
+ s := string(ch)
+ params := map[string]any{
+ "type": "keyDown",
+ "text": s,
+ "key": s,
+ "unmodifiedText": s,
+ "windowsVirtualKeyCode": int(ch),
+ "nativeVirtualKeyCode": int(ch),
+ }
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil); err != nil {
+ return err
+ }
+ paramsUp := map[string]any{
+ "type": "keyUp",
+ "key": s,
+ "windowsVirtualKeyCode": int(ch),
+ "nativeVirtualKeyCode": int(ch),
+ }
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", paramsUp, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+ }))
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"typed": req.Text}, nil
+}
+
+func (b *Bridge) actionKeyboardInsert(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Text == "" {
+ return nil, fmt.Errorf("text required for keyboard-inserttext")
+ }
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.insertText", map[string]any{
+ "text": req.Text,
+ }, nil)
+ }))
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"inserted": req.Text}, nil
+}
+
+func (b *Bridge) actionKeyDown(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Key == "" {
+ return nil, fmt.Errorf("key required for keydown")
+ }
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ params := map[string]any{"type": "keyDown", "key": req.Key}
+ if def, ok := namedKeyDefs[req.Key]; ok {
+ params["code"] = def.code
+ params["windowsVirtualKeyCode"] = def.virtualKey
+ params["nativeVirtualKeyCode"] = def.virtualKey
+ }
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil)
+ }))
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"keydown": req.Key}, nil
+}
+
+func (b *Bridge) actionKeyUp(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Key == "" {
+ return nil, fmt.Errorf("key required for keyup")
+ }
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ params := map[string]any{"type": "keyUp", "key": req.Key}
+ if def, ok := namedKeyDefs[req.Key]; ok {
+ params["code"] = def.code
+ params["windowsVirtualKeyCode"] = def.virtualKey
+ params["nativeVirtualKeyCode"] = def.virtualKey
+ }
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil)
+ }))
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"keyup": req.Key}, nil
+}
diff --git a/internal/bridge/actions.go b/internal/bridge/actions.go
deleted file mode 100644
index 10bd5d6f..00000000
--- a/internal/bridge/actions.go
+++ /dev/null
@@ -1,753 +0,0 @@
-package bridge
-
-import (
- "context"
- "encoding/json"
- "fmt"
-
- "github.com/chromedp/cdproto/cdp"
- "github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/human"
- "github.com/pinchtab/pinchtab/internal/selector"
-)
-
-const (
- ActionClick = "click"
- ActionDoubleClick = "dblclick"
- ActionType = "type"
- ActionFill = "fill"
- ActionPress = "press"
- ActionFocus = "focus"
- ActionHover = "hover"
- ActionSelect = "select"
- ActionScroll = "scroll"
- ActionDrag = "drag"
- ActionHumanClick = "humanClick"
- ActionHumanType = "humanType"
- ActionCheck = "check"
- ActionUncheck = "uncheck"
- ActionKeyboardType = "keyboard-type"
- ActionKeyboardInsert = "keyboard-inserttext"
- ActionKeyDown = "keydown"
- ActionKeyUp = "keyup"
- ActionScrollIntoView = "scrollintoview"
-)
-
-func (b *Bridge) InitActionRegistry() {
- b.Actions = map[string]ActionFunc{
- ActionClick: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- var err error
- if req.Selector != "" {
- err = chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery))
- } else if req.NodeID > 0 {
- err = ClickByNodeID(ctx, req.NodeID)
- } else if req.HasXY {
- err = ClickByCoordinate(ctx, req.X, req.Y)
- } else {
- return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")
- }
- if err != nil {
- return nil, err
- }
- if req.WaitNav {
- _ = chromedp.Run(ctx, chromedp.Sleep(b.Config.WaitNavDelay))
- }
- return map[string]any{"clicked": true}, nil
- },
- ActionDoubleClick: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- var err error
- if req.Selector != "" {
- err = chromedp.Run(ctx, chromedp.DoubleClick(req.Selector, chromedp.ByQuery))
- } else if req.NodeID > 0 {
- err = DoubleClickByNodeID(ctx, req.NodeID)
- } else if req.HasXY {
- err = DoubleClickByCoordinate(ctx, req.X, req.Y)
- } else {
- return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")
- }
- if err != nil {
- return nil, err
- }
- return map[string]any{"doubleclicked": true}, nil
- },
- ActionType: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Text == "" {
- return nil, fmt.Errorf("text required for type")
- }
- if req.Selector != "" {
- return map[string]any{"typed": req.Text}, chromedp.Run(ctx,
- chromedp.Click(req.Selector, chromedp.ByQuery),
- chromedp.SendKeys(req.Selector, req.Text, chromedp.ByQuery),
- )
- }
- if req.NodeID > 0 {
- return map[string]any{"typed": req.Text}, TypeByNodeID(ctx, req.NodeID, req.Text)
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- ActionFill: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Selector != "" {
- return map[string]any{"filled": req.Text}, chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))
- }
- if req.NodeID > 0 {
- return map[string]any{"filled": req.Text}, FillByNodeID(ctx, req.NodeID, req.Text)
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- ActionPress: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Key == "" {
- return nil, fmt.Errorf("key required for press")
- }
- return map[string]any{"pressed": req.Key}, DispatchNamedKey(ctx, req.Key)
- },
- ActionFocus: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Selector != "" {
- return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery))
- }
- if req.NodeID > 0 {
- return map[string]any{"focused": true}, chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- p := map[string]any{"backendNodeId": req.NodeID}
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil)
- }),
- )
- }
- return map[string]any{"focused": true}, nil
- },
- ActionHover: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- return map[string]any{"hovered": true}, HoverByNodeID(ctx, req.NodeID)
- }
- if req.Selector != "" {
- return map[string]any{"hovered": true}, chromedp.Run(ctx,
- chromedp.Evaluate(fmt.Sprintf(`document.querySelector(%q)?.dispatchEvent(new MouseEvent('mouseover', {bubbles:true}))`, req.Selector), nil),
- )
- }
- if req.HasXY {
- return map[string]any{"hovered": true}, HoverByCoordinate(ctx, req.X, req.Y)
- }
- return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")
- },
- ActionSelect: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- val := req.Value
- if val == "" {
- val = req.Text
- }
- if val == "" {
- return nil, fmt.Errorf("value required for select")
- }
- if req.NodeID > 0 {
- return map[string]any{"selected": val}, SelectByNodeID(ctx, req.NodeID, val)
- }
- if req.Selector != "" {
- return map[string]any{"selected": val}, chromedp.Run(ctx,
- chromedp.SetValue(req.Selector, val, chromedp.ByQuery),
- )
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- ActionScroll: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- return map[string]any{"scrolled": true}, ScrollByNodeID(ctx, req.NodeID)
- }
- if req.ScrollX != 0 || req.ScrollY != 0 {
- js := fmt.Sprintf("window.scrollBy(%d, %d)", req.ScrollX, req.ScrollY)
- return map[string]any{"scrolled": true, "x": req.ScrollX, "y": req.ScrollY},
- chromedp.Run(ctx, chromedp.Evaluate(js, nil))
- }
- return map[string]any{"scrolled": true, "y": 800},
- chromedp.Run(ctx, chromedp.Evaluate("window.scrollBy(0, 800)", nil))
- },
- ActionDrag: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.DragX == 0 && req.DragY == 0 {
- return nil, fmt.Errorf("dragX or dragY required for drag")
- }
- if req.NodeID > 0 {
- err := DragByNodeID(ctx, req.NodeID, req.DragX, req.DragY)
- if err != nil {
- return nil, err
- }
- return map[string]any{"dragged": true, "dragX": req.DragX, "dragY": req.DragY}, nil
- }
- if req.Selector != "" {
- var nodes []*cdp.Node
- if err := chromedp.Run(ctx,
- chromedp.Nodes(req.Selector, &nodes, chromedp.ByQuery),
- ); err != nil {
- return nil, err
- }
- if len(nodes) == 0 {
- return nil, fmt.Errorf("element not found: %s", req.Selector)
- }
- err := DragByNodeID(ctx, int64(nodes[0].BackendNodeID), req.DragX, req.DragY)
- if err != nil {
- return nil, err
- }
- return map[string]any{"dragged": true, "dragX": req.DragX, "dragY": req.DragY}, nil
- }
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- },
- ActionHumanClick: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- // req.NodeID is a backendDOMNodeId from the accessibility tree
- if err := human.ClickElement(ctx, cdp.BackendNodeID(req.NodeID)); err != nil {
- return nil, err
- }
- return map[string]any{"clicked": true, "human": true}, nil
- }
- if req.Selector != "" {
- var nodes []*cdp.Node
- if err := chromedp.Run(ctx,
- chromedp.Nodes(req.Selector, &nodes, chromedp.ByQuery),
- ); err != nil {
- return nil, err
- }
- if len(nodes) == 0 {
- return nil, fmt.Errorf("element not found: %s", req.Selector)
- }
- // Use BackendNodeID from the DOM node
- if err := human.ClickElement(ctx, nodes[0].BackendNodeID); err != nil {
- return nil, err
- }
- return map[string]any{"clicked": true, "human": true}, nil
- }
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- },
- ActionHumanType: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Text == "" {
- return nil, fmt.Errorf("text required for humanType")
- }
-
- if req.Selector != "" {
- if err := chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery)); err != nil {
- return nil, err
- }
- } else if req.NodeID > 0 {
- // req.NodeID is a BackendNodeID from the accessibility tree (same as humanClick).
- // Must use DOM.focus with backendNodeId, not dom.Focus().WithNodeID() which
- // expects a DOM NodeID — a different ID space. Using the wrong type causes
- // "Could not find node with given id (-32000)". See issue #226.
- if err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": req.NodeID}, nil)
- }),
- ); err != nil {
- return nil, err
- }
- } else {
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- }
-
- actions := human.Type(req.Text, req.Fast)
- if err := chromedp.Run(ctx, actions...); err != nil {
- return nil, err
- }
-
- return map[string]any{"typed": req.Text, "human": true}, nil
- },
- ActionCheck: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- return checkUncheck(ctx, req, true)
- },
- ActionUncheck: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- return checkUncheck(ctx, req, false)
- },
- ActionKeyboardType: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Text == "" {
- return nil, fmt.Errorf("text required for keyboard-type")
- }
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- for _, ch := range req.Text {
- s := string(ch)
- params := map[string]any{
- "type": "keyDown",
- "text": s,
- "key": s,
- "unmodifiedText": s,
- "windowsVirtualKeyCode": int(ch),
- "nativeVirtualKeyCode": int(ch),
- }
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil); err != nil {
- return err
- }
- paramsUp := map[string]any{
- "type": "keyUp",
- "key": s,
- "windowsVirtualKeyCode": int(ch),
- "nativeVirtualKeyCode": int(ch),
- }
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", paramsUp, nil); err != nil {
- return err
- }
- }
- return nil
- }))
- if err != nil {
- return nil, err
- }
- return map[string]any{"typed": req.Text}, nil
- },
- ActionKeyboardInsert: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Text == "" {
- return nil, fmt.Errorf("text required for keyboard-inserttext")
- }
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.insertText", map[string]any{
- "text": req.Text,
- }, nil)
- }))
- if err != nil {
- return nil, err
- }
- return map[string]any{"inserted": req.Text}, nil
- },
- ActionKeyDown: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Key == "" {
- return nil, fmt.Errorf("key required for keydown")
- }
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- params := map[string]any{"type": "keyDown", "key": req.Key}
- if def, ok := namedKeyDefs[req.Key]; ok {
- params["code"] = def.code
- params["windowsVirtualKeyCode"] = def.virtualKey
- params["nativeVirtualKeyCode"] = def.virtualKey
- }
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil)
- }))
- if err != nil {
- return nil, err
- }
- return map[string]any{"keydown": req.Key}, nil
- },
- ActionKeyUp: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.Key == "" {
- return nil, fmt.Errorf("key required for keyup")
- }
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- params := map[string]any{"type": "keyUp", "key": req.Key}
- if def, ok := namedKeyDefs[req.Key]; ok {
- params["code"] = def.code
- params["windowsVirtualKeyCode"] = def.virtualKey
- params["nativeVirtualKeyCode"] = def.virtualKey
- }
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil)
- }))
- if err != nil {
- return nil, err
- }
- return map[string]any{"keyup": req.Key}, nil
- },
- ActionScrollIntoView: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- return ScrollIntoViewAndGetBox(ctx, req.NodeID)
- }
- if req.Selector != "" {
- nid, err := ResolveCSSToNodeID(ctx, req.Selector)
- if err != nil {
- return nil, err
- }
- return ScrollIntoViewAndGetBox(ctx, nid)
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- }
-}
-
-// checkUncheck implements both check and uncheck actions.
-// If wantChecked is true, it ensures the element is checked; if false, unchecked.
-// It only clicks if the current state differs from the desired state.
-func checkUncheck(ctx context.Context, req ActionRequest, wantChecked bool) (map[string]any, error) {
- // Resolve the element to an objectId via backendNodeId or CSS selector.
- var resolveJS string
- if req.NodeID > 0 {
- // Resolve via backendNodeId using DOM.resolveNode (done below).
- } else if req.Selector != "" {
- resolveJS = req.Selector
- } else {
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- }
-
- var objectID string
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- if req.NodeID > 0 {
- var result json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": req.NodeID,
- }, &result); err != nil {
- return err
- }
- var resolved struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(result, &resolved); err != nil {
- return err
- }
- objectID = resolved.Object.ObjectID
- return nil
- }
- // CSS selector path
- var evalResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
- "expression": fmt.Sprintf(`document.querySelector(%q)`, resolveJS),
- "returnByValue": false,
- }, &evalResult); err != nil {
- return err
- }
- var er struct {
- Result struct {
- ObjectID string `json:"objectId"`
- Type string `json:"type"`
- Subtype string `json:"subtype"`
- } `json:"result"`
- }
- if err := json.Unmarshal(evalResult, &er); err != nil {
- return err
- }
- if er.Result.ObjectID == "" || er.Result.Subtype == "null" {
- return fmt.Errorf("element not found: %s", resolveJS)
- }
- objectID = er.Result.ObjectID
- return nil
- }))
- if err != nil {
- return nil, err
- }
-
- // Validate element is a checkbox or radio, and read current checked state.
- var isChecked bool
- err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- js := `function() {
- var tag = this.tagName ? this.tagName.toLowerCase() : "";
- var type = (this.type || "").toLowerCase();
- if (tag !== "input" || (type !== "checkbox" && type !== "radio")) {
- return {error: "element is not a checkbox or radio input (got " + tag + "[type=" + type + "])"};
- }
- return {checked: this.checked};
- }`
- var callResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": js,
- "objectId": objectID,
- "returnByValue": true,
- }, &callResult); err != nil {
- return err
- }
- var cr struct {
- Result struct {
- Value json.RawMessage `json:"value"`
- } `json:"result"`
- }
- if err := json.Unmarshal(callResult, &cr); err != nil {
- return err
- }
- var val struct {
- Error string `json:"error"`
- Checked bool `json:"checked"`
- }
- if err := json.Unmarshal(cr.Result.Value, &val); err != nil {
- return err
- }
- if val.Error != "" {
- return fmt.Errorf("%s", val.Error)
- }
- isChecked = val.Checked
- return nil
- }))
- if err != nil {
- return nil, err
- }
-
- // Click only if state needs to change.
- if isChecked != wantChecked {
- if req.NodeID > 0 {
- if err := ClickByNodeID(ctx, req.NodeID); err != nil {
- return nil, err
- }
- } else {
- if err := chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery)); err != nil {
- return nil, err
- }
- }
- }
-
- return map[string]any{"checked": wantChecked}, nil
-}
-
-// ResolveXPathToNodeID resolves an XPath expression to a backend node ID
-// using CDP's DOM.performSearch + DOM.getSearchResults.
-func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {
- var backendNodeID int64
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- // Use DOM.getDocument first to ensure the DOM is available.
- var docResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getDocument", map[string]any{"depth": 0}, &docResult); err != nil {
- return fmt.Errorf("get document: %w", err)
- }
-
- // Perform XPath search.
- var searchResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.performSearch", map[string]any{
- "query": xpath,
- }, &searchResult); err != nil {
- return fmt.Errorf("xpath search: %w", err)
- }
-
- var sr struct {
- SearchID string `json:"searchId"`
- ResultCount int `json:"resultCount"`
- }
- if err := json.Unmarshal(searchResult, &sr); err != nil {
- return err
- }
- if sr.ResultCount == 0 {
- return fmt.Errorf("xpath %q: no elements found", xpath)
- }
-
- // Get the first result.
- var getResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getSearchResults", map[string]any{
- "searchId": sr.SearchID,
- "fromIndex": 0,
- "toIndex": 1,
- }, &getResult); err != nil {
- return fmt.Errorf("get search results: %w", err)
- }
-
- var gr struct {
- NodeIDs []int64 `json:"nodeIds"`
- }
- if err := json.Unmarshal(getResult, &gr); err != nil {
- return err
- }
- if len(gr.NodeIDs) == 0 {
- return fmt.Errorf("xpath %q: no node IDs returned", xpath)
- }
-
- // Convert DOM NodeID → BackendNodeID.
- var descResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
- "nodeId": gr.NodeIDs[0],
- }, &descResult); err != nil {
- return fmt.Errorf("describe node: %w", err)
- }
-
- var desc struct {
- Node struct {
- BackendNodeID int64 `json:"backendNodeId"`
- } `json:"node"`
- }
- if err := json.Unmarshal(descResult, &desc); err != nil {
- return err
- }
- backendNodeID = desc.Node.BackendNodeID
-
- // Clean up the search.
- _ = chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.discardSearchResults", map[string]any{
- "searchId": sr.SearchID,
- }, nil)
-
- return nil
- }))
- return backendNodeID, err
-}
-
-// ResolveTextToNodeID finds the first element whose visible text content
-// contains the given string and returns its backend node ID.
-func ResolveTextToNodeID(ctx context.Context, text string) (int64, error) {
- var backendNodeID int64
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- var docResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
- "expression": "document",
- "returnByValue": false,
- }, &docResult); err != nil {
- return fmt.Errorf("resolve document: %w", err)
- }
-
- var doc struct {
- Result struct {
- ObjectID string `json:"objectId"`
- } `json:"result"`
- }
- if err := json.Unmarshal(docResult, &doc); err != nil {
- return err
- }
- if doc.Result.ObjectID == "" {
- return fmt.Errorf("document object not found")
- }
-
- const findTextFn = `function(needle) {
- const root = this.body || this.documentElement;
- if (!root) {
- return null;
- }
- const elements = root.querySelectorAll("*");
- for (const el of elements) {
- const text = el.innerText || "";
- if (!text.includes(needle)) {
- continue;
- }
- let childContainsText = false;
- for (const child of el.children) {
- if ((child.innerText || "").includes(needle)) {
- childContainsText = true;
- break;
- }
- }
- if (!childContainsText) {
- return el;
- }
- }
- return null;
- }`
-
- var callResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": findTextFn,
- "objectId": doc.Result.ObjectID,
- "arguments": []map[string]any{{"value": text}},
- "returnByValue": false,
- }, &callResult); err != nil {
- return fmt.Errorf("find text node: %w", err)
- }
-
- var call struct {
- Result struct {
- ObjectID string `json:"objectId"`
- Subtype string `json:"subtype"`
- } `json:"result"`
- }
- if err := json.Unmarshal(callResult, &call); err != nil {
- return err
- }
- if call.Result.ObjectID == "" || call.Result.Subtype == "null" {
- return fmt.Errorf("text %q not found", text)
- }
-
- var nodeResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.requestNode", map[string]any{
- "objectId": call.Result.ObjectID,
- }, &nodeResult); err != nil {
- return fmt.Errorf("request node: %w", err)
- }
-
- var node struct {
- NodeID int64 `json:"nodeId"`
- }
- if err := json.Unmarshal(nodeResult, &node); err != nil {
- return err
- }
- if node.NodeID == 0 {
- return fmt.Errorf("text %q resolved to an invalid node", text)
- }
-
- var descResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
- "nodeId": node.NodeID,
- }, &descResult); err != nil {
- return fmt.Errorf("describe node: %w", err)
- }
-
- var desc struct {
- Node struct {
- BackendNodeID int64 `json:"backendNodeId"`
- } `json:"node"`
- }
- if err := json.Unmarshal(descResult, &desc); err != nil {
- return err
- }
- if desc.Node.BackendNodeID == 0 {
- return fmt.Errorf("text %q resolved to an invalid backend node", text)
- }
-
- backendNodeID = desc.Node.BackendNodeID
- return nil
- }))
- return backendNodeID, err
-}
-
-// ResolveCSSToNodeID resolves a CSS selector to a backend node ID.
-func ResolveCSSToNodeID(ctx context.Context, css string) (int64, error) {
- var backendNodeID int64
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- var docResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getDocument", map[string]any{"depth": 0}, &docResult); err != nil {
- return fmt.Errorf("get document: %w", err)
- }
- var doc struct {
- Root struct {
- NodeID int64 `json:"nodeId"`
- } `json:"root"`
- }
- if err := json.Unmarshal(docResult, &doc); err != nil {
- return err
- }
-
- var qResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.querySelector", map[string]any{
- "nodeId": doc.Root.NodeID,
- "selector": css,
- }, &qResult); err != nil {
- return fmt.Errorf("querySelector: %w", err)
- }
- var qr struct {
- NodeID int64 `json:"nodeId"`
- }
- if err := json.Unmarshal(qResult, &qr); err != nil {
- return err
- }
- if qr.NodeID == 0 {
- return fmt.Errorf("css %q: no element found", css)
- }
-
- var descResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
- "nodeId": qr.NodeID,
- }, &descResult); err != nil {
- return fmt.Errorf("describe node: %w", err)
- }
- var desc struct {
- Node struct {
- BackendNodeID int64 `json:"backendNodeId"`
- } `json:"node"`
- }
- if err := json.Unmarshal(descResult, &desc); err != nil {
- return err
- }
- backendNodeID = desc.Node.BackendNodeID
- return nil
- }))
- return backendNodeID, err
-}
-
-// ResolveUnifiedSelector resolves a parsed selector to a backend node ID.
-// For ref selectors, the refCache is consulted. For CSS, XPath, and text
-// selectors, CDP is used directly. Semantic selectors are not resolved here
-// (they require the semantic matcher at a higher layer).
-func ResolveUnifiedSelector(ctx context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {
- switch sel.Kind {
- case selector.KindRef:
- if refCache != nil {
- if nid, ok := refCache.Refs[sel.Value]; ok {
- return nid, nil
- }
- }
- return 0, fmt.Errorf("ref %s not found in snapshot cache", sel.Value)
-
- case selector.KindCSS:
- return ResolveCSSToNodeID(ctx, sel.Value)
-
- case selector.KindXPath:
- return ResolveXPathToNodeID(ctx, sel.Value)
-
- case selector.KindText:
- return ResolveTextToNodeID(ctx, sel.Value)
-
- case selector.KindSemantic:
- return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")
-
- default:
- return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)
- }
-}
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index fcd815fb..b3b7fb04 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/chromedp/cdproto/target"
+ bridgetabs "github.com/pinchtab/pinchtab/internal/bridge/tabs"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -52,10 +53,7 @@ type BridgeAPI interface {
GetDialogManager() *DialogManager
}
-type LockInfo struct {
- Owner string
- ExpiresAt time.Time
-}
+type LockInfo = bridgetabs.LockInfo
// ProfileService abstracts profile management operations.
type ProfileService interface {
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index 42fab890..d80a7a0c 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -11,8 +11,7 @@ import (
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/idutil"
- "github.com/pinchtab/pinchtab/internal/uameta"
+ "github.com/pinchtab/pinchtab/internal/ids"
)
type TabEntry struct {
@@ -22,6 +21,8 @@ type TabEntry struct {
CDPID string // raw CDP target ID
CreatedAt time.Time // when the tab was first created/registered
LastUsed time.Time // last time the tab was accessed via TabContext
+ Policy TabPolicyState
+ Watching bool
}
type RefCache struct {
@@ -35,7 +36,7 @@ type Bridge struct {
BrowserCtx context.Context
BrowserCancel context.CancelFunc
Config *config.RuntimeConfig
- IdMgr *idutil.Manager
+ IdMgr *ids.Manager
*TabManager
StealthScript string
Actions map[string]ActionFunc
@@ -55,7 +56,7 @@ type Bridge struct {
}
func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridge {
- idMgr := idutil.NewManager()
+ idMgr := ids.NewManager()
netBufSize := DefaultNetworkBufferSize
if cfg != nil && cfg.NetworkBufferSize > 0 {
netBufSize = cfg.NetworkBufferSize
@@ -71,6 +72,7 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
if cfg != nil && browserCtx != nil {
b.TabManager = NewTabManager(browserCtx, cfg, idMgr, b.tabSetup)
b.SetDialogManager(b.Dialogs)
+ b.StartBrowserGuards()
}
b.Locks = NewLockManager()
b.Dialogs = NewDialogManager()
@@ -92,8 +94,19 @@ func (b *Bridge) injectStealth(ctx context.Context) {
}
}
+func (b *Bridge) injectPopupGuards(ctx context.Context) {
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ _, err := page.AddScriptToEvaluateOnNewDocument(popupGuardInitScript).Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ slog.Warn("popup guard injection failed", "err", err)
+ }
+}
+
func (b *Bridge) tabSetup(ctx context.Context) {
- if override := uameta.Build(b.Config.UserAgent, b.Config.ChromeVersion); override != nil {
+ if override := buildUserAgentOverride(b.Config.UserAgent, b.Config.ChromeVersion); override != nil {
if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
return override.Do(c)
})); err != nil {
@@ -101,6 +114,7 @@ func (b *Bridge) tabSetup(ctx context.Context) {
}
}
b.injectStealth(ctx)
+ b.injectPopupGuards(ctx)
if b.Config.NoAnimations {
if err := b.InjectNoAnimations(ctx); err != nil {
slog.Warn("no-animations injection failed", "err", err)
@@ -181,10 +195,11 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
// Initialize TabManager now that browser is ready
if b.Config != nil && b.TabManager == nil {
if b.IdMgr == nil {
- b.IdMgr = idutil.NewManager()
+ b.IdMgr = ids.NewManager()
}
b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)
b.SetDialogManager(b.Dialogs)
+ b.StartBrowserGuards()
}
// Ensure action registry is populated (idempotent)
@@ -252,7 +267,7 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contex
// Now initialize TabManager with the browser context
if b.Config != nil && b.TabManager == nil {
if b.IdMgr == nil {
- b.IdMgr = idutil.NewManager()
+ b.IdMgr = ids.NewManager()
}
b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)
b.SetDialogManager(b.Dialogs)
diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.go
index 1420a11f..9869ab8b 100644
--- a/internal/bridge/bridge_test.go
+++ b/internal/bridge/bridge_test.go
@@ -5,7 +5,9 @@ import (
"strings"
"sync"
"testing"
+ "time"
+ "github.com/chromedp/cdproto/target"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -196,3 +198,67 @@ func TestCloseTab_PreventsLastTabClose(t *testing.T) {
t.Errorf("expected error about list targets, got: %s", err.Error())
}
}
+
+func TestShouldBlockPopupTarget(t *testing.T) {
+ tests := []struct {
+ name string
+ info *target.Info
+ want bool
+ }{
+ {name: "nil target", info: nil, want: false},
+ {name: "top level page", info: &target.Info{Type: TargetTypePage}, want: false},
+ {name: "non-page target with opener", info: &target.Info{Type: "service_worker", OpenerID: target.ID("opener")}, want: false},
+ {name: "page popup", info: &target.Info{Type: TargetTypePage, OpenerID: target.ID("opener")}, want: true},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := shouldBlockPopupTarget(tc.info); got != tc.want {
+ t.Fatalf("shouldBlockPopupTarget(%+v) = %v, want %v", tc.info, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestEvaluateTabPolicy(t *testing.T) {
+ cfg := config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"example.com"},
+ StrictMode: true,
+ }
+
+ allowed := EvaluateTabPolicy("https://example.com/path", cfg)
+ if allowed.Threat || allowed.Blocked {
+ t.Fatalf("expected allowed domain to pass, got %+v", allowed)
+ }
+
+ blocked := EvaluateTabPolicy("https://evil.example.net/path", cfg)
+ if !blocked.Threat || !blocked.Blocked {
+ t.Fatalf("expected blocked domain to fail, got %+v", blocked)
+ }
+ if blocked.CurrentURL == "" || blocked.UpdatedAt.IsZero() {
+ t.Fatalf("expected policy state metadata to be populated, got %+v", blocked)
+ }
+}
+
+func TestTabManagerStoresTabPolicyState(t *testing.T) {
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm.tabs["tab1"] = &TabEntry{Ctx: context.Background()}
+
+ state := TabPolicyState{
+ CurrentURL: "https://evil.example.net/path",
+ Threat: true,
+ Blocked: true,
+ Reason: "blocked",
+ UpdatedAt: time.Now(),
+ }
+ tm.SetTabPolicyState("tab1", state)
+
+ got, ok := tm.GetTabPolicyState("tab1")
+ if !ok {
+ t.Fatal("expected stored policy state")
+ }
+ if got.CurrentURL != state.CurrentURL || got.Blocked != state.Blocked || got.Reason != state.Reason {
+ t.Fatalf("stored policy state mismatch: got %+v want %+v", got, state)
+ }
+}
diff --git a/internal/bridge/cdp.go b/internal/bridge/cdp.go
deleted file mode 100644
index d9269e20..00000000
--- a/internal/bridge/cdp.go
+++ /dev/null
@@ -1,754 +0,0 @@
-package bridge
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "math"
- "sync/atomic"
- "time"
-
- "github.com/chromedp/cdproto/cdp"
- "github.com/chromedp/cdproto/fetch"
- "github.com/chromedp/cdproto/network"
- "github.com/chromedp/cdproto/page"
- "github.com/chromedp/chromedp"
-)
-
-const TargetTypePage = "page"
-
-// NavigatePage uses raw CDP Page.navigate + polls document.readyState for completion.
-func NavigatePage(ctx context.Context, url string) error {
- err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, _, _, _, err := page.Navigate(url).Do(ctx)
- return err
- }),
- )
- if err != nil {
- return err
- }
-
- ticker := time.NewTicker(200 * time.Millisecond)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-ticker.C:
- var state string
- err = chromedp.Run(ctx,
- chromedp.Evaluate("document.readyState", &state),
- )
- if err == nil && (state == "interactive" || state == "complete") {
- return nil
- }
- }
- }
-}
-
-// ErrTooManyRedirects is returned when a navigation exceeds the configured redirect limit.
-var ErrTooManyRedirects = fmt.Errorf("too many redirects")
-
-// NavigatePageWithRedirectLimit navigates to a URL and enforces a maximum number of
-// HTTP redirects using the Fetch domain to intercept requests. If maxRedirects < 0,
-// redirects are unlimited. If maxRedirects == 0, any redirect is blocked.
-// If maxRedirects > 0, up to that many hops are allowed.
-func NavigatePageWithRedirectLimit(ctx context.Context, url string, maxRedirects int) error {
- // Unlimited: just navigate normally.
- if maxRedirects < 0 {
- return NavigatePage(ctx, url)
- }
-
- // Use Fetch domain to intercept and count redirects.
- // This pauses each request so we can decide to continue or fail it.
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return fetch.Enable().Do(ctx)
- })); err != nil {
- return fmt.Errorf("fetch enable: %w", err)
- }
-
- var redirectCount atomic.Int32
- var blocked atomic.Bool
-
- chromedp.ListenTarget(ctx, func(ev interface{}) {
- e, ok := ev.(*fetch.EventRequestPaused)
- if !ok {
- return
- }
- // Handle in goroutine to avoid deadlocking the event dispatcher.
- go func() {
- reqID := e.RequestID
- // A non-empty RedirectedRequestID means this request is a redirect.
- if e.RedirectedRequestID != "" {
- count := int(redirectCount.Add(1))
- if count > maxRedirects {
- blocked.Store(true)
- _ = fetch.FailRequest(reqID, network.ErrorReasonBlockedByClient).Do(cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target))
- return
- }
- }
- // Allow the request to proceed.
- _ = fetch.ContinueRequest(reqID).Do(cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target))
- }()
- })
-
- // Start navigation.
- err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, _, _, _, err := page.Navigate(url).Do(ctx)
- return err
- }),
- )
-
- // Disable fetch interception regardless of outcome.
- _ = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return fetch.Disable().Do(ctx)
- }))
-
- if blocked.Load() {
- return fmt.Errorf("%w: got %d, max %d", ErrTooManyRedirects, redirectCount.Load(), maxRedirects)
- }
- if err != nil {
- return err
- }
-
- // Wait for page to finish loading.
- ticker := time.NewTicker(200 * time.Millisecond)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-ticker.C:
- var state string
- err := chromedp.Run(ctx,
- chromedp.Evaluate("document.readyState", &state),
- )
- if err == nil && (state == "interactive" || state == "complete") {
- return nil
- }
- }
- }
-}
-
-var ImageBlockPatterns = []string{
- "*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico",
-}
-
-var MediaBlockPatterns = append(ImageBlockPatterns,
- "*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.flac", "*.aac",
-)
-
-// SetResourceBlocking uses Network.setBlockedURLs to block resources by URL pattern.
-func SetResourceBlocking(ctx context.Context, patterns []string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- if len(patterns) == 0 {
- return network.SetBlockedURLs([]string{}).Do(ctx)
- }
- return network.SetBlockedURLs(patterns).Do(ctx)
- }),
- )
-}
-
-func ClickByCoordinate(ctx context.Context, x, y float64) error {
- if x < 0 || y < 0 {
- return fmt.Errorf("x/y coordinates must be >= 0")
- }
-
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx,
- "Input.dispatchMouseEvent", map[string]any{
- "type": "mousePressed",
- "button": "left",
- "clickCount": 1,
- "x": x,
- "y": y,
- }, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx,
- "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseReleased",
- "button": "left",
- "clickCount": 1,
- "x": x,
- "y": y,
- }, nil)
- }),
- )
-}
-
-func ClickByNodeID(ctx context.Context, nodeID int64) error {
- // Get element position via box model
- x, y, err := getElementCenter(ctx, nodeID)
- if err != nil {
- return err
- }
-
- return chromedp.Run(ctx,
- // Scroll element into view first
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- // Focus the element
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- // Mouse down at element center
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mousePressed",
- "button": "left",
- "clickCount": 1,
- "x": x, "y": y,
- }, nil)
- }),
- // Mouse up at element center
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseReleased",
- "button": "left",
- "clickCount": 1,
- "x": x, "y": y,
- }, nil)
- }),
- )
-}
-
-func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {
- if x < 0 || y < 0 {
- return fmt.Errorf("x/y coordinates must be >= 0")
- }
-
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx,
- "Input.dispatchMouseEvent", map[string]any{
- "type": "mousePressed",
- "button": "left",
- "clickCount": 2,
- "x": x,
- "y": y,
- }, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx,
- "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseReleased",
- "button": "left",
- "clickCount": 2,
- "x": x,
- "y": y,
- }, nil)
- }),
- )
-}
-
-func DoubleClickByNodeID(ctx context.Context, nodeID int64) error {
- x, y, err := getElementCenter(ctx, nodeID)
- if err != nil {
- return err
- }
-
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mousePressed",
- "button": "left",
- "clickCount": 2,
- "x": x, "y": y,
- }, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseReleased",
- "button": "left",
- "clickCount": 2,
- "x": x, "y": y,
- }, nil)
- }),
- )
-}
-
-// getElementCenter returns the center coordinates of an element using DOM.getBoxModel.
-func getElementCenter(ctx context.Context, backendNodeID int64) (x, y float64, err error) {
- var result json.RawMessage
- err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getBoxModel", map[string]any{
- "backendNodeId": backendNodeID,
- }, &result)
- }))
- if err != nil {
- return 0, 0, err
- }
-
- // Parse the box model response
- // The "content" quad is [x1,y1, x2,y2, x3,y3, x4,y4] - four corners
- var box struct {
- Model struct {
- Content []float64 `json:"content"`
- } `json:"model"`
- }
- if err = json.Unmarshal(result, &box); err != nil {
- return 0, 0, err
- }
-
- if len(box.Model.Content) < 4 {
- return 0, 0, fmt.Errorf("invalid box model: expected at least 4 coordinates")
- }
-
- // Content quad: [x1,y1, x2,y2, x3,y3, x4,y4]
- // Calculate center as average of all four corners
- x = (box.Model.Content[0] + box.Model.Content[2] + box.Model.Content[4] + box.Model.Content[6]) / 4
- y = (box.Model.Content[1] + box.Model.Content[3] + box.Model.Content[5] + box.Model.Content[7]) / 4
-
- // Some nodes (e.g. Svelte5 snippet child nodes) have a zero-size bounding box
- // in the accessibility tree. Fall back to getBoundingClientRect() for accurate
- // viewport coordinates.
- if x == 0 && y == 0 {
- return getElementCenterJS(ctx, backendNodeID)
- }
-
- return x, y, nil
-}
-
-// getElementCenterJS resolves the DOM node and evaluates getBoundingClientRect()
-// to determine the centre of its rendered area. It is used as a fallback when
-// DOM.getBoxModel returns a zero bounding box.
-func getElementCenterJS(ctx context.Context, backendNodeID int64) (float64, float64, error) {
- var resolveResult json.RawMessage
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": backendNodeID,
- }, &resolveResult)
- })); err != nil {
- return 0, 0, fmt.Errorf("DOM.resolveNode: %w", err)
- }
-
- var resolved struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(resolveResult, &resolved); err != nil {
- return 0, 0, err
- }
- if resolved.Object.ObjectID == "" {
- return 0, 0, fmt.Errorf("element not found in DOM (backendNodeId=%d)", backendNodeID)
- }
-
- const rectFn = `function() {
- var r = this.getBoundingClientRect();
- return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
- }`
-
- var callResult json.RawMessage
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": rectFn,
- "objectId": resolved.Object.ObjectID,
- "returnByValue": true,
- }, &callResult)
- })); err != nil {
- return 0, 0, fmt.Errorf("getBoundingClientRect: %w", err)
- }
-
- var callRes struct {
- Result struct {
- Value struct {
- X float64 `json:"x"`
- Y float64 `json:"y"`
- } `json:"value"`
- } `json:"result"`
- }
- if err := json.Unmarshal(callResult, &callRes); err != nil {
- return 0, 0, err
- }
-
- return callRes.Result.Value.X, callRes.Result.Value.Y, nil
-}
-
-// DragByNodeID drags an element by (dx, dy) pixels using mousePressed → mouseMoved → mouseReleased.
-func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int) error {
- x, y, err := getElementCenter(ctx, nodeID)
- if err != nil {
- return err
- }
-
- endX := x + float64(dx)
- endY := y + float64(dy)
-
- // Number of intermediate mouseMoved events — proportional to distance,
- // clamped to [5, 40] to keep the drag smooth without flooding CDP.
- dist := math.Sqrt(float64(dx*dx + dy*dy))
- steps := int(dist / 10)
- if steps < 5 {
- steps = 5
- }
- if steps > 40 {
- steps = 40
- }
-
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseMoved",
- "x": x, "y": y,
- }, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mousePressed",
- "button": "left",
- "clickCount": 1,
- "x": x, "y": y,
- }, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- for i := 1; i <= steps; i++ {
- t := float64(i) / float64(steps)
- mx := x + t*float64(dx)
- my := y + t*float64(dy)
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseMoved",
- "buttons": 1,
- "x": mx, "y": my,
- }, nil); err != nil {
- return err
- }
- }
- return nil
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseReleased",
- "button": "left",
- "clickCount": 1,
- "x": endX, "y": endY,
- }, nil)
- }),
- )
-}
-
-// namedKeyDefs maps friendly key names (as accepted by the CLI "press" command)
-// to their CDP Input.dispatchKeyEvent parameters. Keys not in this table fall
-// through to chromedp.KeyEvent so that single printable characters still work.
-var namedKeyDefs = map[string]struct {
- code string
- virtualKey int64
- insertText string // non-empty for keys that produce a character (Enter→\r, Tab→\t)
-}{
- "Enter": {"Enter", 13, "\r"},
- "Return": {"Enter", 13, "\r"},
- "Tab": {"Tab", 9, "\t"},
- "Escape": {"Escape", 27, ""},
- "Backspace": {"Backspace", 8, ""},
- "Delete": {"Delete", 46, ""},
- "ArrowLeft": {"ArrowLeft", 37, ""},
- "ArrowRight": {"ArrowRight", 39, ""},
- "ArrowUp": {"ArrowUp", 38, ""},
- "ArrowDown": {"ArrowDown", 40, ""},
- "Home": {"Home", 36, ""},
- "End": {"End", 35, ""},
- "PageUp": {"PageUp", 33, ""},
- "PageDown": {"PageDown", 34, ""},
- "Insert": {"Insert", 45, ""},
- "F1": {"F1", 112, ""},
- "F2": {"F2", 113, ""},
- "F3": {"F3", 114, ""},
- "F4": {"F4", 115, ""},
- "F5": {"F5", 116, ""},
- "F6": {"F6", 117, ""},
- "F7": {"F7", 118, ""},
- "F8": {"F8", 119, ""},
- "F9": {"F9", 120, ""},
- "F10": {"F10", 121, ""},
- "F11": {"F11", 122, ""},
- "F12": {"F12", 123, ""},
-}
-
-// DispatchNamedKey sends proper CDP keyDown / keyUp events for well-known key
-// names (e.g. "Enter", "Tab", "Escape", "ArrowLeft") so that JavaScript event
-// handlers receive a KeyboardEvent with the correct key property.
-//
-// Unlike chromedp.KeyEvent, which treats multi-character strings as text
-// sequences and would type "Enter" as five separate characters, this function
-// consults namedKeyDefs and emits a single logical keystroke. Unrecognised keys
-// fall back to chromedp.KeyEvent so that single printable characters still work.
-func DispatchNamedKey(ctx context.Context, key string) error {
- def, ok := namedKeyDefs[key]
- if !ok {
- return chromedp.Run(ctx, chromedp.KeyEvent(key))
- }
-
- // Normalise "Return" → "Enter" for the W3C key value.
- w3cKey := key
- if key == "Return" {
- w3cKey = "Enter"
- }
-
- dispatchEvent := func(evType string) chromedp.ActionFunc {
- return chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", map[string]any{
- "type": evType,
- "key": w3cKey,
- "code": def.code,
- "windowsVirtualKeyCode": def.virtualKey,
- "nativeVirtualKeyCode": def.virtualKey,
- }, nil)
- })
- }
-
- actions := chromedp.Tasks{dispatchEvent("rawKeyDown")}
- if def.insertText != "" {
- insertText := def.insertText
- actions = append(actions, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.insertText", map[string]any{
- "text": insertText,
- }, nil)
- }))
- }
- actions = append(actions, dispatchEvent("keyUp"))
-
- return chromedp.Run(ctx, actions...)
-}
-
-func TypeByNodeID(ctx context.Context, nodeID int64, text string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- chromedp.KeyEvent(text),
- )
-}
-
-func HoverByCoordinate(ctx context.Context, x, y float64) error {
- if x < 0 || y < 0 {
- return fmt.Errorf("x/y coordinates must be >= 0")
- }
-
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseMoved",
- "x": x,
- "y": y,
- }, nil)
- }),
- )
-}
-
-func HoverByNodeID(ctx context.Context, nodeID int64) error {
- // Get element position via box model
- x, y, err := getElementCenter(ctx, nodeID)
- if err != nil {
- return err
- }
-
- return chromedp.Run(ctx,
- // Scroll element into view first
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- // Move mouse to element center
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
- "type": "mouseMoved",
- "x": x, "y": y,
- }, nil)
- }),
- )
-}
-
-func FillByNodeID(ctx context.Context, nodeID int64, value string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- var result json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": nodeID,
- }, &result); err != nil {
- return err
- }
- var resolved struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(result, &resolved); err != nil {
- return err
- }
- js := `function(v) { this.value = v; this.dispatchEvent(new Event('input', {bubbles: true})); this.dispatchEvent(new Event('change', {bubbles: true})); }`
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": js,
- "objectId": resolved.Object.ObjectID,
- "arguments": []map[string]any{{"value": value}},
- }, nil)
- }),
- )
-}
-
-func SelectByNodeID(ctx context.Context, nodeID int64, value string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- chromedp.ActionFunc(func(ctx context.Context) error {
- var result json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": nodeID,
- }, &result); err != nil {
- return err
- }
- var resolved struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(result, &resolved); err != nil {
- return err
- }
- js := `function(v) { this.value = v; this.dispatchEvent(new Event('input', {bubbles: true})); this.dispatchEvent(new Event('change', {bubbles: true})); }`
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": js,
- "objectId": resolved.Object.ObjectID,
- "arguments": []map[string]any{{"value": value}},
- }, nil)
- }),
- )
-}
-
-func ScrollByNodeID(ctx context.Context, nodeID int64) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
- }),
- )
-}
-
-// ScrollIntoViewAndGetBox scrolls the element into view using
-// DOM.scrollIntoViewIfNeeded (no-op if already visible) and returns
-// the element's bounding box via getBoundingClientRect().
-func ScrollIntoViewAndGetBox(ctx context.Context, nodeID int64) (map[string]any, error) {
- // 1. Scroll into view
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
- })); err != nil {
- return nil, fmt.Errorf("scrollIntoViewIfNeeded: %w", err)
- }
-
- // 2. Resolve backendNodeId → objectId
- var resolveResult json.RawMessage
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": nodeID,
- }, &resolveResult)
- })); err != nil {
- return nil, fmt.Errorf("DOM.resolveNode: %w", err)
- }
-
- var resolved struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(resolveResult, &resolved); err != nil {
- return nil, err
- }
- if resolved.Object.ObjectID == "" {
- return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)
- }
-
- // 3. Get bounding box via getBoundingClientRect
- const boxFn = `function() {
- var r = this.getBoundingClientRect();
- return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
- }`
-
- var callResult json.RawMessage
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": boxFn,
- "objectId": resolved.Object.ObjectID,
- "returnByValue": true,
- }, &callResult)
- })); err != nil {
- return nil, fmt.Errorf("getBoundingClientRect: %w", err)
- }
-
- var callRes struct {
- Result struct {
- Value struct {
- X float64 `json:"x"`
- Y float64 `json:"y"`
- Width float64 `json:"width"`
- Height float64 `json:"height"`
- } `json:"value"`
- } `json:"result"`
- }
- if err := json.Unmarshal(callResult, &callRes); err != nil {
- return nil, err
- }
-
- box := callRes.Result.Value
- return map[string]any{
- "scrolled": true,
- "box": map[string]any{
- "x": box.X,
- "y": box.Y,
- "width": box.Width,
- "height": box.Height,
- },
- }, nil
-}
-
-func WaitForTitle(ctx context.Context, timeout time.Duration) (string, error) {
- if timeout <= 0 {
- var title string
- if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
- return "", err
- }
- return title, nil
- }
-
- deadline := time.After(timeout)
- ticker := time.NewTicker(200 * time.Millisecond)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return "", ctx.Err()
- case <-deadline:
- var title string
- if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
- return "", err
- }
- return title, nil
- case <-ticker.C:
- var title string
- if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
- continue
- }
- if title != "" && title != "about:blank" {
- return title, nil
- }
- }
- }
-}
diff --git a/internal/bridge/cdp_element_ops_test.go b/internal/bridge/cdp_element_ops_test.go
new file mode 100644
index 00000000..a2bb0695
--- /dev/null
+++ b/internal/bridge/cdp_element_ops_test.go
@@ -0,0 +1,18 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+
+ "github.com/chromedp/chromedp"
+)
+
+func TestSelectByNodeID_UsesValue(t *testing.T) {
+ ctx, _ := chromedp.NewContext(context.Background())
+ // Without a real browser this will error, but it must NOT silently succeed
+ // (the old implementation was a no-op that always returned nil).
+ err := SelectByNodeID(ctx, 1, "option-value")
+ if err == nil {
+ t.Error("expected error without browser connection, got nil (possible no-op)")
+ }
+}
diff --git a/internal/bridge/cdp_geometry_test.go b/internal/bridge/cdp_geometry_test.go
new file mode 100644
index 00000000..f9fc6da7
--- /dev/null
+++ b/internal/bridge/cdp_geometry_test.go
@@ -0,0 +1,37 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+)
+
+func TestGetElementCenter_ParsesBoxModel(t *testing.T) {
+ // Test the box model parsing logic
+ // Content quad: [x1,y1, x2,y2, x3,y3, x4,y4]
+ // For a 100x50 box at position (200, 100):
+ // corners: (200,100), (300,100), (300,150), (200,150)
+ content := []float64{200, 100, 300, 100, 300, 150, 200, 150}
+
+ // Calculate expected center
+ expectedX := (content[0] + content[2] + content[4] + content[6]) / 4 // (200+300+300+200)/4 = 250
+ expectedY := (content[1] + content[3] + content[5] + content[7]) / 4 // (100+100+150+150)/4 = 125
+
+ if expectedX != 250 {
+ t.Errorf("expected X=250, got %f", expectedX)
+ }
+ if expectedY != 125 {
+ t.Errorf("expected Y=125, got %f", expectedY)
+ }
+}
+
+// TestGetElementCenterJS_ContextCancelled verifies that getElementCenterJS
+// returns an error when the context is already cancelled (no browser panic).
+func TestGetElementCenterJS_ContextCancelled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ _, _, err := getElementCenterJS(ctx, 1)
+ if err == nil {
+ t.Error("expected error for cancelled context, got nil")
+ }
+}
diff --git a/internal/bridge/cdp_keyboard.go b/internal/bridge/cdp_keyboard.go
new file mode 100644
index 00000000..f215f83f
--- /dev/null
+++ b/internal/bridge/cdp_keyboard.go
@@ -0,0 +1,99 @@
+package bridge
+
+import (
+ "context"
+
+ "github.com/chromedp/chromedp"
+)
+
+// namedKeyDefs maps friendly key names (as accepted by the CLI "press" command)
+// to their CDP Input.dispatchKeyEvent parameters. Keys not in this table fall
+// through to chromedp.KeyEvent so that single printable characters still work.
+var namedKeyDefs = map[string]struct {
+ code string
+ virtualKey int64
+ insertText string // non-empty for keys that produce a character (Enter→\r, Tab→\t)
+}{
+ "Enter": {"Enter", 13, "\r"},
+ "Return": {"Enter", 13, "\r"},
+ "Tab": {"Tab", 9, "\t"},
+ "Escape": {"Escape", 27, ""},
+ "Backspace": {"Backspace", 8, ""},
+ "Delete": {"Delete", 46, ""},
+ "ArrowLeft": {"ArrowLeft", 37, ""},
+ "ArrowRight": {"ArrowRight", 39, ""},
+ "ArrowUp": {"ArrowUp", 38, ""},
+ "ArrowDown": {"ArrowDown", 40, ""},
+ "Home": {"Home", 36, ""},
+ "End": {"End", 35, ""},
+ "PageUp": {"PageUp", 33, ""},
+ "PageDown": {"PageDown", 34, ""},
+ "Insert": {"Insert", 45, ""},
+ "F1": {"F1", 112, ""},
+ "F2": {"F2", 113, ""},
+ "F3": {"F3", 114, ""},
+ "F4": {"F4", 115, ""},
+ "F5": {"F5", 116, ""},
+ "F6": {"F6", 117, ""},
+ "F7": {"F7", 118, ""},
+ "F8": {"F8", 119, ""},
+ "F9": {"F9", 120, ""},
+ "F10": {"F10", 121, ""},
+ "F11": {"F11", 122, ""},
+ "F12": {"F12", 123, ""},
+}
+
+// DispatchNamedKey sends proper CDP keyDown / keyUp events for well-known key
+// names (e.g. "Enter", "Tab", "Escape", "ArrowLeft") so that JavaScript event
+// handlers receive a KeyboardEvent with the correct key property.
+//
+// Unlike chromedp.KeyEvent, which treats multi-character strings as text
+// sequences and would type "Enter" as five separate characters, this function
+// consults namedKeyDefs and emits a single logical keystroke. Unrecognised keys
+// fall back to chromedp.KeyEvent so that single printable characters still work.
+func DispatchNamedKey(ctx context.Context, key string) error {
+ def, ok := namedKeyDefs[key]
+ if !ok {
+ return chromedp.Run(ctx, chromedp.KeyEvent(key))
+ }
+
+ // Normalise "Return" → "Enter" for the W3C key value.
+ w3cKey := key
+ if key == "Return" {
+ w3cKey = "Enter"
+ }
+
+ dispatchEvent := func(evType string) chromedp.ActionFunc {
+ return chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", map[string]any{
+ "type": evType,
+ "key": w3cKey,
+ "code": def.code,
+ "windowsVirtualKeyCode": def.virtualKey,
+ "nativeVirtualKeyCode": def.virtualKey,
+ }, nil)
+ })
+ }
+
+ actions := chromedp.Tasks{dispatchEvent("rawKeyDown")}
+ if def.insertText != "" {
+ insertText := def.insertText
+ actions = append(actions, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.insertText", map[string]any{
+ "text": insertText,
+ }, nil)
+ }))
+ }
+ actions = append(actions, dispatchEvent("keyUp"))
+
+ return chromedp.Run(ctx, actions...)
+}
+
+func TypeByNodeID(ctx context.Context, nodeID int64, text string) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.KeyEvent(text),
+ )
+}
diff --git a/internal/bridge/cdp_keyboard_test.go b/internal/bridge/cdp_keyboard_test.go
new file mode 100644
index 00000000..ba5f1b5f
--- /dev/null
+++ b/internal/bridge/cdp_keyboard_test.go
@@ -0,0 +1,95 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+)
+
+// TestDispatchNamedKey_RecognisedKeys checks that namedKeyDefs contains the
+// keys most commonly used in automation scripts.
+func TestDispatchNamedKey_RecognisedKeys(t *testing.T) {
+ mustBeKnown := []string{
+ "Enter", "Return", "Tab", "Escape", "Backspace", "Delete",
+ "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
+ "Home", "End", "PageUp", "PageDown",
+ "F1", "F5", "F12",
+ }
+ for _, k := range mustBeKnown {
+ if _, ok := namedKeyDefs[k]; !ok {
+ t.Errorf("namedKeyDefs is missing key %q", k)
+ }
+ }
+}
+
+// TestDispatchNamedKey_EnterInsertText verifies that the Enter key definition
+// produces a "\r" insertText payload so that form submissions and textareas
+// receive a newline rather than the literal string "Enter".
+func TestDispatchNamedKey_EnterInsertText(t *testing.T) {
+ def := namedKeyDefs["Enter"]
+ if def.insertText != "\r" {
+ t.Errorf("Enter key should insert \\r, got %q", def.insertText)
+ }
+ if def.code != "Enter" {
+ t.Errorf("Enter key code should be \"Enter\", got %q", def.code)
+ }
+ if def.virtualKey != 13 {
+ t.Errorf("Enter virtual key should be 13, got %d", def.virtualKey)
+ }
+}
+
+// TestDispatchNamedKey_TabInsertText verifies that Tab produces the "\t"
+// insert-text payload so that focus advances in form fields.
+func TestDispatchNamedKey_TabInsertText(t *testing.T) {
+ def := namedKeyDefs["Tab"]
+ if def.insertText != "\t" {
+ t.Errorf("Tab key should insert \\t, got %q", def.insertText)
+ }
+}
+
+// TestDispatchNamedKey_NonPrintableNoInsertText verifies that non-printable
+// keys (Escape, ArrowLeft, F5 …) do NOT carry an insertText payload.
+func TestDispatchNamedKey_NonPrintableNoInsertText(t *testing.T) {
+ nonPrintable := []string{"Escape", "Backspace", "Delete", "ArrowLeft", "F5"}
+ for _, k := range nonPrintable {
+ def := namedKeyDefs[k]
+ if def.insertText != "" {
+ t.Errorf("key %q should have empty insertText, got %q", k, def.insertText)
+ }
+ }
+}
+
+// TestDispatchNamedKey_ReturnAlias verifies that "Return" is an alias for
+// Enter and produces the same CDP parameters.
+func TestDispatchNamedKey_ReturnAlias(t *testing.T) {
+ enter := namedKeyDefs["Enter"]
+ ret := namedKeyDefs["Return"]
+ if enter != ret {
+ t.Error("\"Return\" keyDef should equal \"Enter\" keyDef")
+ }
+}
+
+// TestDispatchNamedKey_FallbackOnCancelledCtx verifies that an unrecognised key
+// ("a") falls back to chromedp.KeyEvent and returns an error on a cancelled
+// context rather than silently succeeding.
+func TestDispatchNamedKey_FallbackOnCancelledCtx(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ // "a" is not in namedKeyDefs → falls back to chromedp.KeyEvent
+ err := DispatchNamedKey(ctx, "a")
+ if err == nil {
+ t.Error("expected error dispatching key on cancelled context")
+ }
+}
+
+// TestDispatchNamedKey_KnownKeyOnCancelledCtx verifies that a known named key
+// ("Enter") also returns an error on a cancelled context.
+func TestDispatchNamedKey_KnownKeyOnCancelledCtx(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ err := DispatchNamedKey(ctx, "Enter")
+ if err == nil {
+ t.Error("expected error dispatching Enter on cancelled context")
+ }
+}
diff --git a/internal/bridge/cdp_navigation_test.go b/internal/bridge/cdp_navigation_test.go
new file mode 100644
index 00000000..468c675b
--- /dev/null
+++ b/internal/bridge/cdp_navigation_test.go
@@ -0,0 +1,61 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+)
+
+func TestWaitForTitle_ContextCancelled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately
+
+ _, err := WaitForTitle(ctx, 5*time.Second)
+ if err == nil {
+ t.Error("expected error for cancelled context")
+ }
+}
+
+func TestWaitForTitle_NoTimeout(t *testing.T) {
+ ctx, _ := chromedp.NewContext(context.Background())
+
+ // With timeout <= 0, should return immediately
+ title, _ := WaitForTitle(ctx, 0)
+ if title != "" {
+ t.Errorf("expected empty title without browser, got %q", title)
+ }
+}
+
+func TestNavigatePage_ContextCancelled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ err := NavigatePage(ctx, "https://pinchtab.com")
+ if err == nil {
+ t.Error("expected error for cancelled context")
+ }
+}
+
+func TestShouldReplaceBlankHistoryEntry(t *testing.T) {
+ tests := []struct {
+ name string
+ curURL string
+ cur int64
+ entryCount int
+ want bool
+ }{
+ {name: "fresh blank tab", curURL: "about:blank", cur: 0, entryCount: 1, want: true},
+ {name: "already navigated", curURL: "https://example.com", cur: 0, entryCount: 1, want: false},
+ {name: "blank with history", curURL: "about:blank", cur: 1, entryCount: 2, want: false},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := shouldReplaceBlankHistoryEntry(tc.curURL, tc.cur, tc.entryCount); got != tc.want {
+ t.Fatalf("shouldReplaceBlankHistoryEntry(%q, %d, %d) = %v, want %v", tc.curURL, tc.cur, tc.entryCount, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/bridge/cdp_pointer_test.go b/internal/bridge/cdp_pointer_test.go
new file mode 100644
index 00000000..0dd524c7
--- /dev/null
+++ b/internal/bridge/cdp_pointer_test.go
@@ -0,0 +1,59 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+)
+
+func TestClickByCoordinate_ContextCancelled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ err := ClickByCoordinate(ctx, 0, 0)
+ if err == nil {
+ t.Fatal("expected error for cancelled context")
+ }
+}
+
+func TestHoverByCoordinate_ContextCancelled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ err := HoverByCoordinate(ctx, 10, 20)
+ if err == nil {
+ t.Fatal("expected error for cancelled context")
+ }
+}
+
+func TestDoubleClickByCoordinate_ContextCancelled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ err := DoubleClickByCoordinate(ctx, 0, 0)
+ if err == nil {
+ t.Fatal("expected error for cancelled context")
+ }
+}
+
+func TestDoubleClickByCoordinate_RejectNegativeCoordinates(t *testing.T) {
+ ctx := context.Background()
+
+ if err := DoubleClickByCoordinate(ctx, -1, 0); err == nil {
+ t.Fatal("expected dblclick negative X coordinate to fail")
+ }
+
+ if err := DoubleClickByCoordinate(ctx, 0, -1); err == nil {
+ t.Fatal("expected dblclick negative Y coordinate to fail")
+ }
+}
+
+func TestCoordinateActions_RejectNegativeCoordinates(t *testing.T) {
+ ctx := context.Background()
+
+ if err := ClickByCoordinate(ctx, -1, 0); err == nil {
+ t.Fatal("expected click negative coordinate to fail")
+ }
+ if err := HoverByCoordinate(ctx, 0, -1); err == nil {
+ t.Fatal("expected hover negative coordinate to fail")
+ }
+}
diff --git a/internal/bridge/cdp_test.go b/internal/bridge/cdp_test.go
deleted file mode 100644
index 279da24c..00000000
--- a/internal/bridge/cdp_test.go
+++ /dev/null
@@ -1,222 +0,0 @@
-package bridge
-
-import (
- "context"
- "testing"
- "time"
-
- "github.com/chromedp/chromedp"
-)
-
-func TestWaitForTitle_ContextCancelled(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel() // cancel immediately
-
- _, err := WaitForTitle(ctx, 5*time.Second)
- if err == nil {
- t.Error("expected error for cancelled context")
- }
-}
-
-func TestWaitForTitle_NoTimeout(t *testing.T) {
- ctx, _ := chromedp.NewContext(context.Background())
-
- // With timeout <= 0, should return immediately
- title, _ := WaitForTitle(ctx, 0)
- if title != "" {
- t.Errorf("expected empty title without browser, got %q", title)
- }
-}
-
-func TestNavigatePage_ContextCancelled(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- err := NavigatePage(ctx, "https://pinchtab.com")
- if err == nil {
- t.Error("expected error for cancelled context")
- }
-}
-
-func TestSelectByNodeID_UsesValue(t *testing.T) {
- ctx, _ := chromedp.NewContext(context.Background())
- // Without a real browser this will error, but it must NOT silently succeed
- // (the old implementation was a no-op that always returned nil).
- err := SelectByNodeID(ctx, 1, "option-value")
- if err == nil {
- t.Error("expected error without browser connection, got nil (possible no-op)")
- }
-}
-
-func TestGetElementCenter_ParsesBoxModel(t *testing.T) {
- // Test the box model parsing logic
- // Content quad: [x1,y1, x2,y2, x3,y3, x4,y4]
- // For a 100x50 box at position (200, 100):
- // corners: (200,100), (300,100), (300,150), (200,150)
- content := []float64{200, 100, 300, 100, 300, 150, 200, 150}
-
- // Calculate expected center
- expectedX := (content[0] + content[2] + content[4] + content[6]) / 4 // (200+300+300+200)/4 = 250
- expectedY := (content[1] + content[3] + content[5] + content[7]) / 4 // (100+100+150+150)/4 = 125
-
- if expectedX != 250 {
- t.Errorf("expected X=250, got %f", expectedX)
- }
- if expectedY != 125 {
- t.Errorf("expected Y=125, got %f", expectedY)
- }
-}
-
-// TestGetElementCenterJS_ContextCancelled verifies that getElementCenterJS
-// returns an error when the context is already cancelled (no browser panic).
-func TestGetElementCenterJS_ContextCancelled(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- _, _, err := getElementCenterJS(ctx, 1)
- if err == nil {
- t.Error("expected error for cancelled context, got nil")
- }
-}
-
-// TestDispatchNamedKey_RecognisedKeys checks that namedKeyDefs contains the
-// keys most commonly used in automation scripts.
-func TestDispatchNamedKey_RecognisedKeys(t *testing.T) {
- mustBeKnown := []string{
- "Enter", "Return", "Tab", "Escape", "Backspace", "Delete",
- "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
- "Home", "End", "PageUp", "PageDown",
- "F1", "F5", "F12",
- }
- for _, k := range mustBeKnown {
- if _, ok := namedKeyDefs[k]; !ok {
- t.Errorf("namedKeyDefs is missing key %q", k)
- }
- }
-}
-
-// TestDispatchNamedKey_EnterInsertText verifies that the Enter key definition
-// produces a "\r" insertText payload so that form submissions and textareas
-// receive a newline rather than the literal string "Enter".
-func TestDispatchNamedKey_EnterInsertText(t *testing.T) {
- def := namedKeyDefs["Enter"]
- if def.insertText != "\r" {
- t.Errorf("Enter key should insert \\r, got %q", def.insertText)
- }
- if def.code != "Enter" {
- t.Errorf("Enter key code should be \"Enter\", got %q", def.code)
- }
- if def.virtualKey != 13 {
- t.Errorf("Enter virtual key should be 13, got %d", def.virtualKey)
- }
-}
-
-// TestDispatchNamedKey_TabInsertText verifies that Tab produces the "\t"
-// insert-text payload so that focus advances in form fields.
-func TestDispatchNamedKey_TabInsertText(t *testing.T) {
- def := namedKeyDefs["Tab"]
- if def.insertText != "\t" {
- t.Errorf("Tab key should insert \\t, got %q", def.insertText)
- }
-}
-
-// TestDispatchNamedKey_NonPrintableNoInsertText verifies that non-printable
-// keys (Escape, ArrowLeft, F5 …) do NOT carry an insertText payload.
-func TestDispatchNamedKey_NonPrintableNoInsertText(t *testing.T) {
- nonPrintable := []string{"Escape", "Backspace", "Delete", "ArrowLeft", "F5"}
- for _, k := range nonPrintable {
- def := namedKeyDefs[k]
- if def.insertText != "" {
- t.Errorf("key %q should have empty insertText, got %q", k, def.insertText)
- }
- }
-}
-
-// TestDispatchNamedKey_ReturnAlias verifies that "Return" is an alias for
-// Enter and produces the same CDP parameters.
-func TestDispatchNamedKey_ReturnAlias(t *testing.T) {
- enter := namedKeyDefs["Enter"]
- ret := namedKeyDefs["Return"]
- if enter != ret {
- t.Error("\"Return\" keyDef should equal \"Enter\" keyDef")
- }
-}
-
-// TestDispatchNamedKey_FallbackOnCancelledCtx verifies that an unrecognised key
-// ("a") falls back to chromedp.KeyEvent and returns an error on a cancelled
-// context rather than silently succeeding.
-func TestDispatchNamedKey_FallbackOnCancelledCtx(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- // "a" is not in namedKeyDefs → falls back to chromedp.KeyEvent
- err := DispatchNamedKey(ctx, "a")
- if err == nil {
- t.Error("expected error dispatching key on cancelled context")
- }
-}
-
-// TestDispatchNamedKey_KnownKeyOnCancelledCtx verifies that a known named key
-// ("Enter") also returns an error on a cancelled context.
-func TestDispatchNamedKey_KnownKeyOnCancelledCtx(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- err := DispatchNamedKey(ctx, "Enter")
- if err == nil {
- t.Error("expected error dispatching Enter on cancelled context")
- }
-}
-
-func TestClickByCoordinate_ContextCancelled(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- err := ClickByCoordinate(ctx, 0, 0)
- if err == nil {
- t.Fatal("expected error for cancelled context")
- }
-}
-
-func TestHoverByCoordinate_ContextCancelled(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- err := HoverByCoordinate(ctx, 10, 20)
- if err == nil {
- t.Fatal("expected error for cancelled context")
- }
-}
-
-func TestDoubleClickByCoordinate_ContextCancelled(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
-
- err := DoubleClickByCoordinate(ctx, 0, 0)
- if err == nil {
- t.Fatal("expected error for cancelled context")
- }
-}
-
-func TestDoubleClickByCoordinate_RejectNegativeCoordinates(t *testing.T) {
- ctx := context.Background()
-
- if err := DoubleClickByCoordinate(ctx, -1, 0); err == nil {
- t.Fatal("expected dblclick negative X coordinate to fail")
- }
-
- if err := DoubleClickByCoordinate(ctx, 0, -1); err == nil {
- t.Fatal("expected dblclick negative Y coordinate to fail")
- }
-}
-
-func TestCoordinateActions_RejectNegativeCoordinates(t *testing.T) {
- ctx := context.Background()
-
- if err := ClickByCoordinate(ctx, -1, 0); err == nil {
- t.Fatal("expected click negative coordinate to fail")
- }
- if err := HoverByCoordinate(ctx, 0, -1); err == nil {
- t.Fatal("expected hover negative coordinate to fail")
- }
-}
diff --git a/internal/bridge/cdpops/element_ops.go b/internal/bridge/cdpops/element_ops.go
new file mode 100644
index 00000000..67c23c6f
--- /dev/null
+++ b/internal/bridge/cdpops/element_ops.go
@@ -0,0 +1,74 @@
+package cdpops
+
+import (
+ "context"
+ "encoding/json"
+
+ "github.com/chromedp/chromedp"
+)
+
+func FillByNodeID(ctx context.Context, nodeID int64, value string) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var result json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": nodeID,
+ }, &result); err != nil {
+ return err
+ }
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(result, &resolved); err != nil {
+ return err
+ }
+ js := `function(v) { this.value = v; this.dispatchEvent(new Event('input', {bubbles: true})); this.dispatchEvent(new Event('change', {bubbles: true})); }`
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": js,
+ "objectId": resolved.Object.ObjectID,
+ "arguments": []map[string]any{{"value": value}},
+ }, nil)
+ }),
+ )
+}
+
+func SelectByNodeID(ctx context.Context, nodeID int64, value string) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var result json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": nodeID,
+ }, &result); err != nil {
+ return err
+ }
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(result, &resolved); err != nil {
+ return err
+ }
+ js := `function(v) { this.value = v; this.dispatchEvent(new Event('input', {bubbles: true})); this.dispatchEvent(new Event('change', {bubbles: true})); }`
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": js,
+ "objectId": resolved.Object.ObjectID,
+ "arguments": []map[string]any{{"value": value}},
+ }, nil)
+ }),
+ )
+}
+
+func ScrollByNodeID(ctx context.Context, nodeID int64) error {
+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ }))
+}
diff --git a/internal/bridge/cdpops/geometry.go b/internal/bridge/cdpops/geometry.go
new file mode 100644
index 00000000..63086e8c
--- /dev/null
+++ b/internal/bridge/cdpops/geometry.go
@@ -0,0 +1,169 @@
+package cdpops
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/chromedp/chromedp"
+)
+
+// GetElementCenter returns the center coordinates of an element using DOM.getBoxModel.
+func GetElementCenter(ctx context.Context, backendNodeID int64) (x, y float64, err error) {
+ var result json.RawMessage
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getBoxModel", map[string]any{
+ "backendNodeId": backendNodeID,
+ }, &result)
+ }))
+ if err != nil {
+ return 0, 0, err
+ }
+
+ var box struct {
+ Model struct {
+ Content []float64 `json:"content"`
+ } `json:"model"`
+ }
+ if err = json.Unmarshal(result, &box); err != nil {
+ return 0, 0, err
+ }
+
+ if len(box.Model.Content) < 4 {
+ return 0, 0, fmt.Errorf("invalid box model: expected at least 4 coordinates")
+ }
+
+ x = (box.Model.Content[0] + box.Model.Content[2] + box.Model.Content[4] + box.Model.Content[6]) / 4
+ y = (box.Model.Content[1] + box.Model.Content[3] + box.Model.Content[5] + box.Model.Content[7]) / 4
+
+ if x == 0 && y == 0 {
+ return GetElementCenterJS(ctx, backendNodeID)
+ }
+
+ return x, y, nil
+}
+
+// GetElementCenterJS resolves the DOM node and evaluates getBoundingClientRect().
+func GetElementCenterJS(ctx context.Context, backendNodeID int64) (float64, float64, error) {
+ var resolveResult json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": backendNodeID,
+ }, &resolveResult)
+ })); err != nil {
+ return 0, 0, fmt.Errorf("DOM.resolveNode: %w", err)
+ }
+
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {
+ return 0, 0, err
+ }
+ if resolved.Object.ObjectID == "" {
+ return 0, 0, fmt.Errorf("element not found in DOM (backendNodeId=%d)", backendNodeID)
+ }
+
+ const rectFn = `function() {
+ var r = this.getBoundingClientRect();
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
+ }`
+
+ var callResult json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": rectFn,
+ "objectId": resolved.Object.ObjectID,
+ "returnByValue": true,
+ }, &callResult)
+ })); err != nil {
+ return 0, 0, fmt.Errorf("getBoundingClientRect: %w", err)
+ }
+
+ var callRes struct {
+ Result struct {
+ Value struct {
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ } `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &callRes); err != nil {
+ return 0, 0, err
+ }
+
+ return callRes.Result.Value.X, callRes.Result.Value.Y, nil
+}
+
+// ScrollIntoViewAndGetBox scrolls the element into view and returns its box.
+func ScrollIntoViewAndGetBox(ctx context.Context, nodeID int64) (map[string]any, error) {
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ })); err != nil {
+ return nil, fmt.Errorf("scrollIntoViewIfNeeded: %w", err)
+ }
+
+ var resolveResult json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": nodeID,
+ }, &resolveResult)
+ })); err != nil {
+ return nil, fmt.Errorf("DOM.resolveNode: %w", err)
+ }
+
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {
+ return nil, err
+ }
+ if resolved.Object.ObjectID == "" {
+ return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)
+ }
+
+ const boxFn = `function() {
+ var r = this.getBoundingClientRect();
+ return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
+ }`
+
+ var callResult json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": boxFn,
+ "objectId": resolved.Object.ObjectID,
+ "returnByValue": true,
+ }, &callResult)
+ })); err != nil {
+ return nil, fmt.Errorf("getBoundingClientRect: %w", err)
+ }
+
+ var callRes struct {
+ Result struct {
+ Value struct {
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ Width float64 `json:"width"`
+ Height float64 `json:"height"`
+ } `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &callRes); err != nil {
+ return nil, err
+ }
+
+ box := callRes.Result.Value
+ return map[string]any{
+ "scrolled": true,
+ "box": map[string]any{
+ "x": box.X,
+ "y": box.Y,
+ "width": box.Width,
+ "height": box.Height,
+ },
+ }, nil
+}
diff --git a/internal/bridge/cdpops/navigation.go b/internal/bridge/cdpops/navigation.go
new file mode 100644
index 00000000..9f00b57b
--- /dev/null
+++ b/internal/bridge/cdpops/navigation.go
@@ -0,0 +1,211 @@
+package cdpops
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "sync/atomic"
+ "time"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/fetch"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+)
+
+const TargetTypePage = "page"
+
+func NavigatePage(ctx context.Context, url string) error {
+ replaceInitialBlank, _ := shouldReplaceInitialBlankNavigation(ctx)
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return startNavigation(ctx, url, replaceInitialBlank)
+ }))
+ if err != nil {
+ return err
+ }
+
+ ticker := time.NewTicker(200 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ var state string
+ err = chromedp.Run(ctx, chromedp.Evaluate("document.readyState", &state))
+ if err == nil && (state == "interactive" || state == "complete") {
+ return nil
+ }
+ }
+ }
+}
+
+var ErrTooManyRedirects = fmt.Errorf("too many redirects")
+
+func NavigatePageWithRedirectLimit(ctx context.Context, url string, maxRedirects int) error {
+ replaceInitialBlank, _ := shouldReplaceInitialBlankNavigation(ctx)
+
+ if maxRedirects < 0 {
+ return navigateAndWait(ctx, url, replaceInitialBlank)
+ }
+
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return fetch.Enable().Do(ctx)
+ })); err != nil {
+ return fmt.Errorf("fetch enable: %w", err)
+ }
+
+ var redirectCount atomic.Int32
+ var blocked atomic.Bool
+
+ chromedp.ListenTarget(ctx, func(ev interface{}) {
+ e, ok := ev.(*fetch.EventRequestPaused)
+ if !ok {
+ return
+ }
+ go func() {
+ reqID := e.RequestID
+ if e.RedirectedRequestID != "" {
+ count := int(redirectCount.Add(1))
+ if count > maxRedirects {
+ blocked.Store(true)
+ _ = fetch.FailRequest(reqID, network.ErrorReasonBlockedByClient).Do(cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target))
+ return
+ }
+ }
+ _ = fetch.ContinueRequest(reqID).Do(cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target))
+ }()
+ })
+
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return startNavigation(ctx, url, replaceInitialBlank)
+ }))
+
+ _ = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return fetch.Disable().Do(ctx)
+ }))
+
+ if blocked.Load() {
+ return fmt.Errorf("%w: got %d, max %d", ErrTooManyRedirects, redirectCount.Load(), maxRedirects)
+ }
+ if err != nil {
+ return err
+ }
+
+ ticker := time.NewTicker(200 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ var state string
+ err := chromedp.Run(ctx, chromedp.Evaluate("document.readyState", &state))
+ if err == nil && (state == "interactive" || state == "complete") {
+ return nil
+ }
+ }
+ }
+}
+
+// ShouldReplaceBlankHistoryEntry reports whether the first navigation should replace an untouched about:blank entry.
+func ShouldReplaceBlankHistoryEntry(curURL string, cur int64, entryCount int) bool {
+ return curURL == "about:blank" && cur == 0 && entryCount == 1
+}
+
+func shouldReplaceInitialBlankNavigation(ctx context.Context) (bool, error) {
+ var (
+ cur int64
+ entries []*page.NavigationEntry
+ curURL string
+ )
+
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ cur, entries, err = page.GetNavigationHistory().Do(ctx)
+ return err
+ }),
+ chromedp.Location(&curURL),
+ ); err != nil {
+ return false, err
+ }
+
+ return ShouldReplaceBlankHistoryEntry(curURL, cur, len(entries)), nil
+}
+
+func startNavigation(ctx context.Context, url string, replaceInitialBlank bool) error {
+ if !replaceInitialBlank {
+ _, _, _, _, err := page.Navigate(url).Do(ctx)
+ return err
+ }
+
+ encodedURL, err := json.Marshal(url)
+ if err != nil {
+ return fmt.Errorf("encode navigation url: %w", err)
+ }
+
+ return chromedp.Evaluate("window.location.replace("+string(encodedURL)+")", nil).Do(ctx)
+}
+
+func navigateAndWait(ctx context.Context, url string, replaceInitialBlank bool) error {
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return startNavigation(ctx, url, replaceInitialBlank)
+ })); err != nil {
+ return err
+ }
+
+ ticker := time.NewTicker(200 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ var state string
+ err := chromedp.Run(ctx, chromedp.Evaluate("document.readyState", &state))
+ if err == nil && (state == "interactive" || state == "complete") {
+ return nil
+ }
+ }
+ }
+}
+
+func WaitForTitle(ctx context.Context, timeout time.Duration) (string, error) {
+ if timeout <= 0 {
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ return "", err
+ }
+ return title, nil
+ }
+
+ deadline := time.After(timeout)
+ ticker := time.NewTicker(200 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-deadline:
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ return "", err
+ }
+ return title, nil
+ case <-ticker.C:
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ continue
+ }
+ if title != "" && title != "about:blank" {
+ return title, nil
+ }
+ }
+ }
+}
diff --git a/internal/bridge/cdpops/pointer.go b/internal/bridge/cdpops/pointer.go
new file mode 100644
index 00000000..2470f56b
--- /dev/null
+++ b/internal/bridge/cdpops/pointer.go
@@ -0,0 +1,222 @@
+package cdpops
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "github.com/chromedp/chromedp"
+)
+
+func ClickByCoordinate(ctx context.Context, x, y float64) error {
+ if x < 0 || y < 0 {
+ return fmt.Errorf("x/y coordinates must be >= 0")
+ }
+
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mousePressed",
+ "button": "left",
+ "clickCount": 1,
+ "x": x,
+ "y": y,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseReleased",
+ "button": "left",
+ "clickCount": 1,
+ "x": x,
+ "y": y,
+ }, nil)
+ }),
+ )
+}
+
+func ClickByNodeID(ctx context.Context, nodeID int64) error {
+ x, y, err := GetElementCenter(ctx, nodeID)
+ if err != nil {
+ return err
+ }
+
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mousePressed",
+ "button": "left",
+ "clickCount": 1,
+ "x": x, "y": y,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseReleased",
+ "button": "left",
+ "clickCount": 1,
+ "x": x, "y": y,
+ }, nil)
+ }),
+ )
+}
+
+func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {
+ if x < 0 || y < 0 {
+ return fmt.Errorf("x/y coordinates must be >= 0")
+ }
+
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mousePressed",
+ "button": "left",
+ "clickCount": 2,
+ "x": x,
+ "y": y,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseReleased",
+ "button": "left",
+ "clickCount": 2,
+ "x": x,
+ "y": y,
+ }, nil)
+ }),
+ )
+}
+
+func DoubleClickByNodeID(ctx context.Context, nodeID int64) error {
+ x, y, err := GetElementCenter(ctx, nodeID)
+ if err != nil {
+ return err
+ }
+
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mousePressed",
+ "button": "left",
+ "clickCount": 2,
+ "x": x, "y": y,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseReleased",
+ "button": "left",
+ "clickCount": 2,
+ "x": x, "y": y,
+ }, nil)
+ }),
+ )
+}
+
+// DragByNodeID drags an element by (dx, dy) pixels using mousePressed → mouseMoved → mouseReleased.
+func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int) error {
+ x, y, err := GetElementCenter(ctx, nodeID)
+ if err != nil {
+ return err
+ }
+
+ endX := x + float64(dx)
+ endY := y + float64(dy)
+ dist := math.Sqrt(float64(dx*dx + dy*dy))
+ steps := int(dist / 10)
+ if steps < 5 {
+ steps = 5
+ }
+ if steps > 40 {
+ steps = 40
+ }
+
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseMoved",
+ "x": x, "y": y,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mousePressed",
+ "button": "left",
+ "clickCount": 1,
+ "x": x, "y": y,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ for i := 1; i <= steps; i++ {
+ t := float64(i) / float64(steps)
+ mx := x + t*float64(dx)
+ my := y + t*float64(dy)
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseMoved",
+ "buttons": 1,
+ "x": mx, "y": my,
+ }, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseReleased",
+ "button": "left",
+ "clickCount": 1,
+ "x": endX, "y": endY,
+ }, nil)
+ }),
+ )
+}
+
+func HoverByCoordinate(ctx context.Context, x, y float64) error {
+ if x < 0 || y < 0 {
+ return fmt.Errorf("x/y coordinates must be >= 0")
+ }
+
+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseMoved",
+ "x": x,
+ "y": y,
+ }, nil)
+ }))
+}
+
+func HoverByNodeID(ctx context.Context, nodeID int64) error {
+ x, y, err := GetElementCenter(ctx, nodeID)
+ if err != nil {
+ return err
+ }
+
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseMoved",
+ "x": x, "y": y,
+ }, nil)
+ }),
+ )
+}
diff --git a/internal/bridge/cdpops/resource_blocking.go b/internal/bridge/cdpops/resource_blocking.go
new file mode 100644
index 00000000..1930bff0
--- /dev/null
+++ b/internal/bridge/cdpops/resource_blocking.go
@@ -0,0 +1,26 @@
+package cdpops
+
+import (
+ "context"
+
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/chromedp"
+)
+
+var ImageBlockPatterns = []string{
+ "*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico",
+}
+
+var MediaBlockPatterns = append(ImageBlockPatterns,
+ "*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.flac", "*.aac",
+)
+
+// SetResourceBlocking uses Network.setBlockedURLs to block resources by URL pattern.
+func SetResourceBlocking(ctx context.Context, patterns []string) error {
+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ if len(patterns) == 0 {
+ return network.SetBlockedURLs([]string{}).Do(ctx)
+ }
+ return network.SetBlockedURLs(patterns).Do(ctx)
+ }))
+}
diff --git a/internal/bridge/cdpops_facade.go b/internal/bridge/cdpops_facade.go
new file mode 100644
index 00000000..ace55d5d
--- /dev/null
+++ b/internal/bridge/cdpops_facade.go
@@ -0,0 +1,84 @@
+package bridge
+
+import (
+ "context"
+ "time"
+
+ bridgecdpops "github.com/pinchtab/pinchtab/internal/bridge/cdpops"
+)
+
+const TargetTypePage = bridgecdpops.TargetTypePage
+
+var (
+ ImageBlockPatterns = bridgecdpops.ImageBlockPatterns
+ MediaBlockPatterns = bridgecdpops.MediaBlockPatterns
+ ErrTooManyRedirects = bridgecdpops.ErrTooManyRedirects
+)
+
+func NavigatePage(ctx context.Context, url string) error {
+ return bridgecdpops.NavigatePage(ctx, url)
+}
+
+func NavigatePageWithRedirectLimit(ctx context.Context, url string, maxRedirects int) error {
+ return bridgecdpops.NavigatePageWithRedirectLimit(ctx, url, maxRedirects)
+}
+
+func shouldReplaceBlankHistoryEntry(curURL string, cur int64, entryCount int) bool {
+ return bridgecdpops.ShouldReplaceBlankHistoryEntry(curURL, cur, entryCount)
+}
+
+func WaitForTitle(ctx context.Context, timeout time.Duration) (string, error) {
+ return bridgecdpops.WaitForTitle(ctx, timeout)
+}
+
+func SetResourceBlocking(ctx context.Context, patterns []string) error {
+ return bridgecdpops.SetResourceBlocking(ctx, patterns)
+}
+
+func getElementCenterJS(ctx context.Context, backendNodeID int64) (float64, float64, error) {
+ return bridgecdpops.GetElementCenterJS(ctx, backendNodeID)
+}
+
+func ScrollIntoViewAndGetBox(ctx context.Context, nodeID int64) (map[string]any, error) {
+ return bridgecdpops.ScrollIntoViewAndGetBox(ctx, nodeID)
+}
+
+func ClickByCoordinate(ctx context.Context, x, y float64) error {
+ return bridgecdpops.ClickByCoordinate(ctx, x, y)
+}
+
+func ClickByNodeID(ctx context.Context, nodeID int64) error {
+ return bridgecdpops.ClickByNodeID(ctx, nodeID)
+}
+
+func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {
+ return bridgecdpops.DoubleClickByCoordinate(ctx, x, y)
+}
+
+func DoubleClickByNodeID(ctx context.Context, nodeID int64) error {
+ return bridgecdpops.DoubleClickByNodeID(ctx, nodeID)
+}
+
+func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int) error {
+ return bridgecdpops.DragByNodeID(ctx, nodeID, dx, dy)
+}
+
+func HoverByCoordinate(ctx context.Context, x, y float64) error {
+ return bridgecdpops.HoverByCoordinate(ctx, x, y)
+}
+
+func HoverByNodeID(ctx context.Context, nodeID int64) error {
+ return bridgecdpops.HoverByNodeID(ctx, nodeID)
+}
+
+func FillByNodeID(ctx context.Context, nodeID int64, value string) error {
+ return bridgecdpops.FillByNodeID(ctx, nodeID, value)
+}
+
+func SelectByNodeID(ctx context.Context, nodeID int64, value string) error {
+ return bridgecdpops.SelectByNodeID(ctx, nodeID, value)
+}
+
+func ScrollByNodeID(ctx context.Context, nodeID int64) error {
+ return bridgecdpops.ScrollByNodeID(ctx, nodeID)
+}
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index cbb5a6e8..c8fe5683 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -1,439 +1,28 @@
package bridge
import (
- "bytes"
"context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "math/rand"
- "net"
- "net/http"
- "os"
- "os/exec"
- "runtime"
- "strconv"
- "strings"
- "time"
- "github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/assets"
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/human"
)
-// InitChrome initializes a Chrome browser for a Bridge instance
-func InitChrome(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
- slog.Info("starting chrome initialization", "headless", cfg.Headless, "profile", cfg.ProfileDir, "binary", cfg.ChromeBinary)
-
- // Setup allocator
- allocCtx, allocCancel, opts, debugPort := setupAllocator(cfg)
-
- // Start Chrome browser
- browserCtx, browserCancel, err := startChrome(allocCtx, cfg, opts, debugPort)
- if err != nil {
- allocCancel()
- slog.Error("chrome initialization failed", "headless", cfg.Headless, "error", err.Error())
- return nil, nil, nil, nil, fmt.Errorf("failed to start chrome: %w", err)
- }
-
- slog.Info("chrome initialized successfully", "headless", cfg.Headless, "profile", cfg.ProfileDir)
- return allocCtx, allocCancel, browserCtx, browserCancel, nil
-}
-
-func findChromeBinary() string {
- var candidates []string
- if runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" {
- candidates = []string{
- "/usr/bin/chromium-browser",
- "/usr/bin/chromium",
- "/usr/bin/google-chrome",
- "/usr/bin/google-chrome-stable",
- }
- } else {
- candidates = []string{
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
- "/usr/bin/google-chrome",
- "/usr/bin/google-chrome-stable",
- "/usr/bin/chromium",
- "/usr/bin/chromium-browser",
- "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
- "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
- }
- }
-
- for _, path := range candidates {
- if _, err := os.Stat(path); err == nil {
- return path
- }
- }
- return ""
-}
-
-func appendExecAllocatorFlag(opts []chromedp.ExecAllocatorOption, flag string) []chromedp.ExecAllocatorOption {
- name := strings.TrimPrefix(flag, "--")
- if parts := strings.SplitN(name, "=", 2); len(parts) == 2 {
- return append(opts, chromedp.Flag(parts[0], parts[1]))
- }
- return append(opts, chromedp.Flag(name, true))
-}
-
-func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int) {
- opts := []chromedp.ExecAllocatorOption{
- chromedp.NoFirstRun,
- chromedp.NoDefaultBrowserCheck,
- }
- for _, flag := range defaultChromeFlagArgs() {
- opts = appendExecAllocatorFlag(opts, flag)
- }
-
- // Binary path
- chromeBinary := cfg.ChromeBinary
- if chromeBinary == "" {
- chromeBinary = findChromeBinary()
- }
- if chromeBinary != "" {
- opts = append(opts, chromedp.ExecPath(chromeBinary))
- }
-
- // Headless mode: always use 'new' for extension support
- if cfg.Headless {
- opts = append(opts, chromedp.Flag("headless", "new"))
- opts = append(opts, chromedp.Flag("hide-scrollbars", true))
- opts = append(opts, chromedp.Flag("mute-audio", true))
- opts = append(opts, chromedp.DisableGPU)
- } else {
- opts = append(opts, chromedp.Flag("headless", false))
- }
-
- // Extensions
- if len(cfg.ExtensionPaths) > 0 {
- var validPaths []string
- for _, path := range cfg.ExtensionPaths {
- if _, err := os.Stat(path); err == nil {
- validPaths = append(validPaths, path)
- }
- }
- if len(validPaths) > 0 {
- joined := strings.Join(validPaths, ",")
- opts = append(opts, chromedp.Flag("disable-extensions", false))
- opts = append(opts, chromedp.Flag("load-extension", joined))
- opts = append(opts, chromedp.Flag("disable-extensions-except", joined))
- opts = append(opts, chromedp.Flag("enable-automation", false))
- slog.Info("loading extensions", "paths", joined)
- }
- opts = append(opts, chromedp.Flag("enable-automation", false))
- } else {
- opts = append(opts, chromedp.Flag("disable-extensions", true))
- opts = append(opts, chromedp.Flag("enable-automation", false))
- }
-
- // User Data Dir
- if cfg.ProfileDir != "" {
- opts = append(opts, chromedp.UserDataDir(cfg.ProfileDir))
- }
-
- // Window Size
- w, h := randomWindowSize()
- opts = append(opts, chromedp.WindowSize(w, h))
-
- // Timezone
- if cfg.Timezone != "" {
- opts = append(opts, chromedp.Flag("tz", cfg.Timezone))
- }
-
- // Extra Flags
- if cfg.ChromeExtraFlags != "" {
- for _, f := range strings.Fields(cfg.ChromeExtraFlags) {
- opts = appendExecAllocatorFlag(opts, f)
- }
- }
-
- // Debug Port
- debugPort := 0
- if port, err := findFreePort(cfg.InstancePortStart, cfg.InstancePortEnd); err == nil {
- debugPort = port
- opts = append(opts, chromedp.Flag("remote-debugging-port", strconv.Itoa(port)))
- }
- opts = append(opts, chromedp.CombinedOutput(newPrefixedLogWriter(os.Stdout, "chrome")))
-
- // Replace chromedp's default allocateCmdOptions to set Pdeathsig on Linux.
- // Do NOT set Setpgid — Chrome should inherit the parent's process group
- // so the orchestrator can kill the entire bridge group at once.
- opts = append(opts, chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) {
- configureChromeProcess(cmd)
- }))
-
- ctx, cancel := context.WithCancel(context.Background())
- return ctx, cancel, opts, debugPort
-}
-
-func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int) (context.Context, context.CancelFunc, error) {
- return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, false)
-}
-
-func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int, retriedProfileLock bool) (context.Context, context.CancelFunc, error) {
- allocCtx, allocCancel := chromedp.NewExecAllocator(parentCtx, opts...)
- browserCtx, browserCancel := chromedp.NewContext(allocCtx)
-
- stealthSeed := rand.Intn(1000000000)
- human.SetHumanRandSeed(int64(stealthSeed))
- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript
-
- const chromeStartupTimeout = 20 * time.Second
- type runResult struct{ err error }
- runCh := make(chan runResult, 1)
- go func() {
- runCh <- runResult{chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return nil
- }))}
- }()
-
- var err error
- select {
- case res := <-runCh:
- err = res.err
- case <-time.After(chromeStartupTimeout):
- err = fmt.Errorf("chrome startup timeout after %v: %w", chromeStartupTimeout, context.DeadlineExceeded)
- }
-
- if err != nil {
- browserCancel()
- allocCancel()
- errMsg := err.Error()
-
- if !retriedProfileLock && isChromeProfileLockError(errMsg) {
- if recovered, _ := clearStaleChromeProfileLock(cfg.ProfileDir, errMsg); recovered {
- time.Sleep(250 * time.Millisecond)
- return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, true)
- }
- }
-
- if isStartupTimeout(err) && debugPort > 0 {
- slog.Warn("chrome startup timeout (Chrome 145+ regression), trying direct-launch fallback", "port", debugPort)
- time.Sleep(500 * time.Millisecond)
- return startChromeWithRemoteAllocator(parentCtx, cfg, debugPort, stealthSeed, seededScript)
- }
-
- return nil, nil, fmt.Errorf("failed to connect to chrome: %w", err)
- }
-
- // Inject stealth
- if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return injectedScript(ctx, seededScript)
- })); err != nil {
- browserCancel()
- allocCancel()
- return nil, nil, fmt.Errorf("failed to inject stealth script: %w", err)
- }
+const popupGuardInitScript = bridgeruntime.PopupGuardInitScript
- return browserCtx, func() {
- browserCancel()
- allocCancel()
- }, nil
-}
-
-func isStartupTimeout(err error) bool {
- if errors.Is(err, context.DeadlineExceeded) {
- return true
- }
- msg := err.Error()
- return strings.Contains(msg, "deadline exceeded") || strings.Contains(msg, "context deadline exceeded")
-}
-
-func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.RuntimeConfig, debugPort int, stealthSeed int, seededScript string) (context.Context, context.CancelFunc, error) {
- chromeBinary := cfg.ChromeBinary
- if chromeBinary == "" {
- chromeBinary = findChromeBinary()
- }
- if chromeBinary == "" {
- return nil, nil, fmt.Errorf("chrome/chromium not found: please install chrome or chromium, or set 'binary' in config.json")
- }
-
- args := buildChromeArgs(cfg, debugPort)
- // #nosec G204 -- chromeBinary from user config or findChromeBinary() known system paths
- cmd := exec.Command(chromeBinary, args...)
- cmd.Stdout = newPrefixedLogWriter(os.Stdout, "chrome stdout")
- cmd.Stderr = newPrefixedLogWriter(os.Stderr, "chrome stderr")
- if err := cmd.Start(); err != nil {
- return nil, nil, fmt.Errorf("failed to start chrome directly: %w", err)
- }
-
- wsURL, err := waitForChromeDevTools(debugPort, 30*time.Second)
- if err != nil {
- _ = cmd.Process.Kill()
- return nil, nil, fmt.Errorf("chrome devtools not ready on port %d: %w", debugPort, err)
- }
-
- remoteAllocCtx, remoteAllocCancel := chromedp.NewRemoteAllocator(parentCtx, wsURL)
- browserCtx, browserCancel := chromedp.NewContext(remoteAllocCtx)
-
- if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return injectedScript(ctx, seededScript)
- })); err != nil {
- browserCancel()
- remoteAllocCancel()
- _ = cmd.Process.Kill()
- return nil, nil, fmt.Errorf("failed to connect/inject via remote: %w", err)
- }
-
- return browserCtx, func() {
- browserCancel()
- remoteAllocCancel()
- _ = cmd.Process.Kill()
- }, nil
-}
-
-func findFreePort(start, end int) (int, error) {
- for port := start; port <= end; port++ {
- l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
- if err == nil {
- _ = l.Close()
- return port, nil
- }
- }
- return 0, fmt.Errorf("no free port available in range %d-%d", start, end)
-}
-
-func waitForChromeDevTools(port int, timeout time.Duration) (string, error) {
- endpoint := fmt.Sprintf("http://127.0.0.1:%d/json/version", port)
- client := &http.Client{Timeout: 2 * time.Second}
- deadline := time.Now().Add(timeout)
-
- for time.Now().Before(deadline) {
- resp, err := client.Get(endpoint)
- if err == nil {
- var info struct {
- WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
- }
- decodeErr := json.NewDecoder(resp.Body).Decode(&info)
- _ = resp.Body.Close()
- if decodeErr == nil && info.WebSocketDebuggerURL != "" {
- return info.WebSocketDebuggerURL, nil
- }
- }
- time.Sleep(250 * time.Millisecond)
- }
- return "", fmt.Errorf("chrome devtools not ready on port %d after %v", port, timeout)
+// InitChrome initializes a Chrome browser for a Bridge instance.
+func InitChrome(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
+ return bridgeruntime.InitChrome(cfg, bridgeruntime.Hooks{
+ SetHumanRandSeed: SetHumanRandSeed,
+ IsChromeProfileLockError: isChromeProfileLockError,
+ ClearStaleChromeProfile: clearStaleChromeProfileLock,
+ ConfigureChromeProcessCmd: configureChromeProcess,
+ })
}
func defaultChromeFlagArgs() []string {
- return []string{
- "--disable-background-networking",
- "--enable-features=NetworkService,NetworkServiceInProcess",
- "--disable-background-timer-throttling",
- "--disable-backgrounding-occluded-windows",
- "--disable-breakpad",
- "--disable-session-crashed-bubble",
- "--disable-client-side-phishing-detection",
- "--disable-default-apps",
- "--disable-dev-shm-usage",
- "--disable-features=site-per-process,Translate,BlinkGenPropertyTrees",
- "--hide-crash-restore-bubble",
- "--disable-hang-monitor",
- "--disable-ipc-flooding-protection",
- "--disable-metrics-reporting",
- "--disable-popup-blocking",
- "--disable-prompt-on-repost",
- "--disable-renderer-backgrounding",
- "--disable-sync",
- "--force-color-profile=srgb",
- "--metrics-recording-only",
- "--noerrdialogs",
- "--safebrowsing-disable-auto-update",
- "--password-store=basic",
- "--use-mock-keychain",
- "--disable-automation",
- "--disable-blink-features=AutomationControlled",
- "--no-sandbox",
- }
+ return bridgeruntime.DefaultChromeFlagArgs()
}
func buildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
- args := append([]string{fmt.Sprintf("--remote-debugging-port=%d", port)}, defaultChromeFlagArgs()...)
-
- if len(cfg.ExtensionPaths) > 0 {
- joined := strings.Join(cfg.ExtensionPaths, ",")
- args = append(args, "--load-extension="+joined, "--disable-extensions-except="+joined)
- } else {
- args = append(args, "--disable-extensions")
- }
-
- if cfg.Headless {
- args = append(args,
- "--headless=new",
- "--disable-gpu",
- "--enable-unsafe-swiftshader",
- )
- }
-
- if cfg.ProfileDir != "" {
- args = append(args, "--user-data-dir="+cfg.ProfileDir)
- }
-
- w, h := randomWindowSize()
- args = append(args, fmt.Sprintf("--window-size=%d,%d", w, h))
-
- if cfg.Timezone != "" {
- args = append(args, "--tz="+cfg.Timezone)
- }
-
- if cfg.ChromeExtraFlags != "" {
- args = append(args, strings.Fields(cfg.ChromeExtraFlags)...)
- }
-
- return args
-}
-
-func injectedScript(ctx context.Context, script string) error {
- // Use Page.addScriptToEvaluateOnNewDocument to inject the stealth script
- // BEFORE any page JavaScript runs. This is critical for hiding automation
- // signals like navigator.webdriver.
- // Note: This is called from within chromedp.Run/ActionFunc, so we use
- // direct CDP execution instead of nested chromedp.Run to avoid deadlocks.
- return chromedp.FromContext(ctx).Target.Execute(ctx,
- "Page.addScriptToEvaluateOnNewDocument",
- map[string]interface{}{
- "source": script,
- }, nil)
-}
-
-func randomWindowSize() (int, int) {
- sizes := [][2]int{
- {1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},
- {1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},
- }
- s := sizes[rand.Intn(len(sizes))]
- return s[0], s[1]
-}
-
-type prefixedLogWriter struct {
- dst io.Writer
- prefix string
- buf []byte
-}
-
-func newPrefixedLogWriter(dst io.Writer, prefix string) *prefixedLogWriter {
- return &prefixedLogWriter{dst: dst, prefix: prefix, buf: make([]byte, 0, 1024)}
-}
-
-func (w *prefixedLogWriter) Write(p []byte) (int, error) {
- w.buf = append(w.buf, p...)
- for {
- idx := bytes.IndexByte(w.buf, '\n')
- if idx < 0 {
- break
- }
- line := w.buf[:idx]
- w.buf = w.buf[idx+1:]
- if len(line) > 0 {
- if _, err := fmt.Fprintf(w.dst, "%s: %s\n", w.prefix, string(line)); err != nil {
- return 0, err
- }
- }
- }
- return len(p), nil
+ return bridgeruntime.BuildChromeArgs(cfg, port)
}
diff --git a/internal/bridge/init_test.go b/internal/bridge/init_test.go
index e2518af5..6dc24a5d 100644
--- a/internal/bridge/init_test.go
+++ b/internal/bridge/init_test.go
@@ -2,6 +2,7 @@ package bridge
import (
"slices"
+ "strings"
"testing"
"github.com/pinchtab/pinchtab/internal/config"
@@ -21,6 +22,22 @@ func TestBuildChromeArgsSuppressesCrashDialogs(t *testing.T) {
}
}
+func TestBuildChromeArgsHeadlessUsesSoftwareRendering(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{Headless: true}, 9222)
+
+ for _, want := range []string{
+ "--headless=new",
+ "--disable-gpu",
+ "--disable-vulkan",
+ "--use-angle=swiftshader",
+ "--enable-unsafe-swiftshader",
+ } {
+ if !slices.Contains(args, want) {
+ t.Fatalf("missing headless chrome arg %q in %v", want, args)
+ }
+ }
+}
+
func TestDefaultChromeFlagArgsDisablesMetricsReporting(t *testing.T) {
args := defaultChromeFlagArgs()
for _, want := range []string{"--disable-metrics-reporting", "--metrics-recording-only"} {
@@ -36,3 +53,28 @@ func TestDefaultChromeFlagArgsDisablesMetricsReporting(t *testing.T) {
}
}
}
+
+func TestDefaultChromeFlagArgsPreservesPopupBlockingAndSiteIsolation(t *testing.T) {
+ args := defaultChromeFlagArgs()
+ for _, forbidden := range []string{
+ "--disable-popup-blocking",
+ "--no-sandbox",
+ "--disable-features=site-per-process,Translate,BlinkGenPropertyTrees",
+ } {
+ if slices.Contains(args, forbidden) {
+ t.Fatalf("did not expect %s in args: %v", forbidden, args)
+ }
+ }
+
+ if !slices.Contains(args, "--disable-features=Translate,BlinkGenPropertyTrees") {
+ t.Fatalf("expected default disable-features arg to keep non-isolation tweaks, got %v", args)
+ }
+}
+
+func TestPopupGuardInitScriptNeutralizesOpener(t *testing.T) {
+ for _, want := range []string{"window.open", "noopener", "noreferrer", "window.opener"} {
+ if !strings.Contains(popupGuardInitScript, want) {
+ t.Fatalf("expected popup guard script to contain %q", want)
+ }
+ }
+}
diff --git a/internal/human/human.go b/internal/bridge/input_human.go
similarity index 99%
rename from internal/human/human.go
rename to internal/bridge/input_human.go
index d6b837cd..96d7116a 100644
--- a/internal/human/human.go
+++ b/internal/bridge/input_human.go
@@ -1,4 +1,4 @@
-package human
+package bridge
import (
"context"
diff --git a/internal/human/human_test.go b/internal/bridge/input_human_test.go
similarity index 99%
rename from internal/human/human_test.go
rename to internal/bridge/input_human_test.go
index be2afdbc..c9b628e2 100644
--- a/internal/human/human_test.go
+++ b/internal/bridge/input_human_test.go
@@ -1,4 +1,4 @@
-package human
+package bridge
import (
"context"
diff --git a/internal/bridge/metrics.go b/internal/bridge/metrics.go
deleted file mode 100644
index f558e120..00000000
--- a/internal/bridge/metrics.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package bridge
-
-import (
- "strings"
-
- "github.com/chromedp/chromedp"
- "github.com/shirou/gopsutil/v4/process"
-)
-
-// MemoryMetrics holds Chrome memory statistics
-type MemoryMetrics struct {
- // OS-level memory (real RAM usage)
- MemoryMB float64 `json:"memoryMB"` // Total RSS across renderer processes
-
- // Legacy JS-heap fields (for backward compat, now estimated)
- JSHeapUsedMB float64 `json:"jsHeapUsedMB"`
- JSHeapTotalMB float64 `json:"jsHeapTotalMB"`
-
- // Process counts
- Renderers int `json:"renderers"` // Number of renderer processes (≈ tabs)
-
- // Legacy fields (set to 0, kept for API compat)
- Documents int64 `json:"documents"`
- Frames int64 `json:"frames"`
- Nodes int64 `json:"nodes"`
- Listeners int64 `json:"listeners"`
-}
-
-// GetMemoryMetrics retrieves memory metrics for a specific tab
-// Now uses OS-level memory instead of per-tab CDP calls
-func (b *Bridge) GetMemoryMetrics(tabID string) (*MemoryMetrics, error) {
- // For single tab, return aggregated (we can't map tab→PID reliably)
- return b.GetAggregatedMemoryMetrics()
-}
-
-// GetBrowserMemoryMetrics retrieves memory metrics for the entire browser
-func (b *Bridge) GetBrowserMemoryMetrics() (*MemoryMetrics, error) {
- return b.GetAggregatedMemoryMetrics()
-}
-
-// GetAggregatedMemoryMetrics returns real OS memory usage across all Chrome processes
-// Uses process tree approach: walks the browser process and its children
-func (b *Bridge) GetAggregatedMemoryMetrics() (*MemoryMetrics, error) {
- if b.BrowserCtx == nil {
- return nil, nil
- }
-
- // Always use process tree approach - it's more reliable for isolating this instance
- return b.getMemoryViaProcessTree()
-}
-
-// getMemoryViaProcessTree is a fallback that walks the browser process tree
-func (b *Bridge) getMemoryViaProcessTree() (*MemoryMetrics, error) {
- result := &MemoryMetrics{}
-
- // Get browser PID from chromedp
- browser := chromedp.FromContext(b.BrowserCtx)
- if browser == nil || browser.Browser == nil {
- return result, nil
- }
-
- proc := browser.Browser.Process()
- if proc == nil {
- return result, nil
- }
-
- mainPID := int32(proc.Pid)
- p, err := process.NewProcess(mainPID)
- if err != nil {
- return result, err
- }
-
- // Get all children (recursive)
- children, err := p.Children()
- if err != nil {
- // Just count main process
- mem, _ := getProcessMemory(mainPID)
- result.MemoryMB = float64(mem) / (1024 * 1024)
- return result, nil
- }
-
- var totalMem uint64
- rendererCount := 0
-
- // Add main process
- mem, _ := getProcessMemory(mainPID)
- totalMem += mem
-
- // Add children
- for _, child := range children {
- cmdline, _ := child.Cmdline()
- // Filter for renderer processes
- if containsRenderer(cmdline) {
- rendererCount++
- }
- childMem, _ := getProcessMemory(child.Pid)
- totalMem += childMem
- }
-
- result.MemoryMB = float64(totalMem) / (1024 * 1024)
- result.Renderers = rendererCount
- result.JSHeapUsedMB = result.MemoryMB * 0.4
- result.JSHeapTotalMB = result.MemoryMB * 0.5
-
- return result, nil
-}
-
-// getProcessMemory returns RSS memory in bytes for a process
-func getProcessMemory(pid int32) (uint64, error) {
- p, err := process.NewProcess(pid)
- if err != nil {
- return 0, err
- }
-
- mem, err := p.MemoryInfo()
- if err != nil {
- return 0, err
- }
-
- // RSS is the resident set size (actual RAM used)
- return mem.RSS, nil
-}
-
-// containsRenderer checks if cmdline indicates a renderer process
-func containsRenderer(cmdline string) bool {
- return strings.Contains(cmdline, "--type=renderer") || strings.Contains(cmdline, "--type=tab")
-}
diff --git a/internal/bridge/network_test.go b/internal/bridge/network_test.go
index c005f5df..774234c0 100644
--- a/internal/bridge/network_test.go
+++ b/internal/bridge/network_test.go
@@ -161,7 +161,7 @@ func TestNetworkMonitor_GetBuffer(t *testing.T) {
}
// Create buffer via getOrCreateBuffer
- buf := nm.getOrCreateBuffer("tab1")
+ buf := nm.GetOrCreateBufferForTest("tab1")
if buf == nil {
t.Fatal("expected non-nil buffer")
}
@@ -175,7 +175,7 @@ func TestNetworkMonitor_GetBuffer(t *testing.T) {
func TestNetworkMonitor_ClearTab(t *testing.T) {
nm := NewNetworkMonitor(50)
- buf := nm.getOrCreateBuffer("tab1")
+ buf := nm.GetOrCreateBufferForTest("tab1")
buf.Add(NetworkEntry{RequestID: "r1"})
nm.ClearTab("tab1")
@@ -186,8 +186,8 @@ func TestNetworkMonitor_ClearTab(t *testing.T) {
func TestNetworkMonitor_ClearAll(t *testing.T) {
nm := NewNetworkMonitor(50)
- buf1 := nm.getOrCreateBuffer("tab1")
- buf2 := nm.getOrCreateBuffer("tab2")
+ buf1 := nm.GetOrCreateBufferForTest("tab1")
+ buf2 := nm.GetOrCreateBufferForTest("tab2")
buf1.Add(NetworkEntry{RequestID: "r1"})
buf2.Add(NetworkEntry{RequestID: "r2"})
@@ -300,31 +300,31 @@ func TestNetworkMonitor_GetOrCreateBufferWithSize(t *testing.T) {
nm := NewNetworkMonitor(50)
// Custom size
- buf := nm.getOrCreateBufferWithSize("tab1", 200)
+ buf := nm.GetOrCreateBufferWithSizeForTest("tab1", 200)
if buf == nil {
t.Fatal("expected non-nil buffer")
}
- if buf.maxSize != 200 {
- t.Errorf("expected maxSize 200, got %d", buf.maxSize)
+ if buf.MaxSizeForTest() != 200 {
+ t.Errorf("expected maxSize 200, got %d", buf.MaxSizeForTest())
}
// Same tab returns existing buffer (doesn't resize)
- buf2 := nm.getOrCreateBufferWithSize("tab1", 500)
+ buf2 := nm.GetOrCreateBufferWithSizeForTest("tab1", 500)
if buf2 != buf {
t.Error("expected same buffer instance")
}
// Zero size uses default
- buf3 := nm.getOrCreateBufferWithSize("tab2", 0)
- if buf3.maxSize != 50 {
- t.Errorf("expected default maxSize 50, got %d", buf3.maxSize)
+ buf3 := nm.GetOrCreateBufferWithSizeForTest("tab2", 0)
+ if buf3.MaxSizeForTest() != 50 {
+ t.Errorf("expected default maxSize 50, got %d", buf3.MaxSizeForTest())
}
}
func TestNewNetworkBuffer_CustomSize(t *testing.T) {
buf := NewNetworkBuffer(500)
- if buf.maxSize != 500 {
- t.Errorf("expected maxSize 500, got %d", buf.maxSize)
+ if buf.MaxSizeForTest() != 500 {
+ t.Errorf("expected maxSize 500, got %d", buf.MaxSizeForTest())
}
// Add more than default (100) entries to verify custom size works
@@ -338,21 +338,21 @@ func TestNewNetworkBuffer_CustomSize(t *testing.T) {
func TestNewNetworkBuffer_ZeroDefaultsTo100(t *testing.T) {
buf := NewNetworkBuffer(0)
- if buf.maxSize != DefaultNetworkBufferSize {
- t.Errorf("expected maxSize %d, got %d", DefaultNetworkBufferSize, buf.maxSize)
+ if buf.MaxSizeForTest() != DefaultNetworkBufferSize {
+ t.Errorf("expected maxSize %d, got %d", DefaultNetworkBufferSize, buf.MaxSizeForTest())
}
}
func TestNewNetworkBuffer_ClampsOversizedBuffer(t *testing.T) {
buf := NewNetworkBuffer(config.MaxNetworkBufferSize + 1)
- if buf.maxSize != config.MaxNetworkBufferSize {
- t.Errorf("expected maxSize %d, got %d", config.MaxNetworkBufferSize, buf.maxSize)
+ if buf.MaxSizeForTest() != config.MaxNetworkBufferSize {
+ t.Errorf("expected maxSize %d, got %d", config.MaxNetworkBufferSize, buf.MaxSizeForTest())
}
}
func TestNewNetworkMonitor_ClampsOversizedBuffer(t *testing.T) {
nm := NewNetworkMonitor(config.MaxNetworkBufferSize + 1)
- if nm.bufSize != config.MaxNetworkBufferSize {
- t.Errorf("expected bufSize %d, got %d", config.MaxNetworkBufferSize, nm.bufSize)
+ if nm.BufferSizeForTest() != config.MaxNetworkBufferSize {
+ t.Errorf("expected bufSize %d, got %d", config.MaxNetworkBufferSize, nm.BufferSizeForTest())
}
}
diff --git a/internal/bridge/observe/metrics.go b/internal/bridge/observe/metrics.go
new file mode 100644
index 00000000..4b38007f
--- /dev/null
+++ b/internal/bridge/observe/metrics.go
@@ -0,0 +1,95 @@
+package observe
+
+import (
+ "context"
+ "strings"
+
+ "github.com/chromedp/chromedp"
+ "github.com/shirou/gopsutil/v4/process"
+)
+
+// MemoryMetrics holds Chrome memory statistics.
+type MemoryMetrics struct {
+ MemoryMB float64 `json:"memoryMB"`
+
+ JSHeapUsedMB float64 `json:"jsHeapUsedMB"`
+ JSHeapTotalMB float64 `json:"jsHeapTotalMB"`
+
+ Renderers int `json:"renderers"`
+
+ Documents int64 `json:"documents"`
+ Frames int64 `json:"frames"`
+ Nodes int64 `json:"nodes"`
+ Listeners int64 `json:"listeners"`
+}
+
+// GetAggregatedMemoryMetrics returns OS-level memory usage across the browser process tree.
+func GetAggregatedMemoryMetrics(browserCtx context.Context) (*MemoryMetrics, error) {
+ if browserCtx == nil {
+ return nil, nil
+ }
+
+ result := &MemoryMetrics{}
+ browser := chromedp.FromContext(browserCtx)
+ if browser == nil || browser.Browser == nil {
+ return result, nil
+ }
+
+ proc := browser.Browser.Process()
+ if proc == nil {
+ return result, nil
+ }
+
+ mainPID := int32(proc.Pid)
+ p, err := process.NewProcess(mainPID)
+ if err != nil {
+ return result, err
+ }
+
+ children, err := p.Children()
+ if err != nil {
+ mem, _ := getProcessMemory(mainPID)
+ result.MemoryMB = float64(mem) / (1024 * 1024)
+ return result, nil
+ }
+
+ var totalMem uint64
+ rendererCount := 0
+
+ mem, _ := getProcessMemory(mainPID)
+ totalMem += mem
+
+ for _, child := range children {
+ cmdline, _ := child.Cmdline()
+ if containsRenderer(cmdline) {
+ rendererCount++
+ }
+ childMem, _ := getProcessMemory(child.Pid)
+ totalMem += childMem
+ }
+
+ result.MemoryMB = float64(totalMem) / (1024 * 1024)
+ result.Renderers = rendererCount
+ result.JSHeapUsedMB = result.MemoryMB * 0.4
+ result.JSHeapTotalMB = result.MemoryMB * 0.5
+
+ return result, nil
+}
+
+func getProcessMemory(pid int32) (uint64, error) {
+ p, err := process.NewProcess(pid)
+ if err != nil {
+ return 0, err
+ }
+
+ mem, err := p.MemoryInfo()
+ if err != nil {
+ return 0, err
+ }
+
+ return mem.RSS, nil
+}
+
+func containsRenderer(cmdline string) bool {
+ return strings.Contains(cmdline, "--type=renderer") || strings.Contains(cmdline, "--type=tab")
+}
diff --git a/internal/bridge/network.go b/internal/bridge/observe/network.go
similarity index 90%
rename from internal/bridge/network.go
rename to internal/bridge/observe/network.go
index 1b78a3ab..79d89e31 100644
--- a/internal/bridge/network.go
+++ b/internal/bridge/observe/network.go
@@ -1,4 +1,4 @@
-package bridge
+package observe
import (
"context"
@@ -32,8 +32,8 @@ type NetworkEntry struct {
MimeType string `json:"mimeType,omitempty"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime,omitempty"`
- Duration float64 `json:"duration,omitempty"` // milliseconds
- Size int64 `json:"size,omitempty"` // encoded data length
+ Duration float64 `json:"duration,omitempty"`
+ Size int64 `json:"size,omitempty"`
Error string `json:"error,omitempty"`
Finished bool `json:"finished"`
Failed bool `json:"failed"`
@@ -43,7 +43,7 @@ type NetworkEntry struct {
type NetworkBuffer struct {
mu sync.RWMutex
entries []NetworkEntry
- index map[string]int // requestId -> position in entries
+ index map[string]int
maxSize int
subMu sync.Mutex
@@ -71,16 +71,13 @@ func (nb *NetworkBuffer) Add(entry NetworkEntry) {
isNew := false
if idx, ok := nb.index[entry.RequestID]; ok {
- // Update existing entry
nb.entries[idx] = entry
} else {
isNew = true
if len(nb.entries) >= nb.maxSize {
- // Remove oldest entry
oldest := nb.entries[0]
delete(nb.index, oldest.RequestID)
nb.entries = nb.entries[1:]
- // Rebuild index after shift
for i, e := range nb.entries {
nb.index[e.RequestID] = i
}
@@ -90,7 +87,6 @@ func (nb *NetworkBuffer) Add(entry NetworkEntry) {
}
nb.mu.Unlock()
- // Notify subscribers of new entries (non-blocking)
if isNew {
nb.subMu.Lock()
for _, ch := range nb.subscribers {
@@ -104,7 +100,6 @@ func (nb *NetworkBuffer) Add(entry NetworkEntry) {
}
// Subscribe returns a channel that receives new entries as they are added.
-// Call Unsubscribe with the returned ID when done.
func (nb *NetworkBuffer) Subscribe() (int, <-chan NetworkEntry) {
nb.subMu.Lock()
defer nb.subMu.Unlock()
@@ -176,12 +171,19 @@ func (nb *NetworkBuffer) Len() int {
return len(nb.entries)
}
+// MaxSizeForTest exposes the effective ring-buffer size for package-external tests.
+func (nb *NetworkBuffer) MaxSizeForTest() int {
+ nb.mu.RLock()
+ defer nb.mu.RUnlock()
+ return nb.maxSize
+}
+
// NetworkFilter defines criteria for filtering network entries.
type NetworkFilter struct {
URLPattern string
Method string
- StatusRange string // e.g. "4xx", "5xx", "200"
- ResourceType string // xhr, fetch, document, etc.
+ StatusRange string
+ ResourceType string
Limit int
}
@@ -196,24 +198,23 @@ func (f NetworkFilter) Match(e NetworkEntry) bool {
if f.ResourceType != "" && !strings.EqualFold(e.ResourceType, f.ResourceType) {
return false
}
- if f.StatusRange != "" && !matchStatusRange(e.Status, f.StatusRange) {
+ if f.StatusRange != "" && !MatchStatusRange(e.Status, f.StatusRange) {
return false
}
return true
}
-func matchStatusRange(status int, pattern string) bool {
+// MatchStatusRange checks whether a status code matches an exact or wildcard range.
+func MatchStatusRange(status int, pattern string) bool {
if pattern == "" {
return true
}
- // Exact match: "200", "404"
if len(pattern) == 3 && pattern[1] != 'x' && pattern[2] != 'x' {
var code int
if _, err := fmt.Sscanf(pattern, "%d", &code); err == nil {
return status == code
}
}
- // Range match: "4xx", "5xx", "2xx"
if len(pattern) == 3 && (pattern[1] == 'x' || pattern[2] == 'x') {
prefix := int(pattern[0] - '0')
return status/100 == prefix
@@ -224,7 +225,7 @@ func matchStatusRange(status int, pattern string) bool {
// NetworkMonitor manages network capture for all tabs.
type NetworkMonitor struct {
mu sync.RWMutex
- buffers map[string]*NetworkBuffer // tabID -> buffer
+ buffers map[string]*NetworkBuffer
listeners map[string]context.CancelFunc
bufSize int
}
@@ -242,13 +243,10 @@ func NewNetworkMonitor(bufferSize int) *NetworkMonitor {
}
}
-// getOrCreateBuffer returns the buffer for a tab, creating one if needed.
func (nm *NetworkMonitor) getOrCreateBuffer(tabID string) *NetworkBuffer {
return nm.getOrCreateBufferWithSize(tabID, 0)
}
-// getOrCreateBufferWithSize returns the buffer for a tab, creating one with the given size if needed.
-// If size is 0, the monitor's default buffer size is used.
func (nm *NetworkMonitor) getOrCreateBufferWithSize(tabID string, size int) *NetworkBuffer {
nm.mu.Lock()
defer nm.mu.Unlock()
@@ -263,11 +261,16 @@ func (nm *NetworkMonitor) getOrCreateBufferWithSize(tabID string, size int) *Net
return buf
}
-// GetOrCreateBufferForTest exposes getOrCreateBuffer for use in tests outside this package.
+// GetOrCreateBufferForTest exposes getOrCreateBuffer for tests outside this package.
func (nm *NetworkMonitor) GetOrCreateBufferForTest(tabID string) *NetworkBuffer {
return nm.getOrCreateBuffer(tabID)
}
+// GetOrCreateBufferWithSizeForTest exposes buffer sizing for package-external tests.
+func (nm *NetworkMonitor) GetOrCreateBufferWithSizeForTest(tabID string, size int) *NetworkBuffer {
+ return nm.getOrCreateBufferWithSize(tabID, size)
+}
+
// GetBuffer returns the buffer for a tab (nil if none).
func (nm *NetworkMonitor) GetBuffer(tabID string) *NetworkBuffer {
nm.mu.RLock()
@@ -275,24 +278,28 @@ func (nm *NetworkMonitor) GetBuffer(tabID string) *NetworkBuffer {
return nm.buffers[tabID]
}
+// BufferSizeForTest exposes the monitor default size for package-external tests.
+func (nm *NetworkMonitor) BufferSizeForTest() int {
+ nm.mu.RLock()
+ defer nm.mu.RUnlock()
+ return nm.bufSize
+}
+
// StartCapture enables network monitoring on a tab's CDP session.
func (nm *NetworkMonitor) StartCapture(tabCtx context.Context, tabID string) error {
return nm.StartCaptureWithSize(tabCtx, tabID, 0)
}
// StartCaptureWithSize enables network monitoring with a specific buffer size.
-// If bufferSize is 0, the monitor's default is used.
func (nm *NetworkMonitor) StartCaptureWithSize(tabCtx context.Context, tabID string, bufferSize int) error {
buf := nm.getOrCreateBufferWithSize(tabID, bufferSize)
- // Enable Network domain
if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
return network.Enable().Do(ctx)
})); err != nil {
return fmt.Errorf("network enable: %w", err)
}
- // Listen for network events
chromedp.ListenTarget(tabCtx, func(ev interface{}) {
switch e := ev.(type) {
case *network.EventRequestWillBeSent:
@@ -442,7 +449,6 @@ func GetResponseBodyDirect(ctx context.Context, requestID string) (string, bool,
return err
}
body = string(resp)
- // The Do method already decodes base64 for us
base64Encoded = false
return nil
}))
diff --git a/internal/bridge/snapshot.go b/internal/bridge/observe/snapshot.go
similarity index 93%
rename from internal/bridge/snapshot.go
rename to internal/bridge/observe/snapshot.go
index 78be9bd3..7766a04f 100644
--- a/internal/bridge/snapshot.go
+++ b/internal/bridge/observe/snapshot.go
@@ -1,4 +1,4 @@
-package bridge
+package observe
import (
"context"
@@ -31,21 +31,22 @@ type RawAXNode struct {
BackendDOMNodeID int64 `json:"backendDOMNodeId"`
}
-type rawAXTreeResponse struct {
+type RawAXTreeResponse struct {
Nodes []RawAXNode `json:"nodes"`
}
-type rawFrameTree struct {
+type RawFrameTree struct {
Frame struct {
ID string `json:"id"`
} `json:"frame"`
- ChildFrames []rawFrameTree `json:"childFrames"`
+ ChildFrames []RawFrameTree `json:"childFrames"`
}
-func frameIDs(tree rawFrameTree) []string {
+// FrameIDs returns every frame id in a frame tree, including descendants.
+func FrameIDs(tree RawFrameTree) []string {
ids := make([]string, 0, 1+len(tree.ChildFrames))
- var walk func(rawFrameTree)
- walk = func(t rawFrameTree) {
+ var walk func(RawFrameTree)
+ walk = func(t RawFrameTree) {
if t.Frame.ID != "" {
ids = append(ids, t.Frame.ID)
}
@@ -58,7 +59,6 @@ func frameIDs(tree rawFrameTree) []string {
}
// FetchAXTree returns the merged accessibility tree for the current page and any child frames.
-// If frame-aware enumeration fails, it falls back to the page-wide tree so snapshotting keeps working.
func FetchAXTree(ctx context.Context) ([]RawAXNode, error) {
var frameTreeResult json.RawMessage
if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
@@ -68,13 +68,13 @@ func FetchAXTree(ctx context.Context) ([]RawAXNode, error) {
}
var frameResp struct {
- FrameTree rawFrameTree `json:"frameTree"`
+ FrameTree RawFrameTree `json:"frameTree"`
}
if err := json.Unmarshal(frameTreeResult, &frameResp); err != nil {
return fetchAXTreeForFrame(ctx, "")
}
- ids := frameIDs(frameResp.FrameTree)
+ ids := FrameIDs(frameResp.FrameTree)
if len(ids) == 0 {
return fetchAXTreeForFrame(ctx, "")
}
@@ -115,7 +115,7 @@ func fetchAXTreeForFrame(ctx context.Context, frameID string) ([]RawAXNode, erro
})); err != nil {
return nil, err
}
- var treeResp rawAXTreeResponse
+ var treeResp RawAXTreeResponse
if err := json.Unmarshal(rawResult, &treeResp); err != nil {
return nil, err
}
diff --git a/internal/bridge/snapshot_format.go b/internal/bridge/observe/snapshot_format.go
similarity index 97%
rename from internal/bridge/snapshot_format.go
rename to internal/bridge/observe/snapshot_format.go
index 20788e3e..cd844c82 100644
--- a/internal/bridge/snapshot_format.go
+++ b/internal/bridge/observe/snapshot_format.go
@@ -1,8 +1,6 @@
-package bridge
+package observe
-import (
- "strings"
-)
+import "strings"
func FormatSnapshotText(nodes []A11yNode) string {
var b strings.Builder
diff --git a/internal/bridge/observe_facade.go b/internal/bridge/observe_facade.go
new file mode 100644
index 00000000..c8c434d8
--- /dev/null
+++ b/internal/bridge/observe_facade.go
@@ -0,0 +1,86 @@
+package bridge
+
+import (
+ "context"
+
+ bridgeobserve "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+const (
+ DefaultNetworkBufferSize = bridgeobserve.DefaultNetworkBufferSize
+ FilterInteractive = bridgeobserve.FilterInteractive
+)
+
+var InteractiveRoles = bridgeobserve.InteractiveRoles
+
+type A11yNode = bridgeobserve.A11yNode
+type RawAXNode = bridgeobserve.RawAXNode
+type RawAXValue = bridgeobserve.RawAXValue
+type RawAXProp = bridgeobserve.RawAXProp
+type rawFrameTree = bridgeobserve.RawFrameTree
+
+type NetworkEntry = bridgeobserve.NetworkEntry
+type NetworkBuffer = bridgeobserve.NetworkBuffer
+type NetworkFilter = bridgeobserve.NetworkFilter
+type NetworkMonitor = bridgeobserve.NetworkMonitor
+type MemoryMetrics = bridgeobserve.MemoryMetrics
+
+func frameIDs(tree rawFrameTree) []string {
+ return bridgeobserve.FrameIDs(tree)
+}
+
+func FetchAXTree(ctx context.Context) ([]RawAXNode, error) {
+ return bridgeobserve.FetchAXTree(ctx)
+}
+
+func BuildSnapshot(nodes []RawAXNode, filter string, maxDepth int) ([]A11yNode, map[string]int64) {
+ return bridgeobserve.BuildSnapshot(nodes, filter, maxDepth)
+}
+
+func FilterSubtree(nodes []RawAXNode, scopeBackendID int64) []RawAXNode {
+ return bridgeobserve.FilterSubtree(nodes, scopeBackendID)
+}
+
+func DiffSnapshot(prev, curr []A11yNode) (added, changed, removed []A11yNode) {
+ return bridgeobserve.DiffSnapshot(prev, curr)
+}
+
+func FormatSnapshotText(nodes []A11yNode) string {
+ return bridgeobserve.FormatSnapshotText(nodes)
+}
+
+func FormatSnapshotCompact(nodes []A11yNode) string {
+ return bridgeobserve.FormatSnapshotCompact(nodes)
+}
+
+func TruncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNode, bool) {
+ return bridgeobserve.TruncateToTokens(nodes, maxTokens, format)
+}
+
+func NewNetworkBuffer(size int) *NetworkBuffer {
+ return bridgeobserve.NewNetworkBuffer(size)
+}
+
+func NewNetworkMonitor(bufferSize int) *NetworkMonitor {
+ return bridgeobserve.NewNetworkMonitor(bufferSize)
+}
+
+func matchStatusRange(status int, pattern string) bool {
+ return bridgeobserve.MatchStatusRange(status, pattern)
+}
+
+func GetResponseBodyDirect(ctx context.Context, requestID string) (string, bool, error) {
+ return bridgeobserve.GetResponseBodyDirect(ctx, requestID)
+}
+
+func (b *Bridge) GetMemoryMetrics(tabID string) (*MemoryMetrics, error) {
+ return b.GetAggregatedMemoryMetrics()
+}
+
+func (b *Bridge) GetBrowserMemoryMetrics() (*MemoryMetrics, error) {
+ return b.GetAggregatedMemoryMetrics()
+}
+
+func (b *Bridge) GetAggregatedMemoryMetrics() (*MemoryMetrics, error) {
+ return bridgeobserve.GetAggregatedMemoryMetrics(b.BrowserCtx)
+}
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
new file mode 100644
index 00000000..1eb6d6d2
--- /dev/null
+++ b/internal/bridge/runtime/init.go
@@ -0,0 +1,483 @@
+package runtime
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "math/rand"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ goruntime "runtime"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type Hooks struct {
+ SetHumanRandSeed func(int64)
+ IsChromeProfileLockError func(string) bool
+ ClearStaleChromeProfile func(profileDir, errMsg string) (bool, error)
+ ConfigureChromeProcessCmd func(*exec.Cmd)
+}
+
+// InitChrome initializes a Chrome browser for a Bridge instance.
+func InitChrome(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
+ slog.Info("starting chrome initialization", "headless", cfg.Headless, "profile", cfg.ProfileDir, "binary", cfg.ChromeBinary)
+
+ allocCtx, allocCancel, opts, debugPort := setupAllocator(cfg, hooks)
+ browserCtx, browserCancel, err := startChrome(allocCtx, cfg, opts, debugPort, hooks)
+ if err != nil {
+ allocCancel()
+ slog.Error("chrome initialization failed", "headless", cfg.Headless, "error", err.Error())
+ return nil, nil, nil, nil, fmt.Errorf("failed to start chrome: %w", err)
+ }
+
+ slog.Info("chrome initialized successfully", "headless", cfg.Headless, "profile", cfg.ProfileDir)
+ return allocCtx, allocCancel, browserCtx, browserCancel, nil
+}
+
+func findChromeBinary() string {
+ var candidates []string
+ if goruntime.GOARCH == "arm64" || goruntime.GOARCH == "arm" {
+ candidates = []string{
+ "/usr/bin/chromium-browser",
+ "/usr/bin/chromium",
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ }
+ } else {
+ candidates = []string{
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ "/usr/bin/chromium",
+ "/usr/bin/chromium-browser",
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
+ }
+ }
+
+ for _, path := range candidates {
+ if _, err := os.Stat(path); err == nil {
+ return path
+ }
+ }
+ return ""
+}
+
+func appendExecAllocatorFlag(opts []chromedp.ExecAllocatorOption, flag string) []chromedp.ExecAllocatorOption {
+ name := strings.TrimPrefix(flag, "--")
+ if parts := strings.SplitN(name, "=", 2); len(parts) == 2 {
+ return append(opts, chromedp.Flag(parts[0], parts[1]))
+ }
+ return append(opts, chromedp.Flag(name, true))
+}
+
+func setupAllocator(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int) {
+ opts := []chromedp.ExecAllocatorOption{
+ chromedp.NoFirstRun,
+ chromedp.NoDefaultBrowserCheck,
+ }
+ for _, flag := range DefaultChromeFlagArgs() {
+ opts = appendExecAllocatorFlag(opts, flag)
+ }
+
+ chromeBinary := cfg.ChromeBinary
+ if chromeBinary == "" {
+ chromeBinary = findChromeBinary()
+ }
+ if chromeBinary != "" {
+ opts = append(opts, chromedp.ExecPath(chromeBinary))
+ }
+
+ if cfg.Headless {
+ opts = append(opts, chromedp.Flag("headless", "new"))
+ opts = append(opts, chromedp.Flag("hide-scrollbars", true))
+ opts = append(opts, chromedp.Flag("mute-audio", true))
+ opts = append(opts, chromedp.Flag("disable-vulkan", true))
+ opts = append(opts, chromedp.Flag("use-angle", "swiftshader"))
+ opts = append(opts, chromedp.DisableGPU)
+ } else {
+ opts = append(opts, chromedp.Flag("headless", false))
+ }
+
+ if len(cfg.ExtensionPaths) > 0 {
+ var validPaths []string
+ for _, path := range cfg.ExtensionPaths {
+ if _, err := os.Stat(path); err == nil {
+ validPaths = append(validPaths, path)
+ }
+ }
+ if len(validPaths) > 0 {
+ joined := strings.Join(validPaths, ",")
+ opts = append(opts, chromedp.Flag("disable-extensions", false))
+ opts = append(opts, chromedp.Flag("load-extension", joined))
+ opts = append(opts, chromedp.Flag("disable-extensions-except", joined))
+ opts = append(opts, chromedp.Flag("enable-automation", false))
+ slog.Info("loading extensions", "paths", joined)
+ }
+ opts = append(opts, chromedp.Flag("enable-automation", false))
+ } else {
+ opts = append(opts, chromedp.Flag("disable-extensions", true))
+ opts = append(opts, chromedp.Flag("enable-automation", false))
+ }
+
+ if cfg.ProfileDir != "" {
+ opts = append(opts, chromedp.UserDataDir(cfg.ProfileDir))
+ }
+
+ w, h := randomWindowSize()
+ opts = append(opts, chromedp.WindowSize(w, h))
+
+ if cfg.Timezone != "" {
+ opts = append(opts, chromedp.Flag("tz", cfg.Timezone))
+ }
+
+ if cfg.ChromeExtraFlags != "" {
+ for _, f := range strings.Fields(cfg.ChromeExtraFlags) {
+ opts = appendExecAllocatorFlag(opts, f)
+ }
+ }
+ for _, flag := range appendChromeCompatibilityFlags(nil) {
+ opts = appendExecAllocatorFlag(opts, flag)
+ }
+
+ debugPort := 0
+ if port, err := findFreePort(cfg.InstancePortStart, cfg.InstancePortEnd); err == nil {
+ debugPort = port
+ opts = append(opts, chromedp.Flag("remote-debugging-port", strconv.Itoa(port)))
+ }
+ opts = append(opts, chromedp.CombinedOutput(newPrefixedLogWriter(os.Stdout, "chrome")))
+ opts = append(opts, chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) {
+ if hooks.ConfigureChromeProcessCmd != nil {
+ hooks.ConfigureChromeProcessCmd(cmd)
+ }
+ }))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ return ctx, cancel, opts, debugPort
+}
+
+func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks) (context.Context, context.CancelFunc, error) {
+ return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, hooks, false)
+}
+
+func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks, retriedProfileLock bool) (context.Context, context.CancelFunc, error) {
+ allocCtx, allocCancel := chromedp.NewExecAllocator(parentCtx, opts...)
+ browserCtx, browserCancel := chromedp.NewContext(allocCtx)
+
+ stealthSeed := rand.Intn(1000000000)
+ if hooks.SetHumanRandSeed != nil {
+ hooks.SetHumanRandSeed(int64(stealthSeed))
+ }
+ seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript + "\n" + PopupGuardInitScript
+
+ const chromeStartupTimeout = 20 * time.Second
+ type runResult struct{ err error }
+ runCh := make(chan runResult, 1)
+ go func() {
+ runCh <- runResult{chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return nil
+ }))}
+ }()
+
+ var err error
+ select {
+ case res := <-runCh:
+ err = res.err
+ case <-time.After(chromeStartupTimeout):
+ err = fmt.Errorf("chrome startup timeout after %v: %w", chromeStartupTimeout, context.DeadlineExceeded)
+ }
+
+ if err != nil {
+ browserCancel()
+ allocCancel()
+ errMsg := err.Error()
+
+ if !retriedProfileLock && hooks.IsChromeProfileLockError != nil && hooks.IsChromeProfileLockError(errMsg) {
+ if hooks.ClearStaleChromeProfile != nil {
+ if recovered, _ := hooks.ClearStaleChromeProfile(cfg.ProfileDir, errMsg); recovered {
+ time.Sleep(250 * time.Millisecond)
+ return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, hooks, true)
+ }
+ }
+ }
+
+ if isStartupTimeout(err) && debugPort > 0 {
+ slog.Warn("chrome startup timeout (Chrome 145+ regression), trying direct-launch fallback", "port", debugPort)
+ time.Sleep(500 * time.Millisecond)
+ return startChromeWithRemoteAllocator(parentCtx, cfg, debugPort, seededScript)
+ }
+
+ return nil, nil, fmt.Errorf("failed to connect to chrome: %w", err)
+ }
+
+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return injectedScript(ctx, seededScript)
+ })); err != nil {
+ browserCancel()
+ allocCancel()
+ return nil, nil, fmt.Errorf("failed to inject stealth script: %w", err)
+ }
+
+ return browserCtx, func() {
+ browserCancel()
+ allocCancel()
+ }, nil
+}
+
+func isStartupTimeout(err error) bool {
+ if errors.Is(err, context.DeadlineExceeded) {
+ return true
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "deadline exceeded") || strings.Contains(msg, "context deadline exceeded")
+}
+
+func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.RuntimeConfig, debugPort int, seededScript string) (context.Context, context.CancelFunc, error) {
+ chromeBinary := cfg.ChromeBinary
+ if chromeBinary == "" {
+ chromeBinary = findChromeBinary()
+ }
+ if chromeBinary == "" {
+ return nil, nil, fmt.Errorf("chrome/chromium not found: please install chrome or chromium, or set 'binary' in config.json")
+ }
+
+ args := BuildChromeArgs(cfg, debugPort)
+ // #nosec G204 -- chromeBinary from user config or findChromeBinary() known system paths
+ cmd := exec.Command(chromeBinary, args...)
+ cmd.Stdout = newPrefixedLogWriter(os.Stdout, "chrome stdout")
+ cmd.Stderr = newPrefixedLogWriter(os.Stderr, "chrome stderr")
+ if err := cmd.Start(); err != nil {
+ return nil, nil, fmt.Errorf("failed to start chrome directly: %w", err)
+ }
+
+ wsURL, err := waitForChromeDevTools(debugPort, 30*time.Second)
+ if err != nil {
+ _ = cmd.Process.Kill()
+ return nil, nil, fmt.Errorf("chrome devtools not ready on port %d: %w", debugPort, err)
+ }
+
+ remoteAllocCtx, remoteAllocCancel := chromedp.NewRemoteAllocator(parentCtx, wsURL)
+ browserCtx, browserCancel := chromedp.NewContext(remoteAllocCtx)
+
+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return injectedScript(ctx, seededScript)
+ })); err != nil {
+ browserCancel()
+ remoteAllocCancel()
+ _ = cmd.Process.Kill()
+ return nil, nil, fmt.Errorf("failed to connect/inject via remote: %w", err)
+ }
+
+ return browserCtx, func() {
+ browserCancel()
+ remoteAllocCancel()
+ _ = cmd.Process.Kill()
+ }, nil
+}
+
+func findFreePort(start, end int) (int, error) {
+ for port := start; port <= end; port++ {
+ l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
+ if err == nil {
+ _ = l.Close()
+ return port, nil
+ }
+ }
+ return 0, fmt.Errorf("no free port available in range %d-%d", start, end)
+}
+
+func waitForChromeDevTools(port int, timeout time.Duration) (string, error) {
+ endpoint := fmt.Sprintf("http://127.0.0.1:%d/json/version", port)
+ client := &http.Client{Timeout: 2 * time.Second}
+ deadline := time.Now().Add(timeout)
+
+ for time.Now().Before(deadline) {
+ resp, err := client.Get(endpoint)
+ if err == nil {
+ var info struct {
+ WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
+ }
+ decodeErr := json.NewDecoder(resp.Body).Decode(&info)
+ _ = resp.Body.Close()
+ if decodeErr == nil && info.WebSocketDebuggerURL != "" {
+ return info.WebSocketDebuggerURL, nil
+ }
+ }
+ time.Sleep(250 * time.Millisecond)
+ }
+ return "", fmt.Errorf("chrome devtools not ready on port %d after %v", port, timeout)
+}
+
+func DefaultChromeFlagArgs() []string {
+ return []string{
+ "--disable-background-networking",
+ "--enable-features=NetworkService,NetworkServiceInProcess",
+ "--disable-background-timer-throttling",
+ "--disable-backgrounding-occluded-windows",
+ "--disable-breakpad",
+ "--disable-session-crashed-bubble",
+ "--disable-client-side-phishing-detection",
+ "--disable-default-apps",
+ "--disable-dev-shm-usage",
+ "--disable-features=Translate,BlinkGenPropertyTrees",
+ "--hide-crash-restore-bubble",
+ "--disable-hang-monitor",
+ "--disable-ipc-flooding-protection",
+ "--disable-metrics-reporting",
+ "--disable-prompt-on-repost",
+ "--disable-renderer-backgrounding",
+ "--disable-sync",
+ "--force-color-profile=srgb",
+ "--metrics-recording-only",
+ "--noerrdialogs",
+ "--safebrowsing-disable-auto-update",
+ "--password-store=basic",
+ "--use-mock-keychain",
+ "--disable-automation",
+ "--disable-blink-features=AutomationControlled",
+ }
+}
+
+func appendChromeCompatibilityFlags(args []string) []string {
+ if goruntime.GOOS == "linux" && os.Geteuid() == 0 {
+ return append(args, "--no-sandbox")
+ }
+ return args
+}
+
+func BuildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
+ args := append([]string{fmt.Sprintf("--remote-debugging-port=%d", port)}, DefaultChromeFlagArgs()...)
+
+ if len(cfg.ExtensionPaths) > 0 {
+ joined := strings.Join(cfg.ExtensionPaths, ",")
+ args = append(args, "--load-extension="+joined, "--disable-extensions-except="+joined)
+ } else {
+ args = append(args, "--disable-extensions")
+ }
+
+ if cfg.Headless {
+ args = append(args,
+ "--headless=new",
+ "--disable-gpu",
+ "--disable-vulkan",
+ "--use-angle=swiftshader",
+ "--enable-unsafe-swiftshader",
+ )
+ }
+
+ if cfg.ProfileDir != "" {
+ args = append(args, "--user-data-dir="+cfg.ProfileDir)
+ }
+
+ w, h := randomWindowSize()
+ args = append(args, fmt.Sprintf("--window-size=%d,%d", w, h))
+
+ if cfg.Timezone != "" {
+ args = append(args, "--tz="+cfg.Timezone)
+ }
+
+ if cfg.ChromeExtraFlags != "" {
+ args = append(args, strings.Fields(cfg.ChromeExtraFlags)...)
+ }
+
+ return appendChromeCompatibilityFlags(args)
+}
+
+const PopupGuardInitScript = `(function() {
+ const mergeWindowFeatures = function(features) {
+ const parts = typeof features === 'string'
+ ? features.split(',').map(function(part) { return String(part).trim(); }).filter(Boolean)
+ : [];
+ const seen = new Set(parts.map(function(part) { return part.toLowerCase(); }));
+ if (!seen.has('noopener')) {
+ parts.push('noopener');
+ }
+ if (!seen.has('noreferrer')) {
+ parts.push('noreferrer');
+ }
+ return parts.join(',');
+ };
+
+ try {
+ const originalOpen = window.open;
+ if (typeof originalOpen === 'function') {
+ Object.defineProperty(window, 'open', {
+ configurable: true,
+ writable: true,
+ value: function(url, target, features) {
+ return originalOpen.call(window, url, target, mergeWindowFeatures(features));
+ }
+ });
+ }
+ } catch (_) {}
+
+ try {
+ Object.defineProperty(window, 'opener', {
+ configurable: true,
+ get: function() { return null; },
+ set: function() { return true; }
+ });
+ } catch (_) {
+ try {
+ window.opener = null;
+ } catch (_) {}
+ }
+})();`
+
+func injectedScript(ctx context.Context, script string) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx,
+ "Page.addScriptToEvaluateOnNewDocument",
+ map[string]interface{}{
+ "source": script,
+ }, nil)
+}
+
+func randomWindowSize() (int, int) {
+ sizes := [][2]int{
+ {1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},
+ {1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},
+ }
+ s := sizes[rand.Intn(len(sizes))]
+ return s[0], s[1]
+}
+
+type prefixedLogWriter struct {
+ dst io.Writer
+ prefix string
+ buf []byte
+}
+
+func newPrefixedLogWriter(dst io.Writer, prefix string) *prefixedLogWriter {
+ return &prefixedLogWriter{dst: dst, prefix: prefix, buf: make([]byte, 0, 1024)}
+}
+
+func (w *prefixedLogWriter) Write(p []byte) (int, error) {
+ w.buf = append(w.buf, p...)
+ for {
+ idx := bytes.IndexByte(w.buf, '\n')
+ if idx < 0 {
+ break
+ }
+ line := w.buf[:idx]
+ w.buf = w.buf[idx+1:]
+ if len(line) > 0 {
+ if _, err := fmt.Fprintf(w.dst, "%s: %s\n", w.prefix, string(line)); err != nil {
+ return 0, err
+ }
+ }
+ }
+ return len(p), nil
+}
diff --git a/internal/bridge/tab_executor.go b/internal/bridge/tab_executor.go
deleted file mode 100644
index ab435d90..00000000
--- a/internal/bridge/tab_executor.go
+++ /dev/null
@@ -1,194 +0,0 @@
-package bridge
-
-import (
- "context"
- "fmt"
- "log/slog"
- "runtime"
- "sync"
- "time"
-)
-
-// TabExecutor provides safe parallel execution across tabs.
-//
-// Each tab executes tasks sequentially (one at a time), but multiple tabs
-// can execute concurrently up to a configurable limit. This prevents
-// resource exhaustion on constrained devices (Raspberry Pi, low-memory
-// servers) while enabling parallelism where hardware allows.
-//
-// Architecture:
-//
-// Tab1 ─── sequential actions ───►
-// Tab2 ─── sequential actions ───► (concurrent across tabs)
-// Tab3 ─── sequential actions ───►
-type TabExecutor struct {
- semaphore chan struct{} // limits concurrent tab executions
- tabLocks map[string]*sync.Mutex // per-tab sequential execution
- mu sync.Mutex // protects tabLocks map
- maxParallel int
-}
-
-// NewTabExecutor creates a TabExecutor with the given concurrency limit.
-// If maxParallel <= 0, DefaultMaxParallel() is used.
-func NewTabExecutor(maxParallel int) *TabExecutor {
- if maxParallel <= 0 {
- maxParallel = DefaultMaxParallel()
- }
- return &TabExecutor{
- semaphore: make(chan struct{}, maxParallel),
- tabLocks: make(map[string]*sync.Mutex),
- maxParallel: maxParallel,
- }
-}
-
-// DefaultMaxParallel returns a safe default based on available CPUs.
-// Capped at 8 to prevent resource exhaustion on large machines.
-func DefaultMaxParallel() int {
- n := runtime.NumCPU() * 2
- if n > 8 {
- n = 8
- }
- if n < 1 {
- n = 1
- }
- return n
-}
-
-// MaxParallel returns the configured concurrency limit.
-func (te *TabExecutor) MaxParallel() int {
- return te.maxParallel
-}
-
-// tabMutex returns the per-tab mutex, creating one if needed.
-func (te *TabExecutor) tabMutex(tabID string) *sync.Mutex {
- te.mu.Lock()
- defer te.mu.Unlock()
- m, ok := te.tabLocks[tabID]
- if !ok {
- m = &sync.Mutex{}
- te.tabLocks[tabID] = m
- }
- return m
-}
-
-// Execute runs a task for the given tab, ensuring:
-// - Only one task runs per tab at a time (per-tab sequential execution)
-// - At most maxParallel tabs execute concurrently (global semaphore)
-// - Panics inside the task are recovered and returned as errors
-// - Context cancellation/timeout is respected
-//
-// The task function receives the same context passed to Execute. Callers
-// should use context.WithTimeout to bound execution time.
-func (te *TabExecutor) Execute(ctx context.Context, tabID string, task func(ctx context.Context) error) error {
- if tabID == "" {
- return fmt.Errorf("tabID must not be empty")
- }
- if ctx.Err() != nil {
- return ctx.Err()
- }
-
- // Acquire global semaphore (respect context cancellation)
- select {
- case te.semaphore <- struct{}{}:
- defer func() { <-te.semaphore }()
- case <-ctx.Done():
- return fmt.Errorf("tab %s: waiting for execution slot: %w", tabID, ctx.Err())
- }
-
- // Acquire per-tab lock for sequential execution within a tab
- tabMu := te.tabMutex(tabID)
- locked := make(chan struct{})
- go func() {
- tabMu.Lock()
- close(locked)
- }()
-
- select {
- case <-locked:
- defer tabMu.Unlock()
- case <-ctx.Done():
- // If we timed out waiting for the per-tab lock, we need to clean up.
- // Launch a goroutine to wait for the lock and immediately release it.
- go func() {
- <-locked
- tabMu.Unlock()
- }()
- return fmt.Errorf("tab %s: waiting for tab lock: %w", tabID, ctx.Err())
- }
-
- // Execute the task with panic recovery
- return te.safeRun(ctx, tabID, task)
-}
-
-// safeRun executes the task with panic recovery.
-func (te *TabExecutor) safeRun(ctx context.Context, tabID string, task func(ctx context.Context) error) (err error) {
- defer func() {
- if r := recover(); r != nil {
- slog.Error("panic recovered in tab execution",
- "tabId", tabID,
- "panic", fmt.Sprintf("%v", r),
- )
- err = fmt.Errorf("tab %s: panic: %v", tabID, r)
- }
- }()
- return task(ctx)
-}
-
-// RemoveTab cleans up the per-tab mutex when a tab is closed.
-// It deletes the entry from the map first, then acquires the old mutex
-// to wait for any in-flight task to complete before returning.
-//
-// Note: after deletion, a concurrent Execute call for the same tabID
-// will create a fresh mutex via tabMutex(). This is intentional — the
-// old tab is being removed and a new tab with the same ID should start
-// with a clean slate. Callers (CloseTab, CleanStaleTabs) ensure the
-// tab context is cancelled before calling RemoveTab, so in-flight tasks
-// will exit promptly.
-func (te *TabExecutor) RemoveTab(tabID string) {
- te.mu.Lock()
- m, ok := te.tabLocks[tabID]
- if !ok {
- te.mu.Unlock()
- return
- }
- delete(te.tabLocks, tabID)
- te.mu.Unlock()
-
- // Wait for any in-flight task holding this mutex to finish.
- // We acquire the lock to block until the active task releases it,
- // then immediately release — the mutex is orphaned after this.
- m.Lock()
- defer m.Unlock() //nolint:staticcheck // SA2001: intentional barrier—blocks until in-flight task completes
-}
-
-// ActiveTabs returns the number of tabs that have associated mutexes.
-func (te *TabExecutor) ActiveTabs() int {
- te.mu.Lock()
- defer te.mu.Unlock()
- return len(te.tabLocks)
-}
-
-// Stats returns execution statistics.
-type ExecutorStats struct {
- MaxParallel int `json:"maxParallel"`
- ActiveTabs int `json:"activeTabs"`
- SemaphoreUsed int `json:"semaphoreUsed"`
- SemaphoreFree int `json:"semaphoreFree"`
-}
-
-func (te *TabExecutor) Stats() ExecutorStats {
- used := len(te.semaphore)
- return ExecutorStats{
- MaxParallel: te.maxParallel,
- ActiveTabs: te.ActiveTabs(),
- SemaphoreUsed: used,
- SemaphoreFree: te.maxParallel - used,
- }
-}
-
-// ExecuteWithTimeout is a convenience wrapper that creates a timeout context.
-func (te *TabExecutor) ExecuteWithTimeout(ctx context.Context, tabID string, timeout time.Duration, task func(ctx context.Context) error) error {
- tCtx, cancel := context.WithTimeout(ctx, timeout)
- defer cancel()
- return te.Execute(tCtx, tabID, task)
-}
diff --git a/internal/bridge/tab_executor_test.go b/internal/bridge/tab_executor_test.go
index 05963b45..50b39bfe 100644
--- a/internal/bridge/tab_executor_test.go
+++ b/internal/bridge/tab_executor_test.go
@@ -82,7 +82,7 @@ func TestTabExecutor_ContextCancellation(t *testing.T) {
te := NewTabExecutor(1)
// Fill semaphore
- te.semaphore <- struct{}{}
+ te.AcquireExecutionSlotForTest()
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
@@ -95,7 +95,7 @@ func TestTabExecutor_ContextCancellation(t *testing.T) {
}
// Release semaphore
- <-te.semaphore
+ te.ReleaseExecutionSlotForTest()
}
func TestTabExecutor_CancelledContextBeforeExecute(t *testing.T) {
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index be0cfabc..f2134e82 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -12,7 +12,7 @@ import (
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/idutil"
+ "github.com/pinchtab/pinchtab/internal/ids"
)
type TabSetupFunc func(ctx context.Context)
@@ -20,7 +20,7 @@ type TabSetupFunc func(ctx context.Context)
type TabManager struct {
browserCtx context.Context
config *config.RuntimeConfig
- idMgr *idutil.Manager
+ idMgr *ids.Manager
tabs map[string]*TabEntry
accessed map[string]bool
snapshots map[string]*RefCache
@@ -28,12 +28,13 @@ type TabManager struct {
dialogMgr *DialogManager
currentTab string // ID of the most recently used tab
executor *TabExecutor
+ guardOnce sync.Once
mu sync.RWMutex
}
-func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *idutil.Manager, onTabSetup TabSetupFunc) *TabManager {
+func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *ids.Manager, onTabSetup TabSetupFunc) *TabManager {
if idMgr == nil {
- idMgr = idutil.NewManager()
+ idMgr = ids.NewManager()
}
maxParallel := 0
if cfg != nil {
@@ -56,6 +57,51 @@ func (tm *TabManager) SetDialogManager(dm *DialogManager) {
tm.dialogMgr = dm
}
+func shouldBlockPopupTarget(info *target.Info) bool {
+ return info != nil && info.Type == TargetTypePage && info.OpenerID != ""
+}
+
+func (tm *TabManager) StartBrowserGuards() {
+ if tm == nil || tm.browserCtx == nil {
+ return
+ }
+
+ tm.guardOnce.Do(func() {
+ if err := chromedp.Run(tm.browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ c := chromedp.FromContext(ctx)
+ if c == nil || c.Browser == nil {
+ return fmt.Errorf("no browser executor")
+ }
+ return target.SetDiscoverTargets(true).Do(cdp.WithExecutor(ctx, c.Browser))
+ })); err != nil {
+ slog.Warn("browser popup guard unavailable", "err", err)
+ return
+ }
+
+ chromedp.ListenBrowser(tm.browserCtx, func(ev any) {
+ created, ok := ev.(*target.EventTargetCreated)
+ if !ok || !shouldBlockPopupTarget(created.TargetInfo) {
+ return
+ }
+
+ info := created.TargetInfo
+ go tm.closePopupTarget(info.TargetID, info.OpenerID, info.URL)
+ })
+ })
+}
+
+func (tm *TabManager) closePopupTarget(targetID, openerID target.ID, url string) {
+ closeCtx, cancel := context.WithTimeout(tm.browserCtx, 5*time.Second)
+ defer cancel()
+
+ if err := target.CloseTarget(targetID).Do(cdp.WithExecutor(closeCtx, chromedp.FromContext(closeCtx).Browser)); err != nil {
+ slog.Debug("popup close failed", "targetId", targetID, "openerId", openerID, "url", url, "err", err)
+ return
+ }
+
+ slog.Info("blocked popup target", "targetId", targetID, "openerId", openerID, "url", url)
+}
+
func (tm *TabManager) markAccessed(tabID string) {
tm.mu.Lock()
tm.accessed[tabID] = true
@@ -245,17 +291,12 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
// Use target.CreateTarget CDP protocol call to create a new tab.
// This works for both local and remote (CDP_URL) allocators.
- navURL := "about:blank"
- if url != "" {
- navURL = url
- }
-
var targetID target.ID
createCtx, createCancel := context.WithTimeout(tm.browserCtx, 10*time.Second)
if err := chromedp.Run(createCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
- targetID, err = target.CreateTarget(navURL).Do(ctx)
+ targetID, err = target.CreateTarget("about:blank").Do(ctx)
return err
}),
); err != nil {
@@ -289,6 +330,17 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
_ = SetResourceBlocking(ctx, blockPatterns)
}
+ if url != "" && url != "about:blank" {
+ navCtx, navCancel := context.WithTimeout(ctx, 30*time.Second)
+ if err := chromedp.Run(navCtx, chromedp.Navigate(url)); err != nil {
+ navCancel()
+ cancel()
+ _ = target.CloseTarget(targetID).Do(cdp.WithExecutor(tm.browserCtx, chromedp.FromContext(tm.browserCtx).Browser))
+ return "", nil, nil, fmt.Errorf("navigate: %w", err)
+ }
+ navCancel()
+ }
+
rawCDPID := string(targetID)
tabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)
now := time.Now()
@@ -305,6 +357,8 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
tm.currentTab = tabID
tm.mu.Unlock()
+ tm.startTabPolicyWatcher(tabID, ctx)
+
return tabID, ctx, cancel, nil
}
@@ -472,18 +526,22 @@ func (tm *TabManager) DeleteRefCache(tabID string) {
func (tm *TabManager) RegisterTab(tabID string, ctx context.Context) {
now := time.Now()
tm.mu.Lock()
- defer tm.mu.Unlock()
tm.tabs[tabID] = &TabEntry{Ctx: ctx, CreatedAt: now, LastUsed: now}
tm.currentTab = tabID
+ tm.mu.Unlock()
+
+ tm.startTabPolicyWatcher(tabID, ctx)
}
// RegisterTabWithCancel registers a tab ID with its context and cancel function.
func (tm *TabManager) RegisterTabWithCancel(tabID, rawCDPID string, ctx context.Context, cancel context.CancelFunc) {
now := time.Now()
tm.mu.Lock()
- defer tm.mu.Unlock()
tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID, CreatedAt: now, LastUsed: now}
tm.currentTab = tabID
+ tm.mu.Unlock()
+
+ tm.startTabPolicyWatcher(tabID, ctx)
}
// Execute runs a task for a tab through the TabExecutor, ensuring per-tab
diff --git a/internal/bridge/tab_policy.go b/internal/bridge/tab_policy.go
new file mode 100644
index 00000000..4c536d8a
--- /dev/null
+++ b/internal/bridge/tab_policy.go
@@ -0,0 +1,129 @@
+package bridge
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/idpi"
+)
+
+type TabPolicyState struct {
+ CurrentURL string
+ Threat bool
+ Blocked bool
+ Reason string
+ UpdatedAt time.Time
+}
+
+func EvaluateTabPolicy(rawURL string, cfg config.IDPIConfig) TabPolicyState {
+ result := idpi.CheckDomain(rawURL, cfg)
+ return TabPolicyState{
+ CurrentURL: rawURL,
+ Threat: result.Threat,
+ Blocked: result.Blocked,
+ Reason: result.Reason,
+ UpdatedAt: time.Now(),
+ }
+}
+
+func (tm *TabManager) idpiDomainPolicyActive() bool {
+ return tm != nil &&
+ tm.config != nil &&
+ tm.config.IDPI.Enabled &&
+ len(tm.config.IDPI.AllowedDomains) > 0
+}
+
+func (tm *TabManager) startTabPolicyWatcher(tabID string, ctx context.Context) {
+ if !tm.idpiDomainPolicyActive() || ctx == nil {
+ return
+ }
+
+ tm.mu.Lock()
+ entry := tm.tabs[tabID]
+ if entry == nil || entry.Watching {
+ tm.mu.Unlock()
+ return
+ }
+ entry.Watching = true
+ tm.mu.Unlock()
+
+ tm.refreshTabPolicyFromContext(tabID, ctx)
+
+ chromedp.ListenTarget(ctx, func(ev any) {
+ switch e := ev.(type) {
+ case *page.EventFrameNavigated:
+ if e.Frame == nil || e.Frame.ParentID != "" {
+ return
+ }
+ tm.updateTabPolicy(tabID, e.Frame.URL)
+ case *page.EventNavigatedWithinDocument:
+ go tm.refreshTabPolicyFromContext(tabID, ctx)
+ }
+ })
+}
+
+func (tm *TabManager) refreshTabPolicyFromContext(tabID string, ctx context.Context) {
+ if !tm.idpiDomainPolicyActive() || ctx == nil {
+ return
+ }
+
+ lookupCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+
+ var currentURL string
+ if err := chromedp.Run(lookupCtx, chromedp.Location(&currentURL)); err != nil {
+ slog.Debug("tab policy refresh failed", "tabId", tabID, "err", err)
+ return
+ }
+
+ tm.updateTabPolicy(tabID, currentURL)
+}
+
+func (tm *TabManager) updateTabPolicy(tabID, rawURL string) TabPolicyState {
+ state := EvaluateTabPolicy(rawURL, tm.config.IDPI)
+
+ tm.mu.Lock()
+ if entry := tm.tabs[tabID]; entry != nil {
+ entry.Policy = state
+ }
+ tm.mu.Unlock()
+
+ if state.Threat {
+ level := slog.LevelWarn
+ if !state.Blocked {
+ level = slog.LevelInfo
+ }
+ slog.Log(context.Background(), level, "tab domain policy updated",
+ "tabId", tabID,
+ "url", state.CurrentURL,
+ "blocked", state.Blocked,
+ "reason", state.Reason,
+ )
+ }
+
+ return state
+}
+
+func (tm *TabManager) GetTabPolicyState(tabID string) (TabPolicyState, bool) {
+ tm.mu.RLock()
+ defer tm.mu.RUnlock()
+
+ entry := tm.tabs[tabID]
+ if entry == nil || entry.Policy.UpdatedAt.IsZero() {
+ return TabPolicyState{}, false
+ }
+ return entry.Policy, true
+}
+
+func (tm *TabManager) SetTabPolicyState(tabID string, state TabPolicyState) {
+ tm.mu.Lock()
+ defer tm.mu.Unlock()
+
+ if entry := tm.tabs[tabID]; entry != nil {
+ entry.Policy = state
+ }
+}
diff --git a/internal/bridge/dialog.go b/internal/bridge/tabs/dialog.go
similarity index 71%
rename from internal/bridge/dialog.go
rename to internal/bridge/tabs/dialog.go
index b49bf6e8..5c13184a 100644
--- a/internal/bridge/dialog.go
+++ b/internal/bridge/tabs/dialog.go
@@ -1,4 +1,4 @@
-package bridge
+package tabs
import (
"context"
@@ -12,47 +12,42 @@ import (
// DialogState represents a pending JavaScript dialog.
type DialogState struct {
- Type string `json:"type"` // "alert", "confirm", "prompt", "beforeunload"
- Message string `json:"message"` // dialog message text
+ Type string `json:"type"`
+ Message string `json:"message"`
DefaultPrompt string `json:"defaultPrompt,omitempty"`
- HasBrowserHandler bool `json:"-"` // whether auto-accept handled it already
+ HasBrowserHandler bool `json:"-"`
}
// DialogManager tracks pending JavaScript dialogs per tab.
type DialogManager struct {
mu sync.RWMutex
- pending map[string]*DialogState // tabID → pending dialog
+ pending map[string]*DialogState
}
-// NewDialogManager creates a new DialogManager.
func NewDialogManager() *DialogManager {
return &DialogManager{
pending: make(map[string]*DialogState),
}
}
-// SetPending stores a pending dialog for a tab.
func (dm *DialogManager) SetPending(tabID string, state *DialogState) {
dm.mu.Lock()
defer dm.mu.Unlock()
dm.pending[tabID] = state
}
-// GetPending returns the pending dialog for a tab, or nil.
func (dm *DialogManager) GetPending(tabID string) *DialogState {
dm.mu.RLock()
defer dm.mu.RUnlock()
return dm.pending[tabID]
}
-// ClearPending removes the pending dialog for a tab.
func (dm *DialogManager) ClearPending(tabID string) {
dm.mu.Lock()
defer dm.mu.Unlock()
delete(dm.pending, tabID)
}
-// GetAndClear atomically gets and clears the pending dialog.
func (dm *DialogManager) GetAndClear(tabID string) *DialogState {
dm.mu.Lock()
defer dm.mu.Unlock()
@@ -61,15 +56,12 @@ func (dm *DialogManager) GetAndClear(tabID string) *DialogState {
return state
}
-// HandleDialog accepts or dismisses the current dialog on a tab via CDP.
func HandleDialog(ctx context.Context, accept bool, promptText string) error {
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return page.HandleJavaScriptDialog(accept).WithPromptText(promptText).Do(ctx)
}))
}
-// ListenDialogEvents sets up a CDP event listener for JavaScript dialog events
-// on the given context. When autoAccept is true, dialogs are automatically accepted.
func ListenDialogEvents(ctx context.Context, tabID string, dm *DialogManager, autoAccept bool) {
chromedp.ListenTarget(ctx, func(ev interface{}) {
switch e := ev.(type) {
@@ -83,14 +75,11 @@ func ListenDialogEvents(ctx context.Context, tabID string, dm *DialogManager, au
if autoAccept {
state.HasBrowserHandler = true
- // Auto-accept: handle immediately
if err := HandleDialog(ctx, true, e.DefaultPrompt); err != nil {
slog.Warn("auto-accept dialog failed", "tabId", tabID, "err", err)
- // Still store it so manual handling can retry
dm.SetPending(tabID, state)
} else {
slog.Debug("dialog auto-accepted", "tabId", tabID, "type", e.Type)
- // Don't store — already handled
}
} else {
dm.SetPending(tabID, state)
@@ -103,22 +92,18 @@ func ListenDialogEvents(ctx context.Context, tabID string, dm *DialogManager, au
})
}
-// EnableDialogEvents enables Page domain events needed for dialog tracking.
func EnableDialogEvents(ctx context.Context) error {
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return page.Enable().Do(ctx)
}))
}
-// DialogResult is the response returned after handling a dialog.
type DialogResult struct {
Type string `json:"type"`
Message string `json:"message"`
Handled bool `json:"handled"`
}
-// HandlePendingDialog handles the pending dialog for a tab.
-// Returns an error if no dialog is pending.
func HandlePendingDialog(ctx context.Context, tabID string, dm *DialogManager, accept bool, promptText string) (*DialogResult, error) {
state := dm.GetAndClear(tabID)
if state == nil {
@@ -126,7 +111,6 @@ func HandlePendingDialog(ctx context.Context, tabID string, dm *DialogManager, a
}
if err := HandleDialog(ctx, accept, promptText); err != nil {
- // Put it back if handling failed
dm.SetPending(tabID, state)
return nil, fmt.Errorf("handle dialog: %w", err)
}
diff --git a/internal/bridge/lock.go b/internal/bridge/tabs/lock.go
similarity index 94%
rename from internal/bridge/lock.go
rename to internal/bridge/tabs/lock.go
index a0b29635..cea6513d 100644
--- a/internal/bridge/lock.go
+++ b/internal/bridge/tabs/lock.go
@@ -1,4 +1,4 @@
-package bridge
+package tabs
import (
"fmt"
@@ -8,6 +8,11 @@ import (
const DefaultLockTimeout = 10 * time.Minute
+type LockInfo struct {
+ Owner string
+ ExpiresAt time.Time
+}
+
type lockEntry struct {
owner string
expires time.Time
diff --git a/internal/bridge/tabs/tab_executor.go b/internal/bridge/tabs/tab_executor.go
new file mode 100644
index 00000000..9691a9f7
--- /dev/null
+++ b/internal/bridge/tabs/tab_executor.go
@@ -0,0 +1,157 @@
+package tabs
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "runtime"
+ "sync"
+ "time"
+)
+
+// TabExecutor provides safe parallel execution across tabs.
+type TabExecutor struct {
+ semaphore chan struct{}
+ tabLocks map[string]*sync.Mutex
+ mu sync.Mutex
+ maxParallel int
+}
+
+func NewTabExecutor(maxParallel int) *TabExecutor {
+ if maxParallel <= 0 {
+ maxParallel = DefaultMaxParallel()
+ }
+ return &TabExecutor{
+ semaphore: make(chan struct{}, maxParallel),
+ tabLocks: make(map[string]*sync.Mutex),
+ maxParallel: maxParallel,
+ }
+}
+
+func DefaultMaxParallel() int {
+ n := runtime.NumCPU() * 2
+ if n > 8 {
+ n = 8
+ }
+ if n < 1 {
+ n = 1
+ }
+ return n
+}
+
+func (te *TabExecutor) MaxParallel() int {
+ return te.maxParallel
+}
+
+func (te *TabExecutor) tabMutex(tabID string) *sync.Mutex {
+ te.mu.Lock()
+ defer te.mu.Unlock()
+ m, ok := te.tabLocks[tabID]
+ if !ok {
+ m = &sync.Mutex{}
+ te.tabLocks[tabID] = m
+ }
+ return m
+}
+
+func (te *TabExecutor) Execute(ctx context.Context, tabID string, task func(ctx context.Context) error) error {
+ if tabID == "" {
+ return fmt.Errorf("tabID must not be empty")
+ }
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+
+ select {
+ case te.semaphore <- struct{}{}:
+ defer func() { <-te.semaphore }()
+ case <-ctx.Done():
+ return fmt.Errorf("tab %s: waiting for execution slot: %w", tabID, ctx.Err())
+ }
+
+ tabMu := te.tabMutex(tabID)
+ locked := make(chan struct{})
+ go func() {
+ tabMu.Lock()
+ close(locked)
+ }()
+
+ select {
+ case <-locked:
+ defer tabMu.Unlock()
+ case <-ctx.Done():
+ go func() {
+ <-locked
+ tabMu.Unlock()
+ }()
+ return fmt.Errorf("tab %s: waiting for tab lock: %w", tabID, ctx.Err())
+ }
+
+ return te.safeRun(ctx, tabID, task)
+}
+
+func (te *TabExecutor) safeRun(ctx context.Context, tabID string, task func(ctx context.Context) error) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ slog.Error("panic recovered in tab execution",
+ "tabId", tabID,
+ "panic", fmt.Sprintf("%v", r),
+ )
+ err = fmt.Errorf("tab %s: panic: %v", tabID, r)
+ }
+ }()
+ return task(ctx)
+}
+
+func (te *TabExecutor) RemoveTab(tabID string) {
+ te.mu.Lock()
+ m, ok := te.tabLocks[tabID]
+ if !ok {
+ te.mu.Unlock()
+ return
+ }
+ delete(te.tabLocks, tabID)
+ te.mu.Unlock()
+
+ m.Lock()
+ defer m.Unlock() //nolint:staticcheck
+}
+
+func (te *TabExecutor) ActiveTabs() int {
+ te.mu.Lock()
+ defer te.mu.Unlock()
+ return len(te.tabLocks)
+}
+
+type ExecutorStats struct {
+ MaxParallel int `json:"maxParallel"`
+ ActiveTabs int `json:"activeTabs"`
+ SemaphoreUsed int `json:"semaphoreUsed"`
+ SemaphoreFree int `json:"semaphoreFree"`
+}
+
+func (te *TabExecutor) Stats() ExecutorStats {
+ used := len(te.semaphore)
+ return ExecutorStats{
+ MaxParallel: te.maxParallel,
+ ActiveTabs: te.ActiveTabs(),
+ SemaphoreUsed: used,
+ SemaphoreFree: te.maxParallel - used,
+ }
+}
+
+func (te *TabExecutor) ExecuteWithTimeout(ctx context.Context, tabID string, timeout time.Duration, task func(ctx context.Context) error) error {
+ tCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ return te.Execute(tCtx, tabID, task)
+}
+
+// AcquireExecutionSlotForTest fills one semaphore slot for package-external tests.
+func (te *TabExecutor) AcquireExecutionSlotForTest() {
+ te.semaphore <- struct{}{}
+}
+
+// ReleaseExecutionSlotForTest releases one semaphore slot for package-external tests.
+func (te *TabExecutor) ReleaseExecutionSlotForTest() {
+ <-te.semaphore
+}
diff --git a/internal/bridge/tabs_facade.go b/internal/bridge/tabs_facade.go
new file mode 100644
index 00000000..d6ff6d62
--- /dev/null
+++ b/internal/bridge/tabs_facade.go
@@ -0,0 +1,48 @@
+package bridge
+
+import (
+ "context"
+
+ bridgetabs "github.com/pinchtab/pinchtab/internal/bridge/tabs"
+)
+
+const DefaultLockTimeout = bridgetabs.DefaultLockTimeout
+
+type DialogState = bridgetabs.DialogState
+type DialogManager = bridgetabs.DialogManager
+type DialogResult = bridgetabs.DialogResult
+type LockManager = bridgetabs.LockManager
+type TabExecutor = bridgetabs.TabExecutor
+type ExecutorStats = bridgetabs.ExecutorStats
+
+func NewDialogManager() *DialogManager {
+ return bridgetabs.NewDialogManager()
+}
+
+func HandleDialog(ctx context.Context, accept bool, promptText string) error {
+ return bridgetabs.HandleDialog(ctx, accept, promptText)
+}
+
+func ListenDialogEvents(ctx context.Context, tabID string, dm *DialogManager, autoAccept bool) {
+ bridgetabs.ListenDialogEvents(ctx, tabID, dm, autoAccept)
+}
+
+func EnableDialogEvents(ctx context.Context) error {
+ return bridgetabs.EnableDialogEvents(ctx)
+}
+
+func HandlePendingDialog(ctx context.Context, tabID string, dm *DialogManager, accept bool, promptText string) (*DialogResult, error) {
+ return bridgetabs.HandlePendingDialog(ctx, tabID, dm, accept, promptText)
+}
+
+func NewLockManager() *LockManager {
+ return bridgetabs.NewLockManager()
+}
+
+func NewTabExecutor(maxParallel int) *TabExecutor {
+ return bridgetabs.NewTabExecutor(maxParallel)
+}
+
+func DefaultMaxParallel() int {
+ return bridgetabs.DefaultMaxParallel()
+}
diff --git a/internal/uameta/uameta.go b/internal/bridge/uameta.go
similarity index 91%
rename from internal/uameta/uameta.go
rename to internal/bridge/uameta.go
index 151e18d9..712a64d6 100644
--- a/internal/uameta/uameta.go
+++ b/internal/bridge/uameta.go
@@ -1,5 +1,4 @@
-// Package uameta builds CDP UserAgentMetadata from config.
-package uameta
+package bridge
import (
"runtime"
@@ -8,11 +7,11 @@ import (
"github.com/chromedp/cdproto/emulation"
)
-// Build creates a SetUserAgentOverride action with full UserAgentMetadata.
+// buildUserAgentOverride creates a SetUserAgentOverride action with full UserAgentMetadata.
// chromeVersion should be the full version (e.g. "144.0.7559.133").
// If userAgent is empty, generates a default one based on the platform.
// If chromeVersion is also empty, returns nil.
-func Build(userAgent, chromeVersion string) *emulation.SetUserAgentOverrideParams {
+func buildUserAgentOverride(userAgent, chromeVersion string) *emulation.SetUserAgentOverrideParams {
if chromeVersion == "" {
return nil
}
diff --git a/internal/uameta/uameta_test.go b/internal/bridge/uameta_test.go
similarity index 85%
rename from internal/uameta/uameta_test.go
rename to internal/bridge/uameta_test.go
index b21521ac..fa365b43 100644
--- a/internal/uameta/uameta_test.go
+++ b/internal/bridge/uameta_test.go
@@ -1,15 +1,15 @@
-package uameta
+package bridge
import (
"testing"
)
func TestBuild_Empty(t *testing.T) {
- if Build("", "") != nil {
+ if buildUserAgentOverride("", "") != nil {
t.Fatal("expected nil for empty chrome version")
}
- p := Build("", "144.0.0.0")
+ p := buildUserAgentOverride("", "144.0.0.0")
if p == nil {
t.Fatal("expected non-nil for empty user agent with chromeVersion")
return
@@ -20,7 +20,7 @@ func TestBuild_Empty(t *testing.T) {
}
func TestBuild_Versions(t *testing.T) {
- p := Build("Mozilla/5.0 Test", "144.0.7559.133")
+ p := buildUserAgentOverride("Mozilla/5.0 Test", "144.0.7559.133")
if p == nil {
t.Fatal("expected non-nil")
return
diff --git a/internal/cli/browsercli_test.go b/internal/cli/mock_server_test.go
similarity index 100%
rename from internal/cli/browsercli_test.go
rename to internal/cli/mock_server_test.go
diff --git a/internal/cli/report/daemon_status.go b/internal/cli/report/daemon_status.go
index 3fd6a5da..fd94ebef 100644
--- a/internal/cli/report/daemon_status.go
+++ b/internal/cli/report/daemon_status.go
@@ -1,102 +1,11 @@
package report
-import (
- "fmt"
- "os"
- "os/exec"
- "os/user"
- "path/filepath"
- "runtime"
- "strings"
-)
-
-var daemonExecCommand = exec.Command
+import "github.com/pinchtab/pinchtab/internal/daemon"
func IsDaemonInstalled() bool {
- manager, err := currentDaemonManager()
- if err != nil {
- return false
- }
- _, err = os.Stat(manager.ServicePath())
- return err == nil
+ return daemon.IsInstalled()
}
func IsDaemonRunning() bool {
- manager, err := currentDaemonManager()
- if err != nil {
- return false
- }
- status, err := manager.Status()
- if err != nil {
- return false
- }
- return daemonStatusLooksRunning(status)
-}
-
-// Internal copy of simplified daemon manager discovery for status checks
-type daemonInfo struct {
- osName string
- userID string
-}
-
-func currentDaemonManager() (daemonService, error) {
- u, err := user.Current()
- if err != nil {
- return nil, err
- }
- info := daemonInfo{osName: runtime.GOOS, userID: u.Uid}
- switch info.osName {
- case "linux":
- return &systemdStatus{userID: u.Uid}, nil
- case "darwin":
- return &launchdStatus{userID: u.Uid}, nil
- default:
- return nil, fmt.Errorf("unsupported OS")
- }
-}
-
-type daemonService interface {
- ServicePath() string
- Status() (string, error)
-}
-
-type systemdStatus struct{ userID string }
-
-func (s *systemdStatus) ServicePath() string {
- if configHome := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")); configHome != "" {
- return filepath.Join(configHome, "systemd", "user", "pinchtab.service")
- }
- home, _ := os.UserHomeDir()
- return filepath.Join(home, ".config", "systemd", "user", "pinchtab.service")
-}
-func (s *systemdStatus) Status() (string, error) {
- return runDaemonCommand("systemctl", "--user", "status", "pinchtab.service", "--no-pager")
-}
-
-type launchdStatus struct{ userID string }
-
-func (s *launchdStatus) ServicePath() string {
- home, _ := os.UserHomeDir()
- return filepath.Join(home, "Library", "LaunchAgents", "com.pinchtab.pinchtab.plist")
-}
-func (s *launchdStatus) Status() (string, error) {
- return runDaemonCommand("launchctl", "print", "gui/"+s.userID+"/com.pinchtab.pinchtab")
-}
-
-func runDaemonCommand(name string, args ...string) (string, error) {
- cmd := daemonExecCommand(name, args...)
- output, err := cmd.CombinedOutput()
- trimmed := strings.TrimSpace(string(output))
- if err == nil {
- return trimmed, nil
- }
- if trimmed == "" {
- return "", fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
- }
- return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, trimmed)
-}
-
-func daemonStatusLooksRunning(status string) bool {
- return strings.Contains(status, "state = running") ||
- strings.Contains(status, "Active: active (running)")
+ return daemon.IsRunning()
}
diff --git a/internal/cli/report/security_defaults.go b/internal/cli/report/security_defaults.go
index 593250a3..a6a46805 100644
--- a/internal/cli/report/security_defaults.go
+++ b/internal/cli/report/security_defaults.go
@@ -1,25 +1,12 @@
package report
import (
- "reflect"
- "strings"
-
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/config/workflow"
)
func ApplyRecommendedSecurityDefaults(fc *config.FileConfig) {
- defaults := config.DefaultFileConfig()
- if fc == nil {
- return
- }
- fc.Server.Bind = defaults.Server.Bind
- fc.Security = defaults.Security
- if strings.TrimSpace(fc.Server.Token) == "" {
- token, err := config.GenerateAuthToken()
- if err == nil {
- fc.Server.Token = token
- }
- }
+ workflow.ApplyRecommendedSecurityDefaults(fc)
}
func applyRecommendedSecurityDefaults(fc *config.FileConfig) {
@@ -27,20 +14,7 @@ func applyRecommendedSecurityDefaults(fc *config.FileConfig) {
}
func RestoreSecurityDefaults() (string, bool, error) {
- fc, configPath, err := config.LoadFileConfig()
- if err != nil {
- return "", false, err
- }
- before := securityDefaultsSnapshot(fc)
- ApplyRecommendedSecurityDefaults(fc)
- after := securityDefaultsSnapshot(fc)
- if reflect.DeepEqual(before, after) {
- return configPath, false, nil
- }
- if err := config.SaveFileConfig(fc, configPath); err != nil {
- return "", false, err
- }
- return configPath, true, nil
+ return workflow.RestoreSecurityDefaults()
}
func restoreSecurityDefaults() (string, bool, error) {
@@ -113,55 +87,3 @@ func RecommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
}
return lines
}
-
-type securityDefaultsState struct {
- Bind string
- Token string
- Security securityConfigValues
-}
-
-type securityConfigValues struct {
- AllowEvaluate bool
- AllowMacro bool
- AllowScreencast bool
- AllowDownload bool
- AllowUpload bool
- MaxRedirects int
- AttachEnabled bool
- IDPI config.IDPIConfig
-}
-
-func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
- if fc == nil {
- return securityDefaultsState{}
- }
- s := securityDefaultsState{
- Bind: fc.Server.Bind,
- Token: fc.Server.Token,
- Security: securityConfigValues{
- IDPI: fc.Security.IDPI,
- },
- }
- if fc.Security.AllowEvaluate != nil {
- s.Security.AllowEvaluate = *fc.Security.AllowEvaluate
- }
- if fc.Security.AllowMacro != nil {
- s.Security.AllowMacro = *fc.Security.AllowMacro
- }
- if fc.Security.AllowScreencast != nil {
- s.Security.AllowScreencast = *fc.Security.AllowScreencast
- }
- if fc.Security.AllowDownload != nil {
- s.Security.AllowDownload = *fc.Security.AllowDownload
- }
- if fc.Security.AllowUpload != nil {
- s.Security.AllowUpload = *fc.Security.AllowUpload
- }
- if fc.Security.MaxRedirects != nil {
- s.Security.MaxRedirects = *fc.Security.MaxRedirects
- }
- if fc.Security.Attach.Enabled != nil {
- s.Security.AttachEnabled = *fc.Security.Attach.Enabled
- }
- return s
-}
diff --git a/internal/cli/report/security_test.go b/internal/cli/report/security_test.go
index e22f5e31..463e2c5b 100644
--- a/internal/cli/report/security_test.go
+++ b/internal/cli/report/security_test.go
@@ -190,6 +190,9 @@ func TestApplyRecommendedSecurityDefaults(t *testing.T) {
if fc.Security.AllowEvaluate == nil || *fc.Security.AllowEvaluate {
t.Fatalf("expected allowEvaluate to reset to false, got %+v", fc.Security.AllowEvaluate)
}
+ if fc.Security.Attach.Enabled == nil || *fc.Security.Attach.Enabled {
+ t.Fatalf("expected attach.enabled to reset to false, got %+v", fc.Security.Attach.Enabled)
+ }
if !fc.Security.IDPI.Enabled {
t.Fatalf("expected idpi to be enabled")
}
@@ -261,6 +264,9 @@ func TestRestoreSecurityDefaults(t *testing.T) {
if loaded.Server.Bind != "127.0.0.1" {
t.Fatalf("expected bind to be restored, got %q", loaded.Server.Bind)
}
+ if loaded.Security.Attach.Enabled == nil || *loaded.Security.Attach.Enabled {
+ t.Fatalf("expected attach.enabled to be restored to false, got %+v", loaded.Security.Attach.Enabled)
+ }
if !loaded.Security.IDPI.Enabled {
t.Fatalf("expected idpi to be enabled after restore")
}
diff --git a/internal/cli/report/startup.go b/internal/cli/report/startup.go
index f9857f2a..2c23365c 100644
--- a/internal/cli/report/startup.go
+++ b/internal/cli/report/startup.go
@@ -7,8 +7,8 @@ import (
"strings"
"sync"
+ "github.com/pinchtab/pinchtab/internal/cli/termstyle"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/termstyle"
)
var menuBannerOnce sync.Once
diff --git a/internal/cli/report/styles.go b/internal/cli/report/styles.go
index 6e04293f..06e62947 100644
--- a/internal/cli/report/styles.go
+++ b/internal/cli/report/styles.go
@@ -3,7 +3,7 @@ package report
import (
"os"
- "github.com/pinchtab/pinchtab/internal/termstyle"
+ "github.com/pinchtab/pinchtab/internal/cli/termstyle"
)
var (
diff --git a/internal/cli/styles.go b/internal/cli/styles.go
index d2a8019b..db87b5bc 100644
--- a/internal/cli/styles.go
+++ b/internal/cli/styles.go
@@ -4,7 +4,7 @@ import (
"fmt"
"os"
- "github.com/pinchtab/pinchtab/internal/termstyle"
+ "github.com/pinchtab/pinchtab/internal/cli/termstyle"
"github.com/spf13/cobra"
)
diff --git a/internal/termstyle/style.go b/internal/cli/termstyle/style.go
similarity index 100%
rename from internal/termstyle/style.go
rename to internal/cli/termstyle/style.go
diff --git a/internal/cliui/styles.go b/internal/cliui/styles.go
deleted file mode 100644
index e1a066a6..00000000
--- a/internal/cliui/styles.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package cliui
-
-import (
- "fmt"
- "os"
- "strings"
-
- "github.com/charmbracelet/lipgloss"
-)
-
-var (
- ColorBorder = lipgloss.Color("#2b3345")
- ColorTextPrimary = lipgloss.Color("#e2e8f0")
- ColorTextMuted = lipgloss.Color("#64748b")
- ColorAccent = lipgloss.Color("#60a5fa")
- ColorAccentLight = lipgloss.Color("#93c5fd")
- ColorSuccess = lipgloss.Color("#22c55e")
- ColorWarning = lipgloss.Color("#fbbf24")
- ColorDanger = lipgloss.Color("#ef4444")
-)
-
-var (
- HeadingStyle = lipgloss.NewStyle().Foreground(ColorAccent).Bold(true)
- CommandStyle = lipgloss.NewStyle().Foreground(ColorAccentLight)
- MutedStyle = lipgloss.NewStyle().Foreground(ColorTextMuted)
- SuccessStyle = lipgloss.NewStyle().Foreground(ColorSuccess).Bold(true)
- WarningStyle = lipgloss.NewStyle().Foreground(ColorWarning).Bold(true)
- ErrorStyle = lipgloss.NewStyle().Foreground(ColorDanger).Bold(true)
- ValueStyle = lipgloss.NewStyle().Foreground(ColorTextPrimary)
-)
-
-func RenderStdout(style lipgloss.Style, text string) string {
- return StyleStdout(style, text)
-}
-
-func RenderStderr(style lipgloss.Style, text string) string {
- return StyleStderr(style, text)
-}
-
-func StyleStdout(style lipgloss.Style, text string) string {
- return renderToWriter(os.Stdout, style, text)
-}
-
-func StyleStderr(style lipgloss.Style, text string) string {
- return renderToWriter(os.Stderr, style, text)
-}
-
-func Fatal(format string, args ...any) {
- fmt.Fprint(os.Stderr, StyleStderr(ErrorStyle, fmt.Sprintf(format, args...))+"\n")
- os.Exit(1)
-}
-
-func renderToWriter(w *os.File, style lipgloss.Style, text string) string {
- if !shouldColorizeFile(w) {
- return text
- }
- return style.Render(text)
-}
-
-func shouldColorizeFile(file *os.File) bool {
- if file == nil {
- return false
- }
- if os.Getenv("NO_COLOR") != "" {
- return false
- }
- if force := os.Getenv("CLICOLOR_FORCE"); force != "" && force != "0" {
- return true
- }
- if strings.EqualFold(os.Getenv("TERM"), "dumb") {
- return false
- }
- info, err := file.Stat()
- if err != nil {
- return false
- }
- return (info.Mode() & os.ModeCharDevice) != 0
-}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index ac9193bd..7b2659ef 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -23,9 +23,14 @@ func DefaultFileConfig() FileConfig {
allowMacro := false
allowScreencast := false
allowDownload := false
+ downloadMaxBytes := DefaultDownloadMaxBytes
allowUpload := false
+ uploadMaxRequestBytes := DefaultUploadMaxRequestBytes
+ uploadMaxFiles := DefaultUploadMaxFiles
+ uploadMaxFileBytes := DefaultUploadMaxFileBytes
+ uploadMaxTotalBytes := DefaultUploadMaxTotalBytes
maxRedirects := -1
- attachEnabled := true
+ attachEnabled := false
activityEnabled := true
activitySessionIdleSec := 1800
activityRetentionDays := 1
@@ -46,12 +51,18 @@ func DefaultFileConfig() FileConfig {
TabEvictionPolicy: "close_lru",
},
Security: SecurityConfig{
- AllowEvaluate: &allowEvaluate,
- AllowMacro: &allowMacro,
- AllowScreencast: &allowScreencast,
- AllowDownload: &allowDownload,
- AllowUpload: &allowUpload,
- MaxRedirects: &maxRedirects,
+ AllowEvaluate: &allowEvaluate,
+ AllowMacro: &allowMacro,
+ AllowScreencast: &allowScreencast,
+ AllowDownload: &allowDownload,
+ DownloadAllowedDomains: []string{},
+ DownloadMaxBytes: &downloadMaxBytes,
+ AllowUpload: &allowUpload,
+ UploadMaxRequestBytes: &uploadMaxRequestBytes,
+ UploadMaxFiles: &uploadMaxFiles,
+ UploadMaxFileBytes: &uploadMaxFileBytes,
+ UploadMaxTotalBytes: &uploadMaxTotalBytes,
+ MaxRedirects: &maxRedirects,
Attach: AttachConfig{
Enabled: &attachEnabled,
AllowHosts: []string{"127.0.0.1", "localhost", "::1"},
@@ -148,14 +159,20 @@ type profilesConfigJSON struct {
}
type securityConfigJSON struct {
- AllowEvaluate *bool `json:"allowEvaluate"`
- AllowMacro *bool `json:"allowMacro"`
- AllowScreencast *bool `json:"allowScreencast"`
- AllowDownload *bool `json:"allowDownload"`
- AllowUpload *bool `json:"allowUpload"`
- MaxRedirects *int `json:"maxRedirects"`
- Attach attachJSON `json:"attach"`
- IDPI idpiConfigJSON `json:"idpi"`
+ AllowEvaluate *bool `json:"allowEvaluate"`
+ AllowMacro *bool `json:"allowMacro"`
+ AllowScreencast *bool `json:"allowScreencast"`
+ AllowDownload *bool `json:"allowDownload"`
+ DownloadAllowedDomains []string `json:"downloadAllowedDomains"`
+ DownloadMaxBytes *int `json:"downloadMaxBytes"`
+ AllowUpload *bool `json:"allowUpload"`
+ UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes"`
+ UploadMaxFiles *int `json:"uploadMaxFiles"`
+ UploadMaxFileBytes *int `json:"uploadMaxFileBytes"`
+ UploadMaxTotalBytes *int `json:"uploadMaxTotalBytes"`
+ MaxRedirects *int `json:"maxRedirects"`
+ Attach attachJSON `json:"attach"`
+ IDPI idpiConfigJSON `json:"idpi"`
}
type attachJSON struct {
@@ -259,12 +276,18 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {
TabEvictionPolicy: fc.InstanceDefaults.TabEvictionPolicy,
},
Security: securityConfigJSON{
- AllowEvaluate: fc.Security.AllowEvaluate,
- AllowMacro: fc.Security.AllowMacro,
- AllowScreencast: fc.Security.AllowScreencast,
- AllowDownload: fc.Security.AllowDownload,
- AllowUpload: fc.Security.AllowUpload,
- MaxRedirects: fc.Security.MaxRedirects,
+ AllowEvaluate: fc.Security.AllowEvaluate,
+ AllowMacro: fc.Security.AllowMacro,
+ AllowScreencast: fc.Security.AllowScreencast,
+ AllowDownload: fc.Security.AllowDownload,
+ DownloadAllowedDomains: copyStringSlice(fc.Security.DownloadAllowedDomains),
+ DownloadMaxBytes: fc.Security.DownloadMaxBytes,
+ AllowUpload: fc.Security.AllowUpload,
+ UploadMaxRequestBytes: fc.Security.UploadMaxRequestBytes,
+ UploadMaxFiles: fc.Security.UploadMaxFiles,
+ UploadMaxFileBytes: fc.Security.UploadMaxFileBytes,
+ UploadMaxTotalBytes: fc.Security.UploadMaxTotalBytes,
+ MaxRedirects: fc.Security.MaxRedirects,
Attach: attachJSON{
Enabled: fc.Security.Attach.Enabled,
AllowHosts: copyStringSlice(fc.Security.Attach.AllowHosts),
@@ -340,7 +363,13 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
allowMacro := cfg.AllowMacro
allowScreencast := cfg.AllowScreencast
allowDownload := cfg.AllowDownload
+ downloadAllowedDomains := copyStringSlice(cfg.DownloadAllowedDomains)
+ downloadMaxBytes := cfg.EffectiveDownloadMaxBytes()
allowUpload := cfg.AllowUpload
+ uploadMaxRequestBytes := cfg.EffectiveUploadMaxRequestBytes()
+ uploadMaxFiles := cfg.EffectiveUploadMaxFiles()
+ uploadMaxFileBytes := cfg.EffectiveUploadMaxFileBytes()
+ uploadMaxTotalBytes := cfg.EffectiveUploadMaxTotalBytes()
maxRedirects := cfg.MaxRedirects
attachEnabled := cfg.AttachEnabled
start := cfg.InstancePortStart
@@ -394,12 +423,18 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
TabEvictionPolicy: cfg.TabEvictionPolicy,
},
Security: SecurityConfig{
- AllowEvaluate: &allowEvaluate,
- AllowMacro: &allowMacro,
- AllowScreencast: &allowScreencast,
- AllowDownload: &allowDownload,
- AllowUpload: &allowUpload,
- MaxRedirects: &maxRedirects,
+ AllowEvaluate: &allowEvaluate,
+ AllowMacro: &allowMacro,
+ AllowScreencast: &allowScreencast,
+ AllowDownload: &allowDownload,
+ DownloadAllowedDomains: downloadAllowedDomains,
+ DownloadMaxBytes: &downloadMaxBytes,
+ AllowUpload: &allowUpload,
+ UploadMaxRequestBytes: &uploadMaxRequestBytes,
+ UploadMaxFiles: &uploadMaxFiles,
+ UploadMaxFileBytes: &uploadMaxFileBytes,
+ UploadMaxTotalBytes: &uploadMaxTotalBytes,
+ MaxRedirects: &maxRedirects,
Attach: AttachConfig{
Enabled: &attachEnabled,
AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.go
index c762c720..3e0ac1d3 100644
--- a/internal/config/config_file_test.go
+++ b/internal/config/config_file_test.go
@@ -22,6 +22,9 @@ func TestDefaultFileConfig(t *testing.T) {
if len(fc.Security.Attach.AllowSchemes) != 2 || fc.Security.Attach.AllowSchemes[0] != "ws" || fc.Security.Attach.AllowSchemes[1] != "wss" {
t.Errorf("DefaultFileConfig.Security.Attach.AllowSchemes = %v, want [ws wss]", fc.Security.Attach.AllowSchemes)
}
+ if fc.Security.Attach.Enabled == nil || *fc.Security.Attach.Enabled {
+ t.Errorf("DefaultFileConfig.Security.Attach.Enabled = %v, want explicit false", formatBoolPtr(fc.Security.Attach.Enabled))
+ }
if fc.Security.AllowEvaluate == nil || *fc.Security.AllowEvaluate {
t.Errorf("DefaultFileConfig.Security.AllowEvaluate = %v, want explicit false", formatBoolPtr(fc.Security.AllowEvaluate))
}
@@ -34,9 +37,27 @@ func TestDefaultFileConfig(t *testing.T) {
if fc.Security.AllowDownload == nil || *fc.Security.AllowDownload {
t.Errorf("DefaultFileConfig.Security.AllowDownload = %v, want explicit false", formatBoolPtr(fc.Security.AllowDownload))
}
+ if len(fc.Security.DownloadAllowedDomains) != 0 {
+ t.Errorf("DefaultFileConfig.Security.DownloadAllowedDomains = %v, want empty list", fc.Security.DownloadAllowedDomains)
+ }
+ if fc.Security.DownloadMaxBytes == nil || *fc.Security.DownloadMaxBytes != DefaultDownloadMaxBytes {
+ t.Errorf("DefaultFileConfig.Security.DownloadMaxBytes = %v, want %d", formatIntPtr(fc.Security.DownloadMaxBytes), DefaultDownloadMaxBytes)
+ }
if fc.Security.AllowUpload == nil || *fc.Security.AllowUpload {
t.Errorf("DefaultFileConfig.Security.AllowUpload = %v, want explicit false", formatBoolPtr(fc.Security.AllowUpload))
}
+ if fc.Security.UploadMaxRequestBytes == nil || *fc.Security.UploadMaxRequestBytes != DefaultUploadMaxRequestBytes {
+ t.Errorf("DefaultFileConfig.Security.UploadMaxRequestBytes = %v, want %d", formatIntPtr(fc.Security.UploadMaxRequestBytes), DefaultUploadMaxRequestBytes)
+ }
+ if fc.Security.UploadMaxFiles == nil || *fc.Security.UploadMaxFiles != DefaultUploadMaxFiles {
+ t.Errorf("DefaultFileConfig.Security.UploadMaxFiles = %v, want %d", formatIntPtr(fc.Security.UploadMaxFiles), DefaultUploadMaxFiles)
+ }
+ if fc.Security.UploadMaxFileBytes == nil || *fc.Security.UploadMaxFileBytes != DefaultUploadMaxFileBytes {
+ t.Errorf("DefaultFileConfig.Security.UploadMaxFileBytes = %v, want %d", formatIntPtr(fc.Security.UploadMaxFileBytes), DefaultUploadMaxFileBytes)
+ }
+ if fc.Security.UploadMaxTotalBytes == nil || *fc.Security.UploadMaxTotalBytes != DefaultUploadMaxTotalBytes {
+ t.Errorf("DefaultFileConfig.Security.UploadMaxTotalBytes = %v, want %d", formatIntPtr(fc.Security.UploadMaxTotalBytes), DefaultUploadMaxTotalBytes)
+ }
if !fc.Security.IDPI.Enabled {
t.Errorf("DefaultFileConfig.Security.IDPI.Enabled = %v, want true", fc.Security.IDPI.Enabled)
}
@@ -175,9 +196,30 @@ func TestDefaultFileConfigJSON(t *testing.T) {
if parsed.Security.AllowDownload == nil || *parsed.Security.AllowDownload {
t.Errorf("round-trip Security.AllowDownload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowDownload))
}
+ if len(parsed.Security.DownloadAllowedDomains) != 0 {
+ t.Errorf("round-trip Security.DownloadAllowedDomains = %v, want empty list", parsed.Security.DownloadAllowedDomains)
+ }
+ if parsed.Security.DownloadMaxBytes == nil || *parsed.Security.DownloadMaxBytes != DefaultDownloadMaxBytes {
+ t.Errorf("round-trip Security.DownloadMaxBytes = %v, want %d", formatIntPtr(parsed.Security.DownloadMaxBytes), DefaultDownloadMaxBytes)
+ }
if parsed.Security.AllowUpload == nil || *parsed.Security.AllowUpload {
t.Errorf("round-trip Security.AllowUpload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowUpload))
}
+ if parsed.Security.UploadMaxRequestBytes == nil || *parsed.Security.UploadMaxRequestBytes != DefaultUploadMaxRequestBytes {
+ t.Errorf("round-trip Security.UploadMaxRequestBytes = %v, want %d", formatIntPtr(parsed.Security.UploadMaxRequestBytes), DefaultUploadMaxRequestBytes)
+ }
+ if parsed.Security.UploadMaxFiles == nil || *parsed.Security.UploadMaxFiles != DefaultUploadMaxFiles {
+ t.Errorf("round-trip Security.UploadMaxFiles = %v, want %d", formatIntPtr(parsed.Security.UploadMaxFiles), DefaultUploadMaxFiles)
+ }
+ if parsed.Security.UploadMaxFileBytes == nil || *parsed.Security.UploadMaxFileBytes != DefaultUploadMaxFileBytes {
+ t.Errorf("round-trip Security.UploadMaxFileBytes = %v, want %d", formatIntPtr(parsed.Security.UploadMaxFileBytes), DefaultUploadMaxFileBytes)
+ }
+ if parsed.Security.UploadMaxTotalBytes == nil || *parsed.Security.UploadMaxTotalBytes != DefaultUploadMaxTotalBytes {
+ t.Errorf("round-trip Security.UploadMaxTotalBytes = %v, want %d", formatIntPtr(parsed.Security.UploadMaxTotalBytes), DefaultUploadMaxTotalBytes)
+ }
+ if parsed.Security.Attach.Enabled == nil || *parsed.Security.Attach.Enabled {
+ t.Errorf("round-trip Security.Attach.Enabled = %v, want explicit false", formatBoolPtr(parsed.Security.Attach.Enabled))
+ }
if !parsed.Security.IDPI.Enabled {
t.Errorf("round-trip Security.IDPI.Enabled = %v, want true", parsed.Security.IDPI.Enabled)
}
@@ -236,6 +278,26 @@ func TestFileConfigJSONPreservesExplicitZeroValues(t *testing.T) {
} else if items, ok := allowedDomains.([]any); !ok || len(items) != 0 {
t.Fatalf("security.idpi.allowedDomains = %#v, want explicit empty list", allowedDomains)
}
+ if downloadAllowedDomains, ok := security["downloadAllowedDomains"]; !ok {
+ t.Fatal("security.downloadAllowedDomains missing from JSON")
+ } else if items, ok := downloadAllowedDomains.([]any); !ok || len(items) != 0 {
+ t.Fatalf("security.downloadAllowedDomains = %#v, want explicit empty list", downloadAllowedDomains)
+ }
+ if raw, ok := security["downloadMaxBytes"]; !ok || int(raw.(float64)) != DefaultDownloadMaxBytes {
+ t.Fatalf("security.downloadMaxBytes = %#v, want %d", raw, DefaultDownloadMaxBytes)
+ }
+ if raw, ok := security["uploadMaxRequestBytes"]; !ok || int(raw.(float64)) != DefaultUploadMaxRequestBytes {
+ t.Fatalf("security.uploadMaxRequestBytes = %#v, want %d", raw, DefaultUploadMaxRequestBytes)
+ }
+ if raw, ok := security["uploadMaxFiles"]; !ok || int(raw.(float64)) != DefaultUploadMaxFiles {
+ t.Fatalf("security.uploadMaxFiles = %#v, want %d", raw, DefaultUploadMaxFiles)
+ }
+ if raw, ok := security["uploadMaxFileBytes"]; !ok || int(raw.(float64)) != DefaultUploadMaxFileBytes {
+ t.Fatalf("security.uploadMaxFileBytes = %#v, want %d", raw, DefaultUploadMaxFileBytes)
+ }
+ if raw, ok := security["uploadMaxTotalBytes"]; !ok || int(raw.(float64)) != DefaultUploadMaxTotalBytes {
+ t.Fatalf("security.uploadMaxTotalBytes = %#v, want %d", raw, DefaultUploadMaxTotalBytes)
+ }
}
func boolPtr(b bool) *bool {
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 163772e2..e839473c 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -21,12 +21,18 @@ func Load() *RuntimeConfig {
StateDir: userConfigDir(),
// Security defaults
- AllowEvaluate: false,
- AllowMacro: false,
- AllowScreencast: false,
- AllowDownload: false,
- AllowUpload: false,
- MaxRedirects: -1, // Unlimited by default; set to N to limit redirect hops
+ AllowEvaluate: false,
+ AllowMacro: false,
+ AllowScreencast: false,
+ AllowDownload: false,
+ DownloadAllowedDomains: nil,
+ DownloadMaxBytes: DefaultDownloadMaxBytes,
+ AllowUpload: false,
+ UploadMaxRequestBytes: DefaultUploadMaxRequestBytes,
+ UploadMaxFiles: DefaultUploadMaxFiles,
+ UploadMaxFileBytes: DefaultUploadMaxFileBytes,
+ UploadMaxTotalBytes: DefaultUploadMaxTotalBytes,
+ MaxRedirects: -1, // Unlimited by default; set to N to limit redirect hops
// Browser / instance defaults
Headless: true,
@@ -64,7 +70,7 @@ func Load() *RuntimeConfig {
RestartStableAfter: 5 * time.Minute,
// Attach defaults
- AttachEnabled: true,
+ AttachEnabled: false,
AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
AttachAllowSchemes: []string{"ws", "wss"},
@@ -176,7 +182,7 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Server.Bind != "" {
cfg.Bind = fc.Server.Bind
}
- if fc.Server.Token != "" && os.Getenv("PINCHTAB_TOKEN") == "" {
+ if os.Getenv("PINCHTAB_TOKEN") == "" {
cfg.Token = fc.Server.Token
}
if fc.Server.StateDir != "" {
@@ -201,9 +207,25 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Security.AllowDownload != nil {
cfg.AllowDownload = *fc.Security.AllowDownload
}
+ cfg.DownloadAllowedDomains = append([]string(nil), fc.Security.DownloadAllowedDomains...)
+ if fc.Security.DownloadMaxBytes != nil {
+ cfg.DownloadMaxBytes = clampPositiveLimit(*fc.Security.DownloadMaxBytes, DefaultDownloadMaxBytes, MaxDownloadMaxBytes)
+ }
if fc.Security.AllowUpload != nil {
cfg.AllowUpload = *fc.Security.AllowUpload
}
+ if fc.Security.UploadMaxRequestBytes != nil {
+ cfg.UploadMaxRequestBytes = clampPositiveLimit(*fc.Security.UploadMaxRequestBytes, DefaultUploadMaxRequestBytes, MaxUploadMaxRequestBytes)
+ }
+ if fc.Security.UploadMaxFiles != nil {
+ cfg.UploadMaxFiles = clampPositiveLimit(*fc.Security.UploadMaxFiles, DefaultUploadMaxFiles, MaxUploadMaxFiles)
+ }
+ if fc.Security.UploadMaxFileBytes != nil {
+ cfg.UploadMaxFileBytes = clampPositiveLimit(*fc.Security.UploadMaxFileBytes, DefaultUploadMaxFileBytes, MaxUploadMaxFileBytes)
+ }
+ if fc.Security.UploadMaxTotalBytes != nil {
+ cfg.UploadMaxTotalBytes = clampPositiveLimit(*fc.Security.UploadMaxTotalBytes, DefaultUploadMaxTotalBytes, MaxUploadMaxTotalBytes)
+ }
if fc.Security.MaxRedirects != nil {
cfg.MaxRedirects = *fc.Security.MaxRedirects
}
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 3d92d438..d305f401 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -59,6 +59,24 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.AllowEvaluate {
t.Errorf("default AllowEvaluate = %v, want false", cfg.AllowEvaluate)
}
+ if len(cfg.DownloadAllowedDomains) != 0 {
+ t.Errorf("default DownloadAllowedDomains = %v, want empty list", cfg.DownloadAllowedDomains)
+ }
+ if cfg.DownloadMaxBytes != DefaultDownloadMaxBytes {
+ t.Errorf("default DownloadMaxBytes = %d, want %d", cfg.DownloadMaxBytes, DefaultDownloadMaxBytes)
+ }
+ if cfg.UploadMaxRequestBytes != DefaultUploadMaxRequestBytes {
+ t.Errorf("default UploadMaxRequestBytes = %d, want %d", cfg.UploadMaxRequestBytes, DefaultUploadMaxRequestBytes)
+ }
+ if cfg.UploadMaxFiles != DefaultUploadMaxFiles {
+ t.Errorf("default UploadMaxFiles = %d, want %d", cfg.UploadMaxFiles, DefaultUploadMaxFiles)
+ }
+ if cfg.UploadMaxFileBytes != DefaultUploadMaxFileBytes {
+ t.Errorf("default UploadMaxFileBytes = %d, want %d", cfg.UploadMaxFileBytes, DefaultUploadMaxFileBytes)
+ }
+ if cfg.UploadMaxTotalBytes != DefaultUploadMaxTotalBytes {
+ t.Errorf("default UploadMaxTotalBytes = %d, want %d", cfg.UploadMaxTotalBytes, DefaultUploadMaxTotalBytes)
+ }
if cfg.Strategy != "always-on" {
t.Errorf("default Strategy = %v, want always-on", cfg.Strategy)
}
@@ -68,8 +86,8 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.TabEvictionPolicy != "close_lru" {
t.Errorf("default TabEvictionPolicy = %v, want close_lru", cfg.TabEvictionPolicy)
}
- if !cfg.AttachEnabled {
- t.Errorf("default AttachEnabled = %v, want true", cfg.AttachEnabled)
+ if cfg.AttachEnabled {
+ t.Errorf("default AttachEnabled = %v, want false", cfg.AttachEnabled)
}
if len(cfg.AttachAllowSchemes) != 2 || cfg.AttachAllowSchemes[0] != "ws" || cfg.AttachAllowSchemes[1] != "wss" {
t.Errorf("default AttachAllowSchemes = %v, want [ws wss]", cfg.AttachAllowSchemes)
@@ -216,6 +234,27 @@ func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T)
if cfg.AllowUpload {
t.Errorf("ApplyFileConfigToRuntime AllowUpload = %v, want false", cfg.AllowUpload)
}
+ if len(cfg.DownloadAllowedDomains) != 0 {
+ t.Errorf("ApplyFileConfigToRuntime DownloadAllowedDomains = %v, want empty list", cfg.DownloadAllowedDomains)
+ }
+ if cfg.DownloadMaxBytes != DefaultDownloadMaxBytes {
+ t.Errorf("ApplyFileConfigToRuntime DownloadMaxBytes = %d, want %d", cfg.DownloadMaxBytes, DefaultDownloadMaxBytes)
+ }
+ if cfg.UploadMaxRequestBytes != DefaultUploadMaxRequestBytes {
+ t.Errorf("ApplyFileConfigToRuntime UploadMaxRequestBytes = %d, want %d", cfg.UploadMaxRequestBytes, DefaultUploadMaxRequestBytes)
+ }
+ if cfg.UploadMaxFiles != DefaultUploadMaxFiles {
+ t.Errorf("ApplyFileConfigToRuntime UploadMaxFiles = %d, want %d", cfg.UploadMaxFiles, DefaultUploadMaxFiles)
+ }
+ if cfg.UploadMaxFileBytes != DefaultUploadMaxFileBytes {
+ t.Errorf("ApplyFileConfigToRuntime UploadMaxFileBytes = %d, want %d", cfg.UploadMaxFileBytes, DefaultUploadMaxFileBytes)
+ }
+ if cfg.UploadMaxTotalBytes != DefaultUploadMaxTotalBytes {
+ t.Errorf("ApplyFileConfigToRuntime UploadMaxTotalBytes = %d, want %d", cfg.UploadMaxTotalBytes, DefaultUploadMaxTotalBytes)
+ }
+ if cfg.AttachEnabled {
+ t.Errorf("ApplyFileConfigToRuntime AttachEnabled = %v, want false", cfg.AttachEnabled)
+ }
if !cfg.IDPI.Enabled {
t.Errorf("ApplyFileConfigToRuntime IDPI.Enabled = %v, want true", cfg.IDPI.Enabled)
}
@@ -227,6 +266,20 @@ func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T)
}
}
+func TestApplyFileConfigToRuntimeClearsTokenWhenFileTokenRemoved(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ cfg := &RuntimeConfig{Token: "secret-token"}
+ fc := DefaultFileConfig()
+ fc.Server.Token = ""
+
+ ApplyFileConfigToRuntime(cfg, &fc)
+
+ if cfg.Token != "" {
+ t.Fatalf("ApplyFileConfigToRuntime Token = %q, want empty string", cfg.Token)
+ }
+}
+
func TestApplyFileConfigToRuntime_ClampsNetworkBufferSize(t *testing.T) {
cfg := &RuntimeConfig{}
oversized := MaxNetworkBufferSize + 1
@@ -241,6 +294,102 @@ func TestApplyFileConfigToRuntime_ClampsNetworkBufferSize(t *testing.T) {
}
}
+func TestApplyFileConfigToRuntime_CopiesDownloadAllowedDomains(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ fc := &FileConfig{
+ Security: SecurityConfig{
+ DownloadAllowedDomains: []string{"pinchtab.com", "*.pinchtab.com"},
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+ fc.Security.DownloadAllowedDomains[0] = "mutated.example.com"
+
+ if len(cfg.DownloadAllowedDomains) != 2 {
+ t.Fatalf("ApplyFileConfigToRuntime DownloadAllowedDomains = %v, want 2 entries", cfg.DownloadAllowedDomains)
+ }
+ if cfg.DownloadAllowedDomains[0] != "pinchtab.com" {
+ t.Fatalf("ApplyFileConfigToRuntime copied list = %v, want original values", cfg.DownloadAllowedDomains)
+ }
+}
+
+func TestRuntimeConfig_EffectiveTransferLimitsFallbackAndClamp(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ if cfg.EffectiveDownloadMaxBytes() != DefaultDownloadMaxBytes {
+ t.Fatalf("EffectiveDownloadMaxBytes() = %d, want %d", cfg.EffectiveDownloadMaxBytes(), DefaultDownloadMaxBytes)
+ }
+ if cfg.EffectiveUploadMaxRequestBytes() != DefaultUploadMaxRequestBytes {
+ t.Fatalf("EffectiveUploadMaxRequestBytes() = %d, want %d", cfg.EffectiveUploadMaxRequestBytes(), DefaultUploadMaxRequestBytes)
+ }
+ if cfg.EffectiveUploadMaxFiles() != DefaultUploadMaxFiles {
+ t.Fatalf("EffectiveUploadMaxFiles() = %d, want %d", cfg.EffectiveUploadMaxFiles(), DefaultUploadMaxFiles)
+ }
+ if cfg.EffectiveUploadMaxFileBytes() != DefaultUploadMaxFileBytes {
+ t.Fatalf("EffectiveUploadMaxFileBytes() = %d, want %d", cfg.EffectiveUploadMaxFileBytes(), DefaultUploadMaxFileBytes)
+ }
+ if cfg.EffectiveUploadMaxTotalBytes() != DefaultUploadMaxTotalBytes {
+ t.Fatalf("EffectiveUploadMaxTotalBytes() = %d, want %d", cfg.EffectiveUploadMaxTotalBytes(), DefaultUploadMaxTotalBytes)
+ }
+
+ cfg.DownloadMaxBytes = MaxDownloadMaxBytes + 1
+ cfg.UploadMaxRequestBytes = MaxUploadMaxRequestBytes + 1
+ cfg.UploadMaxFiles = MaxUploadMaxFiles + 1
+ cfg.UploadMaxFileBytes = MaxUploadMaxFileBytes + 1
+ cfg.UploadMaxTotalBytes = MaxUploadMaxTotalBytes + 1
+
+ if cfg.EffectiveDownloadMaxBytes() != MaxDownloadMaxBytes {
+ t.Fatalf("EffectiveDownloadMaxBytes clamp = %d, want %d", cfg.EffectiveDownloadMaxBytes(), MaxDownloadMaxBytes)
+ }
+ if cfg.EffectiveUploadMaxRequestBytes() != MaxUploadMaxRequestBytes {
+ t.Fatalf("EffectiveUploadMaxRequestBytes clamp = %d, want %d", cfg.EffectiveUploadMaxRequestBytes(), MaxUploadMaxRequestBytes)
+ }
+ if cfg.EffectiveUploadMaxFiles() != MaxUploadMaxFiles {
+ t.Fatalf("EffectiveUploadMaxFiles clamp = %d, want %d", cfg.EffectiveUploadMaxFiles(), MaxUploadMaxFiles)
+ }
+ if cfg.EffectiveUploadMaxFileBytes() != MaxUploadMaxFileBytes {
+ t.Fatalf("EffectiveUploadMaxFileBytes clamp = %d, want %d", cfg.EffectiveUploadMaxFileBytes(), MaxUploadMaxFileBytes)
+ }
+ if cfg.EffectiveUploadMaxTotalBytes() != MaxUploadMaxTotalBytes {
+ t.Fatalf("EffectiveUploadMaxTotalBytes clamp = %d, want %d", cfg.EffectiveUploadMaxTotalBytes(), MaxUploadMaxTotalBytes)
+ }
+}
+
+func TestApplyFileConfigToRuntime_ClampsTransferLimits(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ downloadTooLarge := MaxDownloadMaxBytes + 1
+ requestTooLarge := MaxUploadMaxRequestBytes + 1
+ filesTooLarge := MaxUploadMaxFiles + 1
+ fileTooLarge := MaxUploadMaxFileBytes + 1
+ totalTooLarge := MaxUploadMaxTotalBytes + 1
+ fc := &FileConfig{
+ Security: SecurityConfig{
+ DownloadMaxBytes: &downloadTooLarge,
+ UploadMaxRequestBytes: &requestTooLarge,
+ UploadMaxFiles: &filesTooLarge,
+ UploadMaxFileBytes: &fileTooLarge,
+ UploadMaxTotalBytes: &totalTooLarge,
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+
+ if cfg.DownloadMaxBytes != MaxDownloadMaxBytes {
+ t.Fatalf("DownloadMaxBytes = %d, want %d", cfg.DownloadMaxBytes, MaxDownloadMaxBytes)
+ }
+ if cfg.UploadMaxRequestBytes != MaxUploadMaxRequestBytes {
+ t.Fatalf("UploadMaxRequestBytes = %d, want %d", cfg.UploadMaxRequestBytes, MaxUploadMaxRequestBytes)
+ }
+ if cfg.UploadMaxFiles != MaxUploadMaxFiles {
+ t.Fatalf("UploadMaxFiles = %d, want %d", cfg.UploadMaxFiles, MaxUploadMaxFiles)
+ }
+ if cfg.UploadMaxFileBytes != MaxUploadMaxFileBytes {
+ t.Fatalf("UploadMaxFileBytes = %d, want %d", cfg.UploadMaxFileBytes, MaxUploadMaxFileBytes)
+ }
+ if cfg.UploadMaxTotalBytes != MaxUploadMaxTotalBytes {
+ t.Fatalf("UploadMaxTotalBytes = %d, want %d", cfg.UploadMaxTotalBytes, MaxUploadMaxTotalBytes)
+ }
+}
+
// clearConfigEnvVars unsets all config-related env vars for clean tests.
func clearConfigEnvVars(t *testing.T) {
t.Helper()
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 77d04304..264cb593 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -14,12 +14,18 @@ type RuntimeConfig struct {
StateDir string
// Security settings
- AllowEvaluate bool
- AllowMacro bool
- AllowScreencast bool
- AllowDownload bool
- AllowUpload bool
- MaxRedirects int // Max HTTP redirects (-1=unlimited, 0=none, default=-1)
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ DownloadAllowedDomains []string
+ DownloadMaxBytes int
+ AllowUpload bool
+ UploadMaxRequestBytes int
+ UploadMaxFiles int
+ UploadMaxFileBytes int
+ UploadMaxTotalBytes int
+ MaxRedirects int // Max HTTP redirects (-1=unlimited, 0=none, default=-1)
// Browser/instance settings
Headless bool
@@ -166,14 +172,20 @@ type ProfilesConfig struct {
}
type SecurityConfig struct {
- AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
- AllowMacro *bool `json:"allowMacro,omitempty"`
- AllowScreencast *bool `json:"allowScreencast,omitempty"`
- AllowDownload *bool `json:"allowDownload,omitempty"`
- AllowUpload *bool `json:"allowUpload,omitempty"`
- MaxRedirects *int `json:"maxRedirects,omitempty"`
- Attach AttachConfig `json:"attach,omitempty"`
- IDPI IDPIConfig `json:"idpi,omitempty"`
+ AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
+ AllowMacro *bool `json:"allowMacro,omitempty"`
+ AllowScreencast *bool `json:"allowScreencast,omitempty"`
+ AllowDownload *bool `json:"allowDownload,omitempty"`
+ DownloadAllowedDomains []string `json:"downloadAllowedDomains,omitempty"`
+ DownloadMaxBytes *int `json:"downloadMaxBytes,omitempty"`
+ AllowUpload *bool `json:"allowUpload,omitempty"`
+ UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes,omitempty"`
+ UploadMaxFiles *int `json:"uploadMaxFiles,omitempty"`
+ UploadMaxFileBytes *int `json:"uploadMaxFileBytes,omitempty"`
+ UploadMaxTotalBytes *int `json:"uploadMaxTotalBytes,omitempty"`
+ MaxRedirects *int `json:"maxRedirects,omitempty"`
+ Attach AttachConfig `json:"attach,omitempty"`
+ IDPI IDPIConfig `json:"idpi,omitempty"`
}
type MultiInstanceConfig struct {
diff --git a/internal/config/config_utils.go b/internal/config/config_utils.go
index fc38c5d3..2a386553 100644
--- a/internal/config/config_utils.go
+++ b/internal/config/config_utils.go
@@ -79,6 +79,23 @@ func GenerateAuthToken() (string, error) {
return hex.EncodeToString(buf), nil
}
+// EnsureFileToken guarantees that a persisted config carries a non-empty
+// server token. It returns true when a new token was generated.
+func EnsureFileToken(fc *FileConfig) (bool, error) {
+ if fc == nil {
+ return false, fmt.Errorf("file config is nil")
+ }
+ if strings.TrimSpace(fc.Server.Token) != "" {
+ return false, nil
+ }
+ token, err := GenerateAuthToken()
+ if err != nil {
+ return false, err
+ }
+ fc.Server.Token = token
+ return true, nil
+}
+
func MaskToken(t string) string {
if t == "" {
return "(none)"
diff --git a/internal/config/editor.go b/internal/config/editor.go
deleted file mode 100644
index e3d31eb7..00000000
--- a/internal/config/editor.go
+++ /dev/null
@@ -1,716 +0,0 @@
-package config
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
-)
-
-// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "instanceDefaults.mode").
-// Returns the updated FileConfig and any error.
-func SetConfigValue(fc *FileConfig, path string, value string) error {
- parts := strings.SplitN(path, ".", 2)
- if len(parts) != 2 {
- return fmt.Errorf("invalid path %q (expected section.field, e.g., server.port)", path)
- }
-
- section, field := parts[0], parts[1]
-
- switch section {
- case "server":
- return setServerField(&fc.Server, field, value)
- case "browser":
- return setBrowserField(&fc.Browser, field, value)
- case "instanceDefaults":
- return setInstanceDefaultsField(&fc.InstanceDefaults, field, value)
- case "security":
- return setSecurityField(&fc.Security, field, value)
- case "profiles":
- return setProfilesField(&fc.Profiles, field, value)
- case "multiInstance":
- return setMultiInstanceField(&fc.MultiInstance, field, value)
- case "timeouts":
- return setTimeoutsField(&fc.Timeouts, field, value)
- default:
- return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)
- }
-}
-
-func setServerField(s *ServerConfig, field, value string) error {
- switch field {
- case "port":
- s.Port = value
- case "bind":
- s.Bind = value
- case "token":
- s.Token = value
- case "stateDir":
- s.StateDir = value
- default:
- return fmt.Errorf("unknown field server.%s", field)
- }
- return nil
-}
-
-func setBrowserField(b *BrowserConfig, field, value string) error {
- switch field {
- case "version":
- b.ChromeVersion = value
- case "binary":
- b.ChromeBinary = value
- case "extraFlags":
- b.ChromeExtraFlags = value
- default:
- return fmt.Errorf("unknown field browser.%s", field)
- }
- return nil
-}
-
-func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) error {
- switch field {
- case "mode":
- c.Mode = value
- case "noRestore":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.noRestore: %w", err)
- }
- c.NoRestore = &b
- case "timezone":
- c.Timezone = value
- case "blockImages":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.blockImages: %w", err)
- }
- c.BlockImages = &b
- case "blockMedia":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.blockMedia: %w", err)
- }
- c.BlockMedia = &b
- case "blockAds":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.blockAds: %w", err)
- }
- c.BlockAds = &b
- case "maxTabs":
- n, err := strconv.Atoi(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.maxTabs must be a number: %w", err)
- }
- c.MaxTabs = &n
- case "maxParallelTabs":
- n, err := strconv.Atoi(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.maxParallelTabs must be a number: %w", err)
- }
- c.MaxParallelTabs = &n
- case "userAgent":
- c.UserAgent = value
- case "noAnimations":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("instanceDefaults.noAnimations: %w", err)
- }
- c.NoAnimations = &b
- case "stealthLevel":
- c.StealthLevel = value
- case "tabEvictionPolicy":
- c.TabEvictionPolicy = value
- default:
- return fmt.Errorf("unknown field instanceDefaults.%s", field)
- }
- return nil
-}
-
-func setSecurityField(s *SecurityConfig, field, value string) error {
- if strings.HasPrefix(field, "attach.") {
- return setAttachField(&s.Attach, strings.TrimPrefix(field, "attach."), value)
- }
- if strings.HasPrefix(field, "idpi.") {
- return setIDPIField(&s.IDPI, strings.TrimPrefix(field, "idpi."), value)
- }
-
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("security.%s: %w", field, err)
- }
-
- switch field {
- case "allowEvaluate":
- s.AllowEvaluate = &b
- case "allowMacro":
- s.AllowMacro = &b
- case "allowScreencast":
- s.AllowScreencast = &b
- case "allowDownload":
- s.AllowDownload = &b
- case "allowUpload":
- s.AllowUpload = &b
- default:
- return fmt.Errorf("unknown field security.%s", field)
- }
- return nil
-}
-
-func setProfilesField(p *ProfilesConfig, field, value string) error {
- switch field {
- case "baseDir":
- p.BaseDir = value
- case "defaultProfile":
- p.DefaultProfile = value
- default:
- return fmt.Errorf("unknown field profiles.%s", field)
- }
- return nil
-}
-
-func setMultiInstanceField(o *MultiInstanceConfig, field, value string) error {
- if strings.HasPrefix(field, "restart.") {
- return setMultiInstanceRestartField(&o.Restart, strings.TrimPrefix(field, "restart."), value)
- }
-
- switch field {
- case "strategy":
- o.Strategy = value
- case "allocationPolicy":
- o.AllocationPolicy = value
- case "instancePortStart":
- n, err := strconv.Atoi(value)
- if err != nil {
- return fmt.Errorf("multiInstance.instancePortStart must be a number: %w", err)
- }
- o.InstancePortStart = &n
- case "instancePortEnd":
- n, err := strconv.Atoi(value)
- if err != nil {
- return fmt.Errorf("multiInstance.instancePortEnd must be a number: %w", err)
- }
- o.InstancePortEnd = &n
- default:
- return fmt.Errorf("unknown field multiInstance.%s", field)
- }
- return nil
-}
-
-func setMultiInstanceRestartField(r *MultiInstanceRestartConfig, field, value string) error {
- n, err := strconv.Atoi(value)
- if err != nil {
- return fmt.Errorf("multiInstance.restart.%s must be a number: %w", field, err)
- }
-
- switch field {
- case "maxRestarts":
- r.MaxRestarts = &n
- case "initBackoffSec":
- r.InitBackoffSec = &n
- case "maxBackoffSec":
- r.MaxBackoffSec = &n
- case "stableAfterSec":
- r.StableAfterSec = &n
- default:
- return fmt.Errorf("unknown field multiInstance.restart.%s", field)
- }
- return nil
-}
-
-func setTimeoutsField(t *TimeoutsConfig, field, value string) error {
- n, err := strconv.Atoi(value)
- if err != nil {
- return fmt.Errorf("timeouts.%s must be a number: %w", field, err)
- }
-
- switch field {
- case "actionSec":
- t.ActionSec = n
- case "navigateSec":
- t.NavigateSec = n
- case "shutdownSec":
- t.ShutdownSec = n
- case "waitNavMs":
- t.WaitNavMs = n
- default:
- return fmt.Errorf("unknown field timeouts.%s", field)
- }
- return nil
-}
-
-func setAttachField(a *AttachConfig, field, value string) error {
- switch field {
- case "enabled":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("security.attach.enabled: %w", err)
- }
- a.Enabled = &b
- case "allowHosts":
- a.AllowHosts = parseCSVList(value)
- case "allowSchemes":
- a.AllowSchemes = parseCSVList(value)
- default:
- return fmt.Errorf("unknown field security.attach.%s", field)
- }
- return nil
-}
-
-// GetConfigValue reads a dotted-path field from FileConfig and returns its string representation.
-// The path format matches SetConfigValue (e.g., "server.port", "security.attach.allowHosts").
-// Pointer fields that are unset return an empty string.
-// Slice fields are returned as comma-separated values.
-func GetConfigValue(fc *FileConfig, path string) (string, error) {
- parts := strings.SplitN(path, ".", 2)
- if len(parts) != 2 {
- return "", fmt.Errorf("invalid path %q (expected section.field, e.g., server.port)", path)
- }
-
- section, field := parts[0], parts[1]
-
- switch section {
- case "server":
- return getServerField(&fc.Server, field)
- case "browser":
- return getBrowserField(&fc.Browser, field)
- case "instanceDefaults":
- return getInstanceDefaultsField(&fc.InstanceDefaults, field)
- case "security":
- return getSecurityField(&fc.Security, field)
- case "profiles":
- return getProfilesField(&fc.Profiles, field)
- case "multiInstance":
- return getMultiInstanceField(&fc.MultiInstance, field)
- case "timeouts":
- return getTimeoutsField(&fc.Timeouts, field)
- default:
- return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)
- }
-}
-
-func getServerField(s *ServerConfig, field string) (string, error) {
- switch field {
- case "port":
- return s.Port, nil
- case "bind":
- return s.Bind, nil
- case "token":
- return s.Token, nil
- case "stateDir":
- return s.StateDir, nil
- default:
- return "", fmt.Errorf("unknown field server.%s", field)
- }
-}
-
-func getBrowserField(b *BrowserConfig, field string) (string, error) {
- switch field {
- case "version":
- return b.ChromeVersion, nil
- case "binary":
- return b.ChromeBinary, nil
- case "extraFlags":
- return b.ChromeExtraFlags, nil
- default:
- return "", fmt.Errorf("unknown field browser.%s", field)
- }
-}
-
-func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string, error) {
- switch field {
- case "mode":
- return c.Mode, nil
- case "noRestore":
- return formatBoolPtr(c.NoRestore), nil
- case "timezone":
- return c.Timezone, nil
- case "blockImages":
- return formatBoolPtr(c.BlockImages), nil
- case "blockMedia":
- return formatBoolPtr(c.BlockMedia), nil
- case "blockAds":
- return formatBoolPtr(c.BlockAds), nil
- case "maxTabs":
- return formatIntPtr(c.MaxTabs), nil
- case "maxParallelTabs":
- return formatIntPtr(c.MaxParallelTabs), nil
- case "userAgent":
- return c.UserAgent, nil
- case "noAnimations":
- return formatBoolPtr(c.NoAnimations), nil
- case "stealthLevel":
- return c.StealthLevel, nil
- case "tabEvictionPolicy":
- return c.TabEvictionPolicy, nil
- default:
- return "", fmt.Errorf("unknown field instanceDefaults.%s", field)
- }
-}
-
-func getSecurityField(s *SecurityConfig, field string) (string, error) {
- if strings.HasPrefix(field, "attach.") {
- return getAttachField(&s.Attach, strings.TrimPrefix(field, "attach."))
- }
- if strings.HasPrefix(field, "idpi.") {
- return getIDPIField(&s.IDPI, strings.TrimPrefix(field, "idpi."))
- }
-
- switch field {
- case "allowEvaluate":
- return formatBoolPtr(s.AllowEvaluate), nil
- case "allowMacro":
- return formatBoolPtr(s.AllowMacro), nil
- case "allowScreencast":
- return formatBoolPtr(s.AllowScreencast), nil
- case "allowDownload":
- return formatBoolPtr(s.AllowDownload), nil
- case "allowUpload":
- return formatBoolPtr(s.AllowUpload), nil
- default:
- return "", fmt.Errorf("unknown field security.%s", field)
- }
-}
-
-func getProfilesField(p *ProfilesConfig, field string) (string, error) {
- switch field {
- case "baseDir":
- return p.BaseDir, nil
- case "defaultProfile":
- return p.DefaultProfile, nil
- default:
- return "", fmt.Errorf("unknown field profiles.%s", field)
- }
-}
-
-func getMultiInstanceField(o *MultiInstanceConfig, field string) (string, error) {
- if strings.HasPrefix(field, "restart.") {
- return getMultiInstanceRestartField(&o.Restart, strings.TrimPrefix(field, "restart."))
- }
-
- switch field {
- case "strategy":
- return o.Strategy, nil
- case "allocationPolicy":
- return o.AllocationPolicy, nil
- case "instancePortStart":
- return formatIntPtr(o.InstancePortStart), nil
- case "instancePortEnd":
- return formatIntPtr(o.InstancePortEnd), nil
- default:
- return "", fmt.Errorf("unknown field multiInstance.%s", field)
- }
-}
-
-func getMultiInstanceRestartField(r *MultiInstanceRestartConfig, field string) (string, error) {
- switch field {
- case "maxRestarts":
- return formatIntPtr(r.MaxRestarts), nil
- case "initBackoffSec":
- return formatIntPtr(r.InitBackoffSec), nil
- case "maxBackoffSec":
- return formatIntPtr(r.MaxBackoffSec), nil
- case "stableAfterSec":
- return formatIntPtr(r.StableAfterSec), nil
- default:
- return "", fmt.Errorf("unknown field multiInstance.restart.%s", field)
- }
-}
-
-func getAttachField(a *AttachConfig, field string) (string, error) {
- switch field {
- case "enabled":
- return formatBoolPtr(a.Enabled), nil
- case "allowHosts":
- return strings.Join(a.AllowHosts, ","), nil
- case "allowSchemes":
- return strings.Join(a.AllowSchemes, ","), nil
- default:
- return "", fmt.Errorf("unknown field security.attach.%s", field)
- }
-}
-
-func setIDPIField(i *IDPIConfig, field, value string) error {
- switch field {
- case "enabled":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("security.idpi.enabled: %w", err)
- }
- i.Enabled = b
- case "allowedDomains":
- i.AllowedDomains = parseCSVList(value)
- case "strictMode":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("security.idpi.strictMode: %w", err)
- }
- i.StrictMode = b
- case "scanContent":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("security.idpi.scanContent: %w", err)
- }
- i.ScanContent = b
- case "wrapContent":
- b, err := parseBool(value)
- if err != nil {
- return fmt.Errorf("security.idpi.wrapContent: %w", err)
- }
- i.WrapContent = b
- case "customPatterns":
- i.CustomPatterns = parseCSVList(value)
- default:
- return fmt.Errorf("unknown field security.idpi.%s", field)
- }
- return nil
-}
-
-func getIDPIField(i *IDPIConfig, field string) (string, error) {
- switch field {
- case "enabled":
- return strconv.FormatBool(i.Enabled), nil
- case "allowedDomains":
- return strings.Join(i.AllowedDomains, ","), nil
- case "strictMode":
- return strconv.FormatBool(i.StrictMode), nil
- case "scanContent":
- return strconv.FormatBool(i.ScanContent), nil
- case "wrapContent":
- return strconv.FormatBool(i.WrapContent), nil
- case "customPatterns":
- return strings.Join(i.CustomPatterns, ","), nil
- default:
- return "", fmt.Errorf("unknown field security.idpi.%s", field)
- }
-}
-
-func getTimeoutsField(t *TimeoutsConfig, field string) (string, error) {
- switch field {
- case "actionSec":
- return strconv.Itoa(t.ActionSec), nil
- case "navigateSec":
- return strconv.Itoa(t.NavigateSec), nil
- case "shutdownSec":
- return strconv.Itoa(t.ShutdownSec), nil
- case "waitNavMs":
- return strconv.Itoa(t.WaitNavMs), nil
- default:
- return "", fmt.Errorf("unknown field timeouts.%s", field)
- }
-}
-
-func formatBoolPtr(b *bool) string {
- if b == nil {
- return ""
- }
- if *b {
- return "true"
- }
- return "false"
-}
-
-func formatIntPtr(n *int) string {
- if n == nil {
- return ""
- }
- return strconv.Itoa(*n)
-}
-
-func parseBool(s string) (bool, error) {
- switch strings.ToLower(strings.TrimSpace(s)) {
- case "true", "1", "yes", "on":
- return true, nil
- case "false", "0", "no", "off":
- return false, nil
- default:
- return false, fmt.Errorf("invalid boolean %q (use true/false)", s)
- }
-}
-
-func parseCSVList(s string) []string {
- if strings.TrimSpace(s) == "" {
- return nil
- }
- raw := strings.Split(s, ",")
- out := make([]string, 0, len(raw))
- for _, item := range raw {
- item = strings.TrimSpace(item)
- if item != "" {
- out = append(out, item)
- }
- }
- return out
-}
-
-// PatchConfigJSON merges a JSON object into FileConfig.
-// The patch should be a valid JSON object with the same structure as FileConfig.
-func PatchConfigJSON(fc *FileConfig, jsonPatch string) error {
- // First, serialize current config to JSON
- current, err := json.Marshal(fc)
- if err != nil {
- return fmt.Errorf("failed to serialize current config: %w", err)
- }
-
- // Unmarshal current into a map for merging
- var currentMap map[string]interface{}
- if err := json.Unmarshal(current, &currentMap); err != nil {
- return fmt.Errorf("failed to parse current config: %w", err)
- }
-
- // Parse the patch
- var patchMap map[string]interface{}
- if err := json.Unmarshal([]byte(jsonPatch), &patchMap); err != nil {
- return fmt.Errorf("invalid JSON patch: %w", err)
- }
-
- // Deep merge patch into current
- merged := deepMerge(currentMap, patchMap)
-
- // Serialize merged back to JSON
- mergedJSON, err := json.Marshal(merged)
- if err != nil {
- return fmt.Errorf("failed to serialize merged config: %w", err)
- }
-
- // Unmarshal back into FileConfig
- if err := json.Unmarshal(mergedJSON, fc); err != nil {
- return fmt.Errorf("failed to parse merged config: %w", err)
- }
-
- return nil
-}
-
-// deepMerge recursively merges src into dst, returning the result.
-func deepMerge(dst, src map[string]interface{}) map[string]interface{} {
- result := make(map[string]interface{})
-
- // Copy dst
- for k, v := range dst {
- result[k] = v
- }
-
- // Merge src
- for k, v := range src {
- if srcMap, ok := v.(map[string]interface{}); ok {
- if dstMap, ok := result[k].(map[string]interface{}); ok {
- result[k] = deepMerge(dstMap, srcMap)
- continue
- }
- }
- result[k] = v
- }
-
- return result
-}
-
-// LoadFileConfig loads a FileConfig from the default or specified path.
-// Returns the config and the path it was loaded from.
-func LoadFileConfig() (*FileConfig, string, error) {
- configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- if os.IsNotExist(err) {
- // Return empty config if file doesn't exist
- return &FileConfig{}, configPath, nil
- }
- return nil, configPath, fmt.Errorf("failed to read config file: %w", err)
- }
-
- var fc *FileConfig
-
- if isLegacyConfig(data) {
- var lc legacyFileConfig
- if err := json.Unmarshal(data, &lc); err != nil {
- return nil, configPath, fmt.Errorf("failed to parse legacy config: %w", err)
- }
- defaults := DefaultFileConfig()
- fc = &defaults
- legacy := convertLegacyConfig(&lc)
- if legacy.Server.Port != "" {
- fc.Server.Port = legacy.Server.Port
- }
- if legacy.Server.Token != "" {
- fc.Server.Token = legacy.Server.Token
- }
- if legacy.Server.StateDir != "" {
- fc.Server.StateDir = legacy.Server.StateDir
- }
- if legacy.InstanceDefaults.Mode != "" {
- fc.InstanceDefaults.Mode = legacy.InstanceDefaults.Mode
- }
- if legacy.InstanceDefaults.NoRestore != nil {
- fc.InstanceDefaults.NoRestore = legacy.InstanceDefaults.NoRestore
- }
- if legacy.InstanceDefaults.MaxTabs != nil {
- fc.InstanceDefaults.MaxTabs = legacy.InstanceDefaults.MaxTabs
- }
- if legacy.Profiles.BaseDir != "" {
- fc.Profiles.BaseDir = legacy.Profiles.BaseDir
- }
- if legacy.Profiles.DefaultProfile != "" {
- fc.Profiles.DefaultProfile = legacy.Profiles.DefaultProfile
- }
- if legacy.Security.AllowEvaluate != nil {
- fc.Security.AllowEvaluate = legacy.Security.AllowEvaluate
- }
- if legacy.Security.AllowMacro != nil {
- fc.Security.AllowMacro = legacy.Security.AllowMacro
- }
- if legacy.Security.AllowScreencast != nil {
- fc.Security.AllowScreencast = legacy.Security.AllowScreencast
- }
- if legacy.Security.AllowDownload != nil {
- fc.Security.AllowDownload = legacy.Security.AllowDownload
- }
- if legacy.Security.AllowUpload != nil {
- fc.Security.AllowUpload = legacy.Security.AllowUpload
- }
- if legacy.Timeouts.ActionSec != 0 {
- fc.Timeouts.ActionSec = legacy.Timeouts.ActionSec
- }
- if legacy.Timeouts.NavigateSec != 0 {
- fc.Timeouts.NavigateSec = legacy.Timeouts.NavigateSec
- }
- if legacy.MultiInstance.InstancePortStart != nil {
- fc.MultiInstance.InstancePortStart = legacy.MultiInstance.InstancePortStart
- }
- if legacy.MultiInstance.InstancePortEnd != nil {
- fc.MultiInstance.InstancePortEnd = legacy.MultiInstance.InstancePortEnd
- }
- } else {
- defaults := DefaultFileConfig()
- defaults.ConfigVersion = "" // Don't assume version — let file content determine it
- fc = &defaults
- if err := json.Unmarshal(data, fc); err != nil {
- return nil, configPath, fmt.Errorf("failed to parse config: %w", err)
- }
- }
-
- return fc, configPath, nil
-}
-
-// SaveFileConfig saves a FileConfig to the specified path.
-func SaveFileConfig(fc *FileConfig, path string) error {
- // Create directory if needed
- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
- return fmt.Errorf("failed to create config directory: %w", err)
- }
-
- data, err := json.MarshalIndent(fc, "", " ")
- if err != nil {
- return fmt.Errorf("failed to serialize config: %w", err)
- }
-
- // Add trailing newline
- data = append(data, '\n')
-
- if err := os.WriteFile(path, data, 0644); err != nil {
- return fmt.Errorf("failed to write config file: %w", err)
- }
-
- return nil
-}
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
new file mode 100644
index 00000000..921f2c9d
--- /dev/null
+++ b/internal/config/editor_get.go
@@ -0,0 +1,243 @@
+package config
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// GetConfigValue reads a dotted-path field from FileConfig and returns its string representation.
+// Pointer fields that are unset return an empty string. Slice fields are comma-separated.
+func GetConfigValue(fc *FileConfig, path string) (string, error) {
+ parts := strings.SplitN(path, ".", 2)
+ if len(parts) != 2 {
+ return "", fmt.Errorf("invalid path %q (expected section.field, e.g., server.port)", path)
+ }
+
+ section, field := parts[0], parts[1]
+
+ switch section {
+ case "server":
+ return getServerField(&fc.Server, field)
+ case "browser":
+ return getBrowserField(&fc.Browser, field)
+ case "instanceDefaults":
+ return getInstanceDefaultsField(&fc.InstanceDefaults, field)
+ case "security":
+ return getSecurityField(&fc.Security, field)
+ case "profiles":
+ return getProfilesField(&fc.Profiles, field)
+ case "multiInstance":
+ return getMultiInstanceField(&fc.MultiInstance, field)
+ case "timeouts":
+ return getTimeoutsField(&fc.Timeouts, field)
+ default:
+ return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)
+ }
+}
+
+func getServerField(s *ServerConfig, field string) (string, error) {
+ switch field {
+ case "port":
+ return s.Port, nil
+ case "bind":
+ return s.Bind, nil
+ case "token":
+ return s.Token, nil
+ case "stateDir":
+ return s.StateDir, nil
+ default:
+ return "", fmt.Errorf("unknown field server.%s", field)
+ }
+}
+
+func getBrowserField(b *BrowserConfig, field string) (string, error) {
+ switch field {
+ case "version":
+ return b.ChromeVersion, nil
+ case "binary":
+ return b.ChromeBinary, nil
+ case "extraFlags":
+ return b.ChromeExtraFlags, nil
+ default:
+ return "", fmt.Errorf("unknown field browser.%s", field)
+ }
+}
+
+func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string, error) {
+ switch field {
+ case "mode":
+ return c.Mode, nil
+ case "noRestore":
+ return formatBoolPtr(c.NoRestore), nil
+ case "timezone":
+ return c.Timezone, nil
+ case "blockImages":
+ return formatBoolPtr(c.BlockImages), nil
+ case "blockMedia":
+ return formatBoolPtr(c.BlockMedia), nil
+ case "blockAds":
+ return formatBoolPtr(c.BlockAds), nil
+ case "maxTabs":
+ return formatIntPtr(c.MaxTabs), nil
+ case "maxParallelTabs":
+ return formatIntPtr(c.MaxParallelTabs), nil
+ case "userAgent":
+ return c.UserAgent, nil
+ case "noAnimations":
+ return formatBoolPtr(c.NoAnimations), nil
+ case "stealthLevel":
+ return c.StealthLevel, nil
+ case "tabEvictionPolicy":
+ return c.TabEvictionPolicy, nil
+ default:
+ return "", fmt.Errorf("unknown field instanceDefaults.%s", field)
+ }
+}
+
+func getSecurityField(s *SecurityConfig, field string) (string, error) {
+ if strings.HasPrefix(field, "attach.") {
+ return getAttachField(&s.Attach, strings.TrimPrefix(field, "attach."))
+ }
+ if strings.HasPrefix(field, "idpi.") {
+ return getIDPIField(&s.IDPI, strings.TrimPrefix(field, "idpi."))
+ }
+
+ switch field {
+ case "allowEvaluate":
+ return formatBoolPtr(s.AllowEvaluate), nil
+ case "allowMacro":
+ return formatBoolPtr(s.AllowMacro), nil
+ case "allowScreencast":
+ return formatBoolPtr(s.AllowScreencast), nil
+ case "allowDownload":
+ return formatBoolPtr(s.AllowDownload), nil
+ case "downloadAllowedDomains":
+ return strings.Join(s.DownloadAllowedDomains, ","), nil
+ case "downloadMaxBytes":
+ return formatIntPtr(s.DownloadMaxBytes), nil
+ case "allowUpload":
+ return formatBoolPtr(s.AllowUpload), nil
+ case "uploadMaxRequestBytes":
+ return formatIntPtr(s.UploadMaxRequestBytes), nil
+ case "uploadMaxFiles":
+ return formatIntPtr(s.UploadMaxFiles), nil
+ case "uploadMaxFileBytes":
+ return formatIntPtr(s.UploadMaxFileBytes), nil
+ case "uploadMaxTotalBytes":
+ return formatIntPtr(s.UploadMaxTotalBytes), nil
+ case "maxRedirects":
+ return formatIntPtr(s.MaxRedirects), nil
+ default:
+ return "", fmt.Errorf("unknown field security.%s", field)
+ }
+}
+
+func getProfilesField(p *ProfilesConfig, field string) (string, error) {
+ switch field {
+ case "baseDir":
+ return p.BaseDir, nil
+ case "defaultProfile":
+ return p.DefaultProfile, nil
+ default:
+ return "", fmt.Errorf("unknown field profiles.%s", field)
+ }
+}
+
+func getMultiInstanceField(o *MultiInstanceConfig, field string) (string, error) {
+ if strings.HasPrefix(field, "restart.") {
+ return getMultiInstanceRestartField(&o.Restart, strings.TrimPrefix(field, "restart."))
+ }
+
+ switch field {
+ case "strategy":
+ return o.Strategy, nil
+ case "allocationPolicy":
+ return o.AllocationPolicy, nil
+ case "instancePortStart":
+ return formatIntPtr(o.InstancePortStart), nil
+ case "instancePortEnd":
+ return formatIntPtr(o.InstancePortEnd), nil
+ default:
+ return "", fmt.Errorf("unknown field multiInstance.%s", field)
+ }
+}
+
+func getMultiInstanceRestartField(r *MultiInstanceRestartConfig, field string) (string, error) {
+ switch field {
+ case "maxRestarts":
+ return formatIntPtr(r.MaxRestarts), nil
+ case "initBackoffSec":
+ return formatIntPtr(r.InitBackoffSec), nil
+ case "maxBackoffSec":
+ return formatIntPtr(r.MaxBackoffSec), nil
+ case "stableAfterSec":
+ return formatIntPtr(r.StableAfterSec), nil
+ default:
+ return "", fmt.Errorf("unknown field multiInstance.restart.%s", field)
+ }
+}
+
+func getAttachField(a *AttachConfig, field string) (string, error) {
+ switch field {
+ case "enabled":
+ return formatBoolPtr(a.Enabled), nil
+ case "allowHosts":
+ return strings.Join(a.AllowHosts, ","), nil
+ case "allowSchemes":
+ return strings.Join(a.AllowSchemes, ","), nil
+ default:
+ return "", fmt.Errorf("unknown field security.attach.%s", field)
+ }
+}
+
+func getIDPIField(i *IDPIConfig, field string) (string, error) {
+ switch field {
+ case "enabled":
+ return strconv.FormatBool(i.Enabled), nil
+ case "allowedDomains":
+ return strings.Join(i.AllowedDomains, ","), nil
+ case "strictMode":
+ return strconv.FormatBool(i.StrictMode), nil
+ case "scanContent":
+ return strconv.FormatBool(i.ScanContent), nil
+ case "wrapContent":
+ return strconv.FormatBool(i.WrapContent), nil
+ case "customPatterns":
+ return strings.Join(i.CustomPatterns, ","), nil
+ default:
+ return "", fmt.Errorf("unknown field security.idpi.%s", field)
+ }
+}
+
+func getTimeoutsField(t *TimeoutsConfig, field string) (string, error) {
+ switch field {
+ case "actionSec":
+ return strconv.Itoa(t.ActionSec), nil
+ case "navigateSec":
+ return strconv.Itoa(t.NavigateSec), nil
+ case "shutdownSec":
+ return strconv.Itoa(t.ShutdownSec), nil
+ case "waitNavMs":
+ return strconv.Itoa(t.WaitNavMs), nil
+ default:
+ return "", fmt.Errorf("unknown field timeouts.%s", field)
+ }
+}
+
+func formatBoolPtr(b *bool) string {
+ if b == nil {
+ return ""
+ }
+ if *b {
+ return "true"
+ }
+ return "false"
+}
+
+func formatIntPtr(n *int) string {
+ if n == nil {
+ return ""
+ }
+ return strconv.Itoa(*n)
+}
diff --git a/internal/config/editor_get_test.go b/internal/config/editor_get_test.go
new file mode 100644
index 00000000..b552b514
--- /dev/null
+++ b/internal/config/editor_get_test.go
@@ -0,0 +1,158 @@
+package config
+
+import "testing"
+
+func TestGetConfigValue_RoundTrip(t *testing.T) {
+ // For every path that SetConfigValue accepts, GetConfigValue must return
+ // a string that parses back to the same value.
+ triples := []struct {
+ path string
+ value string
+ want string // what GetConfigValue should return
+ }{
+ {"server.port", "8080", "8080"},
+ {"server.bind", "0.0.0.0", "0.0.0.0"},
+ {"server.token", "s3cr3t", "s3cr3t"},
+ {"server.stateDir", "/tmp/state", "/tmp/state"},
+ {"browser.version", "120.0", "120.0"},
+ {"browser.binary", "/usr/bin/chrome", "/usr/bin/chrome"},
+ {"instanceDefaults.mode", "headed", "headed"},
+ {"instanceDefaults.noRestore", "true", "true"},
+ {"instanceDefaults.blockImages", "false", "false"},
+ {"instanceDefaults.blockAds", "1", "true"}, // normalised by parseBool then formatBoolPtr
+ {"instanceDefaults.maxTabs", "50", "50"},
+ {"instanceDefaults.maxParallelTabs", "8", "8"},
+ {"instanceDefaults.userAgent", "MyBot/1.0", "MyBot/1.0"},
+ {"instanceDefaults.stealthLevel", "full", "full"},
+ {"instanceDefaults.tabEvictionPolicy", "close_lru", "close_lru"},
+ {"security.allowEvaluate", "true", "true"},
+ {"security.allowMacro", "false", "false"},
+ {"security.allowScreencast", "on", "true"},
+ {"security.allowDownload", "off", "false"},
+ {"security.downloadAllowedDomains", "pinchtab.com,*.pinchtab.com", "pinchtab.com,*.pinchtab.com"},
+ {"security.downloadMaxBytes", "33554432", "33554432"},
+ {"security.allowUpload", "yes", "true"},
+ {"security.uploadMaxRequestBytes", "12582912", "12582912"},
+ {"security.uploadMaxFiles", "12", "12"},
+ {"security.uploadMaxFileBytes", "6291456", "6291456"},
+ {"security.uploadMaxTotalBytes", "18874368", "18874368"},
+ {"profiles.baseDir", "/profiles", "/profiles"},
+ {"profiles.defaultProfile", "agent", "agent"},
+ {"multiInstance.strategy", "explicit", "explicit"},
+ {"multiInstance.allocationPolicy", "round_robin", "round_robin"},
+ {"multiInstance.instancePortStart", "9900", "9900"},
+ {"multiInstance.instancePortEnd", "9950", "9950"},
+ {"multiInstance.restart.maxRestarts", "12", "12"},
+ {"multiInstance.restart.initBackoffSec", "3", "3"},
+ {"multiInstance.restart.maxBackoffSec", "45", "45"},
+ {"multiInstance.restart.stableAfterSec", "600", "600"},
+ {"security.attach.enabled", "true", "true"},
+ {"security.idpi.enabled", "true", "true"},
+ {"security.idpi.allowedDomains", "localhost,example.com", "localhost,example.com"},
+ {"security.idpi.strictMode", "false", "false"},
+ {"security.idpi.scanContent", "true", "true"},
+ {"security.idpi.wrapContent", "true", "true"},
+ {"security.idpi.customPatterns", "ignore previous instructions,exfiltrate", "ignore previous instructions,exfiltrate"},
+ {"timeouts.actionSec", "60", "60"},
+ {"timeouts.navigateSec", "90", "90"},
+ {"timeouts.shutdownSec", "15", "15"},
+ {"timeouts.waitNavMs", "3000", "3000"},
+ }
+
+ for _, tt := range triples {
+ t.Run(tt.path, func(t *testing.T) {
+ fc := &FileConfig{}
+ if err := SetConfigValue(fc, tt.path, tt.value); err != nil {
+ t.Fatalf("SetConfigValue(%q, %q) error = %v", tt.path, tt.value, err)
+ }
+ got, err := GetConfigValue(fc, tt.path)
+ if err != nil {
+ t.Fatalf("GetConfigValue(%q) error = %v", tt.path, err)
+ }
+ if got != tt.want {
+ t.Errorf("GetConfigValue(%q) = %q, want %q", tt.path, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {
+ fc := &FileConfig{}
+ // Pointer fields that have not been set should return "".
+ ptrs := []string{
+ "instanceDefaults.noRestore",
+ "instanceDefaults.blockImages",
+ "instanceDefaults.blockMedia",
+ "instanceDefaults.blockAds",
+ "instanceDefaults.maxTabs",
+ "instanceDefaults.maxParallelTabs",
+ "instanceDefaults.noAnimations",
+ "security.allowEvaluate",
+ "security.allowMacro",
+ "security.allowScreencast",
+ "security.allowDownload",
+ "security.downloadMaxBytes",
+ "security.allowUpload",
+ "security.uploadMaxRequestBytes",
+ "security.uploadMaxFiles",
+ "security.uploadMaxFileBytes",
+ "security.uploadMaxTotalBytes",
+ "security.maxRedirects",
+ "multiInstance.instancePortStart",
+ "multiInstance.instancePortEnd",
+ "security.attach.enabled",
+ }
+ for _, path := range ptrs {
+ t.Run(path, func(t *testing.T) {
+ got, err := GetConfigValue(fc, path)
+ if err != nil {
+ t.Fatalf("GetConfigValue(%q) unexpected error: %v", path, err)
+ }
+ if got != "" {
+ t.Errorf("GetConfigValue(%q) = %q, want empty string for unset pointer", path, got)
+ }
+ })
+ }
+}
+
+func TestGetConfigValue_AttachSlices(t *testing.T) {
+ fc := &FileConfig{}
+ fc.Security.Attach.AllowHosts = []string{"127.0.0.1", "localhost"}
+ fc.Security.Attach.AllowSchemes = []string{"ws", "wss"}
+
+ hosts, err := GetConfigValue(fc, "security.attach.allowHosts")
+ if err != nil {
+ t.Fatalf("GetConfigValue(security.attach.allowHosts) error = %v", err)
+ }
+ if hosts != "127.0.0.1,localhost" {
+ t.Errorf("allowHosts = %q, want %q", hosts, "127.0.0.1,localhost")
+ }
+
+ schemes, err := GetConfigValue(fc, "security.attach.allowSchemes")
+ if err != nil {
+ t.Fatalf("GetConfigValue(security.attach.allowSchemes) error = %v", err)
+ }
+ if schemes != "ws,wss" {
+ t.Errorf("allowSchemes = %q, want %q", schemes, "ws,wss")
+ }
+}
+
+func TestGetConfigValue_UnknownPaths(t *testing.T) {
+ fc := &FileConfig{}
+ errorCases := []string{
+ "port", // missing section
+ "", // empty
+ "unknown.field", // unknown section
+ "server.ghost", // unknown field in known section
+ "security.attach.badfield", // unknown attach field
+ "security.idpi.badfield", // unknown idpi field
+ }
+ for _, path := range errorCases {
+ t.Run(path, func(t *testing.T) {
+ _, err := GetConfigValue(fc, path)
+ if err == nil {
+ t.Errorf("GetConfigValue(%q) should have returned an error", path)
+ }
+ })
+ }
+}
diff --git a/internal/config/editor_parse.go b/internal/config/editor_parse.go
new file mode 100644
index 00000000..290e3026
--- /dev/null
+++ b/internal/config/editor_parse.go
@@ -0,0 +1,32 @@
+package config
+
+import (
+ "fmt"
+ "strings"
+)
+
+func parseBool(s string) (bool, error) {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case "true", "1", "yes", "on":
+ return true, nil
+ case "false", "0", "no", "off":
+ return false, nil
+ default:
+ return false, fmt.Errorf("invalid boolean %q (use true/false)", s)
+ }
+}
+
+func parseCSVList(s string) []string {
+ if strings.TrimSpace(s) == "" {
+ return nil
+ }
+ raw := strings.Split(s, ",")
+ out := make([]string, 0, len(raw))
+ for _, item := range raw {
+ item = strings.TrimSpace(item)
+ if item != "" {
+ out = append(out, item)
+ }
+ }
+ return out
+}
diff --git a/internal/config/editor_parse_test.go b/internal/config/editor_parse_test.go
new file mode 100644
index 00000000..6ea2dd37
--- /dev/null
+++ b/internal/config/editor_parse_test.go
@@ -0,0 +1,39 @@
+package config
+
+import "testing"
+
+func TestParseBool(t *testing.T) {
+ tests := []struct {
+ input string
+ want bool
+ wantErr bool
+ }{
+ {"true", true, false},
+ {"True", true, false},
+ {"TRUE", true, false},
+ {"1", true, false},
+ {"yes", true, false},
+ {"on", true, false},
+ {"false", false, false},
+ {"False", false, false},
+ {"0", false, false},
+ {"no", false, false},
+ {"off", false, false},
+ {"maybe", false, true},
+ {"", false, true},
+ {"2", false, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got, err := parseBool(tt.input)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("parseBool(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && got != tt.want {
+ t.Errorf("parseBool(%q) = %v, want %v", tt.input, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/config/editor_patch.go b/internal/config/editor_patch.go
new file mode 100644
index 00000000..593456cc
--- /dev/null
+++ b/internal/config/editor_patch.go
@@ -0,0 +1,54 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+)
+
+// PatchConfigJSON merges a JSON object into FileConfig.
+func PatchConfigJSON(fc *FileConfig, jsonPatch string) error {
+ current, err := json.Marshal(fc)
+ if err != nil {
+ return fmt.Errorf("failed to serialize current config: %w", err)
+ }
+
+ var currentMap map[string]interface{}
+ if err := json.Unmarshal(current, &currentMap); err != nil {
+ return fmt.Errorf("failed to parse current config: %w", err)
+ }
+
+ var patchMap map[string]interface{}
+ if err := json.Unmarshal([]byte(jsonPatch), &patchMap); err != nil {
+ return fmt.Errorf("invalid JSON patch: %w", err)
+ }
+
+ merged := deepMerge(currentMap, patchMap)
+
+ mergedJSON, err := json.Marshal(merged)
+ if err != nil {
+ return fmt.Errorf("failed to serialize merged config: %w", err)
+ }
+
+ if err := json.Unmarshal(mergedJSON, fc); err != nil {
+ return fmt.Errorf("failed to parse merged config: %w", err)
+ }
+
+ return nil
+}
+
+func deepMerge(dst, src map[string]interface{}) map[string]interface{} {
+ result := make(map[string]interface{})
+ for k, v := range dst {
+ result[k] = v
+ }
+ for k, v := range src {
+ if srcMap, ok := v.(map[string]interface{}); ok {
+ if dstMap, ok := result[k].(map[string]interface{}); ok {
+ result[k] = deepMerge(dstMap, srcMap)
+ continue
+ }
+ }
+ result[k] = v
+ }
+ return result
+}
diff --git a/internal/config/editor_patch_test.go b/internal/config/editor_patch_test.go
new file mode 100644
index 00000000..524050e7
--- /dev/null
+++ b/internal/config/editor_patch_test.go
@@ -0,0 +1,67 @@
+package config
+
+import "testing"
+
+func TestPatchConfigJSON(t *testing.T) {
+ fc := &FileConfig{
+ Server: ServerConfig{
+ Port: "9867",
+ Bind: "127.0.0.1",
+ },
+ InstanceDefaults: InstanceDefaultsConfig{
+ StealthLevel: "light",
+ },
+ }
+
+ // Patch to change port and add token
+ patch := `{"server": {"port": "8080", "token": "secret"}}`
+ if err := PatchConfigJSON(fc, patch); err != nil {
+ t.Fatalf("PatchConfigJSON() error = %v", err)
+ }
+
+ if fc.Server.Port != "8080" {
+ t.Errorf("port = %v, want 8080", fc.Server.Port)
+ }
+ if fc.Server.Token != "secret" {
+ t.Errorf("token = %v, want secret", fc.Server.Token)
+ }
+ // Bind should be preserved
+ if fc.Server.Bind != "127.0.0.1" {
+ t.Errorf("bind = %v, want 127.0.0.1 (should be preserved)", fc.Server.Bind)
+ }
+ // InstanceDefaults.StealthLevel should be preserved
+ if fc.InstanceDefaults.StealthLevel != "light" {
+ t.Errorf("stealthLevel = %v, want light (should be preserved)", fc.InstanceDefaults.StealthLevel)
+ }
+}
+
+func TestPatchConfigJSON_NestedMerge(t *testing.T) {
+ fc := &FileConfig{
+ InstanceDefaults: InstanceDefaultsConfig{
+ StealthLevel: "light",
+ TabEvictionPolicy: "reject",
+ },
+ }
+
+ // Patch instanceDefaults section, should merge not replace
+ patch := `{"instanceDefaults": {"stealthLevel": "full"}}`
+ if err := PatchConfigJSON(fc, patch); err != nil {
+ t.Fatalf("PatchConfigJSON() error = %v", err)
+ }
+
+ if fc.InstanceDefaults.StealthLevel != "full" {
+ t.Errorf("stealthLevel = %v, want full", fc.InstanceDefaults.StealthLevel)
+ }
+ // tabEvictionPolicy should be preserved
+ if fc.InstanceDefaults.TabEvictionPolicy != "reject" {
+ t.Errorf("tabEvictionPolicy = %v, want reject (should be preserved)", fc.InstanceDefaults.TabEvictionPolicy)
+ }
+}
+
+func TestPatchConfigJSON_InvalidJSON(t *testing.T) {
+ fc := &FileConfig{}
+ err := PatchConfigJSON(fc, "not json")
+ if err == nil {
+ t.Error("PatchConfigJSON() should fail on invalid JSON")
+ }
+}
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
new file mode 100644
index 00000000..df9096b2
--- /dev/null
+++ b/internal/config/editor_set.go
@@ -0,0 +1,340 @@
+package config
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "instanceDefaults.mode").
+func SetConfigValue(fc *FileConfig, path string, value string) error {
+ parts := strings.SplitN(path, ".", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid path %q (expected section.field, e.g., server.port)", path)
+ }
+
+ section, field := parts[0], parts[1]
+
+ switch section {
+ case "server":
+ return setServerField(&fc.Server, field, value)
+ case "browser":
+ return setBrowserField(&fc.Browser, field, value)
+ case "instanceDefaults":
+ return setInstanceDefaultsField(&fc.InstanceDefaults, field, value)
+ case "security":
+ return setSecurityField(&fc.Security, field, value)
+ case "profiles":
+ return setProfilesField(&fc.Profiles, field, value)
+ case "multiInstance":
+ return setMultiInstanceField(&fc.MultiInstance, field, value)
+ case "timeouts":
+ return setTimeoutsField(&fc.Timeouts, field, value)
+ default:
+ return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)
+ }
+}
+
+func setServerField(s *ServerConfig, field, value string) error {
+ switch field {
+ case "port":
+ s.Port = value
+ case "bind":
+ s.Bind = value
+ case "token":
+ s.Token = value
+ case "stateDir":
+ s.StateDir = value
+ default:
+ return fmt.Errorf("unknown field server.%s", field)
+ }
+ return nil
+}
+
+func setBrowserField(b *BrowserConfig, field, value string) error {
+ switch field {
+ case "version":
+ b.ChromeVersion = value
+ case "binary":
+ b.ChromeBinary = value
+ case "extraFlags":
+ b.ChromeExtraFlags = value
+ default:
+ return fmt.Errorf("unknown field browser.%s", field)
+ }
+ return nil
+}
+
+func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) error {
+ switch field {
+ case "mode":
+ c.Mode = value
+ case "noRestore":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.noRestore: %w", err)
+ }
+ c.NoRestore = &b
+ case "timezone":
+ c.Timezone = value
+ case "blockImages":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.blockImages: %w", err)
+ }
+ c.BlockImages = &b
+ case "blockMedia":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.blockMedia: %w", err)
+ }
+ c.BlockMedia = &b
+ case "blockAds":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.blockAds: %w", err)
+ }
+ c.BlockAds = &b
+ case "maxTabs":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.maxTabs must be a number: %w", err)
+ }
+ c.MaxTabs = &n
+ case "maxParallelTabs":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.maxParallelTabs must be a number: %w", err)
+ }
+ c.MaxParallelTabs = &n
+ case "userAgent":
+ c.UserAgent = value
+ case "noAnimations":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("instanceDefaults.noAnimations: %w", err)
+ }
+ c.NoAnimations = &b
+ case "stealthLevel":
+ c.StealthLevel = value
+ case "tabEvictionPolicy":
+ c.TabEvictionPolicy = value
+ default:
+ return fmt.Errorf("unknown field instanceDefaults.%s", field)
+ }
+ return nil
+}
+
+func setSecurityField(s *SecurityConfig, field, value string) error {
+ if strings.HasPrefix(field, "attach.") {
+ return setAttachField(&s.Attach, strings.TrimPrefix(field, "attach."), value)
+ }
+ if strings.HasPrefix(field, "idpi.") {
+ return setIDPIField(&s.IDPI, strings.TrimPrefix(field, "idpi."), value)
+ }
+ if field == "downloadAllowedDomains" {
+ s.DownloadAllowedDomains = parseCSVList(value)
+ return nil
+ }
+ switch field {
+ case "downloadMaxBytes":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.downloadMaxBytes must be a number: %w", err)
+ }
+ s.DownloadMaxBytes = &n
+ return nil
+ case "uploadMaxRequestBytes":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.uploadMaxRequestBytes must be a number: %w", err)
+ }
+ s.UploadMaxRequestBytes = &n
+ return nil
+ case "uploadMaxFiles":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.uploadMaxFiles must be a number: %w", err)
+ }
+ s.UploadMaxFiles = &n
+ return nil
+ case "uploadMaxFileBytes":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.uploadMaxFileBytes must be a number: %w", err)
+ }
+ s.UploadMaxFileBytes = &n
+ return nil
+ case "uploadMaxTotalBytes":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.uploadMaxTotalBytes must be a number: %w", err)
+ }
+ s.UploadMaxTotalBytes = &n
+ return nil
+ case "maxRedirects":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.maxRedirects must be a number: %w", err)
+ }
+ s.MaxRedirects = &n
+ return nil
+ }
+
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.%s: %w", field, err)
+ }
+
+ switch field {
+ case "allowEvaluate":
+ s.AllowEvaluate = &b
+ case "allowMacro":
+ s.AllowMacro = &b
+ case "allowScreencast":
+ s.AllowScreencast = &b
+ case "allowDownload":
+ s.AllowDownload = &b
+ case "allowUpload":
+ s.AllowUpload = &b
+ default:
+ return fmt.Errorf("unknown field security.%s", field)
+ }
+ return nil
+}
+
+func setProfilesField(p *ProfilesConfig, field, value string) error {
+ switch field {
+ case "baseDir":
+ p.BaseDir = value
+ case "defaultProfile":
+ p.DefaultProfile = value
+ default:
+ return fmt.Errorf("unknown field profiles.%s", field)
+ }
+ return nil
+}
+
+func setMultiInstanceField(o *MultiInstanceConfig, field, value string) error {
+ if strings.HasPrefix(field, "restart.") {
+ return setMultiInstanceRestartField(&o.Restart, strings.TrimPrefix(field, "restart."), value)
+ }
+
+ switch field {
+ case "strategy":
+ o.Strategy = value
+ case "allocationPolicy":
+ o.AllocationPolicy = value
+ case "instancePortStart":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("multiInstance.instancePortStart must be a number: %w", err)
+ }
+ o.InstancePortStart = &n
+ case "instancePortEnd":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("multiInstance.instancePortEnd must be a number: %w", err)
+ }
+ o.InstancePortEnd = &n
+ default:
+ return fmt.Errorf("unknown field multiInstance.%s", field)
+ }
+ return nil
+}
+
+func setMultiInstanceRestartField(r *MultiInstanceRestartConfig, field, value string) error {
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("multiInstance.restart.%s must be a number: %w", field, err)
+ }
+
+ switch field {
+ case "maxRestarts":
+ r.MaxRestarts = &n
+ case "initBackoffSec":
+ r.InitBackoffSec = &n
+ case "maxBackoffSec":
+ r.MaxBackoffSec = &n
+ case "stableAfterSec":
+ r.StableAfterSec = &n
+ default:
+ return fmt.Errorf("unknown field multiInstance.restart.%s", field)
+ }
+ return nil
+}
+
+func setTimeoutsField(t *TimeoutsConfig, field, value string) error {
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("timeouts.%s must be a number: %w", field, err)
+ }
+
+ switch field {
+ case "actionSec":
+ t.ActionSec = n
+ case "navigateSec":
+ t.NavigateSec = n
+ case "shutdownSec":
+ t.ShutdownSec = n
+ case "waitNavMs":
+ t.WaitNavMs = n
+ default:
+ return fmt.Errorf("unknown field timeouts.%s", field)
+ }
+ return nil
+}
+
+func setAttachField(a *AttachConfig, field, value string) error {
+ switch field {
+ case "enabled":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.attach.enabled: %w", err)
+ }
+ a.Enabled = &b
+ case "allowHosts":
+ a.AllowHosts = parseCSVList(value)
+ case "allowSchemes":
+ a.AllowSchemes = parseCSVList(value)
+ default:
+ return fmt.Errorf("unknown field security.attach.%s", field)
+ }
+ return nil
+}
+
+func setIDPIField(i *IDPIConfig, field, value string) error {
+ switch field {
+ case "enabled":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.enabled: %w", err)
+ }
+ i.Enabled = b
+ case "allowedDomains":
+ i.AllowedDomains = parseCSVList(value)
+ case "strictMode":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.strictMode: %w", err)
+ }
+ i.StrictMode = b
+ case "scanContent":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.scanContent: %w", err)
+ }
+ i.ScanContent = b
+ case "wrapContent":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.wrapContent: %w", err)
+ }
+ i.WrapContent = b
+ case "customPatterns":
+ i.CustomPatterns = parseCSVList(value)
+ default:
+ return fmt.Errorf("unknown field security.idpi.%s", field)
+ }
+ return nil
+}
diff --git a/internal/config/editor_set_test.go b/internal/config/editor_set_test.go
new file mode 100644
index 00000000..0c1dad7d
--- /dev/null
+++ b/internal/config/editor_set_test.go
@@ -0,0 +1,271 @@
+package config
+
+import "testing"
+
+func TestSetConfigValue_ServerFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"server.port", "8080", func(fc *FileConfig) bool { return fc.Server.Port == "8080" }, false},
+ {"server.bind", "0.0.0.0", func(fc *FileConfig) bool { return fc.Server.Bind == "0.0.0.0" }, false},
+ {"server.token", "secret", func(fc *FileConfig) bool { return fc.Server.Token == "secret" }, false},
+ {"server.stateDir", "/tmp/state", func(fc *FileConfig) bool { return fc.Server.StateDir == "/tmp/state" }, false},
+ {"server.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_BrowserAndInstanceDefaultsFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"browser.version", "144.0.7559.133", func(fc *FileConfig) bool { return fc.Browser.ChromeVersion == "144.0.7559.133" }, false},
+ {"browser.binary", "/tmp/chrome", func(fc *FileConfig) bool { return fc.Browser.ChromeBinary == "/tmp/chrome" }, false},
+ {"instanceDefaults.mode", "headed", func(fc *FileConfig) bool { return fc.InstanceDefaults.Mode == "headed" }, false},
+ {"instanceDefaults.maxTabs", "50", func(fc *FileConfig) bool { return *fc.InstanceDefaults.MaxTabs == 50 }, false},
+ {"instanceDefaults.stealthLevel", "full", func(fc *FileConfig) bool { return fc.InstanceDefaults.StealthLevel == "full" }, false},
+ {"instanceDefaults.tabEvictionPolicy", "close_lru", func(fc *FileConfig) bool { return fc.InstanceDefaults.TabEvictionPolicy == "close_lru" }, false},
+ {"instanceDefaults.blockAds", "yes", func(fc *FileConfig) bool { return *fc.InstanceDefaults.BlockAds == true }, false},
+ {"profiles.baseDir", "/tmp/profiles", func(fc *FileConfig) bool { return fc.Profiles.BaseDir == "/tmp/profiles" }, false},
+ {"instanceDefaults.noRestore", "maybe", nil, true},
+ {"instanceDefaults.maxTabs", "many", nil, true},
+ {"instanceDefaults.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_SecurityFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"security.allowEvaluate", "true", func(fc *FileConfig) bool { return *fc.Security.AllowEvaluate == true }, false},
+ {"security.allowMacro", "1", func(fc *FileConfig) bool { return *fc.Security.AllowMacro == true }, false},
+ {"security.allowScreencast", "false", func(fc *FileConfig) bool { return *fc.Security.AllowScreencast == false }, false},
+ {"security.allowDownload", "on", func(fc *FileConfig) bool { return *fc.Security.AllowDownload == true }, false},
+ {"security.downloadAllowedDomains", "pinchtab.com, *.pinchtab.com", func(fc *FileConfig) bool {
+ return len(fc.Security.DownloadAllowedDomains) == 2 &&
+ fc.Security.DownloadAllowedDomains[0] == "pinchtab.com" &&
+ fc.Security.DownloadAllowedDomains[1] == "*.pinchtab.com"
+ }, false},
+ {"security.downloadMaxBytes", "33554432", func(fc *FileConfig) bool {
+ return fc.Security.DownloadMaxBytes != nil && *fc.Security.DownloadMaxBytes == 33554432
+ }, false},
+ {"security.allowUpload", "off", func(fc *FileConfig) bool { return *fc.Security.AllowUpload == false }, false},
+ {"security.uploadMaxRequestBytes", "12582912", func(fc *FileConfig) bool {
+ return fc.Security.UploadMaxRequestBytes != nil && *fc.Security.UploadMaxRequestBytes == 12582912
+ }, false},
+ {"security.uploadMaxFiles", "12", func(fc *FileConfig) bool {
+ return fc.Security.UploadMaxFiles != nil && *fc.Security.UploadMaxFiles == 12
+ }, false},
+ {"security.uploadMaxFileBytes", "6291456", func(fc *FileConfig) bool {
+ return fc.Security.UploadMaxFileBytes != nil && *fc.Security.UploadMaxFileBytes == 6291456
+ }, false},
+ {"security.uploadMaxTotalBytes", "18874368", func(fc *FileConfig) bool {
+ return fc.Security.UploadMaxTotalBytes != nil && *fc.Security.UploadMaxTotalBytes == 18874368
+ }, false},
+ {"security.allowEvaluate", "maybe", nil, true},
+ {"security.unknown", "true", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_MultiInstanceFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"multiInstance.strategy", "explicit", func(fc *FileConfig) bool { return fc.MultiInstance.Strategy == "explicit" }, false},
+ {"multiInstance.allocationPolicy", "round_robin", func(fc *FileConfig) bool { return fc.MultiInstance.AllocationPolicy == "round_robin" }, false},
+ {"multiInstance.instancePortStart", "9900", func(fc *FileConfig) bool { return *fc.MultiInstance.InstancePortStart == 9900 }, false},
+ {"multiInstance.restart.maxRestarts", "12", func(fc *FileConfig) bool {
+ return fc.MultiInstance.Restart.MaxRestarts != nil && *fc.MultiInstance.Restart.MaxRestarts == 12
+ }, false},
+ {"multiInstance.restart.initBackoffSec", "3", func(fc *FileConfig) bool {
+ return fc.MultiInstance.Restart.InitBackoffSec != nil && *fc.MultiInstance.Restart.InitBackoffSec == 3
+ }, false},
+ {"multiInstance.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_AttachFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"security.attach.enabled", "true", func(fc *FileConfig) bool { return fc.Security.Attach.Enabled != nil && *fc.Security.Attach.Enabled }, false},
+ {"security.attach.allowHosts", "localhost, chrome.internal", func(fc *FileConfig) bool {
+ return len(fc.Security.Attach.AllowHosts) == 2 && fc.Security.Attach.AllowHosts[1] == "chrome.internal"
+ }, false},
+ {"security.attach.allowSchemes", "ws,wss", func(fc *FileConfig) bool {
+ return len(fc.Security.Attach.AllowSchemes) == 2 && fc.Security.Attach.AllowSchemes[0] == "ws"
+ }, false},
+ {"security.attach.enabled", "maybe", nil, true},
+ {"security.attach.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_IDPIFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"security.idpi.enabled", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.Enabled }, false},
+ {"security.idpi.allowedDomains", "localhost, example.com", func(fc *FileConfig) bool {
+ return len(fc.Security.IDPI.AllowedDomains) == 2 && fc.Security.IDPI.AllowedDomains[1] == "example.com"
+ }, false},
+ {"security.idpi.strictMode", "false", func(fc *FileConfig) bool { return !fc.Security.IDPI.StrictMode }, false},
+ {"security.idpi.scanContent", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.ScanContent }, false},
+ {"security.idpi.wrapContent", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.WrapContent }, false},
+ {"security.idpi.customPatterns", "ignore previous instructions, exfiltrate data", func(fc *FileConfig) bool {
+ return len(fc.Security.IDPI.CustomPatterns) == 2 && fc.Security.IDPI.CustomPatterns[0] == "ignore previous instructions"
+ }, false},
+ {"security.idpi.enabled", "maybe", nil, true},
+ {"security.idpi.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_TimeoutsFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"timeouts.actionSec", "60", func(fc *FileConfig) bool { return fc.Timeouts.ActionSec == 60 }, false},
+ {"timeouts.navigateSec", "120", func(fc *FileConfig) bool { return fc.Timeouts.NavigateSec == 120 }, false},
+ {"timeouts.shutdownSec", "30", func(fc *FileConfig) bool { return fc.Timeouts.ShutdownSec == 30 }, false},
+ {"timeouts.waitNavMs", "2000", func(fc *FileConfig) bool { return fc.Timeouts.WaitNavMs == 2000 }, false},
+ {"timeouts.actionSec", "fast", nil, true},
+ {"timeouts.unknown", "10", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_InvalidPaths(t *testing.T) {
+ tests := []string{
+ "port", // missing section
+ "", // empty
+ "unknown.field", // unknown section
+ "server", // missing field
+ "a.b.c", // too many parts (we only split on first .)
+ }
+
+ for _, path := range tests {
+ t.Run(path, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, path, "value")
+ if err == nil {
+ t.Errorf("SetConfigValue(%q) should have failed", path)
+ }
+ })
+ }
+}
diff --git a/internal/config/editor_test.go b/internal/config/editor_test.go
deleted file mode 100644
index d988ccc6..00000000
--- a/internal/config/editor_test.go
+++ /dev/null
@@ -1,576 +0,0 @@
-package config
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestSetConfigValue_ServerFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"server.port", "8080", func(fc *FileConfig) bool { return fc.Server.Port == "8080" }, false},
- {"server.bind", "0.0.0.0", func(fc *FileConfig) bool { return fc.Server.Bind == "0.0.0.0" }, false},
- {"server.token", "secret", func(fc *FileConfig) bool { return fc.Server.Token == "secret" }, false},
- {"server.stateDir", "/tmp/state", func(fc *FileConfig) bool { return fc.Server.StateDir == "/tmp/state" }, false},
- {"server.unknown", "value", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_BrowserAndInstanceDefaultsFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"browser.version", "144.0.7559.133", func(fc *FileConfig) bool { return fc.Browser.ChromeVersion == "144.0.7559.133" }, false},
- {"browser.binary", "/tmp/chrome", func(fc *FileConfig) bool { return fc.Browser.ChromeBinary == "/tmp/chrome" }, false},
- {"instanceDefaults.mode", "headed", func(fc *FileConfig) bool { return fc.InstanceDefaults.Mode == "headed" }, false},
- {"instanceDefaults.maxTabs", "50", func(fc *FileConfig) bool { return *fc.InstanceDefaults.MaxTabs == 50 }, false},
- {"instanceDefaults.stealthLevel", "full", func(fc *FileConfig) bool { return fc.InstanceDefaults.StealthLevel == "full" }, false},
- {"instanceDefaults.tabEvictionPolicy", "close_lru", func(fc *FileConfig) bool { return fc.InstanceDefaults.TabEvictionPolicy == "close_lru" }, false},
- {"instanceDefaults.blockAds", "yes", func(fc *FileConfig) bool { return *fc.InstanceDefaults.BlockAds == true }, false},
- {"profiles.baseDir", "/tmp/profiles", func(fc *FileConfig) bool { return fc.Profiles.BaseDir == "/tmp/profiles" }, false},
- {"instanceDefaults.noRestore", "maybe", nil, true},
- {"instanceDefaults.maxTabs", "many", nil, true},
- {"instanceDefaults.unknown", "value", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_SecurityFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"security.allowEvaluate", "true", func(fc *FileConfig) bool { return *fc.Security.AllowEvaluate == true }, false},
- {"security.allowMacro", "1", func(fc *FileConfig) bool { return *fc.Security.AllowMacro == true }, false},
- {"security.allowScreencast", "false", func(fc *FileConfig) bool { return *fc.Security.AllowScreencast == false }, false},
- {"security.allowDownload", "on", func(fc *FileConfig) bool { return *fc.Security.AllowDownload == true }, false},
- {"security.allowUpload", "off", func(fc *FileConfig) bool { return *fc.Security.AllowUpload == false }, false},
- {"security.allowEvaluate", "maybe", nil, true},
- {"security.unknown", "true", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_MultiInstanceFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"multiInstance.strategy", "explicit", func(fc *FileConfig) bool { return fc.MultiInstance.Strategy == "explicit" }, false},
- {"multiInstance.allocationPolicy", "round_robin", func(fc *FileConfig) bool { return fc.MultiInstance.AllocationPolicy == "round_robin" }, false},
- {"multiInstance.instancePortStart", "9900", func(fc *FileConfig) bool { return *fc.MultiInstance.InstancePortStart == 9900 }, false},
- {"multiInstance.restart.maxRestarts", "12", func(fc *FileConfig) bool {
- return fc.MultiInstance.Restart.MaxRestarts != nil && *fc.MultiInstance.Restart.MaxRestarts == 12
- }, false},
- {"multiInstance.restart.initBackoffSec", "3", func(fc *FileConfig) bool {
- return fc.MultiInstance.Restart.InitBackoffSec != nil && *fc.MultiInstance.Restart.InitBackoffSec == 3
- }, false},
- {"multiInstance.unknown", "value", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_AttachFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"security.attach.enabled", "true", func(fc *FileConfig) bool { return fc.Security.Attach.Enabled != nil && *fc.Security.Attach.Enabled }, false},
- {"security.attach.allowHosts", "localhost, chrome.internal", func(fc *FileConfig) bool {
- return len(fc.Security.Attach.AllowHosts) == 2 && fc.Security.Attach.AllowHosts[1] == "chrome.internal"
- }, false},
- {"security.attach.allowSchemes", "ws,wss", func(fc *FileConfig) bool {
- return len(fc.Security.Attach.AllowSchemes) == 2 && fc.Security.Attach.AllowSchemes[0] == "ws"
- }, false},
- {"security.attach.enabled", "maybe", nil, true},
- {"security.attach.unknown", "value", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_IDPIFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"security.idpi.enabled", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.Enabled }, false},
- {"security.idpi.allowedDomains", "localhost, example.com", func(fc *FileConfig) bool {
- return len(fc.Security.IDPI.AllowedDomains) == 2 && fc.Security.IDPI.AllowedDomains[1] == "example.com"
- }, false},
- {"security.idpi.strictMode", "false", func(fc *FileConfig) bool { return !fc.Security.IDPI.StrictMode }, false},
- {"security.idpi.scanContent", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.ScanContent }, false},
- {"security.idpi.wrapContent", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.WrapContent }, false},
- {"security.idpi.customPatterns", "ignore previous instructions, exfiltrate data", func(fc *FileConfig) bool {
- return len(fc.Security.IDPI.CustomPatterns) == 2 && fc.Security.IDPI.CustomPatterns[0] == "ignore previous instructions"
- }, false},
- {"security.idpi.enabled", "maybe", nil, true},
- {"security.idpi.unknown", "value", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_TimeoutsFields(t *testing.T) {
- tests := []struct {
- path string
- value string
- check func(*FileConfig) bool
- wantErr bool
- }{
- {"timeouts.actionSec", "60", func(fc *FileConfig) bool { return fc.Timeouts.ActionSec == 60 }, false},
- {"timeouts.navigateSec", "120", func(fc *FileConfig) bool { return fc.Timeouts.NavigateSec == 120 }, false},
- {"timeouts.shutdownSec", "30", func(fc *FileConfig) bool { return fc.Timeouts.ShutdownSec == 30 }, false},
- {"timeouts.waitNavMs", "2000", func(fc *FileConfig) bool { return fc.Timeouts.WaitNavMs == 2000 }, false},
- {"timeouts.actionSec", "fast", nil, true},
- {"timeouts.unknown", "10", nil, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.path+"="+tt.value, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, tt.path, tt.value)
- if (err != nil) != tt.wantErr {
- t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !tt.wantErr && !tt.check(fc) {
- t.Errorf("SetConfigValue() did not set value correctly")
- }
- })
- }
-}
-
-func TestSetConfigValue_InvalidPaths(t *testing.T) {
- tests := []string{
- "port", // missing section
- "", // empty
- "unknown.field", // unknown section
- "server", // missing field
- "a.b.c", // too many parts (we only split on first .)
- }
-
- for _, path := range tests {
- t.Run(path, func(t *testing.T) {
- fc := &FileConfig{}
- err := SetConfigValue(fc, path, "value")
- if err == nil {
- t.Errorf("SetConfigValue(%q) should have failed", path)
- }
- })
- }
-}
-
-func TestPatchConfigJSON(t *testing.T) {
- fc := &FileConfig{
- Server: ServerConfig{
- Port: "9867",
- Bind: "127.0.0.1",
- },
- InstanceDefaults: InstanceDefaultsConfig{
- StealthLevel: "light",
- },
- }
-
- // Patch to change port and add token
- patch := `{"server": {"port": "8080", "token": "secret"}}`
- if err := PatchConfigJSON(fc, patch); err != nil {
- t.Fatalf("PatchConfigJSON() error = %v", err)
- }
-
- if fc.Server.Port != "8080" {
- t.Errorf("port = %v, want 8080", fc.Server.Port)
- }
- if fc.Server.Token != "secret" {
- t.Errorf("token = %v, want secret", fc.Server.Token)
- }
- // Bind should be preserved
- if fc.Server.Bind != "127.0.0.1" {
- t.Errorf("bind = %v, want 127.0.0.1 (should be preserved)", fc.Server.Bind)
- }
- // InstanceDefaults.StealthLevel should be preserved
- if fc.InstanceDefaults.StealthLevel != "light" {
- t.Errorf("stealthLevel = %v, want light (should be preserved)", fc.InstanceDefaults.StealthLevel)
- }
-}
-
-func TestPatchConfigJSON_NestedMerge(t *testing.T) {
- fc := &FileConfig{
- InstanceDefaults: InstanceDefaultsConfig{
- StealthLevel: "light",
- TabEvictionPolicy: "reject",
- },
- }
-
- // Patch instanceDefaults section, should merge not replace
- patch := `{"instanceDefaults": {"stealthLevel": "full"}}`
- if err := PatchConfigJSON(fc, patch); err != nil {
- t.Fatalf("PatchConfigJSON() error = %v", err)
- }
-
- if fc.InstanceDefaults.StealthLevel != "full" {
- t.Errorf("stealthLevel = %v, want full", fc.InstanceDefaults.StealthLevel)
- }
- // tabEvictionPolicy should be preserved
- if fc.InstanceDefaults.TabEvictionPolicy != "reject" {
- t.Errorf("tabEvictionPolicy = %v, want reject (should be preserved)", fc.InstanceDefaults.TabEvictionPolicy)
- }
-}
-
-func TestPatchConfigJSON_InvalidJSON(t *testing.T) {
- fc := &FileConfig{}
- err := PatchConfigJSON(fc, "not json")
- if err == nil {
- t.Error("PatchConfigJSON() should fail on invalid JSON")
- }
-}
-
-func TestLoadAndSaveFileConfig(t *testing.T) {
- tmpDir := t.TempDir()
- configPath := filepath.Join(tmpDir, "config.json")
- _ = os.Setenv("PINCHTAB_CONFIG", configPath)
- defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
-
- // Load (should return empty config for non-existent file)
- fc, path, err := LoadFileConfig()
- if err != nil {
- t.Fatalf("LoadFileConfig() error = %v", err)
- }
- if path != configPath {
- t.Errorf("path = %v, want %v", path, configPath)
- }
-
- // Modify
- fc.Server.Port = "8080"
- fc.InstanceDefaults.StealthLevel = "full"
-
- // Save
- if err := SaveFileConfig(fc, path); err != nil {
- t.Fatalf("SaveFileConfig() error = %v", err)
- }
-
- // Load again
- fc2, _, err := LoadFileConfig()
- if err != nil {
- t.Fatalf("LoadFileConfig() second time error = %v", err)
- }
-
- if fc2.Server.Port != "8080" {
- t.Errorf("loaded port = %v, want 8080", fc2.Server.Port)
- }
- if fc2.InstanceDefaults.StealthLevel != "full" {
- t.Errorf("loaded stealthLevel = %v, want full", fc2.InstanceDefaults.StealthLevel)
- }
-}
-
-func TestLoadAndSaveFileConfigPreservesExplicitZeroValues(t *testing.T) {
- tmpDir := t.TempDir()
- configPath := filepath.Join(tmpDir, "config.json")
- _ = os.Setenv("PINCHTAB_CONFIG", configPath)
- defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
-
- fc := DefaultFileConfig()
- fc.Server.Bind = ""
- fc.Server.Token = ""
- fc.Browser.ExtensionPaths = []string{}
- fc.InstanceDefaults.UserAgent = ""
- fc.Security.IDPI.StrictMode = false
- fc.Security.IDPI.AllowedDomains = []string{}
- fc.Security.IDPI.CustomPatterns = []string{}
-
- if err := SaveFileConfig(&fc, configPath); err != nil {
- t.Fatalf("SaveFileConfig() error = %v", err)
- }
-
- loaded, _, err := LoadFileConfig()
- if err != nil {
- t.Fatalf("LoadFileConfig() error = %v", err)
- }
-
- if loaded.Server.Bind != "" {
- t.Errorf("loaded bind = %q, want empty string", loaded.Server.Bind)
- }
- if loaded.Security.IDPI.StrictMode {
- t.Errorf("loaded strictMode = %v, want false", loaded.Security.IDPI.StrictMode)
- }
- if len(loaded.Security.IDPI.AllowedDomains) != 0 {
- t.Errorf("loaded allowedDomains = %v, want empty list", loaded.Security.IDPI.AllowedDomains)
- }
- if len(loaded.Browser.ExtensionPaths) != 0 {
- t.Errorf("loaded extensionPaths = %v, want empty list", loaded.Browser.ExtensionPaths)
- }
-}
-
-func TestParseBool(t *testing.T) {
- tests := []struct {
- input string
- want bool
- wantErr bool
- }{
- {"true", true, false},
- {"True", true, false},
- {"TRUE", true, false},
- {"1", true, false},
- {"yes", true, false},
- {"on", true, false},
- {"false", false, false},
- {"False", false, false},
- {"0", false, false},
- {"no", false, false},
- {"off", false, false},
- {"maybe", false, true},
- {"", false, true},
- {"2", false, true},
- }
-
- for _, tt := range tests {
- t.Run(tt.input, func(t *testing.T) {
- got, err := parseBool(tt.input)
- if (err != nil) != tt.wantErr {
- t.Errorf("parseBool(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
- return
- }
- if !tt.wantErr && got != tt.want {
- t.Errorf("parseBool(%q) = %v, want %v", tt.input, got, tt.want)
- }
- })
- }
-}
-
-// --- GetConfigValue ---
-
-func TestGetConfigValue_RoundTrip(t *testing.T) {
- // For every path that SetConfigValue accepts, GetConfigValue must return
- // a string that parses back to the same value.
- triples := []struct {
- path string
- value string
- want string // what GetConfigValue should return
- }{
- {"server.port", "8080", "8080"},
- {"server.bind", "0.0.0.0", "0.0.0.0"},
- {"server.token", "s3cr3t", "s3cr3t"},
- {"server.stateDir", "/tmp/state", "/tmp/state"},
- {"browser.version", "120.0", "120.0"},
- {"browser.binary", "/usr/bin/chrome", "/usr/bin/chrome"},
- {"instanceDefaults.mode", "headed", "headed"},
- {"instanceDefaults.noRestore", "true", "true"},
- {"instanceDefaults.blockImages", "false", "false"},
- {"instanceDefaults.blockAds", "1", "true"}, // normalised by parseBool then formatBoolPtr
- {"instanceDefaults.maxTabs", "50", "50"},
- {"instanceDefaults.maxParallelTabs", "8", "8"},
- {"instanceDefaults.userAgent", "MyBot/1.0", "MyBot/1.0"},
- {"instanceDefaults.stealthLevel", "full", "full"},
- {"instanceDefaults.tabEvictionPolicy", "close_lru", "close_lru"},
- {"security.allowEvaluate", "true", "true"},
- {"security.allowMacro", "false", "false"},
- {"security.allowScreencast", "on", "true"},
- {"security.allowDownload", "off", "false"},
- {"security.allowUpload", "yes", "true"},
- {"profiles.baseDir", "/profiles", "/profiles"},
- {"profiles.defaultProfile", "agent", "agent"},
- {"multiInstance.strategy", "explicit", "explicit"},
- {"multiInstance.allocationPolicy", "round_robin", "round_robin"},
- {"multiInstance.instancePortStart", "9900", "9900"},
- {"multiInstance.instancePortEnd", "9950", "9950"},
- {"multiInstance.restart.maxRestarts", "12", "12"},
- {"multiInstance.restart.initBackoffSec", "3", "3"},
- {"multiInstance.restart.maxBackoffSec", "45", "45"},
- {"multiInstance.restart.stableAfterSec", "600", "600"},
- {"security.attach.enabled", "true", "true"},
- {"security.idpi.enabled", "true", "true"},
- {"security.idpi.allowedDomains", "localhost,example.com", "localhost,example.com"},
- {"security.idpi.strictMode", "false", "false"},
- {"security.idpi.scanContent", "true", "true"},
- {"security.idpi.wrapContent", "true", "true"},
- {"security.idpi.customPatterns", "ignore previous instructions,exfiltrate", "ignore previous instructions,exfiltrate"},
- {"timeouts.actionSec", "60", "60"},
- {"timeouts.navigateSec", "90", "90"},
- {"timeouts.shutdownSec", "15", "15"},
- {"timeouts.waitNavMs", "3000", "3000"},
- }
-
- for _, tt := range triples {
- t.Run(tt.path, func(t *testing.T) {
- fc := &FileConfig{}
- if err := SetConfigValue(fc, tt.path, tt.value); err != nil {
- t.Fatalf("SetConfigValue(%q, %q) error = %v", tt.path, tt.value, err)
- }
- got, err := GetConfigValue(fc, tt.path)
- if err != nil {
- t.Fatalf("GetConfigValue(%q) error = %v", tt.path, err)
- }
- if got != tt.want {
- t.Errorf("GetConfigValue(%q) = %q, want %q", tt.path, got, tt.want)
- }
- })
- }
-}
-
-func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {
- fc := &FileConfig{}
- // Pointer fields that have not been set should return "".
- ptrs := []string{
- "instanceDefaults.noRestore",
- "instanceDefaults.blockImages",
- "instanceDefaults.blockMedia",
- "instanceDefaults.blockAds",
- "instanceDefaults.maxTabs",
- "instanceDefaults.maxParallelTabs",
- "instanceDefaults.noAnimations",
- "security.allowEvaluate",
- "security.allowMacro",
- "security.allowScreencast",
- "security.allowDownload",
- "security.allowUpload",
- "multiInstance.instancePortStart",
- "multiInstance.instancePortEnd",
- "security.attach.enabled",
- }
- for _, path := range ptrs {
- t.Run(path, func(t *testing.T) {
- got, err := GetConfigValue(fc, path)
- if err != nil {
- t.Fatalf("GetConfigValue(%q) unexpected error: %v", path, err)
- }
- if got != "" {
- t.Errorf("GetConfigValue(%q) = %q, want empty string for unset pointer", path, got)
- }
- })
- }
-}
-
-func TestGetConfigValue_AttachSlices(t *testing.T) {
- fc := &FileConfig{}
- fc.Security.Attach.AllowHosts = []string{"127.0.0.1", "localhost"}
- fc.Security.Attach.AllowSchemes = []string{"ws", "wss"}
-
- hosts, err := GetConfigValue(fc, "security.attach.allowHosts")
- if err != nil {
- t.Fatalf("GetConfigValue(security.attach.allowHosts) error = %v", err)
- }
- if hosts != "127.0.0.1,localhost" {
- t.Errorf("allowHosts = %q, want %q", hosts, "127.0.0.1,localhost")
- }
-
- schemes, err := GetConfigValue(fc, "security.attach.allowSchemes")
- if err != nil {
- t.Fatalf("GetConfigValue(security.attach.allowSchemes) error = %v", err)
- }
- if schemes != "ws,wss" {
- t.Errorf("allowSchemes = %q, want %q", schemes, "ws,wss")
- }
-}
-
-func TestGetConfigValue_UnknownPaths(t *testing.T) {
- fc := &FileConfig{}
- errorCases := []string{
- "port", // missing section
- "", // empty
- "unknown.field", // unknown section
- "server.ghost", // unknown field in known section
- "security.attach.badfield", // unknown attach field
- "security.idpi.badfield", // unknown idpi field
- }
- for _, path := range errorCases {
- t.Run(path, func(t *testing.T) {
- _, err := GetConfigValue(fc, path)
- if err == nil {
- t.Errorf("GetConfigValue(%q) should have returned an error", path)
- }
- })
- }
-}
diff --git a/internal/config/fileio.go b/internal/config/fileio.go
new file mode 100644
index 00000000..ec60dfb1
--- /dev/null
+++ b/internal/config/fileio.go
@@ -0,0 +1,119 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+// LoadFileConfig loads a FileConfig from the default or specified path.
+// Returns the config and the path it was loaded from.
+func LoadFileConfig() (*FileConfig, string, error) {
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return &FileConfig{}, configPath, nil
+ }
+ return nil, configPath, fmt.Errorf("failed to read config file: %w", err)
+ }
+
+ if isLegacyConfig(data) {
+ fc, err := loadLegacyFileConfig(data)
+ return fc, configPath, err
+ }
+
+ defaults := DefaultFileConfig()
+ defaults.ConfigVersion = ""
+ fc := &defaults
+ if err := json.Unmarshal(data, fc); err != nil {
+ return nil, configPath, fmt.Errorf("failed to parse config: %w", err)
+ }
+
+ return fc, configPath, nil
+}
+
+// SaveFileConfig saves a FileConfig to the specified path.
+func SaveFileConfig(fc *FileConfig, path string) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return fmt.Errorf("failed to create config directory: %w", err)
+ }
+
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to serialize config: %w", err)
+ }
+ data = append(data, '\n')
+
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ return fmt.Errorf("failed to write config file: %w", err)
+ }
+
+ return nil
+}
+
+func loadLegacyFileConfig(data []byte) (*FileConfig, error) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ return nil, fmt.Errorf("failed to parse legacy config: %w", err)
+ }
+
+ defaults := DefaultFileConfig()
+ fc := &defaults
+ legacy := convertLegacyConfig(&lc)
+ if legacy.Server.Port != "" {
+ fc.Server.Port = legacy.Server.Port
+ }
+ if legacy.Server.Token != "" {
+ fc.Server.Token = legacy.Server.Token
+ }
+ if legacy.Server.StateDir != "" {
+ fc.Server.StateDir = legacy.Server.StateDir
+ }
+ if legacy.InstanceDefaults.Mode != "" {
+ fc.InstanceDefaults.Mode = legacy.InstanceDefaults.Mode
+ }
+ if legacy.InstanceDefaults.NoRestore != nil {
+ fc.InstanceDefaults.NoRestore = legacy.InstanceDefaults.NoRestore
+ }
+ if legacy.InstanceDefaults.MaxTabs != nil {
+ fc.InstanceDefaults.MaxTabs = legacy.InstanceDefaults.MaxTabs
+ }
+ if legacy.Profiles.BaseDir != "" {
+ fc.Profiles.BaseDir = legacy.Profiles.BaseDir
+ }
+ if legacy.Profiles.DefaultProfile != "" {
+ fc.Profiles.DefaultProfile = legacy.Profiles.DefaultProfile
+ }
+ if legacy.Security.AllowEvaluate != nil {
+ fc.Security.AllowEvaluate = legacy.Security.AllowEvaluate
+ }
+ if legacy.Security.AllowMacro != nil {
+ fc.Security.AllowMacro = legacy.Security.AllowMacro
+ }
+ if legacy.Security.AllowScreencast != nil {
+ fc.Security.AllowScreencast = legacy.Security.AllowScreencast
+ }
+ if legacy.Security.AllowDownload != nil {
+ fc.Security.AllowDownload = legacy.Security.AllowDownload
+ }
+ if legacy.Security.AllowUpload != nil {
+ fc.Security.AllowUpload = legacy.Security.AllowUpload
+ }
+ if legacy.Timeouts.ActionSec != 0 {
+ fc.Timeouts.ActionSec = legacy.Timeouts.ActionSec
+ }
+ if legacy.Timeouts.NavigateSec != 0 {
+ fc.Timeouts.NavigateSec = legacy.Timeouts.NavigateSec
+ }
+ if legacy.MultiInstance.InstancePortStart != nil {
+ fc.MultiInstance.InstancePortStart = legacy.MultiInstance.InstancePortStart
+ }
+ if legacy.MultiInstance.InstancePortEnd != nil {
+ fc.MultiInstance.InstancePortEnd = legacy.MultiInstance.InstancePortEnd
+ }
+
+ return fc, nil
+}
diff --git a/internal/config/fileio_test.go b/internal/config/fileio_test.go
new file mode 100644
index 00000000..5c9ac4f9
--- /dev/null
+++ b/internal/config/fileio_test.go
@@ -0,0 +1,83 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestLoadAndSaveFileConfig(t *testing.T) {
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
+
+ // Load (should return empty config for non-existent file)
+ fc, path, err := LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if path != configPath {
+ t.Errorf("path = %v, want %v", path, configPath)
+ }
+
+ // Modify
+ fc.Server.Port = "8080"
+ fc.InstanceDefaults.StealthLevel = "full"
+
+ // Save
+ if err := SaveFileConfig(fc, path); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ // Load again
+ fc2, _, err := LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() second time error = %v", err)
+ }
+
+ if fc2.Server.Port != "8080" {
+ t.Errorf("loaded port = %v, want 8080", fc2.Server.Port)
+ }
+ if fc2.InstanceDefaults.StealthLevel != "full" {
+ t.Errorf("loaded stealthLevel = %v, want full", fc2.InstanceDefaults.StealthLevel)
+ }
+}
+
+func TestLoadAndSaveFileConfigPreservesExplicitZeroValues(t *testing.T) {
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
+
+ fc := DefaultFileConfig()
+ fc.Server.Bind = ""
+ fc.Server.Token = ""
+ fc.Browser.ExtensionPaths = []string{}
+ fc.InstanceDefaults.UserAgent = ""
+ fc.Security.IDPI.StrictMode = false
+ fc.Security.IDPI.AllowedDomains = []string{}
+ fc.Security.IDPI.CustomPatterns = []string{}
+
+ if err := SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ loaded, _, err := LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+
+ if loaded.Server.Bind != "" {
+ t.Errorf("loaded bind = %q, want empty string", loaded.Server.Bind)
+ }
+ if loaded.Security.IDPI.StrictMode {
+ t.Errorf("loaded strictMode = %v, want false", loaded.Security.IDPI.StrictMode)
+ }
+ if len(loaded.Security.IDPI.AllowedDomains) != 0 {
+ t.Errorf("loaded allowedDomains = %v, want empty list", loaded.Security.IDPI.AllowedDomains)
+ }
+ if len(loaded.Browser.ExtensionPaths) != 0 {
+ t.Errorf("loaded extensionPaths = %v, want empty list", loaded.Browser.ExtensionPaths)
+ }
+}
diff --git a/internal/config/transfer_limits.go b/internal/config/transfer_limits.go
new file mode 100644
index 00000000..1eb879cb
--- /dev/null
+++ b/internal/config/transfer_limits.go
@@ -0,0 +1,59 @@
+package config
+
+const (
+ DefaultDownloadMaxBytes = 20 << 20
+ MaxDownloadMaxBytes = 100 << 20
+ DefaultUploadMaxRequestBytes = 10 << 20
+ MaxUploadMaxRequestBytes = 100 << 20
+ DefaultUploadMaxFiles = 8
+ MaxUploadMaxFiles = 32
+ DefaultUploadMaxFileBytes = 5 << 20
+ MaxUploadMaxFileBytes = 25 << 20
+ DefaultUploadMaxTotalBytes = 10 << 20
+ MaxUploadMaxTotalBytes = 100 << 20
+)
+
+func clampPositiveLimit(value, fallback, max int) int {
+ if value <= 0 {
+ return fallback
+ }
+ if value > max {
+ return max
+ }
+ return value
+}
+
+func (cfg *RuntimeConfig) EffectiveDownloadMaxBytes() int {
+ if cfg == nil {
+ return DefaultDownloadMaxBytes
+ }
+ return clampPositiveLimit(cfg.DownloadMaxBytes, DefaultDownloadMaxBytes, MaxDownloadMaxBytes)
+}
+
+func (cfg *RuntimeConfig) EffectiveUploadMaxRequestBytes() int {
+ if cfg == nil {
+ return DefaultUploadMaxRequestBytes
+ }
+ return clampPositiveLimit(cfg.UploadMaxRequestBytes, DefaultUploadMaxRequestBytes, MaxUploadMaxRequestBytes)
+}
+
+func (cfg *RuntimeConfig) EffectiveUploadMaxFiles() int {
+ if cfg == nil {
+ return DefaultUploadMaxFiles
+ }
+ return clampPositiveLimit(cfg.UploadMaxFiles, DefaultUploadMaxFiles, MaxUploadMaxFiles)
+}
+
+func (cfg *RuntimeConfig) EffectiveUploadMaxFileBytes() int {
+ if cfg == nil {
+ return DefaultUploadMaxFileBytes
+ }
+ return clampPositiveLimit(cfg.UploadMaxFileBytes, DefaultUploadMaxFileBytes, MaxUploadMaxFileBytes)
+}
+
+func (cfg *RuntimeConfig) EffectiveUploadMaxTotalBytes() int {
+ if cfg == nil {
+ return DefaultUploadMaxTotalBytes
+ }
+ return clampPositiveLimit(cfg.UploadMaxTotalBytes, DefaultUploadMaxTotalBytes, MaxUploadMaxTotalBytes)
+}
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 993c6939..c80e4f1f 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -147,6 +147,19 @@ func ValidateFileConfig(fc *FileConfig) []error {
// IDPI validation
errs = append(errs, validateIDPIConfig(fc.Security.IDPI)...)
+ errs = append(errs, validateAllowedDomainList("security.downloadAllowedDomains", fc.Security.DownloadAllowedDomains)...)
+ errs = append(errs, validatePositiveIntLimit("security.downloadMaxBytes", fc.Security.DownloadMaxBytes, MaxDownloadMaxBytes)...)
+ errs = append(errs, validatePositiveIntLimit("security.uploadMaxRequestBytes", fc.Security.UploadMaxRequestBytes, MaxUploadMaxRequestBytes)...)
+ errs = append(errs, validatePositiveIntLimit("security.uploadMaxFiles", fc.Security.UploadMaxFiles, MaxUploadMaxFiles)...)
+ errs = append(errs, validatePositiveIntLimit("security.uploadMaxFileBytes", fc.Security.UploadMaxFileBytes, MaxUploadMaxFileBytes)...)
+ errs = append(errs, validatePositiveIntLimit("security.uploadMaxTotalBytes", fc.Security.UploadMaxTotalBytes, MaxUploadMaxTotalBytes)...)
+ if fc.Security.UploadMaxFileBytes != nil && fc.Security.UploadMaxTotalBytes != nil &&
+ *fc.Security.UploadMaxFileBytes > *fc.Security.UploadMaxTotalBytes {
+ errs = append(errs, ValidationError{
+ Field: "security.uploadMaxFileBytes/uploadMaxTotalBytes",
+ Message: fmt.Sprintf("uploadMaxFileBytes (%d) must be <= uploadMaxTotalBytes (%d)", *fc.Security.UploadMaxFileBytes, *fc.Security.UploadMaxTotalBytes),
+ })
+ }
// Timeouts validation
if fc.Timeouts.ActionSec < 0 {
@@ -290,48 +303,65 @@ func validateIDPIConfig(cfg IDPIConfig) []error {
return nil
}
- var errs []error
+ errs := validateAllowedDomainList("security.idpi.allowedDomains", cfg.AllowedDomains)
+
+ for _, p := range cfg.CustomPatterns {
+ if strings.TrimSpace(p) == "" {
+ errs = append(errs, ValidationError{
+ Field: "security.idpi.customPatterns",
+ Message: "custom pattern must not be empty or whitespace-only",
+ })
+ }
+ }
+
+ if cfg.ScanTimeoutSec < 0 {
+ errs = append(errs, ValidationError{
+ Field: "security.idpi.scanTimeoutSec",
+ Message: "scanTimeoutSec must not be negative",
+ })
+ }
+
+ return errs
+}
- for _, domain := range cfg.AllowedDomains {
+func validateAllowedDomainList(field string, domains []string) []error {
+ var errs []error
+ for _, domain := range domains {
trimmed := strings.TrimSpace(domain)
if trimmed == "" {
errs = append(errs, ValidationError{
- Field: "security.idpi.allowedDomains",
+ Field: field,
Message: "domain pattern must not be empty or whitespace-only",
})
continue
}
if strings.ContainsAny(trimmed, " \t") {
errs = append(errs, ValidationError{
- Field: "security.idpi.allowedDomains",
+ Field: field,
Message: fmt.Sprintf("domain pattern %q must not contain whitespace", trimmed),
})
}
if strings.HasPrefix(trimmed, "file://") {
errs = append(errs, ValidationError{
- Field: "security.idpi.allowedDomains",
+ Field: field,
Message: fmt.Sprintf("domain pattern %q must not use the file:// scheme; use a hostname", trimmed),
})
}
}
+ return errs
+}
- for _, p := range cfg.CustomPatterns {
- if strings.TrimSpace(p) == "" {
- errs = append(errs, ValidationError{
- Field: "security.idpi.customPatterns",
- Message: "custom pattern must not be empty or whitespace-only",
- })
- }
+func validatePositiveIntLimit(field string, value *int, max int) []error {
+ if value == nil {
+ return nil
}
-
- if cfg.ScanTimeoutSec < 0 {
- errs = append(errs, ValidationError{
- Field: "security.idpi.scanTimeoutSec",
- Message: "scanTimeoutSec must not be negative",
- })
+ if *value < 1 || *value > max {
+ return []error{ValidationError{
+ Field: field,
+ Message: fmt.Sprintf("must be between 1 and %d (got %d)", max, *value),
+ }}
}
-
- return errs
+ return nil
}
// ValidAllocationPolicies returns all valid allocation policy values.
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index ab1f6fd3..0ae0613a 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -517,6 +517,106 @@ func TestValidateIDPIConfig_FileSchemeBlocked(t *testing.T) {
}
}
+func TestValidateFileConfig_DownloadAllowedDomains(t *testing.T) {
+ tests := []struct {
+ name string
+ domains []string
+ wantErr bool
+ }{
+ {"empty list", nil, false},
+ {"valid entries", []string{"pinchtab.com", "*.pinchtab.com"}, false},
+ {"whitespace only", []string{" "}, true},
+ {"internal whitespace", []string{"pinchtab .com"}, true},
+ {"file scheme", []string{"file:///tmp/file.txt"}, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ fc := &FileConfig{
+ Security: SecurityConfig{
+ DownloadAllowedDomains: tt.domains,
+ },
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Fatalf("ValidateFileConfig(downloadAllowedDomains=%v) error=%v, want %v (errs: %v)", tt.domains, hasErr, tt.wantErr, errs)
+ }
+ if tt.wantErr && !strings.Contains(errs[0].Error(), "security.downloadAllowedDomains") {
+ t.Fatalf("expected security.downloadAllowedDomains error, got %v", errs[0])
+ }
+ })
+ }
+}
+
+func TestValidateFileConfig_TransferLimits(t *testing.T) {
+ tests := []struct {
+ name string
+ apply func(*SecurityConfig)
+ wantErr string
+ }{
+ {
+ name: "valid limits",
+ apply: func(s *SecurityConfig) {
+ s.DownloadMaxBytes = intPtr(DefaultDownloadMaxBytes)
+ s.UploadMaxRequestBytes = intPtr(DefaultUploadMaxRequestBytes)
+ s.UploadMaxFiles = intPtr(DefaultUploadMaxFiles)
+ s.UploadMaxFileBytes = intPtr(DefaultUploadMaxFileBytes)
+ s.UploadMaxTotalBytes = intPtr(DefaultUploadMaxTotalBytes)
+ },
+ },
+ {
+ name: "download max bytes too large",
+ apply: func(s *SecurityConfig) {
+ s.DownloadMaxBytes = intPtr(MaxDownloadMaxBytes + 1)
+ },
+ wantErr: "security.downloadMaxBytes",
+ },
+ {
+ name: "upload max files invalid",
+ apply: func(s *SecurityConfig) {
+ s.UploadMaxFiles = intPtr(0)
+ },
+ wantErr: "security.uploadMaxFiles",
+ },
+ {
+ name: "upload max file bytes too large",
+ apply: func(s *SecurityConfig) {
+ s.UploadMaxFileBytes = intPtr(MaxUploadMaxFileBytes + 1)
+ },
+ wantErr: "security.uploadMaxFileBytes",
+ },
+ {
+ name: "upload max file bytes exceeds total",
+ apply: func(s *SecurityConfig) {
+ s.UploadMaxFileBytes = intPtr(8 << 20)
+ s.UploadMaxTotalBytes = intPtr(4 << 20)
+ },
+ wantErr: "security.uploadMaxFileBytes/uploadMaxTotalBytes",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ fc := &FileConfig{}
+ tt.apply(&fc.Security)
+ errs := ValidateFileConfig(fc)
+ if tt.wantErr == "" {
+ if len(errs) > 0 {
+ t.Fatalf("expected no errors, got %v", errs)
+ }
+ return
+ }
+ if len(errs) == 0 {
+ t.Fatalf("expected validation error containing %q, got none", tt.wantErr)
+ }
+ if !strings.Contains(errs[0].Error(), tt.wantErr) {
+ t.Fatalf("expected error containing %q, got %v", tt.wantErr, errs[0])
+ }
+ })
+ }
+}
+
// TestValidateIDPIConfig_EmptyCustomPattern verifies that an empty or
// whitespace-only custom pattern is rejected.
func TestValidateIDPIConfig_EmptyCustomPattern(t *testing.T) {
diff --git a/internal/config/workflow/mutate.go b/internal/config/workflow/mutate.go
new file mode 100644
index 00000000..acc17cd3
--- /dev/null
+++ b/internal/config/workflow/mutate.go
@@ -0,0 +1,118 @@
+package workflow
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type PreparedChange struct {
+ FileConfig *config.FileConfig
+ ConfigPath string
+ ValidationErrors []error
+}
+
+func CurrentConfigPath() string {
+ configPath := os.Getenv("PINCHTAB_CONFIG")
+ if configPath == "" {
+ configPath = config.DefaultConfigPath()
+ }
+ return configPath
+}
+
+func GetValue(path string) (string, error) {
+ fc, _, err := config.LoadFileConfig()
+ if err != nil {
+ return "", fmt.Errorf("load config: %w", err)
+ }
+ value, err := config.GetConfigValue(fc, path)
+ if err != nil {
+ return "", err
+ }
+ return value, nil
+}
+
+func PrepareSetValue(path, value string) (*PreparedChange, error) {
+ return prepareChange(func(fc *config.FileConfig) error {
+ return config.SetConfigValue(fc, path, value)
+ })
+}
+
+func PreparePatch(jsonPatch string) (*PreparedChange, error) {
+ return prepareChange(func(fc *config.FileConfig) error {
+ return config.PatchConfigJSON(fc, jsonPatch)
+ })
+}
+
+func SavePreparedChange(change *PreparedChange) error {
+ if change == nil || change.FileConfig == nil {
+ return fmt.Errorf("prepared change is empty")
+ }
+ if err := config.SaveFileConfig(change.FileConfig, change.ConfigPath); err != nil {
+ return fmt.Errorf("save config: %w", err)
+ }
+ return nil
+}
+
+func ValidateCurrentFile() (string, []error, error) {
+ configPath := CurrentConfigPath()
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ return configPath, nil, fmt.Errorf("read config file: %w", err)
+ }
+
+ fc := &config.FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ return configPath, nil, fmt.Errorf("parse config: %w", err)
+ }
+
+ return configPath, config.ValidateFileConfig(fc), nil
+}
+
+func UpdateValue(path, value string) (*config.RuntimeConfig, bool, error) {
+ change, err := PrepareSetValue(path, value)
+ if err != nil {
+ return nil, false, fmt.Errorf("set %s: %w", path, err)
+ }
+ if len(change.ValidationErrors) > 0 {
+ return nil, false, change.ValidationErrors[0]
+ }
+ if err := SavePreparedChange(change); err != nil {
+ return nil, false, err
+ }
+ return config.Load(), true, nil
+}
+
+func InitDefaultConfig(path string) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return fmt.Errorf("create config directory: %w", err)
+ }
+
+ fc := config.DefaultFileConfig()
+ if _, err := config.EnsureFileToken(&fc); err != nil {
+ return fmt.Errorf("generate auth token: %w", err)
+ }
+
+ if err := config.SaveFileConfig(&fc, path); err != nil {
+ return fmt.Errorf("write config: %w", err)
+ }
+ return nil
+}
+
+func prepareChange(mutate func(*config.FileConfig) error) (*PreparedChange, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return nil, fmt.Errorf("load config: %w", err)
+ }
+ if err := mutate(fc); err != nil {
+ return nil, err
+ }
+ return &PreparedChange{
+ FileConfig: fc,
+ ConfigPath: configPath,
+ ValidationErrors: config.ValidateFileConfig(fc),
+ }, nil
+}
diff --git a/internal/config/workflow/security.go b/internal/config/workflow/security.go
new file mode 100644
index 00000000..48196641
--- /dev/null
+++ b/internal/config/workflow/security.go
@@ -0,0 +1,257 @@
+package workflow
+
+import (
+ "encoding/json"
+ "fmt"
+ "reflect"
+ "slices"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func ApplyRecommendedSecurityDefaults(fc *config.FileConfig) {
+ defaults := config.DefaultFileConfig()
+ if fc == nil {
+ return
+ }
+ fc.Server.Bind = defaults.Server.Bind
+ fc.Security = defaults.Security
+ _, _ = config.EnsureFileToken(fc)
+}
+
+func RestoreSecurityDefaults() (string, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return "", false, err
+ }
+ before := securityDefaultsSnapshot(fc)
+ ApplyRecommendedSecurityDefaults(fc)
+ after := securityDefaultsSnapshot(fc)
+ if reflect.DeepEqual(before, after) {
+ return configPath, false, nil
+ }
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return "", false, err
+ }
+ return configPath, true, nil
+}
+
+func UpdateSensitiveEndpoints(value string) (*config.RuntimeConfig, bool, error) {
+ change, err := prepareChange(func(fc *config.FileConfig) error {
+ selected := map[string]bool{}
+ for _, item := range splitCommaList(value) {
+ selected[item] = true
+ }
+ for endpoint, path := range map[string]string{
+ "evaluate": "security.allowEvaluate",
+ "macro": "security.allowMacro",
+ "screencast": "security.allowScreencast",
+ "download": "security.allowDownload",
+ "upload": "security.allowUpload",
+ } {
+ if err := config.SetConfigValue(fc, path, fmt.Sprintf("%t", selected[endpoint])); err != nil {
+ return fmt.Errorf("set %s: %w", endpoint, err)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, false, err
+ }
+ if len(change.ValidationErrors) > 0 {
+ return nil, false, change.ValidationErrors[0]
+ }
+ if err := SavePreparedChange(change); err != nil {
+ return nil, false, err
+ }
+ return config.Load(), true, nil
+}
+
+func UpdateContentGuard(mode string) (*config.RuntimeConfig, bool, error) {
+ change, err := prepareChange(func(fc *config.FileConfig) error {
+ scan := mode == "both" || mode == "scan"
+ wrap := mode == "both" || mode == "wrap"
+ for _, item := range []struct {
+ path string
+ value bool
+ }{
+ {path: "security.idpi.scanContent", value: scan},
+ {path: "security.idpi.wrapContent", value: wrap},
+ } {
+ if err := config.SetConfigValue(fc, item.path, fmt.Sprintf("%t", item.value)); err != nil {
+ return fmt.Errorf("set %s: %w", item.path, err)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, false, err
+ }
+ if len(change.ValidationErrors) > 0 {
+ return nil, false, change.ValidationErrors[0]
+ }
+ if err := SavePreparedChange(change); err != nil {
+ return nil, false, err
+ }
+ 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)
+ }
+ originalJSON, err := formatFileConfigJSON(fc)
+ if err != nil {
+ return nil, "", false, err
+ }
+
+ original, err := config.GetConfigValue(fc, "server.token")
+ if err != nil {
+ return nil, "", 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)
+ }
+ if err := config.SetConfigValue(fc, "server.token", token); err != nil {
+ return nil, "", false, fmt.Errorf("set server.token: %w", err)
+ }
+ }
+
+ for _, item := range []struct {
+ path string
+ value string
+ }{
+ {path: "server.bind", value: "127.0.0.1"},
+ {path: "security.allowEvaluate", value: "true"},
+ {path: "security.allowMacro", value: "true"},
+ {path: "security.allowScreencast", value: "true"},
+ {path: "security.allowDownload", value: "true"},
+ {path: "security.allowUpload", value: "true"},
+ {path: "security.attach.enabled", value: "true"},
+ {path: "security.attach.allowHosts", value: "127.0.0.1,localhost,::1"},
+ {path: "security.attach.allowSchemes", value: "ws,wss"},
+ {path: "security.idpi.enabled", value: "false"},
+ {path: "security.idpi.strictMode", value: "false"},
+ {path: "security.idpi.scanContent", value: "false"},
+ {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)
+ }
+ }
+
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ return nil, "", false, errs[0]
+ }
+
+ nextJSON, err := formatFileConfigJSON(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)
+ }
+ return config.Load(), configPath, true, nil
+}
+
+func formatFileConfigJSON(fc *config.FileConfig) (string, error) {
+ data, err := json.Marshal(fc)
+ if err != nil {
+ return "", fmt.Errorf("marshal config: %w", err)
+ }
+ return string(data), nil
+}
+
+func splitCommaList(value string) []string {
+ parts := strings.Split(value, ",")
+ items := make([]string, 0, len(parts))
+ for _, part := range parts {
+ trimmed := strings.TrimSpace(strings.ToLower(part))
+ if trimmed != "" {
+ items = append(items, trimmed)
+ }
+ }
+ slices.Sort(items)
+ return slices.Compact(items)
+}
+
+type securityDefaultsState struct {
+ Bind string
+ Token string
+ Security securityConfigValues
+}
+
+type securityConfigValues struct {
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ DownloadMaxBytes int
+ AllowUpload bool
+ UploadMaxRequestBytes int
+ UploadMaxFiles int
+ UploadMaxFileBytes int
+ UploadMaxTotalBytes int
+ MaxRedirects int
+ AttachEnabled bool
+ IDPI config.IDPIConfig
+}
+
+func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
+ if fc == nil {
+ return securityDefaultsState{}
+ }
+ s := securityDefaultsState{
+ Bind: fc.Server.Bind,
+ Token: fc.Server.Token,
+ Security: securityConfigValues{
+ IDPI: fc.Security.IDPI,
+ },
+ }
+ if fc.Security.AllowEvaluate != nil {
+ s.Security.AllowEvaluate = *fc.Security.AllowEvaluate
+ }
+ if fc.Security.AllowMacro != nil {
+ s.Security.AllowMacro = *fc.Security.AllowMacro
+ }
+ if fc.Security.AllowScreencast != nil {
+ s.Security.AllowScreencast = *fc.Security.AllowScreencast
+ }
+ if fc.Security.AllowDownload != nil {
+ s.Security.AllowDownload = *fc.Security.AllowDownload
+ }
+ if fc.Security.DownloadMaxBytes != nil {
+ s.Security.DownloadMaxBytes = *fc.Security.DownloadMaxBytes
+ }
+ if fc.Security.AllowUpload != nil {
+ s.Security.AllowUpload = *fc.Security.AllowUpload
+ }
+ if fc.Security.UploadMaxRequestBytes != nil {
+ s.Security.UploadMaxRequestBytes = *fc.Security.UploadMaxRequestBytes
+ }
+ if fc.Security.UploadMaxFiles != nil {
+ s.Security.UploadMaxFiles = *fc.Security.UploadMaxFiles
+ }
+ if fc.Security.UploadMaxFileBytes != nil {
+ s.Security.UploadMaxFileBytes = *fc.Security.UploadMaxFileBytes
+ }
+ if fc.Security.UploadMaxTotalBytes != nil {
+ s.Security.UploadMaxTotalBytes = *fc.Security.UploadMaxTotalBytes
+ }
+ if fc.Security.MaxRedirects != nil {
+ s.Security.MaxRedirects = *fc.Security.MaxRedirects
+ }
+ if fc.Security.Attach.Enabled != nil {
+ s.Security.AttachEnabled = *fc.Security.Attach.Enabled
+ }
+ return s
+}
diff --git a/internal/config/workflow/security_test.go b/internal/config/workflow/security_test.go
new file mode 100644
index 00000000..5070fef5
--- /dev/null
+++ b/internal/config/workflow/security_test.go
@@ -0,0 +1,57 @@
+package workflow
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestApplyGuardsDownPreset(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "guarded-token"
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
+ t.Fatalf("MkdirAll() error = %v", err)
+ }
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ cfg, gotPath, changed, err := ApplyGuardsDownPreset()
+ if err != nil {
+ t.Fatalf("ApplyGuardsDownPreset() error = %v", err)
+ }
+ if !changed {
+ t.Fatal("expected guards down preset to change config")
+ }
+ if gotPath != configPath {
+ t.Fatalf("config path = %q, want %q", gotPath, configPath)
+ }
+
+ if cfg.Bind != "127.0.0.1" {
+ t.Fatalf("Bind = %q, want 127.0.0.1", cfg.Bind)
+ }
+ if cfg.Token != "guarded-token" {
+ t.Fatalf("Token = %q, want existing token to remain", cfg.Token)
+ }
+ if !cfg.AllowEvaluate || !cfg.AllowMacro || !cfg.AllowScreencast || !cfg.AllowDownload || !cfg.AllowUpload {
+ t.Fatalf("expected sensitive endpoints enabled, got %+v", cfg)
+ }
+ if !cfg.AttachEnabled {
+ t.Fatal("expected attach endpoint enabled")
+ }
+ if got := strings.Join(cfg.AttachAllowHosts, ","); got != "127.0.0.1,localhost,::1" {
+ t.Fatalf("AttachAllowHosts = %q", got)
+ }
+ if got := strings.Join(cfg.AttachAllowSchemes, ","); got != "ws,wss" {
+ t.Fatalf("AttachAllowSchemes = %q", got)
+ }
+ if cfg.IDPI.Enabled || cfg.IDPI.StrictMode || cfg.IDPI.ScanContent || cfg.IDPI.WrapContent {
+ t.Fatalf("expected IDPI protections disabled, got %+v", cfg.IDPI)
+ }
+}
diff --git a/internal/daemon/bootstrap.go b/internal/daemon/bootstrap.go
new file mode 100644
index 00000000..d59db7c3
--- /dev/null
+++ b/internal/daemon/bootstrap.go
@@ -0,0 +1,64 @@
+package daemon
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type ConfigBootstrapStatus string
+
+const (
+ ConfigCreated ConfigBootstrapStatus = "created"
+ ConfigRecovered ConfigBootstrapStatus = "recovered"
+ ConfigVerified ConfigBootstrapStatus = "verified"
+)
+
+func EnsureConfig(force bool) (string, *config.FileConfig, ConfigBootstrapStatus, error) {
+ _, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return "", nil, "", err
+ }
+
+ exists := fileExists(configPath)
+ if !exists || force {
+ defaults := config.DefaultFileConfig()
+ defaults.ConfigVersion = ""
+ token, err := config.GenerateAuthToken()
+ if err != nil {
+ return "", nil, "", err
+ }
+ defaults.Server.Token = token
+ if err := config.SaveFileConfig(&defaults, configPath); err != nil {
+ return "", nil, "", err
+ }
+ status := ConfigCreated
+ if exists {
+ status = ConfigRecovered
+ }
+ return configPath, &defaults, status, nil
+ }
+
+ fileCfg, _, _ := config.LoadFileConfig()
+ if fileCfg == nil {
+ return configPath, nil, "", fmt.Errorf("failed to load existing config at %s", configPath)
+ }
+
+ if strings.TrimSpace(fileCfg.Server.Token) == "" {
+ token, err := config.GenerateAuthToken()
+ if err == nil {
+ fileCfg.Server.Token = token
+ _ = config.SaveFileConfig(fileCfg, configPath)
+ return configPath, fileCfg, ConfigRecovered, nil
+ }
+ }
+
+ return configPath, fileCfg, ConfigVerified, nil
+}
+
+func fileExists(path string) bool {
+ _, err := os.Stat(path)
+ return err == nil
+}
diff --git a/internal/daemon/bootstrap_test.go b/internal/daemon/bootstrap_test.go
new file mode 100644
index 00000000..3bab7c63
--- /dev/null
+++ b/internal/daemon/bootstrap_test.go
@@ -0,0 +1,91 @@
+package daemon
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestEnsureConfigCreatesDefaultConfig(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+ t.Setenv("PINCHTAB_BIND", "")
+
+ gotPath, cfg, status, err := EnsureConfig(false)
+ if err != nil {
+ t.Fatalf("EnsureConfig returned error: %v", err)
+ }
+ if status != ConfigCreated {
+ t.Fatalf("status = %q, want %q", status, ConfigCreated)
+ }
+ if gotPath != configPath {
+ t.Fatalf("config path = %q, want %q", gotPath, configPath)
+ }
+ if cfg.Server.Bind != "127.0.0.1" {
+ t.Fatalf("bind = %q, want 127.0.0.1", cfg.Server.Bind)
+ }
+ if strings.TrimSpace(cfg.Server.Token) == "" {
+ t.Fatal("expected generated token to be set")
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("reading config file: %v", err)
+ }
+ content := string(data)
+ if !strings.Contains(content, `"bind": "127.0.0.1"`) {
+ t.Fatalf("expected config file to include bind, got %s", content)
+ }
+ if !strings.Contains(content, `"token": "`) {
+ t.Fatalf("expected config file to include token, got %s", content)
+ }
+}
+
+func TestEnsureConfigRecoversExistingSecuritySettings(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ input := `{
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9999",
+ "token": ""
+ },
+ "browser": {
+ "binary": "/custom/chrome"
+ },
+ "security": {
+ "allowEvaluate": true
+ }
+}
+`
+ if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ t.Fatalf("creating config dir: %v", err)
+ }
+ if err := os.WriteFile(configPath, []byte(input), 0644); err != nil {
+ t.Fatalf("writing config file: %v", err)
+ }
+
+ _, cfg, status, err := EnsureConfig(false)
+ if err != nil {
+ t.Fatalf("EnsureConfig returned error: %v", err)
+ }
+ if status != ConfigRecovered {
+ t.Fatalf("status = %q, want %q", status, ConfigRecovered)
+ }
+ if cfg.Server.Bind != "0.0.0.0" {
+ t.Fatalf("bind = %q, want 0.0.0.0 (preserved)", cfg.Server.Bind)
+ }
+ if cfg.Server.Port != "9999" {
+ t.Fatalf("port = %q, want 9999", cfg.Server.Port)
+ }
+ if cfg.Browser.ChromeBinary != "/custom/chrome" {
+ t.Fatalf("chrome binary = %q, want /custom/chrome", cfg.Browser.ChromeBinary)
+ }
+ if cfg.Security.AllowEvaluate == nil || !*cfg.Security.AllowEvaluate {
+ t.Fatal("expected allowEvaluate to be preserved as true")
+ }
+ if strings.TrimSpace(cfg.Server.Token) == "" {
+ t.Fatal("expected recovery to generate a token")
+ }
+}
diff --git a/internal/daemon/launchd.go b/internal/daemon/launchd.go
new file mode 100644
index 00000000..d56f3571
--- /dev/null
+++ b/internal/daemon/launchd.go
@@ -0,0 +1,177 @@
+package daemon
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+type launchdManager struct {
+ env environment
+ runner commandRunner
+}
+
+func (m *launchdManager) ServicePath() string {
+ return filepath.Join(m.env.homeDir, "Library", "LaunchAgents", pinchtabLaunchdLabel+".plist")
+}
+
+func (m *launchdManager) Preflight() error {
+ if strings.TrimSpace(m.env.userID) == "" {
+ return fmt.Errorf("macOS daemon install requires a logged-in user session with a launchd GUI domain")
+ }
+ if _, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)); err != nil {
+ return fmt.Errorf("macOS daemon install requires an active launchd GUI session: %w", err)
+ }
+ return nil
+}
+
+func (m *launchdManager) Install(configPath string) (string, error) {
+ if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
+ return "", fmt.Errorf("create LaunchAgents directory: %w", err)
+ }
+ if err := os.WriteFile(m.ServicePath(), []byte(renderLaunchdPlist(m.env.execPath, configPath)), 0644); err != nil {
+ return "", fmt.Errorf("write launchd plist: %w", err)
+ }
+ _, _ = runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
+ if _, err := runCommand(m.runner, "launchctl", "bootstrap", launchdDomainTarget(m.env), m.ServicePath()); err != nil {
+ return "", err
+ }
+ if _, err := runCommand(m.runner, "launchctl", "kickstart", "-k", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("Installed launchd agent at %s", m.ServicePath()), nil
+}
+
+func (m *launchdManager) Start() (string, error) {
+ if _, err := runCommand(m.runner, "launchctl", "bootstrap", launchdDomainTarget(m.env), m.ServicePath()); err != nil && !strings.Contains(err.Error(), "already bootstrapped") {
+ return "", err
+ }
+ if _, err := runCommand(m.runner, "launchctl", "kickstart", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon started.", nil
+}
+
+func (m *launchdManager) Restart() (string, error) {
+ if _, err := runCommand(m.runner, "launchctl", "kickstart", "-k", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon restarted.", nil
+}
+
+func (m *launchdManager) Stop() (string, error) {
+ _, err := runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
+ if err != nil && !isLaunchdIgnorableError(err) {
+ return "", err
+ }
+ return "Pinchtab daemon stopped.", nil
+}
+
+func (m *launchdManager) Status() (string, error) {
+ output, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel)
+ if err != nil {
+ return "", err
+ }
+ if strings.TrimSpace(output) == "" {
+ return "Pinchtab daemon status returned no output.", nil
+ }
+ return output, nil
+}
+
+func (m *launchdManager) Uninstall() (string, error) {
+ var errs []error
+ _, err := runCommand(m.runner, "launchctl", "bootout", launchdDomainTarget(m.env), m.ServicePath())
+ if err != nil && !isLaunchdIgnorableError(err) {
+ errs = append(errs, err)
+ }
+ if err := os.Remove(m.ServicePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
+ errs = append(errs, fmt.Errorf("remove launchd plist: %w", err))
+ }
+ if len(errs) > 0 {
+ return "", errors.Join(errs...)
+ }
+ return "Pinchtab daemon uninstalled.", nil
+}
+
+func (m *launchdManager) Pid() (string, error) {
+ output, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)+"/"+pinchtabLaunchdLabel)
+ if err != nil {
+ return "", err
+ }
+ lines := strings.Split(output, "\n")
+ for _, line := range lines {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "pid = ") {
+ return strings.TrimPrefix(trimmed, "pid = "), nil
+ }
+ }
+ return "", nil
+}
+
+func (m *launchdManager) Logs(n int) (string, error) {
+ logPath := "/tmp/pinchtab.err.log"
+ if _, err := os.Stat(logPath); err != nil {
+ return "No logs found at " + logPath, nil
+ }
+ return runCommand(m.runner, "tail", "-n", fmt.Sprintf("%d", n), logPath)
+}
+
+func (m *launchdManager) ManualInstructions() string {
+ path := m.ServicePath()
+ target := launchdDomainTarget(m.env)
+ var b strings.Builder
+ fmt.Fprintln(&b, "Manual instructions (macOS/launchd):")
+ fmt.Fprintln(&b, "To install manually:")
+ fmt.Fprintf(&b, " 1. Create %s\n", path)
+ fmt.Fprintf(&b, " 2. Run: launchctl bootstrap %s %s\n", target, path)
+ fmt.Fprintln(&b)
+ fmt.Fprintln(&b, "To uninstall manually:")
+ fmt.Fprintf(&b, " 1. Run: launchctl bootout %s %s\n", target, path)
+ fmt.Fprintf(&b, " 2. Remove: %s\n", path)
+ return b.String()
+}
+
+func isLaunchdIgnorableError(err error) bool {
+ if err == nil {
+ return true
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "exit status 5") ||
+ strings.Contains(msg, "No such process") ||
+ strings.Contains(msg, "not found") ||
+ strings.Contains(msg, "already bootstrapped")
+}
+
+func renderLaunchdPlist(execPath, configPath string) string {
+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>%s</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>%s</string>
+ <string>server</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>ExitTimeOut</key>
+ <integer>10</integer>
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PINCHTAB_CONFIG</key>
+ <string>%s</string>
+ </dict>
+ <key>StandardOutPath</key>
+ <string>/tmp/pinchtab.out.log</string>
+ <key>StandardErrorPath</key>
+ <string>/tmp/pinchtab.err.log</string>
+</dict>
+</plist>
+`, pinchtabLaunchdLabel, execPath, configPath)
+}
diff --git a/internal/daemon/launchd_test.go b/internal/daemon/launchd_test.go
new file mode 100644
index 00000000..46f6efaf
--- /dev/null
+++ b/internal/daemon/launchd_test.go
@@ -0,0 +1,74 @@
+package daemon
+
+import (
+ "errors"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestLaunchdManagerInstallWritesPlistAndBootstrapsAgent(t *testing.T) {
+ root := t.TempDir()
+ runner := &fakeCommandRunner{}
+ manager := &launchdManager{
+ env: environment{
+ homeDir: root,
+ osName: "darwin",
+ execPath: "/Applications/Pinchtab.app/Contents/MacOS/pinchtab",
+ userID: "501",
+ },
+ runner: runner,
+ }
+
+ message, err := manager.Install("/tmp/pinchtab/config.json")
+ if err != nil {
+ t.Fatalf("Install returned error: %v", err)
+ }
+ if !strings.Contains(message, manager.ServicePath()) {
+ t.Fatalf("install message = %q, want path %q", message, manager.ServicePath())
+ }
+
+ data, err := os.ReadFile(manager.ServicePath())
+ if err != nil {
+ t.Fatalf("reading launchd plist: %v", err)
+ }
+ content := string(data)
+ if !strings.Contains(content, "<string>com.pinchtab.pinchtab</string>") {
+ t.Fatalf("expected launchd label in plist: %s", content)
+ }
+ if !strings.Contains(content, "<string>/Applications/Pinchtab.app/Contents/MacOS/pinchtab</string>") {
+ t.Fatalf("expected executable path in plist: %s", content)
+ }
+ if !strings.Contains(content, "<string>/tmp/pinchtab/config.json</string>") {
+ t.Fatalf("expected config path in plist: %s", content)
+ }
+
+ expectedCalls := []string{
+ "launchctl bootout gui/501 " + manager.ServicePath(),
+ "launchctl bootstrap gui/501 " + manager.ServicePath(),
+ "launchctl kickstart -k gui/501/com.pinchtab.pinchtab",
+ }
+ if strings.Join(runner.calls, "\n") != strings.Join(expectedCalls, "\n") {
+ t.Fatalf("launchctl calls = %v, want %v", runner.calls, expectedCalls)
+ }
+}
+
+func TestLaunchdManagerPreflightRequiresGUIDomain(t *testing.T) {
+ runner := &fakeCommandRunner{
+ errors: map[string]error{
+ "launchctl print gui/501": errors.New("exit status 113"),
+ },
+ }
+ manager := &launchdManager{
+ env: environment{osName: "darwin", userID: "501"},
+ runner: runner,
+ }
+
+ err := manager.Preflight()
+ if err == nil {
+ t.Fatal("expected preflight error")
+ }
+ if !strings.Contains(err.Error(), "active launchd GUI session") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
diff --git a/internal/daemon/manager.go b/internal/daemon/manager.go
new file mode 100644
index 00000000..ed340ffd
--- /dev/null
+++ b/internal/daemon/manager.go
@@ -0,0 +1,139 @@
+package daemon
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "os/user"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+const (
+ pinchtabDaemonUnitName = "pinchtab.service"
+ pinchtabLaunchdLabel = "com.pinchtab.pinchtab"
+)
+
+type Manager interface {
+ Preflight() error
+ Install(configPath string) (string, error)
+ ServicePath() string
+ Start() (string, error)
+ Restart() (string, error)
+ Status() (string, error)
+ Stop() (string, error)
+ Uninstall() (string, error)
+ ManualInstructions() string
+ Pid() (string, error)
+ Logs(n int) (string, error)
+}
+
+type commandRunner interface {
+ CombinedOutput(name string, arg ...string) ([]byte, error)
+}
+
+type osCommandRunner struct{}
+
+func (r osCommandRunner) CombinedOutput(name string, arg ...string) ([]byte, error) {
+ return exec.Command(name, arg...).CombinedOutput() // #nosec G204 -- args are daemon manager controlled, not user input
+}
+
+type environment struct {
+ execPath string
+ homeDir string
+ osName string
+ userID string
+ xdgConfigHome string
+}
+
+func CurrentManager() (Manager, error) {
+ env, err := currentEnvironment()
+ if err != nil {
+ return nil, err
+ }
+ return newManager(env, osCommandRunner{})
+}
+
+func IsInstalled() bool {
+ manager, err := CurrentManager()
+ if err != nil {
+ return false
+ }
+ _, err = os.Stat(manager.ServicePath())
+ return err == nil
+}
+
+func IsRunning() bool {
+ manager, err := CurrentManager()
+ if err != nil {
+ return false
+ }
+ status, err := manager.Status()
+ if err != nil {
+ return false
+ }
+ return StatusLooksRunning(status)
+}
+
+func StatusLooksRunning(status string) bool {
+ return strings.Contains(status, "state = running") ||
+ strings.Contains(status, "Active: active (running)")
+}
+
+func currentEnvironment() (environment, error) {
+ execPath, err := os.Executable()
+ if err != nil {
+ return environment{}, fmt.Errorf("resolve executable path: %w", err)
+ }
+ homeDir, err := os.UserHomeDir()
+ if err != nil {
+ return environment{}, fmt.Errorf("resolve home directory: %w", err)
+ }
+ currentUser, err := user.Current()
+ if err != nil {
+ return environment{}, fmt.Errorf("resolve current user: %w", err)
+ }
+
+ return environment{
+ execPath: execPath,
+ homeDir: homeDir,
+ osName: runtime.GOOS,
+ userID: currentUser.Uid,
+ xdgConfigHome: os.Getenv("XDG_CONFIG_HOME"),
+ }, nil
+}
+
+func newManager(env environment, runner commandRunner) (Manager, error) {
+ switch env.osName {
+ case "linux":
+ return &systemdUserManager{env: env, runner: runner}, nil
+ case "darwin":
+ return &launchdManager{env: env, runner: runner}, nil
+ default:
+ return nil, fmt.Errorf("pinchtab daemon is supported on macOS and Linux; current OS is %s", env.osName)
+ }
+}
+
+func runCommand(runner commandRunner, name string, args ...string) (string, error) {
+ output, err := runner.CombinedOutput(name, args...)
+ trimmed := strings.TrimSpace(string(output))
+ if err == nil {
+ return trimmed, nil
+ }
+ if trimmed == "" {
+ return "", fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
+ }
+ return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, trimmed)
+}
+
+func launchdDomainTarget(env environment) string {
+ return "gui/" + env.userID
+}
+
+func systemdUserConfigHome(env environment) string {
+ if strings.TrimSpace(env.xdgConfigHome) != "" {
+ return env.xdgConfigHome
+ }
+ return filepath.Join(env.homeDir, ".config")
+}
diff --git a/internal/cli/report/daemon_status_test.go b/internal/daemon/manager_test.go
similarity index 53%
rename from internal/cli/report/daemon_status_test.go
rename to internal/daemon/manager_test.go
index 87dafcec..83e4515f 100644
--- a/internal/cli/report/daemon_status_test.go
+++ b/internal/daemon/manager_test.go
@@ -1,8 +1,15 @@
-package report
+package daemon
import "testing"
-func TestDaemonStatusLooksRunning(t *testing.T) {
+func TestNewManagerRejectsUnsupportedOS(t *testing.T) {
+ _, err := newManager(environment{osName: "windows"}, &fakeCommandRunner{})
+ if err == nil {
+ t.Fatal("expected unsupported OS error")
+ }
+}
+
+func TestStatusLooksRunning(t *testing.T) {
tests := []struct {
name string
status string
@@ -27,8 +34,8 @@ func TestDaemonStatusLooksRunning(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := daemonStatusLooksRunning(tt.status); got != tt.want {
- t.Fatalf("daemonStatusLooksRunning(%q) = %v, want %v", tt.status, got, tt.want)
+ if got := StatusLooksRunning(tt.status); got != tt.want {
+ t.Fatalf("StatusLooksRunning(%q) = %v, want %v", tt.status, got, tt.want)
}
})
}
diff --git a/internal/daemon/systemd.go b/internal/daemon/systemd.go
new file mode 100644
index 00000000..f917e2a4
--- /dev/null
+++ b/internal/daemon/systemd.go
@@ -0,0 +1,142 @@
+package daemon
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+type systemdUserManager struct {
+ env environment
+ runner commandRunner
+}
+
+func (m *systemdUserManager) ServicePath() string {
+ return filepath.Join(systemdUserConfigHome(m.env), "systemd", "user", pinchtabDaemonUnitName)
+}
+
+func (m *systemdUserManager) Preflight() error {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "show-environment"); err != nil {
+ return fmt.Errorf("linux daemon install requires a working user systemd session (`systemctl --user`): %w", err)
+ }
+ return nil
+}
+
+func (m *systemdUserManager) Install(configPath string) (string, error) {
+ if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
+ return "", fmt.Errorf("create systemd user directory: %w", err)
+ }
+ if err := os.WriteFile(m.ServicePath(), []byte(renderSystemdUnit(m.env.execPath, configPath)), 0644); err != nil {
+ return "", fmt.Errorf("write systemd unit: %w", err)
+ }
+ if _, err := runCommand(m.runner, "systemctl", "--user", "daemon-reload"); err != nil {
+ return "", err
+ }
+ if _, err := runCommand(m.runner, "systemctl", "--user", "enable", "--now", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("Installed systemd user service at %s", m.ServicePath()), nil
+}
+
+func (m *systemdUserManager) Start() (string, error) {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "start", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon started.", nil
+}
+
+func (m *systemdUserManager) Restart() (string, error) {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "restart", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon restarted.", nil
+}
+
+func (m *systemdUserManager) Stop() (string, error) {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "stop", pinchtabDaemonUnitName); err != nil {
+ return "", err
+ }
+ return "Pinchtab daemon stopped.", nil
+}
+
+func (m *systemdUserManager) Status() (string, error) {
+ output, err := runCommand(m.runner, "systemctl", "--user", "status", pinchtabDaemonUnitName, "--no-pager")
+ if err != nil {
+ return "", err
+ }
+ if strings.TrimSpace(output) == "" {
+ return "Pinchtab daemon status returned no output.", nil
+ }
+ return output, nil
+}
+
+func (m *systemdUserManager) Uninstall() (string, error) {
+ var errs []error
+ if _, err := runCommand(m.runner, "systemctl", "--user", "disable", "--now", pinchtabDaemonUnitName); err != nil {
+ errs = append(errs, err)
+ }
+ if err := os.Remove(m.ServicePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
+ errs = append(errs, fmt.Errorf("remove unit file: %w", err))
+ }
+ if _, err := runCommand(m.runner, "systemctl", "--user", "daemon-reload"); err != nil {
+ errs = append(errs, err)
+ }
+ if len(errs) > 0 {
+ return "", errors.Join(errs...)
+ }
+ return "Pinchtab daemon uninstalled.", nil
+}
+
+func (m *systemdUserManager) Pid() (string, error) {
+ output, err := runCommand(m.runner, "systemctl", "--user", "show", pinchtabDaemonUnitName, "--property", "MainPID")
+ if err != nil {
+ return "", err
+ }
+ if parts := strings.Split(output, "="); len(parts) == 2 {
+ pid := strings.TrimSpace(parts[1])
+ if pid == "0" {
+ return "", nil
+ }
+ return pid, nil
+ }
+ return "", nil
+}
+
+func (m *systemdUserManager) Logs(n int) (string, error) {
+ return runCommand(m.runner, "journalctl", "--user", "-u", pinchtabDaemonUnitName, "-n", fmt.Sprintf("%d", n), "--no-pager")
+}
+
+func (m *systemdUserManager) ManualInstructions() string {
+ path := m.ServicePath()
+ var b strings.Builder
+ fmt.Fprintln(&b, "Manual instructions (Linux/systemd):")
+ fmt.Fprintln(&b, "To install manually:")
+ fmt.Fprintf(&b, " 1. Create %s\n", path)
+ fmt.Fprintln(&b, " 2. Run: systemctl --user daemon-reload")
+ fmt.Fprintln(&b, " 3. Run: systemctl --user enable --now pinchtab.service")
+ fmt.Fprintln(&b)
+ fmt.Fprintln(&b, "To uninstall manually:")
+ fmt.Fprintln(&b, " 1. Run: systemctl --user disable --now pinchtab.service")
+ fmt.Fprintf(&b, " 2. Remove: %s\n", path)
+ fmt.Fprintln(&b, " 3. Run: systemctl --user daemon-reload")
+ return b.String()
+}
+
+func renderSystemdUnit(execPath, configPath string) string {
+ return fmt.Sprintf(`[Unit]
+Description=Pinchtab Browser Service
+After=network.target
+
+[Service]
+Type=simple
+ExecStart="%s" server
+Environment="PINCHTAB_CONFIG=%s"
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=default.target
+`, execPath, configPath)
+}
diff --git a/internal/daemon/systemd_test.go b/internal/daemon/systemd_test.go
new file mode 100644
index 00000000..0d8fdf6b
--- /dev/null
+++ b/internal/daemon/systemd_test.go
@@ -0,0 +1,71 @@
+package daemon
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestSystemdUserManagerInstallWritesUnitAndEnablesService(t *testing.T) {
+ root := t.TempDir()
+ runner := &fakeCommandRunner{}
+ manager := &systemdUserManager{
+ env: environment{
+ homeDir: root,
+ osName: "linux",
+ execPath: "/usr/local/bin/pinchtab",
+ xdgConfigHome: filepath.Join(root, ".config"),
+ },
+ runner: runner,
+ }
+
+ message, err := manager.Install("/tmp/pinchtab/config.json")
+ if err != nil {
+ t.Fatalf("Install returned error: %v", err)
+ }
+ if !strings.Contains(message, manager.ServicePath()) {
+ t.Fatalf("install message = %q, want path %q", message, manager.ServicePath())
+ }
+
+ data, err := os.ReadFile(manager.ServicePath())
+ if err != nil {
+ t.Fatalf("reading service file: %v", err)
+ }
+ content := string(data)
+ if !strings.Contains(content, `ExecStart="/usr/local/bin/pinchtab" server`) {
+ t.Fatalf("unexpected unit content: %s", content)
+ }
+ if !strings.Contains(content, `Environment="PINCHTAB_CONFIG=/tmp/pinchtab/config.json"`) {
+ t.Fatalf("expected config env in unit content: %s", content)
+ }
+
+ expectedCalls := []string{
+ "systemctl --user daemon-reload",
+ "systemctl --user enable --now pinchtab.service",
+ }
+ if strings.Join(runner.calls, "\n") != strings.Join(expectedCalls, "\n") {
+ t.Fatalf("systemd calls = %v, want %v", runner.calls, expectedCalls)
+ }
+}
+
+func TestSystemdUserManagerPreflightRequiresUserSession(t *testing.T) {
+ runner := &fakeCommandRunner{
+ errors: map[string]error{
+ "systemctl --user show-environment": errors.New("exit status 1"),
+ },
+ }
+ manager := &systemdUserManager{
+ env: environment{osName: "linux"},
+ runner: runner,
+ }
+
+ err := manager.Preflight()
+ if err == nil {
+ t.Fatal("expected preflight error")
+ }
+ if !strings.Contains(err.Error(), "working user systemd session") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
diff --git a/internal/daemon/testutil_test.go b/internal/daemon/testutil_test.go
new file mode 100644
index 00000000..01490b80
--- /dev/null
+++ b/internal/daemon/testutil_test.go
@@ -0,0 +1,20 @@
+package daemon
+
+import (
+ "strings"
+)
+
+type fakeCommandRunner struct {
+ calls []string
+ outputs map[string]string
+ errors map[string]error
+}
+
+func (f *fakeCommandRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
+ call := name + " " + strings.Join(args, " ")
+ f.calls = append(f.calls, call)
+ if out, ok := f.outputs[call]; ok {
+ return []byte(out), f.errors[call]
+ }
+ return nil, f.errors[call]
+}
diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.go
new file mode 100644
index 00000000..45a7af69
--- /dev/null
+++ b/internal/dashboard/auth_api.go
@@ -0,0 +1,193 @@
+package dashboard
+
+import (
+ "crypto/subtle"
+ "encoding/json"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+type AuthAPI struct {
+ runtime *config.RuntimeConfig
+ sessions *authn.SessionManager
+ loginLimiter *authn.AttemptLimiter
+}
+
+func NewAuthAPI(runtime *config.RuntimeConfig, sessions *authn.SessionManager) *AuthAPI {
+ return &AuthAPI{
+ runtime: runtime,
+ sessions: sessions,
+ loginLimiter: authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
+ Window: authn.DefaultLoginRateLimitWindow,
+ MaxAttempts: authn.DefaultLoginRateLimitMaxAttempt,
+ }),
+ }
+}
+
+func (a *AuthAPI) RegisterHandlers(mux *http.ServeMux) {
+ mux.HandleFunc("POST /api/auth/login", a.HandleLogin)
+ mux.HandleFunc("POST /api/auth/elevate", a.HandleElevate)
+ mux.HandleFunc("POST /api/auth/logout", a.HandleLogout)
+}
+
+func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
+ token := strings.TrimSpace(a.runtime.Token)
+ if token == "" {
+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)
+ return
+ }
+ clientIP := authn.ClientIP(r)
+ if a.loginLimiter != nil {
+ if allowed, retryAfter := a.loginLimiter.Allow(clientIP); !allowed {
+ retryAfterSec := secondsCeil(retryAfter)
+ w.Header().Set("Retry-After", strconv.Itoa(retryAfterSec))
+ authn.AuditWarn(r, "auth.login_rate_limited",
+ "retryAfterSec", retryAfterSec,
+ "windowSec", int(a.loginLimiter.Window().Seconds()),
+ "maxAttempts", a.loginLimiter.MaxAttempts(),
+ )
+ httpx.ErrorCode(w, http.StatusTooManyRequests, "login_rate_limited", "too many login attempts", true, map[string]any{
+ "retryAfterSec": retryAfterSec,
+ "windowSec": int(a.loginLimiter.Window().Seconds()),
+ "maxAttempts": a.loginLimiter.MaxAttempts(),
+ })
+ return
+ }
+ }
+
+ var req struct {
+ Token string `json:"token"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&req); err != nil {
+ httpx.ErrorCode(w, http.StatusBadRequest, "bad_auth_json", "invalid auth payload", false, nil)
+ return
+ }
+
+ provided := strings.TrimSpace(req.Token)
+ if provided == "" {
+ if a.loginLimiter != nil {
+ a.loginLimiter.RecordFailure(clientIP)
+ }
+ authn.AuditWarn(r, "auth.login_failed", "reason", "missing_token")
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
+ httpx.ErrorCode(w, http.StatusUnauthorized, "missing_token", "unauthorized", false, nil)
+ return
+ }
+
+ if subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
+ if a.loginLimiter != nil {
+ a.loginLimiter.RecordFailure(clientIP)
+ }
+ authn.ClearSessionCookie(w, r)
+ authn.AuditWarn(r, "auth.login_failed", "reason", "bad_token")
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
+ return
+ }
+
+ if a.sessions == nil {
+ httpx.ErrorCode(w, http.StatusInternalServerError, "session_unavailable", "dashboard sessions are not configured", false, nil)
+ return
+ }
+ if creds := authn.CredentialsFromRequest(r); creds.Method == authn.MethodCookie {
+ a.sessions.Revoke(creds.Value)
+ authn.AuditLog(r, "auth.session_revoked", "reason", "replaced")
+ }
+ if a.loginLimiter != nil {
+ a.loginLimiter.Reset(clientIP)
+ }
+ sessionID, err := a.sessions.Create(token)
+ if err != nil {
+ httpx.Error(w, http.StatusInternalServerError, err)
+ return
+ }
+ authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime())
+ authn.AuditLog(r, "auth.session_created",
+ "sessionIdleSec", int(authn.DefaultSessionIdleTimeout.Seconds()),
+ "sessionMaxLifetimeSec", int(a.sessions.MaxLifetime().Seconds()),
+ )
+ httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
+
+func (a *AuthAPI) HandleLogout(w http.ResponseWriter, r *http.Request) {
+ if a.sessions != nil {
+ if creds := authn.CredentialsFromRequest(r); creds.Method == authn.MethodCookie {
+ a.sessions.Revoke(creds.Value)
+ authn.AuditLog(r, "auth.session_revoked", "reason", "logout")
+ }
+ }
+ authn.ClearSessionCookie(w, r)
+ httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
+
+func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {
+ token := strings.TrimSpace(a.runtime.Token)
+ if token == "" {
+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)
+ return
+ }
+ if a.sessions == nil {
+ httpx.ErrorCode(w, http.StatusInternalServerError, "session_unavailable", "dashboard sessions are not configured", false, nil)
+ return
+ }
+
+ creds := authn.CredentialsFromRequest(r)
+ if creds.Method != authn.MethodCookie || creds.Value == "" {
+ httpx.ErrorCode(w, http.StatusForbidden, "session_auth_required", "dashboard session required", false, nil)
+ return
+ }
+
+ var req struct {
+ Token string `json:"token"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&req); err != nil {
+ httpx.ErrorCode(w, http.StatusBadRequest, "bad_auth_json", "invalid auth payload", false, nil)
+ return
+ }
+
+ provided := strings.TrimSpace(req.Token)
+ if provided == "" {
+ authn.AuditWarn(r, "auth.elevation_failed", "reason", "missing_token")
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
+ httpx.ErrorCode(w, http.StatusUnauthorized, "missing_token", "unauthorized", false, nil)
+ return
+ }
+ if subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
+ authn.AuditWarn(r, "auth.elevation_failed", "reason", "bad_token")
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
+ return
+ }
+ if !a.sessions.Elevate(creds.Value, token) {
+ authn.ClearSessionCookie(w, r)
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
+ return
+ }
+
+ authn.AuditLog(r, "auth.session_elevated", "elevationWindowSec", int(a.sessions.ElevationWindow().Seconds()))
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "status": "ok",
+ "elevationWindowSec": int(a.sessions.ElevationWindow().Seconds()),
+ })
+}
+
+func secondsCeil(d time.Duration) int {
+ if d <= 0 {
+ return 1
+ }
+ sec := int(d / time.Second)
+ if d%time.Second != 0 {
+ sec++
+ }
+ if sec <= 0 {
+ return 1
+ }
+ return sec
+}
diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.go
new file mode 100644
index 00000000..d5c09f63
--- /dev/null
+++ b/internal/dashboard/auth_api_test.go
@@ -0,0 +1,203 @@
+package dashboard
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestAuthAPIHandleLogin(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("cookies = %d, want 1", len(cookies))
+ }
+ cookie := cookies[0]
+ if cookie.Name != authn.CookieName {
+ t.Fatalf("cookie name = %q, want %q", cookie.Name, authn.CookieName)
+ }
+ if cookie.Value == "secret-token" {
+ t.Fatal("expected opaque session cookie, not raw bearer token")
+ }
+ if !cookie.HttpOnly {
+ t.Fatal("expected auth cookie to be HttpOnly")
+ }
+ if !cookie.Secure {
+ t.Fatal("expected auth cookie to be Secure")
+ }
+ if cookie.SameSite != http.SameSiteStrictMode {
+ t.Fatalf("cookie SameSite = %v, want %v", cookie.SameSite, http.SameSiteStrictMode)
+ }
+ if !sessions.Validate(cookie.Value, "secret-token") {
+ t.Fatal("expected session cookie value to validate against current token")
+ }
+}
+
+func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))
+
+ req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusUnauthorized)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 || cookies[0].Name != authn.CookieName || cookies[0].MaxAge != -1 {
+ t.Fatalf("expected expired auth cookie on failure, got %+v", cookies)
+ }
+}
+
+func TestAuthAPIHandleLogoutClearsCookie(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "/api/auth/logout", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+
+ api.HandleLogout(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 || cookies[0].Name != authn.CookieName || cookies[0].MaxAge != -1 {
+ t.Fatalf("expected expired auth cookie, got %+v", cookies)
+ }
+ if !cookies[0].Secure {
+ t.Fatal("expected expired auth cookie to remain Secure")
+ }
+ if sessions.Validate(sessionID, "secret-token") {
+ t.Fatal("expected logout to revoke session")
+ }
+}
+
+func TestAuthAPIHandleElevateMarksSessionElevated(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "/api/auth/elevate", strings.NewReader(`{"token":"secret-token"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+
+ api.HandleElevate(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ if !sessions.IsElevated(sessionID, "secret-token") {
+ t.Fatal("expected session to be elevated after re-entering the token")
+ }
+}
+
+func TestAuthAPIHandleElevateRejectsBadToken(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "/api/auth/elevate", strings.NewReader(`{"token":"wrong"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+
+ api.HandleElevate(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusUnauthorized)
+ }
+ if sessions.IsElevated(sessionID, "secret-token") {
+ t.Fatal("expected session to remain unelevated after bad token")
+ }
+}
+
+func TestAuthAPIHandleLoginRateLimitsRepeatedFailures(t *testing.T) {
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))
+ api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
+ Window: time.Minute,
+ MaxAttempts: 1,
+ })
+
+ req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("first status = %d, want %d", w.Code, http.StatusUnauthorized)
+ }
+
+ req = httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w = httptest.NewRecorder()
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("second status = %d, want %d", w.Code, http.StatusTooManyRequests)
+ }
+ if retryAfter := w.Header().Get("Retry-After"); retryAfter == "" {
+ t.Fatal("expected Retry-After header when login is rate limited")
+ }
+}
+
+func TestAuthAPIHandleLoginRateLimitIgnoresSpoofedForwardedHeaders(t *testing.T) {
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))
+ api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
+ Window: time.Minute,
+ MaxAttempts: 1,
+ })
+
+ req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
+ req.RemoteAddr = "198.51.100.10:41000"
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Forwarded-For", "203.0.113.1")
+ w := httptest.NewRecorder()
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("first status = %d, want %d", w.Code, http.StatusUnauthorized)
+ }
+
+ req = httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
+ req.RemoteAddr = "198.51.100.10:41001"
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Forwarded-For", "203.0.113.2")
+ req.Header.Set("X-Real-Ip", "203.0.113.3")
+ w = httptest.NewRecorder()
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("second status = %d, want %d", w.Code, http.StatusTooManyRequests)
+ }
+}
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index 4a5b4bc8..44ffddd5 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -3,12 +3,14 @@ package dashboard
import (
"encoding/json"
"net/http"
+ "strings"
"sync"
"time"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
type profileLister interface {
@@ -33,14 +35,11 @@ type ConfigAPI struct {
type configEnvelope struct {
Config config.FileConfig `json:"config"`
ConfigPath string `json:"configPath"`
+ TokenConfigured bool `json:"tokenConfigured"`
RestartRequired bool `json:"restartRequired"`
RestartReasons []string `json:"restartReasons,omitempty"`
}
-type tokenEnvelope struct {
- Token string `json:"token"`
-}
-
type healthInstanceInfo struct {
ID string `json:"id"`
Status string `json:"status"`
@@ -51,6 +50,7 @@ type healthEnvelope struct {
Mode string `json:"mode"`
Version string `json:"version"`
Uptime int64 `json:"uptime"`
+ AuthRequired bool `json:"authRequired"`
Profiles int `json:"profiles"`
Instances int `json:"instances"`
DefaultInstance *healthInstanceInfo `json:"defaultInstance,omitempty"`
@@ -87,36 +87,30 @@ func NewConfigAPI(
func (c *ConfigAPI) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /api/config", c.HandleGetConfig)
mux.HandleFunc("PUT /api/config", c.HandlePutConfig)
- mux.HandleFunc("POST /api/config/generate-token", c.HandleGenerateToken)
}
func (c *ConfigAPI) HandleHealth(w http.ResponseWriter, r *http.Request) {
info, err := c.healthInfo()
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, info)
+ httpx.JSON(w, 200, info)
}
func (c *ConfigAPI) HandleGetConfig(w http.ResponseWriter, r *http.Request) {
cfg, path, restartReasons, err := c.currentConfig()
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, configEnvelope{
- Config: cfg,
- ConfigPath: path,
- RestartRequired: len(restartReasons) > 0,
- RestartReasons: restartReasons,
- })
+ httpx.JSON(w, 200, c.configEnvelopeFor(cfg, path, restartReasons))
}
func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
normalized := config.DefaultFileConfig()
if err := json.NewDecoder(r.Body).Decode(&normalized); err != nil {
- web.ErrorCode(w, 400, "bad_config_json", "invalid config payload", false, nil)
+ httpx.ErrorCode(w, 400, "bad_config_json", "invalid config payload", false, nil)
return
}
@@ -125,22 +119,27 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
for _, validationErr := range errs {
messages = append(messages, validationErr.Error())
}
- web.ErrorCode(w, 400, "invalid_config", "config validation failed", false, map[string]any{
+ httpx.ErrorCode(w, 400, "invalid_config", "config validation failed", false, map[string]any{
"errors": messages,
})
return
}
+ if strings.TrimSpace(normalized.Server.Token) != "" {
+ httpx.ErrorCode(w, 400, "token_write_only", "manage the API token outside the dashboard", false, nil)
+ return
+ }
c.mu.Lock()
defer c.mu.Unlock()
- _, path, err := config.LoadFileConfig()
+ current, path, err := config.LoadFileConfig()
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
+ normalized.Server.Token = current.Server.Token
if err := config.SaveFileConfig(&normalized, path); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
@@ -150,21 +149,11 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
}
restartReasons := c.restartReasonsFor(normalized)
- web.JSON(w, 200, configEnvelope{
- Config: normalized,
- ConfigPath: path,
- RestartRequired: len(restartReasons) > 0,
- RestartReasons: restartReasons,
- })
-}
-
-func (c *ConfigAPI) HandleGenerateToken(w http.ResponseWriter, r *http.Request) {
- token, err := config.GenerateAuthToken()
- if err != nil {
- web.Error(w, 500, err)
- return
- }
- web.JSON(w, 200, tokenEnvelope{Token: token})
+ authn.AuditLog(r, "config.updated",
+ "restartRequired", len(restartReasons) > 0,
+ "restartReasons", restartReasons,
+ )
+ httpx.JSON(w, 200, c.configEnvelopeFor(normalized, path, restartReasons))
}
func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {
@@ -198,6 +187,7 @@ func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {
Mode: "dashboard",
Version: c.version,
Uptime: int64(time.Since(c.startedAt).Milliseconds()),
+ AuthRequired: strings.TrimSpace(c.runtime.Token) != "",
Profiles: profileCount,
Instances: instanceCount,
DefaultInstance: defaultInst,
@@ -219,6 +209,28 @@ func (c *ConfigAPI) currentConfig() (config.FileConfig, string, []string, error)
return *fc, path, restartReasons, nil
}
+func (c *ConfigAPI) configEnvelopeFor(cfg config.FileConfig, path string, restartReasons []string) configEnvelope {
+ return configEnvelope{
+ Config: redactToken(cfg),
+ ConfigPath: path,
+ TokenConfigured: c.tokenConfigured(cfg),
+ RestartRequired: len(restartReasons) > 0,
+ RestartReasons: restartReasons,
+ }
+}
+
+func (c *ConfigAPI) tokenConfigured(cfg config.FileConfig) bool {
+ if c != nil && c.runtime != nil && strings.TrimSpace(c.runtime.Token) != "" {
+ return true
+ }
+ return strings.TrimSpace(cfg.Server.Token) != ""
+}
+
+func redactToken(cfg config.FileConfig) config.FileConfig {
+ cfg.Server.Token = ""
+ return cfg
+}
+
func (c *ConfigAPI) restartReasonsFor(next config.FileConfig) []string {
reasons := make([]string, 0, 5)
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
index 119926dd..d51bb76c 100644
--- a/internal/dashboard/config_api_test.go
+++ b/internal/dashboard/config_api_test.go
@@ -1,10 +1,14 @@
package dashboard
import (
+ "bytes"
"encoding/json"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"slices"
+ "strings"
"testing"
"time"
@@ -78,3 +82,116 @@ func TestRestartReasonsIncludeStealthLevel(t *testing.T) {
t.Fatalf("restartReasonsFor() = %v, want Stealth level", reasons)
}
}
+
+func TestHandleGetConfigRedactsToken(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+
+ api := newConfigAPITestAPI(t, fc)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+ api.HandleGetConfig(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("HandleGetConfig() status = %d, want %d", w.Code, http.StatusOK)
+ }
+
+ env := decodeConfigEnvelope(t, w)
+ if env.Config.Server.Token != "" {
+ t.Fatalf("config token = %q, want redacted empty string", env.Config.Server.Token)
+ }
+ if !env.TokenConfigured {
+ t.Fatal("tokenConfigured = false, want true")
+ }
+}
+
+func TestHandlePutConfigPreservesExistingToken(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+
+ api := newConfigAPITestAPI(t, fc)
+
+ payload := config.DefaultFileConfig()
+ payload.Server.Port = "9999"
+
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ api.HandlePutConfig(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("HandlePutConfig() status = %d, want %d", w.Code, http.StatusOK)
+ }
+
+ env := decodeConfigEnvelope(t, w)
+ if env.Config.Server.Token != "" {
+ t.Fatalf("response token = %q, want redacted empty string", env.Config.Server.Token)
+ }
+ if !env.TokenConfigured {
+ t.Fatal("tokenConfigured = false, want true")
+ }
+
+ saved, _, err := config.LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if saved.Server.Token != "secret-token" {
+ t.Fatalf("saved token = %q, want existing token preserved", saved.Server.Token)
+ }
+ if saved.Server.Port != "9999" {
+ t.Fatalf("saved port = %q, want %q", saved.Server.Port, "9999")
+ }
+}
+
+func TestHandlePutConfigRejectsWriteOnlyTokenField(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+
+ api := newConfigAPITestAPI(t, fc)
+
+ payload := config.DefaultFileConfig()
+ payload.Server.Token = "replacement-token"
+
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ api.HandlePutConfig(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("HandlePutConfig() status = %d, want %d", w.Code, http.StatusBadRequest)
+ }
+ if !strings.Contains(w.Body.String(), "token_write_only") {
+ t.Fatalf("response = %q, want token_write_only error", w.Body.String())
+ }
+}
+
+func newConfigAPITestAPI(t *testing.T, fc config.FileConfig) *ConfigAPI {
+ t.Helper()
+
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ return NewConfigAPI(config.Load(), nil, nil, nil, "test", time.Now())
+}
+
+func decodeConfigEnvelope(t *testing.T, w *httptest.ResponseRecorder) configEnvelope {
+ t.Helper()
+
+ var env configEnvelope
+ if err := json.NewDecoder(w.Body).Decode(&env); err != nil {
+ t.Fatalf("Decode() error = %v", err)
+ }
+ return env
+}
diff --git a/internal/engine/lite.go b/internal/engine/lite.go
index eeec8115..a1920d08 100644
--- a/internal/engine/lite.go
+++ b/internal/engine/lite.go
@@ -14,7 +14,7 @@ import (
"github.com/gost-dom/browser/dom"
"github.com/gost-dom/browser/html"
gosturl "github.com/gost-dom/browser/url"
- "github.com/pinchtab/pinchtab/internal/urlutil"
+ "github.com/pinchtab/pinchtab/internal/urls"
nethtml "golang.org/x/net/html"
)
@@ -56,7 +56,7 @@ func (l *LiteEngine) Navigate(ctx context.Context, url string) (*NavigateResult,
defer l.mu.Unlock()
// Validate and sanitize URL to prevent SSRF (CodeQL go/request-forgery).
- safeURL, err := urlutil.Sanitize(url)
+ safeURL, err := urls.Sanitize(url)
if err != nil {
return nil, fmt.Errorf("lite navigate: %w", err)
}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index ce4b533e..2add0a3c 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -14,9 +14,9 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/engine"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/selector"
"github.com/pinchtab/pinchtab/internal/semantic"
- "github.com/pinchtab/pinchtab/internal/web"
)
func resolveOwner(r *http.Request, fallback string) string {
@@ -83,14 +83,14 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
} else {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
}
// Validate kind — single endpoint returns 400 for bad input (unlike batch which returns 200 with errors)
if req.Kind == "" {
- web.Error(w, 400, fmt.Errorf("missing required field 'kind'"))
+ httpx.Error(w, 400, fmt.Errorf("missing required field 'kind'"))
return
}
h.recordActionRequest(r, req)
@@ -104,7 +104,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
}
if !known {
- web.Error(w, 400, fmt.Errorf("unknown action kind: %s", req.Kind))
+ httpx.Error(w, 400, fmt.Errorf("unknown action kind: %s", req.Kind))
return
}
}
@@ -121,7 +121,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
var err error
ctx, resolvedTabID, err = h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if req.TabID == "" {
@@ -129,7 +129,10 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
owner := resolveOwner(r, req.Owner)
if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
- web.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
}
@@ -149,7 +152,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
// Unified selector resolution: normalize legacy ref/selector fields
// into the unified Selector, then resolve to a nodeID when possible.
@@ -183,7 +186,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
case selector.KindXPath:
nid, err := bridge.ResolveXPathToNodeID(tCtx, sel.Value)
if err != nil {
- web.Error(w, 400, fmt.Errorf("xpath selector: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("xpath selector: %w", err))
return
}
req.NodeID = nid
@@ -192,7 +195,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
case selector.KindText:
nid, err := bridge.ResolveTextToNodeID(tCtx, sel.Value)
if err != nil {
- web.Error(w, 400, fmt.Errorf("text selector: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("text selector: %w", err))
return
}
req.NodeID = nid
@@ -217,7 +220,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
Threshold: 0.3, TopK: 1,
})
if err != nil {
- web.Error(w, 500, fmt.Errorf("semantic selector: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("semantic selector: %w", err))
return
}
if result.BestRef != "" {
@@ -230,15 +233,15 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
}
if req.NodeID == 0 {
- web.Error(w, 404, fmt.Errorf("semantic selector %q: no matching element found", sel.Value))
+ httpx.Error(w, 404, fmt.Errorf("semantic selector %q: no matching element found", sel.Value))
return
}
} else {
- web.Error(w, 500, fmt.Errorf("semantic selector: no snapshot available — navigate first"))
+ httpx.Error(w, 500, fmt.Errorf("semantic selector: no snapshot available — navigate first"))
return
}
} else {
- web.Error(w, 501, fmt.Errorf("semantic selectors require a matcher (not configured)"))
+ httpx.Error(w, 501, fmt.Errorf("semantic selectors require a matcher (not configured)"))
return
}
req.Selector = ""
@@ -276,7 +279,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
actionErr = fmt.Errorf("ref %s not found and recovery failed: %w", req.Ref, recoveryErr)
}
} else if refMissing {
- web.Error(w, 404, fmt.Errorf("ref %s not found - take a /snapshot first", req.Ref))
+ httpx.Error(w, 404, fmt.Errorf("ref %s not found - take a /snapshot first", req.Ref))
return
} else {
result, engineName, actionErr = h.executeAction(tCtx, req)
@@ -312,16 +315,16 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
if actionErr != nil {
if strings.HasPrefix(actionErr.Error(), "unknown action") {
kinds := h.Bridge.AvailableActions()
- web.JSON(w, 400, map[string]string{
+ httpx.JSON(w, 400, map[string]string{
"error": fmt.Sprintf("%s - valid values: %s", actionErr.Error(), strings.Join(kinds, ", ")),
})
return
}
if errors.Is(actionErr, engine.ErrLiteNotSupported) {
- web.ErrorCode(w, http.StatusNotImplemented, "not_supported", actionErr.Error(), false, nil)
+ httpx.ErrorCode(w, http.StatusNotImplemented, "not_supported", actionErr.Error(), false, nil)
return
}
- web.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), true, nil)
+ httpx.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), true, nil)
return
}
@@ -333,7 +336,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
if recoveryResult != nil {
resp["recovery"] = recoveryResult
}
- web.JSON(w, 200, resp)
+ httpx.JSON(w, 200, resp)
}
// HandleTabAction performs a single action on a tab identified by path ID.
@@ -342,24 +345,24 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabAction(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
var req bridge.ActionRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.TabID != "" && req.TabID != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
req.TabID = tabID
payload, err := json.Marshal(req)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -388,12 +391,12 @@ type actionResult struct {
func (h *Handlers) HandleActions(w http.ResponseWriter, r *http.Request) {
var req actionsRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if len(req.Actions) == 0 {
- web.Error(w, 400, fmt.Errorf("actions array is empty"))
+ httpx.Error(w, 400, fmt.Errorf("actions array is empty"))
return
}
@@ -406,24 +409,24 @@ func (h *Handlers) HandleActions(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabActions(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
var req actionsRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.TabID != "" && req.TabID != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
req.TabID = tabID
payload, err := json.Marshal(req)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -448,13 +451,13 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
resolvedTabID = req.TabID
} else {
var err error
- ctx, resolvedTabID, err = h.Bridge.TabContext(req.TabID)
+ ctx, resolvedTabID, err = h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
- web.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
return
}
}
@@ -465,7 +468,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
action.TabID = resolvedTabID
} else if !allLite && action.TabID != resolvedTabID {
var err error
- ctx, resolvedTabID, err = h.Bridge.TabContext(action.TabID)
+ ctx, resolvedTabID, err = h.tabContext(r, action.TabID)
if err != nil {
results = append(results, actionResult{
Index: i, Success: false,
@@ -484,6 +487,11 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
continue
}
}
+ if !allLite {
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
+ return
+ }
+ }
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
useLiteAction := h.shouldUseLiteAction(action.Kind)
@@ -697,7 +705,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"results": results,
"total": len(req.Actions),
"successful": countSuccessful(results),
@@ -707,7 +715,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowMacro {
- web.ErrorCode(w, 403, "macro_disabled", web.DisabledEndpointMessage("macro", "security.allowMacro"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "macro_disabled", httpx.DisabledEndpointMessage("macro", "security.allowMacro"), false, map[string]any{
"setting": "security.allowMacro",
})
return
@@ -720,11 +728,11 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
StepTimeout float64 `json:"stepTimeout"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.ErrorCode(w, 400, "bad_request", fmt.Sprintf("decode: %v", err), false, nil)
+ httpx.ErrorCode(w, 400, "bad_request", fmt.Sprintf("decode: %v", err), false, nil)
return
}
if len(req.Steps) == 0 {
- web.ErrorCode(w, 400, "bad_request", "steps array is empty", false, nil)
+ httpx.ErrorCode(w, 400, "bad_request", "steps array is empty", false, nil)
return
}
owner := resolveOwner(r, req.Owner)
@@ -741,13 +749,13 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
resolvedTabID = req.TabID
} else {
var err error
- ctx, resolvedTabID, err = h.Bridge.TabContext(req.TabID)
+ ctx, resolvedTabID, err = h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
- web.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
return
}
}
@@ -757,6 +765,11 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if step.TabID == "" {
step.TabID = resolvedTabID
}
+ if !allLiteMacro {
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
+ return
+ }
+ }
useLiteAction := h.shouldUseLiteAction(step.Kind)
// Unified selector resolution for macro steps (mirrors HandleAction).
step.NormalizeSelector()
@@ -945,7 +958,7 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
results = append(results, actionResult{Index: i, Success: true, Result: res})
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"kind": "macro",
"results": results,
"total": len(req.Steps),
diff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.go
index f333addc..a6573669 100644
--- a/internal/handlers/cookies.go
+++ b/internal/handlers/cookies.go
@@ -14,7 +14,7 @@ import (
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {
@@ -22,9 +22,12 @@ func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("url")
name := r.URL.Query().Get("name")
- ctx, _, err := h.Bridge.TabContext(tabID)
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
@@ -43,7 +46,7 @@ func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {
return err
}),
); err != nil {
- web.Error(w, 500, fmt.Errorf("get cookies: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("get cookies: %w", err))
return
}
@@ -73,7 +76,7 @@ func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {
}
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"url": url,
"cookies": result,
"count": len(result),
@@ -86,7 +89,7 @@ func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabGetCookies(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
@@ -121,23 +124,26 @@ type cookieSetRequest struct {
func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
var req cookieRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.URL == "" {
- web.Error(w, 400, fmt.Errorf("url is required"))
+ httpx.Error(w, 400, fmt.Errorf("url is required"))
return
}
if len(req.Cookies) == 0 {
- web.Error(w, 400, fmt.Errorf("cookies array is empty"))
+ httpx.Error(w, 400, fmt.Errorf("cookies array is empty"))
return
}
- ctx, _, err := h.Bridge.TabContext(req.TabID)
+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
@@ -186,7 +192,7 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
}
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"set": successCount,
"failed": len(req.Cookies) - successCount,
"total": len(req.Cookies),
@@ -199,26 +205,26 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabSetCookies(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
reqBody := cookieRequest{}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
if err := dec.Decode(&reqBody); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if reqBody.TabID != "" && reqBody.TabID != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
reqBody.TabID = tabID
payload, err := json.Marshal(reqBody)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
diff --git a/internal/handlers/dialog.go b/internal/handlers/dialog.go
index e9ed4cc2..06918f55 100644
--- a/internal/handlers/dialog.go
+++ b/internal/handlers/dialog.go
@@ -10,7 +10,7 @@ import (
"net/http"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// HandleDialog handles the current JavaScript dialog (accept/dismiss).
@@ -23,21 +23,21 @@ func (h *Handlers) HandleDialog(w http.ResponseWriter, r *http.Request) {
Text string `json:"text"` // optional prompt text
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.Action == "" {
- web.Error(w, 400, fmt.Errorf("action required (accept or dismiss)"))
+ httpx.Error(w, 400, fmt.Errorf("action required (accept or dismiss)"))
return
}
if req.Action != "accept" && req.Action != "dismiss" {
- web.Error(w, 400, fmt.Errorf("action must be 'accept' or 'dismiss'"))
+ httpx.Error(w, 400, fmt.Errorf("action must be 'accept' or 'dismiss'"))
return
}
ctx, resolvedID, err := h.Bridge.TabContext(req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -51,23 +51,23 @@ func (h *Handlers) HandleDialog(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabDialog(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
body := map[string]any{}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if rawTabID, ok := body["tabId"]; ok {
if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
return
} else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
}
@@ -76,7 +76,7 @@ func (h *Handlers) HandleTabDialog(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(body)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -91,19 +91,19 @@ func (h *Handlers) HandleTabDialog(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) handleDialogAction(w http.ResponseWriter, r *http.Request, ctx context.Context, tabID string, accept bool, promptText string) {
dm := h.Bridge.GetDialogManager()
if dm == nil {
- web.Error(w, 500, fmt.Errorf("dialog manager not available"))
+ httpx.Error(w, 500, fmt.Errorf("dialog manager not available"))
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
result, err := bridge.HandlePendingDialog(tCtx, tabID, dm, accept, promptText)
if err != nil {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
- web.JSON(w, 200, result)
+ httpx.JSON(w, 200, result)
}
diff --git a/internal/handlers/download.go b/internal/handlers/download.go
index aeb4ed87..0f26c781 100644
--- a/internal/handlers/download.go
+++ b/internal/handlers/download.go
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "strconv"
"strings"
"sync"
"time"
@@ -21,22 +22,31 @@ import (
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/idpi"
)
var resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
return net.DefaultResolver.LookupIP(ctx, network, host)
}
+var errDownloadTooLarge = errors.New("download response too large")
+
var blockedDownloadPrefixes = []netip.Prefix{
netip.MustParsePrefix("100.64.0.0/10"), // Carrier-grade NAT/shared address space.
netip.MustParsePrefix("198.18.0.0/15"), // Benchmark/testing networks.
}
-type downloadURLGuard struct{}
+type downloadURLGuard struct {
+ allowedDomains []string
+}
-func newDownloadURLGuard() *downloadURLGuard { return &downloadURLGuard{} }
+func newDownloadURLGuard(allowedDomains []string) *downloadURLGuard {
+ return &downloadURLGuard{allowedDomains: append([]string(nil), allowedDomains...)}
+}
func (g *downloadURLGuard) Validate(rawURL string) error {
parsed, err := url.Parse(rawURL)
@@ -54,20 +64,30 @@ func (g *downloadURLGuard) Validate(rawURL string) error {
}
if ip := net.ParseIP(host); ip != nil {
- return validateDownloadIP(ip)
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
- defer cancel()
-
- ips, err := resolveDownloadHostIPs(ctx, "ip", host)
- if err != nil {
- return fmt.Errorf("could not resolve host")
- }
- for _, ip := range ips {
if err := validateDownloadIP(ip); err != nil {
return err
}
+ } else {
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+
+ ips, err := resolveDownloadHostIPs(ctx, "ip", host)
+ if err != nil {
+ return fmt.Errorf("could not resolve host")
+ }
+ for _, ip := range ips {
+ if err := validateDownloadIP(ip); err != nil {
+ return err
+ }
+ }
+ }
+
+ if result := idpi.CheckDomain(rawURL, config.IDPIConfig{
+ Enabled: len(g.allowedDomains) > 0,
+ AllowedDomains: append([]string(nil), g.allowedDomains...),
+ StrictMode: true,
+ }); result.Blocked {
+ return fmt.Errorf("domain not allowed by security.downloadAllowedDomains")
}
return nil
}
@@ -93,10 +113,53 @@ func validateDownloadIP(ip net.IP) error {
return nil
}
+func validateDownloadRemoteIPAddress(raw string) error {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ // Best-effort mitigation: some responses may not expose a remote IP
+ // (for example, cached responses). Skip the post-connect check then.
+ return nil
+ }
+
+ raw = strings.TrimPrefix(raw, "[")
+ raw = strings.TrimSuffix(raw, "]")
+
+ ip := net.ParseIP(raw)
+ if ip == nil {
+ return fmt.Errorf("download connected to an unparseable remote IP %q", raw)
+ }
+ if err := validateDownloadIP(ip); err != nil {
+ return fmt.Errorf("download connected to blocked remote IP %s", raw)
+ }
+ return nil
+}
+
// validateDownloadURL blocks file://, internal hosts, private IPs, and cloud metadata.
// Only public http/https URLs are allowed.
func validateDownloadURL(rawURL string) error {
- return newDownloadURLGuard().Validate(rawURL)
+ return newDownloadURLGuard(nil).Validate(rawURL)
+}
+
+func validateTabScopedDownloadURL(currentURL, requestedURL string) error {
+ currentParsed, err := url.Parse(strings.TrimSpace(currentURL))
+ if err != nil || currentParsed.Scheme == "" || currentParsed.Host == "" {
+ return fmt.Errorf("tab-scoped downloads require an active http(s) page")
+ }
+ if currentParsed.Scheme != "http" && currentParsed.Scheme != "https" {
+ return fmt.Errorf("tab-scoped downloads require an active http(s) page")
+ }
+
+ requestedParsed, err := url.Parse(strings.TrimSpace(requestedURL))
+ if err != nil || requestedParsed.Scheme == "" || requestedParsed.Host == "" {
+ return fmt.Errorf("invalid download URL")
+ }
+
+ if strings.EqualFold(currentParsed.Scheme, requestedParsed.Scheme) &&
+ strings.EqualFold(currentParsed.Host, requestedParsed.Host) {
+ return nil
+ }
+
+ return fmt.Errorf("tab-scoped downloads are limited to the current page origin")
}
type downloadRequestGuard struct {
@@ -142,29 +205,111 @@ func (g *downloadRequestGuard) BlockedError() error {
return g.blockedErr
}
+func downloadTooLargeError(size int64, maxBytes int) error {
+ return fmt.Errorf("%w: received %d bytes, max %d", errDownloadTooLarge, size, maxBytes)
+}
+
+func parseContentLengthHeader(headers network.Headers) (int64, bool) {
+ for key, raw := range headers {
+ if !strings.EqualFold(strings.TrimSpace(key), "Content-Length") {
+ continue
+ }
+ value := strings.TrimSpace(fmt.Sprint(raw))
+ if value == "" {
+ return 0, false
+ }
+ size, err := strconv.ParseInt(value, 10, 64)
+ if err != nil || size < 0 {
+ return 0, false
+ }
+ return size, true
+ }
+ return 0, false
+}
+
+func writeDownloadGuardError(w http.ResponseWriter, err error, maxBytes int) bool {
+ if err == nil {
+ return false
+ }
+ switch {
+ case errors.Is(err, bridge.ErrTooManyRedirects):
+ httpx.Error(w, 422, fmt.Errorf("download: %w", err))
+ case errors.Is(err, errDownloadTooLarge):
+ httpx.ErrorCode(w, http.StatusRequestEntityTooLarge, "download_too_large", err.Error(), false, map[string]any{
+ "maxBytes": maxBytes,
+ })
+ default:
+ httpx.Error(w, 400, err)
+ }
+ return true
+}
+
// HandleDownload fetches a URL using the browser's session (cookies, stealth)
// and returns the content. This preserves authentication and fingerprint.
//
// GET /download?url=<url>[&tabId=<id>][&output=file&path=/tmp/file][&raw=true]
func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowDownload {
- web.ErrorCode(w, 403, "download_disabled", web.DisabledEndpointMessage("download", "security.allowDownload"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "download_disabled", httpx.DisabledEndpointMessage("download", "security.allowDownload"), false, map[string]any{
"setting": "security.allowDownload",
})
return
}
dlURL := r.URL.Query().Get("url")
if dlURL == "" {
- web.Error(w, 400, fmt.Errorf("url parameter required"))
+ httpx.Error(w, 400, fmt.Errorf("url parameter required"))
return
}
+ maxDownloadBytes := h.Config.EffectiveDownloadMaxBytes()
- validator := newDownloadURLGuard()
+ validator := newDownloadURLGuard(h.Config.DownloadAllowedDomains)
if err := validator.Validate(dlURL); err != nil {
- web.Error(w, 400, fmt.Errorf("unsafe URL: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("unsafe URL: %w", err))
return
}
+ tabID := strings.TrimSpace(r.URL.Query().Get("tabId"))
+ if tabID != "" {
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
+ if err != nil {
+ httpx.Error(w, 404, err)
+ return
+ }
+ owner := resolveOwner(r, "")
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ httpx.ErrorCode(w, http.StatusLocked, "tab_locked", err.Error(), false, nil)
+ return
+ }
+ currentURL, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID)
+ if !ok {
+ return
+ }
+ if currentURL == "" {
+ if provider, ok := h.Bridge.(tabPolicyStateProvider); ok {
+ if state, ok := provider.GetTabPolicyState(resolvedTabID); ok && state.CurrentURL != "" {
+ currentURL = state.CurrentURL
+ }
+ }
+ }
+ if currentURL == "" {
+ lookupCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+ if err := chromedp.Run(lookupCtx, chromedp.Location(&currentURL)); err != nil {
+ httpx.Error(w, 500, fmt.Errorf("resolve current tab url: %w", err))
+ return
+ }
+ }
+ if authn.CredentialsFromRequest(r).Method == authn.MethodCookie {
+ if err := validateTabScopedDownloadURL(currentURL, dlURL); err != nil {
+ httpx.ErrorCode(w, http.StatusForbidden, "download_scope_forbidden", err.Error(), false, map[string]any{
+ "currentURL": currentURL,
+ "requestedURL": dlURL,
+ })
+ return
+ }
+ }
+ }
+
output := r.URL.Query().Get("output")
filePath := r.URL.Query().Get("path")
raw := r.URL.Query().Get("raw") == "true"
@@ -176,7 +321,7 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
tCtx, tCancel := context.WithTimeout(tabCtx, 30*time.Second)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
// Enable network tracking to capture response metadata.
var requestID network.RequestID
@@ -185,13 +330,14 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
requestGuard := newDownloadRequestGuard(validator, h.Config.MaxRedirects)
var mainFrameID cdp.FrameID
done := make(chan struct{}, 1)
+ var receivedBytes atomic.Int64
// Intercept every browser-side request so redirects and follow-on navigations
// cannot escape the public-only URL policy enforced for /download.
if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {
return fetch.Enable().Do(ctx)
})); err != nil {
- web.Error(w, 500, fmt.Errorf("fetch enable: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("fetch enable: %w", err))
return
}
defer func() {
@@ -232,6 +378,40 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
requestID = e.RequestID
responseMIME = e.Response.MimeType
responseStatus = int(e.Response.Status)
+ if err := validateDownloadRemoteIPAddress(e.Response.RemoteIPAddress); err != nil {
+ requestGuard.NoteBlocked(err)
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ tCancel()
+ return
+ }
+ if contentLength, ok := parseContentLengthHeader(e.Response.Headers); ok && contentLength > int64(maxDownloadBytes) {
+ requestGuard.NoteBlocked(downloadTooLargeError(contentLength, maxDownloadBytes))
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ tCancel()
+ return
+ }
+ }
+ case *network.EventDataReceived:
+ if e.RequestID == requestID && requestID != "" {
+ chunk := e.EncodedDataLength
+ if chunk <= 0 {
+ chunk = e.DataLength
+ }
+ if chunk > 0 && receivedBytes.Add(chunk) > int64(maxDownloadBytes) {
+ requestGuard.NoteBlocked(downloadTooLargeError(receivedBytes.Load(), maxDownloadBytes))
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ tCancel()
+ return
+ }
}
case *network.EventLoadingFinished:
if e.RequestID == requestID && requestID != "" {
@@ -251,28 +431,23 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
})
if err := chromedp.Run(tCtx, network.Enable()); err != nil {
- web.Error(w, 500, fmt.Errorf("network enable: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("network enable: %w", err))
return
}
// Re-check scheme before navigation (validateDownloadURL already enforces this,
// but inline check satisfies CodeQL SSRF analysis).
if parsed, err := url.Parse(dlURL); err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
- web.Error(w, 400, fmt.Errorf("invalid download URL scheme"))
+ httpx.Error(w, 400, fmt.Errorf("invalid download URL scheme"))
return
}
// Navigate the temp tab to the URL — uses browser's cookie jar and stealth.
if err := chromedp.Run(tCtx, chromedp.Navigate(dlURL)); err != nil {
- if blockedErr := requestGuard.BlockedError(); blockedErr != nil {
- if errors.Is(blockedErr, bridge.ErrTooManyRedirects) {
- web.Error(w, 422, fmt.Errorf("download: %w", blockedErr))
- return
- }
- web.Error(w, 400, blockedErr)
+ if writeDownloadGuardError(w, requestGuard.BlockedError(), maxDownloadBytes) {
return
}
- web.Error(w, 502, fmt.Errorf("navigate to download URL: %w", err))
+ httpx.Error(w, 502, fmt.Errorf("navigate to download URL: %w", err))
return
}
@@ -280,33 +455,23 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
select {
case <-done:
case <-tCtx.Done():
- if blockedErr := requestGuard.BlockedError(); blockedErr != nil {
- if errors.Is(blockedErr, bridge.ErrTooManyRedirects) {
- web.Error(w, 422, fmt.Errorf("download: %w", blockedErr))
- return
- }
- web.Error(w, 400, blockedErr)
+ if writeDownloadGuardError(w, requestGuard.BlockedError(), maxDownloadBytes) {
return
}
- web.Error(w, 504, fmt.Errorf("download timed out"))
+ httpx.Error(w, 504, fmt.Errorf("download timed out"))
return
}
- if blockedErr := requestGuard.BlockedError(); blockedErr != nil {
- if errors.Is(blockedErr, bridge.ErrTooManyRedirects) {
- web.Error(w, 422, fmt.Errorf("download: %w", blockedErr))
- return
- }
- web.Error(w, 400, blockedErr)
+ if writeDownloadGuardError(w, requestGuard.BlockedError(), maxDownloadBytes) {
return
}
if responseStatus >= 400 {
- web.Error(w, 502, fmt.Errorf("remote server returned HTTP %d", responseStatus))
+ httpx.Error(w, 502, fmt.Errorf("remote server returned HTTP %d", responseStatus))
return
}
if requestID == "" {
- web.Error(w, 502, fmt.Errorf("download response was not captured"))
+ httpx.Error(w, 502, fmt.Errorf("download response was not captured"))
return
}
@@ -322,7 +487,14 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
return nil
}),
); err != nil {
- web.Error(w, 500, fmt.Errorf("get response body: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("get response body: %w", err))
+ return
+ }
+ if len(body) > maxDownloadBytes {
+ httpx.ErrorCode(w, http.StatusRequestEntityTooLarge, "download_too_large",
+ downloadTooLargeError(int64(len(body)), maxDownloadBytes).Error(), false, map[string]any{
+ "maxBytes": maxDownloadBytes,
+ })
return
}
@@ -333,30 +505,30 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
// Write to file.
if output == "file" {
if filePath == "" {
- web.Error(w, 400, fmt.Errorf("path required when output=file"))
+ httpx.Error(w, 400, fmt.Errorf("path required when output=file"))
return
}
- safe, pathErr := web.SafePath(h.Config.StateDir, filePath)
+ safe, pathErr := httpx.SafeCreatePath(h.Config.StateDir, filePath)
if pathErr != nil {
- web.Error(w, 400, fmt.Errorf("invalid path: %w", pathErr))
+ httpx.Error(w, 400, fmt.Errorf("invalid path: %w", pathErr))
return
}
absBase, _ := filepath.Abs(h.Config.StateDir)
absPath, pathErr := filepath.Abs(safe)
if pathErr != nil || !strings.HasPrefix(absPath, absBase+string(filepath.Separator)) {
- web.Error(w, 400, fmt.Errorf("invalid output path"))
+ httpx.Error(w, 400, fmt.Errorf("invalid output path"))
return
}
filePath = absPath
if err := os.MkdirAll(filepath.Dir(filePath), 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("failed to create directory: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("failed to create directory: %w", err))
return
}
if err := os.WriteFile(filePath, body, 0600); err != nil {
- web.Error(w, 500, fmt.Errorf("failed to write file: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("failed to write file: %w", err))
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"status": "saved",
"path": filePath,
"size": len(body),
@@ -375,7 +547,7 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
}
// Default: base64 JSON response.
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"data": base64.StdEncoding.EncodeToString(body),
"contentType": responseMIME,
"size": len(body),
@@ -389,11 +561,11 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabDownload(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
if _, _, err := h.Bridge.TabContext(tabID); err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
diff --git a/internal/handlers/download_test.go b/internal/handlers/download_test.go
index 21d51e39..3bcaa5e8 100644
--- a/internal/handlers/download_test.go
+++ b/internal/handlers/download_test.go
@@ -8,11 +8,43 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
)
+type downloadPolicyBridge struct {
+ bridge.BridgeAPI
+ lock *bridge.LockInfo
+ policy bridge.TabPolicyState
+ hasState bool
+}
+
+func (m *downloadPolicyBridge) BrowserContext() context.Context {
+ return context.Background()
+}
+
+func (m *downloadPolicyBridge) TabContext(tabID string) (context.Context, string, error) {
+ ctx, _ := chromedp.NewContext(context.Background())
+ return ctx, tabID, nil
+}
+
+func (m *downloadPolicyBridge) ListTargets() ([]*target.Info, error) {
+ return []*target.Info{{TargetID: "tab1", Type: "page"}}, nil
+}
+
+func (m *downloadPolicyBridge) TabLockInfo(tabID string) *bridge.LockInfo {
+ return m.lock
+}
+
+func (m *downloadPolicyBridge) GetTabPolicyState(tabID string) (bridge.TabPolicyState, bool) {
+ return m.policy, m.hasState
+}
+
func TestHandleDownload_MissingURL(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowDownload: true}, nil, nil, nil)
req := httptest.NewRequest("GET", "/download", nil)
@@ -80,6 +112,32 @@ func TestValidateDownloadURL(t *testing.T) {
}
}
+func TestValidateDownloadRemoteIPAddress(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ wantErr bool
+ }{
+ {name: "empty allowed", raw: "", wantErr: false},
+ {name: "public ipv4", raw: "93.184.216.34", wantErr: false},
+ {name: "public ipv6", raw: "2606:2800:220:1:248:1893:25c8:1946", wantErr: false},
+ {name: "bracketed ipv6", raw: "[::1]", wantErr: true},
+ {name: "loopback ipv4", raw: "127.0.0.1", wantErr: true},
+ {name: "private ipv4", raw: "192.168.1.10", wantErr: true},
+ {name: "metadata ipv4", raw: "169.254.169.254", wantErr: true},
+ {name: "garbage", raw: "not-an-ip", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateDownloadRemoteIPAddress(tt.raw)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("validateDownloadRemoteIPAddress(%q) error = %v, wantErr %v", tt.raw, err, tt.wantErr)
+ }
+ })
+ }
+}
+
func TestHandleDownload_SSRFBlocked(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowDownload: true}, nil, nil, nil)
urls := []string{
@@ -146,7 +204,7 @@ func TestDownloadRequestGuard_BlocksBrowserSideRequests(t *testing.T) {
}
}
- guard := newDownloadRequestGuard(newDownloadURLGuard(), -1)
+ guard := newDownloadRequestGuard(newDownloadURLGuard(nil), -1)
err := guard.Validate("http://127.0.0.1:1337/increment", false)
if err == nil {
t.Fatal("expected browser-side localhost request to be blocked")
@@ -156,6 +214,173 @@ func TestDownloadRequestGuard_BlocksBrowserSideRequests(t *testing.T) {
}
}
+func TestDownloadURLGuard_EnforcesAllowedDomains(t *testing.T) {
+ originalResolver := resolveDownloadHostIPs
+ t.Cleanup(func() {
+ resolveDownloadHostIPs = originalResolver
+ })
+ resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ switch host {
+ case "pinchtab.com", "cdn.pinchtab.com", "example.com":
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ default:
+ return nil, errors.New("not found")
+ }
+ }
+
+ guard := newDownloadURLGuard([]string{"pinchtab.com", "*.pinchtab.com"})
+
+ if err := guard.Validate("https://pinchtab.com/file.pdf"); err != nil {
+ t.Fatalf("expected exact allowlist match to pass, got %v", err)
+ }
+ if err := guard.Validate("https://cdn.pinchtab.com/file.pdf"); err != nil {
+ t.Fatalf("expected wildcard allowlist match to pass, got %v", err)
+ }
+
+ err := guard.Validate("https://example.com/file.pdf")
+ if err == nil {
+ t.Fatal("expected download allowlist to reject example.com")
+ }
+ if !strings.Contains(err.Error(), "security.downloadAllowedDomains") {
+ t.Fatalf("expected allowlist error, got %v", err)
+ }
+}
+
+func TestValidateTabScopedDownloadURL(t *testing.T) {
+ tests := []struct {
+ name string
+ currentURL string
+ requestURL string
+ wantErr bool
+ }{
+ {"same origin", "https://pinchtab.com/app", "https://pinchtab.com/file.pdf", false},
+ {"same origin with port", "http://127.0.0.1:9867/page", "http://127.0.0.1:9867/file", false},
+ {"cross origin", "https://pinchtab.com/app", "https://example.com/file.pdf", true},
+ {"non http current page", "about:blank", "https://pinchtab.com/file.pdf", true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateTabScopedDownloadURL(tt.currentURL, tt.requestURL)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("validateTabScopedDownloadURL(%q, %q) error = %v, wantErr %v", tt.currentURL, tt.requestURL, err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestParseContentLengthHeader(t *testing.T) {
+ headers := network.Headers{
+ "Content-Length": "12345",
+ }
+ size, ok := parseContentLengthHeader(headers)
+ if !ok || size != 12345 {
+ t.Fatalf("parseContentLengthHeader() = (%d, %v), want (12345, true)", size, ok)
+ }
+}
+
+func TestHandleDownload_TabLocked(t *testing.T) {
+ originalResolver := resolveDownloadHostIPs
+ t.Cleanup(func() {
+ resolveDownloadHostIPs = originalResolver
+ })
+ resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ switch host {
+ case "pinchtab.com":
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ default:
+ return nil, errors.New("not found")
+ }
+ }
+
+ b := &downloadPolicyBridge{
+ lock: &bridge.LockInfo{
+ Owner: "alice",
+ ExpiresAt: time.Now().Add(time.Minute),
+ },
+ }
+ h := New(b, &config.RuntimeConfig{AllowDownload: true}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/download?tabId=tab1&url=https://pinchtab.com/file.txt", nil)
+ w := httptest.NewRecorder()
+ h.HandleDownload(w, req)
+ if w.Code != http.StatusLocked {
+ t.Fatalf("expected 423 for locked tab, got %d", w.Code)
+ }
+}
+
+func TestHandleDownload_TabScopedCrossOriginBlockedForCookieAuth(t *testing.T) {
+ originalResolver := resolveDownloadHostIPs
+ t.Cleanup(func() {
+ resolveDownloadHostIPs = originalResolver
+ })
+ resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ switch host {
+ case "pinchtab.com", "example.com":
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ default:
+ return nil, errors.New("not found")
+ }
+ }
+
+ b := &downloadPolicyBridge{
+ hasState: true,
+ policy: bridge.TabPolicyState{
+ CurrentURL: "https://pinchtab.com/app",
+ UpdatedAt: time.Now(),
+ },
+ }
+ h := New(b, &config.RuntimeConfig{
+ AllowDownload: true,
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"pinchtab.com"},
+ },
+ }, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/download?tabId=tab1&url=https://example.com/file.txt", nil)
+ req.AddCookie(&http.Cookie{Name: "pinchtab_auth_token", Value: "session"})
+ w := httptest.NewRecorder()
+ h.HandleDownload(w, req)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403 for cross-origin tab-scoped download, got %d", w.Code)
+ }
+}
+
+func TestHandleDownload_TabScopedCrossOriginAllowedForHeaderAuth(t *testing.T) {
+ originalResolver := resolveDownloadHostIPs
+ t.Cleanup(func() {
+ resolveDownloadHostIPs = originalResolver
+ })
+ resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ switch host {
+ case "pinchtab.com", "example.com":
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ default:
+ return nil, errors.New("not found")
+ }
+ }
+
+ b := &downloadPolicyBridge{
+ hasState: true,
+ policy: bridge.TabPolicyState{
+ CurrentURL: "https://pinchtab.com/app",
+ UpdatedAt: time.Now(),
+ },
+ }
+ h := New(b, &config.RuntimeConfig{
+ AllowDownload: true,
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"pinchtab.com"},
+ },
+ }, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/download?tabId=tab1&url=https://example.com/file.txt", nil)
+ req.Header.Set("Authorization", "Bearer test-token")
+ w := httptest.NewRecorder()
+ h.HandleDownload(w, req)
+ if w.Code == http.StatusForbidden && strings.Contains(w.Body.String(), "download_scope_forbidden") {
+ t.Fatalf("expected header-auth tab-scoped download to bypass same-origin scope check, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
func TestDownloadRequestGuard_TracksRedirectLimits(t *testing.T) {
originalResolver := resolveDownloadHostIPs
t.Cleanup(func() {
@@ -170,9 +395,40 @@ func TestDownloadRequestGuard_TracksRedirectLimits(t *testing.T) {
}
}
- guard := newDownloadRequestGuard(newDownloadURLGuard(), 0)
+ guard := newDownloadRequestGuard(newDownloadURLGuard(nil), 0)
err := guard.Validate("https://pinchtab.com/redirected", true)
if !errors.Is(err, bridge.ErrTooManyRedirects) {
t.Fatalf("expected too-many-redirects error, got %v", err)
}
}
+
+func TestHandleDownload_RejectsURLOutsideAllowedDomains(t *testing.T) {
+ originalResolver := resolveDownloadHostIPs
+ t.Cleanup(func() {
+ resolveDownloadHostIPs = originalResolver
+ })
+ resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ switch host {
+ case "pinchtab.com", "example.com":
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ default:
+ return nil, errors.New("not found")
+ }
+ }
+
+ h := New(&mockBridge{}, &config.RuntimeConfig{
+ AllowDownload: true,
+ DownloadAllowedDomains: []string{"pinchtab.com"},
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/download?url=https://example.com/file.txt", nil)
+ w := httptest.NewRecorder()
+ h.HandleDownload(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for URL outside allowlist, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "downloadAllowedDomains") {
+ t.Fatalf("expected allowlist error in response, got %s", w.Body.String())
+ }
+}
diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.go
index 3de88392..44ad3971 100644
--- a/internal/handlers/evaluate.go
+++ b/internal/handlers/evaluate.go
@@ -11,7 +11,7 @@ import (
"net/http"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (h *Handlers) evaluateEnabled() bool {
@@ -23,7 +23,7 @@ func (h *Handlers) evaluateEnabled() bool {
// @Endpoint POST /evaluate
func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
if !h.evaluateEnabled() {
- web.ErrorCode(w, 403, "evaluate_disabled", web.DisabledEndpointMessage("evaluate", "security.allowEvaluate"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "evaluate_disabled", httpx.DisabledEndpointMessage("evaluate", "security.allowEvaluate"), false, map[string]any{
"setting": "security.allowEvaluate",
})
return
@@ -34,23 +34,26 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
Expression string `json:"expression"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.Expression == "" {
- web.Error(w, 400, fmt.Errorf("expression required"))
+ httpx.Error(w, 400, fmt.Errorf("expression required"))
return
}
- ctx, _, err := h.Bridge.TabContext(req.TabID)
+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
slog.Warn("evaluate",
"tabId", req.TabID,
@@ -60,11 +63,11 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
var result any
if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {
- web.Error(w, 500, fmt.Errorf("evaluate: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("evaluate: %w", err))
return
}
- web.JSON(w, 200, map[string]any{"result": result})
+ httpx.JSON(w, 200, map[string]any{"result": result})
}
// HandleTabEvaluate runs JavaScript in a tab identified by path ID.
@@ -72,7 +75,7 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
// @Endpoint POST /tabs/{id}/evaluate
func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
if !h.evaluateEnabled() {
- web.ErrorCode(w, 403, "evaluate_disabled", web.DisabledEndpointMessage("evaluate", "security.allowEvaluate"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "evaluate_disabled", httpx.DisabledEndpointMessage("evaluate", "security.allowEvaluate"), false, map[string]any{
"setting": "security.allowEvaluate",
})
return
@@ -80,23 +83,23 @@ func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
body := map[string]any{}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if rawTabID, ok := body["tabId"]; ok {
if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
return
} else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
}
@@ -105,7 +108,7 @@ func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(body)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
diff --git a/internal/handlers/find.go b/internal/handlers/find.go
index 47dd832b..4e2b3295 100644
--- a/internal/handlers/find.go
+++ b/internal/handlers/find.go
@@ -10,9 +10,9 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/idpi"
"github.com/pinchtab/pinchtab/internal/semantic"
- "github.com/pinchtab/pinchtab/internal/web"
)
type findRequest struct {
@@ -55,13 +55,13 @@ type findResponse struct {
// @Response 500 application/json Snapshot or matching error
func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
var req findRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
@@ -71,7 +71,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
req.Query = strings.TrimSpace(req.Query)
if req.Query == "" {
- web.Error(w, 400, fmt.Errorf("missing required field 'query'"))
+ httpx.Error(w, 400, fmt.Errorf("missing required field 'query'"))
return
}
if req.Threshold <= 0 {
@@ -83,9 +83,12 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
// Resolve tab context to get the resolved ID for cache lookup.
// Keep ctxTab so we can reuse it for CDP operations (e.g. auto-refresh).
- ctxTab, resolvedTabID, err := h.Bridge.TabContext(req.TabID)
+ ctxTab, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctxTab, resolvedTabID); !ok {
return
}
@@ -99,7 +102,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
nodes = h.resolveSnapshotNodes(resolvedTabID)
}
if len(nodes) == 0 {
- web.Error(w, 500, fmt.Errorf("no elements found in snapshot for tab %s — navigate first", resolvedTabID))
+ httpx.Error(w, 500, fmt.Errorf("no elements found in snapshot for tab %s — navigate first", resolvedTabID))
return
}
@@ -147,7 +150,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
if corpus := sb.String(); corpus != "" {
if ir := idpi.ScanContent(corpus, h.Config.IDPI); ir.Threat {
if ir.Blocked {
- web.Error(w, http.StatusForbidden, fmt.Errorf("idpi: %s", ir.Reason))
+ httpx.Error(w, http.StatusForbidden, fmt.Errorf("idpi: %s", ir.Reason))
return
}
w.Header().Set("X-IDPI-Warning", ir.Reason)
@@ -168,7 +171,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
Explain: req.Explain,
})
if err != nil {
- web.Error(w, 500, fmt.Errorf("matcher error: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("matcher error: %w", err))
return
}
@@ -207,7 +210,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
})
}
- web.JSON(w, 200, resp)
+ httpx.JSON(w, 200, resp)
}
// resolveSnapshotNodes returns cached A11yNodes for the tab, or an empty
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 76ba4f1b..5cd930ee 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -11,7 +11,7 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/dashboard"
"github.com/pinchtab/pinchtab/internal/engine"
- "github.com/pinchtab/pinchtab/internal/idutil"
+ "github.com/pinchtab/pinchtab/internal/ids"
"github.com/pinchtab/pinchtab/internal/semantic"
)
@@ -21,7 +21,7 @@ type Handlers struct {
Profiles bridge.ProfileService
Dashboard *dashboard.Dashboard
Orchestrator bridge.OrchestratorService
- IdMgr *idutil.Manager
+ IdMgr *ids.Manager
Matcher semantic.ElementMatcher
IntentCache *semantic.IntentCache
Recovery *semantic.RecoveryEngine
@@ -38,7 +38,7 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,
Profiles: p,
Dashboard: d,
Orchestrator: o,
- IdMgr: idutil.NewManager(),
+ IdMgr: ids.NewManager(),
Matcher: matcher,
IntentCache: intentCache,
}
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index c5fc8858..f72fdf3e 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -18,7 +18,8 @@ import (
type mockBridge struct {
bridge.BridgeAPI
- failTab bool
+ failTab bool
+ createTabURLs []string
}
func (m *mockBridge) TabContext(tabID string) (context.Context, string, error) {
@@ -44,6 +45,7 @@ func (m *mockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.
}
func (m *mockBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
+ m.createTabURLs = append(m.createTabURLs, url)
ctx, cancel := chromedp.NewContext(context.Background())
return "tab_abc12345", ctx, cancel, nil
}
@@ -202,10 +204,18 @@ func TestHandleNavigate(t *testing.T) {
if w.Code != 400 {
t.Errorf("expected 400 for missing url, got %d", w.Code)
}
+
+ if len(m.createTabURLs) == 0 {
+ t.Fatalf("expected CreateTab to be called for new-tab navigate")
+ }
+ if m.createTabURLs[0] != "" {
+ t.Fatalf("expected HandleNavigate to create a blank tab first, got %q", m.createTabURLs[0])
+ }
}
func TestHandleTab(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ m := &mockBridge{}
+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
// New Tab
body := `{"action": "new", "url": "about:blank"}`
@@ -215,6 +225,12 @@ func TestHandleTab(t *testing.T) {
if w.Code != 200 && w.Code != 500 {
t.Errorf("unexpected status %d", w.Code)
}
+ if len(m.createTabURLs) == 0 {
+ t.Fatalf("expected CreateTab to be called for action=new")
+ }
+ if m.createTabURLs[0] != "" {
+ t.Fatalf("expected HandleTab to create a blank tab first, got %q", m.createTabURLs[0])
+ }
// Close Tab
body = `{"action": "close", "tabId": "tab1"}`
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
index fd65cb3f..b6add1d5 100644
--- a/internal/handlers/health_tabs.go
+++ b/internal/handlers/health_tabs.go
@@ -6,25 +6,25 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {
// Guard against nil Bridge
if h.Bridge == nil {
- web.JSON(w, 503, map[string]any{"status": "error", "reason": "bridge not initialized"})
+ httpx.JSON(w, 503, map[string]any{"status": "error", "reason": "bridge not initialized"})
return
}
// Ensure Chrome is initialized before checking health
if err := h.ensureChrome(); err != nil {
- web.JSON(w, 503, map[string]any{"status": "error", "reason": fmt.Sprintf("chrome initialization failed: %v", err)})
+ httpx.JSON(w, 503, map[string]any{"status": "error", "reason": fmt.Sprintf("chrome initialization failed: %v", err)})
return
}
targets, err := h.Bridge.ListTargets()
if err != nil {
- web.JSON(w, 503, map[string]any{"status": "error", "reason": err.Error()})
+ httpx.JSON(w, 503, map[string]any{"status": "error", "reason": err.Error()})
return
}
@@ -41,16 +41,16 @@ func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {
resp["crashes"] = bridge.CrashSnapshot()
}
- web.JSON(w, 200, resp)
+ httpx.JSON(w, 200, resp)
}
func (h *Handlers) HandleEnsureChrome(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized for this instance
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization failed: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization failed: %w", err))
return
}
- web.JSON(w, 200, map[string]string{"status": "chrome_ready"})
+ httpx.JSON(w, 200, map[string]string{"status": "chrome_ready"})
}
func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) {
@@ -69,40 +69,40 @@ func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) {
}
}
- web.JSON(w, 200, result)
+ httpx.JSON(w, 200, result)
}
func (h *Handlers) HandleTabMetrics(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("missing tab id"))
+ httpx.Error(w, 400, fmt.Errorf("missing tab id"))
return
}
if h.Bridge == nil {
- web.Error(w, 503, fmt.Errorf("bridge not initialized"))
+ httpx.Error(w, 503, fmt.Errorf("bridge not initialized"))
return
}
mem, err := h.Bridge.GetMemoryMetrics(tabID)
if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to get metrics: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("failed to get metrics: %w", err))
return
}
- web.JSON(w, 200, mem)
+ httpx.JSON(w, 200, mem)
}
func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
// Guard against nil Bridge
if h.Bridge == nil {
- web.Error(w, 503, fmt.Errorf("bridge not initialized"))
+ httpx.Error(w, 503, fmt.Errorf("bridge not initialized"))
return
}
targets, err := h.Bridge.ListTargets()
if err != nil {
- web.Error(w, 503, err)
+ httpx.Error(w, 503, err)
return
}
@@ -121,5 +121,5 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
}
tabs = append(tabs, entry)
}
- web.JSON(w, 200, map[string]any{"tabs": tabs})
+ httpx.JSON(w, 200, map[string]any{"tabs": tabs})
}
diff --git a/internal/handlers/help.go b/internal/handlers/help.go
index 59bd8008..8fbe3067 100644
--- a/internal/handlers/help.go
+++ b/internal/handlers/help.go
@@ -3,12 +3,12 @@ package handlers
import (
"net/http"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (h *Handlers) HandleHelp(wr http.ResponseWriter, _ *http.Request) {
security := h.endpointSecurityStates()
- web.JSON(wr, 200, map[string]any{
+ httpx.JSON(wr, 200, map[string]any{
"name": "pinchtab",
"endpoints": map[string]any{
"GET /health": "health status",
diff --git a/internal/handlers/lock_shutdown.go b/internal/handlers/lock_shutdown.go
index b49d6427..89096744 100644
--- a/internal/handlers/lock_shutdown.go
+++ b/internal/handlers/lock_shutdown.go
@@ -10,8 +10,9 @@ import (
"net/http"
"time"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (h *Handlers) HandleTabLock(w http.ResponseWriter, r *http.Request) {
@@ -21,11 +22,11 @@ func (h *Handlers) HandleTabLock(w http.ResponseWriter, r *http.Request) {
TimeoutSec int `json:"timeoutSec"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.TabID == "" || req.Owner == "" {
- web.Error(w, 400, fmt.Errorf("tabId and owner required"))
+ httpx.Error(w, 400, fmt.Errorf("tabId and owner required"))
return
}
@@ -35,12 +36,12 @@ func (h *Handlers) HandleTabLock(w http.ResponseWriter, r *http.Request) {
}
if err := h.Bridge.Lock(req.TabID, req.Owner, timeout); err != nil {
- web.Error(w, 409, err)
+ httpx.Error(w, 409, err)
return
}
lock := h.Bridge.TabLockInfo(req.TabID)
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"locked": true,
"owner": lock.Owner,
"expiresAt": lock.ExpiresAt.Format(time.RFC3339),
@@ -53,20 +54,20 @@ func (h *Handlers) HandleTabUnlock(w http.ResponseWriter, r *http.Request) {
Owner string `json:"owner"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.TabID == "" || req.Owner == "" {
- web.Error(w, 400, fmt.Errorf("tabId and owner required"))
+ httpx.Error(w, 400, fmt.Errorf("tabId and owner required"))
return
}
if err := h.Bridge.Unlock(req.TabID, req.Owner); err != nil {
- web.Error(w, 409, err)
+ httpx.Error(w, 409, err)
return
}
- web.JSON(w, 200, map[string]any{"unlocked": true})
+ httpx.JSON(w, 200, map[string]any{"unlocked": true})
}
// HandleTabLockByID locks a tab identified by path ID.
@@ -75,23 +76,23 @@ func (h *Handlers) HandleTabUnlock(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabLockByID(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
body := map[string]any{}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if rawTabID, ok := body["tabId"]; ok {
if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
return
} else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
}
@@ -100,7 +101,7 @@ func (h *Handlers) HandleTabLockByID(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(body)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -118,23 +119,23 @@ func (h *Handlers) HandleTabLockByID(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabUnlockByID(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
body := map[string]any{}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if rawTabID, ok := body["tabId"]; ok {
if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
return
} else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
}
@@ -143,7 +144,7 @@ func (h *Handlers) HandleTabUnlockByID(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(body)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -158,7 +159,8 @@ func (h *Handlers) HandleTabUnlockByID(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
slog.Info("shutdown requested via API")
- web.JSON(w, 200, map[string]any{"status": "shutting down"})
+ authn.AuditLog(r, "system.shutdown_requested")
+ httpx.JSON(w, 200, map[string]any{"status": "shutting down"})
go func() {
time.Sleep(100 * time.Millisecond)
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 8c272236..53b409c7 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -5,15 +5,16 @@ import (
"crypto/subtle"
"encoding/hex"
"log/slog"
- "net"
"net/http"
+ "net/url"
"strings"
"sync"
"sync/atomic"
"time"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
var (
@@ -27,7 +28,7 @@ var (
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
- sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
+ sw := &httpx.StatusWriter{ResponseWriter: w, Code: 200}
next.ServeHTTP(sw, r)
ms := uint64(time.Since(start).Milliseconds())
atomic.AddUint64(&metricRequestsTotal, 1)
@@ -54,35 +55,66 @@ func LoggingMiddleware(next http.Handler) http.Handler {
}
func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
+ return AuthMiddlewareWithSessions(cfg, nil, next)
+}
+
+func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.SessionManager, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if isPublicDashboardPath(r.URL.Path) {
+ if isPublicDashboardPath(r.URL.Path) || isPublicAuthPath(r.URL.Path) {
next.ServeHTTP(w, r)
return
}
- if cfg.Token != "" {
- auth := r.Header.Get("Authorization")
- qToken := r.URL.Query().Get("token")
+ token := strings.TrimSpace(cfg.Token)
+ if token == "" {
+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)
+ return
+ }
- if auth == "" && qToken == "" {
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
- web.ErrorCode(w, 401, "missing_token", "unauthorized", false, nil)
+ creds := authn.CredentialsFromRequest(r)
+ if creds.Value == "" {
+ authn.ClearSessionCookie(w, r)
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
+ httpx.ErrorCode(w, 401, "missing_token", "unauthorized", false, nil)
+ return
+ }
+
+ switch creds.Method {
+ case authn.MethodHeader:
+ if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {
+ authn.ClearSessionCookie(w, r)
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
+ httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
return
}
-
- provided := strings.TrimPrefix(auth, "Bearer ")
- if provided == auth { // "Bearer " prefix was not present
- if qToken != "" {
- provided = qToken
- } else {
- provided = auth
- }
+ case authn.MethodCookie:
+ if !cookieOriginAllowed(r) {
+ httpx.ErrorCode(w, http.StatusForbidden, "origin_forbidden", "same-origin browser request required for session authentication", false, map[string]any{
+ "sameOriginRequired": true,
+ })
+ return
}
-
- if subtle.ConstantTimeCompare([]byte(provided), []byte(cfg.Token)) != 1 {
+ if sessions == nil || !sessions.Validate(creds.Value, token) {
+ authn.ClearSessionCookie(w, r)
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- web.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
+ httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
+ return
+ }
+ if !cookieAuthAllowed(r) {
+ httpx.ErrorCode(w, 403, "header_auth_required", "authorization header required for this endpoint", false, nil)
+ return
+ }
+ if cookieElevationRequired(r) && !sessions.IsElevated(creds.Value, token) {
+ authn.AuditWarn(r, "auth.elevation_required", "elevationWindowSec", int(sessions.ElevationWindow().Seconds()))
+ httpx.ErrorCode(w, 403, "elevation_required", "re-enter API token to continue", false, map[string]any{
+ "elevationWindowSec": int(sessions.ElevationWindow().Seconds()),
+ })
return
}
+ default:
+ authn.ClearSessionCookie(w, r)
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
+ httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
+ return
}
next.ServeHTTP(w, r)
})
@@ -96,12 +128,87 @@ func isPublicDashboardPath(path string) bool {
return strings.HasPrefix(path, "/dashboard/") || path == "/dashboard/favicon.png"
}
-func CorsMiddleware(next http.Handler) http.Handler {
+func isPublicAuthPath(path string) bool {
+ switch path {
+ case "/api/auth/login", "/api/auth/logout":
+ return true
+ default:
+ return false
+ }
+}
+
+func cookieAuthAllowed(r *http.Request) bool {
+ path := strings.TrimSpace(r.URL.Path)
+ switch r.Method {
+ case http.MethodGet:
+ switch {
+ case path == "/health",
+ path == "/metrics",
+ path == "/api/activity",
+ path == "/api/events",
+ path == "/api/config",
+ path == "/profiles",
+ path == "/instances",
+ path == "/instances/tabs",
+ path == "/instances/metrics":
+ return true
+ case strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/tabs"),
+ strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/logs"),
+ strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/logs/stream"),
+ strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/proxy/screencast"),
+ strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, "/screenshot"),
+ strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, "/pdf"):
+ return true
+ }
+ case http.MethodPost:
+ switch {
+ case path == "/api/auth/elevate":
+ return true
+ case path == "/instances/launch":
+ return true
+ case strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/stop"):
+ return true
+ case path == "/profiles":
+ return true
+ }
+ case http.MethodPut:
+ return path == "/api/config"
+ case http.MethodPatch:
+ return strings.HasPrefix(path, "/profiles/")
+ case http.MethodDelete:
+ return strings.HasPrefix(path, "/profiles/")
+ }
+ return false
+}
+
+func cookieElevationRequired(r *http.Request) bool {
+ path := strings.TrimSpace(r.URL.Path)
+ switch r.Method {
+ case http.MethodPut:
+ return path == "/api/config"
+ case http.MethodPost:
+ return path == "/shutdown"
+ }
+ return false
+}
+
+func CorsMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ allowedOrigin := corsAllowedOrigin(cfg, r)
+ if allowedOrigin != "" {
+ w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
+ if allowedOrigin != "*" {
+ w.Header().Set("Access-Control-Allow-Credentials", "true")
+ w.Header().Add("Vary", "Origin")
+ }
+ }
+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if r.Method == "OPTIONS" {
+ if strings.TrimSpace(r.Header.Get("Origin")) != "" && allowedOrigin == "" && strings.TrimSpace(cfg.Token) != "" {
+ httpx.ErrorCode(w, 403, "cors_forbidden", "cross-origin requests are disabled when auth is enabled", false, nil)
+ return
+ }
w.WriteHeader(204)
return
}
@@ -109,6 +216,67 @@ func CorsMiddleware(next http.Handler) http.Handler {
})
}
+func corsAllowedOrigin(cfg *config.RuntimeConfig, r *http.Request) string {
+ origin := strings.TrimSpace(r.Header.Get("Origin"))
+ if origin == "" {
+ return ""
+ }
+ if strings.TrimSpace(cfg.Token) == "" {
+ return "*"
+ }
+ if sameOriginRequest(origin, r) {
+ return origin
+ }
+ return ""
+}
+
+func sameOriginRequest(origin string, r *http.Request) bool {
+ parsed, err := url.Parse(origin)
+ if err != nil || parsed.Scheme == "" || parsed.Host == "" {
+ return false
+ }
+ return strings.EqualFold(parsed.Scheme, requestScheme(r)) && strings.EqualFold(parsed.Host, requestHost(r))
+}
+
+func cookieOriginAllowed(r *http.Request) bool {
+ if isWebSocketUpgrade(r) {
+ origin := strings.TrimSpace(r.Header.Get("Origin"))
+ return origin != "" && sameOriginRequest(origin, r)
+ }
+
+ if origin := strings.TrimSpace(r.Header.Get("Origin")); origin != "" {
+ return sameOriginRequest(origin, r)
+ }
+ if referer := strings.TrimSpace(r.Header.Get("Referer")); referer != "" {
+ return sameOriginRequest(referer, r)
+ }
+ return false
+}
+
+func isWebSocketUpgrade(r *http.Request) bool {
+ if r == nil {
+ return false
+ }
+ if !strings.EqualFold(strings.TrimSpace(r.Header.Get("Upgrade")), "websocket") {
+ return false
+ }
+ return strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade")
+}
+
+func requestScheme(r *http.Request) string {
+ if r != nil && r.TLS != nil {
+ return "https"
+ }
+ return "http"
+}
+
+func requestHost(r *http.Request) string {
+ if r == nil {
+ return ""
+ }
+ return strings.TrimSpace(r.Host)
+}
+
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rid := r.Header.Get("X-Request-Id")
@@ -118,6 +286,7 @@ func RequestIDMiddleware(next http.Handler) http.Handler {
rid = hex.EncodeToString(b)
}
w.Header().Set("X-Request-Id", rid)
+ r.Header.Set("X-Request-Id", rid)
next.ServeHTTP(w, r)
})
}
@@ -142,13 +311,7 @@ func RateLimitMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
return
}
- host, _, _ := net.SplitHostPort(r.RemoteAddr)
- if host == "" {
- host = r.RemoteAddr
- }
- if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
- host = strings.TrimSpace(strings.Split(xff, ",")[0])
- }
+ host := authn.ClientIP(r)
now := time.Now()
rateMu.Lock()
@@ -163,7 +326,7 @@ func RateLimitMiddleware(next http.Handler) http.Handler {
rateBuckets[host] = filtered
rateMu.Unlock()
atomic.AddUint64(&metricRateLimited, 1)
- web.ErrorCode(w, 429, "rate_limited", "too many requests", true, map[string]any{"windowSec": int(rateLimitWindow.Seconds()), "max": rateLimitMaxReq})
+ httpx.ErrorCode(w, 429, "rate_limited", "too many requests", true, map[string]any{"windowSec": int(rateLimitWindow.Seconds()), "max": rateLimitMaxReq})
return
}
rateBuckets[host] = append(filtered, now)
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index 76b9265c..781f6d08 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -6,8 +6,9 @@ import (
"testing"
"time"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func TestAuthMiddleware_NoToken(t *testing.T) {
@@ -23,8 +24,11 @@ func TestAuthMiddleware_NoToken(t *testing.T) {
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
- if !called {
- t.Error("handler should have been called")
+ if called {
+ t.Error("handler should NOT have been called when token is missing")
+ }
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("expected 503 when token is missing, got %d", w.Code)
}
}
@@ -90,6 +94,307 @@ func TestAuthMiddleware_MissingTokenHeader(t *testing.T) {
}
}
+func TestAuthMiddleware_ValidCookie(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/health", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Referer", "http://example.com/dashboard")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should have been called with valid cookie auth")
+ }
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieRestrictedEndpointRejected(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/evaluate", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should not allow cookie auth on restricted endpoint")
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Origin", "https://evil.example")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should not allow cross-origin cookie auth")
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieRequestWithoutOriginOrRefererRejected(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should not allow cookie auth without same-origin headers")
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieSameOriginRefererAccepted(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Referer", "http://example.com/dashboard")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow same-origin cookie-authenticated request with referer")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieIgnoresForwardedOriginHints(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ req.Host = "127.0.0.1:9867"
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Origin", "https://pinchtab.example")
+ req.Header.Set("X-Forwarded-Proto", "https")
+ req.Header.Set("X-Forwarded-Host", "pinchtab.example")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should ignore forwarded host/proto headers for cookie same-origin checks")
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieWebSocketRequiresSameOrigin(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/instances/inst1/proxy/screencast", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should not allow cookie-authenticated websocket upgrade without an Origin header")
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
+ }
+
+ called = false
+ req = httptest.NewRequest(http.MethodGet, "/instances/inst1/proxy/screencast", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ req.Header.Set("Origin", "http://example.com")
+ w = httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow same-origin cookie-authenticated websocket upgrade")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodPut, "/api/config", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Referer", "http://example.com/dashboard")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should not allow elevated endpoint without elevation")
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
+ }
+
+ if !sessions.Elevate(sessionID, cfg.Token) {
+ t.Fatal("expected session elevation to succeed in test setup")
+ }
+
+ called = false
+ req = httptest.NewRequest(http.MethodPut, "/api/config", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Referer", "http://example.com/dashboard")
+ w = httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow elevated endpoint with elevation")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_HeaderAllowsRestrictedEndpoint(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ called := false
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/evaluate", nil)
+ req.Header.Set("Authorization", "Bearer secret123")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow header auth on restricted endpoint")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_QueryTokenRejected(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+
+ called := false
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/test?token=secret123", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if called {
+ t.Fatal("handler should not accept query-string tokens")
+ }
+ if w.Code != 401 {
+ t.Fatalf("expected 401, got %d", w.Code)
+ }
+}
+
func TestAuthMiddleware_PublicDashboardPathBypassesAuth(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret123"}
called := false
@@ -130,6 +435,26 @@ func TestAuthMiddleware_PublicDashboardSubpathBypassesAuth(t *testing.T) {
}
}
+func TestAuthMiddleware_PublicAuthPathBypassesAuth(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ called := false
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("POST", "/api/auth/login", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should have been called for public auth path")
+ }
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
func TestAuthMiddleware_ProtectedAPIStillRequiresAuth(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret123"}
handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -158,8 +483,9 @@ func TestAuthMiddleware_TableDriven(t *testing.T) {
{"partial match", "secret", "Bearer secre", 401, false},
{"empty bearer", "secret", "Bearer ", 401, false},
{"missing header", "secret", "", 401, false},
- {"no token configured", "", "", 200, true},
- {"no token configured with header", "", "Bearer anything", 200, true},
+ {"query token rejected", "secret", "", 401, false},
+ {"no token configured", "", "", http.StatusServiceUnavailable, false},
+ {"no token configured with header", "", "Bearer anything", http.StatusServiceUnavailable, false},
}
for _, tt := range tests {
@@ -172,6 +498,9 @@ func TestAuthMiddleware_TableDriven(t *testing.T) {
}))
req := httptest.NewRequest("GET", "/test", nil)
+ if tt.name == "query token rejected" {
+ req = httptest.NewRequest("GET", "/test?token=secret", nil)
+ }
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
@@ -189,11 +518,12 @@ func TestAuthMiddleware_TableDriven(t *testing.T) {
}
func TestCorsMiddleware(t *testing.T) {
- handler := CorsMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := CorsMiddleware(&config.RuntimeConfig{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
req := httptest.NewRequest("OPTIONS", "/test", nil)
+ req.Header.Set("Origin", "https://evil.example")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != 204 {
@@ -204,6 +534,7 @@ func TestCorsMiddleware(t *testing.T) {
}
req = httptest.NewRequest("GET", "/test", nil)
+ req.Header.Set("Origin", "https://evil.example")
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != 200 {
@@ -214,6 +545,47 @@ func TestCorsMiddleware(t *testing.T) {
}
}
+func TestCorsMiddleware_AuthEnabledAllowsOnlySameOrigin(t *testing.T) {
+ handler := CorsMiddleware(&config.RuntimeConfig{Token: "secret"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("OPTIONS", "/test", nil)
+ req.Host = "pinchtab.test"
+ req.Header.Set("Origin", "http://pinchtab.test")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != 204 {
+ t.Fatalf("OPTIONS expected 204, got %d", w.Code)
+ }
+ if got := w.Header().Get("Access-Control-Allow-Origin"); got != "http://pinchtab.test" {
+ t.Fatalf("Access-Control-Allow-Origin = %q, want same origin", got)
+ }
+ if got := w.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
+ t.Fatalf("Access-Control-Allow-Credentials = %q, want true", got)
+ }
+}
+
+func TestCorsMiddleware_AuthEnabledRejectsCrossOriginPreflight(t *testing.T) {
+ handler := CorsMiddleware(&config.RuntimeConfig{Token: "secret"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("OPTIONS", "/test", nil)
+ req.Host = "pinchtab.test"
+ req.Header.Set("Origin", "https://evil.example")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("OPTIONS expected 403, got %d", w.Code)
+ }
+ if got := w.Header().Get("Access-Control-Allow-Origin"); got != "" {
+ t.Fatalf("Access-Control-Allow-Origin = %q, want empty", got)
+ }
+}
+
func TestLoggingMiddleware(t *testing.T) {
resetObservabilityForTests()
handler := LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -328,7 +700,7 @@ func TestEvictStaleRateBuckets_DeletesEmptyHosts(t *testing.T) {
func TestStatusWriter(t *testing.T) {
w := httptest.NewRecorder()
- sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
+ sw := &httpx.StatusWriter{ResponseWriter: w, Code: 200}
sw.WriteHeader(404)
if sw.Code != 404 {
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index 0be292b1..e88ad581 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -17,8 +17,8 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/engine"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/idpi"
- "github.com/pinchtab/pinchtab/internal/web"
)
const maxBodySize = 1 << 20
@@ -86,13 +86,13 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
}
} else {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
}
if req.URL == "" {
- web.Error(w, 400, fmt.Errorf("url required"))
+ httpx.Error(w, 400, fmt.Errorf("url required"))
return
}
h.recordNavigateRequest(r, req.TabID, req.URL)
@@ -102,11 +102,11 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
h.recordEngine(r, "lite")
result, err := h.Router.Lite().Navigate(r.Context(), req.URL)
if err != nil {
- web.Error(w, 502, fmt.Errorf("lite navigate: %w", err))
+ httpx.Error(w, 502, fmt.Errorf("lite navigate: %w", err))
return
}
w.Header().Set("X-Engine", "lite")
- web.JSON(w, 200, map[string]any{"tabId": result.TabID, "url": result.URL, "title": result.Title})
+ httpx.JSON(w, 200, map[string]any{"tabId": result.TabID, "url": result.URL, "title": result.Title})
return
}
@@ -167,27 +167,28 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
if parsed, err := url.Parse(req.URL); err == nil && parsed.Scheme != "" {
blocked := parsed.Scheme == "javascript" || parsed.Scheme == "vbscript" || parsed.Scheme == "data"
if blocked {
- web.Error(w, 400, fmt.Errorf("invalid URL scheme: %s", parsed.Scheme))
+ httpx.Error(w, 400, fmt.Errorf("invalid URL scheme: %s", parsed.Scheme))
return
}
}
// IDPI: block or warn on non-whitelisted domains before the tab opens.
if result := idpi.CheckDomain(req.URL, h.Config.IDPI); result.Blocked {
- web.Error(w, http.StatusForbidden, fmt.Errorf("navigation blocked by IDPI: %s", result.Reason))
+ httpx.Error(w, http.StatusForbidden, fmt.Errorf("navigation blocked by IDPI: %s", result.Reason))
return
} else if result.Threat {
w.Header().Set("X-IDPI-Warning", result.Reason)
}
- // CreateTab returns hash-based tab ID directly (e.g., "tab_XXXXXXXX")
- hashTabID, newCtx, _, err := h.Bridge.CreateTab(req.URL)
+ // Create a blank tab first so the requested URL becomes the first
+ // real history entry.
+ hashTabID, newCtx, _, err := h.Bridge.CreateTab("")
if err != nil {
- web.Error(w, 500, fmt.Errorf("new tab: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("new tab: %w", err))
return
}
tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
if len(blockPatterns) > 0 {
_ = bridge.SetResourceBlocking(tCtx, blockPatterns)
@@ -201,12 +202,12 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
} else if strings.Contains(errMsg, "invalid URL") || strings.Contains(errMsg, "Cannot navigate to invalid URL") || strings.Contains(errMsg, "ERR_INVALID_URL") {
code = 400
}
- web.Error(w, code, fmt.Errorf("navigate: %w", err))
+ httpx.Error(w, code, fmt.Errorf("navigate: %w", err))
return
}
if err := h.waitForNavigationState(tCtx, req.WaitFor, req.WaitSelector); err != nil {
- web.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)
+ httpx.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)
return
}
@@ -216,19 +217,19 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
h.recordResolvedTab(r, hashTabID)
h.recordResolvedURL(r, url)
- web.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": url, "title": title})
+ httpx.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": url, "title": title})
return
}
ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
// IDPI: domain whitelist check also applies when re-navigating an existing tab.
if result := idpi.CheckDomain(req.URL, h.Config.IDPI); result.Blocked {
- web.Error(w, http.StatusForbidden, fmt.Errorf("navigation blocked by IDPI: %s", result.Reason))
+ httpx.Error(w, http.StatusForbidden, fmt.Errorf("navigation blocked by IDPI: %s", result.Reason))
return
} else if result.Threat {
w.Header().Set("X-IDPI-Warning", result.Reason)
@@ -236,7 +237,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
tCtx, tCancel := context.WithTimeout(ctx, navTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
if len(blockPatterns) > 0 {
_ = bridge.SetResourceBlocking(tCtx, blockPatterns)
} else {
@@ -252,14 +253,14 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
} else if strings.Contains(errMsg, "invalid URL") || strings.Contains(errMsg, "Cannot navigate to invalid URL") || strings.Contains(errMsg, "ERR_INVALID_URL") {
code = 400
}
- web.Error(w, code, fmt.Errorf("navigate: %w", err))
+ httpx.Error(w, code, fmt.Errorf("navigate: %w", err))
return
}
h.Bridge.DeleteRefCache(resolvedTabID)
if err := h.waitForNavigationState(tCtx, req.WaitFor, req.WaitSelector); err != nil {
- web.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)
+ httpx.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)
return
}
@@ -268,7 +269,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
title, _ := bridge.WaitForTitle(tCtx, titleWait)
h.recordResolvedURL(r, url)
- web.JSON(w, 200, map[string]any{"tabId": resolvedTabID, "url": url, "title": title})
+ httpx.JSON(w, 200, map[string]any{"tabId": resolvedTabID, "url": url, "title": title})
}
// HandleTabNavigate navigates an existing tab identified by path ID.
@@ -277,7 +278,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabNavigate(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
@@ -285,17 +286,17 @@ func (h *Handlers) HandleTabNavigate(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&body)
if err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
}
if rawTabID, ok := body["tabId"]; ok {
if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
return
} else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
}
@@ -306,7 +307,7 @@ func (h *Handlers) HandleTabNavigate(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(body)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -372,16 +373,17 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
URL string `json:"url"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
switch req.Action {
case tabActionNew:
- // CreateTab returns hash-based tab ID directly (e.g., "tab_XXXXXXXX")
- hashTabID, ctx, _, err := h.Bridge.CreateTab(req.URL)
+ // Create a blank tab first so the requested URL becomes the first
+ // real history entry.
+ hashTabID, ctx, _, err := h.Bridge.CreateTab("")
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
@@ -394,7 +396,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
if errors.Is(err, bridge.ErrTooManyRedirects) {
code = 422
}
- web.Error(w, code, fmt.Errorf("navigate: %w", err))
+ httpx.Error(w, code, fmt.Errorf("navigate: %w", err))
return
}
}
@@ -402,33 +404,33 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
var curURL, title string
_ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))
- web.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": curURL, "title": title})
+ httpx.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": curURL, "title": title})
case tabActionClose:
if req.TabID == "" {
- web.Error(w, 400, fmt.Errorf("tabId required"))
+ httpx.Error(w, 400, fmt.Errorf("tabId required"))
return
}
if err := h.Bridge.CloseTab(req.TabID); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, map[string]any{"closed": true})
+ httpx.JSON(w, 200, map[string]any{"closed": true})
case "focus":
if req.TabID == "" {
- web.Error(w, 400, fmt.Errorf("tabId required"))
+ httpx.Error(w, 400, fmt.Errorf("tabId required"))
return
}
if err := h.Bridge.FocusTab(req.TabID); err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
- web.JSON(w, 200, map[string]any{"focused": true, "tabId": req.TabID})
+ httpx.JSON(w, 200, map[string]any{"focused": true, "tabId": req.TabID})
default:
- web.Error(w, 400, fmt.Errorf("action must be 'new', 'close', or 'focus'"))
+ httpx.Error(w, 400, fmt.Errorf("action must be 'new', 'close', or 'focus'"))
}
}
@@ -461,7 +463,7 @@ func (h *Handlers) HandleBack(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
ctx, resolvedID, err := h.Bridge.TabContext(tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -479,7 +481,7 @@ func (h *Handlers) HandleBack(w http.ResponseWriter, r *http.Request) {
}
return page.NavigateToHistoryEntry(entries[cur-1].ID).Do(ctx)
})); err != nil {
- web.Error(w, 500, fmt.Errorf("back: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("back: %w", err))
return
}
if !noHistory {
@@ -488,7 +490,7 @@ func (h *Handlers) HandleBack(w http.ResponseWriter, r *http.Request) {
var curURL string
_ = chromedp.Run(ctx, chromedp.Location(&curURL))
- web.JSON(w, 200, map[string]any{"tabId": resolvedID, "url": curURL})
+ httpx.JSON(w, 200, map[string]any{"tabId": resolvedID, "url": curURL})
}
// HandleForward navigates the current (or specified) tab forward in history.
@@ -496,7 +498,7 @@ func (h *Handlers) HandleForward(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
ctx, resolvedID, err := h.Bridge.TabContext(tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -514,7 +516,7 @@ func (h *Handlers) HandleForward(w http.ResponseWriter, r *http.Request) {
}
return page.NavigateToHistoryEntry(entries[cur+1].ID).Do(ctx)
})); err != nil {
- web.Error(w, 500, fmt.Errorf("forward: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("forward: %w", err))
return
}
if !noHistory {
@@ -523,7 +525,7 @@ func (h *Handlers) HandleForward(w http.ResponseWriter, r *http.Request) {
var curURL string
_ = chromedp.Run(ctx, chromedp.Location(&curURL))
- web.JSON(w, 200, map[string]any{"tabId": resolvedID, "url": curURL})
+ httpx.JSON(w, 200, map[string]any{"tabId": resolvedID, "url": curURL})
}
// HandleReload reloads the current (or specified) tab.
@@ -531,19 +533,19 @@ func (h *Handlers) HandleReload(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
ctx, resolvedID, err := h.Bridge.TabContext(tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return page.Reload().Do(ctx)
})); err != nil {
- web.Error(w, 500, fmt.Errorf("reload: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("reload: %w", err))
return
}
// Wait briefly for page to start loading
var curURL string
_ = chromedp.Run(ctx, chromedp.Location(&curURL))
- web.JSON(w, 200, map[string]any{"tabId": resolvedID, "url": curURL})
+ httpx.JSON(w, 200, map[string]any{"tabId": resolvedID, "url": curURL})
}
diff --git a/internal/handlers/network.go b/internal/handlers/network.go
index 5c4ffa58..fe2583c7 100644
--- a/internal/handlers/network.go
+++ b/internal/handlers/network.go
@@ -8,7 +8,7 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// parseBufferSize extracts an optional bufferSize query param. Returns 0 if absent.
@@ -38,20 +38,23 @@ func parseBufferSize(r *http.Request) int {
// @Response 404 application/json Tab not found
func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
tabID := r.URL.Query().Get("tabId")
- tabCtx, resolvedTabID, err := h.Bridge.TabContext(tabID)
+ tabCtx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {
return
}
nm := h.Bridge.NetworkMonitor()
if nm == nil {
- web.JSON(w, 200, map[string]any{"entries": []any{}, "count": 0})
+ httpx.JSON(w, 200, map[string]any{"entries": []any{}, "count": 0})
return
}
@@ -61,7 +64,7 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {
buf := nm.GetBuffer(resolvedTabID)
if buf == nil {
if err := nm.StartCaptureWithSize(tabCtx, resolvedTabID, bufferSize); err != nil {
- web.Error(w, 500, fmt.Errorf("start network capture: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("start network capture: %w", err))
return
}
buf = nm.GetBuffer(resolvedTabID)
@@ -85,7 +88,7 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {
entries = entries[len(entries)-filter.Limit:]
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"entries": entries,
"count": len(entries),
"tabId": resolvedTabID,
@@ -105,38 +108,41 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {
// @Response 404 application/json Request not found
func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
requestID := r.PathValue("requestId")
if requestID == "" {
- web.Error(w, 400, fmt.Errorf("requestId required"))
+ httpx.Error(w, 400, fmt.Errorf("requestId required"))
return
}
tabID := r.URL.Query().Get("tabId")
- tabCtx, resolvedTabID, err := h.Bridge.TabContext(tabID)
+ tabCtx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {
return
}
nm := h.Bridge.NetworkMonitor()
if nm == nil {
- web.Error(w, 404, fmt.Errorf("network monitoring not active"))
+ httpx.Error(w, 404, fmt.Errorf("network monitoring not active"))
return
}
buf := nm.GetBuffer(resolvedTabID)
if buf == nil {
- web.Error(w, 404, fmt.Errorf("no network data for tab %s", resolvedTabID))
+ httpx.Error(w, 404, fmt.Errorf("no network data for tab %s", resolvedTabID))
return
}
entry, ok := buf.Get(requestID)
if !ok {
- web.Error(w, 404, fmt.Errorf("request %s not found", requestID))
+ httpx.Error(w, 404, fmt.Errorf("request %s not found", requestID))
return
}
@@ -156,7 +162,7 @@ func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {
}
}
- web.JSON(w, 200, result)
+ httpx.JSON(w, 200, result)
}
// HandleNetworkClear clears captured network data.
@@ -170,7 +176,7 @@ func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleNetworkClear(w http.ResponseWriter, r *http.Request) {
nm := h.Bridge.NetworkMonitor()
if nm == nil {
- web.JSON(w, 200, map[string]any{"cleared": true})
+ httpx.JSON(w, 200, map[string]any{"cleared": true})
return
}
@@ -178,14 +184,14 @@ func (h *Handlers) HandleNetworkClear(w http.ResponseWriter, r *http.Request) {
if tabID != "" {
_, resolvedTabID, err := h.Bridge.TabContext(tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
nm.ClearTab(resolvedTabID)
- web.JSON(w, 200, map[string]any{"cleared": true, "tabId": resolvedTabID})
+ httpx.JSON(w, 200, map[string]any{"cleared": true, "tabId": resolvedTabID})
} else {
nm.ClearAll()
- web.JSON(w, 200, map[string]any{"cleared": true, "all": true})
+ httpx.JSON(w, 200, map[string]any{"cleared": true, "all": true})
}
}
@@ -214,20 +220,23 @@ func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {
_ = http.NewResponseController(w).SetWriteDeadline(time.Time{})
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
tabID := r.URL.Query().Get("tabId")
- tabCtx, resolvedTabID, err := h.Bridge.TabContext(tabID)
+ tabCtx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {
return
}
nm := h.Bridge.NetworkMonitor()
if nm == nil {
- web.Error(w, 500, fmt.Errorf("network monitoring not available"))
+ httpx.Error(w, 500, fmt.Errorf("network monitoring not available"))
return
}
@@ -237,7 +246,7 @@ func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {
buf := nm.GetBuffer(resolvedTabID)
if buf == nil {
if err := nm.StartCaptureWithSize(tabCtx, resolvedTabID, bufferSize); err != nil {
- web.Error(w, 500, fmt.Errorf("start network capture: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("start network capture: %w", err))
return
}
buf = nm.GetBuffer(resolvedTabID)
@@ -298,7 +307,7 @@ func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabNetwork(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
q := r.URL.Query()
@@ -317,7 +326,7 @@ func (h *Handlers) HandleTabNetworkByID(w http.ResponseWriter, r *http.Request)
tabID := r.PathValue("id")
requestID := r.PathValue("requestId")
if tabID == "" || requestID == "" {
- web.Error(w, 400, fmt.Errorf("tab id and request id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id and request id required"))
return
}
q := r.URL.Query()
@@ -336,7 +345,7 @@ func (h *Handlers) HandleTabNetworkByID(w http.ResponseWriter, r *http.Request)
func (h *Handlers) HandleTabNetworkStream(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
q := r.URL.Query()
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index 8a93763c..3298dabc 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -3,12 +3,12 @@ package handlers
import (
"net/http"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
security := h.endpointSecurityStates()
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"openapi": "3.0.0",
"info": map[string]any{
"title": "Pinchtab API",
diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.go
index 80cf2785..4638c6ed 100644
--- a/internal/handlers/pdf.go
+++ b/internal/handlers/pdf.go
@@ -15,8 +15,8 @@ import (
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/idpi"
- "github.com/pinchtab/pinchtab/internal/web"
)
var pdfQueryParams = map[string]struct{}{
@@ -46,7 +46,7 @@ var pdfQueryParams = map[string]struct{}{
func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
@@ -54,15 +54,18 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
output := r.URL.Query().Get("output")
h.recordReadRequest(r, "pdf", tabID)
- ctx, _, err := h.tabContext(r, tabID)
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
// Parse PDF parameters from PrintToPDFParams
landscape := r.URL.Query().Get("landscape") == "true"
@@ -144,7 +147,7 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
corpus := pageTitle + "\n" + pageURL + "\n" + pageText
if ir := idpi.ScanContent(corpus, h.Config.IDPI); ir.Threat {
if ir.Blocked {
- web.Error(w, http.StatusForbidden, fmt.Errorf("idpi: %s", ir.Reason))
+ httpx.Error(w, http.StatusForbidden, fmt.Errorf("idpi: %s", ir.Reason))
return
}
w.Header().Set("X-IDPI-Warning", ir.Reason)
@@ -187,7 +190,7 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
return err
}),
); err != nil {
- web.Error(w, 500, fmt.Errorf("pdf: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("pdf: %w", err))
return
}
@@ -196,36 +199,36 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
if savePath == "" {
pdfDir := filepath.Join(h.Config.StateDir, "pdfs")
if err := os.MkdirAll(pdfDir, 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("create pdf dir: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("create pdf dir: %w", err))
return
}
timestamp := time.Now().Format("20060102-150405")
savePath = filepath.Join(pdfDir, fmt.Sprintf("page-%s.pdf", timestamp))
} else {
- safe, err := web.SafePath(h.Config.StateDir, savePath)
+ safe, err := httpx.SafeCreatePath(h.Config.StateDir, savePath)
if err != nil {
- web.Error(w, 400, fmt.Errorf("invalid path: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("invalid path: %w", err))
return
}
absBase, _ := filepath.Abs(h.Config.StateDir)
absPath, err := filepath.Abs(safe)
if err != nil || !strings.HasPrefix(absPath, absBase+string(filepath.Separator)) {
- web.Error(w, 400, fmt.Errorf("invalid output path"))
+ httpx.Error(w, 400, fmt.Errorf("invalid output path"))
return
}
savePath = absPath
if err := os.MkdirAll(filepath.Dir(savePath), 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("create dir: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("create dir: %w", err))
return
}
}
if err := os.WriteFile(savePath, buf, 0600); err != nil {
- web.Error(w, 500, fmt.Errorf("write pdf: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("write pdf: %w", err))
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"path": savePath,
"size": len(buf),
})
@@ -240,7 +243,7 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"format": "pdf",
"base64": base64.StdEncoding.EncodeToString(buf),
})
@@ -253,7 +256,7 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
@@ -262,7 +265,7 @@ func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
var body map[string]any
if r.ContentLength > 0 {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&body); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
for key, value := range body {
@@ -277,7 +280,7 @@ func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
case float64:
q.Set(key, strconv.FormatFloat(v, 'f', -1, 64))
default:
- web.Error(w, 400, fmt.Errorf("invalid %s type", key))
+ httpx.Error(w, 400, fmt.Errorf("invalid %s type", key))
return
}
}
diff --git a/internal/handlers/screencast.go b/internal/handlers/screencast.go
index c4081317..e7c6a0eb 100644
--- a/internal/handlers/screencast.go
+++ b/internal/handlers/screencast.go
@@ -13,14 +13,14 @@ import (
"github.com/chromedp/chromedp"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// HandleScreencast upgrades to WebSocket and streams screencast frames for a tab.
// Query params: tabId (required), quality (1-100, default 40), maxWidth (default 800), fps (1-30, default 5)
func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
- web.ErrorCode(w, 403, "screencast_disabled", web.DisabledEndpointMessage("screencast", "security.allowScreencast"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "screencast_disabled", httpx.DisabledEndpointMessage("screencast", "security.allowScreencast"), false, map[string]any{
"setting": "security.allowScreencast",
})
return
@@ -33,11 +33,14 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
}
}
- ctx, _, err := h.Bridge.TabContext(tabID)
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
http.Error(w, "tab not found", 404)
return
}
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
+ return
+ }
quality := queryParamInt(r, "quality", 30)
maxWidth := queryParamInt(r, "maxWidth", 800)
@@ -106,7 +109,7 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
}),
)
if err != nil {
- slog.Error("start screencast failed", "err", err, "tab", tabID)
+ slog.Error("start screencast failed", "err", err, "tab", resolvedTabID)
return
}
@@ -119,7 +122,7 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
)
}()
- slog.Info("screencast started", "tab", tabID, "quality", quality, "maxWidth", maxWidth)
+ slog.Info("screencast started", "tab", resolvedTabID, "quality", quality, "maxWidth", maxWidth)
go func() {
for {
@@ -150,7 +153,7 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
// HandleScreencastAll returns info for building a multi-tab screencast view.
func (h *Handlers) HandleScreencastAll(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
- web.ErrorCode(w, 403, "screencast_disabled", web.DisabledEndpointMessage("screencast", "security.allowScreencast"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "screencast_disabled", httpx.DisabledEndpointMessage("screencast", "security.allowScreencast"), false, map[string]any{
"setting": "security.allowScreencast",
})
return
@@ -163,7 +166,7 @@ func (h *Handlers) HandleScreencastAll(w http.ResponseWriter, r *http.Request) {
targets, err := h.Bridge.ListTargets()
if err != nil {
- web.JSON(w, 200, []tabInfo{})
+ httpx.JSON(w, 200, []tabInfo{})
return
}
@@ -176,7 +179,7 @@ func (h *Handlers) HandleScreencastAll(w http.ResponseWriter, r *http.Request) {
})
}
- web.JSON(w, 200, tabs)
+ httpx.JSON(w, 200, tabs)
}
func queryParamInt(r *http.Request, key string, def int) int {
diff --git a/internal/handlers/screencast_test.go b/internal/handlers/screencast_test.go
index c39d5286..8a58f839 100644
--- a/internal/handlers/screencast_test.go
+++ b/internal/handlers/screencast_test.go
@@ -5,6 +5,7 @@ import (
"net/http/httptest"
"testing"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -26,7 +27,9 @@ func TestHandleScreencast_AuthRejectsWrongToken(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret-token-123", AllowScreencast: true}
h := New(&mockBridge{}, cfg, nil, nil, nil)
- req := httptest.NewRequest("GET", "/screencast?token=wrong-token", nil)
+ req := httptest.NewRequest("GET", "/screencast", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: "wrong-token"})
+ req.Header.Set("Referer", "http://example.com/dashboard")
w := httptest.NewRecorder()
handler := AuthMiddleware(cfg, http.HandlerFunc(h.HandleScreencast))
handler.ServeHTTP(w, req)
@@ -51,20 +54,17 @@ func TestHandleScreencast_AuthRejectsWrongHeader(t *testing.T) {
}
}
-func TestHandleScreencast_NoTokenConfigSkipsAuth(t *testing.T) {
+func TestHandleScreencast_NoTokenConfigRejectsRequest(t *testing.T) {
cfg := &config.RuntimeConfig{} // No token configured
h := New(&mockBridge{failTab: true}, cfg, nil, nil, nil)
- // With no token configured, auth is skipped. The handler will then
- // fail at TabContext (failTab=true) and return 404 — proving auth
- // didn't block the request.
req := httptest.NewRequest("GET", "/screencast", nil)
w := httptest.NewRecorder()
handler := AuthMiddleware(cfg, http.HandlerFunc(h.HandleScreencast))
handler.ServeHTTP(w, req)
- if w.Code == http.StatusUnauthorized {
- t.Errorf("should not get 401 when no token is configured, got %d", w.Code)
+ if w.Code != http.StatusServiceUnavailable {
+ t.Errorf("expected 503 when no token is configured, got %d", w.Code)
}
}
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index e125988a..1b9ab9c9 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -14,7 +14,7 @@ import (
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// HandleScreenshot captures a screenshot of the current tab.
@@ -23,7 +23,7 @@ import (
func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
@@ -31,19 +31,22 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
output := r.URL.Query().Get("output")
reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
- ctx, _, err := h.Bridge.TabContext(tabID)
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
if reqNoAnim && !h.Config.NoAnimations {
if err := bridge.DisableAnimationsOnce(tCtx); err != nil {
- web.Error(w, 500, fmt.Errorf("disable animations: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("disable animations: %w", err))
return
}
}
@@ -77,14 +80,14 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
return err
}),
); err != nil {
- web.Error(w, 500, fmt.Errorf("screenshot: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("screenshot: %w", err))
return
}
if output == "file" {
screenshotDir := filepath.Join(h.Config.StateDir, "screenshots")
if err := os.MkdirAll(screenshotDir, 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("create screenshot dir: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("create screenshot dir: %w", err))
return
}
@@ -93,11 +96,11 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
filePath := filepath.Join(screenshotDir, filename)
if err := os.WriteFile(filePath, buf, 0600); err != nil {
- web.Error(w, 500, fmt.Errorf("write screenshot: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("write screenshot: %w", err))
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"path": filePath,
"size": len(buf),
"format": string(format),
@@ -114,7 +117,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"format": string(format),
"base64": base64.StdEncoding.EncodeToString(buf),
})
@@ -126,7 +129,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabScreenshot(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index 8edee09c..071ccbed 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -1,6 +1,6 @@
package handlers
-import "github.com/pinchtab/pinchtab/internal/web"
+import "github.com/pinchtab/pinchtab/internal/httpx"
type endpointSecurityState struct {
Enabled bool `json:"enabled"`
@@ -30,31 +30,31 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
"evaluate": {
Enabled: h.evaluateEnabled(),
Setting: "security.allowEvaluate",
- Message: web.DisabledEndpointMessage("evaluate", "security.allowEvaluate"),
+ Message: httpx.DisabledEndpointMessage("evaluate", "security.allowEvaluate"),
Paths: []string{"POST /evaluate", "POST /tabs/{id}/evaluate"},
},
"macro": {
Enabled: h.macroEnabled(),
Setting: "security.allowMacro",
- Message: web.DisabledEndpointMessage("macro", "security.allowMacro"),
+ Message: httpx.DisabledEndpointMessage("macro", "security.allowMacro"),
Paths: []string{"POST /macro"},
},
"screencast": {
Enabled: h.screencastEnabled(),
Setting: "security.allowScreencast",
- Message: web.DisabledEndpointMessage("screencast", "security.allowScreencast"),
+ Message: httpx.DisabledEndpointMessage("screencast", "security.allowScreencast"),
Paths: []string{"GET /screencast", "GET /screencast/tabs", "GET /instances/{id}/screencast", "GET /instances/{id}/proxy/screencast"},
},
"download": {
Enabled: h.downloadEnabled(),
Setting: "security.allowDownload",
- Message: web.DisabledEndpointMessage("download", "security.allowDownload"),
+ Message: httpx.DisabledEndpointMessage("download", "security.allowDownload"),
Paths: []string{"GET /download", "GET /tabs/{id}/download"},
},
"upload": {
Enabled: h.uploadEnabled(),
Setting: "security.allowUpload",
- Message: web.DisabledEndpointMessage("upload", "security.allowUpload"),
+ Message: httpx.DisabledEndpointMessage("upload", "security.allowUpload"),
Paths: []string{"POST /upload", "POST /tabs/{id}/upload"},
},
}
diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.go
index 829ef57b..a9ba1663 100644
--- a/internal/handlers/snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -14,8 +14,8 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/engine"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/idpi"
- "github.com/pinchtab/pinchtab/internal/web"
"gopkg.in/yaml.v3"
)
@@ -69,7 +69,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
h.recordEngine(r, "lite")
nodes, err := h.Router.Lite().Snapshot(r.Context(), tabID, filter)
if err != nil {
- web.Error(w, 500, fmt.Errorf("lite snapshot: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("lite snapshot: %w", err))
return
}
// Convert to bridge.A11yNode for API compatibility.
@@ -78,13 +78,13 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
flat[i] = bridge.A11yNode{Ref: n.Ref, Role: n.Role, Name: n.Name, Depth: n.Depth, Value: n.Value}
}
w.Header().Set("X-Engine", "lite")
- web.JSON(w, 200, map[string]any{"nodes": flat})
+ httpx.JSON(w, 200, map[string]any{"nodes": flat})
return
}
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
@@ -112,23 +112,26 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
if reqNoAnim && !h.Config.NoAnimations {
if err := bridge.DisableAnimationsOnce(tCtx); err != nil {
- web.Error(w, 500, fmt.Errorf("disable animations: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("disable animations: %w", err))
return
}
}
nodes, err := bridge.FetchAXTree(tCtx)
if err != nil {
- web.Error(w, 500, fmt.Errorf("a11y tree: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("a11y tree: %w", err))
return
}
treeResp := struct {
@@ -156,7 +159,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
if scopeErr != nil {
- web.Error(w, 400, fmt.Errorf("selector: %w", scopeErr))
+ httpx.Error(w, 400, fmt.Errorf("selector: %w", scopeErr))
return
}
@@ -208,7 +211,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
idpiResult = idpi.ScanContent(sb.String(), h.Config.IDPI)
if idpiResult.Blocked {
- web.Error(w, http.StatusForbidden,
+ httpx.Error(w, http.StatusForbidden,
fmt.Errorf("snapshot blocked by IDPI scanner: %s", idpiResult.Reason))
return
}
@@ -223,7 +226,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if output == "file" {
snapshotDir := filepath.Join(h.Config.StateDir, "snapshots")
if err := os.MkdirAll(snapshotDir, 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("create snapshot dir: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("create snapshot dir: %w", err))
return
}
@@ -263,7 +266,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
var err error
content, err = yaml.Marshal(data)
if err != nil {
- web.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
return
}
default:
@@ -291,36 +294,36 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
var err error
content, err = json.MarshalIndent(data, "", " ")
if err != nil {
- web.Error(w, 500, fmt.Errorf("marshal snapshot: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("marshal snapshot: %w", err))
return
}
}
filePath := filepath.Join(snapshotDir, filename)
if outputPath != "" {
- safe, err := web.SafePath(h.Config.StateDir, outputPath)
+ safe, err := httpx.SafeCreatePath(h.Config.StateDir, outputPath)
if err != nil {
- web.Error(w, 400, fmt.Errorf("invalid path: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("invalid path: %w", err))
return
}
absBase, _ := filepath.Abs(h.Config.StateDir)
absPath, err := filepath.Abs(safe)
if err != nil || !strings.HasPrefix(absPath, absBase+string(filepath.Separator)) {
- web.Error(w, 400, fmt.Errorf("invalid output path"))
+ httpx.Error(w, 400, fmt.Errorf("invalid output path"))
return
}
filePath = absPath
if err := os.MkdirAll(filepath.Dir(filePath), 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("create output dir: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("create output dir: %w", err))
return
}
}
if err := os.WriteFile(filePath, content, 0600); err != nil {
- web.Error(w, 500, fmt.Errorf("write snapshot: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("write snapshot: %w", err))
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"path": filePath,
"size": len(content),
"format": format,
@@ -331,7 +334,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if doDiff && prevNodes != nil {
added, changed, removed := bridge.DiffSnapshot(prevNodes, flat)
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"url": url,
"title": title,
"diff": true,
@@ -372,7 +375,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
yamlContent, err := yaml.Marshal(data)
if err != nil {
- web.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
return
}
w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
@@ -392,7 +395,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if idpiResult.Threat {
resp["idpiWarning"] = idpiResult.Reason
}
- web.JSON(w, 200, resp)
+ httpx.JSON(w, 200, resp)
}
}
@@ -402,7 +405,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabSnapshot(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
diff --git a/internal/handlers/stealth.go b/internal/handlers/stealth.go
index 5d3575b6..2e92c3a3 100644
--- a/internal/handlers/stealth.go
+++ b/internal/handlers/stealth.go
@@ -12,7 +12,7 @@ import (
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
type fingerprintRequest struct {
@@ -31,13 +31,16 @@ type fingerprintRequest struct {
func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Request) {
var req fingerprintRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
- ctx, _, err := h.Bridge.TabContext(req.TabID)
+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
@@ -58,7 +61,7 @@ func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Reques
return nil
}),
); err != nil {
- web.Error(w, 500, fmt.Errorf("CDP UA override: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("CDP UA override: %w", err))
return
}
@@ -84,7 +87,7 @@ func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Reques
slog.Warn("JS fingerprint extras failed", "err", err)
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"fingerprint": fp,
"status": "rotated",
})
diff --git a/internal/handlers/tab_policy.go b/internal/handlers/tab_policy.go
new file mode 100644
index 00000000..3b276665
--- /dev/null
+++ b/internal/handlers/tab_policy.go
@@ -0,0 +1,77 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+const cachedTabPolicyTTL = 1 * time.Second
+
+type tabPolicyStateProvider interface {
+ GetTabPolicyState(tabID string) (bridge.TabPolicyState, bool)
+}
+
+type tabPolicyStateSetter interface {
+ SetTabPolicyState(tabID string, state bridge.TabPolicyState)
+}
+
+func (h *Handlers) currentTabDomainPolicyEnabled() bool {
+ return h != nil &&
+ h.Config != nil &&
+ h.Config.IDPI.Enabled &&
+ len(h.Config.IDPI.AllowedDomains) > 0
+}
+
+func (h *Handlers) enforceCurrentTabDomainPolicy(w http.ResponseWriter, r *http.Request, ctx context.Context, tabID string) (string, bool) {
+ if !h.currentTabDomainPolicyEnabled() {
+ return "", true
+ }
+
+ if provider, ok := h.Bridge.(tabPolicyStateProvider); ok {
+ if state, ok := provider.GetTabPolicyState(tabID); ok && !state.UpdatedAt.IsZero() {
+ if state.CurrentURL != "" {
+ h.recordResolvedURL(r, state.CurrentURL)
+ }
+ if time.Since(state.UpdatedAt) <= cachedTabPolicyTTL {
+ return h.applyTabPolicyState(w, state)
+ }
+ }
+ }
+
+ lookupCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+
+ var currentURL string
+ if err := chromedp.Run(lookupCtx, chromedp.Location(&currentURL)); err != nil {
+ httpx.Error(w, 500, fmt.Errorf("resolve current tab url: %w", err))
+ return "", false
+ }
+
+ state := bridge.EvaluateTabPolicy(currentURL, h.Config.IDPI)
+ if setter, ok := h.Bridge.(tabPolicyStateSetter); ok {
+ setter.SetTabPolicyState(tabID, state)
+ }
+ h.recordResolvedURL(r, currentURL)
+
+ return h.applyTabPolicyState(w, state)
+}
+
+func (h *Handlers) applyTabPolicyState(w http.ResponseWriter, state bridge.TabPolicyState) (string, bool) {
+ if state.Threat {
+ w.Header().Set("X-IDPI-Warning", state.Reason)
+ }
+ if state.Blocked {
+ httpx.ErrorCode(w, http.StatusForbidden, "idpi_domain_blocked",
+ fmt.Sprintf("current tab blocked by IDPI: %s", state.Reason), false, map[string]any{
+ "url": state.CurrentURL,
+ })
+ return state.CurrentURL, false
+ }
+ return state.CurrentURL, true
+}
diff --git a/internal/handlers/tab_policy_test.go b/internal/handlers/tab_policy_test.go
new file mode 100644
index 00000000..8c4ac027
--- /dev/null
+++ b/internal/handlers/tab_policy_test.go
@@ -0,0 +1,138 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type policyMockBridge struct {
+ mockBridge
+ state bridge.TabPolicyState
+ hasState bool
+ actionExecuted bool
+}
+
+func (m *policyMockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
+ m.actionExecuted = true
+ return map[string]any{"success": true}, nil
+}
+
+func (m *policyMockBridge) GetTabPolicyState(tabID string) (bridge.TabPolicyState, bool) {
+ return m.state, m.hasState
+}
+
+func (m *policyMockBridge) SetTabPolicyState(tabID string, state bridge.TabPolicyState) {
+ m.state = state
+ m.hasState = true
+}
+
+func TestHandleActionBlocksWhenCachedTabPolicyIsBlocked(t *testing.T) {
+ b := &policyMockBridge{
+ state: bridge.TabPolicyState{
+ CurrentURL: "https://evil.example.net",
+ Threat: true,
+ Blocked: true,
+ Reason: `domain "evil.example.net" is not in the allowed list`,
+ UpdatedAt: time.Now(),
+ },
+ hasState: true,
+ }
+ h := New(b, &config.RuntimeConfig{
+ ActionTimeout: time.Second,
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"example.com"},
+ StrictMode: true,
+ },
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/action", bytes.NewBufferString(`{"tabId":"tab1","kind":"click"}`))
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+
+ if w.Code != 403 {
+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ if b.actionExecuted {
+ t.Fatal("expected action execution to be skipped")
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp["code"] != "idpi_domain_blocked" {
+ t.Fatalf("expected idpi_domain_blocked code, got %v", resp["code"])
+ }
+}
+
+func TestHandleActionWarnsWhenCachedTabPolicyIsThreatOnly(t *testing.T) {
+ b := &policyMockBridge{
+ state: bridge.TabPolicyState{
+ CurrentURL: "https://warn.example.net",
+ Threat: true,
+ Blocked: false,
+ Reason: `domain "warn.example.net" is not in the allowed list`,
+ UpdatedAt: time.Now(),
+ },
+ hasState: true,
+ }
+ h := New(b, &config.RuntimeConfig{
+ ActionTimeout: time.Second,
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"example.com"},
+ StrictMode: false,
+ },
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/action", bytes.NewBufferString(`{"tabId":"tab1","kind":"click"}`))
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get("X-IDPI-Warning"); got == "" {
+ t.Fatal("expected X-IDPI-Warning header")
+ }
+ if !b.actionExecuted {
+ t.Fatal("expected action execution to continue in warn mode")
+ }
+}
+
+func TestHandleBackIgnoresCachedTabPolicyBlock(t *testing.T) {
+ b := &policyMockBridge{
+ state: bridge.TabPolicyState{
+ CurrentURL: "https://evil.example.net",
+ Threat: true,
+ Blocked: true,
+ Reason: `domain "evil.example.net" is not in the allowed list`,
+ UpdatedAt: time.Now(),
+ },
+ hasState: true,
+ }
+ h := New(b, &config.RuntimeConfig{
+ ActionTimeout: time.Second,
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"example.com"},
+ StrictMode: true,
+ },
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/back?tabId=tab1", nil)
+ w := httptest.NewRecorder()
+ h.HandleBack(w, req)
+
+ if w.Code == 403 {
+ t.Fatalf("expected back to bypass current-tab policy enforcement, got %d: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
index 7e675d5c..6fa9cd63 100644
--- a/internal/handlers/text.go
+++ b/internal/handlers/text.go
@@ -10,8 +10,8 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/assets"
"github.com/pinchtab/pinchtab/internal/engine"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/idpi"
- "github.com/pinchtab/pinchtab/internal/web"
)
// HandleText extracts readable text from the current tab.
@@ -25,7 +25,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
h.recordEngine(r, "lite")
text, err := h.Router.Lite().Text(r.Context(), tabID)
if err != nil {
- web.Error(w, 500, fmt.Errorf("lite text: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("lite text: %w", err))
return
}
w.Header().Set("X-Engine", "lite")
@@ -36,7 +36,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
return
}
@@ -49,29 +49,32 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
}
}
- ctx, _, err := h.tabContext(r, tabID)
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
var text string
if mode == "raw" {
if err := chromedp.Run(tCtx,
chromedp.Evaluate(`document.body.innerText`, &text),
); err != nil {
- web.Error(w, 500, fmt.Errorf("text extract: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("text extract: %w", err))
return
}
} else {
if err := chromedp.Run(tCtx,
chromedp.Evaluate(assets.ReadabilityJS, &text),
); err != nil {
- web.Error(w, 500, fmt.Errorf("text extract: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("text extract: %w", err))
return
}
}
@@ -94,7 +97,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
if h.Config.IDPI.Enabled && h.Config.IDPI.ScanContent {
idpiResult = idpi.ScanContent(text, h.Config.IDPI)
if idpiResult.Blocked {
- web.Error(w, http.StatusForbidden,
+ httpx.Error(w, http.StatusForbidden,
fmt.Errorf("content blocked by IDPI scanner: %s", idpiResult.Reason))
return
}
@@ -128,7 +131,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
if idpiResult.Threat {
resp["idpiWarning"] = idpiResult.Reason
}
- web.JSON(w, 200, resp)
+ httpx.JSON(w, 200, resp)
}
// HandleTabText extracts text for a tab identified by path ID.
@@ -137,7 +140,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabText(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
diff --git a/internal/handlers/upload.go b/internal/handlers/upload.go
index a5305f06..f72fb387 100644
--- a/internal/handlers/upload.go
+++ b/internal/handlers/upload.go
@@ -14,7 +14,7 @@ import (
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
type uploadRequest struct {
@@ -23,6 +23,10 @@ type uploadRequest struct {
Paths []string `json:"paths"`
}
+const (
+ uploadSandboxDirName = "uploads"
+)
+
// HandleUpload sets files on an <input type="file"> element via CDP.
//
// POST /upload?tabId=<id>
@@ -30,25 +34,30 @@ type uploadRequest struct {
// {
// "selector": "input[type=file]", // unified selector: CSS, XPath, text, ref, or semantic
// "files": ["data:image/png;base64,...", "base64:..."],
-// "paths": ["/tmp/photo.jpg"]
+// "paths": ["uploads/photo.jpg"]
// }
//
-// Either "files" (base64 data) or "paths" (local file paths) must be provided.
-// Both can be combined. Files are written to a temp dir and passed to CDP.
+// Either "files" (base64 data) or "paths" (relative sandbox paths) must be
+// provided. Both can be combined. Files are written to a temp dir and passed to
+// CDP. Path-based uploads are limited to StateDir/uploads/.
func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowUpload {
- web.ErrorCode(w, 403, "upload_disabled", web.DisabledEndpointMessage("upload", "security.allowUpload"), false, map[string]any{
+ httpx.ErrorCode(w, 403, "upload_disabled", httpx.DisabledEndpointMessage("upload", "security.allowUpload"), false, map[string]any{
"setting": "security.allowUpload",
})
return
}
tabID := r.URL.Query().Get("tabId")
+ maxRequestBytes := h.Config.EffectiveUploadMaxRequestBytes()
+ maxFiles := h.Config.EffectiveUploadMaxFiles()
+ maxFileBytes := h.Config.EffectiveUploadMaxFileBytes()
+ maxTotalBytes := h.Config.EffectiveUploadMaxTotalBytes()
- r.Body = http.MaxBytesReader(w, r.Body, 10<<20) // 10MB limit
+ r.Body = http.MaxBytesReader(w, r.Body, int64(maxRequestBytes))
var req uploadRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON body: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON body: %w", err))
return
}
@@ -57,29 +66,28 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
}
if len(req.Files) == 0 && len(req.Paths) == 0 {
- web.Error(w, 400, fmt.Errorf("either 'files' (base64) or 'paths' (local paths) required"))
+ httpx.Error(w, 400, fmt.Errorf("either 'files' (base64) or 'paths' (sandbox paths) required"))
+ return
+ }
+ if len(req.Files)+len(req.Paths) > maxFiles {
+ httpx.Error(w, 400, fmt.Errorf("too many files: max %d", maxFiles))
return
}
- // Validate local paths stay within the allowed StateDir.
- absBase, _ := filepath.Abs(h.Config.StateDir)
+ uploadBase := filepath.Join(h.Config.StateDir, uploadSandboxDirName)
+ var totalBytes int64
for i, p := range req.Paths {
- safe, err := web.SafePath(h.Config.StateDir, p)
+ safe, size, err := validateUploadSandboxPath(uploadBase, p, maxFileBytes)
if err != nil {
- web.Error(w, 400, fmt.Errorf("invalid path: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("invalid path: %w", err))
return
}
- // Inline sanitizer: CodeQL recognizes filepath.Abs + strings.HasPrefix.
- absPath, err := filepath.Abs(safe)
- if err != nil || !strings.HasPrefix(absPath, absBase+string(filepath.Separator)) {
- web.Error(w, 400, fmt.Errorf("path %q escapes allowed directory", p))
+ totalBytes += size
+ if totalBytes > int64(maxTotalBytes) {
+ httpx.Error(w, 400, fmt.Errorf("upload payload too large: max %d bytes total", maxTotalBytes))
return
}
- if _, err := os.Stat(absPath); err != nil {
- web.Error(w, 400, fmt.Errorf("file not found: %s", absPath))
- return
- }
- req.Paths[i] = absPath
+ req.Paths[i] = safe
}
// Decode base64 files to temp dir.
@@ -87,7 +95,7 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
if len(req.Files) > 0 {
tmpDir, err := os.MkdirTemp("", "pinchtab-upload-*")
if err != nil {
- web.Error(w, 500, fmt.Errorf("create temp dir: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("create temp dir: %w", err))
return
}
defer func() { _ = os.RemoveAll(tmpDir) }()
@@ -95,12 +103,21 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
for i, f := range req.Files {
data, ext, err := decodeFileData(f)
if err != nil {
- web.Error(w, 400, fmt.Errorf("file[%d]: %w", i, err))
+ httpx.Error(w, 400, fmt.Errorf("file[%d]: %w", i, err))
+ return
+ }
+ if len(data) > maxFileBytes {
+ httpx.Error(w, 400, fmt.Errorf("file[%d] exceeds max size %d bytes", i, maxFileBytes))
+ return
+ }
+ totalBytes += int64(len(data))
+ if totalBytes > int64(maxTotalBytes) {
+ httpx.Error(w, 400, fmt.Errorf("upload payload too large: max %d bytes total", maxTotalBytes))
return
}
path := fmt.Sprintf("%s/upload-%d%s", tmpDir, i, ext)
- if err := os.WriteFile(path, data, 0644); err != nil {
- web.Error(w, 500, fmt.Errorf("write temp file: %w", err))
+ if err := os.WriteFile(path, data, 0600); err != nil {
+ httpx.Error(w, 500, fmt.Errorf("write temp file: %w", err))
return
}
tempFiles = append(tempFiles, path)
@@ -109,15 +126,23 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
allPaths := append(tempFiles, req.Paths...)
- ctx, _, err := h.Bridge.TabContext(tabID)
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ owner := resolveOwner(r, "")
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ httpx.ErrorCode(w, http.StatusLocked, "tab_locked", err.Error(), false, nil)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
// Find the file input node and set files via CDP.
if err := chromedp.Run(tCtx,
@@ -130,11 +155,11 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
return dom.SetFileInputFiles(allPaths).WithNodeID(nodeID).Do(ctx)
}),
); err != nil {
- web.Error(w, 500, fmt.Errorf("upload: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("upload: %w", err))
return
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"status": "ok",
"files": len(allPaths),
})
@@ -146,7 +171,7 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabUpload(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
@@ -197,6 +222,34 @@ func resolveSelector(ctx context.Context, sel string) (cdp.NodeID, error) {
return node, nil
}
+func validateUploadSandboxPath(baseDir, rawPath string, maxFileBytes int) (string, int64, error) {
+ normalized := normalizeUploadSandboxPath(rawPath)
+ safe, err := httpx.SafeExistingPath(baseDir, normalized)
+ if err != nil {
+ return "", 0, err
+ }
+ info, err := os.Lstat(safe)
+ if err != nil {
+ return "", 0, fmt.Errorf("file not found: %s", safe)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return "", 0, fmt.Errorf("symlinks are not allowed: %s", rawPath)
+ }
+ if !info.Mode().IsRegular() {
+ return "", 0, fmt.Errorf("path must reference a regular file: %s", rawPath)
+ }
+ if info.Size() > int64(maxFileBytes) {
+ return "", 0, fmt.Errorf("file exceeds max size %d bytes: %s", maxFileBytes, rawPath)
+ }
+ return safe, info.Size(), nil
+}
+
+func normalizeUploadSandboxPath(rawPath string) string {
+ trimmed := filepath.ToSlash(strings.TrimSpace(rawPath))
+ trimmed = strings.TrimPrefix(trimmed, uploadSandboxDirName+"/")
+ return filepath.FromSlash(trimmed)
+}
+
// decodeFileData handles "data:mime;base64,..." and raw base64 strings.
// Returns decoded bytes and a file extension guess.
func decodeFileData(input string) ([]byte, string, error) {
diff --git a/internal/handlers/upload_test.go b/internal/handlers/upload_test.go
index 63618427..d048f183 100644
--- a/internal/handlers/upload_test.go
+++ b/internal/handlers/upload_test.go
@@ -2,14 +2,28 @@ package handlers
import (
"bytes"
+ "encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"testing"
+ "time"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
)
+type uploadLockBridge struct {
+ mockBridge
+ lock *bridge.LockInfo
+}
+
+func (m *uploadLockBridge) TabLockInfo(tabID string) *bridge.LockInfo {
+ return m.lock
+}
+
func TestHandleUpload_BadJSON(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowUpload: true}, nil, nil, nil)
req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte("not json")))
@@ -72,6 +86,123 @@ func TestHandleUpload_PathTraversal(t *testing.T) {
}
}
+func TestHandleUpload_AllowsUploadSandboxPath(t *testing.T) {
+ tmpDir := t.TempDir()
+ uploadsDir := filepath.Join(tmpDir, "uploads")
+ if err := os.MkdirAll(uploadsDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(uploadsDir, "test.txt"), []byte("hello"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{AllowUpload: true, StateDir: tmpDir}, nil, nil, nil)
+ body := `{"selector": "input[type=file]", "paths": ["uploads/test.txt"]}`
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected sandbox path validation to pass and tab lookup to fail, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_RejectsSymlinkedUploadSandboxPath(t *testing.T) {
+ tmpDir := t.TempDir()
+ uploadsDir := filepath.Join(tmpDir, "uploads")
+ outsideDir := t.TempDir()
+ if err := os.MkdirAll(uploadsDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(outsideDir, "secret.txt"), []byte("hello"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outsideDir, filepath.Join(uploadsDir, "linked")); err != nil {
+ t.Skipf("symlink unsupported in test environment: %v", err)
+ }
+
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{AllowUpload: true, StateDir: tmpDir}, nil, nil, nil)
+ body := `{"selector": "input[type=file]", "paths": ["uploads/linked/secret.txt"]}`
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected symlinked sandbox path to be rejected, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_RejectsTooManyFiles(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowUpload: true}, nil, nil, nil)
+
+ var body bytes.Buffer
+ body.WriteString(`{"files":[`)
+ for i := 0; i < config.DefaultUploadMaxFiles+1; i++ {
+ if i > 0 {
+ body.WriteByte(',')
+ }
+ body.WriteString(`"aGVsbG8="`)
+ }
+ body.WriteString(`]}`)
+
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader(body.Bytes()))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for too many files, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_RejectsDecodedFileTooLarge(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowUpload: true}, nil, nil, nil)
+ large := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte("a"), config.DefaultUploadMaxFileBytes+1))
+ body := fmt.Sprintf(`{"files": ["%s"]}`, large)
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for oversized decoded file, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_UsesConfiguredUploadLimits(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{
+ AllowUpload: true,
+ UploadMaxFiles: 1,
+ UploadMaxFileBytes: 4,
+ UploadMaxTotalBytes: 4,
+ }, nil, nil, nil)
+
+ body := `{"files":["aGVsbG8="]}`
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for configured file size limit, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_TabLocked(t *testing.T) {
+ h := New(&uploadLockBridge{
+ lock: &bridge.LockInfo{
+ Owner: "alice",
+ ExpiresAt: time.Now().Add(time.Minute),
+ },
+ }, &config.RuntimeConfig{AllowUpload: true}, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/upload?tabId=tab1", bytes.NewReader([]byte(`{"files":["aGVsbG8="]}`)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+
+ if w.Code != http.StatusLocked {
+ t.Fatalf("expected 423 for locked tab, got %d", w.Code)
+ }
+}
+
func TestHandleTabUpload_MissingTabID(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowUpload: true}, nil, nil, nil)
req := httptest.NewRequest("POST", "/tabs//upload", bytes.NewReader([]byte(`{"selector":"input[type=file]"}`)))
diff --git a/internal/handlers/wait.go b/internal/handlers/wait.go
index 7f240a67..91449622 100644
--- a/internal/handlers/wait.go
+++ b/internal/handlers/wait.go
@@ -11,7 +11,7 @@ import (
"time"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
const (
@@ -81,7 +81,7 @@ func (wr *waitRequest) resolvedTimeout() time.Duration {
func (h *Handlers) HandleWait(w http.ResponseWriter, r *http.Request) {
var req waitRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
@@ -94,23 +94,23 @@ func (h *Handlers) HandleWait(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleTabWait(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
body := map[string]any{}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if rawTabID, ok := body["tabId"]; ok {
if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
return
} else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return
}
}
@@ -119,7 +119,7 @@ func (h *Handlers) HandleTabWait(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(body)
if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
return
}
@@ -136,7 +136,7 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa
mode := req.mode()
if mode == "" {
- web.Error(w, 400, fmt.Errorf("one of selector, text, url, load, fn, or ms is required"))
+ httpx.Error(w, 400, fmt.Errorf("one of selector, text, url, load, fn, or ms is required"))
return
}
@@ -151,13 +151,13 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa
}
select {
case <-time.After(time.Duration(ms) * time.Millisecond):
- web.JSON(w, 200, waitResponse{
+ httpx.JSON(w, 200, waitResponse{
Waited: true,
Elapsed: time.Since(start).Milliseconds(),
Match: fmt.Sprintf("%dms", ms),
})
case <-r.Context().Done():
- web.JSON(w, 200, waitResponse{
+ httpx.JSON(w, 200, waitResponse{
Waited: false,
Elapsed: time.Since(start).Milliseconds(),
Error: "cancelled",
@@ -167,16 +167,19 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa
}
// All other modes need a browser tab.
- ctx, _, err := h.Bridge.TabContext(req.TabID)
+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
timeout := req.resolvedTimeout()
tCtx, tCancel := context.WithTimeout(ctx, timeout)
defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
var js string
var matchLabel string
@@ -195,7 +198,7 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa
js = `document.readyState === 'complete'`
matchLabel = "networkidle"
} else {
- web.Error(w, 400, fmt.Errorf("unsupported load state: %s (supported: networkidle)", req.Load))
+ httpx.Error(w, 400, fmt.Errorf("unsupported load state: %s (supported: networkidle)", req.Load))
return
}
case "fn":
@@ -208,7 +211,7 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa
var result bool
evalErr := chromedp.Run(tCtx, chromedp.Evaluate(js, &result))
if evalErr == nil && result {
- web.JSON(w, 200, waitResponse{
+ httpx.JSON(w, 200, waitResponse{
Waited: true,
Elapsed: time.Since(start).Milliseconds(),
Match: matchLabel,
@@ -219,7 +222,7 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa
select {
case <-tCtx.Done():
elapsed := time.Since(start).Milliseconds()
- web.JSON(w, 200, waitResponse{
+ httpx.JSON(w, 200, waitResponse{
Waited: false,
Elapsed: elapsed,
Error: fmt.Sprintf("timeout after %dms waiting for %s", elapsed, mode),
diff --git a/internal/web/endpointlock.go b/internal/httpx/endpointlock.go
similarity index 97%
rename from internal/web/endpointlock.go
rename to internal/httpx/endpointlock.go
index a9488a84..1d639f54 100644
--- a/internal/web/endpointlock.go
+++ b/internal/httpx/endpointlock.go
@@ -1,4 +1,4 @@
-package web
+package httpx
import (
"fmt"
diff --git a/internal/web/web.go b/internal/httpx/httpx.go
similarity index 99%
rename from internal/web/web.go
rename to internal/httpx/httpx.go
index bddfee19..a3d050c9 100644
--- a/internal/web/web.go
+++ b/internal/httpx/httpx.go
@@ -1,4 +1,4 @@
-package web
+package httpx
import (
"bufio"
diff --git a/internal/web/web_test.go b/internal/httpx/httpx_test.go
similarity index 99%
rename from internal/web/web_test.go
rename to internal/httpx/httpx_test.go
index 936605ec..ad2d02fc 100644
--- a/internal/web/web_test.go
+++ b/internal/httpx/httpx_test.go
@@ -1,4 +1,4 @@
-package web
+package httpx
import (
"fmt"
diff --git a/internal/httpx/safepath.go b/internal/httpx/safepath.go
new file mode 100644
index 00000000..126cb355
--- /dev/null
+++ b/internal/httpx/safepath.go
@@ -0,0 +1,122 @@
+package httpx
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// SafePath resolves a user-provided path against a base directory and ensures
+// the result stays within that directory for file creation. Existing symlinked
+// components are rejected. Returns the cleaned absolute path.
+//
+// The implementation uses the filepath.Abs + strings.HasPrefix pattern
+// recommended by CodeQL (go/path-injection) and OWASP path-traversal guidance.
+func SafePath(base, userPath string) (string, error) {
+ return SafeCreatePath(base, userPath)
+}
+
+// SafeCreatePath resolves a user-provided path against a base directory and
+// rejects any existing symlinked component in the resolved path. It is intended
+// for paths that may be created later.
+func SafeCreatePath(base, userPath string) (string, error) {
+ absBase, absPath, err := safeLexicalPath(base, userPath)
+ if err != nil {
+ return "", err
+ }
+ if err := ensurePathHasNoSymlinkComponents(absBase, absPath, false); err != nil {
+ return "", err
+ }
+ return absPath, nil
+}
+
+// SafeExistingPath resolves a user-provided path against a base directory,
+// requires the full path to exist, and rejects any symlinked component in the
+// resolved path. It is intended for opening existing files.
+func SafeExistingPath(base, userPath string) (string, error) {
+ absBase, absPath, err := safeLexicalPath(base, userPath)
+ if err != nil {
+ return "", err
+ }
+ if err := ensurePathHasNoSymlinkComponents(absBase, absPath, true); err != nil {
+ return "", err
+ }
+ return absPath, nil
+}
+
+func safeLexicalPath(base, userPath string) (string, string, error) {
+ absBase, err := filepath.Abs(base)
+ if err != nil {
+ return "", "", fmt.Errorf("invalid base path: %w", err)
+ }
+
+ // Empty or "." means the base directory itself.
+ if userPath == "" || userPath == "." {
+ return absBase, absBase, nil
+ }
+
+ // Reject absolute paths outright — user input must be relative to base.
+ if filepath.IsAbs(userPath) || strings.HasPrefix(userPath, "/") || strings.HasPrefix(userPath, string(filepath.Separator)) {
+ return "", "", fmt.Errorf("absolute paths not allowed: %q", userPath)
+ }
+
+ // Go 1.20+: reject paths with "..", device names (NUL, CON on Windows),
+ // and other non-local components.
+ if !filepath.IsLocal(userPath) {
+ return "", "", fmt.Errorf("path %q contains invalid components", userPath)
+ }
+
+ // Join, clean, resolve to absolute.
+ joined := filepath.Join(absBase, userPath)
+ absPath, err := filepath.Abs(joined)
+ if err != nil {
+ return "", "", fmt.Errorf("invalid resolved path: %w", err)
+ }
+
+ // Final containment check — the resolved path must be under absBase.
+ if !strings.HasPrefix(absPath, absBase+string(filepath.Separator)) && absPath != absBase {
+ return "", "", fmt.Errorf("path %q escapes base directory %q", userPath, absBase)
+ }
+
+ return absBase, absPath, nil
+}
+
+func ensurePathHasNoSymlinkComponents(absBase, absPath string, requireFullExistence bool) error {
+ if info, err := os.Lstat(absBase); err == nil {
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("base path %q must not be a symlink", absBase)
+ }
+ } else if !os.IsNotExist(err) {
+ return fmt.Errorf("inspect base path %q: %w", absBase, err)
+ } else if requireFullExistence && absPath == absBase {
+ return fmt.Errorf("path does not exist: %q", absBase)
+ }
+
+ relPath, err := filepath.Rel(absBase, absPath)
+ if err != nil {
+ return fmt.Errorf("compute relative path: %w", err)
+ }
+ if relPath == "." {
+ return nil
+ }
+
+ current := absBase
+ for _, part := range strings.Split(relPath, string(filepath.Separator)) {
+ current = filepath.Join(current, part)
+ info, err := os.Lstat(current)
+ if err != nil {
+ if os.IsNotExist(err) && !requireFullExistence {
+ return nil
+ }
+ if os.IsNotExist(err) {
+ return fmt.Errorf("path does not exist: %q", current)
+ }
+ return fmt.Errorf("inspect path %q: %w", current, err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("path %q traverses symlink %q", absPath, current)
+ }
+ }
+ return nil
+}
diff --git a/internal/web/safepath_test.go b/internal/httpx/safepath_test.go
similarity index 77%
rename from internal/web/safepath_test.go
rename to internal/httpx/safepath_test.go
index c43e5f6a..67031b90 100644
--- a/internal/web/safepath_test.go
+++ b/internal/httpx/safepath_test.go
@@ -1,4 +1,4 @@
-package web
+package httpx
import (
"os"
@@ -250,3 +250,67 @@ func TestSafePath_ReturnValueIsAbsolute(t *testing.T) {
}
})
}
+
+func TestSafeExistingPath(t *testing.T) {
+ base := t.TempDir()
+ goodDir := filepath.Join(base, "uploads")
+ if err := os.MkdirAll(goodDir, 0o755); err != nil {
+ t.Fatalf("setup good dir: %v", err)
+ }
+ goodFile := filepath.Join(goodDir, "file.txt")
+ if err := os.WriteFile(goodFile, []byte("ok"), 0o600); err != nil {
+ t.Fatalf("write good file: %v", err)
+ }
+
+ got, err := SafeExistingPath(base, filepath.Join("uploads", "file.txt"))
+ if err != nil {
+ t.Fatalf("SafeExistingPath() unexpected error: %v", err)
+ }
+ if got != goodFile {
+ t.Fatalf("SafeExistingPath() = %q, want %q", got, goodFile)
+ }
+
+ if _, err := SafeExistingPath(base, filepath.Join("uploads", "missing.txt")); err == nil {
+ t.Fatal("expected missing existing path to fail")
+ }
+}
+
+func TestSafePathRejectsSymlinkComponents(t *testing.T) {
+ base := t.TempDir()
+ outside := t.TempDir()
+
+ linkDir := filepath.Join(base, "linked")
+ makeSymlinkOrSkip(t, outside, linkDir)
+
+ if _, err := SafeCreatePath(base, filepath.Join("linked", "new.txt")); err == nil {
+ t.Fatal("expected SafeCreatePath to reject symlinked parent")
+ }
+ if _, err := SafeExistingPath(base, filepath.Join("linked", "existing.txt")); err == nil {
+ t.Fatal("expected SafeExistingPath to reject symlinked parent")
+ }
+ if _, err := SafePath(base, filepath.Join("linked", "compat.txt")); err == nil {
+ t.Fatal("expected SafePath compatibility wrapper to reject symlinked parent")
+ }
+}
+
+func TestSafeCreatePathRejectsSymlinkLeaf(t *testing.T) {
+ base := t.TempDir()
+ target := filepath.Join(t.TempDir(), "target.txt")
+ if err := os.WriteFile(target, []byte("secret"), 0o600); err != nil {
+ t.Fatalf("write target: %v", err)
+ }
+
+ linkPath := filepath.Join(base, "leaf.txt")
+ makeSymlinkOrSkip(t, target, linkPath)
+
+ if _, err := SafeCreatePath(base, "leaf.txt"); err == nil {
+ t.Fatal("expected SafeCreatePath to reject symlink leaf")
+ }
+}
+
+func makeSymlinkOrSkip(t *testing.T, target, link string) {
+ t.Helper()
+ if err := os.Symlink(target, link); err != nil {
+ t.Skipf("symlink unsupported in test environment: %v", err)
+ }
+}
diff --git a/internal/idutil/idutil.go b/internal/ids/ids.go
similarity index 99%
rename from internal/idutil/idutil.go
rename to internal/ids/ids.go
index ceed261e..c1c0f3ff 100644
--- a/internal/idutil/idutil.go
+++ b/internal/ids/ids.go
@@ -1,4 +1,4 @@
-package idutil
+package ids
import (
"crypto/sha256"
diff --git a/internal/idutil/idutil_test.go b/internal/ids/ids_test.go
similarity index 94%
rename from internal/idutil/idutil_test.go
rename to internal/ids/ids_test.go
index fae37673..23e202cd 100644
--- a/internal/idutil/idutil_test.go
+++ b/internal/ids/ids_test.go
@@ -1,4 +1,4 @@
-package idutil
+package ids
import "testing"
diff --git a/internal/allocation/fcfs.go b/internal/instance/allocation/fcfs.go
similarity index 100%
rename from internal/allocation/fcfs.go
rename to internal/instance/allocation/fcfs.go
diff --git a/internal/allocation/policy.go b/internal/instance/allocation/policy.go
similarity index 79%
rename from internal/allocation/policy.go
rename to internal/instance/allocation/policy.go
index b211b3f8..1614d053 100644
--- a/internal/allocation/policy.go
+++ b/internal/instance/allocation/policy.go
@@ -1,6 +1,5 @@
-// Package allocation defines the AllocationPolicy interface and built-in implementations.
-// An AllocationPolicy decides which running instance should handle the next request.
-// It is independent from Strategy (API style) — both are swappable independently.
+// Package allocation defines instance allocation policies.
+// A Policy decides which running instance should handle the next request.
package allocation
import (
diff --git a/internal/allocation/policy_test.go b/internal/instance/allocation/policy_test.go
similarity index 97%
rename from internal/allocation/policy_test.go
rename to internal/instance/allocation/policy_test.go
index 8b56cad5..3c134d9c 100644
--- a/internal/allocation/policy_test.go
+++ b/internal/instance/allocation/policy_test.go
@@ -3,8 +3,8 @@ package allocation_test
import (
"testing"
- "github.com/pinchtab/pinchtab/internal/allocation"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/instance/allocation"
)
func candidates(ids ...string) []bridge.Instance {
diff --git a/internal/allocation/random.go b/internal/instance/allocation/random.go
similarity index 100%
rename from internal/allocation/random.go
rename to internal/instance/allocation/random.go
diff --git a/internal/allocation/round_robin.go b/internal/instance/allocation/round_robin.go
similarity index 100%
rename from internal/allocation/round_robin.go
rename to internal/instance/allocation/round_robin.go
diff --git a/internal/instance/allocator.go b/internal/instance/allocator.go
index 08e24350..806794c6 100644
--- a/internal/instance/allocator.go
+++ b/internal/instance/allocator.go
@@ -3,8 +3,8 @@ package instance
import (
"fmt"
- "github.com/pinchtab/pinchtab/internal/allocation"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/instance/allocation"
)
// Allocator selects an instance using the configured AllocationPolicy.
diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.go
index 476076a6..4402c651 100644
--- a/internal/instance/instance_test.go
+++ b/internal/instance/instance_test.go
@@ -4,9 +4,9 @@ import (
"fmt"
"testing"
- "github.com/pinchtab/pinchtab/internal/allocation"
bridgepkg "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/instance"
+ "github.com/pinchtab/pinchtab/internal/instance/allocation"
)
// --- Test doubles ---
@@ -321,7 +321,7 @@ func TestAllocator_NoRunningInstances(t *testing.T) {
func TestManager_DelegatesToComponents(t *testing.T) {
launcher := newMockLauncher()
fetcher := newMockFetcher()
- mgr := instance.NewManager(launcher, fetcher, &allocation.FCFS{})
+ mgr := instance.NewManager(launcher, fetcher)
// Launch via manager → delegates to repo.
inst, err := mgr.Launch("default", "9868", true)
@@ -372,7 +372,7 @@ func TestManager_DelegatesToComponents(t *testing.T) {
func TestManager_StopInvalidatesTabCache(t *testing.T) {
launcher := newMockLauncher()
fetcher := newMockFetcher()
- mgr := instance.NewManager(launcher, fetcher, nil)
+ mgr := instance.NewManager(launcher, fetcher)
inst, _ := mgr.Launch("default", "9868", true)
mgr.RegisterTab("tab_1", inst.ID)
@@ -386,3 +386,20 @@ func TestManager_StopInvalidatesTabCache(t *testing.T) {
t.Error("expected error: tab cache should be invalidated after stop")
}
}
+
+func TestManager_SetAllocationPolicy(t *testing.T) {
+ launcher := newMockLauncher()
+ fetcher := newMockFetcher()
+ mgr := instance.NewManager(launcher, fetcher)
+
+ if err := mgr.SetAllocationPolicy("round_robin"); err != nil {
+ t.Fatalf("SetAllocationPolicy returned error: %v", err)
+ }
+ if got := mgr.Allocator.Policy().Name(); got != "round_robin" {
+ t.Fatalf("expected round_robin policy, got %q", got)
+ }
+
+ if err := mgr.SetAllocationPolicy("does_not_exist"); err == nil {
+ t.Fatal("expected error for unknown policy")
+ }
+}
diff --git a/internal/instance/manager.go b/internal/instance/manager.go
index b3ea65f3..2d87e60b 100644
--- a/internal/instance/manager.go
+++ b/internal/instance/manager.go
@@ -1,8 +1,8 @@
package instance
import (
- "github.com/pinchtab/pinchtab/internal/allocation"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/instance/allocation"
)
// Manager is the InstanceManager facade.
@@ -15,14 +15,10 @@ type Manager struct {
}
// NewManager creates a fully wired Manager.
-func NewManager(launcher InstanceLauncher, fetcher TabFetcher, policy allocation.Policy) *Manager {
- if policy == nil {
- policy = &allocation.FCFS{}
- }
-
+func NewManager(launcher InstanceLauncher, fetcher TabFetcher) *Manager {
repo := NewRepository(launcher)
locator := NewLocator(repo, fetcher)
- allocator := NewAllocator(repo, policy)
+ allocator := NewAllocator(repo, &allocation.FCFS{})
return &Manager{
Repo: repo,
@@ -82,3 +78,13 @@ func (m *Manager) InvalidateTab(tabID string) {
func (m *Manager) Allocate() (*bridge.Instance, error) {
return m.Allocator.Allocate()
}
+
+// SetAllocationPolicy swaps the allocation policy at runtime by name.
+func (m *Manager) SetAllocationPolicy(name string) error {
+ policy, err := allocation.New(name)
+ if err != nil {
+ return err
+ }
+ m.Allocator.SetPolicy(policy)
+ return nil
+}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index 70a0aaef..16656181 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -8,7 +8,7 @@ import (
"time"
"github.com/mark3labs/mcp-go/mcp"
- "github.com/pinchtab/pinchtab/internal/urlutil"
+ "github.com/pinchtab/pinchtab/internal/urls"
)
// maxWaitMS caps wait/timeout durations for safety.
@@ -118,7 +118,7 @@ func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
- safeURL, err := urlutil.Sanitize(u)
+ safeURL, err := urls.Sanitize(u)
if err != nil {
return mcp.NewToolResultError("invalid URL: " + err.Error()), nil
}
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index dd4aab28..b0244c5c 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -3,7 +3,7 @@ package orchestrator
import (
"net/http"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func registerCapabilityRoute(mux *http.ServeMux, route string, enabled bool, feature, setting, code string, next http.HandlerFunc) {
@@ -11,7 +11,7 @@ func registerCapabilityRoute(mux *http.ServeMux, route string, enabled bool, fea
mux.HandleFunc(route, next)
return
}
- mux.HandleFunc(route, web.DisabledEndpointHandler(feature, setting, code))
+ mux.HandleFunc(route, httpx.DisabledEndpointHandler(feature, setting, code))
}
func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
@@ -70,13 +70,13 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
}
func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, o.List())
+ httpx.JSON(w, 200, o.List())
}
func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, o.AllTabs())
+ httpx.JSON(w, 200, o.AllTabs())
}
func (o *Orchestrator) handleAllMetrics(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, o.AllMetrics())
+ httpx.JSON(w, 200, o.AllMetrics())
}
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index 20907a22..96a384b7 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -8,7 +8,8 @@ import (
"strings"
"time"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request) {
@@ -17,7 +18,7 @@ func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request)
inst, ok := o.instances[id]
if !ok {
o.mu.RUnlock()
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ httpx.Error(w, 404, fmt.Errorf("instance %q not found", id))
return
}
@@ -33,7 +34,7 @@ func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request)
copyInst.Status = "stopped"
}
- web.JSON(w, 200, copyInst)
+ httpx.JSON(w, 200, copyInst)
}
func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request) {
@@ -47,7 +48,7 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request
if r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON"))
return
}
}
@@ -58,7 +59,7 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request
if req.ProfileId != "" {
profs, err := o.profiles.List()
if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to list profiles: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("failed to list profiles: %w", err))
return
}
found := false
@@ -70,7 +71,7 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request
}
}
if !found {
- web.Error(w, 400, fmt.Errorf("profile %q not found", req.ProfileId))
+ httpx.Error(w, 400, fmt.Errorf("profile %q not found", req.ProfileId))
return
}
} else if req.Name != "" {
@@ -82,19 +83,21 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request
inst, err := o.Launch(name, req.Port, headless, req.ExtensionPaths)
if err != nil {
statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
+ httpx.Error(w, statusCode, err)
return
}
- web.JSON(w, 201, inst)
+ authn.AuditLog(r, "instance.launched", "profileName", name, "instanceId", inst.ID)
+ httpx.JSON(w, 201, inst)
}
func (o *Orchestrator) handleStopByInstanceID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if err := o.Stop(id); err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
- web.JSON(w, 200, map[string]string{"status": "stopped", "id": id})
+ authn.AuditLog(r, "instance.stopped", "instanceId", id)
+ httpx.JSON(w, 200, map[string]string{"status": "stopped", "id": id})
}
func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Request) {
@@ -104,7 +107,7 @@ func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Re
inst, ok := o.instances[id]
if !ok {
o.mu.RUnlock()
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ httpx.Error(w, 404, fmt.Errorf("instance %q not found", id))
return
}
active := instanceIsActive(inst)
@@ -114,14 +117,14 @@ func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Re
o.mu.RUnlock()
if inst.Attached && inst.AttachType != "bridge" {
- web.Error(w, 409, fmt.Errorf("attached instance %q cannot be started by the orchestrator", id))
+ httpx.Error(w, 409, fmt.Errorf("attached instance %q cannot be started by the orchestrator", id))
return
}
if active {
targetURL, targetErr := o.instancePathURL(inst, "/ensure-chrome", "")
if targetErr != nil {
- web.Error(w, 502, targetErr)
+ httpx.Error(w, 502, targetErr)
return
}
o.proxyToURL(w, r, targetURL)
@@ -129,24 +132,25 @@ func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Re
}
if inst.Attached {
- web.Error(w, 409, fmt.Errorf("attached instance %q cannot be started by the orchestrator", id))
+ httpx.Error(w, 409, fmt.Errorf("attached instance %q cannot be started by the orchestrator", id))
return
}
started, err := o.Launch(profileName, port, headless, nil)
if err != nil {
statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
+ httpx.Error(w, statusCode, err)
return
}
- web.JSON(w, 201, started)
+ authn.AuditLog(r, "instance.started", "instanceId", started.ID, "profileName", profileName)
+ httpx.JSON(w, 201, started)
}
func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
logs, err := o.Logs(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
w.Header().Set("Content-Type", "text/plain")
@@ -168,7 +172,7 @@ func (o *Orchestrator) handleLogsStreamByID(w http.ResponseWriter, r *http.Reque
id := r.PathValue("id")
initial, err := o.Logs(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -231,7 +235,7 @@ func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Reques
if r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON"))
return
}
}
@@ -242,7 +246,7 @@ func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Reques
if req.ProfileID != "" {
profileName, err = o.resolveProfileName(req.ProfileID)
if err != nil {
- web.Error(w, 404, fmt.Errorf("profile %q not found", req.ProfileID))
+ httpx.Error(w, 404, fmt.Errorf("profile %q not found", req.ProfileID))
return
}
} else {
@@ -254,11 +258,12 @@ func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Reques
inst, err := o.Launch(profileName, req.Port, headless, req.ExtensionPaths)
if err != nil {
statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
+ httpx.Error(w, statusCode, err)
return
}
- web.JSON(w, 201, inst)
+ authn.AuditLog(r, "instance.started", "instanceId", inst.ID, "profileName", profileName)
+ httpx.JSON(w, 201, inst)
}
func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Request) {
@@ -269,18 +274,18 @@ func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Request
o.mu.RUnlock()
if !ok {
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ httpx.Error(w, 404, fmt.Errorf("instance %q not found", id))
return
}
if inst.Status != "running" || !instanceIsActive(inst) {
- web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
+ httpx.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
return
}
tabs, err := o.fetchTabs(inst)
if err != nil {
- web.Error(w, 502, fmt.Errorf("failed to fetch tabs for instance %q: %w", id, err))
+ httpx.Error(w, 502, fmt.Errorf("failed to fetch tabs for instance %q: %w", id, err))
return
}
@@ -294,7 +299,7 @@ func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Request
})
}
- web.JSON(w, 200, result)
+ httpx.JSON(w, 200, result)
}
func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Request) {
@@ -304,18 +309,18 @@ func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Reque
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON"))
return
}
if req.CdpURL == "" {
- web.Error(w, 400, fmt.Errorf("cdpUrl is required"))
+ httpx.Error(w, 400, fmt.Errorf("cdpUrl is required"))
return
}
// Validate attach is enabled and URL is allowed
if err := o.validateAttachURL(req.CdpURL); err != nil {
- web.Error(w, 403, err)
+ httpx.Error(w, 403, err)
return
}
@@ -327,11 +332,12 @@ func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Reque
inst, err := o.Attach(name, req.CdpURL)
if err != nil {
- web.Error(w, classifyLaunchError(err), err)
+ httpx.Error(w, classifyLaunchError(err), err)
return
}
- web.JSON(w, 201, inst)
+ authn.AuditLog(r, "instance.attached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "cdp")
+ httpx.JSON(w, 201, inst)
}
func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request) {
@@ -342,19 +348,19 @@ func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON"))
return
}
if req.BaseURL == "" {
- web.Error(w, 400, fmt.Errorf("baseUrl is required"))
+ httpx.Error(w, 400, fmt.Errorf("baseUrl is required"))
return
}
if err := o.validateAttachURL(req.BaseURL); err != nil {
- web.Error(w, 403, err)
+ httpx.Error(w, 403, err)
return
}
if err := o.probeAttachBridge(req.BaseURL, req.Token); err != nil {
- web.Error(w, 502, err)
+ httpx.Error(w, 502, err)
return
}
@@ -365,10 +371,11 @@ func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request
inst, err := o.AttachBridge(name, req.BaseURL, req.Token)
if err != nil {
- web.Error(w, classifyLaunchError(err), err)
+ httpx.Error(w, classifyLaunchError(err), err)
return
}
- web.JSON(w, 201, inst)
+ authn.AuditLog(r, "instance.attached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "bridge")
+ httpx.JSON(w, 201, inst)
}
// probeAttachBridge checks that a remote bridge is reachable.
diff --git a/internal/orchestrator/handlers_profiles.go b/internal/orchestrator/handlers_profiles.go
index b4cff2f3..cbdaa0ac 100644
--- a/internal/orchestrator/handlers_profiles.go
+++ b/internal/orchestrator/handlers_profiles.go
@@ -5,7 +5,8 @@ import (
"fmt"
"net/http"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (o *Orchestrator) resolveProfileName(idOrName string) (string, error) {
@@ -25,7 +26,7 @@ func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name, err := o.resolveProfileName(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -38,31 +39,33 @@ func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
inst, err := o.Launch(name, req.Port, req.Headless, nil)
if err != nil {
statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
+ httpx.Error(w, statusCode, err)
return
}
- web.JSON(w, 201, inst)
+ authn.AuditLog(r, "instance.started", "profileId", id, "profileName", name, "instanceId", inst.ID)
+ httpx.JSON(w, 201, inst)
}
func (o *Orchestrator) handleStopByID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name, err := o.resolveProfileName(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if err := o.StopProfile(name); err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
- web.JSON(w, 200, map[string]string{"status": "stopped", "id": id, "name": name})
+ authn.AuditLog(r, "instance.stopped", "profileId", id, "profileName", name)
+ httpx.JSON(w, 200, map[string]string{"status": "stopped", "id": id, "name": name})
}
func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name, err := o.resolveProfileName(id)
if err != nil {
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"name": id,
"running": false,
"status": "stopped",
@@ -74,7 +77,7 @@ func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Requ
instances := o.List()
for _, inst := range instances {
if inst.ProfileName == name && (inst.Status == "running" || inst.Status == "starting") {
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"name": name,
"running": inst.Status == "running",
"status": inst.Status,
@@ -84,7 +87,7 @@ func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Requ
return
}
}
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"name": name,
"running": false,
"status": "stopped",
diff --git a/internal/orchestrator/handlers_tabs.go b/internal/orchestrator/handlers_tabs.go
index b96d6b9b..f2b9cbd7 100644
--- a/internal/orchestrator/handlers_tabs.go
+++ b/internal/orchestrator/handlers_tabs.go
@@ -8,7 +8,7 @@ import (
"net/http"
"time"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// handleTabClose closes a tab by finding its instance and sending a close request.
@@ -16,13 +16,13 @@ import (
func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
inst, err := o.findRunningInstanceByTabID(tabID)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -34,12 +34,12 @@ func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {
targetURL, err := o.instancePathURL(inst, "/tab", "")
if err != nil {
- web.Error(w, 502, err)
+ httpx.Error(w, 502, err)
return
}
proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", targetURL.String(), bytes.NewReader(reqBody))
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
proxyReq.Header.Set("Content-Type", "application/json")
@@ -48,7 +48,7 @@ func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(proxyReq)
if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
+ httpx.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
return
}
defer func() { _ = resp.Body.Close() }()
@@ -68,11 +68,11 @@ func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Requ
inst, ok := o.instances[id]
o.mu.RUnlock()
if !ok {
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ httpx.Error(w, 404, fmt.Errorf("instance %q not found", id))
return
}
if inst.Status != "running" {
- web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
+ httpx.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
return
}
@@ -81,7 +81,7 @@ func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Requ
}
if r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON"))
return
}
}
@@ -91,7 +91,7 @@ func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Requ
"url": req.URL,
})
if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to build tab open request: %w", err))
+ httpx.Error(w, 500, fmt.Errorf("failed to build tab open request: %w", err))
return
}
@@ -103,7 +103,7 @@ func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Requ
targetURL, err := o.instancePathURL(inst, "/tab", r.URL.RawQuery)
if err != nil {
- web.Error(w, 502, err)
+ httpx.Error(w, 502, err)
return
}
o.proxyToURL(w, proxyReq, targetURL)
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 228b83b0..ef55ee77 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -16,11 +16,10 @@ import (
"sync"
"time"
- "github.com/pinchtab/pinchtab/internal/allocation"
"github.com/pinchtab/pinchtab/internal/api/types"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/idutil"
+ "github.com/pinchtab/pinchtab/internal/ids"
"github.com/pinchtab/pinchtab/internal/instance"
"github.com/pinchtab/pinchtab/internal/profiles"
)
@@ -45,7 +44,7 @@ type Orchestrator struct {
childAuthToken string
allowEvaluate bool
portAllocator *PortAllocator
- idMgr *idutil.Manager
+ idMgr *ids.Manager
eventHandlers []EventHandler
instanceMgr *instance.Manager
runtimeCfg *config.RuntimeConfig
@@ -135,15 +134,13 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator
childAuthToken: "",
allowEvaluate: false,
portAllocator: NewPortAllocator(9868, 9968),
- idMgr: idutil.NewManager(),
+ idMgr: ids.NewManager(),
}
bridgeClient := instance.NewBridgeClient()
- defaultPolicy, _ := allocation.New("fcfs")
orch.instanceMgr = instance.NewManager(
&orchestratorLauncher{orch: orch},
bridgeClient,
- defaultPolicy,
)
return orch
@@ -156,12 +153,7 @@ func (o *Orchestrator) InstanceManager() *instance.Manager {
// SetAllocationPolicy changes the allocation policy at runtime.
func (o *Orchestrator) SetAllocationPolicy(name string) error {
- p, err := allocation.New(name)
- if err != nil {
- return err
- }
- o.instanceMgr.Allocator.SetPolicy(p)
- return nil
+ return o.instanceMgr.SetAllocationPolicy(name)
}
type orchestratorLauncher struct {
diff --git a/internal/orchestrator/process_test.go b/internal/orchestrator/process_test.go
index 0ac0ead6..4654977e 100644
--- a/internal/orchestrator/process_test.go
+++ b/internal/orchestrator/process_test.go
@@ -6,7 +6,7 @@ import (
"testing"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/idutil"
+ "github.com/pinchtab/pinchtab/internal/ids"
)
type mockRunner struct {
@@ -49,7 +49,7 @@ func TestLaunch_Mocked(t *testing.T) {
if len(runner.args) != 1 || runner.args[0] != "bridge" {
t.Fatalf("expected child process args [bridge], got %v", runner.args)
}
- if !idutil.IsValidID(inst.ID, "inst") {
+ if !ids.IsValidID(inst.ID, "inst") {
t.Errorf("expected ID format inst_XXXXXXXX, got %s", inst.ID)
}
}
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 3c889652..9e16bd01 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -9,8 +9,8 @@ import (
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/httpx"
iproxy "github.com/pinchtab/pinchtab/internal/proxy"
- "github.com/pinchtab/pinchtab/internal/web"
)
// proxyTabRequest is a generic handler that proxies requests to the instance
@@ -21,7 +21,7 @@ import (
func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
return
}
@@ -34,7 +34,7 @@ func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {
})
targetURL, buildErr := o.instancePathURLFromBridge(inst, r.URL.Path, r.URL.RawQuery)
if buildErr != nil {
- web.Error(w, 502, buildErr)
+ httpx.Error(w, 502, buildErr)
return
}
o.proxyToURL(w, r, targetURL)
@@ -68,7 +68,7 @@ func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {
return
}
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
}
// proxyToInstance proxies a request to a specific instance by ID in the path.
@@ -80,12 +80,12 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
o.mu.RUnlock()
if !ok {
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ httpx.Error(w, 404, fmt.Errorf("instance %q not found", id))
return
}
if inst.Status != "running" {
- web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
+ httpx.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
return
}
activity.EnrichRequest(r, activity.Update{
@@ -103,7 +103,7 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
targetURL, err := o.instancePathURL(inst, targetPath, r.URL.RawQuery)
if err != nil {
- web.Error(w, 502, err)
+ httpx.Error(w, 502, err)
return
}
o.proxyToURL(w, r, targetURL)
@@ -164,7 +164,7 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requ
inst, ok := o.instances[id]
o.mu.RUnlock()
if !ok || inst.Status != "running" {
- web.Error(w, 404, fmt.Errorf("instance not found or not running"))
+ httpx.Error(w, 404, fmt.Errorf("instance not found or not running"))
return
}
activity.EnrichRequest(r, activity.Update{
@@ -175,7 +175,7 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requ
targetURL, err := o.instancePathURL(inst, "/screencast", r.URL.RawQuery)
if err != nil {
- web.Error(w, 502, err)
+ httpx.Error(w, 502, err)
return
}
diff --git a/internal/profiles/copydir.go b/internal/profiles/copydir.go
index 82b93dd3..89b897ea 100644
--- a/internal/profiles/copydir.go
+++ b/internal/profiles/copydir.go
@@ -13,6 +13,9 @@ func copyDir(src, dst string) error {
if err != nil {
return err
}
+ if d.Type()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlinks are not allowed in imported profiles: %s", path)
+ }
rel, err := filepath.Rel(src, path)
if err != nil {
diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.go
index 7719bc06..46eac701 100644
--- a/internal/profiles/handlers.go
+++ b/internal/profiles/handlers.go
@@ -7,7 +7,8 @@ import (
"strconv"
"strings"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {
@@ -28,7 +29,7 @@ func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {
func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {
profiles, err := pm.List()
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
@@ -58,11 +59,11 @@ func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {
})
}
}
- web.JSON(w, 200, filtered)
+ httpx.JSON(w, 200, filtered)
return
}
- web.JSON(w, 200, profiles)
+ httpx.JSON(w, 200, profiles)
}
func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {
@@ -72,11 +73,11 @@ func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {
UseWhen string `json:"useWhen"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
if req.Name == "" {
- web.Error(w, 400, fmt.Errorf("name required"))
+ httpx.Error(w, 400, fmt.Errorf("name required"))
return
}
@@ -88,17 +89,18 @@ func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {
if err := pm.CreateWithMeta(req.Name, meta); err != nil {
// Validation errors → 400, already exists → 409, others → 500
if strings.Contains(err.Error(), "cannot contain") || strings.Contains(err.Error(), "cannot be empty") {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
} else if strings.Contains(err.Error(), "already exists") {
- web.Error(w, 409, err)
+ httpx.Error(w, 409, err)
} else {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
}
return
}
generatedID := profileID(req.Name)
- web.JSON(w, 200, map[string]any{
+ authn.AuditLog(r, "profile.created", "profileId", generatedID, "profileName", req.Name)
+ httpx.JSON(w, 200, map[string]any{
"status": "created",
"id": generatedID,
"name": req.Name,
@@ -113,11 +115,11 @@ func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {
UseWhen string `json:"useWhen"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
if req.Name == "" || req.SourcePath == "" {
- web.Error(w, 400, fmt.Errorf("name and sourcePath required"))
+ httpx.Error(w, 400, fmt.Errorf("name and sourcePath required"))
return
}
@@ -127,10 +129,11 @@ func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {
}
if err := pm.ImportWithMeta(req.Name, req.SourcePath, meta); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, map[string]string{"status": "imported", "name": req.Name})
+ authn.AuditLog(r, "profile.imported", "profileName", req.Name)
+ httpx.JSON(w, 200, map[string]string{"status": "imported", "name": req.Name})
}
func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Request) {
@@ -140,11 +143,11 @@ func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Reques
UseWhen *string `json:"useWhen"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
if req.Name == "" {
- web.Error(w, 400, fmt.Errorf("name required"))
+ httpx.Error(w, 400, fmt.Errorf("name required"))
return
}
@@ -157,10 +160,11 @@ func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Reques
}
if err := pm.UpdateMeta(req.Name, updates); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, map[string]string{"status": "updated", "name": req.Name})
+ authn.AuditLog(r, "profile.meta_updated", "profileName", req.Name)
+ httpx.JSON(w, 200, map[string]string{"status": "updated", "name": req.Name})
}
func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request) {
@@ -168,7 +172,7 @@ func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request)
profiles, err := pm.List()
if err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
@@ -198,11 +202,11 @@ func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request)
}
if foundProfile == nil {
- web.Error(w, 404, fmt.Errorf("profile %q not found", id))
+ httpx.Error(w, 404, fmt.Errorf("profile %q not found", id))
return
}
- web.JSON(w, 200, foundProfile)
+ httpx.JSON(w, 200, foundProfile)
}
func (pm *ProfileManager) handleDeleteByID(w http.ResponseWriter, r *http.Request) {
@@ -210,16 +214,17 @@ func (pm *ProfileManager) handleDeleteByID(w http.ResponseWriter, r *http.Reques
name, err := pm.resolveIDOnly(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if err := pm.Delete(name); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, map[string]any{"status": "deleted", "id": id, "name": name})
+ authn.AuditLog(r, "profile.deleted", "profileId", id, "profileName", name)
+ httpx.JSON(w, 200, map[string]any{"status": "deleted", "id": id, "name": name})
}
func (pm *ProfileManager) resolveIDOrName(idOrName string) (string, error) {
@@ -245,7 +250,7 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques
id := r.PathValue("id")
name, err := pm.resolveIDOnly(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
@@ -255,7 +260,7 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques
Description *string `json:"description"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ httpx.Error(w, 400, fmt.Errorf("invalid JSON"))
return
}
@@ -263,11 +268,11 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques
if req.Name != nil && *req.Name != name {
if err := pm.Rename(name, *req.Name); err != nil {
if strings.Contains(err.Error(), "already exists") {
- web.Error(w, 409, err)
+ httpx.Error(w, 409, err)
} else if strings.Contains(err.Error(), "cannot contain") || strings.Contains(err.Error(), "cannot be empty") {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
} else {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
}
return
}
@@ -283,50 +288,52 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques
}
if len(updates) > 0 {
if err := pm.UpdateMeta(finalName, updates); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
}
- web.JSON(w, 200, map[string]any{"status": "updated", "id": profileID(finalName), "name": finalName})
+ authn.AuditLog(r, "profile.updated", "profileId", profileID(finalName), "profileName", finalName)
+ httpx.JSON(w, 200, map[string]any{"status": "updated", "id": profileID(finalName), "name": finalName})
}
func (pm *ProfileManager) handleResetByIDOrName(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name, err := pm.resolveIDOnly(id)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
if err := pm.Reset(name); err != nil {
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, map[string]any{"status": "reset", "id": id, "name": name})
+ authn.AuditLog(r, "profile.reset", "profileId", id, "profileName", name)
+ httpx.JSON(w, 200, map[string]any{"status": "reset", "id": id, "name": name})
}
func (pm *ProfileManager) handleLogsByIDOrName(w http.ResponseWriter, r *http.Request) {
idOrName := r.PathValue("id")
name, err := pm.resolveIDOrName(idOrName)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
logs := pm.Logs(name, limit)
- web.JSON(w, 200, logs)
+ httpx.JSON(w, 200, logs)
}
func (pm *ProfileManager) handleAnalyticsByIDOrName(w http.ResponseWriter, r *http.Request) {
idOrName := r.PathValue("id")
name, err := pm.resolveIDOrName(idOrName)
if err != nil {
- web.Error(w, 404, err)
+ httpx.Error(w, 404, err)
return
}
report := pm.Analytics(name)
- web.JSON(w, 200, report)
+ httpx.JSON(w, 200, report)
}
diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.go
index d6b463bd..68be26fd 100644
--- a/internal/profiles/profiles.go
+++ b/internal/profiles/profiles.go
@@ -12,10 +12,10 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/idutil"
+ "github.com/pinchtab/pinchtab/internal/ids"
)
-var idMgr = idutil.NewManager()
+var idMgr = ids.NewManager()
func profileID(name string) string {
return idMgr.ProfileID(name)
@@ -241,10 +241,13 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {
}
}
- srcInfo, err := os.Stat(sourcePath)
+ srcInfo, err := os.Lstat(sourcePath)
if err != nil {
return fmt.Errorf("source path invalid: %w", err)
}
+ if srcInfo.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("source path must not be a symlink")
+ }
if !srcInfo.IsDir() {
return fmt.Errorf("source path must be a directory")
}
diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.go
index fb7b1368..3a1eb9ec 100644
--- a/internal/profiles/profiles_test.go
+++ b/internal/profiles/profiles_test.go
@@ -95,6 +95,47 @@ func TestProfileManagerImportBadSource(t *testing.T) {
}
}
+func TestProfileManagerImportRejectsSymlinkSource(t *testing.T) {
+ dir := t.TempDir()
+ pm := NewProfileManager(dir)
+
+ src := filepath.Join(t.TempDir(), "chrome-src")
+ _ = os.MkdirAll(filepath.Join(src, "Default"), 0755)
+ _ = os.WriteFile(filepath.Join(src, "Default", "Preferences"), []byte(`{}`), 0644)
+
+ link := filepath.Join(t.TempDir(), "chrome-link")
+ if err := os.Symlink(src, link); err != nil {
+ t.Skipf("symlink not supported: %v", err)
+ }
+
+ err := pm.Import("bad-link", link)
+ if err == nil || !strings.Contains(err.Error(), "symlink") {
+ t.Fatalf("expected symlink source import to fail, got %v", err)
+ }
+}
+
+func TestProfileManagerImportRejectsSymlinkEntry(t *testing.T) {
+ dir := t.TempDir()
+ pm := NewProfileManager(dir)
+
+ src := filepath.Join(t.TempDir(), "chrome-src")
+ _ = os.MkdirAll(filepath.Join(src, "Default"), 0755)
+ _ = os.WriteFile(filepath.Join(src, "Default", "Preferences"), []byte(`{}`), 0644)
+
+ target := filepath.Join(t.TempDir(), "outside-cookie.txt")
+ if err := os.WriteFile(target, []byte("secret"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, filepath.Join(src, "Default", "link.txt")); err != nil {
+ t.Skipf("symlink not supported: %v", err)
+ }
+
+ err := pm.Import("bad-entry", src)
+ if err == nil || !strings.Contains(err.Error(), "symlink") {
+ t.Fatalf("expected symlink entry import to fail, got %v", err)
+ }
+}
+
func TestProfileManagerListReadsAccountFromPreferences(t *testing.T) {
dir := t.TempDir()
pm := NewProfileManager(dir)
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 8fe40d73..83dcd47c 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -13,7 +13,7 @@ import (
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/handlers"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// DefaultClient is the shared HTTP client for proxy requests.
@@ -41,11 +41,11 @@ var hopByHopHeaders = map[string]struct{}{
func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Options) {
if targetURL == nil {
- web.Error(w, 502, fmt.Errorf("proxy error: missing target URL"))
+ httpx.Error(w, 502, fmt.Errorf("proxy error: missing target URL"))
return
}
if opts.AllowedURL != nil && !opts.AllowedURL(targetURL) {
- web.Error(w, 400, fmt.Errorf("invalid proxy target"))
+ httpx.Error(w, 400, fmt.Errorf("invalid proxy target"))
return
}
@@ -70,14 +70,14 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
outReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL.String(), r.Body)
if err != nil {
- web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
+ httpx.Error(w, 502, fmt.Errorf("proxy error: %w", err))
return
}
copyHeaders(outReq.Header, proxyReq.Header)
resp, err := client.Do(outReq)
if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
+ httpx.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
return
}
defer func() { _ = resp.Body.Close() }()
@@ -106,7 +106,7 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
parsed, err := url.Parse(targetURL)
if err != nil {
- web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
+ httpx.Error(w, 502, fmt.Errorf("proxy error: %w", err))
return
}
if parsed.RawQuery == "" {
diff --git a/internal/scheduler/batch.go b/internal/scheduler/batch.go
index 07c2c68c..a61a3633 100644
--- a/internal/scheduler/batch.go
+++ b/internal/scheduler/batch.go
@@ -6,7 +6,7 @@ import (
"log/slog"
"net/http"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
var (
@@ -42,23 +42,23 @@ type BatchResponseItem struct {
func (s *Scheduler) handleBatch(w http.ResponseWriter, r *http.Request) {
var req BatchRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
if req.AgentID == "" {
- web.Error(w, 400, errMissingAgentID)
+ httpx.Error(w, 400, errMissingAgentID)
return
}
if len(req.Tasks) == 0 {
- web.Error(w, 400, errEmptyBatch)
+ httpx.Error(w, 400, errEmptyBatch)
return
}
s.cfgMu.RLock()
maxBatch := s.cfg.MaxBatchSize
s.cfgMu.RUnlock()
if len(req.Tasks) > maxBatch {
- web.ErrorCode(w, 400, "batch_too_large", "batch exceeds maximum size", false, map[string]any{
+ httpx.ErrorCode(w, 400, "batch_too_large", "batch exceeds maximum size", false, map[string]any{
"submitted": len(req.Tasks),
"max": maxBatch,
})
@@ -96,7 +96,7 @@ func (s *Scheduler) handleBatch(w http.ResponseWriter, r *http.Request) {
})
}
- web.JSON(w, 202, map[string]any{
+ httpx.JSON(w, 202, map[string]any{
"tasks": results,
"submitted": len(results),
})
diff --git a/internal/scheduler/batch_test.go b/internal/scheduler/batch_test.go
index 38aa359d..ea02d540 100644
--- a/internal/scheduler/batch_test.go
+++ b/internal/scheduler/batch_test.go
@@ -129,7 +129,7 @@ func TestHandleBatchWithCallbackURL(t *testing.T) {
body := `{
"agentId": "a1",
- "callbackUrl": "http://example.com/hook",
+ "callbackUrl": "http://93.184.216.34/hook",
"tasks": [
{"action":"click","tabId":"tab-1","ref":"e1"}
]
@@ -145,6 +145,45 @@ func TestHandleBatchWithCallbackURL(t *testing.T) {
}
}
+func TestHandleBatchRejectsInvalidCallbackURL(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ body := `{
+ "agentId": "a1",
+ "callbackUrl": "http://127.0.0.1/hook",
+ "tasks": [
+ {"action":"click","tabId":"tab-1","ref":"e1"}
+ ]
+ }`
+
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 202 {
+ t.Fatalf("expected 202, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ tasks, ok := resp["tasks"].([]any)
+ if !ok || len(tasks) != 1 {
+ t.Fatalf("expected 1 task result, got %v", resp["tasks"])
+ }
+ item := tasks[0].(map[string]any)
+ if item["state"] != "rejected" {
+ t.Fatalf("expected rejected state, got %v", item["state"])
+ }
+ if item["error"] == nil || item["error"] == "" {
+ t.Fatal("expected validation error for invalid callbackUrl")
+ }
+}
+
func TestHandleBatchPartialFailure(t *testing.T) {
s, mux, executor := setupHandlerTest(t)
defer executor.Close()
diff --git a/internal/scheduler/handlers.go b/internal/scheduler/handlers.go
index 23dd8a6f..491595b1 100644
--- a/internal/scheduler/handlers.go
+++ b/internal/scheduler/handlers.go
@@ -5,7 +5,7 @@ import (
"net/http"
"strings"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// RegisterHandlers mounts the scheduler API routes on the given mux.
@@ -21,7 +21,7 @@ func (s *Scheduler) RegisterHandlers(mux *http.ServeMux) {
func (s *Scheduler) handleSubmit(w http.ResponseWriter, r *http.Request) {
var req SubmitRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
@@ -29,7 +29,7 @@ func (s *Scheduler) handleSubmit(w http.ResponseWriter, r *http.Request) {
if err != nil {
if task != nil && task.State == StateRejected {
stats := s.QueueStats()
- web.ErrorCode(w, 429, "queue_full", err.Error(), true, map[string]any{
+ httpx.ErrorCode(w, 429, "queue_full", err.Error(), true, map[string]any{
"agentId": req.AgentID,
"queued": stats.TotalQueued,
"maxQueue": s.cfg.MaxQueueSize,
@@ -37,12 +37,12 @@ func (s *Scheduler) handleSubmit(w http.ResponseWriter, r *http.Request) {
})
return
}
- web.Error(w, 400, err)
+ httpx.Error(w, 400, err)
return
}
snap := task.Snapshot()
- web.JSON(w, 202, map[string]any{
+ httpx.JSON(w, 202, map[string]any{
"taskId": snap.ID,
"state": snap.State,
"position": snap.Position,
@@ -53,40 +53,40 @@ func (s *Scheduler) handleSubmit(w http.ResponseWriter, r *http.Request) {
func (s *Scheduler) handleGet(w http.ResponseWriter, r *http.Request) {
taskID := r.PathValue("id")
if taskID == "" {
- web.Error(w, 400, nil)
+ httpx.Error(w, 400, nil)
return
}
task := s.GetTask(taskID)
if task == nil {
- web.ErrorCode(w, 404, "not_found", "task not found", false, nil)
+ httpx.ErrorCode(w, 404, "not_found", "task not found", false, nil)
return
}
- web.JSON(w, 200, task.Snapshot())
+ httpx.JSON(w, 200, task.Snapshot())
}
func (s *Scheduler) handleCancel(w http.ResponseWriter, r *http.Request) {
taskID := r.PathValue("id")
if taskID == "" {
- web.Error(w, 400, nil)
+ httpx.Error(w, 400, nil)
return
}
if err := s.Cancel(taskID); err != nil {
if strings.Contains(err.Error(), "terminal state") {
- web.ErrorCode(w, 409, "conflict", err.Error(), false, nil)
+ httpx.ErrorCode(w, 409, "conflict", err.Error(), false, nil)
return
}
if strings.Contains(err.Error(), "not found") {
- web.ErrorCode(w, 404, "not_found", err.Error(), false, nil)
+ httpx.ErrorCode(w, 404, "not_found", err.Error(), false, nil)
return
}
- web.Error(w, 500, err)
+ httpx.Error(w, 500, err)
return
}
- web.JSON(w, 200, map[string]string{"status": "cancelled", "taskId": taskID})
+ httpx.JSON(w, 200, map[string]string{"status": "cancelled", "taskId": taskID})
}
func (s *Scheduler) handleList(w http.ResponseWriter, r *http.Request) {
@@ -107,13 +107,13 @@ func (s *Scheduler) handleList(w http.ResponseWriter, r *http.Request) {
if tasks == nil {
tasks = []*Task{}
}
- web.JSON(w, 200, map[string]any{"tasks": tasks, "count": len(tasks)})
+ httpx.JSON(w, 200, map[string]any{"tasks": tasks, "count": len(tasks)})
}
func (s *Scheduler) handleStats(w http.ResponseWriter, _ *http.Request) {
queue := s.QueueStats()
metrics := s.GetMetrics()
- web.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, map[string]any{
"queue": queue,
"metrics": metrics,
"config": map[string]any{
diff --git a/internal/scheduler/handlers_test.go b/internal/scheduler/handlers_test.go
index 594a27bd..e31c6a05 100644
--- a/internal/scheduler/handlers_test.go
+++ b/internal/scheduler/handlers_test.go
@@ -75,6 +75,22 @@ func TestHandlerSubmit_Invalid(t *testing.T) {
}
}
+func TestHandlerSubmit_InvalidCallbackURL(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ body := `{"agentId":"agent-1","action":"click","callbackUrl":"http://127.0.0.1/hook"}`
+ req := httptest.NewRequest("POST", "/tasks", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
func TestHandlerSubmitBadJSON(t *testing.T) {
_, mux, executor := setupHandlerTest(t)
defer executor.Close()
diff --git a/internal/scheduler/task.go b/internal/scheduler/task.go
index ba48c65b..26bfcc93 100644
--- a/internal/scheduler/task.go
+++ b/internal/scheduler/task.go
@@ -4,6 +4,7 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
+ "strings"
"sync"
"time"
)
@@ -151,6 +152,11 @@ func (r *SubmitRequest) Validate() error {
if r.Action == "" {
return fmt.Errorf("missing required field 'action'")
}
+ if strings.TrimSpace(r.CallbackURL) != "" {
+ if err := validateCallbackURL(r.CallbackURL); err != nil {
+ return fmt.Errorf("invalid callbackUrl: %w", err)
+ }
+ }
return nil
}
diff --git a/internal/scheduler/task_test.go b/internal/scheduler/task_test.go
index f3c08a9f..754ee3c5 100644
--- a/internal/scheduler/task_test.go
+++ b/internal/scheduler/task_test.go
@@ -132,6 +132,15 @@ func TestSubmitRequestValidate(t *testing.T) {
if err := noAction.Validate(); err == nil {
t.Error("missing action should fail")
}
+
+ blockedCallback := SubmitRequest{
+ AgentID: "a",
+ Action: "click",
+ CallbackURL: "http://127.0.0.1/hook",
+ }
+ if err := blockedCallback.Validate(); err == nil {
+ t.Error("loopback callbackUrl should fail")
+ }
}
func TestGenerateTaskID(t *testing.T) {
diff --git a/internal/scheduler/webhook.go b/internal/scheduler/webhook.go
index cee0148b..79910fda 100644
--- a/internal/scheduler/webhook.go
+++ b/internal/scheduler/webhook.go
@@ -2,17 +2,48 @@ package scheduler
import (
"bytes"
+ "context"
"encoding/json"
+ "errors"
"io"
"log/slog"
+ "net"
"net/http"
- "net/url"
"time"
)
-// webhookClient is a dedicated HTTP client for webhook delivery with short timeouts.
-var webhookClient = &http.Client{
- Timeout: 10 * time.Second,
+var errNoValidatedWebhookIPs = errors.New("no validated callback IPs")
+
+var webhookHTTPTimeout = 10 * time.Second
+
+var dialWebhookAddress = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, addr)
+}
+
+func newPinnedWebhookClient(target *validatedCallbackTarget) *http.Client {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ var lastErr error
+ for _, ip := range target.IPs {
+ conn, err := dialWebhookAddress(ctx, network, net.JoinHostPort(ip.String(), target.Port))
+ if err == nil {
+ return conn, nil
+ }
+ lastErr = err
+ }
+ if lastErr == nil {
+ lastErr = errNoValidatedWebhookIPs
+ }
+ return nil, lastErr
+ }
+ return &http.Client{
+ Timeout: webhookHTTPTimeout,
+ Transport: transport,
+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ }
}
// sendWebhook delivers a task snapshot to the configured callbackUrl.
@@ -22,14 +53,9 @@ func sendWebhook(callbackURL string, t *Task) {
return
}
- // Only allow http/https schemes to prevent SSRF.
- parsed, err := url.Parse(callbackURL)
+ target, err := validateCallbackTarget(callbackURL)
if err != nil {
- slog.Warn("webhook: invalid callback URL", "task", t.ID, "url", callbackURL, "err", err)
- return
- }
- if parsed.Scheme != "http" && parsed.Scheme != "https" {
- slog.Warn("webhook: unsupported scheme", "task", t.ID, "scheme", parsed.Scheme)
+ slog.Warn("webhook: callback rejected", "task", t.ID, "url", callbackURL, "err", err)
return
}
@@ -40,7 +66,7 @@ func sendWebhook(callbackURL string, t *Task) {
return
}
- req, err := http.NewRequest(http.MethodPost, callbackURL, bytes.NewReader(payload))
+ req, err := http.NewRequest(http.MethodPost, target.URL.String(), bytes.NewReader(payload))
if err != nil {
slog.Warn("webhook: failed to create request", "task", t.ID, "err", err)
return
@@ -49,7 +75,12 @@ func sendWebhook(callbackURL string, t *Task) {
req.Header.Set("X-PinchTab-Event", "task.completed")
req.Header.Set("X-PinchTab-Task-ID", snap.ID)
- resp, err := webhookClient.Do(req)
+ client := newPinnedWebhookClient(target)
+ if transport, ok := client.Transport.(*http.Transport); ok {
+ defer transport.CloseIdleConnections()
+ }
+
+ resp, err := client.Do(req)
if err != nil {
slog.Warn("webhook: delivery failed", "task", t.ID, "url", callbackURL, "err", err)
return
@@ -58,7 +89,7 @@ func sendWebhook(callbackURL string, t *Task) {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
- if resp.StatusCode >= 400 {
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
slog.Warn("webhook: non-success response", "task", t.ID, "url", callbackURL, "status", resp.StatusCode)
return
}
diff --git a/internal/scheduler/webhook_guard.go b/internal/scheduler/webhook_guard.go
new file mode 100644
index 00000000..77c39a99
--- /dev/null
+++ b/internal/scheduler/webhook_guard.go
@@ -0,0 +1,145 @@
+package scheduler
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/netip"
+ "net/url"
+ "strings"
+ "time"
+)
+
+var resolveWebhookHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ return net.DefaultResolver.LookupIP(ctx, network, host)
+}
+
+var blockedWebhookPrefixes = []netip.Prefix{
+ netip.MustParsePrefix("100.64.0.0/10"),
+ netip.MustParsePrefix("198.18.0.0/15"),
+}
+
+type callbackURLGuard struct{}
+
+func newCallbackURLGuard() *callbackURLGuard { return &callbackURLGuard{} }
+
+type validatedCallbackTarget struct {
+ URL *url.URL
+ Host string
+ Port string
+ IPs []netip.Addr
+}
+
+func (g *callbackURLGuard) Validate(rawURL string) error {
+ _, err := g.ValidateTarget(rawURL)
+ return err
+}
+
+func (g *callbackURLGuard) ValidateTarget(rawURL string) (*validatedCallbackTarget, error) {
+ parsed, err := url.Parse(strings.TrimSpace(rawURL))
+ if err != nil {
+ return nil, fmt.Errorf("invalid callback URL")
+ }
+ if parsed.Scheme != "http" && parsed.Scheme != "https" {
+ return nil, fmt.Errorf("callback URL must use http or https")
+ }
+ if parsed.Host == "" {
+ return nil, fmt.Errorf("callback URL host is required")
+ }
+ if parsed.User != nil {
+ return nil, fmt.Errorf("callback URL credentials are not allowed")
+ }
+
+ host := strings.TrimSuffix(strings.ToLower(parsed.Hostname()), ".")
+ if host == "" || host == "localhost" || strings.HasSuffix(host, ".localhost") {
+ return nil, fmt.Errorf("callback URL host is not allowed")
+ }
+ port := parsed.Port()
+ if port == "" {
+ switch parsed.Scheme {
+ case "http":
+ port = "80"
+ case "https":
+ port = "443"
+ default:
+ return nil, fmt.Errorf("callback URL must use http or https")
+ }
+ }
+
+ target := &validatedCallbackTarget{
+ URL: parsed,
+ Host: host,
+ Port: port,
+ }
+
+ if ip := net.ParseIP(host); ip != nil {
+ addr, err := validateWebhookIP(ip)
+ if err != nil {
+ return nil, err
+ }
+ target.IPs = []netip.Addr{addr}
+ return target, nil
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+
+ ips, err := resolveWebhookHostIPs(ctx, "ip", host)
+ if err != nil {
+ return nil, fmt.Errorf("could not resolve callback host")
+ }
+ if len(ips) == 0 {
+ return nil, fmt.Errorf("could not resolve callback host")
+ }
+ seen := make(map[netip.Addr]struct{}, len(ips))
+ for _, ip := range ips {
+ addr, err := validateWebhookIP(ip)
+ if err != nil {
+ return nil, err
+ }
+ if _, ok := seen[addr]; ok {
+ continue
+ }
+ seen[addr] = struct{}{}
+ target.IPs = append(target.IPs, addr)
+ }
+ if len(target.IPs) == 0 {
+ return nil, fmt.Errorf("could not resolve callback host")
+ }
+ return target, nil
+}
+
+func validateCallbackURL(rawURL string) error {
+ return newCallbackURLGuard().Validate(rawURL)
+}
+
+func validateCallbackTarget(rawURL string) (*validatedCallbackTarget, error) {
+ return newCallbackURLGuard().ValidateTarget(rawURL)
+}
+
+func validateWebhookIP(ip net.IP) (netip.Addr, error) {
+ if ip == nil {
+ return netip.Addr{}, fmt.Errorf("callback URL host is not allowed")
+ }
+
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return netip.Addr{}, fmt.Errorf("callback URL host is not allowed")
+ }
+ addr = addr.Unmap()
+ if addr.IsPrivate() ||
+ addr.IsLoopback() ||
+ addr.IsLinkLocalUnicast() ||
+ addr.IsLinkLocalMulticast() ||
+ addr.IsInterfaceLocalMulticast() ||
+ addr.IsMulticast() ||
+ addr.IsUnspecified() {
+ return netip.Addr{}, fmt.Errorf("callback URL host is not allowed")
+ }
+ for _, prefix := range blockedWebhookPrefixes {
+ if prefix.Contains(addr) {
+ return netip.Addr{}, fmt.Errorf("callback URL host is not allowed")
+ }
+ }
+ return addr, nil
+}
diff --git a/internal/scheduler/webhook_test.go b/internal/scheduler/webhook_test.go
index 21653faa..c2a88506 100644
--- a/internal/scheduler/webhook_test.go
+++ b/internal/scheduler/webhook_test.go
@@ -1,23 +1,76 @@
package scheduler
import (
+ "context"
"encoding/json"
"io"
+ "net"
"net/http"
"net/http/httptest"
+ "net/url"
+ "strings"
"sync/atomic"
"testing"
"time"
)
+func configureWebhookTestTarget(t *testing.T, serverURL string, timeout time.Duration) (string, *atomic.Value, func()) {
+ t.Helper()
+
+ parsed, err := url.Parse(serverURL)
+ if err != nil {
+ t.Fatalf("parse server URL: %v", err)
+ }
+
+ targetAddr := parsed.Host
+ callbackURL := parsed.Scheme + "://callback.example"
+ if parsed.Port() != "" {
+ callbackURL += ":" + parsed.Port()
+ }
+ callbackURL += parsed.Path
+
+ origResolver := resolveWebhookHostIPs
+ resolveWebhookHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ if strings.EqualFold(host, "callback.example") {
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ }
+ return origResolver(ctx, network, host)
+ }
+
+ dialedAddr := &atomic.Value{}
+ dialedAddr.Store("")
+ pinnedDialAddr := net.JoinHostPort("93.184.216.34", parsed.Port())
+
+ origTimeout := webhookHTTPTimeout
+ webhookHTTPTimeout = timeout
+
+ origDial := dialWebhookAddress
+ dialWebhookAddress = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ dialedAddr.Store(addr)
+ if addr == pinnedDialAddr {
+ addr = targetAddr
+ }
+ return (&net.Dialer{}).DialContext(ctx, network, addr)
+ }
+
+ cleanup := func() {
+ dialWebhookAddress = origDial
+ webhookHTTPTimeout = origTimeout
+ resolveWebhookHostIPs = origResolver
+ }
+ return callbackURL, dialedAddr, cleanup
+}
+
func TestSendWebhookSuccess(t *testing.T) {
var received atomic.Bool
var gotBody []byte
var gotHeaders http.Header
+ var gotHost string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received.Store(true)
gotHeaders = r.Header.Clone()
+ gotHost = r.Host
var err error
gotBody, err = io.ReadAll(r.Body)
if err != nil {
@@ -27,6 +80,9 @@ func TestSendWebhookSuccess(t *testing.T) {
}))
defer srv.Close()
+ callbackURL, dialedAddr, cleanup := configureWebhookTestTarget(t, srv.URL, 10*time.Second)
+ defer cleanup()
+
task := &Task{
ID: "tsk_webhook_1",
AgentID: "a1",
@@ -34,7 +90,7 @@ func TestSendWebhookSuccess(t *testing.T) {
State: StateDone,
}
- sendWebhook(srv.URL, task)
+ sendWebhook(callbackURL, task)
if !received.Load() {
t.Fatal("webhook was never received")
@@ -50,6 +106,12 @@ func TestSendWebhookSuccess(t *testing.T) {
if tid := gotHeaders.Get("X-PinchTab-Task-ID"); tid != "tsk_webhook_1" {
t.Errorf("expected task ID header, got %s", tid)
}
+ if !strings.HasPrefix(gotHost, "callback.example") {
+ t.Fatalf("expected request host to preserve callback hostname, got %q", gotHost)
+ }
+ if !strings.HasPrefix(dialedAddr.Load().(string), "93.184.216.34:") {
+ t.Fatalf("expected webhook dial to use pinned IP, got %q", dialedAddr.Load().(string))
+ }
// Verify body is a valid task snapshot.
var snap Task
@@ -67,24 +129,70 @@ func TestSendWebhookEmptyURL(t *testing.T) {
}
func TestSendWebhookUnsupportedScheme(t *testing.T) {
- // file:// scheme should be rejected for SSRF protection.
- sendWebhook("file:///etc/passwd", &Task{ID: "tsk_ssrf"})
- // ftp:// should also be rejected.
- sendWebhook("ftp://malicious.host/data", &Task{ID: "tsk_ssrf2"})
+ sendWebhook("file:///etc/passwd", &Task{ID: "tsk_scheme_1"})
+ sendWebhook("ftp://malicious.host/data", &Task{ID: "tsk_scheme_2"})
}
func TestSendWebhookInvalidURL(t *testing.T) {
sendWebhook("://bad-url", &Task{ID: "tsk_bad_url"})
}
+func TestSendWebhookRejectedHost(t *testing.T) {
+ sendWebhook("http://127.0.0.1/hook", &Task{ID: "tsk_blocked"})
+ sendWebhook("http://169.254.169.254/latest/meta-data", &Task{ID: "tsk_blocked2"})
+}
+
+func TestValidateCallbackURLRejectsResolvedBlockedHost(t *testing.T) {
+ origResolver := resolveWebhookHostIPs
+ resolveWebhookHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("10.0.0.8")}, nil
+ }
+ defer func() { resolveWebhookHostIPs = origResolver }()
+
+ if err := validateCallbackURL("http://callback.example/hook"); err == nil {
+ t.Fatal("expected resolved private host to be rejected")
+ }
+}
+
func TestSendWebhookServerError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
defer srv.Close()
- // Should not panic — just logs warning.
- sendWebhook(srv.URL, &Task{ID: "tsk_500", State: StateFailed})
+ callbackURL, _, cleanup := configureWebhookTestTarget(t, srv.URL, 10*time.Second)
+ defer cleanup()
+
+ sendWebhook(callbackURL, &Task{ID: "tsk_500", State: StateFailed})
+}
+
+func TestSendWebhookRedirectNotFollowed(t *testing.T) {
+ var firstHit atomic.Bool
+ var secondHit atomic.Bool
+
+ redirectTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ secondHit.Store(true)
+ w.WriteHeader(200)
+ }))
+ defer redirectTarget.Close()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ firstHit.Store(true)
+ http.Redirect(w, r, redirectTarget.URL, http.StatusTemporaryRedirect)
+ }))
+ defer srv.Close()
+
+ callbackURL, _, cleanup := configureWebhookTestTarget(t, srv.URL, 10*time.Second)
+ defer cleanup()
+
+ sendWebhook(callbackURL, &Task{ID: "tsk_redirect"})
+
+ if !firstHit.Load() {
+ t.Fatal("expected initial webhook target to receive the request")
+ }
+ if secondHit.Load() {
+ t.Fatal("redirect target should not be reached when redirects are disabled")
+ }
}
func TestSendWebhookTimeout(t *testing.T) {
@@ -94,13 +202,10 @@ func TestSendWebhookTimeout(t *testing.T) {
}))
defer srv.Close()
- // Use a short-timeout client for testing.
- origClient := webhookClient
- webhookClient = &http.Client{Timeout: 10 * time.Millisecond}
- defer func() { webhookClient = origClient }()
+ callbackURL, _, cleanup := configureWebhookTestTarget(t, srv.URL, 10*time.Millisecond)
+ defer cleanup()
- // Should not panic — timeout is logged.
- sendWebhook(srv.URL, &Task{ID: "tsk_timeout"})
+ sendWebhook(callbackURL, &Task{ID: "tsk_timeout"})
}
func TestWebhookFiredOnFinishTask(t *testing.T) {
@@ -111,6 +216,9 @@ func TestWebhookFiredOnFinishTask(t *testing.T) {
}))
defer srv.Close()
+ callbackURL, _, cleanup := configureWebhookTestTarget(t, srv.URL, 10*time.Second)
+ defer cleanup()
+
s, executor := newTestScheduler(t)
defer executor.Close()
@@ -119,7 +227,7 @@ func TestWebhookFiredOnFinishTask(t *testing.T) {
AgentID: "a1",
Action: "click",
State: StateDone,
- CallbackURL: srv.URL,
+ CallbackURL: callbackURL,
}
s.live["tsk_cb_1"] = task
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index 0a3624b8..f77db557 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -66,7 +66,7 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {
activity.Middleware(
actStore,
"bridge",
- handlers.LoggingMiddleware(handlers.AuthMiddleware(cfg, mux)),
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(cfg, mux))),
),
),
ReadHeaderTimeout: 10 * time.Second,
diff --git a/internal/server/bridge_test.go b/internal/server/bridge_test.go
index 99a1a8a6..298ed5d2 100644
--- a/internal/server/bridge_test.go
+++ b/internal/server/bridge_test.go
@@ -1,8 +1,11 @@
package server
import (
+ "net/http"
+ "net/http/httptest"
"testing"
+ "github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/handlers"
)
@@ -31,3 +34,39 @@ func TestConfigureBridgeRouter(t *testing.T) {
})
}
}
+
+func TestBridgeHandlerChainAppliesRateLimit(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret"}
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /protected", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ handler := handlers.RequestIDMiddleware(
+ activity.Middleware(
+ nil,
+ "bridge",
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(cfg, mux))),
+ ),
+ )
+
+ for i := 0; i < 120; i++ {
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ req.RemoteAddr = "198.51.100.10:41000"
+ req.Header.Set("Authorization", "Bearer secret")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("request %d: expected 200, got %d", i+1, w.Code)
+ }
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ req.RemoteAddr = "198.51.100.10:41000"
+ req.Header.Set("Authorization", "Bearer secret")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("expected 429 after limit exceeded, got %d", w.Code)
+ }
+}
diff --git a/internal/server/helpers.go b/internal/server/helpers.go
index b8623ffb..721fd553 100644
--- a/internal/server/helpers.go
+++ b/internal/server/helpers.go
@@ -5,9 +5,9 @@ import (
"net/http"
"time"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
- "github.com/pinchtab/pinchtab/internal/web"
)
func CheckPinchTabRunning(port, token string) bool {
@@ -31,7 +31,7 @@ func RegisterDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestra
mux.HandleFunc("GET /tabs", func(w http.ResponseWriter, r *http.Request) {
target := orch.FirstRunningURL()
if target == "" {
- web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
proxy.HTTP(w, r, target+"/tabs")
@@ -52,7 +52,7 @@ func RegisterDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestra
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
target := orch.FirstRunningURL()
if target == "" {
- web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
+ httpx.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
return
}
path := r.URL.Path
diff --git a/internal/server/server.go b/internal/server/server.go
index 0cb7667f..314f4d6e 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -12,16 +12,17 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/dashboard"
"github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/profiles"
"github.com/pinchtab/pinchtab/internal/scheduler"
"github.com/pinchtab/pinchtab/internal/strategy"
- "github.com/pinchtab/pinchtab/internal/web"
// Register strategies
_ "github.com/pinchtab/pinchtab/internal/strategy/alwayson"
@@ -62,6 +63,11 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
}
})
configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, version, startedAt)
+ sessions := authn.NewSessionManager(authn.SessionConfig{
+ IdleTimeout: authn.DefaultSessionIdleTimeout,
+ MaxLifetime: authn.DefaultSessionMaxLifetime,
+ })
+ authAPI := dashboard.NewAuthAPI(cfg, sessions)
// Wire up instance events to SSE broadcast
orch.OnEvent(func(evt orchestrator.InstanceEvent) {
@@ -84,6 +90,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
dash.RegisterHandlers(mux)
configAPI.RegisterHandlers(mux)
+ authAPI.RegisterHandlers(mux)
profMgr.RegisterHandlers(mux)
activity.RegisterHandlers(mux, actStore)
@@ -172,14 +179,14 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
mux.HandleFunc("GET /health", configAPI.HandleHealth)
mux.HandleFunc("GET /metrics", func(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, map[string]any{"metrics": handlers.SnapshotMetrics()})
+ httpx.JSON(w, 200, map[string]any{"metrics": handlers.SnapshotMetrics()})
})
handler := handlers.RequestIDMiddleware(
activity.Middleware(
actStore,
"server",
- handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, mux)))),
),
)
cli.LogSecurityWarnings(cfg)
@@ -222,7 +229,8 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
}
mux.HandleFunc("POST /shutdown", func(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, map[string]string{"status": "shutting down"})
+ authn.AuditLog(r, "system.shutdown_requested")
+ httpx.JSON(w, 200, map[string]string{"status": "shutting down"})
go doShutdown()
})
diff --git a/internal/server/timeouts_test.go b/internal/server/timeouts_test.go
index 90059d5f..4de2910a 100644
--- a/internal/server/timeouts_test.go
+++ b/internal/server/timeouts_test.go
@@ -1,8 +1,15 @@
package server
import (
+ "net/http"
+ "net/http/httptest"
"testing"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/handlers"
)
func TestServerTimeoutOrdering(t *testing.T) {
@@ -21,3 +28,40 @@ func TestServerTimeoutOrdering(t *testing.T) {
t.Errorf("WriteTimeout (%v) should be less than IdleTimeout (%v)", write, idle)
}
}
+
+func TestDashboardHandlerChainAppliesRateLimit(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /protected", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ handler := handlers.RequestIDMiddleware(
+ activity.Middleware(
+ nil,
+ "server",
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, mux)))),
+ ),
+ )
+
+ for i := 0; i < 120; i++ {
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ req.RemoteAddr = "198.51.100.11:41001"
+ req.Header.Set("Authorization", "Bearer secret")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("request %d: expected 200, got %d", i+1, w.Code)
+ }
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ req.RemoteAddr = "198.51.100.11:41001"
+ req.Header.Set("Authorization", "Bearer secret")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("expected 429 after limit exceeded, got %d", w.Code)
+ }
+}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index 8e113668..3ee913f4 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -18,10 +18,10 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
- "github.com/pinchtab/pinchtab/internal/web"
)
const (
@@ -435,7 +435,7 @@ func (s *Strategy) stabilityLoop() {
func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
target, err := s.ensureRunning()
if err != nil {
- web.Error(w, 503, err)
+ httpx.Error(w, 503, err)
return
}
strategy.EnrichForTarget(r, s.orch, target)
@@ -456,14 +456,14 @@ func (s *Strategy) ensureRunning() (string, error) {
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
target := s.orch.FirstRunningURL()
if target == "" {
- web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
proxy.HTTP(w, r, target+"/tabs")
}
func (s *Strategy) handleStatus(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, s.State())
+ httpx.JSON(w, 200, s.State())
}
func (s *Strategy) hasRestartLimit() bool {
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index b9fea879..c2261808 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -9,10 +9,10 @@ import (
"fmt"
"net/http"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
- "github.com/pinchtab/pinchtab/internal/web"
)
func init() {
@@ -67,7 +67,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
target := s.orch.FirstRunningURL()
if target == "" {
- web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
+ httpx.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
return
}
strategy.EnrichForTarget(r, s.orch, target)
@@ -77,7 +77,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
target := s.orch.FirstRunningURL()
if target == "" {
- web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
proxy.HTTP(w, r, target+"/tabs")
diff --git a/internal/strategy/gating.go b/internal/strategy/gating.go
index af165641..15dfdd87 100644
--- a/internal/strategy/gating.go
+++ b/internal/strategy/gating.go
@@ -3,7 +3,7 @@ package strategy
import (
"net/http"
- "github.com/pinchtab/pinchtab/internal/web"
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
// RegisterCapabilityRoute registers a route that either proxies to the active
@@ -13,5 +13,5 @@ func RegisterCapabilityRoute(mux *http.ServeMux, route string, enabled bool, fea
mux.HandleFunc(route, handler)
return
}
- mux.HandleFunc(route, web.DisabledEndpointHandler(feature, setting, code))
+ mux.HandleFunc(route, httpx.DisabledEndpointHandler(feature, setting, code))
}
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index d0ddc3fa..1f0cc56d 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -15,10 +15,10 @@ import (
"net/http"
"time"
+ "github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
- "github.com/pinchtab/pinchtab/internal/web"
)
func init() {
@@ -75,7 +75,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
target, err := s.ensureRunning()
if err != nil {
- web.Error(w, 503, err)
+ httpx.Error(w, 503, err)
return
}
strategy.EnrichForTarget(r, s.orch, target)
@@ -85,7 +85,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
target := s.orch.FirstRunningURL()
if target == "" {
- web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
proxy.HTTP(w, r, target+"/tabs")
diff --git a/internal/urlutil/urlutil.go b/internal/urls/urls.go
similarity index 95%
rename from internal/urlutil/urlutil.go
rename to internal/urls/urls.go
index 5c92feee..6d324bab 100644
--- a/internal/urlutil/urlutil.go
+++ b/internal/urls/urls.go
@@ -1,5 +1,5 @@
-// Package urlutil provides URL normalization and validation utilities.
-package urlutil
+// Package urls provides URL normalization and validation utilities.
+package urls
import (
"fmt"
diff --git a/internal/urlutil/urlutil_test.go b/internal/urls/urls_test.go
similarity index 99%
rename from internal/urlutil/urlutil_test.go
rename to internal/urls/urls_test.go
index 29e2a535..c881f56e 100644
--- a/internal/urlutil/urlutil_test.go
+++ b/internal/urls/urls_test.go
@@ -1,4 +1,4 @@
-package urlutil
+package urls
import "testing"
diff --git a/internal/web/safepath.go b/internal/web/safepath.go
deleted file mode 100644
index 630ba1b5..00000000
--- a/internal/web/safepath.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package web
-
-import (
- "fmt"
- "path/filepath"
- "strings"
-)
-
-// SafePath resolves a user-provided path against a base directory and ensures
-// the result stays within that directory. Returns the cleaned absolute path.
-//
-// The implementation uses the filepath.Abs + strings.HasPrefix pattern
-// recommended by CodeQL (go/path-injection) and OWASP path-traversal guidance.
-func SafePath(base, userPath string) (string, error) {
- absBase, err := filepath.Abs(base)
- if err != nil {
- return "", fmt.Errorf("invalid base path: %w", err)
- }
-
- // Empty or "." means the base directory itself.
- if userPath == "" || userPath == "." {
- return absBase, nil
- }
-
- // Reject absolute paths outright — user input must be relative to base.
- if filepath.IsAbs(userPath) || strings.HasPrefix(userPath, "/") || strings.HasPrefix(userPath, string(filepath.Separator)) {
- return "", fmt.Errorf("absolute paths not allowed: %q", userPath)
- }
-
- // Go 1.20+: reject paths with "..", device names (NUL, CON on Windows),
- // and other non-local components.
- if !filepath.IsLocal(userPath) {
- return "", fmt.Errorf("path %q contains invalid components", userPath)
- }
-
- // Join, clean, resolve to absolute.
- joined := filepath.Join(absBase, userPath)
- absPath, err := filepath.Abs(joined)
- if err != nil {
- return "", fmt.Errorf("invalid resolved path: %w", err)
- }
-
- // Final containment check — the resolved path must be under absBase.
- if !strings.HasPrefix(absPath, absBase+string(filepath.Separator)) && absPath != absBase {
- return "", fmt.Errorf("path %q escapes base directory %q", userPath, absBase)
- }
-
- return absPath, nil
-}
diff --git a/tests/e2e/config/pinchtab-full-permissive.json b/tests/e2e/config/pinchtab-full-permissive.json
index 1481445c..ef4e19f1 100644
--- a/tests/e2e/config/pinchtab-full-permissive.json
+++ b/tests/e2e/config/pinchtab-full-permissive.json
@@ -1,7 +1,8 @@
{
"server": {
"bind": "0.0.0.0",
- "port": "9999"
+ "port": "9999",
+ "token": "e2e-token"
},
"browser": {
"extraFlags": "--no-sandbox --disable-dev-shm-usage",
@@ -36,6 +37,7 @@
"security": {
"allowEvaluate": true,
"allowDownload": true,
+ "allowScreencast": true,
"allowUpload": true,
"attach": {
"enabled": true,
diff --git a/tests/e2e/config/pinchtab-lite.json b/tests/e2e/config/pinchtab-lite.json
index 8d89de05..18cbb89e 100644
--- a/tests/e2e/config/pinchtab-lite.json
+++ b/tests/e2e/config/pinchtab-lite.json
@@ -2,7 +2,8 @@
"server": {
"bind": "0.0.0.0",
"port": "9999",
- "engine": "lite"
+ "engine": "lite",
+ "token": "e2e-token"
},
"security": {
"allowEvaluate": false,
diff --git a/tests/e2e/config/pinchtab-medium-permissive.json b/tests/e2e/config/pinchtab-medium-permissive.json
index 13f2f7ce..b592e3cc 100644
--- a/tests/e2e/config/pinchtab-medium-permissive.json
+++ b/tests/e2e/config/pinchtab-medium-permissive.json
@@ -1,7 +1,8 @@
{
"server": {
"bind": "0.0.0.0",
- "port": "9999"
+ "port": "9999",
+ "token": "e2e-token"
},
"browser": {
"extraFlags": "--no-sandbox --disable-dev-shm-usage",
diff --git a/tests/e2e/config/pinchtab-secure.json b/tests/e2e/config/pinchtab-secure.json
index 1f2f6135..daafb95e 100644
--- a/tests/e2e/config/pinchtab-secure.json
+++ b/tests/e2e/config/pinchtab-secure.json
@@ -1,7 +1,8 @@
{
"server": {
"bind": "0.0.0.0",
- "port": "9999"
+ "port": "9999",
+ "token": "e2e-token"
},
"browser": {
"extraFlags": "--no-sandbox --disable-dev-shm-usage"
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index bec6628e..905139b8 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -1,7 +1,8 @@
{
"server": {
"bind": "0.0.0.0",
- "port": "9999"
+ "port": "9999",
+ "token": "e2e-token"
},
"browser": {
"extraFlags": "--no-sandbox --disable-dev-shm-usage",
diff --git a/tests/e2e/docker-compose-multi.yml b/tests/e2e/docker-compose-multi.yml
index b5aad009..40ba7061 100644
--- a/tests/e2e/docker-compose-multi.yml
+++ b/tests/e2e/docker-compose-multi.yml
@@ -13,7 +13,7 @@ services:
- "9999:9999"
shm_size: '2gb'
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
timeout: 10s
retries: 20
@@ -31,7 +31,7 @@ services:
- "9998:9999"
shm_size: '2gb'
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
timeout: 10s
retries: 20
@@ -50,7 +50,7 @@ services:
- "9994:9999"
shm_size: '2gb'
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
timeout: 10s
retries: 20
@@ -69,7 +69,7 @@ services:
- "9995:9999"
shm_size: '2gb'
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
timeout: 10s
retries: 20
@@ -87,7 +87,7 @@ services:
- "9997:9999"
command: ["/usr/local/bin/pinchtab", "bridge"]
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
timeout: 10s
retries: 20
@@ -146,6 +146,7 @@ services:
- E2E_MEDIUM_SERVER=http://pinchtab-medium:9999
- E2E_FULL_SERVER=http://pinchtab-full:9999
- E2E_LITE_SERVER=http://pinchtab-lite:9999
+ - E2E_SERVER_TOKEN=e2e-token
- E2E_BRIDGE_URL=http://pinchtab-bridge:9999
- E2E_BRIDGE_TOKEN=e2e-bridge-token
- FIXTURES_URL=http://fixtures:80
diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml
index ff2ba579..294118f6 100644
--- a/tests/e2e/docker-compose.yml
+++ b/tests/e2e/docker-compose.yml
@@ -13,7 +13,7 @@ services:
- "9999:9999"
shm_size: '2gb'
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
timeout: 10s
retries: 20
@@ -39,6 +39,7 @@ services:
condition: service_healthy
environment:
- E2E_SERVER=http://pinchtab:9999
+ - E2E_SERVER_TOKEN=e2e-token
- FIXTURES_URL=http://fixtures:80
volumes:
- ./:/e2e:ro
@@ -55,6 +56,7 @@ services:
condition: service_healthy
environment:
- E2E_SERVER=http://pinchtab:9999
+ - E2E_SERVER_TOKEN=e2e-token
- FIXTURES_URL=http://fixtures:80
volumes:
- ./:/e2e:ro
diff --git a/tests/e2e/fixtures/idpi-domain-pivot.html b/tests/e2e/fixtures/idpi-domain-pivot.html
new file mode 100644
index 00000000..4635a7b8
--- /dev/null
+++ b/tests/e2e/fixtures/idpi-domain-pivot.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>IDPI Domain Pivot</title>
+</head>
+<body>
+ <h1>Allowed Origin Before Pivot</h1>
+ <p>This page starts on the fixtures origin, then pivots the tab to a blocked domain.</p>
+ <script>
+ setTimeout(function () {
+ window.location.href = "https://example.com/";
+ }, 250);
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/helpers/api-http.sh b/tests/e2e/helpers/api-http.sh
index e6103f1c..9472cd32 100644
--- a/tests/e2e/helpers/api-http.sh
+++ b/tests/e2e/helpers/api-http.sh
@@ -18,7 +18,7 @@ wait_for_orchestrator_instance_status() {
fi
local inst_json
- inst_json=$(curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
+ inst_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
if [ -n "$inst_json" ]; then
local inst_status
inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
@@ -48,7 +48,7 @@ wait_for_instances_gone() {
local remaining=0
for instance_id in "${instance_ids[@]}"; do
local inst_json
- inst_json=$(curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
+ inst_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
if [ -n "$inst_json" ]; then
local inst_status
inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
@@ -84,7 +84,7 @@ wait_for_instances_running() {
local ready=0
for instance_id in "${instance_ids[@]}"; do
local inst_json
- inst_json=$(curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
+ inst_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
if [ -n "$inst_json" ]; then
local inst_status
inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
@@ -119,7 +119,7 @@ pinchtab() {
echo -e "${BLUE}→ curl -X $method ${E2E_SERVER}$path $(printf "%q " "$@")${NC}" >&2
local response
- response=$(curl -s -w "\n%{http_code}" \
+ response=$(e2e_curl -s -w "\n%{http_code}" \
-X "$method" \
"${E2E_SERVER}$path" \
-H "Content-Type: application/json" \
@@ -160,7 +160,7 @@ pt_patch() {
local body="$2"
echo -e "${BLUE}→ curl -X PATCH ${E2E_SERVER}$path${NC}" >&2
local response
- response=$(curl -s -w "\n%{http_code}" \
+ response=$(e2e_curl -s -w "\n%{http_code}" \
-X PATCH \
"${E2E_SERVER}$path" \
-H "Content-Type: application/json" \
@@ -174,7 +174,7 @@ pt_delete() {
local path="$1"
echo -e "${BLUE}→ curl -X DELETE ${E2E_SERVER}$path${NC}" >&2
local response
- response=$(curl -s -w "\n%{http_code}" \
+ response=$(e2e_curl -s -w "\n%{http_code}" \
-X DELETE \
"${E2E_SERVER}$path")
RESULT=$(echo "$response" | head -n -1)
@@ -187,7 +187,7 @@ pt_post_raw() {
local body="$2"
echo -e "${BLUE}→ curl -X POST ${E2E_SERVER}$path -d '$body'${NC}" >&2
local response
- response=$(curl -s -w "\n%{http_code}" \
+ response=$(e2e_curl -s -w "\n%{http_code}" \
-X POST \
"${E2E_SERVER}$path" \
-H "Content-Type: application/json" \
@@ -297,7 +297,7 @@ press_key() {
}
get_tab_count() {
- curl -s "${E2E_SERVER}/tabs" | jq '.tabs | length'
+ e2e_curl -s "${E2E_SERVER}/tabs" | jq '.tabs | length'
}
get_tab_id() {
diff --git a/tests/e2e/helpers/base.sh b/tests/e2e/helpers/base.sh
index 1b3754ba..4d2923df 100644
--- a/tests/e2e/helpers/base.sh
+++ b/tests/e2e/helpers/base.sh
@@ -17,6 +17,7 @@ E2E_SECURE_SERVER="${E2E_SECURE_SERVER:-http://localhost:9998}"
E2E_MEDIUM_SERVER="${E2E_MEDIUM_SERVER:-}"
E2E_FULL_SERVER="${E2E_FULL_SERVER:-}"
E2E_BRIDGE_URL="${E2E_BRIDGE_URL:-}"
+E2E_SERVER_TOKEN="${E2E_SERVER_TOKEN:-}"
E2E_BRIDGE_TOKEN="${E2E_BRIDGE_TOKEN:-}"
FIXTURES_URL="${FIXTURES_URL:-http://localhost:8080}"
RESULTS_DIR="${RESULTS_DIR:-/results}"
@@ -45,10 +46,24 @@ get_time_ms() {
fi
}
+e2e_curl() {
+ local token="${E2E_SERVER_TOKEN:-}"
+ if [ "${1:-}" = "--token" ]; then
+ token="${2:-}"
+ shift 2
+ fi
+
+ if [ -n "$token" ]; then
+ curl -H "Authorization: Bearer ${token}" "$@"
+ else
+ curl "$@"
+ fi
+}
+
wait_for_instance_ready() {
local base_url="$1"
local timeout_sec="${2:-60}"
- local token="${3:-}"
+ local token="${3:-${E2E_SERVER_TOKEN:-}}"
local started_at
started_at=$(date +%s)
@@ -61,11 +76,7 @@ wait_for_instance_ready() {
fi
local health_json
- if [ -n "$token" ]; then
- health_json=$(curl -sf -H "Authorization: Bearer ${token}" "${base_url}/health" 2>/dev/null || true)
- else
- health_json=$(curl -sf "${base_url}/health" 2>/dev/null || true)
- fi
+ health_json=$(e2e_curl --token "$token" -sf "${base_url}/health" 2>/dev/null || true)
if [ -n "$health_json" ]; then
local inst_status
inst_status=$(echo "$health_json" | jq -r '.defaultInstance.status // .status // empty' 2>/dev/null || true)
diff --git a/tests/e2e/helpers/cli.sh b/tests/e2e/helpers/cli.sh
index abcad9f8..c6b68c1c 100644
--- a/tests/e2e/helpers/cli.sh
+++ b/tests/e2e/helpers/cli.sh
@@ -13,11 +13,23 @@ pt() {
tmpout=$(mktemp)
local tmperr
tmperr=$(mktemp)
+ local first_arg="${1:-}"
+ local -a cmd_prefix=()
+
+ case "$first_arg" in
+ ""|config|daemon|security|help|--help|version|--version)
+ ;;
+ *)
+ if [ -n "${E2E_SERVER_TOKEN:-}" ]; then
+ cmd_prefix=(env "PINCHTAB_TOKEN=${E2E_SERVER_TOKEN}")
+ fi
+ ;;
+ esac
echo -e " ${BLUE}→ pinchtab --server $E2E_SERVER $@${NC}"
set +e
- pinchtab --server "$E2E_SERVER" "$@" > "$tmpout" 2> "$tmperr"
+ "${cmd_prefix[@]}" pinchtab --server "$E2E_SERVER" "$@" > "$tmpout" 2> "$tmperr"
PT_CODE=$?
set -e
diff --git a/tests/e2e/scenarios-api/auth-full.sh b/tests/e2e/scenarios-api/auth-full.sh
new file mode 100644
index 00000000..aa322566
--- /dev/null
+++ b/tests/e2e/scenarios-api/auth-full.sh
@@ -0,0 +1,338 @@
+#!/bin/bash
+# auth-full.sh — API auth, session, and elevation scenarios.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/api.sh"
+
+AUTH_COOKIE_FILE="/tmp/pinchtab-auth-cookie-$$.txt"
+AUTH_HEADERS_FILE="/tmp/pinchtab-auth-headers-$$.txt"
+AUTH_BODY_FILE="/tmp/pinchtab-auth-body-$$.txt"
+
+trap 'rm -f "$AUTH_COOKIE_FILE" "$AUTH_HEADERS_FILE" "$AUTH_BODY_FILE"' EXIT
+
+auth_reset_session() {
+ rm -f "$AUTH_COOKIE_FILE" "$AUTH_HEADERS_FILE" "$AUTH_BODY_FILE"
+ : > "$AUTH_COOKIE_FILE"
+ : > "$AUTH_HEADERS_FILE"
+ : > "$AUTH_BODY_FILE"
+}
+
+capture_session_cookie() {
+ local cookie_line
+ cookie_line=$(grep -i '^Set-Cookie: pinchtab_auth_token=' "$AUTH_HEADERS_FILE" | tail -n 1 | sed 's/\r$//' || true)
+ if [[ -z "$cookie_line" ]]; then
+ return
+ fi
+
+ echo "$cookie_line" | sed -E 's/^Set-Cookie: ([^;]+).*/\1/I' > "$AUTH_COOKIE_FILE"
+}
+
+auth_request() {
+ local method="$1"
+ local path="$2"
+ shift 2
+
+ echo -e "${BLUE}→ curl -X $method ${E2E_SERVER}$path $(printf "%q " "$@")${NC}" >&2
+
+ local -a cookie_args=()
+ if [[ -s "$AUTH_COOKIE_FILE" ]]; then
+ cookie_args=(-H "Cookie: $(cat "$AUTH_COOKIE_FILE")")
+ fi
+
+ local response
+ response=$(e2e_curl --token "" -s -D "$AUTH_HEADERS_FILE" -w "\n%{http_code}" \
+ -X "$method" \
+ "${E2E_SERVER}$path" \
+ "${cookie_args[@]}" \
+ "$@")
+
+ capture_session_cookie
+
+ RESULT=$(echo "$response" | head -n -1)
+ HTTP_STATUS=$(echo "$response" | tail -n 1)
+
+ if [[ ! "$HTTP_STATUS" =~ ^2 ]]; then
+ echo -e "${ERROR} HTTP $HTTP_STATUS: $RESULT${NC}" >&2
+ fi
+}
+
+auth_get() {
+ local path="$1"
+ shift
+ auth_request GET "$path" "$@"
+ _echo_truncated
+}
+
+auth_post_json() {
+ local path="$1"
+ local body="$2"
+ shift 2
+ auth_request POST "$path" -H "Content-Type: application/json" -d "$body" "$@"
+ _echo_truncated
+}
+
+auth_put_json() {
+ local path="$1"
+ local body="$2"
+ shift 2
+ auth_request PUT "$path" -H "Content-Type: application/json" -d "$body" "$@"
+ _echo_truncated
+}
+
+assert_auth_header_contains() {
+ local needle="$1"
+ local desc="${2:-header contains '$needle'}"
+ local headers
+ headers=$(cat "$AUTH_HEADERS_FILE" 2>/dev/null || true)
+ assert_contains "$headers" "$needle" "$desc"
+}
+
+assert_session_cookie_present() {
+ local desc="${1:-session cookie persisted}"
+ local cookie
+ cookie=$(cat "$AUTH_COOKIE_FILE" 2>/dev/null || true)
+ assert_contains "$cookie" "pinchtab_auth_token=" "$desc"
+}
+
+auth_ws_get() {
+ local path="$1"
+ shift
+
+ rm -f "$AUTH_HEADERS_FILE" "$AUTH_BODY_FILE"
+ : > "$AUTH_HEADERS_FILE"
+ : > "$AUTH_BODY_FILE"
+
+ echo -e "${BLUE}→ curl -X GET ${E2E_SERVER}$path [websocket] $(printf "%q " "$@")${NC}" >&2
+
+ local -a cookie_args=()
+ if [[ -s "$AUTH_COOKIE_FILE" ]]; then
+ cookie_args=(-H "Cookie: $(cat "$AUTH_COOKIE_FILE")")
+ fi
+
+ e2e_curl --token "" -s --http1.1 \
+ -X GET \
+ "${E2E_SERVER}$path" \
+ "${cookie_args[@]}" \
+ -D "$AUTH_HEADERS_FILE" \
+ -o "$AUTH_BODY_FILE" \
+ -H "Connection: Upgrade" \
+ -H "Upgrade: websocket" \
+ -H "Sec-WebSocket-Version: 13" \
+ -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
+ --max-time 2 \
+ "$@" >/dev/null 2>&1 || true
+
+ capture_session_cookie
+
+ RESULT=$(cat "$AUTH_BODY_FILE" 2>/dev/null || true)
+ HTTP_STATUS=$(grep '^HTTP/' "$AUTH_HEADERS_FILE" | tail -n 1 | awk '{print $2}')
+
+ if [[ "$HTTP_STATUS" != "101" && ! "$HTTP_STATUS" =~ ^2 && -n "$RESULT" ]]; then
+ echo -e "${ERROR} HTTP $HTTP_STATUS: $RESULT${NC}" >&2
+ fi
+}
+
+start_test "auth: query token is rejected"
+
+auth_reset_session
+auth_get "/health?token=${E2E_SERVER_TOKEN}"
+assert_http_status 401 "query token auth rejected"
+assert_contains "$RESULT" "missing_token" "query token ignored"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: login sets session cookie"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+assert_json_value "$RESULT" ".status" "ok" "login status ok"
+assert_auth_header_contains "Set-Cookie: pinchtab_auth_token=" "session cookie set"
+assert_session_cookie_present "session cookie stored in cookie jar"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: session cookie can access allowed dashboard route"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_get /api/config -H "Origin: ${E2E_SERVER}"
+assert_http_status 200 "cookie auth can access config"
+assert_json_exists "$RESULT" ".config" "config payload returned"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: cookie auth rejects cross-origin requests"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_get /api/config -H "Origin: http://evil.example"
+assert_http_status 403 "cross-origin cookie request blocked"
+assert_contains "$RESULT" "origin_forbidden" "origin error code returned"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: cookie auth allows same-origin requests"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_get /api/config -H "Origin: ${E2E_SERVER}"
+assert_http_status 200 "same-origin cookie request allowed"
+assert_json_exists "$RESULT" ".config" "config payload returned"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: sensitive dashboard config update requires elevation"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_put_json /api/config '{"server":{"token":"forbidden-from-dashboard"}}' -H "Origin: ${E2E_SERVER}"
+assert_http_status 403 "config update requires elevation"
+assert_contains "$RESULT" "elevation_required" "elevation error code returned"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: elevation unlocks sensitive dashboard config update"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_post_json /api/auth/elevate "{\"token\":\"${E2E_SERVER_TOKEN}\"}" -H "Origin: ${E2E_SERVER}"
+assert_http_status 200 "session elevated"
+assert_json_exists "$RESULT" ".elevationWindowSec" "elevation window returned"
+auth_put_json /api/config '{"server":{"token":"forbidden-from-dashboard"}}' -H "Origin: ${E2E_SERVER}"
+assert_http_status 400 "elevated request reaches config handler"
+assert_contains "$RESULT" "token_write_only" "write-only token guard returned"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: header auth bypasses dashboard elevation flow for config updates"
+
+pt PUT /api/config -d '{"server":{"token":"forbidden-from-dashboard"}}'
+assert_http_status 400 "header auth reaches config handler directly"
+assert_contains "$RESULT" "token_write_only" "write-only token guard returned"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: cookie session cannot use download endpoint"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_get "/download?url=https://httpbin.org/robots.txt" -H "Origin: ${E2E_SERVER}"
+assert_http_status 403 "cookie session blocked on download endpoint"
+assert_contains "$RESULT" "header_auth_required" "download requires authorization header"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: cookie session cannot use tab download endpoint"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/table.html\"}"
+DOWNLOAD_TAB_ID=$(get_tab_id)
+assert_ok "navigate for tab download auth boundary"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_get "/tabs/${DOWNLOAD_TAB_ID}/download?url=https://httpbin.org/robots.txt" -H "Origin: ${E2E_SERVER}"
+assert_http_status 403 "cookie session blocked on download endpoint"
+assert_contains "$RESULT" "header_auth_required" "download requires authorization header"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: screencast websocket rejects bad origin for cookie session"
+
+OLD_SERVER="$E2E_SERVER"
+E2E_SERVER="${E2E_FULL_SERVER:-$E2E_SERVER}"
+
+pt_get /instances
+SCREENCAST_INST_ID=$(echo "$RESULT" | jq -r '.[0].id')
+assert_ok "list instances for screencast"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/table.html\"}"
+SCREENCAST_TAB_ID=$(get_tab_id)
+assert_ok "navigate for screencast auth boundary"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_ws_get "/instances/${SCREENCAST_INST_ID}/proxy/screencast?tabId=${SCREENCAST_TAB_ID}" -H "Origin: http://evil.example"
+assert_http_status 403 "bad origin websocket upgrade blocked"
+assert_contains "$RESULT" "origin_forbidden" "websocket origin error returned"
+
+E2E_SERVER="$OLD_SERVER"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: screencast websocket allows same-origin cookie session"
+
+OLD_SERVER="$E2E_SERVER"
+E2E_SERVER="${E2E_FULL_SERVER:-$E2E_SERVER}"
+
+pt_get /instances
+SCREENCAST_INST_ID=$(echo "$RESULT" | jq -r '.[0].id')
+assert_ok "list instances for same-origin screencast"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/table.html\"}"
+SCREENCAST_TAB_ID=$(get_tab_id)
+assert_ok "navigate for same-origin screencast"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_ws_get "/instances/${SCREENCAST_INST_ID}/proxy/screencast?tabId=${SCREENCAST_TAB_ID}" -H "Origin: ${E2E_SERVER}"
+assert_http_status 101 "same-origin websocket upgrade allowed"
+assert_auth_header_contains "101 Switching Protocols" "websocket handshake completed"
+
+E2E_SERVER="$OLD_SERVER"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: logout revokes the session cookie"
+
+auth_reset_session
+auth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"
+assert_http_status 200 "login succeeds"
+auth_request POST /api/auth/logout
+assert_http_status 200 "logout succeeds"
+assert_json_value "$RESULT" ".status" "ok" "logout status ok"
+auth_get /api/config
+assert_http_status 401 "logged out session cannot access config"
+assert_contains "$RESULT" "missing_token" "session cookie no longer accepted"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "auth: login attempts are rate limited"
+
+auth_reset_session
+
+for attempt in $(seq 1 10); do
+ auth_post_json /api/auth/login '{"token":"wrong-token"}'
+ assert_http_status 401 "bad login attempt ${attempt}"
+ assert_contains "$RESULT" "bad_token" "bad token rejected on attempt ${attempt}"
+done
+
+auth_post_json /api/auth/login '{"token":"wrong-token"}'
+assert_http_status 429 "rate limit triggers after repeated failures"
+assert_contains "$RESULT" "login_rate_limited" "rate limit error code returned"
+assert_json_exists "$RESULT" ".details.retryAfterSec" "retry-after details returned"
+assert_auth_header_contains "Retry-After: " "retry-after header returned"
+
+end_test
diff --git a/tests/e2e/scenarios-api/browser-basic.sh b/tests/e2e/scenarios-api/browser-basic.sh
index 5cddc92a..4b82bb92 100644
--- a/tests/e2e/scenarios-api/browser-basic.sh
+++ b/tests/e2e/scenarios-api/browser-basic.sh
@@ -136,7 +136,7 @@ start_test "pinchtab text (table.html)"
pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/table.html\"}"
sleep 1
-TEXT_RESULT=$(curl -s "${E2E_SERVER}/text" | jq -r '.text')
+TEXT_RESULT=$(e2e_curl -s "${E2E_SERVER}/text" | jq -r '.text')
assert_table_page "$TEXT_RESULT"
end_test
@@ -573,7 +573,7 @@ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
assert_ok "navigate"
# format=text should return plain text content type
-RESPONSE=$(curl -s -w "\n%{http_code}\n%{content_type}" "${E2E_SERVER}/text?format=text")
+RESPONSE=$(e2e_curl -s -w "\n%{http_code}\n%{content_type}" "${E2E_SERVER}/text?format=text")
BODY=$(echo "$RESPONSE" | head -n -2)
STATUS=$(echo "$RESPONSE" | tail -n 2 | head -1)
CTYPE=$(echo "$RESPONSE" | tail -n 1)
diff --git a/tests/e2e/scenarios-api/files-basic.sh b/tests/e2e/scenarios-api/files-basic.sh
index c83ecfa4..40d9bf43 100644
--- a/tests/e2e/scenarios-api/files-basic.sh
+++ b/tests/e2e/scenarios-api/files-basic.sh
@@ -62,8 +62,8 @@ start_test "screenshot: quality parameter"
pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/table.html\"}"
sleep 1
-LOW_Q_SIZE=$(curl -s "${E2E_SERVER}/screenshot?quality=10" | wc -c)
-HIGH_Q_SIZE=$(curl -s "${E2E_SERVER}/screenshot?quality=95" | wc -c)
+LOW_Q_SIZE=$(e2e_curl -s "${E2E_SERVER}/screenshot?quality=10" | wc -c)
+HIGH_Q_SIZE=$(e2e_curl -s "${E2E_SERVER}/screenshot?quality=95" | wc -c)
if [ "$LOW_Q_SIZE" -lt "$HIGH_Q_SIZE" ]; then
echo -e " ${GREEN}✓${NC} quality=10 ($LOW_Q_SIZE bytes) < quality=95 ($HIGH_Q_SIZE bytes)"
diff --git a/tests/e2e/scenarios-api/files-full.sh b/tests/e2e/scenarios-api/files-full.sh
index 6b414c19..c4b55edc 100644
--- a/tests/e2e/scenarios-api/files-full.sh
+++ b/tests/e2e/scenarios-api/files-full.sh
@@ -51,6 +51,15 @@ assert_not_ok "rejects missing file"
end_test
+# ─────────────────────────────────────────────────────────────────
+start_test "upload: too many files → error"
+
+pt_post /upload '{"selector":"#multi-file","files":["data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ==","data:text/plain;base64,QQ=="]}'
+assert_http_status 400 "rejects too many files"
+assert_contains "$RESULT" "too many files" "too many files message returned"
+
+end_test
+
# Migrated from: tests/integration/pdf_test.go (PD1-PD12)
pt_post /navigate "{\"url\":\"${FIXTURES_URL}/table.html\"}"
diff --git a/tests/e2e/scenarios-api/system-basic.sh b/tests/e2e/scenarios-api/system-basic.sh
index ff1a7b33..6fe94a34 100644
--- a/tests/e2e/scenarios-api/system-basic.sh
+++ b/tests/e2e/scenarios-api/system-basic.sh
@@ -148,7 +148,9 @@ assert_instance_logs_poll() {
local i
for i in $(seq 1 "$attempts"); do
E2E_SERVER=$ORCH_URL pt_get "/instances/${inst_id}/logs" >/dev/null
- if [[ "$HTTP_STATUS" =~ ^2 ]] && echo "$RESULT" | grep -Fq "$needle"; then
+ # Avoid a false negative under `set -o pipefail`: `grep -q` exits early
+ # after a match, which can SIGPIPE the writer side of a pipeline.
+ if [[ "$HTTP_STATUS" =~ ^2 ]] && grep -Fq -- "$needle" <<<"$RESULT"; then
echo -e " ${GREEN}✓${NC} $desc"
((ASSERTIONS_PASSED++)) || true
return 0
diff --git a/tests/e2e/scenarios-api/system-full.sh b/tests/e2e/scenarios-api/system-full.sh
index 1df7d2f2..61eb270c 100644
--- a/tests/e2e/scenarios-api/system-full.sh
+++ b/tests/e2e/scenarios-api/system-full.sh
@@ -193,7 +193,7 @@ idpi_setup() {
idpi_cleanup() {
local base_url="$1" tab_id="$2"
- curl -sf -X POST "${base_url}/tab" \
+ e2e_curl -sf -X POST "${base_url}/tab" \
-H "Content-Type: application/json" \
-d "{\"tabId\":\"$tab_id\",\"action\":\"close\"}" >/dev/null 2>&1 || true
}
@@ -208,7 +208,7 @@ idpi_request() {
local curl_args=(-s -w "\n%{http_code}" -X "$method" "${base_url}${path}" -H "Content-Type: application/json" -D "$tmpheaders")
[ -n "$body" ] && curl_args+=(-d "$body")
local response
- response=$(curl "${curl_args[@]}")
+ response=$(e2e_curl "${curl_args[@]}")
RESULT=$(echo "$response" | head -n -1)
HTTP_STATUS=$(echo "$response" | tail -n 1)
HDR_VALUE=$(grep -i "^${header_name}:" "$tmpheaders" | sed 's/^[^:]*: *//' | tr -d '\r' | head -1)
@@ -287,6 +287,29 @@ assert_contains "$RESULT" "idpi" "403 body mentions IDPI"
idpi_cleanup "$E2E_SECURE_SERVER" "$TAB_ID"
end_test
+# ─────────────────────────────────────────────────────────────────
+start_test "idpi: same-tab domain pivot warns in warn mode"
+TAB_ID=$(idpi_setup "$E2E_SERVER" "${FIXTURES_URL}/idpi-domain-pivot.html")
+sleep 2
+idpi_request GET "$E2E_SERVER" "/tabs/${TAB_ID}/text" "" "X-IDPI-Warning"
+assert_ok "text allowed after domain pivot in warn mode"
+assert_header_present "X-IDPI-Warning present after domain pivot"
+assert_json_contains "$RESULT" ".url" "example.com" "warn mode response reflects pivoted URL"
+idpi_cleanup "$E2E_SERVER" "$TAB_ID"
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "idpi: same-tab domain pivot blocks in strict mode"
+TAB_ID=$(idpi_setup "$E2E_SECURE_SERVER" "${FIXTURES_URL}/idpi-domain-pivot.html")
+sleep 2
+idpi_request GET "$E2E_SECURE_SERVER" "/tabs/${TAB_ID}/text" "" "X-IDPI-Warning"
+assert_http_status 403 "text blocked after domain pivot in strict mode"
+assert_header_present "X-IDPI-Warning present on strict block"
+assert_contains "$RESULT" "idpi_domain_blocked" "strict block returns domain policy code"
+assert_contains "$RESULT" "allowedDomains" "strict block mentions domain policy"
+idpi_cleanup "$E2E_SECURE_SERVER" "$TAB_ID"
+end_test
+
# /pdf — WARN MODE (main instance)
start_test "idpi: /pdf clean page — no warning (warn mode)"
@@ -327,7 +350,7 @@ end_test
start_test "idpi: multiple injection phrases — single warning header"
TAB_ID=$(idpi_setup "$E2E_SERVER" "${FIXTURES_URL}/idpi-inject.html")
tmpheaders=$(mktemp)
-curl -s -X POST "${E2E_SERVER}/tabs/${TAB_ID}/find" \
+e2e_curl -s -X POST "${E2E_SERVER}/tabs/${TAB_ID}/find" \
-H "Content-Type: application/json" \
-D "$tmpheaders" \
-d "$FIND_BODY" >/dev/null
@@ -550,7 +573,7 @@ lite() {
shift 2
echo -e "${BLUE}→ curl -X $method ${LITE_URL}$path $(printf "%q " "$@")${NC}" >&2
local response
- response=$(curl -s -w "\n%{http_code}" \
+ response=$(e2e_curl -s -w "\n%{http_code}" \
-X "$method" \
"${LITE_URL}${path}" \
-H "Content-Type: application/json" \
diff --git a/tests/e2e/scenarios-api/tabs-full.sh b/tests/e2e/scenarios-api/tabs-full.sh
index f9e39a9a..ff5e5586 100644
--- a/tests/e2e/scenarios-api/tabs-full.sh
+++ b/tests/e2e/scenarios-api/tabs-full.sh
@@ -25,6 +25,34 @@ assert_json_contains "$RESULT" ".files" "2" "uploaded 2 files"
end_test
+# ─────────────────────────────────────────────────────────────────
+start_test "tab-specific upload: locked tab rejects wrong owner"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/upload.html\"}"
+LOCKED_UPLOAD_TAB_ID=$(get_tab_id)
+show_tab "created" "$LOCKED_UPLOAD_TAB_ID"
+
+pt_post "/tabs/${LOCKED_UPLOAD_TAB_ID}/lock" -d '{"owner":"agent-a"}'
+assert_ok "lock upload tab"
+
+pinchtab POST "/tabs/${LOCKED_UPLOAD_TAB_ID}/upload" \
+ -H "X-Owner: intruder" \
+ -d '{"selector":"#single-file","files":["data:text/plain;base64,dGVzdCBmaWxl"]}'
+_echo_truncated
+assert_http_status 423 "wrong owner blocked on upload"
+assert_contains "$RESULT" "tab_locked" "locked tab error returned for upload"
+
+pinchtab POST "/tabs/${LOCKED_UPLOAD_TAB_ID}/upload" \
+ -H "X-Owner: agent-a" \
+ -d '{"selector":"#single-file","files":["data:text/plain;base64,dGVzdCBmaWxl"]}'
+_echo_truncated
+assert_ok "correct owner can upload to locked tab"
+
+pt_post "/tabs/${LOCKED_UPLOAD_TAB_ID}/unlock" -d '{"owner":"agent-a"}'
+assert_ok "unlock upload tab"
+
+end_test
+
# ─────────────────────────────────────────────────────────────────
start_test "tab-specific download: GET /tabs/{id}/download"
@@ -55,6 +83,32 @@ end_test
# Note: Chrome keeps an initial about:blank target that is unmanaged.
# Eviction is based on managed tab count, not Chrome target count.
+# ─────────────────────────────────────────────────────────────────
+start_test "tab-specific download: locked tab rejects wrong owner"
+
+pt_post /navigate -d '{"url":"https://httpbin.org/robots.txt"}'
+LOCKED_DOWNLOAD_TAB_ID=$(get_tab_id)
+show_tab "created" "$LOCKED_DOWNLOAD_TAB_ID"
+
+pt_post "/tabs/${LOCKED_DOWNLOAD_TAB_ID}/lock" -d '{"owner":"agent-a"}'
+assert_ok "lock download tab"
+
+pinchtab GET "/tabs/${LOCKED_DOWNLOAD_TAB_ID}/download?url=https://httpbin.org/json" \
+ -H "X-Owner: intruder"
+_echo_truncated
+assert_http_status 423 "wrong owner blocked on download"
+assert_contains "$RESULT" "tab_locked" "locked tab error returned for download"
+
+pinchtab GET "/tabs/${LOCKED_DOWNLOAD_TAB_ID}/download?url=https://httpbin.org/json" \
+ -H "X-Owner: agent-a"
+_echo_truncated
+assert_ok "correct owner can download from locked tab"
+
+pt_post "/tabs/${LOCKED_DOWNLOAD_TAB_ID}/unlock" -d '{"owner":"agent-a"}'
+assert_ok "unlock download tab"
+
+end_test
+
ORIG_URL="$E2E_SERVER"
E2E_SERVER="$E2E_SECURE_SERVER"