@wasit-dev/core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,14 @@ export interface MppChannelCheckOptions {
27
27
  /** Overrides the default RPC endpoint for the network. */
28
28
  rpcUrl?: string;
29
29
  }
30
+ /**
31
+ * Explains a replay that did not get HTTP 402.
32
+ *
33
+ * Only a 2xx means the replay was honoured. Any other status still refused it,
34
+ * so the rule held and only the protocol's status contract was broken; calling
35
+ * that a double-spend would be a claim the response does not support.
36
+ */
37
+ export declare function describeReplayOutcome(status: number): string;
30
38
  /**
31
39
  * MPP-11: A commitment that does not advance the cumulative must be rejected.
32
40
  *
@@ -49,6 +49,19 @@ export async function runMppChannelDeployChecks(options) {
49
49
  function failure(id, name, detail) {
50
50
  return [{ id, name, pass: false, detail }];
51
51
  }
52
+ /**
53
+ * Explains a replay that did not get HTTP 402.
54
+ *
55
+ * Only a 2xx means the replay was honoured. Any other status still refused it,
56
+ * so the rule held and only the protocol's status contract was broken; calling
57
+ * that a double-spend would be a claim the response does not support.
58
+ */
59
+ export function describeReplayOutcome(status) {
60
+ return status >= 200 && status < 300
61
+ ? `This is a double-spend.`
62
+ : `The replay was still refused, so this is not a double-spend, but a ` +
63
+ `refusal must be HTTP 402 so a client can tell it from a server fault.`;
64
+ }
52
65
  /**
53
66
  * Attempts allowed when establishing the accepted commitment a check needs.
54
67
  *
@@ -189,8 +202,8 @@ export async function runMppChannelReplayCheck(options) {
189
202
  const { credential } = await advanceCumulative(options);
190
203
  const replay = await submitCredential(target, credential);
191
204
  if (replay.status !== 402) {
192
- return failure(id, name, `An identical credential was accepted twice — expected HTTP 402 on replay, ` +
193
- `got ${replay.status}: ${replay.body}. This is a double-spend.`);
205
+ return failure(id, name, `A byte-identical credential was not rejected with HTTP 402 on replay — ` +
206
+ `got ${replay.status}: ${replay.body}. ${describeReplayOutcome(replay.status)}`);
194
207
  }
195
208
  return [
196
209
  {
@@ -226,9 +239,9 @@ export async function runMppChannelCommitmentReplayCheck(options) {
226
239
  const fresh = await fetchChannelChallenge(target);
227
240
  const replay = await submitCredential(target, serializeChannelCredential({ challenge: fresh, amount, signature }));
228
241
  if (replay.status !== 402) {
229
- return failure(id, name, `A captured commitment (${amount}) was redeemed a second time against a ` +
230
- `fresh challenge — expected HTTP 402, got ${replay.status}: ${replay.body}. ` +
231
- `This is a double-spend.`);
242
+ return failure(id, name, `A captured commitment (${amount}) re-presented against a fresh challenge ` +
243
+ `was not rejected with HTTP 402 — got ${replay.status}: ${replay.body}. ` +
244
+ `${describeReplayOutcome(replay.status)}`);
232
245
  }
233
246
  return [
234
247
  {
@@ -27,6 +27,15 @@ export interface X402SimulatorOptions extends RequestShape {
27
27
  */
28
28
  readonly onResult?: (result: CheckResult) => void;
29
29
  }
30
+ /**
31
+ * Reads an x402 v1 challenge from a 402 response body, if that is what it is.
32
+ *
33
+ * Returns the parsed body only when it declares `x402Version: 1` and carries an
34
+ * `accepts` array, the v1 HTTP transport's `PaymentRequirementsResponse`. Any
35
+ * other body, including a v2 payload misplaced into the body, is not treated
36
+ * as a challenge.
37
+ */
38
+ export declare function readV1BodyChallenge(body: string): Record<string, unknown> | undefined;
30
39
  /**
31
40
  * Runs X402-01 through X402-05 against a target.
32
41
  *
@@ -1,5 +1,5 @@
1
1
  import { errored, skipped } from "../check.js";
2
- import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
2
+ import { ConfigurationError, assertHttpUrl, fetchTarget, } from "../errors.js";
3
3
  const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
4
4
  const KNOWN_METHODS = new Set([
5
5
  "GET",
@@ -145,6 +145,34 @@ function checkRequiredFields(payload) {
145
145
  : `Missing: ${missing.join(", ")}.`,
146
146
  };
147
147
  }
148
+ /**
149
+ * Reads an x402 v1 challenge from a 402 response body, if that is what it is.
150
+ *
151
+ * Returns the parsed body only when it declares `x402Version: 1` and carries an
152
+ * `accepts` array, the v1 HTTP transport's `PaymentRequirementsResponse`. Any
153
+ * other body, including a v2 payload misplaced into the body, is not treated
154
+ * as a challenge.
155
+ */
156
+ export function readV1BodyChallenge(body) {
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(body);
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ const record = asRecord(parsed);
165
+ return record?.["x402Version"] === 1 && Array.isArray(record["accepts"]) ? record : undefined;
166
+ }
167
+ /** A body that cannot be read is simply not a v1 challenge. */
168
+ async function readText(response) {
169
+ try {
170
+ return await response.text();
171
+ }
172
+ catch {
173
+ return "";
174
+ }
175
+ }
148
176
  /** X402-05: the network identifier must be CAIP-2. */
149
177
  function checkNetworkIdentifier(payload) {
150
178
  const network = firstAccept(payload)?.["network"];
@@ -159,7 +187,8 @@ function checkNetworkIdentifier(payload) {
159
187
  pass,
160
188
  detail: pass
161
189
  ? `Network identifier "${network}" is valid.`
162
- : `"${network}" does not match stellar:testnet or stellar:pubnet.`,
190
+ : `"${network}" does not match stellar:testnet or stellar:pubnet, the CAIP-2 ` +
191
+ `identifiers the \`exact\` scheme on Stellar defines.`,
163
192
  };
164
193
  }
165
194
  /**
@@ -216,14 +245,39 @@ export async function runX402ReadChecks(options) {
216
245
  // Both names are checked because Stellar's own documentation is not yet
217
246
  // internally consistent — see docs/CHECKS.md.
218
247
  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. The
249
+ // `exact` scheme on Stellar is defined for v2 only, so a missing header is
250
+ // still X402-02's failure — but a v1 challenge in the body still has terms
251
+ // worth checking, and skipping them would hide which ones diverge.
252
+ const v1Payload = headerValue === null ? readV1BodyChallenge(await readText(response)) : undefined;
219
253
  const r2 = {
220
254
  id: "X402-02",
221
255
  name: "Payment Header Present",
222
256
  pass: headerValue !== null,
223
257
  detail: headerValue !== null
224
258
  ? "Payment header found."
225
- : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
259
+ : v1Payload !== undefined
260
+ ? `Neither PAYMENT-REQUIRED nor X-Payment header was present. The ` +
261
+ `response body carries an x402 v1 challenge instead; the \`exact\` ` +
262
+ `scheme on Stellar is defined for v2 only, which signals payment in ` +
263
+ `the PAYMENT-REQUIRED header.`
264
+ : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
226
265
  };
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
+ }
227
281
  if (headerValue === null) {
228
282
  return emit([
229
283
  r1,
@@ -264,6 +318,13 @@ export async function runX402ReadChecks(options) {
264
318
  import { x402Client, x402HTTPClient } from "@x402/fetch";
265
319
  import { createEd25519Signer } from "@x402/stellar";
266
320
  import { ExactStellarScheme as ExactStellarClientScheme } from "@x402/stellar/exact/client";
321
+ /** The payment flow was never started, so neither payment check has a verdict. */
322
+ class PaymentNotAttemptedError extends Error {
323
+ constructor(reason) {
324
+ super(reason);
325
+ this.name = "PaymentNotAttemptedError";
326
+ }
327
+ }
267
328
  function buildX402Client(network, payerSecretKey) {
268
329
  const signer = createEd25519Signer(payerSecretKey, network);
269
330
  const client = new x402Client().register("stellar:*", new ExactStellarClientScheme(signer));
@@ -283,8 +344,19 @@ async function preparePayment(options) {
283
344
  paymentRequired = httpClient.getPaymentRequiredResponse((name) => challenge.headers.get(name));
284
345
  }
285
346
  catch (error) {
286
- throw new MalformedResponseError(`The challenge could not be read as x402 payment requirements: ` +
287
- `${error.message}`);
347
+ // The read checks already report what is wrong with the challenge. Failing
348
+ // X402-06/07 here too would count one broken challenge three times, and
349
+ // would make X402-07 read as a signature that was not rejected when no
350
+ // payment was ever sent. docs/CHECKS.md: an unreadable challenge produces
351
+ // no verdict.
352
+ const v1 = readV1BodyChallenge(await readText(challenge)) !== undefined;
353
+ throw new PaymentNotAttemptedError(v1
354
+ ? `the target issued an x402 v1 challenge, and Wasit pays through the ` +
355
+ `v2 \`exact\` scheme on Stellar, the only version the spec defines, ` +
356
+ `so no payment was attempted (see X402-02).`
357
+ : `the challenge could not be read as x402 payment requirements ` +
358
+ `(${error.message}), so no payment was attempted ` +
359
+ `(see X402-02–04).`);
288
360
  }
289
361
  const paymentPayload = await client.createPaymentPayload(paymentRequired);
290
362
  return { httpClient, paymentPayload };
@@ -321,7 +393,7 @@ async function checkInvalidSignatureRejected(options) {
321
393
  // signature verification, which is weaker than this check should be: a target
322
394
  // that parsed the envelope and skipped verification entirely would still pass.
323
395
  // Corrupting only the signature bytes, preserving a decodable envelope, is a
324
- // 0.4.0 item. See docs/CHECKS.md's X402-07 row.
396
+ // tracked for 0.6.0. See docs/CHECKS.md's X402-07 row.
325
397
  const corrupted = {
326
398
  ...paymentPayload,
327
399
  payload: {
@@ -362,6 +434,15 @@ export async function runX402PaymentChecks(options) {
362
434
  accepted = await checkSignatureAccepted(options);
363
435
  }
364
436
  catch (error) {
437
+ if (error instanceof PaymentNotAttemptedError) {
438
+ const notAttempted = [
439
+ skipped("X402-06", "Signature Resubmit Accepted", error.message),
440
+ skipped("X402-07", "Invalid Signature Rejected", error.message),
441
+ ];
442
+ for (const result of notAttempted)
443
+ options.onResult?.(result);
444
+ return notAttempted;
445
+ }
365
446
  accepted = errored("X402-06", "Signature Resubmit Accepted", error);
366
447
  }
367
448
  results.push(accepted);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wasit-dev/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Check suite for x402/MPP protocol-conformance testing on Stellar. Powers the wasit CLI and wasit-mcp server.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",