@wasit-dev/core 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -80,6 +80,49 @@ Every check function returns `Promise<CheckResult[]>` and never rejects for a ta
80
80
 
81
81
  The full check catalogue — every check's exact pass criteria and spec reference — is in [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md).
82
82
 
83
+ ### Catalogue and structured output
84
+
85
+ | Export | What it is |
86
+ |---|---|
87
+ | `CHECK_CATALOGUE` | `readonly CheckCatalogueEntry[]` — every check the suite can run: `id`, `name`, `protocol`, `specRef`, a one-line `summary`, and the optional flags `negative`, `destructive`, `costsFunds`. This is what `wasit checks` prints. |
88
+ | `PROTOCOL_IDS` | `readonly ProtocolId[]` — `"x402"`, `"mpp-charge"`, `"mpp-channel"` |
89
+ | `toStructuredRun(results)` | → `StructuredRun` — the machine-readable reshape of a run: `outcome`, per-status counts, and a `results` array of `StructuredCheckResult`. The CLI's `--json` and the MCP server's `structuredContent` are both this function's output verbatim, so the three surfaces cannot describe the same run differently. |
90
+
91
+ `outcome` is a name — `"conformant"`, `"non-conformant"`, `"no-verdict"` — not an exit code. `no-verdict` must never be read as `conformant`.
92
+
93
+ The catalogue is a short-form companion to [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md), which stays the source of truth for pass criteria and spec citations.
94
+
95
+ ### Errors
96
+
97
+ | Export | What it is |
98
+ |---|---|
99
+ | `ConfigurationError` | Something was wrong before any request went out — a malformed key, an invalid URL, an out-of-range argument |
100
+ | `TargetUnreachableError` | The request itself failed or timed out; no verdict about the target can be drawn from it |
101
+ | `MalformedResponseError` | The target answered, but not in a shape the check could read |
102
+ | `classifyCheckError(error)` | → `ClassifiedError` — maps an unknown throw to the `errorKind` (`"unreachable"`, `"configuration"`, `"harness"`) that appears in structured output |
103
+ | `assertHttpUrl(target)`, `fetchTarget(...)` | The URL guard and bounded fetch the checks themselves use |
104
+
105
+ ### Testnet wallet helpers
106
+
107
+ A convenience layer for setting up the keys the check functions read. It is not part of the check surface, and it is exported by name rather than with `export *` so `wallet.ts` stays free to change without that being a breaking change to this package.
108
+
109
+ | Export | Signature |
110
+ |---|---|
111
+ | `publicKeyFromSecret(secretKey, source?)` | → `string`. `source` names the offending variable in the error message |
112
+ | `getTestnetWalletStatus(publicKey)` | → `Promise<WalletStatus>` — `{ publicKey, exists, balances }`; `exists` is false for an account never created on-chain |
113
+ | `generateTestnetWallet()` | → `GeneratedWallet` — a fresh keypair, unfunded |
114
+ | `generateCommitmentKey()` | → `GeneratedCommitmentKey` — a raw ed25519 seed for `COMMITMENT_SECRET_HEX`, which has no on-chain account and is not an `S...` key |
115
+ | `fundWithFriendbot(publicKey, attempts?)` | → `Promise<FriendbotOutcome>` — `"funded"` or `"already-funded"`. Two different claims: an account that already exists is a success, but no transfer happened |
116
+ | `createUsdcTrustline(secretKey, source?)` | → `Promise<void>` — opens the Circle testnet USDC trustline. A trustline is not a balance |
117
+ | `sendUsdcFromDistributor(distributorSecretKey, destinationPublicKey, amount)` | → `Promise<void>` — `amount` is a positive decimal string, at most 7 places |
118
+ | `testnetUsdcAsset()` / `TESTNET_USDC_ISSUER` | The Circle testnet USDC `Asset` and its issuer address |
119
+ | `describeTransactionError(error)` | → `string` — Horizon result codes formatted for a human |
120
+
121
+ **These throw; the check functions do not.** Every function above raises `ConfigurationError` or `TargetUnreachableError` rather than leaking a Stellar SDK error, with Horizon's result codes (`op_underfunded`, `op_no_trust`) folded into the message — so a caller renders `error.message` and never inspects an SDK error type. Horizon and Friendbot requests are bounded by a 15s timeout. A rejected secret key is never echoed back in the message.
122
+
123
+ There is deliberately no network parameter anywhere in this layer. Friendbot, the printed USDC issuer, and the whole idea of a disposable generated key only make sense on testnet.
124
+
125
+
83
126
  ## Design
84
127
 
85
128
  - **`FAIL`, `ERROR`, and `SKIP` are different claims.** `FAIL` means the target answered and didn't conform. `ERROR` means no verdict was produced at all (unreachable, misconfigured, harness failure). `SKIP` is neither. Conflating "your service is broken" with "we never reached your service" would make a tool worse than no tool.
package/dist/check.d.ts CHANGED
@@ -75,7 +75,10 @@ export interface StructuredCheckResult {
75
75
  readonly status: CheckStatus;
76
76
  readonly detail: string;
77
77
  readonly destructive: boolean;
78
- /** Present only when `status` is "ERROR": unreachable | configuration | harness. */
78
+ /**
79
+ * Present only when `status` is "ERROR":
80
+ * unreachable | configuration | harness | setup.
81
+ */
79
82
  readonly errorKind?: string;
80
83
  }
81
84
  /** A full run, reshaped for a machine-readable front end (CLI --json, MCP). */
package/dist/errors.d.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * the call site knows what it was doing and wraps accordingly.
15
15
  */
16
16
  /** Why a check could not produce a verdict about the target. */
17
- export type CheckErrorKind = "unreachable" | "configuration" | "harness";
17
+ export type CheckErrorKind = "unreachable" | "configuration" | "harness" | "setup";
18
18
  /** A check that did not run. Never a statement about the target's conformance. */
19
19
  export interface CheckError {
20
20
  readonly kind: CheckErrorKind;
@@ -39,6 +39,21 @@ export declare class MalformedResponseError extends Error {
39
39
  export declare class ConfigurationError extends Error {
40
40
  constructor(message: string);
41
41
  }
42
+ /**
43
+ * A precondition the check needed could not be established, so the check never
44
+ * reached the rule it exists to test.
45
+ *
46
+ * Kept apart from a conformance failure deliberately. MPP channel checks must
47
+ * first get one correctly advancing commitment accepted before they can probe
48
+ * anything, and two very different worlds refuse that submission identically: a
49
+ * target that wrongly rejects valid vouchers, and a channel whose cumulative
50
+ * moved between the challenge being issued and the credential being submitted,
51
+ * because something else is paying through it. Reporting the second as a defect
52
+ * tells an operator their service is broken on the evidence of a busy channel.
53
+ */
54
+ export declare class CheckSetupError extends Error {
55
+ constructor(message: string);
56
+ }
42
57
  /** No HTTP conversation took place: the connection never succeeded. */
43
58
  export declare class TargetUnreachableError extends Error {
44
59
  readonly target: string;
@@ -55,11 +70,6 @@ export declare class TargetUnreachableError extends Error {
55
70
  * under N identical copies.
56
71
  */
57
72
  export declare function assertHttpUrl(target: string): void;
58
- /**
59
- * Performs a request against the target, distinguishing "never connected"
60
- * from every other failure. Use this instead of bare `fetch` for anything
61
- * addressed at the service under test.
62
- */
63
73
  export declare function fetchTarget(target: string, init?: Parameters<typeof fetch>[1]): Promise<Awaited<ReturnType<typeof fetch>>>;
64
74
  /** Maps a thrown value onto the taxonomy. */
65
75
  export declare function classifyCheckError(error: unknown): ClassifiedError;
package/dist/errors.js CHANGED
@@ -30,6 +30,24 @@ export class ConfigurationError extends Error {
30
30
  this.name = "ConfigurationError";
31
31
  }
32
32
  }
33
+ /**
34
+ * A precondition the check needed could not be established, so the check never
35
+ * reached the rule it exists to test.
36
+ *
37
+ * Kept apart from a conformance failure deliberately. MPP channel checks must
38
+ * first get one correctly advancing commitment accepted before they can probe
39
+ * anything, and two very different worlds refuse that submission identically: a
40
+ * target that wrongly rejects valid vouchers, and a channel whose cumulative
41
+ * moved between the challenge being issued and the credential being submitted,
42
+ * because something else is paying through it. Reporting the second as a defect
43
+ * tells an operator their service is broken on the evidence of a busy channel.
44
+ */
45
+ export class CheckSetupError extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "CheckSetupError";
49
+ }
50
+ }
33
51
  /** No HTTP conversation took place: the connection never succeeded. */
34
52
  export class TargetUnreachableError extends Error {
35
53
  target;
@@ -96,10 +114,36 @@ export function assertHttpUrl(target) {
96
114
  * from every other failure. Use this instead of bare `fetch` for anything
97
115
  * addressed at the service under test.
98
116
  */
117
+ /**
118
+ * The global symbol mppx tags its fetch wrappers with, so a wrapper can be
119
+ * recognised across module instances and bundles.
120
+ * See mppx/dist/client/internal/Fetch.js.
121
+ */
122
+ const MPPX_FETCH_WRAPPER = Symbol.for("mppx.fetch.wrapper");
123
+ /**
124
+ * Resolves the underlying fetch, stepping past any mppx payment wrapper
125
+ * installed on `globalThis`.
126
+ *
127
+ * `Mppx.create` replaces `globalThis.fetch` with a wrapper bound to one
128
+ * payment method unless `polyfill: false` is passed. A charge-mode client
129
+ * created earlier in the process therefore makes every later 402 carrying a
130
+ * different intent fail with "No method found for challenges", even though the
131
+ * target is conformant. Checks must observe the target, never a payment client
132
+ * some other check left behind, so this unwraps rather than trusting the global.
133
+ */
134
+ function baseFetch() {
135
+ let current = globalThis.fetch;
136
+ const seen = new Set();
137
+ while (current[MPPX_FETCH_WRAPPER] && !seen.has(current)) {
138
+ seen.add(current);
139
+ current = current[MPPX_FETCH_WRAPPER];
140
+ }
141
+ return current;
142
+ }
99
143
  export async function fetchTarget(target, init) {
100
144
  assertHttpUrl(target);
101
145
  try {
102
- return await fetch(target, init);
146
+ return await baseFetch()(target, init);
103
147
  }
104
148
  catch (error) {
105
149
  throw new TargetUnreachableError(target, error);
@@ -120,6 +164,9 @@ export function classifyCheckError(error) {
120
164
  if (error instanceof ConfigurationError) {
121
165
  return { kind: "configuration", message: error.message };
122
166
  }
167
+ if (error instanceof CheckSetupError) {
168
+ return { kind: "setup", message: error.message };
169
+ }
123
170
  return {
124
171
  kind: "harness",
125
172
  message: error instanceof Error ? error.message : String(error),
@@ -1,6 +1,7 @@
1
1
  import { getChannelState } from "@stellar/mpp/channel/server";
2
2
  import { errored, skippedDestructive } from "../check.js";
3
- import { readChannelWithdrawn, signChannelCommitment } from "./channel-commitment.js";
3
+ import { CheckSetupError } from "../errors.js";
4
+ import { readChannelWithdrawn } from "./channel-commitment.js";
4
5
  import { buildChannelCredential, fetchChannelChallenge, serializeChannelCredential, submitCredential, } from "./channel-credential.js";
5
6
  import { assertMppNetwork, networkPassphrase, resolveRpcUrl } from "./network.js";
6
7
  /**
@@ -48,6 +49,55 @@ export async function runMppChannelDeployChecks(options) {
48
49
  function failure(id, name, detail) {
49
50
  return [{ id, name, pass: false, detail }];
50
51
  }
52
+ /**
53
+ * Attempts allowed when establishing the accepted commitment a check needs.
54
+ *
55
+ * One attempt is what turned a busy channel into a reported defect. Many
56
+ * attempts would hide a target that always refuses valid vouchers. Three is
57
+ * enough that ordinary contention clears, because every attempt re-reads the
58
+ * cumulative from a freshly issued challenge, while a real refusal reproduces
59
+ * on all of them.
60
+ */
61
+ const SETUP_ATTEMPTS = 3;
62
+ /**
63
+ * Advances the channel's cumulative by exactly one request price.
64
+ *
65
+ * Every ordering and replay check needs this first: a commitment the target has
66
+ * just accepted, so the probe that follows differs from it in exactly the one
67
+ * respect the check is about. Reading the cumulative from a freshly issued
68
+ * challenge on every attempt is what makes these checks re-runnable against a
69
+ * channel with any prior history, and what lets a retry recover when another
70
+ * payer advanced the cumulative mid-run.
71
+ *
72
+ * @throws {CheckSetupError} No attempt was accepted, so the check has no verdict.
73
+ */
74
+ async function advanceCumulative(options) {
75
+ const { target, commitmentSecretHex, network, rpcUrl } = options;
76
+ const refusals = [];
77
+ for (let attempt = 1; attempt <= SETUP_ATTEMPTS; attempt += 1) {
78
+ const challenge = await fetchChannelChallenge(target);
79
+ const amount = challenge.cumulativeAmount + challenge.requestedAmount;
80
+ const { credential, signature } = await buildChannelCredential({
81
+ challenge,
82
+ amount,
83
+ commitmentSecretHex,
84
+ network,
85
+ rpcUrl,
86
+ });
87
+ const submission = await submitCredential(target, credential);
88
+ if (submission.status === 200)
89
+ return { amount, credential, signature };
90
+ refusals.push(`attempt ${attempt}: ${amount} refused with HTTP ${submission.status}: ` +
91
+ `${submission.body}`);
92
+ }
93
+ throw new CheckSetupError(`A correctly advancing commitment was refused ${SETUP_ATTEMPTS} times, each ` +
94
+ `one signed against a freshly issued challenge, so this check never ` +
95
+ `reached the rule it tests (${refusals.join("; ")}). Either the target ` +
96
+ `refuses valid vouchers, which is a defect in its own right, or the ` +
97
+ `channel's cumulative is being advanced by something else while this run ` +
98
+ `is in progress. Re-run against a channel nothing else is paying through ` +
99
+ `to tell the two apart.`);
100
+ }
51
101
  /**
52
102
  * MPP-11: A commitment that does not advance the cumulative must be rejected.
53
103
  *
@@ -66,20 +116,7 @@ export async function runMppChannelOrderingCheck(options) {
66
116
  const name = "Cumulative Commitment Ordering";
67
117
  const { target, commitmentSecretHex, network, rpcUrl } = options;
68
118
  try {
69
- const opening = await fetchChannelChallenge(target);
70
- const baseline = opening.cumulativeAmount + opening.requestedAmount;
71
- const { credential } = await buildChannelCredential({
72
- challenge: opening,
73
- amount: baseline,
74
- commitmentSecretHex,
75
- network,
76
- rpcUrl,
77
- });
78
- const accepted = await submitCredential(target, credential);
79
- if (accepted.status !== 200) {
80
- return failure(id, name, `Setup failed: a correctly advancing commitment (${baseline}) was not accepted — ` +
81
- `HTTP ${accepted.status}: ${accepted.body}`);
82
- }
119
+ const { amount: baseline } = await advanceCumulative(options);
83
120
  // (a) Exactly equal to the cumulative the server now holds.
84
121
  const equalChallenge = await fetchChannelChallenge(target);
85
122
  const equal = await submitCredential(target, (await buildChannelCredential({
@@ -147,22 +184,9 @@ export async function runMppChannelOrderingCheck(options) {
147
184
  export async function runMppChannelReplayCheck(options) {
148
185
  const id = "MPP-12";
149
186
  const name = "Challenge Replay Rejection";
150
- const { target, commitmentSecretHex, network, rpcUrl } = options;
187
+ const { target } = options;
151
188
  try {
152
- const opening = await fetchChannelChallenge(target);
153
- const amount = opening.cumulativeAmount + opening.requestedAmount;
154
- const { credential } = await buildChannelCredential({
155
- challenge: opening,
156
- amount,
157
- commitmentSecretHex,
158
- network,
159
- rpcUrl,
160
- });
161
- const first = await submitCredential(target, credential);
162
- if (first.status !== 200) {
163
- return failure(id, name, `Setup failed: a valid commitment (${amount}) was not accepted — ` +
164
- `HTTP ${first.status}: ${first.body}`);
165
- }
189
+ const { credential } = await advanceCumulative(options);
166
190
  const replay = await submitCredential(target, credential);
167
191
  if (replay.status !== 402) {
168
192
  return failure(id, name, `An identical credential was accepted twice — expected HTTP 402 on replay, ` +
@@ -194,22 +218,9 @@ export async function runMppChannelReplayCheck(options) {
194
218
  export async function runMppChannelCommitmentReplayCheck(options) {
195
219
  const id = "MPP-14";
196
220
  const name = "Commitment Replay Rejection";
197
- const { target, commitmentSecretHex, network, rpcUrl } = options;
221
+ const { target } = options;
198
222
  try {
199
- const opening = await fetchChannelChallenge(target);
200
- const amount = opening.cumulativeAmount + opening.requestedAmount;
201
- const signature = await signChannelCommitment({
202
- channelContract: opening.channelContract,
203
- amount,
204
- commitmentSecretHex,
205
- networkPassphrase: networkPassphrase(network),
206
- rpcUrl: resolveRpcUrl(network, rpcUrl),
207
- });
208
- const first = await submitCredential(target, serializeChannelCredential({ challenge: opening, amount, signature }));
209
- if (first.status !== 200) {
210
- return failure(id, name, `Setup failed: a valid commitment (${amount}) was not accepted — ` +
211
- `HTTP ${first.status}: ${first.body}`);
212
- }
223
+ const { amount, signature } = await advanceCumulative(options);
213
224
  // Fresh challenge, same commitment. The signature is still cryptographically
214
225
  // valid; only the cumulative rule can reject it.
215
226
  const fresh = await fetchChannelChallenge(target);
@@ -166,7 +166,7 @@ export async function runMppChargeChecks(options) {
166
166
  // after settlement would leave money moved and no verdict to show for it.
167
167
  const endpoint = resolveRpcUrl(network, rpcUrl);
168
168
  const advertised = await fetchChargeChallenge(target);
169
- const mppx = Mppx.create({ methods: [charge({ secretKey: payerSecretKey })] });
169
+ const mppx = Mppx.create({ methods: [charge({ secretKey: payerSecretKey })], polyfill: false });
170
170
  let paid;
171
171
  try {
172
172
  paid = await mppx.fetch(target);
@@ -314,8 +314,14 @@ async function checkSignatureAccepted(options) {
314
314
  */
315
315
  async function checkInvalidSignatureRejected(options) {
316
316
  const { httpClient, paymentPayload } = await preparePayment(options);
317
- // Corrupt the signed transaction after signing, so the payload is
318
- // well-formed everywhere except the signature it carries.
317
+ // Corrupt the signed transaction after signing. This overwrites the tail of
318
+ // the base64 envelope, which also drops its padding — so the decoded envelope
319
+ // gains two bytes and stops parsing as XDR. Against the reference facilitator
320
+ // in stellar/x402-stellar the rejection therefore happens at decoding, not at
321
+ // signature verification, which is weaker than this check should be: a target
322
+ // that parsed the envelope and skipped verification entirely would still pass.
323
+ // Corrupting only the signature bytes, preserving a decodable envelope, is a
324
+ // 0.4.0 item. See docs/CHECKS.md's X402-07 row.
319
325
  const corrupted = {
320
326
  ...paymentPayload,
321
327
  payload: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wasit-dev/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.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",