agent-traffic-gate 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +272 -2
- package/bin/agent-traffic-gate.js +166 -0
- package/package.json +58 -4
- package/src/agents.js +45 -0
- package/src/classify.js +64 -0
- package/src/directory.js +237 -0
- package/src/gate.js +112 -0
- package/src/httpsig.js +232 -0
- package/src/index.js +8 -0
- package/src/policy.js +77 -0
- package/src/sfv.js +199 -0
- package/src/util.js +41 -0
- package/src/verify.js +157 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (4 Dec 2026)
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- Verifies Web Bot Auth signatures (draft-ietf-webbotauth-httpsig-protocol-01 on RFC 9421): Ed25519, RSA-PSS SHA-512, ECDSA P-256/P-384, RSA v1.5; HMAC refused. Dictionary and legacy Signature-Agent forms, multiple signatures, Content-Digest, nonce replay store.
|
|
8
|
+
- Key discovery with the draft's rules: direct JWKS URL, legacy origin to well-known fallback, no redirects, 200 only, media type and kid = thumbprint at the well-known URI, optional directory signature (possession proof), per (URL, keyid) cache, rate-limited refetch for rotation, failed refresh keeps the cache, SSRF guards (HTTPS only, private addresses refused including via DNS, size and key limits, signer allowlist).
|
|
9
|
+
- Visa Trusted Agent Protocol profile (agent-browser-auth / agent-payer-auth, @authority + @path, nonce, 8-minute window) with your key source.
|
|
10
|
+
- Classification: signed agent, verified crawler (official IP lists via ai-traffic-insights), spoofed, claimed bot, automation, unknown. Known signers: ChatGPT agent, Google-Agent, Cloudflare Browser Run.
|
|
11
|
+
- Store policy with checkout, account and admin areas, per-agent overrides, payment-intent requirement; actions allow, block, require-signature (403 + Accept-Signature), rate limit (429 + Retry-After), challenge hook; monitor mode.
|
|
12
|
+
- Fetch middleware (Workers, Vercel and Next.js, Hono, Bun, Deno) and Express middleware.
|
|
13
|
+
- CLI: verify a captured request, check a key directory, keygen, sign test requests, policy check.
|
|
14
|
+
- Passes the IETF draft's Appendix E vectors and Cloudflare's reference vectors.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmad Zia (https://www.ahmadzia.com)
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,273 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent-traffic-gate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<!-- badges -->
|
|
4
|
+
[](https://www.npmjs.com/package/agent-traffic-gate) [](https://github.com/MuhammadAhmadZia/agent-traffic-gate/actions/workflows/ci.yml) [](LICENSE) [](skills/agent-traffic-gate/SKILL.md) [](https://www.ahmadzia.com/tools/agent-traffic-gate)
|
|
5
|
+
|
|
6
|
+
Let real AI shopping agents into your store, and keep fake bots out.
|
|
7
|
+
|
|
8
|
+
AI agents now browse and buy for people. Some examples:
|
|
9
|
+
|
|
10
|
+
- ChatGPT's agent opens product pages and checks out.
|
|
11
|
+
- Google-Agent acts for Google users.
|
|
12
|
+
- Visa and Mastercard are building checkout flows for agents that carry a payment credential.
|
|
13
|
+
|
|
14
|
+
Most store firewalls were built to block anything automated. Their choice is to block these agents, and lose the sale, or let every bot through.
|
|
15
|
+
|
|
16
|
+
The way out is a cryptographic signature. More and more agents sign their requests with **Web Bot Auth**: an IETF draft built on HTTP Message Signatures (RFC 9421), co-written by Cloudflare and Google. A signed request names the URL of its keys. Your server fetches the keys, checks the signature, and then knows for certain who sent it.
|
|
17
|
+
|
|
18
|
+
agent-traffic-gate does that check in your own code, then sorts every request into one of six groups:
|
|
19
|
+
|
|
20
|
+
| Class | What it means |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `signed-agent` | Signature verified against keys fetched from the agent's own URL (or a payment network's keys) |
|
|
23
|
+
| `verified-bot` | A known crawler's user agent, from an address on that operator's published IP list |
|
|
24
|
+
| `spoofed` | Claims to be a known bot or a known signer, and the proof fails |
|
|
25
|
+
| `claimed-bot` | Claims a known bot whose operator publishes no IP list |
|
|
26
|
+
| `automation` | Looks like a script, crawler or headless browser, with no proof |
|
|
27
|
+
| `unknown` | No sign of automation (most people) |
|
|
28
|
+
|
|
29
|
+
A store policy then decides what each group may do on each kind of page:
|
|
30
|
+
|
|
31
|
+
| | Browsing | Cart and checkout | Account and login | Admin |
|
|
32
|
+
|---|---|---|---|---|
|
|
33
|
+
| signed-agent | allow | allow | allow | block |
|
|
34
|
+
| verified-bot | allow | block | block | block |
|
|
35
|
+
| spoofed | block | block | block | block |
|
|
36
|
+
| claimed-bot, automation | 30 per minute | 403 asking for a signature | block | block |
|
|
37
|
+
| unknown (people) | allow | allow | allow | allow |
|
|
38
|
+
|
|
39
|
+
You can change any cell. The 403 includes an `Accept-Signature` header, which is the draft's way of telling an honest agent how to sign.
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
You need Node.js 20 or newer. Check with `node --version`.
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install agent-traffic-gate
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**Cloudflare Workers, Hono, Bun or Deno (any Fetch API server):**
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
import { createGate } from 'agent-traffic-gate';
|
|
53
|
+
|
|
54
|
+
const gate = createGate({ ipFrom: 'cf-connecting-ip', mode: 'monitor', onDecision: (d) => console.log(JSON.stringify(d)) });
|
|
55
|
+
|
|
56
|
+
export default { fetch: gate.fetch((request) => fetch(request)) };
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**Next.js (middleware.js):**
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
import { NextResponse } from 'next/server';
|
|
63
|
+
import { createGate } from 'agent-traffic-gate';
|
|
64
|
+
|
|
65
|
+
const gate = createGate({ ipFrom: 'x-vercel-forwarded-for' });
|
|
66
|
+
|
|
67
|
+
export async function middleware(request) {
|
|
68
|
+
const r = await gate.check(request);
|
|
69
|
+
const blocked = gate.responseFor(r);
|
|
70
|
+
if (blocked) return blocked;
|
|
71
|
+
const res = NextResponse.next();
|
|
72
|
+
res.headers.set('x-agent-class', r.info.class);
|
|
73
|
+
return res;
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
**Express:**
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
import express from 'express';
|
|
81
|
+
import { createGate } from 'agent-traffic-gate';
|
|
82
|
+
|
|
83
|
+
const app = express();
|
|
84
|
+
app.set('trust proxy', 1); // so req.ip is the visitor, not your load balancer
|
|
85
|
+
app.use(createGate().express()); // req.agent tells your routes who is calling
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
**Start in monitor mode.** In `mode: 'monitor'` the gate decides and logs, but lets everything through. Read the logs for a week, then switch to `'enforce'`.
|
|
89
|
+
|
|
90
|
+
### Checking crawler IPs
|
|
91
|
+
|
|
92
|
+
To tell a real GPTBot or Googlebot from a fake one, the gate needs each operator's published IP list. In Node, load the lists once at start-up. They are downloaded from the operators and cached for a day:
|
|
93
|
+
|
|
94
|
+
```js
|
|
95
|
+
import { createGate, loadBotRanges } from 'agent-traffic-gate';
|
|
96
|
+
const gate = createGate({ ranges: await loadBotRanges() });
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
At the edge, fetch the JSON files yourself and pass them in with `botRangesFromJson({ url: json })`. The lists come from ai-traffic-insights, which covers 22 crawlers from OpenAI, Anthropic, Perplexity, Google, Microsoft, Apple, DuckDuckGo and Common Crawl.
|
|
100
|
+
|
|
101
|
+
## What the verifier checks
|
|
102
|
+
|
|
103
|
+
The checks follow `draft-ietf-webbotauth-httpsig-protocol-01` (October 2026).
|
|
104
|
+
|
|
105
|
+
**The signature**
|
|
106
|
+
|
|
107
|
+
- It must carry the tag `web-bot-auth`.
|
|
108
|
+
- It must have `created`, `expires` and `keyid`, and cover `@authority` or `@target-uri`.
|
|
109
|
+
- If there is a `Signature-Agent` member, the signature must cover it, or the request cannot be attributed to that URL.
|
|
110
|
+
- `created` cannot be in the future. `expires` cannot have passed. You can set the clock skew.
|
|
111
|
+
- The lifetime can be at most 24 hours. That is the draft's recommendation, and you can lower it.
|
|
112
|
+
- The `keyid` must be the key's JWK thumbprint.
|
|
113
|
+
- Supported algorithms: Ed25519, RSA-PSS SHA-512, ECDSA P-256 and P-384, and RSA v1.5. HMAC is refused, because the draft forbids shared secrets.
|
|
114
|
+
- If `Content-Digest` is covered, the body is checked against it.
|
|
115
|
+
- If you give a nonce store, each nonce is accepted only once.
|
|
116
|
+
- Each signature on a request is checked on its own.
|
|
117
|
+
|
|
118
|
+
**Fetching the keys**
|
|
119
|
+
|
|
120
|
+
- Fetches use HTTPS only and never follow redirects. Only a 200 counts.
|
|
121
|
+
- The response can be at most 64 KB and hold at most 100 keys. The fetch times out after 5 seconds.
|
|
122
|
+
- Private and loopback addresses are refused. In Node that includes hosts whose DNS answers are private.
|
|
123
|
+
- At the well-known URI, the media type is checked, and each `kid` must equal its thumbprint.
|
|
124
|
+
- Keys with private material are skipped.
|
|
125
|
+
- If the directory signs its own response (a possession proof, recommended by the draft), the signature is checked and the result says `bound`.
|
|
126
|
+
- Keys are cached per (URL, keyid) for the `max-age` the directory sends, kept between 5 minutes and 24 hours.
|
|
127
|
+
- An unknown `keyid` triggers a refetch, in case the agent rotated keys. It refetches at most once a minute, so random key ids cannot make you hammer a directory.
|
|
128
|
+
- If a refresh fails, the keys already cached are kept.
|
|
129
|
+
- You can limit which signers are fetched at all with `allowSigners`.
|
|
130
|
+
|
|
131
|
+
**The legacy form**
|
|
132
|
+
|
|
133
|
+
Some agents still send the older bare form, such as ChatGPT's `Signature-Agent: "https://chatgpt.com"`. A bare origin resolves to its `/.well-known/http-message-signatures-directory` first, and falls back to the URL itself only on 404 or 410. This is the same as Cloudflare's reference verifier.
|
|
134
|
+
|
|
135
|
+
**Known signers**
|
|
136
|
+
|
|
137
|
+
These were checked on 4 Dec 2026. The name is attached only after the signature verifies against keys from that URL:
|
|
138
|
+
|
|
139
|
+
| Agent | Signature-Agent |
|
|
140
|
+
|---|---|
|
|
141
|
+
| ChatGPT agent (cloud browser) | `"https://chatgpt.com"` |
|
|
142
|
+
| Google-Agent (experimental, only some requests are signed) | `g="https://agent.bot.goog"` |
|
|
143
|
+
| Cloudflare Browser Run | its workers.dev directory |
|
|
144
|
+
|
|
145
|
+
Any other agent that signs correctly is accepted as a `signed-agent` and named by its host.
|
|
146
|
+
|
|
147
|
+
### Visa Trusted Agent Protocol
|
|
148
|
+
|
|
149
|
+
Visa's Trusted Agent Protocol is built on the same signatures. It uses two tags: `agent-browser-auth` for browsing and `agent-payer-auth` for checkout. To accept it, turn on the profile:
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
createGate({ profiles: ['web-bot-auth', 'visa-tap'], tapKeys: async (keyid) => lookUpVisaKey(keyid), nonceStore: myRedisNonceStore });
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
With this profile on, the gate:
|
|
156
|
+
|
|
157
|
+
- requires a nonce and coverage of `@authority` and `@path`;
|
|
158
|
+
- keeps the timestamps within 8 minutes, as Visa's specification says;
|
|
159
|
+
- sets `intent` to `browse` or `pay`.
|
|
160
|
+
|
|
161
|
+
Add `requirePayIntent: ['checkout']` to your policy to admit only paying agents to checkout.
|
|
162
|
+
|
|
163
|
+
Keys come from Visa's agent registry, so you supply the lookup. Visa does not publish a public directory URL.
|
|
164
|
+
|
|
165
|
+
Mastercard Agent Pay also uses Web Bot Auth, but its tag is not public yet, so it is not built in.
|
|
166
|
+
|
|
167
|
+
## Accuracy
|
|
168
|
+
|
|
169
|
+
These test vectors pass:
|
|
170
|
+
|
|
171
|
+
- every vector in the IETF draft's Appendix E: Ed25519 and RSA-PSS, with both the dictionary and the legacy `Signature-Agent` form;
|
|
172
|
+
- the signed directory response in Appendix E;
|
|
173
|
+
- all 8 signature vectors and the directory vector from Cloudflare's reference implementation.
|
|
174
|
+
|
|
175
|
+
Tampering with the path, the method or the authority breaks verification. So does a covered header that is missing.
|
|
176
|
+
|
|
177
|
+
The tests also cover:
|
|
178
|
+
|
|
179
|
+
- expiry and future dates;
|
|
180
|
+
- lifetimes that are too long;
|
|
181
|
+
- private hosts and redirects;
|
|
182
|
+
- wrong media types;
|
|
183
|
+
- `kid` values that are not thumbprints;
|
|
184
|
+
- key rotation and failed refreshes;
|
|
185
|
+
- nonce replay and the Visa profile;
|
|
186
|
+
- classification and policy;
|
|
187
|
+
- both middlewares and the CLI.
|
|
188
|
+
|
|
189
|
+
**Speed.** On one core (Node 22), the full check takes about 0.28 ms for a signed request, once its keys are cached. That is about 3,600 per second. An unsigned request takes about 0.01 ms, which is about 87,000 per second.
|
|
190
|
+
|
|
191
|
+
## Command line
|
|
192
|
+
|
|
193
|
+
You can check a signed request copied from your logs or browser devtools:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
npx agent-traffic-gate verify request.txt
|
|
197
|
+
npx agent-traffic-gate directory https://chatgpt.com
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
If you build an agent, you can make a key, publish the directory and sign test requests against your own gate or CDN rules:
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
npx agent-traffic-gate keygen --out ./keys
|
|
204
|
+
npx agent-traffic-gate sign https://your-store.com/checkout --key ./keys/private.jwk.json \
|
|
205
|
+
--agent https://your-agent.example/.well-known/http-message-signatures-directory --curl
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
You can also print or check a policy:
|
|
209
|
+
|
|
210
|
+
```bash
|
|
211
|
+
npx agent-traffic-gate policy > policy.json
|
|
212
|
+
npx agent-traffic-gate policy policy.json
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Options
|
|
216
|
+
|
|
217
|
+
| Option | Default | What it does |
|
|
218
|
+
|---|---|---|
|
|
219
|
+
| `policy` | `STORE_POLICY` | Classes, areas (path globs), actions, per-agent overrides, `requirePayIntent` |
|
|
220
|
+
| `mode` | `enforce` | `monitor` decides and logs without blocking |
|
|
221
|
+
| `ipFrom` | none | Which header holds the visitor IP: `cf-connecting-ip`, `x-vercel-forwarded-for`, `x-real-ip`, `fastly-client-ip`, `x-forwarded-for`, or a function. Only trust a header your own proxy sets |
|
|
222
|
+
| `ranges` | none | Crawler IP lists (`loadBotRanges()` or `botRangesFromJson()`) |
|
|
223
|
+
| `profiles` | `['web-bot-auth']` | Add `'visa-tap'` for Visa's protocol |
|
|
224
|
+
| `allowSigners` | any | Hosts or URL prefixes you are willing to fetch keys from |
|
|
225
|
+
| `nonceStore`, `limiter` | in memory | Swap in Redis or KV when you run more than one server |
|
|
226
|
+
| `clockSkew`, `maxWindow` | 60 s, profile limit | Time checks |
|
|
227
|
+
| `strictDirectory` | `false` | Reject directories that break the draft's format rules (default: log and continue) |
|
|
228
|
+
| `challenge` | none | `async (request, info) => Response` to hand off to your CDN challenge or CAPTCHA (default: a strict rate limit) |
|
|
229
|
+
| `onDecision` | none | Log every decision |
|
|
230
|
+
|
|
231
|
+
## What it does not do
|
|
232
|
+
|
|
233
|
+
- **A valid signature proves who signed, not that they are honest.** The draft says this itself. Whether to trust a signer is your policy. That is why admin pages stay closed even to signed agents.
|
|
234
|
+
- **It does not see TLS fingerprints or behaviour.** A bot that looks exactly like a browser and signs nothing lands in `unknown`. Keep your CDN's bot protection for that. This gate is for the traffic that identifies itself.
|
|
235
|
+
- **It does not issue CAPTCHAs.** It can call your challenge handler.
|
|
236
|
+
- **It has not been tried against live agents.** The machine it was built on cannot reach chatgpt.com or agent.bot.goog. Run `npx agent-traffic-gate directory https://chatgpt.com` once on your machine. The draft's own test vectors and Cloudflare's all pass.
|
|
237
|
+
|
|
238
|
+
## Where the other tools fit
|
|
239
|
+
|
|
240
|
+
- **ai-traffic-insights:** shows how much AI traffic you get, from your logs. This gate acts on it in real time.
|
|
241
|
+
- **agentic-commerce-readiness:** checks that agents can read your products and checkout.
|
|
242
|
+
- **storeguard:** checks the rest of the store's security.
|
|
243
|
+
|
|
244
|
+
## Sustainable Development Goals
|
|
245
|
+
|
|
246
|
+
This tool supports **SDG target 9.1**: reliable, resilient and affordable infrastructure with equitable access.
|
|
247
|
+
|
|
248
|
+
As buying moves to AI agents, small stores face a bad choice. They can block agents and lose customers, or open up to scraping, fake bots and card testing. Verification has so far lived in enterprise bot-management products. This gate brings the same open standard to any store that runs code, for free, so a small merchant can be reached by AI agents without becoming easier to attack.
|
|
249
|
+
|
|
250
|
+
## License
|
|
251
|
+
|
|
252
|
+
MIT © Ahmad Zia. The test vectors under `test/vectors/web_bot_auth_*.json` come from Cloudflare's web-bot-auth repository (Apache-2.0).
|
|
253
|
+
|
|
254
|
+
<!-- ahmadzia-links -->
|
|
255
|
+
## Guide, help and author
|
|
256
|
+
|
|
257
|
+
- **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/agent-traffic-gate](https://www.ahmadzia.com/tools/agent-traffic-gate)
|
|
258
|
+
- **Background reading:** [WebMCP vs MCP for online stores](https://www.ahmadzia.com/blog/webmcp-vs-mcp-online-stores)
|
|
259
|
+
- **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
|
|
260
|
+
- **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)
|
|
261
|
+
|
|
262
|
+
Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
|
|
263
|
+
<!-- /ahmadzia-links -->
|
|
264
|
+
|
|
265
|
+
## More AI and store security tools
|
|
266
|
+
|
|
267
|
+
- [shopbot-shield](https://github.com/MuhammadAhmadZia/shopbot-shield): Prompt injection protection for ecommerce chatbots and AI shopping assistants
|
|
268
|
+
- [model-file-guard](https://github.com/MuhammadAhmadZia/model-file-guard): Scan pickle, PyTorch, joblib and other ML model files for hidden code before you load them
|
|
269
|
+
- [llm-store-review](https://github.com/MuhammadAhmadZia/llm-store-review): Security review of AI chatbots and agents in your code, mapped to the OWASP LLM Top 10 2026
|
|
270
|
+
- [rag-content-guard](https://github.com/MuhammadAhmadZia/rag-content-guard): Find hidden instructions and poisoned documents before they reach your RAG index or AI agent
|
|
271
|
+
- [storeguard](https://github.com/MuhammadAhmadZia/storeguard): Free security scanner for vibe-coded online stores
|
|
272
|
+
|
|
273
|
+
All 30 tools and agent skills: [github.com/MuhammadAhmadZia](https://github.com/MuhammadAhmadZia) · [ahmadzia.com/tools](https://www.ahmadzia.com/tools)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, writeFile, mkdir } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import {
|
|
5
|
+
createVerifier, classify, loadBotRanges, STORE_POLICY, validatePolicy, decide, checkDirectory, signRequest, jwkThumbprint,
|
|
6
|
+
KNOWN_SIGNERS, CHECKED, MEDIA_TYPE, WELL_KNOWN, SigError,
|
|
7
|
+
} from '../src/index.js';
|
|
8
|
+
|
|
9
|
+
const HELP = `agent-traffic-gate: let real AI agents in, keep fake bots out.
|
|
10
|
+
|
|
11
|
+
Commands
|
|
12
|
+
verify <request.txt> Check the signatures on a raw HTTP request copied from logs or devtools
|
|
13
|
+
--now <unix-seconds> Pretend it is this time (for old captures)
|
|
14
|
+
--jwks <file> Trust keys from this JWK Set instead of fetching (offline)
|
|
15
|
+
--visa-tap Also accept Visa Trusted Agent Protocol tags (keys via --jwks)
|
|
16
|
+
--ip <address> Client address, to check crawler IP lists too
|
|
17
|
+
--ranges Download official crawler IP lists (cached a day) for the IP check
|
|
18
|
+
--max-window <seconds> Longest accepted expires - created (default 86400; 0 = no limit, for test vectors)
|
|
19
|
+
directory <url> Fetch an agent's key directory and check it against the Web Bot Auth draft
|
|
20
|
+
keygen [--out <dir>] Make an Ed25519 signing key and the directory file to publish (for agent builders)
|
|
21
|
+
sign <url> --key <private.jwk.json> --agent <directory-url> [--method GET] [--ttl 300] [--curl]
|
|
22
|
+
Sign a test request, to try your gate or CDN rules
|
|
23
|
+
policy [file.json] Print the default store policy, or check your own
|
|
24
|
+
signers List the agents this version knows by name
|
|
25
|
+
|
|
26
|
+
-h, --help
|
|
27
|
+
|
|
28
|
+
The middleware (createGate) is the main use: see the README.
|
|
29
|
+
More: https://www.ahmadzia.com/tools/agent-traffic-gate
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
function args(argv) {
|
|
33
|
+
const o = { _: [] };
|
|
34
|
+
for (let i = 0; i < argv.length; i++) {
|
|
35
|
+
const a = argv[i];
|
|
36
|
+
if (a === '-h' || a === '--help') o.help = true;
|
|
37
|
+
else if (['--now', '--jwks', '--ip', '--out', '--key', '--agent', '--method', '--ttl', '--max-window'].includes(a)) { const v = argv[++i]; if (v === undefined) throw new Error(`${a} needs a value`); o[a.slice(2)] = v; }
|
|
38
|
+
else if (['--visa-tap', '--ranges', '--curl', '--json'].includes(a)) o[a.slice(2).replace(/-(\w)/g, (_, c) => c.toUpperCase())] = true;
|
|
39
|
+
else if (a.startsWith('-')) throw new Error(`Unknown option ${a}`);
|
|
40
|
+
else o._.push(a);
|
|
41
|
+
}
|
|
42
|
+
return o;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Parse a raw HTTP/1.1 request (request line + headers). Folded and repeated headers are joined. */
|
|
46
|
+
export function parseRawRequest(text) {
|
|
47
|
+
const lines = text.replace(/\r\n/g, '\n').split('\n');
|
|
48
|
+
const first = lines.shift().trim();
|
|
49
|
+
const m = /^([A-Z]+)\s+(\S+)(?:\s+HTTP\/[\d.]+)?$/.exec(first);
|
|
50
|
+
if (!m) throw new Error('first line must be a request line, for example: GET /path HTTP/1.1');
|
|
51
|
+
const headers = {};
|
|
52
|
+
let last = null;
|
|
53
|
+
for (const l of lines) {
|
|
54
|
+
if (!l.trim()) break;
|
|
55
|
+
if (/^[ \t]/.test(l) && last) { headers[last] += ` ${l.trim()}`; continue; }
|
|
56
|
+
const i = l.indexOf(':');
|
|
57
|
+
if (i < 1) continue;
|
|
58
|
+
last = l.slice(0, i).trim().toLowerCase();
|
|
59
|
+
const v = l.slice(i + 1).trim();
|
|
60
|
+
headers[last] = headers[last] ? `${headers[last]}, ${v}` : v;
|
|
61
|
+
}
|
|
62
|
+
const target = m[2];
|
|
63
|
+
const url = /^https?:\/\//i.test(target) ? target : `https://${headers.host || headers[':authority'] || 'localhost'}${target}`;
|
|
64
|
+
return { method: m[1], url, headers };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function cmdVerify(o) {
|
|
68
|
+
if (!o._[1]) throw new Error('verify needs a request file');
|
|
69
|
+
const req = parseRawRequest(await readFile(o._[1], 'utf8'));
|
|
70
|
+
const jwks = o.jwks ? JSON.parse(await readFile(o.jwks, 'utf8')) : null;
|
|
71
|
+
const staticKeys = jwks ? jwks.keys || [jwks] : [];
|
|
72
|
+
const now = o.now ? () => Number(o.now) : undefined;
|
|
73
|
+
const resolver = jwks ? { async resolve(url, keyid) { for (const k of staticKeys) if ((await jwkThumbprint(k)) === keyid || k.kid === keyid) return { key: { jwk: k }, url, bound: false }; throw new SigError('unknown-key', `key ${keyid} is not in ${o.jwks}`); } } : undefined;
|
|
74
|
+
const maxWindow = o['max-window'] === undefined ? undefined : Number(o['max-window']) === 0 ? Infinity : Number(o['max-window']);
|
|
75
|
+
const v = createVerifier({ maxWindow, profiles: o.visaTap ? ['web-bot-auth', 'visa-tap'] : ['web-bot-auth'], staticKeys, resolver, now, tapKeys: async (kid) => staticKeys.find((k) => k.kid === kid) || null, log: (m) => process.stderr.write(` note: ${m}\n`) });
|
|
76
|
+
const r = await v.verify(req);
|
|
77
|
+
const ranges = o.ranges ? await loadBotRanges({ log: (m) => process.stderr.write(`${m}\n`) }) : null;
|
|
78
|
+
const c = classify({ ua: req.headers['user-agent'], ip: o.ip, verification: r, ranges });
|
|
79
|
+
const d = decide(STORE_POLICY, { path: new URL(req.url).pathname, query: new URL(req.url).search }, c);
|
|
80
|
+
if (o.json) { process.stdout.write(JSON.stringify({ verification: r, classification: c, decision: d }, null, 2) + '\n'); return r.verified ? 0 : 1; }
|
|
81
|
+
const out = [`${req.method} ${req.url}${maxWindow === Infinity ? ' (window limit off)' : ''}`, ''];
|
|
82
|
+
if (r.status === 'unsigned') out.push('No Signature / Signature-Input headers: the request is not signed.');
|
|
83
|
+
for (const s of r.signatures) {
|
|
84
|
+
out.push(`Signature ${s.label} (tag ${s.tag ?? 'none'}): ${s.ok ? 'VERIFIED' : s.status.toUpperCase()}${s.reason ? `: ${s.reason}` : ''}`);
|
|
85
|
+
if (s.keyid) out.push(` keyid ${s.keyid}${s.alg ? `, ${s.alg}` : ''}`);
|
|
86
|
+
if (s.created != null) out.push(` created ${new Date(s.created * 1000).toISOString()}, expires ${new Date(s.expires * 1000).toISOString()} (${s.expires - s.created}s window)`);
|
|
87
|
+
if (s.covered) out.push(` covers ${s.covered.join(' ')}`);
|
|
88
|
+
for (const ck of s.checks || []) out.push(` - ${ck}`);
|
|
89
|
+
for (const p of s.directoryProblems || []) out.push(` ! directory: ${p}`);
|
|
90
|
+
if (s.identity) out.push(` identity ${s.identity}${s.known ? ` = ${s.known.name} (${s.known.operator})` : ''}${s.bound ? ', directory signed by the same key' : ''}`);
|
|
91
|
+
}
|
|
92
|
+
out.push('', `Class: ${c.class}${c.name ? ` (${c.name})` : ''}. ${c.evidence}`, `Default store policy here: ${d.action}${d.area ? ` (${d.area})` : ''}`);
|
|
93
|
+
process.stdout.write(out.join('\n') + '\n');
|
|
94
|
+
return r.verified ? 0 : 1;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function cmdDirectory(o) {
|
|
98
|
+
const url = o._[1];
|
|
99
|
+
if (!url) throw new Error('directory needs a URL');
|
|
100
|
+
let target = new URL(url);
|
|
101
|
+
if (target.pathname === '/') target = new URL(WELL_KNOWN, target);
|
|
102
|
+
const r = await fetch(target, { redirect: 'manual', headers: { accept: MEDIA_TYPE } });
|
|
103
|
+
const body = r.status === 200 ? await r.text() : '';
|
|
104
|
+
const d = await checkDirectory({ url: target.href, status: r.status, headers: r.headers, body });
|
|
105
|
+
const out = [`${target.href}: HTTP ${r.status}, ${d.keys.length} usable key(s)${d.bound ? ', signed by its own key (bound to this host)' : ', not signed (allowed; signing is recommended)'}`];
|
|
106
|
+
for (const k of d.keys) out.push(` ${k.thumbprint} ${k.jwk.kty}${k.jwk.crv ? `/${k.jwk.crv}` : ''}${k.alg ? ` ${k.alg}` : ''}`);
|
|
107
|
+
for (const p of d.problems) out.push(` ! ${p}`);
|
|
108
|
+
out.push(` cache-control max-age: ${d.maxAge ?? 'not set'}`);
|
|
109
|
+
process.stdout.write(out.join('\n') + '\n');
|
|
110
|
+
return d.keys.length && !d.problems.length ? 0 : 1;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function cmdKeygen(o) {
|
|
114
|
+
const dir = o.out || '.';
|
|
115
|
+
const pair = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
|
|
116
|
+
const priv = await crypto.subtle.exportKey('jwk', pair.privateKey);
|
|
117
|
+
const pub = await crypto.subtle.exportKey('jwk', pair.publicKey);
|
|
118
|
+
const kid = await jwkThumbprint(pub);
|
|
119
|
+
const publicJwk = { kty: pub.kty, crv: pub.crv, x: pub.x, kid, use: 'sig' };
|
|
120
|
+
await mkdir(dir, { recursive: true });
|
|
121
|
+
await writeFile(join(dir, 'private.jwk.json'), JSON.stringify({ kty: priv.kty, crv: priv.crv, x: priv.x, d: priv.d, kid }, null, 2) + '\n', { mode: 0o600 });
|
|
122
|
+
await writeFile(join(dir, 'http-message-signatures-directory.json'), JSON.stringify({ keys: [publicJwk] }, null, 2) + '\n');
|
|
123
|
+
process.stdout.write([`Key id (thumbprint): ${kid}`, `Wrote ${join(dir, 'private.jwk.json')} (keep secret, never commit)`, `Wrote ${join(dir, 'http-message-signatures-directory.json')}`, '', 'Publish the directory file at', ` https://YOUR-AGENT-DOMAIN${WELL_KNOWN}`, `with Content-Type: ${MEDIA_TYPE}, and send`, ' Signature-Agent: sig1="https://YOUR-AGENT-DOMAIN/.well-known/http-message-signatures-directory"', 'on every request (agent-traffic-gate sign shows the full headers).', ''].join('\n'));
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function cmdSign(o) {
|
|
128
|
+
const url = o._[1];
|
|
129
|
+
if (!url || !o.key || !o.agent) throw new Error('sign needs <url> --key <private.jwk.json> --agent <directory-url>');
|
|
130
|
+
const jwk = JSON.parse(await readFile(o.key, 'utf8'));
|
|
131
|
+
const ttl = Number(o.ttl || 300);
|
|
132
|
+
const created = Math.floor(Date.now() / 1000);
|
|
133
|
+
const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));
|
|
134
|
+
const method = (o.method || 'GET').toUpperCase();
|
|
135
|
+
const { base, ...h } = await signRequest({ method, url, headers: {} }, { jwk, signatureAgent: o.agent, created, expires: created + ttl, nonce, components: ['@authority', '@method', '@path', ['signature-agent', { key: 'sig1' }]] });
|
|
136
|
+
if (o.curl) process.stdout.write(`curl -i -X ${method} '${url}' ${Object.entries(h).map(([k, v]) => `-H '${k}: ${v.replace(/'/g, "'\\''")}'`).join(' ')}\n`);
|
|
137
|
+
else process.stdout.write(`${Object.entries(h).map(([k, v]) => `${k}: ${v}`).join('\n')}\n\n# signature base\n${base}\n`);
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function cmdPolicy(o) {
|
|
142
|
+
if (!o._[1]) { process.stdout.write(JSON.stringify(STORE_POLICY, null, 2) + '\n'); return 0; }
|
|
143
|
+
const p = JSON.parse(await readFile(o._[1], 'utf8'));
|
|
144
|
+
const problems = validatePolicy(p);
|
|
145
|
+
process.stdout.write(problems.length ? problems.map((x) => `! ${x}`).join('\n') + '\n' : 'Policy is valid.\n');
|
|
146
|
+
return problems.length ? 1 : 0;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function main() {
|
|
150
|
+
let o;
|
|
151
|
+
try { o = args(process.argv.slice(2)); } catch (e) { process.stderr.write(`${e.message}\n\n${HELP}`); return 2; }
|
|
152
|
+
const cmd = o._[0];
|
|
153
|
+
if (o.help || !cmd) { process.stdout.write(HELP); return o.help ? 0 : 2; }
|
|
154
|
+
try {
|
|
155
|
+
if (cmd === 'verify') return await cmdVerify(o);
|
|
156
|
+
if (cmd === 'directory') return await cmdDirectory(o);
|
|
157
|
+
if (cmd === 'keygen') return await cmdKeygen(o);
|
|
158
|
+
if (cmd === 'sign') return await cmdSign(o);
|
|
159
|
+
if (cmd === 'policy') return await cmdPolicy(o);
|
|
160
|
+
if (cmd === 'signers') { process.stdout.write(`${KNOWN_SIGNERS.map((s) => `${s.name} (${s.operator})\n ${s.urls.join('\n ')}\n ${s.note}\n ${s.docs}`).join('\n')}\n(checked ${CHECKED})\n`); return 0; }
|
|
161
|
+
process.stderr.write(`Unknown command ${cmd}\n\n${HELP}`);
|
|
162
|
+
return 2;
|
|
163
|
+
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); return 2; }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('agent-traffic-gate') || process.argv[1]?.endsWith('agent-traffic-gate.js')) main().then((c) => { process.exitCode = c; });
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-traffic-gate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Let real AI shopping agents in and keep fake bots out: verifies Web Bot Auth signatures (RFC 9421) from ChatGPT agent, Google-Agent and others, checks crawler IPs, and applies a store policy for checkout, cart and admin. Fetch and Express middleware plus a CLI.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"agent-traffic-gate": "bin/agent-traffic-gate.js"
|
|
8
|
+
},
|
|
9
|
+
"main": "src/index.js",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./src/index.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"bin",
|
|
15
|
+
"src",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"CHANGELOG.md"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "node --test test/*.test.js"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=20"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"ai-traffic-insights": "^0.1.0"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"web-bot-auth",
|
|
31
|
+
"http-message-signatures",
|
|
32
|
+
"rfc9421",
|
|
33
|
+
"ai-agents",
|
|
34
|
+
"agentic-commerce",
|
|
35
|
+
"bot-detection",
|
|
36
|
+
"bot-management",
|
|
37
|
+
"chatgpt-agent",
|
|
38
|
+
"signed-agents",
|
|
39
|
+
"trusted-agent-protocol",
|
|
40
|
+
"visa-tap",
|
|
41
|
+
"middleware",
|
|
42
|
+
"cloudflare-workers",
|
|
43
|
+
"nextjs-middleware",
|
|
44
|
+
"express",
|
|
45
|
+
"ecommerce"
|
|
46
|
+
],
|
|
47
|
+
"author": {
|
|
48
|
+
"name": "Ahmad Zia (Muhammad Ahmad Zia)",
|
|
49
|
+
"url": "https://www.ahmadzia.com"
|
|
50
|
+
},
|
|
51
|
+
"license": "MIT",
|
|
52
|
+
"homepage": "https://www.ahmadzia.com/tools/agent-traffic-gate",
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "git+https://github.com/MuhammadAhmadZia/agent-traffic-gate.git"
|
|
56
|
+
},
|
|
57
|
+
"bugs": {
|
|
58
|
+
"url": "https://github.com/MuhammadAhmadZia/agent-traffic-gate/issues"
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/agents.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Agents known to sign their requests with Web Bot Auth, from each operator's own documentation
|
|
2
|
+
// (checked 4 Dec 2026). A request is attributed to one of these only after its signature verifies
|
|
3
|
+
// against keys fetched from that URL; the name is a label for the verified URL, not a claim.
|
|
4
|
+
|
|
5
|
+
export const CHECKED = '2026-12-04';
|
|
6
|
+
|
|
7
|
+
export const KNOWN_SIGNERS = [
|
|
8
|
+
{
|
|
9
|
+
id: 'chatgpt-agent', name: 'ChatGPT agent (cloud browser)', operator: 'OpenAI', kind: 'user-agent',
|
|
10
|
+
urls: ['https://chatgpt.com/', 'https://chatgpt.com/.well-known/http-message-signatures-directory'],
|
|
11
|
+
note: 'Sends Signature-Agent: "https://chatgpt.com" (the legacy string form). Acts for a ChatGPT user, including shopping and checkout.',
|
|
12
|
+
docs: 'https://help.openai.com/en/articles/11845367',
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
id: 'google-agent', name: 'Google-Agent', operator: 'Google', kind: 'user-agent',
|
|
16
|
+
urls: ['https://agent.bot.goog/', 'https://agent.bot.goog/.well-known/http-message-signatures-directory'],
|
|
17
|
+
note: 'Experimental: only some Google-Agent requests are signed (label g). Google asks sites to keep IP and user-agent checks as a fallback.',
|
|
18
|
+
docs: 'https://developers.google.com/crawling/docs/crawlers-fetchers/web-bot-auth',
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
id: 'cloudflare-browser-run', name: 'Cloudflare Browser Run (Browser Rendering)', operator: 'Cloudflare', kind: 'browser-platform',
|
|
22
|
+
urls: ['https://web-bot-auth.cloudflare-browser-rendering-085.workers.dev/.well-known/http-message-signatures-directory'],
|
|
23
|
+
note: 'Remote browser used by many agents; the signature identifies the platform, not the end customer.',
|
|
24
|
+
docs: 'https://radar.cloudflare.com/bots/directory/cloudflare-browser-rendering',
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** The known signer for a resolved Signature-Agent URL, or null. */
|
|
29
|
+
export function knownSigner(url) {
|
|
30
|
+
if (!url) return null;
|
|
31
|
+
let u;
|
|
32
|
+
try { u = new URL(url); } catch { return null; }
|
|
33
|
+
const norm = (x) => { const v = new URL(x); return `${v.origin}${v.pathname}`; };
|
|
34
|
+
const key = `${u.origin}${u.pathname}`;
|
|
35
|
+
return KNOWN_SIGNERS.find((s) => s.urls.some((x) => norm(x) === key)) || null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Payment-network profiles built on HTTP Message Signatures.
|
|
39
|
+
// Visa Trusted Agent Protocol: tags agent-browser-auth (browsing) and agent-payer-auth (checkout),
|
|
40
|
+
// covers @authority and @path, needs a nonce, and the two timestamps must be at most 8 minutes apart.
|
|
41
|
+
// Keys come from Visa's agent registry by keyid, not from a Signature-Agent URL.
|
|
42
|
+
export const PROFILES = {
|
|
43
|
+
'web-bot-auth': { tags: ['web-bot-auth'], requireAny: ['@authority', '@target-uri'], maxWindow: 86400, requireNonce: false, needsAgentHeader: true },
|
|
44
|
+
'visa-tap': { tags: ['agent-browser-auth', 'agent-payer-auth'], requireAll: ['@authority', '@path'], maxWindow: 480, requireNonce: true, needsAgentHeader: false, intents: { 'agent-browser-auth': 'browse', 'agent-payer-auth': 'pay' } },
|
|
45
|
+
};
|