@wasit-dev/core 0.6.0 → 0.8.0-beta.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/README.md +12 -4
- package/dist/baseline.d.ts +109 -0
- package/dist/baseline.js +351 -0
- package/dist/catalogue.d.ts +10 -0
- package/dist/catalogue.js +69 -3
- package/dist/check.d.ts +78 -2
- package/dist/check.js +69 -10
- package/dist/ci-report.d.ts +74 -0
- package/dist/ci-report.js +391 -0
- package/dist/config.d.ts +205 -0
- package/dist/config.js +1011 -0
- package/dist/denied-env.d.ts +33 -0
- package/dist/denied-env.js +86 -0
- package/dist/errors.d.ts +44 -1
- package/dist/errors.js +151 -2
- package/dist/guard/budget.d.ts +135 -0
- package/dist/guard/budget.js +199 -0
- package/dist/guard/ci-event.d.ts +50 -0
- package/dist/guard/ci-event.js +125 -0
- package/dist/guard/mainnet-optin.d.ts +58 -0
- package/dist/guard/mainnet-optin.js +95 -0
- package/dist/guard/networks.d.ts +50 -0
- package/dist/guard/networks.js +80 -0
- package/dist/guard/rpc-identity.d.ts +45 -0
- package/dist/guard/rpc-identity.js +156 -0
- package/dist/guard/rpc-in-use.d.ts +48 -0
- package/dist/guard/rpc-in-use.js +84 -0
- package/dist/index.d.ts +34 -3
- package/dist/index.js +31 -2
- package/dist/mpp/channel-commitment.d.ts +48 -2
- package/dist/mpp/channel-commitment.js +80 -4
- package/dist/mpp/channel-credential.js +3 -0
- package/dist/mpp/channel.js +29 -0
- package/dist/mpp/charge.d.ts +25 -2
- package/dist/mpp/charge.js +100 -8
- package/dist/mpp/network.js +4 -1
- package/dist/mpp/suite.js +10 -2
- package/dist/report.d.ts +163 -0
- package/dist/report.js +282 -0
- package/dist/sanitize.d.ts +52 -0
- package/dist/sanitize.js +106 -0
- package/dist/settlement.d.ts +14 -0
- package/dist/settlement.js +1 -1
- package/dist/verdict.d.ts +24 -0
- package/dist/verdict.js +46 -0
- package/dist/versions.d.ts +50 -0
- package/dist/versions.js +123 -0
- package/dist/x402/chains/evm.d.ts +65 -0
- package/dist/x402/chains/evm.js +237 -0
- package/dist/x402/chains/index.d.ts +18 -0
- package/dist/x402/chains/index.js +28 -0
- package/dist/x402/chains/stellar.d.ts +38 -0
- package/dist/x402/chains/stellar.js +277 -0
- package/dist/x402/chains/svm.d.ts +69 -0
- package/dist/x402/chains/svm.js +333 -0
- package/dist/x402/chains/types.d.ts +152 -0
- package/dist/x402/chains/types.js +10 -0
- package/dist/x402/chains/wait.d.ts +36 -0
- package/dist/x402/chains/wait.js +42 -0
- package/dist/x402/plan.d.ts +82 -0
- package/dist/x402/plan.js +146 -0
- package/dist/x402/rejected-request.d.ts +146 -0
- package/dist/x402/rejected-request.js +269 -0
- package/dist/x402/requirements.d.ts +46 -0
- package/dist/x402/requirements.js +359 -0
- package/dist/x402/simulator.d.ts +74 -17
- package/dist/x402/simulator.js +907 -246
- package/package.json +11 -6
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* X402-11, "Rejected Request Not Settled" (spec B7 as D-032 changed it).
|
|
3
|
+
*
|
|
4
|
+
* Wasit sends a valid payment, for the advertised terms exactly, with a request
|
|
5
|
+
* the builder's config declares invalid (`endpoints[].reject`), then reads the
|
|
6
|
+
* chain: the nonce of that payment's authorization must still be unused once
|
|
7
|
+
* its expiration ledger has passed. The verdict comes from one read that asks
|
|
8
|
+
* for that nonce and for X402-06's, which was used and must be found: a read
|
|
9
|
+
* that cannot find X402-06's cannot show that ours is absent. The payer's
|
|
10
|
+
* balance and the transfer events are second readings; when they disagree with
|
|
11
|
+
* the nonce, there is no verdict.
|
|
12
|
+
*
|
|
13
|
+
* The wait (Najmi, 2026-11-16): a payment whose advertised lifetime
|
|
14
|
+
* (`maxTimeoutSeconds`) is at most 300 s is waited out, with a hard stop 360 s
|
|
15
|
+
* after it was sent; a longer one is not signed at all (it is read again on the
|
|
16
|
+
* challenge the payment is signed from), and an authorization the client signs
|
|
17
|
+
* to outlive it is not sent. A lifetime below 30 s is not signed either, and an
|
|
18
|
+
* authorization with fewer than 3 ledgers left is not sent (2026-11-17).
|
|
19
|
+
*
|
|
20
|
+
* This file holds the parts that need no network: the rules, the reject
|
|
21
|
+
* request's shape, the watch loop over a chain's reads, and the verdict. The
|
|
22
|
+
* check itself, which pays, is in `simulator.ts` with the other payment checks.
|
|
23
|
+
*/
|
|
24
|
+
import { errored, skipped } from "../check.js";
|
|
25
|
+
import { CheckSetupError } from "../errors.js";
|
|
26
|
+
import { sanitizeText } from "../sanitize.js";
|
|
27
|
+
export const REJECTED_REQUEST_ID = "X402-11";
|
|
28
|
+
export const REJECTED_REQUEST_NAME = "Rejected Request Not Settled";
|
|
29
|
+
/** The longest advertised lifetime X402-11 waits out on a test network. */
|
|
30
|
+
export const REJECTED_REQUEST_MAX_LIFETIME_SECONDS = 300;
|
|
31
|
+
/**
|
|
32
|
+
* The shortest advertised lifetime X402-11 signs for (Najmi, 2026-11-17,
|
|
33
|
+
* screening S-1): a payment valid for a few seconds can expire before a service
|
|
34
|
+
* that settles it has it on chain, and its unused authorization would then show
|
|
35
|
+
* nothing about the service.
|
|
36
|
+
*/
|
|
37
|
+
export const REJECTED_REQUEST_MIN_LIFETIME_SECONDS = 30;
|
|
38
|
+
/** The fewest units of validity a signed authorization must have left when X402-11 sends it. */
|
|
39
|
+
export const REJECTED_REQUEST_MIN_UNITS_LEFT = 3;
|
|
40
|
+
/**
|
|
41
|
+
* How long after the payment is sent the watch stops, whatever the lifetime:
|
|
42
|
+
* a 300 s lifetime is 60 ledgers of 5 s, and the verdict needs the ledger
|
|
43
|
+
* after it, so about 305 s; the rest is slack for a slow ledger or RPC.
|
|
44
|
+
*/
|
|
45
|
+
export const REJECTED_REQUEST_HARD_STOP_MS = 360_000;
|
|
46
|
+
let hardStopForTesting;
|
|
47
|
+
/**
|
|
48
|
+
* Tests only: a shorter hard stop, so "still valid when the watch stopped" can
|
|
49
|
+
* be shown without a six-minute test. It can only lower the stop. Not exported
|
|
50
|
+
* from the package index; no flag, setting or tool argument reaches it.
|
|
51
|
+
*/
|
|
52
|
+
export function setRejectedRequestHardStopForTesting(ms) {
|
|
53
|
+
hardStopForTesting = ms;
|
|
54
|
+
}
|
|
55
|
+
export function rejectedRequestHardStopMs() {
|
|
56
|
+
return hardStopForTesting === undefined
|
|
57
|
+
? REJECTED_REQUEST_HARD_STOP_MS
|
|
58
|
+
: Math.min(hardStopForTesting, REJECTED_REQUEST_HARD_STOP_MS);
|
|
59
|
+
}
|
|
60
|
+
const BODYLESS = new Set(["GET", "HEAD"]);
|
|
61
|
+
/**
|
|
62
|
+
* The endpoint's own request with the reject case over it: its method when it
|
|
63
|
+
* names one, its headers over the endpoint's (by name, ignoring case), and its
|
|
64
|
+
* body instead of the endpoint's. A method that carries no body drops the
|
|
65
|
+
* endpoint's body; the config already refuses a reject body on such a method.
|
|
66
|
+
*/
|
|
67
|
+
export function rejectRequestShape(shape, reject) {
|
|
68
|
+
const method = (reject.method ?? shape.method ?? "GET").toUpperCase();
|
|
69
|
+
const replaced = new Set(Object.keys(reject.headers ?? {}).map((name) => name.toLowerCase()));
|
|
70
|
+
const headers = {};
|
|
71
|
+
for (const [name, value] of Object.entries(shape.headers ?? {})) {
|
|
72
|
+
if (!replaced.has(name.toLowerCase()))
|
|
73
|
+
headers[name] = value;
|
|
74
|
+
}
|
|
75
|
+
Object.assign(headers, reject.headers ?? {});
|
|
76
|
+
const body = reject.body !== undefined ? reject.body : BODYLESS.has(method) ? undefined : shape.body;
|
|
77
|
+
return {
|
|
78
|
+
method,
|
|
79
|
+
...(Object.keys(headers).length === 0 ? {} : { headers }),
|
|
80
|
+
...(body === undefined ? {} : { body }),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function message(error) {
|
|
84
|
+
return sanitizeText(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").slice(0, 200);
|
|
85
|
+
}
|
|
86
|
+
class ReadTimedOut extends Error {
|
|
87
|
+
}
|
|
88
|
+
/** `promise`, or `ReadTimedOut` once `ms` have passed (at once when `ms` is 0 or less). */
|
|
89
|
+
function withinMs(promise, ms) {
|
|
90
|
+
// A read that answers after the stop is ignored, and its failure too.
|
|
91
|
+
promise.catch(() => undefined);
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
const timer = setTimeout(() => reject(new ReadTimedOut()), Math.max(0, ms));
|
|
94
|
+
promise.then((value) => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
resolve(value);
|
|
97
|
+
}, (error) => {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
reject(error);
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Reads the chain once a ledger until the authorization is used, or a read
|
|
105
|
+
* past its expiration ledger finds it unused, or the hard stop comes. Every
|
|
106
|
+
* read asks for the control too; one that does not return it ends the watch
|
|
107
|
+
* with no reading. Never throws: a failed read is an `unread` outcome.
|
|
108
|
+
*/
|
|
109
|
+
export async function watchAuthorization(input) {
|
|
110
|
+
const now = input.now ?? Date.now;
|
|
111
|
+
const sleep = input.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
112
|
+
const stop = input.sentAt + rejectedRequestHardStopMs();
|
|
113
|
+
for (;;) {
|
|
114
|
+
let read;
|
|
115
|
+
try {
|
|
116
|
+
// A read that has not answered by the hard stop ends the watch there: the
|
|
117
|
+
// stop holds while a read is in flight, not only between reads.
|
|
118
|
+
read = await withinMs(input.watch.read(input.network, input.rpcUrl, [input.ours, input.control]), stop - now());
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error instanceof ReadTimedOut) {
|
|
122
|
+
return {
|
|
123
|
+
kind: "unread",
|
|
124
|
+
why: `the chain did not answer a read before the watch's hard stop, ${Math.round(rejectedRequestHardStopMs() / 1000)} s after the payment was sent`,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
return { kind: "unread", why: `the chain read failed: ${message(error)}` };
|
|
128
|
+
}
|
|
129
|
+
if (read.used[1] === undefined) {
|
|
130
|
+
return {
|
|
131
|
+
kind: "unread",
|
|
132
|
+
why: "the chain's answer left out X402-06's authorization, which was used, so it cannot show that this one was not",
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const usedAt = read.used[0];
|
|
136
|
+
if (usedAt !== undefined)
|
|
137
|
+
return { kind: "used", ledger: usedAt, latest: read.latest };
|
|
138
|
+
if (read.latest > input.ours.expiresAt)
|
|
139
|
+
return { kind: "unused", latest: read.latest };
|
|
140
|
+
const left = stop - now();
|
|
141
|
+
if (left <= 0)
|
|
142
|
+
return { kind: "still-valid", latest: read.latest };
|
|
143
|
+
await sleep(Math.max(1, Math.min(input.watch.unitMs, left)));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function refusal(status, reason) {
|
|
147
|
+
return reason === undefined ? `HTTP ${status}` : `HTTP ${status}: ${reason}`;
|
|
148
|
+
}
|
|
149
|
+
/** Why the second readings do not support "taken", or undefined when they do. */
|
|
150
|
+
function notTaken(evidence) {
|
|
151
|
+
const { balance, transfers, amount } = evidence;
|
|
152
|
+
if (balance === undefined || transfers === undefined)
|
|
153
|
+
return "the payer's balance or the transfer events were not read";
|
|
154
|
+
const fell = balance.before - balance.after;
|
|
155
|
+
if (transfers.length === 0)
|
|
156
|
+
return `no transfer of ${amount} base units from the payer to payTo was recorded`;
|
|
157
|
+
if (fell < amount)
|
|
158
|
+
return `the payer's balance fell by ${fell} base units, less than the ${amount} paid`;
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
/** Why the second readings do not support "not taken", or undefined when they do. */
|
|
162
|
+
function notUntaken(evidence) {
|
|
163
|
+
const { balance, transfers, amount } = evidence;
|
|
164
|
+
if (balance === undefined || transfers === undefined)
|
|
165
|
+
return "the payer's balance or the transfer events were not read";
|
|
166
|
+
const fell = balance.before - balance.after;
|
|
167
|
+
if (transfers.length > 0) {
|
|
168
|
+
return `a transfer of ${amount} base units from the payer to payTo was recorded (${transfers.map((item) => item.reference).join(", ")})`;
|
|
169
|
+
}
|
|
170
|
+
if (fell >= amount)
|
|
171
|
+
return `the payer's balance fell by ${fell} base units, at least the ${amount} paid`;
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
174
|
+
const SERVED_HINT = "Refuse an invalid request before its payment is settled. The official x402 Express middleware does not settle " +
|
|
175
|
+
"when the handler answers 400 or above; a route that serves every request it is paid for sells what it should refuse.";
|
|
176
|
+
const TAKEN_HINT = "A refused request must not cost the payer: settle a payment only after the request has been accepted. The " +
|
|
177
|
+
"official x402 Express middleware does not settle when the handler answers 400 or above; code that settles " +
|
|
178
|
+
"before validating the request, or settles on its own, takes the payment for a request it then refuses.";
|
|
179
|
+
/**
|
|
180
|
+
* X402-11's verdict from what the service answered and what the chain shows.
|
|
181
|
+
*
|
|
182
|
+
* - served (2xx): FAIL, whatever the chain shows; the chain only adds whether it settled.
|
|
183
|
+
* - refused, used, the second readings agree: FAIL, the payment was taken.
|
|
184
|
+
* - refused, unused past the expiry, the second readings agree: PASS.
|
|
185
|
+
* - refused and still valid at the hard stop: SKIP, "not settled by ledger N; still valid until ledger M".
|
|
186
|
+
* - anything else (a reading that disagrees or is missing, a read that failed): no verdict, never PASS.
|
|
187
|
+
*/
|
|
188
|
+
export function rejectedRequestVerdict(evidence) {
|
|
189
|
+
const id = REJECTED_REQUEST_ID;
|
|
190
|
+
const name = REJECTED_REQUEST_NAME;
|
|
191
|
+
const { watch, unit, expiresAt, amount, status } = evidence;
|
|
192
|
+
const served = status >= 200 && status < 300;
|
|
193
|
+
if (served) {
|
|
194
|
+
let note;
|
|
195
|
+
if (watch.kind === "used") {
|
|
196
|
+
const why = notTaken(evidence);
|
|
197
|
+
note =
|
|
198
|
+
why === undefined
|
|
199
|
+
? ` The payment was taken: ${evidence.transfers.map((item) => `${item.reference} (${unit} ${item.ledger})`).join(", ")}.`
|
|
200
|
+
: ` The chain records its authorization as used (${unit} ${watch.ledger}), but ${why}, so whether it was taken is not stated.`;
|
|
201
|
+
}
|
|
202
|
+
else if (watch.kind === "unused") {
|
|
203
|
+
const why = notUntaken(evidence);
|
|
204
|
+
note =
|
|
205
|
+
why === undefined
|
|
206
|
+
? ` The payment did not settle: its authorization expired at ${unit} ${expiresAt} unused.`
|
|
207
|
+
: ` Whether the payment settled is not stated: the chain records its authorization as unused, but ${why}.`;
|
|
208
|
+
}
|
|
209
|
+
else if (watch.kind === "still-valid") {
|
|
210
|
+
note = ` Whether the payment settled is not known: it was still valid at ${unit} ${watch.latest}, until ${unit} ${expiresAt}, when Wasit stopped waiting.`;
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
note = ` Whether the payment settled was not read: ${watch.why}.`;
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
id,
|
|
217
|
+
name,
|
|
218
|
+
pass: false,
|
|
219
|
+
detail: `A request the config declares invalid was served (HTTP ${status}) with a valid payment for ${amount} base units.${note}`,
|
|
220
|
+
hint: SERVED_HINT,
|
|
221
|
+
expected: "the invalid request refused",
|
|
222
|
+
actual: `HTTP ${status}`,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const refused = `The request the config declares invalid was refused (${refusal(status, evidence.reason)})`;
|
|
226
|
+
const noVerdict = (text) => errored(id, name, new CheckSetupError(text));
|
|
227
|
+
switch (watch.kind) {
|
|
228
|
+
case "used": {
|
|
229
|
+
const why = notTaken(evidence);
|
|
230
|
+
if (why !== undefined) {
|
|
231
|
+
return noVerdict(`${refused}. The chain records this payment's authorization as used (${unit} ${watch.ledger}), but ${why}, ` +
|
|
232
|
+
`so the readings disagree and there is no verdict.`);
|
|
233
|
+
}
|
|
234
|
+
const where = evidence.transfers.map((item) => `${item.reference} (${unit} ${item.ledger})`).join(", ");
|
|
235
|
+
return {
|
|
236
|
+
id,
|
|
237
|
+
name,
|
|
238
|
+
pass: false,
|
|
239
|
+
detail: `${refused} and the payment was taken: ${amount} base units moved from the payer to payTo in ${where}; ` +
|
|
240
|
+
`the chain records its authorization as used.`,
|
|
241
|
+
hint: TAKEN_HINT,
|
|
242
|
+
expected: "a refused request leaves its payment unsettled",
|
|
243
|
+
actual: `the payment settled (${unit} ${watch.ledger})`,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
case "unused": {
|
|
247
|
+
const why = notUntaken(evidence);
|
|
248
|
+
if (why !== undefined) {
|
|
249
|
+
return noVerdict(`${refused}. The chain records this payment's authorization as unused past its expiry (${unit} ${expiresAt}), ` +
|
|
250
|
+
`but ${why}, so the readings disagree and there is no verdict.`);
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
id,
|
|
254
|
+
name,
|
|
255
|
+
pass: true,
|
|
256
|
+
detail: `${refused}, and the payment was not taken: its authorization expired at ${unit} ${expiresAt} unused ` +
|
|
257
|
+
`(read at ${unit} ${watch.latest}, in the same read that found X402-06's used authorization); no transfer ` +
|
|
258
|
+
`of it to payTo was recorded, and the payer's balance did not fall by it.`,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
case "still-valid":
|
|
262
|
+
return skipped(id, name, `the request was refused (${refusal(status, evidence.reason)}), and its payment was not settled by ${unit} ` +
|
|
263
|
+
`${watch.latest}; still valid until ${unit} ${expiresAt} when Wasit stopped waiting (at most ` +
|
|
264
|
+
`${REJECTED_REQUEST_HARD_STOP_MS / 1000} s on a test network), so whether it settles is not known.`);
|
|
265
|
+
case "unread":
|
|
266
|
+
return noVerdict(`${refused}, but the chain was not read to the end of the payment's validity (${watch.why}), so whether it ` +
|
|
267
|
+
`settled is not known.`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The payment terms an x402 challenge advertises, and the rules X402-04 and
|
|
3
|
+
* X402-05 hold them to.
|
|
4
|
+
*
|
|
5
|
+
* Split from the HTTP calls in simulator.ts so the rules can be exercised
|
|
6
|
+
* without a network. Nothing here is specific to one chain: x402 v2 names the
|
|
7
|
+
* network of every payment option with a CAIP-2 identifier, and a challenge
|
|
8
|
+
* may offer several options on several chains at once.
|
|
9
|
+
*/
|
|
10
|
+
import { type CheckResult } from "../check.js";
|
|
11
|
+
/**
|
|
12
|
+
* Every payment option a challenge offers, in order.
|
|
13
|
+
*
|
|
14
|
+
* x402 v2 nests the payment terms inside `accepts[]`. Each entry is a separate
|
|
15
|
+
* option, typically one per network or asset, so each is checked on its own:
|
|
16
|
+
* judging only the first would pass a challenge whose other options are broken,
|
|
17
|
+
* and fail one whose first option is on a chain the reader did not expect.
|
|
18
|
+
* An entry that is not an object is kept as `undefined`, so it reads as an
|
|
19
|
+
* option with every field missing rather than disappearing from the count.
|
|
20
|
+
*/
|
|
21
|
+
export declare function acceptsOf(payload: unknown): ReadonlyArray<Record<string, unknown> | undefined> | undefined;
|
|
22
|
+
/** X402-04: every payment option must carry the fields its version requires. */
|
|
23
|
+
export declare function checkRequiredFields(payload: unknown): CheckResult;
|
|
24
|
+
/** What X402-05 established about one network identifier. */
|
|
25
|
+
export type NetworkVerdict = {
|
|
26
|
+
readonly valid: true;
|
|
27
|
+
readonly namespace: string;
|
|
28
|
+
readonly known: boolean;
|
|
29
|
+
} | {
|
|
30
|
+
readonly valid: false;
|
|
31
|
+
readonly reason: string;
|
|
32
|
+
readonly fix: string;
|
|
33
|
+
readonly expected: string;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Validates one network identifier against CAIP-2, which x402 v2 requires,
|
|
37
|
+
* and against its namespace's own rules where Wasit knows them.
|
|
38
|
+
*
|
|
39
|
+
* A well-formed identifier in a namespace Wasit has no rules for is valid:
|
|
40
|
+
* x402 v2 asks for CAIP-2 and nothing more, and even encourages non-blockchain
|
|
41
|
+
* networks to follow it (`ach:us`). Failing it would report Wasit's own
|
|
42
|
+
* ignorance as the target's defect.
|
|
43
|
+
*/
|
|
44
|
+
export declare function validateNetwork(network: string): NetworkVerdict;
|
|
45
|
+
/** X402-05: every advertised network identifier must be CAIP-2. */
|
|
46
|
+
export declare function checkNetworkIdentifier(payload: unknown): CheckResult;
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The payment terms an x402 challenge advertises, and the rules X402-04 and
|
|
3
|
+
* X402-05 hold them to.
|
|
4
|
+
*
|
|
5
|
+
* Split from the HTTP calls in simulator.ts so the rules can be exercised
|
|
6
|
+
* without a network. Nothing here is specific to one chain: x402 v2 names the
|
|
7
|
+
* network of every payment option with a CAIP-2 identifier, and a challenge
|
|
8
|
+
* may offer several options on several chains at once.
|
|
9
|
+
*/
|
|
10
|
+
import { quoteValue, skipped } from "../check.js";
|
|
11
|
+
function asRecord(value) {
|
|
12
|
+
return typeof value === "object" && value !== null
|
|
13
|
+
? value
|
|
14
|
+
: undefined;
|
|
15
|
+
}
|
|
16
|
+
function nonEmptyString(value) {
|
|
17
|
+
return typeof value === "string" && value.length > 0;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Every payment option a challenge offers, in order.
|
|
21
|
+
*
|
|
22
|
+
* x402 v2 nests the payment terms inside `accepts[]`. Each entry is a separate
|
|
23
|
+
* option, typically one per network or asset, so each is checked on its own:
|
|
24
|
+
* judging only the first would pass a challenge whose other options are broken,
|
|
25
|
+
* and fail one whose first option is on a chain the reader did not expect.
|
|
26
|
+
* An entry that is not an object is kept as `undefined`, so it reads as an
|
|
27
|
+
* option with every field missing rather than disappearing from the count.
|
|
28
|
+
*/
|
|
29
|
+
export function acceptsOf(payload) {
|
|
30
|
+
const accepts = asRecord(payload)?.["accepts"];
|
|
31
|
+
return Array.isArray(accepts) ? accepts.map(asRecord) : undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The fields every payment option must carry, per protocol version (x402 v2
|
|
35
|
+
* spec 5.1.2; v1 spec 5.1).
|
|
36
|
+
*
|
|
37
|
+
* x402 v2 renamed `maxAmountRequired` to `amount` and moved `resource` and
|
|
38
|
+
* `description` out of the option. Checking for whichever price name happens
|
|
39
|
+
* to be present would hide a real conformance failure: a service advertising
|
|
40
|
+
* `x402Version: 2` while emitting the v1 field name is not conformant to the
|
|
41
|
+
* version it claims.
|
|
42
|
+
*/
|
|
43
|
+
const REQUIRED_FIELDS = {
|
|
44
|
+
2: ["scheme", "network", "amount", "asset", "payTo", "maxTimeoutSeconds"],
|
|
45
|
+
1: [
|
|
46
|
+
"scheme",
|
|
47
|
+
"network",
|
|
48
|
+
"maxAmountRequired",
|
|
49
|
+
"asset",
|
|
50
|
+
"payTo",
|
|
51
|
+
"resource",
|
|
52
|
+
"description",
|
|
53
|
+
"maxTimeoutSeconds",
|
|
54
|
+
],
|
|
55
|
+
};
|
|
56
|
+
const PRICE_FIELD = { 1: "maxAmountRequired", 2: "amount" };
|
|
57
|
+
/** One sentence per missing field, saying what to put there. */
|
|
58
|
+
const FIELD_FIXES = {
|
|
59
|
+
scheme: 'Add `scheme`, e.g. "exact": clients pick a payment option by its scheme.',
|
|
60
|
+
network: "Add `network` as a CAIP-2 id, e.g. stellar:testnet or eip155:84532.",
|
|
61
|
+
amount: 'Add `amount`: the price in the token\'s smallest unit, as a string (e.g. "10000").',
|
|
62
|
+
maxAmountRequired: "Add `maxAmountRequired`: the price in the token's smallest unit, as a string.",
|
|
63
|
+
asset: "Add `asset`: the address of the token the client pays in.",
|
|
64
|
+
payTo: "Add `payTo`: the address that receives the payment.",
|
|
65
|
+
resource: "Add `resource`: the URL of the paid resource.",
|
|
66
|
+
description: "Add `description`: a human-readable description of the resource.",
|
|
67
|
+
maxTimeoutSeconds: "Add `maxTimeoutSeconds`: the seconds a client has to complete payment.",
|
|
68
|
+
};
|
|
69
|
+
/** Said once whenever a field is missing: the usual cause is a hand-built 402. */
|
|
70
|
+
const SDK_NOTE = "The official x402 server SDK fills every required field, maxTimeoutSeconds defaulting to 300.";
|
|
71
|
+
function isSupportedVersion(value) {
|
|
72
|
+
return value === 1 || value === 2;
|
|
73
|
+
}
|
|
74
|
+
/** Names one option in a report: unprefixed when it is the only one. */
|
|
75
|
+
function optionLabel(index, count) {
|
|
76
|
+
return count === 1 ? "" : `accepts[${index}]: `;
|
|
77
|
+
}
|
|
78
|
+
function describeValue(value) {
|
|
79
|
+
return typeof value === "object" ? "an object" : `${typeof value} ${JSON.stringify(value)}`;
|
|
80
|
+
}
|
|
81
|
+
/** What is wrong with one payment option's fields, or undefined if nothing is. */
|
|
82
|
+
function fieldProblem(accept, version) {
|
|
83
|
+
const expected = PRICE_FIELD[version];
|
|
84
|
+
const wrongVersionField = version === 2 ? "maxAmountRequired" : "amount";
|
|
85
|
+
// A v2 challenge carrying the v1 field name is a specific, actionable
|
|
86
|
+
// failure — say which name was found and which one the version requires,
|
|
87
|
+
// rather than reporting the price as simply absent.
|
|
88
|
+
if (!nonEmptyString(accept?.[expected]) && accept?.[wrongVersionField] !== undefined) {
|
|
89
|
+
return {
|
|
90
|
+
detail: `Challenge advertises x402Version ${version} but carries ` +
|
|
91
|
+
`\`${wrongVersionField}\`, which is the v${version === 2 ? 1 : 2} field ` +
|
|
92
|
+
`name. v${version} requires \`${expected}\`.`,
|
|
93
|
+
fixes: [
|
|
94
|
+
`Rename \`${wrongVersionField}\` to \`${expected}\`, which is what v${version} ` +
|
|
95
|
+
`calls the price, or advertise x402Version ${version === 2 ? 1 : 2} if the ` +
|
|
96
|
+
`service speaks that version.`,
|
|
97
|
+
],
|
|
98
|
+
missing: false,
|
|
99
|
+
expected: `the field \`${expected}\` (v${version})`,
|
|
100
|
+
actual: `the field \`${wrongVersionField}\` (v${version === 2 ? 1 : 2})`,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const missing = [];
|
|
104
|
+
const wrongType = [];
|
|
105
|
+
// The same findings as short expected and actual values, in the same order.
|
|
106
|
+
const wrongExpected = [];
|
|
107
|
+
const wrongActual = [];
|
|
108
|
+
for (const field of REQUIRED_FIELDS[version]) {
|
|
109
|
+
const value = accept?.[field];
|
|
110
|
+
if (value === undefined || value === null || value === "") {
|
|
111
|
+
missing.push(field);
|
|
112
|
+
}
|
|
113
|
+
else if (field === "maxTimeoutSeconds") {
|
|
114
|
+
// A zero or negative timeout leaves the client no time to pay.
|
|
115
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
116
|
+
wrongType.push(`maxTimeoutSeconds must be a positive number of seconds (got ${describeValue(value)})`);
|
|
117
|
+
wrongExpected.push("maxTimeoutSeconds as a positive number");
|
|
118
|
+
wrongActual.push(`maxTimeoutSeconds is ${describeValue(value)}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
else if (typeof value !== "string") {
|
|
122
|
+
wrongType.push(`${field} must be a string (got ${describeValue(value)})`);
|
|
123
|
+
wrongExpected.push(`${field} as a string`);
|
|
124
|
+
wrongActual.push(`${field} is ${describeValue(value)}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (missing.length === 0 && wrongType.length === 0)
|
|
128
|
+
return undefined;
|
|
129
|
+
const detail = [
|
|
130
|
+
missing.length > 0 ? `Missing: ${missing.join(", ")}.` : undefined,
|
|
131
|
+
wrongType.length > 0 ? `Wrong type: ${wrongType.join("; ")}.` : undefined,
|
|
132
|
+
]
|
|
133
|
+
.filter((part) => part !== undefined)
|
|
134
|
+
.join(" ");
|
|
135
|
+
const fixes = [
|
|
136
|
+
...missing.map((field) => FIELD_FIXES[field]),
|
|
137
|
+
...(wrongType.length > 0
|
|
138
|
+
? [
|
|
139
|
+
"Send each field with the type the spec gives it: strings for amounts " +
|
|
140
|
+
"and addresses, a number for maxTimeoutSeconds.",
|
|
141
|
+
]
|
|
142
|
+
: []),
|
|
143
|
+
];
|
|
144
|
+
return {
|
|
145
|
+
detail,
|
|
146
|
+
fixes,
|
|
147
|
+
missing: missing.length > 0,
|
|
148
|
+
expected: [...(missing.length > 0 ? [`${missing.join(", ")} present`] : []), ...wrongExpected].join("; "),
|
|
149
|
+
actual: [...(missing.length > 0 ? [`${missing.join(", ")} missing`] : []), ...wrongActual].join("; "),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** X402-04: every payment option must carry the fields its version requires. */
|
|
153
|
+
export function checkRequiredFields(payload) {
|
|
154
|
+
const id = "X402-04";
|
|
155
|
+
const name = "Required Fields Present";
|
|
156
|
+
const version = asRecord(payload)?.["x402Version"];
|
|
157
|
+
if (!isSupportedVersion(version)) {
|
|
158
|
+
return {
|
|
159
|
+
id,
|
|
160
|
+
name,
|
|
161
|
+
pass: false,
|
|
162
|
+
detail: `Challenge advertises x402Version ${JSON.stringify(version)}, which is ` +
|
|
163
|
+
`neither 1 nor 2. The payment terms use different field names per ` +
|
|
164
|
+
`version, so they cannot be checked against an unknown one.`,
|
|
165
|
+
hint: "Set `x402Version` to 2, the current protocol version, and use its field names.",
|
|
166
|
+
expected: "x402Version 2",
|
|
167
|
+
actual: version === undefined ? "no x402Version" : `x402Version ${quoteValue(version)}`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const accepts = acceptsOf(payload);
|
|
171
|
+
if (accepts === undefined || accepts.length === 0) {
|
|
172
|
+
const raw = asRecord(payload)?.["accepts"];
|
|
173
|
+
return {
|
|
174
|
+
id,
|
|
175
|
+
name,
|
|
176
|
+
pass: false,
|
|
177
|
+
detail: "Challenge offers no payment options: `accepts` is missing or empty, so " +
|
|
178
|
+
`there is no price, network or payTo to read.`,
|
|
179
|
+
hint: "List at least one payment option in `accepts`, each with " +
|
|
180
|
+
`${REQUIRED_FIELDS[version].join(", ")}.`,
|
|
181
|
+
expected: "at least one entry in accepts",
|
|
182
|
+
actual: raw === undefined ? "accepts is missing" : Array.isArray(raw) ? "accepts is empty" : "accepts is not a list",
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const problems = accepts
|
|
186
|
+
.map((accept, index) => {
|
|
187
|
+
const problem = fieldProblem(accept, version);
|
|
188
|
+
return problem === undefined
|
|
189
|
+
? undefined
|
|
190
|
+
: {
|
|
191
|
+
...problem,
|
|
192
|
+
detail: optionLabel(index, accepts.length) + problem.detail,
|
|
193
|
+
expected: optionLabel(index, accepts.length) + problem.expected,
|
|
194
|
+
actual: optionLabel(index, accepts.length) + problem.actual,
|
|
195
|
+
};
|
|
196
|
+
})
|
|
197
|
+
.filter((problem) => problem !== undefined);
|
|
198
|
+
if (problems.length > 0) {
|
|
199
|
+
const fixes = [
|
|
200
|
+
...new Set([
|
|
201
|
+
...problems.flatMap((problem) => problem.fixes),
|
|
202
|
+
...(problems.some((problem) => problem.missing) ? [SDK_NOTE] : []),
|
|
203
|
+
]),
|
|
204
|
+
];
|
|
205
|
+
return {
|
|
206
|
+
id,
|
|
207
|
+
name,
|
|
208
|
+
pass: false,
|
|
209
|
+
detail: problems.map((problem) => problem.detail).join(" "),
|
|
210
|
+
hint: fixes.join(" "),
|
|
211
|
+
expected: problems.map((problem) => problem.expected).join("; "),
|
|
212
|
+
actual: problems.map((problem) => problem.actual).join("; "),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
id,
|
|
217
|
+
name,
|
|
218
|
+
pass: true,
|
|
219
|
+
detail: accepts.length === 1
|
|
220
|
+
? `All required v${version} fields present.`
|
|
221
|
+
: `All required v${version} fields present in each of the ` +
|
|
222
|
+
`${accepts.length} payment options.`,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/** CAIP-2: `namespace:reference`, with the character sets the standard fixes. */
|
|
226
|
+
const CAIP2 = /^([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32})$/;
|
|
227
|
+
/** Base58 (bitcoin alphabet): no 0, O, I or l. */
|
|
228
|
+
const BASE58_32 = /^[1-9A-HJ-NP-Za-km-z]{32}$/;
|
|
229
|
+
const CAIP2_EXAMPLES = "stellar:testnet, eip155:84532 (Base Sepolia) or " +
|
|
230
|
+
"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet)";
|
|
231
|
+
/** `eip155:0x14a34` is a common slip: `eth_chainId` returns hex. */
|
|
232
|
+
function eip155Fix(reference) {
|
|
233
|
+
if (/^0x[0-9a-f]+$/i.test(reference)) {
|
|
234
|
+
return `Write the chain id in base 10: eip155:${BigInt(reference).toString()}.`;
|
|
235
|
+
}
|
|
236
|
+
return "Use the chain id in base 10, as eth_chainId returns it converted from hex (Base Sepolia is eip155:84532).";
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Reference rules for the namespaces whose CAIP-2 definition fixes them.
|
|
240
|
+
* Each returns what is wrong with a reference, or undefined when it is right.
|
|
241
|
+
*
|
|
242
|
+
* - stellar: the namespace knows exactly two networks.
|
|
243
|
+
* - eip155: the EIP-155 chain id, in base 10 (`eth_chainId` returns hex,
|
|
244
|
+
* which the namespace converts).
|
|
245
|
+
* - solana: the first 32 characters of the base58 genesis hash.
|
|
246
|
+
*
|
|
247
|
+
* Sources: ChainAgnostic/namespaces `stellar`, `eip155`, `solana` caip2.md.
|
|
248
|
+
*/
|
|
249
|
+
const NAMESPACE_RULES = {
|
|
250
|
+
stellar: (reference) => reference === "testnet" || reference === "pubnet"
|
|
251
|
+
? undefined
|
|
252
|
+
: {
|
|
253
|
+
reason: `"stellar:${reference}" does not match stellar:testnet or stellar:pubnet, ` +
|
|
254
|
+
`the only Stellar networks CAIP-2 defines.`,
|
|
255
|
+
fix: "Use stellar:testnet or stellar:pubnet.",
|
|
256
|
+
expected: "stellar:testnet or stellar:pubnet",
|
|
257
|
+
},
|
|
258
|
+
eip155: (reference) => /^[1-9][0-9]*$/.test(reference)
|
|
259
|
+
? undefined
|
|
260
|
+
: {
|
|
261
|
+
reason: `"eip155:${reference}" does not carry an EIP-155 chain id in base 10, ` +
|
|
262
|
+
`which the eip155 namespace requires (Base Sepolia is eip155:84532).`,
|
|
263
|
+
fix: eip155Fix(reference),
|
|
264
|
+
expected: "eip155:<chain id in base 10>",
|
|
265
|
+
},
|
|
266
|
+
solana: (reference) => BASE58_32.test(reference)
|
|
267
|
+
? undefined
|
|
268
|
+
: {
|
|
269
|
+
reason: `"solana:${reference}" is not the first 32 characters of a base58 ` +
|
|
270
|
+
`genesis hash, which the solana namespace requires (devnet is ` +
|
|
271
|
+
`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1).`,
|
|
272
|
+
fix: "Use the first 32 characters of the cluster's genesis hash (RPC " +
|
|
273
|
+
"getGenesisHash): solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 for devnet, " +
|
|
274
|
+
"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp for mainnet.",
|
|
275
|
+
expected: "solana:<first 32 characters of the base58 genesis hash>",
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
/**
|
|
279
|
+
* Validates one network identifier against CAIP-2, which x402 v2 requires,
|
|
280
|
+
* and against its namespace's own rules where Wasit knows them.
|
|
281
|
+
*
|
|
282
|
+
* A well-formed identifier in a namespace Wasit has no rules for is valid:
|
|
283
|
+
* x402 v2 asks for CAIP-2 and nothing more, and even encourages non-blockchain
|
|
284
|
+
* networks to follow it (`ach:us`). Failing it would report Wasit's own
|
|
285
|
+
* ignorance as the target's defect.
|
|
286
|
+
*/
|
|
287
|
+
export function validateNetwork(network) {
|
|
288
|
+
const match = CAIP2.exec(network);
|
|
289
|
+
if (match === null) {
|
|
290
|
+
return {
|
|
291
|
+
valid: false,
|
|
292
|
+
reason: `"${network}" is not a CAIP-2 identifier (namespace:reference, e.g. ` +
|
|
293
|
+
`stellar:testnet or eip155:84532), which x402 v2 requires.`,
|
|
294
|
+
fix: `Use the network's CAIP-2 id, namespace:reference, such as ${CAIP2_EXAMPLES}.`,
|
|
295
|
+
expected: "a CAIP-2 id, namespace:reference, such as stellar:testnet",
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const namespace = match[1];
|
|
299
|
+
const rule = NAMESPACE_RULES[namespace];
|
|
300
|
+
if (rule === undefined)
|
|
301
|
+
return { valid: true, namespace, known: false };
|
|
302
|
+
const problem = rule(match[2]);
|
|
303
|
+
return problem === undefined
|
|
304
|
+
? { valid: true, namespace, known: true }
|
|
305
|
+
: { valid: false, ...problem };
|
|
306
|
+
}
|
|
307
|
+
/** X402-05: every advertised network identifier must be CAIP-2. */
|
|
308
|
+
export function checkNetworkIdentifier(payload) {
|
|
309
|
+
const id = "X402-05";
|
|
310
|
+
const name = "Network Identifier Valid";
|
|
311
|
+
const accepts = acceptsOf(payload) ?? [];
|
|
312
|
+
const advertised = accepts
|
|
313
|
+
.map((accept, index) => ({ index, network: accept?.["network"] }))
|
|
314
|
+
.filter((entry) => nonEmptyString(entry.network));
|
|
315
|
+
// Absent is X402-04's finding, not a second one: report it there only.
|
|
316
|
+
if (advertised.length === 0) {
|
|
317
|
+
return skipped(id, name, "the challenge carries no network field to validate (see X402-04).", "dependency");
|
|
318
|
+
}
|
|
319
|
+
const v1 = asRecord(payload)?.["x402Version"] === 1;
|
|
320
|
+
const verdicts = advertised.map((entry) => ({ ...entry, verdict: validateNetwork(entry.network) }));
|
|
321
|
+
const invalid = verdicts.filter((entry) => !entry.verdict.valid);
|
|
322
|
+
if (invalid.length > 0) {
|
|
323
|
+
const problems = invalid.map((entry) => entry.verdict);
|
|
324
|
+
const reasons = invalid.map((entry, i) => optionLabel(entry.index, accepts.length) + problems[i].reason);
|
|
325
|
+
// x402 v1 named networks plainly ("base-sepolia"); saying so turns a bare
|
|
326
|
+
// FAIL into the one change that fixes it.
|
|
327
|
+
const v1Note = v1 ? " x402 v1 used plain names; v2 requires CAIP-2." : "";
|
|
328
|
+
return {
|
|
329
|
+
id,
|
|
330
|
+
name,
|
|
331
|
+
pass: false,
|
|
332
|
+
detail: reasons.join(" ") + v1Note,
|
|
333
|
+
hint: [...new Set(problems.map((problem) => problem.fix))].join(" "),
|
|
334
|
+
expected: invalid.map((entry, i) => optionLabel(entry.index, accepts.length) + problems[i].expected).join("; "),
|
|
335
|
+
actual: invalid.map((entry) => optionLabel(entry.index, accepts.length) + quoteValue(entry.network)).join("; "),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
const unknownNamespaces = [
|
|
339
|
+
...new Set(verdicts
|
|
340
|
+
.map((entry) => entry.verdict)
|
|
341
|
+
.filter((verdict) => verdict.valid && !verdict.known)
|
|
342
|
+
.map((verdict) => verdict.namespace)),
|
|
343
|
+
];
|
|
344
|
+
const unknownNote = unknownNamespaces.length === 0
|
|
345
|
+
? ""
|
|
346
|
+
: ` Wasit has no further rules for the ${unknownNamespaces
|
|
347
|
+
.map((namespace) => `"${namespace}"`)
|
|
348
|
+
.join(", ")} namespace${unknownNamespaces.length === 1 ? "" : "s"}, ` +
|
|
349
|
+
`so only the CAIP-2 format was checked there.`;
|
|
350
|
+
const networks = advertised.map((entry) => entry.network);
|
|
351
|
+
return {
|
|
352
|
+
id,
|
|
353
|
+
name,
|
|
354
|
+
pass: true,
|
|
355
|
+
detail: (networks.length === 1
|
|
356
|
+
? `Network identifier "${networks[0]}" is valid.`
|
|
357
|
+
: `Network identifiers are valid: ${networks.join(", ")}.`) + unknownNote,
|
|
358
|
+
};
|
|
359
|
+
}
|