@wasit-dev/core 0.4.0 → 0.6.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 +2 -2
- package/dist/mpp/channel.d.ts +8 -0
- package/dist/mpp/channel.js +18 -5
- package/dist/mpp/charge.js +14 -102
- package/dist/settlement.d.ts +93 -0
- package/dist/settlement.js +220 -0
- package/dist/x402/simulator.d.ts +42 -0
- package/dist/x402/simulator.js +234 -33
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Most people should reach for [`@wasit-dev/cli`](https://www.npmjs.com/package/@w
|
|
|
14
14
|
npm install @wasit-dev/core
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
Requires Node.js `>=
|
|
17
|
+
Requires Node.js `>=22`. Ships ESM only (`"type": "module"`), with TypeScript types included (`dist/index.d.ts`).
|
|
18
18
|
|
|
19
19
|
## Usage
|
|
20
20
|
|
|
@@ -51,7 +51,7 @@ Every check function returns `Promise<CheckResult[]>` and never rejects for a ta
|
|
|
51
51
|
| Function | Checks | Cost |
|
|
52
52
|
|---|---|---|
|
|
53
53
|
| `runX402ReadChecks({ target, method?, body?, headers? })` | `X402-01`–`05` | Free |
|
|
54
|
-
| `runX402PaymentChecks({ target, network, payerSecretKey, method?, body?, headers? })` | `X402-06`, `07` | **Settles a real payment every call** |
|
|
54
|
+
| `runX402PaymentChecks({ target, network, payerSecretKey, rpcUrl?, method?, body?, headers? })` | `X402-06`, `07` | **Settles a real payment every call** |
|
|
55
55
|
|
|
56
56
|
### MPP — charge mode
|
|
57
57
|
|
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
|
@@ -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, `
|
|
193
|
-
`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)}`);
|
|
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})
|
|
230
|
-
`
|
|
231
|
-
`
|
|
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
|
{
|
package/dist/mpp/charge.js
CHANGED
|
@@ -14,17 +14,14 @@
|
|
|
14
14
|
* @stellar/mpp's own client guards against when it refuses to sign a
|
|
15
15
|
* non-transfer authorization.
|
|
16
16
|
*/
|
|
17
|
-
import { Address, rpc, scValToNative, xdr } from "@stellar/stellar-sdk";
|
|
18
17
|
import { Mppx, charge } from "@stellar/mpp/charge/client";
|
|
19
18
|
import { Challenge, Receipt } from "mppx";
|
|
20
19
|
import { Keypair } from "@stellar/stellar-sdk";
|
|
21
20
|
import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
22
21
|
import { assertMppNetwork, resolveRpcUrl } from "./network.js";
|
|
22
|
+
import { verifySettlement } from "../settlement.js";
|
|
23
23
|
const CHECK_ID = "MPP-01";
|
|
24
24
|
const CHECK_NAME = "Charge Settlement On-Chain";
|
|
25
|
-
/** How long to wait for the settled transaction to become visible to RPC. */
|
|
26
|
-
const POLL_ATTEMPTS = 12;
|
|
27
|
-
const POLL_DELAY_MS = 1_000;
|
|
28
25
|
function asRecord(value) {
|
|
29
26
|
return typeof value === "object" && value !== null
|
|
30
27
|
? value
|
|
@@ -92,45 +89,6 @@ export function parseChargeChallenge(challenge) {
|
|
|
92
89
|
}
|
|
93
90
|
return { amount, currency, recipient };
|
|
94
91
|
}
|
|
95
|
-
/**
|
|
96
|
-
* Extracts CAP-46 `transfer` events from a settled transaction.
|
|
97
|
-
*
|
|
98
|
-
* Adapted from @stellar/mpp's own `validateSimulationEvents`, with one
|
|
99
|
-
* necessary difference: that function reads `xdr.DiagnosticEvent[]` from a
|
|
100
|
-
* simulation and unwraps each via `.event()`. RPC's `getTransaction` returns
|
|
101
|
-
* `contractEventsXdr` as `xdr.ContractEvent[][]` — already unwrapped, and
|
|
102
|
-
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
103
|
-
*/
|
|
104
|
-
function collectTransferEvents(contractEventsXdr) {
|
|
105
|
-
const transfers = [];
|
|
106
|
-
for (const perOperation of contractEventsXdr) {
|
|
107
|
-
for (const contractEvent of perOperation) {
|
|
108
|
-
if (contractEvent.type().name !== "contract")
|
|
109
|
-
continue;
|
|
110
|
-
const body = contractEvent.body().v0();
|
|
111
|
-
const topics = body.topics();
|
|
112
|
-
if (topics.length < 3)
|
|
113
|
-
continue;
|
|
114
|
-
// CAP-46: topic[0] = "transfer", topic[1] = from, topic[2] = to.
|
|
115
|
-
if (topics[0]?.sym?.()?.toString() !== "transfer")
|
|
116
|
-
continue;
|
|
117
|
-
const amount = scValToNative(body.data());
|
|
118
|
-
if (typeof amount !== "bigint")
|
|
119
|
-
continue;
|
|
120
|
-
const contractId = contractEvent.contractId();
|
|
121
|
-
if (!contractId)
|
|
122
|
-
continue;
|
|
123
|
-
transfers.push({
|
|
124
|
-
from: Address.fromScVal(topics[1]).toString(),
|
|
125
|
-
to: Address.fromScVal(topics[2]).toString(),
|
|
126
|
-
amount,
|
|
127
|
-
contract: Address.fromScAddress(xdr.ScAddress.scAddressTypeContract(contractId)).toString(),
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
return transfers;
|
|
132
|
-
}
|
|
133
|
-
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
134
92
|
function fail(detail) {
|
|
135
93
|
return [{ id: CHECK_ID, name: CHECK_NAME, pass: false, detail }];
|
|
136
94
|
}
|
|
@@ -177,8 +135,10 @@ export async function runMppChargeChecks(options) {
|
|
|
177
135
|
throw new MalformedResponseError(`Payment attempt failed: ${error.message}`);
|
|
178
136
|
}
|
|
179
137
|
if (!paid.ok) {
|
|
180
|
-
return fail(`
|
|
181
|
-
`answered HTTP ${paid.status} instead of
|
|
138
|
+
return fail(`Submitted a payment for the advertised ${advertised.amount} base ` +
|
|
139
|
+
`units, but the target answered HTTP ${paid.status} instead of ` +
|
|
140
|
+
`serving the resource. Nothing is claimed about settlement: a target ` +
|
|
141
|
+
`that refuses may never have broadcast the transaction.`);
|
|
182
142
|
}
|
|
183
143
|
let reference;
|
|
184
144
|
try {
|
|
@@ -188,62 +148,14 @@ export async function runMppChargeChecks(options) {
|
|
|
188
148
|
return fail(`Target returned ${paid.status} but no valid Payment-Receipt header: ` +
|
|
189
149
|
`${error.message}`);
|
|
190
150
|
}
|
|
191
|
-
const
|
|
192
|
-
|
|
151
|
+
const verdict = await verifySettlement(endpoint, reference, {
|
|
152
|
+
amount: advertised.amount,
|
|
153
|
+
token: advertised.currency,
|
|
154
|
+
recipient: advertised.recipient,
|
|
155
|
+
payer: payer.publicKey(),
|
|
193
156
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
if (current.status !== rpc.Api.GetTransactionStatus.NOT_FOUND) {
|
|
199
|
-
settled = current;
|
|
200
|
-
break;
|
|
201
|
-
}
|
|
202
|
-
await sleep(POLL_DELAY_MS);
|
|
203
|
-
}
|
|
204
|
-
if (!settled || settled.status === rpc.Api.GetTransactionStatus.NOT_FOUND) {
|
|
205
|
-
return fail(`Target reported settlement as tx ${reference}, but RPC still has no ` +
|
|
206
|
-
`such transaction after ${POLL_ATTEMPTS} seconds. Either it was never ` +
|
|
207
|
-
`broadcast, or the receipt references a transaction that does not exist.`);
|
|
208
|
-
}
|
|
209
|
-
if (settled.status !== rpc.Api.GetTransactionStatus.SUCCESS) {
|
|
210
|
-
return fail(`Transaction ${reference} exists on-chain but failed (status ` +
|
|
211
|
-
`${settled.status}). The target reported success for a settlement that ` +
|
|
212
|
-
`did not settle.`);
|
|
213
|
-
}
|
|
214
|
-
const transfers = collectTransferEvents(settled.events.contractEventsXdr);
|
|
215
|
-
if (transfers.length === 0) {
|
|
216
|
-
return fail(`Transaction ${reference} succeeded but emitted no CAP-46 transfer ` +
|
|
217
|
-
`event, so no token movement can be verified.`);
|
|
218
|
-
}
|
|
219
|
-
// Per the MPP spec, events must show only the expected balance change.
|
|
220
|
-
if (transfers.length !== 1) {
|
|
221
|
-
return fail(`Transaction ${reference} emitted ${transfers.length} transfer events; ` +
|
|
222
|
-
`exactly one was expected. Additional balance changes mean the ` +
|
|
223
|
-
`settlement moved more than what was advertised.`);
|
|
224
|
-
}
|
|
225
|
-
const actual = transfers[0];
|
|
226
|
-
const mismatches = [];
|
|
227
|
-
if (actual.amount !== advertised.amount) {
|
|
228
|
-
mismatches.push(`amount: advertised ${advertised.amount} base units, moved ${actual.amount}`);
|
|
229
|
-
}
|
|
230
|
-
if (actual.to !== advertised.recipient) {
|
|
231
|
-
mismatches.push(`recipient: advertised ${advertised.recipient}, paid ${actual.to}`);
|
|
232
|
-
}
|
|
233
|
-
if (actual.contract !== advertised.currency) {
|
|
234
|
-
mismatches.push(`token: advertised ${advertised.currency}, moved ${actual.contract}`);
|
|
235
|
-
}
|
|
236
|
-
// Without this, a target could reference any pre-existing transaction that
|
|
237
|
-
// happens to match the amount and recipient, and never take payment at all.
|
|
238
|
-
if (actual.from !== payer.publicKey()) {
|
|
239
|
-
mismatches.push(`payer: this run paid from ${payer.publicKey()}, but the referenced ` +
|
|
240
|
-
`transfer came from ${actual.from}`);
|
|
241
|
-
}
|
|
242
|
-
if (mismatches.length > 0) {
|
|
243
|
-
return fail(`Settlement does not match what the target advertised — ` +
|
|
244
|
-
`${mismatches.join("; ")} (tx ${reference}).`);
|
|
245
|
-
}
|
|
246
|
-
return pass(`Settled on-chain for exactly the advertised ${advertised.amount} base ` +
|
|
247
|
-
`units of ${advertised.currency} to ${advertised.recipient}, verified ` +
|
|
248
|
-
`from the transfer event (tx ${reference}).`);
|
|
157
|
+
// Same sentence MPP-01 has always printed, capitalised and closed.
|
|
158
|
+
return verdict.pass
|
|
159
|
+
? pass(`${verdict.detail.charAt(0).toUpperCase()}${verdict.detail.slice(1)}.`)
|
|
160
|
+
: fail(verdict.detail);
|
|
249
161
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-chain settlement verification, shared by every check that pays.
|
|
3
|
+
*
|
|
4
|
+
* A target's claim that it settled is only a claim. These helpers look the
|
|
5
|
+
* referenced transaction up on Stellar RPC and read what the token contract
|
|
6
|
+
* actually did from its `transfer` event, so MPP-01 and X402-06 hold every
|
|
7
|
+
* target to the same standard, with the same reading of the event formats and
|
|
8
|
+
* the same rules for when a missing transaction is the target's fault.
|
|
9
|
+
*/
|
|
10
|
+
import { rpc, xdr } from "@stellar/stellar-sdk";
|
|
11
|
+
/** What the token contract actually did, read from the settled transaction. */
|
|
12
|
+
export interface TransferEvent {
|
|
13
|
+
readonly from: string;
|
|
14
|
+
/** The destination's base address. CAP-67 never puts a muxed address in a topic. */
|
|
15
|
+
readonly to: string;
|
|
16
|
+
/**
|
|
17
|
+
* The destination's multiplexing id, when the transfer went to a muxed
|
|
18
|
+
* address (CAP-67). A `u64` id is kept as its decimal string; a memo-derived
|
|
19
|
+
* string or bytes value is kept as given (bytes as hex).
|
|
20
|
+
*/
|
|
21
|
+
readonly toMuxedId?: string;
|
|
22
|
+
readonly amount: bigint;
|
|
23
|
+
readonly contract: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Extracts CAP-46 `transfer` events from a settled transaction.
|
|
27
|
+
*
|
|
28
|
+
* Adapted from @stellar/mpp's own `validateSimulationEvents`, with one
|
|
29
|
+
* necessary difference: that function reads `xdr.DiagnosticEvent[]` from a
|
|
30
|
+
* simulation and unwraps each via `.event()`. RPC's `getTransaction` returns
|
|
31
|
+
* `contractEventsXdr` as `xdr.ContractEvent[][]` — already unwrapped, and
|
|
32
|
+
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
33
|
+
* Both the CAP-46 and the CAP-67 data formats are read; see
|
|
34
|
+
* {@link readTransferData}.
|
|
35
|
+
*/
|
|
36
|
+
export declare function collectTransferEvents(contractEventsXdr: xdr.ContractEvent[][]): TransferEvent[];
|
|
37
|
+
/**
|
|
38
|
+
* Whether a transfer reached the recipient the target advertised.
|
|
39
|
+
*
|
|
40
|
+
* A muxed recipient (`M...`) is one base account plus an id, and CAP-67
|
|
41
|
+
* reports it that way: the base address in the topic, the id in the data. So
|
|
42
|
+
* an advertised muxed recipient matches only when both parts do. Any other
|
|
43
|
+
* recipient is compared by address, as before.
|
|
44
|
+
*/
|
|
45
|
+
export declare function transferReachedRecipient(advertised: string, transfer: TransferEvent): boolean;
|
|
46
|
+
/** What looking for a settled transaction on RPC established. */
|
|
47
|
+
export type TransactionLookup = {
|
|
48
|
+
readonly kind: "found";
|
|
49
|
+
readonly response: rpc.Api.GetTransactionResponse;
|
|
50
|
+
} | {
|
|
51
|
+
readonly kind: "missing";
|
|
52
|
+
readonly ledgersWatched: number;
|
|
53
|
+
} | {
|
|
54
|
+
readonly kind: "stalled";
|
|
55
|
+
readonly ledgersWatched: number;
|
|
56
|
+
readonly waitedMs: number;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Polls RPC for a transaction until it appears, until RPC has closed enough
|
|
60
|
+
* ledgers without it to say it is missing, or until RPC stops advancing.
|
|
61
|
+
*
|
|
62
|
+
* Takes the lookup, the clock and the sleep as parameters so the three
|
|
63
|
+
* outcomes can be exercised without a network.
|
|
64
|
+
*/
|
|
65
|
+
export declare function waitForTransaction(getTransaction: () => Promise<rpc.Api.GetTransactionResponse>, options?: {
|
|
66
|
+
readonly ledgers?: number;
|
|
67
|
+
readonly maxWaitMs?: number;
|
|
68
|
+
readonly delayMs?: number;
|
|
69
|
+
readonly now?: () => number;
|
|
70
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
71
|
+
}): Promise<TransactionLookup>;
|
|
72
|
+
/** What a target advertised it would be paid, and who this run paid from. */
|
|
73
|
+
export interface ExpectedSettlement {
|
|
74
|
+
/** In base units, directly comparable to the event's `i128`. */
|
|
75
|
+
readonly amount: bigint;
|
|
76
|
+
/** The token contract (`C...`). */
|
|
77
|
+
readonly token: string;
|
|
78
|
+
readonly recipient: string;
|
|
79
|
+
/** This run's own payer, so an unrelated transaction cannot pass. */
|
|
80
|
+
readonly payer: string;
|
|
81
|
+
}
|
|
82
|
+
/** A verdict about the target's settlement. */
|
|
83
|
+
export interface SettlementVerdict {
|
|
84
|
+
readonly pass: boolean;
|
|
85
|
+
readonly detail: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Verifies that `reference` settled exactly what was expected.
|
|
89
|
+
*
|
|
90
|
+
* Returns a verdict about the target. Throws when RPC stops advancing, which
|
|
91
|
+
* says nothing about the target; callers report that as no verdict.
|
|
92
|
+
*/
|
|
93
|
+
export declare function verifySettlement(rpcUrl: string, reference: string, expected: ExpectedSettlement): Promise<SettlementVerdict>;
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-chain settlement verification, shared by every check that pays.
|
|
3
|
+
*
|
|
4
|
+
* A target's claim that it settled is only a claim. These helpers look the
|
|
5
|
+
* referenced transaction up on Stellar RPC and read what the token contract
|
|
6
|
+
* actually did from its `transfer` event, so MPP-01 and X402-06 hold every
|
|
7
|
+
* target to the same standard, with the same reading of the event formats and
|
|
8
|
+
* the same rules for when a missing transaction is the target's fault.
|
|
9
|
+
*/
|
|
10
|
+
import { Address, MuxedAccount, StrKey, rpc, scValToNative, xdr } from "@stellar/stellar-sdk";
|
|
11
|
+
/**
|
|
12
|
+
* How long to look for the settled transaction.
|
|
13
|
+
*
|
|
14
|
+
* A fixed wall-clock wait cannot tell a transaction that does not exist from
|
|
15
|
+
* an RPC that is behind, and reporting the second as the first blames the
|
|
16
|
+
* target for our infrastructure. So the wait is measured in ledgers RPC has
|
|
17
|
+
* closed: once it has closed this many more without the transaction, the
|
|
18
|
+
* transaction is not coming. An RPC that stops advancing before then gives no
|
|
19
|
+
* verdict at all.
|
|
20
|
+
*/
|
|
21
|
+
const LEDGERS_BEFORE_MISSING = 10;
|
|
22
|
+
const MAX_WAIT_MS = 120_000;
|
|
23
|
+
const POLL_DELAY_MS = 1_000;
|
|
24
|
+
function asRecord(value) {
|
|
25
|
+
return typeof value === "object" && value !== null
|
|
26
|
+
? value
|
|
27
|
+
: undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Reads the amount, and the destination's muxed id if any, from a `transfer`
|
|
31
|
+
* event's data.
|
|
32
|
+
*
|
|
33
|
+
* CAP-46 made the data a bare `i128` amount. CAP-67 keeps that when no muxed
|
|
34
|
+
* information is emitted, and otherwise makes it a map
|
|
35
|
+
* `{ amount: i128, to_muxed_id: u64 | bytes | string }`. Reading only the bare
|
|
36
|
+
* form would drop every payment to a muxed address, and report a settlement
|
|
37
|
+
* that happened as one that did not.
|
|
38
|
+
*/
|
|
39
|
+
function readTransferData(data) {
|
|
40
|
+
const native = scValToNative(data);
|
|
41
|
+
if (typeof native === "bigint")
|
|
42
|
+
return { amount: native };
|
|
43
|
+
const map = asRecord(native);
|
|
44
|
+
if (!map || typeof map["amount"] !== "bigint")
|
|
45
|
+
return undefined;
|
|
46
|
+
const id = map["to_muxed_id"];
|
|
47
|
+
if (id === undefined)
|
|
48
|
+
return { amount: map["amount"] };
|
|
49
|
+
if (typeof id === "bigint" || typeof id === "number") {
|
|
50
|
+
return { amount: map["amount"], toMuxedId: id.toString() };
|
|
51
|
+
}
|
|
52
|
+
if (typeof id === "string")
|
|
53
|
+
return { amount: map["amount"], toMuxedId: id };
|
|
54
|
+
if (id instanceof Uint8Array) {
|
|
55
|
+
return { amount: map["amount"], toMuxedId: Buffer.from(id).toString("hex") };
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Extracts CAP-46 `transfer` events from a settled transaction.
|
|
61
|
+
*
|
|
62
|
+
* Adapted from @stellar/mpp's own `validateSimulationEvents`, with one
|
|
63
|
+
* necessary difference: that function reads `xdr.DiagnosticEvent[]` from a
|
|
64
|
+
* simulation and unwraps each via `.event()`. RPC's `getTransaction` returns
|
|
65
|
+
* `contractEventsXdr` as `xdr.ContractEvent[][]` — already unwrapped, and
|
|
66
|
+
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
67
|
+
* Both the CAP-46 and the CAP-67 data formats are read; see
|
|
68
|
+
* {@link readTransferData}.
|
|
69
|
+
*/
|
|
70
|
+
export function collectTransferEvents(contractEventsXdr) {
|
|
71
|
+
const transfers = [];
|
|
72
|
+
for (const perOperation of contractEventsXdr) {
|
|
73
|
+
for (const contractEvent of perOperation) {
|
|
74
|
+
if (contractEvent.type().name !== "contract")
|
|
75
|
+
continue;
|
|
76
|
+
const body = contractEvent.body().v0();
|
|
77
|
+
const topics = body.topics();
|
|
78
|
+
if (topics.length < 3)
|
|
79
|
+
continue;
|
|
80
|
+
// CAP-46: topic[0] = "transfer", topic[1] = from, topic[2] = to.
|
|
81
|
+
if (topics[0]?.sym?.()?.toString() !== "transfer")
|
|
82
|
+
continue;
|
|
83
|
+
const data = readTransferData(body.data());
|
|
84
|
+
if (!data)
|
|
85
|
+
continue;
|
|
86
|
+
const contractId = contractEvent.contractId();
|
|
87
|
+
if (!contractId)
|
|
88
|
+
continue;
|
|
89
|
+
transfers.push({
|
|
90
|
+
from: Address.fromScVal(topics[1]).toString(),
|
|
91
|
+
to: Address.fromScVal(topics[2]).toString(),
|
|
92
|
+
...(data.toMuxedId !== undefined ? { toMuxedId: data.toMuxedId } : {}),
|
|
93
|
+
amount: data.amount,
|
|
94
|
+
contract: Address.fromScAddress(xdr.ScAddress.scAddressTypeContract(contractId)).toString(),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return transfers;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Whether a transfer reached the recipient the target advertised.
|
|
102
|
+
*
|
|
103
|
+
* A muxed recipient (`M...`) is one base account plus an id, and CAP-67
|
|
104
|
+
* reports it that way: the base address in the topic, the id in the data. So
|
|
105
|
+
* an advertised muxed recipient matches only when both parts do. Any other
|
|
106
|
+
* recipient is compared by address, as before.
|
|
107
|
+
*/
|
|
108
|
+
export function transferReachedRecipient(advertised, transfer) {
|
|
109
|
+
if (StrKey.isValidMed25519PublicKey(advertised)) {
|
|
110
|
+
const muxed = MuxedAccount.fromAddress(advertised, "0");
|
|
111
|
+
return (transfer.to === muxed.baseAccount().accountId() &&
|
|
112
|
+
transfer.toMuxedId === muxed.id());
|
|
113
|
+
}
|
|
114
|
+
return transfer.to === advertised;
|
|
115
|
+
}
|
|
116
|
+
/** How a transfer's destination reads in a report. */
|
|
117
|
+
function describeDestination(transfer) {
|
|
118
|
+
return transfer.toMuxedId === undefined
|
|
119
|
+
? transfer.to
|
|
120
|
+
: `${transfer.to} (muxed id ${transfer.toMuxedId})`;
|
|
121
|
+
}
|
|
122
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
123
|
+
/**
|
|
124
|
+
* Polls RPC for a transaction until it appears, until RPC has closed enough
|
|
125
|
+
* ledgers without it to say it is missing, or until RPC stops advancing.
|
|
126
|
+
*
|
|
127
|
+
* Takes the lookup, the clock and the sleep as parameters so the three
|
|
128
|
+
* outcomes can be exercised without a network.
|
|
129
|
+
*/
|
|
130
|
+
export async function waitForTransaction(getTransaction, options = {}) {
|
|
131
|
+
const ledgers = options.ledgers ?? LEDGERS_BEFORE_MISSING;
|
|
132
|
+
const maxWaitMs = options.maxWaitMs ?? MAX_WAIT_MS;
|
|
133
|
+
const delayMs = options.delayMs ?? POLL_DELAY_MS;
|
|
134
|
+
const now = options.now ?? Date.now;
|
|
135
|
+
const pause = options.sleep ?? sleep;
|
|
136
|
+
const startedAt = now();
|
|
137
|
+
let firstLedger;
|
|
138
|
+
for (;;) {
|
|
139
|
+
// An RPC failure is a harness problem: it says nothing about the target.
|
|
140
|
+
const current = await getTransaction();
|
|
141
|
+
if (current.status !== rpc.Api.GetTransactionStatus.NOT_FOUND) {
|
|
142
|
+
return { kind: "found", response: current };
|
|
143
|
+
}
|
|
144
|
+
firstLedger ??= current.latestLedger;
|
|
145
|
+
const ledgersWatched = current.latestLedger - firstLedger;
|
|
146
|
+
if (ledgersWatched >= ledgers)
|
|
147
|
+
return { kind: "missing", ledgersWatched };
|
|
148
|
+
const waitedMs = now() - startedAt;
|
|
149
|
+
if (waitedMs >= maxWaitMs)
|
|
150
|
+
return { kind: "stalled", ledgersWatched, waitedMs };
|
|
151
|
+
await pause(delayMs);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Verifies that `reference` settled exactly what was expected.
|
|
156
|
+
*
|
|
157
|
+
* Returns a verdict about the target. Throws when RPC stops advancing, which
|
|
158
|
+
* says nothing about the target; callers report that as no verdict.
|
|
159
|
+
*/
|
|
160
|
+
export async function verifySettlement(rpcUrl, reference, expected) {
|
|
161
|
+
const fail = (detail) => ({ pass: false, detail });
|
|
162
|
+
const server = new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith("http://") });
|
|
163
|
+
const lookup = await waitForTransaction(() => server.getTransaction(reference));
|
|
164
|
+
if (lookup.kind === "stalled") {
|
|
165
|
+
// RPC not advancing says nothing about the target: no verdict.
|
|
166
|
+
throw new Error(`RPC at ${rpcUrl} closed only ${lookup.ledgersWatched} ledgers in ` +
|
|
167
|
+
`${Math.round(lookup.waitedMs / 1000)} seconds while looking for tx ` +
|
|
168
|
+
`${reference}, so its absence says nothing about the target. Re-run, ` +
|
|
169
|
+
`or point --rpc-url at another endpoint.`);
|
|
170
|
+
}
|
|
171
|
+
if (lookup.kind === "missing") {
|
|
172
|
+
return fail(`Target reported settlement as tx ${reference}, but RPC closed ` +
|
|
173
|
+
`${lookup.ledgersWatched} more ledgers without it. Either it was never ` +
|
|
174
|
+
`broadcast, or the target referenced a transaction that does not exist.`);
|
|
175
|
+
}
|
|
176
|
+
const settled = lookup.response;
|
|
177
|
+
if (settled.status !== rpc.Api.GetTransactionStatus.SUCCESS) {
|
|
178
|
+
return fail(`Transaction ${reference} exists on-chain but failed (status ` +
|
|
179
|
+
`${settled.status}). The target reported success for a settlement that ` +
|
|
180
|
+
`did not settle.`);
|
|
181
|
+
}
|
|
182
|
+
const transfers = collectTransferEvents(settled.events.contractEventsXdr);
|
|
183
|
+
if (transfers.length === 0) {
|
|
184
|
+
return fail(`Transaction ${reference} succeeded but emitted no CAP-46 transfer ` +
|
|
185
|
+
`event, so no token movement can be verified.`);
|
|
186
|
+
}
|
|
187
|
+
// Both specs require the events to show only the expected balance change.
|
|
188
|
+
if (transfers.length !== 1) {
|
|
189
|
+
return fail(`Transaction ${reference} emitted ${transfers.length} transfer events; ` +
|
|
190
|
+
`exactly one was expected. Additional balance changes mean the ` +
|
|
191
|
+
`settlement moved more than what was advertised.`);
|
|
192
|
+
}
|
|
193
|
+
const actual = transfers[0];
|
|
194
|
+
const mismatches = [];
|
|
195
|
+
if (actual.amount !== expected.amount) {
|
|
196
|
+
mismatches.push(`amount: advertised ${expected.amount} base units, moved ${actual.amount}`);
|
|
197
|
+
}
|
|
198
|
+
if (!transferReachedRecipient(expected.recipient, actual)) {
|
|
199
|
+
mismatches.push(`recipient: advertised ${expected.recipient}, paid ${describeDestination(actual)}`);
|
|
200
|
+
}
|
|
201
|
+
if (actual.contract !== expected.token) {
|
|
202
|
+
mismatches.push(`token: advertised ${expected.token}, moved ${actual.contract}`);
|
|
203
|
+
}
|
|
204
|
+
// Without this, a target could reference any pre-existing transaction that
|
|
205
|
+
// happens to match the amount and recipient, and never take payment at all.
|
|
206
|
+
if (actual.from !== expected.payer) {
|
|
207
|
+
mismatches.push(`payer: this run paid from ${expected.payer}, but the referenced ` +
|
|
208
|
+
`transfer came from ${actual.from}`);
|
|
209
|
+
}
|
|
210
|
+
if (mismatches.length > 0) {
|
|
211
|
+
return fail(`Settlement does not match what the target advertised — ` +
|
|
212
|
+
`${mismatches.join("; ")} (tx ${reference}).`);
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
pass: true,
|
|
216
|
+
detail: `settled on-chain for exactly the advertised ${expected.amount} base ` +
|
|
217
|
+
`units of ${expected.token} to ${expected.recipient}, verified from the ` +
|
|
218
|
+
`transfer event (tx ${reference})`,
|
|
219
|
+
};
|
|
220
|
+
}
|
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
|
*
|
|
@@ -38,9 +47,42 @@ export interface X402PaymentCheckOptions extends RequestShape {
|
|
|
38
47
|
readonly target: string;
|
|
39
48
|
readonly network: string;
|
|
40
49
|
readonly payerSecretKey: string;
|
|
50
|
+
/** Overrides the default RPC endpoint used to verify settlement. */
|
|
51
|
+
readonly rpcUrl?: string;
|
|
41
52
|
/** See {@link X402SimulatorOptions.onResult} — same contract. */
|
|
42
53
|
readonly onResult?: (result: CheckResult) => void;
|
|
43
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Reads the settlement a paid response reports, before anything is looked up.
|
|
57
|
+
*
|
|
58
|
+
* Takes the header decoder rather than the response so the rules can be
|
|
59
|
+
* exercised without a network. `readSettlement` throws when the response
|
|
60
|
+
* carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
|
|
61
|
+
*/
|
|
62
|
+
export declare function readSettlementReference(status: number, readSettlement: () => {
|
|
63
|
+
readonly success: boolean;
|
|
64
|
+
readonly transaction?: string;
|
|
65
|
+
readonly errorReason?: string;
|
|
66
|
+
}): {
|
|
67
|
+
readonly reference: string;
|
|
68
|
+
} | {
|
|
69
|
+
readonly failure: string;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Corrupts the client's authorization signature, and nothing else.
|
|
73
|
+
*
|
|
74
|
+
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
75
|
+
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
76
|
+
* signature that proves the payer consented is the address credential's
|
|
77
|
+
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
78
|
+
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
79
|
+
* recipient, and fails only signature verification. A target can refuse it
|
|
80
|
+
* only by verifying the signature.
|
|
81
|
+
*
|
|
82
|
+
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
83
|
+
* the check reports no verdict rather than one it did not establish.
|
|
84
|
+
*/
|
|
85
|
+
export declare function corruptAuthSignature(transaction: string): string;
|
|
44
86
|
/**
|
|
45
87
|
* Runs X402-06 and X402-07 against a target.
|
|
46
88
|
*
|
package/dist/x402/simulator.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { errored, skipped } from "../check.js";
|
|
2
|
-
import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
2
|
+
import { CheckSetupError, ConfigurationError, MalformedResponseError, 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,16 @@ 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
|
+
import { Keypair, xdr } from "@stellar/stellar-sdk";
|
|
322
|
+
import { resolveRpcUrl } from "../mpp/network.js";
|
|
323
|
+
import { verifySettlement } from "../settlement.js";
|
|
324
|
+
/** The payment flow was never started, so neither payment check has a verdict. */
|
|
325
|
+
class PaymentNotAttemptedError extends Error {
|
|
326
|
+
constructor(reason) {
|
|
327
|
+
super(reason);
|
|
328
|
+
this.name = "PaymentNotAttemptedError";
|
|
329
|
+
}
|
|
330
|
+
}
|
|
267
331
|
function buildX402Client(network, payerSecretKey) {
|
|
268
332
|
const signer = createEd25519Signer(payerSecretKey, network);
|
|
269
333
|
const client = new x402Client().register("stellar:*", new ExactStellarClientScheme(signer));
|
|
@@ -283,62 +347,190 @@ async function preparePayment(options) {
|
|
|
283
347
|
paymentRequired = httpClient.getPaymentRequiredResponse((name) => challenge.headers.get(name));
|
|
284
348
|
}
|
|
285
349
|
catch (error) {
|
|
286
|
-
|
|
287
|
-
|
|
350
|
+
// The read checks already report what is wrong with the challenge. Failing
|
|
351
|
+
// X402-06/07 here too would count one broken challenge three times, and
|
|
352
|
+
// would make X402-07 read as a signature that was not rejected when no
|
|
353
|
+
// payment was ever sent. docs/CHECKS.md: an unreadable challenge produces
|
|
354
|
+
// no verdict.
|
|
355
|
+
const v1 = readV1BodyChallenge(await readText(challenge)) !== undefined;
|
|
356
|
+
throw new PaymentNotAttemptedError(v1
|
|
357
|
+
? `the target issued an x402 v1 challenge, and Wasit pays through the ` +
|
|
358
|
+
`v2 \`exact\` scheme on Stellar, the only version the spec defines, ` +
|
|
359
|
+
`so no payment was attempted (see X402-02).`
|
|
360
|
+
: `the challenge could not be read as x402 payment requirements ` +
|
|
361
|
+
`(${error.message}), so no payment was attempted ` +
|
|
362
|
+
`(see X402-02–04).`);
|
|
288
363
|
}
|
|
289
364
|
const paymentPayload = await client.createPaymentPayload(paymentRequired);
|
|
290
365
|
return { httpClient, paymentPayload };
|
|
291
366
|
}
|
|
292
|
-
/**
|
|
367
|
+
/** A Stellar transaction hash: 64 hex characters. */
|
|
368
|
+
const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
|
|
369
|
+
/**
|
|
370
|
+
* Reads the settlement a paid response reports, before anything is looked up.
|
|
371
|
+
*
|
|
372
|
+
* Takes the header decoder rather than the response so the rules can be
|
|
373
|
+
* exercised without a network. `readSettlement` throws when the response
|
|
374
|
+
* carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
|
|
375
|
+
*/
|
|
376
|
+
export function readSettlementReference(status, readSettlement) {
|
|
377
|
+
let settlement;
|
|
378
|
+
try {
|
|
379
|
+
settlement = readSettlement();
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return {
|
|
383
|
+
failure: `Valid payment accepted (HTTP ${status}), but the response carried no ` +
|
|
384
|
+
`PAYMENT-RESPONSE header, which the x402 v2 HTTP transport uses to ` +
|
|
385
|
+
`report settlement. Whether the payment settled cannot be verified.`,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
const reference = settlement.transaction ?? "";
|
|
389
|
+
// `settlement_pending` means broadcast but unconfirmed; the x402 spec has the
|
|
390
|
+
// caller reconcile on chain, which is exactly what X402-06 goes on to do.
|
|
391
|
+
const pending = !settlement.success && settlement.errorReason === "settlement_pending";
|
|
392
|
+
if ((!settlement.success && !pending) || !TRANSACTION_HASH.test(reference)) {
|
|
393
|
+
return {
|
|
394
|
+
failure: `Valid payment accepted (HTTP ${status}), but its PAYMENT-RESPONSE ` +
|
|
395
|
+
`reports ${settlement.success ? "success" : "failure"} with transaction ` +
|
|
396
|
+
`${JSON.stringify(reference)}, not a settled Stellar transaction hash.`,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
return { reference };
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* X402-06: a valid payment must be accepted, and must settle on-chain.
|
|
403
|
+
*
|
|
404
|
+
* A 2xx proves only that the target served the resource. The x402 v2 HTTP
|
|
405
|
+
* transport reports settlement in the `PAYMENT-RESPONSE` header, whose
|
|
406
|
+
* `transaction` is, for the `exact` scheme on Stellar, the settlement's hash.
|
|
407
|
+
* That hash is looked up on RPC and the token contract's own transfer event is
|
|
408
|
+
* held to what the target advertised, as MPP-01 does: a target that serves
|
|
409
|
+
* the resource without settling, or settles something else, fails here.
|
|
410
|
+
*/
|
|
293
411
|
async function checkSignatureAccepted(options) {
|
|
412
|
+
const id = "X402-06";
|
|
413
|
+
const name = "Signature Resubmit Accepted";
|
|
414
|
+
const fail = (detail) => ({ id, name, pass: false, detail });
|
|
294
415
|
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
295
416
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
|
|
296
417
|
const paid = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
418
|
+
if (paid.status < 200 || paid.status >= 300) {
|
|
419
|
+
return fail(`Expected 2xx after a valid payment, got ${paid.status}.`);
|
|
420
|
+
}
|
|
421
|
+
const read = readSettlementReference(paid.status, () => httpClient.getPaymentSettleResponse((header) => paid.headers.get(header)));
|
|
422
|
+
if ("failure" in read)
|
|
423
|
+
return fail(read.failure);
|
|
424
|
+
const reference = read.reference;
|
|
425
|
+
const accepted = paymentPayload.accepted;
|
|
426
|
+
let amount;
|
|
427
|
+
try {
|
|
428
|
+
amount = BigInt(accepted.amount);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
throw new MalformedResponseError(`The accepted payment requirements carry a non-numeric amount ` +
|
|
432
|
+
`(${JSON.stringify(accepted.amount)}).`);
|
|
433
|
+
}
|
|
434
|
+
const rpcUrl = resolveRpcUrl(options.network, options.rpcUrl);
|
|
435
|
+
const verdict = await verifySettlement(rpcUrl, reference, {
|
|
436
|
+
amount,
|
|
437
|
+
token: accepted.asset,
|
|
438
|
+
recipient: accepted.payTo,
|
|
439
|
+
payer: Keypair.fromSecret(options.payerSecretKey).publicKey(),
|
|
440
|
+
});
|
|
441
|
+
return verdict.pass
|
|
442
|
+
? {
|
|
443
|
+
id,
|
|
444
|
+
name,
|
|
445
|
+
pass: true,
|
|
446
|
+
detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
|
|
447
|
+
}
|
|
448
|
+
: fail(verdict.detail);
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Corrupts the client's authorization signature, and nothing else.
|
|
452
|
+
*
|
|
453
|
+
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
454
|
+
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
455
|
+
* signature that proves the payer consented is the address credential's
|
|
456
|
+
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
457
|
+
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
458
|
+
* recipient, and fails only signature verification. A target can refuse it
|
|
459
|
+
* only by verifying the signature.
|
|
460
|
+
*
|
|
461
|
+
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
462
|
+
* the check reports no verdict rather than one it did not establish.
|
|
463
|
+
*/
|
|
464
|
+
export function corruptAuthSignature(transaction) {
|
|
465
|
+
const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
|
|
466
|
+
const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
|
|
467
|
+
let corrupted = false;
|
|
468
|
+
for (const operation of operations) {
|
|
469
|
+
if (operation.body().switch().name !== "invokeHostFunction")
|
|
470
|
+
continue;
|
|
471
|
+
for (const entry of operation.body().invokeHostFunctionOp().auth()) {
|
|
472
|
+
const credentials = entry.credentials();
|
|
473
|
+
if (credentials.switch().name !== "sorobanCredentialsAddress")
|
|
474
|
+
continue;
|
|
475
|
+
const signature = credentials.address().signature();
|
|
476
|
+
if (signature.switch().name !== "scvVec")
|
|
477
|
+
continue;
|
|
478
|
+
for (const item of signature.vec() ?? []) {
|
|
479
|
+
if (item.switch().name !== "scvMap")
|
|
480
|
+
continue;
|
|
481
|
+
for (const field of item.map() ?? []) {
|
|
482
|
+
if (field.key().switch().name !== "scvSymbol")
|
|
483
|
+
continue;
|
|
484
|
+
if (field.key().sym().toString() !== "signature")
|
|
485
|
+
continue;
|
|
486
|
+
const bytes = Buffer.from(field.val().bytes());
|
|
487
|
+
bytes[0] = bytes[0] ^ 0xff;
|
|
488
|
+
field.val(xdr.ScVal.scvBytes(bytes));
|
|
489
|
+
corrupted = true;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (!corrupted) {
|
|
495
|
+
throw new CheckSetupError("The payment payload carries no authorization-entry signature to " +
|
|
496
|
+
"corrupt, so a corrupted signature cannot be tested.");
|
|
497
|
+
}
|
|
498
|
+
return envelope.toXDR("base64");
|
|
306
499
|
}
|
|
307
500
|
/**
|
|
308
501
|
* X402-07 (negative): a corrupted signature must be rejected.
|
|
309
502
|
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
503
|
+
* The payment is built exactly as for X402-06, then only the client's
|
|
504
|
+
* authorization signature is corrupted (see {@link corruptAuthSignature}), so
|
|
505
|
+
* the envelope still decodes and a target can refuse it only by verifying the
|
|
506
|
+
* signature. Before 0.6.0 the base64 envelope's tail was overwritten instead,
|
|
507
|
+
* which broke XDR decoding: a target that parsed the envelope and skipped
|
|
508
|
+
* signature verification entirely still passed.
|
|
509
|
+
*
|
|
510
|
+
* A rejection is any non-2xx answer. A rejection is only established by an
|
|
511
|
+
* answer: anything that prevents one produces no verdict.
|
|
314
512
|
*/
|
|
315
513
|
async function checkInvalidSignatureRejected(options) {
|
|
316
514
|
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
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.
|
|
325
515
|
const corrupted = {
|
|
326
516
|
...paymentPayload,
|
|
327
517
|
payload: {
|
|
328
518
|
...paymentPayload.payload,
|
|
329
|
-
transaction: paymentPayload.payload.transaction
|
|
519
|
+
transaction: corruptAuthSignature(paymentPayload.payload.transaction),
|
|
330
520
|
},
|
|
331
521
|
};
|
|
332
522
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
|
|
333
523
|
const response = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
|
|
334
|
-
const
|
|
524
|
+
const accepted = response.status >= 200 && response.status < 300;
|
|
335
525
|
return {
|
|
336
526
|
id: "X402-07",
|
|
337
527
|
name: "Invalid Signature Rejected",
|
|
338
|
-
pass,
|
|
339
|
-
detail:
|
|
340
|
-
? `
|
|
341
|
-
|
|
528
|
+
pass: !accepted,
|
|
529
|
+
detail: accepted
|
|
530
|
+
? `A payment with a corrupted authorization signature was accepted with ` +
|
|
531
|
+
`HTTP ${response.status} — security-relevant failure.`
|
|
532
|
+
: `Payment with a corrupted authorization signature correctly rejected ` +
|
|
533
|
+
`(HTTP ${response.status}).`,
|
|
342
534
|
};
|
|
343
535
|
}
|
|
344
536
|
/**
|
|
@@ -362,6 +554,15 @@ export async function runX402PaymentChecks(options) {
|
|
|
362
554
|
accepted = await checkSignatureAccepted(options);
|
|
363
555
|
}
|
|
364
556
|
catch (error) {
|
|
557
|
+
if (error instanceof PaymentNotAttemptedError) {
|
|
558
|
+
const notAttempted = [
|
|
559
|
+
skipped("X402-06", "Signature Resubmit Accepted", error.message),
|
|
560
|
+
skipped("X402-07", "Invalid Signature Rejected", error.message),
|
|
561
|
+
];
|
|
562
|
+
for (const result of notAttempted)
|
|
563
|
+
options.onResult?.(result);
|
|
564
|
+
return notAttempted;
|
|
565
|
+
}
|
|
365
566
|
accepted = errored("X402-06", "Signature Resubmit Accepted", error);
|
|
366
567
|
}
|
|
367
568
|
results.push(accepted);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wasit-dev/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"author": "Muhammad Dzakwan Najmi",
|
|
29
29
|
"license": "Apache-2.0",
|
|
30
30
|
"engines": {
|
|
31
|
-
"node": ">=
|
|
31
|
+
"node": ">=22"
|
|
32
32
|
},
|
|
33
33
|
"publishConfig": {
|
|
34
34
|
"access": "public"
|