@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
package/dist/x402/simulator.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
|
-
import { errored, skipped } from "../check.js";
|
|
2
|
-
import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
1
|
+
import { errored, quoteValue, skipped } from "../check.js";
|
|
2
|
+
import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchPaymentChallenge, fetchTarget, } from "../errors.js";
|
|
3
|
+
import { PER_PAYMENT_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, sameAddress, } from "../guard/budget.js";
|
|
4
|
+
import { assertPaymentNetworkAllowed } from "../guard/networks.js";
|
|
5
|
+
import { assertRpcServesNetwork } from "../guard/rpc-identity.js";
|
|
6
|
+
import { REJECTED_REQUEST_ID, REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_UNITS_LEFT, REJECTED_REQUEST_NAME, rejectRequestShape, rejectedRequestHardStopMs, rejectedRequestVerdict, watchAuthorization, } from "./rejected-request.js";
|
|
7
|
+
import { sanitizeText } from "../sanitize.js";
|
|
8
|
+
import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js";
|
|
3
9
|
const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
|
|
4
10
|
const KNOWN_METHODS = new Set([
|
|
5
11
|
"GET",
|
|
@@ -69,82 +75,32 @@ const READ_CHECKS = [
|
|
|
69
75
|
["X402-04", "Required Fields Present"],
|
|
70
76
|
["X402-05", "Network Identifier Valid"],
|
|
71
77
|
];
|
|
78
|
+
/** What a wrong status on an unpaid request usually means, and what to do. */
|
|
79
|
+
function statusHint(status) {
|
|
80
|
+
if (status >= 200 && status < 300) {
|
|
81
|
+
return (`The route served HTTP ${status} without payment: put the x402 payment ` +
|
|
82
|
+
`middleware in front of it, so unpaid requests get 402 and a challenge.`);
|
|
83
|
+
}
|
|
84
|
+
if (status === 401 || status === 403) {
|
|
85
|
+
return (`Answer an unpaid request with 402, not ${status}: authentication errors ` +
|
|
86
|
+
`and payment challenges are different signals, and x402 clients act only on 402.`);
|
|
87
|
+
}
|
|
88
|
+
if (status === 404 || status === 405) {
|
|
89
|
+
return (`A ${status} usually means the wrong path or method. Check the URL, and ` +
|
|
90
|
+
`pass the method the endpoint uses (--method POST, MCP \`method\`).`);
|
|
91
|
+
}
|
|
92
|
+
return "Answer an unpaid request with 402 Payment Required and the challenge in a PAYMENT-REQUIRED header.";
|
|
93
|
+
}
|
|
72
94
|
/** Skips every check after `id`, naming the one cause they all depend on. */
|
|
73
95
|
function skipAfter(id, reason) {
|
|
74
96
|
const index = READ_CHECKS.findIndex(([candidate]) => candidate === id);
|
|
75
|
-
return READ_CHECKS.slice(index + 1).map(([checkId, name]) => skipped(checkId, name, reason));
|
|
97
|
+
return READ_CHECKS.slice(index + 1).map(([checkId, name]) => skipped(checkId, name, reason, "dependency"));
|
|
76
98
|
}
|
|
77
99
|
function asRecord(value) {
|
|
78
100
|
return typeof value === "object" && value !== null
|
|
79
101
|
? value
|
|
80
102
|
: undefined;
|
|
81
103
|
}
|
|
82
|
-
/** x402 v2 nests the payment terms inside `accepts[]`, not at the top level. */
|
|
83
|
-
function firstAccept(payload) {
|
|
84
|
-
const accepts = asRecord(payload)?.["accepts"];
|
|
85
|
-
return Array.isArray(accepts) ? asRecord(accepts[0]) : undefined;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* The field carrying the price, per protocol version.
|
|
89
|
-
*
|
|
90
|
-
* x402 v2 renamed `maxAmountRequired` to `amount` and dropped the embedded
|
|
91
|
-
* resource object. Checking for whichever name happens to be present would
|
|
92
|
-
* hide a real conformance failure: a service advertising `x402Version: 2`
|
|
93
|
-
* while emitting the v1 field name is not conformant to the version it claims.
|
|
94
|
-
*/
|
|
95
|
-
const PRICE_FIELD = {
|
|
96
|
-
1: "maxAmountRequired",
|
|
97
|
-
2: "amount",
|
|
98
|
-
};
|
|
99
|
-
function isSupportedVersion(value) {
|
|
100
|
-
return value === 1 || value === 2;
|
|
101
|
-
}
|
|
102
|
-
function nonEmptyString(value) {
|
|
103
|
-
return typeof value === "string" && value.length > 0;
|
|
104
|
-
}
|
|
105
|
-
/** X402-04: the challenge must carry price, network, and payTo. */
|
|
106
|
-
function checkRequiredFields(payload) {
|
|
107
|
-
const version = asRecord(payload)?.["x402Version"];
|
|
108
|
-
const accept = firstAccept(payload);
|
|
109
|
-
if (!isSupportedVersion(version)) {
|
|
110
|
-
return {
|
|
111
|
-
id: "X402-04",
|
|
112
|
-
name: "Required Fields Present",
|
|
113
|
-
pass: false,
|
|
114
|
-
detail: `Challenge advertises x402Version ${JSON.stringify(version)}, which is ` +
|
|
115
|
-
`neither 1 nor 2. The payment terms use different field names per ` +
|
|
116
|
-
`version, so they cannot be checked against an unknown one.`,
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
const expected = PRICE_FIELD[version];
|
|
120
|
-
const wrongVersionField = version === 2 ? "maxAmountRequired" : "amount";
|
|
121
|
-
// A v2 challenge carrying the v1 field name is a specific, actionable
|
|
122
|
-
// failure — say which name was found and which one the version requires,
|
|
123
|
-
// rather than reporting the price as simply absent.
|
|
124
|
-
if (!nonEmptyString(accept?.[expected]) && accept?.[wrongVersionField] !== undefined) {
|
|
125
|
-
return {
|
|
126
|
-
id: "X402-04",
|
|
127
|
-
name: "Required Fields Present",
|
|
128
|
-
pass: false,
|
|
129
|
-
detail: `Challenge advertises x402Version ${version} but carries ` +
|
|
130
|
-
`\`${wrongVersionField}\`, which is the v${version === 2 ? 1 : 2} field ` +
|
|
131
|
-
`name. v${version} requires \`${expected}\`.`,
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
const missing = [
|
|
135
|
-
nonEmptyString(accept?.[expected]) ? null : expected,
|
|
136
|
-
nonEmptyString(accept?.["network"]) ? null : "network",
|
|
137
|
-
nonEmptyString(accept?.["payTo"]) ? null : "payTo",
|
|
138
|
-
].filter((entry) => entry !== null);
|
|
139
|
-
return {
|
|
140
|
-
id: "X402-04",
|
|
141
|
-
name: "Required Fields Present",
|
|
142
|
-
pass: missing.length === 0,
|
|
143
|
-
detail: missing.length === 0
|
|
144
|
-
? `All required v${version} fields present.`
|
|
145
|
-
: `Missing: ${missing.join(", ")}.`,
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
104
|
/**
|
|
149
105
|
* Reads an x402 v1 challenge from a 402 response body, if that is what it is.
|
|
150
106
|
*
|
|
@@ -164,6 +120,11 @@ export function readV1BodyChallenge(body) {
|
|
|
164
120
|
const record = asRecord(parsed);
|
|
165
121
|
return record?.["x402Version"] === 1 && Array.isArray(record["accepts"]) ? record : undefined;
|
|
166
122
|
}
|
|
123
|
+
/** What a header that did not decode to JSON held, quoted. The service chose it; the sinks cut it. */
|
|
124
|
+
function decodedStart(headerValue) {
|
|
125
|
+
const decoded = Buffer.from(headerValue, "base64").toString("utf-8");
|
|
126
|
+
return decoded === "" ? "an empty value" : `a value that starts with ${quoteValue(decoded)}`;
|
|
127
|
+
}
|
|
167
128
|
/** A body that cannot be read is simply not a v1 challenge. */
|
|
168
129
|
async function readText(response) {
|
|
169
130
|
try {
|
|
@@ -173,23 +134,20 @@ async function readText(response) {
|
|
|
173
134
|
return "";
|
|
174
135
|
}
|
|
175
136
|
}
|
|
176
|
-
/**
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
: `"${network}" does not match stellar:testnet or stellar:pubnet, the CAIP-2 ` +
|
|
191
|
-
`identifiers the \`exact\` scheme on Stellar defines.`,
|
|
192
|
-
};
|
|
137
|
+
/**
|
|
138
|
+
* Why an x402 v1 challenge is not graded: the reason on X402-02..05 and on the
|
|
139
|
+
* endpoint, on every chain (a v1 service on an EVM chain gets it too). Kept
|
|
140
|
+
* under 300 characters, the longest a value goes into a pull request comment,
|
|
141
|
+
* so the way to get graded is not cut off. It names no URL: the comment's
|
|
142
|
+
* sanitiser removes links from check text, so it points at docs/CHECKS.md,
|
|
143
|
+
* whose note on x402 v1 links the x402 specification.
|
|
144
|
+
*/
|
|
145
|
+
const V1_UNSUPPORTED_REASON = "the service sent an x402 v1 challenge (x402Version 1, in the body). Wasit grades only x402 v2, on " +
|
|
146
|
+
"every chain: challenge in a PAYMENT-REQUIRED header, CAIP-2 networks, v2 `exact` scheme (Stellar is " +
|
|
147
|
+
"v2 only). Unsupported, not failed. Fix: move it to that header. Why: docs/CHECKS.md.";
|
|
148
|
+
/** What a check found on a challenge Wasit does not grade, to be shown as a note. */
|
|
149
|
+
function noteOf(result) {
|
|
150
|
+
return result.skipped === true ? (result.skipReason ?? result.detail) : result.detail;
|
|
193
151
|
}
|
|
194
152
|
/**
|
|
195
153
|
* Runs X402-01 through X402-05 against a target.
|
|
@@ -218,7 +176,9 @@ export async function runX402ReadChecks(options) {
|
|
|
218
176
|
}
|
|
219
177
|
let response;
|
|
220
178
|
try {
|
|
221
|
-
|
|
179
|
+
// The unpaid request of the read-only tier: a redirect to another origin
|
|
180
|
+
// is reported and gives no verdict, never followed (spec A8 #5).
|
|
181
|
+
response = await fetchTarget(target, init, { redirects: "same-origin" });
|
|
222
182
|
}
|
|
223
183
|
catch (error) {
|
|
224
184
|
return emit([
|
|
@@ -234,6 +194,9 @@ export async function runX402ReadChecks(options) {
|
|
|
234
194
|
detail: statusPass
|
|
235
195
|
? "Server responded with 402 as required."
|
|
236
196
|
: `Expected status 402, got ${response.status}.`,
|
|
197
|
+
...(statusPass
|
|
198
|
+
? {}
|
|
199
|
+
: { hint: statusHint(response.status), expected: "status 402", actual: `status ${response.status}` }),
|
|
237
200
|
};
|
|
238
201
|
if (!statusPass) {
|
|
239
202
|
return emit([
|
|
@@ -245,39 +208,42 @@ export async function runX402ReadChecks(options) {
|
|
|
245
208
|
// Both names are checked because Stellar's own documentation is not yet
|
|
246
209
|
// internally consistent — see docs/CHECKS.md.
|
|
247
210
|
const headerValue = response.headers.get("PAYMENT-REQUIRED") ?? response.headers.get("X-Payment");
|
|
248
|
-
// x402 v1 signals payment in the response body rather than a header
|
|
249
|
-
// `exact` scheme on Stellar is defined for v2 only, so a
|
|
250
|
-
//
|
|
251
|
-
//
|
|
211
|
+
// x402 v1 signals payment in the response body rather than a header, and the
|
|
212
|
+
// `exact` scheme on Stellar is defined for v2 only. Wasit grades v2, so a v1
|
|
213
|
+
// service is unsupported, not failed (spec A3): X402-02..05 are skipped with
|
|
214
|
+
// that reason. The v1 terms are still read and reported as notes, so an
|
|
215
|
+
// operator sees which of them diverge without being handed a verdict.
|
|
252
216
|
const v1Payload = headerValue === null ? readV1BodyChallenge(await readText(response)) : undefined;
|
|
217
|
+
if (headerValue === null && v1Payload !== undefined) {
|
|
218
|
+
const notes = new Map([
|
|
219
|
+
["X402-04", noteOf(checkRequiredFields(v1Payload))],
|
|
220
|
+
["X402-05", noteOf(checkNetworkIdentifier(v1Payload))],
|
|
221
|
+
]);
|
|
222
|
+
return emit([
|
|
223
|
+
r1,
|
|
224
|
+
...READ_CHECKS.slice(1).map(([id, name]) => {
|
|
225
|
+
const skip = skipped(id, name, V1_UNSUPPORTED_REASON, "unsupported");
|
|
226
|
+
const note = notes.get(id);
|
|
227
|
+
return note === undefined ? skip : { ...skip, detail: `${skip.detail} Note, not a verdict: ${note}` };
|
|
228
|
+
}),
|
|
229
|
+
]);
|
|
230
|
+
}
|
|
253
231
|
const r2 = {
|
|
254
232
|
id: "X402-02",
|
|
255
233
|
name: "Payment Header Present",
|
|
256
234
|
pass: headerValue !== null,
|
|
257
235
|
detail: headerValue !== null
|
|
258
236
|
? "Payment header found."
|
|
259
|
-
:
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
237
|
+
: "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
|
|
238
|
+
...(headerValue !== null
|
|
239
|
+
? {}
|
|
240
|
+
: {
|
|
241
|
+
hint: "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED " +
|
|
242
|
+
"response header, as the x402 v2 HTTP transport defines.",
|
|
243
|
+
expected: "a PAYMENT-REQUIRED header",
|
|
244
|
+
actual: "no PAYMENT-REQUIRED or X-Payment header",
|
|
245
|
+
}),
|
|
265
246
|
};
|
|
266
|
-
if (headerValue === null && v1Payload !== undefined) {
|
|
267
|
-
return emit([
|
|
268
|
-
r1,
|
|
269
|
-
r2,
|
|
270
|
-
{
|
|
271
|
-
id: "X402-03",
|
|
272
|
-
name: "Header Payload Decodable",
|
|
273
|
-
pass: true,
|
|
274
|
-
detail: "No header to decode; the x402 v1 challenge in the response body " +
|
|
275
|
-
"decoded to valid JSON.",
|
|
276
|
-
},
|
|
277
|
-
checkRequiredFields(v1Payload),
|
|
278
|
-
checkNetworkIdentifier(v1Payload),
|
|
279
|
-
]);
|
|
280
|
-
}
|
|
281
247
|
if (headerValue === null) {
|
|
282
248
|
return emit([
|
|
283
249
|
r1,
|
|
@@ -299,6 +265,10 @@ export async function runX402ReadChecks(options) {
|
|
|
299
265
|
name: "Header Payload Decodable",
|
|
300
266
|
pass: false,
|
|
301
267
|
detail: `Failed to decode/parse: ${error.message}`,
|
|
268
|
+
hint: "Base64-encode the JSON PaymentRequired object for the header; raw " +
|
|
269
|
+
"JSON or a truncated value does not decode.",
|
|
270
|
+
expected: "a base64 value that decodes to JSON",
|
|
271
|
+
actual: decodedStart(headerValue),
|
|
302
272
|
},
|
|
303
273
|
...skipAfter("X402-03", "the payment header did not decode to JSON, so no payload was " +
|
|
304
274
|
"available to inspect."),
|
|
@@ -316,11 +286,16 @@ export async function runX402ReadChecks(options) {
|
|
|
316
286
|
]));
|
|
317
287
|
}
|
|
318
288
|
import { x402Client, x402HTTPClient } from "@x402/fetch";
|
|
319
|
-
import {
|
|
320
|
-
import {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
289
|
+
import { paymentChainFor, paymentNetworks } from "./chains/index.js";
|
|
290
|
+
import { stellarChain } from "./chains/stellar.js";
|
|
291
|
+
export { corruptAuthSignature } from "./chains/stellar.js";
|
|
292
|
+
/** One check has nothing to test against this target; it is skipped with the reason. */
|
|
293
|
+
class CheckNotApplicable extends Error {
|
|
294
|
+
constructor(reason) {
|
|
295
|
+
super(reason);
|
|
296
|
+
this.name = "CheckNotApplicable";
|
|
297
|
+
}
|
|
298
|
+
}
|
|
324
299
|
/** The payment flow was never started, so neither payment check has a verdict. */
|
|
325
300
|
class PaymentNotAttemptedError extends Error {
|
|
326
301
|
constructor(reason) {
|
|
@@ -328,44 +303,236 @@ class PaymentNotAttemptedError extends Error {
|
|
|
328
303
|
this.name = "PaymentNotAttemptedError";
|
|
329
304
|
}
|
|
330
305
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
306
|
+
/**
|
|
307
|
+
* No payment adapter pays on this network, so the payment checks cannot be
|
|
308
|
+
* graded here. A `ConfigurationError`, so a caller that does not know the class
|
|
309
|
+
* still reads it as no verdict; preflight turns it into a skip of kind
|
|
310
|
+
* `unsupported` (spec A3). It is not the guard's refusal: `stellar:pubnet` has
|
|
311
|
+
* an adapter and is refused by `assertPaymentNetworkAllowed`, as an error.
|
|
312
|
+
*/
|
|
313
|
+
export class UnsupportedPaymentNetworkError extends ConfigurationError {
|
|
314
|
+
network;
|
|
315
|
+
constructor(network) {
|
|
316
|
+
super(`Wasit's payment checks pay on ${paymentNetworks().join(", ")}; ` +
|
|
317
|
+
`${sanitizeText(JSON.stringify(String(network)))} is not one of them, so no payment ` +
|
|
318
|
+
`was attempted. X402-01..05 still apply to a challenge on any chain.`);
|
|
319
|
+
this.name = "UnsupportedPaymentNetworkError";
|
|
320
|
+
this.network = String(network);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* The adapter for the run's network. Throws `UnsupportedPaymentNetworkError`
|
|
325
|
+
* for a network the payment checks cannot pay on; preflight calls this before
|
|
326
|
+
* anything is sent.
|
|
327
|
+
*/
|
|
328
|
+
function chainFor(network) {
|
|
329
|
+
const chain = paymentChainFor(network);
|
|
330
|
+
if (chain === undefined)
|
|
331
|
+
throw new UnsupportedPaymentNetworkError(network);
|
|
332
|
+
return chain;
|
|
333
|
+
}
|
|
334
|
+
async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin) {
|
|
335
|
+
const client = new x402Client();
|
|
336
|
+
// L3 (spec B3): the SDK's own spend controls, set here rather than left to
|
|
337
|
+
// its default, as a second implementation of the $1 cap. An adapter that
|
|
338
|
+
// allows more assets replaces them and states the cap again (`evm.ts`).
|
|
339
|
+
client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` });
|
|
340
|
+
await chain.registerPayer(client, network, payerSecretKey, rpcUrl);
|
|
341
|
+
client
|
|
342
|
+
// A challenge may offer several networks, including both Stellar ones.
|
|
343
|
+
// The client's default pick is the first it supports, which would sign
|
|
344
|
+
// for one network with a signer built for another; pay only on the
|
|
345
|
+
// network this run was asked to use. With a pin, L3 also keeps only the
|
|
346
|
+
// pinned payee and asset, whatever else picked the option.
|
|
347
|
+
.registerPolicy((_version, requirements) => requirements.filter((requirement) => requirement.network === network &&
|
|
348
|
+
(pin === undefined ||
|
|
349
|
+
(sameAddress(network, requirement.payTo, pin.payTo) && sameAddress(network, requirement.asset, pin.asset)))));
|
|
334
350
|
return { client, httpClient: new x402HTTPClient(client) };
|
|
335
351
|
}
|
|
352
|
+
/** The networks a challenge offers, for a report. */
|
|
353
|
+
function describeOffered(accepts) {
|
|
354
|
+
const networks = [...new Set(accepts.map((requirement) => requirement.network))];
|
|
355
|
+
return networks.length === 0 ? "none" : networks.join(", ");
|
|
356
|
+
}
|
|
357
|
+
/** What the SDK client's spend controls say when they refuse a payment. */
|
|
358
|
+
const SPEND_CONTROLS_REFUSAL = "All payment requirements were rejected by spendControls";
|
|
336
359
|
/**
|
|
337
|
-
*
|
|
360
|
+
* Builds a payment, turning a refusal by the SDK client's spend controls into
|
|
361
|
+
* no verdict that says why.
|
|
362
|
+
*
|
|
363
|
+
* The official client pays only its default assets (plus the ones an adapter
|
|
364
|
+
* allows, such as Circle's USDC on Ethereum Sepolia) and at most $1 a
|
|
365
|
+
* payment, so that a paywall cannot charge a payer more than it meant to.
|
|
366
|
+
* Wasit keeps those limits: it pays automatically, and on `stellar:pubnet`
|
|
367
|
+
* with real money. A target above them is not at fault, and nothing was
|
|
368
|
+
* sent, so this is `ERROR (setup)`, not a harness error. Matched on the SDK's
|
|
369
|
+
* message (`@x402/core` 2.28 `client/index.mjs`); a message it does not
|
|
370
|
+
* recognise passes through as before.
|
|
371
|
+
*/
|
|
372
|
+
async function withinSpendControls(network, selected, build) {
|
|
373
|
+
try {
|
|
374
|
+
return await build();
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
const message = error instanceof Error ? error.message : "";
|
|
378
|
+
if (!message.startsWith(SPEND_CONTROLS_REFUSAL))
|
|
379
|
+
throw error;
|
|
380
|
+
if (message.includes("only default assets")) {
|
|
381
|
+
throw new CheckSetupError(`The target asks to be paid in ${selected.asset} on ${network}, which is not ` +
|
|
382
|
+
`an asset the official x402 client pays in by default, nor one Wasit allows, ` +
|
|
383
|
+
`so nothing was sent.`);
|
|
384
|
+
}
|
|
385
|
+
throw new CheckSetupError(`The target asks for ${selected.amount} base units of ${selected.asset}, more ` +
|
|
386
|
+
`than the $1 a payment the official x402 client pays by default, so nothing ` +
|
|
387
|
+
`was sent. The cap keeps a paywall from charging a payer more than it meant ` +
|
|
388
|
+
`to; a target priced at $1 or less is checked as usual.`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* What a payment check reads before it can pay: the challenge, the URL to pay
|
|
393
|
+
* at, and the one option it would pay. Shared by `preparePayment` and the plan
|
|
394
|
+
* (L1), so both judge the same option by the same rules.
|
|
338
395
|
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
396
|
+
* Throws `PaymentNotAttemptedError` when there is nothing to pay: an
|
|
397
|
+
* unreadable or v1 challenge, no option on the run's network, or none in the
|
|
398
|
+
* `exact` scheme.
|
|
341
399
|
*/
|
|
342
|
-
async function
|
|
343
|
-
|
|
344
|
-
|
|
400
|
+
export async function readPaymentChallenge(options) {
|
|
401
|
+
// The payment goes where this challenge came from, never through a redirect
|
|
402
|
+
// (D-022c): `payUrl` is the target, or the URL one same-origin redirect led to.
|
|
403
|
+
const { response: challenge, url: payUrl } = await fetchPaymentChallenge(options.target, buildInit(options));
|
|
404
|
+
return { ...(await paymentTerms(challenge, options.network)), payUrl };
|
|
405
|
+
}
|
|
406
|
+
/** The terms of a challenge already fetched, by the rules of {@link readPaymentChallenge}. */
|
|
407
|
+
async function paymentTerms(challenge, network) {
|
|
408
|
+
const options = { network };
|
|
345
409
|
let paymentRequired;
|
|
346
410
|
try {
|
|
347
|
-
paymentRequired =
|
|
411
|
+
paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name));
|
|
348
412
|
}
|
|
349
413
|
catch (error) {
|
|
350
414
|
// The read checks already report what is wrong with the challenge. Failing
|
|
351
|
-
//
|
|
415
|
+
// the payment checks here too would count one broken challenge many times, and
|
|
352
416
|
// would make X402-07 read as a signature that was not rejected when no
|
|
353
417
|
// payment was ever sent. docs/CHECKS.md: an unreadable challenge produces
|
|
354
418
|
// no verdict.
|
|
355
419
|
const v1 = readV1BodyChallenge(await readText(challenge)) !== undefined;
|
|
356
420
|
throw new PaymentNotAttemptedError(v1
|
|
357
|
-
? `the target issued an x402 v1 challenge, and Wasit
|
|
358
|
-
`v2
|
|
359
|
-
`so no payment was attempted (see X402-02).`
|
|
421
|
+
? `the target issued an x402 v1 challenge, and Wasit's payment checks ` +
|
|
422
|
+
`pay through x402 v2 only (on Stellar, the only version the \`exact\` ` +
|
|
423
|
+
`scheme defines), so no payment was attempted (see X402-02).`
|
|
360
424
|
: `the challenge could not be read as x402 payment requirements ` +
|
|
361
425
|
`(${error.message}), so no payment was attempted ` +
|
|
362
426
|
`(see X402-02–04).`);
|
|
363
427
|
}
|
|
364
|
-
|
|
365
|
-
|
|
428
|
+
await challenge.body?.cancel().catch(() => undefined);
|
|
429
|
+
// A target that offers no option Wasit can pay has not refused anything:
|
|
430
|
+
// there is no payment to judge, so neither check gets a verdict. X402-05
|
|
431
|
+
// already reports which networks it advertises.
|
|
432
|
+
const onNetwork = paymentRequired.accepts.filter((requirement) => requirement.network === options.network);
|
|
433
|
+
if (onNetwork.length === 0) {
|
|
434
|
+
throw new PaymentNotAttemptedError(`the target offers no payment option on ${options.network} (it offers ` +
|
|
435
|
+
`${describeOffered(paymentRequired.accepts)}), so no payment was ` +
|
|
436
|
+
`attempted (see X402-05).`);
|
|
437
|
+
}
|
|
438
|
+
if (!onNetwork.some((requirement) => requirement.scheme === "exact")) {
|
|
439
|
+
throw new PaymentNotAttemptedError(`the target's ${options.network} option uses the ` +
|
|
440
|
+
`"${onNetwork[0].scheme}" scheme, and Wasit pays through the \`exact\` ` +
|
|
441
|
+
`scheme only, so no payment was attempted.`);
|
|
442
|
+
}
|
|
443
|
+
const selected = onNetwork.find((requirement) => requirement.scheme === "exact");
|
|
444
|
+
// The payment-identifier extension lets a server answer a repeated payload
|
|
445
|
+
// with its cached response (specs/extensions/payment_identifier.md).
|
|
446
|
+
const idempotent = paymentRequired.extensions?.["payment-identifier"] !== undefined;
|
|
447
|
+
return { paymentRequired, selected, idempotent };
|
|
448
|
+
}
|
|
449
|
+
/** A stable text of a value, keys sorted, for a field-by-field comparison. */
|
|
450
|
+
function canonical(value) {
|
|
451
|
+
return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item)
|
|
452
|
+
? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
|
|
453
|
+
: item);
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* L2 against the plan: the option a check is about to pay must be the one the
|
|
457
|
+
* plan read, and the amount at most what the plan allowed for that check.
|
|
458
|
+
* Returns that amount, or undefined when the run has no plan.
|
|
459
|
+
*/
|
|
460
|
+
function plannedAmount(plan, check, selected) {
|
|
461
|
+
if (plan === undefined)
|
|
462
|
+
return undefined;
|
|
463
|
+
const option = plan.option;
|
|
464
|
+
if (plan.status !== "planned" || option === undefined) {
|
|
465
|
+
throw new PaymentGuardRefusedError("plan", `The plan of this run did not plan a payment for ${plan.name} (${plan.status}), so ${check} does not pay it.` +
|
|
466
|
+
(plan.reason === undefined ? "" : ` The plan says: ${plan.reason}`));
|
|
467
|
+
}
|
|
468
|
+
for (const field of ["scheme", "network", "payTo", "asset"]) {
|
|
469
|
+
const same = field === "payTo" || field === "asset"
|
|
470
|
+
? sameAddress(option.network, String(selected[field]), option[field])
|
|
471
|
+
: selected[field] === option[field];
|
|
472
|
+
if (!same) {
|
|
473
|
+
throw new PaymentGuardRefusedError("plan", `${check}: the service changed its ${field} after the plan (the plan read ${option[field]}), ` +
|
|
474
|
+
`so the payment the plan allowed is not the one it now asks for.`);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const entry = plan.signatures.find((signature) => signature.check === check);
|
|
478
|
+
if (entry === undefined) {
|
|
479
|
+
throw new PaymentGuardRefusedError("plan", `The plan of this run has no signature for ${check}.`);
|
|
480
|
+
}
|
|
481
|
+
return entry.amount;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Reads the challenge and produces a signed payment payload for it.
|
|
485
|
+
*
|
|
486
|
+
* Shared by every payment check so each one starts from a challenge the
|
|
487
|
+
* target issued just now, rather than reusing a stale one. With `altered`,
|
|
488
|
+
* the payment is signed for those terms instead, and its `accepted` is set
|
|
489
|
+
* back to what the target advertised. `beforeSigning` runs once the option
|
|
490
|
+
* to pay is known and before the client builds anything: the Stellar client
|
|
491
|
+
* simulates the transfer while building, so a check placed later would never
|
|
492
|
+
* see an unfunded payer.
|
|
493
|
+
*
|
|
494
|
+
* L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over
|
|
495
|
+
* every `exact` option, the plan, the $1 cap and the run's cap, the run charged
|
|
496
|
+
* before the signature. The SDK is then handed exactly the one option checked,
|
|
497
|
+
* and a payload whose `accepted` is not that option is discarded unsent.
|
|
498
|
+
*/
|
|
499
|
+
async function preparePayment(options, check, alter, beforeSigning) {
|
|
500
|
+
// L0 again at the one function every x402 signature goes through, whoever
|
|
501
|
+
// reaches it: nothing is fetched or signed on a network that is not a test
|
|
502
|
+
// network.
|
|
503
|
+
assertPaymentNetworkAllowed("x402", options.network);
|
|
504
|
+
const chain = chainFor(options.network);
|
|
505
|
+
const budget = options.budget ?? new RunBudget();
|
|
506
|
+
const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, chain.resolveRpcUrl(options.network, options.rpcUrl), options.pin);
|
|
507
|
+
const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options);
|
|
508
|
+
// L2, before anything is built: the service may change its challenge between
|
|
509
|
+
// requests, so the plan alone is not enough.
|
|
510
|
+
assertPinned(options.network, paymentRequired.accepts, options.pin);
|
|
511
|
+
const planned = plannedAmount(options.plan, check, selected);
|
|
512
|
+
const signing = alter === undefined ? selected : { ...selected, ...(await alter(selected)) };
|
|
513
|
+
for (const field of ["scheme", "network", "payTo", "asset"]) {
|
|
514
|
+
if (signing[field] !== selected[field]) {
|
|
515
|
+
throw new PaymentGuardRefusedError("accepted", `${check} would sign different ${field} terms than the target's.`);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
budget.charge({
|
|
519
|
+
check,
|
|
520
|
+
network: options.network,
|
|
521
|
+
asset: signing.asset,
|
|
522
|
+
amount: signing.amount,
|
|
523
|
+
...(planned === undefined ? {} : { planned }),
|
|
524
|
+
});
|
|
525
|
+
await beforeSigning?.(selected);
|
|
526
|
+
const signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }));
|
|
527
|
+
// What the SDK says it signed must be the option checked, field by field;
|
|
528
|
+
// otherwise the payload is discarded here, unsent. It stays charged.
|
|
529
|
+
if (canonical(signed.accepted) !== canonical(signing)) {
|
|
530
|
+
throw new PaymentGuardRefusedError("accepted", `The payment the x402 client built for ${check} names other terms in its accepted field than the ` +
|
|
531
|
+
`option Wasit checked.`, { signed: true });
|
|
532
|
+
}
|
|
533
|
+
const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected };
|
|
534
|
+
return { httpClient, paymentPayload, selected, idempotent, payUrl };
|
|
366
535
|
}
|
|
367
|
-
/** A Stellar transaction hash: 64 hex characters. */
|
|
368
|
-
const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
|
|
369
536
|
/**
|
|
370
537
|
* Reads the settlement a paid response reports, before anything is looked up.
|
|
371
538
|
*
|
|
@@ -373,7 +540,7 @@ const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
|
|
|
373
540
|
* exercised without a network. `readSettlement` throws when the response
|
|
374
541
|
* carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
|
|
375
542
|
*/
|
|
376
|
-
export function readSettlementReference(status, readSettlement) {
|
|
543
|
+
export function readSettlementReference(status, readSettlement, chain = stellarChain) {
|
|
377
544
|
let settlement;
|
|
378
545
|
try {
|
|
379
546
|
settlement = readSettlement();
|
|
@@ -383,44 +550,99 @@ export function readSettlementReference(status, readSettlement) {
|
|
|
383
550
|
failure: `Valid payment accepted (HTTP ${status}), but the response carried no ` +
|
|
384
551
|
`PAYMENT-RESPONSE header, which the x402 v2 HTTP transport uses to ` +
|
|
385
552
|
`report settlement. Whether the payment settled cannot be verified.`,
|
|
553
|
+
hint: "After settling, return the facilitator's settle result base64-encoded " +
|
|
554
|
+
"in a PAYMENT-RESPONSE header; the official x402 middleware does this.",
|
|
386
555
|
};
|
|
387
556
|
}
|
|
388
557
|
const reference = settlement.transaction ?? "";
|
|
389
558
|
// `settlement_pending` means broadcast but unconfirmed; the x402 spec has the
|
|
390
559
|
// caller reconcile on chain, which is exactly what X402-06 goes on to do.
|
|
391
560
|
const pending = !settlement.success && settlement.errorReason === "settlement_pending";
|
|
392
|
-
if ((!settlement.success && !pending) || !
|
|
561
|
+
if ((!settlement.success && !pending) || !chain.isSettlementReference(reference)) {
|
|
393
562
|
return {
|
|
394
563
|
failure: `Valid payment accepted (HTTP ${status}), but its PAYMENT-RESPONSE ` +
|
|
395
564
|
`reports ${settlement.success ? "success" : "failure"} with transaction ` +
|
|
396
|
-
`${JSON.stringify(reference)}, not
|
|
565
|
+
`${JSON.stringify(reference)}, not ${chain.referenceKind}.`,
|
|
566
|
+
hint: "PAYMENT-RESPONSE must report `success: true` and carry the settlement " +
|
|
567
|
+
"transaction's hash in `transaction`.",
|
|
397
568
|
};
|
|
398
569
|
}
|
|
399
570
|
return { reference };
|
|
400
571
|
}
|
|
401
572
|
/**
|
|
402
|
-
* X402-06
|
|
573
|
+
* Stops X402-06 before it pays when the payer certainly cannot cover the
|
|
574
|
+
* price.
|
|
403
575
|
*
|
|
404
|
-
* A
|
|
405
|
-
*
|
|
406
|
-
* `
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
576
|
+
* A payment the payer cannot fund is refused, and the refusal reads as the
|
|
577
|
+
* target's: on Solana devnet the facilitator answers
|
|
578
|
+
* `invalid_exact_svm_transaction_simulation_failed`, the reason a real defect
|
|
579
|
+
* gives too, so it cannot be told apart afterwards; the Stellar client fails
|
|
580
|
+
* earlier, simulating the transfer while it builds, with only the token's
|
|
581
|
+
* error code. Read before signing, so a target that settles and then refuses
|
|
582
|
+
* still shows as one. Only a balance the
|
|
583
|
+
* chain reported counts: when it cannot be read, the run pays as before, and
|
|
584
|
+
* a failed read never becomes a verdict either way.
|
|
410
585
|
*/
|
|
586
|
+
async function assertPayerCanPay(options, selected) {
|
|
587
|
+
let price;
|
|
588
|
+
try {
|
|
589
|
+
price = BigInt(selected.amount);
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
const chain = chainFor(options.network);
|
|
595
|
+
let balance;
|
|
596
|
+
try {
|
|
597
|
+
balance = await chain.payerBalance(options.network, chain.resolveRpcUrl(options.network, options.rpcUrl), chain.payerAddress(options.payerSecretKey), selected.asset);
|
|
598
|
+
}
|
|
599
|
+
catch {
|
|
600
|
+
balance = undefined;
|
|
601
|
+
}
|
|
602
|
+
if (balance !== undefined && balance < price) {
|
|
603
|
+
throw new CheckSetupError(`This run's payer holds less of ${selected.asset} than the advertised ${price} ` +
|
|
604
|
+
`base units, so its payment cannot settle, and a refusal would say nothing ` +
|
|
605
|
+
`about the target. Fund the payer (${chain.payerKeyEnv}), then re-run.`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
411
608
|
async function checkSignatureAccepted(options) {
|
|
412
609
|
const id = "X402-06";
|
|
413
610
|
const name = "Signature Resubmit Accepted";
|
|
414
|
-
const fail = (detail) => ({ id, name, pass: false, detail });
|
|
415
|
-
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
611
|
+
const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
|
|
612
|
+
const { httpClient, paymentPayload, idempotent, payUrl } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
|
|
416
613
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
|
|
417
|
-
const paid = await fetchTarget(
|
|
614
|
+
const paid = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders));
|
|
615
|
+
const honest = (result, accepted) => ({
|
|
616
|
+
result,
|
|
617
|
+
accepted,
|
|
618
|
+
headers: paymentHeaders,
|
|
619
|
+
url: payUrl,
|
|
620
|
+
idempotent,
|
|
621
|
+
payload: paymentPayload.payload,
|
|
622
|
+
});
|
|
418
623
|
if (paid.status < 200 || paid.status >= 300) {
|
|
419
|
-
|
|
624
|
+
const reason = await refusalReason(paid);
|
|
625
|
+
// Permit2 needs the payer to have approved the Permit2 contract once. A
|
|
626
|
+
// target that offers no gas-sponsored approval leaves that to the payer,
|
|
627
|
+
// so this refusal is about Wasit's payer, not the target: no verdict.
|
|
628
|
+
if (reason === "permit2_allowance_required") {
|
|
629
|
+
throw new CheckSetupError("The target pays through Permit2 without a gas-sponsored approval, and this " +
|
|
630
|
+
"run's payer has not approved the Permit2 contract for the token. Approve it " +
|
|
631
|
+
"once (an on-chain transaction that needs gas), then re-run.");
|
|
632
|
+
}
|
|
633
|
+
return honest(fail(`Expected 2xx after a valid payment, got ${paid.status}` +
|
|
634
|
+
`${reason === undefined ? "" : ` (${reason})`}.`, reason?.startsWith("settlement failed:")
|
|
635
|
+
? "The payment verified, but the facilitator did not settle it, and said why. " +
|
|
636
|
+
"That is the facilitator's failure, or its RPC's, yet a valid payment was " +
|
|
637
|
+
"refused; check the facilitator's account and endpoint, then re-run."
|
|
638
|
+
: "A valid payment was refused. Your server's log of the facilitator's " +
|
|
639
|
+
"verify or settle response says why; serve the resource with a 2xx once " +
|
|
640
|
+
"the payment settles."), false);
|
|
420
641
|
}
|
|
421
|
-
const
|
|
642
|
+
const chain = chainFor(options.network);
|
|
643
|
+
const read = readSettlementReference(paid.status, () => httpClient.getPaymentSettleResponse((header) => paid.headers.get(header)), chain);
|
|
422
644
|
if ("failure" in read)
|
|
423
|
-
return fail(read.failure);
|
|
645
|
+
return honest(fail(read.failure, read.hint), true);
|
|
424
646
|
const reference = read.reference;
|
|
425
647
|
const accepted = paymentPayload.accepted;
|
|
426
648
|
let amount;
|
|
@@ -431,71 +653,25 @@ async function checkSignatureAccepted(options) {
|
|
|
431
653
|
throw new MalformedResponseError(`The accepted payment requirements carry a non-numeric amount ` +
|
|
432
654
|
`(${JSON.stringify(accepted.amount)}).`);
|
|
433
655
|
}
|
|
434
|
-
const rpcUrl = resolveRpcUrl(options.network, options.rpcUrl);
|
|
435
|
-
const verdict = await verifySettlement(rpcUrl, reference, {
|
|
656
|
+
const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
|
|
657
|
+
const verdict = await chain.verifySettlement(options.network, rpcUrl, reference, {
|
|
436
658
|
amount,
|
|
437
659
|
token: accepted.asset,
|
|
438
660
|
recipient: accepted.payTo,
|
|
439
|
-
payer:
|
|
661
|
+
payer: chain.payerAddress(options.payerSecretKey),
|
|
440
662
|
});
|
|
441
|
-
return verdict.pass
|
|
663
|
+
return honest(verdict.pass
|
|
442
664
|
? {
|
|
443
665
|
id,
|
|
444
666
|
name,
|
|
445
667
|
pass: true,
|
|
446
668
|
detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
|
|
669
|
+
// Read back from the chain and found to be this payment: a report may link it.
|
|
670
|
+
reference,
|
|
447
671
|
}
|
|
448
|
-
: fail(verdict.detail
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
* Corrupts the client's authorization signature, and nothing else.
|
|
452
|
-
*
|
|
453
|
-
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
454
|
-
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
455
|
-
* signature that proves the payer consented is the address credential's
|
|
456
|
-
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
457
|
-
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
458
|
-
* recipient, and fails only signature verification. A target can refuse it
|
|
459
|
-
* only by verifying the signature.
|
|
460
|
-
*
|
|
461
|
-
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
462
|
-
* the check reports no verdict rather than one it did not establish.
|
|
463
|
-
*/
|
|
464
|
-
export function corruptAuthSignature(transaction) {
|
|
465
|
-
const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
|
|
466
|
-
const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
|
|
467
|
-
let corrupted = false;
|
|
468
|
-
for (const operation of operations) {
|
|
469
|
-
if (operation.body().switch().name !== "invokeHostFunction")
|
|
470
|
-
continue;
|
|
471
|
-
for (const entry of operation.body().invokeHostFunctionOp().auth()) {
|
|
472
|
-
const credentials = entry.credentials();
|
|
473
|
-
if (credentials.switch().name !== "sorobanCredentialsAddress")
|
|
474
|
-
continue;
|
|
475
|
-
const signature = credentials.address().signature();
|
|
476
|
-
if (signature.switch().name !== "scvVec")
|
|
477
|
-
continue;
|
|
478
|
-
for (const item of signature.vec() ?? []) {
|
|
479
|
-
if (item.switch().name !== "scvMap")
|
|
480
|
-
continue;
|
|
481
|
-
for (const field of item.map() ?? []) {
|
|
482
|
-
if (field.key().switch().name !== "scvSymbol")
|
|
483
|
-
continue;
|
|
484
|
-
if (field.key().sym().toString() !== "signature")
|
|
485
|
-
continue;
|
|
486
|
-
const bytes = Buffer.from(field.val().bytes());
|
|
487
|
-
bytes[0] = bytes[0] ^ 0xff;
|
|
488
|
-
field.val(xdr.ScVal.scvBytes(bytes));
|
|
489
|
-
corrupted = true;
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
if (!corrupted) {
|
|
495
|
-
throw new CheckSetupError("The payment payload carries no authorization-entry signature to " +
|
|
496
|
-
"corrupt, so a corrupted signature cannot be tested.");
|
|
497
|
-
}
|
|
498
|
-
return envelope.toXDR("base64");
|
|
672
|
+
: fail(verdict.detail, "PAYMENT-RESPONSE must name the transaction that settled this payment, " +
|
|
673
|
+
"and that transaction must move exactly `amount` of `asset` from the " +
|
|
674
|
+
"payer to `payTo`, in a single transfer."), true);
|
|
499
675
|
}
|
|
500
676
|
/**
|
|
501
677
|
* X402-07 (negative): a corrupted signature must be rejected.
|
|
@@ -511,79 +687,564 @@ export function corruptAuthSignature(transaction) {
|
|
|
511
687
|
* answer: anything that prevents one produces no verdict.
|
|
512
688
|
*/
|
|
513
689
|
async function checkInvalidSignatureRejected(options) {
|
|
514
|
-
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
690
|
+
const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07");
|
|
515
691
|
const corrupted = {
|
|
516
692
|
...paymentPayload,
|
|
517
|
-
payload:
|
|
518
|
-
...paymentPayload.payload,
|
|
519
|
-
transaction: corruptAuthSignature(paymentPayload.payload.transaction),
|
|
520
|
-
},
|
|
693
|
+
payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
|
|
521
694
|
};
|
|
522
695
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
|
|
523
|
-
const response = await fetchTarget(
|
|
524
|
-
|
|
696
|
+
const response = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders));
|
|
697
|
+
return signatureRejectionVerdict(response.status, await refusalReason(response));
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* X402-07's verdict from the status a corrupted payment drew. Split out so
|
|
701
|
+
* the verdict can be tested without building a payment.
|
|
702
|
+
*/
|
|
703
|
+
export function signatureRejectionVerdict(status, reason) {
|
|
704
|
+
const accepted = status >= 200 && status < 300;
|
|
525
705
|
return {
|
|
526
706
|
id: "X402-07",
|
|
527
707
|
name: "Invalid Signature Rejected",
|
|
528
708
|
pass: !accepted,
|
|
529
709
|
detail: accepted
|
|
530
710
|
? `A payment with a corrupted authorization signature was accepted with ` +
|
|
531
|
-
`HTTP ${
|
|
711
|
+
`HTTP ${status} — security-relevant failure.`
|
|
532
712
|
: `Payment with a corrupted authorization signature correctly rejected ` +
|
|
533
|
-
`(
|
|
713
|
+
`(${statusWithReason(status, reason)}).`,
|
|
714
|
+
...(accepted
|
|
715
|
+
? {
|
|
716
|
+
hint: "Verify every payment before serving: pass it to the facilitator's " +
|
|
717
|
+
"verify step and refuse it when verification fails. Never serve on a " +
|
|
718
|
+
"payload that was only decoded.",
|
|
719
|
+
}
|
|
720
|
+
: {}),
|
|
534
721
|
};
|
|
535
722
|
}
|
|
723
|
+
/** Any 2xx is the target serving the resource. */
|
|
724
|
+
function served(status) {
|
|
725
|
+
return status >= 200 && status < 300;
|
|
726
|
+
}
|
|
536
727
|
/**
|
|
537
|
-
*
|
|
728
|
+
* Why the target refused a payment, when it says. A payment refused at
|
|
729
|
+
* verify comes back with a fresh challenge whose `error` names the reason
|
|
730
|
+
* (often the facilitator's, e.g. `invalid_exact_evm_payload_signature`). One
|
|
731
|
+
* that verified but did not settle comes back with a `PAYMENT-RESPONSE` whose
|
|
732
|
+
* `success` is false and whose `errorReason` says why, as the official SDK
|
|
733
|
+
* server sends it; that is read first, and named as a settlement failure, so
|
|
734
|
+
* an operator can tell their facilitator's failure from a refusal. Shown with
|
|
735
|
+
* a PASS so a reader can tell the refusal came from the rule the check is
|
|
736
|
+
* about, not from something else that also answers 402.
|
|
737
|
+
*/
|
|
738
|
+
async function refusalReason(response) {
|
|
739
|
+
const decode = (header) => {
|
|
740
|
+
try {
|
|
741
|
+
return asRecord(JSON.parse(Buffer.from(header, "base64").toString("utf-8")));
|
|
742
|
+
}
|
|
743
|
+
catch {
|
|
744
|
+
return undefined;
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
const settlement = response.headers.get("PAYMENT-RESPONSE");
|
|
748
|
+
if (settlement !== null) {
|
|
749
|
+
const parsed = decode(settlement);
|
|
750
|
+
const reason = parsed?.["errorReason"];
|
|
751
|
+
if (parsed?.["success"] === false && typeof reason === "string" && reason.length > 0) {
|
|
752
|
+
// The reason is a code; some facilitators append a long RPC message.
|
|
753
|
+
return `settlement failed: ${/^[\w.-]+/.exec(reason)?.[0] ?? reason}`;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
const errorOf = (record) => {
|
|
757
|
+
const error = record?.["error"];
|
|
758
|
+
return typeof error === "string" && error.length > 0 ? error : undefined;
|
|
759
|
+
};
|
|
760
|
+
const header = response.headers.get("PAYMENT-REQUIRED");
|
|
761
|
+
if (header !== null)
|
|
762
|
+
return errorOf(decode(header));
|
|
763
|
+
try {
|
|
764
|
+
return errorOf(asRecord(JSON.parse(await readText(response))));
|
|
765
|
+
}
|
|
766
|
+
catch {
|
|
767
|
+
return undefined;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
function statusWithReason(status, reason) {
|
|
771
|
+
return reason === undefined ? `HTTP ${status}` : `HTTP ${status}: ${reason}`;
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* X402-08 (negative): a payment already accepted must not be accepted again.
|
|
538
775
|
*
|
|
539
|
-
*
|
|
776
|
+
* The headers X402-06's honest payment was sent with are sent once more,
|
|
777
|
+
* byte for byte. Each authorization is single-use: an EIP-3009 nonce, or a
|
|
778
|
+
* Soroban auth entry's nonce, is spent once the payment settles, so the
|
|
779
|
+
* facilitator's verify refuses it (spec §10.1). A target that serves it again
|
|
780
|
+
* has sold the resource twice for one payment. Nothing can settle twice.
|
|
540
781
|
*/
|
|
541
|
-
|
|
782
|
+
async function checkReplayRejected(options, honest) {
|
|
783
|
+
if (honest.idempotent) {
|
|
784
|
+
return skipped("X402-08", "Payment Replay Rejected", "the challenge advertises the payment-identifier extension, under which a " +
|
|
785
|
+
"server may answer a repeated payment with its cached response.");
|
|
786
|
+
}
|
|
787
|
+
const response = await fetchTarget(honest.url, withPaymentHeaders(options, honest.headers));
|
|
788
|
+
return replayVerdict(response.status, await refusalReason(response));
|
|
789
|
+
}
|
|
790
|
+
/** X402-08's verdict from the status the replayed payment drew. */
|
|
791
|
+
export function replayVerdict(status, reason) {
|
|
792
|
+
const accepted = served(status);
|
|
793
|
+
return {
|
|
794
|
+
id: "X402-08",
|
|
795
|
+
name: "Payment Replay Rejected",
|
|
796
|
+
pass: !accepted,
|
|
797
|
+
detail: accepted
|
|
798
|
+
? `The payment X402-06 had already been accepted for was accepted again ` +
|
|
799
|
+
`(HTTP ${status}): one payment bought the resource twice.`
|
|
800
|
+
: `The same payment, sent again, was refused (${statusWithReason(status, reason)}).`,
|
|
801
|
+
...(accepted
|
|
802
|
+
? {
|
|
803
|
+
hint: "Treat every payment as single-use: verify it with the facilitator " +
|
|
804
|
+
"before serving, which refuses an authorization whose nonce is already " +
|
|
805
|
+
"spent, and never serve the same payload twice.",
|
|
806
|
+
}
|
|
807
|
+
: {}),
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* X402-09 (negative): a validly signed payment for less than the price must
|
|
812
|
+
* be rejected.
|
|
813
|
+
*
|
|
814
|
+
* The payment is signed for half the advertised amount, while its `accepted`
|
|
815
|
+
* still claims the advertised terms, so the signature is good and only the
|
|
816
|
+
* amount is wrong. The facilitator must hold the signed amount to the
|
|
817
|
+
* requirement (Stellar: exactly; EVM: verification step 3). If the target
|
|
818
|
+
* accepts, the lower amount may settle.
|
|
819
|
+
*/
|
|
820
|
+
async function checkUnderpaymentRejected(options) {
|
|
821
|
+
// The plan of `wasit run` leaves X402-09 out at a price below 2 base units;
|
|
822
|
+
// the check is then skipped as it is without a plan, and nothing is fetched.
|
|
823
|
+
const plan = options.plan;
|
|
824
|
+
if (plan?.status === "planned" &&
|
|
825
|
+
plan.option !== undefined &&
|
|
826
|
+
plan.option.amount < 2n &&
|
|
827
|
+
!plan.signatures.some((signature) => signature.check === "X402-09")) {
|
|
828
|
+
const price = plan.option.amount;
|
|
829
|
+
return skipped("X402-09", "Underpayment Rejected", `the advertised price is ${price} base unit${price === 1n ? "" : "s"} (as the plan read it before the run), so ` +
|
|
830
|
+
`there is no smaller payment to offer.`);
|
|
831
|
+
}
|
|
832
|
+
let advertised = 0n;
|
|
833
|
+
let offered = 0n;
|
|
834
|
+
let prepared;
|
|
835
|
+
try {
|
|
836
|
+
prepared = await preparePayment(options, "X402-09", (selected) => {
|
|
837
|
+
try {
|
|
838
|
+
advertised = BigInt(selected.amount);
|
|
839
|
+
}
|
|
840
|
+
catch {
|
|
841
|
+
throw new MalformedResponseError(`The payment requirements carry a non-numeric amount (${JSON.stringify(selected.amount)}).`);
|
|
842
|
+
}
|
|
843
|
+
if (advertised < 2n) {
|
|
844
|
+
throw new CheckNotApplicable(`the advertised price is ${advertised} base unit${advertised === 1n ? "" : "s"}, so ` +
|
|
845
|
+
`there is no smaller payment to offer.`);
|
|
846
|
+
}
|
|
847
|
+
offered = advertised / 2n;
|
|
848
|
+
return { amount: offered.toString() };
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
catch (error) {
|
|
852
|
+
if (error instanceof CheckNotApplicable) {
|
|
853
|
+
return skipped("X402-09", "Underpayment Rejected", error.message);
|
|
854
|
+
}
|
|
855
|
+
throw error;
|
|
856
|
+
}
|
|
857
|
+
const { httpClient, paymentPayload, payUrl } = prepared;
|
|
858
|
+
const response = await fetchTarget(payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
|
|
859
|
+
return underpaymentVerdict(response.status, offered, advertised, await refusalReason(response));
|
|
860
|
+
}
|
|
861
|
+
/** X402-09's verdict from the status the underpaid payment drew. */
|
|
862
|
+
export function underpaymentVerdict(status, offered, advertised, reason) {
|
|
863
|
+
const accepted = served(status);
|
|
864
|
+
return {
|
|
865
|
+
id: "X402-09",
|
|
866
|
+
name: "Underpayment Rejected",
|
|
867
|
+
pass: !accepted,
|
|
868
|
+
detail: accepted
|
|
869
|
+
? `A validly signed payment for ${offered} of the advertised ${advertised} base ` +
|
|
870
|
+
`units was accepted (HTTP ${status}) — security-relevant failure: the target ` +
|
|
871
|
+
`served for less than its price.`
|
|
872
|
+
: `A validly signed payment for ${offered} of the advertised ${advertised} base ` +
|
|
873
|
+
`units was refused (${statusWithReason(status, reason)}).`,
|
|
874
|
+
...(accepted
|
|
875
|
+
? {
|
|
876
|
+
hint: "Hold the signed payment to the advertised amount before serving. The " +
|
|
877
|
+
"facilitator's verify does; a server that skips it, or checks only the " +
|
|
878
|
+
"signature, sells for less than its price.",
|
|
879
|
+
}
|
|
880
|
+
: {}),
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* X402-10 (negative): a payment whose authorization has expired must be
|
|
885
|
+
* rejected.
|
|
886
|
+
*
|
|
887
|
+
* Each chain says how the payment is made to expire (`expiredSigning`): on
|
|
888
|
+
* Stellar and EVM it is signed with a one-second lifetime (the auth entry's
|
|
889
|
+
* expiration ledger, or `validBefore`, both derived from `maxTimeoutSeconds`)
|
|
890
|
+
* and held until that has passed; on Solana it is built on a blockhash already
|
|
891
|
+
* past its lifetime. It is sent claiming the advertised terms. An expired
|
|
892
|
+
* authorization cannot settle, so a target that serves it serves for nothing.
|
|
893
|
+
*/
|
|
894
|
+
async function checkExpiredRejected(options) {
|
|
895
|
+
const chain = chainFor(options.network);
|
|
896
|
+
const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
|
|
897
|
+
let holdMs = 0;
|
|
898
|
+
const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-10", async (selected) => {
|
|
899
|
+
const expired = await chain.expiredSigning(selected, rpcUrl);
|
|
900
|
+
holdMs = expired.holdMs;
|
|
901
|
+
return expired.terms;
|
|
902
|
+
});
|
|
903
|
+
await new Promise((done) => setTimeout(done, holdMs));
|
|
904
|
+
const response = await fetchTarget(payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
|
|
905
|
+
return expiredVerdict(response.status, await refusalReason(response));
|
|
906
|
+
}
|
|
907
|
+
/** X402-10's verdict from the status the expired payment drew. */
|
|
908
|
+
export function expiredVerdict(status, reason) {
|
|
909
|
+
const accepted = served(status);
|
|
910
|
+
return {
|
|
911
|
+
id: "X402-10",
|
|
912
|
+
name: "Expired Authorization Rejected",
|
|
913
|
+
pass: !accepted,
|
|
914
|
+
detail: accepted
|
|
915
|
+
? `A payment whose authorization had already expired was accepted (HTTP ` +
|
|
916
|
+
`${status}). It cannot settle, so the target served for nothing.`
|
|
917
|
+
: `A payment whose authorization had expired was refused (${statusWithReason(status, reason)}).`,
|
|
918
|
+
...(accepted
|
|
919
|
+
? {
|
|
920
|
+
hint: "Verify each payment with the facilitator before serving: it refuses an " +
|
|
921
|
+
"authorization past its window (validBefore on EVM, the auth entry's " +
|
|
922
|
+
"expiration ledger on Stellar, the recent blockhash on Solana).",
|
|
923
|
+
}
|
|
924
|
+
: {}),
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
/** A signed authorization, decoded and held to the run's payer; `what` names it in a message. */
|
|
928
|
+
function authorizationOf(chain, payload, payer, what) {
|
|
929
|
+
const watch = chain.authorizations;
|
|
930
|
+
let decoded;
|
|
931
|
+
try {
|
|
932
|
+
decoded = watch.decode(payload);
|
|
933
|
+
}
|
|
934
|
+
catch (error) {
|
|
935
|
+
if (error instanceof CheckSetupError)
|
|
936
|
+
throw error;
|
|
937
|
+
throw new CheckSetupError(`The authorization of ${what} could not be read from its payload (${error.message}).`);
|
|
938
|
+
}
|
|
939
|
+
if (decoded.payer !== payer) {
|
|
940
|
+
throw new CheckSetupError(`The authorization of ${what} is signed by another address than this run's payer.`);
|
|
941
|
+
}
|
|
942
|
+
return decoded;
|
|
943
|
+
}
|
|
944
|
+
/** A lifetime X402-11 signs for: at least 30 s, and at most the 300 s it waits out. */
|
|
945
|
+
function withinRejectLifetime(value) {
|
|
946
|
+
const lifetime = Number(value);
|
|
947
|
+
return lifetime >= REJECTED_REQUEST_MIN_LIFETIME_SECONDS && lifetime <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS;
|
|
948
|
+
}
|
|
949
|
+
/** Thrown before signing when the challenge X402-11 is paid from advertises a lifetime it does not sign for. */
|
|
950
|
+
class RejectLifetimeOutside extends Error {
|
|
951
|
+
lifetime;
|
|
952
|
+
constructor(lifetime) {
|
|
953
|
+
super("the advertised lifetime is outside what X402-11 signs for");
|
|
954
|
+
this.lifetime = lifetime;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* X402-11 (negative, spec B7 as D-032 changed it): a valid payment sent with a
|
|
959
|
+
* request the service must refuse must not settle. See `rejected-request.ts`
|
|
960
|
+
* for the rules and the verdict.
|
|
961
|
+
*
|
|
962
|
+
* Nothing is signed when the check could not reach a verdict anyway: no
|
|
963
|
+
* reject case, X402-06 not shown settled (its nonce is the control), a chain
|
|
964
|
+
* whose authorizations Wasit cannot read, a service that refuses the request
|
|
965
|
+
* before asking for payment, an advertised lifetime above 300 s, or a control
|
|
966
|
+
* the chain does not return. The payment then goes through `preparePayment`
|
|
967
|
+
* like every other: the pin, the plan, the $1 and run caps, the advertised
|
|
968
|
+
* terms exactly.
|
|
969
|
+
*/
|
|
970
|
+
async function checkRejectedRequestNotSettled(options, honest) {
|
|
971
|
+
const id = REJECTED_REQUEST_ID;
|
|
972
|
+
const name = REJECTED_REQUEST_NAME;
|
|
973
|
+
const reject = options.reject;
|
|
974
|
+
if (reject === undefined) {
|
|
975
|
+
return skipped(id, name, "no request the service must refuse is configured (endpoints[].reject in wasit.config.json, read by " +
|
|
976
|
+
"wasit run), so there is nothing to send. Nothing was signed.", "not-applicable");
|
|
977
|
+
}
|
|
978
|
+
const chain = chainFor(options.network);
|
|
979
|
+
const watch = chain.authorizations;
|
|
980
|
+
if (watch === undefined) {
|
|
981
|
+
return skipped(id, name, `Wasit cannot read on ${chain.name} whether a payment's authorization was used, which this check needs, ` +
|
|
982
|
+
`so nothing was signed.`, "not-applicable");
|
|
983
|
+
}
|
|
984
|
+
if (honest.result.pass !== true || honest.result.error !== undefined || honest.result.skipped === true) {
|
|
985
|
+
return skipped(id, name, "X402-06's payment was not shown settled on chain, so its authorization cannot be the control that shows a " +
|
|
986
|
+
"chain read is complete. Nothing was signed.", "dependency");
|
|
987
|
+
}
|
|
988
|
+
// The reject request is the endpoint's request with the reject case over it.
|
|
989
|
+
const { method: _method, headers: _headers, body: _body, ...rest } = options;
|
|
990
|
+
const shape = rejectRequestShape(options, reject);
|
|
991
|
+
const rejectOptions = { ...rest, ...shape };
|
|
992
|
+
// Without payment first: a service that refuses it before asking for payment
|
|
993
|
+
// gives this check nothing to watch.
|
|
994
|
+
const { response: unpaid } = await fetchPaymentChallenge(options.target, buildInit(shape));
|
|
995
|
+
if (unpaid.status !== 402) {
|
|
996
|
+
await unpaid.body?.cancel().catch(() => undefined);
|
|
997
|
+
const status = unpaid.status;
|
|
998
|
+
return skipped(id, name, status >= 400 && status < 500
|
|
999
|
+
? `the service refuses this request before any payment is asked (HTTP ${status}), so there is no payment ` +
|
|
1000
|
+
`to watch. Nothing was signed.`
|
|
1001
|
+
: `the service answered this request with HTTP ${status} without asking for payment, so there is no ` +
|
|
1002
|
+
`payment to watch. Nothing was signed.`, "not-applicable");
|
|
1003
|
+
}
|
|
1004
|
+
const { selected: advertised } = await paymentTerms(unpaid, options.network);
|
|
1005
|
+
const outside = (value, again) => skipped(id, name, `the service's payments stay valid for ${sanitizeText(String(value))} seconds (maxTimeoutSeconds)` +
|
|
1006
|
+
(again ? ", as it said when asked for payment again" : "") +
|
|
1007
|
+
(Number(value) > REJECTED_REQUEST_MAX_LIFETIME_SECONDS
|
|
1008
|
+
? `, longer than the ${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds Wasit waits for one to expire on a ` +
|
|
1009
|
+
`test network, so this check could not show that the payment never settled.`
|
|
1010
|
+
: `, shorter than the ${REJECTED_REQUEST_MIN_LIFETIME_SECONDS} seconds this check needs: such a payment can ` +
|
|
1011
|
+
`expire before a service that settles it has it on chain, so its unused authorization would show nothing.`) +
|
|
1012
|
+
` Nothing was signed.`);
|
|
1013
|
+
if (!withinRejectLifetime(advertised.maxTimeoutSeconds))
|
|
1014
|
+
return outside(advertised.maxTimeoutSeconds, false);
|
|
1015
|
+
const network = options.network;
|
|
1016
|
+
const rpcUrl = chain.resolveRpcUrl(network, options.rpcUrl);
|
|
1017
|
+
const payer = chain.payerAddress(options.payerSecretKey);
|
|
1018
|
+
const control = authorizationOf(chain, honest.payload, payer, "X402-06's payment");
|
|
1019
|
+
// Before signing: the chain must return X402-06's used authorization, and the
|
|
1020
|
+
// payer's balance must be readable. Otherwise no verdict could be reached, and
|
|
1021
|
+
// nothing is signed.
|
|
1022
|
+
let balanceBefore = 0n;
|
|
1023
|
+
let prepared;
|
|
1024
|
+
try {
|
|
1025
|
+
prepared = await preparePayment(rejectOptions, id, undefined, async (selected) => {
|
|
1026
|
+
// The challenge is read again for the signature, and the service may
|
|
1027
|
+
// answer it with another lifetime: the one signed is held to 300 s too.
|
|
1028
|
+
if (!withinRejectLifetime(selected.maxTimeoutSeconds))
|
|
1029
|
+
throw new RejectLifetimeOutside(selected.maxTimeoutSeconds);
|
|
1030
|
+
let read;
|
|
1031
|
+
try {
|
|
1032
|
+
read = await watch.read(network, rpcUrl, [control]);
|
|
1033
|
+
}
|
|
1034
|
+
catch (error) {
|
|
1035
|
+
throw new CheckSetupError(`The chain could not be read before signing (${error.message}). Nothing was signed.`);
|
|
1036
|
+
}
|
|
1037
|
+
if (read.used[0] === undefined) {
|
|
1038
|
+
throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, which was used, so a later read could not show " +
|
|
1039
|
+
"that this payment's was not. Nothing was signed.");
|
|
1040
|
+
}
|
|
1041
|
+
let balance;
|
|
1042
|
+
try {
|
|
1043
|
+
balance = await chain.payerBalance(network, rpcUrl, payer, advertised.asset);
|
|
1044
|
+
}
|
|
1045
|
+
catch {
|
|
1046
|
+
balance = undefined;
|
|
1047
|
+
}
|
|
1048
|
+
if (balance === undefined) {
|
|
1049
|
+
throw new CheckSetupError("The payer's balance could not be read, and this check needs it as a second reading. Nothing was signed.");
|
|
1050
|
+
}
|
|
1051
|
+
balanceBefore = balance;
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
catch (error) {
|
|
1055
|
+
if (error instanceof RejectLifetimeOutside)
|
|
1056
|
+
return outside(error.lifetime, true);
|
|
1057
|
+
throw error;
|
|
1058
|
+
}
|
|
1059
|
+
const { httpClient, paymentPayload, selected, payUrl } = prepared;
|
|
1060
|
+
const amount = BigInt(selected.amount);
|
|
1061
|
+
const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment");
|
|
1062
|
+
if (ours.nonce === control.nonce) {
|
|
1063
|
+
throw new CheckSetupError("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent.");
|
|
1064
|
+
}
|
|
1065
|
+
// Right before sending: ours unused, the control found. This read's ledger
|
|
1066
|
+
// starts the range the transfers are read over.
|
|
1067
|
+
const before = await watch.read(network, rpcUrl, [ours, control]);
|
|
1068
|
+
if (before.used[1] === undefined) {
|
|
1069
|
+
throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, so this payment was not sent.");
|
|
1070
|
+
}
|
|
1071
|
+
if (before.used[0] !== undefined) {
|
|
1072
|
+
throw new CheckSetupError("The chain records this payment's authorization as used before it was sent, so it was not sent.");
|
|
1073
|
+
}
|
|
1074
|
+
// What the client signed, not what it was asked: an authorization that stays
|
|
1075
|
+
// valid longer than the 300 s this check waits is not sent (2 units of slack
|
|
1076
|
+
// for the ledgers that close while it is built).
|
|
1077
|
+
const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2;
|
|
1078
|
+
if (ours.expiresAt - before.latest > longest) {
|
|
1079
|
+
throw new CheckSetupError(`This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` +
|
|
1080
|
+
`${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` +
|
|
1081
|
+
`${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`);
|
|
1082
|
+
}
|
|
1083
|
+
// And long enough that a service which settles it could still get it on chain.
|
|
1084
|
+
if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) {
|
|
1085
|
+
throw new CheckSetupError(`This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` +
|
|
1086
|
+
`${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` +
|
|
1087
|
+
`authorization to show anything. It was signed and discarded; it was not sent.`);
|
|
1088
|
+
}
|
|
1089
|
+
const sentAt = Date.now();
|
|
1090
|
+
const response = await fetchTarget(payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload)));
|
|
1091
|
+
const status = response.status;
|
|
1092
|
+
const reason = await refusalReason(response);
|
|
1093
|
+
options.onProgress?.(`X402-11: the payment was sent with the request the service must refuse (HTTP ${status}); reading the chain ` +
|
|
1094
|
+
`once a ${watch.unit} until its authorization expires at ${watch.unit} ${ours.expiresAt}, for at most ` +
|
|
1095
|
+
`${Math.round(rejectedRequestHardStopMs() / 1000)} s.`);
|
|
1096
|
+
let outcome = await watchAuthorization({ watch, network, rpcUrl, ours, control, sentAt });
|
|
1097
|
+
let balance;
|
|
1098
|
+
let transfers;
|
|
1099
|
+
if (outcome.kind === "used" || outcome.kind === "unused") {
|
|
1100
|
+
try {
|
|
1101
|
+
const after = await chain.payerBalance(network, rpcUrl, payer, selected.asset);
|
|
1102
|
+
if (after === undefined)
|
|
1103
|
+
throw new Error("the payer's balance could not be read after the watch");
|
|
1104
|
+
balance = { before: balanceBefore, after };
|
|
1105
|
+
const recorded = await watch.transfers(network, rpcUrl, {
|
|
1106
|
+
asset: selected.asset,
|
|
1107
|
+
from: payer,
|
|
1108
|
+
to: selected.payTo,
|
|
1109
|
+
fromLedger: before.latest + 1,
|
|
1110
|
+
});
|
|
1111
|
+
// Only what the watch covered: from the ledger after the pre-send read to the last ledger
|
|
1112
|
+
// it read. A later transfer of the same amount (another run with this payer) is not this one.
|
|
1113
|
+
const lastRead = outcome.latest;
|
|
1114
|
+
transfers = recorded.transfers
|
|
1115
|
+
.filter((transfer) => transfer.amount === amount && transfer.ledger <= lastRead)
|
|
1116
|
+
.map((transfer) => ({ reference: transfer.reference, ledger: transfer.ledger }));
|
|
1117
|
+
}
|
|
1118
|
+
catch (error) {
|
|
1119
|
+
outcome = { kind: "unread", why: `the second readings failed: ${sanitizeText(error.message).slice(0, 200)}` };
|
|
1120
|
+
balance = undefined;
|
|
1121
|
+
transfers = undefined;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return rejectedRequestVerdict({
|
|
1125
|
+
status,
|
|
1126
|
+
...(reason === undefined ? {} : { reason }),
|
|
1127
|
+
amount,
|
|
1128
|
+
expiresAt: ours.expiresAt,
|
|
1129
|
+
unit: watch.unit,
|
|
1130
|
+
watch: outcome,
|
|
1131
|
+
...(balance === undefined ? {} : { balance }),
|
|
1132
|
+
...(transfers === undefined ? {} : { transfers }),
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
/** The negative checks, in catalogue order, each with how it runs. */
|
|
1136
|
+
const NEGATIVE_CHECKS = [
|
|
1137
|
+
["X402-07", "Invalid Signature Rejected", (options) => checkInvalidSignatureRejected(options)],
|
|
1138
|
+
["X402-08", "Payment Replay Rejected", checkReplayRejected],
|
|
1139
|
+
["X402-09", "Underpayment Rejected", (options) => checkUnderpaymentRejected(options)],
|
|
1140
|
+
["X402-10", "Expired Authorization Rejected", (options) => checkExpiredRejected(options)],
|
|
1141
|
+
[REJECTED_REQUEST_ID, REJECTED_REQUEST_NAME, checkRejectedRequestNotSettled],
|
|
1142
|
+
];
|
|
1143
|
+
/**
|
|
1144
|
+
* Every check `runX402PaymentChecks` reports, in order. Front ends that list
|
|
1145
|
+
* checks before a run use it, so a read-only run never shows these as pending.
|
|
1146
|
+
*/
|
|
1147
|
+
export const X402_PAYMENT_CHECK_IDS = [
|
|
1148
|
+
"X402-06",
|
|
1149
|
+
...NEGATIVE_CHECKS.map(([id]) => id),
|
|
1150
|
+
];
|
|
1151
|
+
/**
|
|
1152
|
+
* Runs X402-06 through X402-10 against a target.
|
|
1153
|
+
*
|
|
1154
|
+
* X402-06 settles a real payment. The negative checks send payments the
|
|
1155
|
+
* target must refuse; a target that accepts the underpaid one may settle it.
|
|
1156
|
+
* See docs/CHECKS.md.
|
|
1157
|
+
*/
|
|
1158
|
+
export async function runX402PaymentChecks(input) {
|
|
1159
|
+
// One budget for every signature these checks make: the run's, when the
|
|
1160
|
+
// caller shares one across endpoints, or this call's own $5.
|
|
1161
|
+
const options = { ...input, budget: input.budget ?? new RunBudget() };
|
|
542
1162
|
try {
|
|
543
1163
|
assertHttpUrl(options.target);
|
|
544
1164
|
buildInit(options);
|
|
1165
|
+
// The payment checks pay only where Wasit has an adapter, and X402-06 can
|
|
1166
|
+
// only verify a settlement it can look up. Both are known before any
|
|
1167
|
+
// money moves, so a run that could not finish is stopped here rather than
|
|
1168
|
+
// after paying.
|
|
1169
|
+
const chain = chainFor(options.network);
|
|
1170
|
+
// L0: an adapter for the network is not permission to pay on it. Only a
|
|
1171
|
+
// test network passes; stellar:pubnet waits for the mainnet opt-in, which
|
|
1172
|
+
// this version does not have.
|
|
1173
|
+
assertPaymentNetworkAllowed("x402", options.network);
|
|
1174
|
+
const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
|
|
1175
|
+
// A key for another chain, or a malformed one, would otherwise surface
|
|
1176
|
+
// mid-payment as a harness error. Checked here, it is what it is: the
|
|
1177
|
+
// run's configuration. The message never echoes the key.
|
|
1178
|
+
try {
|
|
1179
|
+
chain.payerAddress(options.payerSecretKey);
|
|
1180
|
+
}
|
|
1181
|
+
catch (error) {
|
|
1182
|
+
if (error instanceof ConfigurationError)
|
|
1183
|
+
throw error;
|
|
1184
|
+
throw new ConfigurationError(`The payer key is not a valid ${chain.name} key (read from ${chain.payerKeyEnv} ` +
|
|
1185
|
+
`or --payer-key).`);
|
|
1186
|
+
}
|
|
1187
|
+
// The RPC signs and settles nothing itself, but the payment is built and
|
|
1188
|
+
// its settlement read through it: it must serve the run's network (D-023).
|
|
1189
|
+
await assertRpcServesNetwork(options.network, rpcUrl);
|
|
545
1190
|
}
|
|
546
1191
|
catch (error) {
|
|
1192
|
+
// A network no adapter pays on is not a failure of the run: Wasit does not
|
|
1193
|
+
// grade it (spec A3). Every payment check is skipped as unsupported, and
|
|
1194
|
+
// nothing was fetched or signed. The guard's refusals are not this: they
|
|
1195
|
+
// are other errors, and stay a PREFLIGHT error below.
|
|
1196
|
+
if (error instanceof UnsupportedPaymentNetworkError) {
|
|
1197
|
+
const unsupported = [["X402-06", "Signature Resubmit Accepted"], ...NEGATIVE_CHECKS.map(([id, name]) => [id, name])]
|
|
1198
|
+
.map(([id, name]) => skipped(id, name, error.message, "unsupported"));
|
|
1199
|
+
for (const result of unsupported)
|
|
1200
|
+
options.onResult?.(result);
|
|
1201
|
+
return unsupported;
|
|
1202
|
+
}
|
|
547
1203
|
const preflight = errored("PREFLIGHT", "Run Preflight", error);
|
|
548
1204
|
options.onResult?.(preflight);
|
|
549
1205
|
return [preflight];
|
|
550
1206
|
}
|
|
551
1207
|
const results = [];
|
|
552
|
-
|
|
1208
|
+
const emit = (result) => {
|
|
1209
|
+
results.push(result);
|
|
1210
|
+
options.onResult?.(result);
|
|
1211
|
+
};
|
|
1212
|
+
const skipNegatives = (reason) => {
|
|
1213
|
+
for (const [id, name] of NEGATIVE_CHECKS)
|
|
1214
|
+
emit(skipped(id, name, reason));
|
|
1215
|
+
return results;
|
|
1216
|
+
};
|
|
1217
|
+
let honest;
|
|
553
1218
|
try {
|
|
554
|
-
|
|
1219
|
+
honest = await checkSignatureAccepted(options);
|
|
555
1220
|
}
|
|
556
1221
|
catch (error) {
|
|
557
1222
|
if (error instanceof PaymentNotAttemptedError) {
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
skipped("X402-07", "Invalid Signature Rejected", error.message),
|
|
561
|
-
];
|
|
562
|
-
for (const result of notAttempted)
|
|
563
|
-
options.onResult?.(result);
|
|
564
|
-
return notAttempted;
|
|
1223
|
+
emit(skipped("X402-06", "Signature Resubmit Accepted", error.message));
|
|
1224
|
+
return skipNegatives(error.message);
|
|
565
1225
|
}
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
if (accepted.error !== undefined) {
|
|
573
|
-
const notExercised = skipped("X402-07", "Invalid Signature Rejected", `the payment flow could not be exercised (${accepted.error.kind}), so ` +
|
|
574
|
-
`a corrupted signature cannot be tested against it.`);
|
|
575
|
-
results.push(notExercised);
|
|
576
|
-
options.onResult?.(notExercised);
|
|
577
|
-
return results;
|
|
1226
|
+
const failed = errored("X402-06", "Signature Resubmit Accepted", error);
|
|
1227
|
+
emit(failed);
|
|
1228
|
+
// If the payment flow could not be exercised at all, no altered variant of
|
|
1229
|
+
// it can be either, and none may be reported as a passing rejection.
|
|
1230
|
+
return skipNegatives(`the payment flow could not be exercised (${failed.error?.kind ?? "harness"}), ` +
|
|
1231
|
+
`so no altered payment can be tested against it.`);
|
|
578
1232
|
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
1233
|
+
emit(honest.result);
|
|
1234
|
+
// A negative check passes when the target refuses. A target that refused
|
|
1235
|
+
// the honest payment too proves nothing by refusing a bad one, so without an
|
|
1236
|
+
// accepted baseline none of them has a verdict.
|
|
1237
|
+
if (!honest.accepted) {
|
|
1238
|
+
return skipNegatives("the target refused X402-06's valid payment, so refusing an altered one " +
|
|
1239
|
+
"says nothing about what it checks.");
|
|
582
1240
|
}
|
|
583
|
-
|
|
584
|
-
|
|
1241
|
+
for (const [id, name, run] of NEGATIVE_CHECKS) {
|
|
1242
|
+
try {
|
|
1243
|
+
emit(await run(options, honest));
|
|
1244
|
+
}
|
|
1245
|
+
catch (error) {
|
|
1246
|
+
emit(errored(id, name, error));
|
|
1247
|
+
}
|
|
585
1248
|
}
|
|
586
|
-
results.push(rejected);
|
|
587
|
-
options.onResult?.(rejected);
|
|
588
1249
|
return results;
|
|
589
1250
|
}
|