SilentShield

에이전트 규칙 적용

적용은 SilentShield AI 에이전트 제어의 2단계입니다: AI 에이전트 방문을 기록만 하는 대신, 서버나 엣지가 키별 정책을 능동적으로 적용해 각 에이전트를 허용, 제한 또는 차단합니다. 관찰 모드 위에 그대로 쌓아 올리는 구조입니다. 시행 구성 요소(Next.js 미들웨어, sidecar 바이너리, Cloudflare Worker)는 현재 얼리 액세스로 요청 시 제공됩니다 — [email protected] 로 문의하세요.

먼저 관찰하고, 그다음 적용

저희의 분명한 권장 사항: 먼저 관찰을 활성화하고 1–2주 동안 실행한 뒤, 무언가를 차단하기 전에 리포트를 확인하세요 — Wordfence의 학습 모드나 DMARC 롤아웃(none → quarantine → reject)과 같은 단계적 방식입니다. 어떤 AI 서비스가 실제로 사이트를 방문하는지, 차단하면 무엇을 잃게 되는지(예: AI 검색에서의 인용)는 리포트만이 보여 줍니다. 이 그림 없이 적용하는 것은 눈을 감고 결정하는 것과 같습니다.

적용 방식

모든 Enforcer는 같은 계약을 공유합니다: API 키의 정책 번들을 가져와 SilentShield의 고정(pinned) 공개 키로 번들의 Ed25519 서명을 검증한 뒤, 요청 경로에서 어떤 외부 호출도 없이 로컬에서 허용, 거부 또는 제한을 결정합니다.

고정 서명 키는 https://api.silentshield.io/.well-known/silentshield-agent-keys 에서 한 번만 가져오면 됩니다. 그리고 모든 Enforcer는 fail-open으로 동작합니다: 네트워크, 서명, 만료된 번들 등 어떤 오류가 발생해도 요청은 통과됩니다. 적용이 사이트를 다운시키는 일은 절대 없습니다.

설정 방식

Go (net/http)

독립형 엔포서입니다 — 표준 라이브러리만 사용하며 SDK가 필요 없습니다. 서명된 정책을 백그라운드에서 가져와 검증하고(Ed25519, 고정된 키) 요청마다 판단합니다. 핸들러를 해당 미들웨어로 감싸세요. 실패 시 허용(fail-open) 방식으로, 오류나 관찰 모드에서는 요청을 통과시킵니다.

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

Node.js용 동일한 엔포서로, 내장 crypto 모듈만 사용합니다. 라우트보다 먼저 실행되도록 첫 번째 미들웨어로 등록하세요. 설계상 실패 시 허용(fail-open) 방식입니다.

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

v2.11.1 이전에 Go 또는 Node 템플릿을 복사하셨습니까?

버전 2.11.1 이전의 Go 및 Node 템플릿은 “unsigned”와 “any” 조건을 식별된 에이전트가 없는 요청에도 적용했습니다. 이전 템플릿을 사용하면서 이 조건 중 하나를 “deny”와 연결했다면 엔포서가 일반 브라우저도 차단합니다. 위의 템플릿을 다시 복사하십시오. 새 템플릿은 두 조건을 식별된 에이전트에만 적용합니다.

PHP

PHP SDK에는 동일한 엔포서가 포함되어 있습니다(PHP 8.1 이상, ext-sodium 및 ext-curl 필요). Composer로 설치하고 프런트 컨트롤러의 맨 위에서 enforce()를 호출하십시오. 차단된 요청에는 403 또는 429로 응답하고 스크립트를 종료하며, 그렇지 않으면 애플리케이션이 계속 실행됩니다. Fail-open 설계로, 오류가 발생하거나 모니터링 모드에서는 요청을 통과시킵니다. 어떤 방문자 주소 설정이 필요한지는 다음 섹션에서 설명합니다.

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

프록시 뒤에서의 방문자 주소

두 가지 검사에는 실제 방문자 주소가 필요합니다. 공개된 IP 범위로 크롤러를 확인하는 것과, 잘 알려진 이름만 빌린 위장(spoof)을 알아보는 것입니다. 리버스 프록시, 로드 밸런서 또는 CDN 뒤에서는 서버에 프록시의 주소만 보입니다. X-Forwarded-For 헤더만으로는 아무것도 증명되지 않습니다. 왼쪽 부분은 발신자가 직접 쓰기 때문입니다. 그래서 템플릿은 지정하신 프록시를 거친 경우에만 방문자 주소를 받아들입니다.

TrustedProxies (Go) · trustedProxies (Node) · trusted_proxies (PHP SDK)
일반적인 경우: 서버 앞에 리버스 프록시, 로드 밸런서 또는 CDN이 있습니다. 그 주소나 범위를 입력하십시오(예: 127.0.0.1 또는 10.0.0.0/8). 템플릿은 X-Forwarded-For를 오른쪽부터 읽고 귀하의 프록시에 속하지 않는 첫 번째 주소를 사용합니다.
clientIpHeader (Edge SDK)
Edge SDK 전용(Next.js, Cloudflare Workers, Vercel Edge): 호스팅 플랫폼이 방문자 주소를 기록하는 헤더를 지정하십시오(예: Vercel의 x-real-ip, Cloudflare의 cf-connecting-ip). 단, 플랫폼이 설정하고 방문자가 보낸 값을 덮어쓰는 헤더만 지정하십시오. 지정하지 않으면 ip 유형의 규칙은 적용되지 않으며 어떤 요청도 위장으로 간주되지 않습니다.
DirectConnection (Go) · directConnection (Node) · direct_connection (PHP SDK)
서버 앞에 아무것도 없고 방문자가 직접 연결하는 경우에만: 그때는 연결 상대의 주소가 방문자입니다.

Go·Node 템플릿과 PHP SDK: 두 설정 중 어느 것도 없으면 엔포서는 방문자 주소를 사용하지 않습니다. ip 유형의 규칙은 적용되지 않으며 어떤 요청도 위장으로 간주되지 않습니다. 크롤러는 직접 연결을 통해 여전히 확인될 수 있습니다.

Edge SDK: clientIpHeader가 없으면 ip 유형의 규칙도 적용되지 않으며 어떤 요청도 위장으로 간주되지 않습니다. 이 경우 크롤러는 플랫폼이 직접 엔포서에 전달하는 주소(req.ip)로만 확인됩니다. 전달하지 않으면 IP 범위로 확인되는 크롤러는 없습니다.

이전 버전의 템플릿을 복사하셨습니까? 다시 복사하고 설정 중 하나를 지정하십시오. 서버에 프록시 없이 접근할 수 있다면 직접 연결을 설정하십시오. 그렇지 않으면 업데이트 후 IP 범위를 통한 확인이 중단됩니다.

WordPress

WordPress를 사용하시나요? SilentShield 플러그인은 2.10.0 버전부터 엔포서를 포함하며 코드가 필요 없습니다. 고급 →「AI 크롤러 차단(강제)」(기본값 꺼짐)에서 켜세요. 동일한 서명된 정책을 서버 측에서 가져와 검증하고 허용되지 않은 봇을 대신 차단합니다.

Next.js 및 기타 엣지 / 서버리스 호스트

엣지용 패키지는 Next.js의 두 형태 모두에서 동작합니다. Next.js 16 이상의 proxy.ts(Node.js 런타임)와 Next.js 15 이하의 middleware.ts(Edge 런타임)입니다. Node.js 엔포서는 여기에 맞지 않습니다. Express용 미들웨어인 반면, Next.js는 표준 요청을 넘기고 응답을 기대하기 때문입니다. 엣지용 패키지는 순수 JavaScript로 서명을 확인하고 로컬에서 판단하므로 요청마다 추가 호출이 없으며, 문제가 생기면 요청을 통과시킵니다. 설치한 뒤 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).*)"],
};

같은 엔포서는 Cloudflare Workers, Vercel Edge, Deno에서도 동작합니다. 표준 요청을 받아 403 또는 429 응답을 반환하며, 통과해도 되는 요청이면 아무것도 반환하지 않습니다. 앱을 전혀 바꾸고 싶지 않다면 리버스 프록시 사이드카(아래)를 앞에 두세요.

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

리버스 프록시 (nginx / Caddy / Traefik)

작은 사이드카 바이너리 하나로 세 가지 프록시를 모두 지원합니다: 프록시가 forward auth를 통해 요청마다 한 번 물어봅니다. 사이트 키와 신뢰 키를 지정해 시작하세요:

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

사이드카는 GET /auth에 204(허용), 403(거부) 또는 429와 Retry-After(제한)로 응답합니다. 프록시에 다음과 같이 연결하세요:

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

Cloudflare Worker

Cloudflare Worker Enforcer는 Web Crypto Ed25519로 정책 번들을 검증하며, 요청이 오리진에 도달하기 전에 차단합니다:

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

공식 SDK

위의 복사·붙여넣기 스니펫보다 관리되는 패키지를 선호하시나요? 저희 공식 SDK 중 하나를 설치하세요 — 동일한 엔포서에 verify 및 observe 헬퍼가 더해지며 항상 최신 상태로 유지됩니다:

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

각 SDK의 소스 코드, 이슈 및 전체 README는 GitHub에서 확인하실 수 있습니다: silentshield-sdk-js (새 탭에서 열림) · silentshield-go (새 탭에서 열림) · silentshield-edge (새 탭에서 열림) · silentshield-sdk-php (새 탭에서 열림)

솔직한 한계

가정용 IP 주소의 에이전트형 브라우저(Comet, ChatGPT Atlas 등)는 기술적으로 사람 방문자와 구별할 수 없습니다. 어떤 제품도 이를 확실하게 식별할 수 없으며 — 그래서 SilentShield는 이 카테고리에 대해 의도적으로 어떤 적용 약속도 하지 않습니다.

robots.txt와 발행되는 콘텐츠 시그널은 권고 사항입니다: 예의 바른 크롤러는 따르지만, 강제할 방법은 없습니다. 기술적 적용은 이 페이지의 Enforcer에서만 이루어지며 — Enforcer조차 보수적으로 동작해, 확실하게 식별된 알려진 에이전트만 거부하므로 정상 방문자가 차단되는 일은 없습니다.

정책 구성

어떤 에이전트에게 무엇을 허용할지는 API 키별로 에이전트 허브에서 구성합니다: API 키 → 키 선택 → 에이전트. 프리셋이 일반적인 경우를 다루며, 변경할 때마다 새로 서명된 번들이 만들어져 Enforcer가 자동으로 적용합니다.

에이전트 허브 열기 →

개요 및 이점: AI 크롤러와 에이전트 제어 →