Skip to content

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

feat: add network route/unroute request interception

Luigi Agostia26f83e76bc1
diff --git a/cmd/pinchtab/cmd_cli_network_route.go b/cmd/pinchtab/cmd_cli_network_route.go
new file mode 100644
index 00000000..1d156a17
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_network_route.go
@@ -0,0 +1,40 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var networkRouteCmd = &cobra.Command{
+ Use: "route <url>",
+ Short: "Intercept matching requests on the active tab",
+ Long: `Install a network interception rule on the active tab. The pattern is matched
+against request URLs as a substring (no wildcards) or as a glob ('*', '?').
+
+ pinchtab network route '*.png' --abort # block matching requests
+ pinchtab network route 'api/users' --body '{}' # fulfill with JSON body
+ pinchtab network route 'tracker.io' # pass-through (no-op rule)
+
+Use 'pinchtab network unroute' to remove a rule.`,
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.NetworkRoute(rt.client, rt.base, rt.token, cmd, args[0])
+ })
+ },
+}
+
+var networkUnrouteCmd = &cobra.Command{
+ Use: "unroute [url]",
+ Short: "Remove an interception rule (or all rules if no pattern given)",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ pattern := ""
+ if len(args) > 0 {
+ pattern = args[0]
+ }
+ runCLI(func(rt cliRuntime) {
+ browseractions.NetworkUnroute(rt.client, rt.base, rt.token, cmd, pattern)
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 99650466..a70dfab4 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -79,6 +79,7 @@ func registerBrowserCommands() {
keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)
dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)
mouseCmd.AddCommand(mouseMoveCmd, mouseDownCmd, mouseUpCmd, mouseWheelCmd)
+ networkCmd.AddCommand(networkRouteCmd, networkUnrouteCmd)
configureBrowserFlags()
@@ -374,6 +375,15 @@ func configureBrowserFlags() {
scrollintoviewCmd.Flags().String("css", "", "CSS selector instead of ref")
+ networkRouteCmd.Flags().Bool("abort", false, "Block matching requests instead of letting them through")
+ networkRouteCmd.Flags().String("body", "", "Fulfill matching requests with this JSON body (mutually exclusive with --abort)")
+ networkRouteCmd.Flags().String("resource-type", "", "Limit to a CDP resource category (e.g. script, image, xhr, fetch)")
+ networkRouteCmd.Flags().String("content-type", "", "(With --body) Response Content-Type (default application/json)")
+ networkRouteCmd.Flags().Int("status", 0, "(With --body) Response status code (default 200)")
+ networkRouteCmd.Flags().String("method", "", "Limit to an HTTP method (GET, POST, ...). Fulfill rules without --method skip OPTIONS preflights to avoid breaking CORS.")
+ addTabFlag(networkRouteCmd, networkUnrouteCmd)
+ addJSONFlag(networkRouteCmd, networkUnrouteCmd)
+
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)")
diff --git a/dashboard/src/pages/settings/settingsShared.ts b/dashboard/src/pages/settings/settingsShared.ts
index 6a802d51..944a1c95 100644
--- a/dashboard/src/pages/settings/settingsShared.ts
+++ b/dashboard/src/pages/settings/settingsShared.ts
@@ -103,6 +103,7 @@ export const securityEndpointRows = [
["allowScreencast", "Allow screencast"],
["allowDownload", "Allow download"],
["allowUpload", "Allow upload"],
+ ["allowNetworkIntercept", "Allow network interception"],
] as const satisfies ReadonlyArray<readonly [SecurityEndpointKey, string]>;
export const idpiToggleRows = [
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index a6edd12e..dfe0aa01 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -133,6 +133,7 @@ export interface BackendSecurityConfig {
allowScreencast: boolean;
allowDownload: boolean;
allowUpload: boolean;
+ allowNetworkIntercept: boolean;
allowedDomains: string[];
trustedProxyCIDRs: string[];
trustedResolveCIDRs: string[];
@@ -261,6 +262,7 @@ export const defaultBackendConfig: BackendConfig = {
allowScreencast: false,
allowDownload: false,
allowUpload: false,
+ allowNetworkIntercept: false,
allowedDomains: ["127.0.0.1", "localhost", "::1"],
trustedProxyCIDRs: [],
trustedResolveCIDRs: [],
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index 03eaa667..8bf56e78 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -60,6 +60,11 @@ type BridgeAPI interface {
// Network monitoring
NetworkMonitor() *NetworkMonitor
+ // Network request interception (Fetch domain).
+ AddRouteRule(tabID string, rule RouteRule) error
+ RemoveRouteRule(tabID, pattern string) (int, error)
+ ListRouteRules(tabID string) ([]RouteRule, error)
+
// Dialog management
GetDialogManager() *DialogManager
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index f267ee8d..f977f7b5 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -30,6 +30,10 @@ type Bridge struct {
// Network monitoring
netMonitor *NetworkMonitor
+ // Network route interception (Fetch domain). Lazy: enables CDP fetch
+ // only when at least one rule is active for a tab.
+ routeMgr *RouteManager
+
fingerprintMu sync.RWMutex
fingerprintOverlays map[string]bool
workerStealthTargets sync.Map
@@ -70,6 +74,12 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
LogStore: logStore,
stealthLaunchMode: stealth.LaunchModeUninitialized,
}
+ b.routeMgr = NewRouteManager(func() []string {
+ if b.Config == nil {
+ return nil
+ }
+ return b.Config.AllowedDomains
+ })
b.ensureStealthBundle()
b.Dialogs = NewDialogManager()
if cfg != nil && browserCtx != nil {
@@ -77,6 +87,7 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
b.SetOnAfterClose(func() { go b.SaveState() })
b.SetDialogManager(b.Dialogs)
b.SetNetworkMonitor(b.netMonitor)
+ b.SetRouteManager(b.routeMgr)
if !b.quietStealthObservers() {
b.StartBrowserGuards()
}
@@ -247,6 +258,44 @@ func (b *Bridge) NetworkMonitor() *NetworkMonitor {
return b.netMonitor
}
+// AddRouteRule installs (or replaces by Pattern) an interception rule for the
+// given tab. The first call for a tab enables CDP Fetch interception.
+func (b *Bridge) AddRouteRule(tabID string, rule RouteRule) error {
+ if b.routeMgr == nil {
+ return fmt.Errorf("route manager not initialized")
+ }
+ tabCtx, resolvedID, err := b.TabContext(tabID)
+ if err != nil {
+ return err
+ }
+ return b.routeMgr.AddRule(tabCtx, resolvedID, rule)
+}
+
+// RemoveRouteRule removes a rule by Pattern, or all rules when pattern is empty.
+// Returns the count of rules removed.
+func (b *Bridge) RemoveRouteRule(tabID, pattern string) (int, error) {
+ if b.routeMgr == nil {
+ return 0, fmt.Errorf("route manager not initialized")
+ }
+ tabCtx, resolvedID, err := b.TabContext(tabID)
+ if err != nil {
+ return 0, err
+ }
+ return b.routeMgr.Remove(tabCtx, resolvedID, pattern)
+}
+
+// ListRouteRules returns the current interception rules for a tab.
+func (b *Bridge) ListRouteRules(tabID string) ([]RouteRule, error) {
+ if b.routeMgr == nil {
+ return nil, fmt.Errorf("route manager not initialized")
+ }
+ _, resolvedID, err := b.TabContext(tabID)
+ if err != nil {
+ return nil, err
+ }
+ return b.routeMgr.List(resolvedID), nil
+}
+
// GetDialogManager returns the bridge's dialog manager.
func (b *Bridge) GetDialogManager() *DialogManager {
return b.Dialogs
diff --git a/internal/bridge/route.go b/internal/bridge/route.go
new file mode 100644
index 00000000..33c85dd1
--- /dev/null
+++ b/internal/bridge/route.go
@@ -0,0 +1,717 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/url"
+ "regexp"
+ "strings"
+ "sync"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/fetch"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/security"
+)
+
+// RouteAction names how an intercepted request should be handled.
+type RouteAction string
+
+const (
+ RouteActionContinue RouteAction = "continue"
+ RouteActionAbort RouteAction = "abort"
+ RouteActionFulfill RouteAction = "fulfill"
+)
+
+// allowedFulfillContentTypes is the explicit safe-list of MIME types that may
+// be used as the Content-Type of a fulfilled (mocked) response. Notably
+// excluded: text/html, application/javascript (and aliases),
+// application/xhtml+xml, image/svg+xml — all of which execute script in the
+// response origin's security context. Allowing those would let an agent (or
+// prompt-injection in the agent's input) run JS in any third-party origin
+// it can navigate the page to call.
+var allowedFulfillContentTypes = map[string]struct{}{
+ "application/json": {},
+ "application/xml": {},
+ "application/pdf": {},
+ "application/octet-stream": {},
+ "text/plain": {},
+ "text/csv": {},
+ "text/xml": {},
+ "image/png": {},
+ "image/jpeg": {},
+ "image/gif": {},
+ "image/webp": {},
+ "video/mp4": {},
+ "video/webm": {},
+ "audio/mpeg": {},
+ "audio/ogg": {},
+ "audio/wav": {},
+}
+
+// validResourceTypes is the CDP Network.ResourceType enum lowercased. Match
+// is case-insensitive (see ruleMatches), so callers can pass "Script", "xhr",
+// etc., but the rule must name a known category.
+var validResourceTypes = map[string]struct{}{
+ "document": {},
+ "stylesheet": {},
+ "image": {},
+ "media": {},
+ "font": {},
+ "script": {},
+ "texttrack": {},
+ "xhr": {},
+ "fetch": {},
+ "prefetch": {},
+ "eventsource": {},
+ "websocket": {},
+ "manifest": {},
+ "signedexchange": {},
+ "ping": {},
+ "cspviolationreport": {},
+ "preflight": {},
+ "other": {},
+}
+
+// IsFulfillContentTypeAllowed reports whether ct is on the safe-list and free
+// of header-injection control bytes. Empty ct returns true — AddRule defaults
+// it to application/json before storing.
+func IsFulfillContentTypeAllowed(ct string) bool {
+ if ct == "" {
+ return true
+ }
+ if containsHeaderControlChar(ct) {
+ return false
+ }
+ base := strings.TrimSpace(strings.ToLower(strings.SplitN(ct, ";", 2)[0]))
+ _, ok := allowedFulfillContentTypes[base]
+ return ok
+}
+
+// IsResourceTypeValid reports whether rt names a known CDP resource category.
+// Empty rt is valid (means "no resource-type filter").
+func IsResourceTypeValid(rt string) bool {
+ if rt == "" {
+ return true
+ }
+ _, ok := validResourceTypes[strings.ToLower(rt)]
+ return ok
+}
+
+// normalizeHTTPMethod returns the upper-case form of m (trimmed) when it is a
+// recognised HTTP method, and ok=false otherwise. Only methods the browser
+// actually emits are accepted; custom verbs would never match a browser
+// request anyway, so there's no point letting them through.
+func normalizeHTTPMethod(m string) (string, bool) {
+ upper := strings.ToUpper(strings.TrimSpace(m))
+ switch upper {
+ case "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "CONNECT", "TRACE":
+ return upper, true
+ }
+ return "", false
+}
+
+// containsHeaderControlChar reports whether s contains any byte that would
+// allow header injection if the string were spliced into an HTTP header value
+// (CR, LF, NUL).
+func containsHeaderControlChar(s string) bool {
+ for i := 0; i < len(s); i++ {
+ switch s[i] {
+ case '\r', '\n', 0:
+ return true
+ }
+ }
+ return false
+}
+
+// RouteRule describes a single interception rule for a tab.
+//
+// Pattern matching semantics (deliberately asymmetric, mirrors the user-facing
+// CLI ergonomics):
+//
+// - No wildcards in Pattern → SUBSTRING match against the request URL.
+// "tracker.io" matches "https://tracker.io/x" and "https://x?ref=tracker.io".
+//
+// - Pattern contains '*' or '?' → ANCHORED full-URL glob match.
+// "*.png" compiles to "^.*\.png$" and matches URLs ending in .png.
+// "*api*" matches any URL containing "api". To get substring-style
+// matching with a wildcard, wrap the pattern in '*'s on both sides.
+//
+// The asymmetry is intentional: bare strings are the common
+// "block-this-domain" case where substring is what users mean; wildcards are
+// the structural case (extension, host shape) where anchored full-URL is
+// what they mean. ResourceType, when set, narrows matches to a specific CDP
+// resource category (e.g. "script", "xhr", "image").
+type RouteRule struct {
+ Pattern string `json:"pattern"`
+ Action RouteAction `json:"action"`
+ Body string `json:"body,omitempty"`
+ ContentType string `json:"contentType,omitempty"`
+ Status int `json:"status,omitempty"`
+ ResourceType string `json:"resourceType,omitempty"`
+
+ // Method, when non-empty, narrows matches to the given HTTP method
+ // (case-insensitive). Empty Method matches any method, with one exception:
+ // fulfill rules skip OPTIONS preflights by default — fulfilling preflights
+ // can break or bypass CORS, so the operator must explicitly set
+ // Method="OPTIONS" to opt in.
+ Method string `json:"method,omitempty"`
+
+ // compiled is the precompiled regex for wildcard patterns. It is nil for
+ // substring patterns (Pattern has no '*' or '?'). Set once at AddRule time
+ // and read-only thereafter so the listener doesn't recompile per event.
+ // Unexported so encoding/json skips it on the way out of /network/route.
+ compiled *regexp.Regexp
+}
+
+// RouteManager tracks active per-tab interception rules. It enables CDP fetch
+// interception lazily when the first rule is added and disables it when the
+// last rule is removed.
+type RouteManager struct {
+ mu sync.Mutex
+ perTab map[string]*tabRouteState
+ allowedDomainsFn func() []string // nil ⇒ no allowlist enforcement
+}
+
+// tabRouteState holds per-tab interception state. listenCtx, when non-nil, is
+// derived from the tab's chromedp context and gates the listener; cancelling
+// listenCancel stops dispatch (chromedp skips listeners with a done context)
+// and is called when the last rule is removed or the tab closes.
+type tabRouteState struct {
+ rules []RouteRule
+ listenCtx context.Context
+ listenCancel context.CancelFunc
+ fetchEnabled bool
+}
+
+// NewRouteManager constructs a RouteManager. allowedDomainsFn, when non-nil, is
+// called at fulfill-time to decide whether the matched URL host is allowed to
+// receive a fabricated response body (security.allowedDomains boundary).
+// Pass nil to disable that check.
+func NewRouteManager(allowedDomainsFn func() []string) *RouteManager {
+ return &RouteManager{perTab: make(map[string]*tabRouteState), allowedDomainsFn: allowedDomainsFn}
+}
+
+// MaxFulfillBodyBytes caps the size of a fulfill rule's response body. The
+// HTTP handler enforces this for early 400s; AddRule re-checks so non-HTTP
+// callers (direct bridge users, future ipc) also benefit.
+const MaxFulfillBodyBytes = 1 << 20 // 1 MiB
+
+// MaxRulesPerTab caps how many interception rules a single tab may carry.
+// Without a cap an attacker (or runaway agent) could install thousands of
+// rules to consume memory and slow every paused request through a long
+// per-event match loop. The number is generous for legitimate use — typical
+// fixtures have a few rules — and conservative against abuse.
+const MaxRulesPerTab = 100
+
+// ErrTooManyRules is returned by AddRule when a tab already holds
+// MaxRulesPerTab rules and the incoming rule is not a same-pattern replace.
+var ErrTooManyRules = errors.New("too many interception rules on this tab")
+
+// forbiddenFulfillSchemes lists URL schemes where fulfill must always be
+// rejected regardless of the host allowlist. data:/javascript: are inline
+// pseudo-URLs that don't traverse the network so a fulfill is meaningless;
+// file:/blob:/ftp: bypass the web origin model in surprising ways; chrome:
+// and chrome-extension: are privileged browser origins where forging a
+// response is dangerous; about: should never be intercepted at all (about:
+// blank in particular is special-cased earlier in the stack).
+var forbiddenFulfillSchemes = map[string]struct{}{
+ "javascript": {},
+ "data": {},
+ "file": {},
+ "blob": {},
+ "ftp": {},
+ "chrome": {},
+ "chrome-extension": {},
+ "about": {},
+}
+
+// ErrTabNotRouted is returned by Remove when the tab has no rule state
+// registered with the manager — distinct from "tab found, pattern matched
+// nothing" which returns (0, nil). Callers can map this to a 404 to
+// differentiate from a benign no-op removal.
+var ErrTabNotRouted = errors.New("tab has no interception rules registered")
+
+// AddRule installs (or replaces, by Pattern) a rule for the given tab.
+func (rm *RouteManager) AddRule(ctx context.Context, tabID string, rule RouteRule) error {
+ if rm == nil {
+ return fmt.Errorf("route manager not initialized")
+ }
+ if rule.Pattern == "" {
+ return fmt.Errorf("pattern required")
+ }
+ if rule.Action == "" {
+ rule.Action = RouteActionContinue
+ }
+ switch rule.Action {
+ case RouteActionContinue, RouteActionAbort, RouteActionFulfill:
+ default:
+ return fmt.Errorf("invalid action %q", rule.Action)
+ }
+ if !IsResourceTypeValid(rule.ResourceType) {
+ return fmt.Errorf("invalid resourceType %q", rule.ResourceType)
+ }
+ if rule.Method != "" {
+ normalized, ok := normalizeHTTPMethod(rule.Method)
+ if !ok {
+ return fmt.Errorf("invalid method %q", rule.Method)
+ }
+ rule.Method = normalized
+ }
+ // Body cap, status range, and content-type validation apply regardless of
+ // Action so non-HTTP callers (MCP, future ipc) can't smuggle malformed
+ // values past the bridge by setting Action=abort/continue. Defaults
+ // (Status=200, ContentType=application/json) are still applied only when
+ // the rule actually uses them (fulfill).
+ if len(rule.Body) > MaxFulfillBodyBytes {
+ return fmt.Errorf("body exceeds %d bytes (cap)", MaxFulfillBodyBytes)
+ }
+ if rule.Status != 0 && (rule.Status < 100 || rule.Status > 599) {
+ return fmt.Errorf("status %d out of HTTP range (100-599)", rule.Status)
+ }
+ if rule.ContentType != "" && !IsFulfillContentTypeAllowed(rule.ContentType) {
+ return fmt.Errorf("contentType %q is not on the fulfill safe-list (or contains control chars)", rule.ContentType)
+ }
+ if rule.Action == RouteActionFulfill {
+ if rule.Status == 0 {
+ rule.Status = 200
+ }
+ if rule.ContentType == "" {
+ rule.ContentType = "application/json"
+ }
+ }
+
+ compiled, err := compileRulePattern(rule.Pattern)
+ if err != nil {
+ return fmt.Errorf("invalid pattern %q: %w", rule.Pattern, err)
+ }
+ rule.compiled = compiled
+
+ rm.mu.Lock()
+ state := rm.perTab[tabID]
+ isNewState := state == nil
+ if state == nil {
+ state = &tabRouteState{}
+ rm.perTab[tabID] = state
+ }
+
+ // Snapshot for rollback on fetch.Enable failure.
+ priorRules := append([]RouteRule(nil), state.rules...)
+ priorListenCtx := state.listenCtx
+ priorListenCancel := state.listenCancel
+ priorFetchEnabled := state.fetchEnabled
+
+ replaced := false
+ for i, r := range state.rules {
+ if r.Pattern == rule.Pattern {
+ state.rules[i] = rule
+ replaced = true
+ break
+ }
+ }
+ if !replaced {
+ if len(state.rules) >= MaxRulesPerTab {
+ if isNewState {
+ delete(rm.perTab, tabID)
+ }
+ rm.mu.Unlock()
+ return fmt.Errorf("%w: cap is %d", ErrTooManyRules, MaxRulesPerTab)
+ }
+ state.rules = append(state.rules, rule)
+ }
+
+ needRegister := state.listenCancel == nil
+ needEnable := !state.fetchEnabled
+ if needRegister {
+ state.listenCtx, state.listenCancel = context.WithCancel(ctx)
+ }
+ listenCtx := state.listenCtx
+ rm.mu.Unlock()
+
+ if needRegister {
+ rm.registerListener(listenCtx, tabID)
+ }
+ if needEnable {
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
+ return fetch.Enable().
+ WithPatterns([]*fetch.RequestPattern{{URLPattern: "*"}}).
+ Do(c)
+ })); err != nil {
+ rm.rollbackAddRule(tabID, isNewState, needRegister, priorRules, priorListenCtx, priorListenCancel, priorFetchEnabled)
+ return fmt.Errorf("fetch.enable: %w", err)
+ }
+ rm.mu.Lock()
+ if s := rm.perTab[tabID]; s != nil {
+ s.fetchEnabled = true
+ }
+ rm.mu.Unlock()
+ }
+ return nil
+}
+
+// rollbackAddRule restores the per-tab state captured before a failed AddRule.
+// If we registered a fresh listener for this call, its context is cancelled so
+// the no-op listener handle is released.
+func (rm *RouteManager) rollbackAddRule(tabID string, isNewState, registeredListener bool, priorRules []RouteRule, priorListenCtx context.Context, priorListenCancel context.CancelFunc, priorFetchEnabled bool) {
+ rm.mu.Lock()
+ s := rm.perTab[tabID]
+ if s == nil {
+ rm.mu.Unlock()
+ return
+ }
+ var newCancel context.CancelFunc
+ if registeredListener {
+ newCancel = s.listenCancel
+ s.listenCtx = priorListenCtx
+ s.listenCancel = priorListenCancel
+ }
+ s.rules = priorRules
+ s.fetchEnabled = priorFetchEnabled
+ if isNewState && len(s.rules) == 0 {
+ delete(rm.perTab, tabID)
+ }
+ rm.mu.Unlock()
+
+ if newCancel != nil {
+ newCancel()
+ }
+}
+
+// Remove deletes rules matching pattern. Empty pattern removes all rules for
+// the tab. Returns the number of rules removed. When the last rule is removed,
+// the listener context is cancelled and CDP fetch interception is disabled.
+func (rm *RouteManager) Remove(ctx context.Context, tabID string, pattern string) (int, error) {
+ if rm == nil {
+ return 0, fmt.Errorf("route manager not initialized")
+ }
+
+ rm.mu.Lock()
+ state := rm.perTab[tabID]
+ if state == nil {
+ rm.mu.Unlock()
+ // Tab has no rule state at all — distinct from "rules exist but the
+ // pattern matched nothing." The handler maps ErrTabNotRouted to 404.
+ return 0, ErrTabNotRouted
+ }
+
+ removed := 0
+ if pattern == "" {
+ removed = len(state.rules)
+ state.rules = nil
+ } else {
+ kept := state.rules[:0]
+ for _, r := range state.rules {
+ if r.Pattern == pattern {
+ removed++
+ continue
+ }
+ kept = append(kept, r)
+ }
+ state.rules = kept
+ }
+
+ teardown := len(state.rules) == 0
+ wasEnabled := state.fetchEnabled
+ cancel := state.listenCancel
+ if teardown {
+ state.fetchEnabled = false
+ state.listenCancel = nil
+ state.listenCtx = nil
+ delete(rm.perTab, tabID)
+ }
+ rm.mu.Unlock()
+
+ if teardown {
+ if wasEnabled {
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
+ return fetch.Disable().Do(c)
+ })); err != nil {
+ slog.Debug("fetch.disable failed during route teardown", "tabId", tabID, "err", err)
+ }
+ }
+ if cancel != nil {
+ cancel()
+ }
+ }
+ return removed, nil
+}
+
+// RemoveTab drops all rule state for a tab without issuing CDP calls. It is
+// the cleanup hook fired by TabManager when a tab closes (manual close,
+// eviction, auto-close, or Chrome reporting the target gone). When the tab's
+// chromedp context is already canceled, fetch.Disable would fail anyway —
+// canceling the listener context is the only meaningful step. Without this
+// hook, perTab[tabID] and its cancel func would leak; if Chrome ever reused
+// the target id, a stale entry would be found.
+func (rm *RouteManager) RemoveTab(tabID string) {
+ if rm == nil || tabID == "" {
+ return
+ }
+ rm.mu.Lock()
+ state := rm.perTab[tabID]
+ if state == nil {
+ rm.mu.Unlock()
+ return
+ }
+ cancel := state.listenCancel
+ delete(rm.perTab, tabID)
+ rm.mu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+}
+
+// List returns the current rules for a tab.
+func (rm *RouteManager) List(tabID string) []RouteRule {
+ if rm == nil {
+ return nil
+ }
+ rm.mu.Lock()
+ defer rm.mu.Unlock()
+ state := rm.perTab[tabID]
+ if state == nil {
+ return nil
+ }
+ out := make([]RouteRule, len(state.rules))
+ copy(out, state.rules)
+ return out
+}
+
+func (rm *RouteManager) registerListener(listenCtx context.Context, tabID string) {
+ // Verify the context is target-bound. chromedp.ListenTarget on a
+ // browser-level context (Target == nil) would broadcast to every tab —
+ // we explicitly require the per-tab target so dispatch is session-scoped.
+ if c := chromedp.FromContext(listenCtx); c == nil || c.Target == nil {
+ slog.Warn("route listener not registered: chromedp context has no target", "tabId", tabID)
+ return
+ }
+ chromedp.ListenTarget(listenCtx, func(ev interface{}) {
+ if listenCtx.Err() != nil {
+ return
+ }
+ e, ok := ev.(*fetch.EventRequestPaused)
+ if !ok {
+ return
+ }
+ eventResourceType := strings.ToLower(string(e.ResourceType))
+ eventMethod := strings.ToUpper(strings.TrimSpace(e.Request.Method))
+ rule, matched, hasRules := rm.match(tabID, e.Request.URL, eventResourceType, eventMethod)
+ // Teardown in progress: rules drained but fetch.Disable not yet
+ // landed. Skip dispatch — fetch.Disable will release pending requests.
+ if !hasRules {
+ return
+ }
+ go rm.dispatch(listenCtx, tabID, e, rule, matched)
+ })
+}
+
+// dispatch issues the CDP response for a paused request. Errors are logged at
+// Debug level — fetch operations frequently fail benignly when a tab navigates
+// while a request is paused, and elevating those to Warn would be noisy.
+func (rm *RouteManager) dispatch(listenCtx context.Context, tabID string, e *fetch.EventRequestPaused, rule RouteRule, matched bool) {
+ if listenCtx.Err() != nil {
+ return
+ }
+ executor := cdp.WithExecutor(listenCtx, chromedp.FromContext(listenCtx).Target)
+
+ if !matched || rule.Action == RouteActionContinue {
+ if err := fetch.ContinueRequest(e.RequestID).Do(executor); err != nil {
+ slog.Debug("fetch.continueRequest failed", "tabId", tabID, "url", e.Request.URL, "err", err)
+ }
+ return
+ }
+
+ switch rule.Action {
+ case RouteActionAbort:
+ if err := fetch.FailRequest(e.RequestID, network.ErrorReasonBlockedByClient).Do(executor); err != nil {
+ slog.Debug("fetch.failRequest failed", "tabId", tabID, "url", e.Request.URL, "err", err)
+ }
+ case RouteActionFulfill:
+ if !rm.fulfillForgeryPermittedFor(e.Request.URL) {
+ slog.Warn("route fulfill blocked: response forgery not permitted (allowlisted host or forbidden scheme)",
+ "tabId", tabID,
+ "url", e.Request.URL,
+ "pattern", rule.Pattern,
+ )
+ if err := fetch.ContinueRequest(e.RequestID).Do(executor); err != nil {
+ slog.Debug("fetch.continueRequest (fulfill fallthrough) failed", "tabId", tabID, "url", e.Request.URL, "err", err)
+ }
+ return
+ }
+ headers := []*fetch.HeaderEntry{{Name: "Content-Type", Value: rule.ContentType}}
+ if err := fetch.FulfillRequest(e.RequestID, int64(rule.Status)).
+ WithResponseHeaders(headers).
+ WithBody(base64.StdEncoding.EncodeToString([]byte(rule.Body))).
+ Do(executor); err != nil {
+ slog.Debug("fetch.fulfillRequest failed", "tabId", tabID, "url", e.Request.URL, "err", err)
+ }
+ default:
+ if err := fetch.ContinueRequest(e.RequestID).Do(executor); err != nil {
+ slog.Debug("fetch.continueRequest (default) failed", "tabId", tabID, "url", e.Request.URL, "err", err)
+ }
+ }
+}
+
+// match looks for the first rule matching url + resourceType + method. The
+// third return value (hasRules) is true iff the tab has any rules at all —
+// callers use it to skip dispatch entirely during teardown windows.
+//
+// Method semantics:
+//
+// - Rule.Method != "" → strict method match (case-insensitive).
+// - Rule.Method == "" + non-OPTIONS event → match any method.
+// - Rule.Method == "" + OPTIONS event + Action == fulfill → SKIP. CORS
+// preflights deserve explicit opt-in: a fulfill that catches the
+// preflight without ACAO/ACAM/ACAH headers breaks the real request, and
+// a fulfill that fakes those headers bypasses CORS for the real call.
+// Operators who genuinely want to mock OPTIONS set Method:"OPTIONS".
+// - Rule.Method == "" + OPTIONS event + Action != fulfill → match.
+// Aborting/passing-through preflights is benign.
+func (rm *RouteManager) match(tabID, url, resourceType, method string) (rule RouteRule, matched bool, hasRules bool) {
+ rm.mu.Lock()
+ defer rm.mu.Unlock()
+ state := rm.perTab[tabID]
+ if state == nil || len(state.rules) == 0 {
+ return RouteRule{}, false, false
+ }
+ const optionsMethod = "OPTIONS"
+ for _, r := range state.rules {
+ if r.ResourceType != "" && !strings.EqualFold(r.ResourceType, resourceType) {
+ continue
+ }
+ if r.Method != "" {
+ if !strings.EqualFold(r.Method, method) {
+ continue
+ }
+ } else if r.Action == RouteActionFulfill && method == optionsMethod {
+ continue
+ }
+ if ruleMatchesURL(r, url) {
+ return r, true, true
+ }
+ }
+ return RouteRule{}, false, true
+}
+
+// fulfillForgeryPermittedFor reports whether forging a response (action
+// fulfill) is permitted for rawURL. The name is deliberate: this is a
+// permission check on RESPONSE FORGERY, not a generic "is this URL allowed"
+// query, and it inverts the host-allowlist on purpose.
+//
+// Policy:
+//
+// 1. Special-scheme URLs (data:, javascript:, file:, blob:, ftp:, chrome:,
+// chrome-extension:, about:) are ALWAYS denied — fulfilling those either
+// makes no sense or escapes the web origin model in surprising ways.
+// 2. With no allowlist configured (nil accessor or empty list) the policy
+// is inactive and forgery is permitted on all normal-scheme URLs.
+// 3. Otherwise: forgery is BLOCKED on hosts listed in security.allowedDomains
+// and PERMITTED on all other hosts. Rationale: allowedDomains marks the
+// sensitive surfaces the operator has authorized the agent to interact
+// with (banking, email, internal SaaS) — exactly the origins where
+// injecting attacker-controlled responses is most damaging, because the
+// body executes in that origin's security context with access to its
+// cookies, localStorage, and DOM. Unlisted hosts are the typical mocking
+// targets (third-party APIs, CDNs, analytics endpoints) where response
+// forgery is a normal test/dev tool.
+//
+// Yes, this is intentionally the opposite of "is the host allowlisted." If
+// you find yourself reading `!security.HostAllowed(...)` and reaching for the
+// `!`, that is the policy.
+func (rm *RouteManager) fulfillForgeryPermittedFor(rawURL string) bool {
+ if isForbiddenFulfillScheme(rawURL) {
+ return false
+ }
+ if rm.allowedDomainsFn == nil {
+ return true
+ }
+ allow := rm.allowedDomainsFn()
+ if len(allow) == 0 {
+ return true
+ }
+ return !security.HostAllowed(rawURL, allow)
+}
+
+// isForbiddenFulfillScheme reports whether rawURL uses a scheme where
+// fulfill must always be rejected (see forbiddenFulfillSchemes for the set
+// and rationale). Unparseable URLs are treated as forbidden.
+func isForbiddenFulfillScheme(rawURL string) bool {
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ return true
+ }
+ scheme := strings.ToLower(strings.TrimSpace(parsed.Scheme))
+ if scheme == "" {
+ return false
+ }
+ _, forbidden := forbiddenFulfillSchemes[scheme]
+ return forbidden
+}
+
+// ruleMatchesURL reports whether r matches url, using the precompiled regex
+// when present (wildcard patterns) and a substring check otherwise. AddRule
+// always populates r.compiled for wildcard patterns; the on-the-fly fallback
+// here keeps the function correct when state is populated by other paths
+// (e.g. unit tests) and is never hit in production.
+func ruleMatchesURL(r RouteRule, url string) bool {
+ if r.Pattern == "" {
+ return false
+ }
+ if r.compiled != nil {
+ return r.compiled.MatchString(url)
+ }
+ if strings.ContainsAny(r.Pattern, "*?") {
+ return globMatch(r.Pattern, url)
+ }
+ return strings.Contains(url, r.Pattern)
+}
+
+// compileRulePattern returns the precompiled regex for wildcard patterns or
+// nil for substring patterns. Errors only when a wildcard pattern fails to
+// compile (escaped char issues).
+func compileRulePattern(pattern string) (*regexp.Regexp, error) {
+ if pattern == "" || !strings.ContainsAny(pattern, "*?") {
+ return nil, nil
+ }
+ return globToRegex(pattern)
+}
+
+// globMatch is a convenience used by tests; production code uses
+// ruleMatchesURL with the precompiled regex stored on the rule.
+func globMatch(pattern, url string) bool {
+ if pattern == "" {
+ return false
+ }
+ if !strings.ContainsAny(pattern, "*?") {
+ return strings.Contains(url, pattern)
+ }
+ re, err := globToRegex(pattern)
+ if err != nil {
+ return false
+ }
+ return re.MatchString(url)
+}
+
+func globToRegex(pattern string) (*regexp.Regexp, error) {
+ var sb strings.Builder
+ sb.WriteString("^")
+ for _, r := range pattern {
+ switch r {
+ case '*':
+ sb.WriteString(".*")
+ case '?':
+ sb.WriteString(".")
+ case '.', '+', '(', ')', '[', ']', '{', '}', '|', '^', '$', '\\':
+ sb.WriteRune('\\')
+ sb.WriteRune(r)
+ default:
+ sb.WriteRune(r)
+ }
+ }
+ sb.WriteString("$")
+ return regexp.Compile(sb.String())
+}
diff --git a/internal/bridge/route_test.go b/internal/bridge/route_test.go
new file mode 100644
index 00000000..db3c8e31
--- /dev/null
+++ b/internal/bridge/route_test.go
@@ -0,0 +1,634 @@
+package bridge
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+)
+
+func TestGlobMatch(t *testing.T) {
+ cases := []struct {
+ pattern string
+ url string
+ want bool
+ }{
+ {"api.example.com", "https://api.example.com/users", true},
+ {"api.example.com", "https://other.example.com/users", false},
+ {"*.example.com/*", "https://api.example.com/users", true},
+ {"*.example.com/*", "https://example.com/users", false},
+ {"https://api.example.com/users", "https://api.example.com/users", true},
+ {"*", "https://anything.test/", true},
+ {"", "https://anything.test/", false},
+ {"*users?id", "https://x/usersaid", true},
+ {"*users?id", "https://x/usersid", false},
+ {"path/with.dots", "https://x/path/with.dots", true},
+ {"path/with.dots", "https://x/path/withxdots", false},
+ }
+ for _, tc := range cases {
+ got := globMatch(tc.pattern, tc.url)
+ if got != tc.want {
+ t.Errorf("globMatch(%q, %q) = %v, want %v", tc.pattern, tc.url, got, tc.want)
+ }
+ }
+}
+
+func TestRouteManager_AddRemove_NoCDP(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rules := rm.List("tab1")
+ if len(rules) != 0 {
+ t.Fatalf("expected 0 rules initially, got %d", len(rules))
+ }
+
+ // Direct manipulation to exercise rule storage without spinning up Chrome.
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*.png", Action: RouteActionAbort},
+ {Pattern: "api/users", Action: RouteActionFulfill, Body: "{}", ContentType: "application/json", Status: 200},
+ }}
+ rm.mu.Unlock()
+
+ got := rm.List("tab1")
+ if len(got) != 2 {
+ t.Fatalf("expected 2 rules, got %d", len(got))
+ }
+
+ // Remove all (pattern == "") — fetchEnabled is false so no CDP call needed.
+ removed, err := rm.Remove(t.Context(), "tab1", "")
+ if err != nil {
+ t.Fatalf("remove: %v", err)
+ }
+ if removed != 2 {
+ t.Errorf("expected 2 removed, got %d", removed)
+ }
+ if len(rm.List("tab1")) != 0 {
+ t.Errorf("expected 0 remaining, got %d", len(rm.List("tab1")))
+ }
+}
+
+func TestRouteManager_Remove_TabNotRoutedReturnsSentinel(t *testing.T) {
+ rm := NewRouteManager(nil)
+ _, err := rm.Remove(t.Context(), "tab-never-routed", "*.png")
+ if err == nil {
+ t.Fatal("expected ErrTabNotRouted when tab has no rule state")
+ }
+ if !errors.Is(err, ErrTabNotRouted) {
+ t.Errorf("expected errors.Is(err, ErrTabNotRouted), got %v", err)
+ }
+}
+
+func TestRouteManager_Remove_TabRoutedButPatternMisses(t *testing.T) {
+ // When the tab has rule state but the pattern doesn't match anything,
+ // Remove should succeed with removed=0 (idempotent), not the sentinel.
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{{Pattern: "a", Action: RouteActionAbort}}}
+ rm.mu.Unlock()
+
+ removed, err := rm.Remove(t.Context(), "tab1", "z")
+ if err != nil {
+ t.Fatalf("expected nil error for tab-with-rules + non-matching pattern, got %v", err)
+ }
+ if removed != 0 {
+ t.Errorf("expected removed=0, got %d", removed)
+ }
+}
+
+func TestRouteManager_RemoveByPattern(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "a", Action: RouteActionAbort},
+ {Pattern: "b", Action: RouteActionAbort},
+ {Pattern: "c", Action: RouteActionAbort},
+ }}
+ rm.mu.Unlock()
+
+ removed, err := rm.Remove(t.Context(), "tab1", "b")
+ if err != nil {
+ t.Fatalf("remove: %v", err)
+ }
+ if removed != 1 {
+ t.Errorf("expected 1 removed, got %d", removed)
+ }
+ rules := rm.List("tab1")
+ if len(rules) != 2 {
+ t.Fatalf("expected 2 remaining, got %d", len(rules))
+ }
+ for _, r := range rules {
+ if r.Pattern == "b" {
+ t.Errorf("pattern b should have been removed")
+ }
+ }
+}
+
+func TestRouteManager_Match_FirstWins(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*.example.com/*", Action: RouteActionFulfill, Body: "first", Status: 200, ContentType: "text/plain"},
+ {Pattern: "api.example.com/*", Action: RouteActionAbort},
+ }}
+ rm.mu.Unlock()
+
+ rule, ok, _ := rm.match("tab1", "https://api.example.com/users", "", "GET")
+ if !ok {
+ t.Fatal("expected match")
+ }
+ if rule.Action != RouteActionFulfill {
+ t.Errorf("expected first rule (fulfill) to win, got %s", rule.Action)
+ }
+}
+
+func TestRouteManager_Match_NoneMatches(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*.png", Action: RouteActionAbort},
+ }}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://api.example.com/users", "", "GET"); ok {
+ t.Error("expected no match")
+ }
+}
+
+func TestRouteManager_Match_ResourceTypeFilter(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*", Action: RouteActionAbort, ResourceType: "script"},
+ }}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://x/img.png", "image", "GET"); ok {
+ t.Error("rule with ResourceType=script should not match resourceType=image")
+ }
+ if _, ok, _ := rm.match("tab1", "https://x/app.js", "script", "GET"); !ok {
+ t.Error("rule with ResourceType=script should match resourceType=script")
+ }
+ if _, ok, _ := rm.match("tab1", "https://x/app.js", "Script", "GET"); !ok {
+ t.Error("ResourceType match should be case-insensitive")
+ }
+}
+
+func TestRouteManager_FulfillAllowedFor_NoAccessor(t *testing.T) {
+ rm := NewRouteManager(nil)
+ if !rm.fulfillForgeryPermittedFor("https://anything.test/") {
+ t.Error("nil accessor should allow fulfill on any URL")
+ }
+}
+
+// Policy is inverted: fulfill is BLOCKED on hosts in the allowlist (the
+// sensitive surfaces) and ALLOWED on hosts outside the allowlist (normal
+// mocking targets like third-party APIs/CDNs).
+func TestRouteManager_FulfillAllowedFor_BlockedOnAllowlistedHost(t *testing.T) {
+ allow := []string{"api.example.com"}
+ rm := NewRouteManager(func() []string { return allow })
+
+ if rm.fulfillForgeryPermittedFor("https://api.example.com/users") {
+ t.Error("allowlisted host should BLOCK fulfill (response forgery on sensitive surface)")
+ }
+}
+
+func TestRouteManager_FulfillAllowedFor_AllowedOnUnlistedHost(t *testing.T) {
+ allow := []string{"api.example.com"}
+ rm := NewRouteManager(func() []string { return allow })
+
+ if !rm.fulfillForgeryPermittedFor("https://cdn.unrelated.test/asset") {
+ t.Error("unlisted host should ALLOW fulfill (typical mock target)")
+ }
+}
+
+func TestRouteManager_FulfillAllowedFor_WildcardSubdomain(t *testing.T) {
+ allow := []string{"*.example.com"}
+ rm := NewRouteManager(func() []string { return allow })
+
+ if rm.fulfillForgeryPermittedFor("https://api.example.com/x") {
+ t.Error("wildcard match means in-allowlist → fulfill blocked")
+ }
+ if !rm.fulfillForgeryPermittedFor("https://example.com/x") {
+ t.Error("apex example.com is NOT covered by *.example.com → fulfill allowed")
+ }
+}
+
+func TestRouteManager_FulfillAllowedFor_EmptyAllowlistMeansNoEnforcement(t *testing.T) {
+ rm := NewRouteManager(func() []string { return nil })
+ if !rm.fulfillForgeryPermittedFor("https://anything.test/") {
+ t.Error("empty allowlist should mean no enforcement → fulfill allowed")
+ }
+ rm2 := NewRouteManager(func() []string { return []string{} })
+ if !rm2.fulfillForgeryPermittedFor("https://anything.test/") {
+ t.Error("zero-length allowlist should mean no enforcement → fulfill allowed")
+ }
+}
+
+func TestIsFulfillContentTypeAllowed(t *testing.T) {
+ allowed := []string{
+ "application/json",
+ "application/json; charset=utf-8",
+ "APPLICATION/JSON",
+ "text/plain",
+ "image/png",
+ "",
+ }
+ for _, ct := range allowed {
+ if !IsFulfillContentTypeAllowed(ct) {
+ t.Errorf("expected %q allowed", ct)
+ }
+ }
+ denied := []string{
+ "text/html",
+ "text/html; charset=utf-8",
+ "application/javascript",
+ "application/x-javascript",
+ "text/javascript",
+ "application/ecmascript",
+ "application/xhtml+xml",
+ "image/svg+xml",
+ "application/json\r\nX-Injected: evil",
+ "application/json\nX-Injected: evil",
+ "application/json\x00null",
+ }
+ for _, ct := range denied {
+ if IsFulfillContentTypeAllowed(ct) {
+ t.Errorf("expected %q denied", ct)
+ }
+ }
+}
+
+func TestIsResourceTypeValid(t *testing.T) {
+ for _, rt := range []string{"", "Document", "script", "XHR", "fetch", "image"} {
+ if !IsResourceTypeValid(rt) {
+ t.Errorf("expected %q valid", rt)
+ }
+ }
+ for _, rt := range []string{"bogus", "java", "html"} {
+ if IsResourceTypeValid(rt) {
+ t.Errorf("expected %q invalid", rt)
+ }
+ }
+}
+
+func TestRouteManager_AddRule_RejectsBadFulfillContentType(t *testing.T) {
+ rm := NewRouteManager(nil)
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "x",
+ Action: RouteActionFulfill,
+ Body: "{}",
+ ContentType: "text/html",
+ })
+ if err == nil {
+ t.Error("expected fulfill with text/html to be rejected")
+ }
+}
+
+func TestRouteManager_AddRule_RejectsCRLFInContentType(t *testing.T) {
+ rm := NewRouteManager(nil)
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "x",
+ Action: RouteActionFulfill,
+ Body: "{}",
+ ContentType: "application/json\r\nX-Evil: 1",
+ })
+ if err == nil {
+ t.Error("expected CRLF in contentType to be rejected")
+ }
+}
+
+func TestRouteManager_AddRule_RejectsBadResourceType(t *testing.T) {
+ rm := NewRouteManager(nil)
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "x",
+ Action: RouteActionAbort,
+ ResourceType: "bogus",
+ })
+ if err == nil {
+ t.Error("expected bogus resourceType to be rejected")
+ }
+}
+
+func TestRouteManager_AddRule_RejectsOversizeBody(t *testing.T) {
+ rm := NewRouteManager(nil)
+ huge := make([]byte, MaxFulfillBodyBytes+1)
+ for i := range huge {
+ huge[i] = 'x'
+ }
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "x",
+ Action: RouteActionFulfill,
+ Body: string(huge),
+ })
+ if err == nil {
+ t.Error("expected oversize body to be rejected")
+ }
+}
+
+func TestRouteManager_AddRule_RejectsBadStatus(t *testing.T) {
+ rm := NewRouteManager(nil)
+ for _, bad := range []int{-1, 99, 600, 1000} {
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "x",
+ Action: RouteActionFulfill,
+ Body: "{}",
+ Status: bad,
+ })
+ if err == nil {
+ t.Errorf("expected status=%d to be rejected", bad)
+ }
+ }
+}
+
+// allowedDomains == ["*"] is a wildcard "match anything" entry; per the
+// inverted policy that means all hosts are treated as allowlisted, so fulfill
+// should be blocked everywhere (the operator chose "trust everywhere", which
+// also means "forbid forgery everywhere").
+func TestRouteManager_FulfillAllowedFor_GlobalWildcardBlocksAll(t *testing.T) {
+ rm := NewRouteManager(func() []string { return []string{"*"} })
+ for _, u := range []string{
+ "https://api.example.com/users",
+ "http://random-blog.test/post",
+ "https://internal.corp/admin",
+ } {
+ if rm.fulfillForgeryPermittedFor(u) {
+ t.Errorf("with allowedDomains=['*'] every host should block fulfill (got allowed for %s)", u)
+ }
+ }
+}
+
+// Forbidden URL schemes are always rejected for fulfill, with or without an
+// allowlist. Forging a response for data:/javascript:/file:/chrome:/about:
+// either makes no sense (inline pseudo-URLs never traverse the network) or
+// escapes the web origin model (privileged origins, local files).
+func TestRouteManager_FulfillForgeryPermittedFor_ForbiddenSchemesDenied(t *testing.T) {
+ for _, accessor := range []func() []string{
+ nil, // no policy
+ func() []string { return nil },
+ func() []string { return []string{"api.example.com"} },
+ func() []string { return []string{"*"} },
+ } {
+ rm := NewRouteManager(accessor)
+ for _, u := range []string{
+ "javascript:alert(1)",
+ "data:text/plain,hello",
+ "data:text/html,<script>alert(1)</script>",
+ "file:///etc/passwd",
+ "blob:https://x.test/abc",
+ "ftp://files.example.com/x",
+ "chrome://settings",
+ "chrome-extension://abc/options.html",
+ "about:blank",
+ "about:srcdoc",
+ } {
+ if rm.fulfillForgeryPermittedFor(u) {
+ t.Errorf("forbidden-scheme URL %q must reject fulfill regardless of allowlist", u)
+ }
+ }
+ }
+}
+
+// Unparseable URLs are conservatively treated as forbidden so the fulfill
+// path never operates on inputs we can't reason about.
+func TestRouteManager_FulfillForgeryPermittedFor_UnparseableURLDenied(t *testing.T) {
+ rm := NewRouteManager(nil)
+ if rm.fulfillForgeryPermittedFor("ht!tp://[invalid") {
+ t.Error("unparseable URL must reject fulfill")
+ }
+}
+
+// Cross-tab dispatch sanity check: rules on tab1 must not match URLs queried
+// against tab2. (chromedp's per-target listener dispatch already isolates
+// events at the wire level; this asserts the manager-level filter hasn't
+// regressed to a global lookup.)
+// Fulfill rules without an explicit Method should NOT match an OPTIONS
+// preflight — fulfilling it without ACAO/ACAM/ACAH headers breaks the real
+// request, and would also let a future custom-headers feature smuggle CORS
+// approval through.
+func TestRouteManager_Match_FulfillSkipsOPTIONSByDefault(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*", Action: RouteActionFulfill, Body: "{}", Status: 200, ContentType: "application/json"},
+ }}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://api.example.com/x", "fetch", "OPTIONS"); ok {
+ t.Error("fulfill rule with no Method must skip OPTIONS preflight")
+ }
+ if _, ok, _ := rm.match("tab1", "https://api.example.com/x", "fetch", "GET"); !ok {
+ t.Error("fulfill rule should still match non-OPTIONS methods")
+ }
+}
+
+// Aborting OPTIONS without an explicit Method is fine — abort can't bypass
+// CORS, and operators commonly want to block third-party API calls including
+// their preflights.
+func TestRouteManager_Match_AbortAllowsOPTIONSByDefault(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*", Action: RouteActionAbort},
+ }}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://api.example.com/x", "fetch", "OPTIONS"); !ok {
+ t.Error("abort rule with no Method should match OPTIONS too (no CORS bypass risk)")
+ }
+}
+
+// Explicit Method opt-in: operator can fulfill OPTIONS by naming it.
+func TestRouteManager_Match_ExplicitOPTIONSOptIn(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*", Action: RouteActionFulfill, Method: "OPTIONS", Body: "{}", Status: 204, ContentType: "application/json"},
+ }}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://api.example.com/x", "fetch", "OPTIONS"); !ok {
+ t.Error("fulfill rule with Method=OPTIONS must match OPTIONS")
+ }
+ if _, ok, _ := rm.match("tab1", "https://api.example.com/x", "fetch", "GET"); ok {
+ t.Error("fulfill rule with Method=OPTIONS must NOT match GET")
+ }
+}
+
+func TestRouteManager_Match_MethodFilterCaseInsensitive(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*", Action: RouteActionAbort, Method: "post"},
+ }}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://x/", "fetch", "POST"); !ok {
+ t.Error("Method filter should be case-insensitive")
+ }
+ if _, ok, _ := rm.match("tab1", "https://x/", "fetch", "GET"); ok {
+ t.Error("Method=POST should not match GET")
+ }
+}
+
+func TestRouteManager_AddRule_RejectsInvalidMethod(t *testing.T) {
+ rm := NewRouteManager(nil)
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "x",
+ Action: RouteActionAbort,
+ Method: "FOOBAR",
+ })
+ if err == nil {
+ t.Error("expected unknown method to be rejected")
+ }
+}
+
+func TestNormalizeHTTPMethod(t *testing.T) {
+ for _, in := range []string{"get", "POST", " patch ", "delete"} {
+ if _, ok := normalizeHTTPMethod(in); !ok {
+ t.Errorf("expected %q to normalize", in)
+ }
+ }
+ if got, _ := normalizeHTTPMethod("post"); got != "POST" {
+ t.Errorf("expected uppercase, got %q", got)
+ }
+ for _, in := range []string{"", " ", "FOOBAR", "GET-but-not-really"} {
+ if _, ok := normalizeHTTPMethod(in); ok {
+ t.Errorf("expected %q to be rejected", in)
+ }
+ }
+}
+
+func TestRouteManager_Match_PerTabIsolation(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{{Pattern: "*", Action: RouteActionAbort}}}
+ rm.perTab["tab2"] = &tabRouteState{rules: []RouteRule{{Pattern: "tab2-only", Action: RouteActionAbort}}}
+ rm.mu.Unlock()
+
+ if _, ok, _ := rm.match("tab1", "https://anywhere/", "", "GET"); !ok {
+ t.Error("tab1 should match its own '*' rule")
+ }
+ if _, ok, _ := rm.match("tab2", "https://anywhere/", "", "GET"); ok {
+ t.Error("tab2 must NOT match tab1's rule (cross-tab leak)")
+ }
+ if _, ok, _ := rm.match("tab1", "https://x/tab2-only", "", "GET"); !ok {
+ // tab1's '*' covers everything, so still matches.
+ t.Error("tab1 '*' rule should still match URL containing tab2-only")
+ }
+}
+
+// Pins the documented asymmetry: bare strings → substring, wildcards →
+// anchored full-URL. Reads as a behavior contract; if this changes, the
+// docstring on RouteRule.Pattern must change too.
+func TestGlobMatch_AsymmetryIsDocumented(t *testing.T) {
+ // Bare string: substring match.
+ if !globMatch("tracker.io", "https://x.com/?ref=tracker.io") {
+ t.Error("bare 'tracker.io' should match URL containing it (substring)")
+ }
+ if !globMatch("api.example.com", "https://api.example.com/users") {
+ t.Error("bare host should match URL containing it (substring)")
+ }
+
+ // Wildcard pattern: anchored full-URL match.
+ if !globMatch("*.png", "https://x/img.png") {
+ t.Error("'*.png' should anchor and match URLs ending in .png")
+ }
+ if globMatch("*.png", "https://x/img.png/redirect") {
+ t.Error("'*.png' should NOT match when .png is in the middle (anchored)")
+ }
+ // To get substring-with-wildcard, wrap with '*'.
+ if !globMatch("*.png*", "https://x/img.png/redirect") {
+ t.Error("'*.png*' should match .png appearing anywhere")
+ }
+}
+
+func TestRouteManager_RemoveTab_DropsState(t *testing.T) {
+ rm := NewRouteManager(nil)
+ called := false
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{
+ rules: []RouteRule{{Pattern: "*.png", Action: RouteActionAbort}},
+ listenCancel: func() { called = true },
+ }
+ rm.mu.Unlock()
+
+ rm.RemoveTab("tab1")
+
+ if !called {
+ t.Error("RemoveTab should call listenCancel")
+ }
+ rm.mu.Lock()
+ _, present := rm.perTab["tab1"]
+ rm.mu.Unlock()
+ if present {
+ t.Error("RemoveTab should delete the perTab entry")
+ }
+}
+
+func TestRouteManager_RemoveTab_NoStateNoOp(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.RemoveTab("nonexistent") // must not panic
+}
+
+func TestRouteManager_AddRule_PerTabCapEnforced(t *testing.T) {
+ rm := NewRouteManager(nil)
+ rm.mu.Lock()
+ rules := make([]RouteRule, 0, MaxRulesPerTab)
+ for i := 0; i < MaxRulesPerTab; i++ {
+ rules = append(rules, RouteRule{
+ Pattern: fmt.Sprintf("p%d", i),
+ Action: RouteActionAbort,
+ })
+ }
+ rm.perTab["tab1"] = &tabRouteState{rules: rules}
+ rm.mu.Unlock()
+
+ // New pattern → rejected (cap reached).
+ err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "p-overflow",
+ Action: RouteActionAbort,
+ })
+ if err == nil {
+ t.Fatal("expected ErrTooManyRules when at cap")
+ }
+ if !errors.Is(err, ErrTooManyRules) {
+ t.Errorf("expected errors.Is(err, ErrTooManyRules), got %v", err)
+ }
+
+ // Same-pattern replace → allowed even at cap.
+ rm.mu.Lock()
+ state := rm.perTab["tab1"]
+ rm.mu.Unlock()
+ originalLen := len(state.rules)
+ if err := rm.AddRule(t.Context(), "tab1", RouteRule{
+ Pattern: "p0",
+ Action: RouteActionContinue,
+ }); err != nil {
+ // AddRule will get past validation but then call fetch.Enable on a
+ // non-chromedp context — that part fails. We only care that the cap
+ // check didn't reject the replace; ErrTooManyRules must NOT be the
+ // reason, and the rule mutation must have happened.
+ if errors.Is(err, ErrTooManyRules) {
+ t.Errorf("same-pattern replace must not hit cap: %v", err)
+ }
+ }
+ rm.mu.Lock()
+ state = rm.perTab["tab1"]
+ rm.mu.Unlock()
+ if state == nil {
+ // rollback after fetch.Enable failure may have wiped state if it was
+ // ever empty; here state existed before, so a snapshot was restored.
+ t.Skip("rollback path consumed the state; cap-replace assertion still valid via no error")
+ }
+ if len(state.rules) != originalLen {
+ t.Errorf("expected rule count unchanged on replace, got %d (was %d)", len(state.rules), originalLen)
+ }
+}
+
+func TestRouteManager_AddRule_Validation(t *testing.T) {
+ rm := NewRouteManager(nil)
+ if err := rm.AddRule(t.Context(), "tab1", RouteRule{}); err == nil {
+ t.Error("expected error for empty pattern")
+ }
+ if err := rm.AddRule(t.Context(), "tab1", RouteRule{Pattern: "x", Action: "bogus"}); err == nil {
+ t.Error("expected error for invalid action")
+ }
+}
diff --git a/internal/bridge/tab_cleanup.go b/internal/bridge/tab_cleanup.go
index 03fd4f83..64c65041 100644
--- a/internal/bridge/tab_cleanup.go
+++ b/internal/bridge/tab_cleanup.go
@@ -129,6 +129,9 @@ func (tm *TabManager) purgeTrackedTabState(tabID, cdpTargetID string) bool {
if tm.logStore != nil {
tm.logStore.RemoveTab(resolvedCDPID)
}
+ if tm.routeMgr != nil {
+ tm.routeMgr.RemoveTab(resolvedTabID)
+ }
// Notify listeners (e.g. session persistence) that a tab disappeared,
// regardless of whether the trigger was a deliberate CloseTab, an eviction,
// the auto-close lifecycle timer, or Chrome reporting the target gone
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index 811c0a1c..5300ff62 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -29,6 +29,7 @@ type TabManager struct {
onAfterClose func() // optional: invoked after any successful CloseTab
dialogMgr *DialogManager
logStore *ConsoleLogStore
+ routeMgr *RouteManager
netMonitor *NetworkMonitor
currentTab string // ID of the most recently used tab
executor *TabExecutor
@@ -77,6 +78,13 @@ func (tm *TabManager) SetNetworkMonitor(nm *NetworkMonitor) {
tm.netMonitor = nm
}
+// SetRouteManager registers the per-bridge RouteManager so the cleanup path
+// can drop a tab's interception state when the tab closes (mirrors the
+// network-monitor / log-store / executor cleanup hooks in tab_cleanup.go).
+func (tm *TabManager) SetRouteManager(rm *RouteManager) {
+ tm.routeMgr = rm
+}
+
// browserExecutorContext returns a context bound to the top-level browser
// executor, suitable for issuing browser-scoped CDP calls (e.g. target.*).
// Shared helper used by tab lifecycle, lookup, popup-guard, and cleanup paths.
diff --git a/internal/cli/actions/actions_network_route.go b/internal/cli/actions/actions_network_route.go
new file mode 100644
index 00000000..184357a9
--- /dev/null
+++ b/internal/cli/actions/actions_network_route.go
@@ -0,0 +1,113 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+// NetworkRoute installs an interception rule on the active tab.
+// Behavior depends on flags:
+//
+// --abort : block matching requests
+// --body <json> : fulfill matching requests with the given JSON body
+//
+// With neither flag set, the rule is a pass-through (continue).
+//
+// Optional refinements:
+//
+// --resource-type <kind> : only intercept this CDP resource category
+// --status <code> : (with --body) override the response status (default 200)
+// --content-type <ct> : (with --body) override Content-Type (default application/json)
+//
+// The --tab flag (state file) selects the target tab; when
+// empty the bare /network/route endpoint resolves to the active tab.
+func NetworkRoute(client *http.Client, base, token string, cmd *cobra.Command, pattern string) {
+ abort, _ := cmd.Flags().GetBool("abort")
+ body, _ := cmd.Flags().GetString("body")
+ resourceType, _ := cmd.Flags().GetString("resource-type")
+ contentType, _ := cmd.Flags().GetString("content-type")
+ status, _ := cmd.Flags().GetInt("status")
+ method, _ := cmd.Flags().GetString("method")
+
+ if abort && body != "" {
+ fmt.Fprintln(os.Stderr, "Error: --abort and --body are mutually exclusive")
+ os.Exit(1)
+ }
+
+ req := map[string]any{"pattern": pattern}
+ switch {
+ case abort:
+ req["action"] = "abort"
+ case body != "":
+ req["action"] = "fulfill"
+ req["body"] = body
+ default:
+ req["action"] = "continue"
+ }
+ if resourceType != "" {
+ req["resourceType"] = resourceType
+ }
+ if contentType != "" {
+ req["contentType"] = contentType
+ }
+ if status != 0 {
+ req["status"] = status
+ }
+ if method != "" {
+ req["method"] = method
+ }
+
+ path := "/network/route"
+ if tab, _ := cmd.Flags().GetString("tab"); tab != "" {
+ path = fmt.Sprintf("/tabs/%s/network/route", url.PathEscape(tab))
+ }
+ result := apiclient.DoPostQuiet(client, base, token, path, req)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to install route")
+ os.Exit(1)
+ }
+
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ if jsonOutput {
+ out, _ := json.MarshalIndent(result, "", " ")
+ fmt.Println(string(out))
+ return
+ }
+ fmt.Printf("route installed: %s (%s)\n", pattern, req["action"])
+}
+
+// NetworkUnroute removes one or all rules from the active tab. Empty pattern
+// removes all rules.
+func NetworkUnroute(client *http.Client, base, token string, cmd *cobra.Command, pattern string) {
+ params := url.Values{}
+ if pattern != "" {
+ params.Set("pattern", pattern)
+ }
+ path := "/network/route"
+ if tab, _ := cmd.Flags().GetString("tab"); tab != "" {
+ path = fmt.Sprintf("/tabs/%s/network/route", url.PathEscape(tab))
+ }
+ result := apiclient.DoDelete(client, base, token, path, params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to remove route(s)")
+ os.Exit(1)
+ }
+
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ if jsonOutput {
+ out, _ := json.MarshalIndent(result, "", " ")
+ fmt.Println(string(out))
+ return
+ }
+ if removed, ok := result["removed"].(float64); ok {
+ fmt.Printf("removed %d route(s)\n", int(removed))
+ } else {
+ fmt.Println("routes cleared")
+ }
+}
diff --git a/internal/cli/report/security_defaults.go b/internal/cli/report/security_defaults.go
index 6b740b4e..91ee9e5d 100644
--- a/internal/cli/report/security_defaults.go
+++ b/internal/cli/report/security_defaults.go
@@ -30,6 +30,7 @@ func RecommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
"security.allowScreencast = false",
"security.allowDownload = false",
"security.allowUpload = false",
+ "security.allowNetworkIntercept = false",
"security.attach.enabled = false",
"security.attach.allowHosts = 127.0.0.1,localhost,::1",
"security.attach.allowSchemes = ws,wss",
@@ -55,6 +56,7 @@ func RecommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
"security.allowScreencast = false",
"security.allowDownload = false",
"security.allowUpload = false",
+ "security.allowNetworkIntercept = false",
} {
needed[line] = true
}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index d89381c6..07dcff22 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -121,6 +121,7 @@ func DefaultFileConfig() FileConfig {
allowMacro := false
allowScreencast := false
allowDownload := false
+ allowNetworkIntercept := false
downloadMaxBytes := DefaultDownloadMaxBytes
allowUpload := false
allowClipboard := false
@@ -180,6 +181,7 @@ func DefaultFileConfig() FileConfig {
AllowMacro: &allowMacro,
AllowScreencast: &allowScreencast,
AllowDownload: &allowDownload,
+ AllowNetworkIntercept: &allowNetworkIntercept,
AllowedDomains: append([]string(nil), defaultLocalAllowedDomains...),
DownloadAllowedDomains: []string{},
DownloadMaxBytes: &downloadMaxBytes,
diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.go
index ee7f4d24..893bfbb1 100644
--- a/internal/config/config_file_json.go
+++ b/internal/config/config_file_json.go
@@ -62,6 +62,7 @@ type securityConfigJSON struct {
AllowMacro *bool `json:"allowMacro"`
AllowScreencast *bool `json:"allowScreencast"`
AllowDownload *bool `json:"allowDownload"`
+ AllowNetworkIntercept *bool `json:"allowNetworkIntercept"`
AllowedDomains []string `json:"allowedDomains"`
DownloadAllowedDomains []string `json:"downloadAllowedDomains"`
DownloadMaxBytes *int `json:"downloadMaxBytes"`
diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.go
index e3542c34..98303bc8 100644
--- a/internal/config/config_file_marshal.go
+++ b/internal/config/config_file_marshal.go
@@ -94,6 +94,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {
AllowMacro: fc.Security.AllowMacro,
AllowScreencast: fc.Security.AllowScreencast,
AllowDownload: fc.Security.AllowDownload,
+ AllowNetworkIntercept: fc.Security.AllowNetworkIntercept,
AllowedDomains: effectiveSecurityAllowedDomains(fc.Security),
DownloadAllowedDomains: copyStringSlice(fc.Security.DownloadAllowedDomains),
DownloadMaxBytes: fc.Security.DownloadMaxBytes,
@@ -249,6 +250,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
allowMacro := cfg.AllowMacro
allowScreencast := cfg.AllowScreencast
allowDownload := cfg.AllowDownload
+ allowNetworkIntercept := cfg.AllowNetworkIntercept
downloadAllowedDomains := copyStringSlice(cfg.DownloadAllowedDomains)
downloadMaxBytes := cfg.EffectiveDownloadMaxBytes()
allowUpload := cfg.AllowUpload
@@ -344,6 +346,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
AllowMacro: &allowMacro,
AllowScreencast: &allowScreencast,
AllowDownload: &allowDownload,
+ AllowNetworkIntercept: &allowNetworkIntercept,
AllowedDomains: append([]string(nil), cfg.AllowedDomains...),
DownloadAllowedDomains: downloadAllowedDomains,
DownloadMaxBytes: &downloadMaxBytes,
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index d6f21caa..8bac5fc7 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -25,6 +25,7 @@ func Load() *RuntimeConfig {
AllowMacro: false,
AllowScreencast: false,
AllowDownload: false,
+ AllowNetworkIntercept: false,
AllowedDomains: append([]string(nil), defaultLocalAllowedDomains...),
DownloadAllowedDomains: nil,
DownloadMaxBytes: DefaultDownloadMaxBytes,
@@ -245,6 +246,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Security.AllowDownload != nil {
cfg.AllowDownload = *fc.Security.AllowDownload
}
+ if fc.Security.AllowNetworkIntercept != nil {
+ cfg.AllowNetworkIntercept = *fc.Security.AllowNetworkIntercept
+ }
cfg.DownloadAllowedDomains = append([]string(nil), fc.Security.DownloadAllowedDomains...)
if fc.Security.DownloadMaxBytes != nil {
cfg.DownloadMaxBytes = clampPositiveLimit(*fc.Security.DownloadMaxBytes, DefaultDownloadMaxBytes, MaxDownloadMaxBytes)
diff --git a/internal/config/config_methods.go b/internal/config/config_methods.go
index f3c6ad9b..510699ee 100644
--- a/internal/config/config_methods.go
+++ b/internal/config/config_methods.go
@@ -7,7 +7,7 @@ func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {
return nil
}
- enabled := make([]string, 0, 5)
+ enabled := make([]string, 0, 6)
if cfg.AllowEvaluate {
enabled = append(enabled, "evaluate")
}
@@ -23,6 +23,9 @@ func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {
if cfg.AllowUpload {
enabled = append(enabled, "upload")
}
+ if cfg.AllowNetworkIntercept {
+ enabled = append(enabled, "networkIntercept")
+ }
return enabled
}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 164b0e0b..290e9bcb 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -18,10 +18,11 @@ type RuntimeConfig struct {
CookieSecure *bool // Nil = auto-detect based on request scheme/host for backward compatibility
// Security settings
- AllowEvaluate bool
- AllowMacro bool
- AllowScreencast bool
- AllowDownload bool
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ AllowNetworkIntercept bool
// AllowedDomains is the unified per-instance allowlist sourced from
// security.allowedDomains in the file config.
AllowedDomains []string
@@ -319,6 +320,7 @@ type SecurityConfig struct {
AllowMacro *bool `json:"allowMacro,omitempty"`
AllowScreencast *bool `json:"allowScreencast,omitempty"`
AllowDownload *bool `json:"allowDownload,omitempty"`
+ AllowNetworkIntercept *bool `json:"allowNetworkIntercept,omitempty"`
AllowedDomains []string `json:"allowedDomains,omitempty"`
DownloadAllowedDomains []string `json:"downloadAllowedDomains,omitempty"`
DownloadMaxBytes *int `json:"downloadMaxBytes,omitempty"`
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
index dd8a85d0..c50d7a61 100644
--- a/internal/config/editor_get.go
+++ b/internal/config/editor_get.go
@@ -216,6 +216,8 @@ func getSecurityField(s *SecurityConfig, field string) (string, error) {
return formatBoolPtr(s.AllowScreencast), nil
case "allowDownload":
return formatBoolPtr(s.AllowDownload), nil
+ case "allowNetworkIntercept":
+ return formatBoolPtr(s.AllowNetworkIntercept), nil
case "allowedDomains":
return strings.Join(s.AllowedDomains, ","), nil
case "downloadAllowedDomains":
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
index 7c268ae7..1e0a3085 100644
--- a/internal/config/editor_set.go
+++ b/internal/config/editor_set.go
@@ -380,6 +380,8 @@ func setSecurityField(s *SecurityConfig, field, value string) error {
s.AllowDownload = &b
case "allowUpload":
s.AllowUpload = &b
+ case "allowNetworkIntercept":
+ s.AllowNetworkIntercept = &b
case "enableActionGuards":
s.EnableActionGuards = &b
default:
diff --git a/internal/config/workflow/security.go b/internal/config/workflow/security.go
index 48196641..b08260fe 100644
--- a/internal/config/workflow/security.go
+++ b/internal/config/workflow/security.go
@@ -44,11 +44,12 @@ func UpdateSensitiveEndpoints(value string) (*config.RuntimeConfig, bool, error)
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",
+ "evaluate": "security.allowEvaluate",
+ "macro": "security.allowMacro",
+ "screencast": "security.allowScreencast",
+ "download": "security.allowDownload",
+ "upload": "security.allowUpload",
+ "networkIntercept": "security.allowNetworkIntercept",
} {
if err := config.SetConfigValue(fc, path, fmt.Sprintf("%t", selected[endpoint])); err != nil {
return fmt.Errorf("set %s: %w", endpoint, err)
@@ -131,6 +132,7 @@ func ApplyGuardsDownPreset() (*config.RuntimeConfig, string, bool, error) {
{path: "security.allowScreencast", value: "true"},
{path: "security.allowDownload", value: "true"},
{path: "security.allowUpload", value: "true"},
+ {path: "security.allowNetworkIntercept", 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"},
@@ -195,6 +197,7 @@ type securityConfigValues struct {
AllowMacro bool
AllowScreencast bool
AllowDownload bool
+ AllowNetworkIntercept bool
DownloadMaxBytes int
AllowUpload bool
UploadMaxRequestBytes int
@@ -229,6 +232,9 @@ func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
if fc.Security.AllowDownload != nil {
s.Security.AllowDownload = *fc.Security.AllowDownload
}
+ if fc.Security.AllowNetworkIntercept != nil {
+ s.Security.AllowNetworkIntercept = *fc.Security.AllowNetworkIntercept
+ }
if fc.Security.DownloadMaxBytes != nil {
s.Security.DownloadMaxBytes = *fc.Security.DownloadMaxBytes
}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 3a397ce7..30a56a3c 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -269,6 +269,12 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /tabs/{id}/network/export", h.HandleTabNetworkExport)
mux.HandleFunc("GET /tabs/{id}/network/export/stream", h.HandleTabNetworkExportStream)
mux.HandleFunc("GET /tabs/{id}/network/{requestId}", h.HandleTabNetworkByID)
+ mux.HandleFunc("POST /network/route", h.HandleNetworkRoute)
+ mux.HandleFunc("DELETE /network/route", h.HandleNetworkUnroute)
+ mux.HandleFunc("GET /network/route", h.HandleNetworkRouteList)
+ mux.HandleFunc("POST /tabs/{id}/network/route", h.HandleTabNetworkRoute)
+ mux.HandleFunc("DELETE /tabs/{id}/network/route", h.HandleTabNetworkUnroute)
+ mux.HandleFunc("GET /tabs/{id}/network/route", h.HandleTabNetworkRouteList)
mux.HandleFunc("POST /dialog", h.HandleDialog)
mux.HandleFunc("POST /tabs/{id}/dialog", h.HandleTabDialog)
mux.HandleFunc("POST /wait", h.HandleWait)
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index dce16f09..37f01cf9 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -470,6 +470,12 @@ func (m *MockBridge) NetworkMonitor() *bridge.NetworkMonitor {
return nil
}
+func (m *MockBridge) AddRouteRule(tabID string, rule bridge.RouteRule) error { return nil }
+
+func (m *MockBridge) RemoveRouteRule(tabID, pattern string) (int, error) { return 0, nil }
+
+func (m *MockBridge) ListRouteRules(tabID string) ([]bridge.RouteRule, error) { return nil, nil }
+
func (m *MockBridge) GetDialogManager() *bridge.DialogManager {
return bridge.NewDialogManager()
}
diff --git a/internal/handlers/network_route.go b/internal/handlers/network_route.go
new file mode 100644
index 00000000..1bf2efd3
--- /dev/null
+++ b/internal/handlers/network_route.go
@@ -0,0 +1,244 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+type routeRuleRequest struct {
+ Pattern string `json:"pattern"`
+ Action string `json:"action"`
+ Body string `json:"body,omitempty"`
+ ContentType string `json:"contentType,omitempty"`
+ Status int `json:"status,omitempty"`
+ ResourceType string `json:"resourceType,omitempty"`
+ Method string `json:"method,omitempty"`
+}
+
+// HandleNetworkRoute installs (or replaces by pattern) an interception rule on
+// the active or query-specified tab.
+//
+// @Endpoint POST /network/route
+// @Description Install a request interception rule on a tab
+//
+// @Param tabId string query Tab ID (optional, uses current tab if empty)
+// @Param body object body {pattern, action, body?, contentType?, status?, resourceType?}
+//
+// @Response 200 application/json {ok, rules}
+// @Response 400 application/json Validation error
+// @Response 404 application/json Tab not found
+func (h *Handlers) HandleNetworkRoute(w http.ResponseWriter, r *http.Request) {
+ h.handleNetworkRouteFor(w, r, r.URL.Query().Get("tabId"))
+}
+
+// HandleNetworkUnroute removes one or all rules.
+//
+// @Endpoint DELETE /network/route
+// @Description Remove an interception rule (or all if pattern is empty/missing)
+//
+// @Param tabId string query Tab ID (optional, uses current tab if empty)
+// @Param pattern string query Pattern to remove (omit to remove all)
+//
+// @Response 200 application/json {ok, removed, rules}
+// @Response 404 application/json Tab not found
+func (h *Handlers) HandleNetworkUnroute(w http.ResponseWriter, r *http.Request) {
+ h.handleNetworkUnrouteFor(w, r, r.URL.Query().Get("tabId"))
+}
+
+// HandleNetworkRouteList returns the current rules for the active or
+// query-specified tab.
+//
+// @Endpoint GET /network/route
+// @Description List active interception rules for a tab
+func (h *Handlers) HandleNetworkRouteList(w http.ResponseWriter, r *http.Request) {
+ h.handleNetworkRouteListFor(w, r, r.URL.Query().Get("tabId"))
+}
+
+// HandleTabNetworkRoute is the path-scoped wrapper for HandleNetworkRoute.
+//
+// @Endpoint POST /tabs/{id}/network/route
+func (h *Handlers) HandleTabNetworkRoute(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+ h.handleNetworkRouteFor(w, r, tabID)
+}
+
+// HandleTabNetworkUnroute is the path-scoped wrapper for HandleNetworkUnroute.
+//
+// @Endpoint DELETE /tabs/{id}/network/route
+func (h *Handlers) HandleTabNetworkUnroute(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+ h.handleNetworkUnrouteFor(w, r, tabID)
+}
+
+// HandleTabNetworkRouteList is the path-scoped wrapper for HandleNetworkRouteList.
+//
+// @Endpoint GET /tabs/{id}/network/route
+func (h *Handlers) HandleTabNetworkRouteList(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+ h.handleNetworkRouteListFor(w, r, tabID)
+}
+
+// requireRouteContext is the shared prelude for the network/route handlers.
+// It runs the capability gate, ensures Chrome is up, and resolves the tab
+// context. On failure the response has been written and ok=false. On success
+// the caller has tabCtx + resolved tab ID; mutation handlers should follow up
+// with enforceCurrentTabDomainPolicy(tabCtx, resolvedID).
+func (h *Handlers) requireRouteContext(w http.ResponseWriter, r *http.Request, tabID string) (tabCtx context.Context, resolvedID string, ok bool) {
+ if !h.networkInterceptEnabled() {
+ httpx.ErrorCode(w, 403, "network_intercept_disabled",
+ httpx.DisabledEndpointMessage("networkIntercept", "security.allowNetworkIntercept"),
+ false, map[string]any{"setting": "security.allowNetworkIntercept"})
+ return nil, "", false
+ }
+ if err := h.ensureChrome(); err != nil {
+ if h.writeBridgeUnavailable(w, err) {
+ return nil, "", false
+ }
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ return nil, "", false
+ }
+ ctx, id, err := h.tabContext(r, tabID)
+ if err != nil {
+ httpx.Error(w, 404, err)
+ return nil, "", false
+ }
+ return ctx, id, true
+}
+
+func (h *Handlers) handleNetworkRouteFor(w http.ResponseWriter, r *http.Request, tabID string) {
+ tabCtx, resolvedID, ok := h.requireRouteContext(w, r, tabID)
+ if !ok {
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedID); !ok {
+ return
+ }
+
+ var req routeRuleRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ httpx.Error(w, 400, fmt.Errorf("decode body: %w", err))
+ return
+ }
+ if req.Pattern == "" {
+ httpx.Error(w, 400, fmt.Errorf("pattern required"))
+ return
+ }
+ // Early validation for clean 400s. AddRule re-checks authoritatively so
+ // non-HTTP callers are protected too — these are belt-and-suspenders.
+ if len(req.Body) > bridge.MaxFulfillBodyBytes {
+ httpx.Error(w, 400, fmt.Errorf("body exceeds %d bytes (cap)", bridge.MaxFulfillBodyBytes))
+ return
+ }
+ if req.Status != 0 && (req.Status < 100 || req.Status > 599) {
+ httpx.Error(w, 400, fmt.Errorf("status %d out of HTTP range (100-599)", req.Status))
+ return
+ }
+ if req.ContentType != "" && !bridge.IsFulfillContentTypeAllowed(req.ContentType) {
+ httpx.Error(w, 400, fmt.Errorf("contentType %q is not on the fulfill safe-list (or contains control chars)", req.ContentType))
+ return
+ }
+ if !bridge.IsResourceTypeValid(req.ResourceType) {
+ httpx.Error(w, 400, fmt.Errorf("invalid resourceType %q", req.ResourceType))
+ return
+ }
+ if req.Action == "" {
+ req.Action = string(bridge.RouteActionContinue)
+ }
+
+ rule := bridge.RouteRule{
+ Pattern: req.Pattern,
+ Action: bridge.RouteAction(req.Action),
+ Body: req.Body,
+ ContentType: req.ContentType,
+ Status: req.Status,
+ ResourceType: req.ResourceType,
+ Method: req.Method,
+ }
+ if err := h.Bridge.AddRouteRule(resolvedID, rule); err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+
+ rules, _ := h.Bridge.ListRouteRules(resolvedID)
+ httpx.JSON(w, 200, map[string]any{
+ "ok": true,
+ "tabId": resolvedID,
+ "rules": rules,
+ })
+}
+
+func (h *Handlers) handleNetworkUnrouteFor(w http.ResponseWriter, r *http.Request, tabID string) {
+ tabCtx, resolvedID, ok := h.requireRouteContext(w, r, tabID)
+ if !ok {
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedID); !ok {
+ return
+ }
+
+ pattern := r.URL.Query().Get("pattern")
+ if pattern == "" && r.ContentLength > 0 {
+ var body struct {
+ Pattern string `json:"pattern"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ httpx.Error(w, 400, fmt.Errorf("decode body: %w", err))
+ return
+ }
+ pattern = body.Pattern
+ }
+
+ removed, err := h.Bridge.RemoveRouteRule(resolvedID, pattern)
+ if err != nil {
+ if errors.Is(err, bridge.ErrTabNotRouted) {
+ httpx.Error(w, 404, err)
+ return
+ }
+ httpx.Error(w, 500, err)
+ return
+ }
+ rules, _ := h.Bridge.ListRouteRules(resolvedID)
+ httpx.JSON(w, 200, map[string]any{
+ "ok": true,
+ "tabId": resolvedID,
+ "removed": removed,
+ "rules": rules,
+ })
+}
+
+func (h *Handlers) handleNetworkRouteListFor(w http.ResponseWriter, r *http.Request, tabID string) {
+ _, resolvedID, ok := h.requireRouteContext(w, r, tabID)
+ if !ok {
+ return
+ }
+ rules, err := h.Bridge.ListRouteRules(resolvedID)
+ if err != nil {
+ httpx.Error(w, 500, err)
+ return
+ }
+ if rules == nil {
+ rules = []bridge.RouteRule{}
+ }
+ httpx.JSON(w, 200, map[string]any{
+ "tabId": resolvedID,
+ "rules": rules,
+ })
+}
diff --git a/internal/handlers/network_route_test.go b/internal/handlers/network_route_test.go
new file mode 100644
index 00000000..0f235878
--- /dev/null
+++ b/internal/handlers/network_route_test.go
@@ -0,0 +1,371 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// routeMockBridge implements just the slice of BridgeAPI used by the route
+// handlers. Rule storage is in-memory per tab; CDP is never touched.
+type routeMockBridge struct {
+ mockBridge
+ rules map[string][]bridge.RouteRule
+}
+
+func newRouteMockBridge() *routeMockBridge {
+ return &routeMockBridge{rules: map[string][]bridge.RouteRule{}}
+}
+
+func (m *routeMockBridge) AddRouteRule(tabID string, rule bridge.RouteRule) error {
+ for i, r := range m.rules[tabID] {
+ if r.Pattern == rule.Pattern {
+ m.rules[tabID][i] = rule
+ return nil
+ }
+ }
+ m.rules[tabID] = append(m.rules[tabID], rule)
+ return nil
+}
+
+func (m *routeMockBridge) RemoveRouteRule(tabID, pattern string) (int, error) {
+ if pattern == "" {
+ n := len(m.rules[tabID])
+ delete(m.rules, tabID)
+ return n, nil
+ }
+ kept := m.rules[tabID][:0]
+ removed := 0
+ for _, r := range m.rules[tabID] {
+ if r.Pattern == pattern {
+ removed++
+ continue
+ }
+ kept = append(kept, r)
+ }
+ m.rules[tabID] = kept
+ return removed, nil
+}
+
+func (m *routeMockBridge) ListRouteRules(tabID string) ([]bridge.RouteRule, error) {
+ return m.rules[tabID], nil
+}
+
+func newRouteHandler(b *routeMockBridge) *Handlers {
+ return New(b, &config.RuntimeConfig{AllowNetworkIntercept: true}, nil, nil, nil)
+}
+
+func TestHandleTabNetworkRoute_AddAbort(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+
+ body := `{"pattern":"*.png","action":"abort"}`
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader([]byte(body)))
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRoute(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ OK bool `json:"ok"`
+ Rules []bridge.RouteRule `json:"rules"`
+ }
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if !resp.OK || len(resp.Rules) != 1 || resp.Rules[0].Action != bridge.RouteActionAbort {
+ t.Errorf("unexpected response: %s", w.Body.String())
+ }
+}
+
+func TestHandleTabNetworkRoute_AddFulfill_DefaultsContentType(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+
+ body := `{"pattern":"api","action":"fulfill","body":"{\"k\":1}"}`
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader([]byte(body)))
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRoute(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := b.rules["tab1"][0]; got.Body != `{"k":1}` || got.Action != bridge.RouteActionFulfill {
+ t.Errorf("rule not stored as expected: %+v", got)
+ }
+}
+
+func TestHandleTabNetworkRoute_CapabilityDisabled(t *testing.T) {
+ b := newRouteMockBridge()
+ // Default RuntimeConfig has AllowNetworkIntercept=false.
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+
+ body := `{"pattern":"x","action":"continue"}`
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader([]byte(body)))
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRoute(w, req)
+
+ if w.Code != 403 {
+ t.Fatalf("expected 403 when capability disabled, got %d: %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "security.allowNetworkIntercept") {
+ t.Errorf("expected setting key in error body, got %s", w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "network_intercept_disabled") {
+ t.Errorf("expected error code in body, got %s", w.Body.String())
+ }
+}
+
+func TestHandleTabNetworkUnroute_CapabilityDisabled(t *testing.T) {
+ b := newRouteMockBridge()
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("DELETE", "/tabs/tab1/network/route", nil)
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkUnroute(w, req)
+
+ if w.Code != 403 {
+ t.Fatalf("expected 403 when capability disabled, got %d", w.Code)
+ }
+}
+
+func TestHandleTabNetworkRouteList_CapabilityDisabled(t *testing.T) {
+ b := newRouteMockBridge()
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/tabs/tab1/network/route", nil)
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRouteList(w, req)
+
+ if w.Code != 403 {
+ t.Fatalf("expected 403 when capability disabled, got %d", w.Code)
+ }
+}
+
+func TestHandleTabNetworkRoute_BodyExceedsCap(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+
+ huge := make([]byte, bridge.MaxFulfillBodyBytes+1)
+ for i := range huge {
+ huge[i] = 'a'
+ }
+ payload, _ := json.Marshal(map[string]any{
+ "pattern": "api",
+ "action": "fulfill",
+ "body": string(huge),
+ })
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader(payload))
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRoute(w, req)
+
+ if w.Code != 400 {
+ t.Fatalf("expected 400 for oversized body, got %d: %s", w.Code, w.Body.String())
+ }
+ if len(b.rules["tab1"]) != 0 {
+ t.Errorf("oversized rule should not have been stored")
+ }
+}
+
+func TestHandleTabNetworkRoute_StatusOutOfRange(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+
+ for _, bad := range []int{99, 600, -1, 1000} {
+ body := fmt.Sprintf(`{"pattern":"api","action":"fulfill","body":"{}","status":%d}`, bad)
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader([]byte(body)))
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRoute(w, req)
+ if w.Code != 400 {
+ t.Errorf("status=%d should reject (400), got %d: %s", bad, w.Code, w.Body.String())
+ }
+ }
+}
+
+func TestHandleTabNetworkUnroute_BadJSONReturns400(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+
+ req := httptest.NewRequest("DELETE", "/tabs/tab1/network/route", bytes.NewReader([]byte(`{not json`)))
+ req.SetPathValue("id", "tab1")
+ req.ContentLength = 9
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkUnroute(w, req)
+
+ if w.Code != 400 {
+ t.Fatalf("expected 400 for malformed body, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleTabNetworkRoute_MissingPattern(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader([]byte(`{}`)))
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRoute(w, req)
+
+ if w.Code != 400 {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleTabNetworkUnroute_All(t *testing.T) {
+ b := newRouteMockBridge()
+ b.rules["tab1"] = []bridge.RouteRule{
+ {Pattern: "a", Action: bridge.RouteActionAbort},
+ {Pattern: "b", Action: bridge.RouteActionAbort},
+ }
+ h := newRouteHandler(b)
+
+ req := httptest.NewRequest("DELETE", "/tabs/tab1/network/route", nil)
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkUnroute(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Removed int `json:"removed"`
+ }
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp.Removed != 2 {
+ t.Errorf("expected 2 removed, got %d", resp.Removed)
+ }
+ if len(b.rules["tab1"]) != 0 {
+ t.Errorf("expected rules cleared, got %d", len(b.rules["tab1"]))
+ }
+}
+
+func TestHandleTabNetworkUnroute_ByPatternQuery(t *testing.T) {
+ b := newRouteMockBridge()
+ b.rules["tab1"] = []bridge.RouteRule{
+ {Pattern: "a", Action: bridge.RouteActionAbort},
+ {Pattern: "b", Action: bridge.RouteActionAbort},
+ }
+ h := newRouteHandler(b)
+
+ req := httptest.NewRequest("DELETE", "/tabs/tab1/network/route?pattern=a", nil)
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkUnroute(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if len(b.rules["tab1"]) != 1 || b.rules["tab1"][0].Pattern != "b" {
+ t.Errorf("unexpected remaining rules: %+v", b.rules["tab1"])
+ }
+}
+
+func TestHandleTabNetworkRouteList(t *testing.T) {
+ b := newRouteMockBridge()
+ b.rules["tab1"] = []bridge.RouteRule{
+ {Pattern: "*.png", Action: bridge.RouteActionAbort},
+ }
+ h := newRouteHandler(b)
+
+ req := httptest.NewRequest("GET", "/tabs/tab1/network/route", nil)
+ req.SetPathValue("id", "tab1")
+ w := httptest.NewRecorder()
+ h.HandleTabNetworkRouteList(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Rules []bridge.RouteRule `json:"rules"`
+ }
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if len(resp.Rules) != 1 || resp.Rules[0].Pattern != "*.png" {
+ t.Errorf("unexpected rules in response: %s", w.Body.String())
+ }
+}
+
+func TestRegisterRoutes_Mounts(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ body := `{"pattern":"x","action":"continue"}`
+ req := httptest.NewRequest("POST", "/tabs/tab1/network/route", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleNetworkRoute_BareForm(t *testing.T) {
+ b := newRouteMockBridge()
+ h := newRouteHandler(b)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ body := `{"pattern":"*.png","action":"abort"}`
+ req := httptest.NewRequest("POST", "/network/route?tabId=tab1", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if len(b.rules["tab1"]) != 1 || b.rules["tab1"][0].Action != bridge.RouteActionAbort {
+ t.Errorf("rule not stored on tab1 via bare form: %+v", b.rules["tab1"])
+ }
+}
+
+func TestHandleNetworkUnroute_BareForm(t *testing.T) {
+ b := newRouteMockBridge()
+ b.rules["tab1"] = []bridge.RouteRule{
+ {Pattern: "a", Action: bridge.RouteActionAbort},
+ {Pattern: "b", Action: bridge.RouteActionAbort},
+ }
+ h := newRouteHandler(b)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ req := httptest.NewRequest("DELETE", "/network/route?tabId=tab1&pattern=a", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if len(b.rules["tab1"]) != 1 || b.rules["tab1"][0].Pattern != "b" {
+ t.Errorf("unexpected remaining rules: %+v", b.rules["tab1"])
+ }
+}
+
+func TestHandleNetworkRouteList_BareForm(t *testing.T) {
+ b := newRouteMockBridge()
+ b.rules["tab1"] = []bridge.RouteRule{{Pattern: "*.css", Action: bridge.RouteActionAbort}}
+ h := newRouteHandler(b)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ req := httptest.NewRequest("GET", "/network/route?tabId=tab1", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index 66614ce5..13294564 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -25,6 +25,10 @@ func (h *Handlers) uploadEnabled() bool {
return h != nil && h.Config != nil && h.Config.AllowUpload
}
+func (h *Handlers) networkInterceptEnabled() bool {
+ return h != nil && h.Config != nil && h.Config.AllowNetworkIntercept
+}
+
func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
return map[string]endpointSecurityState{
"evaluate": {
@@ -74,5 +78,14 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
"POST /state/load", "DELETE /state", "POST /state/clean",
},
},
+ "networkIntercept": {
+ Enabled: h.networkInterceptEnabled(),
+ Setting: "security.allowNetworkIntercept",
+ Message: httpx.DisabledEndpointMessage("networkIntercept", "security.allowNetworkIntercept"),
+ Paths: []string{
+ "GET /network/route", "POST /network/route", "DELETE /network/route",
+ "GET /tabs/{id}/network/route", "POST /tabs/{id}/network/route", "DELETE /tabs/{id}/network/route",
+ },
+ },
}
}
diff --git a/internal/idpi/domain.go b/internal/idpi/domain.go
index c043ea3c..7107390f 100644
--- a/internal/idpi/domain.go
+++ b/internal/idpi/domain.go
@@ -2,42 +2,37 @@ package idpi
import (
"fmt"
- "net"
- "net/url"
- "strings"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/security"
)
// CheckDomain evaluates rawURL against the domain whitelist in cfg.
//
// It returns a non-zero CheckResult when the feature is enabled, the whitelist
// is non-empty, and the host extracted from rawURL does not match any allowed
-// pattern.
+// pattern. The host-allowlist primitive lives in internal/security; this
+// function layers IDPI's enabled/strictMode policy on top.
//
-// Supported pattern forms:
+// Supported pattern forms (delegated to security):
// - "example.com" – exact host match (case-insensitive, port stripped)
-// - "*.example.com" – matches any single subdomain of example.com but NOT
-// example.com itself
+// - "*.example.com" – any single subdomain of example.com but NOT example.com
// - "*" – matches any host (effectively disables the whitelist)
func CheckDomain(rawURL string, cfg config.IDPIConfig, allowedDomains []string) CheckResult {
if !cfg.Enabled || len(allowedDomains) == 0 {
return CheckResult{}
}
- if isAllowedSpecialURL(rawURL) {
+ if security.IsAllowedSpecialURL(rawURL) {
return CheckResult{}
}
- host := extractHost(rawURL)
+ host := security.ExtractHost(rawURL)
if host == "" {
- // Cannot extract a domain component (e.g. file://, about:blank, chrome://).
- // When a whitelist is active we must not silently allow URLs we cannot
- // verify — deny them so callers can decide how to proceed.
return makeResult(cfg.StrictMode,
"URL has no domain component and cannot be verified against allowedDomains")
}
- if domainAllowed(host, allowedDomains) {
+ if security.HostMatchesPatterns(host, allowedDomains) {
return CheckResult{}
}
@@ -46,75 +41,17 @@ func CheckDomain(rawURL string, cfg config.IDPIConfig, allowedDomains []string)
}
// DomainAllowed reports whether rawURL's host matches an explicit allowedDomains
-// entry under an active IDPI domain allowlist.
+// entry under an active IDPI domain allowlist. For an IDPI-independent check
+// callers should use security.HostAllowed directly.
func DomainAllowed(rawURL string, cfg config.IDPIConfig, allowedDomains []string) bool {
- if !cfg.Enabled || len(allowedDomains) == 0 || isAllowedSpecialURL(rawURL) {
+ if !cfg.Enabled || len(allowedDomains) == 0 || security.IsAllowedSpecialURL(rawURL) {
return false
}
- host := extractHost(rawURL)
+ host := security.ExtractHost(rawURL)
if host == "" {
return false
}
- return domainAllowed(host, allowedDomains)
-}
-
-func isAllowedSpecialURL(rawURL string) bool {
- return strings.EqualFold(strings.TrimSpace(rawURL), "about:blank")
-}
-
-// extractHost parses rawURL and returns the lowercase bare hostname (no port).
-// It handles both fully-qualified URLs ("https://example.com:8080/path") and
-// bare hostnames ("example.com" or "example.com/path").
-func extractHost(rawURL string) string {
- parsed, err := url.Parse(rawURL)
- if err != nil {
- return ""
- }
-
- host := parsed.Hostname() // strips port; returns "" for bare hostnames
-
- if host == "" {
- // url.Parse puts bare hostnames into Path when no scheme is present.
- // Recover the host by treating the first path segment as the authority.
- bare := parsed.Path
- bare = strings.SplitN(bare, "/", 2)[0]
- bare = strings.SplitN(bare, "?", 2)[0]
- bare = strings.SplitN(bare, "#", 2)[0]
- if h, _, err := net.SplitHostPort(bare); err == nil {
- host = h
- } else {
- host = bare
- }
- }
-
- return strings.ToLower(strings.TrimSpace(host))
-}
-
-func domainAllowed(host string, patterns []string) bool {
- for _, pattern := range patterns {
- pattern = strings.ToLower(strings.TrimSpace(pattern))
- if pattern == "" {
- continue
- }
- if matchDomain(host, pattern) {
- return true
- }
- }
- return false
-}
-
-// matchDomain reports whether host matches pattern (both already lowercased).
-func matchDomain(host, pattern string) bool {
- switch {
- case pattern == "*":
- return true
- case strings.HasPrefix(pattern, "*."):
- // "*.example.com" matches "foo.example.com" but NOT "example.com"
- suffix := pattern[1:] // ".example.com"
- return strings.HasSuffix(host, suffix)
- default:
- return host == pattern
- }
+ return security.HostMatchesPatterns(host, allowedDomains)
}
func makeResult(strictMode bool, reason string) CheckResult {
diff --git a/internal/mcp/client.go b/internal/mcp/client.go
index de0499a4..85cdd449 100644
--- a/internal/mcp/client.go
+++ b/internal/mcp/client.go
@@ -77,6 +77,19 @@ func (c *Client) Get(ctx context.Context, path string, query url.Values) ([]byte
return c.do(req)
}
+// Delete performs a DELETE request, optionally with a query string.
+func (c *Client) Delete(ctx context.Context, path string, query url.Values) ([]byte, int, error) {
+ u := c.url(path)
+ if len(query) > 0 {
+ u += "?" + query.Encode()
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodDelete, u, nil)
+ if err != nil {
+ return nil, 0, err
+ }
+ return c.do(req)
+}
+
// Post performs a POST request with a JSON body.
func (c *Client) Post(ctx context.Context, path string, payload any) ([]byte, int, error) {
var body io.Reader
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index 91b96e14..dbabdd4e 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -57,9 +57,11 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)
"pinchtab_wait_for_function": handleWaitForFunction(c),
// Network monitoring
- "pinchtab_network": handleNetwork(c),
- "pinchtab_network_detail": handleNetworkDetail(c),
- "pinchtab_network_clear": handleNetworkClear(c),
+ "pinchtab_network": handleNetwork(c),
+ "pinchtab_network_detail": handleNetworkDetail(c),
+ "pinchtab_network_clear": handleNetworkClear(c),
+ "pinchtab_network_route": handleNetworkRoute(c),
+ "pinchtab_network_unroute": handleNetworkUnroute(c),
// Dialog
"pinchtab_dialog": handleDialog(c),
diff --git a/internal/mcp/handlers_network.go b/internal/mcp/handlers_network.go
index b5b32476..6f7a5bda 100644
--- a/internal/mcp/handlers_network.go
+++ b/internal/mcp/handlers_network.go
@@ -75,3 +75,64 @@ func handleNetworkClear(c *Client) func(context.Context, mcp.CallToolRequest) (*
return resultFromBytes(body, code)
}
}
+
+func handleNetworkRoute(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ tabID, err := r.RequireString("tabId")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ pattern, err := r.RequireString("pattern")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+
+ payload := map[string]any{"pattern": pattern}
+ if action := optString(r, "action"); action != "" {
+ payload["action"] = action
+ } else {
+ payload["action"] = "continue"
+ }
+ if body := optString(r, "body"); body != "" {
+ payload["body"] = body
+ }
+ if ct := optString(r, "contentType"); ct != "" {
+ payload["contentType"] = ct
+ }
+ if rt := optString(r, "resourceType"); rt != "" {
+ payload["resourceType"] = rt
+ }
+ if status, ok := optInt(r, "status"); ok {
+ payload["status"] = status
+ }
+ if method := optString(r, "method"); method != "" {
+ payload["method"] = method
+ }
+
+ path := "/tabs/" + url.PathEscape(tabID) + "/network/route"
+ respBody, code, err := c.Post(ctx, path, payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(respBody, code)
+ }
+}
+
+func handleNetworkUnroute(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ tabID, err := r.RequireString("tabId")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ q := url.Values{}
+ if pattern := optString(r, "pattern"); pattern != "" {
+ q.Set("pattern", pattern)
+ }
+ path := "/tabs/" + url.PathEscape(tabID) + "/network/route"
+ respBody, code, err := c.Delete(ctx, path, q)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(respBody, code)
+ }
+}
diff --git a/internal/mcp/handlers_network_test.go b/internal/mcp/handlers_network_test.go
index 447ae469..edf59daf 100644
--- a/internal/mcp/handlers_network_test.go
+++ b/internal/mcp/handlers_network_test.go
@@ -91,3 +91,86 @@ func TestHandleNetworkClearWithTab(t *testing.T) {
t.Errorf("expected /network/clear path, got %s", text)
}
}
+
+func TestHandleNetworkRoute_Abort(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_network_route", map[string]any{
+ "tabId": "t1",
+ "pattern": "*.png",
+ "action": "abort",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/tabs/t1/network/route") {
+ t.Errorf("expected /tabs/t1/network/route path, got %s", text)
+ }
+ if !strings.Contains(text, `"action":"abort"`) {
+ t.Errorf("expected action=abort in body echo, got %s", text)
+ }
+}
+
+func TestHandleNetworkRoute_Fulfill_PassesAllFields(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_network_route", map[string]any{
+ "tabId": "t1",
+ "pattern": "api",
+ "action": "fulfill",
+ "body": `{"k":1}`,
+ "contentType": "application/json",
+ "status": float64(201),
+ "resourceType": "xhr",
+ }, srv)
+
+ text := resultText(t, r)
+ for _, want := range []string{`"contentType":"application/json"`, `"resourceType":"xhr"`, `"status":201`} {
+ if !strings.Contains(text, want) {
+ t.Errorf("expected %s in body echo, got %s", want, text)
+ }
+ }
+}
+
+func TestHandleNetworkRoute_MissingPattern(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_network_route", map[string]any{"tabId": "t1"}, srv)
+ if !r.IsError {
+ t.Error("expected error when pattern missing")
+ }
+}
+
+func TestHandleNetworkUnroute(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_network_unroute", map[string]any{
+ "tabId": "t1",
+ "pattern": "*.png",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/tabs/t1/network/route") {
+ t.Errorf("expected /tabs/t1/network/route path, got %s", text)
+ }
+ if !strings.Contains(text, `"DELETE"`) {
+ t.Errorf("expected DELETE method, got %s", text)
+ }
+ if !strings.Contains(text, "*.png") {
+ t.Errorf("expected pattern in query, got %s", text)
+ }
+}
+
+func TestHandleNetworkUnroute_All(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_network_unroute", map[string]any{"tabId": "t1"}, srv)
+ text := resultText(t, r)
+ if !strings.Contains(text, "/tabs/t1/network/route") {
+ t.Errorf("expected /tabs/t1/network/route path, got %s", text)
+ }
+}
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
index ecffc0b7..d7ed5fa2 100644
--- a/internal/mcp/server_test.go
+++ b/internal/mcp/server_test.go
@@ -18,8 +18,8 @@ func TestNewServerRegistersAllTools(t *testing.T) {
// The server should have registered all tools.
// We verify by checking that NewServer doesn't panic — the panic
// in NewServer fires if any tool lacks a handler.
- if len(tools) != 36 {
- t.Errorf("expected 36 tools, got %d", len(tools))
+ if len(tools) != 38 {
+ t.Errorf("expected 38 tools, got %d", len(tools))
}
}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 8854f254..04ac9038 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -250,6 +250,22 @@ func allTools() []mcp.Tool {
mcp.WithDescription("Clear captured network data for a tab or all tabs"),
mcp.WithString("tabId", mcp.Description("Target tab ID (optional, clears all if empty)")),
),
+ mcp.NewTool("pinchtab_network_route",
+ mcp.WithDescription("Install a request interception rule on a tab. Action 'abort' blocks matching requests, 'fulfill' returns a mocked response body, 'continue' passes through. Fulfill is BLOCKED on hosts in security.allowedDomains (the operator's authorized/sensitive surfaces) and ALLOWED on other hosts; matched fulfill rules on allowlisted hosts fall through to a real network fetch."),
+ mcp.WithString("tabId", mcp.Required(), mcp.Description("Target tab ID")),
+ mcp.WithString("pattern", mcp.Required(), mcp.Description("URL pattern: substring (no wildcards) or glob ('*', '?')")),
+ mcp.WithString("action", mcp.Description("'continue' (default), 'abort', or 'fulfill'")),
+ mcp.WithString("body", mcp.Description("Response body (with action=fulfill). Sent verbatim; not auto-encoded.")),
+ mcp.WithString("contentType", mcp.Description("Response Content-Type for fulfill (default application/json)")),
+ mcp.WithNumber("status", mcp.Description("Response status code for fulfill (default 200)")),
+ mcp.WithString("resourceType", mcp.Description("Limit to a CDP resource category (e.g. script, image, xhr, fetch, stylesheet)")),
+ mcp.WithString("method", mcp.Description("Limit to an HTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS). Fulfill rules without method skip OPTIONS preflights to avoid breaking or bypassing CORS.")),
+ ),
+ mcp.NewTool("pinchtab_network_unroute",
+ mcp.WithDescription("Remove a tab's interception rule by pattern, or all rules if pattern is omitted"),
+ mcp.WithString("tabId", mcp.Required(), mcp.Description("Target tab ID")),
+ mcp.WithString("pattern", mcp.Description("Pattern to remove (omit to clear all rules)")),
+ ),
// ── Dialog ──────────────────────────────────────────────────
mcp.NewTool("pinchtab_dialog",
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index 496915f7..ba31c94a 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -24,6 +24,8 @@ func (o *Orchestrator) Allows(cap routes.Capability) bool {
return o.AllowsUpload()
case routes.CapStateExport:
return o.AllowsStateExport()
+ case routes.CapNetworkIntercept:
+ return o.AllowsNetworkIntercept()
default:
return false
}
@@ -107,6 +109,9 @@ func (o *Orchestrator) registerHandlers(mux *http.ServeMux, skipLaunch bool) {
case routes.CapStateExport:
enabled = o.AllowsStateExport()
feature, setting, code = "stateExport", "security.allowStateExport", "state_export_disabled"
+ case routes.CapNetworkIntercept:
+ enabled = o.AllowsNetworkIntercept()
+ feature, setting, code = "networkIntercept", "security.allowNetworkIntercept", "network_intercept_disabled"
}
for _, ep := range eps {
registerCapabilityRoute(mux, ep.TabRoute(), enabled, feature, setting, code, o.proxyTabRequest)
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 2eb3d5ac..78177790 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -230,6 +230,10 @@ func (o *Orchestrator) AllowsStateExport() bool {
return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowStateExport
}
+func (o *Orchestrator) AllowsNetworkIntercept() bool {
+ return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowNetworkIntercept
+}
+
func (o *Orchestrator) SetPortRange(start, end int) {
o.portAllocator = NewPortAllocator(start, end)
}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index eb7a83b0..6378f420 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -10,13 +10,14 @@ import "fmt"
type Capability string
const (
- CapNone Capability = ""
- CapEvaluate Capability = "evaluate"
- CapMacro Capability = "macro"
- CapScreencast Capability = "screencast"
- CapDownload Capability = "download"
- CapUpload Capability = "upload"
- CapStateExport Capability = "stateExport"
+ CapNone Capability = ""
+ CapEvaluate Capability = "evaluate"
+ CapMacro Capability = "macro"
+ CapScreencast Capability = "screencast"
+ CapDownload Capability = "download"
+ CapUpload Capability = "upload"
+ CapStateExport Capability = "stateExport"
+ CapNetworkIntercept Capability = "networkIntercept"
)
// Endpoint describes a single API route.
@@ -95,6 +96,9 @@ var coreEndpoints = []Endpoint{
{"GET", "/network/export/stream", "Export HAR stream", CapNone, true},
{"GET", "/network/{requestId}", "Single network request", CapNone, true},
{"POST", "/network/clear", "Clear network log", CapNone, false},
+ {"GET", "/network/route", "List interception rules for a tab", CapNetworkIntercept, true},
+ {"POST", "/network/route", "Install an interception rule", CapNetworkIntercept, true},
+ {"DELETE", "/network/route", "Remove interception rule(s)", CapNetworkIntercept, true},
// Console & errors
{"GET", "/console", "Console logs", CapNone, false},
diff --git a/internal/security/allowlist.go b/internal/security/allowlist.go
new file mode 100644
index 00000000..8a4fdff2
--- /dev/null
+++ b/internal/security/allowlist.go
@@ -0,0 +1,99 @@
+// Package security owns the cross-cutting host allowlist primitive sourced
+// from security.allowedDomains in the file config. Feature-specific consumers
+// (IDPI, route interception, download policy, ...) import this package; the
+// reverse must not happen.
+package security
+
+import (
+ "net"
+ "net/url"
+ "strings"
+)
+
+// HostAllowed reports whether rawURL's host matches an entry in allowedDomains.
+//
+// An empty allowedDomains list means "no allowlist active" → returns true.
+// A non-empty list with no matching host → returns false. Special non-routable
+// URLs ("about:blank") are always allowed because they have no host to verify.
+//
+// Supported pattern forms:
+// - "example.com" – exact host match (case-insensitive, port stripped)
+// - "*.example.com" – any single subdomain of example.com but NOT example.com
+// - "*" – matches any host (effectively disables the allowlist)
+func HostAllowed(rawURL string, allowedDomains []string) bool {
+ if len(allowedDomains) == 0 {
+ return true
+ }
+ if isAllowedSpecialURL(rawURL) {
+ return true
+ }
+ host := ExtractHost(rawURL)
+ if host == "" {
+ return false
+ }
+ return HostMatchesPatterns(host, allowedDomains)
+}
+
+// HostMatchesPatterns reports whether host (already lowercased) matches any of
+// the patterns. Exposed so callers that already have a host don't have to
+// re-parse a URL.
+func HostMatchesPatterns(host string, patterns []string) bool {
+ for _, pattern := range patterns {
+ pattern = strings.ToLower(strings.TrimSpace(pattern))
+ if pattern == "" {
+ continue
+ }
+ if matchDomain(host, pattern) {
+ return true
+ }
+ }
+ return false
+}
+
+// ExtractHost parses rawURL and returns the lowercase bare hostname (no port).
+// It handles both fully-qualified URLs ("https://example.com:8080/path") and
+// bare hostnames ("example.com" or "example.com/path").
+func ExtractHost(rawURL string) string {
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ return ""
+ }
+
+ host := parsed.Hostname()
+
+ if host == "" {
+ bare := parsed.Path
+ bare = strings.SplitN(bare, "/", 2)[0]
+ bare = strings.SplitN(bare, "?", 2)[0]
+ bare = strings.SplitN(bare, "#", 2)[0]
+ if h, _, err := net.SplitHostPort(bare); err == nil {
+ host = h
+ } else {
+ host = bare
+ }
+ }
+
+ return strings.ToLower(strings.TrimSpace(host))
+}
+
+// IsAllowedSpecialURL reports whether rawURL is a non-routable URL that bypasses
+// host-based allowlist checks (e.g. "about:blank").
+func IsAllowedSpecialURL(rawURL string) bool {
+ return isAllowedSpecialURL(rawURL)
+}
+
+func isAllowedSpecialURL(rawURL string) bool {
+ return strings.EqualFold(strings.TrimSpace(rawURL), "about:blank")
+}
+
+func matchDomain(host, pattern string) bool {
+ switch {
+ case pattern == "*":
+ return true
+ case strings.HasPrefix(pattern, "*."):
+ suffix := pattern[1:]
+ return strings.HasSuffix(host, suffix)
+ default:
+ return host == pattern
+ }
+}
diff --git a/internal/security/allowlist_test.go b/internal/security/allowlist_test.go
new file mode 100644
index 00000000..85863a95
--- /dev/null
+++ b/internal/security/allowlist_test.go
@@ -0,0 +1,77 @@
+package security
+
+import "testing"
+
+func TestHostAllowed_EmptyAllowlistMeansNoEnforcement(t *testing.T) {
+ if !HostAllowed("https://anything.test/", nil) {
+ t.Error("nil allowlist should mean no enforcement → allowed")
+ }
+ if !HostAllowed("https://anything.test/", []string{}) {
+ t.Error("empty allowlist should mean no enforcement → allowed")
+ }
+}
+
+func TestHostAllowed_ExactMatch(t *testing.T) {
+ allow := []string{"api.example.com"}
+ if !HostAllowed("https://api.example.com/users", allow) {
+ t.Error("exact match should be allowed")
+ }
+ if HostAllowed("https://other.example.com/users", allow) {
+ t.Error("non-matching host should be blocked")
+ }
+}
+
+func TestHostAllowed_WildcardSubdomain(t *testing.T) {
+ allow := []string{"*.example.com"}
+ if !HostAllowed("https://api.example.com/", allow) {
+ t.Error("*.example.com should match api.example.com")
+ }
+ if HostAllowed("https://example.com/", allow) {
+ t.Error("*.example.com should NOT match example.com (apex)")
+ }
+}
+
+func TestHostAllowed_GlobalWildcard(t *testing.T) {
+ if !HostAllowed("https://anything.test/", []string{"*"}) {
+ t.Error("'*' should allow any host")
+ }
+}
+
+func TestHostAllowed_AboutBlankBypassesCheck(t *testing.T) {
+ allow := []string{"api.example.com"}
+ if !HostAllowed("about:blank", allow) {
+ t.Error("about:blank should bypass the host check (no host to verify)")
+ }
+}
+
+func TestHostAllowed_PortStripped(t *testing.T) {
+ allow := []string{"localhost"}
+ if !HostAllowed("http://localhost:8080/page", allow) {
+ t.Error("port should be stripped before host comparison")
+ }
+}
+
+func TestHostAllowed_CaseInsensitive(t *testing.T) {
+ allow := []string{"API.example.com"}
+ if !HostAllowed("https://api.EXAMPLE.com/", allow) {
+ t.Error("host comparison should be case-insensitive")
+ }
+}
+
+func TestExtractHost_BareHostname(t *testing.T) {
+ if got := ExtractHost("example.com/path"); got != "example.com" {
+ t.Errorf("ExtractHost('example.com/path') = %q, want 'example.com'", got)
+ }
+}
+
+func TestExtractHost_FullURL(t *testing.T) {
+ if got := ExtractHost("https://example.com:8080/path?q=1"); got != "example.com" {
+ t.Errorf("ExtractHost full URL = %q, want 'example.com'", got)
+ }
+}
+
+func TestExtractHost_NoHost(t *testing.T) {
+ if got := ExtractHost("about:blank"); got != "" {
+ t.Errorf("ExtractHost('about:blank') = %q, want ''", got)
+ }
+}
diff --git a/internal/strategy/routes.go b/internal/strategy/routes.go
index 8cf04763..abe2ed73 100644
--- a/internal/strategy/routes.go
+++ b/internal/strategy/routes.go
@@ -22,6 +22,8 @@ func capabilitySetting(cap routes.Capability) (feature, setting, code string) {
return "upload", "security.allowUpload", "upload_disabled"
case routes.CapStateExport:
return "stateExport", "security.allowStateExport", "state_export_disabled"
+ case routes.CapNetworkIntercept:
+ return "networkIntercept", "security.allowNetworkIntercept", "network_intercept_disabled"
default:
return string(cap), "security.allow" + string(cap), string(cap) + "_disabled"
}
diff --git a/plugin/policy.ts b/plugin/policy.ts
index fe14811d..4cf51558 100644
--- a/plugin/policy.ts
+++ b/plugin/policy.ts
@@ -48,6 +48,13 @@ export function checkUploadPolicy(cfg: PluginConfig): { allowed: boolean; error?
return { allowed: true };
}
+export function checkNetworkInterceptPolicy(cfg: PluginConfig): { allowed: boolean; error?: string } {
+ if (cfg.allowNetworkIntercept !== true) {
+ return { allowed: false, error: "network interception blocked by plugin policy (allowNetworkIntercept: false)" };
+ }
+ return { allowed: true };
+}
+
export function enforcePolicyOrReturn(check: { allowed: boolean; error?: string }): any | null {
if (!check.allowed) {
return textResult({ error: check.error });
diff --git a/plugin/tools/pinchtab.ts b/plugin/tools/pinchtab.ts
index 8a5637ef..11381fcd 100644
--- a/plugin/tools/pinchtab.ts
+++ b/plugin/tools/pinchtab.ts
@@ -1,6 +1,6 @@
import type { PluginConfig } from "../types.js";
import { pinchtabFetch, textResult, imageResult, resourceResult, normalizeActionParams, looksLikeStaleRef } from "../client.js";
-import { checkNavigationPolicy, checkEvaluatePolicy, checkDownloadPolicy, checkUploadPolicy, enforcePolicyOrReturn } from "../policy.js";
+import { checkNavigationPolicy, checkEvaluatePolicy, checkDownloadPolicy, checkUploadPolicy, checkNetworkInterceptPolicy, enforcePolicyOrReturn } from "../policy.js";
import { ensureServerRunning, getEnhancedHealth, getLastTabId, setLastTabId } from "../session.js";
export const pinchtabToolSchema = {
@@ -55,13 +55,18 @@ export const pinchtabToolSchema = {
savePath: { type: "string", description: "Path to save downloaded file" },
files: { type: "array", items: { type: "string" }, description: "Base64-encoded files for upload" },
paths: { type: "array", items: { type: "string" }, description: "File paths for upload" },
- networkAction: { type: "string", enum: ["list", "get", "export", "clear"], description: "Network sub-action" },
+ networkAction: { type: "string", enum: ["list", "get", "export", "clear", "route", "unroute"], description: "Network sub-action" },
requestId: { type: "string", description: "Network request ID for get action" },
- method: { type: "string", description: "Filter network by HTTP method" },
+ method: { type: "string", description: "Filter network by HTTP method (also: limits a route rule to one method; fulfill rules without method skip OPTIONS preflights to avoid breaking CORS)" },
status: { type: "string", description: "Filter network by status (e.g. 4xx, 5xx, 200)" },
- resourceType: { type: "string", description: "Filter network by resource type (xhr, fetch, document)" },
+ resourceType: { type: "string", description: "Filter network by resource type, or limit a route to one type (xhr, fetch, document, script, image, etc)" },
limit: { type: "number", description: "Limit network results" },
exportFormat: { type: "string", enum: ["har", "json"], description: "Network export format" },
+ pattern: { type: "string", description: "URL pattern for network route/unroute (substring or glob)" },
+ routeAction: { type: "string", enum: ["continue", "abort", "fulfill"], description: "Network route behavior. Default 'continue' (pass-through)." },
+ responseBody: { type: "string", description: "Response body for routeAction=fulfill (sent verbatim; not auto-encoded)" },
+ contentType: { type: "string", description: "Response Content-Type for fulfill (default application/json)" },
+ responseStatus: { type: "number", description: "Response status code for fulfill (default 200)" },
},
required: ["action"],
};
@@ -80,7 +85,7 @@ export const pinchtabToolDescription = `Browser control via Pinchtab. Actions:
- pdf: export page as PDF (landscape?, scale?, tabId?)
- download: download file from URL (downloadUrl, savePath?, tabId?)
- upload: upload files to file input (selector, files[]|paths[], tabId?)
-- network: capture/inspect network requests (networkAction: list|get|export|clear, requestId?, method?, status?, limit?)
+- network: capture/inspect/intercept network requests (networkAction: list|get|export|clear|route|unroute). For route: pattern, routeAction (continue|abort|fulfill), responseBody?, contentType?, responseStatus?, resourceType?. For unroute: pattern? (omit to clear all). Fulfill is BLOCKED on hosts in security.allowedDomains (sensitive surfaces) and allowed elsewhere; rules on allowlisted hosts fall through to real fetch.
- health: check connectivity
Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=interactive&format=compact for interactions (~3,600), diff=true on subsequent snapshots.`;
@@ -325,6 +330,37 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
return textResult(result);
}
+ if (networkAction === "route") {
+ const policyResult = enforcePolicyOrReturn(checkNetworkInterceptPolicy(cfg));
+ if (policyResult) return policyResult;
+ if (!normalized.tabId) return textResult({ error: "route requires tabId" });
+ if (!normalized.pattern) return textResult({ error: "route requires pattern" });
+ const payload: Record<string, any> = {
+ pattern: normalized.pattern,
+ action: normalized.routeAction || "continue",
+ };
+ if (normalized.responseBody !== undefined) payload.body = normalized.responseBody;
+ if (normalized.contentType) payload.contentType = normalized.contentType;
+ if (typeof normalized.responseStatus === "number") payload.status = normalized.responseStatus;
+ if (normalized.resourceType) payload.resourceType = normalized.resourceType;
+ if (normalized.method) payload.method = normalized.method;
+ return textResult(await pinchtabFetch(cfg, `/tabs/${encodeURIComponent(normalized.tabId)}/network/route`, {
+ method: "POST",
+ body: payload,
+ }));
+ }
+
+ if (networkAction === "unroute") {
+ const policyResult = enforcePolicyOrReturn(checkNetworkInterceptPolicy(cfg));
+ if (policyResult) return policyResult;
+ if (!normalized.tabId) return textResult({ error: "unroute requires tabId" });
+ const query = new URLSearchParams();
+ if (normalized.pattern) query.set("pattern", normalized.pattern);
+ const qs = query.toString();
+ const path = `/tabs/${encodeURIComponent(normalized.tabId)}/network/route${qs ? `?${qs}` : ""}`;
+ return textResult(await pinchtabFetch(cfg, path, { method: "DELETE" }));
+ }
+
// list
const query = new URLSearchParams();
if (normalized.tabId) query.set("tabId", normalized.tabId);
diff --git a/plugin/types.ts b/plugin/types.ts
index 23f8c51f..0f52703c 100644
--- a/plugin/types.ts
+++ b/plugin/types.ts
@@ -11,6 +11,7 @@ export interface PluginConfig {
allowedDomains?: string[];
allowDownloads?: boolean;
allowUploads?: boolean;
+ allowNetworkIntercept?: boolean;
defaultSnapshotFormat?: string;
defaultSnapshotFilter?: string;
screenshotFormat?: string;