-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
247 lines (216 loc) · 7.38 KB
/
index.js
File metadata and controls
247 lines (216 loc) · 7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* @agentscore/x402-gate
* Trust-gate your x402 API. Check agent reputation before accepting payment.
*
* Usage:
* import { withTrustGate } from "@agentscore/x402-gate";
* export const GET = withTrustGate(handler, { minScore: 40 });
*/
const DEFAULT_API = "https://agentscores.xyz/api/score";
const DEFAULT_TTL = 5 * 60 * 1000; // 5 minutes
// In-memory cache: agentName -> { score, grade, expires }
const cache = new Map();
function getCached(name) {
const entry = cache.get(name);
if (!entry) return null;
if (Date.now() > entry.expires) {
cache.delete(name);
return null;
}
return entry;
}
function setCache(name, score, grade, ttl) {
cache.set(name, { score, grade, expires: Date.now() + ttl });
}
async function fetchScore(agentName, apiUrl) {
const url = `${apiUrl}?name=${encodeURIComponent(agentName)}`;
const res = await fetch(url);
if (!res.ok) return null;
const data = await res.json();
if (data.agent) return { score: data.agent.score, grade: data.agent.grade };
return null;
}
function extractAgentName(request) {
// Priority: X-Agent-Name header > x-agent-name query param > null
const headerName =
request.headers.get("X-Agent-Name") ||
request.headers.get("x-agent-name");
if (headerName) return headerName;
const url = new URL(request.url);
return url.searchParams.get("x-agent-name") || null;
}
function jsonResponse(body, status, extraHeaders = {}) {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json", ...extraHeaders },
});
}
/**
* Wrap any Next.js route handler with trust gating.
*
* @param {Function} handler - Your route handler (request, context) => Response
* @param {Object} options
* @param {number} options.minScore - Minimum trust score (0-100) to allow access
* @param {"block"|"warn"|"surcharge"} [options.action="block"] - What to do when score is below threshold
* @param {number} [options.surchargeMultiplier=2] - Price multiplier for low-trust agents (surcharge mode)
* @param {boolean} [options.allowUnknown=true] - Allow agents with no score data
* @param {string} [options.apiUrl] - AgentScore API URL (default: https://agentscores.xyz/api/score)
* @param {number} [options.cacheTtl] - Cache TTL in ms (default: 5 minutes)
* @returns {Function} Wrapped handler
*/
function withTrustGate(handler, options = {}) {
const {
minScore = 0,
action = "block",
surchargeMultiplier = 2,
allowUnknown = true,
apiUrl = DEFAULT_API,
cacheTtl = DEFAULT_TTL,
} = options;
return async function trustGatedHandler(request, context) {
const agentName = extractAgentName(request);
// No agent name provided — pass through (human users)
if (!agentName) {
return handler(request, context);
}
// Check cache first
let result = getCached(agentName);
// Fetch if not cached
if (!result) {
result = await fetchScore(agentName, apiUrl);
if (result) {
setCache(agentName, result.score, result.grade, cacheTtl);
}
}
// Unknown agent (no data found)
if (!result) {
if (!allowUnknown) {
return jsonResponse(
{
error: "trust_unknown",
message: `Agent "${agentName}" has no trust score. Access denied.`,
register: "https://agentscores.xyz",
},
403,
{ "X-AgentScore": "unknown", "X-AgentScore-Action": "blocked" }
);
}
// Allow unknown agents through with warning headers
const response = await handler(request, context);
const newResponse = new Response(response.body, response);
newResponse.headers.set("X-AgentScore", "unknown");
newResponse.headers.set("X-AgentScore-Action", "passed");
return newResponse;
}
const { score, grade } = result;
const trusted = score >= minScore;
// BLOCK mode
if (!trusted && action === "block") {
return jsonResponse(
{
error: "trust_insufficient",
message: `Agent "${agentName}" scored ${score}/100 (${grade}). Minimum required: ${minScore}.`,
score,
grade,
required: minScore,
improve: "https://agentscores.xyz",
},
403,
{
"X-AgentScore": String(score),
"X-AgentScore-Grade": grade,
"X-AgentScore-Action": "blocked",
}
);
}
// Execute the handler
const response = await handler(request, context);
const newResponse = new Response(response.body, response);
// Add trust headers to all responses
newResponse.headers.set("X-AgentScore", String(score));
newResponse.headers.set("X-AgentScore-Grade", grade);
// WARN mode — serve but add warning
if (!trusted && action === "warn") {
newResponse.headers.set("X-AgentScore-Action", "warning");
newResponse.headers.set(
"X-AgentScore-Warning",
`Agent scored ${score}/100. Minimum recommended: ${minScore}.`
);
return newResponse;
}
// SURCHARGE mode — add surcharge header for payment layer to read
if (!trusted && action === "surcharge") {
newResponse.headers.set("X-AgentScore-Action", "surcharge");
newResponse.headers.set(
"X-AgentScore-Surcharge",
String(surchargeMultiplier)
);
return newResponse;
}
// Trusted — pass through with score headers
newResponse.headers.set("X-AgentScore-Action", "trusted");
return newResponse;
};
}
/**
* Express/Connect-style middleware for trust gating.
*
* @param {Object} options - Same options as withTrustGate
* @returns {Function} Express middleware (req, res, next)
*/
function trustGateMiddleware(options = {}) {
const {
minScore = 0,
action = "block",
surchargeMultiplier = 2,
allowUnknown = true,
apiUrl = DEFAULT_API,
cacheTtl = DEFAULT_TTL,
} = options;
return async function (req, res, next) {
const agentName =
req.headers["x-agent-name"] ||
req.query?.["x-agent-name"] ||
null;
if (!agentName) return next();
let result = getCached(agentName);
if (!result) {
result = await fetchScore(agentName, apiUrl);
if (result) setCache(agentName, result.score, result.grade, cacheTtl);
}
if (!result) {
if (!allowUnknown) {
return res.status(403).json({
error: "trust_unknown",
message: `Agent "${agentName}" has no trust score. Access denied.`,
register: "https://agentscores.xyz",
});
}
res.set("X-AgentScore", "unknown");
return next();
}
const { score, grade } = result;
res.set("X-AgentScore", String(score));
res.set("X-AgentScore-Grade", grade);
if (score < minScore && action === "block") {
return res.status(403).json({
error: "trust_insufficient",
message: `Agent "${agentName}" scored ${score}/100 (${grade}). Minimum required: ${minScore}.`,
score,
grade,
required: minScore,
improve: "https://agentscores.xyz",
});
}
if (score < minScore && action === "warn") {
res.set("X-AgentScore-Action", "warning");
} else if (score < minScore && action === "surcharge") {
res.set("X-AgentScore-Action", "surcharge");
res.set("X-AgentScore-Surcharge", String(surchargeMultiplier));
} else {
res.set("X-AgentScore-Action", "trusted");
}
next();
};
}
module.exports = { withTrustGate, trustGateMiddleware };