Appliquer les règles d'agents
L'application des règles est le niveau 2 du Contrôle des agents IA de SilentShield : au lieu de seulement enregistrer les visites des agents IA, votre serveur ou votre edge applique activement votre politique par clé — chaque agent est autorisé, limité ou bloqué. Elle s'appuie directement sur le mode observation. Les composants d'enforcement (middleware Next.js, binaire sidecar, Cloudflare Worker) sont actuellement fournis sur demande en accès anticipé — contactez [email protected].
Observer d'abord, appliquer ensuite
Notre recommandation claire : activez d'abord l'observation, laissez-la tourner une à deux semaines et consultez le rapport avant de bloquer quoi que ce soit — le même déploiement par étapes que le mode apprentissage de Wordfence ou un rollout DMARC (none → quarantine → reject). Seul le rapport montre quels services IA visitent réellement votre site et ce qu'un blocage vous coûterait, par exemple des citations dans la recherche IA. Appliquer sans cette vision, c'est décider à l'aveugle.
Comment fonctionne l'application
Tous les enforcers partagent le même contrat : ils récupèrent un bundle de politique pour votre clé API, vérifient sa signature Ed25519 avec les clés publiques épinglées de SilentShield, puis décident localement — autoriser, refuser ou limiter — sans aucun appel sur le chemin de la requête.
Vous récupérez une seule fois les clés de signature épinglées sur https://api.silentshield.io/.well-known/silentshield-agent-keys. Et chaque enforcer fonctionne en fail-open : à la moindre erreur — réseau, signature, bundle expiré — la requête est laissée passer. L'application des règles ne peut jamais mettre votre site hors service.
Variantes de configuration
Go (net/http)
Un enforcer autonome — bibliothèque standard uniquement, sans SDK. Il récupère et vérifie la politique signée en arrière-plan (Ed25519, clés épinglées) et décide à chaque requête ; enveloppez votre handler avec son middleware. Fail-open : toute erreur ou le mode surveillance laisse passer la requête.
// 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
Le même enforcer pour Node.js, utilisant uniquement le module crypto intégré. Enregistrez-le comme premier middleware afin qu'il s'exécute avant vos routes. Fail-open par conception.
// 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"],
// }));Modèle Go ou Node copié avant la v2.11.1 ?
Avant la version 2.11.1, les modèles Go et Node appliquaient les conditions « unsigned » et « any » aussi aux requêtes sans agent identifié. Si vous utilisez un modèle plus ancien et avez associé l’une de ces conditions à « deny », votre enforcer bloque aussi les navigateurs ordinaires. Copiez de nouveau le modèle ci-dessus : il n’applique plus les deux conditions qu’aux agents identifiés.
PHP
Le SDK PHP intègre le même enforcer (PHP 8.1 ou plus récent avec ext-sodium et ext-curl). Installez-le avec Composer et appelez enforce() tout en haut de votre contrôleur frontal : il répond à une requête bloquée par 403 ou 429 et termine le script ; sinon, votre application continue. Fail-open : toute erreur ou le mode surveillance laisse passer la requête. La section suivante explique quel réglage d’adresse de visiteur il vous faut.
composer config repositories.silentshield vcs https://github.com/forge12interactive/silentshield-sdk-php
composer require forge12interactive/silentshield-sdk<?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();Adresse du visiteur derrière un proxy
Deux contrôles ont besoin de l’adresse réelle du visiteur : confirmer un robot d’exploration par ses plages IP publiées, et reconnaître une usurpation qui ne fait qu’emprunter un nom connu (spoof). Derrière un proxy inverse, un répartiteur de charge ou un CDN, votre serveur ne voit que l’adresse du proxy. L’en-tête X-Forwarded-For seul ne prouve rien : sa partie gauche est écrite par l’expéditeur lui-même. C’est pourquoi les modèles ne reprennent une adresse de visiteur que via les proxys que vous indiquez.
TrustedProxies(Go) ·trustedProxies(Node) ·trusted_proxies(PHP SDK)- Le cas habituel : un proxy inverse, un répartiteur de charge ou un CDN se trouve devant votre serveur. Indiquez ses adresses ou plages, par exemple 127.0.0.1 ou 10.0.0.0/8. Le modèle lit X-Forwarded-For en partant de la droite et prend la première adresse qui n’appartient pas à vos proxys.
clientIpHeader(Edge SDK)- Edge SDK uniquement (Next.js, Cloudflare Workers, Vercel Edge) : indiquez l’en-tête dans lequel votre plateforme d’hébergement écrit l’adresse du visiteur, par exemple x-real-ip chez Vercel ou cf-connecting-ip chez Cloudflare — mais seulement si la plateforme le définit et écrase toute valeur envoyée par le visiteur. Sans lui, les règles de type ip ne s’appliquent pas et aucune requête n’est considérée comme une usurpation.
DirectConnection(Go) ·directConnection(Node) ·direct_connection(PHP SDK)- Uniquement si rien ne se trouve devant votre serveur et que les visiteurs s’y connectent directement : l’adresse de la connexion est alors celle du visiteur.
Modèles Go et Node, SDK PHP : sans l’un de ces deux réglages, l’enforcer n’utilise aucune adresse de visiteur. Les règles de type ip ne s’appliquent pas et aucune requête n’est considérée comme une usurpation. Un robot peut toujours être confirmé via la connexion directe.
Edge SDK : sans clientIpHeader, les règles de type ip ne s’appliquent pas non plus et aucune requête n’est considérée comme une usurpation. Un robot n’est alors confirmé que par l’adresse que la plateforme transmet elle-même à l’enforcer (req.ip) ; si elle n’en transmet aucune, aucun robot n’est confirmé par sa plage d’IP.
Vous avez copié une version antérieure d’un modèle ? Copiez-le à nouveau et définissez l’un des réglages. Si votre serveur est joignable sans proxy, activez la connexion directe ; sinon, la confirmation par plage IP cesse après la mise à jour.
WordPress
Vous utilisez WordPress ? Le plugin SilentShield embarque l'enforcer à partir de la version 2.10.0 — aucun code nécessaire. Activez-le sous Advanced → « Bloquer les robots d'IA (enforce) » (désactivé par défaut). Il récupère et vérifie la même politique signée côté serveur et bloque pour vous les bots non autorisés.
Next.js et autres hébergements edge / serverless
Notre paquet edge convient aux deux variantes de Next.js : proxy.ts à partir de Next.js 16 (runtime Node.js) et middleware.ts jusqu'à Next.js 15 (runtime Edge). L'enforcer Node.js n'y convient pas : c'est un middleware Express, alors que Next.js transmet une requête standard et attend une réponse. Le paquet edge vérifie la signature en JavaScript pur et décide localement, sans appel supplémentaire par requête — et laisse passer la requête en cas de problème. Installez-le et ajoutez-le à votre proxy.ts :
npm i @forge12interactive/silentshield-edgeimport { 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).*)"],
};Le même enforcer fonctionne aussi sur Cloudflare Workers, Vercel Edge et Deno : il reçoit une requête standard et renvoie une réponse 403 ou 429, ou rien si la requête peut passer. Vous préférez ne pas modifier votre application ? Placez le sidecar reverse-proxy (ci-dessous) devant elle.
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)
Un seul petit binaire sidecar dessert les trois proxys : le proxy l'interroge une fois par requête via forward auth. Démarrez-le avec votre clé de site et les clés de confiance :
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-sidecarLe sidecar répond sur GET /auth par 204 (autorisé), 403 (refusé) ou 429 avec Retry-After (limité). Voici comment le raccorder à votre proxy :
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 ...
}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
}http:
middlewares:
silentshield:
forwardAuth:
address: "http://agent-sidecar:8127/auth"
authRequestHeaders:
- "User-Agent"
- "Signature"
- "Signature-Input"
- "Signature-Agent"Cloudflare Worker
L'enforcer Cloudflare Worker vérifie le bundle de politique via Web Crypto Ed25519 et bloque avant même que les requêtes n'atteignent votre origin :
cd enforcers/cloudflare-worker
npx wrangler secret put AGENT_SITE_KEY
# set AGENT_POLICY_URL + AGENT_TRUSTED_KEYS in wrangler.toml [vars]
npx wrangler deploySDK officiels
Vous préférez un paquet maintenu plutôt que l'extrait à copier-coller ci-dessus ? Installez l'un de nos SDK officiels — le même enforcer, plus les utilitaires verify et observe, tenus à jour :
npm install @forge12interactive/silentshield-sdk-jsgo get github.com/forge12interactive/silentshield-gonpm i @forge12interactive/silentshield-edgecomposer config repositories.silentshield vcs https://github.com/forge12interactive/silentshield-sdk-php
composer require forge12interactive/silentshield-sdkLe code source, les tickets et le README complet de chaque SDK sont sur GitHub : silentshield-sdk-js (s’ouvre dans un nouvel onglet) · silentshield-go (s’ouvre dans un nouvel onglet) · silentshield-edge (s’ouvre dans un nouvel onglet) · silentshield-sdk-php (s’ouvre dans un nouvel onglet)
Limites honnêtes
Les navigateurs agentiques sur des adresses IP résidentielles (Comet, ChatGPT Atlas et similaires) sont techniquement impossibles à distinguer des visiteurs humains. Aucun produit ne peut les identifier de manière fiable — SilentShield ne fait donc délibérément aucune promesse d'application pour cette catégorie.
robots.txt et les signaux de contenu émis sont indicatifs : les crawlers bien élevés les respectent, mais rien ne les y oblige. L'application technique n'a lieu que dans les enforcers de cette page — et même eux agissent de façon conservatrice, en ne refusant que les agents connus formellement identifiés, afin que les visiteurs légitimes ne soient jamais bloqués.
Configurer votre politique
Ce que chaque agent peut faire se configure par clé API dans le hub d'agents : Clés API → sélectionner une clé → Agent. Les préréglages couvrent les cas courants ; chaque modification devient un nouveau bundle signé que vos enforcers récupèrent automatiquement.
Aperçu et avantages : Contrôler les robots et agents d’IA →