botsrated 0.3.1__tar.gz → 0.3.2__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.
- {botsrated-0.3.1 → botsrated-0.3.2}/PKG-INFO +30 -13
- {botsrated-0.3.1 → botsrated-0.3.2}/README.md +29 -12
- {botsrated-0.3.1 → botsrated-0.3.2}/pyproject.toml +1 -1
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/guard.py +179 -24
- botsrated-0.3.2/src/botsrated/guard_checks.py +560 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/payment_guard.py +350 -43
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/util.py +109 -1
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/conftest.py +11 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/test_c1_no_repay.py +2 -2
- botsrated-0.3.2/tests/test_guard_checks.py +581 -0
- botsrated-0.3.2/tests/test_hosted_circuit.py +297 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/test_remote_policy.py +7 -1
- {botsrated-0.3.1 → botsrated-0.3.2}/.gitignore +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/LICENSE +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/__init__.py +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/client.py +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/onchain.py +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/src/botsrated/py.typed +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/test_guard.py +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/test_onchain.py +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/test_payment_guard.py +0 -0
- {botsrated-0.3.1 → botsrated-0.3.2}/tests/test_x402_sdk.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: botsrated
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Payment guard for x402 agents: checks facts BotsRated measured about a seller before paying (advice-only by default), adds a payment-identifier retry key where supported, and checks on chain, read-only, whether a payment settled once. Not affiliated with Coinbase or the x402 Foundation.
|
|
5
5
|
Project-URL: Homepage, https://botsrated.com
|
|
6
6
|
Project-URL: Repository, https://github.com/botsrated/botsrated
|
|
@@ -21,14 +21,17 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
|
|
22
22
|
## Install in 3 steps
|
|
23
23
|
|
|
24
|
-
1. Install: `pip install "botsrated[x402]"` (PyPI 0.3.1).
|
|
25
|
-
2. Attach to your x402 client:
|
|
24
|
+
1. Install: `pip install "botsrated[x402]"` (this tree is 0.3.2; PyPI still serves 0.3.1 until a later publish).
|
|
25
|
+
2. Attach to your x402 client (omit `preset` for advice only; omit `fail_mode` to stay open):
|
|
26
26
|
```python
|
|
27
27
|
from botsrated import PaymentGuard
|
|
28
|
-
guard = PaymentGuard(preset=
|
|
29
|
-
guard.install(
|
|
28
|
+
guard = PaymentGuard() # omit preset = advice; omit fail_mode = open
|
|
29
|
+
guard.install(x402_client)
|
|
30
|
+
paid_get = guard.wrap_get(session.get) # or guard.wrap_async_get(http.get)
|
|
30
31
|
```
|
|
31
|
-
3.
|
|
32
|
+
3. Omit `preset`, or call `PaymentGuard()`, for advice only. That never stops a payment. Pick `preset="carefulBuyer"` only when you want it (same stops as `POLICIES["strict"]`; stops an unobserved payTo). `strict` is not a preset name. Omit `fail_mode` inside `remote_policy` to stay open. `"closed"` stops the payment when BotsRated or your policy cannot answer. A missing decision is never a pass. A remote pass never clears a local block.
|
|
33
|
+
|
|
34
|
+
Same paste in TypeScript / JS, Python, and curl (curl reads free preflight facts and does not attach): [`docs/guard/copy-paste-attach.md`](../../docs/guard/copy-paste-attach.md).
|
|
32
35
|
|
|
33
36
|
`BOTSRATED_TOKEN` is optional. Framework attaches read it when `token` is omitted and send it only as `remote_policy` on botsrated 0.3.0 and later, never as a bare string. A configured token on a core without `parse_remote_policy` raises and is not dropped. The policy decision is not signed. Get a token in [Desk](https://botsrated.com/desk). Nothing defaults you to closed.
|
|
34
37
|
|
|
@@ -43,7 +46,7 @@ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment che
|
|
|
43
46
|
|
|
44
47
|
It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
|
|
45
48
|
|
|
46
|
-
**Status: published
|
|
49
|
+
**Status: source version 0.3.2 in this repo. Not published.** PyPI still serves [`botsrated` 0.3.1](https://pypi.org/project/botsrated/). 0.3.2 adds `repeat_payment`, `delivery_check`, `payto_base58_format`, and `quote_above_listing`. Each warns by default. None of them is a new default block. `replay_tested` stays false.
|
|
47
50
|
|
|
48
51
|
**What this does and doesn't do.** This package checks facts BotsRated measured about a seller before your agent signs, adds a retry key to the payment request, and reads the blockchain to see whether a payment already settled. It can't promise that a payment is right, that a seller will deliver, or that you'll never pay twice: a retry key only stops a second charge if the seller supports the x402 `payment-identifier` extension, and on-chain reads can be late or fail. You choose the rules that stop a payment, and you remain responsible for what your agent pays. Provided under the MIT license, "as is", without warranty.
|
|
49
52
|
|
|
@@ -63,14 +66,14 @@ uses the hook and extension points of the x402 client you pass in.
|
|
|
63
66
|
You set the thresholds. The guard compares the payment with facts BotsRated measured and, when the preflight included
|
|
64
67
|
one, a receipt link.
|
|
65
68
|
|
|
66
|
-
Pick a named preset. The zero-config call (`PaymentGuard()`) is `warn`: advice only, it never stops a payment.
|
|
69
|
+
Pick a named preset. Preset keys are `warn`, `carefulBuyer`, and `dry-run-only`. `strict` is not a preset key; it is `POLICIES["strict"]`. The zero-config call (`PaymentGuard()`) is `warn`: advice only, it never stops a payment.
|
|
67
70
|
Dry-run is optional: it logs `would_block` and still never stops a payment.
|
|
68
71
|
|
|
69
72
|
| Name | How to select it | What you get |
|
|
70
73
|
|---|---|---|
|
|
71
74
|
| `warn` | `PaymentGuard()` or `preset="warn"` or `policy=POLICIES["warn"]` | Advice only. The default. |
|
|
72
75
|
| `carefulBuyer` | `preset="carefulBuyer"` or `policy=POLICIES["carefulBuyer"]` | Same rule effects as `POLICIES["strict"]`. Stops when the payTo wasn't observed, is invalid, the host mismatches, or the paid URL is unknown. |
|
|
73
|
-
| `strict` | `policy=POLICIES["strict"]` | The same stops as `carefulBuyer`. |
|
|
76
|
+
| `POLICIES["strict"]` | `policy=POLICIES["strict"]` | The same stops as `carefulBuyer`. Not a preset. |
|
|
74
77
|
| `dry-run-only` | `dry_run_only(...)`, `preset="dry-run-only"`, or `PaymentGuard(**PRESETS["dry-run-only"])` | Logs `would_block` and never stops a payment. No retry key. `preset="dry-run-only"` and `dry_run_only()` force dry-run. |
|
|
75
78
|
|
|
76
79
|
```python
|
|
@@ -122,10 +125,14 @@ A stopped payment raises the x402 abort error with text like:
|
|
|
122
125
|
| Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["carefulBuyer"]` / `POLICIES["strict"]` |
|
|
123
126
|
|---|---|---|---|
|
|
124
127
|
| `pay_to_mismatch`: the payTo is not among the payTos BotsRated's probes recorded for the host | `payto_not_observed` | warn | **block** |
|
|
125
|
-
| `pay_to_invalid`: the payTo is not a 20-byte hex address | `payto_invalid` | warn | **block** |
|
|
128
|
+
| `pay_to_invalid`: the payTo is not a 20-byte hex address on `eip155` or v1 `base`. A Solana payTo that is not a base58 32-byte public key is `payto_base58_format`, not this code | `payto_invalid` | warn | **block** |
|
|
126
129
|
| `resource_host_mismatch`: the 402's `resource.url` names another host than the URL being paid (checked locally) | `resource_host_mismatch` | warn | **block** |
|
|
127
130
|
| `paid_url_unknown`: the URL being paid is unknown (no `wrap_get` / `guard.request(url)`), so the only host is the 402's own claim | `paid_url_unknown` | warn | **block** |
|
|
128
131
|
| `price_above_observed`: same route, amount above the last amount BotsRated recorded (compared locally) | `price_above_observed` | warn | warn |
|
|
132
|
+
| `quote_above_listing`: same route, amount above the listed amount. A server policy reason with this code uses the same effect | `quote_above_listing` | warn | warn |
|
|
133
|
+
| `repeat_payment`: the same payment identifier, or the same host, route, amount and nonce, repeats within 60 seconds. Local only. `replay_tested` stays false | `repeat_payment` | warn | warn |
|
|
134
|
+
| `pay_to_base58_format`: a Solana payTo is not a base58 32-byte public key. A Base payTo is not judged. The Base USDC rule is unchanged | `payto_base58_format` | warn | warn |
|
|
135
|
+
| After payment, on `wrap_get` / `wrap_async_get`, once a payload was created: a 2xx is not a delivery unless the body is non-empty, the content type is one this check accepts (`application/json`, `application/problem+json`, `text/plain`, `text/json`, or a `+json` type), and a JSON schema the seller declared matches. This check does not block | `delivery_check` | warn | warn |
|
|
129
136
|
| `not_covered`: BotsRated has no probe record for the host | `not_covered` | info | info |
|
|
130
137
|
| `stale`: BotsRated's latest probe is older than 24 h | `data_stale` | info | info |
|
|
131
138
|
| BotsRated unreachable (3 s timeout) | `botsrated_unreachable` | info (`fail_open=True`) | info unless `fail_open=False` |
|
|
@@ -171,7 +178,7 @@ smaller local bundle and does not add a summary number, because the response has
|
|
|
171
178
|
| `fail_open` | `True` | `False`: stop the payment when BotsRated can't be reached or the guard errors |
|
|
172
179
|
| `retry_key` | `True` | Add a `payment-identifier` id where the seller advertises it |
|
|
173
180
|
| `onchain` | default RPCs | RPC settings for `payment_state` (`rpcs`, `extra_rpc`, `margin_seconds`, `expiry_tag`, `confirm_tag`), or `False` |
|
|
174
|
-
| `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout and per-host cache |
|
|
181
|
+
| `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout, clamped to 10 s, and per-host cache |
|
|
175
182
|
| `preflight` | hosted call | Your own lookup `(host) -> (found, body)` |
|
|
176
183
|
| `on_decision` | none | Receives every decision (errors in it are ignored) |
|
|
177
184
|
| `remote_policy` | unset | Private policy check. See below. Unset: local presets only |
|
|
@@ -180,7 +187,9 @@ smaller local bundle and does not add a summary number, because the response has
|
|
|
180
187
|
|
|
181
188
|
- **Fail-open (default):** if botsrated.com is down or slow, or the guard itself hits an error, the payment goes
|
|
182
189
|
ahead and the decision says `botsrated_unreachable` (or `hook_error`). Our outage never stops your agent, but
|
|
183
|
-
during an outage you get no seller facts.
|
|
190
|
+
during an outage you get no seller facts. HTTP 503, HTTP 429 and a timeout are that miss: the guard reads
|
|
191
|
+
`Retry-After` (or waits 5 s, at most 60 s) and skips further hosted lookups in the process until then.
|
|
192
|
+
A skipped lookup is not a pass. A fresh cached success is still used.
|
|
184
193
|
- **Fail-closed (`fail_open=False`):** the same cases stop the payment. Use it only if an unchecked payment is worse
|
|
185
194
|
for you than a missed call.
|
|
186
195
|
- Local checks (`resource_host_mismatch`, `payto_invalid`) and the on-chain check never depend on botsrated.com.
|
|
@@ -198,10 +207,18 @@ guard = PaymentGuard(
|
|
|
198
207
|
)
|
|
199
208
|
```
|
|
200
209
|
|
|
201
|
-
`fail_mode` is yours: `open` or `closed`. Omit it and the check stays open. Nothing defaults you to closed. `"closed"` stops the payment when BotsRated or your policy cannot answer. The guard `POST`s `/v1/policy/check` with the seller host and the quote (`payTo`, `amount`, `asset`, `network`). On HTTP 503, HTTP 404, or `"decision": null`, it applies `fail_mode` (`open`: an info reason, payment continues unless a local rule stops it; `closed`: the payment stops). A missing decision is never a pass. A remote pass never clears a local block. Server fields are kept when the server sends them. The last `policy_version` is remembered on the guard. The policy decision is not signed. Leave `remote_policy` unset and local presets behave as before.
|
|
210
|
+
`fail_mode` is yours: `open` or `closed`. Omit it and the check stays open. Nothing defaults you to closed. `"closed"` stops the payment when BotsRated or your policy cannot answer. The guard `POST`s `/v1/policy/check` with the seller host and the quote (`payTo`, `amount`, `asset`, `network`). On HTTP 503, HTTP 429, HTTP 404, a timeout, or `"decision": null`, it applies `fail_mode` (`open`: an info reason, payment continues unless a local rule stops it; `closed`: the payment stops). A 503, 429 or timeout also opens the in-process circuit above, and the next hosted lookup is skipped. A missing decision is never a pass. A remote pass never clears a local block. Server fields are kept when the server sends them. The last `policy_version` is remembered on the guard. The policy decision is not signed. Leave `remote_policy` unset and local presets behave as before.
|
|
202
211
|
|
|
203
212
|
`BOTSRATED_TOKEN` is optional. Framework attaches read it when `token` is omitted and send it only as `remote_policy` on botsrated 0.3.0 and later. A configured token on a core without `parse_remote_policy` raises and is not dropped. Get a token in [Desk](https://botsrated.com/desk).
|
|
204
213
|
|
|
214
|
+
**Save a policy first.** `remote_policy` only checks; it never saves. With no saved policy every check answers `404 no_policy_saved`, and the guard applies your `fail_mode` (`closed` stops every payment). Start from a private pack (`none`, `warn`, `careful-buyer`, `strict`; list at `GET https://botsrated.com/v1/policy/packs`), then `PUT /v1/policy` with your token, or use [Desk → Policy](https://botsrated.com/desk/policy). The smallest one is `none` (only the two always-on checks):
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
curl -X PUT https://botsrated.com/v1/policy -H "Authorization: Bearer $BOTSRATED_TOKEN" -H "Content-Type: application/json" -d '{"preset":"none","fail_mode":"open"}'
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`fail_mode` in that body is yours to pick (`open` or `closed`). The token needs `policy-write` (a paid-plan `brs_` token, or a `brk_` org key with that scope). Server pack names (`careful-buyer`) are your saved server rules. The local `preset` (`carefulBuyer`) is a separate client table. They don't have to match.
|
|
221
|
+
|
|
205
222
|
### What The Guard Sends, And To Whom
|
|
206
223
|
|
|
207
224
|
- **botsrated.com (preflight):** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
|
|
@@ -2,14 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
## Install in 3 steps
|
|
4
4
|
|
|
5
|
-
1. Install: `pip install "botsrated[x402]"` (PyPI 0.3.1).
|
|
6
|
-
2. Attach to your x402 client:
|
|
5
|
+
1. Install: `pip install "botsrated[x402]"` (this tree is 0.3.2; PyPI still serves 0.3.1 until a later publish).
|
|
6
|
+
2. Attach to your x402 client (omit `preset` for advice only; omit `fail_mode` to stay open):
|
|
7
7
|
```python
|
|
8
8
|
from botsrated import PaymentGuard
|
|
9
|
-
guard = PaymentGuard(preset=
|
|
10
|
-
guard.install(
|
|
9
|
+
guard = PaymentGuard() # omit preset = advice; omit fail_mode = open
|
|
10
|
+
guard.install(x402_client)
|
|
11
|
+
paid_get = guard.wrap_get(session.get) # or guard.wrap_async_get(http.get)
|
|
11
12
|
```
|
|
12
|
-
3.
|
|
13
|
+
3. Omit `preset`, or call `PaymentGuard()`, for advice only. That never stops a payment. Pick `preset="carefulBuyer"` only when you want it (same stops as `POLICIES["strict"]`; stops an unobserved payTo). `strict` is not a preset name. Omit `fail_mode` inside `remote_policy` to stay open. `"closed"` stops the payment when BotsRated or your policy cannot answer. A missing decision is never a pass. A remote pass never clears a local block.
|
|
14
|
+
|
|
15
|
+
Same paste in TypeScript / JS, Python, and curl (curl reads free preflight facts and does not attach): [`docs/guard/copy-paste-attach.md`](../../docs/guard/copy-paste-attach.md).
|
|
13
16
|
|
|
14
17
|
`BOTSRATED_TOKEN` is optional. Framework attaches read it when `token` is omitted and send it only as `remote_policy` on botsrated 0.3.0 and later, never as a bare string. A configured token on a core without `parse_remote_policy` raises and is not dropped. The policy decision is not signed. Get a token in [Desk](https://botsrated.com/desk). Nothing defaults you to closed.
|
|
15
18
|
|
|
@@ -24,7 +27,7 @@ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment che
|
|
|
24
27
|
|
|
25
28
|
It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
|
|
26
29
|
|
|
27
|
-
**Status: published
|
|
30
|
+
**Status: source version 0.3.2 in this repo. Not published.** PyPI still serves [`botsrated` 0.3.1](https://pypi.org/project/botsrated/). 0.3.2 adds `repeat_payment`, `delivery_check`, `payto_base58_format`, and `quote_above_listing`. Each warns by default. None of them is a new default block. `replay_tested` stays false.
|
|
28
31
|
|
|
29
32
|
**What this does and doesn't do.** This package checks facts BotsRated measured about a seller before your agent signs, adds a retry key to the payment request, and reads the blockchain to see whether a payment already settled. It can't promise that a payment is right, that a seller will deliver, or that you'll never pay twice: a retry key only stops a second charge if the seller supports the x402 `payment-identifier` extension, and on-chain reads can be late or fail. You choose the rules that stop a payment, and you remain responsible for what your agent pays. Provided under the MIT license, "as is", without warranty.
|
|
30
33
|
|
|
@@ -44,14 +47,14 @@ uses the hook and extension points of the x402 client you pass in.
|
|
|
44
47
|
You set the thresholds. The guard compares the payment with facts BotsRated measured and, when the preflight included
|
|
45
48
|
one, a receipt link.
|
|
46
49
|
|
|
47
|
-
Pick a named preset. The zero-config call (`PaymentGuard()`) is `warn`: advice only, it never stops a payment.
|
|
50
|
+
Pick a named preset. Preset keys are `warn`, `carefulBuyer`, and `dry-run-only`. `strict` is not a preset key; it is `POLICIES["strict"]`. The zero-config call (`PaymentGuard()`) is `warn`: advice only, it never stops a payment.
|
|
48
51
|
Dry-run is optional: it logs `would_block` and still never stops a payment.
|
|
49
52
|
|
|
50
53
|
| Name | How to select it | What you get |
|
|
51
54
|
|---|---|---|
|
|
52
55
|
| `warn` | `PaymentGuard()` or `preset="warn"` or `policy=POLICIES["warn"]` | Advice only. The default. |
|
|
53
56
|
| `carefulBuyer` | `preset="carefulBuyer"` or `policy=POLICIES["carefulBuyer"]` | Same rule effects as `POLICIES["strict"]`. Stops when the payTo wasn't observed, is invalid, the host mismatches, or the paid URL is unknown. |
|
|
54
|
-
| `strict` | `policy=POLICIES["strict"]` | The same stops as `carefulBuyer`. |
|
|
57
|
+
| `POLICIES["strict"]` | `policy=POLICIES["strict"]` | The same stops as `carefulBuyer`. Not a preset. |
|
|
55
58
|
| `dry-run-only` | `dry_run_only(...)`, `preset="dry-run-only"`, or `PaymentGuard(**PRESETS["dry-run-only"])` | Logs `would_block` and never stops a payment. No retry key. `preset="dry-run-only"` and `dry_run_only()` force dry-run. |
|
|
56
59
|
|
|
57
60
|
```python
|
|
@@ -103,10 +106,14 @@ A stopped payment raises the x402 abort error with text like:
|
|
|
103
106
|
| Rule (`PaymentGuardPolicy(...)`) | Reason code | `POLICIES["warn"]` (default) | `POLICIES["carefulBuyer"]` / `POLICIES["strict"]` |
|
|
104
107
|
|---|---|---|---|
|
|
105
108
|
| `pay_to_mismatch`: the payTo is not among the payTos BotsRated's probes recorded for the host | `payto_not_observed` | warn | **block** |
|
|
106
|
-
| `pay_to_invalid`: the payTo is not a 20-byte hex address | `payto_invalid` | warn | **block** |
|
|
109
|
+
| `pay_to_invalid`: the payTo is not a 20-byte hex address on `eip155` or v1 `base`. A Solana payTo that is not a base58 32-byte public key is `payto_base58_format`, not this code | `payto_invalid` | warn | **block** |
|
|
107
110
|
| `resource_host_mismatch`: the 402's `resource.url` names another host than the URL being paid (checked locally) | `resource_host_mismatch` | warn | **block** |
|
|
108
111
|
| `paid_url_unknown`: the URL being paid is unknown (no `wrap_get` / `guard.request(url)`), so the only host is the 402's own claim | `paid_url_unknown` | warn | **block** |
|
|
109
112
|
| `price_above_observed`: same route, amount above the last amount BotsRated recorded (compared locally) | `price_above_observed` | warn | warn |
|
|
113
|
+
| `quote_above_listing`: same route, amount above the listed amount. A server policy reason with this code uses the same effect | `quote_above_listing` | warn | warn |
|
|
114
|
+
| `repeat_payment`: the same payment identifier, or the same host, route, amount and nonce, repeats within 60 seconds. Local only. `replay_tested` stays false | `repeat_payment` | warn | warn |
|
|
115
|
+
| `pay_to_base58_format`: a Solana payTo is not a base58 32-byte public key. A Base payTo is not judged. The Base USDC rule is unchanged | `payto_base58_format` | warn | warn |
|
|
116
|
+
| After payment, on `wrap_get` / `wrap_async_get`, once a payload was created: a 2xx is not a delivery unless the body is non-empty, the content type is one this check accepts (`application/json`, `application/problem+json`, `text/plain`, `text/json`, or a `+json` type), and a JSON schema the seller declared matches. This check does not block | `delivery_check` | warn | warn |
|
|
110
117
|
| `not_covered`: BotsRated has no probe record for the host | `not_covered` | info | info |
|
|
111
118
|
| `stale`: BotsRated's latest probe is older than 24 h | `data_stale` | info | info |
|
|
112
119
|
| BotsRated unreachable (3 s timeout) | `botsrated_unreachable` | info (`fail_open=True`) | info unless `fail_open=False` |
|
|
@@ -152,7 +159,7 @@ smaller local bundle and does not add a summary number, because the response has
|
|
|
152
159
|
| `fail_open` | `True` | `False`: stop the payment when BotsRated can't be reached or the guard errors |
|
|
153
160
|
| `retry_key` | `True` | Add a `payment-identifier` id where the seller advertises it |
|
|
154
161
|
| `onchain` | default RPCs | RPC settings for `payment_state` (`rpcs`, `extra_rpc`, `margin_seconds`, `expiry_tag`, `confirm_tag`), or `False` |
|
|
155
|
-
| `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout and per-host cache |
|
|
162
|
+
| `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout, clamped to 10 s, and per-host cache |
|
|
156
163
|
| `preflight` | hosted call | Your own lookup `(host) -> (found, body)` |
|
|
157
164
|
| `on_decision` | none | Receives every decision (errors in it are ignored) |
|
|
158
165
|
| `remote_policy` | unset | Private policy check. See below. Unset: local presets only |
|
|
@@ -161,7 +168,9 @@ smaller local bundle and does not add a summary number, because the response has
|
|
|
161
168
|
|
|
162
169
|
- **Fail-open (default):** if botsrated.com is down or slow, or the guard itself hits an error, the payment goes
|
|
163
170
|
ahead and the decision says `botsrated_unreachable` (or `hook_error`). Our outage never stops your agent, but
|
|
164
|
-
during an outage you get no seller facts.
|
|
171
|
+
during an outage you get no seller facts. HTTP 503, HTTP 429 and a timeout are that miss: the guard reads
|
|
172
|
+
`Retry-After` (or waits 5 s, at most 60 s) and skips further hosted lookups in the process until then.
|
|
173
|
+
A skipped lookup is not a pass. A fresh cached success is still used.
|
|
165
174
|
- **Fail-closed (`fail_open=False`):** the same cases stop the payment. Use it only if an unchecked payment is worse
|
|
166
175
|
for you than a missed call.
|
|
167
176
|
- Local checks (`resource_host_mismatch`, `payto_invalid`) and the on-chain check never depend on botsrated.com.
|
|
@@ -179,10 +188,18 @@ guard = PaymentGuard(
|
|
|
179
188
|
)
|
|
180
189
|
```
|
|
181
190
|
|
|
182
|
-
`fail_mode` is yours: `open` or `closed`. Omit it and the check stays open. Nothing defaults you to closed. `"closed"` stops the payment when BotsRated or your policy cannot answer. The guard `POST`s `/v1/policy/check` with the seller host and the quote (`payTo`, `amount`, `asset`, `network`). On HTTP 503, HTTP 404, or `"decision": null`, it applies `fail_mode` (`open`: an info reason, payment continues unless a local rule stops it; `closed`: the payment stops). A missing decision is never a pass. A remote pass never clears a local block. Server fields are kept when the server sends them. The last `policy_version` is remembered on the guard. The policy decision is not signed. Leave `remote_policy` unset and local presets behave as before.
|
|
191
|
+
`fail_mode` is yours: `open` or `closed`. Omit it and the check stays open. Nothing defaults you to closed. `"closed"` stops the payment when BotsRated or your policy cannot answer. The guard `POST`s `/v1/policy/check` with the seller host and the quote (`payTo`, `amount`, `asset`, `network`). On HTTP 503, HTTP 429, HTTP 404, a timeout, or `"decision": null`, it applies `fail_mode` (`open`: an info reason, payment continues unless a local rule stops it; `closed`: the payment stops). A 503, 429 or timeout also opens the in-process circuit above, and the next hosted lookup is skipped. A missing decision is never a pass. A remote pass never clears a local block. Server fields are kept when the server sends them. The last `policy_version` is remembered on the guard. The policy decision is not signed. Leave `remote_policy` unset and local presets behave as before.
|
|
183
192
|
|
|
184
193
|
`BOTSRATED_TOKEN` is optional. Framework attaches read it when `token` is omitted and send it only as `remote_policy` on botsrated 0.3.0 and later. A configured token on a core without `parse_remote_policy` raises and is not dropped. Get a token in [Desk](https://botsrated.com/desk).
|
|
185
194
|
|
|
195
|
+
**Save a policy first.** `remote_policy` only checks; it never saves. With no saved policy every check answers `404 no_policy_saved`, and the guard applies your `fail_mode` (`closed` stops every payment). Start from a private pack (`none`, `warn`, `careful-buyer`, `strict`; list at `GET https://botsrated.com/v1/policy/packs`), then `PUT /v1/policy` with your token, or use [Desk → Policy](https://botsrated.com/desk/policy). The smallest one is `none` (only the two always-on checks):
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
curl -X PUT https://botsrated.com/v1/policy -H "Authorization: Bearer $BOTSRATED_TOKEN" -H "Content-Type: application/json" -d '{"preset":"none","fail_mode":"open"}'
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`fail_mode` in that body is yours to pick (`open` or `closed`). The token needs `policy-write` (a paid-plan `brs_` token, or a `brk_` org key with that scope). Server pack names (`careful-buyer`) are your saved server rules. The local `preset` (`carefulBuyer`) is a separate client table. They don't have to match.
|
|
202
|
+
|
|
186
203
|
### What The Guard Sends, And To Whom
|
|
187
204
|
|
|
188
205
|
- **botsrated.com (preflight):** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "botsrated"
|
|
3
|
-
version = "0.3.
|
|
3
|
+
version = "0.3.2"
|
|
4
4
|
description = "Payment guard for x402 agents: checks facts BotsRated measured about a seller before paying (advice-only by default), adds a payment-identifier retry key where supported, and checks on chain, read-only, whether a payment settled once. Not affiliated with Coinbase or the x402 Foundation."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections.abc import Awaitable, Callable, Mapping
|
|
6
|
+
from contextvars import ContextVar
|
|
6
7
|
from dataclasses import dataclass, field
|
|
7
8
|
from typing import Any, Literal, TypeVar
|
|
8
9
|
from urllib.parse import urlsplit
|
|
@@ -15,6 +16,21 @@ from botsrated.client import (
|
|
|
15
16
|
paying_request,
|
|
16
17
|
usd_to_atomic,
|
|
17
18
|
)
|
|
19
|
+
from botsrated.guard_checks import (
|
|
20
|
+
PAYTO_BASE58_FACT,
|
|
21
|
+
RepeatWindow,
|
|
22
|
+
declared_output_schema,
|
|
23
|
+
delivery_fact,
|
|
24
|
+
evaluate_delivery,
|
|
25
|
+
listed_amount_of,
|
|
26
|
+
nonce_of,
|
|
27
|
+
payment_identifier_of,
|
|
28
|
+
payto_base58_assessment,
|
|
29
|
+
quote_above_listing_sentence,
|
|
30
|
+
read_buffered_body,
|
|
31
|
+
repeat_fact,
|
|
32
|
+
repeat_sighting,
|
|
33
|
+
)
|
|
18
34
|
from botsrated.payment_guard import (
|
|
19
35
|
RemotePolicy,
|
|
20
36
|
fetch_remote_policy,
|
|
@@ -26,11 +42,15 @@ from botsrated.util import (
|
|
|
26
42
|
clean_text,
|
|
27
43
|
is_address,
|
|
28
44
|
is_atomic_amount,
|
|
45
|
+
is_base58_pubkey,
|
|
46
|
+
network_family,
|
|
47
|
+
same_observed_network,
|
|
29
48
|
same_site_host,
|
|
30
49
|
try_host_of,
|
|
31
50
|
)
|
|
32
51
|
|
|
33
52
|
MEASUREMENT_NOTE = "This is a measurement, not a finding about the seller."
|
|
53
|
+
_DELIVERY: ContextVar[dict[str, Any] | None] = ContextVar("botsrated_prepay_delivery", default=None)
|
|
34
54
|
|
|
35
55
|
T = TypeVar("T")
|
|
36
56
|
|
|
@@ -54,6 +74,7 @@ class SellerFacts:
|
|
|
54
74
|
observed_network: str | None = None
|
|
55
75
|
probed_url: str | None = None
|
|
56
76
|
observed_amount: str | None = None
|
|
77
|
+
listed_amount: str | None = None
|
|
57
78
|
valid_402_rate: float | None = None
|
|
58
79
|
recent_probes: int | None = None
|
|
59
80
|
stale: bool | None = None
|
|
@@ -95,6 +116,12 @@ class GuardPolicy:
|
|
|
95
116
|
# (was "block"); use STRICT_GUARD_POLICY or pay_to_mismatch="block" to stop those payments.
|
|
96
117
|
pay_to_mismatch: Literal["allow", "warn", "block"] = "warn"
|
|
97
118
|
price_above_observed: Literal["allow", "warn", "block"] = "warn"
|
|
119
|
+
# Same payment identifier, or the same host, route, amount and nonce, within 60 seconds. strict does not change it.
|
|
120
|
+
repeat_payment: Literal["allow", "warn", "block"] = "warn"
|
|
121
|
+
# Solana payTo is not a base58 32-byte public key. A Base payTo is not judged. Does not change the Base USDC rule.
|
|
122
|
+
pay_to_base58_format: Literal["allow", "warn", "block"] = "warn"
|
|
123
|
+
# Same route, quoted amount above the listed amount. strict stays warn.
|
|
124
|
+
quote_above_listing: Literal["allow", "warn", "block"] = "warn"
|
|
98
125
|
stale: Literal["allow", "block"] = "allow"
|
|
99
126
|
min_valid_402_rate: float | None = None
|
|
100
127
|
# Block an x402 hook payment when the request URL being paid is unknown (no ``paying_request`` /
|
|
@@ -117,15 +144,20 @@ def facts_from(body: dict[str, Any], host: str, source: Literal["preflight", "ch
|
|
|
117
144
|
pay_tos = [probe.get("live_payTo"), measured.get("last_quoted_payTo")]
|
|
118
145
|
freshness = body.get("freshness") or {}
|
|
119
146
|
listing_pay_to = listing.get("payTo")
|
|
147
|
+
|
|
148
|
+
def stored_pay_to(value: str) -> str:
|
|
149
|
+
return value if is_base58_pubkey(value) else value.lower()
|
|
150
|
+
|
|
120
151
|
return SellerFacts(
|
|
121
152
|
covered=body.get("found") is not False,
|
|
122
153
|
host=host,
|
|
123
154
|
source=source,
|
|
124
|
-
known_pay_tos=sorted({p
|
|
125
|
-
listing_pay_to=listing_pay_to
|
|
155
|
+
known_pay_tos=sorted({stored_pay_to(p) for p in pay_tos if isinstance(p, str) and p}),
|
|
156
|
+
listing_pay_to=stored_pay_to(listing_pay_to) if isinstance(listing_pay_to, str) and listing_pay_to else None,
|
|
126
157
|
observed_network=probe.get("live_network") or listing.get("network"),
|
|
127
158
|
probed_url=probe.get("url") or (body.get("route_probed") or {}).get("url"),
|
|
128
159
|
observed_amount=probe.get("live_amount") or measured.get("last_quoted_amount_atomic"),
|
|
160
|
+
listed_amount=listed_amount_of(body),
|
|
129
161
|
valid_402_rate=rw.get("valid_402_rate"),
|
|
130
162
|
recent_probes=rw.get("probes"),
|
|
131
163
|
stale=freshness.get("stale"),
|
|
@@ -176,25 +208,58 @@ def evaluate_payment(facts: SellerFacts, req: dict[str, Any], resource_url: str
|
|
|
176
208
|
observed = clean_text(facts.observed_network, 40) if facts.observed_network else None
|
|
177
209
|
known = [x.lower() for x in facts.known_pay_tos if is_address(x)]
|
|
178
210
|
listing = facts.listing_pay_to.lower() if is_address(facts.listing_pay_to) else None
|
|
179
|
-
|
|
211
|
+
family = network_family(req.get("network"))
|
|
212
|
+
# A non-hex payTo on any family that is not Solana, including an unknown or missing network, stays payto_invalid.
|
|
213
|
+
if family == "solana" and is_base58_pubkey(raw_pay_to):
|
|
214
|
+
known_sol = [x for x in facts.known_pay_tos if is_base58_pubkey(x)]
|
|
215
|
+
listing_sol = facts.listing_pay_to if is_base58_pubkey(facts.listing_pay_to) else None
|
|
216
|
+
no_base58 = not known_sol and not listing_sol
|
|
217
|
+
if observed and not same_observed_network(observed, network):
|
|
218
|
+
add("network_not_observed", f"BotsRated's probes recorded {host} on {observed}, not on {network}.", "info")
|
|
219
|
+
elif known_sol and raw_pay_to not in known_sol:
|
|
220
|
+
add(
|
|
221
|
+
"payto_not_observed",
|
|
222
|
+
f"the payTo in this payment request is not among the payTo addresses BotsRated's probes recorded for {host} on {observed or network}.",
|
|
223
|
+
p.pay_to_mismatch,
|
|
224
|
+
)
|
|
225
|
+
elif listing_sol and not known_sol:
|
|
226
|
+
if raw_pay_to == listing_sol:
|
|
227
|
+
add("payto_listing_only", f"the payTo matches {host}'s directory listing; BotsRated's probes have not recorded a payTo for {host} yet.", "info")
|
|
228
|
+
else:
|
|
229
|
+
add(
|
|
230
|
+
"payto_not_observed",
|
|
231
|
+
f"the payTo in this payment request differs from the payTo in {host}'s directory listing; BotsRated's probes have not recorded a payTo for {host} yet.",
|
|
232
|
+
p.pay_to_mismatch,
|
|
233
|
+
)
|
|
234
|
+
elif no_base58 and (facts.known_pay_tos or facts.listing_pay_to):
|
|
235
|
+
if not observed:
|
|
236
|
+
add("network_not_observed", f"the payTo addresses BotsRated's probes recorded for {host} are eip155 addresses, not {network} addresses.", "info")
|
|
237
|
+
else:
|
|
238
|
+
add(
|
|
239
|
+
"payto_not_observed",
|
|
240
|
+
f"the payTo in this payment request is not among the payTo addresses BotsRated's probes recorded for {host} on {observed}.",
|
|
241
|
+
p.pay_to_mismatch,
|
|
242
|
+
)
|
|
243
|
+
elif family != "solana" and not is_address(raw_pay_to):
|
|
180
244
|
add("payto_invalid", "the payTo in this payment request is not a 20-byte hex address.", p.pay_to_mismatch)
|
|
181
|
-
elif
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
"payto_not_observed",
|
|
186
|
-
f"the payTo in this payment request is not among the payTo addresses BotsRated's probes recorded for {host} on {observed or network}.",
|
|
187
|
-
p.pay_to_mismatch,
|
|
188
|
-
)
|
|
189
|
-
elif not known and listing:
|
|
190
|
-
if raw_pay_to.lower() == listing:
|
|
191
|
-
add("payto_listing_only", f"the payTo matches {host}'s directory listing; BotsRated's probes have not recorded a payTo for {host} yet.", "info")
|
|
192
|
-
else:
|
|
245
|
+
elif is_address(raw_pay_to):
|
|
246
|
+
if observed and not same_observed_network(observed, network):
|
|
247
|
+
add("network_not_observed", f"BotsRated's probes recorded {host} on {observed}, not on {network}.", "info")
|
|
248
|
+
elif known and raw_pay_to.lower() not in known:
|
|
193
249
|
add(
|
|
194
250
|
"payto_not_observed",
|
|
195
|
-
f"the payTo in this payment request
|
|
251
|
+
f"the payTo in this payment request is not among the payTo addresses BotsRated's probes recorded for {host} on {observed or network}.",
|
|
196
252
|
p.pay_to_mismatch,
|
|
197
253
|
)
|
|
254
|
+
elif not known and listing:
|
|
255
|
+
if raw_pay_to.lower() == listing:
|
|
256
|
+
add("payto_listing_only", f"the payTo matches {host}'s directory listing; BotsRated's probes have not recorded a payTo for {host} yet.", "info")
|
|
257
|
+
else:
|
|
258
|
+
add(
|
|
259
|
+
"payto_not_observed",
|
|
260
|
+
f"the payTo in this payment request differs from the payTo in {host}'s directory listing; BotsRated's probes have not recorded a payTo for {host} yet.",
|
|
261
|
+
p.pay_to_mismatch,
|
|
262
|
+
)
|
|
198
263
|
if (
|
|
199
264
|
facts.observed_amount
|
|
200
265
|
and is_atomic_amount(str(facts.observed_amount))
|
|
@@ -207,6 +272,14 @@ def evaluate_payment(facts: SellerFacts, req: dict[str, Any], resource_url: str
|
|
|
207
272
|
f"the quoted amount ({amount} atomic units) is above the last amount BotsRated recorded on this route ({facts.observed_amount}).",
|
|
208
273
|
p.price_above_observed,
|
|
209
274
|
)
|
|
275
|
+
if (
|
|
276
|
+
facts.listed_amount
|
|
277
|
+
and is_atomic_amount(str(facts.listed_amount))
|
|
278
|
+
and is_atomic_amount(amount)
|
|
279
|
+
and _same_route(resource_url, facts.probed_url)
|
|
280
|
+
and int(amount) > int(facts.listed_amount)
|
|
281
|
+
):
|
|
282
|
+
add("quote_above_listing", quote_above_listing_sentence(amount, facts.listed_amount), p.quote_above_listing)
|
|
210
283
|
if facts.stale:
|
|
211
284
|
add("data_stale", f"BotsRated's latest probe of {host} is older than 24 hours.", "block" if p.stale == "block" else "info")
|
|
212
285
|
if (
|
|
@@ -220,6 +293,9 @@ def evaluate_payment(facts: SellerFacts, req: dict[str, Any], resource_url: str
|
|
|
220
293
|
f"the recent valid-402 rate BotsRated measured ({facts.valid_402_rate}) is below your minimum ({p.min_valid_402_rate}).",
|
|
221
294
|
"block",
|
|
222
295
|
)
|
|
296
|
+
base58 = payto_base58_assessment(req.get("network"), raw_pay_to)
|
|
297
|
+
if base58["applies"] and base58["valid"] is False:
|
|
298
|
+
add("payto_base58_format", PAYTO_BASE58_FACT, p.pay_to_base58_format)
|
|
223
299
|
action: Literal["allow", "block"] = "block" if any(r.effect == "block" for r in reasons) else "allow"
|
|
224
300
|
return Decision(action, facts.host, reasons, facts)
|
|
225
301
|
|
|
@@ -257,12 +333,13 @@ class PrePaymentGuard:
|
|
|
257
333
|
self.on_decision = on_decision
|
|
258
334
|
self.remote_policy = parse_remote_policy(remote_policy)
|
|
259
335
|
self.remote_policy_version: str | None = None
|
|
336
|
+
self._repeats = RepeatWindow()
|
|
260
337
|
|
|
261
338
|
def _open_or_closed(self, code: str, detail: str, host: str | None = None) -> Decision:
|
|
262
339
|
eff: Effect = "info" if self.fail_open else "block"
|
|
263
340
|
return Decision("allow" if self.fail_open else "block", host, [Reason(code, detail, eff)])
|
|
264
341
|
|
|
265
|
-
def decide(self, resource_url: str | None, requirements: Any, *, request_url: str | None = None) -> Decision:
|
|
342
|
+
def decide(self, resource_url: str | None, requirements: Any, *, request_url: str | None = None, payment_required: Any = None) -> Decision:
|
|
266
343
|
"""Decide on one payment. Never raises when ``fail_open`` is True.
|
|
267
344
|
|
|
268
345
|
Args:
|
|
@@ -275,10 +352,64 @@ class PrePaymentGuard:
|
|
|
275
352
|
difference (a redirect between the two) is tolerated. Only host names are sent to BotsRated.
|
|
276
353
|
"""
|
|
277
354
|
try:
|
|
278
|
-
|
|
355
|
+
note = _DELIVERY.get()
|
|
356
|
+
if note is not None:
|
|
357
|
+
schema = declared_output_schema(payment_required, as_requirements(requirements))
|
|
358
|
+
if schema is not None:
|
|
359
|
+
note["schema"] = schema
|
|
360
|
+
decision = self._apply_repeat(self._decide(resource_url, requirements, request_url), requirements, request_url or resource_url, payment_required)
|
|
279
361
|
except Exception: # noqa: BLE001
|
|
280
362
|
decision = self._open_or_closed("hook_error", "the pre-payment check could not evaluate this payment.")
|
|
281
|
-
|
|
363
|
+
decision = self._merge_remote(decision, requirements)
|
|
364
|
+
# A block means no payment was created, so the wrapped response is not a delivery check.
|
|
365
|
+
note = _DELIVERY.get()
|
|
366
|
+
if note is not None:
|
|
367
|
+
note["paid"] = decision.action == "allow"
|
|
368
|
+
return decision
|
|
369
|
+
|
|
370
|
+
def _apply_repeat(self, decision: Decision, requirements: Any, request_url: str | None, payment_required: Any) -> Decision:
|
|
371
|
+
req = as_requirements(requirements)
|
|
372
|
+
sighting = repeat_sighting(
|
|
373
|
+
payment_id=payment_identifier_of(payment_required, req),
|
|
374
|
+
url=request_url,
|
|
375
|
+
amount=req.get("amount"),
|
|
376
|
+
nonce=nonce_of(req),
|
|
377
|
+
)
|
|
378
|
+
now = self._repeats.now()
|
|
379
|
+
hit = self._repeats.check(sighting, now)
|
|
380
|
+
effect = self.policy.repeat_payment
|
|
381
|
+
if hit and effect != "allow":
|
|
382
|
+
decision.reasons.append(Reason("repeat_payment", repeat_fact(hit), "block" if effect == "block" else "warn"))
|
|
383
|
+
if effect == "block":
|
|
384
|
+
decision.action = "block"
|
|
385
|
+
if decision.action == "allow":
|
|
386
|
+
self._repeats.record(sighting, now)
|
|
387
|
+
return decision
|
|
388
|
+
|
|
389
|
+
def _note_delivery(self, result: Any, note: dict[str, Any], url: str) -> None:
|
|
390
|
+
try:
|
|
391
|
+
if not note.get("paid"):
|
|
392
|
+
return
|
|
393
|
+
status = getattr(result, "status_code", None)
|
|
394
|
+
if status is None:
|
|
395
|
+
status = getattr(result, "status", None)
|
|
396
|
+
if not isinstance(status, int):
|
|
397
|
+
return
|
|
398
|
+
loaded = read_buffered_body(result)
|
|
399
|
+
if loaded is None:
|
|
400
|
+
return
|
|
401
|
+
body, content_type, truncated = loaded
|
|
402
|
+
check = evaluate_delivery(status=status, body=body, content_type=content_type, schema=note.get("schema"), truncated=truncated)
|
|
403
|
+
if check["effect"] != "warn" or self.on_decision is None:
|
|
404
|
+
return
|
|
405
|
+
host = try_host_of(url)
|
|
406
|
+
decision = Decision("allow", host, [Reason("delivery_check", delivery_fact(check), "warn")])
|
|
407
|
+
try:
|
|
408
|
+
self.on_decision(decision)
|
|
409
|
+
except Exception: # noqa: BLE001
|
|
410
|
+
return
|
|
411
|
+
except Exception: # noqa: BLE001
|
|
412
|
+
return
|
|
282
413
|
|
|
283
414
|
def _merge_remote(self, decision: Decision, requirements: Any) -> Decision:
|
|
284
415
|
"""POST /v1/policy/check when configured. A remote block wins. A missing decision follows fail_mode."""
|
|
@@ -293,6 +424,12 @@ class PrePaymentGuard:
|
|
|
293
424
|
version = effect.policy_version or self.remote_policy_version
|
|
294
425
|
if effect.policy_version:
|
|
295
426
|
self.remote_policy_version = effect.policy_version
|
|
427
|
+
if effect.quote_above_listing_fact and not any(r.code == "quote_above_listing" for r in decision.reasons):
|
|
428
|
+
quote_effect = self.policy.quote_above_listing
|
|
429
|
+
if quote_effect != "allow":
|
|
430
|
+
decision.reasons.append(Reason("quote_above_listing", effect.quote_above_listing_fact, "block" if quote_effect == "block" else "warn"))
|
|
431
|
+
if quote_effect == "block":
|
|
432
|
+
decision.action = "block"
|
|
296
433
|
if effect.effect and effect.code and effect.fact:
|
|
297
434
|
decision.reasons.append(Reason(effect.code, effect.fact, effect.effect))
|
|
298
435
|
if effect.effect == "block":
|
|
@@ -366,8 +503,15 @@ class PrePaymentGuard:
|
|
|
366
503
|
"""Wrap a paying GET (e.g. ``x402_requests(client).get``) so :meth:`x402_hook` knows the URL being paid."""
|
|
367
504
|
|
|
368
505
|
def guarded_get(url: Any, *args: Any, **kwargs: Any) -> T:
|
|
369
|
-
|
|
370
|
-
|
|
506
|
+
note: dict[str, Any] = {"paid": False, "schema": None}
|
|
507
|
+
token = _DELIVERY.set(note)
|
|
508
|
+
try:
|
|
509
|
+
with paying_request(str(url)):
|
|
510
|
+
result = get(url, *args, **kwargs)
|
|
511
|
+
finally:
|
|
512
|
+
_DELIVERY.reset(token)
|
|
513
|
+
self._note_delivery(result, note, str(url))
|
|
514
|
+
return result
|
|
371
515
|
|
|
372
516
|
return guarded_get
|
|
373
517
|
|
|
@@ -375,8 +519,15 @@ class PrePaymentGuard:
|
|
|
375
519
|
"""Async version of :meth:`wrap_get`, e.g. for an x402 ``httpx.AsyncClient``'s ``get``."""
|
|
376
520
|
|
|
377
521
|
async def guarded_get(url: Any, *args: Any, **kwargs: Any) -> T:
|
|
378
|
-
|
|
379
|
-
|
|
522
|
+
note: dict[str, Any] = {"paid": False, "schema": None}
|
|
523
|
+
token = _DELIVERY.set(note)
|
|
524
|
+
try:
|
|
525
|
+
with paying_request(str(url)):
|
|
526
|
+
result = await get(url, *args, **kwargs)
|
|
527
|
+
finally:
|
|
528
|
+
_DELIVERY.reset(token)
|
|
529
|
+
self._note_delivery(result, note, str(url))
|
|
530
|
+
return result
|
|
380
531
|
|
|
381
532
|
return guarded_get
|
|
382
533
|
|
|
@@ -388,7 +539,7 @@ class PrePaymentGuard:
|
|
|
388
539
|
if not request_url and self.policy.require_request_url:
|
|
389
540
|
d = Decision("block", None, [Reason("no_request_url", "the URL being paid is unknown; wrap the request with paying_request(url).", "block")])
|
|
390
541
|
else:
|
|
391
|
-
d = self.decide(url, context.selected_requirements, request_url=request_url)
|
|
542
|
+
d = self.decide(url, context.selected_requirements, request_url=request_url, payment_required=pr)
|
|
392
543
|
paid_url = request_url or url
|
|
393
544
|
if paid_url and d.action == "allow" and try_host_of(paid_url) == self.client.host:
|
|
394
545
|
# A BotsRated payment is a one-shot EIP-3009 transfer: refuse payment extensions (e.g. an
|
|
@@ -397,6 +548,10 @@ class PrePaymentGuard:
|
|
|
397
548
|
d = Decision("block", d.host, [Reason("botsrated_payment_extensions", "BotsRated quotes must not carry payment extensions.", "block")])
|
|
398
549
|
else:
|
|
399
550
|
pr.extensions = None
|
|
551
|
+
if d.action != "allow":
|
|
552
|
+
note = _DELIVERY.get()
|
|
553
|
+
if note is not None:
|
|
554
|
+
note["paid"] = False
|
|
400
555
|
return d
|
|
401
556
|
|
|
402
557
|
def _hook(self, context: Any, request_url: str | None) -> Any:
|