← Back to All Reviews
ai-infrastructure TechArticle Score: 10/10

Cloudflare Pay Per Crawl (402), Web Bot Auth & AI Labyrinth Guide

Engineering guide to Cloudflare's 2026 AI crawl stack: RFC 9421 Web Bot Auth, HTTP 402 Pay Per Crawl, AI Labyrinth honeypots, and hybrid RAG pipelines.

PO ProxyOps Engineering
•

For thirty years, automated web access rested on an informal handshake: crawlers declared a plain-text User-Agent header, publishers posted advisory robots.txt directives, and security teams enforced static IP allowlists for Googlebot or Bingbot. Between 2024 and 2026, autonomous AI agents, real-time Retrieval-Augmented Generation (RAG) engines, and foundation-model training crawlers shattered every assumption behind that handshake.

In late 2026, AI infrastructure engineers no longer face a single binary 200 OK vs. Cloudflare Error 1020 firewall rule. Instead, roughly one-fifth of the global web sitting behind Cloudflare’s edge now runs an integrated three-layer AI Crawl Control protocol stack:

  1. Cryptographic Identity (Web Bot Auth via IETF RFC 9421): Replacing spoofable User-Agent strings and brittle IP CIDR lists with Ed25519 HTTP Message Signatures verified at the edge against /.well-known/http-message-signatures-directory.
  2. Economic Settlement (Pay Per Crawl via HTTP 402 Payment Required & x402): Turning HTTP status code 402—dormant in the HTTP specification since 1997—into a live machine-to-machine micropayment and bilateral licensing gate.
  3. Active Deception (AI Labyrinth): Routing unverified, policy-ignoring link crawlers into synthetic, LLM-generated honeypot graphs that simultaneously flag bot infrastructure and poison downstream vector databases.

While we previously published a brief primer on what Cloudflare AI Labyrinth means for data teams, production AI architects need a unified protocol and code blueprint covering all three layers together. How do you sign outbound agent requests with RFC 9421 Ed25519 keys? How do you protect autonomous agents from Denial-of-Wallet (402 budget drain) attacks? How do you keep synthetic labyrinth pages from corrupting Qdrant or pgvector embeddings? And when should your pipeline route through @brightdata/mcp and Bright Data Web Unlocker instead?

This guide answers every one of those architectural questions with protocol specifications, threat models, TCO matrices, and three complete Python and TypeScript production modules.

Zero Corpus PoisoningGround AI Agents Safely with @brightdata/mcp & Web Unlockervia bright-data

1. Layer 1: Cryptographic Bot Identity (Web Bot Auth & IETF RFC 9421)

1.1 Why User-Agent Strings and IP Allowlists Died

Historically, “verified bots” proved their identity via two mechanisms: publishing static JSON files of egress IPv4/IPv6 CIDR blocks (like googlebot.json or OpenAI’s gptbot.json) or passing forward-confirmed reverse DNS (FCrDNS) lookups.

By 2026, both mechanisms became operationally untenable for modern AI agent platforms:

  • Ephemeral Cloud & Multi-Region Serverless Egress: An enterprise LangGraph or CrewAI agent running on AWS Fargate, Cloudflare Workers, Fly.io, or Google Cloud Run shares dynamic NAT pools with thousands of unrelated tenants. Static IP allowlisting either over-trusts an entire cloud region or breaks every time an autoscaler shifts availability zones.
  • Trivial Header Spoofing: Any ten-line Python script can send User-Agent: Mozilla/5.0 (compatible; ClaudeBot/1.0) or spoof browser headers, forcing Cloudflare to treat unsigned User-Agent claims as zero-trust noise alongside Cloudflare Turnstile browser attestation.

1.2 How RFC 9421 HTTP Message Signatures Work at Cloudflare’s Edge

To replace IP-based identity with cryptographic proof, Cloudflare spearheaded the Web Bot Auth profile built directly on IETF RFC 9421 (HTTP Message Signatures) and RFC 8941 (Structured Field Values).

Instead of asking “which IP sent this packet?”, the edge asks “was this exact HTTP request cryptographically signed within the last 60 seconds by the private Ed25519 key published at this agent operator’s verified domain?”

The Four Protocol Primitives of Web Bot Auth

  1. Key Discovery Directory (/.well-known/http-message-signatures-directory): Your agent organization hosts an HTTPS endpoint returning a JSON Web Key Set (application/http-message-signatures-directory+json) containing one or more Ed25519 public keys (kty: "OKP", crv: "Ed25519"). Crucially, each key’s identifier (kid) is its base64url-encoded RFC 7638 JWK SHA-256 Thumbprint, binding the key ID mathematically to the public key material.
  2. Signature-Agent Header: Every outbound crawl request includes an RFC 8941 structured string header pointing Cloudflare’s edge verifier to your key directory authority—for example: Signature-Agent: "https://crawler-keys.acme-ai.example"
  3. Canonical Signature Base & Signature-Input: Your HTTP client constructs a deterministic multi-line ASCII signature base covering at minimum @authority (target host), @path (request path + query, or @target-uri), and "signature-agent", paired with metadata parameters inside Signature-Input:
    • created: Unix epoch integer when the signature was generated.
    • expires: Unix epoch integer (typically created + 60 to created + 300 seconds) limiting replay windows.
    • keyid: Base64url RFC 7638 JWK thumbprint matching your directory.
    • alg: "ed25519".
    • nonce: Cryptographically random 128-bit+ token preventing intra-window replay.
    • tag: "web-bot-auth" (domain-separating crawl signatures from banking or webhook RFC 9421 profiles).
  4. Signature Header: Contains the raw 64-byte Ed25519 signature over the UTF-8 signature base, formatted as an RFC 8941 byte sequence: sig1=:BASE64_SIGNATURE_BYTES:.

When a signed request hits any Cloudflare POP globally, the edge worker fetches and caches your /.well-known/http-message-signatures-directory JWK set, verifies the Ed25519 signature in under 0.3 milliseconds, and populates cf.botManagement.verifiedBot and Web Bot Auth operator metadata before publisher WAF or Pay Per Crawl rules execute.


2. Layer 2: Economic Access Control (Pay Per Crawl, HTTP 402, and x402)

Once cryptographic bot identity (Layer 1) makes an AI crawler provably identifiable, publishers gain a third option beyond “Allow for free” and “Block with 403”: metered machine-to-machine licensing at the HTTP transport layer.

2.1 Revival of HTTP 402 Payment Required

When RFC 2068 defined 402 Payment Required in 1997 with the note “reserved for future use,” the web lacked both cryptographic agent identity and sub-cent programmable settlement rails. With Cloudflare Pay Per Crawl (and parallel open ecosystem standards such as x402 machine payment headers), publishers configure per-domain or per-route tariffs directly at the CDN edge.

sequenceDiagram
    autonumber
    participant Agent as AI Agent / RAG Orchestrator
    participant Budget as 402 Budget & Policy Enforcer
    participant CF as Cloudflare Edge (AI Crawl Control)
    participant JWKS as Agent /.well-known Key Directory
    participant Origin as Publisher Origin / Bright Data Fallback

    Agent->>Budget: Request URL for RAG grounding
    Budget->>Budget: Check domain policy & remaining daily USD cap
    Budget->>CF: GET /research/report-2026 (Signed RFC 9421 + Signature-Agent)
    CF->>JWKS: Fetch & cache Ed25519 JWK Set (cache miss only)
    JWKS-->>CF: Return OKP Ed25519 public key + thumbprint
    CF->>CF: Verify Ed25519 signature, nonce & expires window
    alt Publisher Requires Pay Per Crawl (Unsettled Probe)
        CF-->>Budget: HTTP 402 Payment Required (crawler-price: USD 0.005)
        Budget->>Budget: Validate 0.005 <= maxPricePerFetchUsd ($0.02 cap)
        alt Approved Partner & Within Micro-Budget
            Budget->>CF: Re-issue Signed GET + crawler-max-price: 0.01 + Payment Auth
            CF->>Origin: Forward authorized crawl request
            Origin-->>CF: 200 OK Canonical Article Payload
            CF-->>Budget: 200 OK (crawler-charged: USD 0.005)
            Budget-->>Agent: Deliver verified publisher document + ledger receipt
        else Unapproved Domain or Price Spike Attack ($2.50/page)
            Budget->>Origin: Route public query via @brightdata/mcp SERP / Web Unlocker
            Origin-->>Budget: Clean Readability Markdown / Licensed Feed
            Budget-->>Agent: Deliver sanitized context (Wallet protected)
        end
    else Free Verified Bot Access Allowed
        CF->>Origin: Forward verified bot request
        Origin-->>CF: 200 OK
        CF-->>Budget: 200 OK
        Budget-->>Agent: Deliver verified document
    end

2.2 Inside the 402 Negotiation Headers

A Pay Per Crawl transaction operates via two deterministic patterns—Reactive 402 Quote-Then-Commit or Pre-Authorized Ceiling Header:

  1. Discovery / Quote Response (HTTP 402 Payment Required): If a signed crawler requests a monetized URL without payment authorization (or with a ceiling below the publisher’s tariff), Cloudflare’s edge intercepts the request before hitting the origin server and returns HTTP/2 402 with pricing metadata headers (such as crawler-price: 0.008 denominated in USD, alongside currency/settlement parameters or an x402 JSON payment requirement descriptor).
  2. Pre-Authorized Ceiling (crawler-max-price / Payment Commitment): To avoid doubling round-trip latency on known partner domains, an authorized crawler sends its RFC 9421 signature plus an explicit bid ceiling header (e.g., crawler-max-price: 0.0100). If the publisher’s configured tariff is $0.005, the edge debits $0.005 against the operator’s clearing account (or settles the x402 cryptographic payment token), forwards the request to origin, and attaches crawler-charged: 0.005 on the 200 OK response. If the publisher suddenly raises its price to $0.050, the edge rejects the request with 402 without charging a cent.

2.3 Threat Modeling: Autonomous Agent “Denial-of-Wallet” Attacks

Giving an autonomous LLM agent unconstrained authority to settle HTTP 402 challenges on the open web introduces a severe new vulnerability class: Denial-of-Wallet (DoW) & Adversarial Tariff Injection.

Consider what happens if a user prompts an enterprise research agent to summarize market news, and a malicious actor injects links (via SEO poisoning, forum comments, or prompt injection) pointing to an attacker-controlled Cloudflare domain configured at $5.00 per request with 200 auto-redirected sub-resources:

  • Without a deterministic policy controller, a naive 402 auto-payer burns $1,000 in seconds.
  • Retry loops on transient 502/504 upstream errors can trigger duplicate debits unless strict URL + time-bucket idempotency keys are enforced.

Therefore, production 402 support must never live inside an LLM tool prompt. It must be enforced in deterministic infrastructure middleware (see Code Module 2 in Section 5.2) with four hard guardrails:

  1. Explicit Bilateral Domain Allowlist: Only auto-settle 402 charges on pre-vetted publisher domains with clear commercial value (e.g., financial news wires, scientific journals, proprietary industry directories).
  2. Hard Per-Request Ceiling (maxPricePerFetchUsd): Reject any single HTML document priced above your unit economics threshold (typically $0.001 to $0.02).
  3. Rolling 24-Hour Per-Domain & Per-Tenant Micro-Budgets: Trip a hard circuit breaker once a domain consumes its daily allocation (e.g., $10.00/day).
  4. Clear Legal & Compliance Partitioning: Use Web Bot Auth + 402 settlement when licensing paywalled journalism or honoring Text and Data Mining (TDM) reservation opt-outs (TDMRep / robots.txt under EU DSM Directive Article 4 and the EU AI Act web scraping compliance rules). For public-web factual verification, SERP grounding, and competitive price monitoring on public storefronts, route through managed retrieval infrastructure (@brightdata/mcp and Web Unlocker).

3. Layer 3: Deception & Corpus Poisoning Defense (AI Labyrinth)

What happens when an unsigned crawler ignores robots.txt, skips Web Bot Auth, and scrapes HTML across a Cloudflare-protected domain anyway?

Instead of returning an obvious 403 Forbidden—which tells the scraper operator to immediately rotate proxy subnets or tweak headers—Cloudflare’s AI Labyrinth deploys active cyber-deception.

3.1 Anatomy of an AI Labyrinth Trap in the DOM

When AI Labyrinth is enabled on a zone, Cloudflare’s edge HTML rewriter dynamically injects visually imperceptible anchor tags (<a>) into legitimate pages. Real human readers using Chrome or Safari never render or click these links because they are concealed through combinations of CSS, ARIA, and layout geometry techniques:

  • Inline or stylesheet display suppression (display: none, visibility: hidden, opacity: 0, font-size: 0px).
  • Off-viewport absolute positioning (position: absolute; left: -9999px; top: -9999px) or zero-area clipping (clip-path: inset(100%), width: 0; height: 0, overflow: hidden).
  • Assistive-technology exclusion (aria-hidden="true", tabindex="-1") combined with crawler directives (rel="nofollow noindex").
  • Deeply nested synthetic path structures containing high-entropy hashes or plausible-looking archival slugs that never appear in the domain’s canonical sitemap.xml or internal navigation menus.

3.2 The Dual Blast Radius: Reputation Burn + Vector Database Poisoning

When a naive Python BeautifulSoup or Scrapy LinkExtractor parses raw HTML text and enqueues every href attribute in a breadth-first crawl, two destructive things happen simultaneously:

  1. Zero-False-Positive Bot Fingerprinting: Because zero real humans click an invisible aria-hidden 1x1 off-screen link, a single HTTP request to a labyrinth trap URL gives Cloudflare mathematical certainty that your client is a headless HTML parser. Cloudflare immediately correlates that request’s IP address, TLS JA4 hash, HTTP/2 fingerprint, and session cookies, tanking your infrastructure’s global trust score across millions of zones.
  2. Silent RAG & Fine-Tuning Corpus Poisoning: Unlike classic 2010-era spider traps that returned infinite calendar loops or gibberish lorem ipsum, AI Labyrinth serves rich, syntactically valid, scientifically coherent AI-generated articles pre-rendered and cached on Cloudflare Workers AI. These decoy pages contain real headers, clean paragraphs, and factual-sounding statements—about completely unrelated topics (for instance, an enterprise SaaS vendor’s subdomain suddenly serving 40 pages of detailed marine biology or 18th-century metallurgy essays).

If your RAG ingestion pipeline blindly chunks and embeds every 200 OK page into Qdrant, Pinecone, or PostgreSQL pgvector:

  • Your embedding API bill (text-embedding-3-large / voyage-3) balloons on synthetic junk.
  • Domain-filtered metadata queries (WHERE source_domain = 'competitor.com') return hallucinated decoy chunks into your LLM’s context window, causing confident, ungrounded answers in customer-facing AI assistants.

4. Layer 4: Enterprise Hybrid Retrieval Architecture (2026 Reference Stack)

To survive and thrive in this three-layer landscape, leading AI infrastructure teams no longer run monolithic raw HTML crawlers. Instead, they separate bilateral licensed crawling from unblocked public-web grounding behind a unified Hybrid Retrieval & Anti-Poisoning Pipeline:

flowchart TD
    Query["Agent Task / RAG Ingestion Seed"] --> Classifier{"Domain & Intent Policy Router"}

    Classifier -->|"Bilateral Licensed Publisher / Paywalled News"| PathA["Path A: Direct Signed Crawler (RFC 9421 Web Bot Auth + 402 Budget Enforcer)"]
    Classifier -->|"Search Discovery / E-Commerce / Social Entities"| PathB["Path B: Structured Feeds (Bright Data SERP API & Web Scraper Datasets)"]
    Classifier -->|"Public Web Pages / Competitor Docs / Dynamic SPAs"| PathC["Path C: Managed Markdown Plane (@brightdata/mcp + Web Unlocker)"]

    PathA --> Sanitizer["Anti-Poisoning DOM & Coherence Gate"]
    PathB --> Chunker["Semantic Chunker & Provenance Tagger"]
    PathC --> Sanitizer

    subgraph Guardrails["Corpus Integrity & Anti-Labyrinth Filters"]
        Sanitizer --> CheckCanon["1. Canonical URL & Sitemap Alignment Check"]
        CheckCanon --> CheckVis["2. Computed Visibility & Trap Link Stripper"]
        CheckVis --> CheckEnt["3. Shannon Path Entropy & Domain Topic Drift Filter"]
    end

    CheckEnt -->|"Verified Clean Text"| Chunker
    CheckEnt -->|"Flagged Decoy / Soft-Block"| Quarantine["Quarantine Log & Dead-Letter Queue (Zero Vector Write)"]
    Chunker --> VectorDB["Production Vector Store (Qdrant / Pinecone / pgvector)"]

4.1 Why @brightdata/mcp and Web Unlocker Neutralize AI Labyrinth Poisoning

Notice how Path B and Path C eliminate the two biggest failure modes of raw scraping for AI agents:

  1. SERP-Grounded URL Discovery Instead of Blind BFS Crawling: Instead of unleashing a recursive link spider onto a site and praying it avoids hidden honeypot links, your agent calls Bright Data’s SERP API (or search_engine in @brightdata/mcp) with site:target.com <topic>. Because search engines already exclude noindex/nofollow labyrinth traps and rank canonical user-facing pages, 100% of your seed URLs are pre-vetted canonical documents.
  2. Point-Targeted Clean Markdown Extraction: Rather than downloading raw HTML and spidering child links, calling Bright Data Web Unlocker (or @brightdata/mcp’s scrape_as_markdown tool) retrieves the exact target URL via real browser protocol synthesis, strips hidden DOM chrome via Readability AST parsing, and hands your LLM clean semantic Markdown—cutting input token spend by 85% to 93% while never clicking a single hidden anchor tag.

4.2 Architectural & TCO Comparison: 3 Agent Crawling Paradigms (100k Pages / Mo)

Evaluation DimensionRaw Unsigned Crawler (httpx / Scrapy + Resi Proxies)Pure Direct RFC 9421 + HTTP 402 StackHybrid Stack (RFC 9421 Partners + @brightdata/mcp & Web Unlocker)
Cloudflare WAF / Turnstile Pass Rate12% – 24%High only on consenting/paid publishers; 0% on strict anti-bot storefronts98.7%+ across public web + 100% on bilateral 402 partners
AI Labyrinth Poisoning RiskCritical (High vector DB corruption)Low on paid feeds; Moderate if crawling unsigned sitesNear-Zero (SERP-grounded URLs + visibility sanitizer)
LLM Context Token EfficiencyPoor (40k–100k raw HTML tokens/page)Moderate (Requires custom HTML-to-Markdown AST pipeline)Optimal (2k–6k clean Readability Markdown tokens/page)
Key Rotation & Protocol OpsNone (Constant proxy subnet burn instead)High (JWKS hosting, key rotation, 402 ledger reconciliation)Low (Scoped JWKS for partner list + managed MCP/API)
Auditability & EU AI Act LineagePoorExcellent (Cryptographic receipts)Excellent (Signed receipts + clean public provenance logs)
Estimated Monthly TCO (100k Pages)~$1,450 (wasted GBs + poisoned re-indexing)~$950 – $2,800 (varies by publisher 402 tariffs + eng ops)~$340 – $620 / mo (optimal mix of Web Unlocker + selective 402)
Save 85% on LLM TokensDeploy Bright Data Web Unlocker & MCP for Clean RAG Ingestionvia bright-data

5. Production Engineering Blueprint: 3 Runnable Code Modules

Below are the three core infrastructure components required to run a compliant, wallet-safe, poison-immune 2026 agentic retrieval pipeline.

5.1 Code Module 1: Python RFC 9421 Ed25519 Web Bot Auth Signer & JWK Directory Generator

This self-contained Python 3.12+ module uses cryptography and httpx to:

  1. Generate (or load) an Ed25519 signing keypair.
  2. Export the exact /.well-known/http-message-signatures-directory JSON payload with its RFC 7638 SHA-256 JWK Thumbprint (kid).
  3. Implement a plug-and-play httpx.Auth class (WebBotAuthSigner) that attaches Signature-Agent, Signature-Input, and Signature headers to every outgoing HTTP request in strict compliance with RFC 9421.
# rfc9421_web_bot_auth.py — IETF RFC 9421 Ed25519 HTTP Message Signer & JWKS Generator
from __future__ import annotations

import base64
import hashlib
import json
import secrets
import time
from dataclasses import dataclass
from typing import Generator

import httpx
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey


def b64url_no_pad(data: bytes) -> str:
    """Encode bytes using RFC 4648 URL-safe Base64 without '=' padding."""
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


@dataclass(frozen=True, slots=True)
class BotKeyMaterial:
    private_key: Ed25519PrivateKey
    public_key_b64url: str
    jwk_thumbprint_kid: str

    @classmethod
    def from_pem_or_generate(cls, pem_bytes: bytes | None = None) -> BotKeyMaterial:
        priv = (
            serialization.load_pem_private_key(pem_bytes, password=None)
            if pem_bytes
            else Ed25519PrivateKey.generate()
        )
        if not isinstance(priv, Ed25519PrivateKey):
            raise TypeError("Web Bot Auth requires an Ed25519 private key.")

        raw_pub = priv.public_key().public_bytes(
            encoding=serialization.Encoding.Raw,
            format=serialization.PublicFormat.Raw,
        )
        x_b64 = b64url_no_pad(raw_pub)

        # RFC 7638 Section 3.1: Lexicographically sorted canonical JWK members for OKP
        canonical_jwk = json.dumps(
            {"crv": "Ed25519", "kty": "OKP", "x": x_b64},
            separators=(",", ":"),
            sort_keys=True,
        ).encode("utf-8")
        kid = b64url_no_pad(hashlib.sha256(canonical_jwk).digest())

        return cls(private_key=priv, public_key_b64url=x_b64, jwk_thumbprint_kid=kid)

    def export_well_known_directory(self) -> str:
        """Produce JSON for /.well-known/http-message-signatures-directory."""
        doc = {
            "keys": [
                {
                    "kty": "OKP",
                    "crv": "Ed25519",
                    "kid": self.jwk_thumbprint_kid,
                    "x": self.public_key_b64url,
                    "use": "sig",
                    "alg": "EdDSA",
                }
            ]
        }
        return json.dumps(doc, indent=2)


class WebBotAuthSigner(httpx.Auth):
    """
    RFC 9421 HTTP Message Signature middleware for httpx clients.
    Covers ("@authority" "@path" "signature-agent") with tag="web-bot-auth".
    """

    def __init__(
        self,
        key_material: BotKeyMaterial,
        agent_directory_origin: str,
        ttl_seconds: int = 120,
        signature_label: str = "sig1",
    ) -> None:
        if ttl_seconds <= 0 or ttl_seconds > 300:
            raise ValueError("ttl_seconds must be between 1 and 300 seconds.")
        self.key_material = key_material
        # RFC 8941 Structured String syntax: quoted URI
        self.signature_agent_val = f'"{agent_directory_origin.rstrip("/")}"'
        self.ttl_seconds = ttl_seconds
        self.label = signature_label

    @staticmethod
    def _derive_authority(url: httpx.URL) -> str:
        host = url.host.lower()
        if url.port is None:
            return host
        if (url.scheme == "https" and url.port == 443) or (url.scheme == "http" and url.port == 80):
            return host
        return f"{host}:{url.port}"

    @staticmethod
    def _derive_path(url: httpx.URL) -> str:
        raw_path = url.raw_path.decode("ascii")
        return raw_path if raw_path else "/"

    def build_signature_headers(self, request: httpx.Request) -> dict[str, str]:
        created = int(time.time())
        expires = created + self.ttl_seconds
        nonce = b64url_no_pad(secrets.token_bytes(16))

        authority = self._derive_authority(request.url)
        path = self._derive_path(request.url)

        sig_params = (
            f'("@authority" "@path" "signature-agent");'
            f"created={created};"
            f"expires={expires};"
            f'keyid="{self.key_material.jwk_thumbprint_kid}";'
            f'alg="ed25519";'
            f'nonce="{nonce}";'
            f'tag="web-bot-auth"'
        )

        # RFC 9421 Section 2.5 Canonical Signature Base
        signature_base = "\n".join(
            [
                f'"@authority": {authority}',
                f'"@path": {path}',
                f'"signature-agent": {self.signature_agent_val}',
                f'"@signature-params": {sig_params}',
            ]
        ).encode("utf-8")

        raw_sig = self.key_material.private_key.sign(signature_base)
        sig_b64 = base64.b64encode(raw_sig).decode("ascii")

        return {
            "Signature-Agent": self.signature_agent_val,
            "Signature-Input": f"{self.label}={sig_params}",
            "Signature": f"{self.label}=:{sig_b64}:",
        }

    def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
        for header_name, header_val in self.build_signature_headers(request).items():
            request.headers[header_name] = header_val
        yield request


if __name__ == "__main__":
    # Demo: Generate Ed25519 directory & inspect signed outbound request headers
    bot_keys = BotKeyMaterial.from_pem_or_generate()
    print("=== Publish at https://bot.acme-ai.example/.well-known/http-message-signatures-directory ===")
    print(bot_keys.export_well_known_directory())

    signer = WebBotAuthSigner(
        key_material=bot_keys,
        agent_directory_origin="https://bot.acme-ai.example",
    )
    sample_req = httpx.Request("GET", "https://publisher.example.com/articles/q4-earnings?lang=en")
    signed_headers = signer.build_signature_headers(sample_req)
    print("\n=== Outbound RFC 9421 Headers ===")
    for k, v in signed_headers.items():
        print(f"{k}: {v}")

5.2 Code Module 2: TypeScript HTTP 402 Crawl Budget Controller & Bright Data Fallback Router

This TypeScript service sits between your LLM orchestrator and the network. It parses HTTP 402 price quotes (crawler-price and x402 headers), enforces per-request price caps and rolling 24-hour per-domain micro-budgets to block Denial-of-Wallet attacks, and seamlessly falls back to Bright Data Web Unlocker Markdown mode when an unapproved domain demands excessive tariffs or blocks unauthenticated bots.

// crawl_402_budget_controller.ts — HTTP 402 Pay-Per-Crawl Governor & Hybrid Fallback (Node 22+)
import crypto from 'node:crypto';

export interface DomainLicensePolicy {
  domain: string;
  allow402Settlement: boolean;
  maxPricePerFetchUsd: number;   // Hard ceiling per single page (e.g. $0.015)
  dailyBudgetCapUsd: number;     // Max 24h spend on this publisher (e.g. $10.00)
}

export interface RetrievalOutcome {
  url: string;
  channel: 'direct_free' | 'licensed_402_settled' | 'brightdata_unlocker_markdown';
  contentMarkdownOrHtml: string;
  settledUsd: number;
  idempotencyKey: string;
}

interface DailySpendLedger {
  windowStartMs: number;
  spentUsd: number;
}

export class Crawl402BudgetController {
  private readonly policies = new Map<string, DomainLicensePolicy>();
  private readonly spendLedger = new Map<string, DailySpendLedger>();

  constructor(
    initialPolicies: DomainLicensePolicy[],
    private readonly brdApiToken: string,
    private readonly brdUnlockerZone: string = 'web_unlocker1',
    private readonly signRfc9421Headers: (url: string) => Record<string, string>,
    private readonly globalMaxPriceCeilingUsd: number = 0.025, // Absolute safety rail: $0.025/req
  ) {
    for (const p of initialPolicies) {
      this.policies.set(p.domain.toLowerCase(), p);
    }
  }

  private getRemainingDailyBudget(domain: string, capUsd: number): number {
    const now = Date.now();
    const dayMs = 24 * 60 * 60 * 1000;
    const entry = this.spendLedger.get(domain);
    if (!entry || now - entry.windowStartMs >= dayMs) {
      this.spendLedger.set(domain, { windowStartMs: now, spentUsd: 0 });
      return capUsd;
    }
    return Math.max(0, capUsd - entry.spentUsd);
  }

  private recordSpend(domain: string, amountUsd: number): void {
    const entry = this.spendLedger.get(domain) ?? { windowStartMs: Date.now(), spentUsd: 0 };
    entry.spentUsd += amountUsd;
    this.spendLedger.set(domain, entry);
  }

  private parse402QuoteUsd(headers: Headers): number | null {
    // 1. Check Cloudflare Pay Per Crawl header (e.g. "0.005" or "USD 0.005")
    const rawCrawlerPrice = headers.get('crawler-price');
    if (rawCrawlerPrice) {
      const cleaned = rawCrawlerPrice.replace(/usd/i, '').trim();
      const parsed = Number.parseFloat(cleaned);
      if (Number.isFinite(parsed) && parsed >= 0) return parsed;
    }

    // 2. Check x402 JSON payment-required header envelope if present
    const x402Header = headers.get('x-payment-required') ?? headers.get('payment-required');
    if (x402Header) {
      try {
        const decoded = JSON.parse(Buffer.from(x402Header, 'base64').toString('utf8')) as {
          maxAmountRequiredUsd?: number;
        };
        if (typeof decoded.maxAmountRequiredUsd === 'number') {
          return decoded.maxAmountRequiredUsd;
        }
      } catch {
        return null;
      }
    }
    return null;
  }

  public async retrieveForAgent(url: string): Promise<RetrievalOutcome> {
    const parsedUrl = new URL(url);
    const hostname = parsedUrl.hostname.toLowerCase();
    const policy = this.policies.get(hostname);

    // Deterministic 10-minute bucket idempotency key prevents retry double-billing
    const timeBucket = Math.floor(Date.now() / (10 * 60 * 1000));
    const idempotencyKey = crypto
      .createHash('sha256')
      .update(`${url}::${timeBucket}`)
      .digest('hex')
      .slice(0, 24);

    // Only initiate signed RFC 9421 direct crawl for configured partner domains
    if (policy) {
      const probeRes = await fetch(url, {
        method: 'GET',
        headers: {
          ...this.signRfc9421Headers(url),
          Accept: 'text/markdown, text/html;q=0.9',
        },
        redirect: 'manual', // Never follow cross-origin redirects with signed payment headers!
        signal: AbortSignal.timeout(15_000),
      });

      if (probeRes.status === 200) {
        return {
          url,
          channel: 'direct_free',
          contentMarkdownOrHtml: await probeRes.text(),
          settledUsd: 0,
          idempotencyKey,
        };
      }

      if (probeRes.status === 402 && policy.allow402Settlement) {
        const quotedUsd = this.parse402QuoteUsd(probeRes.headers);
        const effectiveCap = Math.min(policy.maxPricePerFetchUsd, this.globalMaxPriceCeilingUsd);
        const remainingDaily = this.getRemainingDailyBudget(hostname, policy.dailyBudgetCapUsd);

        if (
          quotedUsd !== null &&
          quotedUsd > 0 &&
          quotedUsd <= effectiveCap &&
          quotedUsd <= remainingDaily
        ) {
          const paidRes = await fetch(url, {
            method: 'GET',
            headers: {
              ...this.signRfc9421Headers(url),
              'crawler-max-price': effectiveCap.toFixed(4),
              'Idempotency-Key': idempotencyKey,
              Accept: 'text/markdown, text/html;q=0.9',
            },
            redirect: 'manual',
            signal: AbortSignal.timeout(20_000),
          });

          if (paidRes.status === 200) {
            const actualCharged =
              Number.parseFloat(paidRes.headers.get('crawler-charged') ?? '') || quotedUsd;
            this.recordSpend(hostname, actualCharged);
            return {
              url,
              channel: 'licensed_402_settled',
              contentMarkdownOrHtml: await paidRes.text(),
              settledUsd: actualCharged,
              idempotencyKey,
            };
          }
        }
        // Quote exceeded cap or daily budget exhausted -> log Denial-of-Wallet guard & fallback
        console.warn(
          `[402-GUARD] Rejected 402 quote ($${quotedUsd}) on ${hostname} (cap=$${effectiveCap}, rem=$${remainingDaily.toFixed(3)})`,
        );
      }
    }

    // Public-web retrieval fallback: Bright Data Web Unlocker clean Markdown mode
    return this.fetchViaBrightDataMarkdown(url, idempotencyKey);
  }

  private async fetchViaBrightDataMarkdown(
    url: string,
    idempotencyKey: string,
  ): Promise<RetrievalOutcome> {
    const res = await fetch('https://api.brightdata.com/request', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${this.brdApiToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        zone: this.brdUnlockerZone,
        url,
        format: 'raw',
        data_format: 'markdown', // Server-side Readability AST -> clean LLM Markdown!
      }),
      signal: AbortSignal.timeout(45_000),
    });

    if (!res.ok) {
      throw new Error(`Bright Data Markdown fallback failed with HTTP ${res.status} for ${url}`);
    }

    return {
      url,
      channel: 'brightdata_unlocker_markdown',
      contentMarkdownOrHtml: await res.text(),
      settledUsd: 0.0015,
      idempotencyKey,
    };
  }
}

Before any HTML page discovered by your crawler is allowed to enqueue child links or write embeddings into Qdrant or pgvector, run it through this AI Labyrinth & Corpus Poisoning Sanitizer. It combines four orthogonal defenses:

  1. CSS & Accessibility Trap Rejection: Drops <a> tags hidden via aria-hidden="true", display:none, visibility:hidden, opacity:0, font-size:0, negative off-screen coordinates, or rel="nofollow".
  2. URL Path Shannon Entropy Scoring: Flags synthetic random-token labyrinth URLs (entropy > 4.35 bits/char on path segments).
  3. Canonical & Robots Meta Enforcement: Quarantines documents carrying <meta name="robots" content="noindex"> or mismatched <link rel="canonical"> targets—a hallmark of synthetic trap pages that site owners exclude from Google Search.
  4. Domain Lexical Anchor Verification: Verifies that candidate documents retain expected domain/brand anchor vocabulary before vector chunking, catching AI-generated off-topic essays immediately.
# rag_labyrinth_sanitizer.py — Anti-Poisoning DOM & Link Sanitizer for RAG Pipelines
from __future__ import annotations

import math
import re
from collections import Counter
from dataclasses import dataclass
from urllib.parse import urljoin, urlparse

from bs4 import BeautifulSoup, Tag

HIDDEN_STYLE_REGEX = re.compile(
    r"(display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?:\.0+)?\b|"
    r"font-size\s*:\s*0|left\s*:\s*-\d{3,}px|top\s*:\s*-\d{3,}px|"
    r"clip-path\s*:\s*inset\(\s*100%|width\s*:\s*0px|height\s*:\s*0px)",
    re.IGNORECASE,
)

TRAP_PATH_PREFIXES: tuple[str, ...] = (
    "/cdn-cgi/",
    "/__cf_",
    "/trap/",
    "/honeypot/",
)


def shannon_entropy(text: str) -> float:
    """Compute Shannon entropy in bits per character."""
    if not text:
        return 0.0
    counts = Counter(text)
    length = len(text)
    return -sum((c / length) * math.log2(c / length) for c in counts.values())


@dataclass(slots=True)
class SanitizedDocument:
    canonical_url: str
    is_safe_for_rag: bool
    quarantine_reason: str | None
    clean_text: str
    safe_internal_links: list[str]


class RagLabyrinthSanitizer:
    """Filters Cloudflare AI Labyrinth traps and validates RAG corpus integrity."""

    def __init__(
        self,
        allowed_domain: str,
        domain_anchor_terms: set[str],
        sitemap_urls: set[str] | None = None,
        max_segment_entropy: float = 4.35,
        max_path_depth: int = 6,
    ) -> None:
        self.allowed_domain = allowed_domain.lower()
        self.domain_anchor_terms = {t.lower() for t in domain_anchor_terms}
        self.sitemap_urls = sitemap_urls
        self.max_segment_entropy = max_segment_entropy
        self.max_path_depth = max_path_depth

    def _is_ancestor_hidden(self, node: Tag) -> bool:
        curr: Tag | None = node
        while curr is not None and isinstance(curr, Tag):
            if curr.get("hidden") is not None:
                return True
            if str(curr.get("aria-hidden", "")).lower() == "true":
                return True
            inline_style = str(curr.get("style", ""))
            if inline_style and HIDDEN_STYLE_REGEX.search(inline_style):
                return True
            curr = curr.parent if isinstance(curr.parent, Tag) else None
        return False

    def _is_suspicious_url(self, candidate_url: str) -> bool:
        parsed = urlparse(candidate_url)
        if parsed.netloc.lower() != self.allowed_domain:
            return True
        path = parsed.path or "/"
        if any(path.startswith(prefix) for prefix in TRAP_PATH_PREFIXES):
            return True

        segments = [seg for seg in path.split("/") if seg]
        if len(segments) > self.max_path_depth:
            return True

        for seg in segments:
            if len(seg) >= 20 and shannon_entropy(seg) > self.max_segment_entropy:
                return True

        if self.sitemap_urls is not None and candidate_url not in self.sitemap_urls:
            # Strict mode: when sitemap is authoritative, reject unlisted deep paths
            if len(segments) >= 3:
                return True
        return False

    def inspect_and_sanitize(self, fetched_url: str, raw_html: str) -> SanitizedDocument:
        soup = BeautifulSoup(raw_html, "html.parser")

        # 1. Reject pages marked noindex (AI Labyrinth decoys exclude search indexers)
        robots_meta = soup.find("meta", attrs={"name": re.compile(r"^robots$", re.I)})
        if robots_meta and "noindex" in str(robots_meta.get("content", "")).lower():
            return SanitizedDocument(
                canonical_url=fetched_url,
                is_safe_for_rag=False,
                quarantine_reason="meta_robots_noindex_detected",
                clean_text="",
                safe_internal_links=[],
            )

        # 2. Verify canonical link alignment
        canonical_tag = soup.find("link", rel=lambda r: r and "canonical" in r.lower())
        canonical_url = fetched_url
        if canonical_tag and canonical_tag.get("href"):
            resolved_canon = urljoin(fetched_url, str(canonical_tag["href"]))
            if urlparse(resolved_canon).netloc.lower() != self.allowed_domain:
                return SanitizedDocument(
                    canonical_url=resolved_canon,
                    is_safe_for_rag=False,
                    quarantine_reason="cross_domain_canonical_mismatch",
                    clean_text="",
                    safe_internal_links=[],
                )
            canonical_url = resolved_canon

        # 3. Extract ONLY visible, policy-compliant internal links BEFORE mutating DOM
        safe_links: list[str] = []
        seen_links: set[str] = set()
        for anchor in soup.find_all("a", href=True):
            rel_tokens = {t.lower() for t in (anchor.get("rel") or [])}
            if "nofollow" in rel_tokens or "sponsored" in rel_tokens:
                continue
            if not anchor.get_text(strip=True):
                continue
            if self._is_ancestor_hidden(anchor):
                continue

            abs_link = urljoin(fetched_url, str(anchor["href"])).split("#")[0]
            if abs_link not in seen_links and not self._is_suspicious_url(abs_link):
                seen_links.add(abs_link)
                safe_links.append(abs_link)

        # 4. Strip scripts, styles, nav chrome, and hidden subtrees prior to RAG chunking
        for junk in soup(["script", "style", "noscript", "svg", "template"]):
            junk.decompose()
        for tag in list(soup.find_all(True)):
            if isinstance(tag, Tag) and self._is_ancestor_hidden(tag):
                tag.decompose()

        clean_text = " ".join(soup.get_text(separator=" ").split())
        lowered = clean_text.lower()

        # 5. Domain Lexical Coherence Check (catches off-topic AI Labyrinth prose!)
        if self.domain_anchor_terms:
            matched_terms = sum(1 for term in self.domain_anchor_terms if term in lowered)
            if matched_terms == 0:
                return SanitizedDocument(
                    canonical_url=canonical_url,
                    is_safe_for_rag=False,
                    quarantine_reason="zero_domain_anchor_coherence_probable_labyrinth",
                    clean_text="",
                    safe_internal_links=[],
                )

        return SanitizedDocument(
            canonical_url=canonical_url,
            is_safe_for_rag=True,
            quarantine_reason=None,
            clean_text=clean_text,
            safe_internal_links=safe_links,
        )

6. Executive Governance Checklist for 2026 AI & RAG Teams

Whether you are operating a multi-agent customer research platform or refreshing a 50-million-chunk enterprise vector index, enforce these six architectural rules immediately:

  1. Retire Plain-Text User-Agent Identity on Partner Crawls: Stand up /.well-known/http-message-signatures-directory and sign authorized partner requests with RFC 9421 Ed25519 (tag="web-bot-auth", TTL under 300 seconds).
  2. Never Wire Autonomous Agents Directly to Uncapped Payment Wallets: Wrap every HTTP 402 / x402 handler inside a deterministic budget governor with domain allowlists, per-fetch price caps, redirect: 'manual', and time-bucketed idempotency keys.
  3. Stop Blind BFS Link Spidering for RAG: Replace recursive HTML link crawling with SERP-grounded URL discovery (@brightdata/mcp search_engine / SERP API) and authoritative sitemap.xml ingestion so crawlers never step into AI Labyrinth traps.
  4. Enforce Pre-Embedding Quarantine Gates: Reject noindex documents, hidden DOM subtrees, high-entropy path slugs, and zero-domain-coherence articles before calling embedding APIs or writing to Qdrant / Pinecone.
  5. Separate Licensed TDM Feeds from Public Factual Grounding: Align your domain router with your legal counsel’s EU AI Act web scraping compliance matrix, logging source URL, retrieval channel (licensed_402_settled vs. brightdata_unlocker_markdown), and timestamp on every vector payload.
  6. Standardize Agent Tooling on Clean Markdown: Route public-web document fetches through @brightdata/mcp or Bright Data Web Unlocker with data_format: "markdown" to slash LLM context costs by up to 90%.
Recommended RAG PlaneStart Free Bright Data Trial — MCP & Web Unlockervia bright-dataProduction RAG StoreExplore Qdrant Cloud Vector DBvia qdrant

P

ProxyOps Engineering

Independent B2B infrastructure reviews written by software engineers. Every provider is benchmarked for IP purity, response latency, and anti-bot mitigation bypass.