High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: fold three private copies of the UTF-8 byte-truncate helper into the exported one PIN-036
Luigi Agosti9d165d4c3e6a
diff --git a/internal/activity/url_sanitize.go b/internal/activity/url_sanitize.goindex 744599cd..3bb73dfc 100644--- a/internal/activity/url_sanitize.go+++ b/internal/activity/url_sanitize.go@@ -5,13 +5,11 @@ import ("net/url""strings"+ "github.com/pinchtab/pinchtab/internal/sanitize"internalurls "github.com/pinchtab/pinchtab/internal/urls")-const (- maxActivityURLBytes = 2048- activityTruncateSuffix = "..."-)+const maxActivityURLBytes = 2048func sanitizeActivityURL(raw string) string {raw = strings.TrimSpace(raw)@@ -47,30 +45,5 @@ func sanitizeActivityURL(raw string) string {}}- 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+ return sanitize.TruncateUTF8Bytes(parsed.String(), maxActivityURLBytes)}diff --git a/internal/bridge/console_logs.go b/internal/bridge/console_logs.goindex 4a025708..12a6a831 100644--- a/internal/bridge/console_logs.go+++ b/internal/bridge/console_logs.go@@ -3,6 +3,8 @@ package bridgeimport ("sync""time"++ "github.com/pinchtab/pinchtab/internal/sanitize")const (@@ -15,7 +17,6 @@ const (maxErrorTypeBytes = 128maxErrorURLBytes = 2 * 1024maxErrorStackBytes = 8 * 1024- truncationSuffix = "...")// LogEntry represents a single console log entry.@@ -182,41 +183,16 @@ func (s *ConsoleLogStore) RemoveTab(tabID string) {}func normalizeConsoleLogEntry(entry LogEntry) LogEntry {- entry.Level = truncateUTF8Bytes(entry.Level, maxConsoleLevelBytes)- entry.Message = truncateUTF8Bytes(entry.Message, maxConsoleMessageBytes)- entry.Source = truncateUTF8Bytes(entry.Source, maxConsoleSourceBytes)+ entry.Level = sanitize.TruncateUTF8Bytes(entry.Level, maxConsoleLevelBytes)+ entry.Message = sanitize.TruncateUTF8Bytes(entry.Message, maxConsoleMessageBytes)+ entry.Source = sanitize.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)+ entry.Message = sanitize.TruncateUTF8Bytes(entry.Message, maxErrorMessageBytes)+ entry.Type = sanitize.TruncateUTF8Bytes(entry.Type, maxErrorTypeBytes)+ entry.URL = sanitize.TruncateUTF8Bytes(entry.URL, maxErrorURLBytes)+ entry.Stack = sanitize.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.goindex c7dcf4be..7090c275 100644--- a/internal/bridge/console_logs_test.go+++ b/internal/bridge/console_logs_test.go@@ -1,6 +1,7 @@package bridgeimport (+ "github.com/pinchtab/pinchtab/internal/sanitize""strings""testing""time"@@ -208,24 +209,24 @@ func TestConsoleLogStore_TruncatesOversizedFields(t *testing.T) {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].Message; len(got) > maxConsoleMessageBytes || !utf8.ValidString(got) || !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ t.Fatalf("unexpected truncated console message: len=%d valid=%v suffix=%v", len(got), utf8.ValidString(got), strings.HasSuffix(got, sanitize.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))+ if got := logs[0].Source; len(got) > maxConsoleSourceBytes || !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ t.Fatalf("unexpected truncated console source: len=%d suffix=%v", len(got), strings.HasSuffix(got, sanitize.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].Message; len(got) > maxErrorMessageBytes || !utf8.ValidString(got) || !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ t.Fatalf("unexpected truncated error message: len=%d valid=%v suffix=%v", len(got), utf8.ValidString(got), strings.HasSuffix(got, sanitize.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].Type; len(got) > maxErrorTypeBytes || !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ t.Fatalf("unexpected truncated error type: len=%d suffix=%v", len(got), strings.HasSuffix(got, sanitize.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].URL; len(got) > maxErrorURLBytes || !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ t.Fatalf("unexpected truncated error url: len=%d suffix=%v", len(got), strings.HasSuffix(got, sanitize.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))+ if got := errors[0].Stack; len(got) > maxErrorStackBytes || !utf8.ValidString(got) || !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ t.Fatalf("unexpected truncated error stack: len=%d valid=%v suffix=%v", len(got), utf8.ValidString(got), strings.HasSuffix(got, sanitize.TruncationSuffix))}}diff --git a/internal/handlers/network_export_stream.go b/internal/handlers/network_export_stream.goindex 498e3e23..dc4cb005 100644--- a/internal/handlers/network_export_stream.go+++ b/internal/handlers/network_export_stream.go@@ -8,11 +8,11 @@ import ("os""sync""time"- "unicode/utf8""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/bridge/observe""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/sanitize")// HandleNetworkExportStream streams network entries to a file as they arrive.@@ -274,12 +274,17 @@ func (s *exportStreamSession) exportEntry(entry bridge.NetworkEntry) (stop bool)return true}s.count++- data, _ := json.Marshal(map[string]any{"entries": s.count, "url": safetruncateURL(entry.URL)})+ data, _ := json.Marshal(map[string]any{"entries": s.count, "url": sanitize.TruncateUTF8Bytes(entry.URL, maxProgressURLBytes)})_, _ = fmt.Fprintf(s.w, "event: export\ndata: %s\n\n", data)s.flusher.Flush()return false}+// maxProgressURLBytes caps the URL echoed in an export progress event. The cut+// carries the shared truncation marker: nothing consumes this URL, so a visible+// marker is strictly better than a prefix that reads as a complete address.+const maxProgressURLBytes = 120+// drainPending flushes any still-pending entries best-effort on graceful shutdown,// preferring the latest buffered copy. It returns true if encoding stopped the loop.func (s *exportStreamSession) drainPending(pending map[string]pendingExport) (stop bool) {@@ -329,17 +334,3 @@ func (s *exportStreamSession) sendDone() {func (h *Handlers) HandleTabNetworkExportStream(w http.ResponseWriter, r *http.Request) {h.withPathTabID(w, r, h.HandleNetworkExportStream)}--// safetruncateURL truncates at a valid UTF-8 boundary (#21).-func safetruncateURL(u string) string {- const maxLen = 120- if len(u) <= maxLen {- return u- }- for i := maxLen; i > 0; i-- {- if utf8.RuneStart(u[i]) {- return u[:i]- }- }- return u[:maxLen]-}diff --git a/internal/urls/log_redact.go b/internal/urls/log_redact.goindex fa263b0c..ee25c9d3 100644--- a/internal/urls/log_redact.go+++ b/internal/urls/log_redact.go@@ -4,13 +4,12 @@ import ("net""net/url""strings"-)-const (- maxLogURLBytes = 512- logTruncateSuffix = "..."+ "github.com/pinchtab/pinchtab/internal/sanitize")+const maxLogURLBytes = 512+// 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@@ -48,30 +47,5 @@ func RedactForLog(raw string) string {}}- 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+ return sanitize.TruncateUTF8Bytes(parsed.String(), maxLogURLBytes)}diff --git a/internal/urls/urls_test.go b/internal/urls/urls_test.goindex d45915db..326b2a84 100644--- a/internal/urls/urls_test.go+++ b/internal/urls/urls_test.go@@ -1,6 +1,13 @@package urls-import "testing"+import (+ "fmt"+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/pinchtab/pinchtab/internal/sanitize"+)func TestNormalize(t *testing.T) {tests := []struct {@@ -145,3 +152,75 @@ func TestRedactForLog(t *testing.T) {})}}++// The byte cap on a redacted log URL moved from a package-private copy to+// sanitize.TruncateUTF8Bytes. These are the four cases where a byte-budget+// truncator can change behaviour, pinned at a converted call site.+func TestRedactForLogTruncationBoundaries(t *testing.T) {+ host := "https://example.com/"+ fill := maxLogURLBytes - len(host)++ tests := []struct {+ name string+ raw string+ want func(got string) error+ }{+ {+ name: "empty input stays empty",+ raw: "",+ want: func(got string) error {+ if got != "" {+ return fmt.Errorf("got %q, want empty", got)+ }+ return nil+ },+ },+ {+ name: "under the limit is returned verbatim",+ raw: host + strings.Repeat("a", 10),+ want: func(got string) error {+ if got != host+strings.Repeat("a", 10) {+ return fmt.Errorf("got %q, want the input unchanged", got)+ }+ return nil+ },+ },+ {+ name: "exactly at the limit is returned verbatim",+ raw: host + strings.Repeat("a", fill),+ want: func(got string) error {+ if len(got) != maxLogURLBytes {+ return fmt.Errorf("len = %d, want %d", len(got), maxLogURLBytes)+ }+ if strings.HasSuffix(got, sanitize.TruncationSuffix) {+ return fmt.Errorf("a URL exactly at the limit must not be marked truncated: %q", got)+ }+ return nil+ },+ },+ {+ name: "a cut landing inside a multi-byte rune keeps valid UTF-8",+ raw: host + strings.Repeat("a", fill-1) + "€€€",+ want: func(got string) error {+ if !utf8.ValidString(got) {+ return fmt.Errorf("truncated URL is not valid UTF-8: %q", got)+ }+ if len(got) > maxLogURLBytes {+ return fmt.Errorf("len = %d, want <= %d", len(got), maxLogURLBytes)+ }+ if !strings.HasSuffix(got, sanitize.TruncationSuffix) {+ return fmt.Errorf("a cut URL must carry the truncation marker: %q", got)+ }+ return nil+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if err := tt.want(RedactForLog(tt.raw)); err != nil {+ t.Fatal(err)+ }+ })+ }+}