@wasit-dev/core 0.3.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.
- package/README.md +43 -0
- package/dist/check.d.ts +4 -1
- package/dist/errors.d.ts +16 -6
- package/dist/errors.js +48 -1
- package/dist/mpp/channel.d.ts +8 -0
- package/dist/mpp/channel.js +74 -50
- package/dist/mpp/charge.js +1 -1
- package/dist/x402/simulator.d.ts +9 -0
- package/dist/x402/simulator.js +94 -7
- package/package.json +1 -1
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
|
-
/**
|
|
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
|
|
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),
|
package/dist/mpp/channel.d.ts
CHANGED
|
@@ -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
|
*
|
package/dist/mpp/channel.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getChannelState } from "@stellar/mpp/channel/server";
|
|
2
2
|
import { errored, skippedDestructive } from "../check.js";
|
|
3
|
-
import {
|
|
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,68 @@ export async function runMppChannelDeployChecks(options) {
|
|
|
48
49
|
function failure(id, name, detail) {
|
|
49
50
|
return [{ id, name, pass: false, detail }];
|
|
50
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
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Attempts allowed when establishing the accepted commitment a check needs.
|
|
67
|
+
*
|
|
68
|
+
* One attempt is what turned a busy channel into a reported defect. Many
|
|
69
|
+
* attempts would hide a target that always refuses valid vouchers. Three is
|
|
70
|
+
* enough that ordinary contention clears, because every attempt re-reads the
|
|
71
|
+
* cumulative from a freshly issued challenge, while a real refusal reproduces
|
|
72
|
+
* on all of them.
|
|
73
|
+
*/
|
|
74
|
+
const SETUP_ATTEMPTS = 3;
|
|
75
|
+
/**
|
|
76
|
+
* Advances the channel's cumulative by exactly one request price.
|
|
77
|
+
*
|
|
78
|
+
* Every ordering and replay check needs this first: a commitment the target has
|
|
79
|
+
* just accepted, so the probe that follows differs from it in exactly the one
|
|
80
|
+
* respect the check is about. Reading the cumulative from a freshly issued
|
|
81
|
+
* challenge on every attempt is what makes these checks re-runnable against a
|
|
82
|
+
* channel with any prior history, and what lets a retry recover when another
|
|
83
|
+
* payer advanced the cumulative mid-run.
|
|
84
|
+
*
|
|
85
|
+
* @throws {CheckSetupError} No attempt was accepted, so the check has no verdict.
|
|
86
|
+
*/
|
|
87
|
+
async function advanceCumulative(options) {
|
|
88
|
+
const { target, commitmentSecretHex, network, rpcUrl } = options;
|
|
89
|
+
const refusals = [];
|
|
90
|
+
for (let attempt = 1; attempt <= SETUP_ATTEMPTS; attempt += 1) {
|
|
91
|
+
const challenge = await fetchChannelChallenge(target);
|
|
92
|
+
const amount = challenge.cumulativeAmount + challenge.requestedAmount;
|
|
93
|
+
const { credential, signature } = await buildChannelCredential({
|
|
94
|
+
challenge,
|
|
95
|
+
amount,
|
|
96
|
+
commitmentSecretHex,
|
|
97
|
+
network,
|
|
98
|
+
rpcUrl,
|
|
99
|
+
});
|
|
100
|
+
const submission = await submitCredential(target, credential);
|
|
101
|
+
if (submission.status === 200)
|
|
102
|
+
return { amount, credential, signature };
|
|
103
|
+
refusals.push(`attempt ${attempt}: ${amount} refused with HTTP ${submission.status}: ` +
|
|
104
|
+
`${submission.body}`);
|
|
105
|
+
}
|
|
106
|
+
throw new CheckSetupError(`A correctly advancing commitment was refused ${SETUP_ATTEMPTS} times, each ` +
|
|
107
|
+
`one signed against a freshly issued challenge, so this check never ` +
|
|
108
|
+
`reached the rule it tests (${refusals.join("; ")}). Either the target ` +
|
|
109
|
+
`refuses valid vouchers, which is a defect in its own right, or the ` +
|
|
110
|
+
`channel's cumulative is being advanced by something else while this run ` +
|
|
111
|
+
`is in progress. Re-run against a channel nothing else is paying through ` +
|
|
112
|
+
`to tell the two apart.`);
|
|
113
|
+
}
|
|
51
114
|
/**
|
|
52
115
|
* MPP-11: A commitment that does not advance the cumulative must be rejected.
|
|
53
116
|
*
|
|
@@ -66,20 +129,7 @@ export async function runMppChannelOrderingCheck(options) {
|
|
|
66
129
|
const name = "Cumulative Commitment Ordering";
|
|
67
130
|
const { target, commitmentSecretHex, network, rpcUrl } = options;
|
|
68
131
|
try {
|
|
69
|
-
const
|
|
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
|
-
}
|
|
132
|
+
const { amount: baseline } = await advanceCumulative(options);
|
|
83
133
|
// (a) Exactly equal to the cumulative the server now holds.
|
|
84
134
|
const equalChallenge = await fetchChannelChallenge(target);
|
|
85
135
|
const equal = await submitCredential(target, (await buildChannelCredential({
|
|
@@ -147,26 +197,13 @@ export async function runMppChannelOrderingCheck(options) {
|
|
|
147
197
|
export async function runMppChannelReplayCheck(options) {
|
|
148
198
|
const id = "MPP-12";
|
|
149
199
|
const name = "Challenge Replay Rejection";
|
|
150
|
-
const { target
|
|
200
|
+
const { target } = options;
|
|
151
201
|
try {
|
|
152
|
-
const
|
|
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
|
-
}
|
|
202
|
+
const { credential } = await advanceCumulative(options);
|
|
166
203
|
const replay = await submitCredential(target, credential);
|
|
167
204
|
if (replay.status !== 402) {
|
|
168
|
-
return failure(id, name, `
|
|
169
|
-
`got ${replay.status}: ${replay.body}.
|
|
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)}`);
|
|
170
207
|
}
|
|
171
208
|
return [
|
|
172
209
|
{
|
|
@@ -194,30 +231,17 @@ export async function runMppChannelReplayCheck(options) {
|
|
|
194
231
|
export async function runMppChannelCommitmentReplayCheck(options) {
|
|
195
232
|
const id = "MPP-14";
|
|
196
233
|
const name = "Commitment Replay Rejection";
|
|
197
|
-
const { target
|
|
234
|
+
const { target } = options;
|
|
198
235
|
try {
|
|
199
|
-
const
|
|
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
|
-
}
|
|
236
|
+
const { amount, signature } = await advanceCumulative(options);
|
|
213
237
|
// Fresh challenge, same commitment. The signature is still cryptographically
|
|
214
238
|
// valid; only the cumulative rule can reject it.
|
|
215
239
|
const fresh = await fetchChannelChallenge(target);
|
|
216
240
|
const replay = await submitCredential(target, serializeChannelCredential({ challenge: fresh, amount, signature }));
|
|
217
241
|
if (replay.status !== 402) {
|
|
218
|
-
return failure(id, name, `A captured commitment (${amount})
|
|
219
|
-
`
|
|
220
|
-
`
|
|
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)}`);
|
|
221
245
|
}
|
|
222
246
|
return [
|
|
223
247
|
{
|
package/dist/mpp/charge.js
CHANGED
|
@@ -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);
|
package/dist/x402/simulator.d.ts
CHANGED
|
@@ -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
|
*
|
package/dist/x402/simulator.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { errored, skipped } from "../check.js";
|
|
2
|
-
import { ConfigurationError,
|
|
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
|
-
:
|
|
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
|
-
|
|
287
|
-
|
|
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 };
|
|
@@ -314,8 +386,14 @@ async function checkSignatureAccepted(options) {
|
|
|
314
386
|
*/
|
|
315
387
|
async function checkInvalidSignatureRejected(options) {
|
|
316
388
|
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
317
|
-
// Corrupt the signed transaction after signing
|
|
318
|
-
//
|
|
389
|
+
// Corrupt the signed transaction after signing. This overwrites the tail of
|
|
390
|
+
// the base64 envelope, which also drops its padding — so the decoded envelope
|
|
391
|
+
// gains two bytes and stops parsing as XDR. Against the reference facilitator
|
|
392
|
+
// in stellar/x402-stellar the rejection therefore happens at decoding, not at
|
|
393
|
+
// signature verification, which is weaker than this check should be: a target
|
|
394
|
+
// that parsed the envelope and skipped verification entirely would still pass.
|
|
395
|
+
// Corrupting only the signature bytes, preserving a decodable envelope, is a
|
|
396
|
+
// tracked for 0.6.0. See docs/CHECKS.md's X402-07 row.
|
|
319
397
|
const corrupted = {
|
|
320
398
|
...paymentPayload,
|
|
321
399
|
payload: {
|
|
@@ -356,6 +434,15 @@ export async function runX402PaymentChecks(options) {
|
|
|
356
434
|
accepted = await checkSignatureAccepted(options);
|
|
357
435
|
}
|
|
358
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
|
+
}
|
|
359
446
|
accepted = errored("X402-06", "Signature Resubmit Accepted", error);
|
|
360
447
|
}
|
|
361
448
|
results.push(accepted);
|
package/package.json
CHANGED