agentpayments-python 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ # Adapters are optional: each import succeeds only if its framework is
2
+ # installed. ImportError (missing framework) is expected; any other exception
3
+ # is a real bug and should propagate.
4
+
5
+ # x402 helpers are always available (no framework dependency).
6
+ from .x402 import build_payment_requirements, enrich_402_body, payment_required_header
7
+
8
+ __all__ = [
9
+ "build_payment_requirements",
10
+ "enrich_402_body",
11
+ "payment_required_header",
12
+ ]
13
+
14
+ try:
15
+ from .django_adapter import GateMiddleware, challenge_verify
16
+ __all__ += ["GateMiddleware", "challenge_verify"]
17
+ except ImportError:
18
+ pass
19
+
20
+ try:
21
+ from .fastapi_adapter import AgentPaymentsASGIMiddleware, challenge_verify_endpoint as fastapi_challenge_verify
22
+ __all__ += ["AgentPaymentsASGIMiddleware", "fastapi_challenge_verify"]
23
+ except ImportError:
24
+ pass
25
+
26
+ try:
27
+ from .flask_adapter import register_agentpayments
28
+ __all__ += ["register_agentpayments"]
29
+ except ImportError:
30
+ pass
@@ -0,0 +1,151 @@
1
+ import hmac
2
+ import json
3
+ import re
4
+ import secrets as _secrets
5
+ import threading
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from .crypto import client_id_for_ip, hmac_sign, sha256_hex
10
+
11
+ _constants = json.loads((Path(__file__).resolve().parent / "constants.json").read_text())
12
+ POW_DIFFICULTY = _constants["POW_DIFFICULTY"]
13
+ MAX_POW_LENGTH = _constants["MAX_POW_LENGTH"]
14
+ NONCE_TTL_MS = _constants["NONCE_TTL_MS"]
15
+
16
+ # Canvas fingerprints are a base64 slice of a data URL. Reject anything that
17
+ # isn't base64 or is degenerate (e.g. a single repeated character).
18
+ _FP_RE = re.compile(r"^[A-Za-z0-9+/]{10,}$")
19
+ _POW_RE = re.compile(r"^\d{1,20}$")
20
+
21
+
22
+ def make_nonce(secret: str, client_ip: str) -> str:
23
+ """Nonce format: <ts>.<rand>.<sig>, signature bound to the client IP."""
24
+ ts = str(int(time.time() * 1000))
25
+ rand = _secrets.token_hex(8)
26
+ client_id = client_id_for_ip(client_ip, secret)
27
+ sig = hmac_sign(f"nonce:{ts}:{rand}:{client_id}", secret)
28
+ return f"{ts}.{rand}.{sig}"
29
+
30
+
31
+ def _is_plausible_fingerprint(fp: str) -> bool:
32
+ return bool(_FP_RE.match(fp)) and len(set(fp)) >= 4
33
+
34
+
35
+ def _verify_pow(nonce: str, pow_value: str, difficulty: int) -> bool:
36
+ """Proof-of-work: sha256(f"{nonce}:{pow}") must start with `difficulty`
37
+ zero hex chars. Verification is one hash; solving costs ~16^difficulty."""
38
+ if not _POW_RE.match(pow_value):
39
+ return False
40
+ return sha256_hex(f"{nonce}:{pow_value}").startswith("0" * difficulty)
41
+
42
+
43
+ class _ConsumedNonces:
44
+ """Single-use nonce tracking (best-effort, in-memory, thread-safe)."""
45
+
46
+ def __init__(self, ttl_ms: int = NONCE_TTL_MS, max_size: int = 10000):
47
+ self.ttl = ttl_ms / 1000.0
48
+ self.max_size = max_size
49
+ self._seen: dict[str, float] = {}
50
+ self._lock = threading.Lock()
51
+
52
+ def consume(self, sig: str) -> bool:
53
+ """Returns True if the nonce was fresh (and marks it consumed)."""
54
+ now = time.time()
55
+ with self._lock:
56
+ exp = self._seen.get(sig)
57
+ if exp is not None and exp > now:
58
+ return False
59
+ if len(self._seen) >= self.max_size:
60
+ expired = [k for k, v in self._seen.items() if v <= now]
61
+ for k in expired:
62
+ del self._seen[k]
63
+ if len(self._seen) >= self.max_size:
64
+ del self._seen[next(iter(self._seen))]
65
+ self._seen[sig] = now + self.ttl
66
+ return True
67
+
68
+
69
+ _consumed_nonces = _ConsumedNonces()
70
+
71
+
72
+ def validate_challenge_submission(
73
+ nonce: str,
74
+ fp: str,
75
+ pow_value: str,
76
+ secret: str,
77
+ client_ip: str,
78
+ difficulty: int = POW_DIFFICULTY,
79
+ ) -> bool:
80
+ """Full server-side validation of a challenge form submission.
81
+
82
+ Checks: nonce structure and expiry, IP-bound HMAC signature, plausible
83
+ fingerprint, proof-of-work, and single use.
84
+ """
85
+ parts = nonce.split(".")
86
+ if len(parts) != 3 or not _is_plausible_fingerprint(fp):
87
+ return False
88
+ nonce_ts, nonce_rand, nonce_sig = parts
89
+ try:
90
+ ts = int(nonce_ts)
91
+ except ValueError:
92
+ return False
93
+ if int(time.time() * 1000) - ts > NONCE_TTL_MS:
94
+ return False
95
+ client_id = client_id_for_ip(client_ip, secret)
96
+ expected = hmac_sign(f"nonce:{nonce_ts}:{nonce_rand}:{client_id}", secret)
97
+ if not hmac.compare_digest(nonce_sig, expected):
98
+ return False
99
+ if not _verify_pow(nonce, pow_value, difficulty):
100
+ return False
101
+ return _consumed_nonces.consume(nonce_sig)
102
+
103
+
104
+ def challenge_html(return_to: str, nonce: str, pow_difficulty: int = POW_DIFFICULTY) -> str:
105
+ # Reject protocol-relative URLs (e.g. //attacker.com) which start with '/'
106
+ # but are treated as external by browsers.
107
+ safe_path = return_to if (return_to.startswith("/") and not return_to.startswith("//")) else "/"
108
+ nonce_json = json.dumps(nonce)
109
+ safe_path_json = json.dumps(safe_path)
110
+ target_json = json.dumps("0" * pow_difficulty)
111
+ return (
112
+ "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'>"
113
+ "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
114
+ "<title>Verifying your access...</title>"
115
+ "<style>body{font-family:system-ui,sans-serif;display:flex;justify-content:center;"
116
+ "align-items:center;min-height:100vh;margin:0;background:#fafafa;color:#333}"
117
+ "main{text-align:center;padding:2rem}"
118
+ ".spinner{width:40px;height:40px;border:4px solid #e0e0e0;border-top-color:#333;"
119
+ "border-radius:50%;animation:spin .8s linear infinite;margin:1rem auto}"
120
+ "@keyframes spin{to{transform:rotate(360deg)}}</style>"
121
+ "</head><body>"
122
+ "<main role='status' aria-live='polite'>"
123
+ "<div class='spinner' aria-hidden='true'></div>"
124
+ "<p>Verifying your access&hellip;</p>"
125
+ "<noscript><p><strong>JavaScript is required to verify your access. "
126
+ "Please enable JavaScript and reload this page.</strong></p></noscript>"
127
+ "</main>"
128
+ "<script>(function(){"
129
+ "if(navigator.webdriver)return;"
130
+ "if(!window.crypto||!window.crypto.subtle)return;"
131
+ "var c=document.createElement('canvas');c.width=200;c.height=50;"
132
+ "var ctx=c.getContext('2d');if(!ctx)return;"
133
+ "ctx.font='18px Arial';ctx.fillStyle='#1a1a2e';ctx.fillText('verify',10,30);"
134
+ "var data=c.toDataURL();if(!data||data.length<100)return;"
135
+ "if(typeof window.innerWidth==='undefined'||window.innerWidth===0)return;"
136
+ f"var nonce={nonce_json};var target={target_json};"
137
+ "var enc=new TextEncoder();var i=0;"
138
+ "function submit(pow){"
139
+ "var form=document.createElement('form');form.method='POST';form.action='/__challenge/verify';"
140
+ f"var fields={{nonce:nonce,return_to:{safe_path_json},fp:data.slice(22,86),pow:pow}};"
141
+ "for(var k in fields){var input=document.createElement('input');"
142
+ "input.type='hidden';input.name=k;input.value=fields[k];form.appendChild(input);}"
143
+ "document.body.appendChild(form);form.submit();}"
144
+ "function mine(){window.crypto.subtle.digest('SHA-256',enc.encode(nonce+':'+i)).then(function(buf){"
145
+ "var b=new Uint8Array(buf);var h='';"
146
+ "for(var j=0;j<4;j++)h+=(b[j]<16?'0':'')+b[j].toString(16);"
147
+ "if(h.slice(0,target.length)===target)return submit(String(i));"
148
+ "i++;mine();});}"
149
+ "mine();})();</script>"
150
+ "</body></html>"
151
+ )
@@ -0,0 +1,27 @@
1
+ {
2
+ "USDC_MINT_DEVNET": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
3
+ "USDC_MINT_MAINNET": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
4
+ "RPC_DEVNET": "https://api.devnet.solana.com",
5
+ "RPC_MAINNET": "https://api.mainnet-beta.solana.com",
6
+ "MEMO_PROGRAM": "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr",
7
+ "MIN_PAYMENT": 0.01,
8
+ "COOKIE_NAME": "__agp_verified",
9
+ "COOKIE_MAX_AGE": 86400,
10
+ "KEY_PREFIX": "ag_",
11
+ "POW_DIFFICULTY": 4,
12
+ "MAX_POW_LENGTH": 20,
13
+ "NONCE_TTL_MS": 300000,
14
+ "MAX_KEY_LENGTH": 64,
15
+ "MAX_NONCE_LENGTH": 128,
16
+ "MAX_RETURN_TO_LENGTH": 2048,
17
+ "MAX_FP_LENGTH": 128,
18
+ "NEGATIVE_CACHE_TTL_MS": 30000,
19
+ "MAX_TRANSACTIONS_PER_VERIFY": 20,
20
+ "AGENT_KEY_RATE_LIMIT_MAX": 10,
21
+ "USDC_DECIMALS": 6,
22
+ "X402_VERSION": 1,
23
+ "SOLANA_CHAIN_ID_MAINNET": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
24
+ "SOLANA_CHAIN_ID_DEVNET": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
25
+ "PLATFORM_API_URL": "https://api.agentpayments.dev",
26
+ "HOSTED_KEY_PREFIX": "agp_"
27
+ }
@@ -0,0 +1,37 @@
1
+ import hmac
2
+ import json
3
+ import time
4
+ from pathlib import Path
5
+
6
+ from .crypto import client_id_for_ip, hmac_sign
7
+
8
+ _constants = json.loads((Path(__file__).resolve().parent / "constants.json").read_text())
9
+ COOKIE_NAME = _constants["COOKIE_NAME"]
10
+ COOKIE_MAX_AGE = _constants["COOKIE_MAX_AGE"]
11
+
12
+
13
+ def make_cookie(secret: str, client_ip: str) -> str:
14
+ """Cookie format: <ts>.<sig>, signature bound to the client IP that
15
+ solved the challenge, so a captured cookie is useless from another IP."""
16
+ now_ms = str(int(time.time() * 1000))
17
+ client_id = client_id_for_ip(client_ip, secret)
18
+ return f"{now_ms}.{hmac_sign(f'cookie:{now_ms}:{client_id}', secret)}"
19
+
20
+
21
+ def is_valid_cookie_value(cookie_value: str, secret: str, client_ip: str) -> bool:
22
+ if not cookie_value:
23
+ return False
24
+ i = cookie_value.find(".")
25
+ if i == -1:
26
+ return False
27
+ ts_str = cookie_value[:i]
28
+ sig = cookie_value[i + 1:]
29
+ try:
30
+ ts = int(ts_str)
31
+ except ValueError:
32
+ return False
33
+ if int(time.time() * 1000) - ts > COOKIE_MAX_AGE * 1000:
34
+ return False
35
+ client_id = client_id_for_ip(client_ip, secret)
36
+ expected = hmac_sign(f"cookie:{ts_str}:{client_id}", secret)
37
+ return hmac.compare_digest(sig, expected)
@@ -0,0 +1,74 @@
1
+ """
2
+ Verified search crawler detection.
3
+
4
+ UA heuristic + reverse/forward DNS (Google's documented method).
5
+ Results are cached for 1 hour to avoid repeated DNS lookups.
6
+ """
7
+ import re
8
+ import socket
9
+ import time
10
+ import threading
11
+ from typing import Optional
12
+
13
+ # (ua_pattern, expected_ptr_suffix)
14
+ # suffix=None means UA match only — not recommended, included for completeness.
15
+ CRAWLERS = [
16
+ (re.compile(r'googlebot', re.I), '.googlebot.com'),
17
+ (re.compile(r'google-inspectiontool', re.I), '.google.com'),
18
+ (re.compile(r'bingbot', re.I), '.search.msn.com'),
19
+ (re.compile(r'slurp', re.I), '.crawl.yahoo.net'),
20
+ (re.compile(r'duckduckbot', re.I), '.duckduckgo.com'),
21
+ (re.compile(r'baiduspider', re.I), '.crawl.baidu.com'),
22
+ (re.compile(r'yandexbot', re.I), '.yandex.com'),
23
+ (re.compile(r'applebot', re.I), '.applebot.apple.com'),
24
+ ]
25
+
26
+ CRAWLER_CACHE_TTL = 3600 # 1 hour
27
+ _cache: dict[str, tuple[bool, float]] = {} # ip -> (verified, expiry)
28
+ _cache_lock = threading.Lock()
29
+
30
+
31
+ def is_verified_crawler(ip: str, user_agent: str) -> bool:
32
+ """
33
+ Return True if the request is from a verified search crawler.
34
+
35
+ Verification is: UA matches a known crawler pattern AND the IP's reverse-DNS
36
+ hostname ends with the crawler's published suffix AND a forward DNS lookup of
37
+ that hostname resolves back to the same IP.
38
+
39
+ Results are cached for 1 hour to limit DNS round-trips. Blocking I/O — for
40
+ FastAPI/async use, call this in a thread-pool executor.
41
+ """
42
+ if not user_agent or not ip or ip == 'unknown':
43
+ return False
44
+
45
+ match = next((c for c in CRAWLERS if c[0].search(user_agent)), None)
46
+ if match is None:
47
+ return False
48
+
49
+ suffix = match[1]
50
+
51
+ with _cache_lock:
52
+ entry = _cache.get(ip)
53
+ if entry is not None and entry[1] > time.time():
54
+ return entry[0]
55
+
56
+ verified = _verify_dns(ip, suffix)
57
+
58
+ with _cache_lock:
59
+ _cache[ip] = (verified, time.time() + CRAWLER_CACHE_TTL)
60
+
61
+ return verified
62
+
63
+
64
+ def _verify_dns(ip: str, suffix: str) -> bool:
65
+ try:
66
+ hostname, _, _ = socket.gethostbyaddr(ip)
67
+ if not hostname.endswith(suffix):
68
+ return False
69
+ # Forward verify: resolve hostname back and confirm it includes the original IP.
70
+ results = socket.getaddrinfo(hostname, None)
71
+ resolved_ips = {r[4][0] for r in results}
72
+ return ip in resolved_ips
73
+ except Exception:
74
+ return False
@@ -0,0 +1,43 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import uuid
5
+ from pathlib import Path
6
+
7
+ _constants = json.loads((Path(__file__).resolve().parent / "constants.json").read_text())
8
+ KEY_PREFIX = _constants["KEY_PREFIX"]
9
+ MAX_KEY_LENGTH = _constants["MAX_KEY_LENGTH"]
10
+
11
+
12
+ def hmac_sign(data: str, secret: str) -> str:
13
+ return hmac.new(secret.encode(), data.encode(), hashlib.sha256).hexdigest()
14
+
15
+
16
+ def sha256_hex(data: str) -> str:
17
+ return hashlib.sha256(data.encode()).hexdigest()
18
+
19
+
20
+ def client_id_for_ip(ip: str, secret: str) -> str:
21
+ """Short HMAC of the client IP. Used to bind nonces and cookies to the
22
+ client that solved the challenge, so a captured cookie is useless from
23
+ another IP."""
24
+ return hmac_sign(f"client:{ip}", secret)[:16]
25
+
26
+
27
+ def generate_agent_key(secret: str) -> str:
28
+ random_part = uuid.uuid4().hex[:16]
29
+ sig = hmac_sign(random_part, secret)
30
+ return f"{KEY_PREFIX}{random_part}_{sig[:16]}"
31
+
32
+
33
+ def is_valid_agent_key(key: str, secret: str) -> bool:
34
+ if not key or len(key) > MAX_KEY_LENGTH or not key.startswith(KEY_PREFIX):
35
+ return False
36
+ rest = key[len(KEY_PREFIX):]
37
+ i = rest.find("_")
38
+ if i == -1:
39
+ return False
40
+ random_part = rest[:i]
41
+ sig = rest[i + 1:]
42
+ expected = hmac_sign(random_part, secret)
43
+ return hmac.compare_digest(sig, expected[:16])
@@ -0,0 +1,28 @@
1
+ import re as _re
2
+
3
+ def is_public_path(pathname: str) -> bool:
4
+ return pathname == "/robots.txt" or pathname.startswith("/.well-known/")
5
+
6
+
7
+ # Sec-Fetch-* headers were introduced in Chrome 76 (2019) and Firefox 90 (2021).
8
+ # Older browsers, some mobile WebViews, and certain proxies strip them.
9
+ # This UA pattern matches common desktop/mobile browsers as a fallback so they
10
+ # get a challenge rather than a 402.
11
+ _BROWSER_UA_RE = _re.compile(
12
+ r"(Chrome|Chromium|Firefox|Safari|Edg|OPR|Opera|SamsungBrowser|UCBrowser|Mobile Safari)"
13
+ r"(?!/.*bot)", # exclude UA strings that contain the browser name followed by /.*bot
14
+ _re.IGNORECASE,
15
+ )
16
+ # Explicit bot/crawler suffixes that should NOT match even if they spoof a browser UA.
17
+ _BOT_UA_RE = _re.compile(r"bot|crawl|spider|slurp|mediapartners|adsbot", _re.IGNORECASE)
18
+
19
+
20
+ def is_browser_from_headers(headers: dict) -> bool:
21
+ # Primary signal: Fetch metadata headers (Chrome 76+, Firefox 90+).
22
+ if headers.get("sec-fetch-mode") or headers.get("sec-fetch-dest"):
23
+ return True
24
+ # Fallback: UA heuristic for older browsers that don't send Sec-Fetch-*.
25
+ ua = headers.get("user-agent") or headers.get("User-Agent") or ""
26
+ if ua and not _BOT_UA_RE.search(ua) and _BROWSER_UA_RE.search(ua):
27
+ return True
28
+ return False
@@ -0,0 +1,232 @@
1
+ import logging
2
+
3
+ from django.conf import settings
4
+ from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
5
+ from django.views.decorators.csrf import csrf_exempt
6
+ from django.views.decorators.http import require_POST
7
+
8
+ from .challenge import POW_DIFFICULTY, challenge_html, make_nonce, validate_challenge_submission
9
+ from .cookies import COOKIE_MAX_AGE, COOKIE_NAME, is_valid_cookie_value, make_cookie
10
+ from .crypto import generate_agent_key, is_valid_agent_key
11
+ from .detection import is_browser_from_headers, is_public_path
12
+ from .ratelimit import _challenge_limiter, _agent_key_limiter, _challenge_issue_limiter
13
+ from .crawler import is_verified_crawler
14
+ from .solana import MIN_PAYMENT, RPC_DEVNET, RPC_MAINNET, USDC_MINT_DEVNET, USDC_MINT_MAINNET, is_valid_solana_address, verify_payment_on_chain
15
+ from .x402 import build_payment_requirements, enrich_402_body, payment_required_header
16
+ from .platform_client import HOSTED_KEY_PREFIX, PlatformClient, is_valid_hosted_key
17
+
18
+ import json as _json
19
+ from pathlib import Path as _Path
20
+ _constants = _json.loads((_Path(__file__).resolve().parent / "constants.json").read_text())
21
+ MAX_NONCE_LENGTH = _constants["MAX_NONCE_LENGTH"]
22
+ MAX_RETURN_TO_LENGTH = _constants["MAX_RETURN_TO_LENGTH"]
23
+ MAX_FP_LENGTH = _constants["MAX_FP_LENGTH"]
24
+ MAX_POW_LENGTH = _constants["MAX_POW_LENGTH"]
25
+
26
+ logger = logging.getLogger("agentpayments")
27
+
28
+
29
+ def _payment_required_response(body: dict, *, wallet_address: str, mint: str, min_payment: float, debug: bool, agent_key: str = "", resource: str = "") -> JsonResponse:
30
+ """Return a 402 JsonResponse enriched with x402-standard fields and header."""
31
+ pay_req = build_payment_requirements(wallet_address=wallet_address, mint=mint, min_payment=min_payment, debug=debug, agent_key=agent_key, resource=resource)
32
+ resp = JsonResponse(enrich_402_body(body, pay_req), status=402, json_dumps_params={"indent": 2})
33
+ resp["X-PAYMENT-REQUIRED"] = payment_required_header(pay_req)
34
+ return resp
35
+
36
+
37
+ def _client_ip(request):
38
+ return request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")[0].strip() or request.META.get("REMOTE_ADDR", "unknown")
39
+
40
+
41
+ class GateMiddleware:
42
+ def __init__(self, get_response):
43
+ self.get_response = get_response
44
+
45
+ # Resolve and validate config once at startup, not per-request.
46
+ secret = settings.CHALLENGE_SECRET
47
+ if secret == "default-secret-change-me":
48
+ if settings.DEBUG:
49
+ logger.warning("Using default CHALLENGE_SECRET. Set a strong secret before deploying to production.")
50
+ else:
51
+ raise RuntimeError("CHALLENGE_SECRET is set to the insecure default. Set a strong, unique secret for production.")
52
+ wallet_address = getattr(settings, "HOME_WALLET_ADDRESS", None)
53
+ if wallet_address and not is_valid_solana_address(wallet_address):
54
+ raise ValueError(f"HOME_WALLET_ADDRESS '{wallet_address}' is not a valid Solana public key (expected 32-44 base58 characters).")
55
+ debug = settings.DEBUG
56
+ raw_rpc = getattr(settings, "SOLANA_RPC_URL", None) or (RPC_DEVNET if debug else RPC_MAINNET)
57
+ rpc_url = raw_rpc if isinstance(raw_rpc, list) else [raw_rpc]
58
+ self.require_https = getattr(settings, "AGENTPAYMENTS_REQUIRE_HTTPS", not debug)
59
+ # Hosted key-issuance mode. Set AGENTPAYMENTS_API_KEY in settings.py.
60
+ # When set, keys are issued via the platform (metered) and carry the agp_ prefix.
61
+ api_key = getattr(settings, "AGENTPAYMENTS_API_KEY", None)
62
+ platform_url = getattr(settings, "AGENTPAYMENTS_PLATFORM_URL", None)
63
+ self._platform_client = PlatformClient(api_key, platform_url) if api_key else None
64
+ usdc_mint = getattr(settings, "USDC_MINT", None) or (USDC_MINT_DEVNET if debug else USDC_MINT_MAINNET)
65
+
66
+ self.secret = secret
67
+ self.wallet_address = wallet_address
68
+ self.debug = debug
69
+ self.rpc_url = rpc_url
70
+ self.usdc_mint = usdc_mint
71
+ self.network = "devnet" if debug else "mainnet-beta"
72
+ self.pow_difficulty = getattr(settings, "POW_DIFFICULTY", POW_DIFFICULTY)
73
+ self.verify_crawlers = getattr(settings, "AGENTPAYMENTS_VERIFY_CRAWLERS", True)
74
+ # Optional grant store for durable paid-key persistence. Set
75
+ # AGENTPAYMENTS_GRANT_STORE to a GrantStore instance in settings.py.
76
+ self.grant_store = getattr(settings, "AGENTPAYMENTS_GRANT_STORE", None)
77
+
78
+ def __call__(self, request):
79
+ secret = self.secret
80
+ wallet_address = self.wallet_address
81
+ network = self.network
82
+
83
+ pathname = request.path
84
+ if is_public_path(pathname):
85
+ return self.get_response(request)
86
+
87
+ if pathname == "/__challenge/verify" and request.method == "POST":
88
+ return self.get_response(request)
89
+
90
+ # Reject plaintext HTTP in production. Behind a reverse proxy, Django
91
+ # uses X-Forwarded-Proto via SECURE_PROXY_SSL_HEADER in settings.
92
+ if self.require_https and not request.is_secure():
93
+ return JsonResponse({"error": "https_required", "message": "This service requires a secure HTTPS connection."}, status=400)
94
+
95
+ # Verified search crawlers bypass the gate entirely.
96
+ if self.verify_crawlers:
97
+ client_ip_early = _client_ip(request)
98
+ ua = request.META.get("HTTP_USER_AGENT", "")
99
+ if is_verified_crawler(client_ip_early, ua):
100
+ return self.get_response(request)
101
+
102
+ headers = {
103
+ "sec-fetch-mode": request.META.get("HTTP_SEC_FETCH_MODE"),
104
+ "sec-fetch-dest": request.META.get("HTTP_SEC_FETCH_DEST"),
105
+ }
106
+ if not is_browser_from_headers(headers):
107
+ agent_key = request.META.get("HTTP_X_AGENT_KEY")
108
+ if not agent_key:
109
+ # Hosted mode: issue metered platform key (agp_).
110
+ # Local mode: generate self-signed key (ag_).
111
+ if self._platform_client:
112
+ try:
113
+ new_key = self._platform_client.issue_key()
114
+ except Exception as exc:
115
+ logger.warning("Platform key issuance failed, falling back to local key: %s", exc)
116
+ new_key = generate_agent_key(secret)
117
+ else:
118
+ new_key = generate_agent_key(secret)
119
+ return _payment_required_response(
120
+ {
121
+ "error": "payment_required",
122
+ "message": "Access requires a paid API key. A key has been generated for you below. Send a USDC payment on Solana with this key as the memo to activate it, then retry your request with the X-Agent-Key header.",
123
+ "your_key": new_key,
124
+ "payment": {
125
+ "chain": "solana",
126
+ "network": network,
127
+ "token": "USDC",
128
+ "amount": str(MIN_PAYMENT),
129
+ "wallet_address": wallet_address,
130
+ "memo": new_key,
131
+ "instructions": f'Send {MIN_PAYMENT} USDC on Solana {network} to {wallet_address} with memo "{new_key}". Then include the header X-Agent-Key: {new_key} on all subsequent requests.',
132
+ },
133
+ },
134
+ wallet_address=wallet_address, mint=self.usdc_mint, min_payment=MIN_PAYMENT,
135
+ debug=self.debug, agent_key=new_key, resource=pathname,
136
+ )
137
+
138
+ # Validate the key. Platform-issued (agp_) use verificationSecret;
139
+ # local keys (ag_) use challengeSecret.
140
+ if agent_key.startswith(HOSTED_KEY_PREFIX):
141
+ if not self._platform_client:
142
+ return JsonResponse({"error": "forbidden", "message": "Platform-issued keys (agp_) require AGENTPAYMENTS_API_KEY to be configured."}, status=403)
143
+ try:
144
+ ver_sec = self._platform_client.verification_secret
145
+ except Exception as exc:
146
+ logger.error("Failed to fetch verificationSecret from platform: %s", exc)
147
+ return JsonResponse({"error": "service_unavailable", "message": "Key verification temporarily unavailable."}, status=503)
148
+ if not is_valid_hosted_key(agent_key, ver_sec):
149
+ return JsonResponse({"error": "forbidden", "message": "Invalid API key."}, status=403)
150
+ elif not is_valid_agent_key(agent_key, secret):
151
+ return JsonResponse({"error": "forbidden", "message": "Invalid API key. Keys must be issued by this server."}, status=403)
152
+
153
+ if not _agent_key_limiter.check(_client_ip(request)):
154
+ return JsonResponse({"error": "rate_limited", "message": "Too many payment verification requests. Please wait and try again."}, status=429)
155
+
156
+ if not wallet_address:
157
+ return JsonResponse({"error": "server_error", "message": "Payment verification unavailable."}, status=500)
158
+
159
+ # Durable grant check — bypasses RPC scan entirely for known-paid keys.
160
+ if self.grant_store and self.grant_store.has(agent_key):
161
+ return self.get_response(request)
162
+
163
+ paid = verify_payment_on_chain(agent_key, wallet_address, self.rpc_url, self.usdc_mint)
164
+ if paid and self.grant_store:
165
+ self.grant_store.add(agent_key)
166
+ if not paid:
167
+ return _payment_required_response(
168
+ {
169
+ "error": "payment_required",
170
+ "message": "Key is valid but payment has not been verified on-chain yet.",
171
+ "your_key": agent_key,
172
+ "payment": {
173
+ "chain": "solana",
174
+ "network": network,
175
+ "token": "USDC",
176
+ "amount": str(MIN_PAYMENT),
177
+ "wallet_address": wallet_address,
178
+ "memo": agent_key,
179
+ },
180
+ },
181
+ wallet_address=wallet_address, mint=self.usdc_mint, min_payment=MIN_PAYMENT,
182
+ debug=self.debug, agent_key=agent_key, resource=pathname,
183
+ )
184
+
185
+ return self.get_response(request)
186
+
187
+ client_ip = _client_ip(request)
188
+ cookie_val = request.COOKIES.get(COOKIE_NAME, "")
189
+ if is_valid_cookie_value(cookie_val, secret, client_ip):
190
+ return self.get_response(request)
191
+
192
+ # Rate-limit challenge page issuance to prevent unlimited nonce harvesting.
193
+ if not _challenge_issue_limiter.check(client_ip):
194
+ return JsonResponse({"error": "rate_limited", "message": "Too many requests. Please try again later."}, status=429)
195
+
196
+ nonce = make_nonce(secret, client_ip)
197
+ resp = HttpResponse(challenge_html(request.get_full_path(), nonce, self.pow_difficulty), content_type="text/html")
198
+ resp["Cache-Control"] = "no-store"
199
+ resp["X-Frame-Options"] = "DENY"
200
+ resp["Content-Security-Policy"] = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; form-action 'self'"
201
+ return resp
202
+
203
+
204
+ @csrf_exempt
205
+ @require_POST
206
+ def challenge_verify(request):
207
+ client_ip = _client_ip(request)
208
+ if not _challenge_limiter.check(client_ip):
209
+ return JsonResponse({"error": "rate_limited", "message": "Too many verification attempts. Please wait and try again."}, status=429)
210
+ secret = settings.CHALLENGE_SECRET
211
+ nonce = request.POST.get("nonce", "")[:MAX_NONCE_LENGTH]
212
+ return_to = request.POST.get("return_to", "/")[:MAX_RETURN_TO_LENGTH]
213
+ fp = request.POST.get("fp", "")[:MAX_FP_LENGTH]
214
+ pow_value = request.POST.get("pow", "")[:MAX_POW_LENGTH]
215
+
216
+ difficulty = getattr(settings, "POW_DIFFICULTY", POW_DIFFICULTY)
217
+ if not validate_challenge_submission(nonce, fp, pow_value, secret, client_ip, difficulty):
218
+ return JsonResponse({"error": "forbidden", "message": "Challenge verification failed."}, status=403)
219
+
220
+ safe_path = return_to if (return_to.startswith("/") and not return_to.startswith("//")) else "/"
221
+ response = HttpResponseRedirect(safe_path)
222
+ secure_cookie = request.is_secure()
223
+ response.set_cookie(
224
+ COOKIE_NAME,
225
+ make_cookie(secret, client_ip),
226
+ max_age=COOKIE_MAX_AGE,
227
+ path="/",
228
+ httponly=True,
229
+ secure=secure_cookie,
230
+ samesite="Lax",
231
+ )
232
+ return response