risk

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ActionAllow   = "allow"
	ActionReview  = "review"
	ActionCaptcha = "captcha"
	ActionLimit   = "limit"
	ActionDeny    = "deny"
	ActionBlock   = "block"

	LevelLow      = "low"
	LevelMedium   = "medium"
	LevelHigh     = "high"
	LevelCritical = "critical"

	StatusAllow   = "allow"
	StatusHit     = "hit"
	StatusBlocked = "blocked"

	RuleTypeList      = "list"
	RuleTypeFrequency = "frequency"

	ResponseActionNone       = "none"
	ResponseActionToast      = "toast"
	ResponseActionCaptcha    = "captcha"
	ResponseActionAppeal     = "appeal"
	ResponseActionRetryLater = "retry_later"
	ResponseActionContact    = "contact"
)

Variables

View Source
var ErrChallengeUnavailable = errors.New("risk: challenge store unavailable")
View Source
var ErrCounterUnavailable = errors.New("risk: counter unavailable")
View Source
var ErrMissingStore = errors.New("risk: missing store")

Functions

func TargetValue added in v0.1.4

func TargetValue(event Event, targetType string) (string, bool)

func TargetValues added in v0.1.4

func TargetValues(event Event) map[string]string

Types

type CacheCounter added in v0.1.4

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

func NewCacheCounter added in v0.1.4

func NewCacheCounter(cache CounterCache, opts ...CacheCounterOption) *CacheCounter

func (*CacheCounter) Incr added in v0.1.4

func (c *CacheCounter) Incr(ctx context.Context, key CounterKey) (int64, error)

type CacheCounterOption added in v0.1.4

type CacheCounterOption func(*CacheCounter)

func WithCounterPrefix added in v0.1.4

func WithCounterPrefix(prefix string) CacheCounterOption

type ChallengeKey added in v0.1.16

type ChallengeKey struct {
	Service     string
	Scene       string
	Rule        string
	TargetType  string
	TargetValue string
}

ChallengeKey identifies one rule's verification requirement for one target. It deliberately excludes the request IP for account-scoped requirements.

type ChallengeRequirement added in v0.1.16

type ChallengeRequirement struct {
	Key     ChallengeKey
	Version string
}

type ChallengeStore added in v0.1.16

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

ChallengeStore keeps temporary verification requirements separate from audit counters. Reading does not increment counters or extend the requirement TTL.

func NewChallengeStore added in v0.1.16

func NewChallengeStore(client redis.UniversalClient) *ChallengeStore

func (*ChallengeStore) ClaimProof added in v0.1.16

func (s *ChallengeStore) ClaimProof(ctx context.Context, scope, proof string, ttl time.Duration) (bool, error)

ClaimProof prevents concurrent reuse of a proof before its verifier runs. The scope must match the verifier's namespace; ttl must cover proof validity.

func (*ChallengeStore) Get added in v0.1.16

func (*ChallengeStore) Require added in v0.1.16

func (s *ChallengeStore) Require(ctx context.Context, key ChallengeKey, ttl time.Duration) error

func (*ChallengeStore) Resolve added in v0.1.16

func (s *ChallengeStore) Resolve(ctx context.Context, requirement ChallengeRequirement) error

Resolve clears only the observed generation. A concurrent failure's newer requirement survives. Callers explicitly choose which target types to clear.

type Counter added in v0.1.4

type Counter interface {
	Incr(ctx context.Context, key CounterKey) (int64, error)
}

type CounterCache added in v0.1.4

type CounterCache interface {
	Incr(ctx context.Context, key string) (int64, error)
	TTL(ctx context.Context, key string) (time.Duration, error)
	Expire(ctx context.Context, key string, ttl time.Duration) error
}

type CounterKey added in v0.1.4

type CounterKey struct {
	Service       string
	Scene         string
	Event         string
	TargetType    string
	TargetValue   string
	WindowSeconds int
}

type Decision added in v0.1.4

type Decision struct {
	Passed          bool             `json:"passed"`
	EventID         int64            `json:"event_id"`
	Service         string           `json:"service"`
	Scene           string           `json:"scene"`
	Event           string           `json:"event"`
	Level           string           `json:"level"`
	Score           int              `json:"score"`
	Action          string           `json:"action"`
	Status          string           `json:"status"`
	ResponseCode    int              `json:"response_code"`
	ResponseMessage string           `json:"response_message"`
	ResponseAction  string           `json:"response_action"`
	ResponsePayload map[string]any   `json:"response_payload"`
	HTTPStatus      int              `json:"http_status"`
	Reasons         []map[string]any `json:"reasons"`
	Hits            []HitDecision    `json:"hits"`
	CreatedAt       time.Time        `json:"created_at"`
}

type DecisionRecord added in v0.1.4

type DecisionRecord struct {
	Event    Event
	Decision Decision
}

func NewDecisionRecord added in v0.1.4

func NewDecisionRecord(event Event, decision *Decision) DecisionRecord

type DecisionWriter added in v0.1.4

type DecisionWriter interface {
	WriteDecisionBatch(ctx context.Context, records []DecisionRecord) error
}

type Engine added in v0.1.4

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

func NewEngine added in v0.1.4

func NewEngine(store Store, opts ...Option) *Engine

func (*Engine) Evaluate added in v0.1.4

func (e *Engine) Evaluate(ctx context.Context, event Event) (*Decision, error)

type Event added in v0.1.4

type Event struct {
	Service     string         `json:"service"`
	Scene       string         `json:"scene"`
	Event       string         `json:"event"`
	Level       string         `json:"level"`
	SubjectType string         `json:"subject_type"`
	SubjectID   string         `json:"subject_id"`
	UID         string         `json:"uid"`
	IP          string         `json:"ip"`
	DeviceID    string         `json:"device_id"`
	TrackID     string         `json:"track_id"`
	TraceID     string         `json:"trace_id"`
	RequestID   string         `json:"request_id"`
	Score       int            `json:"score"`
	Action      string         `json:"action"`
	Extra       map[string]any `json:"extra"`
}

type EventCountQuery added in v0.1.4

type EventCountQuery struct {
	Service     string
	Scene       string
	Event       string
	TargetType  string
	TargetValue string
	Since       time.Time
}

type FrequencyRule added in v0.1.4

type FrequencyRule struct {
	ID              int64          `json:"id"`
	Code            string         `json:"code"`
	Name            string         `json:"name"`
	Event           string         `json:"event"`
	TargetType      string         `json:"target_type"`
	WindowSeconds   int            `json:"window_seconds"`
	LimitCount      int            `json:"limit_count"`
	Level           string         `json:"level"`
	Action          string         `json:"action"`
	Score           int            `json:"score"`
	ResponseCode    int            `json:"response_code"`
	ResponseMessage string         `json:"response_message"`
	ResponseAction  string         `json:"response_action"`
	ResponsePayload map[string]any `json:"response_payload"`
	HTTPStatus      int            `json:"http_status"`
}

type HitDecision added in v0.1.4

type HitDecision struct {
	ID              int64          `json:"id"`
	RuleID          int64          `json:"rule_id"`
	RuleCode        string         `json:"rule_code"`
	RuleName        string         `json:"rule_name"`
	RuleType        string         `json:"rule_type"`
	Level           string         `json:"level"`
	Score           int            `json:"score"`
	Action          string         `json:"action"`
	ResponseCode    int            `json:"response_code"`
	ResponseMessage string         `json:"response_message"`
	ResponseAction  string         `json:"response_action"`
	ResponsePayload map[string]any `json:"response_payload"`
	HTTPStatus      int            `json:"http_status"`
	Reason          map[string]any `json:"reason"`
	Snapshot        map[string]any `json:"snapshot"`
}

type ListRule added in v0.1.4

type ListRule struct {
	ID              int64          `json:"id"`
	ListType        string         `json:"list_type"`
	TargetType      string         `json:"target_type"`
	TargetValue     string         `json:"target_value"`
	Scene           string         `json:"scene"`
	Reason          string         `json:"reason"`
	ResponseCode    int            `json:"response_code"`
	ResponseMessage string         `json:"response_message"`
	ResponseAction  string         `json:"response_action"`
	ResponsePayload map[string]any `json:"response_payload"`
	HTTPStatus      int            `json:"http_status"`
}

type Logger added in v0.1.4

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

func NewLogger added in v0.1.4

func NewLogger(writer DecisionWriter, cfg LoggerConfig) *Logger

func (*Logger) Push added in v0.1.4

func (l *Logger) Push(event Event, decision *Decision) bool

func (*Logger) Start added in v0.1.4

func (l *Logger) Start(ctx context.Context)

type LoggerConfig added in v0.1.4

type LoggerConfig struct {
	QueueSize     int
	BatchSize     int
	FlushInterval time.Duration
}

type Option added in v0.1.4

type Option func(*Engine)

func WithCounter added in v0.1.4

func WithCounter(counter Counter) Option

func WithLogger added in v0.1.4

func WithLogger(logger *Logger) Option

func WithNow added in v0.1.4

func WithNow(now func() time.Time) Option

type RedisCounter added in v0.1.4

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

func NewRedisCounter added in v0.1.4

func NewRedisCounter(client goredis.Cmdable, opts ...RedisCounterOption) *RedisCounter

func (*RedisCounter) Incr added in v0.1.4

func (c *RedisCounter) Incr(ctx context.Context, key CounterKey) (int64, error)

type RedisCounterOption added in v0.1.4

type RedisCounterOption func(*RedisCounter)

func WithRedisCounterPrefix added in v0.1.4

func WithRedisCounterPrefix(prefix string) RedisCounterOption

type Scene added in v0.1.4

type Scene struct {
	Service        string `json:"service"`
	Code           string `json:"code"`
	DefaultLevel   string `json:"default_level"`
	DefaultAction  string `json:"default_action"`
	ScoreThreshold int    `json:"score_threshold"`
}

type Store added in v0.1.4

type Store interface {
	LoadScene(ctx context.Context, service string, scene string) (*Scene, error)
	MatchList(ctx context.Context, event Event, listType string) (*ListRule, error)
	ListFrequencyRules(ctx context.Context, event Event) ([]FrequencyRule, error)
	CountEvents(ctx context.Context, query EventCountQuery) (int64, error)
	SaveDecision(ctx context.Context, event Event, decision *Decision) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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