@fiderail/indexer 0.0.0-stage → 2.3.1
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/LICENSE +21 -0
- package/README.md +47 -2
- package/dist/bazaar-sync.d.ts +23 -0
- package/dist/bazaar-sync.js +151 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +30 -0
- package/dist/evm-adapter.d.ts +36 -0
- package/dist/evm-adapter.js +98 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexer.d.ts +112 -0
- package/dist/indexer.js +1043 -0
- package/dist/liveness-probe.d.ts +178 -0
- package/dist/liveness-probe.js +662 -0
- package/dist/svm-adapter.d.ts +41 -0
- package/dist/svm-adapter.js +485 -0
- package/package.json +57 -4
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
import dns from "node:dns/promises";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import { parseX402ChallengeWithMeta } from "@fiderail/guard";
|
|
4
|
+
const AIOHTTP_MAX_HEADER_BYTES = 8192;
|
|
5
|
+
const NODE_MAX_HEADER_BYTES = 16384;
|
|
6
|
+
const MAX_PROBE_RESPONSE_BYTES = 131072; // 128 KB
|
|
7
|
+
function isPrivateIpv4(ip) {
|
|
8
|
+
const parts = ip.split(".").map(Number);
|
|
9
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
const [a, b] = parts;
|
|
13
|
+
if (a === 0 || a === 10 || a === 127)
|
|
14
|
+
return true;
|
|
15
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
16
|
+
return true;
|
|
17
|
+
if (a === 169 && b === 254)
|
|
18
|
+
return true;
|
|
19
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
20
|
+
return true;
|
|
21
|
+
if (a === 192 && b === 168)
|
|
22
|
+
return true;
|
|
23
|
+
if (a === 198 && (b === 18 || b === 19))
|
|
24
|
+
return true;
|
|
25
|
+
if (a >= 224)
|
|
26
|
+
return true;
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
function isPrivateIpv6(ip) {
|
|
30
|
+
const lower = ip.toLowerCase();
|
|
31
|
+
if (lower.startsWith("::ffff:")) {
|
|
32
|
+
return isPrivateIpv4(lower.slice(7));
|
|
33
|
+
}
|
|
34
|
+
return (lower === "::1" ||
|
|
35
|
+
lower === "::" ||
|
|
36
|
+
lower.startsWith("fc") ||
|
|
37
|
+
lower.startsWith("fd") ||
|
|
38
|
+
lower.startsWith("fe80") ||
|
|
39
|
+
lower.startsWith("fe9") ||
|
|
40
|
+
lower.startsWith("fea") ||
|
|
41
|
+
lower.startsWith("feb") ||
|
|
42
|
+
lower.startsWith("ff"));
|
|
43
|
+
}
|
|
44
|
+
const MAX_URL_LENGTH = 2048;
|
|
45
|
+
const DANGEROUS_URL_CHARS_RE = /[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/;
|
|
46
|
+
const DANGEROUS_URL_ENCODED_RE = /%(?:00|0a|0d)/i;
|
|
47
|
+
export function isSafePublicHttpUrl(rawUrl, { allowPrivateHosts = false } = {}) {
|
|
48
|
+
if (typeof rawUrl !== "string")
|
|
49
|
+
return false;
|
|
50
|
+
const trimmed = rawUrl.trim();
|
|
51
|
+
if (!trimmed || trimmed.length > MAX_URL_LENGTH)
|
|
52
|
+
return false;
|
|
53
|
+
if (DANGEROUS_URL_CHARS_RE.test(trimmed) || DANGEROUS_URL_ENCODED_RE.test(trimmed)) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
let u;
|
|
57
|
+
try {
|
|
58
|
+
u = new URL(trimmed);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
if (u.protocol !== "http:" && u.protocol !== "https:")
|
|
64
|
+
return false;
|
|
65
|
+
if (u.username || u.password)
|
|
66
|
+
return false;
|
|
67
|
+
if (allowPrivateHosts)
|
|
68
|
+
return true;
|
|
69
|
+
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
70
|
+
if (!host || host === "localhost" || host.endsWith(".local") || host.endsWith(".internal")) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
const ipVer = net.isIP(host);
|
|
74
|
+
if (ipVer === 4)
|
|
75
|
+
return !isPrivateIpv4(host);
|
|
76
|
+
if (ipVer === 6)
|
|
77
|
+
return !isPrivateIpv6(host);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
export async function assertSafePublicUrlWithDns(rawUrl, { allowPrivateHosts = false, dnsLookup = dns.lookup, } = {}) {
|
|
81
|
+
if (!isSafePublicHttpUrl(rawUrl, { allowPrivateHosts })) {
|
|
82
|
+
return { safe: false, reason: "Blocked unsafe or private URL" };
|
|
83
|
+
}
|
|
84
|
+
if (allowPrivateHosts) {
|
|
85
|
+
return { safe: true };
|
|
86
|
+
}
|
|
87
|
+
const host = new URL(rawUrl).hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
88
|
+
if (net.isIP(host) !== 0) {
|
|
89
|
+
return { safe: true };
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
const records = await dnsLookup(host, { all: true });
|
|
93
|
+
if (!Array.isArray(records) || records.length === 0) {
|
|
94
|
+
return { safe: false, reason: "Blocked unresolvable target hostname" };
|
|
95
|
+
}
|
|
96
|
+
for (const r of records) {
|
|
97
|
+
const addr = String(r?.address || "").trim();
|
|
98
|
+
const ver = net.isIP(addr);
|
|
99
|
+
if (ver === 4 && isPrivateIpv4(addr)) {
|
|
100
|
+
return { safe: false, reason: "Blocked DNS resolution to private or loopback IP" };
|
|
101
|
+
}
|
|
102
|
+
if (ver === 6 && isPrivateIpv6(addr)) {
|
|
103
|
+
return { safe: false, reason: "Blocked DNS resolution to private or loopback IP" };
|
|
104
|
+
}
|
|
105
|
+
if (ver === 0) {
|
|
106
|
+
return { safe: false, reason: "Blocked invalid DNS record" };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { safe: true };
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return { safe: false, reason: "Blocked DNS resolution failure" };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function readResponseTextBounded(res, maxBytes = MAX_PROBE_RESPONSE_BYTES) {
|
|
116
|
+
if (!res)
|
|
117
|
+
return "";
|
|
118
|
+
if (res.body && typeof res.body.getReader === "function") {
|
|
119
|
+
const reader = res.body.getReader();
|
|
120
|
+
const chunks = [];
|
|
121
|
+
let total = 0;
|
|
122
|
+
try {
|
|
123
|
+
while (true) {
|
|
124
|
+
const { done, value } = await reader.read();
|
|
125
|
+
if (done)
|
|
126
|
+
break;
|
|
127
|
+
if (!value)
|
|
128
|
+
continue;
|
|
129
|
+
if (total + value.byteLength > maxBytes) {
|
|
130
|
+
const remaining = maxBytes - total;
|
|
131
|
+
if (remaining > 0) {
|
|
132
|
+
chunks.push(Buffer.from(value.subarray(0, remaining)));
|
|
133
|
+
total += remaining;
|
|
134
|
+
}
|
|
135
|
+
await reader.cancel().catch(() => { });
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
chunks.push(Buffer.from(value));
|
|
139
|
+
total += value.byteLength;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
reader.releaseLock?.();
|
|
144
|
+
}
|
|
145
|
+
return Buffer.concat(chunks, total).toString("utf8");
|
|
146
|
+
}
|
|
147
|
+
const raw = await res.text().catch(() => "");
|
|
148
|
+
const buf = Buffer.from(String(raw), "utf8");
|
|
149
|
+
return buf.byteLength <= maxBytes ? String(raw) : buf.subarray(0, maxBytes).toString("utf8");
|
|
150
|
+
}
|
|
151
|
+
export function createProxyFetch({ proxyUrl, proxyToken = "", baseFetch = globalThis.fetch, }) {
|
|
152
|
+
return async function proxiedFetch(targetUrl, init = {}) {
|
|
153
|
+
const forwardHeaders = {};
|
|
154
|
+
if (init.headers) {
|
|
155
|
+
const h = new Headers(init.headers);
|
|
156
|
+
for (const key of ["accept", "user-agent", "content-type"]) {
|
|
157
|
+
const val = h.get(key);
|
|
158
|
+
if (val)
|
|
159
|
+
forwardHeaders[key] = val;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const payload = {
|
|
163
|
+
url: String(targetUrl),
|
|
164
|
+
method: String(init.method || "GET").toUpperCase(),
|
|
165
|
+
headers: forwardHeaders,
|
|
166
|
+
body: typeof init.body === "string" ? init.body : undefined,
|
|
167
|
+
timeoutMs: 8000,
|
|
168
|
+
};
|
|
169
|
+
const proxyRes = await baseFetch(proxyUrl, {
|
|
170
|
+
method: "POST",
|
|
171
|
+
headers: {
|
|
172
|
+
"Content-Type": "application/json",
|
|
173
|
+
...(proxyToken ? { "X-FideRail-Proxy-Token": proxyToken } : {}),
|
|
174
|
+
},
|
|
175
|
+
body: JSON.stringify(payload),
|
|
176
|
+
signal: init.signal,
|
|
177
|
+
});
|
|
178
|
+
const envelope = (await proxyRes.json().catch(() => null));
|
|
179
|
+
if (!envelope || envelope.ok !== true) {
|
|
180
|
+
if (envelope?.isHeaderOverflow) {
|
|
181
|
+
throw new Error(`HeadersOverflow: ${envelope.error || "Response header overflow"}`);
|
|
182
|
+
}
|
|
183
|
+
const errMsg = envelope?.error || `HTTP ${proxyRes.status}`;
|
|
184
|
+
throw new Error(`Outbound probe proxy failed: ${errMsg}`);
|
|
185
|
+
}
|
|
186
|
+
const respHeaders = new Headers(envelope.headers || {});
|
|
187
|
+
const bodyStr = typeof envelope.bodyText === "string" ? envelope.bodyText : "";
|
|
188
|
+
const status = Number(envelope.status || 502);
|
|
189
|
+
return {
|
|
190
|
+
status,
|
|
191
|
+
ok: status >= 200 && status < 300,
|
|
192
|
+
headers: respHeaders,
|
|
193
|
+
async text() {
|
|
194
|
+
return bodyStr;
|
|
195
|
+
},
|
|
196
|
+
async json() {
|
|
197
|
+
return JSON.parse(bodyStr);
|
|
198
|
+
},
|
|
199
|
+
async arrayBuffer() {
|
|
200
|
+
const buf = Buffer.from(bodyStr, "utf8");
|
|
201
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function inspect402Payload({ resourceUrl, headers, bodyText, expectedChain = null, expectedAddress = null, catalogPriceUsdc = null, allowPrivateHosts = false, }) {
|
|
207
|
+
let bodyJson = null;
|
|
208
|
+
try {
|
|
209
|
+
bodyJson = bodyText ? JSON.parse(bodyText) : null;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
bodyJson = null;
|
|
213
|
+
}
|
|
214
|
+
const meta = parseX402ChallengeWithMeta(headers, bodyJson);
|
|
215
|
+
const diagnosticFlags = [];
|
|
216
|
+
if (!meta.hasPaymentRequiredHeader) {
|
|
217
|
+
diagnosticFlags.push("MISSING_PAYMENT_REQUIRED_HEADER");
|
|
218
|
+
}
|
|
219
|
+
if (meta.headerBytes !== null && meta.headerBytes > AIOHTTP_MAX_HEADER_BYTES) {
|
|
220
|
+
diagnosticFlags.push("HEADER_OVER_8KB_AIOHTTP");
|
|
221
|
+
}
|
|
222
|
+
if (meta.headerBytes !== null && meta.headerBytes > NODE_MAX_HEADER_BYTES) {
|
|
223
|
+
diagnosticFlags.push("HEADER_OVER_16KB_NODE");
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
const parsedUrl = new URL(resourceUrl);
|
|
227
|
+
if (parsedUrl.protocol === "http:" && !allowPrivateHosts) {
|
|
228
|
+
diagnosticFlags.push("HTTP_NON_HTTPS_RESOURCE");
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
// ignore URL parse error
|
|
233
|
+
}
|
|
234
|
+
const bazaarInfo = meta.challenge?.extensions?.bazaar?.info;
|
|
235
|
+
if (bazaarInfo && bazaarInfo.inputSchema && !bazaarInfo.input) {
|
|
236
|
+
diagnosticFlags.push("INPUT_SCHEMA_MISSING_INPUT");
|
|
237
|
+
}
|
|
238
|
+
let observedPriceUsdc = null;
|
|
239
|
+
if (expectedChain) {
|
|
240
|
+
const chainMatches = meta.options.filter((o) => o.chain === expectedChain);
|
|
241
|
+
if (chainMatches.length > 0) {
|
|
242
|
+
observedPriceUsdc = chainMatches[0].amountUsdc;
|
|
243
|
+
if (expectedAddress && !chainMatches.some((o) => o.payTo === expectedAddress)) {
|
|
244
|
+
diagnosticFlags.push("MISMATCH_PAYTO");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
else if (meta.options.length > 0) {
|
|
249
|
+
observedPriceUsdc = meta.options[0].amountUsdc;
|
|
250
|
+
}
|
|
251
|
+
if (catalogPriceUsdc !== null &&
|
|
252
|
+
catalogPriceUsdc !== undefined &&
|
|
253
|
+
observedPriceUsdc !== null &&
|
|
254
|
+
Number.isFinite(Number(catalogPriceUsdc))) {
|
|
255
|
+
const catPrice = Number(catalogPriceUsdc);
|
|
256
|
+
const threshold = Math.max(0.0001, catPrice * 0.05);
|
|
257
|
+
if (Math.abs(observedPriceUsdc - catPrice) > threshold) {
|
|
258
|
+
diagnosticFlags.push("PRICE_DRIFT");
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
meta,
|
|
263
|
+
headerBytes: meta.headerBytes,
|
|
264
|
+
aiohttpSafe: meta.headerBytes === null ? true : meta.headerBytes <= AIOHTTP_MAX_HEADER_BYTES,
|
|
265
|
+
nodeHttpSafe: meta.headerBytes === null ? true : meta.headerBytes <= NODE_MAX_HEADER_BYTES,
|
|
266
|
+
observedPriceUsdc,
|
|
267
|
+
diagnosticFlags,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
export async function probeSingleEndpoint({ chain, address, resourceUrl, method = "GET", catalogPriceUsdc = null, fetchImpl = globalThis.fetch, timeoutMs = 8000, allowPrivateHosts = false, proxyUrl = "", proxyToken = "", dnsLookup = dns.lookup, }) {
|
|
271
|
+
const urlCheck = await assertSafePublicUrlWithDns(resourceUrl, { allowPrivateHosts, dnsLookup });
|
|
272
|
+
if (!urlCheck.safe) {
|
|
273
|
+
return {
|
|
274
|
+
chain,
|
|
275
|
+
address,
|
|
276
|
+
resourceUrl,
|
|
277
|
+
livenessStatus: "DOWN",
|
|
278
|
+
httpStatus: null,
|
|
279
|
+
latencyMs: 0,
|
|
280
|
+
headerBytes: null,
|
|
281
|
+
observedPriceUsdc: null,
|
|
282
|
+
diagnosticFlags: [],
|
|
283
|
+
error: urlCheck.reason || "Blocked URL",
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
const effectiveFetch = proxyUrl
|
|
287
|
+
? createProxyFetch({ proxyUrl, proxyToken, baseFetch: fetchImpl })
|
|
288
|
+
: fetchImpl;
|
|
289
|
+
const probeMethod = String(method || "GET").toUpperCase() === "POST" ? "POST" : "GET";
|
|
290
|
+
const reqInit = {
|
|
291
|
+
method: probeMethod,
|
|
292
|
+
headers: {
|
|
293
|
+
Accept: "application/json",
|
|
294
|
+
"User-Agent": "FideRail-LivenessProbe/2.0",
|
|
295
|
+
...(probeMethod === "POST" ? { "Content-Type": "application/json" } : {}),
|
|
296
|
+
},
|
|
297
|
+
...(probeMethod === "POST" ? { body: "{}" } : {}),
|
|
298
|
+
redirect: "manual",
|
|
299
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
300
|
+
};
|
|
301
|
+
const t0 = Date.now();
|
|
302
|
+
try {
|
|
303
|
+
const res = await effectiveFetch(resourceUrl, reqInit);
|
|
304
|
+
const latencyMs = Date.now() - t0;
|
|
305
|
+
const status = res.status;
|
|
306
|
+
if (status === 402) {
|
|
307
|
+
const txt = await readResponseTextBounded(res, MAX_PROBE_RESPONSE_BYTES);
|
|
308
|
+
const inspection = inspect402Payload({
|
|
309
|
+
resourceUrl,
|
|
310
|
+
headers: res.headers,
|
|
311
|
+
bodyText: txt,
|
|
312
|
+
expectedChain: chain,
|
|
313
|
+
expectedAddress: address,
|
|
314
|
+
catalogPriceUsdc,
|
|
315
|
+
allowPrivateHosts,
|
|
316
|
+
});
|
|
317
|
+
if (inspection.diagnosticFlags.includes("MISMATCH_PAYTO")) {
|
|
318
|
+
return {
|
|
319
|
+
chain,
|
|
320
|
+
address,
|
|
321
|
+
resourceUrl,
|
|
322
|
+
livenessStatus: "MISMATCH_PAYTO",
|
|
323
|
+
httpStatus: status,
|
|
324
|
+
latencyMs,
|
|
325
|
+
headerBytes: inspection.headerBytes,
|
|
326
|
+
observedPriceUsdc: inspection.observedPriceUsdc,
|
|
327
|
+
diagnosticFlags: inspection.diagnosticFlags,
|
|
328
|
+
error: `402 payTo mismatch for ${chain}`,
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
chain,
|
|
333
|
+
address,
|
|
334
|
+
resourceUrl,
|
|
335
|
+
livenessStatus: "LIVE_402",
|
|
336
|
+
httpStatus: status,
|
|
337
|
+
latencyMs,
|
|
338
|
+
headerBytes: inspection.headerBytes,
|
|
339
|
+
observedPriceUsdc: inspection.observedPriceUsdc,
|
|
340
|
+
diagnosticFlags: inspection.diagnosticFlags,
|
|
341
|
+
error: null,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
await res.body?.cancel?.().catch(() => { });
|
|
345
|
+
if (status >= 200 && status < 300) {
|
|
346
|
+
return {
|
|
347
|
+
chain,
|
|
348
|
+
address,
|
|
349
|
+
resourceUrl,
|
|
350
|
+
livenessStatus: "LIVE_200",
|
|
351
|
+
httpStatus: status,
|
|
352
|
+
latencyMs,
|
|
353
|
+
headerBytes: null,
|
|
354
|
+
observedPriceUsdc: null,
|
|
355
|
+
diagnosticFlags: [],
|
|
356
|
+
error: null,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
if (status === 400 || status === 405 || status === 422 || (status >= 300 && status < 400)) {
|
|
360
|
+
return {
|
|
361
|
+
chain,
|
|
362
|
+
address,
|
|
363
|
+
resourceUrl,
|
|
364
|
+
livenessStatus: "LIVE_REACHABLE",
|
|
365
|
+
httpStatus: status,
|
|
366
|
+
latencyMs,
|
|
367
|
+
headerBytes: null,
|
|
368
|
+
observedPriceUsdc: null,
|
|
369
|
+
diagnosticFlags: [],
|
|
370
|
+
error: null,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
if (status === 403 || status === 429) {
|
|
374
|
+
return {
|
|
375
|
+
chain,
|
|
376
|
+
address,
|
|
377
|
+
resourceUrl,
|
|
378
|
+
livenessStatus: "DEGRADED",
|
|
379
|
+
httpStatus: status,
|
|
380
|
+
latencyMs,
|
|
381
|
+
headerBytes: null,
|
|
382
|
+
observedPriceUsdc: null,
|
|
383
|
+
diagnosticFlags: [],
|
|
384
|
+
error: `HTTP ${status}`,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
chain,
|
|
389
|
+
address,
|
|
390
|
+
resourceUrl,
|
|
391
|
+
livenessStatus: "DOWN",
|
|
392
|
+
httpStatus: status,
|
|
393
|
+
latencyMs,
|
|
394
|
+
headerBytes: null,
|
|
395
|
+
observedPriceUsdc: null,
|
|
396
|
+
diagnosticFlags: [],
|
|
397
|
+
error: `HTTP ${status}`,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
catch (err) {
|
|
401
|
+
return {
|
|
402
|
+
chain,
|
|
403
|
+
address,
|
|
404
|
+
resourceUrl,
|
|
405
|
+
livenessStatus: "DOWN",
|
|
406
|
+
httpStatus: null,
|
|
407
|
+
latencyMs: Date.now() - t0,
|
|
408
|
+
headerBytes: null,
|
|
409
|
+
observedPriceUsdc: null,
|
|
410
|
+
diagnosticFlags: [],
|
|
411
|
+
error: err.message,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const DIAGNOSTIC_RECOMMENDATIONS = Object.freeze({
|
|
416
|
+
HEADER_OVER_8KB_AIOHTTP: "PAYMENT-REQUIRED header exceeds 8 KB; Python aiohttp buyers may fail (x402#3803). Trim Bazaar examples/schemas.",
|
|
417
|
+
HEADER_OVER_16KB_NODE: "PAYMENT-REQUIRED header exceeds 16 KB; Node.js default header limit will crash buyers (x402#3803).",
|
|
418
|
+
MISSING_PAYMENT_REQUIRED_HEADER: "Include Base64-encoded PAYMENT-REQUIRED header alongside JSON body for x402 v2 compatibility.",
|
|
419
|
+
HTTP_NON_HTTPS_RESOURCE: "Expose HTTPS resource URLs behind TLS proxy ('trust proxy') so Bazaar indexers accept the endpoint.",
|
|
420
|
+
INPUT_SCHEMA_MISSING_INPUT: "extensions.bazaar.info declares inputSchema without an example 'input' object; Coinbase Bazaar validation may silently drop indexing.",
|
|
421
|
+
PRICE_DRIFT: "Observed 402 price differs by >5% from previously indexed catalog price.",
|
|
422
|
+
MISMATCH_PAYTO: "Observed 402 payTo address does not match expected catalog address.",
|
|
423
|
+
EMPTY_OR_UNSUPPORTED_ACCEPTS: "HTTP 402 response lacks valid Base, Solana, Arbitrum, or Polygon payment options in accepts[].",
|
|
424
|
+
});
|
|
425
|
+
export async function diagnoseX402Endpoint({ url, method = "GET", catalogPriceUsdc = null, fetchImpl = globalThis.fetch, timeoutMs = 8000, allowPrivateHosts = false, proxyUrl = "", proxyToken = "", dnsLookup = dns.lookup, }) {
|
|
426
|
+
const checkedAt = new Date().toISOString();
|
|
427
|
+
const urlCheck = await assertSafePublicUrlWithDns(url, { allowPrivateHosts, dnsLookup });
|
|
428
|
+
if (!urlCheck.safe) {
|
|
429
|
+
return {
|
|
430
|
+
url,
|
|
431
|
+
method: String(method || "GET").toUpperCase(),
|
|
432
|
+
grade: "F",
|
|
433
|
+
healthy: false,
|
|
434
|
+
livenessStatus: "DOWN",
|
|
435
|
+
httpStatus: null,
|
|
436
|
+
latencyMs: 0,
|
|
437
|
+
headerBytes: null,
|
|
438
|
+
aiohttpSafe: null,
|
|
439
|
+
nodeHttpSafe: null,
|
|
440
|
+
observedPriceUsdc: null,
|
|
441
|
+
accepts: [],
|
|
442
|
+
diagnosticFlags: ["UNSAFE_OR_INVALID_URL"],
|
|
443
|
+
recommendations: ["Provide a valid public http(s) URL."],
|
|
444
|
+
wellKnownFound: false,
|
|
445
|
+
wellKnownDescriptor: null,
|
|
446
|
+
error: urlCheck.reason || "Blocked URL",
|
|
447
|
+
checkedAt,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
const effectiveFetch = proxyUrl
|
|
451
|
+
? createProxyFetch({ proxyUrl, proxyToken, baseFetch: fetchImpl })
|
|
452
|
+
: fetchImpl;
|
|
453
|
+
const probeMethod = String(method || "GET").toUpperCase() === "POST" ? "POST" : "GET";
|
|
454
|
+
const reqInit = {
|
|
455
|
+
method: probeMethod,
|
|
456
|
+
headers: {
|
|
457
|
+
Accept: "application/json",
|
|
458
|
+
"User-Agent": "FideRail-Diagnostic/2.0",
|
|
459
|
+
...(probeMethod === "POST" ? { "Content-Type": "application/json" } : {}),
|
|
460
|
+
},
|
|
461
|
+
...(probeMethod === "POST" ? { body: "{}" } : {}),
|
|
462
|
+
redirect: "manual",
|
|
463
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
464
|
+
};
|
|
465
|
+
let wellKnownFound = false;
|
|
466
|
+
let wellKnownDescriptor = null;
|
|
467
|
+
try {
|
|
468
|
+
const origin = new URL(url).origin;
|
|
469
|
+
const wkRes = await effectiveFetch(`${origin}/.well-known/fiderail-service.json`, {
|
|
470
|
+
method: "GET",
|
|
471
|
+
headers: { Accept: "application/json", "User-Agent": "FideRail-Diagnostic/2.0" },
|
|
472
|
+
signal: AbortSignal.timeout(Math.min(3000, timeoutMs)),
|
|
473
|
+
});
|
|
474
|
+
if (wkRes.ok) {
|
|
475
|
+
const wkText = await readResponseTextBounded(wkRes, 32768);
|
|
476
|
+
const parsed = wkText ? JSON.parse(wkText) : null;
|
|
477
|
+
if (parsed && typeof parsed === "object") {
|
|
478
|
+
wellKnownFound = true;
|
|
479
|
+
wellKnownDescriptor = parsed;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
await wkRes.body?.cancel?.().catch(() => { });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
// Optional metadata endpoint
|
|
488
|
+
}
|
|
489
|
+
const t0 = Date.now();
|
|
490
|
+
try {
|
|
491
|
+
const res = await effectiveFetch(url, reqInit);
|
|
492
|
+
const latencyMs = Date.now() - t0;
|
|
493
|
+
const httpStatus = res.status;
|
|
494
|
+
if (httpStatus === 402) {
|
|
495
|
+
const txt = await readResponseTextBounded(res, MAX_PROBE_RESPONSE_BYTES);
|
|
496
|
+
const inspection = inspect402Payload({
|
|
497
|
+
resourceUrl: url,
|
|
498
|
+
headers: res.headers,
|
|
499
|
+
bodyText: txt,
|
|
500
|
+
catalogPriceUsdc,
|
|
501
|
+
allowPrivateHosts,
|
|
502
|
+
});
|
|
503
|
+
const flags = [...inspection.diagnosticFlags];
|
|
504
|
+
if (inspection.meta.options.length === 0) {
|
|
505
|
+
flags.push("EMPTY_OR_UNSUPPORTED_ACCEPTS");
|
|
506
|
+
}
|
|
507
|
+
let grade = "A";
|
|
508
|
+
if (flags.includes("EMPTY_OR_UNSUPPORTED_ACCEPTS") || flags.includes("MISMATCH_PAYTO")) {
|
|
509
|
+
grade = "F";
|
|
510
|
+
}
|
|
511
|
+
else if (flags.includes("HEADER_OVER_8KB_AIOHTTP") ||
|
|
512
|
+
flags.includes("HEADER_OVER_16KB_NODE") ||
|
|
513
|
+
flags.includes("HTTP_NON_HTTPS_RESOURCE")) {
|
|
514
|
+
grade = "C";
|
|
515
|
+
}
|
|
516
|
+
else if (flags.length > 0) {
|
|
517
|
+
grade = "B";
|
|
518
|
+
}
|
|
519
|
+
return {
|
|
520
|
+
url,
|
|
521
|
+
method: probeMethod,
|
|
522
|
+
grade,
|
|
523
|
+
healthy: grade !== "F",
|
|
524
|
+
livenessStatus: "LIVE_402",
|
|
525
|
+
httpStatus,
|
|
526
|
+
latencyMs,
|
|
527
|
+
headerBytes: inspection.headerBytes,
|
|
528
|
+
aiohttpSafe: inspection.aiohttpSafe,
|
|
529
|
+
nodeHttpSafe: inspection.nodeHttpSafe,
|
|
530
|
+
observedPriceUsdc: inspection.observedPriceUsdc,
|
|
531
|
+
accepts: inspection.meta.options.map((o) => ({
|
|
532
|
+
chain: o.chain,
|
|
533
|
+
network: o.network,
|
|
534
|
+
payTo: o.payTo,
|
|
535
|
+
asset: o.asset,
|
|
536
|
+
assetSymbol: o.assetSymbol,
|
|
537
|
+
amountUsdc: o.amountUsdc,
|
|
538
|
+
scheme: o.scheme,
|
|
539
|
+
})),
|
|
540
|
+
diagnosticFlags: flags,
|
|
541
|
+
recommendations: flags.map((f) => DIAGNOSTIC_RECOMMENDATIONS[f]).filter(Boolean),
|
|
542
|
+
wellKnownFound,
|
|
543
|
+
wellKnownDescriptor,
|
|
544
|
+
error: null,
|
|
545
|
+
checkedAt,
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
await res.body?.cancel?.().catch(() => { });
|
|
549
|
+
const isReachable = httpStatus >= 200 && httpStatus < 500 && httpStatus !== 403 && httpStatus !== 429;
|
|
550
|
+
const livenessStatus = httpStatus >= 200 && httpStatus < 300
|
|
551
|
+
? "LIVE_200"
|
|
552
|
+
: isReachable
|
|
553
|
+
? "LIVE_REACHABLE"
|
|
554
|
+
: httpStatus === 403 || httpStatus === 429
|
|
555
|
+
? "DEGRADED"
|
|
556
|
+
: "DOWN";
|
|
557
|
+
const grade = livenessStatus === "DOWN" ? "F" : "C";
|
|
558
|
+
return {
|
|
559
|
+
url,
|
|
560
|
+
method: probeMethod,
|
|
561
|
+
grade,
|
|
562
|
+
healthy: livenessStatus !== "DOWN",
|
|
563
|
+
livenessStatus,
|
|
564
|
+
httpStatus,
|
|
565
|
+
latencyMs,
|
|
566
|
+
headerBytes: null,
|
|
567
|
+
aiohttpSafe: null,
|
|
568
|
+
nodeHttpSafe: null,
|
|
569
|
+
observedPriceUsdc: null,
|
|
570
|
+
accepts: [],
|
|
571
|
+
diagnosticFlags: [],
|
|
572
|
+
recommendations: [
|
|
573
|
+
livenessStatus === "DOWN"
|
|
574
|
+
? "Endpoint returned an error or is unreachable."
|
|
575
|
+
: "Endpoint did not return HTTP 402 Payment Required on unauthenticated probe.",
|
|
576
|
+
],
|
|
577
|
+
wellKnownFound,
|
|
578
|
+
wellKnownDescriptor,
|
|
579
|
+
error: livenessStatus === "DOWN" ? `HTTP ${httpStatus}` : null,
|
|
580
|
+
checkedAt,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
catch (err) {
|
|
584
|
+
const errDetail = `${err?.message || ""} ${err?.cause?.code || ""} ${err?.cause?.message || ""}`;
|
|
585
|
+
const isHeaderOverflow = /HeadersOverflow|HPE_HEADER_OVERFLOW|header.*overflow/i.test(errDetail);
|
|
586
|
+
const flags = isHeaderOverflow ? ["HEADER_OVER_8KB_AIOHTTP", "HEADER_OVER_16KB_NODE"] : [];
|
|
587
|
+
return {
|
|
588
|
+
url,
|
|
589
|
+
method: probeMethod,
|
|
590
|
+
grade: isHeaderOverflow ? "C" : "F",
|
|
591
|
+
healthy: false,
|
|
592
|
+
livenessStatus: "DOWN",
|
|
593
|
+
httpStatus: null,
|
|
594
|
+
latencyMs: Date.now() - t0,
|
|
595
|
+
headerBytes: null,
|
|
596
|
+
aiohttpSafe: isHeaderOverflow ? false : null,
|
|
597
|
+
nodeHttpSafe: isHeaderOverflow ? false : null,
|
|
598
|
+
observedPriceUsdc: null,
|
|
599
|
+
accepts: [],
|
|
600
|
+
diagnosticFlags: flags,
|
|
601
|
+
recommendations: isHeaderOverflow
|
|
602
|
+
? flags.map((f) => DIAGNOSTIC_RECOMMENDATIONS[f]).filter(Boolean)
|
|
603
|
+
: ["Check DNS, TLS certificate, and public HTTP reachability."],
|
|
604
|
+
wellKnownFound,
|
|
605
|
+
wellKnownDescriptor,
|
|
606
|
+
error: isHeaderOverflow
|
|
607
|
+
? `Response header overflow (>16KB Node limit): ${err.message}`
|
|
608
|
+
: err.message,
|
|
609
|
+
checkedAt,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
export async function runLivenessProbeBatch({ repo, limit = 30, concurrency = 4, fetchImpl = globalThis.fetch, timeoutMs = 8000, allowPrivateHosts = false, proxyUrl = "", proxyToken = "", dnsLookup = dns.lookup, }) {
|
|
614
|
+
const targets = await repo.listServicesToProbe({ limit });
|
|
615
|
+
if (targets.length === 0) {
|
|
616
|
+
await repo.setState("liveness_last_run_at", new Date().toISOString());
|
|
617
|
+
await repo.setState("liveness_last_probed", "0");
|
|
618
|
+
await repo.setState("liveness_last_healthy", "0");
|
|
619
|
+
await repo.setState("liveness_last_error", "");
|
|
620
|
+
return { probed: 0, healthy: 0, downOrDegraded: 0 };
|
|
621
|
+
}
|
|
622
|
+
let healthy = 0;
|
|
623
|
+
let downOrDegraded = 0;
|
|
624
|
+
const maxConc = Math.max(1, Number(concurrency) || 4);
|
|
625
|
+
for (let i = 0; i < targets.length; i += maxConc) {
|
|
626
|
+
const slice = targets.slice(i, i + maxConc);
|
|
627
|
+
const results = await Promise.all(slice.map((t) => probeSingleEndpoint({
|
|
628
|
+
chain: t.chain,
|
|
629
|
+
address: t.address,
|
|
630
|
+
resourceUrl: t.resourceUrl,
|
|
631
|
+
method: t.method,
|
|
632
|
+
catalogPriceUsdc: t.catalogPriceUsdc ?? null,
|
|
633
|
+
fetchImpl,
|
|
634
|
+
timeoutMs,
|
|
635
|
+
allowPrivateHosts,
|
|
636
|
+
proxyUrl,
|
|
637
|
+
proxyToken,
|
|
638
|
+
dnsLookup,
|
|
639
|
+
})));
|
|
640
|
+
for (const r of results) {
|
|
641
|
+
await repo.recordLivenessProbe(r);
|
|
642
|
+
if (r.livenessStatus === "LIVE_402" ||
|
|
643
|
+
r.livenessStatus === "LIVE_200" ||
|
|
644
|
+
r.livenessStatus === "LIVE_REACHABLE") {
|
|
645
|
+
healthy += 1;
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
downOrDegraded += 1;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
await repo.setState("liveness_last_run_at", new Date().toISOString());
|
|
653
|
+
await repo.setState("liveness_last_probed", String(targets.length));
|
|
654
|
+
await repo.setState("liveness_last_healthy", String(healthy));
|
|
655
|
+
await repo.setState("liveness_last_error", "");
|
|
656
|
+
return {
|
|
657
|
+
probed: targets.length,
|
|
658
|
+
healthy,
|
|
659
|
+
downOrDegraded,
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
//# sourceMappingURL=liveness-probe.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type AssetSymbol } from "@fiderail/spec";
|
|
2
|
+
export declare const SOL_USDC_MINT: string;
|
|
3
|
+
export declare const SOL_USDT_MINT: string;
|
|
4
|
+
export declare const SOL_MEMO_PROGRAMS: Set<string>;
|
|
5
|
+
export declare const SOL_TOKEN_PROGRAMS: Set<string>;
|
|
6
|
+
export interface SolanaTarget {
|
|
7
|
+
label: string;
|
|
8
|
+
address: string;
|
|
9
|
+
channel?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare const DEFAULT_SOLANA_TARGETS: SolanaTarget[];
|
|
12
|
+
export interface ParsedSolanaStablecoinTransfer {
|
|
13
|
+
eventIndex: number;
|
|
14
|
+
assetContract: string;
|
|
15
|
+
assetSymbol: AssetSymbol;
|
|
16
|
+
amountRaw: string;
|
|
17
|
+
amountDecimal: number;
|
|
18
|
+
amountUsd: number;
|
|
19
|
+
amountUsdc: number;
|
|
20
|
+
payer: string;
|
|
21
|
+
payee: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Parses ALL recognized Solana stablecoin transfers (USDC + USDT) from a parsed transaction.
|
|
25
|
+
*
|
|
26
|
+
* Strategy:
|
|
27
|
+
* 1. Instruction-level SPL Token / Token-2022 `transfer` & `transferChecked` parsing (outer + inner CPI),
|
|
28
|
+
* resolving token account owners via `accountKeys` + `loadedAddresses` + token balance metadata.
|
|
29
|
+
* Accurately preserves multi-payer `x402:batch` settlements, multi-receiver fee splits,
|
|
30
|
+
* and true self-transfers while collapsing acyclic zero-delta pass-through routers.
|
|
31
|
+
* 2. Deterministic multi-sender/multi-receiver balance-delta fallback for minimal transactions
|
|
32
|
+
* without parsed instruction / accountKey tables.
|
|
33
|
+
* 3. Strict self-transfer fallback that NEVER misclassifies non-stablecoin SPL tokens as USDC.
|
|
34
|
+
*/
|
|
35
|
+
export declare function parseSolanaStablecoinTransfers(tx: Record<string, any> | null | undefined): ParsedSolanaStablecoinTransfer[];
|
|
36
|
+
/**
|
|
37
|
+
* Backward-compatible single-transfer parser (prefers USDC, falls back to USDT).
|
|
38
|
+
*/
|
|
39
|
+
export declare function parseSolanaUsdcTransfer(tx: Record<string, any> | null | undefined): ParsedSolanaStablecoinTransfer | null;
|
|
40
|
+
export declare function hasSolanaMemo(tx: Record<string, any> | null | undefined): boolean;
|
|
41
|
+
//# sourceMappingURL=svm-adapter.d.ts.map
|