SilentShield

Agentregels afdwingen

Afdwingen is fase 2 van SilentShields AI-agentcontrole: in plaats van AI-agentbezoeken alleen te registreren, past uw server of edge uw beleid per sleutel actief toe — elke agent wordt toegestaan, beperkt of geblokkeerd. Het bouwt direct voort op de observatiemodus. De enforcement-componenten (Next.js-middleware, sidecar-binary, Cloudflare Worker) zijn momenteel op aanvraag beschikbaar in early access — neem contact op via [email protected].

Eerst observeren, dan afdwingen

Onze duidelijke aanbeveling: schakel eerst de observatie in, laat die een tot twee weken draaien en bekijk het rapport voordat u iets blokkeert — dezelfde gefaseerde aanpak als de leermodus van Wordfence of een DMARC-rollout (none → quarantine → reject). Pas het rapport laat zien welke AI-diensten uw site daadwerkelijk bezoeken en wat een blokkade u zou kosten, bijvoorbeeld citaties in AI-zoekresultaten. Afdwingen zonder dat beeld is blind beslissen.

Zo werkt het afdwingen

Elke enforcer deelt hetzelfde contract: hij haalt een policy-bundle op voor uw API-sleutel, verifieert de Ed25519-handtekening van de bundle tegen SilentShields gepinde publieke sleutels en beslist vervolgens lokaal — toestaan, weigeren of beperken — zonder één aanroep in het antwoordpad.

De gepinde signeersleutels haalt u eenmalig op van https://api.silentshield.io/.well-known/silentshield-agent-keys. En elke enforcer werkt fail-open: bij elke fout — netwerk, handtekening, verlopen bundle — wordt het verzoek doorgelaten. Het afdwingen kan uw site nooit platleggen.

Installatievarianten

Go (net/http)

Een op zichzelf staande enforcer — alleen de standaardbibliotheek, geen SDK. Hij haalt de gesigneerde policy op de achtergrond op, verifieert die (Ed25519, gepinde sleutels) en beslist per verzoek; verpak uw handler met de middleware ervan. Fail-open: bij elke fout of in monitormodus wordt het verzoek doorgelaten.

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

Dezelfde enforcer voor Node.js, die uitsluitend de ingebouwde crypto-module gebruikt. Registreer hem als eerste middleware, zodat hij vóór uw routes draait. Fail-open van opzet.

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

Go- of Node-sjabloon gekopieerd vóór v2.11.1?

Vóór versie 2.11.1 pasten de Go- en Node-sjablonen de voorwaarden “unsigned” en “any” ook toe op aanvragen zonder herkende agent. Gebruikt u een ouder sjabloon en hebt u een van deze voorwaarden aan “deny” gekoppeld, dan blokkeert uw enforcer ook gewone browsers. Kopieer het sjabloon hierboven opnieuw: het past beide voorwaarden alleen nog toe op herkende agents.

PHP

De PHP SDK bevat dezelfde enforcer (PHP 8.1 of nieuwer met ext-sodium en ext-curl). Installeer hem met Composer en roep enforce() helemaal bovenaan uw front controller aan: een geblokkeerd verzoek beantwoordt hij met 403 of 429 en hij beëindigt het script, anders gaat uw applicatie verder. Fail-open: bij elke fout of in de observatiemodus wordt het verzoek doorgelaten. Welke instelling voor het bezoekersadres u nodig hebt, legt de volgende sectie uit.

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

Bezoekersadres achter een proxy

Twee controles hebben het echte bezoekersadres nodig: een crawler bevestigen via zijn gepubliceerde IP-bereiken en een vervalsing herkennen die alleen een bekende naam leent (spoof). Achter een reverse proxy, load balancer of CDN ziet uw server alleen het adres van de proxy. De header X-Forwarded-For alleen bewijst niets: het linkerdeel schrijft de afzender zelf. Daarom nemen de sjablonen een bezoekersadres alleen over via proxy’s die u opgeeft.

TrustedProxies (Go) · trustedProxies (Node) · trusted_proxies (PHP SDK)
Het gebruikelijke geval: voor uw server staat een reverse proxy, load balancer of CDN. Geef de adressen of bereiken daarvan op, bijvoorbeeld 127.0.0.1 of 10.0.0.0/8. Het sjabloon leest X-Forwarded-For van rechts en neemt het eerste adres dat niet bij uw proxy’s hoort.
clientIpHeader (Edge SDK)
Alleen Edge SDK (Next.js, Cloudflare Workers, Vercel Edge): geef de header op waarin uw hostingplatform het bezoekersadres schrijft, bijvoorbeeld x-real-ip bij Vercel of cf-connecting-ip bij Cloudflare — maar alleen als het platform hem zet en een door de bezoeker verstuurde waarde overschrijft. Zonder deze header werken regels van het type ip niet en geldt geen enkel verzoek als vervalsing.
DirectConnection (Go) · directConnection (Node) · direct_connection (PHP SDK)
Alleen als er niets voor uw server staat en bezoekers direct verbinden: het adres van de verbinding is dan de bezoeker.

Go- en Node-sjabloon, PHP SDK: zonder een van beide instellingen gebruikt de enforcer geen bezoekersadres. Regels van het type ip werken niet en geen enkel verzoek geldt als vervalsing. Een crawler kan nog steeds via de directe verbinding worden bevestigd.

Edge SDK: zonder clientIpHeader werken regels van het type ip evenmin en geldt geen enkel verzoek als vervalsing. Een crawler wordt dan alleen bevestigd via het adres dat het platform zelf aan de enforcer doorgeeft (req.ip); geeft het er geen door, dan wordt geen crawler via zijn IP-bereik bevestigd.

Heeft u een eerdere versie van een sjabloon gekopieerd? Kopieer het opnieuw en stel een van de opties in. Is uw server zonder proxy bereikbaar, stel dan de directe verbinding in; anders vervalt na de update de bevestiging via het IP-bereik.

WordPress

Gebruikt u WordPress? De SilentShield-plugin levert de enforcer vanaf versie 2.10.0 — zonder code. Schakel hem in onder Geavanceerd → "AI-crawlers blokkeren (afdwingen)" (standaard uit). Hij haalt dezelfde gesigneerde policy server-side op, verifieert die en blokkeert niet-toegestane bots voor u.

Next.js en andere edge-/serverless-hosts

Ons edge-pakket past in beide Next.js-varianten: proxy.ts vanaf Next.js 16 (Node.js-runtime) en middleware.ts tot en met Next.js 15 (Edge-runtime). De Node.js-enforcer past daar niet: dat is Express-middleware, terwijl Next.js een standaardverzoek doorgeeft en een antwoord verwacht. Het edge-pakket controleert de handtekening in puur JavaScript en beslist lokaal, zonder extra aanroep per verzoek — en laat het verzoek door als er iets misgaat. Installeer het en voeg het toe aan uw 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).*)"],
};

Dezelfde enforcer draait ook op Cloudflare Workers, Vercel Edge en Deno: hij neemt een standaardverzoek aan en geeft een 403- of 429-antwoord terug, of niets als het verzoek door mag. Wilt u uw app liever helemaal niet aanpassen? Zet dan de reverse-proxy-sidecar (hieronder) ervoor.

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

Reverse proxy (nginx / Caddy / Traefik)

Eén klein sidecar-binary bedient alle drie de proxy's: de proxy vraagt het via forward auth één keer per verzoek. Start het met uw site-sleutel en de vertrouwde sleutels:

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

Het sidecar antwoordt op GET /auth met 204 (toestaan), 403 (weigeren) of 429 plus Retry-After (beperken). Zo koppelt u het aan uw 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

De Cloudflare Worker-enforcer verifieert de policy-bundle met Web Crypto Ed25519 en blokkeert voordat verzoeken uw origin überhaupt bereiken:

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

Officiële SDK's

Liever een onderhouden pakket dan het kopieer-plaksnippet hierboven? Installeer een van onze officiële SDK's — dezelfde enforcer plus de verify- en observe-helpers, up-to-date gehouden:

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

De broncode, issues en de volledige README van elke SDK vindt u op GitHub: silentshield-sdk-js (opent in een nieuw tabblad) · silentshield-go (opent in een nieuw tabblad) · silentshield-edge (opent in een nieuw tabblad) · silentshield-sdk-php (opent in een nieuw tabblad)

Eerlijke grenzen

Agentische browsers op residentiële IP-adressen (Comet, ChatGPT Atlas en vergelijkbare) zijn technisch niet te onderscheiden van menselijke bezoekers. Geen enkel product kan ze betrouwbaar identificeren — SilentShield doet voor deze categorie daarom bewust geen afdwingbelofte.

robots.txt en uitgestuurde content-signalen zijn adviserend: nette crawlers houden zich eraan, maar niets dwingt ze daartoe. Technische afdwinging gebeurt alleen in de enforcers op deze pagina — en zelfs die handelen conservatief en weigeren alleen eenduidig geïdentificeerde bekende agents, zodat legitieme bezoekers nooit worden geblokkeerd.

Uw beleid configureren

Welke agent wat mag, configureert u per API-sleutel in de agent-hub: API-sleutels → sleutel selecteren → Agent. Voorinstellingen dekken de gangbare gevallen af; elke wijziging wordt een nieuw ondertekende bundle die uw enforcers automatisch overnemen.

Naar de agent-hub →

Overzicht en voordelen: AI-crawlers en -agents beheren →