SilentShield

Taikyti agentų taisykles

Vykdymas yra SilentShield DI agentų kontrolės 2 lygis: užuot tik registravęs DI agentų apsilankymus, jūsų serveris ar edge aktyviai taiko jūsų politiką kiekvienam raktui — kiekvienas agentas leidžiamas, ribojamas arba blokuojamas. Jis tiesiogiai remiasi stebėjimo režimu. Vykdymo komponentai (Next.js middleware, sidecar dvejetainis failas, Cloudflare Worker) šiuo metu teikiami pagal užklausą ankstyvosios prieigos etape — rašykite [email protected].

Pirmiausia stebėkite, tada taikykite

Mūsų aiški rekomendacija: pirmiausia įjunkite stebėjimą, leiskite jam veikti savaitę ar dvi ir peržiūrėkite ataskaitą, prieš ką nors blokuodami — toks pat pakopinis diegimas kaip Wordfence mokymosi režimas ar DMARC (none → quarantine → reject). Tik ataskaita parodo, kurios DI paslaugos iš tikrųjų lankosi jūsų svetainėje ir ko jums kainuotų blokavimas, pavyzdžiui, citatų DI paieškoje. Taikyti be šio vaizdo reiškia spręsti aklai.

Kaip veikia vykdymas

Visi vykdytojai laikosi tos pačios sutarties: jie paima jūsų API rakto politikos paketą, patikrina paketo Ed25519 parašą pagal prisegtus SilentShield viešuosius raktus ir tada sprendžia lokaliai — leisti, atmesti ar riboti — be jokio iškvietimo užklausos kelyje.

Prisegtus pasirašymo raktus vieną kartą atsisiunčiate iš https://api.silentshield.io/.well-known/silentshield-agent-keys. Ir kiekvienas vykdytojas veikia „fail-open“ principu: įvykus bet kokiai klaidai — tinklo, parašo, pasibaigusio paketo — užklausa praleidžiama. Vykdymas niekada negali sustabdyti jūsų svetainės.

Sąrankos variantai

Go (net/http)

Savarankiškas vykdytojas — tik standartinė biblioteka, be SDK. Jis fone parsisiunčia ir patikrina pasirašytą politiką (Ed25519, prisegti raktai) ir sprendžia kiekvienai užklausai; apvyniokite savo tvarkyklę jo tarpine programine įranga. Fail-open: bet kokia klaida ar stebėjimo režimas praleidžia užklausą.

silentshield_enforcer.gogo
// Self-contained SilentShield agent-policy enforcer — stdlib only, no SDK.
// Drop this in, wrap your handler with New(cfg).Middleware, and blocked bots
// get a 403 (throttled ones a 429). Fail-open by design: any error, an
// unverifiable bundle, or monitor mode lets the request through — enforcement
// can never take your site down.
package ssenforce

import (
	"bytes"
	"crypto/ed25519"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"io"
	"net"
	"net/http"
	"net/netip"
	"strconv"
	"strings"
	"sync"
	"time"
)

// Config for the enforcer. PolicyURL + APIKey + at least one trusted key are
// required; with any missing the enforcer is a no-op (always allow).
type Config struct {
	PolicyURL string // https://api.silentshield.io/api/v1/agent/policy
	KeysURL   string // https://api.silentshield.io/.well-known/silentshield-agent-keys
	APIKey    string // your publishable site key (x-api-key)

	// Where does the visitor's address come from? Set ONE of the two, or
	// neither. Anyone can send an X-Forwarded-For header, so the enforcer only
	// believes one behind a proxy you name here.
	//
	// TrustedProxies lists YOUR reverse proxies (CIDRs or bare IPs, e.g.
	// "10.0.0.0/8" for nginx/Traefik in Docker, plus Cloudflare's ranges if it
	// sits in front). When the connection peer is one of them, X-Forwarded-For
	// is read from the RIGHT and the first address that is not one of your
	// proxies is the visitor. A peer that is not listed is the visitor itself
	// and its X-Forwarded-For is ignored.
	TrustedProxies []string
	// DirectConnection: no proxy in front, the connection peer IS the visitor.
	DirectConnection bool
	// Neither set: the enforcer cannot tell a visitor from your proxy. It then
	// never calls a request "spoof" and ignores "ip" rules (behind a proxy both
	// would judge the proxy's address — a spoof rule would block the genuine
	// Googlebot); verification still uses the connection peer, which can only
	// confirm, never wrongly accuse.
}

type signedBundle struct {
	Payload string `json:"payload"`
	Alg     string `json:"alg"`
	Kid     string `json:"kid"`
	Sig     string `json:"sig"`
}

type bundle struct {
	FormatVersion int     `json:"format_version"`
	Mode          string  `json:"mode"`
	QuotaEnabled  bool    `json:"quota_enabled"`
	Rules         []rule  `json:"rules"`
	Agents        []agent `json:"agents"`
}

type agent struct {
	Slug      string   `json:"slug"`
	Category  string   `json:"category"`
	Behaviors []string `json:"behaviors"` // search, agent, training, transact, other
	UATokens  []string `json:"ua_tokens"`
	CIDRs     []string `json:"cidrs"`
}

type rule struct {
	Match       match      `json:"match"`
	PathPattern string     `json:"path_pattern"`
	Methods     []string   `json:"methods"`
	Action      string     `json:"action"`
	RateLimit   *rateLimit `json:"rate_limit"`
}

type match struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type rateLimit struct {
	Requests  int    `json:"requests"`
	WindowSec int    `json:"window_sec"`
	Key       string `json:"key"` // "" = per agent; ip | ip_prefix | ip_path = per visitor
}

// enforcerID tells SilentShield on every policy fetch which rule types this
// enforcer carries out, so the dashboard can say whether a rule applies here.
// "ip", "spoof" and "visitor_rate" (per-visitor limits such as "protect login")
// only with a trustworthy visitor address (TrustedProxies or DirectConnection).
// Edited the matching yourself? Remove what it no longer does.
const (
	enforcerIDBase = "snippet-go/1 caps=behaviors,header,user_agent,verified_by"
	enforcerIDFull = "snippet-go/1 caps=behaviors,header,ip,spoof,user_agent,verified_by,visitor_rate"
)

// Enforcer fetches, verifies and caches the signed policy, refreshing every
// 5 minutes in the background, and decides per request.
type Enforcer struct {
	cfg     Config
	enabled bool
	trusted []*net.IPNet // cfg.TrustedProxies parsed; unparsable entries dropped

	mu      sync.RWMutex
	b       *bundle
	cidrs   map[string][]*net.IPNet
	ruleIDs []string // per rule of b: what its per-visitor counters hang on

	countersMu sync.Mutex
	counters   map[string]*window
	visitors   map[string]*window // per-visitor counters, at most maxVisitors
	swept      int64
}

type window struct {
	bucket int64
	ends   int64
	count  int
}

// maxVisitors bounds the per-visitor counters. When full, ended windows are
// dropped (at most once a second); still full → a new visitor is not counted.
// Fail-open, and memory stays flat under a flood of changing addresses.
const maxVisitors = 100000

// New builds an enforcer and starts background refresh. Call once at startup.
func New(cfg Config) *Enforcer {
	e := &Enforcer{cfg: cfg, counters: map[string]*window{}, visitors: map[string]*window{}}
	e.trusted = parseTrustedProxies(cfg.TrustedProxies)
	e.enabled = cfg.PolicyURL != "" && cfg.KeysURL != "" && cfg.APIKey != ""
	if !e.enabled {
		return e
	}
	_ = e.refresh() // best-effort initial load
	go func() {
		t := time.NewTicker(5 * time.Minute)
		defer t.Stop()
		for range t.C {
			_ = e.refresh()
		}
	}()
	return e
}

// Middleware wraps next, blocking disallowed bots. Monitor mode / fail-open
// never block.
func (e *Enforcer) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Optional: exempt your own trusted traffic (e.g. logged-in users) from
		// enforcement. Plug in your own check — it runs first, so a matching
		// request is never blocked. Keep it cheap (inspect your session cookie /
		// JWT), no I/O.
		// if isLoggedIn(r) {
		// 	next.ServeHTTP(w, r)
		// 	return
		// }
		if block, status, retry := e.decide(r); block {
			if retry > 0 {
				w.Header().Set("Retry-After", strconv.Itoa(retry))
			}
			w.WriteHeader(status)
			reportBlock(e.cfg.APIKey, e.reportedIP(r), r, status) // feed the dashboard's blocked-bots report
			return
		}
		next.ServeHTTP(w, r)
	})
}

// reportBlock fire-and-forgets a report that this request was blocked, so the
// SilentShield dashboard's "blocked bots" report has data. Best-effort: its own
// goroutine + timeout, all errors ignored — it never delays the response.
func reportBlock(apiKey, visitor string, r *http.Request, status int) {
	outcome := "deny"
	if status == http.StatusTooManyRequests {
		outcome = "throttle"
	}
	s := map[string]any{"ua": r.UserAgent(), "path": r.URL.Path, "method": r.Method, "outcome": outcome}
	if visitor != "" {
		s["ip"] = visitor
	}
	body, _ := json.Marshal(map[string]any{"sightings": []any{s}})
	go func() {
		req, err := http.NewRequest("POST", "https://api.silentshield.io/api/v1/agent/telemetry", bytes.NewReader(body))
		if err != nil {
			return
		}
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("x-api-key", apiKey)
		if resp, err := (&http.Client{Timeout: 3 * time.Second}).Do(req); err == nil {
			resp.Body.Close()
		}
	}()
}

func (e *Enforcer) decide(r *http.Request) (block bool, status, retry int) {
	if !e.enabled {
		return false, 0, 0
	}
	e.mu.RLock()
	b, cidrs, ids := e.b, e.cidrs, e.ruleIDs
	e.mu.RUnlock()
	if b == nil || b.Mode != "enforce" {
		return false, 0, 0 // no bundle or monitor → never block
	}

	slug, category := "", ""
	var behaviors []string
	best := 0
	ua := strings.ToLower(r.UserAgent())
	for _, a := range b.Agents {
		for _, tok := range a.UATokens {
			tl := strings.ToLower(tok)
			if tl != "" && strings.Contains(ua, tl) && len(tl) > best {
				best, slug, category, behaviors = len(tl), a.Slug, a.Category, a.Behaviors
			}
		}
	}
	visitor, trustworthy := e.visitorIP(r)
	ip := net.ParseIP(visitor)
	f := facts{behaviors: behaviors, ua: r.UserAgent(), header: r.Header.Get}
	if trustworthy {
		f.ip = ip // ip rules only on an address we can vouch for
	}
	verified := false
	if slug != "" {
		for _, n := range cidrs[slug] {
			if ip != nil && n.Contains(ip) {
				verified = true
				f.verifiedBy = "ip_list"
				break
			}
		}
		// Definitively refuted, not merely unconfirmed: the operator publishes
		// ranges for this address family and the source is outside all of them.
		// Anything we cannot check stays unsigned, never spoof — and without a
		// trustworthy address (see Config) we cannot check.
		f.spoof = trustworthy && !verified && ip != nil && sameFamily(cidrs[slug], ip)
	}

	ru, throttles, agentThrottles := evaluate(b.Rules, slug, category, verified, r.URL.Path, r.Method, f)
	if ru != nil && ru.Action == "deny" {
		return true, http.StatusForbidden, 0
	}
	// Per-visitor limits (rate_limit.key, e.g. "protect login") count every
	// throttle that matched before the deciding rule — a later deny has already
	// won above. Only on an address we can vouch for and never one of your own
	// proxies: behind an unnamed proxy every visitor would share one counter.
	if f.ip != nil && !isTrusted(f.ip.String(), e.trusted) {
		if over, ra := e.countVisitors(b.Rules, ids, throttles, f.ip, r.URL.Path); over {
			return true, http.StatusTooManyRequests, ra
		}
	}
	// Per-agent limits (a throttle without key) work the same way: every one
	// that matched before the deciding rule counts — per rule and agent (slug,
	// else cat:<category>, else any), and only with quota_enabled.
	if b.QuotaEnabled && len(agentThrottles) > 0 {
		if len(ids) != len(b.Rules) {
			ids = ruleIDs(b.Rules)
		}
		agent := slug
		if agent == "" && category != "" {
			agent = "cat:" + category
		}
		if agent == "" {
			agent = "any"
		}
		over, retry := false, 0
		for _, i := range agentThrottles {
			rl := b.Rules[i].RateLimit
			if rl == nil {
				continue
			}
			if ok, ra := e.allowThrottle(ids[i]+"|"+agent, rl); !ok {
				over = true
				if ra > retry {
					retry = ra
				}
			}
		}
		if over {
			return true, http.StatusTooManyRequests, retry
		}
	}
	return false, 0, 0
}

// evaluate walks the rules in order, first match wins (nil → allow) — except a
// throttle: it is collected (with a visitor key in throttles, without one in
// agentThrottles) and the walk goes on, so a later deny still wins. Nothing
// else matched → the first of them.
func evaluate(rules []rule, slug, category string, verified bool, path, method string, f facts) (*rule, []int, []int) {
	var throttles, agentThrottles []int
	first := -1
	for i := range rules {
		ru := &rules[i]
		if !matchApplies(ru.Match, slug, category, verified, f) {
			continue
		}
		if !pathMatches(ru.PathPattern, path) {
			continue
		}
		if !methodMatches(ru.Methods, method) {
			continue
		}
		if ru.Action == "throttle" {
			if ru.RateLimit != nil && ru.RateLimit.Key != "" {
				throttles = append(throttles, i)
			} else {
				agentThrottles = append(agentThrottles, i)
			}
			if first < 0 {
				first = i
			}
			continue
		}
		return ru, throttles, agentThrottles
	}
	if first >= 0 {
		return &rules[first], throttles, agentThrottles
	}
	return nil, nil, nil
}

// countVisitors counts the request for every collected per-visitor throttle
// (fixed window) and reports whether one is over its limit, with the longest
// Retry-After. The counter hangs on the rule's content (ids), not its position,
// so a rule added in front in the dashboard does not reset it.
func (e *Enforcer) countVisitors(rules []rule, ids []string, throttles []int, ip net.IP, path string) (bool, int) {
	addr, ok := netip.AddrFromSlice(ip)
	if !ok || len(throttles) == 0 {
		return false, 0
	}
	if len(ids) != len(rules) {
		ids = ruleIDs(rules)
	}
	now := time.Now().Unix()
	over, retry := false, 0
	e.countersMu.Lock()
	defer e.countersMu.Unlock()
	for _, i := range throttles {
		rl := rules[i].RateLimit
		bucket, ok := visitorBucket(rl.Key, addr, path)
		if !ok || rl.Requests <= 0 || rl.WindowSec <= 0 {
			continue // no visitor identity or no limit → let through
		}
		win := now / int64(rl.WindowSec)
		ends := (win + 1) * int64(rl.WindowSec)
		key := ids[i] + "|" + bucket
		c := e.visitors[key]
		if c == nil && len(e.visitors) >= maxVisitors {
			if e.swept != now {
				e.swept = now
				for k, v := range e.visitors {
					if v.ends <= now {
						delete(e.visitors, k)
					}
				}
			}
			if len(e.visitors) >= maxVisitors {
				continue // full: do not count a new visitor (fail-open)
			}
		}
		if c == nil || c.bucket != win {
			c = &window{bucket: win, ends: ends}
			e.visitors[key] = c
		}
		c.count++
		if c.count > rl.Requests {
			over = true
			if ra := int(ends - now); ra > retry {
				retry = ra
			}
		}
	}
	if over && retry < 1 {
		retry = 1
	}
	return over, retry
}

// visitorBucket: key "ip" = the address (IPv6 always per /64 — a connection
// owns the whole /64 and could rotate inside it), "ip_prefix" = IPv4 /24 or
// IPv6 /64, "ip_path" = the "ip" identity + "|" + path. Unknown key → none.
func visitorBucket(key string, ip netip.Addr, path string) (string, bool) {
	ip = ip.Unmap().WithZone("")
	switch key {
	case "ip", "ip_path":
		id := ip.String()
		if ip.Is6() {
			p, _ := ip.Prefix(64)
			id = p.String()
		}
		if key == "ip_path" {
			id += "|" + path
		}
		return id, true
	case "ip_prefix":
		bits := 64
		if ip.Is4() {
			bits = 24
		}
		p, _ := ip.Prefix(bits)
		return p.String(), true
	}
	return "", false
}

// ruleIDs names each rule by what defines its counters: condition, path,
// methods and visitor key — not limit and window, so tuning a number keeps the
// counter. Identical rules get a running number.
func ruleIDs(rules []rule) []string {
	ids := make([]string, len(rules))
	seen := map[string]int{}
	for i, r := range rules {
		key := ""
		if r.RateLimit != nil {
			key = r.RateLimit.Key
		}
		raw, _ := json.Marshal([]any{r.Match.Type, r.Match.Value, r.PathPattern, r.Methods, key})
		sum := sha256.Sum256(raw)
		id := hex.EncodeToString(sum[:8])
		seen[id]++
		if n := seen[id]; n > 1 {
			id += "#" + strconv.Itoa(n)
		}
		ids[i] = id
	}
	return ids
}

// facts are what the rules read beyond the agent identity: the agent's
// behaviors, how it was verified (spoof, verified_by) and the request itself
// (ip, user_agent, header — your own rules, which can match ANY visitor,
// humans included).
type facts struct {
	behaviors  []string // an agent_category rule also matches any of these
	spoof      bool
	verifiedBy string // "ip_list" when the source IP is in the agent's published range
	ip         net.IP
	ua         string
	header     func(name string) string
}

func matchApplies(m match, slug, category string, verified bool, f facts) bool {
	switch m.Type {
	case "any":
		// any/unsigned match AGENTS only — never a request without an agent identity.
		return slug != ""
	case "agent_slug":
		return slug != "" && slug == m.Value
	case "agent_category":
		// Category OR any behavior: Googlebot is filed under search but also
		// trains, so a rule against "training" must hit it too.
		if category != "" && category == m.Value {
			return true
		}
		for _, b := range f.behaviors {
			if b != "" && b == m.Value {
				return true
			}
		}
		return false
	case "unsigned":
		return slug != "" && !verified
	case "spoof":
		return f.spoof
	case "verified_by":
		return verified && m.Value != "" && f.verifiedBy == m.Value
	case "not_verified_by":
		return slug != "" && m.Value != "" && (!verified || f.verifiedBy != m.Value)
	case "ip":
		return ipListMatches(m.Value, f.ip)
	case "user_agent":
		v := strings.TrimSpace(m.Value)
		return v != "" && strings.Contains(strings.ToLower(f.ua), strings.ToLower(v))
	case "header":
		return headerMatches(m.Value, f.header)
	}
	return false
}

// ipListMatches: list is comma-separated IPs and/or CIDR prefixes.
func ipListMatches(list string, ip net.IP) bool {
	if ip == nil {
		return false
	}
	for _, p := range strings.Split(list, ",") {
		p = strings.TrimSpace(p)
		if strings.Contains(p, "/") {
			if _, n, err := net.ParseCIDR(p); err == nil && n.Contains(ip) {
				return true
			}
		} else if a := net.ParseIP(p); a != nil && a.Equal(ip) {
			return true
		}
	}
	return false
}

// headerMatches: value is "Name" (present, non-empty) or "Name=value"
// (case-insensitive equality).
func headerMatches(value string, get func(string) string) bool {
	if get == nil {
		return false
	}
	name, want, hasValue := strings.Cut(value, "=")
	name = strings.TrimSpace(name)
	if name == "" {
		return false
	}
	got := strings.TrimSpace(get(name))
	if !hasValue {
		return got != ""
	}
	return strings.EqualFold(got, strings.TrimSpace(want))
}

// sameFamily: at least one published range is of the address family of ip.
func sameFamily(nets []*net.IPNet, ip net.IP) bool {
	v4 := ip.To4() != nil
	for _, n := range nets {
		if (n.IP.To4() != nil) == v4 {
			return true
		}
	}
	return false
}

func pathMatches(pattern, path string) bool {
	if pattern == "" || pattern == "*" {
		return true
	}
	if strings.HasSuffix(pattern, "*") {
		return strings.HasPrefix(path, strings.TrimSuffix(pattern, "*"))
	}
	return path == pattern
}

func methodMatches(methods []string, method string) bool {
	if len(methods) == 0 {
		return true
	}
	for _, m := range methods {
		if strings.EqualFold(strings.TrimSpace(m), method) {
			return true
		}
	}
	return false
}

func (e *Enforcer) allowThrottle(key string, rl *rateLimit) (bool, int) {
	if rl.Requests <= 0 || rl.WindowSec <= 0 {
		return true, 0
	}
	now := time.Now().Unix()
	bucket := now / int64(rl.WindowSec)
	e.countersMu.Lock()
	defer e.countersMu.Unlock()
	c := e.counters[key]
	if c == nil || c.bucket != bucket {
		c = &window{bucket: bucket}
		e.counters[key] = c
	}
	c.count++
	if c.count > rl.Requests {
		retry := int((bucket+1)*int64(rl.WindowSec) - now)
		if retry < 1 {
			retry = 1
		}
		return false, retry
	}
	return true, 0
}

// refresh fetches + verifies the bundle and swaps it in. On any error the
// previous bundle is kept (fail-open).
func (e *Enforcer) refresh() error {
	keys, err := e.fetchKeys()
	if err != nil {
		return err
	}
	req, _ := http.NewRequest(http.MethodGet, e.cfg.PolicyURL, nil)
	req.Header.Set("x-api-key", e.cfg.APIKey)
	req.Header.Set("X-SilentShield-Enforcer", e.enforcerID())
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil // 304/anything else → keep last good bundle
	}
	raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	if err != nil {
		return err
	}
	b, err := verifyBundle(raw, keys)
	if err != nil {
		return err
	}
	cidrs := map[string][]*net.IPNet{}
	for _, a := range b.Agents {
		for _, c := range a.CIDRs {
			if _, n, err := net.ParseCIDR(c); err == nil {
				cidrs[a.Slug] = append(cidrs[a.Slug], n)
			}
		}
	}
	ids := ruleIDs(b.Rules)
	e.mu.Lock()
	e.b, e.cidrs, e.ruleIDs = b, cidrs, ids
	e.mu.Unlock()
	return nil
}

func (e *Enforcer) fetchKeys() (map[string]ed25519.PublicKey, error) {
	resp, err := http.Get(e.cfg.KeysURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var payload struct {
		Keys []struct {
			Kid string `json:"kid"`
			Key string `json:"key"`
		} `json:"keys"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
		return nil, err
	}
	out := map[string]ed25519.PublicKey{}
	for _, k := range payload.Keys {
		if raw, err := base64.StdEncoding.DecodeString(k.Key); err == nil && len(raw) == ed25519.PublicKeySize {
			out[k.Kid] = ed25519.PublicKey(raw)
		}
	}
	return out, nil
}

// verifyBundle checks the Ed25519 signature over the raw payload and returns the
// decoded bundle. The signed bytes are the payload JSON exactly (no hashing).
func verifyBundle(body []byte, keys map[string]ed25519.PublicKey) (*bundle, error) {
	var sb signedBundle
	if err := json.Unmarshal(body, &sb); err != nil {
		return nil, err
	}
	if sb.Alg != "ed25519" {
		return nil, errInvalid
	}
	pub, ok := keys[sb.Kid]
	if !ok {
		return nil, errInvalid
	}
	payload, err := base64.StdEncoding.DecodeString(sb.Payload)
	if err != nil {
		return nil, err
	}
	sig, err := base64.StdEncoding.DecodeString(sb.Sig)
	if err != nil {
		return nil, err
	}
	if !ed25519.Verify(pub, payload, sig) {
		return nil, errInvalid
	}
	var b bundle
	if err := json.Unmarshal(payload, &b); err != nil {
		return nil, err
	}
	if b.FormatVersion > 1 {
		return nil, errInvalid // a newer wire format we can't be sure we understand
	}
	return &b, nil
}

// remoteIP is the connection peer (r.RemoteAddr without the port).
func remoteIP(r *http.Request) string {
	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return ip
}

// enforcerID declares "ip", "spoof" and "visitor_rate" only when they are
// actually computed.
func (e *Enforcer) enforcerID() string {
	if len(e.trusted) > 0 || e.cfg.DirectConnection {
		return enforcerIDFull
	}
	return enforcerIDBase
}

// visitorIP returns the address to judge a request by and whether it is
// trustworthy (see Config). TrustedProxies → clientIP; DirectConnection → the
// peer; neither → the peer, not trustworthy.
func (e *Enforcer) visitorIP(r *http.Request) (string, bool) {
	peer := remoteIP(r)
	if len(e.trusted) > 0 {
		return clientIP(peer, r.Header.Get("X-Forwarded-For"), e.trusted), true
	}
	return peer, e.cfg.DirectConnection
}

// reportedIP is the address a block report carries, or "". SilentShield checks
// it against the agent's published ranges, so it must be the visitor's: without
// TrustedProxies/DirectConnection the peer may be your proxy (a genuine,
// blocked GPTBot would show up as spoofed) — then none. A chain of only your
// own proxies is no visitor address either.
func (e *Enforcer) reportedIP(r *http.Request) string {
	visitor, trustworthy := e.visitorIP(r)
	if !trustworthy || net.ParseIP(visitor) == nil || isTrusted(visitor, e.trusted) {
		return ""
	}
	return visitor
}

// clientIP: an untrusted peer is the visitor and its X-Forwarded-For is
// ignored; behind a trusted peer the chain is walked from the RIGHT (the
// entries your own proxies appended) and the first address that is not a
// trusted proxy wins. Never take the left-most entry: the client writes it.
// Garbage stops the walk rather than stepping past it.
func clientIP(peer, xff string, trusted []*net.IPNet) string {
	if !isTrusted(peer, trusted) {
		return peer
	}
	parts := strings.Split(xff, ",")
	for i := len(parts) - 1; i >= 0; i-- {
		candidate := strings.TrimSpace(parts[i])
		if candidate == "" {
			continue
		}
		if net.ParseIP(candidate) == nil {
			break
		}
		if !isTrusted(candidate, trusted) {
			return candidate
		}
	}
	return peer // only trusted hops (or no header)
}

func isTrusted(ip string, nets []*net.IPNet) bool {
	parsed := net.ParseIP(strings.TrimSpace(ip))
	if parsed == nil {
		return false
	}
	for _, n := range nets {
		if n.Contains(parsed) {
			return true
		}
	}
	return false
}

// parseTrustedProxies accepts CIDRs and bare IPs; unparsable entries are dropped.
func parseTrustedProxies(entries []string) []*net.IPNet {
	var nets []*net.IPNet
	for _, entry := range entries {
		entry = strings.TrimSpace(entry)
		if !strings.Contains(entry, "/") {
			ip := net.ParseIP(entry)
			if ip == nil {
				continue
			}
			bits := 128
			if ip.To4() != nil {
				ip, bits = ip.To4(), 32
			}
			nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
			continue
		}
		if _, n, err := net.ParseCIDR(entry); err == nil {
			nets = append(nets, n)
		}
	}
	return nets
}

type sentinel string

func (s sentinel) Error() string { return string(s) }

const errInvalid = sentinel("invalid bundle")

// Wiring:
//   enf := ssenforce.New(ssenforce.Config{
//       PolicyURL: "https://api.silentshield.io/api/v1/agent/policy",
//       KeysURL:   "https://api.silentshield.io/.well-known/silentshield-agent-keys",
//       APIKey:    "YOUR_API_KEY",
//       // Behind nginx/Traefik/Cloudflare: name them, so the visitor's real
//       // address is used (or DirectConnection: true without a proxy).
//       TrustedProxies: []string{"10.0.0.0/8", "127.0.0.1"},
//   })
//   http.ListenAndServe(":8080", enf.Middleware(mux))

Node.js / Express

Tas pats vykdytojas, skirtas Node.js, naudojant tik įtaisytą crypto modulį. Užregistruokite jį kaip pirmąją tarpinę programinę įrangą, kad jis būtų vykdomas prieš jūsų maršrutus. Fail-open pagal sumanymą.

silentshield-enforcer.jsjavascript
// Self-contained SilentShield agent-policy enforcer for Node.js / Express —
// no SDK, only the built-in `crypto`. Wrap your app with enforcer(cfg) and
// blocked bots get a 403 (throttled ones a 429). Fail-open by design: any
// error, an unverifiable bundle, or monitor mode lets the request through.
const crypto = require("crypto");

// Sent on every policy fetch: which rule types this enforcer carries out, so
// the dashboard can say whether a rule applies here. "ip", "spoof" and
// "visitor_rate" (per-visitor limits such as "protect login") only with a
// trustworthy visitor address (trustedProxies or directConnection, see
// visitorIp). Edited the matching yourself? Remove what it no longer does.
const ENFORCER_ID_BASE = "snippet-node/1 caps=behaviors,header,user_agent,verified_by";
const ENFORCER_ID_FULL = "snippet-node/1 caps=behaviors,header,ip,spoof,user_agent,verified_by,visitor_rate";

// Raw 32-byte Ed25519 public key → a verifiable KeyObject (DER SPKI wrap).
const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
function toPublicKey(rawBase64) {
  const raw = Buffer.from(rawBase64, "base64");
  if (raw.length !== 32) return null;
  return crypto.createPublicKey({
    key: Buffer.concat([ED25519_SPKI_PREFIX, raw]),
    format: "der",
    type: "spki",
  });
}

function ipInCidr(ip, cidr) {
  // Node's net has no CIDR test; do a byte-mask compare on the parsed buffers.
  const [subnet, bitsStr] = cidr.split("/");
  const bits = Number(bitsStr);
  const a = ipToBuf(ip);
  const b = ipToBuf(subnet);
  // A missing or malformed prefix length must never match (NaN would compare nothing and pass).
  if (!a || !b || a.length !== b.length || !Number.isInteger(bits) || bits < 0 || bits > a.length * 8) return false;
  const full = Math.floor(bits / 8);
  for (let i = 0; i < full; i++) if (a[i] !== b[i]) return false;
  const rem = bits % 8;
  if (rem === 0) return true;
  const mask = (0xff << (8 - rem)) & 0xff;
  return (a[full] & mask) === (b[full] & mask);
}
function ipToBuf(ip) {
  if (net_isIPv4(ip)) return Buffer.from(ip.split(".").map((n) => parseInt(n, 10)));
  try {
    // Expand IPv6 to 16 bytes via the built-in parser.
    const parts = require("net").isIPv6(ip) ? ip : null;
    if (!parts) return null;
    return ipv6ToBuf(ip);
  } catch {
    return null;
  }
}
function net_isIPv4(ip) {
  return require("net").isIPv4(ip);
}
function ipv6ToBuf(ip) {
  // Minimal IPv6 → 16-byte buffer (handles "::" compression).
  let [head, tail] = ip.split("::");
  const h = head ? head.split(":") : [];
  const t = tail ? tail.split(":") : [];
  const missing = 8 - (h.length + t.length);
  if (missing < 0) return null;
  const groups = [...h, ...Array(missing).fill("0"), ...t];
  const buf = Buffer.alloc(16);
  for (let i = 0; i < 8; i++) {
    const v = parseInt(groups[i] || "0", 16);
    buf.writeUInt16BE(v, i * 2);
  }
  return buf;
}

// visitorIp returns the address to judge a request by and whether it is
// trustworthy. Anyone can send an X-Forwarded-For header, so it is only read
// behind a proxy named in cfg.trustedProxies — from the RIGHT (the entries your
// own proxies appended), the first address that is not one of them is the
// visitor; never the left-most entry, the client writes it. A peer that is not
// listed is the visitor itself. cfg.directConnection: no proxy, the peer IS the
// visitor. Neither: not trustworthy — then no "spoof" verdict and no "ip"
// rules (behind a proxy both would judge the proxy's address).
function visitorIp(req, trusted, directConnection) {
  const norm = (ip) => {
    const t = String(ip || "").trim();
    const v4 = t.replace(/^::ffff:/i, ""); // IPv4-mapped peer (dual-stack socket)
    return require("net").isIPv4(v4) ? v4 : t;
  };
  const isTrusted = (ip) => require("net").isIP(ip) !== 0 && trusted.some((c) => ipInCidr(ip, c));
  const peer = norm(req.socket && req.socket.remoteAddress);
  if (trusted.length === 0) return { ip: peer, trustworthy: directConnection === true };
  if (!isTrusted(peer)) return { ip: peer, trustworthy: true };
  const xff = req.headers["x-forwarded-for"];
  const parts = String(Array.isArray(xff) ? xff.join(",") : xff || "").split(",");
  for (let i = parts.length - 1; i >= 0; i--) {
    const c = norm(parts[i]);
    if (c === "") continue;
    if (require("net").isIP(c) === 0) break; // garbage stops the walk
    if (!isTrusted(c)) return { ip: c, trustworthy: true };
  }
  return { ip: peer, trustworthy: true }; // only trusted hops (or no header)
}
// trustedCidrs accepts CIDRs and bare IPs; unparsable entries are dropped.
function trustedCidrs(list) {
  const out = [];
  for (const raw of list || []) {
    const e = String(raw).trim();
    const host = e.split("/")[0];
    const v = require("net").isIP(host);
    if (v === 0) continue;
    out.push(e.includes("/") ? e : host + (v === 4 ? "/32" : "/128"));
  }
  return out;
}

// f carries what the rules read beyond the agent identity: the agent's
// behaviors, how it was verified (spoof, verifiedBy) and the request itself
// (ip, ua, header — your own rules, which can match ANY visitor, humans
// included).
function matchApplies(m, slug, category, verified, f) {
  f = f || {};
  switch (m && m.type) {
    // any/unsigned match AGENTS only — never a request without an agent identity.
    case "any": return slug !== "";
    case "agent_slug": return slug !== "" && slug === m.value;
    // Category OR any behavior: Googlebot is filed under search but also
    // trains, so a rule against "training" must hit it too.
    case "agent_category":
      return (category !== "" && category === m.value) ||
        (f.behaviors || []).some((b) => b !== "" && b === m.value);
    case "unsigned": return slug !== "" && !verified;
    case "spoof": return f.spoof === true;
    case "verified_by": return verified && m.value !== "" && f.verifiedBy === m.value;
    case "not_verified_by": return slug !== "" && m.value !== "" && (!verified || f.verifiedBy !== m.value);
    case "ip": return ipListMatches(m.value, f.ip);
    case "user_agent": return userAgentMatches(m.value, f.ua);
    case "header": return headerMatches(m.value, f.header);
    default: return false;
  }
}
// ipListMatches: list is comma-separated IPs and/or CIDR prefixes.
function ipListMatches(list, ip) {
  if (!ip) return false;
  for (const part of String(list || "").split(",")) {
    const p = part.trim();
    if (!p) continue;
    const cidr = p.includes("/") ? p : p + (p.includes(":") ? "/128" : "/32");
    if (ipInCidr(ip, cidr)) return true;
  }
  return false;
}
function userAgentMatches(value, ua) {
  const v = String(value || "").trim().toLowerCase();
  return v !== "" && String(ua || "").toLowerCase().includes(v);
}
// headerMatches: value is "Name" (present, non-empty) or "Name=value"
// (case-insensitive equality).
function headerMatches(value, get) {
  if (typeof get !== "function") return false;
  const v = String(value || "");
  const eq = v.indexOf("=");
  const name = (eq < 0 ? v : v.slice(0, eq)).trim();
  if (!name) return false;
  const got = String(get(name) || "").trim();
  if (eq < 0) return got !== "";
  return got.toLowerCase() === v.slice(eq + 1).trim().toLowerCase();
}
function pathMatches(pattern, path) {
  if (!pattern || pattern === "*") return true;
  if (pattern.endsWith("*")) return path.startsWith(pattern.slice(0, -1));
  return path === pattern;
}
function methodMatches(methods, method) {
  if (!methods || methods.length === 0) return true;
  return methods.some((m) => String(m).trim().toUpperCase() === method.toUpperCase());
}
// evaluate: first match wins (null → allow) — except a throttle: its index goes
// to f.throttles (with a visitor key) or f.agentThrottles (without), when given,
// and the walk goes on, so a later deny still wins. Nothing else matched → the
// first of them.
function evaluate(rules, slug, category, verified, path, method, f) {
  let first = null;
  const list = rules || [];
  for (let i = 0; i < list.length; i++) {
    const r = list[i];
    if (!matchApplies(r.match || {}, slug, category, verified, f)) continue;
    if (!pathMatches(r.path_pattern || "", path)) continue;
    if (!methodMatches(r.methods || [], method)) continue;
    if (r.action === "throttle") {
      if (r.rate_limit && r.rate_limit.key) {
        if (f && f.throttles) f.throttles.push(i);
      } else if (f && f.agentThrottles) {
        f.agentThrottles.push(i);
      }
      if (!first) first = r;
      continue;
    }
    return r;
  }
  return first;
}

function verifyBundle(body, keys) {
  let env;
  try { env = JSON.parse(body); } catch { return null; }
  if (!env || env.alg !== "ed25519") return null;
  const pub = keys[env.kid];
  if (!pub) return null;
  const payload = Buffer.from(env.payload || "", "base64");
  const sig = Buffer.from(env.sig || "", "base64");
  if (sig.length !== 64) return null;
  if (!crypto.verify(null, payload, pub, sig)) return null;
  let bundle;
  try { bundle = JSON.parse(payload.toString("utf8")); } catch { return null; }
  if ((bundle.format_version || 1) > 1) return null;
  return bundle;
}

function enforcer(cfg) {
  const state = { bundle: null };
  const trusted = trustedCidrs(cfg.trustedProxies);
  const enforcerId = trusted.length > 0 || cfg.directConnection === true ? ENFORCER_ID_FULL : ENFORCER_ID_BASE;
  const counters = new Map();
  const visitors = new Map(); // per-visitor counters, at most MAX_VISITORS

  async function refresh() {
    try {
      const keysRes = await fetch(cfg.keysUrl);
      const keysJson = await keysRes.json();
      const keys = {};
      for (const k of keysJson.keys || []) {
        const pk = toPublicKey(k.key);
        if (pk) keys[k.kid] = pk;
      }
      if (Object.keys(keys).length === 0) return;
      const res = await fetch(cfg.policyUrl, {
        headers: { "x-api-key": cfg.apiKey, "X-SilentShield-Enforcer": enforcerId },
      });
      if (res.status !== 200) return; // 304/other → keep last good bundle
      const bundle = verifyBundle(await res.text(), keys);
      if (bundle) {
        state.ids = ruleIds(bundle.rules);
        state.bundle = bundle;
      }
    } catch {
      /* fail-open: keep the last good bundle */
    }
  }
  refresh();
  setInterval(refresh, 5 * 60 * 1000).unref();

  return function (req, res, next) {
    try {
      // Optional: exempt your own trusted traffic (e.g. logged-in users) from
      // enforcement. Plug in your own check — it runs first, so a matching
      // request is never blocked. Keep it cheap (inspect your session cookie /
      // JWT), no I/O.
      // if (isLoggedIn(req)) return next();

      const b = state.bundle;
      if (!b || b.mode !== "enforce") return next();

      const ua = (req.headers["user-agent"] || "").toLowerCase();
      let slug = "", category = "", best = 0, cidrs = [], behaviors = [];
      for (const a of b.agents || []) {
        for (const tok of a.ua_tokens || []) {
          const tl = String(tok).toLowerCase();
          if (tl && ua.includes(tl) && tl.length > best) {
            best = tl.length; slug = a.slug; category = a.category; cidrs = a.cidrs || []; behaviors = a.behaviors || [];
          }
        }
      }
      const visitor = visitorIp(req, trusted, cfg.directConnection);
      const ip = require("net").isIP(visitor.ip) ? visitor.ip : "";
      const f = {
        behaviors,
        spoof: false,
        verifiedBy: "",
        ip: visitor.trustworthy ? ip : "", // ip rules only on an address we can vouch for
        ua: req.headers["user-agent"] || "",
        header: (name) => {
          const v = req.headers[String(name).toLowerCase()];
          return Array.isArray(v) ? v[0] : (v || "");
        },
      };
      let verified = false;
      if (slug) {
        verified = cidrs.some((c) => ipInCidr(ip, c));
        if (verified) f.verifiedBy = "ip_list";
        // Definitively refuted, not merely unconfirmed: the operator publishes
        // ranges for this address family and the source is outside all of them.
        // Anything we cannot check stays unsigned, never spoof — and without a
        // trustworthy address (see visitorIp) we cannot check.
        f.spoof = !verified && f.ip !== "" && cidrs.some((c) => c.includes(":") === f.ip.includes(":"));
      }

      const path = String(req.path || req.url || "/").split("?")[0] || "/";
      f.throttles = [];
      f.agentThrottles = [];
      const rule = evaluate(b.rules, slug, category, verified, path, req.method, f);

      // The block report carries only an address we can vouch for (f.ip), never
      // one of your own proxies — SilentShield checks it against the agent's
      // ranges, and a proxy address would make a genuine bot look spoofed.
      const reportIp = f.ip !== "" && !trusted.some((c) => ipInCidr(f.ip, c)) ? f.ip : "";
      if (rule && rule.action === "deny") { res.statusCode = 403; reportBlock(cfg.apiKey, reportIp, req, "deny"); return res.end("Forbidden"); }
      // Per-visitor limits (rate_limit.key, e.g. "protect login") count every
      // throttle that matched before the deciding rule — a later deny has won
      // above. Only on an address we can vouch for (reportIp: never one of your
      // own proxies), else every visitor behind a proxy would share a counter.
      if (reportIp !== "" && f.throttles.length > 0) {
        const v = countVisitors(visitors, state.ids || ruleIds(b.rules), f.throttles, b.rules, reportIp, path);
        if (v.over) { res.statusCode = 429; res.setHeader("Retry-After", String(v.retry)); reportBlock(cfg.apiKey, reportIp, req, "throttle"); return res.end("Too Many Requests"); }
      }
      // Per-agent limits (a throttle without key) work the same way: every one
      // that matched before the deciding rule counts — per rule and agent (slug,
      // else cat:<category>, else any), and only with quota_enabled.
      if (b.quota_enabled && f.agentThrottles.length > 0) {
        const ids = state.ids || ruleIds(b.rules);
        const agent = slug || (category ? "cat:" + category : "any");
        let over = false, retry = 0;
        for (const i of f.agentThrottles) {
          const t = throttleOk(counters, ids[i] + "|" + agent, b.rules[i].rate_limit || {});
          if (!t.ok) { over = true; retry = Math.max(retry, t.retry); }
        }
        if (over) { res.statusCode = 429; res.setHeader("Retry-After", String(retry)); reportBlock(cfg.apiKey, reportIp, req, "throttle"); return res.end("Too Many Requests"); }
      }
      return next();
    } catch {
      return next(); // fail-open
    }
  };
}

// reportBlock fire-and-forgets a report that this request was blocked, so the
// SilentShield dashboard's "blocked bots" report has data. Best-effort — errors
// are swallowed and it never delays the response.
function reportBlock(apiKey, ip, req, outcome) {
  try {
    const s = {
      ua: req.headers["user-agent"] || "",
      path: req.path || req.url || "/",
      method: req.method,
      outcome,
    };
    if (ip) s.ip = ip;
    fetch("https://api.silentshield.io/api/v1/agent/telemetry", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-api-key": apiKey },
      body: JSON.stringify({ sightings: [s] }),
    }).catch(() => {}); // best-effort, fail-open
  } catch {
    /* ignore */
  }
}

function throttleOk(counters, key, rl) {
  const requests = rl.requests | 0, window = rl.window_sec | 0;
  if (requests <= 0 || window <= 0) return { ok: true, retry: 0 };
  const now = Math.floor(Date.now() / 1000);
  const bucket = Math.floor(now / window);
  let c = counters.get(key);
  if (!c || c.bucket !== bucket) { c = { bucket, count: 0 }; counters.set(key, c); }
  c.count++;
  if (c.count > requests) {
    const retry = Math.max(1, (bucket + 1) * window - now);
    return { ok: false, retry };
  }
  return { ok: true, retry: 0 };
}

// countVisitors counts the request for every collected per-visitor throttle
// (fixed window) and reports whether one is over its limit, with the longest
// Retry-After. The counter hangs on the rule's content (ids), not its position,
// so a rule added in front in the dashboard does not reset it. When full, ended
// windows are dropped (at most once a second); still full → a new visitor is
// not counted (fail-open, memory stays flat under a flood of addresses).
const MAX_VISITORS = 100000;
function countVisitors(visitors, ids, throttles, rules, ip, path) {
  const now = Math.floor(Date.now() / 1000);
  let over = false, retry = 0;
  for (const i of throttles) {
    const rl = rules[i].rate_limit || {};
    const requests = rl.requests | 0, windowSec = rl.window_sec | 0;
    const bucket = visitorBucket(rl.key, ip, path);
    if (bucket === null || requests <= 0 || windowSec <= 0) continue;
    const win = Math.floor(now / windowSec), ends = (win + 1) * windowSec;
    const key = ids[i] + "|" + bucket;
    let c = visitors.get(key);
    if (!c && visitors.size >= MAX_VISITORS) {
      if (visitors.swept !== now) {
        visitors.swept = now;
        for (const [k, w] of visitors) if (w.ends <= now) visitors.delete(k);
      }
      if (visitors.size >= MAX_VISITORS) continue;
    }
    if (!c || c.win !== win) { c = { win, ends, count: 0 }; visitors.set(key, c); }
    c.count++;
    if (c.count > requests) { over = true; retry = Math.max(retry, ends - now, 1); }
  }
  return { over, retry };
}

// visitorBucket: key "ip" = the address (IPv6 always per /64 — a connection
// owns the whole /64 and could rotate inside it), "ip_prefix" = IPv4 /24 or
// IPv6 /64, "ip_path" = the "ip" identity + "|" + path. null → not counted.
function visitorBucket(key, ip, path) {
  const b = ipToBuf(String(ip || "").replace(/%.*$/, ""));
  if (!b) return null;
  const v4 = b.length === 4;
  // The /64 network as Go prints it (RFC 5952): the longest run of zero
  // groups — the first on a tie — becomes "::".
  const v6net = () => {
    const g = [];
    for (let i = 0; i < 8; i++) g.push(i < 4 ? b.readUInt16BE(i * 2) : 0);
    let bs = -1, bl = 0;
    for (let i = 0; i < 8; ) {
      if (g[i] !== 0) { i++; continue; }
      let j = i;
      while (j < 8 && g[j] === 0) j++;
      if (j - i > bl) { bs = i; bl = j - i; }
      i = j;
    }
    const h = g.map((x) => x.toString(16));
    return h.slice(0, bs).join(":") + "::" + h.slice(bs + bl).join(":") + "/64";
  };
  switch (key) {
    case "ip":
    case "ip_path": {
      const id = v4 ? Array.from(b).join(".") : v6net();
      return key === "ip_path" ? id + "|" + path : id;
    }
    case "ip_prefix":
      return v4 ? b[0] + "." + b[1] + "." + b[2] + ".0/24" : v6net();
    default:
      return null;
  }
}

// ruleIds names each rule by what defines its counters: condition, path,
// methods and visitor key — not limit and window, so tuning a number keeps the
// counter. Identical rules get a running number.
function ruleIds(rules) {
  const seen = new Map();
  return (rules || []).map((r) => {
    const raw = JSON.stringify([(r.match || {}).type || "", (r.match || {}).value || "", r.path_pattern || "", r.methods || [], (r.rate_limit && r.rate_limit.key) || ""]);
    let id = crypto.createHash("sha256").update(raw).digest("hex").slice(0, 16);
    const n = (seen.get(id) || 0) + 1;
    seen.set(id, n);
    return n > 1 ? id + "#" + n : id;
  });
}

module.exports = { enforcer };

// Wiring (Express):
//   const { enforcer } = require("./silentshield-enforcer");
//   app.use(enforcer({
//     policyUrl: "https://api.silentshield.io/api/v1/agent/policy",
//     keysUrl:   "https://api.silentshield.io/.well-known/silentshield-agent-keys",
//     apiKey:    "YOUR_API_KEY",
//     // Behind nginx/Traefik/Cloudflare: name them, so the visitor's real
//     // address is used (or directConnection: true without a proxy).
//     trustedProxies: ["10.0.0.0/8", "127.0.0.1"],
//   }));

Ar nukopijavote Go ar Node šabloną prieš v2.11.1?

Iki 2.11.1 versijos Go ir Node šablonai sąlygas „unsigned“ ir „any“ taikė ir užklausoms be atpažinto agento. Jei naudojate senesnį šabloną ir vieną iš šių sąlygų susiejote su „deny“, jūsų vykdytojas blokuoja ir įprastas naršykles. Nukopijuokite aukščiau esantį šabloną iš naujo: abi sąlygas jis taiko tik atpažintiems agentams.

PHP

PHP SDK turi tą patį enforcerį (PHP 8.1 ar naujesnė su ext-sodium ir ext-curl). Įdiekite jį per Composer ir iškvieskite enforce() pačioje savo front controller pradžioje: į užblokuotą užklausą jis atsako 403 arba 429 ir nutraukia skriptą, kitu atveju jūsų programa tęsia darbą. Fail-open: įvykus bet kokiai klaidai arba stebėjimo režimu užklausa praleidžiama. Kurio lankytojo adreso nustatymo jums reikia, paaiškina kitas skyrius.

Terminalbash
composer config repositories.silentshield vcs https://github.com/forge12interactive/silentshield-sdk-php
composer require forge12interactive/silentshield-sdk
index.phpphp
<?php
// index.php: at the very top of your front controller
require __DIR__ . '/vendor/autoload.php';

// Behind your own reverse proxy: name it, so the enforcer reads the
// visitor address from X-Forwarded-For (from the right).
// Nothing in front of PHP? Use ['direct_connection' => true] instead.
$enforcer = new \SilentShield\Enforcer('YOUR_SITE_KEY', [
    'trusted_proxies' => ['10.0.0.0/8'],
]);

// A blocked agent gets 403 or 429 and the script exits;
// otherwise your app continues. Fail-open on any error.
$enforcer->enforce();

Lankytojo adresas už tarpinio serverio

Dviem patikroms reikia tikrojo lankytojo adreso: patvirtinti paieškos robotą pagal jo paskelbtus IP diapazonus ir atpažinti klastotę, kuri tik pasiskolina žinomą pavadinimą (spoof). Už atvirkštinio tarpinio serverio, apkrovos balansavimo įrenginio ar CDN jūsų serveris mato tik tarpinio serverio adresą. Vien antraštė X-Forwarded-For nieko neįrodo: jos kairiąją dalį įrašo pats siuntėjas. Todėl šablonai priima lankytojo adresą tik per jūsų nurodytus tarpinius serverius.

TrustedProxies (Go) · trustedProxies (Node) · trusted_proxies (PHP SDK)
Įprastas atvejis: prieš jūsų serverį yra atvirkštinis tarpinis serveris, apkrovos balansavimo įrenginys arba CDN. Nurodykite jo adresus ar diapazonus, pavyzdžiui, 127.0.0.1 arba 10.0.0.0/8. Šablonas skaito X-Forwarded-For iš dešinės ir paima pirmą adresą, kuris nepriklauso jūsų tarpiniams serveriams.
clientIpHeader (Edge SDK)
Tik Edge SDK (Next.js, Cloudflare Workers, Vercel Edge): nurodykite antraštę, į kurią jūsų prieglobos platforma įrašo lankytojo adresą, pavyzdžiui, x-real-ip „Vercel“ arba cf-connecting-ip „Cloudflare“ — bet tik tada, jei platforma ją nustato ir perrašo lankytojo atsiųstą reikšmę. Be jos ip tipo taisyklės netaikomos ir nė viena užklausa nelaikoma klastote.
DirectConnection (Go) · directConnection (Node) · direct_connection (PHP SDK)
Tik jei prieš jūsų serverį nieko nėra ir lankytojai jungiasi tiesiogiai: tada ryšio adresas yra lankytojas.

Go ir Node šablonai, PHP SDK: be nė vieno iš šių nustatymų enforceris nenaudoja lankytojo adreso. Netaikomos ip tipo taisyklės, ir nė viena užklausa nelaikoma klastote. Paieškos robotą vis tiek galima patvirtinti per tiesioginį ryšį.

Edge SDK: be clientIpHeader ip tipo taisyklės taip pat netaikomos ir nė viena užklausa nelaikoma klastote. Paieškos robotas tada patvirtinamas tik pagal adresą, kurį enforceriui perduoda pati platforma (req.ip); jei ji jo neperduoda, nė vienas robotas nepatvirtinamas pagal savo IP diapazoną.

Ar nukopijavote ankstesnę šablono versiją? Nukopijuokite jį iš naujo ir nustatykite vieną iš parinkčių. Jei jūsų serveris pasiekiamas be tarpinio serverio, nustatykite tiesioginį ryšį; kitaip po atnaujinimo patvirtinimas pagal IP diapazoną nebeveiks.

WordPress

Naudojate WordPress? SilentShield papildinys nuo 2.10.0 versijos pristato vykdytoją — kodo nereikia. Įjunkite jį skiltyje Išplėstiniai → „Blokuoti AI naršykles (vykdyti)“ (pagal numatytuosius nustatymus išjungta). Jis parsisiunčia ir patikrina tą pačią pasirašytą politiką serverio pusėje ir už jus blokuoja neleidžiamus botus.

Next.js ir kiti edge / serverless prieglobos serveriai

Mūsų edge paketas tinka abiem Next.js variantams: proxy.ts nuo Next.js 16 (Node.js vykdymo aplinka) ir middleware.ts iki Next.js 15 (Edge vykdymo aplinka). Node.js vykdytojas čia netinka: tai Express tarpinė programinė įranga, o Next.js perduoda standartinę užklausą ir laukia atsakymo. Edge paketas tikrina parašą grynu JavaScript ir sprendžia vietoje, be papildomo kreipinio kiekvienai užklausai, o jei kas nors nepavyksta, užklausą praleidžia. Įdiekite jį ir įtraukite į savo proxy.ts:

Terminalbash
npm i @forge12interactive/silentshield-edge
proxy.tstypescript
import { NextResponse, type NextRequest } from "next/server";
import { createEnforcer } from "@forge12interactive/silentshield-edge";

// proxy.ts (Next.js 16+). On Next.js 15 or older, name the file
// middleware.ts and the function middleware; nothing else changes.

// Create it ONCE at module scope so the verified bundle is cached.
const enforcer = createEnforcer({ apiKey: process.env.SILENTSHIELD_SITE_KEY! });

export async function proxy(req: NextRequest) {
  // Decides locally from the signed bundle: 403/429 or null. Fail-open.
  const blocked = await enforcer.enforce(req);
  return blocked ?? NextResponse.next();
}

// Skip static assets.
export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};

Tas pats vykdytojas veikia ir Cloudflare Workers, Vercel Edge bei Deno aplinkose: jis priima standartinę užklausą ir grąžina atsakymą 403 arba 429 arba nieko, jei užklausa gali praeiti. Nenorite apskritai keisti programos? Pastatykite reverse-proxy sidecar (žemiau) priešais ją.

worker.jsjavascript
import { createEnforcer } from "@forge12interactive/silentshield-edge";

const enforcer = createEnforcer({ apiKey: SILENTSHIELD_SITE_KEY });

export default {
  async fetch(request) {
    const blocked = await enforcer.enforce(request);
    if (blocked) return blocked;
    return fetch(request); // or your handler
  },
};

Atvirkštinis proxy (nginx / Caddy / Traefik)

Vienas mažytis sidecar dvejetainis failas aptarnauja visus tris proxy: proxy per forward auth jo paklausia kartą per užklausą. Paleiskite jį su savo svetainės raktu ir patikimais raktais:

Terminalbash
AGENT_POLICY_URL="https://api.silentshield.io/api/v1/agent/policy" \
AGENT_SITE_KEY="YOUR_API_KEY" \
AGENT_TRUSTED_KEYS='[{"kid":"…","key":"<base64 ed25519 pubkey>"}]' \
AGENT_SIDECAR_LISTEN=":8127" \
  ./agent-sidecar

Sidecar į GET /auth atsako 204 (leisti), 403 (atmesti) arba 429 su Retry-After (riboti). Prijunkite jį prie savo proxy:

nginx.confnginx
location = /_ss_auth {
    internal;
    proxy_pass              http://127.0.0.1:8127/auth;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        X-Forwarded-Method $request_method;
    proxy_set_header        X-Forwarded-Uri    $request_uri;
    proxy_set_header        X-Forwarded-Host   $host;
    proxy_set_header        X-Forwarded-For    $remote_addr;
    proxy_set_header        User-Agent         $http_user_agent;
    proxy_set_header        Signature          $http_signature;
    proxy_set_header        Signature-Input    $http_signature_input;
    proxy_set_header        Signature-Agent    $http_signature_agent;
}
location / {
    auth_request /_ss_auth;
    # ... your normal proxy_pass to the origin ...
}
Caddyfilecaddy
example.com {
    forward_auth 127.0.0.1:8127 {
        uri /auth
        copy_headers User-Agent Signature Signature-Input Signature-Agent
        # Caddy sends X-Forwarded-Method/-Uri/-Host automatically
    }
    reverse_proxy origin:8080
}
traefik.ymlyaml
http:
  middlewares:
    silentshield:
      forwardAuth:
        address: "http://agent-sidecar:8127/auth"
        authRequestHeaders:
          - "User-Agent"
          - "Signature"
          - "Signature-Input"
          - "Signature-Agent"

Cloudflare Worker

Cloudflare Worker vykdytojas patikrina politikos paketą naudodamas Web Crypto Ed25519 ir blokuoja dar prieš užklausoms pasiekiant jūsų origin serverį:

Terminalbash
cd enforcers/cloudflare-worker
npx wrangler secret put AGENT_SITE_KEY
# set AGENT_POLICY_URL + AGENT_TRUSTED_KEYS in wrangler.toml [vars]
npx wrangler deploy

Oficialūs SDK

Ar vietoje pirmiau pateikto kopijuojamo fragmento norėtumėte prižiūrimo paketo? Įdiekite vieną iš mūsų oficialių SDK — tas pats vykdytojas bei verify ir observe pagalbinės funkcijos, nuolat atnaujinamos:

Node.js — npmbash
npm install @forge12interactive/silentshield-sdk-js
Gobash
go get github.com/forge12interactive/silentshield-go
Edge — npmbash
npm i @forge12interactive/silentshield-edge
PHP — Composer (from GitHub)bash
composer config repositories.silentshield vcs https://github.com/forge12interactive/silentshield-sdk-php
composer require forge12interactive/silentshield-sdk

Kiekvieno SDK pirminis kodas, problemų pranešimai ir visas README yra „GitHub“: silentshield-sdk-js (atsidaro naujoje kortelėje) · silentshield-go (atsidaro naujoje kortelėje) · silentshield-edge (atsidaro naujoje kortelėje) · silentshield-sdk-php (atsidaro naujoje kortelėje)

Sąžiningos ribos

Agentinės naršyklės su namų (residential) IP adresais (Comet, ChatGPT Atlas ir panašios) techniškai nesiskiria nuo žmonių lankytojų. Joks produktas negali jų patikimai atpažinti — todėl SilentShield šiai kategorijai sąmoningai neduoda jokio vykdymo pažado.

robots.txt ir siunčiami turinio signalai yra tik rekomendacijos: tvarkingos naršyklės jų laikosi, bet niekas jų neverčia. Techninis vykdymas vyksta tik šiame puslapyje aprašytuose vykdytojuose — ir net jie elgiasi konservatyviai, atmesdami tik vienareikšmiškai atpažintus žinomus agentus, kad teisėti lankytojai niekada nebūtų blokuojami.

Sukonfigūruokite savo politiką

Ką kuris agentas gali daryti, konfigūruojate kiekvienam API raktui agentų centre: API raktai → pasirinkite raktą → Agentas. Išankstiniai nustatymai apima dažniausius atvejus; kiekvienas pakeitimas tampa naujai pasirašytu paketu, kurį jūsų vykdytojai perima automatiškai.

Atidaryti agentų centrą →

Apžvalga ir nauda: DI tikrintuvų ir agentų valdymas →