agentpayments-python 0.1.0__tar.gz
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.
- agentpayments_python-0.1.0/LICENSE +21 -0
- agentpayments_python-0.1.0/PKG-INFO +152 -0
- agentpayments_python-0.1.0/README.md +115 -0
- agentpayments_python-0.1.0/agentpayments_python/__init__.py +30 -0
- agentpayments_python-0.1.0/agentpayments_python/challenge.py +151 -0
- agentpayments_python-0.1.0/agentpayments_python/constants.json +27 -0
- agentpayments_python-0.1.0/agentpayments_python/cookies.py +37 -0
- agentpayments_python-0.1.0/agentpayments_python/crawler.py +74 -0
- agentpayments_python-0.1.0/agentpayments_python/crypto.py +43 -0
- agentpayments_python-0.1.0/agentpayments_python/detection.py +28 -0
- agentpayments_python-0.1.0/agentpayments_python/django_adapter.py +232 -0
- agentpayments_python-0.1.0/agentpayments_python/fastapi_adapter.py +198 -0
- agentpayments_python-0.1.0/agentpayments_python/flask_adapter.py +167 -0
- agentpayments_python-0.1.0/agentpayments_python/grant_store.py +86 -0
- agentpayments_python-0.1.0/agentpayments_python/platform_client.py +117 -0
- agentpayments_python-0.1.0/agentpayments_python/ratelimit.py +43 -0
- agentpayments_python-0.1.0/agentpayments_python/solana.py +196 -0
- agentpayments_python-0.1.0/agentpayments_python/x402.py +84 -0
- agentpayments_python-0.1.0/agentpayments_python.egg-info/PKG-INFO +152 -0
- agentpayments_python-0.1.0/agentpayments_python.egg-info/SOURCES.txt +24 -0
- agentpayments_python-0.1.0/agentpayments_python.egg-info/dependency_links.txt +1 -0
- agentpayments_python-0.1.0/agentpayments_python.egg-info/requires.txt +17 -0
- agentpayments_python-0.1.0/agentpayments_python.egg-info/top_level.txt +1 -0
- agentpayments_python-0.1.0/pyproject.toml +48 -0
- agentpayments_python-0.1.0/setup.cfg +4 -0
- agentpayments_python-0.1.0/tests/test_core.py +767 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Adam Brzosko
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentpayments-python
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: AgentPayments gate for Python web frameworks — charge AI agents USDC on Solana before they can access your API
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/adambrzosko/AgentPayments
|
|
7
|
+
Project-URL: Documentation, https://github.com/adambrzosko/AgentPayments/tree/main/sdk/python
|
|
8
|
+
Project-URL: Repository, https://github.com/adambrzosko/AgentPayments
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/adambrzosko/AgentPayments/issues
|
|
10
|
+
Keywords: agentpayments,ai-agents,solana,usdc,payments,middleware,x402
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: requests>=2.31
|
|
24
|
+
Provides-Extra: django
|
|
25
|
+
Requires-Dist: Django>=5.0; extra == "django"
|
|
26
|
+
Provides-Extra: fastapi
|
|
27
|
+
Requires-Dist: fastapi>=0.110; extra == "fastapi"
|
|
28
|
+
Requires-Dist: starlette>=0.37; extra == "fastapi"
|
|
29
|
+
Provides-Extra: flask
|
|
30
|
+
Requires-Dist: flask>=3.0; extra == "flask"
|
|
31
|
+
Provides-Extra: all
|
|
32
|
+
Requires-Dist: Django>=5.0; extra == "all"
|
|
33
|
+
Requires-Dist: fastapi>=0.110; extra == "all"
|
|
34
|
+
Requires-Dist: starlette>=0.37; extra == "all"
|
|
35
|
+
Requires-Dist: flask>=3.0; extra == "all"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# agentpayments-python
|
|
39
|
+
|
|
40
|
+
Python adapters for the AgentPayments gate. Supports Django, FastAPI/Starlette, and Flask.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install agentpayments-python
|
|
46
|
+
# or, in this monorepo:
|
|
47
|
+
# pip install -e sdk/python
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Django
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
# settings.py
|
|
54
|
+
MIDDLEWARE = [
|
|
55
|
+
"django.middleware.security.SecurityMiddleware",
|
|
56
|
+
"agentpayments_python.django_adapter.GateMiddleware",
|
|
57
|
+
# ... other middleware
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
# Required settings
|
|
61
|
+
CHALLENGE_SECRET = os.environ["CHALLENGE_SECRET"]
|
|
62
|
+
HOME_WALLET_ADDRESS = os.environ["HOME_WALLET_ADDRESS"]
|
|
63
|
+
|
|
64
|
+
# Optional settings
|
|
65
|
+
SOLANA_RPC_URL = os.environ.get("SOLANA_RPC_URL")
|
|
66
|
+
USDC_MINT = os.environ.get("USDC_MINT")
|
|
67
|
+
DEBUG = True # True = devnet, False = mainnet
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## FastAPI
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from fastapi import FastAPI, Request
|
|
74
|
+
from agentpayments_python.fastapi_adapter import (
|
|
75
|
+
AgentPaymentsASGIMiddleware,
|
|
76
|
+
challenge_verify_endpoint,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
app = FastAPI()
|
|
80
|
+
|
|
81
|
+
app.add_middleware(
|
|
82
|
+
AgentPaymentsASGIMiddleware,
|
|
83
|
+
challenge_secret=os.environ["CHALLENGE_SECRET"],
|
|
84
|
+
home_wallet_address=os.environ["HOME_WALLET_ADDRESS"],
|
|
85
|
+
debug=True,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
@app.post("/__challenge/verify")
|
|
89
|
+
async def verify(request: Request):
|
|
90
|
+
return await challenge_verify_endpoint(
|
|
91
|
+
request,
|
|
92
|
+
challenge_secret=os.environ["CHALLENGE_SECRET"],
|
|
93
|
+
)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Flask
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from flask import Flask
|
|
100
|
+
from agentpayments_python.flask_adapter import register_agentpayments
|
|
101
|
+
|
|
102
|
+
app = Flask(__name__)
|
|
103
|
+
register_agentpayments(
|
|
104
|
+
app,
|
|
105
|
+
challenge_secret=os.environ["CHALLENGE_SECRET"],
|
|
106
|
+
home_wallet_address=os.environ["HOME_WALLET_ADDRESS"],
|
|
107
|
+
debug=True,
|
|
108
|
+
)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Configuration
|
|
112
|
+
|
|
113
|
+
| Parameter | Required | Default | Description |
|
|
114
|
+
|---|---|---|---|
|
|
115
|
+
| `challenge_secret` | Yes (production) | `'default-secret-change-me'` | HMAC secret for signing cookies, nonces, and agent keys. |
|
|
116
|
+
| `home_wallet_address` | Yes | `''` | Solana wallet address to receive USDC payments. |
|
|
117
|
+
| `solana_rpc_url` | No | Auto (devnet/mainnet) | Custom Solana RPC endpoint. |
|
|
118
|
+
| `usdc_mint` | No | Auto (devnet/mainnet) | Custom USDC mint address. |
|
|
119
|
+
| `debug` | No | `True` | `True` = devnet. `False` = mainnet + strict mode. |
|
|
120
|
+
|
|
121
|
+
Django reads these from `settings.*` (e.g., `settings.CHALLENGE_SECRET`). FastAPI and Flask accept them as constructor arguments.
|
|
122
|
+
|
|
123
|
+
## Security Features
|
|
124
|
+
|
|
125
|
+
- **Timing-safe HMAC comparison** — uses `hmac.compare_digest()` for all signature checks
|
|
126
|
+
- **Payment verification cache** — 10-minute TTL, 1000-entry max (thread-safe)
|
|
127
|
+
- **Rate limiting** — 20 challenge verifications per minute per IP (thread-safe)
|
|
128
|
+
- **Input size limits** — key (64 chars), nonce (128), return URL (2048), fingerprint (128)
|
|
129
|
+
- **Wallet address validation** — base58 format, 32-44 chars, validated at init
|
|
130
|
+
- **Default secret detection** — warns in debug, raises `RuntimeError` in production
|
|
131
|
+
- **Secure cookies** — Django auto-detects HTTPS via `request.is_secure()`
|
|
132
|
+
|
|
133
|
+
## Module Structure
|
|
134
|
+
|
|
135
|
+
```
|
|
136
|
+
agentpayments_python/
|
|
137
|
+
__init__.py
|
|
138
|
+
django_adapter.py Django middleware (GateMiddleware)
|
|
139
|
+
fastapi_adapter.py FastAPI/Starlette ASGI middleware
|
|
140
|
+
flask_adapter.py Flask integration (before_request hook)
|
|
141
|
+
challenge.py Shared challenge HTML generation
|
|
142
|
+
cookies.py Cookie creation and validation
|
|
143
|
+
crypto.py HMAC signing and agent key management
|
|
144
|
+
detection.py Browser detection and public path checks
|
|
145
|
+
solana.py On-chain payment verification + caching
|
|
146
|
+
ratelimit.py Shared IP-based rate limiter
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Notes
|
|
150
|
+
- Constants loaded from `sdk/constants.json` via `pathlib`.
|
|
151
|
+
- Logging uses Python stdlib `logging` module.
|
|
152
|
+
- All shared modules are framework-agnostic; adapters are thin wiring.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# agentpayments-python
|
|
2
|
+
|
|
3
|
+
Python adapters for the AgentPayments gate. Supports Django, FastAPI/Starlette, and Flask.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install agentpayments-python
|
|
9
|
+
# or, in this monorepo:
|
|
10
|
+
# pip install -e sdk/python
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Django
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
# settings.py
|
|
17
|
+
MIDDLEWARE = [
|
|
18
|
+
"django.middleware.security.SecurityMiddleware",
|
|
19
|
+
"agentpayments_python.django_adapter.GateMiddleware",
|
|
20
|
+
# ... other middleware
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
# Required settings
|
|
24
|
+
CHALLENGE_SECRET = os.environ["CHALLENGE_SECRET"]
|
|
25
|
+
HOME_WALLET_ADDRESS = os.environ["HOME_WALLET_ADDRESS"]
|
|
26
|
+
|
|
27
|
+
# Optional settings
|
|
28
|
+
SOLANA_RPC_URL = os.environ.get("SOLANA_RPC_URL")
|
|
29
|
+
USDC_MINT = os.environ.get("USDC_MINT")
|
|
30
|
+
DEBUG = True # True = devnet, False = mainnet
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## FastAPI
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from fastapi import FastAPI, Request
|
|
37
|
+
from agentpayments_python.fastapi_adapter import (
|
|
38
|
+
AgentPaymentsASGIMiddleware,
|
|
39
|
+
challenge_verify_endpoint,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
app = FastAPI()
|
|
43
|
+
|
|
44
|
+
app.add_middleware(
|
|
45
|
+
AgentPaymentsASGIMiddleware,
|
|
46
|
+
challenge_secret=os.environ["CHALLENGE_SECRET"],
|
|
47
|
+
home_wallet_address=os.environ["HOME_WALLET_ADDRESS"],
|
|
48
|
+
debug=True,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
@app.post("/__challenge/verify")
|
|
52
|
+
async def verify(request: Request):
|
|
53
|
+
return await challenge_verify_endpoint(
|
|
54
|
+
request,
|
|
55
|
+
challenge_secret=os.environ["CHALLENGE_SECRET"],
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Flask
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from flask import Flask
|
|
63
|
+
from agentpayments_python.flask_adapter import register_agentpayments
|
|
64
|
+
|
|
65
|
+
app = Flask(__name__)
|
|
66
|
+
register_agentpayments(
|
|
67
|
+
app,
|
|
68
|
+
challenge_secret=os.environ["CHALLENGE_SECRET"],
|
|
69
|
+
home_wallet_address=os.environ["HOME_WALLET_ADDRESS"],
|
|
70
|
+
debug=True,
|
|
71
|
+
)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Configuration
|
|
75
|
+
|
|
76
|
+
| Parameter | Required | Default | Description |
|
|
77
|
+
|---|---|---|---|
|
|
78
|
+
| `challenge_secret` | Yes (production) | `'default-secret-change-me'` | HMAC secret for signing cookies, nonces, and agent keys. |
|
|
79
|
+
| `home_wallet_address` | Yes | `''` | Solana wallet address to receive USDC payments. |
|
|
80
|
+
| `solana_rpc_url` | No | Auto (devnet/mainnet) | Custom Solana RPC endpoint. |
|
|
81
|
+
| `usdc_mint` | No | Auto (devnet/mainnet) | Custom USDC mint address. |
|
|
82
|
+
| `debug` | No | `True` | `True` = devnet. `False` = mainnet + strict mode. |
|
|
83
|
+
|
|
84
|
+
Django reads these from `settings.*` (e.g., `settings.CHALLENGE_SECRET`). FastAPI and Flask accept them as constructor arguments.
|
|
85
|
+
|
|
86
|
+
## Security Features
|
|
87
|
+
|
|
88
|
+
- **Timing-safe HMAC comparison** — uses `hmac.compare_digest()` for all signature checks
|
|
89
|
+
- **Payment verification cache** — 10-minute TTL, 1000-entry max (thread-safe)
|
|
90
|
+
- **Rate limiting** — 20 challenge verifications per minute per IP (thread-safe)
|
|
91
|
+
- **Input size limits** — key (64 chars), nonce (128), return URL (2048), fingerprint (128)
|
|
92
|
+
- **Wallet address validation** — base58 format, 32-44 chars, validated at init
|
|
93
|
+
- **Default secret detection** — warns in debug, raises `RuntimeError` in production
|
|
94
|
+
- **Secure cookies** — Django auto-detects HTTPS via `request.is_secure()`
|
|
95
|
+
|
|
96
|
+
## Module Structure
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
agentpayments_python/
|
|
100
|
+
__init__.py
|
|
101
|
+
django_adapter.py Django middleware (GateMiddleware)
|
|
102
|
+
fastapi_adapter.py FastAPI/Starlette ASGI middleware
|
|
103
|
+
flask_adapter.py Flask integration (before_request hook)
|
|
104
|
+
challenge.py Shared challenge HTML generation
|
|
105
|
+
cookies.py Cookie creation and validation
|
|
106
|
+
crypto.py HMAC signing and agent key management
|
|
107
|
+
detection.py Browser detection and public path checks
|
|
108
|
+
solana.py On-chain payment verification + caching
|
|
109
|
+
ratelimit.py Shared IP-based rate limiter
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Notes
|
|
113
|
+
- Constants loaded from `sdk/constants.json` via `pathlib`.
|
|
114
|
+
- Logging uses Python stdlib `logging` module.
|
|
115
|
+
- All shared modules are framework-agnostic; adapters are thin wiring.
|
|
@@ -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…</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
|