Skip to content

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

feat: support cookie injection and profile auth in audit runs

Luigi Agostib926b6c378c0
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index c25d1f47..b2027828 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -365,6 +365,9 @@ func configureBrowserFlags() {
auditCmd.Flags().String("seaportal-report", "", "Audit pages from a SeaPortal results JSON file (array of Result objects)")
auditCmd.Flags().Bool("enrich-all", false, "Browser-enrich every seaportal page, ignoring browserRecommended routing")
auditCmd.Flags().String("format", "json", "Report format: json, md, or html (md/html written next to report.json, or printed without --output-dir)")
+ auditCmd.Flags().StringArray("cookie", nil, "Inject a cookie as name=value before the run (repeatable; the cookie jar is cleared afterwards)")
+ auditCmd.Flags().String("cookies-file", "", "Inject cookies from a JSON array of {name, value, domain, ...} objects")
+ auditCmd.Flags().String("profile", "", "Run against the instance of this browser profile")
compareCmd.Flags().String("pages", "", "Comma-separated relative paths to compare (default: the base URLs)")
compareCmd.Flags().Bool("visual-diff", true, "Capture screenshots and compute visual diffs")
@@ -373,6 +376,9 @@ func configureBrowserFlags() {
compareCmd.Flags().Bool("json", false, "Print the comparison report JSON to stdout")
compareCmd.Flags().Bool("fail-on-diff", false, "Exit non-zero when any visual or data diff exists")
compareCmd.Flags().String("format", "json", "Report format: json, md, or html")
+ compareCmd.Flags().StringArray("cookie", nil, "Inject a cookie as name=value before the run (repeatable; the cookie jar is cleared afterwards)")
+ compareCmd.Flags().String("cookies-file", "", "Inject cookies from a JSON array of {name, value, domain, ...} objects")
+ compareCmd.Flags().String("profile", "", "Run against the instance of this browser profile")
addTabFlag(consoleCmd, errorsCmd)
}
diff --git a/internal/audit/auth.go b/internal/audit/auth.go
new file mode 100644
index 00000000..526579b6
--- /dev/null
+++ b/internal/audit/auth.go
@@ -0,0 +1,66 @@
+package audit
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+// Cookie is one cookie to inject before an audit run. The JSON shape
+// matches the POST /cookies request entries (bridge SetCookieParams).
+type Cookie struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ Domain string `json:"domain,omitempty"`
+ Path string `json:"path,omitempty"`
+ Secure bool `json:"secure,omitempty"`
+ HTTPOnly bool `json:"httpOnly,omitempty"`
+ SameSite string `json:"sameSite,omitempty"`
+ Expires float64 `json:"expires,omitempty"`
+}
+
+// ParseCookieFlag parses one --cookie "name=value" flag.
+func ParseCookieFlag(s string) (Cookie, error) {
+ name, value, ok := strings.Cut(s, "=")
+ name = strings.TrimSpace(name)
+ if !ok || name == "" || value == "" {
+ return Cookie{}, fmt.Errorf("invalid --cookie %q: expected name=value", s)
+ }
+ return Cookie{Name: name, Value: value}, nil
+}
+
+// ParseCookiesFile parses a cookies JSON file: an array of cookie objects
+// in the SetCookieParams shape. Every entry must carry name and value.
+func ParseCookiesFile(data []byte) ([]Cookie, error) {
+ var cookies []Cookie
+ if err := json.Unmarshal(data, &cookies); err != nil {
+ return nil, fmt.Errorf("parse cookies file: %w (expected a JSON array of {name, value, ...} objects)", err)
+ }
+ for i, c := range cookies {
+ if strings.TrimSpace(c.Name) == "" || c.Value == "" {
+ return nil, fmt.Errorf("cookies file entry %d: name and value are required", i)
+ }
+ }
+ return cookies, nil
+}
+
+// CollectCookies merges repeatable --cookie flags with an optional cookies
+// file (flags first, then file entries).
+func CollectCookies(flags []string, fileData []byte) ([]Cookie, error) {
+ var cookies []Cookie
+ for _, f := range flags {
+ c, err := ParseCookieFlag(f)
+ if err != nil {
+ return nil, err
+ }
+ cookies = append(cookies, c)
+ }
+ if len(fileData) > 0 {
+ fromFile, err := ParseCookiesFile(fileData)
+ if err != nil {
+ return nil, err
+ }
+ cookies = append(cookies, fromFile...)
+ }
+ return cookies, nil
+}
diff --git a/internal/audit/auth_test.go b/internal/audit/auth_test.go
new file mode 100644
index 00000000..633f296e
--- /dev/null
+++ b/internal/audit/auth_test.go
@@ -0,0 +1,78 @@
+package audit
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestParseCookieFlag(t *testing.T) {
+ c, err := ParseCookieFlag("session=abc123")
+ if err != nil {
+ t.Fatalf("ParseCookieFlag: %v", err)
+ }
+ if c.Name != "session" || c.Value != "abc123" {
+ t.Errorf("cookie = %+v", c)
+ }
+
+ if c, err := ParseCookieFlag("k=v=with=equals"); err != nil || c.Value != "v=with=equals" {
+ t.Errorf("value with equals: %+v, %v", c, err)
+ }
+
+ for _, bad := range []string{"", "novalue", "=v", "name="} {
+ if _, err := ParseCookieFlag(bad); err == nil {
+ t.Errorf("ParseCookieFlag(%q) should error", bad)
+ }
+ }
+}
+
+func TestParseCookiesFile(t *testing.T) {
+ data := []byte(`[
+ {"name":"session","value":"abc","domain":"fixtures","path":"/","httpOnly":true},
+ {"name":"pref","value":"dark"}
+ ]`)
+ cookies, err := ParseCookiesFile(data)
+ if err != nil {
+ t.Fatalf("ParseCookiesFile: %v", err)
+ }
+ if len(cookies) != 2 || cookies[0].Domain != "fixtures" || !cookies[0].HTTPOnly {
+ t.Errorf("cookies = %+v", cookies)
+ }
+}
+
+func TestParseCookiesFileErrors(t *testing.T) {
+ if _, err := ParseCookiesFile([]byte("{not json")); err == nil {
+ t.Error("malformed JSON should error")
+ } else if !strings.Contains(err.Error(), "expected a JSON array") {
+ t.Errorf("malformed JSON error should explain the expected shape, got %v", err)
+ }
+
+ if _, err := ParseCookiesFile([]byte(`[{"name":"","value":"x"}]`)); err == nil {
+ t.Error("missing name should error")
+ }
+ if _, err := ParseCookiesFile([]byte(`[{"name":"x","value":""}]`)); err == nil {
+ t.Error("missing value should error")
+ }
+ if _, err := ParseCookiesFile([]byte(`{"name":"x","value":"y"}`)); err == nil {
+ t.Error("non-array JSON should error")
+ }
+}
+
+func TestCollectCookies(t *testing.T) {
+ cookies, err := CollectCookies([]string{"a=1", "b=2"}, []byte(`[{"name":"c","value":"3"}]`))
+ if err != nil {
+ t.Fatalf("CollectCookies: %v", err)
+ }
+ if len(cookies) != 3 || cookies[0].Name != "a" || cookies[2].Name != "c" {
+ t.Errorf("cookies = %+v", cookies)
+ }
+
+ if _, err := CollectCookies([]string{"bad"}, nil); err == nil {
+ t.Error("bad flag should error")
+ }
+ if _, err := CollectCookies(nil, []byte("bad")); err == nil {
+ t.Error("bad file should error")
+ }
+ if cookies, err := CollectCookies(nil, nil); err != nil || len(cookies) != 0 {
+ t.Errorf("empty input = %+v, %v", cookies, err)
+ }
+}
diff --git a/internal/cli/actions/actions_audit.go b/internal/cli/actions/actions_audit.go
index 9f35a4c7..9eefd887 100644
--- a/internal/cli/actions/actions_audit.go
+++ b/internal/cli/actions/actions_audit.go
@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "strings"
"time"
"github.com/pinchtab/pinchtab/internal/audit"
@@ -29,8 +30,118 @@ func mustBool(cmd *cobra.Command, name string) bool {
return v
}
+// applyRunAuth resolves --profile routing and injects --cookie /
+// --cookies-file cookies before the run. Isolation approach: injected
+// cookies live in the shared browser jar, so the returned cleanup clears
+// the jar after the run (documented on the audit/compare help).
+func applyRunAuth(client *http.Client, base, token string, cmd *cobra.Command, scopeURL string) (string, func()) {
+ if profile := mustString(cmd, "profile"); profile != "" {
+ base = resolveProfileBase(client, base, token, profile)
+ }
+ cookies := loadRunCookies(cmd)
+ if len(cookies) == 0 {
+ return base, func() {}
+ }
+ if scopeURL == "" {
+ fmt.Fprintln(os.Stderr, "cookie injection requires a URL target")
+ os.Exit(1)
+ }
+ setRunCookies(client, base, token, scopeURL, cookies)
+ return base, func() { clearRunCookies(client, base, token) }
+}
+
+func loadRunCookies(cmd *cobra.Command) []audit.Cookie {
+ flags, _ := cmd.Flags().GetStringArray("cookie")
+ var fileData []byte
+ if path := mustString(cmd, "cookies-file"); path != "" {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "read cookies file: %v\n", err)
+ os.Exit(1)
+ }
+ fileData = data
+ }
+ cookies, err := audit.CollectCookies(flags, fileData)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "%v\n", err)
+ os.Exit(1)
+ }
+ return cookies
+}
+
+// setRunCookies injects cookies through POST /cookies, using a throwaway
+// blank tab for the required tab context so it works on a fresh browser.
+func setRunCookies(client *http.Client, base, token, url string, cookies []audit.Cookie) {
+ tab := apiclient.DoPostQuiet(client, base, token, "/tab", map[string]any{"action": "new"})
+ tabID, _ := tab["tabId"].(string)
+ body := map[string]any{"url": url, "cookies": cookies}
+ if tabID != "" {
+ body["tabId"] = tabID
+ }
+ apiclient.DoPostQuiet(client, base, token, "/cookies", body)
+ if tabID != "" {
+ apiclient.DoPostQuiet(client, base, token, "/close", map[string]any{"tabId": tabID})
+ }
+}
+
+// clearRunCookies clears the browser cookie jar, quietly and best-effort.
+func clearRunCookies(client *http.Client, base, token string) {
+ req, err := http.NewRequest(http.MethodDelete, base+"/cookies", nil)
+ if err != nil {
+ return
+ }
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ if resp, err := client.Do(req); err == nil {
+ _ = resp.Body.Close()
+ }
+}
+
+// resolveProfileBase routes the run at the instance owning the named
+// profile: the orchestrator base for the default-routed instance, or the
+// instance's own URL otherwise.
+func resolveProfileBase(client *http.Client, base, token, profile string) string {
+ raw := apiclient.DoGetRaw(client, base, token, "/instances", nil)
+ var instances []struct {
+ ID string `json:"id"`
+ ProfileName string `json:"profileName"`
+ Status string `json:"status"`
+ URL string `json:"url"`
+ }
+ if err := json.Unmarshal(raw, &instances); err != nil {
+ fmt.Fprintf(os.Stderr, "parse instances: %v\n", err)
+ os.Exit(1)
+ }
+ for _, inst := range instances {
+ if inst.ProfileName != profile || inst.Status != "running" {
+ continue
+ }
+ if inst.ID == defaultInstanceID(client, base, token) {
+ return base
+ }
+ return strings.TrimSuffix(inst.URL, "/")
+ }
+ fmt.Fprintf(os.Stderr, "no running instance for profile %q (start one: pinchtab instance start --profile %s)\n", profile, profile)
+ os.Exit(1)
+ return ""
+}
+
+func defaultInstanceID(client *http.Client, base, token string) string {
+ raw := apiclient.DoGetRaw(client, base, token, "/health", nil)
+ var health struct {
+ DefaultInstance struct {
+ ID string `json:"id"`
+ } `json:"defaultInstance"`
+ }
+ _ = json.Unmarshal(raw, &health)
+ return health.DefaultInstance.ID
+}
+
// Audit runs a multi-page site audit via POST /audit and writes artifacts.
func Audit(client *http.Client, base, token string, cmd *cobra.Command, target string) {
+ base, cleanupCookies := applyRunAuth(client, base, token, cmd, target)
+
body := map[string]any{}
switch {
case mustString(cmd, "seaportal-report") != "":
@@ -63,6 +174,7 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target s
longClient := &http.Client{Transport: client.Transport, Timeout: auditTimeout}
raw := apiclient.DoPostRaw(longClient, base, token, "/audit", body)
+ cleanupCookies()
var report map[string]any
if err := json.Unmarshal(raw, &report); err != nil {
diff --git a/internal/cli/actions/actions_compare.go b/internal/cli/actions/actions_compare.go
index 0237bd9c..135641d7 100644
--- a/internal/cli/actions/actions_compare.go
+++ b/internal/cli/actions/actions_compare.go
@@ -21,6 +21,8 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBa
visual := mustBool(cmd, "visual-diff")
concurrency, _ := cmd.Flags().GetInt("concurrency")
+ base, cleanupCookies := applyRunAuth(client, base, token, cmd, liveBase)
+
longClient := &http.Client{Transport: client.Transport, Timeout: auditTimeout}
runSide := func(siteBase string) audit.AuditReport {
body := map[string]any{
@@ -41,6 +43,7 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBa
liveReport := runSide(liveBase)
stagingReport := runSide(stagingBase)
+ cleanupCookies()
outcome, err := audit.ComparePages(liveBase, stagingBase, liveReport, stagingReport)
if err != nil {
diff --git a/tests/e2e/fixtures/audit-site-staging/cookie-echo.html b/tests/e2e/fixtures/audit-site-staging/cookie-echo.html
index b574019a..a5a85537 100644
--- a/tests/e2e/fixtures/audit-site-staging/cookie-echo.html
+++ b/tests/e2e/fixtures/audit-site-staging/cookie-echo.html
@@ -1,6 +1,7 @@
<!doctype html>
-<!-- No intentional defects: renders document.cookie into #cookies so
- cookie-injection e2e scenarios can assert what the page can read. -->
+<!-- No intentional defects: renders document.cookie into #cookies and
+ logs it to the console so cookie-injection e2e scenarios can assert
+ what the page can read (audit reports capture console logs). -->
<html lang="en">
<head>
<meta charset="utf-8">
@@ -15,6 +16,7 @@
<p><a href="index.html">Home</a></p>
<script>
document.getElementById('cookies').textContent = document.cookie;
+ console.log('cookies: ' + document.cookie);
</script>
</body>
</html>
diff --git a/tests/e2e/fixtures/audit-site/cookie-echo.html b/tests/e2e/fixtures/audit-site/cookie-echo.html
index b574019a..a5a85537 100644
--- a/tests/e2e/fixtures/audit-site/cookie-echo.html
+++ b/tests/e2e/fixtures/audit-site/cookie-echo.html
@@ -1,6 +1,7 @@
<!doctype html>
-<!-- No intentional defects: renders document.cookie into #cookies so
- cookie-injection e2e scenarios can assert what the page can read. -->
+<!-- No intentional defects: renders document.cookie into #cookies and
+ logs it to the console so cookie-injection e2e scenarios can assert
+ what the page can read (audit reports capture console logs). -->
<html lang="en">
<head>
<meta charset="utf-8">
@@ -15,6 +16,7 @@
<p><a href="index.html">Home</a></p>
<script>
document.getElementById('cookies').textContent = document.cookie;
+ console.log('cookies: ' + document.cookie);
</script>
</body>
</html>
diff --git a/tests/e2e/scenarios/cli/audit-auth-basic.sh b/tests/e2e/scenarios/cli/audit-auth-basic.sh
new file mode 100755
index 00000000..14aedf4f
--- /dev/null
+++ b/tests/e2e/scenarios/cli/audit-auth-basic.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# audit-auth-basic.sh — cookie injection and profile auth on audit runs.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/cli.sh"
+
+COOKIE_ECHO="http://fixtures/audit-site/cookie-echo.html"
+
+report_has_cookie_value() {
+ echo "$PT_OUT" | jq -e '[.pages[].browser.consoleLogs[]?.message // empty] | any(contains("e2evalue"))' >/dev/null 2>&1
+}
+
+# ─────────────────────────────────────────────────────────────────
+start_test "--cookie injects a cookie visible to the audited page"
+
+pt_ok audit "$COOKIE_ECHO" --cookie test=e2evalue --screenshot=false --json
+
+if report_has_cookie_value; then
+ pass_assert "report captures e2evalue from the page"
+else
+ fail_assert "report captures e2evalue (console logs: $(echo "$PT_OUT" | jq -c '[.pages[].browser.consoleLogs[]?.message]'))"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "cookies do not leak into a later run (isolation)"
+
+pt_ok audit "$COOKIE_ECHO" --screenshot=false --json
+
+if report_has_cookie_value; then
+ fail_assert "no e2evalue without the flag (leaked cookie)"
+else
+ pass_assert "no e2evalue without the flag"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "--profile default routes the run"
+
+pt_ok audit "$COOKIE_ECHO" --profile default --screenshot=false --json
+
+PAGE_COUNT=$(echo "$PT_OUT" | jq '.pages | length' 2>/dev/null)
+if [ "${PAGE_COUNT:-0}" -eq 1 ] 2>/dev/null; then
+ pass_assert "audit ran against the default profile instance"
+else
+ fail_assert "audit ran against the default profile instance (pages: $PAGE_COUNT)"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "bad cookies file fails with a clear error"
+
+BAD_FILE=$(mktemp /tmp/bad-cookies.XXXXXX.json)
+echo '{definitely not valid json' > "$BAD_FILE"
+
+pt_fail audit "$COOKIE_ECHO" --cookies-file "$BAD_FILE"
+if echo "$PT_ERR" | grep -q "cookies file"; then
+ pass_assert "error message mentions the cookies file"
+else
+ fail_assert "error message mentions the cookies file (stderr: $PT_ERR)"
+fi
+
+rm -f "$BAD_FILE"
+
+end_test