core

package module
v1.0.28 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: BSD-3-Clause Imports: 18 Imported by: 13

Documentation

Overview

Package core re-exports error types from the canonical errors package for backward compatibility. New code should import modules/errors directly.

Package core provides object pool implementation to reduce GC pressure

Package core provides memory pool monitoring metrics

Package core provides core interface definitions

Package core provides core types and fundamental definitions for the fingerprint library This is the base dependency for all modules, does not depend on any other internal packages

Package core provides utility functions

Package core provides input validation utilities

Index

Constants

View Source
const (
	// DefaultTimeout default timeout duration
	DefaultTimeout = 30 * time.Second
	// DefaultDialTimeout default connection timeout
	DefaultDialTimeout = 10 * time.Second
	// DefaultTLSTimeout default TLS handshake timeout
	DefaultTLSTimeout = 15 * time.Second
	// DefaultDNSTimeout default DNS resolution timeout
	DefaultDNSTimeout = 5 * time.Second
	// DefaultReadTimeout default read timeout
	DefaultReadTimeout = 10 * time.Second
)
View Source
const (
	// DefaultCacheSize default cache size
	DefaultCacheSize = 10000
	// DefaultCacheTTL default cache expiration time
	DefaultCacheTTL = 5 * time.Minute
	// MaxCacheKeySize maximum cache key length
	MaxCacheKeySize = 1024
)
View Source
const (
	// DefaultRateLimit default requests per second limit
	DefaultRateLimit = 1000
	// DefaultRateLimitBurst default burst request count
	DefaultRateLimitBurst = 2000
	// DefaultRateLimitWindow default rate limit window
	DefaultRateLimitWindow = time.Second
	// DefaultVisitorTTL default visitor log expiration time
	DefaultVisitorTTL = 5 * time.Minute
)
View Source
const (
	// MaxRequestBodySize maximum request body size (5MB)
	MaxRequestBodySize = 5 * 1024 * 1024
	// MaxRedirects maximum redirect count
	MaxRedirects = 10
	// MaxHeaderSize maximum header size (1MB)
	MaxHeaderSize = 1 * 1024 * 1024
)
View Source
const (
	// RiskThresholdLow low risk threshold
	RiskThresholdLow = 0.1
	// RiskThresholdMedium medium risk threshold
	RiskThresholdMedium = 0.4
	// RiskThresholdHigh high risk threshold
	RiskThresholdHigh = 0.7
	// RiskThresholdCritical critical risk threshold
	RiskThresholdCritical = 0.9
)
View Source
const (
	// TLSVersion13 TLS 1.3
	TLSVersion13 = 0x0304
	// TLSVersion12 TLS 1.2
	TLSVersion12 = 0x0303
	// TLSVersion11 TLS 1.1
	TLSVersion11 = 0x0302
	// TLSVersion10 TLS 1.0
	TLSVersion10 = 0x0301
)
View Source
const (
	// DefaultHTTPTimeout default HTTP timeout
	DefaultHTTPTimeout = 30 * time.Second
	// DefaultHTTPReadTimeout HTTP read timeout
	DefaultHTTPReadTimeout = 10 * time.Second
	// DefaultHTTPWriteTimeout HTTP write timeout
	DefaultHTTPWriteTimeout = 10 * time.Second
	// DefaultIdleConnTimeout idle connection timeout
	DefaultIdleConnTimeout = 30 * time.Second
	// DefaultResponseHeaderTimeout response header timeout
	DefaultResponseHeaderTimeout = 8 * time.Second
	// DefaultExpectContinueTimeout ExpectContinue timeout
	DefaultExpectContinueTimeout = 1 * time.Second
	// DefaultKeepAliveInterval TCP keep-alive interval
	DefaultKeepAliveInterval = 30 * time.Second
)
View Source
const (
	// DefaultScanTimeout default scan timeout
	DefaultScanTimeout = 20 * time.Second
	// MinScanTimeout minimum scan timeout
	MinScanTimeout = 10 * time.Second
	// MaxScanTimeout maximum scan timeout
	MaxScanTimeout = 120 * time.Second
	// DefaultBrowserTimeout default browser scraping timeout
	DefaultBrowserTimeout = 25 * time.Second
	// DefaultBrowserWaitMs browser wait milliseconds
	DefaultBrowserWaitMs = 1200
	// MaxBrowserWaitMs maximum browser wait milliseconds
	MaxBrowserWaitMs = 3500
	// DefaultRemainingBudget default remaining time budget
	DefaultRemainingBudget = 12 * time.Second
	// MinRequestTimeout minimumrequesttimeout
	MinRequestTimeout = 3 * time.Second
	// MaxRequestTimeout maximumrequesttimeout
	MaxRequestTimeout = 20 * time.Second
)
View Source
const (
	// DefaultSessionTimeout default session timeout
	DefaultSessionTimeout = 30 * time.Minute
	// DefaultPoolIdleTime connection pool idle time
	DefaultPoolIdleTime = 10 * time.Minute
)
View Source
const (
	// Size1KB 1 KB
	Size1KB = 1024
	// Size1MB 1 MB
	Size1MB = 1024 * 1024
	// Size5MB 5 MB
	Size5MB = 5 * 1024 * 1024
	// Size10MB 10 MB
	Size10MB = 10 * 1024 * 1024
	// MaxCapturedScriptBytes maximum captured script bytes
	MaxCapturedScriptBytes = 1 * 1024 * 1024
	// MaxConfigDataSize maximumconfigurationdatasize
	MaxConfigDataSize = 1 * 1024 * 1024
)
View Source
const (
	ErrCodeInvalidInput   = errs.ErrCodeInvalidInput
	ErrCodeRequiredField  = errs.ErrCodeRequiredField
	ErrCodeInvalidFormat  = errs.ErrCodeInvalidFormat
	ErrCodeOutOfRange     = errs.ErrCodeOutOfRange
	ErrCodeNilPointer     = errs.ErrCodeNilPointer
	ErrCodeInvalidType    = errs.ErrCodeInvalidType
	ErrCodeEmptyValue     = errs.ErrCodeEmptyValue
	ErrCodeInvalidLength  = errs.ErrCodeInvalidLength
	ErrCodeInvalidCharset = errs.ErrCodeInvalidCharset
	ErrCodeInvalidPattern = errs.ErrCodeInvalidPattern
)

Validation error codes (VAL001-VAL010)

View Source
const (
	ErrCodeProfileNotFound  = errs.ErrCodeProfileNTF
	ErrCodeResourceNotFound = errs.ErrCodeResourceNTF
	ErrCodeKeyNotFound      = errs.ErrCodeKeyNTF
	ErrCodeFileNotFound     = errs.ErrCodeFileNTF
	ErrCodeRouteNotFound    = errs.ErrCodeRouteNTF
)

Not Found error codes (NTF001-NTF005)

View Source
const (
	ErrCodeSecurityError       = errs.ErrCodeSecurityError
	ErrCodeAuthFailed          = errs.ErrCodeAuthFailed
	ErrCodeUnauthorized        = errs.ErrCodeUnauthorized
	ErrCodeForbidden           = errs.ErrCodeForbidden
	ErrCodeInvalidToken        = errs.ErrCodeInvalidToken
	ErrCodeReplayAttack        = errs.ErrCodeReplayAttack
	ErrCodeFingerprintMismatch = errs.ErrCodeFingerprintMismatch
	ErrCodeInvalidTLSVersion   = errs.ErrCodeInvalidTLSVersion
	ErrCodeInvalidJA3Hash      = errs.ErrCodeInvalidJA3Hash
	ErrCodeInvalidJA4Hash      = errs.ErrCodeInvalidJA4Hash
)

Security error codes (SEC001-SEC010)

View Source
const (
	QUICVersion1       uint32 = 0x00000001 // RFC 9000
	QUICVersionDraft29 uint32 = 0xff00001d // Draft 29
	QUICVersionDraft30 uint32 = 0xff00001e // Draft 30
	QUICVersionDraft31 uint32 = 0xff00001f // Draft 31
	QUICVersionDraft32 uint32 = 0xff000020 // Draft 32
)

QUICVersion defines known QUIC versions

Variables

View Source
var (
	ErrInvalidProfile          = errs.ErrInvalidProfile
	ErrProfileNotFound         = errs.ErrProfileNotFound
	ErrUnsupportedBrowser      = errs.ErrUnsupportedBrowser
	ErrInvalidTLSVersion       = errs.ErrInvalidTLSVersion
	ErrInvalidJA3Hash          = errs.ErrInvalidJA3Hash
	ErrInvalidJA4Hash          = errs.ErrInvalidJA4Hash
	ErrFeatureExtractionFailed = errs.ErrFeatureExtractionFailed
	ErrClassificationFailed    = errs.ErrClassificationFailed
	ErrRiskAssessmentFailed    = errs.ErrRiskAssessmentFailed
	ErrNilPointer              = errs.ErrNilPointer
	ErrInvalidInput            = errs.ErrInvalidInput
	ErrOutOfRange              = errs.ErrOutOfRange
	ErrEmptyValue              = errs.ErrEmptyValue
	ErrAlreadyExists           = errs.ErrAlreadyExists
)

Sentinel errors re-exported from errors package

View Source
var DefaultPoolConfig = PoolConfig{
	MaxSize:       10000,
	InitialSize:   100,
	EnableMetrics: true,
}

DefaultPoolConfig default pool configuration

View Source
var GlobalMonitor = NewPoolMonitor()

GlobalMonitor global monitor instance

View Source
var GlobalPoolMetrics = struct {
	// individual pool statistics
	FeatureVectorGets int64
	FeatureVectorPuts int64
	FeatureVectorHits int64
	HTTPHeadersGets   int64
	HTTPHeadersPuts   int64
	HTTPHeadersHits   int64
	StringBuilderGets int64
	StringBuilderPuts int64
	MapPoolGets       int64
	MapPoolPuts       int64
	SlicePoolGets     int64
	SlicePoolPuts     int64

	// summaries
	TotalAllocations int64
	TotalReleases    int64
}{}

GlobalPoolMetrics global pool metrics (atomic operations)

OperatingSystems operating system list (for random selection, deduplicated to avoid probability bias)

View Source
var Pools = &GlobalPools{}

Pools global pool instances

Functions

func AcquireBuffer

func AcquireBuffer() *bytes.Buffer

AcquireBuffer get bytes.Buffer

func AcquireMap

func AcquireMap() map[string]interface{}

AcquireMap get map

func AcquireSlice

func AcquireSlice() []byte

AcquireSlice get byte slice

func AcquireStringBuilder

func AcquireStringBuilder() *strings.Builder

AcquireStringBuilder get strings.Builder

func CalculateJA3Hash

func CalculateJA3Hash(tlsVersion uint16, cipherSuites, extensions, curves, points []uint16) string

CalculateJA3Hash calculates JA3 hash (simplified version)

func CalculateMD5

func CalculateMD5(data []byte) string

CalculateMD5 calculates MD5 hash

func CalculateSHA256

func CalculateSHA256(data []byte) string

CalculateSHA256 calculates SHA256 hash

func Contains

func Contains[T comparable](slice []T, elem T) bool

Contains checks if slice contains element

func CopyMap

func CopyMap(m map[string]string) map[string]string

CopyMap copies map

func Filter

func Filter[T any](slice []T, predicate func(T) bool) []T

Filter filters slice elements

func ForceGC

func ForceGC() runtime.MemStats

ForceGC forces garbage collection and returns statistics

func GenerateRandomID

func GenerateRandomID() string

GenerateRandomID generates random ID

func GetAllPoolStats

func GetAllPoolStats() map[string]PoolStats

GetAllPoolStats gets all pool statistics

func GetMemoryStats

func GetMemoryStats() runtime.MemStats

GetMemoryStats gets memory statistics

func HexSliceToString

func HexSliceToString(data []byte) string

HexSliceToString converts byte slice to hexadecimal string

func InitPools

func InitPools()

InitPools initializes global object pools

func InitPoolsWithConfig

func InitPoolsWithConfig(config *PoolConfig)

InitPoolsWithConfig initializes global object pools with custom configuration

func IsCoreError

func IsCoreError(err error) bool

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

func Map

func Map[T, U any](slice []T, mapper func(T) U) []U

Map maps slice elements

func MergeMaps

func MergeMaps(maps ...map[string]string) map[string]string

MergeMaps merges multiple maps

func NormalizeString

func NormalizeString(s string) string

NormalizeString normalizes string (lowercase, trim spaces)

func ParseTLSVersion

func ParseTLSVersion(version string) uint16

ParseTLSVersion parses TLS version string

func PtrBool

func PtrBool(b bool) *bool

PtrBool creates bool pointer

func PtrInt

func PtrInt(i int) *int

PtrInt creates int pointer

func PtrString

func PtrString(s string) *string

PtrString creates string pointer

func RandomChoice

func RandomChoice[T any](slice []T) T

RandomChoice randomly selects one element from slice

func RandomChoiceWithSeed

func RandomChoiceWithSeed[T any](slice []T, seed int64) T

RandomChoiceWithSeed randomly selects from slice using specified seed

func ReleaseBuffer

func ReleaseBuffer(b *bytes.Buffer)

ReleaseBuffer releases bytes.Buffer back to pool

func ReleaseFeatureVector

func ReleaseFeatureVector(fv *FeatureVector)

ReleaseFeatureVector releases FeatureVector back to pool

func ReleaseHTTPHeaders

func ReleaseHTTPHeaders(h *HTTPHeaders)

ReleaseHTTPHeaders releases HTTPHeaders back to pool

func ReleaseMap

func ReleaseMap(m map[string]interface{})

ReleaseMap releases map back to pool

func ReleaseSlice

func ReleaseSlice(s []byte)

ReleaseSlice releases byte slice back to pool

func ReleaseStringBuilder

func ReleaseStringBuilder(sb *strings.Builder)

ReleaseStringBuilder releases strings.Builder back to pool

func ResetPoolMetrics

func ResetPoolMetrics()

ResetPoolMetrics resets all pool metrics

func SafeDereference

func SafeDereference(ptr *int, defaultVal int) int

SafeDereference safely dereferences pointer

func SafeSliceAccess

func SafeSliceAccess(slice []interface{}, index int) (interface{}, bool)

SafeSliceAccess safely accesses slice

func SafeString

func SafeString(s *string) string

SafeString safely gets string (handles nil)

func SanitizeString

func SanitizeString(s string, maxLen int) string

SanitizeString sanitizes string input

func Shuffle

func Shuffle[T any](slice []T)

Shuffle randomly shuffles slice order

func StringSliceToString

func StringSliceToString(slice []string) string

StringSliceToString converts string slice to comma-separated string

func TLSVersionToString

func TLSVersionToString(version uint16) string

TLSVersionToString converts TLS version to string

func TruncateString

func TruncateString(s string, maxLen int) string

TruncateString truncates string to specified length

func Uint16SliceToString

func Uint16SliceToString(slice []uint16) string

Uint16SliceToString converts uint16 slice to comma-separated string

func Unique

func Unique[T comparable](slice []T) []T

Unique deduplicates slice elements

func ValidateJA3Hash

func ValidateJA3Hash(hash string) error

ValidateJA3Hash validates JA3 hash

func ValidateTLSVersion

func ValidateTLSVersion(version uint16) error

ValidateTLSVersion validates TLS version

Types

type BrowserType

type BrowserType string

BrowserType browser type

const (
	BrowserChrome  BrowserType = "chrome"
	BrowserFirefox BrowserType = "firefox"
	BrowserSafari  BrowserType = "safari"
	BrowserOpera   BrowserType = "opera"
	BrowserEdge    BrowserType = "edge"
	BrowserBrave   BrowserType = "brave"
	BrowserSamsung BrowserType = "samsung"
)

type BufferPool

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

BufferPool bytes.Buffer object pool

func NewBufferPool

func NewBufferPool(config *PoolConfig) *BufferPool

NewBufferPool creates a new Buffer pool

func (*BufferPool) Get

func (p *BufferPool) Get() *bytes.Buffer

Get fetches bytes.Buffer from pool

func (*BufferPool) Put

func (p *BufferPool) Put(b *bytes.Buffer)

Put returns bytes.Buffer back to pool

func (*BufferPool) Stats

func (p *BufferPool) Stats() PoolStats

Stats gets pool statistics

type ClassificationResult

type ClassificationResult struct {
	Protocol   ProtocolType
	Family     BrowserType
	Version    string
	Confidence float64
	Labels     map[string]string
}

ClassificationResult classifyresult

type ClientHelloSpec

type ClientHelloSpec struct {
	CipherSuites       []uint16
	Extensions         []TLSExtension
	SupportedCurves    []CurveID
	SupportedPoints    []uint8
	TLSVersion         uint16
	CompressionMethods []uint8
}

ClientHelloSpec TLS ClientHello specification

type CoreError

type CoreError = errs.CoreError

func NewCodedError

func NewCodedError(code ErrorCode, op string, err error) *CoreError

Error creation functions re-exported from errors package

func NewCodedErrorf

func NewCodedErrorf(code ErrorCode, op, format string, args ...interface{}) *CoreError

func WrapError

func WrapError(code ErrorCode, op string, err error, context string) *CoreError

func WrapErrorf

func WrapErrorf(code ErrorCode, op string, err error, format string, args ...interface{}) *CoreError

type CurveID

type CurveID uint16

CurveID elliptic curve ID

const (
	CurveX25519    CurveID = 0x001d
	CurveP256      CurveID = 0x0017
	CurveP384      CurveID = 0x0018
	CurveP521      CurveID = 0x0019
	CurveP256Kyber CurveID = 0x6399
)

type ErrorCode

type ErrorCode = errs.ErrorCode

Type aliases — identical to modules/errors types

func GetErrorCode

func GetErrorCode(err error) ErrorCode

type FeatureType

type FeatureType string

FeatureType featuretype

const (
	FeatureTLSVersion      FeatureType = "tls_version"
	FeatureCipherSuites    FeatureType = "cipher_suites"
	FeatureExtensions      FeatureType = "extensions"
	FeatureHTTP2Settings   FeatureType = "http2_settings"
	FeatureHTTPHeaders     FeatureType = "http_headers"
	FeatureUserAgent       FeatureType = "user_agent"
	FeatureCanvas          FeatureType = "canvas"
	FeatureWebGL           FeatureType = "webgl"
	FeatureAudio           FeatureType = "audio"
	FeatureFonts           FeatureType = "fonts"
	FeatureStorage         FeatureType = "storage"
	FeatureWebRTC          FeatureType = "webrtc"
	FeatureHardware        FeatureType = "hardware"
	FeatureTiming          FeatureType = "timing"
	FeatureHeadlessBrowser FeatureType = "headless_browser"
	FeatureEntropy         FeatureType = "entropy"
	FeatureToolMarker      FeatureType = "tool_marker"
	FeatureBehaviorPattern FeatureType = "behavior_pattern"
)

type FeatureVector

type FeatureVector struct {
	Features map[FeatureType]float64
	Metadata map[string]interface{}
}

FeatureVector feature vector

func AcquireFeatureVector

func AcquireFeatureVector() *FeatureVector

AcquireFeatureVector get FeatureVector

func NewFeatureVector

func NewFeatureVector() *FeatureVector

NewFeatureVector creates new feature vector

func (*FeatureVector) Get

func (fv *FeatureVector) Get(feature FeatureType) float64

Get gets feature value

func (*FeatureVector) Set

func (fv *FeatureVector) Set(feature FeatureType, value float64)

Set sets feature value

type FeatureVectorPool

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

FeatureVectorPool FeatureVector object pool

func NewFeatureVectorPool

func NewFeatureVectorPool(config *PoolConfig) *FeatureVectorPool

NewFeatureVectorPool creates a new FeatureVector pool

func (*FeatureVectorPool) Get

func (p *FeatureVectorPool) Get() *FeatureVector

Get fetches FeatureVector from pool

func (*FeatureVectorPool) Put

func (p *FeatureVectorPool) Put(fv *FeatureVector)

Put returns FeatureVector back to pool

func (*FeatureVectorPool) Stats

func (p *FeatureVectorPool) Stats() PoolStats

Stats gets pool statistics

type FingerprintResult

type FingerprintResult interface {
	// GetUserAgent return User-Agent
	GetUserAgent() string
	// GetHeaders return HTTP Headers
	GetHeaders() *HTTPHeaders
	// GetSpec returns fingerprint specification
	GetSpec() FingerprintSpec
}

FingerprintResult fingerprint result interface

type FingerprintSpec

type FingerprintSpec interface {
	// GetID returns unique fingerprint identifier
	GetID() string
	// GetBrowserType returns browser type
	GetBrowserType() BrowserType
	// GetOS returns operating system
	GetOS() OperatingSystem
}

FingerprintSpec fingerprint specification interface

type GlobalPools

type GlobalPools struct {
	FeatureVectors *FeatureVectorPool
	HTTPHeaders    *HTTPHeadersPool
	Strings        *StringBuilderPool
	Buffers        *BufferPool
	Maps           *MapPool
	Slices         *SlicePool
}

type HTTP2Priority

type HTTP2Priority struct {
	StreamID  uint32
	Weight    uint8
	DependsOn uint32
	Exclusive bool
}

HTTP2Priority HTTP/2 Priority

type HTTP2Settings

type HTTP2Settings struct {
	HeaderTableSize      uint32
	EnablePush           uint32
	MaxConcurrentStreams uint32
	InitialWindowSize    uint32
	MaxFrameSize         uint32
	MaxHeaderListSize    uint32
}

HTTP2Settings HTTP/2 Settings

type HTTP3Settings added in v1.0.5

type HTTP3Settings struct {
	QUICVersion            uint32 // QUIC version (e.g., 0x00000001 for RFC 9000)
	InitialMaxData         uint64 // initial maximum data
	InitialMaxStreamData   uint64 // initial maximum stream data
	InitialMaxStreamsBidi  uint64 // initial maximum bidirectional streams
	InitialMaxStreamsUni   uint64 // initial maximum unidirectional streams
	MaxUDPPayloadSize      uint64 // maximum UDP payload size
	AckDelayExponent       uint8  // ACK delay exponent
	MaxAckDelay            uint16 // maximum ACK delay (ms)
	DisableActiveMigration bool   // disable active connection migration
}

HTTP3Settings HTTP/3 (QUIC) Settings

type HTTPHeaders

type HTTPHeaders struct {
	Accept                  string            // Accept header
	AcceptLanguage          string            // Accept-Language header (supports global languages)
	AcceptEncoding          string            // Accept-Encoding header
	UserAgent               string            // User-Agent header
	SecFetchSite            string            // Sec-Fetch-Site header
	SecFetchMode            string            // Sec-Fetch-Mode header
	SecFetchUser            string            // Sec-Fetch-User header
	SecFetchDest            string            // Sec-Fetch-Dest header
	SecCHUA                 string            // Sec-CH-UA header
	SecCHUAMobile           string            // Sec-CH-UA-Mobile header
	SecCHUAPlatform         string            // Sec-CH-UA-Platform header
	UpgradeInsecureRequests string            // Upgrade-Insecure-Requests header
	Custom                  map[string]string // user-defined headers
}

HTTPHeaders standard HTTP request headers

func AcquireHTTPHeaders

func AcquireHTTPHeaders() *HTTPHeaders

AcquireHTTPHeaders get HTTPHeaders

func (*HTTPHeaders) Clone

func (h *HTTPHeaders) Clone() *HTTPHeaders

Clone clones HTTPHeaders object, returns a new copy

func (*HTTPHeaders) Merge

func (h *HTTPHeaders) Merge(customHeaders map[string]string) *HTTPHeaders

Merge merges user-defined headers

func (*HTTPHeaders) Set

func (h *HTTPHeaders) Set(key, value string)

Set sets user-defined header

func (*HTTPHeaders) SetHeaders

func (h *HTTPHeaders) SetHeaders(customHeaders map[string]string)

SetHeaders batch sets user-defined headers

func (*HTTPHeaders) ToMap

func (h *HTTPHeaders) ToMap() map[string]string

ToMap converts HTTPHeaders to map[string]string

func (*HTTPHeaders) ToMapWithCustom

func (h *HTTPHeaders) ToMapWithCustom(customHeaders map[string]string) map[string]string

ToMapWithCustom converts HTTPHeaders to map[string]string and merges user-defined headers

type HTTPHeadersPool

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

HTTPHeadersPool HTTPHeaders object pool

func NewHTTPHeadersPool

func NewHTTPHeadersPool(config *PoolConfig) *HTTPHeadersPool

NewHTTPHeadersPool creates a new HTTPHeaders pool

func (*HTTPHeadersPool) Get

func (p *HTTPHeadersPool) Get() *HTTPHeaders

Get fetches HTTPHeaders from pool

func (*HTTPHeadersPool) Put

func (p *HTTPHeadersPool) Put(h *HTTPHeaders)

Put returns HTTPHeaders back to pool

func (*HTTPHeadersPool) Stats

func (p *HTTPHeadersPool) Stats() PoolStats

Stats gets pool statistics

type Logger added in v1.0.5

type Logger interface {
	// Debug logdebuginfo
	Debug(msg string, keysAndValues ...any)
	// Info logs general information
	Info(msg string, keysAndValues ...any)
	// Warn logwarninginfo
	Warn(msg string, keysAndValues ...any)
	// Error logerrorinfo
	Error(msg string, keysAndValues ...any)
}

Logger standard logging interface design principle: minimal interface, adapts to most logging libraries

func NewDefaultLogger added in v1.0.5

func NewDefaultLogger(level string) Logger

NewDefaultLogger creates default slog logger

func NewLogrusAdapter added in v1.0.5

func NewLogrusAdapter(logger LogrusLogger) Logger

NewLogrusAdapter create logrus adapter

func NewSlogAdapter added in v1.0.5

func NewSlogAdapter(logger *slog.Logger) Logger

NewSlogAdapter create slog adapter

func NewStdLoggerAdapter added in v1.0.5

func NewStdLoggerAdapter(logger *log.Logger) Logger

NewStdLoggerAdapter creates standard library log adapter

func NewZapAdapter added in v1.0.5

func NewZapAdapter(logger ZapLogger) Logger

NewZapAdapter create zap adapter

type LogrusAdapter added in v1.0.5

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

LogrusAdapter adapts logrus.Logger

func (*LogrusAdapter) Debug added in v1.0.5

func (a *LogrusAdapter) Debug(msg string, keysAndValues ...any)

func (*LogrusAdapter) Error added in v1.0.5

func (a *LogrusAdapter) Error(msg string, keysAndValues ...any)

func (*LogrusAdapter) Info added in v1.0.5

func (a *LogrusAdapter) Info(msg string, keysAndValues ...any)

func (*LogrusAdapter) Warn added in v1.0.5

func (a *LogrusAdapter) Warn(msg string, keysAndValues ...any)

type LogrusLogger added in v1.0.5

type LogrusLogger interface {
	Debug(args ...any)
	Info(args ...any)
	Warn(args ...any)
	Error(args ...any)
	WithFields(fields map[string]any) LogrusLogger
}

LogrusLogger interface definition (avoid direct dependency on logrus)

type MapPool

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

MapPool map object pool

func NewMapPool

func NewMapPool(config *PoolConfig) *MapPool

NewMapPool creates a new Map pool

func (*MapPool) Get

func (p *MapPool) Get() map[string]interface{}

Get fetches map from pool

func (*MapPool) Put

func (p *MapPool) Put(m map[string]interface{})

Put returns map back to pool

func (*MapPool) Stats

func (p *MapPool) Stats() PoolStats

Stats gets pool statistics

type NoOpLogger added in v1.0.5

type NoOpLogger struct{}

NoOpLogger empty log implementation, used for default values or testing

func (NoOpLogger) Debug added in v1.0.5

func (l NoOpLogger) Debug(msg string, keysAndValues ...any)

func (NoOpLogger) Error added in v1.0.5

func (l NoOpLogger) Error(msg string, keysAndValues ...any)

func (NoOpLogger) Info added in v1.0.5

func (l NoOpLogger) Info(msg string, keysAndValues ...any)

func (NoOpLogger) Warn added in v1.0.5

func (l NoOpLogger) Warn(msg string, keysAndValues ...any)

type OperatingSystem

type OperatingSystem string

OperatingSystem operating system type

const (
	OSWindows10 OperatingSystem = "Windows NT 10.0; Win64; x64"
	// OSWindows11 UA is same as Win10 (actual browser behavior), distinguished by Sec-CH-UA-Platform-Version
	OSWindows11 OperatingSystem = "Windows NT 10.0; Win64; x64"
	OSMacOS13   OperatingSystem = "Macintosh; Intel Mac OS X 13_0_0"
	OSMacOS14   OperatingSystem = "Macintosh; Intel Mac OS X 14_0_0"
	OSMacOS15   OperatingSystem = "Macintosh; Intel Mac OS X 15_0_0"
	OSLinux     OperatingSystem = "X11; Linux x86_64"
	// Following Linux distributions have same UA (actual browser behavior), aliases kept for semantic distinction
	OSLinuxUbuntu OperatingSystem = "X11; Linux x86_64"
	OSLinuxDebian OperatingSystem = "X11; Linux x86_64"
	OSLinuxFedora OperatingSystem = "X11; Linux x86_64"
	OSiOS         OperatingSystem = "iPhone; CPU iPhone OS 17_0"
	OSiPadOS      OperatingSystem = "iPad; CPU OS 17_0"
	OSAndroid     OperatingSystem = "Linux; Android 14"
)

type PoolConfig

type PoolConfig struct {
	// MaxSize maximum number of objects in pool (0 = unlimited)
	MaxSize int

	// InitialSize initial number of objects
	InitialSize int

	// EnableMetrics whether to enable monitoring
	EnableMetrics bool
}

PoolConfig pool configuration

type PoolMonitor

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

PoolMonitor pool monitoring manager

func NewPoolMonitor

func NewPoolMonitor() *PoolMonitor

NewPoolMonitor creates new pool monitor

func (*PoolMonitor) AllStats

func (pm *PoolMonitor) AllStats() map[string]PoolStats

AllStats gets all pool statistics

func (*PoolMonitor) Get

func (pm *PoolMonitor) Get(name string) (*poolMetrics, bool)

Get gets pool metrics

func (*PoolMonitor) Register

func (pm *PoolMonitor) Register(name string) *poolMetrics

Register registers pool metrics

func (*PoolMonitor) ResetAll

func (pm *PoolMonitor) ResetAll()

ResetAll resets all statistics

func (*PoolMonitor) Summary

func (pm *PoolMonitor) Summary() PoolSummary

Summary gets summary statistics

type PoolStats

type PoolStats struct {
	Name          string  `json:"name"`
	HitRate       float64 `json:"hit_rate"`       // cache hit rate
	ObjectsInUse  int64   `json:"objects_in_use"` // number of objects in use
	TotalGets     int64   `json:"total_gets"`     // total get count
	TotalPuts     int64   `json:"total_puts"`     // total put count
	CacheHits     int64   `json:"cache_hits"`     // cache hit count
	CacheMisses   int64   `json:"cache_misses"`   // cache miss count
	ActiveObjects int64   `json:"active_objects"` // current active object count (estimated)
}

PoolStats memory pool statistics info

func GetPoolStats

func GetPoolStats(name string) (PoolStats, bool)

GetPoolStats gets statistics for specified pool

type PoolSummary

type PoolSummary struct {
	PoolCount      int                  `json:"pool_count"`
	TotalGets      int64                `json:"total_gets"`
	TotalPuts      int64                `json:"total_puts"`
	TotalHits      int64                `json:"total_hits"`
	TotalMisses    int64                `json:"total_misses"`
	TotalInUse     int64                `json:"total_in_use"`
	OverallHitRate float64              `json:"overall_hit_rate"`
	Pools          map[string]PoolStats `json:"pools"`
}

PoolSummary pool summary statistics

func GetPoolSummary

func GetPoolSummary() PoolSummary

GetPoolSummary gets pool summary statistics

type ProtocolType

type ProtocolType string

ProtocolType protocoltype

const (
	ProtocolTLS   ProtocolType = "tls"
	ProtocolHTTP  ProtocolType = "http"
	ProtocolHTTP2 ProtocolType = "http2"
	ProtocolQUIC  ProtocolType = "quic"
	ProtocolHTTP3 ProtocolType = "http3"
)

type RiskAssessment

type RiskAssessment struct {
	Score       float64
	Level       RiskLevel
	Factors     []RiskFactor
	Suggestions []string
}

RiskAssessment risk assessment result

type RiskFactor

type RiskFactor struct {
	Name        string
	Weight      float64
	Description string
}

RiskFactor risk factor

type RiskLevel

type RiskLevel int

RiskLevel risk level

const (
	RiskLevelNone     RiskLevel = 0
	RiskLevelLow      RiskLevel = 1
	RiskLevelMedium   RiskLevel = 2
	RiskLevelHigh     RiskLevel = 3
	RiskLevelCritical RiskLevel = 4
)

func RiskLevelFromScore added in v1.0.5

func RiskLevelFromScore(score float64) RiskLevel

RiskLevelFromScore calculates risk level from risk score score range: 0.0-1.0

func (RiskLevel) String

func (r RiskLevel) String() string

String returns string representation of risk level

type SlicePool

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

SlicePool byte slice object pool

func NewSlicePool

func NewSlicePool(size int, config *PoolConfig) *SlicePool

NewSlicePool creates a new Slice pool

func (*SlicePool) Get

func (p *SlicePool) Get() []byte

Get fetches byte slice from pool

func (*SlicePool) Put

func (p *SlicePool) Put(s []byte)

Put returns byte slice back to pool

func (*SlicePool) Stats

func (p *SlicePool) Stats() PoolStats

Stats gets pool statistics

type SlogAdapter added in v1.0.5

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

SlogAdapter adapts slog.Logger

func (*SlogAdapter) Debug added in v1.0.5

func (a *SlogAdapter) Debug(msg string, keysAndValues ...any)

func (*SlogAdapter) Error added in v1.0.5

func (a *SlogAdapter) Error(msg string, keysAndValues ...any)

func (*SlogAdapter) Info added in v1.0.5

func (a *SlogAdapter) Info(msg string, keysAndValues ...any)

func (*SlogAdapter) Warn added in v1.0.5

func (a *SlogAdapter) Warn(msg string, keysAndValues ...any)

type StdLoggerAdapter added in v1.0.5

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

StdLoggerAdapter adapts standard library log.Logger

func (*StdLoggerAdapter) Debug added in v1.0.5

func (a *StdLoggerAdapter) Debug(msg string, keysAndValues ...any)

func (*StdLoggerAdapter) Error added in v1.0.5

func (a *StdLoggerAdapter) Error(msg string, keysAndValues ...any)

func (*StdLoggerAdapter) Info added in v1.0.5

func (a *StdLoggerAdapter) Info(msg string, keysAndValues ...any)

func (*StdLoggerAdapter) Warn added in v1.0.5

func (a *StdLoggerAdapter) Warn(msg string, keysAndValues ...any)

type StringBuilderPool

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

StringBuilderPool strings.Builder object pool

func NewStringBuilderPool

func NewStringBuilderPool(config *PoolConfig) *StringBuilderPool

NewStringBuilderPool creates a new StringBuilder pool

func (*StringBuilderPool) Get

func (p *StringBuilderPool) Get() *strings.Builder

Get fetches strings.Builder from pool

func (*StringBuilderPool) Put

func (p *StringBuilderPool) Put(sb *strings.Builder)

Put returns strings.Builder back to pool

func (*StringBuilderPool) Stats

func (p *StringBuilderPool) Stats() PoolStats

Stats gets pool statistics

type TLSClient

type TLSClient interface {
	// GetClientHelloSpec returns ClientHello specification
	GetClientHelloSpec() (ClientHelloSpec, error)
	// GetJA3 returns JA3 fingerprint string
	GetJA3() string
	// GetJA4 returns JA4 fingerprint string
	GetJA4() string
}

TLSClient defines TLS client capabilities

type TLSExtension

type TLSExtension struct {
	Type uint16
	Data []byte
}

TLSExtension TLS extension definition

type UserAgentTemplate

type UserAgentTemplate struct {
	Browser    BrowserType
	Version    string
	Template   string // template string, use %s placeholder for operating system
	Mobile     bool   // whether it is mobile
	OSRequired bool   // whether operating system info is required
}

UserAgentTemplate User-Agent template

type Validator

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

Validator input validator

func NewValidator

func NewValidator() *Validator

NewValidator creates new validator

func (*Validator) AddError

func (v *Validator) AddError(err error)

AddError adds error

func (*Validator) AddErrorf

func (v *Validator) AddErrorf(format string, args ...interface{})

AddErrorf adds formatted error

func (*Validator) Error

func (v *Validator) Error() error

Error returns combined error

func (*Validator) Errors

func (v *Validator) Errors() []error

Errors gets all errors

func (*Validator) HasErrors

func (v *Validator) HasErrors() bool

HasErrors checks if there are errors

func (*Validator) InRange

func (v *Validator) InRange(n, min, max int, name string) *Validator

InRange verifyrange

func (*Validator) Matches

func (v *Validator) Matches(s string, pattern *regexp.Regexp, name string) *Validator

Matches validates regex match

func (*Validator) MaxLength

func (v *Validator) MaxLength(s string, max int, name string) *Validator

MaxLength verifymaximumlength

func (*Validator) MinLength

func (v *Validator) MinLength(s string, min int, name string) *Validator

MinLength verifyminimumlength

func (*Validator) NotEmpty

func (v *Validator) NotEmpty(s string, name string) *Validator

NotEmpty validates string is not empty

func (*Validator) NotNil

func (v *Validator) NotNil(val interface{}, name string) *Validator

NotNil validates not nil

func (*Validator) NotZero

func (v *Validator) NotZero(n int, name string) *Validator

NotZero validates integer is not zero

func (*Validator) Positive

func (v *Validator) Positive(n int, name string) *Validator

Positive validates positive number

func (*Validator) ValidBrowserType

func (v *Validator) ValidBrowserType(bt BrowserType, name string) *Validator

ValidBrowserType validates browser type

func (*Validator) ValidOS

func (v *Validator) ValidOS(os OperatingSystem, name string) *Validator

ValidOS validates operating system

type ZapAdapter added in v1.0.5

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

ZapAdapter adapts zap.Logger

func (*ZapAdapter) Debug added in v1.0.5

func (a *ZapAdapter) Debug(msg string, keysAndValues ...any)

func (*ZapAdapter) Error added in v1.0.5

func (a *ZapAdapter) Error(msg string, keysAndValues ...any)

func (*ZapAdapter) Info added in v1.0.5

func (a *ZapAdapter) Info(msg string, keysAndValues ...any)

func (*ZapAdapter) Warn added in v1.0.5

func (a *ZapAdapter) Warn(msg string, keysAndValues ...any)

type ZapLogger added in v1.0.5

type ZapLogger interface {
	Debug(msg string, fields ...any)
	Info(msg string, fields ...any)
	Warn(msg string, fields ...any)
	Error(msg string, fields ...any)
}

ZapLogger interface definition (avoid direct dependency on zap)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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