SilentShield

Aplicar reglas de agentes

La aplicación es el nivel 2 del control de agentes de IA de SilentShield: en lugar de solo registrar las visitas de agentes de IA, su servidor o su edge aplica activamente su política por clave — cada agente se permite, se limita o se bloquea. Se basa directamente en el modo de observación. Los componentes de aplicación (middleware de Next.js, binario sidecar, Cloudflare Worker) se proporcionan actualmente bajo petición en acceso anticipado — contacta con [email protected].

Primero observar, luego aplicar

Nuestra recomendación clara: active primero la observación, déjela funcionar una o dos semanas y revise el informe antes de bloquear nada — el mismo despliegue por etapas que el modo de aprendizaje de Wordfence o un rollout de DMARC (none → quarantine → reject). Solo el informe muestra qué servicios de IA visitan realmente su sitio y qué le costaría un bloqueo, por ejemplo citas en la búsqueda de IA. Aplicar sin esa imagen es decidir a ciegas.

Cómo funciona la aplicación

Todos los enforcers comparten el mismo contrato: obtienen un bundle de política para su clave API, verifican la firma Ed25519 del bundle contra las claves públicas fijadas de SilentShield y luego deciden localmente — permitir, denegar o limitar — sin ninguna llamada en la ruta de la solicitud.

Las claves de firma fijadas se obtienen una sola vez de https://api.silentshield.io/.well-known/silentshield-agent-keys. Y cada enforcer funciona en modo fail-open: ante cualquier error — red, firma, bundle caducado — la solicitud se deja pasar. La aplicación nunca puede tumbar su sitio.

Variantes de configuración

Go (net/http)

Un enforcer autónomo: solo la biblioteca estándar, sin SDK. Descarga y verifica la política firmada en segundo plano (Ed25519, claves ancladas) y decide por cada solicitud; envuelva su handler con su middleware. Fail-open: cualquier error o el modo de observación deja pasar la solicitud.

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

El mismo enforcer para Node.js, usando únicamente el módulo integrado crypto. Regístrelo como el primer middleware para que se ejecute antes que sus rutas. Fail-open por diseño.

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"],
//   }));

¿Copió la plantilla de Go o Node antes de la v2.11.1?

Antes de la versión 2.11.1, las plantillas de Go y Node aplicaban las condiciones «unsigned» y «any» también a solicitudes sin un agente reconocido. Si utiliza una plantilla anterior y combinó una de estas condiciones con «deny», su enforcer bloquea también navegadores normales. Vuelva a copiar la plantilla de arriba: aplica ambas condiciones solo a agentes reconocidos.

PHP

El SDK de PHP incluye el mismo enforcer (PHP 8.1 o posterior con ext-sodium y ext-curl). Instálelo con Composer y llame a enforce() al principio de su front controller: responde a una solicitud bloqueada con 403 o 429 y termina el script; si no, su aplicación continúa. Fail-open: ante cualquier error o en modo de supervisión, la solicitud pasa. La sección siguiente explica qué ajuste de dirección de visitante necesita.

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();

Dirección del visitante detrás de un proxy

Dos comprobaciones necesitan la dirección real del visitante: confirmar un rastreador por sus rangos de IP publicados y reconocer una suplantación que solo toma prestado un nombre conocido (spoof). Detrás de un proxy inverso, un balanceador de carga o una CDN, su servidor solo ve la dirección del proxy. La cabecera X-Forwarded-For por sí sola no demuestra nada: su parte izquierda la escribe el propio remitente. Por eso las plantillas solo aceptan una dirección de visitante a través de los proxies que usted indique.

TrustedProxies (Go) · trustedProxies (Node) · trusted_proxies (PHP SDK)
El caso habitual: delante de su servidor hay un proxy inverso, un balanceador de carga o una CDN. Indique sus direcciones o rangos, por ejemplo 127.0.0.1 o 10.0.0.0/8. La plantilla lee X-Forwarded-For desde la derecha y toma la primera dirección que no pertenece a sus proxies.
clientIpHeader (Edge SDK)
Solo Edge SDK (Next.js, Cloudflare Workers, Vercel Edge): indique la cabecera en la que su plataforma de alojamiento escribe la dirección del visitante, por ejemplo x-real-ip en Vercel o cf-connecting-ip en Cloudflare, pero solo si la plataforma la establece y sobrescribe cualquier valor enviado por el visitante. Sin ella, las reglas de tipo ip no se aplican y ninguna solicitud se considera una suplantación.
DirectConnection (Go) · directConnection (Node) · direct_connection (PHP SDK)
Solo si no hay nada delante de su servidor y los visitantes se conectan directamente: la dirección de la conexión es entonces la del visitante.

Plantillas de Go y Node, SDK de PHP: sin ninguno de los dos ajustes, el enforcer no utiliza ninguna dirección de visitante. Las reglas de tipo ip no se aplican y ninguna solicitud se considera una suplantación. Un rastreador puede seguir confirmándose a través de la conexión directa.

Edge SDK: sin clientIpHeader, las reglas de tipo ip tampoco se aplican y ninguna solicitud se considera una suplantación. Un rastreador solo se confirma entonces mediante la dirección que la propia plataforma entrega al enforcer (req.ip); si no entrega ninguna, ningún rastreador se confirma por su rango de IP.

¿Copió una versión anterior de una plantilla? Cópiela de nuevo y configure uno de los ajustes. Si su servidor es accesible sin proxy, active la conexión directa; de lo contrario, la confirmación por rango de IP deja de funcionar tras la actualización.

WordPress

¿Usa WordPress? El plugin de SilentShield incluye el enforcer desde la versión 2.10.0, sin necesidad de código. Actívelo en Advanced → «Bloquear rastreadores de IA (enforce)» (desactivado de forma predeterminada). Descarga y verifica la misma política firmada en el lado del servidor y bloquea por usted los bots no permitidos.

Next.js y otros hosts edge / serverless

Nuestro paquete edge sirve para las dos variantes de Next.js: proxy.ts desde Next.js 16 (runtime Node.js) y middleware.ts hasta Next.js 15 (runtime Edge). El enforcer de Node.js no encaja ahí: es un middleware de Express, mientras que Next.js entrega una solicitud estándar y espera una respuesta. El paquete edge comprueba la firma en JavaScript puro y decide localmente, sin llamadas adicionales por solicitud, y deja pasar la solicitud si algo falla. Instálelo y añádalo a su 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).*)"],
};

El mismo enforcer funciona también en Cloudflare Workers, Vercel Edge y Deno: recibe una solicitud estándar y devuelve una respuesta 403 o 429, o nada si la solicitud puede pasar. ¿Prefiere no modificar su aplicación? Coloque el sidecar de proxy inverso (más abajo) delante de ella.

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
  },
};

Proxy inverso (nginx / Caddy / Traefik)

Un único y diminuto binario sidecar sirve a los tres proxies: el proxy le pregunta una vez por solicitud mediante forward auth. Inícielo con su clave de sitio y las claves de confianza:

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

El sidecar responde en GET /auth con 204 (permitir), 403 (denegar) o 429 más Retry-After (limitar). Así se conecta a su 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

El enforcer de Cloudflare Worker verifica el bundle de política con Ed25519 de Web Crypto y bloquea antes de que las solicitudes lleguen siquiera a su origen:

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

SDK oficiales

¿Prefiere un paquete mantenido en lugar del fragmento para copiar y pegar de arriba? Instale uno de nuestros SDK oficiales: el mismo enforcer más los ayudantes verify y observe, mantenidos al día:

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

El código fuente, las incidencias y el README completo de cada SDK están en GitHub: silentshield-sdk-js (se abre en una pestaña nueva) · silentshield-go (se abre en una pestaña nueva) · silentshield-edge (se abre en una pestaña nueva) · silentshield-sdk-php (se abre en una pestaña nueva)

Límites honestos

Los navegadores agénticos con direcciones IP residenciales (Comet, ChatGPT Atlas y similares) son técnicamente indistinguibles de los visitantes humanos. Ningún producto puede identificarlos de forma fiable — por eso SilentShield, deliberadamente, no hace ninguna promesa de aplicación para esta categoría.

robots.txt y las señales de contenido emitidas son consultivas: los rastreadores educados las respetan, pero nada los obliga. La aplicación técnica ocurre solo en los enforcers de esta página — e incluso ellos actúan de forma conservadora, denegando únicamente agentes conocidos identificados con certeza, para que los visitantes legítimos nunca sean bloqueados.

Configurar su política

Qué puede hacer cada agente se configura por clave API en el hub de agentes: Claves API → seleccione una clave → Agente. Los preajustes cubren los casos habituales; cada cambio se convierte en un bundle recién firmado que sus enforcers adoptan automáticamente.

Abrir el hub de agentes →

Resumen y ventajas: Controle los rastreadores y agentes de IA →