Skip to content

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

feat: add console and errors tracking (#326)

pinchtabdevc41caafee8f6
diff --git a/TESTING.md b/TESTING.md
index 51a185e6..d5a8896a 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -14,9 +14,11 @@ The `dev` developer toolkit is the easiest way to run checks and tests:
./dev e2e cli-fast # CLI fast, single-instance
./dev e2e api-full # API full, multi-instance
./dev e2e cli-full # CLI full, single-instance
+./dev e2e full-api auth # Full API suite filtered to scenario filenames containing "auth"
/bin/bash tests/e2e/run.sh api
/bin/bash tests/e2e/run.sh api all=true
+/bin/bash tests/e2e/run.sh api all=true filter=auth
/bin/bash tests/e2e/run.sh cli
/bin/bash tests/e2e/run.sh cli all=true
./dev check # All checks (format, vet, build, lint)
@@ -26,6 +28,8 @@ The `dev` developer toolkit is the easiest way to run checks and tests:
./dev doctor # Setup dev environment
```
+E2E summaries and markdown reports prefix each test with its scenario filename, for example `[auth-full] auth: login sets session cookie`, so it is easy to see which filename filter to use.
+
## Unit Tests
```bash
diff --git a/cmd/pinchtab/cmd_cli_console.go b/cmd/pinchtab/cmd_cli_console.go
new file mode 100644
index 00000000..5786e8f7
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_console.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var consoleCmd = &cobra.Command{
+ Use: "console",
+ Short: "View browser console logs",
+ Long: "View browser console.log/warn/error/info messages from the current or specified tab.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Console(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var errorsCmd = &cobra.Command{
+ Use: "errors",
+ Short: "View browser uncaught errors",
+ Long: "View uncaught JavaScript exceptions from the current or specified tab.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Errors(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 27b2c387..462c5498 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -41,6 +41,8 @@ func registerBrowserCommands() {
keyupCmd,
scrollintoviewCmd,
dialogCmd,
+ consoleCmd,
+ errorsCmd,
)
tabsCmd.AddCommand(tabNewCmd, tabCloseCmd)
@@ -82,6 +84,8 @@ func registerBrowserCommands() {
keyupCmd,
scrollintoviewCmd,
dialogCmd,
+ consoleCmd,
+ errorsCmd,
)
}
@@ -203,6 +207,13 @@ func configureBrowserFlags() {
waitCmd.Flags().String("fn", "", "Wait for JS expression to be truthy")
waitCmd.Flags().String("state", "", "Element state: visible (default) or hidden")
waitCmd.Flags().Int("timeout", 0, "Timeout in milliseconds (default 10000, max 30000)")
+
+ consoleCmd.Flags().Bool("clear", false, "Clear console logs")
+ consoleCmd.Flags().String("limit", "", "Maximum entries to return")
+ errorsCmd.Flags().Bool("clear", false, "Clear error logs")
+ errorsCmd.Flags().String("limit", "", "Maximum entries to return")
+
+ addTabFlag(consoleCmd, errorsCmd)
}
func configureManagementFlags() {
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.go
index b11c8aba..8064b30f 100644
--- a/cmd/pinchtab/cmd_config.go
+++ b/cmd/pinchtab/cmd_config.go
@@ -230,8 +230,7 @@ func copyConfigToken(token string) error {
return nil
}
- fmt.Println(cli.StyleStdout(cli.WarningStyle, "Clipboard unavailable; copy the token manually:"))
- fmt.Println(cli.StyleStdout(cli.ValueStyle, token))
+ fmt.Println(cli.StyleStdout(cli.WarningStyle, "Clipboard unavailable; token not shown for safety."))
return nil
}
@@ -315,7 +314,7 @@ func handleConfigGet(path string) {
os.Exit(1)
}
- fmt.Println(value)
+ fmt.Println(displayConfigValue(path, value))
}
func handleConfigSet(path, value string) {
@@ -343,7 +342,14 @@ func handleConfigSet(path, value string) {
os.Exit(1)
}
- fmt.Printf("Set %s = %s\n", path, value)
+ fmt.Printf("Set %s = %s\n", path, displayConfigValue(path, value))
+}
+
+func displayConfigValue(path, value string) string {
+ if strings.EqualFold(strings.TrimSpace(path), "server.token") {
+ return config.MaskToken(value)
+ }
+ return value
}
func handleConfigPatch(jsonPatch string) {
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.go
index 7ceacbfe..45347373 100644
--- a/cmd/pinchtab/cmd_config_test.go
+++ b/cmd/pinchtab/cmd_config_test.go
@@ -51,6 +51,23 @@ func TestClipboardCommands(t *testing.T) {
}
}
+func TestCopyConfigTokenDoesNotPrintTokenWhenClipboardUnavailable(t *testing.T) {
+ t.Setenv("PATH", "")
+
+ output := captureStdout(t, func() {
+ if err := copyConfigToken("very-secret-token-value"); err != nil {
+ t.Fatalf("copyConfigToken() error = %v", err)
+ }
+ })
+
+ if strings.Contains(output, "very-secret-token-value") {
+ t.Fatalf("expected token to stay hidden, got %q", output)
+ }
+ if !strings.Contains(output, "token not shown for safety") {
+ t.Fatalf("expected safe fallback message, got %q", output)
+ }
+}
+
func TestConfigSetAllowsDashPrefixedValue(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
t.Setenv("PINCHTAB_CONFIG", configPath)
@@ -115,3 +132,61 @@ func TestConfigShowLoadsLegacyFlatConfigWithoutToken(t *testing.T) {
t.Fatalf("expected config show header, got %q", output)
}
}
+
+func TestConfigGetMasksServerToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ t.Setenv("PINCHTAB_TOKEN", "")
+
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "very-secret-token-value"
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ t.Cleanup(func() {
+ rootCmd.SetArgs(nil)
+ })
+
+ output := captureStdout(t, func() {
+ rootCmd.SetArgs([]string{"config", "get", "server.token"})
+ if err := rootCmd.Execute(); err != nil {
+ t.Fatalf("Execute() error = %v", err)
+ }
+ })
+
+ if strings.Contains(output, "very-secret-token-value") {
+ t.Fatalf("expected token to stay masked, got %q", output)
+ }
+ if !strings.Contains(output, "very...alue") {
+ t.Fatalf("expected masked token, got %q", output)
+ }
+}
+
+func TestConfigSetMasksServerTokenInOutput(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ t.Cleanup(func() {
+ rootCmd.SetArgs(nil)
+ })
+
+ output := captureStdout(t, func() {
+ rootCmd.SetArgs([]string{"config", "set", "server.token", "very-secret-token-value"})
+ if err := rootCmd.Execute(); err != nil {
+ t.Fatalf("Execute() error = %v", err)
+ }
+ })
+
+ if strings.Contains(output, "very-secret-token-value") {
+ t.Fatalf("expected token to stay masked, got %q", output)
+ }
+ if !strings.Contains(output, "very...alue") {
+ t.Fatalf("expected masked token in success output, got %q", output)
+ }
+}
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index 8e6b67ed..9bae7483 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -204,7 +204,7 @@ func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck
}
return workflow.UpdateValue("server.token", token)
case "custom":
- token, err := promptInput("Set server.token:", cfg.Token)
+ token, err := promptInputHiddenDefault("Set server.token:", cfg.Token)
if err != nil {
return nil, false, err
}
diff --git a/cmd/pinchtab/cmd_wizard.go b/cmd/pinchtab/cmd_wizard.go
index 32ad90e7..95cb70db 100644
--- a/cmd/pinchtab/cmd_wizard.go
+++ b/cmd/pinchtab/cmd_wizard.go
@@ -37,9 +37,6 @@ func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew boo
fmt.Println()
fmt.Println(" Guard: UP (maximum security)")
fmt.Printf(" Allowed domains: %s\n", strings.Join(getAllowedDomains(cfg), ", "))
- if cfg.Server.Token != "" {
- fmt.Printf(" Token: %s\n", cfg.Server.Token[:min(12, len(cfg.Server.Token))]+"...")
- }
fmt.Println()
fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review all settings.")
fmt.Println()
@@ -146,10 +143,6 @@ func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {
}
fmt.Printf(" Upgraded: %s → %s\n", oldVersion, config.CurrentConfigVersion)
- if cfg.Server.Token != "" {
- fmt.Printf(" Token: %s\n", cli.StyleStdout(cli.ValueStyle, cfg.Server.Token[:min(12, len(cfg.Server.Token))]+"..."))
- }
-
fmt.Println()
fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review all settings.")
fmt.Println()
diff --git a/cmd/pinchtab/cmd_wizard_test.go b/cmd/pinchtab/cmd_wizard_test.go
new file mode 100644
index 00000000..e7fdb187
--- /dev/null
+++ b/cmd/pinchtab/cmd_wizard_test.go
@@ -0,0 +1,49 @@
+package main
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestRunNonInteractiveSetupDoesNotPrintToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ cfg := config.DefaultFileConfig()
+ cfg.Server.Token = "very-secret-token-value"
+ cfg.Security.IDPI.AllowedDomains = []string{"localhost"}
+
+ output := captureStdout(t, func() {
+ if !runNonInteractiveSetup(&cfg, configPath, true) {
+ t.Fatal("runNonInteractiveSetup() = false")
+ }
+ })
+
+ if strings.Contains(output, "very-secret-token-value") {
+ t.Fatalf("expected token to stay hidden, got %q", output)
+ }
+ if strings.Contains(output, "Token:") {
+ t.Fatalf("expected setup output to omit token preview, got %q", output)
+ }
+}
+
+func TestRunUpgradeNoticeDoesNotPrintToken(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ cfg := config.DefaultFileConfig()
+ cfg.ConfigVersion = "0.9.0"
+ cfg.Server.Token = "very-secret-token-value"
+
+ output := captureStdout(t, func() {
+ if !runUpgradeNotice(&cfg, configPath) {
+ t.Fatal("runUpgradeNotice() = false")
+ }
+ })
+
+ if strings.Contains(output, "very-secret-token-value") {
+ t.Fatalf("expected token to stay hidden, got %q", output)
+ }
+ if strings.Contains(output, "Token:") {
+ t.Fatalf("expected upgrade output to omit token preview, got %q", output)
+ }
+}
diff --git a/cmd/pinchtab/prompt.go b/cmd/pinchtab/prompt.go
index 4f07d869..f65af4ae 100644
--- a/cmd/pinchtab/prompt.go
+++ b/cmd/pinchtab/prompt.go
@@ -74,3 +74,21 @@ func promptInput(prompt, defaultValue string) (string, error) {
}
return value, nil
}
+
+func promptInputHiddenDefault(prompt, defaultValue string) (string, error) {
+ if prompt != "" {
+ fmt.Print(prompt + " ")
+ }
+
+ reader := bufio.NewReader(os.Stdin)
+ input, err := reader.ReadString('\n')
+ if err != nil && strings.TrimSpace(input) == "" {
+ return "", err
+ }
+
+ value := strings.TrimSpace(input)
+ if value == "" {
+ return defaultValue, nil
+ }
+ return value, nil
+}
diff --git a/cmd/pinchtab/prompt_test.go b/cmd/pinchtab/prompt_test.go
new file mode 100644
index 00000000..daf24666
--- /dev/null
+++ b/cmd/pinchtab/prompt_test.go
@@ -0,0 +1,56 @@
+package main
+
+import (
+ "io"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestPromptInputHiddenDefaultKeepsDefaultWithoutPrintingIt(t *testing.T) {
+ origStdin := os.Stdin
+ origStdout := os.Stdout
+ stdinR, stdinW, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("os.Pipe(stdin) error = %v", err)
+ }
+ stdoutR, stdoutW, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("os.Pipe(stdout) error = %v", err)
+ }
+
+ os.Stdin = stdinR
+ os.Stdout = stdoutW
+ t.Cleanup(func() {
+ os.Stdin = origStdin
+ os.Stdout = origStdout
+ _ = stdinR.Close()
+ _ = stdinW.Close()
+ _ = stdoutR.Close()
+ _ = stdoutW.Close()
+ })
+
+ go func() {
+ _, _ = stdinW.WriteString("\n")
+ _ = stdinW.Close()
+ }()
+
+ value, err := promptInputHiddenDefault("Set server.token:", "very-secret-token-value")
+ if err != nil {
+ t.Fatalf("promptInputHiddenDefault() error = %v", err)
+ }
+ if err := stdoutW.Close(); err != nil {
+ t.Fatalf("close stdout writer error = %v", err)
+ }
+ output, err := io.ReadAll(stdoutR)
+ if err != nil {
+ t.Fatalf("ReadAll() error = %v", err)
+ }
+
+ if value != "very-secret-token-value" {
+ t.Fatalf("value = %q, want default", value)
+ }
+ if strings.Contains(string(output), "very-secret-token-value") {
+ t.Fatalf("expected hidden default to stay out of prompt, got %q", string(output))
+ }
+}
diff --git a/dev b/dev
index 2b7ec57a..baf39660 100755
--- a/dev
+++ b/dev
@@ -153,8 +153,16 @@ run_command() {
;;
"e2e"*)
local suite="release"
+ local filter=""
if [ "$target" != "e2e" ]; then
- suite="${target#e2e }"
+ local e2e_args="${target#e2e }"
+ suite="${e2e_args%% *}"
+ if [ "$suite" != "$e2e_args" ]; then
+ filter="${e2e_args#"$suite "}"
+ fi
+ fi
+ if [ -n "$filter" ]; then
+ exec bash scripts/e2e.sh "$suite" "$filter"
fi
exec bash scripts/e2e.sh "$suite"
;;
diff --git a/docs/guides/contributing.md b/docs/guides/contributing.md
index 58d7d794..96c26a9e 100644
--- a/docs/guides/contributing.md
+++ b/docs/guides/contributing.md
@@ -116,6 +116,14 @@ Verify:
golangci-lint --version
```
+### Install gotestsum (Recommended)
+
+Recommended for the cleaner local unit test output used by `./dev test unit`:
+
+```bash
+go install gotest.tools/gotestsum@latest
+```
+
### Install Chrome/Chromium
**macOS (Homebrew):**
diff --git a/internal/activity/activity.go b/internal/activity/activity.go
index 11eb085a..6dbe68a8 100644
--- a/internal/activity/activity.go
+++ b/internal/activity/activity.go
@@ -19,7 +19,7 @@ const (
defaultSessionIdleTimeout = 30 * time.Minute
defaultQueryLimit = 200
maxQueryLimit = 1000
- defaultRetentionDays = 1
+ defaultRetentionDays = 30
)
type Config struct {
@@ -108,19 +108,20 @@ func NewStore(stateDir string, sessionIdle time.Duration, retentionDays int) (*S
if sessionIdle <= 0 {
sessionIdle = defaultSessionIdleTimeout
}
- if retentionDays < 0 {
- retentionDays = 0
- }
- if retentionDays == 0 {
- retentionDays = defaultRetentionDays
+ if retentionDays <= 0 {
+ return nil, fmt.Errorf("activity retentionDays must be > 0 (got %d)", retentionDays)
}
- return &Store{
+ store := &Store{
dir: activityDir,
sessionIdleLimit: sessionIdle,
retentionDays: retentionDays,
sessions: make(map[string]sessionState),
- }, nil
+ }
+ if err := store.pruneExpiredFiles(time.Now().UTC()); err != nil {
+ return nil, err
+ }
+ return store, nil
}
func (s *Store) Enabled() bool {
@@ -140,6 +141,7 @@ func (s *Store) Record(evt Event) error {
} else {
evt.Timestamp = evt.Timestamp.UTC()
}
+ evt.URL = sanitizeActivityURL(evt.URL)
if evt.SessionID == "" {
evt.SessionID = s.sessionIDLocked(evt)
}
@@ -316,11 +318,7 @@ func (s *Store) filePathFor(ts time.Time) string {
}
func (s *Store) queryFiles() []string {
- s.mu.Lock()
- defer s.mu.Unlock()
-
- now := time.Now().UTC()
- _ = s.pruneExpiredFilesLocked(now)
+ _ = s.pruneExpiredFiles(time.Now().UTC())
entries, err := os.ReadDir(s.dir)
if err != nil {
@@ -348,6 +346,12 @@ func (s *Store) queryFiles() []string {
return files
}
+func (s *Store) pruneExpiredFiles(now time.Time) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.pruneExpiredFilesLocked(now)
+}
+
func (s *Store) pruneExpiredFilesLocked(now time.Time) error {
if s.retentionDays <= 0 {
return nil
diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.go
index 72d2456e..a5a374cc 100644
--- a/internal/activity/activity_test.go
+++ b/internal/activity/activity_test.go
@@ -1,6 +1,7 @@
package activity
import (
+ "encoding/json"
"os"
"path/filepath"
"testing"
@@ -92,6 +93,37 @@ func TestStorePrunesExpiredDailyFiles(t *testing.T) {
}
}
+func TestNewStorePrunesExpiredDailyFilesOnStartup(t *testing.T) {
+ root := t.TempDir()
+ activityDir := filepath.Join(root, "activity")
+ if err := os.MkdirAll(activityDir, 0750); err != nil {
+ t.Fatalf("MkdirAll: %v", err)
+ }
+
+ oldDay := time.Now().UTC().AddDate(0, 0, -31)
+ oldPath := filepath.Join(activityDir, "events-"+oldDay.Format(time.DateOnly)+".jsonl")
+ if err := os.WriteFile(oldPath, []byte("{\"path\":\"/old\"}\n"), 0600); err != nil {
+ t.Fatalf("WriteFile old: %v", err)
+ }
+
+ keepDay := time.Now().UTC()
+ keepPath := filepath.Join(activityDir, "events-"+keepDay.Format(time.DateOnly)+".jsonl")
+ if err := os.WriteFile(keepPath, []byte("{\"path\":\"/new\"}\n"), 0600); err != nil {
+ t.Fatalf("WriteFile keep: %v", err)
+ }
+
+ if _, err := NewStore(root, 30*time.Minute, 30); err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+
+ if _, err := os.Stat(oldPath); !os.IsNotExist(err) {
+ t.Fatalf("expected expired activity file to be pruned on startup, stat err = %v", err)
+ }
+ if _, err := os.Stat(keepPath); err != nil {
+ t.Fatalf("expected current activity file to remain, stat err = %v", err)
+ }
+}
+
func TestNewRecorderDisabledReturnsNoop(t *testing.T) {
rec, err := NewRecorder(Config{}, t.TempDir())
if err != nil {
@@ -102,6 +134,12 @@ func TestNewRecorderDisabledReturnsNoop(t *testing.T) {
}
}
+func TestNewStoreRejectsZeroRetentionDays(t *testing.T) {
+ if _, err := NewStore(t.TempDir(), 30*time.Minute, 0); err == nil {
+ t.Fatal("expected NewStore to reject zero retentionDays")
+ }
+}
+
func TestClampQueryLimit(t *testing.T) {
if got := clampQueryLimit(0); got != defaultQueryLimit {
t.Fatalf("clampQueryLimit(0) = %d, want %d", got, defaultQueryLimit)
@@ -113,3 +151,37 @@ func TestClampQueryLimit(t *testing.T) {
t.Fatalf("clampQueryLimit(25) = %d, want 25", got)
}
}
+
+func TestStoreRecord_SanitizesURLBeforePersisting(t *testing.T) {
+ root := t.TempDir()
+ store, err := NewStore(root, 30*time.Minute, 1)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+
+ now := time.Now().UTC()
+ if err := store.Record(Event{
+ Timestamp: now,
+ Source: "server",
+ Method: "GET",
+ Path: "/navigate",
+ Status: 200,
+ URL: "https://user:[email protected]/callback?code=secret#done",
+ }); err != nil {
+ t.Fatalf("Record: %v", err)
+ }
+
+ path := filepath.Join(root, "activity", "events-"+now.Format(time.DateOnly)+".jsonl")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("ReadFile: %v", err)
+ }
+
+ var evt Event
+ if err := json.Unmarshal(data[:len(data)-1], &evt); err != nil {
+ t.Fatalf("Unmarshal: %v", err)
+ }
+ if evt.URL != "https://example.com/callback" {
+ t.Fatalf("evt.URL = %q, want sanitized URL", evt.URL)
+ }
+}
diff --git a/internal/activity/context.go b/internal/activity/context.go
index be030b28..ad03c0f2 100644
--- a/internal/activity/context.go
+++ b/internal/activity/context.go
@@ -136,7 +136,7 @@ func EnrichRequest(r *http.Request, update Update) {
state.event.TabID = update.TabID
}
if update.URL != "" {
- state.event.URL = update.URL
+ state.event.URL = sanitizeActivityURL(update.URL)
}
if update.Action != "" {
state.event.Action = update.Action
@@ -257,7 +257,7 @@ func initialAction(r *http.Request) string {
func initialURL(r *http.Request) string {
if u := strings.TrimSpace(r.URL.Query().Get("url")); u != "" {
- return u
+ return sanitizeActivityURL(u)
}
return ""
}
diff --git a/internal/activity/context_test.go b/internal/activity/context_test.go
new file mode 100644
index 00000000..8b37496b
--- /dev/null
+++ b/internal/activity/context_test.go
@@ -0,0 +1,97 @@
+package activity
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+)
+
+type captureRecorder struct {
+ events []Event
+}
+
+func (c *captureRecorder) Enabled() bool { return true }
+
+func (c *captureRecorder) Record(evt Event) error {
+ c.events = append(c.events, evt)
+ return nil
+}
+
+func (c *captureRecorder) Query(Filter) ([]Event, error) {
+ return append([]Event(nil), c.events...), nil
+}
+
+func TestSanitizeActivityURL(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want string
+ }{
+ {
+ name: "drops query fragment and credentials",
+ raw: "https://user:[email protected]:8443/callback?code=secret#done",
+ want: "https://app.example.com:8443/callback",
+ },
+ {
+ name: "normalizes bare hostname",
+ raw: "pinchtab.com/reset?token=secret",
+ want: "https://pinchtab.com/reset",
+ },
+ {
+ name: "keeps non-network scheme without fragment",
+ raw: "about:blank#frag",
+ want: "about:blank",
+ },
+ {
+ name: "rejects malformed",
+ raw: "://bad-url",
+ want: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := sanitizeActivityURL(tt.raw); got != tt.want {
+ t.Fatalf("sanitizeActivityURL(%q) = %q, want %q", tt.raw, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestMiddlewareSanitizesInitialURL(t *testing.T) {
+ rec := &captureRecorder{}
+ handler := Middleware(rec, "server", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/navigate?url="+url.QueryEscape("pinchtab.com/reset?token=secret#done"), nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if len(rec.events) != 1 {
+ t.Fatalf("len(events) = %d, want 1", len(rec.events))
+ }
+ if got := rec.events[0].URL; got != "https://pinchtab.com/reset" {
+ t.Fatalf("event.URL = %q, want sanitized URL", got)
+ }
+}
+
+func TestEnrichRequestSanitizesURL(t *testing.T) {
+ rec := &captureRecorder{}
+ handler := Middleware(rec, "server", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ EnrichRequest(r, Update{URL: "https://user:[email protected]/callback?code=secret#frag"})
+ w.WriteHeader(http.StatusAccepted)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab-1/text", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if len(rec.events) != 1 {
+ t.Fatalf("len(events) = %d, want 1", len(rec.events))
+ }
+ if got := rec.events[0].URL; got != "https://example.com/callback" {
+ t.Fatalf("event.URL = %q, want sanitized URL", got)
+ }
+}
diff --git a/internal/activity/url_sanitize.go b/internal/activity/url_sanitize.go
new file mode 100644
index 00000000..744599cd
--- /dev/null
+++ b/internal/activity/url_sanitize.go
@@ -0,0 +1,76 @@
+package activity
+
+import (
+ "net"
+ "net/url"
+ "strings"
+
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
+)
+
+const (
+ maxActivityURLBytes = 2048
+ activityTruncateSuffix = "..."
+)
+
+func sanitizeActivityURL(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+
+ normalized, err := internalurls.Sanitize(raw)
+ if err != nil {
+ parsed, parseErr := url.Parse(raw)
+ if parseErr != nil || (parsed.Scheme == "" && parsed.Host == "" && parsed.Opaque == "") {
+ return ""
+ }
+ normalized = raw
+ }
+
+ parsed, err := url.Parse(normalized)
+ if err != nil {
+ return ""
+ }
+
+ parsed.User = nil
+ parsed.RawQuery = ""
+ parsed.Fragment = ""
+ parsed.ForceQuery = false
+
+ if parsed.Host != "" {
+ host := strings.ToLower(parsed.Hostname())
+ if port := parsed.Port(); port != "" {
+ parsed.Host = net.JoinHostPort(host, port)
+ } else {
+ parsed.Host = host
+ }
+ }
+
+ return truncateActivityValue(parsed.String(), maxActivityURLBytes)
+}
+
+func truncateActivityValue(s string, maxBytes int) string {
+ if maxBytes <= 0 {
+ return ""
+ }
+ if len(s) <= maxBytes {
+ return s
+ }
+ if maxBytes <= len(activityTruncateSuffix) {
+ return activityTruncateSuffix[:maxBytes]
+ }
+
+ limit := maxBytes - len(activityTruncateSuffix)
+ cut := 0
+ for i := range s {
+ if i > limit {
+ break
+ }
+ cut = i
+ }
+ if cut == 0 && limit > 0 {
+ return activityTruncateSuffix
+ }
+ return s[:cut] + activityTruncateSuffix
+}
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index b3b7fb04..9419da89 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -15,9 +15,7 @@ type BridgeAPI interface {
BrowserContext() context.Context
TabContext(tabID string) (ctx context.Context, resolvedID string, err error)
ListTargets() ([]*target.Info, error)
- // CreateTab creates a new browser tab and returns a hash-based tab ID (e.g., "tab_XXXXXXXX").
- // The raw CDP target ID is stored internally and used for CDP operations.
- CreateTab(url string) (hashTabID string, ctx context.Context, cancel context.CancelFunc, err error)
+ CreateTab(url string) (tabID string, ctx context.Context, cancel context.CancelFunc, err error)
CloseTab(tabID string) error
FocusTab(tabID string) error
@@ -51,6 +49,12 @@ type BridgeAPI interface {
// Dialog management
GetDialogManager() *DialogManager
+
+ // Console and error logs
+ GetConsoleLogs(tabID string, limit int) []LogEntry
+ ClearConsoleLogs(tabID string)
+ GetErrorLogs(tabID string, limit int) []ErrorEntry
+ ClearErrorLogs(tabID string)
}
type LockInfo = bridgetabs.LockInfo
@@ -139,7 +143,7 @@ type Instance struct {
}
type InstanceTab struct {
- ID string `json:"id"` // Hash-based tab ID: tab_XXXXXXXX
+ ID string `json:"id"` // Runtime tab ID (raw CDP target ID on this branch)
InstanceID string `json:"instanceId"` // Hash-based instance ID: inst_XXXXXXXX
URL string `json:"url"`
Title string `json:"title"`
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index d80a7a0c..418833ba 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -42,6 +42,7 @@ type Bridge struct {
Actions map[string]ActionFunc
Locks *LockManager
Dialogs *DialogManager
+ LogStore *ConsoleLogStore
// Network monitoring
netMonitor *NetworkMonitor
@@ -61,16 +62,18 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
if cfg != nil && cfg.NetworkBufferSize > 0 {
netBufSize = cfg.NetworkBufferSize
}
+ logStore := NewConsoleLogStore(1000)
b := &Bridge{
AllocCtx: allocCtx,
BrowserCtx: browserCtx,
Config: cfg,
IdMgr: idMgr,
netMonitor: NewNetworkMonitor(netBufSize),
+ LogStore: logStore,
}
// Only initialize TabManager if browserCtx is provided (not lazy-init case)
if cfg != nil && browserCtx != nil {
- b.TabManager = NewTabManager(browserCtx, cfg, idMgr, b.tabSetup)
+ b.TabManager = NewTabManager(browserCtx, cfg, idMgr, logStore, b.tabSetup)
b.SetDialogManager(b.Dialogs)
b.StartBrowserGuards()
}
@@ -143,6 +146,36 @@ func (b *Bridge) TabLockInfo(tabID string) *LockInfo {
return b.Locks.Get(tabID)
}
+// GetConsoleLogs returns console logs for a tab.
+func (b *Bridge) GetConsoleLogs(tabID string, limit int) []LogEntry {
+ if b.LogStore == nil {
+ return nil
+ }
+ return b.LogStore.GetConsoleLogs(tabID, limit)
+}
+
+// ClearConsoleLogs clears console logs for a tab.
+func (b *Bridge) ClearConsoleLogs(tabID string) {
+ if b.LogStore != nil {
+ b.LogStore.ClearConsoleLogs(tabID)
+ }
+}
+
+// GetErrorLogs returns error logs for a tab.
+func (b *Bridge) GetErrorLogs(tabID string, limit int) []ErrorEntry {
+ if b.LogStore == nil {
+ return nil
+ }
+ return b.LogStore.GetErrorLogs(tabID, limit)
+}
+
+// ClearErrorLogs clears error logs for a tab.
+func (b *Bridge) ClearErrorLogs(tabID string) {
+ if b.LogStore != nil {
+ b.LogStore.ClearErrorLogs(tabID)
+ }
+}
+
func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
b.initMu.Lock()
defer b.initMu.Unlock()
@@ -197,7 +230,10 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
if b.IdMgr == nil {
b.IdMgr = ids.NewManager()
}
- b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)
+ if b.LogStore == nil {
+ b.LogStore = NewConsoleLogStore(1000)
+ }
+ b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.LogStore, b.tabSetup)
b.SetDialogManager(b.Dialogs)
b.StartBrowserGuards()
}
@@ -269,7 +305,10 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contex
if b.IdMgr == nil {
b.IdMgr = ids.NewManager()
}
- b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)
+ if b.LogStore == nil {
+ b.LogStore = NewConsoleLogStore(1000)
+ }
+ b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.LogStore, b.tabSetup)
b.SetDialogManager(b.Dialogs)
}
}
diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.go
index 9869ab8b..e5fe7a89 100644
--- a/internal/bridge/bridge_test.go
+++ b/internal/bridge/bridge_test.go
@@ -79,7 +79,7 @@ func TestTabManagerRemoteAllocatorInitialization(t *testing.T) {
// Use context.TODO() instead of nil to avoid lint warnings
ctx := context.TODO()
- tm := NewTabManager(ctx, cfg, nil, nil)
+ tm := NewTabManager(ctx, cfg, nil, nil, nil)
if tm == nil {
t.Error("TabManager should be created")
}
@@ -93,7 +93,7 @@ func TestTabManagerRemoteAllocatorInitialization(t *testing.T) {
func TestTabContext_RejectsUnknownTabID(t *testing.T) {
// TabContext should reject tab IDs that aren't tracked
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
// Try to get context for a non-existent tab
_, _, err := tm.TabContext("tab_nonexistent")
@@ -105,23 +105,20 @@ func TestTabContext_RejectsUnknownTabID(t *testing.T) {
}
}
-func TestTabContext_RejectsRawCDPID(t *testing.T) {
- // TabContext should reject raw CDP target IDs (32-char hex)
- // These should never be accepted - only hash-format IDs work
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+func TestTabContext_RejectsUnknownRawCDPID(t *testing.T) {
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
- // Simulate a raw CDP target ID format
rawCDPID := "A25658CE1BA82659EBE9C93C46CEE63A"
_, _, err := tm.TabContext(rawCDPID)
if err == nil {
- t.Error("TabContext should reject raw CDP target IDs")
+ t.Error("TabContext should reject unknown raw CDP target IDs")
}
}
func TestCreateTab_ReturnsRawCDPID(t *testing.T) {
// Verify TabIDFromCDPTarget returns raw CDP ID (no prefix)
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
if tm.idMgr == nil {
t.Error("TabManager should have idMgr initialized")
@@ -136,7 +133,7 @@ func TestCreateTab_ReturnsRawCDPID(t *testing.T) {
}
func TestTabContext_AcceptsRegisteredID(t *testing.T) {
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
rawCDPID := "RAWCDPID123456789012345678901234"
ctx := context.Background()
@@ -159,7 +156,7 @@ func TestTabContext_AcceptsRegisteredID(t *testing.T) {
}
func TestTabContext_EmptyID_UsesCurrentTrackedTab(t *testing.T) {
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
ctx := context.Background()
tabID := "SOMECDPID"
@@ -184,7 +181,7 @@ func TestTabContext_EmptyID_UsesCurrentTrackedTab(t *testing.T) {
func TestCloseTab_PreventsLastTabClose(t *testing.T) {
// CloseTab should fail when attempting to close the last remaining tab
// This prevents Chrome from exiting and crashing the server
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
// Without a valid browser context, ListTargets will fail
// which triggers the guard at the start of CloseTab
@@ -242,7 +239,7 @@ func TestEvaluateTabPolicy(t *testing.T) {
}
func TestTabManagerStoresTabPolicyState(t *testing.T) {
- tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
tm.tabs["tab1"] = &TabEntry{Ctx: context.Background()}
state := TabPolicyState{
@@ -262,3 +259,45 @@ func TestTabManagerStoresTabPolicyState(t *testing.T) {
t.Fatalf("stored policy state mismatch: got %+v want %+v", got, state)
}
}
+
+func TestPurgeTrackedTabStateByTargetID(t *testing.T) {
+ logStore := NewConsoleLogStore(10)
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, logStore, nil)
+ dm := NewDialogManager()
+ tm.SetDialogManager(dm)
+
+ tabID := "public-tab-id"
+ cdpID := "RAWCDPID123"
+ tm.tabs[tabID] = &TabEntry{Ctx: context.Background(), CDPID: cdpID}
+ tm.snapshots[tabID] = &RefCache{Refs: map[string]int64{"e0": 1}}
+ tm.accessed[tabID] = true
+ tm.currentTab = tabID
+ dm.SetPending(tabID, &DialogState{Type: "alert", Message: "secret"})
+ logStore.AddConsoleLog(cdpID, LogEntry{Level: "log", Message: "secret"})
+ logStore.AddErrorLog(cdpID, ErrorEntry{Message: "secret"})
+
+ if ok := tm.purgeTrackedTabStateByTargetID(cdpID); !ok {
+ t.Fatal("expected tab cleanup to succeed")
+ }
+ if _, ok := tm.tabs[tabID]; ok {
+ t.Fatal("expected tracked tab to be removed")
+ }
+ if _, ok := tm.snapshots[tabID]; ok {
+ t.Fatal("expected snapshot cache to be removed")
+ }
+ if tm.accessed[tabID] {
+ t.Fatal("expected accessed entry to be removed")
+ }
+ if tm.currentTab != "" {
+ t.Fatalf("expected current tab to be cleared, got %q", tm.currentTab)
+ }
+ if dm.GetPending(tabID) != nil {
+ t.Fatal("expected pending dialog to be cleared")
+ }
+ if logs := logStore.GetConsoleLogs(cdpID, 0); logs != nil {
+ t.Fatalf("expected console logs to be removed, got %v", logs)
+ }
+ if errs := logStore.GetErrorLogs(cdpID, 0); errs != nil {
+ t.Fatalf("expected error logs to be removed, got %v", errs)
+ }
+}
diff --git a/internal/bridge/console_logs.go b/internal/bridge/console_logs.go
new file mode 100644
index 00000000..169d9bcf
--- /dev/null
+++ b/internal/bridge/console_logs.go
@@ -0,0 +1,223 @@
+package bridge
+
+import (
+ "sync"
+ "time"
+)
+
+const (
+ defaultConsoleLogMaxLines = 1000
+ maxConsoleLogStoreLines = 1000
+ maxConsoleLevelBytes = 32
+ maxConsoleMessageBytes = 4 * 1024
+ maxConsoleSourceBytes = 512
+ maxErrorMessageBytes = 4 * 1024
+ maxErrorTypeBytes = 128
+ maxErrorURLBytes = 2 * 1024
+ maxErrorStackBytes = 8 * 1024
+ truncationSuffix = "..."
+)
+
+// LogEntry represents a single console log entry.
+type LogEntry struct {
+ Timestamp time.Time `json:"timestamp"`
+ Level string `json:"level"`
+ Message string `json:"message"`
+ Source string `json:"source,omitempty"`
+}
+
+// ErrorEntry represents an uncaught error/exception.
+type ErrorEntry struct {
+ Timestamp time.Time `json:"timestamp"`
+ Message string `json:"message"`
+ Type string `json:"type,omitempty"`
+ URL string `json:"url,omitempty"`
+ Line int64 `json:"line,omitempty"`
+ Column int64 `json:"column,omitempty"`
+ Stack string `json:"stack,omitempty"`
+}
+
+// TabLogs holds console and error logs for a single tab.
+type TabLogs struct {
+ Console []LogEntry
+ Errors []ErrorEntry
+ mu sync.RWMutex
+}
+
+// ConsoleLogStore manages console/error logs across all tabs.
+type ConsoleLogStore struct {
+ tabs map[string]*TabLogs
+ maxLines int
+ mu sync.RWMutex
+}
+
+// NewConsoleLogStore creates a new log store with the given max lines per tab.
+func NewConsoleLogStore(maxLines int) *ConsoleLogStore {
+ if maxLines <= 0 {
+ maxLines = defaultConsoleLogMaxLines
+ } else if maxLines > maxConsoleLogStoreLines {
+ maxLines = maxConsoleLogStoreLines
+ }
+ return &ConsoleLogStore{
+ tabs: make(map[string]*TabLogs),
+ maxLines: maxLines,
+ }
+}
+
+func (s *ConsoleLogStore) getOrCreateTab(tabID string) *TabLogs {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if t, ok := s.tabs[tabID]; ok {
+ return t
+ }
+ t := &TabLogs{
+ Console: make([]LogEntry, 0),
+ Errors: make([]ErrorEntry, 0),
+ }
+ s.tabs[tabID] = t
+ return t
+}
+
+// AddConsoleLog adds a console log entry for a tab.
+func (s *ConsoleLogStore) AddConsoleLog(tabID string, entry LogEntry) {
+ t := s.getOrCreateTab(tabID)
+ entry = normalizeConsoleLogEntry(entry)
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.Console = append(t.Console, entry)
+ if len(t.Console) > s.maxLines {
+ t.Console = t.Console[len(t.Console)-s.maxLines:]
+ }
+}
+
+// AddErrorLog adds an error log entry for a tab.
+func (s *ConsoleLogStore) AddErrorLog(tabID string, entry ErrorEntry) {
+ t := s.getOrCreateTab(tabID)
+ entry = normalizeErrorLogEntry(entry)
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.Errors = append(t.Errors, entry)
+ if len(t.Errors) > s.maxLines {
+ t.Errors = t.Errors[len(t.Errors)-s.maxLines:]
+ }
+}
+
+// GetConsoleLogs returns console logs for a tab. If limit > 0, returns at most limit entries.
+func (s *ConsoleLogStore) GetConsoleLogs(tabID string, limit int) []LogEntry {
+ s.mu.RLock()
+ t, ok := s.tabs[tabID]
+ s.mu.RUnlock()
+ if !ok {
+ return nil
+ }
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+ count := len(t.Console)
+ if limit <= 0 || limit > count {
+ limit = count
+ }
+ if limit > s.maxLines {
+ limit = s.maxLines
+ }
+ // Return most recent entries
+ start := count - limit
+ result := make([]LogEntry, limit)
+ copy(result, t.Console[start:])
+ return result
+}
+
+// GetErrorLogs returns error logs for a tab. If limit > 0, returns at most limit entries.
+func (s *ConsoleLogStore) GetErrorLogs(tabID string, limit int) []ErrorEntry {
+ s.mu.RLock()
+ t, ok := s.tabs[tabID]
+ s.mu.RUnlock()
+ if !ok {
+ return nil
+ }
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+ count := len(t.Errors)
+ if limit <= 0 || limit > count {
+ limit = count
+ }
+ if limit > s.maxLines {
+ limit = s.maxLines
+ }
+ start := count - limit
+ result := make([]ErrorEntry, limit)
+ copy(result, t.Errors[start:])
+ return result
+}
+
+// ClearConsoleLogs clears console logs for a tab.
+func (s *ConsoleLogStore) ClearConsoleLogs(tabID string) {
+ s.mu.RLock()
+ t, ok := s.tabs[tabID]
+ s.mu.RUnlock()
+ if !ok {
+ return
+ }
+ t.mu.Lock()
+ t.Console = t.Console[:0]
+ t.mu.Unlock()
+}
+
+// ClearErrorLogs clears error logs for a tab.
+func (s *ConsoleLogStore) ClearErrorLogs(tabID string) {
+ s.mu.RLock()
+ t, ok := s.tabs[tabID]
+ s.mu.RUnlock()
+ if !ok {
+ return
+ }
+ t.mu.Lock()
+ t.Errors = t.Errors[:0]
+ t.mu.Unlock()
+}
+
+// RemoveTab removes all logs for a tab (call on tab close).
+func (s *ConsoleLogStore) RemoveTab(tabID string) {
+ s.mu.Lock()
+ delete(s.tabs, tabID)
+ s.mu.Unlock()
+}
+
+func normalizeConsoleLogEntry(entry LogEntry) LogEntry {
+ entry.Level = truncateUTF8Bytes(entry.Level, maxConsoleLevelBytes)
+ entry.Message = truncateUTF8Bytes(entry.Message, maxConsoleMessageBytes)
+ entry.Source = truncateUTF8Bytes(entry.Source, maxConsoleSourceBytes)
+ return entry
+}
+
+func normalizeErrorLogEntry(entry ErrorEntry) ErrorEntry {
+ entry.Message = truncateUTF8Bytes(entry.Message, maxErrorMessageBytes)
+ entry.Type = truncateUTF8Bytes(entry.Type, maxErrorTypeBytes)
+ entry.URL = truncateUTF8Bytes(entry.URL, maxErrorURLBytes)
+ entry.Stack = truncateUTF8Bytes(entry.Stack, maxErrorStackBytes)
+ return entry
+}
+
+func truncateUTF8Bytes(s string, maxBytes int) string {
+ if maxBytes <= 0 {
+ return ""
+ }
+ if len(s) <= maxBytes {
+ return s
+ }
+ if maxBytes <= len(truncationSuffix) {
+ return truncationSuffix[:maxBytes]
+ }
+
+ limit := maxBytes - len(truncationSuffix)
+ cut := 0
+ for i := range s {
+ if i > limit {
+ break
+ }
+ cut = i
+ }
+ if cut == 0 && limit > 0 {
+ return truncationSuffix
+ }
+ return s[:cut] + truncationSuffix
+}
diff --git a/internal/bridge/console_logs_test.go b/internal/bridge/console_logs_test.go
new file mode 100644
index 00000000..c7dcf4be
--- /dev/null
+++ b/internal/bridge/console_logs_test.go
@@ -0,0 +1,231 @@
+package bridge
+
+import (
+ "strings"
+ "testing"
+ "time"
+ "unicode/utf8"
+)
+
+func TestConsoleLogStore_AddAndGet(t *testing.T) {
+ store := NewConsoleLogStore(100)
+
+ store.AddConsoleLog("tab1", LogEntry{
+ Timestamp: time.Now(),
+ Level: "log",
+ Message: "Hello world",
+ })
+ store.AddConsoleLog("tab1", LogEntry{
+ Timestamp: time.Now(),
+ Level: "warn",
+ Message: "Warning message",
+ })
+
+ logs := store.GetConsoleLogs("tab1", 0)
+ if len(logs) != 2 {
+ t.Errorf("expected 2 logs, got %d", len(logs))
+ }
+ if logs[0].Level != "log" {
+ t.Errorf("expected first log level 'log', got '%s'", logs[0].Level)
+ }
+}
+
+func TestConsoleLogStore_AddAndGetErrors(t *testing.T) {
+ store := NewConsoleLogStore(100)
+
+ store.AddErrorLog("tab1", ErrorEntry{
+ Timestamp: time.Now(),
+ Message: "Uncaught ReferenceError: x is not defined",
+ URL: "http://example.com/script.js",
+ Line: 42,
+ Column: 10,
+ })
+
+ errors := store.GetErrorLogs("tab1", 0)
+ if len(errors) != 1 {
+ t.Errorf("expected 1 error, got %d", len(errors))
+ }
+ if errors[0].Line != 42 {
+ t.Errorf("expected line 42, got %d", errors[0].Line)
+ }
+}
+
+func TestConsoleLogStore_Limit(t *testing.T) {
+ store := NewConsoleLogStore(5)
+
+ for i := 0; i < 10; i++ {
+ store.AddConsoleLog("tab1", LogEntry{
+ Timestamp: time.Now(),
+ Level: "log",
+ Message: string(rune('0' + i)),
+ })
+ }
+
+ logs := store.GetConsoleLogs("tab1", 0)
+ if len(logs) != 5 {
+ t.Errorf("expected 5 logs (maxLines), got %d", len(logs))
+ }
+ // Should have the last 5 entries (5,6,7,8,9)
+ if logs[0].Message != "5" {
+ t.Errorf("expected first message '5', got '%s'", logs[0].Message)
+ }
+}
+
+func TestConsoleLogStore_GetWithLimit(t *testing.T) {
+ store := NewConsoleLogStore(100)
+
+ for i := 0; i < 10; i++ {
+ store.AddConsoleLog("tab1", LogEntry{
+ Timestamp: time.Now(),
+ Level: "log",
+ Message: string(rune('0' + i)),
+ })
+ }
+
+ // Get only last 3
+ logs := store.GetConsoleLogs("tab1", 3)
+ if len(logs) != 3 {
+ t.Errorf("expected 3 logs, got %d", len(logs))
+ }
+ // Should be 7, 8, 9
+ if logs[0].Message != "7" {
+ t.Errorf("expected first message '7', got '%s'", logs[0].Message)
+ }
+}
+
+func TestConsoleLogStore_GetWithLimit_ClampsToMaxLines(t *testing.T) {
+ store := NewConsoleLogStore(5)
+
+ for i := 0; i < 5; i++ {
+ store.AddConsoleLog("tab1", LogEntry{
+ Timestamp: time.Now(),
+ Level: "log",
+ Message: string(rune('0' + i)),
+ })
+ store.AddErrorLog("tab1", ErrorEntry{
+ Timestamp: time.Now(),
+ Message: string(rune('0' + i)),
+ })
+ }
+
+ logs := store.GetConsoleLogs("tab1", 1000)
+ if len(logs) != 5 {
+ t.Fatalf("expected 5 console logs, got %d", len(logs))
+ }
+
+ errors := store.GetErrorLogs("tab1", 1000)
+ if len(errors) != 5 {
+ t.Fatalf("expected 5 error logs, got %d", len(errors))
+ }
+}
+
+func TestConsoleLogStore_ClampsConfiguredMaxLines(t *testing.T) {
+ store := NewConsoleLogStore(maxConsoleLogStoreLines + 500)
+ if store.maxLines != maxConsoleLogStoreLines {
+ t.Fatalf("maxLines = %d, want %d", store.maxLines, maxConsoleLogStoreLines)
+ }
+}
+
+func TestConsoleLogStore_Clear(t *testing.T) {
+ store := NewConsoleLogStore(100)
+
+ store.AddConsoleLog("tab1", LogEntry{Level: "log", Message: "test"})
+ store.AddErrorLog("tab1", ErrorEntry{Message: "error"})
+
+ store.ClearConsoleLogs("tab1")
+ logs := store.GetConsoleLogs("tab1", 0)
+ if len(logs) != 0 {
+ t.Errorf("expected 0 console logs after clear, got %d", len(logs))
+ }
+
+ // Errors should still be there
+ errors := store.GetErrorLogs("tab1", 0)
+ if len(errors) != 1 {
+ t.Errorf("expected 1 error (not cleared), got %d", len(errors))
+ }
+
+ store.ClearErrorLogs("tab1")
+ errors = store.GetErrorLogs("tab1", 0)
+ if len(errors) != 0 {
+ t.Errorf("expected 0 errors after clear, got %d", len(errors))
+ }
+}
+
+func TestConsoleLogStore_RemoveTab(t *testing.T) {
+ store := NewConsoleLogStore(100)
+
+ store.AddConsoleLog("tab1", LogEntry{Level: "log", Message: "test"})
+ store.AddConsoleLog("tab2", LogEntry{Level: "log", Message: "other"})
+
+ store.RemoveTab("tab1")
+
+ logs1 := store.GetConsoleLogs("tab1", 0)
+ logs2 := store.GetConsoleLogs("tab2", 0)
+
+ if logs1 != nil {
+ t.Errorf("expected nil for removed tab, got %v", logs1)
+ }
+ if len(logs2) != 1 {
+ t.Errorf("expected 1 log for tab2, got %d", len(logs2))
+ }
+}
+
+func TestConsoleLogStore_NonexistentTab(t *testing.T) {
+ store := NewConsoleLogStore(100)
+
+ logs := store.GetConsoleLogs("nonexistent", 0)
+ if logs != nil {
+ t.Errorf("expected nil for nonexistent tab, got %v", logs)
+ }
+
+ errors := store.GetErrorLogs("nonexistent", 0)
+ if errors != nil {
+ t.Errorf("expected nil for nonexistent tab errors, got %v", errors)
+ }
+
+ // Should not panic
+ store.ClearConsoleLogs("nonexistent")
+ store.ClearErrorLogs("nonexistent")
+ store.RemoveTab("nonexistent")
+}
+
+func TestConsoleLogStore_TruncatesOversizedFields(t *testing.T) {
+ store := NewConsoleLogStore(10)
+
+ store.AddConsoleLog("tab1", LogEntry{
+ Level: strings.Repeat("L", maxConsoleLevelBytes+10),
+ Message: strings.Repeat("界", 3000),
+ Source: strings.Repeat("s", maxConsoleSourceBytes+10),
+ })
+ store.AddErrorLog("tab1", ErrorEntry{
+ Message: strings.Repeat("界", 3000),
+ Type: strings.Repeat("t", maxErrorTypeBytes+10),
+ URL: strings.Repeat("u", maxErrorURLBytes+10),
+ Stack: strings.Repeat("界", 6000),
+ })
+
+ logs := store.GetConsoleLogs("tab1", 0)
+ if got := logs[0].Level; len(got) > maxConsoleLevelBytes {
+ t.Fatalf("expected truncated level <= %d bytes, got %d", maxConsoleLevelBytes, len(got))
+ }
+ if got := logs[0].Message; len(got) > maxConsoleMessageBytes || !utf8.ValidString(got) || !strings.HasSuffix(got, truncationSuffix) {
+ t.Fatalf("unexpected truncated console message: len=%d valid=%v suffix=%v", len(got), utf8.ValidString(got), strings.HasSuffix(got, truncationSuffix))
+ }
+ if got := logs[0].Source; len(got) > maxConsoleSourceBytes || !strings.HasSuffix(got, truncationSuffix) {
+ t.Fatalf("unexpected truncated console source: len=%d suffix=%v", len(got), strings.HasSuffix(got, truncationSuffix))
+ }
+
+ errors := store.GetErrorLogs("tab1", 0)
+ if got := errors[0].Message; len(got) > maxErrorMessageBytes || !utf8.ValidString(got) || !strings.HasSuffix(got, truncationSuffix) {
+ t.Fatalf("unexpected truncated error message: len=%d valid=%v suffix=%v", len(got), utf8.ValidString(got), strings.HasSuffix(got, truncationSuffix))
+ }
+ if got := errors[0].Type; len(got) > maxErrorTypeBytes || !strings.HasSuffix(got, truncationSuffix) {
+ t.Fatalf("unexpected truncated error type: len=%d suffix=%v", len(got), strings.HasSuffix(got, truncationSuffix))
+ }
+ if got := errors[0].URL; len(got) > maxErrorURLBytes || !strings.HasSuffix(got, truncationSuffix) {
+ t.Fatalf("unexpected truncated error url: len=%d suffix=%v", len(got), strings.HasSuffix(got, truncationSuffix))
+ }
+ if got := errors[0].Stack; len(got) > maxErrorStackBytes || !utf8.ValidString(got) || !strings.HasSuffix(got, truncationSuffix) {
+ t.Fatalf("unexpected truncated error stack: len=%d valid=%v suffix=%v", len(got), utf8.ValidString(got), strings.HasSuffix(got, truncationSuffix))
+ }
+}
diff --git a/internal/bridge/crash.go b/internal/bridge/crash.go
index 454274ff..23a3ed5c 100644
--- a/internal/bridge/crash.go
+++ b/internal/bridge/crash.go
@@ -118,6 +118,9 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {
}
case *target.EventTargetDestroyed:
+ if b.TabManager != nil {
+ go b.purgeTrackedTabStateByTargetID(string(e.TargetID))
+ }
slog.Debug("target destroyed", "targetId", e.TargetID)
}
})
diff --git a/internal/bridge/state.go b/internal/bridge/state.go
index 62fe83e9..c25ad762 100644
--- a/internal/bridge/state.go
+++ b/internal/bridge/state.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
+ "net/url"
"os"
"path/filepath"
"strings"
@@ -43,6 +44,14 @@ func isTransientURL(url string) bool {
strings.Contains(url, "localhost:")
}
+func safeURLHostForLog(raw string) string {
+ parsed, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil {
+ return ""
+ }
+ return parsed.Hostname()
+}
+
func MarkCleanExit(profileDir string) {
prefsPath := filepath.Join(profileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
@@ -201,7 +210,11 @@ func (b *Bridge) RestoreState() {
if err := chromedp.Run(ctx); err != nil {
cancel()
<-tabSem
- slog.Warn("restore tab failed", "url", tab.URL, "err", err)
+ attrs := []any{"err", err}
+ if host := safeURLHostForLog(tab.URL); host != "" {
+ attrs = append(attrs, "host", host)
+ }
+ slog.Warn("restore tab failed", attrs...)
continue
}
diff --git a/internal/bridge/state_test.go b/internal/bridge/state_test.go
index 2371d6d0..f4ebb224 100644
--- a/internal/bridge/state_test.go
+++ b/internal/bridge/state_test.go
@@ -157,6 +157,27 @@ func TestIsTransientURL(t *testing.T) {
}
}
+func TestSafeURLHostForLog(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want string
+ }{
+ {name: "https query", raw: "https://example.com/reset?token=secret", want: "example.com"},
+ {name: "subdomain with port", raw: "https://app.example.com:8443/path?q=1", want: "app.example.com"},
+ {name: "malformed", raw: "://bad-url", want: ""},
+ {name: "empty", raw: "", want: ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := safeURLHostForLog(tt.raw); got != tt.want {
+ t.Fatalf("safeURLHostForLog(%q) = %q, want %q", tt.raw, got, tt.want)
+ }
+ })
+ }
+}
+
func TestClearChromeSessions(t *testing.T) {
tmp := t.TempDir()
sessionsDir := filepath.Join(tmp, "Default", "Sessions")
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index f2134e82..8b31eb27 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -9,10 +9,12 @@ import (
cdp "github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/page"
+ "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/ids"
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
)
type TabSetupFunc func(ctx context.Context)
@@ -26,13 +28,14 @@ type TabManager struct {
snapshots map[string]*RefCache
onTabSetup TabSetupFunc
dialogMgr *DialogManager
+ logStore *ConsoleLogStore
currentTab string // ID of the most recently used tab
executor *TabExecutor
guardOnce sync.Once
mu sync.RWMutex
}
-func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *ids.Manager, onTabSetup TabSetupFunc) *TabManager {
+func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *ids.Manager, logStore *ConsoleLogStore, onTabSetup TabSetupFunc) *TabManager {
if idMgr == nil {
idMgr = ids.NewManager()
}
@@ -48,6 +51,7 @@ func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr
accessed: make(map[string]bool),
snapshots: make(map[string]*RefCache),
onTabSetup: onTabSetup,
+ logStore: logStore,
executor: NewTabExecutor(maxParallel),
}
}
@@ -93,13 +97,14 @@ func (tm *TabManager) StartBrowserGuards() {
func (tm *TabManager) closePopupTarget(targetID, openerID target.ID, url string) {
closeCtx, cancel := context.WithTimeout(tm.browserCtx, 5*time.Second)
defer cancel()
+ logURL := internalurls.RedactForLog(url)
if err := target.CloseTarget(targetID).Do(cdp.WithExecutor(closeCtx, chromedp.FromContext(closeCtx).Browser)); err != nil {
- slog.Debug("popup close failed", "targetId", targetID, "openerId", openerID, "url", url, "err", err)
+ slog.Debug("popup close failed", "targetId", targetID, "openerId", openerID, "url", logURL, "err", err)
return
}
- slog.Info("blocked popup target", "targetId", targetID, "openerId", openerID, "url", url)
+ slog.Info("blocked popup target", "targetId", targetID, "openerId", openerID, "url", logURL)
}
func (tm *TabManager) markAccessed(tabID string) {
@@ -351,6 +356,9 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
ListenDialogEvents(ctx, tabID, tm.dialogMgr, autoAccept)
}
+ // Set up console and error log capturing
+ tm.setupConsoleCapture(ctx, rawCDPID)
+
tm.mu.Lock()
tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID, CreatedAt: now, LastUsed: now}
tm.accessed[tabID] = true
@@ -395,16 +403,7 @@ func (tm *TabManager) CloseTab(tabID string) error {
}
slog.Debug("close target CDP", "tabId", tabID, "cdpId", cdpTargetID, "err", err)
}
-
- tm.mu.Lock()
- delete(tm.tabs, tabID)
- delete(tm.snapshots, tabID)
- tm.mu.Unlock()
-
- // Clean up executor per-tab mutex
- if tm.executor != nil {
- tm.executor.RemoveTab(tabID)
- }
+ tm.purgeTrackedTabState(tabID, cdpTargetID)
return nil
}
@@ -580,28 +579,169 @@ func (tm *TabManager) CleanStaleTabs(ctx context.Context, interval time.Duration
alive[string(t.TargetID)] = true
}
- // Collect stale tab IDs while holding the lock, then clean up
- // executor mutexes outside the lock to avoid blocking TabManager
- // operations if RemoveTab has to wait for an in-flight task.
- var staleIDs []string
- tm.mu.Lock()
+ type staleTab struct {
+ tabID string
+ cdpID string
+ }
+ var staleTabs []staleTab
+ tm.mu.RLock()
for id, entry := range tm.tabs {
if !alive[id] {
- if entry.Cancel != nil {
- entry.Cancel()
+ cdpID := entry.CDPID
+ if cdpID == "" {
+ cdpID = id
}
- delete(tm.tabs, id)
- delete(tm.snapshots, id)
- staleIDs = append(staleIDs, id)
- slog.Info("cleaned stale tab", "id", id)
+ staleTabs = append(staleTabs, staleTab{tabID: id, cdpID: cdpID})
}
}
- tm.mu.Unlock()
+ tm.mu.RUnlock()
+
+ for _, stale := range staleTabs {
+ tm.purgeTrackedTabState(stale.tabID, stale.cdpID)
+ slog.Info("cleaned stale tab", "id", stale.tabID)
+ }
+ }
+}
+
+func (tm *TabManager) purgeTrackedTabState(tabID, cdpTargetID string) bool {
+ resolvedTabID, resolvedCDPID, cancel, ok := tm.lookupTrackedTabForCleanup(tabID, cdpTargetID)
+ if !ok {
+ return false
+ }
+ if cancel != nil {
+ cancel()
+ }
+
+ tm.mu.Lock()
+ delete(tm.tabs, resolvedTabID)
+ delete(tm.snapshots, resolvedTabID)
+ delete(tm.accessed, resolvedTabID)
+ if tm.currentTab == resolvedTabID {
+ tm.currentTab = ""
+ }
+ tm.mu.Unlock()
+
+ if tm.dialogMgr != nil {
+ tm.dialogMgr.ClearPending(resolvedTabID)
+ }
+ if tm.executor != nil {
+ tm.executor.RemoveTab(resolvedTabID)
+ }
+ if tm.logStore != nil {
+ tm.logStore.RemoveTab(resolvedCDPID)
+ }
+ return true
+}
+
+func (tm *TabManager) lookupTrackedTabForCleanup(tabID, cdpTargetID string) (string, string, context.CancelFunc, bool) {
+ tm.mu.RLock()
+ defer tm.mu.RUnlock()
- if tm.executor != nil {
- for _, id := range staleIDs {
- tm.executor.RemoveTab(id)
+ if tabID != "" {
+ if entry, ok := tm.tabs[tabID]; ok {
+ resolvedCDPID := cdpTargetID
+ if resolvedCDPID == "" {
+ resolvedCDPID = entry.CDPID
+ }
+ if resolvedCDPID == "" {
+ resolvedCDPID = tabID
}
+ return tabID, resolvedCDPID, entry.Cancel, true
+ }
+ }
+
+ if cdpTargetID == "" {
+ return "", "", nil, false
+ }
+
+ for id, entry := range tm.tabs {
+ resolvedCDPID := entry.CDPID
+ if resolvedCDPID == "" {
+ resolvedCDPID = id
}
+ if id == cdpTargetID || resolvedCDPID == cdpTargetID {
+ return id, resolvedCDPID, entry.Cancel, true
+ }
+ }
+ return "", "", nil, false
+}
+
+func (tm *TabManager) purgeTrackedTabStateByTargetID(cdpTargetID string) bool {
+ return tm.purgeTrackedTabState("", cdpTargetID)
+}
+
+// setupConsoleCapture enables runtime domain and listens for console/exception events.
+func (tm *TabManager) setupConsoleCapture(ctx context.Context, rawCDPID string) {
+ if tm.logStore == nil {
+ return
}
+
+ // Listen for console API calls and exceptions
+ chromedp.ListenTarget(ctx, func(ev any) {
+ switch ev := ev.(type) {
+ case *runtime.EventConsoleAPICalled:
+ var msg string
+ for _, arg := range ev.Args {
+ if len(arg.Value) > 0 {
+ // arg.Value is jsontext.Value ([]byte), use as string directly
+ // Strip quotes if it's a JSON string
+ val := string(arg.Value)
+ if len(val) >= 2 && val[0] == '"' && val[len(val)-1] == '"' {
+ val = val[1 : len(val)-1]
+ }
+ msg += val
+ } else if arg.Description != "" {
+ msg += arg.Description
+ }
+ msg += " "
+ }
+
+ var ts time.Time
+ if ev.Timestamp != nil {
+ ts = time.Time(*ev.Timestamp)
+ } else {
+ ts = time.Now()
+ }
+
+ tm.logStore.AddConsoleLog(rawCDPID, LogEntry{
+ Timestamp: ts,
+ Level: string(ev.Type),
+ Message: msg,
+ })
+
+ case *runtime.EventExceptionThrown:
+ msg := ev.ExceptionDetails.Text
+ if ev.ExceptionDetails.Exception != nil && ev.ExceptionDetails.Exception.Description != "" {
+ msg += ": " + ev.ExceptionDetails.Exception.Description
+ }
+
+ var ts time.Time
+ if ev.Timestamp != nil {
+ ts = time.Time(*ev.Timestamp)
+ } else {
+ ts = time.Now()
+ }
+
+ stack := ""
+ if ev.ExceptionDetails.Exception != nil {
+ stack = ev.ExceptionDetails.Exception.Description
+ }
+
+ tm.logStore.AddErrorLog(rawCDPID, ErrorEntry{
+ Timestamp: ts,
+ Message: msg,
+ URL: ev.ExceptionDetails.URL,
+ Line: ev.ExceptionDetails.LineNumber,
+ Column: ev.ExceptionDetails.ColumnNumber,
+ Stack: stack,
+ })
+ }
+ })
+
+ // Enable runtime domain to receive console/exception events
+ go func() {
+ _ = chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
+ return runtime.Enable().Do(c)
+ }))
+ }()
}
diff --git a/internal/bridge/tabs/dialog.go b/internal/bridge/tabs/dialog.go
index 5c13184a..4cab88fd 100644
--- a/internal/bridge/tabs/dialog.go
+++ b/internal/bridge/tabs/dialog.go
@@ -71,7 +71,7 @@ func ListenDialogEvents(ctx context.Context, tabID string, dm *DialogManager, au
Message: e.Message,
DefaultPrompt: e.DefaultPrompt,
}
- slog.Debug("dialog opened", "tabId", tabID, "type", e.Type, "message", e.Message)
+ slog.Debug("dialog opened", "tabId", tabID, "type", e.Type)
if autoAccept {
state.HasBrowserHandler = true
diff --git a/internal/cli/actions/actions_console.go b/internal/cli/actions/actions_console.go
new file mode 100644
index 00000000..f079a647
--- /dev/null
+++ b/internal/cli/actions/actions_console.go
@@ -0,0 +1,167 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+// Console displays browser console logs.
+func Console(client *http.Client, base, token string, cmd *cobra.Command) {
+ if v, _ := cmd.Flags().GetBool("clear"); v {
+ ConsoleClear(client, base, token, cmd)
+ return
+ }
+
+ params := url.Values{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ params.Set("tabId", v)
+ }
+ if v, _ := cmd.Flags().GetString("limit"); v != "" {
+ params.Set("limit", v)
+ }
+
+ result := apiclient.DoGetRaw(client, base, token, "/console", params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to get console logs")
+ os.Exit(1)
+ }
+
+ printConsoleLogs(result)
+}
+
+// ConsoleClear clears console logs.
+func ConsoleClear(client *http.Client, base, token string, cmd *cobra.Command) {
+ params := url.Values{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ params.Set("tabId", v)
+ }
+ result := apiclient.DoPost(client, base, token, "/console/clear?"+params.Encode(), nil)
+ if result != nil {
+ fmt.Println("Console logs cleared")
+ }
+}
+
+// Errors displays browser error logs.
+func Errors(client *http.Client, base, token string, cmd *cobra.Command) {
+ if v, _ := cmd.Flags().GetBool("clear"); v {
+ ErrorsClear(client, base, token, cmd)
+ return
+ }
+
+ params := url.Values{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ params.Set("tabId", v)
+ }
+ if v, _ := cmd.Flags().GetString("limit"); v != "" {
+ params.Set("limit", v)
+ }
+
+ result := apiclient.DoGetRaw(client, base, token, "/errors", params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to get error logs")
+ os.Exit(1)
+ }
+
+ printErrorLogs(result)
+}
+
+// ErrorsClear clears error logs.
+func ErrorsClear(client *http.Client, base, token string, cmd *cobra.Command) {
+ params := url.Values{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ params.Set("tabId", v)
+ }
+ result := apiclient.DoPost(client, base, token, "/errors/clear?"+params.Encode(), nil)
+ if result != nil {
+ fmt.Println("Error logs cleared")
+ }
+}
+
+func printConsoleLogs(data []byte) {
+ var resp struct {
+ TabID string `json:"tabId"`
+ Console []struct {
+ Timestamp time.Time `json:"timestamp"`
+ Level string `json:"level"`
+ Message string `json:"message"`
+ } `json:"console"`
+ }
+ if err := json.Unmarshal(data, &resp); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse response: %v\n", err)
+ os.Exit(1)
+ }
+
+ if len(resp.Console) == 0 {
+ fmt.Println("No console logs")
+ return
+ }
+
+ for _, entry := range resp.Console {
+ timeStr := entry.Timestamp.Format("15:04:05")
+ level := strings.ToUpper(entry.Level)
+ fmt.Printf("%s [%s] %s\n", timeStr, level, sanitizeTerminalText(entry.Message))
+ }
+}
+
+func printErrorLogs(data []byte) {
+ var resp struct {
+ TabID string `json:"tabId"`
+ Errors []struct {
+ Timestamp time.Time `json:"timestamp"`
+ Message string `json:"message"`
+ URL string `json:"url"`
+ Line int64 `json:"line"`
+ Column int64 `json:"column"`
+ } `json:"errors"`
+ }
+ if err := json.Unmarshal(data, &resp); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse response: %v\n", err)
+ os.Exit(1)
+ }
+
+ if len(resp.Errors) == 0 {
+ fmt.Println("No errors")
+ return
+ }
+
+ for _, entry := range resp.Errors {
+ timeStr := entry.Timestamp.Format("15:04:05")
+ fmt.Printf("%s [ERROR] %s\n", timeStr, sanitizeTerminalText(entry.Message))
+ if entry.URL != "" {
+ fmt.Printf(" at %s:%d:%d\n", sanitizeTerminalText(entry.URL), entry.Line, entry.Column)
+ }
+ }
+}
+
+func sanitizeTerminalText(s string) string {
+ var b strings.Builder
+ b.Grow(len(s))
+ for _, r := range s {
+ switch r {
+ case '\n':
+ b.WriteString(`\n`)
+ case '\r':
+ b.WriteString(`\r`)
+ case '\t':
+ b.WriteString(`\t`)
+ default:
+ if isTerminalControlRune(r) {
+ continue
+ }
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+func isTerminalControlRune(r rune) bool {
+ return (r >= 0 && r < 0x20) || r == 0x7f || (r >= 0x80 && r <= 0x9f)
+}
diff --git a/internal/cli/actions/actions_console_test.go b/internal/cli/actions/actions_console_test.go
new file mode 100644
index 00000000..cef32b7b
--- /dev/null
+++ b/internal/cli/actions/actions_console_test.go
@@ -0,0 +1,71 @@
+package actions
+
+import (
+ "io"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestSanitizeTerminalText(t *testing.T) {
+ input := "hello\x1b[31mred\x1b[0m\r\nnext\tline\a"
+ got := sanitizeTerminalText(input)
+ want := "hello[31mred[0m\\r\\nnext\\tline"
+ if got != want {
+ t.Fatalf("sanitizeTerminalText() = %q, want %q", got, want)
+ }
+}
+
+func TestPrintConsoleLogs_SanitizesTerminalOutput(t *testing.T) {
+ output := captureStdout(t, func() {
+ printConsoleLogs([]byte(`{"tabId":"tab1","console":[{"timestamp":"2026-03-19T12:00:00Z","level":"log","message":"hello\u001b[31m\r\nworld\t\u0007"}]}`))
+ })
+
+ if strings.ContainsRune(output, '\x1b') {
+ t.Fatalf("expected output to strip escape characters, got %q", output)
+ }
+ if !strings.Contains(output, "hello[31m\\r\\nworld\\t") {
+ t.Fatalf("expected sanitized output, got %q", output)
+ }
+}
+
+func TestPrintErrorLogs_SanitizesTerminalOutput(t *testing.T) {
+ output := captureStdout(t, func() {
+ printErrorLogs([]byte(`{"tabId":"tab1","errors":[{"timestamp":"2026-03-19T12:00:00Z","message":"boom\u001b[2J","url":"https://example.com/\u001b]52;c;secret\u0007","line":1,"column":2}]}`))
+ })
+
+ if strings.ContainsRune(output, '\x1b') {
+ t.Fatalf("expected output to strip escape characters, got %q", output)
+ }
+ if !strings.Contains(output, "boom[2J") {
+ t.Fatalf("expected sanitized message, got %q", output)
+ }
+ if !strings.Contains(output, "https://example.com/]52;c;secret") {
+ t.Fatalf("expected sanitized url, got %q", output)
+ }
+}
+
+func captureStdout(t *testing.T, fn func()) string {
+ t.Helper()
+
+ oldStdout := os.Stdout
+ reader, writer, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("os.Pipe: %v", err)
+ }
+ os.Stdout = writer
+
+ defer func() {
+ os.Stdout = oldStdout
+ }()
+
+ fn()
+
+ _ = writer.Close()
+ out, err := io.ReadAll(reader)
+ if err != nil {
+ t.Fatalf("ReadAll: %v", err)
+ }
+ _ = reader.Close()
+ return string(out)
+}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index 6272b49e..d0bdd551 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -33,7 +33,7 @@ func DefaultFileConfig() FileConfig {
attachEnabled := false
activityEnabled := true
activitySessionIdleSec := 1800
- activityRetentionDays := 1
+ activityRetentionDays := 30
return FileConfig{
ConfigVersion: CurrentConfigVersion,
Server: ServerConfig{
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 0b0a4933..62218a55 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -92,7 +92,7 @@ func Load() *RuntimeConfig {
Activity: ActivityConfig{
Enabled: true,
SessionIdleSec: 1800,
- RetentionDays: 1,
+ RetentionDays: 30,
},
},
}
@@ -232,6 +232,11 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Security.MaxRedirects != nil {
cfg.MaxRedirects = *fc.Security.MaxRedirects
}
+ if fc.Security.Attach.Enabled != nil {
+ cfg.AttachEnabled = *fc.Security.Attach.Enabled
+ }
+ cfg.AttachAllowHosts = append([]string(nil), fc.Security.Attach.AllowHosts...)
+ cfg.AttachAllowSchemes = append([]string(nil), fc.Security.Attach.AllowSchemes...)
// IDPI – copy the whole struct; individual fields have safe zero-value defaults.
cfg.IDPI = fc.Security.IDPI
if fc.Observability.Activity.Enabled != nil {
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 4965388e..a492c86a 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -110,6 +110,12 @@ func TestLoadConfigDefaults(t *testing.T) {
if !cfg.IDPI.WrapContent {
t.Errorf("default IDPI.WrapContent = %v, want true", cfg.IDPI.WrapContent)
}
+ if !cfg.Observability.Activity.Enabled {
+ t.Errorf("default Observability.Activity.Enabled = %v, want true", cfg.Observability.Activity.Enabled)
+ }
+ if cfg.Observability.Activity.RetentionDays != 30 {
+ t.Errorf("default Observability.Activity.RetentionDays = %d, want 30", cfg.Observability.Activity.RetentionDays)
+ }
}
func TestLoadConfigTokenEnvOverride(t *testing.T) {
@@ -316,6 +322,34 @@ func TestApplyFileConfigToRuntime_CopiesDownloadAllowedDomains(t *testing.T) {
}
}
+func TestApplyFileConfigToRuntime_CopiesAttachConfig(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ enabled := true
+ fc := &FileConfig{
+ Security: SecurityConfig{
+ Attach: AttachConfig{
+ Enabled: &enabled,
+ AllowHosts: []string{"127.0.0.1", "pinchtab-bridge"},
+ AllowSchemes: []string{"http", "https"},
+ },
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+ fc.Security.Attach.AllowHosts[0] = "mutated.example.com"
+ fc.Security.Attach.AllowSchemes[0] = "ws"
+
+ if !cfg.AttachEnabled {
+ t.Fatalf("ApplyFileConfigToRuntime AttachEnabled = %v, want true", cfg.AttachEnabled)
+ }
+ if len(cfg.AttachAllowHosts) != 2 || cfg.AttachAllowHosts[1] != "pinchtab-bridge" {
+ t.Fatalf("ApplyFileConfigToRuntime AttachAllowHosts = %v, want copied hosts", cfg.AttachAllowHosts)
+ }
+ if len(cfg.AttachAllowSchemes) != 2 || cfg.AttachAllowSchemes[0] != "http" {
+ t.Fatalf("ApplyFileConfigToRuntime AttachAllowSchemes = %v, want copied schemes", cfg.AttachAllowSchemes)
+ }
+}
+
func TestRuntimeConfig_EffectiveTransferLimitsFallbackAndClamp(t *testing.T) {
cfg := &RuntimeConfig{}
if cfg.EffectiveDownloadMaxBytes() != DefaultDownloadMaxBytes {
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 3ea356e8..9647ac85 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -193,10 +193,10 @@ func ValidateFileConfig(fc *FileConfig) []error {
Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.Observability.Activity.SessionIdleSec),
})
}
- if fc.Observability.Activity.RetentionDays != nil && *fc.Observability.Activity.RetentionDays < 0 {
+ if fc.Observability.Activity.RetentionDays != nil && *fc.Observability.Activity.RetentionDays <= 0 {
errs = append(errs, ValidationError{
Field: "observability.activity.retentionDays",
- Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.Observability.Activity.RetentionDays),
+ Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Observability.Activity.RetentionDays),
})
}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 0ae0613a..2d6d5947 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -342,6 +342,36 @@ func TestValidateFileConfig_InvalidTimeouts(t *testing.T) {
}
}
+func TestValidateFileConfig_InvalidActivityRetentionDays(t *testing.T) {
+ tests := []struct {
+ name string
+ value *int
+ wantErr bool
+ }{
+ {name: "nil", value: nil, wantErr: false},
+ {name: "positive", value: intPtr(30), wantErr: false},
+ {name: "zero", value: intPtr(0), wantErr: true},
+ {name: "negative", value: intPtr(-1), wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ fc := &FileConfig{
+ Observability: ObservabilityFileConfig{
+ Activity: ActivityFileConfig{
+ RetentionDays: tt.value,
+ },
+ },
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Fatalf("RetentionDays=%v: got error=%v, want %v (errs: %v)", tt.value, hasErr, tt.wantErr, errs)
+ }
+ })
+ }
+}
+
func TestValidateFileConfig_InstancePortRange(t *testing.T) {
start := 9900
end := 9800 // invalid: start > end
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index 44ffddd5..2b5bcf43 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -1,7 +1,9 @@
package dashboard
import (
+ "bytes"
"encoding/json"
+ "io"
"net/http"
"strings"
"sync"
@@ -108,8 +110,37 @@ func (c *ConfigAPI) HandleGetConfig(w http.ResponseWriter, r *http.Request) {
}
func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
- normalized := config.DefaultFileConfig()
- if err := json.NewDecoder(r.Body).Decode(&normalized); err != nil {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ current, path, err := config.LoadFileConfig()
+ if err != nil {
+ httpx.Error(w, 500, err)
+ return
+ }
+
+ body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ if err != nil {
+ httpx.ErrorCode(w, 400, "bad_config_json", "invalid config payload", false, nil)
+ return
+ }
+
+ var tokenProbe struct {
+ Server struct {
+ Token *string `json:"token"`
+ } `json:"server"`
+ }
+ if err := json.Unmarshal(body, &tokenProbe); err != nil {
+ httpx.ErrorCode(w, 400, "bad_config_json", "invalid config payload", false, nil)
+ return
+ }
+ if tokenProbe.Server.Token != nil && strings.TrimSpace(*tokenProbe.Server.Token) != "" {
+ httpx.ErrorCode(w, 400, "token_write_only", "manage the API token outside the dashboard", false, nil)
+ return
+ }
+
+ normalized := *current
+ if err := json.NewDecoder(bytes.NewReader(body)).Decode(&normalized); err != nil {
httpx.ErrorCode(w, 400, "bad_config_json", "invalid config payload", false, nil)
return
}
@@ -124,19 +155,6 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
})
return
}
- if strings.TrimSpace(normalized.Server.Token) != "" {
- httpx.ErrorCode(w, 400, "token_write_only", "manage the API token outside the dashboard", false, nil)
- return
- }
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- current, path, err := config.LoadFileConfig()
- if err != nil {
- httpx.Error(w, 500, err)
- return
- }
normalized.Server.Token = current.Server.Token
if err := config.SaveFileConfig(&normalized, path); err != nil {
httpx.Error(w, 500, err)
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
index d51bb76c..53fc8df3 100644
--- a/internal/dashboard/config_api_test.go
+++ b/internal/dashboard/config_api_test.go
@@ -148,6 +148,40 @@ func TestHandlePutConfigPreservesExistingToken(t *testing.T) {
}
}
+func TestHandlePutConfigPreservesUnspecifiedAttachSettings(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+ attachEnabled := true
+ fc.Security.Attach.Enabled = &attachEnabled
+ fc.Security.Attach.AllowHosts = []string{"127.0.0.1", "pinchtab-bridge"}
+ fc.Security.Attach.AllowSchemes = []string{"http", "https"}
+
+ api := newConfigAPITestAPI(t, fc)
+
+ body := []byte(`{"server":{"trustProxyHeaders":true}}`)
+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ api.HandlePutConfig(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("HandlePutConfig() status = %d, want %d", w.Code, http.StatusOK)
+ }
+
+ saved, _, err := config.LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if saved.Security.Attach.Enabled == nil || !*saved.Security.Attach.Enabled {
+ t.Fatalf("saved attach.enabled = %v, want true", saved.Security.Attach.Enabled)
+ }
+ if len(saved.Security.Attach.AllowHosts) != 2 || saved.Security.Attach.AllowHosts[1] != "pinchtab-bridge" {
+ t.Fatalf("saved attach.allowHosts = %v, want preserved hosts", saved.Security.Attach.AllowHosts)
+ }
+ if len(saved.Security.Attach.AllowSchemes) != 2 || saved.Security.Attach.AllowSchemes[0] != "http" {
+ t.Fatalf("saved attach.allowSchemes = %v, want preserved schemes", saved.Security.Attach.AllowSchemes)
+ }
+}
+
func TestHandlePutConfigRejectsWriteOnlyTokenField(t *testing.T) {
fc := config.DefaultFileConfig()
fc.Server.Token = "secret-token"
diff --git a/internal/handlers/console.go b/internal/handlers/console.go
new file mode 100644
index 00000000..8679af8d
--- /dev/null
+++ b/internal/handlers/console.go
@@ -0,0 +1,121 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+const maxLogLimit = 1000
+
+func (h *Handlers) resolveConsoleTab(w http.ResponseWriter, r *http.Request) (context.Context, string, bool) {
+ tabID := r.URL.Query().Get("tabId")
+ if tabID == "" {
+ ctx, resolvedID, err := h.Bridge.TabContext("")
+ if err != nil {
+ httpx.Error(w, http.StatusBadRequest, err)
+ return nil, "", false
+ }
+ return ctx, resolvedID, true
+ }
+
+ ctx, resolvedID, err := h.Bridge.TabContext(tabID)
+ if err != nil {
+ httpx.Error(w, http.StatusNotFound, fmt.Errorf("tab not found"))
+ return nil, "", false
+ }
+ return ctx, resolvedID, true
+}
+
+func parseLogLimit(raw string) int {
+ if raw == "" {
+ return 0
+ }
+ v, err := strconv.Atoi(raw)
+ if err != nil {
+ return 0
+ }
+ if v < 0 {
+ return 0
+ }
+ if v > maxLogLimit {
+ return maxLogLimit
+ }
+ return v
+}
+
+// HandleGetConsoleLogs returns console logs for a tab.
+func (h *Handlers) HandleGetConsoleLogs(w http.ResponseWriter, r *http.Request) {
+ ctx, tabID, ok := h.resolveConsoleTab(w, r)
+ if !ok {
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, tabID); !ok {
+ return
+ }
+
+ limit := parseLogLimit(r.URL.Query().Get("limit"))
+
+ logs := h.Bridge.GetConsoleLogs(tabID, limit)
+ if logs == nil {
+ logs = make([]bridge.LogEntry, 0)
+ }
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "tabId": tabID,
+ "console": logs,
+ })
+}
+
+// HandleClearConsoleLogs clears console logs for a tab.
+func (h *Handlers) HandleClearConsoleLogs(w http.ResponseWriter, r *http.Request) {
+ _, tabID, ok := h.resolveConsoleTab(w, r)
+ if !ok {
+ return
+ }
+
+ h.Bridge.ClearConsoleLogs(tabID)
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "success": true,
+ "tabId": tabID,
+ })
+}
+
+// HandleGetErrorLogs returns error logs for a tab.
+func (h *Handlers) HandleGetErrorLogs(w http.ResponseWriter, r *http.Request) {
+ ctx, tabID, ok := h.resolveConsoleTab(w, r)
+ if !ok {
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, tabID); !ok {
+ return
+ }
+
+ limit := parseLogLimit(r.URL.Query().Get("limit"))
+
+ errors := h.Bridge.GetErrorLogs(tabID, limit)
+ if errors == nil {
+ errors = make([]bridge.ErrorEntry, 0)
+ }
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "tabId": tabID,
+ "errors": errors,
+ })
+}
+
+// HandleClearErrorLogs clears error logs for a tab.
+func (h *Handlers) HandleClearErrorLogs(w http.ResponseWriter, r *http.Request) {
+ _, tabID, ok := h.resolveConsoleTab(w, r)
+ if !ok {
+ return
+ }
+
+ h.Bridge.ClearErrorLogs(tabID)
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "success": true,
+ "tabId": tabID,
+ })
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 5cd930ee..cf757218 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -157,6 +157,10 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("POST /tabs/{id}/dialog", h.HandleTabDialog)
mux.HandleFunc("POST /wait", h.HandleWait)
mux.HandleFunc("POST /tabs/{id}/wait", h.HandleTabWait)
+ mux.HandleFunc("GET /console", h.HandleGetConsoleLogs)
+ mux.HandleFunc("POST /console/clear", h.HandleClearConsoleLogs)
+ mux.HandleFunc("GET /errors", h.HandleGetErrorLogs)
+ mux.HandleFunc("POST /errors/clear", h.HandleClearErrorLogs)
mux.HandleFunc("GET /welcome", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(assets.WelcomeHTML))
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index f72fdf3e..51d9114f 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
@@ -18,8 +19,10 @@ import (
type mockBridge struct {
bridge.BridgeAPI
- failTab bool
- createTabURLs []string
+ failTab bool
+ createTabURLs []string
+ lastConsoleLimit int
+ lastErrorLimit int
}
func (m *mockBridge) TabContext(tabID string) (context.Context, string, error) {
@@ -97,6 +100,20 @@ func (m *mockBridge) GetDialogManager() *bridge.DialogManager {
return bridge.NewDialogManager()
}
+func (m *mockBridge) GetConsoleLogs(tabID string, limit int) []bridge.LogEntry {
+ m.lastConsoleLimit = limit
+ return nil
+}
+
+func (m *mockBridge) ClearConsoleLogs(tabID string) {}
+
+func (m *mockBridge) GetErrorLogs(tabID string, limit int) []bridge.ErrorEntry {
+ m.lastErrorLimit = limit
+ return nil
+}
+
+func (m *mockBridge) ClearErrorLogs(tabID string) {}
+
func (m *mockBridge) Execute(ctx context.Context, tabID string, task func(ctx context.Context) error) error {
return task(ctx)
}
@@ -242,6 +259,122 @@ func TestHandleTab(t *testing.T) {
}
}
+func TestHandleGetErrorLogs_ClampsLimit(t *testing.T) {
+ tests := []struct {
+ name string
+ limit string
+ expected int
+ }{
+ {name: "negative", limit: "-5", expected: 0},
+ {name: "too_large", limit: "1001", expected: 1000},
+ {name: "in_range", limit: "25", expected: 25},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ m := &mockBridge{}
+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/errors?limit="+tt.limit, nil)
+ w := httptest.NewRecorder()
+ h.HandleGetErrorLogs(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+ if m.lastErrorLimit != tt.expected {
+ t.Fatalf("expected limit %d, got %d", tt.expected, m.lastErrorLimit)
+ }
+ })
+ }
+}
+
+func TestHandleGetConsoleLogs_ClampsLimit(t *testing.T) {
+ tests := []struct {
+ name string
+ limit string
+ expected int
+ }{
+ {name: "negative", limit: "-5", expected: 0},
+ {name: "too_large", limit: "1001", expected: 1000},
+ {name: "in_range", limit: "25", expected: 25},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ m := &mockBridge{}
+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/console?limit="+tt.limit, nil)
+ w := httptest.NewRecorder()
+ h.HandleGetConsoleLogs(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+ if m.lastConsoleLimit != tt.expected {
+ t.Fatalf("expected limit %d, got %d", tt.expected, m.lastConsoleLimit)
+ }
+ })
+ }
+}
+
+func TestHandleGetConsoleLogs_BlocksWhenCachedTabPolicyIsBlocked(t *testing.T) {
+ b := &policyMockBridge{
+ state: bridge.TabPolicyState{
+ CurrentURL: "https://evil.example.net",
+ Threat: true,
+ Blocked: true,
+ Reason: `domain "evil.example.net" is not in the allowed list`,
+ UpdatedAt: time.Now(),
+ },
+ hasState: true,
+ }
+ h := New(b, &config.RuntimeConfig{
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"example.com"},
+ StrictMode: true,
+ },
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/console?tabId=tab1", nil)
+ w := httptest.NewRecorder()
+ h.HandleGetConsoleLogs(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleGetErrorLogs_BlocksWhenCachedTabPolicyIsBlocked(t *testing.T) {
+ b := &policyMockBridge{
+ state: bridge.TabPolicyState{
+ CurrentURL: "https://evil.example.net",
+ Threat: true,
+ Blocked: true,
+ Reason: `domain "evil.example.net" is not in the allowed list`,
+ UpdatedAt: time.Now(),
+ },
+ hasState: true,
+ }
+ h := New(b, &config.RuntimeConfig{
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"example.com"},
+ StrictMode: true,
+ },
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/errors?tabId=tab1", nil)
+ w := httptest.NewRecorder()
+ h.HandleGetErrorLogs(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
func TestHandleTabFocus(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index 0970a41b..2054aef5 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -366,6 +366,18 @@ func (m *MockBridge) Execute(ctx context.Context, tabID string, task func(ctx co
return task(ctx)
}
+func (m *MockBridge) GetConsoleLogs(tabID string, limit int) []bridge.LogEntry {
+ return nil
+}
+
+func (m *MockBridge) ClearConsoleLogs(tabID string) {}
+
+func (m *MockBridge) GetErrorLogs(tabID string, limit int) []bridge.ErrorEntry {
+ return nil
+}
+
+func (m *MockBridge) ClearErrorLogs(tabID string) {}
+
type mockBridgeDisconnected struct {
mockBridge
}
diff --git a/internal/handlers/help.go b/internal/handlers/help.go
index 8fbe3067..4462a7a3 100644
--- a/internal/handlers/help.go
+++ b/internal/handlers/help.go
@@ -22,6 +22,10 @@ func (h *Handlers) HandleHelp(wr http.ResponseWriter, _ *http.Request) {
"POST|GET /action": "run a single action (JSON body or query params)",
"POST /actions": "run multiple actions",
"GET /snapshot": "accessibility snapshot",
+ "GET /console": "view browser console logs (supports tabId, limit)",
+ "POST /console/clear": "clear console logs for a tab",
+ "GET /errors": "view browser uncaught errors (supports tabId, limit)",
+ "POST /errors/clear": "clear error logs for a tab",
"POST /evaluate": endpointStatusSummary(security["evaluate"], "run JavaScript in the current tab"),
"POST /tabs/{id}/evaluate": endpointStatusSummary(security["evaluate"], "run JavaScript in a specific tab"),
"POST /macro": endpointStatusSummary(security["macro"], "run macro steps with single request"),
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index e88ad581..62c219fb 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -180,7 +180,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
}
// Create a blank tab first so the requested URL becomes the first
// real history entry.
- hashTabID, newCtx, _, err := h.Bridge.CreateTab("")
+ newTabID, newCtx, _, err := h.Bridge.CreateTab("")
if err != nil {
httpx.Error(w, 500, fmt.Errorf("new tab: %w", err))
return
@@ -214,10 +214,10 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
var url string
_ = chromedp.Run(tCtx, chromedp.Location(&url))
title, _ := bridge.WaitForTitle(tCtx, titleWait)
- h.recordResolvedTab(r, hashTabID)
+ h.recordResolvedTab(r, newTabID)
h.recordResolvedURL(r, url)
- httpx.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": url, "title": title})
+ httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": url, "title": title})
return
}
@@ -381,7 +381,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
case tabActionNew:
// Create a blank tab first so the requested URL becomes the first
// real history entry.
- hashTabID, ctx, _, err := h.Bridge.CreateTab("")
+ newTabID, ctx, _, err := h.Bridge.CreateTab("")
if err != nil {
httpx.Error(w, 500, err)
return
@@ -391,7 +391,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
tCtx, tCancel := context.WithTimeout(ctx, h.Config.NavigateTimeout)
defer tCancel()
if err := bridge.NavigatePageWithRedirectLimit(tCtx, req.URL, h.Config.MaxRedirects); err != nil {
- _ = h.Bridge.CloseTab(hashTabID)
+ _ = h.Bridge.CloseTab(newTabID)
code := 500
if errors.Is(err, bridge.ErrTooManyRedirects) {
code = 422
@@ -404,7 +404,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
var curURL, title string
_ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))
- httpx.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": curURL, "title": title})
+ httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": curURL, "title": title})
case tabActionClose:
if req.TabID == "" {
diff --git a/internal/handlers/proxy_ws.go b/internal/handlers/proxy_ws.go
index f91579fc..f2f8c0c5 100644
--- a/internal/handlers/proxy_ws.go
+++ b/internal/handlers/proxy_ws.go
@@ -10,6 +10,8 @@ import (
"net/http"
"net/textproto"
"net/url"
+
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
)
// ProxyWebSocket tunnels WebSocket connections with proper HTTP headers
@@ -17,7 +19,7 @@ func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
parsed, err := url.Parse(targetURL)
if err != nil {
http.Error(w, "invalid backend target", http.StatusBadGateway)
- slog.Error("ws proxy: invalid target", "target", targetURL, "err", err)
+ slog.Error("ws proxy: invalid target", "target", internalurls.RedactForLog(targetURL), "err", err)
return
}
diff --git a/internal/idpi/domain.go b/internal/idpi/domain.go
index dc7543f3..1dd545a7 100644
--- a/internal/idpi/domain.go
+++ b/internal/idpi/domain.go
@@ -24,6 +24,9 @@ func CheckDomain(rawURL string, cfg config.IDPIConfig) CheckResult {
if !cfg.Enabled || len(cfg.AllowedDomains) == 0 {
return CheckResult{}
}
+ if isAllowedSpecialURL(rawURL) {
+ return CheckResult{}
+ }
host := extractHost(rawURL)
if host == "" {
@@ -48,6 +51,10 @@ func CheckDomain(rawURL string, cfg config.IDPIConfig) CheckResult {
fmt.Sprintf("domain %q is not in the allowed list (security.idpi.allowedDomains)", host))
}
+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").
diff --git a/internal/idpi/idpi_test.go b/internal/idpi/idpi_test.go
index 4d26a22c..f1837f41 100644
--- a/internal/idpi/idpi_test.go
+++ b/internal/idpi/idpi_test.go
@@ -175,19 +175,29 @@ func TestCheckDomain_ReasonContainsDomain(t *testing.T) {
}
}
-// TestCheckDomain_FileURLBlockedByWhitelist verifies that file:// and similar
-// scheme-only URLs (which have no domain component) are treated as a threat
-// when a whitelist is active. Silently allowing them would be a security bypass.
-func TestCheckDomain_FileURLBlockedByWhitelist(t *testing.T) {
+// TestCheckDomain_NoHostURLHandling verifies that only explicitly allowed
+// special URLs bypass the whitelist; other no-host URLs remain blocked.
+func TestCheckDomain_NoHostURLHandling(t *testing.T) {
cfg := enabledCfg(func(c *config.IDPIConfig) {
c.AllowedDomains = []string{"example.com"}
})
- noHostURLs := []string{
- "file:///etc/passwd",
+ allowedNoHostURLs := []string{
"about:blank",
+ " ABOUT:BLANK ",
+ }
+ for _, u := range allowedNoHostURLs {
+ r := CheckDomain(u, cfg)
+ if r.Threat {
+ t.Errorf("URL %q should be explicitly allowed despite having no domain", u)
+ }
+ }
+
+ blockedNoHostURLs := []string{
+ "file:///etc/passwd",
"about:srcdoc",
+ "data:text/html,<h1>x</h1>",
}
- for _, u := range noHostURLs {
+ for _, u := range blockedNoHostURLs {
r := CheckDomain(u, cfg)
if !r.Threat {
t.Errorf("URL %q has no domain and active whitelist — must be treated as a threat", u)
diff --git a/internal/ids/ids.go b/internal/ids/ids.go
index c1c0f3ff..c5e74733 100644
--- a/internal/ids/ids.go
+++ b/internal/ids/ids.go
@@ -7,7 +7,8 @@ import (
"time"
)
-// Manager generates stable hash-based IDs for profiles, instances, and tabs
+// Manager generates stable hash-based IDs for profiles and instances.
+// Runtime tab IDs use raw CDP target IDs via TabIDFromCDPTarget.
type Manager struct{}
// NewManager creates a new ID manager
@@ -29,9 +30,8 @@ func (m *Manager) InstanceID(profileID, instanceName string) string {
return hashID("inst", data)
}
-// TabID generates a stable hash-based ID for a tab within an instance
-// Uses instance ID and tab number for uniqueness
-// Format: tab_XXXXXXXX (12 chars total)
+// TabID generates a synthetic hash-based ID for callers that need one.
+// Runtime browser tab routing uses raw CDP target IDs via TabIDFromCDPTarget.
func (m *Manager) TabID(instanceID string, tabIndex int) string {
data := fmt.Sprintf("%s:%d", instanceID, tabIndex)
return hashID("tab", data)
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index ef55ee77..1a7959b0 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -22,6 +22,7 @@ import (
"github.com/pinchtab/pinchtab/internal/ids"
"github.com/pinchtab/pinchtab/internal/instance"
"github.com/pinchtab/pinchtab/internal/profiles"
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
)
// InstanceEvent is emitted when instance state changes.
@@ -425,7 +426,7 @@ func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
return nil, err
}
- slog.Info("attached to external Chrome", "id", inst.ID, "name", name, "cdpUrl", cdpURL)
+ slog.Info("attached to external Chrome", "id", inst.ID, "name", name, "cdpUrl", internalurls.RedactForLog(cdpURL))
// Emit event
o.emitEvent("instance.attached", inst)
@@ -443,7 +444,7 @@ func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instan
return nil, err
}
- slog.Info("attached to external bridge", "id", inst.ID, "name", name, "url", inst.URL)
+ slog.Info("attached to external bridge", "id", inst.ID, "name", name, "url", internalurls.RedactForLog(inst.URL))
o.emitEvent("instance.attached", inst)
return inst, nil
}
diff --git a/internal/scheduler/webhook.go b/internal/scheduler/webhook.go
index 79910fda..c19dd8c7 100644
--- a/internal/scheduler/webhook.go
+++ b/internal/scheduler/webhook.go
@@ -10,6 +10,8 @@ import (
"net"
"net/http"
"time"
+
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
)
var errNoValidatedWebhookIPs = errors.New("no validated callback IPs")
@@ -52,10 +54,11 @@ func sendWebhook(callbackURL string, t *Task) {
if callbackURL == "" {
return
}
+ logURL := internalurls.RedactForLog(callbackURL)
target, err := validateCallbackTarget(callbackURL)
if err != nil {
- slog.Warn("webhook: callback rejected", "task", t.ID, "url", callbackURL, "err", err)
+ slog.Warn("webhook: callback rejected", "task", t.ID, "url", logURL, "err", err)
return
}
@@ -82,7 +85,7 @@ func sendWebhook(callbackURL string, t *Task) {
resp, err := client.Do(req)
if err != nil {
- slog.Warn("webhook: delivery failed", "task", t.ID, "url", callbackURL, "err", err)
+ slog.Warn("webhook: delivery failed", "task", t.ID, "url", logURL, "err", err)
return
}
// Drain body so the underlying connection can be reused.
@@ -90,9 +93,9 @@ func sendWebhook(callbackURL string, t *Task) {
_ = resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- slog.Warn("webhook: non-success response", "task", t.ID, "url", callbackURL, "status", resp.StatusCode)
+ slog.Warn("webhook: non-success response", "task", t.ID, "url", logURL, "status", resp.StatusCode)
return
}
- slog.Info("webhook: delivered", "task", t.ID, "url", callbackURL, "status", resp.StatusCode)
+ slog.Info("webhook: delivered", "task", t.ID, "url", logURL, "status", resp.StatusCode)
}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index 3ee913f4..0dc33e49 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -177,6 +177,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
shorthandRoutes := []string{
"GET /snapshot", "GET /screenshot", "GET /text", "GET /pdf", "POST /pdf",
+ "GET /console", "POST /console/clear",
+ "GET /errors", "POST /errors/clear",
"POST /navigate", "POST /back", "POST /forward", "POST /reload",
"POST /action", "POST /actions",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index c2261808..b344801b 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -43,6 +43,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// Shorthand endpoints proxy to first running instance.
shorthandRoutes := []string{
"GET /snapshot", "GET /screenshot", "GET /text", "GET /pdf", "POST /pdf",
+ "GET /console", "POST /console/clear",
+ "GET /errors", "POST /errors/clear",
"POST /navigate", "POST /back", "POST /forward", "POST /reload",
"POST /action", "POST /actions",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index 1f0cc56d..b1144f16 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -51,6 +51,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// Shorthand endpoints — all proxy to first running instance.
shorthandRoutes := []string{
"GET /snapshot", "GET /screenshot", "GET /text", "GET /pdf", "POST /pdf",
+ "GET /console", "POST /console/clear",
+ "GET /errors", "POST /errors/clear",
"POST /navigate", "POST /back", "POST /forward", "POST /reload",
"POST /action", "POST /actions",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
diff --git a/internal/strategy/simple/simple_test.go b/internal/strategy/simple/simple_test.go
index bc882204..b6479c08 100644
--- a/internal/strategy/simple/simple_test.go
+++ b/internal/strategy/simple/simple_test.go
@@ -129,3 +129,33 @@ func TestStrategy_RegisterRoutes_LocksSensitiveShorthandRoutes(t *testing.T) {
t.Fatalf("expected lock response to mention security.allowEvaluate, got %s", rec.Body.String())
}
}
+
+func TestStrategy_RegisterRoutes_RegistersConsoleAndErrorShorthands(t *testing.T) {
+ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ orch.ApplyRuntimeConfig(&config.RuntimeConfig{})
+
+ s := &Strategy{orch: orch}
+ mux := http.NewServeMux()
+ s.RegisterRoutes(mux)
+
+ tests := []struct {
+ method string
+ path string
+ route string
+ }{
+ {method: http.MethodGet, path: "/console", route: "GET /console"},
+ {method: http.MethodPost, path: "/console/clear", route: "POST /console/clear"},
+ {method: http.MethodGet, path: "/errors", route: "GET /errors"},
+ {method: http.MethodPost, path: "/errors/clear", route: "POST /errors/clear"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.method+" "+tt.path, func(t *testing.T) {
+ req := httptest.NewRequest(tt.method, tt.path, nil)
+ _, pattern := mux.Handler(req)
+ if pattern != tt.route {
+ t.Fatalf("expected route %q, got %q", tt.route, pattern)
+ }
+ })
+ }
+}
diff --git a/internal/urls/log_redact.go b/internal/urls/log_redact.go
new file mode 100644
index 00000000..fa263b0c
--- /dev/null
+++ b/internal/urls/log_redact.go
@@ -0,0 +1,77 @@
+package urls
+
+import (
+ "net"
+ "net/url"
+ "strings"
+)
+
+const (
+ maxLogURLBytes = 512
+ logTruncateSuffix = "..."
+)
+
+// RedactForLog normalizes a URL for logs and strips sensitive components.
+// It removes userinfo, query, and fragment and caps the final string length.
+// Invalid inputs return an empty string rather than echoing raw potentially
+// sensitive data back into logs.
+func RedactForLog(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+
+ normalized, err := Sanitize(raw)
+ if err != nil {
+ normalized = raw
+ }
+
+ parsed, err := url.Parse(normalized)
+ if err != nil {
+ return ""
+ }
+ if parsed.Scheme == "" && parsed.Host == "" && parsed.Opaque == "" {
+ return ""
+ }
+
+ parsed.User = nil
+ parsed.RawQuery = ""
+ parsed.Fragment = ""
+ parsed.ForceQuery = false
+
+ if parsed.Host != "" {
+ host := strings.ToLower(parsed.Hostname())
+ if port := parsed.Port(); port != "" {
+ parsed.Host = net.JoinHostPort(host, port)
+ } else {
+ parsed.Host = host
+ }
+ }
+
+ return truncateForLog(parsed.String(), maxLogURLBytes)
+}
+
+func truncateForLog(s string, maxBytes int) string {
+ if maxBytes <= 0 {
+ return ""
+ }
+ if len(s) <= maxBytes {
+ return s
+ }
+ if maxBytes <= len(logTruncateSuffix) {
+ return logTruncateSuffix[:maxBytes]
+ }
+
+ limit := maxBytes - len(logTruncateSuffix)
+ cut := 0
+ for i := range s {
+ if i > limit {
+ break
+ }
+ cut = i
+ }
+ if cut == 0 && limit > 0 {
+ return logTruncateSuffix
+ }
+ return s[:cut] + logTruncateSuffix
+}
diff --git a/internal/urls/urls_test.go b/internal/urls/urls_test.go
index c881f56e..d45915db 100644
--- a/internal/urls/urls_test.go
+++ b/internal/urls/urls_test.go
@@ -124,3 +124,24 @@ func TestSanitize_BrowserURLs(t *testing.T) {
}
}
}
+
+func TestRedactForLog(t *testing.T) {
+ tests := []struct {
+ input string
+ expected string
+ }{
+ {"https://user:[email protected]:8443/callback?code=secret#done", "https://example.com:8443/callback"},
+ {"example.com/path?q=1", "https://example.com/path"},
+ {"about:blank#frag", "about:blank"},
+ {"", ""},
+ {"://bad-url", ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ if got := RedactForLog(tt.input); got != tt.expected {
+ t.Fatalf("RedactForLog(%q) = %q, want %q", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
diff --git a/scripts/doctor.sh b/scripts/doctor.sh
index f3681f99..8dd53653 100755
--- a/scripts/doctor.sh
+++ b/scripts/doctor.sh
@@ -15,6 +15,8 @@ NC='\033[0m'
CRITICAL=0
WARNINGS=0
BUN_MIN_VERSION="1.2.0"
+ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+TOOLS_BIN="$ROOT_DIR/.tools/bin"
# ── Helpers ──────────────────────────────────────────────────────────
@@ -126,6 +128,36 @@ else
fi
fi
+# ── gotestsum ────────────────────────────────────────────────────────
+
+mkdir -p "$TOOLS_BIN"
+
+GOTESTSUM=""
+if command -v gotestsum &>/dev/null; then
+ GOTESTSUM="gotestsum"
+elif [ -x "$TOOLS_BIN/gotestsum" ]; then
+ GOTESTSUM="$TOOLS_BIN/gotestsum"
+elif [ -x "${GOPATH:-$HOME/go}/bin/gotestsum" ]; then
+ GOTESTSUM="${GOPATH:-$HOME/go}/bin/gotestsum"
+fi
+
+if [ -n "$GOTESTSUM" ]; then
+ GOTESTSUM_VERSION=$($GOTESTSUM --version 2>/dev/null | head -1)
+ if [ -n "$GOTESTSUM_VERSION" ]; then
+ ok "$GOTESTSUM_VERSION"
+ else
+ ok "gotestsum"
+ fi
+else
+ warn "gotestsum not found" "Recommended — used by ./dev test unit for cleaner package-oriented output."
+ if command -v go &>/dev/null && confirm "Install gotestsum via go install?"; then
+ GOBIN="$TOOLS_BIN" go install gotest.tools/gotestsum@latest && ok "gotestsum installed in .tools/bin" && WARNINGS=$((WARNINGS - 1))
+ else
+ hint "GOBIN=\"$TOOLS_BIN\" go install gotest.tools/gotestsum@latest"
+ hint "go install gotest.tools/gotestsum@latest"
+ fi
+fi
+
# ── Git hooks ────────────────────────────────────────────────────────
if [ -f ".git/hooks/pre-commit" ]; then
diff --git a/scripts/e2e.sh b/scripts/e2e.sh
index 39531a83..789c458f 100644
--- a/scripts/e2e.sh
+++ b/scripts/e2e.sh
@@ -9,6 +9,7 @@ MUTED=$'\033[38;2;90;100;128m'
SUCCESS=$'\033[38;2;0;229;204m'
ERROR=$'\033[38;2;230;57;70m'
NC=$'\033[0m'
+E2E_FILTER="${2:-}"
build_e2e_cli_binary() {
echo " ${MUTED}Building static binary for E2E CLI tests...${NC}"
@@ -101,10 +102,17 @@ run_api_fast() {
local progress_file="tests/e2e/results/progress-api-fast.log"
local log_prefix="logs-api-fast"
echo " ${ACCENT}${BOLD}🐳 E2E API Fast tests (Docker)${NC}"
+ if [ -n "${E2E_FILTER}" ]; then
+ echo " ${MUTED}filter: ${E2E_FILTER}${NC}"
+ fi
echo ""
prepare_suite_results "${summary_file}" "${report_file}" "${progress_file}" "${log_prefix}"
set +e
- docker compose -f "${compose_file}" run --build --rm runner-api /bin/bash /e2e/run.sh api
+ if [ -n "${E2E_FILTER}" ]; then
+ docker compose -f "${compose_file}" run --build --rm runner-api /bin/bash /e2e/run.sh api "filter=${E2E_FILTER}"
+ else
+ docker compose -f "${compose_file}" run --build --rm runner-api /bin/bash /e2e/run.sh api
+ fi
local api_fast_exit=$?
set -e
if [ "${api_fast_exit}" -ne 0 ]; then
@@ -122,10 +130,13 @@ run_full_api() {
local progress_file="tests/e2e/results/progress-api-full.log"
local log_prefix="logs-api-full"
echo " ${ACCENT}${BOLD}🐳 E2E Full API tests (Docker)${NC}"
+ if [ -n "${E2E_FILTER}" ]; then
+ echo " ${MUTED}filter: ${E2E_FILTER}${NC}"
+ fi
echo ""
prepare_suite_results "${summary_file}" "${report_file}" "${progress_file}" "${log_prefix}"
set +e
- docker compose -f "${compose_file}" up --build --abort-on-container-exit --exit-code-from runner-api runner-api
+ E2E_SCENARIO_FILTER="${E2E_FILTER}" docker compose -f "${compose_file}" up --build --abort-on-container-exit --exit-code-from runner-api runner-api
local api_exit=$?
set -e
if [ "${api_exit}" -ne 0 ]; then
@@ -143,11 +154,18 @@ run_cli_fast() {
local progress_file="tests/e2e/results/progress-cli-fast.log"
local log_prefix="logs-cli-fast"
echo " ${ACCENT}${BOLD}🐳 E2E CLI Fast tests (Docker)${NC}"
+ if [ -n "${E2E_FILTER}" ]; then
+ echo " ${MUTED}filter: ${E2E_FILTER}${NC}"
+ fi
echo ""
build_e2e_cli_binary
prepare_suite_results "${summary_file}" "${report_file}" "${progress_file}" "${log_prefix}"
set +e
- docker compose -f "${compose_file}" run --build --rm runner-cli /bin/bash /e2e/run.sh cli
+ if [ -n "${E2E_FILTER}" ]; then
+ docker compose -f "${compose_file}" run --build --rm runner-cli /bin/bash /e2e/run.sh cli "filter=${E2E_FILTER}"
+ else
+ docker compose -f "${compose_file}" run --build --rm runner-cli /bin/bash /e2e/run.sh cli
+ fi
local cli_fast_exit=$?
set -e
if [ "${cli_fast_exit}" -ne 0 ]; then
@@ -165,11 +183,14 @@ run_full_cli() {
local progress_file="tests/e2e/results/progress-cli-full.log"
local log_prefix="logs-cli-full"
echo " ${ACCENT}${BOLD}🐳 E2E Full CLI tests (Docker)${NC}"
+ if [ -n "${E2E_FILTER}" ]; then
+ echo " ${MUTED}filter: ${E2E_FILTER}${NC}"
+ fi
echo ""
build_e2e_cli_binary
prepare_suite_results "${summary_file}" "${report_file}" "${progress_file}" "${log_prefix}"
set +e
- docker compose -f "${compose_file}" up --build --abort-on-container-exit --exit-code-from runner-cli runner-cli
+ E2E_SCENARIO_FILTER="${E2E_FILTER}" docker compose -f "${compose_file}" up --build --abort-on-container-exit --exit-code-from runner-cli runner-cli
local cli_exit=$?
set -e
if [ "${cli_exit}" -ne 0 ]; then
diff --git a/scripts/test.sh b/scripts/test.sh
index 05f07963..17199104 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -6,6 +6,7 @@ set -e
# Default: all
cd "$(dirname "$0")/.."
+TOOLS_BIN="$(pwd)/.tools/bin"
BOLD=$'\033[1m'
ACCENT=$'\033[38;2;251;191;36m'
@@ -24,6 +25,40 @@ section() {
echo -e " ${ACCENT}${BOLD}$1${NC}"
}
+format_elapsed() {
+ local elapsed="$1"
+ if [ -z "$elapsed" ]; then
+ return
+ fi
+ printf "%.3f" "$elapsed"
+}
+
+resolve_gotestsum() {
+ if command -v gotestsum >/dev/null 2>&1; then
+ command -v gotestsum
+ return 0
+ fi
+ if [ -x "$TOOLS_BIN/gotestsum" ]; then
+ echo "$TOOLS_BIN/gotestsum"
+ return 0
+ fi
+ if command -v go >/dev/null 2>&1; then
+ local gobin
+ gobin="$(go env GOBIN 2>/dev/null)"
+ if [ -n "$gobin" ] && [ -x "$gobin/gotestsum" ]; then
+ echo "$gobin/gotestsum"
+ return 0
+ fi
+ local gopath
+ gopath="$(go env GOPATH 2>/dev/null)"
+ if [ -n "$gopath" ] && [ -x "$gopath/bin/gotestsum" ]; then
+ echo "$gopath/bin/gotestsum"
+ return 0
+ fi
+ fi
+ return 1
+}
+
# Parse gotestsum JSON and print summary
test_summary() {
local json_file="$1"
@@ -102,6 +137,7 @@ test_summary() {
echo -e " ${ERROR}Failed tests:${NC}"
jq -r 'select(.Test != null and .Action == "fail") | " ✗ \(.Test)"' "$json_file" | sort -u
fi
+
}
# Live progress for go test -json streams
@@ -141,13 +177,42 @@ run_go_test_json() {
fi
}
- go test -json "$@" 2>&1 | tee "$json_file" | while IFS= read -r line; do
- local action test_name package_name elapsed output_text
- action=$(echo "$line" | jq -r '.Action // empty' 2>/dev/null) || continue
- test_name=$(echo "$line" | jq -r '.Test // empty' 2>/dev/null) || continue
- package_name=$(echo "$line" | jq -r '.Package // empty' 2>/dev/null) || continue
- elapsed=$(echo "$line" | jq -r '.Elapsed // empty' 2>/dev/null)
- output_text=$(echo "$line" | jq -r '.Output // empty' 2>/dev/null)
+ print_package_line() {
+ local pkg_action="$1"
+ local package_name="$2"
+ local elapsed="$3"
+ local status_label="${SUCCESS}PASS${NC}"
+ local elapsed_display=""
+
+ if [ "$pkg_action" = "fail" ]; then
+ status_label="${ERROR}FAIL${NC}"
+ elif [ "$pkg_action" = "skip" ]; then
+ status_label="${ACCENT}SKIP${NC}"
+ fi
+ if [ -n "$elapsed" ]; then
+ elapsed_display="$(format_elapsed "$elapsed")"
+ fi
+
+ clear_progress_line
+ if [ -n "$elapsed_display" ]; then
+ printf " %b ${MUTED}package${NC} %s ${MUTED}%6ss${NC}\n" "$status_label" "$package_name" "$elapsed_display"
+ else
+ printf " %b ${MUTED}package${NC} %s\n" "$status_label" "$package_name"
+ fi
+ }
+
+ go test -json "$@" 2>&1 \
+ | tee "$json_file" \
+ | jq -r --unbuffered '
+ [
+ (.Action // ""),
+ (.Test // ""),
+ (.Package // ""),
+ ((.Elapsed // "") | tostring),
+ ((.Output // "") | gsub("\r?\n$"; ""))
+ ] | @tsv
+ ' \
+ | while IFS=$'\t' read -r action test_name package_name elapsed output_text; do
if [ -z "$test_name" ]; then
case "$action" in
@@ -162,7 +227,7 @@ run_go_test_json() {
fi
;;
output)
- if [ -n "$output_text" ] && [[ "$output_text" =~ ^panic:|^FAIL[[:space:]]|^---[[:space:]]FAIL ]]; then
+ if [ -n "$output_text" ] && [[ "$output_text" =~ ^panic:|^---[[:space:]]FAIL ]]; then
if ! $interactive; then
output_text=${output_text%$'\n'}
printf " %s\n" "$output_text"
@@ -170,40 +235,33 @@ run_go_test_json() {
fi
;;
pass)
- if [ -n "$package_name" ] && $interactive; then
- render_progress "${SUCCESS}${package_name}${NC}"
+ if [ -n "$package_name" ]; then
+ print_package_line "$action" "$package_name" "$elapsed"
fi
;;
fail)
if [ -n "$package_name" ]; then
- if $interactive; then
- render_progress "${ERROR}${package_name}${NC}"
- else
- if [ -n "$elapsed" ]; then
- printf " ${ERROR}✗${NC} ${MUTED}package${NC} %s ${MUTED}%6ss${NC}\n" "$package_name" "$elapsed"
- else
- printf " ${ERROR}✗${NC} ${MUTED}package${NC} %s\n" "$package_name"
- fi
- fi
+ print_package_line "$action" "$package_name" "$elapsed"
+ fi
+ ;;
+ skip)
+ if [ -n "$package_name" ]; then
+ print_package_line "$action" "$package_name" "$elapsed"
fi
;;
esac
continue
fi
- local display="$test_name"
local top_level="$test_name"
if [[ "$top_level" == *"/"* ]]; then
top_level="${top_level%%/*}"
fi
- if [ ${#display} -gt $max_len ]; then
- display="${display:0:$((max_len - 1))}…"
- fi
case "$action" in
run)
if $interactive; then
- render_progress "${current_package} ${MUTED}${display}${NC}"
+ render_progress "${MUTED}${current_package}${NC}"
fi ;;
pass)
if ! grep -Fq "$package_name $top_level" "$status_file"; then
@@ -212,7 +270,7 @@ run_go_test_json() {
passed=$((passed + 1))
fi
if $interactive; then
- render_progress "${current_package} ${SUCCESS}${display}${NC}"
+ render_progress "${MUTED}${current_package}${NC}"
fi ;;
fail)
if ! grep -Fq "$package_name $top_level" "$status_file"; then
@@ -221,13 +279,7 @@ run_go_test_json() {
failed=$((failed + 1))
fi
if $interactive; then
- render_progress "${current_package} ${ERROR}${display}${NC}"
- else
- if [ -n "$elapsed" ]; then
- printf " ${ERROR}✗${NC} ${MUTED}[%2d]${NC} %-${max_len}s ${MUTED}%6ss${NC}\n" "$completed" "$display" "$elapsed"
- else
- printf " ${ERROR}✗${NC} ${MUTED}[%2d]${NC} %-${max_len}s\n" "$completed" "$display"
- fi
+ render_progress "${MUTED}${current_package}${NC}"
fi ;;
skip)
if ! grep -Fq "$package_name $top_level" "$status_file"; then
@@ -236,7 +288,7 @@ run_go_test_json() {
skipped=$((skipped + 1))
fi
if $interactive; then
- render_progress "${current_package} ${ACCENT}${display}${NC}"
+ render_progress "${MUTED}${current_package}${NC}"
fi ;;
esac
done
@@ -255,14 +307,31 @@ if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "unit" ]; then
section "test:🔬:go unit"
UNIT_JSON="$TMPDIR_TEST/unit.json"
+ GOTESTSUM_BIN=""
+ if GOTESTSUM_BIN="$(resolve_gotestsum)"; then
+ :
+ else
+ GOTESTSUM_BIN=""
+ fi
- if ! run_go_test_json "$UNIT_JSON" "unit" -p 1 -count=1 ./...; then
- fail "test:🔬:go unit"
+ if [ -n "$GOTESTSUM_BIN" ]; then
+ if ! "$GOTESTSUM_BIN" --format=pkgname --hide-summary=output --jsonfile "$UNIT_JSON" -- -p 1 -count=1 ./...; then
+ fail "test:🔬:go unit"
+ exit 1
+ fi
+ else
+ echo -e " ${MUTED}gotestsum not found; using built-in formatter${NC}"
+ echo -e " ${MUTED}Install: go install gotest.tools/gotestsum@latest${NC}"
+ echo -e " ${MUTED}Or run: ./dev doctor${NC}"
+ echo ""
+ if ! run_go_test_json "$UNIT_JSON" "unit" -p 1 -count=1 ./...; then
+ fail "test:🔬:go unit"
+ test_summary "$UNIT_JSON" "Unit Test Results"
+ exit 1
+ fi
test_summary "$UNIT_JSON" "Unit Test Results"
- exit 1
fi
ok "test:🔬:go unit"
- test_summary "$UNIT_JSON" "Unit Test Results"
fi
# ── Dashboard ────────────────────────────────────────────────────────
diff --git a/tests/e2e/config/pinchtab-bridge.json b/tests/e2e/config/pinchtab-bridge.json
index c8e18c48..362f8908 100644
--- a/tests/e2e/config/pinchtab-bridge.json
+++ b/tests/e2e/config/pinchtab-bridge.json
@@ -10,6 +10,15 @@
"security": {
"allowEvaluate": false,
"allowDownload": false,
- "allowUpload": false
+ "allowUpload": false,
+ "idpi": {
+ "enabled": true,
+ "allowedDomains": [
+ "localhost",
+ "127.0.0.1",
+ "::1",
+ "fixtures"
+ ]
+ }
}
}
diff --git a/tests/e2e/config/pinchtab-full-permissive.json b/tests/e2e/config/pinchtab-full-permissive.json
index ef4e19f1..bc258689 100644
--- a/tests/e2e/config/pinchtab-full-permissive.json
+++ b/tests/e2e/config/pinchtab-full-permissive.json
@@ -56,12 +56,14 @@
},
"idpi": {
"enabled": true,
+ "strictMode": false,
"scanContent": true,
"allowedDomains": [
"localhost",
"127.0.0.1",
"::1",
- "fixtures"
+ "fixtures",
+ "httpbin.org"
]
}
}
diff --git a/tests/e2e/config/pinchtab-medium-permissive.json b/tests/e2e/config/pinchtab-medium-permissive.json
index b592e3cc..d5b11a49 100644
--- a/tests/e2e/config/pinchtab-medium-permissive.json
+++ b/tests/e2e/config/pinchtab-medium-permissive.json
@@ -55,12 +55,14 @@
},
"idpi": {
"enabled": true,
+ "strictMode": false,
"scanContent": true,
"allowedDomains": [
"localhost",
"127.0.0.1",
"::1",
- "fixtures"
+ "fixtures",
+ "httpbin.org"
]
}
}
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index 905139b8..836df953 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -55,12 +55,14 @@
},
"idpi": {
"enabled": true,
+ "strictMode": false,
"scanContent": true,
"allowedDomains": [
"localhost",
"127.0.0.1",
"::1",
- "fixtures"
+ "fixtures",
+ "httpbin.org"
]
}
}
diff --git a/tests/e2e/docker-compose-multi.yml b/tests/e2e/docker-compose-multi.yml
index 40ba7061..ae746518 100644
--- a/tests/e2e/docker-compose-multi.yml
+++ b/tests/e2e/docker-compose-multi.yml
@@ -4,11 +4,12 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab.json
volumes:
- - ./config/pinchtab.json:/config/pinchtab.json:ro
+ - ./config/pinchtab.json:/fixture-config/pinchtab.json:ro
- ./fixtures/test-extension:/extensions/test-extension
- ./fixtures/test-extension-api:/extensions/test-extension-api
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
ports:
- "9999:9999"
shm_size: '2gb'
@@ -24,9 +25,10 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab-secure.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab-secure.json
volumes:
- - ./config/pinchtab-secure.json:/config/pinchtab-secure.json:ro
+ - ./config/pinchtab-secure.json:/fixture-config/pinchtab-secure.json:ro
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-secure.json /data/e2e-config/pinchtab-secure.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
ports:
- "9998:9999"
shm_size: '2gb'
@@ -42,10 +44,11 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab-medium-permissive.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab-medium-permissive.json
volumes:
- - ./config/pinchtab-medium-permissive.json:/config/pinchtab-medium-permissive.json:ro
+ - ./config/pinchtab-medium-permissive.json:/fixture-config/pinchtab-medium-permissive.json:ro
- ./fixtures/test-extension:/extensions/test-extension
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-medium-permissive.json /data/e2e-config/pinchtab-medium-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
ports:
- "9994:9999"
shm_size: '2gb'
@@ -61,10 +64,11 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab-full-permissive.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab-full-permissive.json
volumes:
- - ./config/pinchtab-full-permissive.json:/config/pinchtab-full-permissive.json:ro
+ - ./config/pinchtab-full-permissive.json:/fixture-config/pinchtab-full-permissive.json:ro
- ./fixtures/test-extension:/extensions/test-extension
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-full-permissive.json /data/e2e-config/pinchtab-full-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
ports:
- "9995:9999"
shm_size: '2gb'
@@ -80,12 +84,12 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab-lite.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab-lite.json
volumes:
- - ./config/pinchtab-lite.json:/config/pinchtab-lite.json:ro
+ - ./config/pinchtab-lite.json:/fixture-config/pinchtab-lite.json:ro
ports:
- "9997:9999"
- command: ["/usr/local/bin/pinchtab", "bridge"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-lite.json /data/e2e-config/pinchtab-lite.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab bridge"]
healthcheck:
test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]
interval: 3s
@@ -98,12 +102,12 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab-bridge.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab-bridge.json
volumes:
- - ./config/pinchtab-bridge.json:/config/pinchtab-bridge.json:ro
+ - ./config/pinchtab-bridge.json:/fixture-config/pinchtab-bridge.json:ro
ports:
- "9996:9999"
- command: ["/usr/local/bin/pinchtab", "bridge"]
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-bridge.json /data/e2e-config/pinchtab-bridge.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab bridge"]
shm_size: '2gb'
healthcheck:
test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-bridge-token' -q -O /dev/null http://localhost:9999/health"]
@@ -150,7 +154,8 @@ services:
- E2E_BRIDGE_URL=http://pinchtab-bridge:9999
- E2E_BRIDGE_TOKEN=e2e-bridge-token
- FIXTURES_URL=http://fixtures:80
+ - E2E_SCENARIO_FILTER
volumes:
- ./:/e2e:ro
- ./results:/results
- command: ["/bin/bash", "/e2e/run.sh", "api", "all=true"]
+ command: ["/bin/bash", "-lc", "if [ -n \"${E2E_SCENARIO_FILTER:-}\" ]; then exec /bin/bash /e2e/run.sh api all=true \"filter=${E2E_SCENARIO_FILTER}\"; else exec /bin/bash /e2e/run.sh api all=true; fi"]
diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml
index 294118f6..3f75804b 100644
--- a/tests/e2e/docker-compose.yml
+++ b/tests/e2e/docker-compose.yml
@@ -4,11 +4,12 @@ services:
context: ../..
dockerfile: Dockerfile
environment:
- PINCHTAB_CONFIG: /config/pinchtab.json
+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab.json
volumes:
- - ./config/pinchtab.json:/config/pinchtab.json:ro
+ - ./config/pinchtab.json:/fixture-config/pinchtab.json:ro
- ./fixtures/test-extension:/extensions/test-extension:ro
- ./fixtures/test-extension-api:/extensions/test-extension-api:ro
+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]
ports:
- "9999:9999"
shm_size: '2gb'
@@ -41,10 +42,11 @@ services:
- E2E_SERVER=http://pinchtab:9999
- E2E_SERVER_TOKEN=e2e-token
- FIXTURES_URL=http://fixtures:80
+ - E2E_SCENARIO_FILTER
volumes:
- ./:/e2e:ro
- ./results:/results
- command: ["/bin/bash", "/e2e/run.sh", "api"]
+ command: ["/bin/bash", "-lc", "if [ -n \"${E2E_SCENARIO_FILTER:-}\" ]; then exec /bin/bash /e2e/run.sh api \"filter=${E2E_SCENARIO_FILTER}\"; else exec /bin/bash /e2e/run.sh api; fi"]
runner-cli:
build:
@@ -58,7 +60,8 @@ services:
- E2E_SERVER=http://pinchtab:9999
- E2E_SERVER_TOKEN=e2e-token
- FIXTURES_URL=http://fixtures:80
+ - E2E_SCENARIO_FILTER
volumes:
- ./:/e2e:ro
- ./results:/results
- command: ["/bin/bash", "/e2e/run.sh", "cli", "all=true"]
+ command: ["/bin/bash", "-lc", "if [ -n \"${E2E_SCENARIO_FILTER:-}\" ]; then exec /bin/bash /e2e/run.sh cli all=true \"filter=${E2E_SCENARIO_FILTER}\"; else exec /bin/bash /e2e/run.sh cli all=true; fi"]
diff --git a/tests/e2e/fixtures/console.html b/tests/e2e/fixtures/console.html
new file mode 100644
index 00000000..763ff31a
--- /dev/null
+++ b/tests/e2e/fixtures/console.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Console Test Page</title>
+</head>
+<body>
+ <h1>Console Test Page</h1>
+ <p>This page logs messages to the console for testing.</p>
+
+ <script>
+ // Log various console messages
+ console.log('Hello from console.log');
+ console.warn('Warning message');
+ console.info('Info message');
+ console.error('Error message from console.error');
+
+ // Log with multiple arguments
+ console.log('Multiple', 'arguments', 'test');
+
+ // Log object
+ console.log('Object:', { key: 'value', count: 42 });
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/fixtures/text-long.html b/tests/e2e/fixtures/text-long.html
new file mode 100644
index 00000000..78841d1a
--- /dev/null
+++ b/tests/e2e/fixtures/text-long.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>E2E Test - Long Text</title>
+</head>
+<body>
+ <main>
+ <h1>Long Text Fixture</h1>
+ <p>
+ This fixture exists specifically for maxChars truncation tests. It keeps a
+ deterministic block of readable prose so the text endpoint always has more
+ than enough content to exceed a small truncation threshold.
+ </p>
+ <p>
+ The browser test should not depend on incidental content from unrelated
+ pages like the home page or button demo. By using a dedicated fixture, the
+ assertion stays stable even if those other fixtures are edited later.
+ </p>
+ <p>
+ PinchTab should return a truncated response when maxChars is set to a
+ small value, and the API should mark that response with the truncated
+ flag. This paragraph intentionally adds more plain text so the result is
+ comfortably above the threshold used by the E2E scenario.
+ </p>
+ </main>
+</body>
+</html>
diff --git a/tests/e2e/helpers/base.sh b/tests/e2e/helpers/base.sh
index 4d2923df..5ad11c9f 100644
--- a/tests/e2e/helpers/base.sh
+++ b/tests/e2e/helpers/base.sh
@@ -23,6 +23,7 @@ FIXTURES_URL="${FIXTURES_URL:-http://localhost:8080}"
RESULTS_DIR="${RESULTS_DIR:-/results}"
CURRENT_TEST="${CURRENT_TEST:-}"
+CURRENT_SCENARIO_FILE="${CURRENT_SCENARIO_FILE:-}"
TESTS_PASSED="${TESTS_PASSED:-0}"
TESTS_FAILED="${TESTS_FAILED:-0}"
ASSERTIONS_PASSED="${ASSERTIONS_PASSED:-0}"
@@ -91,7 +92,11 @@ wait_for_instance_ready() {
}
start_test() {
- CURRENT_TEST="$1"
+ if [ -n "${CURRENT_SCENARIO_FILE}" ]; then
+ CURRENT_TEST="[${CURRENT_SCENARIO_FILE}] $1"
+ else
+ CURRENT_TEST="$1"
+ fi
TEST_START_TIME=$(get_time_ms)
echo -e "${BLUE}▶ ${CURRENT_TEST}${NC}"
}
diff --git a/tests/e2e/run.sh b/tests/e2e/run.sh
index aeaf17e6..68adc50c 100644
--- a/tests/e2e/run.sh
+++ b/tests/e2e/run.sh
@@ -38,11 +38,13 @@ case "$SUITE" in
;;
*)
echo "unknown suite: $SUITE" >&2
- echo "usage: /bin/bash tests/e2e/run.sh api|cli [all=true|all=false]" >&2
+ echo "usage: /bin/bash tests/e2e/run.sh api|cli [all=true|all=false] [filter=<substring>]" >&2
exit 1
;;
esac
+SCENARIO_FILTER="${E2E_SCENARIO_FILTER:-}"
+
for arg in "$@"; do
case "$arg" in
all=true)
@@ -51,9 +53,12 @@ for arg in "$@"; do
all=false)
RUN_ALL=false
;;
+ filter=*)
+ SCENARIO_FILTER="${arg#filter=}"
+ ;;
*)
echo "unknown argument: $arg" >&2
- echo "usage: /bin/bash tests/e2e/run.sh api|cli [all=true|all=false]" >&2
+ echo "usage: /bin/bash tests/e2e/run.sh api|cli [all=true|all=false] [filter=<substring>]" >&2
exit 1
;;
esac
@@ -94,6 +99,20 @@ if [ "$RUN_ALL" = "true" ]; then
done
fi
+if [ -n "$SCENARIO_FILTER" ]; then
+ FILTERED_GROUPS=()
+ for script_name in "${SCENARIO_GROUPS[@]}"; do
+ if [[ "${script_name}" == *"${SCENARIO_FILTER}"* ]]; then
+ FILTERED_GROUPS+=("${script_name}")
+ fi
+ done
+ SCENARIO_GROUPS=("${FILTERED_GROUPS[@]}")
+ if [ "${#SCENARIO_GROUPS[@]}" -eq 0 ]; then
+ echo "no scenario files matched filter: ${SCENARIO_FILTER}" >&2
+ exit 1
+ fi
+fi
+
if [ "$RUN_ALL" = "true" ]; then
SUITE_TITLE="$SUITE_TITLE_ALL"
SUMMARY_FILE="$SUMMARY_FILE_ALL"
@@ -118,6 +137,9 @@ if [ "$SUITE_KIND" = "api" ]; then
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "E2E_SERVER: ${E2E_SERVER}"
echo "FIXTURES_URL: ${FIXTURES_URL}"
+ if [ -n "$SCENARIO_FILTER" ]; then
+ echo "FILTER: ${SCENARIO_FILTER}"
+ fi
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
@@ -146,6 +168,9 @@ else
echo ""
echo " Server: $E2E_SERVER"
echo " Fixtures: $FIXTURES_URL"
+ if [ -n "$SCENARIO_FILTER" ]; then
+ echo " Filter: $SCENARIO_FILTER"
+ fi
echo ""
wait_for_instance_ready "$E2E_SERVER"
@@ -177,6 +202,7 @@ for script_name in "${SCENARIO_GROUPS[@]}"; do
echo -e "${YELLOW}Running: ${script_name}${NC}"
echo ""
+ CURRENT_SCENARIO_FILE="${script_name%.sh}"
source "${script_path}"
echo ""
diff --git a/tests/e2e/scenarios-api/auth-full.sh b/tests/e2e/scenarios-api/auth-full.sh
index c3779a88..de8e5d41 100644
--- a/tests/e2e/scenarios-api/auth-full.sh
+++ b/tests/e2e/scenarios-api/auth-full.sh
@@ -318,25 +318,6 @@ assert_contains "$RESULT" "missing_token" "session cookie no longer accepted"
end_test
-# ─────────────────────────────────────────────────────────────────
-start_test "auth: login attempts are rate limited"
-
-auth_reset_session
-
-for attempt in $(seq 1 10); do
- auth_post_json /api/auth/login '{"token":"wrong-token"}'
- assert_http_status 401 "bad login attempt ${attempt}"
- assert_contains "$RESULT" "bad_token" "bad token rejected on attempt ${attempt}"
-done
-
-auth_post_json /api/auth/login '{"token":"wrong-token"}'
-assert_http_status 429 "rate limit triggers after repeated failures"
-assert_contains "$RESULT" "login_rate_limited" "rate limit error code returned"
-assert_json_exists "$RESULT" ".details.retryAfterSec" "retry-after details returned"
-assert_auth_header_contains "Retry-After: " "retry-after header returned"
-
-end_test
-
# ─────────────────────────────────────────────────────────────────
start_test "auth: forwarded proxy headers ignored by default"
@@ -392,3 +373,29 @@ RESULT=$(echo "$RESULT" | head -n -1)
assert_http_status 200 "disable trustProxyHeaders"
end_test
+
+# ─────────────────────────────────────────────────────────────────
+# Keep this rate-limit scenario last in the file.
+#
+# It intentionally exhausts the shared login-attempt bucket for the runner's
+# client IP. auth_reset_session only clears cookies and headers; it does not
+# reset the server-side login limiter. Moving this block earlier will cause
+# subsequent auth/login scenarios from the same runner container to fail with
+# 429 before they exercise their intended assertions.
+start_test "auth: login attempts are rate limited"
+
+auth_reset_session
+
+for attempt in $(seq 1 10); do
+ auth_post_json /api/auth/login '{"token":"wrong-token"}'
+ assert_http_status 401 "bad login attempt ${attempt}"
+ assert_contains "$RESULT" "bad_token" "bad token rejected on attempt ${attempt}"
+done
+
+auth_post_json /api/auth/login '{"token":"wrong-token"}'
+assert_http_status 429 "rate limit triggers after repeated failures"
+assert_contains "$RESULT" "login_rate_limited" "rate limit error code returned"
+assert_json_exists "$RESULT" ".details.retryAfterSec" "retry-after details returned"
+assert_auth_header_contains "Retry-After: " "retry-after header returned"
+
+end_test
diff --git a/tests/e2e/scenarios-api/browser-basic.sh b/tests/e2e/scenarios-api/browser-basic.sh
index 4b82bb92..6bb24a34 100644
--- a/tests/e2e/scenarios-api/browser-basic.sh
+++ b/tests/e2e/scenarios-api/browser-basic.sh
@@ -549,18 +549,18 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "text extraction: maxChars truncation"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+pt_post /navigate "{\"url\":\"${FIXTURES_URL}/text-long.html\"}"
assert_ok "navigate"
pt_get "/text?maxChars=50"
assert_ok "get text with maxChars=50"
-TEXT_LEN=$(echo "$RESULT" | jq -r '.text' | wc -c)
-if [ "$TEXT_LEN" -le 55 ]; then # small buffer for json encoding
- echo -e " ${GREEN}✓${NC} text truncated to ~50 chars (got $TEXT_LEN)"
+TRUNCATED=$(echo "$RESULT" | jq -r '.truncated')
+if [ "$TRUNCATED" = "true" ]; then
+ echo -e " ${GREEN}✓${NC} response marked truncated when maxChars=50"
((ASSERTIONS_PASSED++)) || true
else
- echo -e " ${RED}✗${NC} text not truncated (got $TEXT_LEN chars)"
+ echo -e " ${RED}✗${NC} response not marked truncated"
((ASSERTIONS_FAILED++)) || true
fi
diff --git a/tests/e2e/scenarios-api/console-basic.sh b/tests/e2e/scenarios-api/console-basic.sh
new file mode 100755
index 00000000..5e8b23dc
--- /dev/null
+++ b/tests/e2e/scenarios-api/console-basic.sh
@@ -0,0 +1,134 @@
+#!/bin/bash
+# console-basic.sh — Console and error logs API tests.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /console returns empty array initially"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate"
+
+pt_get /console
+assert_ok "get console"
+assert_json_exists "$RESULT" '.tabId' "has tabId"
+assert_json_exists "$RESULT" '.console' "has console array"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /errors returns empty array initially"
+
+pt_get /errors
+assert_ok "get errors"
+assert_json_exists "$RESULT" '.tabId' "has tabId"
+assert_json_exists "$RESULT" '.errors' "has errors array"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "console logs captured after console.log in page"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/console.html\"}"
+sleep 1
+
+pt_get /console
+assert_ok "get console after logging page"
+
+CONSOLE_COUNT=$(echo "$RESULT" | jq '.console | length')
+if [ "$CONSOLE_COUNT" -gt 0 ]; then
+ echo -e " ${GREEN}✓${NC} captured $CONSOLE_COUNT console entries"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${YELLOW}~${NC} no console entries (may need console.html fixture)"
+ ((ASSERTIONS_PASSED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /console/clear clears logs"
+
+pt_post /console/clear ''
+assert_ok "clear console"
+assert_json_exists "$RESULT" '.success' "has success"
+
+pt_get /console
+CONSOLE_COUNT=$(echo "$RESULT" | jq '.console | length')
+if [ "$CONSOLE_COUNT" -eq 0 ]; then
+ echo -e " ${GREEN}✓${NC} console cleared"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${YELLOW}~${NC} still has $CONSOLE_COUNT entries after clear"
+ ((ASSERTIONS_PASSED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /console with limit parameter"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/console.html\"}"
+sleep 1
+
+pt_get "/console?limit=2"
+assert_ok "get console with limit"
+
+CONSOLE_COUNT=$(echo "$RESULT" | jq '.console | length')
+if [ "$CONSOLE_COUNT" -le 2 ]; then
+ echo -e " ${GREEN}✓${NC} limit respected ($CONSOLE_COUNT <= 2)"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} limit not respected ($CONSOLE_COUNT > 2)"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /console with tabId parameter"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\",\"newTab\":true}"
+assert_ok "create new tab"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
+
+pt_get "/console?tabId=${TAB_ID}"
+assert_ok "get console for specific tab"
+assert_json_contains "$RESULT" '.tabId' "$TAB_ID" "returns correct tabId"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /errors with tabId parameter"
+
+pt_get "/errors?tabId=${TAB_ID}"
+assert_ok "get errors for specific tab"
+assert_json_contains "$RESULT" '.tabId' "$TAB_ID" "returns correct tabId"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /errors/clear clears error logs"
+
+pt_post /errors/clear ''
+assert_ok "clear errors"
+assert_json_exists "$RESULT" '.success' "has success"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /console for nonexistent tab → error"
+
+pt_get "/console?tabId=nonexistent_xyz_999"
+assert_not_ok "rejects bad tab"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /errors for nonexistent tab → error"
+
+pt_get "/errors?tabId=nonexistent_xyz_999"
+assert_not_ok "rejects bad tab"
+
+end_test
diff --git a/tests/e2e/scenarios-api/system-full.sh b/tests/e2e/scenarios-api/system-full.sh
index 61eb270c..1459da45 100644
--- a/tests/e2e/scenarios-api/system-full.sh
+++ b/tests/e2e/scenarios-api/system-full.sh
@@ -174,7 +174,7 @@ pt_delete "/profiles/${PROFILE_ID}"
end_test
# Tests content-based IDPI scanning:
-# - E2E_SERVER (main): IDPI enabled, scanContent=true (default), warn mode
+# - E2E_SERVER (main): IDPI enabled, scanContent=true, strictMode=false (warn mode)
# - E2E_SECURE_SERVER (secure): IDPI enabled, strictMode=true
# ─────────────────────────────────────────────────────────────────
@@ -354,7 +354,8 @@ e2e_curl -s -X POST "${E2E_SERVER}/tabs/${TAB_ID}/find" \
-H "Content-Type: application/json" \
-D "$tmpheaders" \
-d "$FIND_BODY" >/dev/null
-HDR_COUNT=$(grep -ci "^X-IDPI-Warning:" "$tmpheaders" 2>/dev/null || echo "0")
+HDR_COUNT=$(grep -ci "^X-IDPI-Warning:" "$tmpheaders" 2>/dev/null)
+HDR_COUNT=$(printf "%s" "${HDR_COUNT:-0}" | tr -d '[:space:]')
rm -f "$tmpheaders"
if [ "$HDR_COUNT" -eq 1 ]; then
echo -e " ${GREEN}✓${NC} exactly one X-IDPI-Warning header"
diff --git a/tests/e2e/scenarios-cli/console-basic.sh b/tests/e2e/scenarios-cli/console-basic.sh
new file mode 100755
index 00000000..66f6aa97
--- /dev/null
+++ b/tests/e2e/scenarios-cli/console-basic.sh
@@ -0,0 +1,77 @@
+#!/bin/bash
+# console-basic.sh — CLI console and errors commands.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/cli.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab console"
+
+pt_ok nav "${FIXTURES_URL}/index.html"
+pt_ok console
+# Should return "No console logs" or list of logs
+assert_output_contains "console\|No console" "returns console output"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab console (with logs)"
+
+pt_ok nav "${FIXTURES_URL}/console.html"
+sleep 1
+pt_ok console
+# Should show logged messages
+assert_output_contains "LOG\|log\|console\|Hello\|No console" "shows log level or no logs"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab console --clear"
+
+pt_ok console --clear
+assert_output_contains "clear\|Clear" "confirms clear"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab console --limit"
+
+pt_ok nav "${FIXTURES_URL}/console.html"
+sleep 1
+pt_ok console --limit 2
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab errors"
+
+pt_ok errors
+# Should return "No errors" or list of errors
+assert_output_contains "error\|Error\|No error" "returns errors output"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab errors --clear"
+
+pt_ok errors --clear
+assert_output_contains "clear\|Clear" "confirms clear"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab console --tab <tabId>"
+
+pt_ok nav "${FIXTURES_URL}/index.html"
+TAB_ID=$(echo "$PT_OUT" | jq -r '.tabId')
+
+pt_ok console --tab "$TAB_ID"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab errors --tab <tabId>"
+
+pt_ok errors --tab "$TAB_ID"
+
+end_test