@wasit-dev/core 0.7.0 → 0.8.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +353 -0
  4. package/dist/catalogue.js +10 -0
  5. package/dist/check.d.ts +57 -2
  6. package/dist/check.js +46 -6
  7. package/dist/ci-report.d.ts +74 -0
  8. package/dist/ci-report.js +399 -0
  9. package/dist/config-writer.d.ts +96 -0
  10. package/dist/config-writer.js +281 -0
  11. package/dist/config.d.ts +205 -0
  12. package/dist/config.js +1011 -0
  13. package/dist/denied-env.d.ts +33 -0
  14. package/dist/denied-env.js +86 -0
  15. package/dist/errors.d.ts +44 -1
  16. package/dist/errors.js +151 -2
  17. package/dist/guard/budget.d.ts +138 -0
  18. package/dist/guard/budget.js +206 -0
  19. package/dist/guard/ci-event.d.ts +56 -0
  20. package/dist/guard/ci-event.js +129 -0
  21. package/dist/guard/ci-mainnet.d.ts +59 -0
  22. package/dist/guard/ci-mainnet.js +149 -0
  23. package/dist/guard/horizon.d.ts +30 -0
  24. package/dist/guard/horizon.js +107 -0
  25. package/dist/guard/mainnet-payer.d.ts +66 -0
  26. package/dist/guard/mainnet-payer.js +92 -0
  27. package/dist/guard/mainnet-plan.d.ts +133 -0
  28. package/dist/guard/mainnet-plan.js +208 -0
  29. package/dist/guard/mainnet-run.d.ts +87 -0
  30. package/dist/guard/mainnet-run.js +225 -0
  31. package/dist/guard/networks.d.ts +51 -0
  32. package/dist/guard/networks.js +91 -0
  33. package/dist/guard/optin.d.ts +106 -0
  34. package/dist/guard/optin.js +202 -0
  35. package/dist/guard/rpc-identity.d.ts +45 -0
  36. package/dist/guard/rpc-identity.js +156 -0
  37. package/dist/guard/rpc-in-use.d.ts +48 -0
  38. package/dist/guard/rpc-in-use.js +84 -0
  39. package/dist/guard/run-ledger.d.ts +212 -0
  40. package/dist/guard/run-ledger.js +426 -0
  41. package/dist/guard/run-lock.d.ts +62 -0
  42. package/dist/guard/run-lock.js +172 -0
  43. package/dist/guard/signed-terms.d.ts +96 -0
  44. package/dist/guard/signed-terms.js +207 -0
  45. package/dist/index.d.ts +44 -4
  46. package/dist/index.js +42 -2
  47. package/dist/mpp/channel-commitment.d.ts +48 -2
  48. package/dist/mpp/channel-commitment.js +80 -4
  49. package/dist/mpp/channel-credential.d.ts +13 -1
  50. package/dist/mpp/channel-credential.js +21 -2
  51. package/dist/mpp/channel.d.ts +6 -0
  52. package/dist/mpp/channel.js +36 -3
  53. package/dist/mpp/charge.d.ts +33 -1
  54. package/dist/mpp/charge.js +90 -20
  55. package/dist/mpp/network.js +4 -1
  56. package/dist/mpp/plan.d.ts +77 -0
  57. package/dist/mpp/plan.js +188 -0
  58. package/dist/mpp/suite.d.ts +6 -0
  59. package/dist/mpp/suite.js +12 -3
  60. package/dist/report.d.ts +163 -0
  61. package/dist/report.js +282 -0
  62. package/dist/route-reader.d.ts +124 -0
  63. package/dist/route-reader.js +349 -0
  64. package/dist/sanitize.d.ts +52 -0
  65. package/dist/sanitize.js +106 -0
  66. package/dist/settlement.d.ts +14 -0
  67. package/dist/settlement.js +1 -1
  68. package/dist/verdict.d.ts +24 -0
  69. package/dist/verdict.js +46 -0
  70. package/dist/versions.d.ts +50 -0
  71. package/dist/versions.js +123 -0
  72. package/dist/wallet.d.ts +58 -1
  73. package/dist/wallet.js +128 -0
  74. package/dist/x402/chains/evm.js +3 -0
  75. package/dist/x402/chains/index.d.ts +8 -0
  76. package/dist/x402/chains/index.js +13 -2
  77. package/dist/x402/chains/stellar.d.ts +8 -1
  78. package/dist/x402/chains/stellar.js +259 -4
  79. package/dist/x402/chains/types.d.ts +104 -2
  80. package/dist/x402/plan.d.ts +184 -0
  81. package/dist/x402/plan.js +520 -0
  82. package/dist/x402/rejected-request.d.ts +156 -0
  83. package/dist/x402/rejected-request.js +287 -0
  84. package/dist/x402/requirements.d.ts +1 -0
  85. package/dist/x402/requirements.js +37 -4
  86. package/dist/x402/simulator.d.ts +86 -1
  87. package/dist/x402/simulator.js +863 -87
  88. package/package.json +1 -1
@@ -9,13 +9,53 @@
9
9
  * Mirrors `verifyCommitmentSignature` in @stellar/mpp channel/server: simulate
10
10
  * `prepare_commitment(amount)` read-only, take the returned Bytes, and sign them
11
11
  * with the raw ed25519 commitment key. No transaction is submitted, no fee paid.
12
+ *
13
+ * The bytes come from an RPC the caller chooses, and the contract writes the
14
+ * network it runs on into them. So before signing, the bytes are decoded and
15
+ * must name this channel, this amount and the run's network
16
+ * ({@link assertCommitmentBinds}), as the SDK's own client does: the network the
17
+ * guard allowed is then also the network the signature is valid on.
12
18
  */
13
19
  import { Keypair } from "@stellar/stellar-sdk";
20
+ import { ConfigurationError } from "../errors.js";
14
21
  export declare const COMMITMENT_SEED_BYTES = 32;
15
22
  export declare class CommitmentSimulationError extends Error {
16
23
  readonly cause?: unknown;
17
24
  constructor(message: string, cause?: unknown);
18
25
  }
26
+ /**
27
+ * The commitment the RPC returned is not one for this run's channel, amount and
28
+ * network. A `ConfigurationError`: it says nothing about the target's
29
+ * conformance, only that the RPC or the channel the run was given does not
30
+ * belong to the run's network, or answered with something that is not a
31
+ * commitment. Nothing is signed when it is thrown.
32
+ */
33
+ export declare class CommitmentBindingError extends ConfigurationError {
34
+ constructor(reason: string);
35
+ }
36
+ /** The domain separator in every one-way-channel commitment (`symbol_short!("chancmmt")` in the contract). */
37
+ export declare const COMMITMENT_DOMAIN = "chancmmt";
38
+ export interface CommitmentExpectation {
39
+ /** The channel contract (C...) this run pays through. */
40
+ readonly channelContract: string;
41
+ /** The cumulative amount this run means to sign, in base units. */
42
+ readonly amount: bigint;
43
+ /** The passphrase of the run's network, the one the network guard allowed. */
44
+ readonly networkPassphrase: string;
45
+ }
46
+ /**
47
+ * Throws unless `bytes` decode to a commitment for exactly this channel, amount
48
+ * and network, under the commitment domain.
49
+ *
50
+ * The same rule as `assertCommitmentBinds` in @stellar/mpp 0.7.1
51
+ * (`dist/channel/commitment.js`), which the package does not export: the network
52
+ * field is the SHA-256 of the network's passphrase, written by the contract from
53
+ * the ledger it runs on, so it says which network the signature would be valid
54
+ * on whatever the run was told.
55
+ *
56
+ * @throws {CommitmentBindingError} On any mismatch, or bytes that are not a commitment.
57
+ */
58
+ export declare function assertCommitmentBinds(bytes: Uint8Array, expected: CommitmentExpectation): void;
19
59
  export interface PrepareCommitmentParams {
20
60
  /** Channel contract address (C...). */
21
61
  readonly channelContract: string;
@@ -62,10 +102,16 @@ export declare function readChannelWithdrawn(parameters: {
62
102
  * Simulates `prepare_commitment(amount)` and returns the bytes to be signed.
63
103
  */
64
104
  export declare function prepareCommitmentBytes(params: PrepareCommitmentParams): Promise<Buffer>;
105
+ /** What `signChannelCommitment` can be given instead of its own steps, for tests. */
106
+ export interface SignChannelCommitmentDeps {
107
+ /** In place of the simulation of `prepare_commitment` on the RPC. */
108
+ readonly prepare?: (params: PrepareCommitmentParams) => Promise<Buffer>;
109
+ }
65
110
  /**
66
- * Signs a channel commitment for an explicit cumulative amount.
111
+ * Signs a channel commitment for an explicit cumulative amount, after
112
+ * {@link assertCommitmentBinds} has checked what it is about to sign.
67
113
  *
68
114
  * @returns The raw 64-byte ed25519 signature, hex-encoded, ready to be placed
69
115
  * in the credential payload's `signature` field.
70
116
  */
71
- export declare function signChannelCommitment(params: SignChannelCommitmentParams): Promise<string>;
117
+ export declare function signChannelCommitment(params: SignChannelCommitmentParams, deps?: SignChannelCommitmentDeps): Promise<string>;
@@ -9,8 +9,15 @@
9
9
  * Mirrors `verifyCommitmentSignature` in @stellar/mpp channel/server: simulate
10
10
  * `prepare_commitment(amount)` read-only, take the returned Bytes, and sign them
11
11
  * with the raw ed25519 commitment key. No transaction is submitted, no fee paid.
12
+ *
13
+ * The bytes come from an RPC the caller chooses, and the contract writes the
14
+ * network it runs on into them. So before signing, the bytes are decoded and
15
+ * must name this channel, this amount and the run's network
16
+ * ({@link assertCommitmentBinds}), as the SDK's own client does: the network the
17
+ * guard allowed is then also the network the signature is valid on.
12
18
  */
13
- import { Account, Contract, Keypair, TransactionBuilder, nativeToScVal, rpc, scValToNative, } from "@stellar/stellar-sdk";
19
+ import { Account, Contract, Keypair, TransactionBuilder, hash, nativeToScVal, rpc, scValToNative, xdr, } from "@stellar/stellar-sdk";
20
+ import { ConfigurationError } from "../errors.js";
14
21
  /**
15
22
  * Format-valid all-zero account used purely as a simulation source. It need not
16
23
  * exist on the ledger: read-only simulation never touches the source account.
@@ -32,6 +39,67 @@ export class CommitmentSimulationError extends Error {
32
39
  this.name = "CommitmentSimulationError";
33
40
  }
34
41
  }
42
+ /**
43
+ * The commitment the RPC returned is not one for this run's channel, amount and
44
+ * network. A `ConfigurationError`: it says nothing about the target's
45
+ * conformance, only that the RPC or the channel the run was given does not
46
+ * belong to the run's network, or answered with something that is not a
47
+ * commitment. Nothing is signed when it is thrown.
48
+ */
49
+ export class CommitmentBindingError extends ConfigurationError {
50
+ constructor(reason) {
51
+ super(`Refusing to sign the channel commitment: ${reason} Nothing was signed.`);
52
+ this.name = "CommitmentBindingError";
53
+ }
54
+ }
55
+ /** The domain separator in every one-way-channel commitment (`symbol_short!("chancmmt")` in the contract). */
56
+ export const COMMITMENT_DOMAIN = "chancmmt";
57
+ /**
58
+ * Throws unless `bytes` decode to a commitment for exactly this channel, amount
59
+ * and network, under the commitment domain.
60
+ *
61
+ * The same rule as `assertCommitmentBinds` in @stellar/mpp 0.7.1
62
+ * (`dist/channel/commitment.js`), which the package does not export: the network
63
+ * field is the SHA-256 of the network's passphrase, written by the contract from
64
+ * the ledger it runs on, so it says which network the signature would be valid
65
+ * on whatever the run was told.
66
+ *
67
+ * @throws {CommitmentBindingError} On any mismatch, or bytes that are not a commitment.
68
+ */
69
+ export function assertCommitmentBinds(bytes, expected) {
70
+ let decoded;
71
+ try {
72
+ decoded = scValToNative(xdr.ScVal.fromXDR(Buffer.from(bytes)));
73
+ }
74
+ catch {
75
+ throw new CommitmentBindingError("prepare_commitment did not return a decodable commitment.");
76
+ }
77
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded) || decoded instanceof Uint8Array) {
78
+ throw new CommitmentBindingError("prepare_commitment did not return a commitment struct.");
79
+ }
80
+ const { domain, network, channel, amount } = decoded;
81
+ if (domain !== COMMITMENT_DOMAIN) {
82
+ throw new CommitmentBindingError("the commitment does not carry the commitment domain.");
83
+ }
84
+ if (channel !== expected.channelContract) {
85
+ throw new CommitmentBindingError("the commitment is for another channel than the one this run pays through.");
86
+ }
87
+ let committed;
88
+ try {
89
+ committed = BigInt(amount);
90
+ }
91
+ catch {
92
+ throw new CommitmentBindingError("the commitment amount is not an integer.");
93
+ }
94
+ if (committed !== expected.amount) {
95
+ throw new CommitmentBindingError(`the commitment is for ${committed} base units, not the ${expected.amount} this run means to sign.`);
96
+ }
97
+ const runNetwork = hash(Buffer.from(expected.networkPassphrase));
98
+ if (!(network instanceof Uint8Array) || !Buffer.from(network).equals(runNetwork)) {
99
+ throw new CommitmentBindingError("the commitment is for another network than the run's. The RPC or the channel belongs to another network " +
100
+ "(a mainnet RPC on a test-network run, for example); point the run at an RPC of its own network.");
101
+ }
102
+ }
35
103
  /**
36
104
  * Builds a Keypair from the raw ed25519 seed used for channel commitments.
37
105
  * This is deliberately not a Stellar secret key: the contract verifies the
@@ -180,15 +248,23 @@ export async function prepareCommitmentBytes(params) {
180
248
  return Buffer.from(returnValue.bytes());
181
249
  }
182
250
  /**
183
- * Signs a channel commitment for an explicit cumulative amount.
251
+ * Signs a channel commitment for an explicit cumulative amount, after
252
+ * {@link assertCommitmentBinds} has checked what it is about to sign.
184
253
  *
185
254
  * @returns The raw 64-byte ed25519 signature, hex-encoded, ready to be placed
186
255
  * in the credential payload's `signature` field.
187
256
  */
188
- export async function signChannelCommitment(params) {
257
+ export async function signChannelCommitment(params, deps = {}) {
189
258
  const { commitmentSecretHex, ...prepareParams } = params;
190
259
  const keypair = commitmentKeypairFromHex(commitmentSecretHex);
191
- const commitmentBytes = await prepareCommitmentBytes(prepareParams);
260
+ const commitmentBytes = await (deps.prepare ?? prepareCommitmentBytes)(prepareParams);
261
+ // Before the key touches the bytes: they must commit to this channel, this
262
+ // amount and the run's network, whatever the RPC that produced them.
263
+ assertCommitmentBinds(commitmentBytes, {
264
+ channelContract: prepareParams.channelContract,
265
+ amount: prepareParams.amount,
266
+ networkPassphrase: prepareParams.networkPassphrase,
267
+ });
192
268
  const signature = keypair.sign(commitmentBytes);
193
269
  if (signature.length !== ED25519_SIGNATURE_BYTES) {
194
270
  throw new CommitmentSimulationError(`Expected a ${ED25519_SIGNATURE_BYTES}-byte signature, got ${signature.length}.`);
@@ -9,7 +9,7 @@
9
9
  * amounts, so they assemble credentials directly.
10
10
  */
11
11
  import { Challenge } from "mppx";
12
- import { MalformedResponseError } from "../errors.js";
12
+ import { CheckSetupError, MalformedResponseError } from "../errors.js";
13
13
  export type ChannelAction = "voucher" | "close";
14
14
  export declare class ChannelChallengeError extends MalformedResponseError {
15
15
  constructor(message: string);
@@ -70,6 +70,18 @@ export interface BuildChannelCredentialParams {
70
70
  readonly network: string;
71
71
  readonly rpcUrl?: string;
72
72
  readonly action?: ChannelAction;
73
+ /**
74
+ * The only channel a commitment may be signed for (`wasit run`: the config's
75
+ * `channel`). A challenge that names another channel gets no signature.
76
+ */
77
+ readonly onlyChannel?: string;
78
+ }
79
+ /**
80
+ * A challenge names another channel than the one the run signs for. A setup
81
+ * error: the check that hit it has no verdict, and nothing was signed.
82
+ */
83
+ export declare class OtherChannelRefusedError extends CheckSetupError {
84
+ constructor(named: string, onlyChannel: string);
73
85
  }
74
86
  /** Signs `amount` for this challenge's channel and serialises the credential. */
75
87
  export declare function buildChannelCredential(parameters: BuildChannelCredentialParams): Promise<{
@@ -9,9 +9,11 @@
9
9
  * amounts, so they assemble credentials directly.
10
10
  */
11
11
  import { Challenge, Credential } from "mppx";
12
- import { MalformedResponseError, fetchTarget } from "../errors.js";
12
+ import { CheckSetupError, MalformedResponseError, fetchTarget } from "../errors.js";
13
+ import { shown } from "../guard/budget.js";
13
14
  import { signChannelCommitment } from "./channel-commitment.js";
14
15
  import { networkPassphrase, resolveRpcUrl } from "./network.js";
16
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
15
17
  export class ChannelChallengeError extends MalformedResponseError {
16
18
  constructor(message) {
17
19
  super(message);
@@ -103,9 +105,26 @@ export function serializeChannelCredential(parameters) {
103
105
  payload: { action, amount: amount.toString(), signature },
104
106
  }));
105
107
  }
108
+ /**
109
+ * A challenge names another channel than the one the run signs for. A setup
110
+ * error: the check that hit it has no verdict, and nothing was signed.
111
+ */
112
+ export class OtherChannelRefusedError extends CheckSetupError {
113
+ constructor(named, onlyChannel) {
114
+ super(`The route's challenge names the channel ${shown(named)}, and this run signs commitments for its ` +
115
+ `configured channel ${onlyChannel} only. Nothing was signed.`);
116
+ this.name = "OtherChannelRefusedError";
117
+ }
118
+ }
106
119
  /** Signs `amount` for this challenge's channel and serialises the credential. */
107
120
  export async function buildChannelCredential(parameters) {
108
- const { challenge, amount, commitmentSecretHex, network, rpcUrl, action } = parameters;
121
+ const { challenge, amount, commitmentSecretHex, network, rpcUrl, action, onlyChannel } = parameters;
122
+ // L0 at the signature itself, whoever calls it.
123
+ assertPaymentNetworkAllowed("mpp-channel", network);
124
+ // The channel, at the signature too: the service may name another one in any fresh challenge.
125
+ if (onlyChannel !== undefined && challenge.channelContract !== onlyChannel) {
126
+ throw new OtherChannelRefusedError(challenge.channelContract, onlyChannel);
127
+ }
109
128
  const signature = await signChannelCommitment({
110
129
  channelContract: challenge.channelContract,
111
130
  amount,
@@ -26,6 +26,12 @@ export interface MppChannelCheckOptions {
26
26
  network: string;
27
27
  /** Overrides the default RPC endpoint for the network. */
28
28
  rpcUrl?: string;
29
+ /**
30
+ * The only channel a commitment is signed for (`wasit run`: the config's
31
+ * `channel`). A fresh challenge that names another gets no signature, and the
32
+ * check has no verdict.
33
+ */
34
+ onlyChannel?: string;
29
35
  }
30
36
  /**
31
37
  * Explains a replay that did not get HTTP 402.
@@ -4,6 +4,7 @@ import { CheckSetupError } from "../errors.js";
4
4
  import { readChannelWithdrawn } from "./channel-commitment.js";
5
5
  import { buildChannelCredential, fetchChannelChallenge, serializeChannelCredential, submitCredential, } from "./channel-credential.js";
6
6
  import { assertMppNetwork, networkPassphrase, resolveRpcUrl } from "./network.js";
7
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
7
8
  /**
8
9
  * MPP-10: The channel contract deploys correctly — its address is valid
9
10
  * and its on-chain state is queryable, and matches the parameters it was
@@ -46,6 +47,20 @@ export async function runMppChannelDeployChecks(options) {
46
47
  },
47
48
  ];
48
49
  }
50
+ /**
51
+ * L0 for a channel check called on its own: these checks sign commitments, and
52
+ * MPP-13 closes the channel on-chain, so they run on test networks only. The
53
+ * suite runs the same guard once at preflight.
54
+ */
55
+ function refusedNetwork(id, name, network) {
56
+ try {
57
+ assertPaymentNetworkAllowed("mpp-channel", network);
58
+ return undefined;
59
+ }
60
+ catch (error) {
61
+ return [errored(id, name, error)];
62
+ }
63
+ }
49
64
  function failure(id, name, detail) {
50
65
  return [{ id, name, pass: false, detail }];
51
66
  }
@@ -85,7 +100,7 @@ const SETUP_ATTEMPTS = 3;
85
100
  * @throws {CheckSetupError} No attempt was accepted, so the check has no verdict.
86
101
  */
87
102
  async function advanceCumulative(options) {
88
- const { target, commitmentSecretHex, network, rpcUrl } = options;
103
+ const { target, commitmentSecretHex, network, rpcUrl, onlyChannel } = options;
89
104
  const refusals = [];
90
105
  for (let attempt = 1; attempt <= SETUP_ATTEMPTS; attempt += 1) {
91
106
  const challenge = await fetchChannelChallenge(target);
@@ -96,6 +111,7 @@ async function advanceCumulative(options) {
96
111
  commitmentSecretHex,
97
112
  network,
98
113
  rpcUrl,
114
+ ...(onlyChannel === undefined ? {} : { onlyChannel }),
99
115
  });
100
116
  const submission = await submitCredential(target, credential);
101
117
  if (submission.status === 200)
@@ -127,7 +143,10 @@ async function advanceCumulative(options) {
127
143
  export async function runMppChannelOrderingCheck(options) {
128
144
  const id = "MPP-11";
129
145
  const name = "Cumulative Commitment Ordering";
130
- const { target, commitmentSecretHex, network, rpcUrl } = options;
146
+ const { target, commitmentSecretHex, network, rpcUrl, onlyChannel } = options;
147
+ const refused = refusedNetwork(id, name, network);
148
+ if (refused)
149
+ return refused;
131
150
  try {
132
151
  const { amount: baseline } = await advanceCumulative(options);
133
152
  // (a) Exactly equal to the cumulative the server now holds.
@@ -138,6 +157,7 @@ export async function runMppChannelOrderingCheck(options) {
138
157
  commitmentSecretHex,
139
158
  network,
140
159
  rpcUrl,
160
+ ...(onlyChannel === undefined ? {} : { onlyChannel }),
141
161
  })).credential);
142
162
  if (equal.status !== 402) {
143
163
  return failure(id, name, `A commitment equal to the current cumulative (${baseline}) was not rejected — ` +
@@ -165,6 +185,7 @@ export async function runMppChannelOrderingCheck(options) {
165
185
  commitmentSecretHex,
166
186
  network,
167
187
  rpcUrl,
188
+ ...(onlyChannel === undefined ? {} : { onlyChannel }),
168
189
  })).credential);
169
190
  if (short.status !== 402) {
170
191
  return failure(id, name, `A commitment that advances but under-covers the request price ` +
@@ -198,6 +219,9 @@ export async function runMppChannelReplayCheck(options) {
198
219
  const id = "MPP-12";
199
220
  const name = "Challenge Replay Rejection";
200
221
  const { target } = options;
222
+ const refused = refusedNetwork(id, name, options.network);
223
+ if (refused)
224
+ return refused;
201
225
  try {
202
226
  const { credential } = await advanceCumulative(options);
203
227
  const replay = await submitCredential(target, credential);
@@ -232,6 +256,9 @@ export async function runMppChannelCommitmentReplayCheck(options) {
232
256
  const id = "MPP-14";
233
257
  const name = "Commitment Replay Rejection";
234
258
  const { target } = options;
259
+ const refused = refusedNetwork(id, name, options.network);
260
+ if (refused)
261
+ return refused;
235
262
  try {
236
263
  const { amount, signature } = await advanceCumulative(options);
237
264
  // Fresh challenge, same commitment. The signature is still cryptographically
@@ -263,7 +290,12 @@ function sleep(ms) {
263
290
  export async function runMppChannelCloseCheck(options) {
264
291
  const id = "MPP-13";
265
292
  const name = "Close Settlement";
266
- const { target, commitmentSecretHex, network, rpcUrl, expectedChannel, allowDestructive = false, closePollAttempts = 6, closePollDelayMs = 2_000, } = options;
293
+ const { target, commitmentSecretHex, network, rpcUrl, onlyChannel, expectedChannel, allowDestructive = false, closePollAttempts = 6, closePollDelayMs = 2_000, } = options;
294
+ // Before the destructive switch is even looked at: a close on a network
295
+ // that is not a test network is refused, enabled or not.
296
+ const refused = refusedNetwork(id, name, network);
297
+ if (refused)
298
+ return refused;
267
299
  if (!allowDestructive) {
268
300
  return [
269
301
  skippedDestructive(id, name, "closing settles the channel on-chain and permanently ends it. " +
@@ -305,6 +337,7 @@ export async function runMppChannelCloseCheck(options) {
305
337
  network,
306
338
  rpcUrl,
307
339
  action: "close",
340
+ ...(onlyChannel === undefined ? {} : { onlyChannel }),
308
341
  });
309
342
  const closed = await submitCredential(target, credential);
310
343
  if (closed.status !== 200) {
@@ -21,11 +21,32 @@ import { charge } from "@stellar/mpp/charge/client";
21
21
  import { Challenge } from "mppx";
22
22
  import { type CheckResult } from "../check.js";
23
23
  import { type MppNetwork } from "./network.js";
24
+ import { type RunBudget } from "../guard/budget.js";
25
+ /** What the plan of a run (L1) allowed MPP-01 to pay, read from the unpaid challenge before anything was signed. */
26
+ export interface PlannedCharge {
27
+ /** Base units of `currency`. */
28
+ readonly amount: bigint;
29
+ readonly currency: string;
30
+ readonly recipient: string;
31
+ }
32
+ /**
33
+ * The caps of a run, on MPP-01 (D-036, `wasit run`): the payment must be the
34
+ * one the plan read, and it is charged to the run's budget before the SDK
35
+ * signs it. Without `planned` the endpoint was not planned and MPP-01 pays
36
+ * nothing; `notPlanned` says why.
37
+ */
38
+ export interface MppChargeGuard {
39
+ readonly budget: RunBudget;
40
+ readonly planned?: PlannedCharge;
41
+ readonly notPlanned?: string;
42
+ }
24
43
  export interface MppChargeCheckOptions {
25
44
  readonly target: string;
26
45
  readonly network: string;
27
46
  readonly payerSecretKey: string;
28
47
  readonly rpcUrl?: string;
48
+ /** `wasit run` only: the plan's entry and the run's budget. The old command runs without it. */
49
+ readonly guard?: MppChargeGuard;
29
50
  }
30
51
  /** What the target advertised it wants paid, read from its own 402 challenge. */
31
52
  export interface ChargeChallenge {
@@ -37,6 +58,15 @@ export interface ChargeChallenge {
37
58
  }
38
59
  /** The SDK's charge client, as `charge()` from @stellar/mpp builds it. */
39
60
  type ChargeClient = ReturnType<typeof charge>;
61
+ /**
62
+ * Reads the charge challenge without paying.
63
+ *
64
+ * Done as a separate unpaid request so the advertised terms are captured
65
+ * before any money moves. `amount` is in base units: the server converts via
66
+ * `toBaseUnits()` before building the challenge, so it is directly comparable
67
+ * to the `i128` in the transfer event without any decimal handling.
68
+ */
69
+ export declare function readChargeChallenge(target: string): Promise<ChargeChallenge>;
40
70
  /**
41
71
  * Reads the advertised charge terms out of an already-decoded challenge.
42
72
  *
@@ -56,7 +86,7 @@ export declare function parseChargeChallenge(challenge: Challenge.Challenge): Ch
56
86
  * 0.8.14). MPP-01 judges one payment: a target that answers 402 after being
57
87
  * paid has that 402 reported, rather than being paid twice more.
58
88
  */
59
- export declare function payCharge(target: string, network: MppNetwork, method: ChargeClient): Promise<Response>;
89
+ export declare function payCharge(target: string, network: MppNetwork, method: ChargeClient, guard?: MppChargeGuard): Promise<Response>;
60
90
  /**
61
91
  * MPP-01: the charge must settle on-chain for exactly the advertised amount.
62
92
  *
@@ -65,6 +95,8 @@ export declare function payCharge(target: string, network: MppNetwork, method: C
65
95
  *
66
96
  * @throws {ConfigurationError} Invalid target URL, network, or missing key, or
67
97
  * a challenge for another network than the run's (nothing is signed).
98
+ * @throws {PaymentNetworkRefusedError} The run's network is not a test network
99
+ * (nothing is sent).
68
100
  * @throws {TargetUnreachableError} The target never answered.
69
101
  * @throws {MalformedResponseError} The target answered, non-conformantly.
70
102
  * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
@@ -20,11 +20,16 @@
20
20
  import { Mppx, charge } from "@stellar/mpp/charge/client";
21
21
  import { Challenge, Receipt } from "mppx";
22
22
  import { Keypair } from "@stellar/stellar-sdk";
23
- import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
23
+ import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, fetchWithoutRedirects, } from "../errors.js";
24
24
  import { assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js";
25
+ import { PaymentGuardRefusedError, shown } from "../guard/budget.js";
26
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
27
+ import { assertRpcServesNetwork } from "../guard/rpc-identity.js";
25
28
  import { verifySettlement } from "../settlement.js";
26
29
  const CHECK_ID = "MPP-01";
27
30
  const CHECK_NAME = "Charge Settlement On-Chain";
31
+ /** An amount as a charge challenge must give it: base units, digits only, at most 78 (a uint256). */
32
+ const WHOLE_BASE_UNITS = /^\d{1,78}$/;
28
33
  function asRecord(value) {
29
34
  return typeof value === "object" && value !== null
30
35
  ? value
@@ -42,7 +47,7 @@ function readString(source, key) {
42
47
  * `toBaseUnits()` before building the challenge, so it is directly comparable
43
48
  * to the `i128` in the transfer event without any decimal handling.
44
49
  */
45
- async function fetchChargeChallenge(target) {
50
+ export async function readChargeChallenge(target) {
46
51
  const response = await fetchTarget(target);
47
52
  if (response.status !== 402) {
48
53
  throw new MalformedResponseError(`Expected HTTP 402 with a payment challenge, got ${response.status}.`);
@@ -82,14 +87,14 @@ export function parseChargeChallenge(challenge) {
82
87
  if (missing.length > 0 || !amountRaw || !currency || !recipient) {
83
88
  throw new MalformedResponseError(`Charge challenge is missing ${missing.join(", ")}.`);
84
89
  }
85
- let amount;
86
- try {
87
- amount = BigInt(amountRaw);
88
- }
89
- catch {
90
- throw new MalformedResponseError(`Challenge advertises a non-numeric amount ("${amountRaw}"). The spec ` +
90
+ // Digits only, the rule the run's guard holds a signed amount to (`parseAmount`
91
+ // in guard/budget.ts). `BigInt` alone also takes "-5", "0x10" and " 10 ": a
92
+ // negative price would lower the worst case a run's plan adds up.
93
+ if (!WHOLE_BASE_UNITS.test(amountRaw)) {
94
+ throw new MalformedResponseError(`Challenge advertises an amount that is not a whole number of base units (${shown(amountRaw)}). The spec ` +
91
95
  `requires base units, e.g. "10000" for 0.001 of a 7-decimal token.`);
92
96
  }
97
+ const amount = BigInt(amountRaw);
93
98
  return { amount, currency, recipient, network: chargeNetwork(request) };
94
99
  }
95
100
  /**
@@ -117,7 +122,34 @@ function assertRunNetwork(asked, network) {
117
122
  }
118
123
  }
119
124
  /**
120
- * `method`, refusing to sign a challenge for any network but `network`.
125
+ * Refuses a charge that is not the one the plan read: another amount, currency
126
+ * or recipient. The service may change its challenge between the plan and the
127
+ * payment; L2 then refuses, rather than signing what the plan never saw.
128
+ */
129
+ function assertPlanned(asked, planned) {
130
+ const differs = [];
131
+ if (typeof asked.amount !== "string" || !WHOLE_BASE_UNITS.test(asked.amount) || BigInt(asked.amount) !== planned.amount) {
132
+ differs.push(`amount ${shown(asked.amount)} (planned ${planned.amount})`);
133
+ }
134
+ if (asked.currency !== planned.currency)
135
+ differs.push(`currency ${shown(asked.currency)} (planned ${planned.currency})`);
136
+ if (asked.recipient !== planned.recipient)
137
+ differs.push(`recipient ${shown(asked.recipient)} (planned ${planned.recipient})`);
138
+ if (differs.length > 0) {
139
+ throw new PaymentGuardRefusedError("plan", `MPP-01 would pay a charge the plan did not read before the run started: ${differs.join(", ")}. ` +
140
+ `The service changed its challenge after the plan.`);
141
+ }
142
+ }
143
+ /** Why a guarded MPP-01 pays nothing: the plan of the run did not plan a payment for the endpoint. */
144
+ function notPlannedRefusal(guard) {
145
+ const says = guard.notPlanned?.replace(/\s*Nothing was signed\.?\s*$/, "").trim();
146
+ return new PaymentGuardRefusedError("plan", `The plan of this run did not plan a payment for this endpoint, so MPP-01 does not pay it.` +
147
+ (says === undefined || says === "" ? "" : ` The plan says: ${says.replace(/\.?$/, ".")}`));
148
+ }
149
+ /**
150
+ * `method`, refusing to sign a challenge for any network but `network` and,
151
+ * with a guard, any charge but the planned one, and charging the run's budget
152
+ * before the SDK signs.
121
153
  *
122
154
  * Checking the unpaid challenge is not enough on its own: mppx requests the
123
155
  * target again and pays the challenge in that answer, which the target is
@@ -125,11 +157,25 @@ function assertRunNetwork(asked, network) {
125
157
  * be signed. Without it a target asking for `stellar:pubnet` gets a mainnet
126
158
  * transfer signed, sent through the SDK's own default pubnet RPC endpoint.
127
159
  */
128
- function onNetwork(method, network) {
160
+ function onNetwork(method, network, guard) {
129
161
  return {
130
162
  ...method,
131
163
  createCredential: async (parameters) => {
132
- assertRunNetwork(chargeNetwork(asRecord(parameters.challenge.request) ?? {}), network);
164
+ const request = asRecord(parameters.challenge.request) ?? {};
165
+ assertRunNetwork(chargeNetwork(request), network);
166
+ if (guard !== undefined) {
167
+ if (guard.planned === undefined)
168
+ throw notPlannedRefusal(guard);
169
+ assertPlanned({ amount: request["amount"], currency: request["currency"], recipient: request["recipient"] }, guard.planned);
170
+ // Charged before the signature and never credited back: a payment that fails after it was signed may still settle.
171
+ guard.budget.charge({
172
+ check: CHECK_ID,
173
+ network,
174
+ asset: guard.planned.currency,
175
+ amount: String(guard.planned.amount),
176
+ planned: guard.planned.amount,
177
+ });
178
+ }
133
179
  return method.createCredential(parameters);
134
180
  },
135
181
  };
@@ -143,19 +189,26 @@ function onNetwork(method, network) {
143
189
  * 0.8.14). MPP-01 judges one payment: a target that answers 402 after being
144
190
  * paid has that 402 reported, rather than being paid twice more.
145
191
  */
146
- export async function payCharge(target, network, method) {
192
+ export async function payCharge(target, network, method, guard) {
193
+ // L0 again at the signing call itself: it is exported, so a caller can
194
+ // reach it without going through runMppChargeChecks.
195
+ assertPaymentNetworkAllowed("mpp-charge", network);
147
196
  const mppx = Mppx.create({
148
- methods: [onNetwork(method, network)],
197
+ methods: [onNetwork(method, network, guard)],
149
198
  polyfill: false,
150
199
  maxPaymentRetries: 1,
200
+ // Every request mppx makes here refuses a redirect (D-022c): it pays at the
201
+ // URL it read the challenge from, never at a URL the target sends it on to.
202
+ fetch: fetchWithoutRedirects,
151
203
  });
152
204
  return mppx.fetch(target);
153
205
  }
154
206
  function fail(detail) {
155
207
  return [{ id: CHECK_ID, name: CHECK_NAME, pass: false, detail }];
156
208
  }
157
- function pass(detail) {
158
- return [{ id: CHECK_ID, name: CHECK_NAME, pass: true, detail }];
209
+ function pass(detail, reference) {
210
+ // Read back from the chain and found to be this payment: a report may link it.
211
+ return [{ id: CHECK_ID, name: CHECK_NAME, pass: true, detail, reference }];
159
212
  }
160
213
  /**
161
214
  * MPP-01: the charge must settle on-chain for exactly the advertised amount.
@@ -165,14 +218,19 @@ function pass(detail) {
165
218
  *
166
219
  * @throws {ConfigurationError} Invalid target URL, network, or missing key, or
167
220
  * a challenge for another network than the run's (nothing is signed).
221
+ * @throws {PaymentNetworkRefusedError} The run's network is not a test network
222
+ * (nothing is sent).
168
223
  * @throws {TargetUnreachableError} The target never answered.
169
224
  * @throws {MalformedResponseError} The target answered, non-conformantly.
170
225
  * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
171
226
  */
172
227
  export async function runMppChargeChecks(options) {
173
- const { target, network, payerSecretKey, rpcUrl } = options;
228
+ const { target, network, payerSecretKey, rpcUrl, guard } = options;
174
229
  assertHttpUrl(target);
175
230
  const runNetwork = assertMppNetwork(network);
231
+ // L0: before the key is read, any request is sent or the SDK's charge
232
+ // client is built. MPP pays on test networks only.
233
+ assertPaymentNetworkAllowed("mpp-charge", runNetwork);
176
234
  if (!payerSecretKey) {
177
235
  throw new ConfigurationError("No payer secret key. MPP-01 settles a real payment and cannot run without one.");
178
236
  }
@@ -194,17 +252,29 @@ export async function runMppChargeChecks(options) {
194
252
  throw new ConfigurationError(`MPP-01 pays through @stellar/mpp's charge client, which accepts only an ` +
195
253
  `https RPC endpoint, and ${endpoint} is http. Nothing was sent.`);
196
254
  }
197
- const advertised = await fetchChargeChallenge(target);
255
+ // The payment is built and its settlement read through this endpoint: it
256
+ // must serve the run's network before the target is asked anything (D-023).
257
+ await assertRpcServesNetwork(runNetwork, endpoint);
258
+ const advertised = await readChargeChallenge(target);
198
259
  assertRunNetwork(advertised.network, runNetwork);
260
+ if (guard !== undefined) {
261
+ // A guarded run pays only what its plan read. An endpoint it did not plan still has its unpaid challenge read
262
+ // above, so a service that does not answer with one gets its verdict; one that does is not paid.
263
+ if (guard.planned === undefined)
264
+ throw notPlannedRefusal(guard);
265
+ // The challenge the check judges against is the planned one, or nothing is paid.
266
+ assertPlanned({ ...advertised, amount: String(advertised.amount) }, guard.planned);
267
+ }
199
268
  let paid;
200
269
  try {
201
270
  // The payment goes through the run's endpoint too. Left to itself the SDK
202
271
  // picks its own per network, so `--rpc-url` would cover only the
203
272
  // settlement read, and pubnet would get a default endpoint after all.
204
- paid = await payCharge(target, runNetwork, charge({ secretKey: payerSecretKey, rpcUrl: endpoint }));
273
+ paid = await payCharge(target, runNetwork, charge({ secretKey: payerSecretKey, rpcUrl: endpoint }), guard);
205
274
  }
206
275
  catch (error) {
207
- if (error instanceof ConfigurationError)
276
+ // A refusal of the run's own rules (network, plan, budget) is not the target's failure: no verdict.
277
+ if (error instanceof ConfigurationError || error instanceof CheckSetupError)
208
278
  throw error;
209
279
  // The target was reachable moments ago, so this is the payment path
210
280
  // failing, not the network. Report it as a conformance failure.
@@ -232,6 +302,6 @@ export async function runMppChargeChecks(options) {
232
302
  });
233
303
  // Same sentence MPP-01 has always printed, capitalised and closed.
234
304
  return verdict.pass
235
- ? pass(`${verdict.detail.charAt(0).toUpperCase()}${verdict.detail.slice(1)}.`)
305
+ ? pass(`${verdict.detail.charAt(0).toUpperCase()}${verdict.detail.slice(1)}.`, reference)
236
306
  : fail(verdict.detail);
237
307
  }
@@ -9,7 +9,10 @@ import { Networks } from "@stellar/stellar-sdk";
9
9
  import { ConfigurationError } from "../errors.js";
10
10
  export class UnsupportedNetworkError extends ConfigurationError {
11
11
  constructor(network) {
12
- super(`Unsupported network "${network}". Expected "stellar:testnet" or "stellar:pubnet".`);
12
+ super(
13
+ // stellar:pubnet is a known network (a challenge may name it), but the
14
+ // MPP checks never pay on it (L0), so only the test network is offered.
15
+ `Unsupported network "${network}". The MPP checks run on "stellar:testnet" only.`);
13
16
  this.name = "UnsupportedNetworkError";
14
17
  }
15
18
  }