@wasit-dev/core 0.1.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.
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Manual credential construction for MPP channel mode.
3
+ *
4
+ * The official client always signs `localBaseline + price`, and that baseline
5
+ * starts at zero for a fresh client. This makes it single-use per channel: once
6
+ * any voucher lands, the server's cumulative has moved past anything a fresh
7
+ * client will offer. Conformance checks must be re-runnable against a channel
8
+ * with arbitrary prior history, and must be able to submit deliberately invalid
9
+ * amounts, so they assemble credentials directly.
10
+ */
11
+ import { Challenge } from "mppx";
12
+ import { MalformedResponseError } from "../errors.js";
13
+ export type ChannelAction = "voucher" | "close";
14
+ export declare class ChannelChallengeError extends MalformedResponseError {
15
+ constructor(message: string);
16
+ }
17
+ /** The channel-specific fields Wasit reads out of a 402 challenge. */
18
+ export interface ChannelChallenge {
19
+ /** The raw challenge, needed verbatim when serialising a credential. */
20
+ readonly challenge: Challenge.Challenge;
21
+ /** Channel contract the server expects to be paid through. */
22
+ readonly channelContract: string;
23
+ /** Price of this single request, in base units. */
24
+ readonly requestedAmount: bigint;
25
+ /**
26
+ * Cumulative the server claims to hold. Self-reported by the target, so a
27
+ * dishonest server could skew any amount derived from it. Used only to
28
+ * construct probe amounts, never as the thing being asserted.
29
+ */
30
+ readonly cumulativeAmount: bigint;
31
+ }
32
+ /**
33
+ * Requests the resource unpaid and parses the resulting 402 challenge.
34
+ *
35
+ * Every probe must call this fresh. The server claims a challenge ID on first
36
+ * use via an atomic compare-and-set, so reusing a challenge triggers replay
37
+ * rejection before any commitment logic runs — which would silently mask the
38
+ * rule a check is trying to exercise.
39
+ */
40
+ export declare function fetchChannelChallenge(target: string): Promise<ChannelChallenge>;
41
+ /**
42
+ * Serialises an already-signed commitment into an Authorization header value.
43
+ *
44
+ * Kept separate from signing so a check can re-present a captured
45
+ * (amount, signature) pair against a *different* challenge — the commitment
46
+ * replay vector, which the official client cannot express because it always
47
+ * re-signs.
48
+ */
49
+ export declare function serializeChannelCredential(parameters: {
50
+ readonly challenge: ChannelChallenge;
51
+ readonly amount: bigint;
52
+ readonly signature: string;
53
+ readonly action?: ChannelAction;
54
+ }): string;
55
+ export interface BuildChannelCredentialParams {
56
+ readonly challenge: ChannelChallenge;
57
+ /** Absolute cumulative amount to commit to, in base units. */
58
+ readonly amount: bigint;
59
+ readonly commitmentSecretHex: string;
60
+ readonly network: string;
61
+ readonly rpcUrl?: string;
62
+ readonly action?: ChannelAction;
63
+ }
64
+ /** Signs `amount` for this challenge's channel and serialises the credential. */
65
+ export declare function buildChannelCredential(parameters: BuildChannelCredentialParams): Promise<{
66
+ credential: string;
67
+ signature: string;
68
+ }>;
69
+ export interface SubmissionResult {
70
+ readonly status: number;
71
+ readonly body: string;
72
+ }
73
+ /** Submits a credential and captures both status and body for diagnostics. */
74
+ export declare function submitCredential(target: string, credential: string): Promise<SubmissionResult>;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Manual credential construction for MPP channel mode.
3
+ *
4
+ * The official client always signs `localBaseline + price`, and that baseline
5
+ * starts at zero for a fresh client. This makes it single-use per channel: once
6
+ * any voucher lands, the server's cumulative has moved past anything a fresh
7
+ * client will offer. Conformance checks must be re-runnable against a channel
8
+ * with arbitrary prior history, and must be able to submit deliberately invalid
9
+ * amounts, so they assemble credentials directly.
10
+ */
11
+ import { Challenge, Credential } from "mppx";
12
+ import { MalformedResponseError, fetchTarget } from "../errors.js";
13
+ import { signChannelCommitment } from "./channel-commitment.js";
14
+ import { networkPassphrase, resolveRpcUrl } from "./network.js";
15
+ export class ChannelChallengeError extends MalformedResponseError {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "ChannelChallengeError";
19
+ }
20
+ }
21
+ function asRecord(value) {
22
+ return typeof value === "object" && value !== null
23
+ ? value
24
+ : undefined;
25
+ }
26
+ function readString(source, key) {
27
+ const value = source[key];
28
+ return typeof value === "string" ? value : undefined;
29
+ }
30
+ /**
31
+ * Requests the resource unpaid and parses the resulting 402 challenge.
32
+ *
33
+ * Every probe must call this fresh. The server claims a challenge ID on first
34
+ * use via an atomic compare-and-set, so reusing a challenge triggers replay
35
+ * rejection before any commitment logic runs — which would silently mask the
36
+ * rule a check is trying to exercise.
37
+ */
38
+ export async function fetchChannelChallenge(target) {
39
+ const response = await fetchTarget(target);
40
+ if (response.status !== 402) {
41
+ throw new ChannelChallengeError(`Expected HTTP 402 with a payment challenge, got ${response.status}.`);
42
+ }
43
+ let challenge;
44
+ try {
45
+ challenge = Challenge.fromResponse(response);
46
+ }
47
+ catch (error) {
48
+ throw new ChannelChallengeError(`Challenge could not be parsed from the WWW-Authenticate header: ` +
49
+ `${error.message}`);
50
+ }
51
+ const request = asRecord(challenge.request);
52
+ if (!request) {
53
+ throw new ChannelChallengeError("Challenge carries no request object.");
54
+ }
55
+ const channelContract = readString(request, "channel");
56
+ const requested = readString(request, "amount");
57
+ if (!channelContract || !requested) {
58
+ throw new ChannelChallengeError("Challenge request is missing `channel` or `amount`.");
59
+ }
60
+ // Absent on a channel that has not yet taken a voucher. Zero is the server's
61
+ // own starting cumulative, so it is the correct reading of "not present".
62
+ const methodDetails = asRecord(request["methodDetails"]);
63
+ const cumulativeRaw = methodDetails
64
+ ? readString(methodDetails, "cumulativeAmount")
65
+ : undefined;
66
+ try {
67
+ return {
68
+ challenge,
69
+ channelContract,
70
+ requestedAmount: BigInt(requested),
71
+ cumulativeAmount: BigInt(cumulativeRaw ?? "0"),
72
+ };
73
+ }
74
+ catch {
75
+ throw new ChannelChallengeError(`Challenge carries non-numeric amounts (amount="${requested}", ` +
76
+ `cumulativeAmount="${cumulativeRaw ?? "0"}").`);
77
+ }
78
+ }
79
+ /**
80
+ * Serialises an already-signed commitment into an Authorization header value.
81
+ *
82
+ * Kept separate from signing so a check can re-present a captured
83
+ * (amount, signature) pair against a *different* challenge — the commitment
84
+ * replay vector, which the official client cannot express because it always
85
+ * re-signs.
86
+ */
87
+ export function serializeChannelCredential(parameters) {
88
+ const { challenge, amount, signature, action = "voucher" } = parameters;
89
+ return Credential.serialize(Credential.from({
90
+ challenge: challenge.challenge,
91
+ payload: { action, amount: amount.toString(), signature },
92
+ }));
93
+ }
94
+ /** Signs `amount` for this challenge's channel and serialises the credential. */
95
+ export async function buildChannelCredential(parameters) {
96
+ const { challenge, amount, commitmentSecretHex, network, rpcUrl, action } = parameters;
97
+ const signature = await signChannelCommitment({
98
+ channelContract: challenge.channelContract,
99
+ amount,
100
+ commitmentSecretHex,
101
+ networkPassphrase: networkPassphrase(network),
102
+ rpcUrl: resolveRpcUrl(network, rpcUrl),
103
+ });
104
+ return {
105
+ signature,
106
+ credential: serializeChannelCredential({ challenge, amount, signature, action }),
107
+ };
108
+ }
109
+ /** Submits a credential and captures both status and body for diagnostics. */
110
+ export async function submitCredential(target, credential) {
111
+ const response = await fetchTarget(target, {
112
+ headers: { Authorization: credential },
113
+ });
114
+ return { status: response.status, body: await response.text() };
115
+ }
@@ -0,0 +1,75 @@
1
+ import type { CheckResult } from "../check.js";
2
+ export interface MppChannelDeployCheckOptions {
3
+ channelContract: string;
4
+ network: string;
5
+ /** Overrides the default RPC endpoint, as every other channel check does. */
6
+ rpcUrl?: string;
7
+ expected: {
8
+ token: string;
9
+ from: string;
10
+ to: string;
11
+ refundWaitingPeriod: number;
12
+ };
13
+ }
14
+ /**
15
+ * MPP-10: The channel contract deploys correctly — its address is valid
16
+ * and its on-chain state is queryable, and matches the parameters it was
17
+ * opened with (token, funder, recipient, refund waiting period).
18
+ */
19
+ export declare function runMppChannelDeployChecks(options: MppChannelDeployCheckOptions): Promise<CheckResult[]>;
20
+ export interface MppChannelCheckOptions {
21
+ /** URL of the paid resource on the target service. */
22
+ target: string;
23
+ /** Raw ed25519 commitment seed, hex. Must match the channel's commitment key. */
24
+ commitmentSecretHex: string;
25
+ /** CAIP-2 network id, e.g. "stellar:testnet". */
26
+ network: string;
27
+ /** Overrides the default RPC endpoint for the network. */
28
+ rpcUrl?: string;
29
+ }
30
+ /**
31
+ * MPP-11: A commitment that does not advance the cumulative must be rejected.
32
+ *
33
+ * The server applies two distinct rules (cumulativeMonotonicityError):
34
+ * (a) commitmentAmount > previousCumulative
35
+ * (b) commitmentAmount >= previousCumulative + requestedAmount
36
+ * Both are probed. Each probe fetches a FRESH challenge, so the challenge
37
+ * replay guard — which runs earlier and returns the same HTTP 402 — cannot
38
+ * fire and be mistaken for monotonicity enforcement.
39
+ *
40
+ * The check first advances the cumulative by exactly one request, which makes
41
+ * it re-runnable against a channel with any prior history.
42
+ */
43
+ export declare function runMppChannelOrderingCheck(options: MppChannelCheckOptions): Promise<CheckResult[]>;
44
+ /**
45
+ * MPP-12: Resubmitting an identical credential must be rejected.
46
+ *
47
+ * Targets the challenge replay guard specifically: the credential replayed is
48
+ * byte-identical to one the server accepted moments earlier, so its signature
49
+ * and amount are already proven valid and only the challenge-ID claim can
50
+ * account for the rejection.
51
+ */
52
+ export declare function runMppChannelReplayCheck(options: MppChannelCheckOptions): Promise<CheckResult[]>;
53
+ /**
54
+ * MPP-14: A captured commitment must not be redeemable against a new challenge.
55
+ *
56
+ * The realistic double-spend: an observer lifts a valid (amount, signature)
57
+ * pair off the wire, requests a fresh challenge of their own, and re-presents
58
+ * the captured commitment. The challenge replay guard cannot help — the
59
+ * challenge ID is new — so only the cumulative rule stands between the attacker
60
+ * and a second delivery. The official client cannot express this, because it
61
+ * re-signs on every call.
62
+ */
63
+ export declare function runMppChannelCommitmentReplayCheck(options: MppChannelCheckOptions): Promise<CheckResult[]>;
64
+ export interface MppChannelCloseCheckOptions extends MppChannelCheckOptions {
65
+ /**
66
+ * Contract address the operator intends to destroy. The check refuses to run
67
+ * unless the target's challenge advertises exactly this channel, so pointing
68
+ * a destructive run at the wrong service closes nothing.
69
+ */
70
+ expectedChannel?: string;
71
+ allowDestructive?: boolean;
72
+ closePollAttempts?: number;
73
+ closePollDelayMs?: number;
74
+ }
75
+ export declare function runMppChannelCloseCheck(options: MppChannelCloseCheckOptions): Promise<CheckResult[]>;
@@ -0,0 +1,335 @@
1
+ import { getChannelState } from "@stellar/mpp/channel/server";
2
+ import { errored, skippedDestructive } from "../check.js";
3
+ import { readChannelWithdrawn, signChannelCommitment } from "./channel-commitment.js";
4
+ import { buildChannelCredential, fetchChannelChallenge, serializeChannelCredential, submitCredential, } from "./channel-credential.js";
5
+ import { assertMppNetwork, networkPassphrase, resolveRpcUrl } from "./network.js";
6
+ /**
7
+ * MPP-10: The channel contract deploys correctly — its address is valid
8
+ * and its on-chain state is queryable, and matches the parameters it was
9
+ * opened with (token, funder, recipient, refund waiting period).
10
+ */
11
+ export async function runMppChannelDeployChecks(options) {
12
+ let state;
13
+ try {
14
+ state = await getChannelState({
15
+ channel: options.channelContract,
16
+ network: assertMppNetwork(options.network),
17
+ ...(options.rpcUrl ? { rpcUrl: options.rpcUrl } : {}),
18
+ });
19
+ }
20
+ catch (err) {
21
+ return [errored("MPP-10", "Channel Deploy", err)];
22
+ }
23
+ const mismatches = [];
24
+ if (state.token !== options.expected.token) {
25
+ mismatches.push(`token: expected ${options.expected.token}, got ${state.token}`);
26
+ }
27
+ if (state.from !== options.expected.from) {
28
+ mismatches.push(`from: expected ${options.expected.from}, got ${state.from}`);
29
+ }
30
+ if (state.to !== options.expected.to) {
31
+ mismatches.push(`to: expected ${options.expected.to}, got ${state.to}`);
32
+ }
33
+ if (state.refundWaitingPeriod !== options.expected.refundWaitingPeriod) {
34
+ mismatches.push(`refundWaitingPeriod: expected ${options.expected.refundWaitingPeriod}, got ${state.refundWaitingPeriod}`);
35
+ }
36
+ const pass = mismatches.length === 0;
37
+ return [
38
+ {
39
+ id: "MPP-10",
40
+ name: "Channel Deploy",
41
+ pass,
42
+ detail: pass
43
+ ? `Channel ${options.channelContract} deployed and queryable — balance=${state.balance}, currentLedger=${state.currentLedger}.`
44
+ : `Channel state mismatch: ${mismatches.join("; ")}.`,
45
+ },
46
+ ];
47
+ }
48
+ function failure(id, name, detail) {
49
+ return [{ id, name, pass: false, detail }];
50
+ }
51
+ /**
52
+ * MPP-11: A commitment that does not advance the cumulative must be rejected.
53
+ *
54
+ * The server applies two distinct rules (cumulativeMonotonicityError):
55
+ * (a) commitmentAmount > previousCumulative
56
+ * (b) commitmentAmount >= previousCumulative + requestedAmount
57
+ * Both are probed. Each probe fetches a FRESH challenge, so the challenge
58
+ * replay guard — which runs earlier and returns the same HTTP 402 — cannot
59
+ * fire and be mistaken for monotonicity enforcement.
60
+ *
61
+ * The check first advances the cumulative by exactly one request, which makes
62
+ * it re-runnable against a channel with any prior history.
63
+ */
64
+ export async function runMppChannelOrderingCheck(options) {
65
+ const id = "MPP-11";
66
+ const name = "Cumulative Commitment Ordering";
67
+ const { target, commitmentSecretHex, network, rpcUrl } = options;
68
+ 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
+ }
83
+ // (a) Exactly equal to the cumulative the server now holds.
84
+ const equalChallenge = await fetchChannelChallenge(target);
85
+ const equal = await submitCredential(target, (await buildChannelCredential({
86
+ challenge: equalChallenge,
87
+ amount: baseline,
88
+ commitmentSecretHex,
89
+ network,
90
+ rpcUrl,
91
+ })).credential);
92
+ if (equal.status !== 402) {
93
+ return failure(id, name, `A commitment equal to the current cumulative (${baseline}) was not rejected — ` +
94
+ `expected HTTP 402, got ${equal.status}: ${equal.body}`);
95
+ }
96
+ // (b) Advances, but does not cover this request's price. Only meaningful
97
+ // when the price exceeds one base unit; otherwise it collapses into (a).
98
+ const shortChallenge = await fetchChannelChallenge(target);
99
+ if (shortChallenge.requestedAmount <= 1n) {
100
+ return [
101
+ {
102
+ id,
103
+ name,
104
+ pass: true,
105
+ detail: `Non-advancing commitment correctly rejected (HTTP 402). ` +
106
+ `Under-covering sub-case not probed: the request price is ` +
107
+ `${shortChallenge.requestedAmount} base unit, too small to distinguish it.`,
108
+ },
109
+ ];
110
+ }
111
+ const shortAmount = baseline + shortChallenge.requestedAmount - 1n;
112
+ const short = await submitCredential(target, (await buildChannelCredential({
113
+ challenge: shortChallenge,
114
+ amount: shortAmount,
115
+ commitmentSecretHex,
116
+ network,
117
+ rpcUrl,
118
+ })).credential);
119
+ if (short.status !== 402) {
120
+ return failure(id, name, `A commitment that advances but under-covers the request price ` +
121
+ `(${shortAmount} vs required ${baseline + shortChallenge.requestedAmount}) ` +
122
+ `was not rejected — expected HTTP 402, got ${short.status}: ${short.body}`);
123
+ }
124
+ return [
125
+ {
126
+ id,
127
+ name,
128
+ pass: true,
129
+ detail: `Both ordering rules enforced: a commitment equal to the cumulative ` +
130
+ `(${baseline}) and one that under-covers the price (${shortAmount}) ` +
131
+ `were each rejected with HTTP 402.`,
132
+ },
133
+ ];
134
+ }
135
+ catch (error) {
136
+ return [errored(id, name, error)];
137
+ }
138
+ }
139
+ /**
140
+ * MPP-12: Resubmitting an identical credential must be rejected.
141
+ *
142
+ * Targets the challenge replay guard specifically: the credential replayed is
143
+ * byte-identical to one the server accepted moments earlier, so its signature
144
+ * and amount are already proven valid and only the challenge-ID claim can
145
+ * account for the rejection.
146
+ */
147
+ export async function runMppChannelReplayCheck(options) {
148
+ const id = "MPP-12";
149
+ const name = "Challenge Replay Rejection";
150
+ const { target, commitmentSecretHex, network, rpcUrl } = options;
151
+ 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
+ }
166
+ const replay = await submitCredential(target, credential);
167
+ if (replay.status !== 402) {
168
+ return failure(id, name, `An identical credential was accepted twice — expected HTTP 402 on replay, ` +
169
+ `got ${replay.status}: ${replay.body}. This is a double-spend.`);
170
+ }
171
+ return [
172
+ {
173
+ id,
174
+ name,
175
+ pass: true,
176
+ detail: `Byte-identical credential correctly rejected on replay (HTTP 402).`,
177
+ },
178
+ ];
179
+ }
180
+ catch (error) {
181
+ return [errored(id, name, error)];
182
+ }
183
+ }
184
+ /**
185
+ * MPP-14: A captured commitment must not be redeemable against a new challenge.
186
+ *
187
+ * The realistic double-spend: an observer lifts a valid (amount, signature)
188
+ * pair off the wire, requests a fresh challenge of their own, and re-presents
189
+ * the captured commitment. The challenge replay guard cannot help — the
190
+ * challenge ID is new — so only the cumulative rule stands between the attacker
191
+ * and a second delivery. The official client cannot express this, because it
192
+ * re-signs on every call.
193
+ */
194
+ export async function runMppChannelCommitmentReplayCheck(options) {
195
+ const id = "MPP-14";
196
+ const name = "Commitment Replay Rejection";
197
+ const { target, commitmentSecretHex, network, rpcUrl } = options;
198
+ 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
+ }
213
+ // Fresh challenge, same commitment. The signature is still cryptographically
214
+ // valid; only the cumulative rule can reject it.
215
+ const fresh = await fetchChannelChallenge(target);
216
+ const replay = await submitCredential(target, serializeChannelCredential({ challenge: fresh, amount, signature }));
217
+ if (replay.status !== 402) {
218
+ return failure(id, name, `A captured commitment (${amount}) was redeemed a second time against a ` +
219
+ `fresh challenge — expected HTTP 402, got ${replay.status}: ${replay.body}. ` +
220
+ `This is a double-spend.`);
221
+ }
222
+ return [
223
+ {
224
+ id,
225
+ name,
226
+ pass: true,
227
+ detail: `Captured commitment (${amount}) correctly rejected when re-presented ` +
228
+ `against a fresh challenge (HTTP 402).`,
229
+ },
230
+ ];
231
+ }
232
+ catch (error) {
233
+ return [errored(id, name, error)];
234
+ }
235
+ }
236
+ function sleep(ms) {
237
+ return new Promise((resolve) => setTimeout(resolve, ms));
238
+ }
239
+ export async function runMppChannelCloseCheck(options) {
240
+ const id = "MPP-13";
241
+ const name = "Close Settlement";
242
+ const { target, commitmentSecretHex, network, rpcUrl, expectedChannel, allowDestructive = false, closePollAttempts = 6, closePollDelayMs = 2_000, } = options;
243
+ if (!allowDestructive) {
244
+ return [
245
+ skippedDestructive(id, name, "closing settles the channel on-chain and permanently ends it. " +
246
+ "Re-run with destructive checks enabled, against a channel you own."),
247
+ ];
248
+ }
249
+ if (!expectedChannel) {
250
+ return failure(id, name, "Destructive checks are enabled but no expected channel was named. " +
251
+ "Name the channel you intend to close, so a misconfigured target " +
252
+ "cannot close a different one.");
253
+ }
254
+ try {
255
+ const challenge = await fetchChannelChallenge(target);
256
+ const channel = challenge.channelContract;
257
+ // The target decides which channel it bills through, so the address in the
258
+ // challenge is the one that would actually be closed. Refusing on mismatch
259
+ // is what makes naming the channel a safeguard rather than a formality.
260
+ if (channel !== expectedChannel) {
261
+ return failure(id, name, `Refusing to close: ${target} bills through channel ${channel}, but the ` +
262
+ `run named ${expectedChannel} as the channel to destroy. Point the ` +
263
+ `target at the intended channel, or correct the expected address.`);
264
+ }
265
+ const readState = () => getChannelState({
266
+ channel,
267
+ network: assertMppNetwork(network),
268
+ ...(rpcUrl ? { rpcUrl } : {}),
269
+ });
270
+ const before = await readState();
271
+ if (before.closeEffectiveAtLedger !== null) {
272
+ return failure(id, name, `Channel ${channel} is already closing or closed ` +
273
+ `(closeEffectiveAtLedger=${before.closeEffectiveAtLedger}). ` +
274
+ `This check needs a channel that is still open.`);
275
+ }
276
+ const amount = challenge.cumulativeAmount + challenge.requestedAmount;
277
+ const { credential } = await buildChannelCredential({
278
+ challenge,
279
+ amount,
280
+ commitmentSecretHex,
281
+ network,
282
+ rpcUrl,
283
+ action: "close",
284
+ });
285
+ const closed = await submitCredential(target, credential);
286
+ if (closed.status !== 200) {
287
+ return failure(id, name, `Close credential (${amount}) was not accepted — expected HTTP 200, ` +
288
+ `got ${closed.status}: ${closed.body}`);
289
+ }
290
+ let after;
291
+ for (let attempt = 0; attempt < closePollAttempts; attempt += 1) {
292
+ after = await readState();
293
+ if (after.closeEffectiveAtLedger !== null)
294
+ break;
295
+ await sleep(closePollDelayMs);
296
+ }
297
+ if (!after || after.closeEffectiveAtLedger === null) {
298
+ return failure(id, name, `Server reported the close succeeded, but on-chain state still shows ` +
299
+ `the channel open after ${closePollAttempts} polls. The settlement ` +
300
+ `was not observable on-chain.`);
301
+ }
302
+ // The channel always ends at zero: close pays the commitment to the
303
+ // recipient and auto-refunds whatever is left to the funder. So the balance
304
+ // delta proves nothing. `withdrawn` is the real evidence — the contract
305
+ // records it in the same call that transfers the payout, and that transfer
306
+ // is non-fallible, so a mismatch there would have reverted the whole close.
307
+ const withdrawn = await readChannelWithdrawn({
308
+ channelContract: channel,
309
+ networkPassphrase: networkPassphrase(network),
310
+ rpcUrl: resolveRpcUrl(network, rpcUrl),
311
+ });
312
+ if (withdrawn !== amount) {
313
+ return failure(id, name, `Channel closed (closeEffectiveAtLedger=${after.closeEffectiveAtLedger}), ` +
314
+ `but the contract recorded ${withdrawn} withdrawn instead of the ` +
315
+ `committed ${amount}. The payout did not match the commitment.`);
316
+ }
317
+ return [
318
+ {
319
+ id,
320
+ name,
321
+ pass: true,
322
+ destructive: true,
323
+ detail: `Close settled on-chain: the contract recorded exactly the committed ` +
324
+ `${amount} as withdrawn, and closeEffectiveAtLedger is set to ` +
325
+ `${after.closeEffectiveAtLedger}. Channel balance went from ` +
326
+ `${before.balance} to ${after.balance}; the remainder was auto-refunded ` +
327
+ `to the funder, which is the contract's designed close behaviour. ` +
328
+ `Channel ${channel} is now permanently closed.`,
329
+ },
330
+ ];
331
+ }
332
+ catch (error) {
333
+ return [errored(id, name, error)];
334
+ }
335
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Orchestration for MPP charge mode.
3
+ *
4
+ * Thin, but it exists for the same reason `suite.ts` does: the CLI and the MCP
5
+ * server must classify failures identically. `runMppChargeChecks` throws so it
6
+ * can distinguish an unreachable target from a non-conformant one; this maps
7
+ * those throws onto the catalogue's reporting semantics exactly once.
8
+ */
9
+ import { type CheckResult } from "../check.js";
10
+ import { type MppChargeCheckOptions } from "./charge.js";
11
+ export type MppChargeSuiteOptions = MppChargeCheckOptions;
12
+ export declare function runMppChargeSuite(options: MppChargeSuiteOptions): Promise<CheckResult[]>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Orchestration for MPP charge mode.
3
+ *
4
+ * Thin, but it exists for the same reason `suite.ts` does: the CLI and the MCP
5
+ * server must classify failures identically. `runMppChargeChecks` throws so it
6
+ * can distinguish an unreachable target from a non-conformant one; this maps
7
+ * those throws onto the catalogue's reporting semantics exactly once.
8
+ */
9
+ import { errored } from "../check.js";
10
+ import { runMppChargeChecks } from "./charge.js";
11
+ export async function runMppChargeSuite(options) {
12
+ try {
13
+ return await runMppChargeChecks(options);
14
+ }
15
+ catch (error) {
16
+ return [errored("MPP-01", "Charge Settlement On-Chain", error)];
17
+ }
18
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * MPP-01: Charge-mode settlement, verified on-chain.
3
+ *
4
+ * The target's own 402 challenge is the source of truth for what should be
5
+ * paid. Verifying against it rather than against this run's configuration is
6
+ * what makes the check meaningful against a third-party service: it asks
7
+ * whether the service settled what it advertised, not what we assumed.
8
+ *
9
+ * Settlement is verified from the CAP-46 `transfer` contract event rather than
10
+ * the transaction envelope, because those can disagree. The envelope records
11
+ * what was requested; the event records what the token contract actually did.
12
+ * A `currency` contract whose `transfer` moves a different amount than its
13
+ * arguments claim is caught here and nowhere else — the same threat model
14
+ * @stellar/mpp's own client guards against when it refuses to sign a
15
+ * non-transfer authorization.
16
+ */
17
+ import { type CheckResult } from "../check.js";
18
+ export interface MppChargeCheckOptions {
19
+ readonly target: string;
20
+ readonly network: string;
21
+ readonly payerSecretKey: string;
22
+ readonly rpcUrl?: string;
23
+ }
24
+ /**
25
+ * MPP-01: the charge must settle on-chain for exactly the advertised amount.
26
+ *
27
+ * Runs a real payment against the target every time it is called. See
28
+ * docs/CHECKS.md — this check spends funds by design.
29
+ *
30
+ * @throws {ConfigurationError} Invalid target URL, network, or missing key.
31
+ * @throws {TargetUnreachableError} The target never answered.
32
+ * @throws {MalformedResponseError} The target answered, non-conformantly.
33
+ * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
34
+ */
35
+ export declare function runMppChargeChecks(options: MppChargeCheckOptions): Promise<CheckResult[]>;