Skip to content

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

implement cookies endpoints (P6 feature 2/4)

botd97eda64965e
diff --git a/handlers.go b/handlers.go
index 83176b30..1eecf74d 100644
--- a/handlers.go
+++ b/handlers.go
@@ -11,6 +11,8 @@ import (
"strings"
"time"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
@@ -644,3 +646,170 @@ func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 400, map[string]string{"error": "action must be 'new' or 'close'"})
}
}
+
+// ── GET /cookies ───────────────────────────────────────────
+
+func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+ url := r.URL.Query().Get("url")
+ name := r.URL.Query().Get("name")
+
+ ctx, _, err := b.TabContext(tabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)
+ defer tCancel()
+
+ // Import the network domain for cookie access
+ var cookies []*network.Cookie
+ if err := chromedp.Run(tCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ // Get current URL if not specified
+ if url == "" {
+ _ = chromedp.Location(&url).Do(ctx)
+ }
+
+ // Get cookies for the URL
+ var err error
+ cookies, err = network.GetCookies().WithURLs([]string{url}).Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ jsonErr(w, 500, fmt.Errorf("get cookies: %w", err))
+ return
+ }
+
+ // Filter by name if specified
+ if name != "" {
+ filtered := make([]*network.Cookie, 0)
+ for _, c := range cookies {
+ if c.Name == name {
+ filtered = append(filtered, c)
+ }
+ }
+ cookies = filtered
+ }
+
+ // Convert to simpler format
+ result := make([]map[string]any, len(cookies))
+ for i, c := range cookies {
+ result[i] = map[string]any{
+ "name": c.Name,
+ "value": c.Value,
+ "domain": c.Domain,
+ "path": c.Path,
+ "secure": c.Secure,
+ "httpOnly": c.HTTPOnly,
+ "sameSite": c.SameSite.String(),
+ }
+ if c.Expires > 0 {
+ result[i]["expires"] = c.Expires
+ }
+ }
+
+ jsonResp(w, 200, map[string]any{
+ "url": url,
+ "cookies": result,
+ "count": len(result),
+ })
+}
+
+// ── POST /cookies ──────────────────────────────────────────
+
+type cookieRequest struct {
+ TabID string `json:"tabId"`
+ URL string `json:"url"` // Required
+ Cookies []cookieSetRequest `json:"cookies"` // Array of cookies to set
+}
+
+type cookieSetRequest struct {
+ Name string `json:"name"` // Required
+ Value string `json:"value"` // Required
+ Domain string `json:"domain"` // Optional, defaults to current domain
+ Path string `json:"path"` // Optional, defaults to "/"
+ Secure bool `json:"secure"`
+ HTTPOnly bool `json:"httpOnly"`
+ SameSite string `json:"sameSite"` // "Strict", "Lax", "None"
+ Expires float64 `json:"expires"` // Unix timestamp
+}
+
+func (b *Bridge) handleSetCookies(w http.ResponseWriter, r *http.Request) {
+ var req cookieRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ if req.URL == "" {
+ jsonResp(w, 400, map[string]string{"error": "url is required"})
+ return
+ }
+
+ if len(req.Cookies) == 0 {
+ jsonResp(w, 400, map[string]string{"error": "cookies array is empty"})
+ return
+ }
+
+ ctx, _, err := b.TabContext(req.TabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)
+ defer tCancel()
+
+ successCount := 0
+ for _, cookie := range req.Cookies {
+ if cookie.Name == "" || cookie.Value == "" {
+ continue // Skip invalid cookies
+ }
+
+ // Build CDP cookie parameters
+ params := network.SetCookie(cookie.Name, cookie.Value).
+ WithURL(req.URL).
+ WithHTTPOnly(cookie.HTTPOnly).
+ WithSecure(cookie.Secure)
+
+ if cookie.Domain != "" {
+ params = params.WithDomain(cookie.Domain)
+ }
+ if cookie.Path != "" {
+ params = params.WithPath(cookie.Path)
+ }
+ if cookie.Expires > 0 {
+ expires := cdp.TimeSinceEpoch(time.Unix(int64(cookie.Expires), 0))
+ params = params.WithExpires(&expires)
+ }
+
+ // Handle SameSite
+ if cookie.SameSite != "" {
+ var sameSite network.CookieSameSite
+ switch strings.ToLower(cookie.SameSite) {
+ case "strict":
+ sameSite = network.CookieSameSiteStrict
+ case "lax":
+ sameSite = network.CookieSameSiteLax
+ case "none":
+ sameSite = network.CookieSameSiteNone
+ }
+ if sameSite != "" {
+ params = params.WithSameSite(sameSite)
+ }
+ }
+
+ // Set the cookie
+ if err := chromedp.Run(tCtx, params); err == nil {
+ successCount++
+ }
+ }
+
+ jsonResp(w, 200, map[string]any{
+ "set": successCount,
+ "failed": len(req.Cookies) - successCount,
+ "total": len(req.Cookies),
+ })
+}
diff --git a/main.go b/main.go
index 422457de..3bdf13e9 100644
--- a/main.go
+++ b/main.go
@@ -137,6 +137,8 @@ func main() {
mux.HandleFunc("POST /actions", bridge.handleActions)
mux.HandleFunc("POST /evaluate", bridge.handleEvaluate)
mux.HandleFunc("POST /tab", bridge.handleTab)
+ mux.HandleFunc("GET /cookies", bridge.handleGetCookies)
+ mux.HandleFunc("POST /cookies", bridge.handleSetCookies)
srv := &http.Server{Addr: ":" + port, Handler: loggingMiddleware(corsMiddleware(authMiddleware(mux)))}