@wasit-dev/core 0.7.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.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +351 -0
  4. package/dist/catalogue.js +10 -0
  5. package/dist/check.d.ts +57 -2
  6. package/dist/check.js +46 -6
  7. package/dist/ci-report.d.ts +74 -0
  8. package/dist/ci-report.js +391 -0
  9. package/dist/config.d.ts +205 -0
  10. package/dist/config.js +1011 -0
  11. package/dist/denied-env.d.ts +33 -0
  12. package/dist/denied-env.js +86 -0
  13. package/dist/errors.d.ts +44 -1
  14. package/dist/errors.js +151 -2
  15. package/dist/guard/budget.d.ts +135 -0
  16. package/dist/guard/budget.js +199 -0
  17. package/dist/guard/ci-event.d.ts +50 -0
  18. package/dist/guard/ci-event.js +125 -0
  19. package/dist/guard/mainnet-optin.d.ts +58 -0
  20. package/dist/guard/mainnet-optin.js +95 -0
  21. package/dist/guard/networks.d.ts +50 -0
  22. package/dist/guard/networks.js +80 -0
  23. package/dist/guard/rpc-identity.d.ts +45 -0
  24. package/dist/guard/rpc-identity.js +156 -0
  25. package/dist/guard/rpc-in-use.d.ts +48 -0
  26. package/dist/guard/rpc-in-use.js +84 -0
  27. package/dist/index.d.ts +31 -2
  28. package/dist/index.js +27 -1
  29. package/dist/mpp/channel-commitment.d.ts +48 -2
  30. package/dist/mpp/channel-commitment.js +80 -4
  31. package/dist/mpp/channel-credential.js +3 -0
  32. package/dist/mpp/channel.js +29 -0
  33. package/dist/mpp/charge.d.ts +2 -0
  34. package/dist/mpp/charge.js +17 -1
  35. package/dist/mpp/network.js +4 -1
  36. package/dist/mpp/suite.js +10 -2
  37. package/dist/report.d.ts +163 -0
  38. package/dist/report.js +282 -0
  39. package/dist/sanitize.d.ts +52 -0
  40. package/dist/sanitize.js +106 -0
  41. package/dist/settlement.d.ts +14 -0
  42. package/dist/settlement.js +1 -1
  43. package/dist/verdict.d.ts +24 -0
  44. package/dist/verdict.js +46 -0
  45. package/dist/versions.d.ts +50 -0
  46. package/dist/versions.js +123 -0
  47. package/dist/x402/chains/evm.js +3 -0
  48. package/dist/x402/chains/index.d.ts +8 -0
  49. package/dist/x402/chains/index.js +13 -2
  50. package/dist/x402/chains/stellar.d.ts +8 -1
  51. package/dist/x402/chains/stellar.js +125 -1
  52. package/dist/x402/chains/types.d.ts +68 -0
  53. package/dist/x402/plan.d.ts +82 -0
  54. package/dist/x402/plan.js +146 -0
  55. package/dist/x402/rejected-request.d.ts +146 -0
  56. package/dist/x402/rejected-request.js +269 -0
  57. package/dist/x402/requirements.d.ts +1 -0
  58. package/dist/x402/requirements.js +37 -4
  59. package/dist/x402/simulator.d.ts +52 -1
  60. package/dist/x402/simulator.js +452 -82
  61. package/package.json +1 -1
@@ -4,6 +4,7 @@ import { CheckSetupError } from "../errors.js";
4
4
  import { readChannelWithdrawn } from "./channel-commitment.js";
5
5
  import { buildChannelCredential, fetchChannelChallenge, serializeChannelCredential, submitCredential, } from "./channel-credential.js";
6
6
  import { assertMppNetwork, networkPassphrase, resolveRpcUrl } from "./network.js";
7
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
7
8
  /**
8
9
  * MPP-10: The channel contract deploys correctly — its address is valid
9
10
  * and its on-chain state is queryable, and matches the parameters it was
@@ -46,6 +47,20 @@ export async function runMppChannelDeployChecks(options) {
46
47
  },
47
48
  ];
48
49
  }
50
+ /**
51
+ * L0 for a channel check called on its own: these checks sign commitments, and
52
+ * MPP-13 closes the channel on-chain, so they run on test networks only. The
53
+ * suite runs the same guard once at preflight.
54
+ */
55
+ function refusedNetwork(id, name, network) {
56
+ try {
57
+ assertPaymentNetworkAllowed("mpp-channel", network);
58
+ return undefined;
59
+ }
60
+ catch (error) {
61
+ return [errored(id, name, error)];
62
+ }
63
+ }
49
64
  function failure(id, name, detail) {
50
65
  return [{ id, name, pass: false, detail }];
51
66
  }
@@ -128,6 +143,9 @@ export async function runMppChannelOrderingCheck(options) {
128
143
  const id = "MPP-11";
129
144
  const name = "Cumulative Commitment Ordering";
130
145
  const { target, commitmentSecretHex, network, rpcUrl } = options;
146
+ const refused = refusedNetwork(id, name, network);
147
+ if (refused)
148
+ return refused;
131
149
  try {
132
150
  const { amount: baseline } = await advanceCumulative(options);
133
151
  // (a) Exactly equal to the cumulative the server now holds.
@@ -198,6 +216,9 @@ export async function runMppChannelReplayCheck(options) {
198
216
  const id = "MPP-12";
199
217
  const name = "Challenge Replay Rejection";
200
218
  const { target } = options;
219
+ const refused = refusedNetwork(id, name, options.network);
220
+ if (refused)
221
+ return refused;
201
222
  try {
202
223
  const { credential } = await advanceCumulative(options);
203
224
  const replay = await submitCredential(target, credential);
@@ -232,6 +253,9 @@ export async function runMppChannelCommitmentReplayCheck(options) {
232
253
  const id = "MPP-14";
233
254
  const name = "Commitment Replay Rejection";
234
255
  const { target } = options;
256
+ const refused = refusedNetwork(id, name, options.network);
257
+ if (refused)
258
+ return refused;
235
259
  try {
236
260
  const { amount, signature } = await advanceCumulative(options);
237
261
  // Fresh challenge, same commitment. The signature is still cryptographically
@@ -264,6 +288,11 @@ export async function runMppChannelCloseCheck(options) {
264
288
  const id = "MPP-13";
265
289
  const name = "Close Settlement";
266
290
  const { target, commitmentSecretHex, network, rpcUrl, expectedChannel, allowDestructive = false, closePollAttempts = 6, closePollDelayMs = 2_000, } = options;
291
+ // Before the destructive switch is even looked at: a close on a network
292
+ // that is not a test network is refused, enabled or not.
293
+ const refused = refusedNetwork(id, name, network);
294
+ if (refused)
295
+ return refused;
267
296
  if (!allowDestructive) {
268
297
  return [
269
298
  skippedDestructive(id, name, "closing settles the channel on-chain and permanently ends it. " +
@@ -65,6 +65,8 @@ export declare function payCharge(target: string, network: MppNetwork, method: C
65
65
  *
66
66
  * @throws {ConfigurationError} Invalid target URL, network, or missing key, or
67
67
  * a challenge for another network than the run's (nothing is signed).
68
+ * @throws {PaymentNetworkRefusedError} The run's network is not a test network
69
+ * (nothing is sent).
68
70
  * @throws {TargetUnreachableError} The target never answered.
69
71
  * @throws {MalformedResponseError} The target answered, non-conformantly.
70
72
  * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
@@ -20,8 +20,10 @@
20
20
  import { Mppx, charge } from "@stellar/mpp/charge/client";
21
21
  import { Challenge, Receipt } from "mppx";
22
22
  import { Keypair } from "@stellar/stellar-sdk";
23
- import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
23
+ import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, fetchWithoutRedirects, } from "../errors.js";
24
24
  import { assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js";
25
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
26
+ import { assertRpcServesNetwork } from "../guard/rpc-identity.js";
25
27
  import { verifySettlement } from "../settlement.js";
26
28
  const CHECK_ID = "MPP-01";
27
29
  const CHECK_NAME = "Charge Settlement On-Chain";
@@ -144,10 +146,16 @@ function onNetwork(method, network) {
144
146
  * paid has that 402 reported, rather than being paid twice more.
145
147
  */
146
148
  export async function payCharge(target, network, method) {
149
+ // L0 again at the signing call itself: it is exported, so a caller can
150
+ // reach it without going through runMppChargeChecks.
151
+ assertPaymentNetworkAllowed("mpp-charge", network);
147
152
  const mppx = Mppx.create({
148
153
  methods: [onNetwork(method, network)],
149
154
  polyfill: false,
150
155
  maxPaymentRetries: 1,
156
+ // Every request mppx makes here refuses a redirect (D-022c): it pays at the
157
+ // URL it read the challenge from, never at a URL the target sends it on to.
158
+ fetch: fetchWithoutRedirects,
151
159
  });
152
160
  return mppx.fetch(target);
153
161
  }
@@ -165,6 +173,8 @@ function pass(detail) {
165
173
  *
166
174
  * @throws {ConfigurationError} Invalid target URL, network, or missing key, or
167
175
  * a challenge for another network than the run's (nothing is signed).
176
+ * @throws {PaymentNetworkRefusedError} The run's network is not a test network
177
+ * (nothing is sent).
168
178
  * @throws {TargetUnreachableError} The target never answered.
169
179
  * @throws {MalformedResponseError} The target answered, non-conformantly.
170
180
  * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
@@ -173,6 +183,9 @@ export async function runMppChargeChecks(options) {
173
183
  const { target, network, payerSecretKey, rpcUrl } = options;
174
184
  assertHttpUrl(target);
175
185
  const runNetwork = assertMppNetwork(network);
186
+ // L0: before the key is read, any request is sent or the SDK's charge
187
+ // client is built. MPP pays on test networks only.
188
+ assertPaymentNetworkAllowed("mpp-charge", runNetwork);
176
189
  if (!payerSecretKey) {
177
190
  throw new ConfigurationError("No payer secret key. MPP-01 settles a real payment and cannot run without one.");
178
191
  }
@@ -194,6 +207,9 @@ export async function runMppChargeChecks(options) {
194
207
  throw new ConfigurationError(`MPP-01 pays through @stellar/mpp's charge client, which accepts only an ` +
195
208
  `https RPC endpoint, and ${endpoint} is http. Nothing was sent.`);
196
209
  }
210
+ // The payment is built and its settlement read through this endpoint: it
211
+ // must serve the run's network before the target is asked anything (D-023).
212
+ await assertRpcServesNetwork(runNetwork, endpoint);
197
213
  const advertised = await fetchChargeChallenge(target);
198
214
  assertRunNetwork(advertised.network, runNetwork);
199
215
  let paid;
@@ -9,7 +9,10 @@ import { Networks } from "@stellar/stellar-sdk";
9
9
  import { ConfigurationError } from "../errors.js";
10
10
  export class UnsupportedNetworkError extends ConfigurationError {
11
11
  constructor(network) {
12
- super(`Unsupported network "${network}". Expected "stellar:testnet" or "stellar:pubnet".`);
12
+ super(
13
+ // stellar:pubnet is a known network (a challenge may name it), but the
14
+ // MPP checks never pay on it (L0), so only the test network is offered.
15
+ `Unsupported network "${network}". The MPP checks run on "stellar:testnet" only.`);
13
16
  this.name = "UnsupportedNetworkError";
14
17
  }
15
18
  }
package/dist/mpp/suite.js CHANGED
@@ -9,7 +9,9 @@ import { errored, skipped } from "../check.js";
9
9
  import { assertHttpUrl, classifyCheckError } from "../errors.js";
10
10
  import { runMppChannelCloseCheck, runMppChannelCommitmentReplayCheck, runMppChannelDeployChecks, runMppChannelOrderingCheck, runMppChannelReplayCheck, } from "./channel.js";
11
11
  import { fetchChannelChallenge } from "./channel-credential.js";
12
- import { assertMppNetwork } from "./network.js";
12
+ import { assertMppNetwork, resolveRpcUrl } from "./network.js";
13
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
14
+ import { assertRpcServesNetwork } from "../guard/rpc-identity.js";
13
15
  const DEPLOY_ID = "MPP-10";
14
16
  const DEPLOY_NAME = "Channel Deploy";
15
17
  function missingExpectations(expected) {
@@ -84,10 +86,16 @@ async function runDeployCheck(params) {
84
86
  export async function runMppChannelSuite(options) {
85
87
  const { target, commitmentSecretHex, network, rpcUrl, channelOverride, expected, allowDestructive = false, destructiveChannel, } = options;
86
88
  // A bad URL or an unknown network is wrong for every check in the suite, so
87
- // it is reported once here instead of repeated identically per check.
89
+ // it is reported once here instead of repeated identically per check. L0
90
+ // runs here too: the suite signs commitments and may close a channel, so a
91
+ // network that is not a test network stops it before any request.
88
92
  try {
89
93
  assertHttpUrl(target);
90
94
  assertMppNetwork(network);
95
+ assertPaymentNetworkAllowed("mpp-channel", network);
96
+ // Commitments are prepared and the channel read through this endpoint: it
97
+ // must serve the run's network before the target is asked anything (D-023).
98
+ await assertRpcServesNetwork(network, resolveRpcUrl(network, rpcUrl));
91
99
  }
92
100
  catch (error) {
93
101
  const preflight = errored("PREFLIGHT", "Run Preflight", error);
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The run report: what `wasit run` produces for the CLI's `--json`, the Action
3
+ * and the pull request comment, one shape (spec A2).
4
+ *
5
+ * The central rule is the endpoint outcome. An endpoint counts as graded only
6
+ * when it is `conformant` or `non-conformant` (spec A8 #3, D-021). A service
7
+ * Wasit cannot grade is `unsupported`; one that gave no verdict is
8
+ * `no-verdict`. Neither is a FAIL, and neither is a pass: the totals say how
9
+ * many endpoints were graded, so a run where nothing was cannot be read as
10
+ * green.
11
+ */
12
+ import { type ProtocolId } from "./catalogue.js";
13
+ import { type CheckResult, type CheckStatus, type SkipKind, type StructuredCheckResult, type StructuredRun } from "./check.js";
14
+ import { type NetworkClass } from "./guard/networks.js";
15
+ import type { ToolVersions } from "./versions.js";
16
+ export type EndpointOutcome = "conformant" | "non-conformant" | "no-verdict" | "unsupported";
17
+ /** The groups of checks a report counts: the read-only challenge checks, the payment checks, and the two MPP modes. */
18
+ export type CheckGroup = "challenge" | "payment" | "mppCharge" | "mppChannel";
19
+ export interface GroupCounts {
20
+ readonly passed: number;
21
+ readonly failed: number;
22
+ readonly errored: number;
23
+ readonly skipped: number;
24
+ }
25
+ /**
26
+ * The group of a check id. X402-01..05 read the challenge, X402-06..10 pay;
27
+ * the MPP checks follow their mode. An id with no catalogue entry (PREFLIGHT)
28
+ * belongs to the group of the endpoint it was raised for.
29
+ */
30
+ export declare function checkGroup(id: string, protocol: ProtocolId): CheckGroup;
31
+ /**
32
+ * True when an x402 payment check (X402-06..11) was skipped as `unsupported`:
33
+ * the run asked to pay and Wasit cannot pay on that network. A read-only or
34
+ * no-payer skip is not this, and neither is a result of another protocol. An MPP
35
+ * endpoint has no group besides its gating one, so for it this is always false.
36
+ * Works on the results of a fresh run and on the structured results of a report.
37
+ */
38
+ export declare function paymentGroupUnsupported(results: ReadonlyArray<{
39
+ readonly id: string;
40
+ readonly skipKind?: SkipKind;
41
+ }>, protocol: ProtocolId): boolean;
42
+ /**
43
+ * The outcome of one endpoint from its results.
44
+ *
45
+ * - any FAIL: `non-conformant`. A real finding outranks a missing one.
46
+ * - else an `unsupported` skip in the endpoint's gating group (the challenge
47
+ * checks for x402): `unsupported`. X402-01 may have passed on an x402 v1
48
+ * service; one passing check does not grade a paywall Wasit cannot read. An
49
+ * `unsupported` payment group alone does not make the endpoint unsupported:
50
+ * the challenge was graded.
51
+ * - else an `unsupported` skip in the payment group (payment checks were asked
52
+ * for and none could be graded on this network): `no-verdict`, so it is not
53
+ * green (Najmi, 2026-11-15).
54
+ * - else any ERROR: `no-verdict`.
55
+ * - else at least one PASS: `conformant`.
56
+ * - else (nothing ran, or everything was skipped): `no-verdict`.
57
+ */
58
+ export declare function endpointOutcome(results: readonly CheckResult[], protocol: ProtocolId): EndpointOutcome;
59
+ /**
60
+ * The checks of an endpoint that pay or sign, as SKIPs the report can count and
61
+ * name (spec A2: the report says which checks need a payer).
62
+ *
63
+ * `read-only`: the run was asked not to pay. `needs-payer`: the run could have
64
+ * paid and had no key. The names come from the catalogue, so a rename there is
65
+ * the only place to change.
66
+ */
67
+ export declare function skippedPaymentChecks(protocol: ProtocolId, kind: "read-only" | "needs-payer"): CheckResult[];
68
+ /**
69
+ * The same checks, skipped with a reason the caller words: the run asked to pay
70
+ * and a rule of the run stopped it (the GitHub event, `operatedByMe`, a key
71
+ * variable that is not set), or the front end does not run them.
72
+ */
73
+ export declare function paymentChecksSkipped(protocol: ProtocolId, kind: SkipKind, reason: string): CheckResult[];
74
+ /**
75
+ * The exit code of one endpoint's checks (spec A8 #3, D-021): 1 on any FAIL; 2
76
+ * when the endpoint was not graded (`unsupported` or `no-verdict`) or a check
77
+ * could not run; else 0. Used where there is one endpoint, `wasit test` and the
78
+ * MCP x402 tool; a run of several endpoints uses {@link runExitCode}.
79
+ */
80
+ export declare function exitCodeForEndpoint(results: readonly CheckResult[], protocol: ProtocolId): 0 | 1 | 2;
81
+ /**
82
+ * `toStructuredRun` with the outcome the exit rule gives: a service that was
83
+ * never graded is `no-verdict`, never `conformant`, for the MCP agent as for the
84
+ * shell. The counts are the same.
85
+ */
86
+ export declare function toGradedRun(results: readonly CheckResult[], protocol: ProtocolId): StructuredRun;
87
+ export interface EndpointReport {
88
+ readonly name: string;
89
+ readonly protocol: ProtocolId;
90
+ readonly method: string;
91
+ readonly path: string;
92
+ readonly outcome: EndpointOutcome;
93
+ /** Why the endpoint is `unsupported` or has `no-verdict`; absent otherwise. */
94
+ readonly reason?: string;
95
+ /** Counts for each group that has at least one result; a group with no checks is absent. */
96
+ readonly groups: Readonly<Partial<Record<CheckGroup, GroupCounts>>>;
97
+ readonly results: readonly StructuredCheckResult[];
98
+ }
99
+ export interface EndpointInput {
100
+ readonly name: string;
101
+ readonly protocol: ProtocolId;
102
+ readonly method: string;
103
+ readonly path: string;
104
+ readonly results: readonly CheckResult[];
105
+ }
106
+ /**
107
+ * Counts per group from any list of results that have an id and a status: the
108
+ * CheckResults of a fresh run, or the structured results of a report read back.
109
+ */
110
+ export declare function groupCounts(results: ReadonlyArray<{
111
+ readonly id: string;
112
+ readonly status: CheckStatus;
113
+ }>, protocol: ProtocolId): Partial<Record<CheckGroup, GroupCounts>>;
114
+ /** Builds the report of one endpoint. Every text in it has passed through the sanitiser. */
115
+ export declare function buildEndpointReport(input: EndpointInput): EndpointReport;
116
+ export interface RunTotals {
117
+ readonly endpoints: number;
118
+ /** Endpoints that are `conformant` or `non-conformant`: the ones that were tested. */
119
+ readonly graded: number;
120
+ readonly conformant: number;
121
+ readonly nonConformant: number;
122
+ readonly noVerdict: number;
123
+ readonly unsupported: number;
124
+ }
125
+ export declare function reportTotals(endpoints: readonly EndpointReport[]): RunTotals;
126
+ /**
127
+ * The summary line: "0 graded, 1 unsupported". Says how many endpoints were
128
+ * graded first, so a run in which nothing was cannot be read as a pass.
129
+ */
130
+ export declare function describeTotals(totals: RunTotals): string;
131
+ export interface RunReport {
132
+ readonly schema: 1;
133
+ readonly wasit: ToolVersions["wasit"];
134
+ readonly sdk: ToolVersions["sdk"];
135
+ readonly environment: string;
136
+ readonly network: string;
137
+ readonly networkClass: NetworkClass;
138
+ /** ISO 8601, supplied by the caller. */
139
+ readonly startedAt: string;
140
+ readonly endpoints: readonly EndpointReport[];
141
+ readonly totals: RunTotals;
142
+ readonly notes: readonly string[];
143
+ }
144
+ export interface RunReportInput {
145
+ readonly environment: string;
146
+ readonly network: string;
147
+ readonly startedAt: string;
148
+ readonly versions: ToolVersions;
149
+ readonly endpoints: readonly EndpointReport[];
150
+ readonly notes?: readonly string[];
151
+ }
152
+ /** Builds the run report. Pure: the clock and the installed versions are inputs. */
153
+ export declare function buildRunReport(input: RunReportInput): RunReport;
154
+ /**
155
+ * A copy of a JSON-shaped value with `secrets` removed from every string in it
156
+ * (and control characters, `::` lines and Stellar keys dealt with, as
157
+ * everywhere), and every `expected` and `actual` cut to a short length. The
158
+ * report is built from text a service sent, and a service can echo a header it
159
+ * was sent; this is the last pass before it is printed or written.
160
+ */
161
+ export declare function redactValue<T>(value: T, secrets: readonly string[]): T;
162
+ /** {@link redactValue} for a run report. */
163
+ export declare function redactReport(report: RunReport, secrets: readonly string[]): RunReport;
package/dist/report.js ADDED
@@ -0,0 +1,282 @@
1
+ /**
2
+ * The run report: what `wasit run` produces for the CLI's `--json`, the Action
3
+ * and the pull request comment, one shape (spec A2).
4
+ *
5
+ * The central rule is the endpoint outcome. An endpoint counts as graded only
6
+ * when it is `conformant` or `non-conformant` (spec A8 #3, D-021). A service
7
+ * Wasit cannot grade is `unsupported`; one that gave no verdict is
8
+ * `no-verdict`. Neither is a FAIL, and neither is a pass: the totals say how
9
+ * many endpoints were graded, so a run where nothing was cannot be read as
10
+ * green.
11
+ */
12
+ import { catalogueEntry } from "./catalogue.js";
13
+ import { checkStatus, skipped, summarize, toStructuredRun, } from "./check.js";
14
+ import { networkClass } from "./guard/networks.js";
15
+ import { sanitizeText } from "./sanitize.js";
16
+ /** The group whose result decides whether an endpoint can be graded at all. */
17
+ const GATING_GROUP = {
18
+ x402: "challenge",
19
+ "mpp-charge": "mppCharge",
20
+ "mpp-channel": "mppChannel",
21
+ };
22
+ /**
23
+ * The group of a check id. X402-01..05 read the challenge, X402-06..10 pay;
24
+ * the MPP checks follow their mode. An id with no catalogue entry (PREFLIGHT)
25
+ * belongs to the group of the endpoint it was raised for.
26
+ */
27
+ export function checkGroup(id, protocol) {
28
+ const entry = catalogueEntry(id);
29
+ if (entry === undefined)
30
+ return GATING_GROUP[protocol];
31
+ if (entry.protocol === "x402")
32
+ return Number(id.slice("X402-".length)) <= 5 ? "challenge" : "payment";
33
+ return GATING_GROUP[entry.protocol];
34
+ }
35
+ /**
36
+ * True when an x402 payment check (X402-06..11) was skipped as `unsupported`:
37
+ * the run asked to pay and Wasit cannot pay on that network. A read-only or
38
+ * no-payer skip is not this, and neither is a result of another protocol. An MPP
39
+ * endpoint has no group besides its gating one, so for it this is always false.
40
+ * Works on the results of a fresh run and on the structured results of a report.
41
+ */
42
+ export function paymentGroupUnsupported(results, protocol) {
43
+ return protocol === "x402" && results.some((result) => result.skipKind === "unsupported" && checkGroup(result.id, protocol) === "payment");
44
+ }
45
+ /**
46
+ * The outcome of one endpoint from its results.
47
+ *
48
+ * - any FAIL: `non-conformant`. A real finding outranks a missing one.
49
+ * - else an `unsupported` skip in the endpoint's gating group (the challenge
50
+ * checks for x402): `unsupported`. X402-01 may have passed on an x402 v1
51
+ * service; one passing check does not grade a paywall Wasit cannot read. An
52
+ * `unsupported` payment group alone does not make the endpoint unsupported:
53
+ * the challenge was graded.
54
+ * - else an `unsupported` skip in the payment group (payment checks were asked
55
+ * for and none could be graded on this network): `no-verdict`, so it is not
56
+ * green (Najmi, 2026-11-15).
57
+ * - else any ERROR: `no-verdict`.
58
+ * - else at least one PASS: `conformant`.
59
+ * - else (nothing ran, or everything was skipped): `no-verdict`.
60
+ */
61
+ export function endpointOutcome(results, protocol) {
62
+ const gating = GATING_GROUP[protocol];
63
+ let passed = 0;
64
+ let errored = 0;
65
+ let unsupported = false;
66
+ for (const result of results) {
67
+ const status = checkStatus(result);
68
+ if (status === "FAIL")
69
+ return "non-conformant";
70
+ if (status === "PASS")
71
+ passed += 1;
72
+ else if (status === "ERROR")
73
+ errored += 1;
74
+ else if (result.skipKind === "unsupported" && checkGroup(result.id, protocol) === gating)
75
+ unsupported = true;
76
+ }
77
+ if (unsupported)
78
+ return "unsupported";
79
+ // Payment checks were asked for and none could be graded here (a typo in the network, a chain
80
+ // with no adapter): the challenge was graded, but the run did not do what it was asked.
81
+ // Najmi, 2026-11-15: not green, exit 2, like 0.7.0.
82
+ if (paymentGroupUnsupported(results, protocol))
83
+ return "no-verdict";
84
+ if (errored > 0)
85
+ return "no-verdict";
86
+ return passed > 0 ? "conformant" : "no-verdict";
87
+ }
88
+ /** The key a protocol's payment group needs, for the words of a skip reason. */
89
+ const KEY_LABEL = {
90
+ x402: "a payer key",
91
+ "mpp-charge": "a payer key",
92
+ "mpp-channel": "a commitment key",
93
+ };
94
+ /** The checks of a protocol that pay or sign. MPP-13 closes a channel for good and is never listed. */
95
+ const PAYMENT_CHECK_IDS = {
96
+ x402: ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"],
97
+ "mpp-charge": ["MPP-01"],
98
+ "mpp-channel": ["MPP-10", "MPP-11", "MPP-12", "MPP-14"],
99
+ };
100
+ /**
101
+ * The checks of an endpoint that pay or sign, as SKIPs the report can count and
102
+ * name (spec A2: the report says which checks need a payer).
103
+ *
104
+ * `read-only`: the run was asked not to pay. `needs-payer`: the run could have
105
+ * paid and had no key. The names come from the catalogue, so a rename there is
106
+ * the only place to change.
107
+ */
108
+ export function skippedPaymentChecks(protocol, kind) {
109
+ const key = KEY_LABEL[protocol];
110
+ const reason = kind === "read-only"
111
+ ? `the read-only tier makes no payment and signs nothing; this check needs ${key} and the payment tier`
112
+ : `this check pays or signs and no ${key.replace(/^a /, "")} was given`;
113
+ return PAYMENT_CHECK_IDS[protocol].map((id) => skipped(id, catalogueEntry(id)?.name ?? id, reason, kind));
114
+ }
115
+ /**
116
+ * The same checks, skipped with a reason the caller words: the run asked to pay
117
+ * and a rule of the run stopped it (the GitHub event, `operatedByMe`, a key
118
+ * variable that is not set), or the front end does not run them.
119
+ */
120
+ export function paymentChecksSkipped(protocol, kind, reason) {
121
+ return PAYMENT_CHECK_IDS[protocol].map((id) => skipped(id, catalogueEntry(id)?.name ?? id, reason, kind));
122
+ }
123
+ /**
124
+ * The exit code of one endpoint's checks (spec A8 #3, D-021): 1 on any FAIL; 2
125
+ * when the endpoint was not graded (`unsupported` or `no-verdict`) or a check
126
+ * could not run; else 0. Used where there is one endpoint, `wasit test` and the
127
+ * MCP x402 tool; a run of several endpoints uses {@link runExitCode}.
128
+ */
129
+ export function exitCodeForEndpoint(results, protocol) {
130
+ const base = summarize([...results]).exitCode;
131
+ if (base !== 0)
132
+ return base;
133
+ const outcome = endpointOutcome(results, protocol);
134
+ return outcome === "unsupported" || outcome === "no-verdict" ? 2 : 0;
135
+ }
136
+ /**
137
+ * `toStructuredRun` with the outcome the exit rule gives: a service that was
138
+ * never graded is `no-verdict`, never `conformant`, for the MCP agent as for the
139
+ * shell. The counts are the same.
140
+ */
141
+ export function toGradedRun(results, protocol) {
142
+ const run = toStructuredRun([...results]);
143
+ const code = exitCodeForEndpoint(results, protocol);
144
+ const outcome = code === 0 ? "conformant" : code === 1 ? "non-conformant" : "no-verdict";
145
+ return { ...run, outcome };
146
+ }
147
+ function reasonFor(results, protocol, outcome) {
148
+ if (outcome === "unsupported") {
149
+ const skip = results.find((result) => result.skipKind === "unsupported" && checkGroup(result.id, protocol) === GATING_GROUP[protocol]);
150
+ return skip?.skipReason === undefined ? undefined : sanitizeText(skip.skipReason);
151
+ }
152
+ if (outcome === "no-verdict") {
153
+ const error = results.find((result) => checkStatus(result) === "ERROR");
154
+ if (error !== undefined)
155
+ return sanitizeText(error.error?.message ?? "a check could not run");
156
+ const unsupportedPayment = results.find((result) => result.skipKind === "unsupported" && paymentGroupUnsupported([result], protocol));
157
+ if (unsupportedPayment?.skipReason !== undefined)
158
+ return sanitizeText(unsupportedPayment.skipReason);
159
+ // Skipped only because the run was asked not to pay: say so, not "nothing ran".
160
+ const readOnly = results.find((result) => result.skipKind === "read-only");
161
+ if (readOnly?.skipReason !== undefined)
162
+ return sanitizeText(readOnly.skipReason);
163
+ return "no check passed: every check was skipped or none ran";
164
+ }
165
+ return undefined;
166
+ }
167
+ /**
168
+ * Counts per group from any list of results that have an id and a status: the
169
+ * CheckResults of a fresh run, or the structured results of a report read back.
170
+ */
171
+ export function groupCounts(results, protocol) {
172
+ const counts = new Map();
173
+ for (const result of results) {
174
+ const group = checkGroup(result.id, protocol);
175
+ const entry = counts.get(group) ?? { passed: 0, failed: 0, errored: 0, skipped: 0 };
176
+ if (result.status === "PASS")
177
+ entry.passed += 1;
178
+ else if (result.status === "FAIL")
179
+ entry.failed += 1;
180
+ else if (result.status === "ERROR")
181
+ entry.errored += 1;
182
+ else
183
+ entry.skipped += 1;
184
+ counts.set(group, entry);
185
+ }
186
+ return Object.fromEntries(counts);
187
+ }
188
+ /** Builds the report of one endpoint. Every text in it has passed through the sanitiser. */
189
+ export function buildEndpointReport(input) {
190
+ const outcome = endpointOutcome(input.results, input.protocol);
191
+ const reason = reasonFor(input.results, input.protocol, outcome);
192
+ return {
193
+ name: sanitizeText(input.name),
194
+ protocol: input.protocol,
195
+ method: sanitizeText(input.method),
196
+ path: sanitizeText(input.path),
197
+ outcome,
198
+ ...(reason === undefined ? {} : { reason }),
199
+ groups: groupCounts(input.results.map((result) => ({ id: result.id, status: checkStatus(result) })), input.protocol),
200
+ results: toStructuredRun([...input.results]).results,
201
+ };
202
+ }
203
+ export function reportTotals(endpoints) {
204
+ const count = (outcome) => endpoints.filter((endpoint) => endpoint.outcome === outcome).length;
205
+ const conformant = count("conformant");
206
+ const nonConformant = count("non-conformant");
207
+ return {
208
+ endpoints: endpoints.length,
209
+ graded: conformant + nonConformant,
210
+ conformant,
211
+ nonConformant,
212
+ noVerdict: count("no-verdict"),
213
+ unsupported: count("unsupported"),
214
+ };
215
+ }
216
+ /**
217
+ * The summary line: "0 graded, 1 unsupported". Says how many endpoints were
218
+ * graded first, so a run in which nothing was cannot be read as a pass.
219
+ */
220
+ export function describeTotals(totals) {
221
+ return [
222
+ `${totals.graded} graded${totals.nonConformant > 0 ? ` (${totals.nonConformant} non-conformant)` : ""}`,
223
+ ...(totals.unsupported > 0 ? [`${totals.unsupported} unsupported`] : []),
224
+ ...(totals.noVerdict > 0 ? [`${totals.noVerdict} no verdict`] : []),
225
+ ].join(", ");
226
+ }
227
+ /** Builds the run report. Pure: the clock and the installed versions are inputs. */
228
+ export function buildRunReport(input) {
229
+ return {
230
+ schema: 1,
231
+ wasit: input.versions.wasit,
232
+ sdk: input.versions.sdk,
233
+ environment: sanitizeText(input.environment),
234
+ network: sanitizeText(input.network),
235
+ networkClass: networkClass(input.network),
236
+ startedAt: input.startedAt,
237
+ endpoints: input.endpoints,
238
+ totals: reportTotals(input.endpoints),
239
+ notes: (input.notes ?? []).map((note) => sanitizeText(note)),
240
+ };
241
+ }
242
+ /** The keys whose value is a short quote of what the service sent. */
243
+ const SHORT_VALUE_KEYS = new Set(["expected", "actual"]);
244
+ /** The longest `expected` or `actual` in an output. */
245
+ const SHORT_VALUE_MAX = 200;
246
+ function clipValue(text) {
247
+ const characters = Array.from(text);
248
+ return characters.length <= SHORT_VALUE_MAX ? text : `${characters.slice(0, SHORT_VALUE_MAX - 1).join("")}…`;
249
+ }
250
+ /**
251
+ * Applies `change` to every string in a JSON-shaped value; numbers, booleans and
252
+ * null stay. The string under an `expected` or `actual` key is changed first and
253
+ * cut to {@link SHORT_VALUE_MAX} after: a cut made before the secrets are removed
254
+ * could leave the start of one in the output.
255
+ */
256
+ function mapStrings(value, change) {
257
+ if (typeof value === "string")
258
+ return change(value);
259
+ if (Array.isArray(value))
260
+ return value.map((item) => mapStrings(item, change));
261
+ if (typeof value === "object" && value !== null) {
262
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
263
+ key,
264
+ typeof item === "string" && SHORT_VALUE_KEYS.has(key) ? clipValue(change(item)) : mapStrings(item, change),
265
+ ]));
266
+ }
267
+ return value;
268
+ }
269
+ /**
270
+ * A copy of a JSON-shaped value with `secrets` removed from every string in it
271
+ * (and control characters, `::` lines and Stellar keys dealt with, as
272
+ * everywhere), and every `expected` and `actual` cut to a short length. The
273
+ * report is built from text a service sent, and a service can echo a header it
274
+ * was sent; this is the last pass before it is printed or written.
275
+ */
276
+ export function redactValue(value, secrets) {
277
+ return mapStrings(value, (text) => sanitizeText(text, { redact: secrets }));
278
+ }
279
+ /** {@link redactValue} for a run report. */
280
+ export function redactReport(report, secrets) {
281
+ return redactValue(report, secrets);
282
+ }