session

package
v1.6.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const SessionStateVersion = 5

Variables

View Source
var (
	ErrSessionClosed = errors.New("session is closed")
)

Functions

func ValidateSessionFile added in v1.5.5

func ValidateSessionFile(path string) error

ValidateSessionFile validates a session file without loading it

Types

type CookieData added in v1.5.10

type CookieData struct {
	Name      string
	Value     string
	Domain    string // Normalized domain (with leading dot for domain cookies)
	HostOnly  bool   // True if cookie should only be sent to exact host
	Path      string
	Expires   *time.Time
	MaxAge    int
	Secure    bool
	HttpOnly  bool
	SameSite  string
	CreatedAt time.Time
}

CookieData extends CookieState with creation time for sorting

type CookieJar added in v1.5.10

type CookieJar struct {
	// contains filtered or unexported fields
}

CookieJar manages cookies with proper domain and path scoping Cookies are stored by domain, then by (path, name) tuple

func NewCookieJar added in v1.5.10

func NewCookieJar() *CookieJar

NewCookieJar creates a new empty cookie jar

func (*CookieJar) BuildCookieHeader added in v1.5.10

func (j *CookieJar) BuildCookieHeader(requestHost, requestPath string, requestSecure bool) string

BuildCookieHeader builds the Cookie header value for a request

func (*CookieJar) Clear added in v1.5.10

func (j *CookieJar) Clear()

Clear removes all cookies

func (*CookieJar) ClearExpired added in v1.5.10

func (j *CookieJar) ClearExpired()

ClearExpired removes all expired cookies

func (*CookieJar) Count added in v1.5.10

func (j *CookieJar) Count() int

Count returns the total number of cookies across all domains

func (*CookieJar) Delete added in v1.6.1

func (j *CookieJar) Delete(name, domain string)

Delete removes cookies by name. If domain is empty, removes ALL cookies with that name across all domains. If domain is provided, removes only from that domain.

func (*CookieJar) Export added in v1.5.10

func (j *CookieJar) Export() map[string][]CookieState

Export exports all cookies grouped by domain for serialization

func (*CookieJar) Get added in v1.5.10

func (j *CookieJar) Get(requestHost, requestPath string, requestSecure bool) []*CookieData

Get returns all cookies that should be sent for a request requestHost is the target host requestPath is the request path requestSecure is true if the request is over HTTPS

func (*CookieJar) GetAll added in v1.5.10

func (j *CookieJar) GetAll() []CookieState

GetAll returns all non-expired cookies with full metadata

func (*CookieJar) Import added in v1.5.10

func (j *CookieJar) Import(cookies map[string][]CookieState)

Import imports cookies from the v5 format (domain-keyed)

func (*CookieJar) ImportV4 added in v1.5.10

func (j *CookieJar) ImportV4(cookies []CookieState)

ImportV4 imports cookies from the v4 format (flat list)

func (*CookieJar) Set added in v1.5.10

func (j *CookieJar) Set(requestHost string, cookie *CookieData, requestSecure bool)

Set adds or updates a cookie from a Set-Cookie header requestHost is the host that sent the Set-Cookie header requestSecure is true if the request was over HTTPS

func (*CookieJar) SetSimple added in v1.5.10

func (j *CookieJar) SetSimple(name, value, domain, path string, secure, httpOnly bool, sameSite string, maxAge int, expires *time.Time)

SetSimple sets a cookie with full metadata. If domain is empty, creates a global cookie (sent to all domains). If domain is provided, normalizes it and stores as a domain-scoped cookie.

type CookieState added in v1.5.5

type CookieState struct {
	Name      string     `json:"name"`
	Value     string     `json:"value"`
	Domain    string     `json:"domain,omitempty"`
	Path      string     `json:"path,omitempty"`
	Expires   *time.Time `json:"expires,omitempty"`
	MaxAge    int        `json:"max_age,omitempty"`
	Secure    bool       `json:"secure,omitempty"`
	HttpOnly  bool       `json:"http_only,omitempty"`
	SameSite  string     `json:"same_site,omitempty"`
	CreatedAt *time.Time `json:"created_at,omitempty"` // v5: for sorting
}

CookieState represents a serializable cookie with full metadata

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager manages all active sessions

func NewManager

func NewManager() *Manager

NewManager creates a new session manager

func (*Manager) CloseSession

func (m *Manager) CloseSession(sessionID string) error

CloseSession closes and removes a session

func (*Manager) CreateSession

func (m *Manager) CreateSession(config *protocol.SessionConfig) (string, error)

CreateSession creates a new session and returns its ID

func (*Manager) GetSession

func (m *Manager) GetSession(sessionID string) (*Session, error)

GetSession retrieves a session by ID

func (*Manager) ListSessions

func (m *Manager) ListSessions() []SessionStats

ListSessions returns stats for all active sessions

func (*Manager) SessionCount

func (m *Manager) SessionCount() int

SessionCount returns the number of active sessions

func (*Manager) SetMaxSessions

func (m *Manager) SetMaxSessions(max int)

SetMaxSessions sets the maximum number of concurrent sessions

func (*Manager) SetSessionTimeout

func (m *Manager) SetSessionTimeout(timeout time.Duration)

SetSessionTimeout sets the session idle timeout

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown closes all sessions and stops the manager

type Session

type Session struct {
	ID           string
	CreatedAt    time.Time
	LastUsed     time.Time
	RequestCount int64
	Config       *protocol.SessionConfig
	// contains filtered or unexported fields
}

Session represents a persistent HTTP session with connection affinity

func LoadSession added in v1.5.5

func LoadSession(path string) (*Session, error)

LoadSession loads a session from a file

func NewSession

func NewSession(id string, config *protocol.SessionConfig) *Session

NewSession creates a new session with its own connection pool

func NewSessionWithOptions added in v1.5.8

func NewSessionWithOptions(id string, config *protocol.SessionConfig, opts *SessionOptions) *Session

NewSessionWithOptions creates a new session with additional options for distributed caching etc.

func UnmarshalSession added in v1.5.5

func UnmarshalSession(data []byte) (*Session, error)

UnmarshalSession loads a session from JSON bytes

func (*Session) ClearCache

func (s *Session) ClearCache()

ClearCache clears all cached URLs (removes If-None-Match/If-Modified-Since headers)

func (*Session) ClearCookies

func (s *Session) ClearCookies()

ClearCookies removes all cookies from this session

func (*Session) Close

func (s *Session) Close()

Close marks the session as inactive and closes connections

func (*Session) ConditionalCacheEnabled added in v1.6.7

func (s *Session) ConditionalCacheEnabled() bool

ConditionalCacheEnabled reports whether the session is currently injecting and storing ETag / If-Modified-Since validators.

func (*Session) DeleteCookie added in v1.6.1

func (s *Session) DeleteCookie(name, domain string)

DeleteCookie removes cookies by name. If domain is empty, removes from all domains.

func (*Session) FollowRedirects added in v1.6.7

func (s *Session) FollowRedirects() bool

FollowRedirects reports the session's current redirect-following policy. Returns true when the session will follow redirects by default; per-request overrides can still flip the behaviour for a single call.

func (*Session) Fork added in v1.6.0

func (s *Session) Fork(n int) []*Session

Fork creates n new sessions that share cookies and TLS session caches with the parent, but have independent connections. This simulates multiple browser tabs from the same browser instance — same cookies, same TLS resumption tickets, same fingerprint, but independent TCP/QUIC connections for parallel requests.

func (*Session) Get

func (s *Session) Get(ctx context.Context, url string, headers map[string][]string) (*transport.Response, error)

Get performs a GET request

func (*Session) GetCookies

func (s *Session) GetCookies() []CookieState

GetCookies returns all cookies with full metadata

func (*Session) GetCookiesDetailed added in v1.6.1

func (s *Session) GetCookiesDetailed() []CookieState

GetCookiesDetailed is an alias for GetCookies, returning full cookie metadata.

func (*Session) GetHeaderOrder added in v1.5.8

func (s *Session) GetHeaderOrder() []string

GetHeaderOrder returns the current header order. Returns preset's default order if no custom order is set.

func (*Session) GetProxy added in v1.5.8

func (s *Session) GetProxy() string

GetProxy returns the current proxy URL (unified proxy or TCP proxy)

func (*Session) GetStream added in v1.5.3

func (s *Session) GetStream(ctx context.Context, url string, headers map[string][]string) (*StreamResponse, error)

GetStream performs a streaming GET request

func (*Session) GetTCPProxy added in v1.5.8

func (s *Session) GetTCPProxy() string

GetTCPProxy returns the current TCP proxy URL

func (*Session) GetTransport

func (s *Session) GetTransport() *transport.Transport

GetTransport returns the session's transport

func (*Session) GetUDPProxy added in v1.5.8

func (s *Session) GetUDPProxy() string

GetUDPProxy returns the current UDP proxy URL

func (*Session) IdleTime

func (s *Session) IdleTime() time.Duration

IdleTime returns how long since the session was last used

func (*Session) IsActive

func (s *Session) IsActive() bool

IsActive returns whether the session is active

func (*Session) Marshal added in v1.5.5

func (s *Session) Marshal() ([]byte, error)

Marshal exports session state to JSON bytes

func (*Session) MaxRedirects added in v1.6.7

func (s *Session) MaxRedirects() int

MaxRedirects reports the session's current redirect cap. Returns the configured value, or 10 (the default applied in requestWithRedirects) when nothing has been set.

func (*Session) Post

func (s *Session) Post(ctx context.Context, url string, body []byte, headers map[string][]string) (*transport.Response, error)

Post performs a POST request

func (*Session) PostStream added in v1.5.3

func (s *Session) PostStream(ctx context.Context, url string, body []byte, headers map[string][]string) (*StreamResponse, error)

PostStream performs a streaming POST request

func (*Session) Refresh added in v1.5.10

func (s *Session) Refresh()

Refresh closes all connections but keeps TLS session caches and cookies intact. This simulates a browser page refresh - new TCP/QUIC connections but TLS resumption. If a switchProtocol was configured, the session switches to that protocol.

func (*Session) RefreshWithProtocol added in v1.6.0

func (s *Session) RefreshWithProtocol(proto string) error

RefreshWithProtocol closes all connections and switches to a new protocol. The protocol change persists for future Refresh() calls as well. Valid protocols: "h1", "h2", "h3", "auto".

func (*Session) Request

func (s *Session) Request(ctx context.Context, req *transport.Request) (*transport.Response, error)

Request executes an HTTP request within this session

func (*Session) RequestStream added in v1.5.3

func (s *Session) RequestStream(ctx context.Context, req *transport.Request) (*StreamResponse, error)

RequestStream executes an HTTP request and returns a streaming response The caller is responsible for closing the response when done Note: Streaming does NOT support redirects - use Request() for redirect handling

func (*Session) Save added in v1.5.5

func (s *Session) Save(path string) error

Save exports session state to a file

func (*Session) SetConditionalCacheEnabled added in v1.6.7

func (s *Session) SetConditionalCacheEnabled(enabled bool)

SetConditionalCacheEnabled toggles the session's ETag / If-Modified-Since handling at runtime. When false, the session stops injecting cache validators and stops storing them from responses; the existing cache map is preserved (re-enabling will resume using it). To wipe the stored validators, pair this with ClearCache.

func (*Session) SetCookie

func (s *Session) SetCookie(name, value, domain, path string, secure, httpOnly bool, sameSite string, maxAge int, expires *time.Time)

SetCookie sets a cookie with full metadata. If domain is empty, creates a global cookie (sent to all domains).

func (*Session) SetCookies

func (s *Session) SetCookies(cookies []CookieState)

SetCookies sets multiple cookies from CookieState entries

func (*Session) SetFollowRedirects added in v1.6.7

func (s *Session) SetFollowRedirects(enabled bool)

SetFollowRedirects toggles the session's redirect-following policy at runtime. Per-request overrides via transport.Request.FollowRedirects still take precedence over this value.

func (*Session) SetHeaderOrder added in v1.5.8

func (s *Session) SetHeaderOrder(order []string)

SetHeaderOrder sets a custom header order for all requests. Pass nil or empty slice to reset to preset's default order. Order should contain lowercase header names.

func (*Session) SetMaxRedirects added in v1.6.7

func (s *Session) SetMaxRedirects(max int)

SetMaxRedirects updates the session's redirect cap at runtime. A value of zero or below leaves the cap at the prior setting (or the default of 10 if none was configured).

func (*Session) SetProxy added in v1.5.8

func (s *Session) SetProxy(proxyURL string)

SetProxy sets or updates the proxy for all protocols (HTTP/1.1, HTTP/2, HTTP/3) This closes existing connections and recreates transports with the new proxy

func (*Session) SetSessionIdentifier added in v1.5.8

func (s *Session) SetSessionIdentifier(sessionId string)

SetSessionIdentifier sets a session identifier for TLS cache key isolation. This is used when the session is registered with a LocalProxy to ensure TLS sessions are isolated per proxy/session configuration.

func (*Session) SetTCPProxy added in v1.5.8

func (s *Session) SetTCPProxy(proxyURL string)

SetTCPProxy sets the proxy for TCP protocols (HTTP/1.1, HTTP/2)

func (*Session) SetUDPProxy added in v1.5.8

func (s *Session) SetUDPProxy(proxyURL string)

SetUDPProxy sets the proxy for UDP protocols (HTTP/3 via SOCKS5 or MASQUE)

func (*Session) Stats

func (s *Session) Stats() SessionStats

Stats returns session statistics

func (*Session) Touch

func (s *Session) Touch()

Touch updates the last used timestamp

func (*Session) Warmup added in v1.6.0

func (s *Session) Warmup(ctx context.Context, url string) error

Warmup simulates a real browser page load: fetches the HTML, discovers subresources (CSS, JS, images, fonts), and fetches them in batches with realistic timing. Cookies, TLS sessions, cache state, and client hints all accumulate through the existing Request() pipeline.

Navigation failure returns an error. Subresource failures are silently ignored (matching browser behavior). A non-HTML response returns nil (the navigation still warmed TLS/cookies).

type SessionOptions added in v1.5.8

type SessionOptions struct {
	// SessionCacheBackend is an optional distributed cache for TLS sessions
	SessionCacheBackend transport.SessionCacheBackend

	// SessionCacheErrorCallback is called when backend operations fail
	SessionCacheErrorCallback transport.ErrorCallback

	// CustomJA3 is a JA3 fingerprint string for custom TLS fingerprinting
	CustomJA3 string

	// CustomJA3Extras provides extension data that JA3 cannot capture
	CustomJA3Extras *fingerprint.JA3Extras

	// CustomH2Settings overrides the preset's HTTP/2 settings (from Akamai fingerprint)
	CustomH2Settings *fingerprint.HTTP2Settings

	// CustomPseudoOrder overrides the pseudo-header order (from Akamai fingerprint)
	CustomPseudoOrder []string

	// CustomTCPFingerprint overrides individual TCP/IP fingerprint fields from the preset
	CustomTCPFingerprint *fingerprint.TCPFingerprint
}

SessionOptions contains additional options that can't be expressed in protocol.SessionConfig (e.g., interfaces and callbacks that can't be JSON serialized)

type SessionState added in v1.5.5

type SessionState struct {
	Version   int       `json:"version"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// Full session configuration - saves everything
	Config *protocol.SessionConfig `json:"config"`

	// Session data - v5 format: cookies keyed by domain
	// Key is the domain (e.g., ".example.com" for domain cookies, "example.com" for host-only)
	Cookies map[string][]CookieState `json:"cookies"`

	// TLS Sessions keyed by origin "protocol:host:port"
	// e.g., "h2:example.com:443", "h3:api.example.com:443"
	TLSSessions map[string]transport.TLSSessionState `json:"tls_sessions"`

	// ECHConfigs stores ECH configurations per domain (base64 encoded)
	// This is essential for session resumption - the same ECH config must be used
	// when resuming as was used when creating the session ticket
	ECHConfigs map[string]string `json:"ech_configs,omitempty"`
}

SessionState represents the complete saveable session state

type SessionStateV4 added in v1.5.10

type SessionStateV4 struct {
	Version     int                                  `json:"version"`
	CreatedAt   time.Time                            `json:"created_at"`
	UpdatedAt   time.Time                            `json:"updated_at"`
	Config      *protocol.SessionConfig              `json:"config"`
	Cookies     []CookieState                        `json:"cookies"` // v4: flat list
	TLSSessions map[string]transport.TLSSessionState `json:"tls_sessions"`
	ECHConfigs  map[string]string                    `json:"ech_configs,omitempty"`
}

SessionStateV4 represents the v4 format for migration

type SessionStats

type SessionStats struct {
	ID              string
	Preset          string
	CreatedAt       time.Time
	LastUsed        time.Time
	RequestCount    int64
	Active          bool
	CookieCount     int
	CacheEntryCount int // Number of cached URLs (for If-None-Match/If-Modified-Since)
	Age             time.Duration
	IdleTime        time.Duration
	TransportStats  map[string]interface{}
}

SessionStats contains session statistics

type StreamResponse added in v1.5.3

type StreamResponse = transport.StreamResponse

StreamResponse wraps transport.StreamResponse for session-level streaming

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL