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

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 (61) hide show
  1. package/README.md +1 -1
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +351 -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 +391 -0
  9. package/dist/config.d.ts +205 -0
  10. package/dist/config.js +1011 -0
  11. package/dist/denied-env.d.ts +33 -0
  12. package/dist/denied-env.js +86 -0
  13. package/dist/errors.d.ts +44 -1
  14. package/dist/errors.js +151 -2
  15. package/dist/guard/budget.d.ts +135 -0
  16. package/dist/guard/budget.js +199 -0
  17. package/dist/guard/ci-event.d.ts +50 -0
  18. package/dist/guard/ci-event.js +125 -0
  19. package/dist/guard/mainnet-optin.d.ts +58 -0
  20. package/dist/guard/mainnet-optin.js +95 -0
  21. package/dist/guard/networks.d.ts +50 -0
  22. package/dist/guard/networks.js +80 -0
  23. package/dist/guard/rpc-identity.d.ts +45 -0
  24. package/dist/guard/rpc-identity.js +156 -0
  25. package/dist/guard/rpc-in-use.d.ts +48 -0
  26. package/dist/guard/rpc-in-use.js +84 -0
  27. package/dist/index.d.ts +31 -2
  28. package/dist/index.js +27 -1
  29. package/dist/mpp/channel-commitment.d.ts +48 -2
  30. package/dist/mpp/channel-commitment.js +80 -4
  31. package/dist/mpp/channel-credential.js +3 -0
  32. package/dist/mpp/channel.js +29 -0
  33. package/dist/mpp/charge.d.ts +2 -0
  34. package/dist/mpp/charge.js +17 -1
  35. package/dist/mpp/network.js +4 -1
  36. package/dist/mpp/suite.js +10 -2
  37. package/dist/report.d.ts +163 -0
  38. package/dist/report.js +282 -0
  39. package/dist/sanitize.d.ts +52 -0
  40. package/dist/sanitize.js +106 -0
  41. package/dist/settlement.d.ts +14 -0
  42. package/dist/settlement.js +1 -1
  43. package/dist/verdict.d.ts +24 -0
  44. package/dist/verdict.js +46 -0
  45. package/dist/versions.d.ts +50 -0
  46. package/dist/versions.js +123 -0
  47. package/dist/x402/chains/evm.js +3 -0
  48. package/dist/x402/chains/index.d.ts +8 -0
  49. package/dist/x402/chains/index.js +13 -2
  50. package/dist/x402/chains/stellar.d.ts +8 -1
  51. package/dist/x402/chains/stellar.js +125 -1
  52. package/dist/x402/chains/types.d.ts +68 -0
  53. package/dist/x402/plan.d.ts +82 -0
  54. package/dist/x402/plan.js +146 -0
  55. package/dist/x402/rejected-request.d.ts +146 -0
  56. package/dist/x402/rejected-request.js +269 -0
  57. package/dist/x402/requirements.d.ts +1 -0
  58. package/dist/x402/requirements.js +37 -4
  59. package/dist/x402/simulator.d.ts +52 -1
  60. package/dist/x402/simulator.js +452 -82
  61. package/package.json +1 -1
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The RPC identity check (D-032, D-023a+b): before a run signs anything or
3
+ * reads a settlement, the RPC it was given must say which network it serves,
4
+ * and it must be the run's.
5
+ *
6
+ * L0 judges the network the run is labelled with. The RPC is a separate input
7
+ * (`--rpc-url`, the MCP tool argument `rpcUrl`, the config), and nothing tied
8
+ * the two together: a `stellar:testnet` run pointed at a mainnet RPC signed a
9
+ * mainnet-valid channel commitment in 0.7.0, and every settlement read of such
10
+ * a run comes from another chain. So each entry point that signs or reads a
11
+ * settlement asks the RPC first:
12
+ *
13
+ * - Stellar: `getNetwork`, whose `passphrase` must be the run's network's;
14
+ * - EVM: `eth_chainId`, which must equal the CAIP-2 reference;
15
+ * - Solana: `getGenesisHash`, whose first characters are the CAIP-2 reference.
16
+ *
17
+ * A mismatch, no answer, or an answer that cannot be read refuses the run
18
+ * before any request reaches the target (fail closed). This guards against a
19
+ * mistake or a wrong default, not against an RPC that lies: an RPC that answers
20
+ * the right identity and then serves another chain is outside what any client
21
+ * check can see.
22
+ */
23
+ import { ConfigurationError } from "../errors.js";
24
+ /** The RPC does not serve the run's network, or would not say which one it serves. Nothing was sent or signed. */
25
+ export declare class RpcIdentityError extends ConfigurationError {
26
+ constructor(message: string);
27
+ }
28
+ /** One JSON-RPC call: the `result`, or a throw. */
29
+ export type RpcIdentityTransport = (rpcUrl: string, method: string) => Promise<unknown>;
30
+ /**
31
+ * Tests only: replaces the JSON-RPC call (an SDK that accepts only https RPCs
32
+ * cannot be given a loopback stand-in). `undefined` restores the real one. Not
33
+ * exported from the package index, and reachable from no flag, setting or tool
34
+ * argument.
35
+ */
36
+ export declare function setRpcIdentityTransportForTesting(replacement: RpcIdentityTransport | undefined): void;
37
+ /**
38
+ * Refuses unless the RPC at `rpcUrl` says it serves `network`.
39
+ *
40
+ * @throws {RpcIdentityError} The RPC serves another network, did not answer, or
41
+ * answered something that does not name a network; or Wasit has no rule to
42
+ * tell which network an RPC for `network` serves. Nothing was sent to the
43
+ * target and nothing was signed.
44
+ */
45
+ export declare function assertRpcServesNetwork(network: string, rpcUrl: string): Promise<void>;
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The RPC identity check (D-032, D-023a+b): before a run signs anything or
3
+ * reads a settlement, the RPC it was given must say which network it serves,
4
+ * and it must be the run's.
5
+ *
6
+ * L0 judges the network the run is labelled with. The RPC is a separate input
7
+ * (`--rpc-url`, the MCP tool argument `rpcUrl`, the config), and nothing tied
8
+ * the two together: a `stellar:testnet` run pointed at a mainnet RPC signed a
9
+ * mainnet-valid channel commitment in 0.7.0, and every settlement read of such
10
+ * a run comes from another chain. So each entry point that signs or reads a
11
+ * settlement asks the RPC first:
12
+ *
13
+ * - Stellar: `getNetwork`, whose `passphrase` must be the run's network's;
14
+ * - EVM: `eth_chainId`, which must equal the CAIP-2 reference;
15
+ * - Solana: `getGenesisHash`, whose first characters are the CAIP-2 reference.
16
+ *
17
+ * A mismatch, no answer, or an answer that cannot be read refuses the run
18
+ * before any request reaches the target (fail closed). This guards against a
19
+ * mistake or a wrong default, not against an RPC that lies: an RPC that answers
20
+ * the right identity and then serves another chain is outside what any client
21
+ * check can see.
22
+ */
23
+ import { Networks } from "@stellar/stellar-sdk";
24
+ import { ConfigurationError } from "../errors.js";
25
+ import { sanitizeText } from "../sanitize.js";
26
+ /** The RPC does not serve the run's network, or would not say which one it serves. Nothing was sent or signed. */
27
+ export class RpcIdentityError extends ConfigurationError {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "RpcIdentityError";
31
+ }
32
+ }
33
+ const TIMEOUT_MS = 10_000;
34
+ /** The origin of the RPC for a message: its path or query may hold an API key. */
35
+ function origin(rpcUrl) {
36
+ try {
37
+ const parsed = new URL(rpcUrl);
38
+ return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : "an RPC that is not an http URL";
39
+ }
40
+ catch {
41
+ return "an RPC that is not a URL";
42
+ }
43
+ }
44
+ const jsonRpc = async (rpcUrl, method) => {
45
+ const response = await fetch(rpcUrl, {
46
+ method: "POST",
47
+ headers: { "content-type": "application/json" },
48
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method }),
49
+ // An RPC that redirects is not followed: the identity must come from the
50
+ // URL the run will use.
51
+ redirect: "manual",
52
+ signal: AbortSignal.timeout(TIMEOUT_MS),
53
+ });
54
+ if (response.status !== 200) {
55
+ await response.body?.cancel().catch(() => undefined);
56
+ throw new Error(`HTTP ${response.status}`);
57
+ }
58
+ const body = (await response.json());
59
+ if (body.error !== undefined) {
60
+ throw new Error(typeof body.error.message === "string" ? body.error.message : "a JSON-RPC error");
61
+ }
62
+ return body.result;
63
+ };
64
+ let transport = jsonRpc;
65
+ /**
66
+ * Tests only: replaces the JSON-RPC call (an SDK that accepts only https RPCs
67
+ * cannot be given a loopback stand-in). `undefined` restores the real one. Not
68
+ * exported from the package index, and reachable from no flag, setting or tool
69
+ * argument.
70
+ */
71
+ export function setRpcIdentityTransportForTesting(replacement) {
72
+ transport = replacement ?? jsonRpc;
73
+ }
74
+ const STELLAR_PASSPHRASES = new Map([
75
+ ["stellar:testnet", Networks.TESTNET],
76
+ ["stellar:pubnet", Networks.PUBLIC],
77
+ ]);
78
+ /** The network a Stellar passphrase belongs to, for the message. */
79
+ function stellarNetworkOf(passphrase) {
80
+ for (const [network, known] of STELLAR_PASSPHRASES)
81
+ if (known === passphrase)
82
+ return network;
83
+ return `a network with the passphrase "${sanitizeText(passphrase).slice(0, 80)}"`;
84
+ }
85
+ /** The method to ask, and how to read the answer into the CAIP-2 id it shows (or `undefined` when unreadable). */
86
+ function ruleFor(network) {
87
+ const [namespace, reference] = network.split(":", 2);
88
+ if (reference === undefined || reference === "")
89
+ return undefined;
90
+ if (namespace === "stellar" && STELLAR_PASSPHRASES.has(network)) {
91
+ return {
92
+ method: "getNetwork",
93
+ served: (result) => {
94
+ const passphrase = result?.passphrase;
95
+ return typeof passphrase === "string" ? stellarNetworkOf(passphrase) : undefined;
96
+ },
97
+ };
98
+ }
99
+ if (namespace === "eip155" && /^[1-9][0-9]*$/.test(reference)) {
100
+ return {
101
+ method: "eth_chainId",
102
+ served: (result) => {
103
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]{1,16}$/.test(result))
104
+ return undefined;
105
+ return `eip155:${BigInt(result).toString()}`;
106
+ },
107
+ };
108
+ }
109
+ if (namespace === "solana" && /^[1-9A-HJ-NP-Za-km-z]{32}$/.test(reference)) {
110
+ return {
111
+ method: "getGenesisHash",
112
+ served: (result) => {
113
+ if (typeof result !== "string" || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(result))
114
+ return undefined;
115
+ return `solana:${result.slice(0, 32)}`;
116
+ },
117
+ };
118
+ }
119
+ return undefined;
120
+ }
121
+ /**
122
+ * Refuses unless the RPC at `rpcUrl` says it serves `network`.
123
+ *
124
+ * @throws {RpcIdentityError} The RPC serves another network, did not answer, or
125
+ * answered something that does not name a network; or Wasit has no rule to
126
+ * tell which network an RPC for `network` serves. Nothing was sent to the
127
+ * target and nothing was signed.
128
+ */
129
+ export async function assertRpcServesNetwork(network, rpcUrl) {
130
+ const label = sanitizeText(network);
131
+ const at = sanitizeText(origin(rpcUrl));
132
+ const rule = ruleFor(network);
133
+ if (rule === undefined) {
134
+ throw new RpcIdentityError(`Wasit cannot tell which network an RPC for ${label} serves, so it does not pay or read ` +
135
+ `settlements through ${at}; nothing was signed.`);
136
+ }
137
+ let result;
138
+ try {
139
+ result = await transport(rpcUrl, rule.method);
140
+ }
141
+ catch (error) {
142
+ const reason = sanitizeText(error instanceof Error ? error.message : String(error)).slice(0, 160);
143
+ throw new RpcIdentityError(`The RPC at ${at} did not say which network it serves (${rule.method}: ${reason}), so Wasit ` +
144
+ `could not confirm it is ${label}. No payment was sent and nothing was signed.`);
145
+ }
146
+ const served = rule.served(result);
147
+ if (served === undefined) {
148
+ throw new RpcIdentityError(`The RPC at ${at} answered ${rule.method} with something that does not name a network, so ` +
149
+ `Wasit could not confirm it is ${label}. No payment was sent and nothing was signed.`);
150
+ }
151
+ if (served !== network) {
152
+ throw new RpcIdentityError(`The RPC at ${at} serves ${served}, and this run is on ${label}. Wasit pays and reads ` +
153
+ `settlements only through an RPC of the run's own network, so no payment was sent and ` +
154
+ `nothing was signed. Point the run at an RPC for ${label}.`);
155
+ }
156
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Which RPC a run reads the chain through, as a result names it (D-023c,
3
+ * option C), and the start-up setting that fixes it for the MCP server.
4
+ *
5
+ * The RPC identity check (rpc-identity.ts) refuses an RPC of another network.
6
+ * What it cannot see is an RPC of the right network that lies about a
7
+ * settlement: that is a false PASS, not a payment on another chain. So a result
8
+ * says which RPC it read through, by origin only (a key often rides in the path
9
+ * or the query), where that RPC came from, and when it is not Wasit's default
10
+ * for the network: then every chain read of the run is that RPC's word.
11
+ *
12
+ * `WASIT_RPC_URL`, read once when the MCP server starts, fixes the RPC of every
13
+ * tool call; the server then refuses the `rpcUrl` argument, so an agent cannot
14
+ * point a run at another RPC.
15
+ */
16
+ /** Where the RPC of a run came from. */
17
+ export type RpcSource = "default" | "argument" | "start-up";
18
+ export interface RpcInUse {
19
+ /** The origin only: scheme, host and port. */
20
+ readonly origin: string;
21
+ readonly source: RpcSource;
22
+ /** True when it is Wasit's default RPC for the network. */
23
+ readonly isDefault: boolean;
24
+ }
25
+ /** The variable that fixes the MCP server's RPC at start-up. */
26
+ export declare const RPC_LOCK_VARIABLE = "WASIT_RPC_URL";
27
+ /**
28
+ * The RPC a run on `network` reads through: `given` when there is one, else
29
+ * Wasit's default for the network. Undefined on a network that is not a test
30
+ * network (nothing is read there: the guard refuses first), and when there is
31
+ * neither.
32
+ */
33
+ export declare function rpcInUse(protocol: "x402" | "mpp", network: string, given?: {
34
+ readonly url: string;
35
+ readonly source: "argument" | "start-up";
36
+ }): RpcInUse | undefined;
37
+ /** One line for a result: which RPC, from where, and a flag when it is not the default. */
38
+ export declare function describeRpcInUse(network: string, rpc: RpcInUse): string;
39
+ /**
40
+ * The MCP server's RPC lock: `WASIT_RPC_URL` when it holds a value. Off when it
41
+ * is unset or blank. A value that is not an http(s) URL is a problem the server
42
+ * refuses to start on; the message never quotes the value.
43
+ */
44
+ export declare function readRpcLock(env: Readonly<Record<string, string | undefined>>): {
45
+ readonly url: string;
46
+ } | {
47
+ readonly problem: string;
48
+ } | undefined;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Which RPC a run reads the chain through, as a result names it (D-023c,
3
+ * option C), and the start-up setting that fixes it for the MCP server.
4
+ *
5
+ * The RPC identity check (rpc-identity.ts) refuses an RPC of another network.
6
+ * What it cannot see is an RPC of the right network that lies about a
7
+ * settlement: that is a false PASS, not a payment on another chain. So a result
8
+ * says which RPC it read through, by origin only (a key often rides in the path
9
+ * or the query), where that RPC came from, and when it is not Wasit's default
10
+ * for the network: then every chain read of the run is that RPC's word.
11
+ *
12
+ * `WASIT_RPC_URL`, read once when the MCP server starts, fixes the RPC of every
13
+ * tool call; the server then refuses the `rpcUrl` argument, so an agent cannot
14
+ * point a run at another RPC.
15
+ */
16
+ import { urlOrigin } from "../config.js";
17
+ import { resolveRpcUrl as resolveMppRpcUrl } from "../mpp/network.js";
18
+ import { paymentChainFor } from "../x402/chains/index.js";
19
+ import { networkClass } from "./networks.js";
20
+ /** The variable that fixes the MCP server's RPC at start-up. */
21
+ export const RPC_LOCK_VARIABLE = "WASIT_RPC_URL";
22
+ function defaultRpc(protocol, network) {
23
+ try {
24
+ return protocol === "x402" ? paymentChainFor(network)?.resolveRpcUrl(network) : resolveMppRpcUrl(network);
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ function sameUrl(a, b) {
31
+ try {
32
+ return new URL(a).href === new URL(b).href;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * The RPC a run on `network` reads through: `given` when there is one, else
40
+ * Wasit's default for the network. Undefined on a network that is not a test
41
+ * network (nothing is read there: the guard refuses first), and when there is
42
+ * neither.
43
+ */
44
+ export function rpcInUse(protocol, network, given) {
45
+ if (networkClass(network) !== "test")
46
+ return undefined;
47
+ const fallback = defaultRpc(protocol, network);
48
+ if (fallback === undefined)
49
+ return undefined;
50
+ if (given === undefined)
51
+ return { origin: urlOrigin(fallback), source: "default", isDefault: true };
52
+ return { origin: urlOrigin(given.url), source: given.source, isDefault: sameUrl(given.url, fallback) };
53
+ }
54
+ /** One line for a result: which RPC, from where, and a flag when it is not the default. */
55
+ export function describeRpcInUse(network, rpc) {
56
+ if (rpc.source === "default")
57
+ return `RPC: ${rpc.origin}, Wasit's default for ${network}.`;
58
+ const from = rpc.source === "argument" ? "from the rpcUrl argument" : `fixed when this server started (${RPC_LOCK_VARIABLE})`;
59
+ return rpc.isDefault
60
+ ? `RPC: ${rpc.origin}, ${from} (Wasit's default for ${network}).`
61
+ : `RPC: ${rpc.origin}, ${from}: not Wasit's default for ${network}, so every chain read of this run is this RPC's word.`;
62
+ }
63
+ /**
64
+ * The MCP server's RPC lock: `WASIT_RPC_URL` when it holds a value. Off when it
65
+ * is unset or blank. A value that is not an http(s) URL is a problem the server
66
+ * refuses to start on; the message never quotes the value.
67
+ */
68
+ export function readRpcLock(env) {
69
+ const value = env[RPC_LOCK_VARIABLE];
70
+ if (value === undefined || value.trim() === "")
71
+ return undefined;
72
+ let url;
73
+ try {
74
+ url = new URL(value.trim());
75
+ }
76
+ catch {
77
+ return { problem: `${RPC_LOCK_VARIABLE} is not a valid absolute URL; include the scheme, e.g. https://rpc.example.com` };
78
+ }
79
+ if (url.protocol !== "http:" && url.protocol !== "https:")
80
+ return { problem: `${RPC_LOCK_VARIABLE} must be an http or https URL` };
81
+ if (url.hostname === "")
82
+ return { problem: `${RPC_LOCK_VARIABLE} has no host` };
83
+ return { url: value.trim() };
84
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,37 @@
1
- export { checkStatus, errored, fixFor, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
- export type { CheckResult, CheckStatus, FailureGuidance, RunSummary, StructuredCheckResult, StructuredRun, } from "./check.js";
1
+ export { SKIP_KINDS, checkStatus, errored, fixFor, quoteValue, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
+ export type { CheckResult, CheckStatus, FailureGuidance, RunSummary, SkipKind, StructuredCheckResult, StructuredRun, } from "./check.js";
3
+ export { MARKDOWN_VALUE_MAX, sanitizeForMarkdown, sanitizeText } from "./sanitize.js";
4
+ export type { MarkdownOptions, SanitizeOptions } from "./sanitize.js";
5
+ export { CONFIG_VERSION, ConfigError, describeRun, headerEnvName, headersFromEnv, isLoopbackUrl, joinTarget, parseConfig, readConfigFile, resolveRun, urlOrigin, validateConfig, } from "./config.js";
6
+ export type { ChannelExpectation, ConfigIssue, EndpointConfig, EnvironmentConfig, JsonValue, PinConfig, ReadyConfig, RejectConfig, ResolvedEndpoint, ResolvedReject, ResolvedRun, RunSelection, ServiceConfig, WasitConfig, } from "./config.js";
7
+ export { buildEndpointReport, buildRunReport, checkGroup, describeTotals, endpointOutcome, paymentGroupUnsupported, exitCodeForEndpoint, groupCounts, redactReport, redactValue, reportTotals, paymentChecksSkipped, skippedPaymentChecks, toGradedRun, } from "./report.js";
8
+ export type { CheckGroup, EndpointInput, EndpointOutcome, EndpointReport, GroupCounts, RunReport, RunReportInput, RunTotals, } from "./report.js";
9
+ export { readBuildCommit, readPackageVersion, readToolVersions } from "./versions.js";
10
+ export type { ToolVersions } from "./versions.js";
11
+ export { HISTORY_LIMIT, MAX_BASELINE_BYTES, ReportFormatError, baselineProblem, diffReports, findRegressions, parseRunReport, readBaseline, recentFailures, selectBaseline, serializeBaseline, updateHistory, } from "./baseline.js";
12
+ export type { Baseline, BaselineResult, Change, ChangeKind, History, RecentFailure, Regression, } from "./baseline.js";
13
+ export { runExitCode } from "./verdict.js";
14
+ export type { RunVerdict } from "./verdict.js";
15
+ export { COMMENT_MARKER, renderCheckRun, renderComment, renderNoReportCheckRun, renderNoReportComment, renderNoReportSummary, renderRunningComment, renderSummary, } from "./ci-report.js";
16
+ export type { CheckRunOutput, RunningCommentInput } from "./ci-report.js";
17
+ export type { CiReportInput } from "./ci-report.js";
18
+ export { DENIED_ENV_NAMES, deniedEnvValues, isDeniedEnvName, scrubEnv } from "./denied-env.js";
3
19
  export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js";
4
20
  export type { CheckCatalogueEntry, ProtocolId } from "./catalogue.js";
5
21
  export * from "./errors.js";
22
+ export { NETWORK_CLASSES, PaymentNetworkRefusedError, assertPaymentNetworkAllowed, networkClass, } from "./guard/networks.js";
23
+ export type { NetworkClass, PaymentProtocol } from "./guard/networks.js";
24
+ export { MAINNET_OPT_IN_ABSENT, MainnetOptInRefusedError, mainnetStartupSwitches, refuseMainnetSwitch, } from "./guard/mainnet-optin.js";
25
+ export type { MainnetSwitch } from "./guard/mainnet-optin.js";
26
+ export { RPC_LOCK_VARIABLE, describeRpcInUse, readRpcLock, rpcInUse } from "./guard/rpc-in-use.js";
27
+ export { RpcIdentityError, assertRpcServesNetwork } from "./guard/rpc-identity.js";
28
+ export type { RpcInUse, RpcSource } from "./guard/rpc-in-use.js";
29
+ export { inGithubActions, payerKeyVariables, paymentEventGate, readGithubEvent } from "./guard/ci-event.js";
30
+ export type { PaymentEventGate } from "./guard/ci-event.js";
31
+ export { PER_PAYMENT_CAP_USD, PER_RUN_CAP_USD, PaymentGuardRefusedError, RunBudget, formatUsd, } from "./guard/budget.js";
32
+ export type { GuardRefusal, PinTerms, PlannedSignature } from "./guard/budget.js";
33
+ export { describePlan, planX402Run } from "./x402/plan.js";
34
+ export type { EndpointPlan, EndpointPlanStatus, PlannedOption, RunPlan, X402PlanOptions } from "./x402/plan.js";
6
35
  export * from "./x402/simulator.js";
7
36
  export * from "./mpp/channel.js";
8
37
  export * from "./mpp/charge.js";
package/dist/index.js CHANGED
@@ -1,6 +1,32 @@
1
- export { checkStatus, errored, fixFor, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
1
+ export { SKIP_KINDS, checkStatus, errored, fixFor, quoteValue, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
+ // The one sanitiser: everything printed or written into a report passes through it.
3
+ export { MARKDOWN_VALUE_MAX, sanitizeForMarkdown, sanitizeText } from "./sanitize.js";
4
+ // wasit.config.json, version 1.
5
+ export { CONFIG_VERSION, ConfigError, describeRun, headerEnvName, headersFromEnv, isLoopbackUrl, joinTarget, parseConfig, readConfigFile, resolveRun, urlOrigin, validateConfig, } from "./config.js";
6
+ // The run report, the endpoint outcome and the versions a result names.
7
+ export { buildEndpointReport, buildRunReport, checkGroup, describeTotals, endpointOutcome, paymentGroupUnsupported, exitCodeForEndpoint, groupCounts, redactReport, redactValue, reportTotals, paymentChecksSkipped, skippedPaymentChecks, toGradedRun, } from "./report.js";
8
+ export { readBuildCommit, readPackageVersion, readToolVersions } from "./versions.js";
9
+ // The baseline of the default branch, the diff against it, and the exit rule of a run.
10
+ export { HISTORY_LIMIT, MAX_BASELINE_BYTES, ReportFormatError, baselineProblem, diffReports, findRegressions, parseRunReport, readBaseline, recentFailures, selectBaseline, serializeBaseline, updateHistory, } from "./baseline.js";
11
+ export { runExitCode } from "./verdict.js";
12
+ // The pull request comment and the job summary.
13
+ export { COMMENT_MARKER, renderCheckRun, renderComment, renderNoReportCheckRun, renderNoReportComment, renderNoReportSummary, renderRunningComment, renderSummary, } from "./ci-report.js";
14
+ // Variables kept away from a service Wasit starts, and values kept out of output.
15
+ export { DENIED_ENV_NAMES, deniedEnvValues, isDeniedEnvName, scrubEnv } from "./denied-env.js";
2
16
  export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js";
3
17
  export * from "./errors.js";
18
+ // L0, the network guard every signing entry point runs.
19
+ export { NETWORK_CLASSES, PaymentNetworkRefusedError, assertPaymentNetworkAllowed, networkClass, } from "./guard/networks.js";
20
+ // The mainnet opt-in switches of this version: each one refuses (spec B12).
21
+ export { MAINNET_OPT_IN_ABSENT, MainnetOptInRefusedError, mainnetStartupSwitches, refuseMainnetSwitch, } from "./guard/mainnet-optin.js";
22
+ // Which RPC a result read the chain through, and the MCP server's start-up RPC lock (D-023c).
23
+ export { RPC_LOCK_VARIABLE, describeRpcInUse, readRpcLock, rpcInUse } from "./guard/rpc-in-use.js";
24
+ export { RpcIdentityError, assertRpcServesNetwork } from "./guard/rpc-identity.js";
25
+ // Which GitHub events may run the payment tier (D-022a), and which key variables are set.
26
+ export { inGithubActions, payerKeyVariables, paymentEventGate, readGithubEvent } from "./guard/ci-event.js";
27
+ // L1 and L2: the plan, and the caps every signature is charged against.
28
+ export { PER_PAYMENT_CAP_USD, PER_RUN_CAP_USD, PaymentGuardRefusedError, RunBudget, formatUsd, } from "./guard/budget.js";
29
+ export { describePlan, planX402Run } from "./x402/plan.js";
4
30
  export * from "./x402/simulator.js";
5
31
  export * from "./mpp/channel.js";
6
32
  export * from "./mpp/charge.js";
@@ -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}.`);
@@ -12,6 +12,7 @@ import { Challenge, Credential } from "mppx";
12
12
  import { MalformedResponseError, fetchTarget } from "../errors.js";
13
13
  import { signChannelCommitment } from "./channel-commitment.js";
14
14
  import { networkPassphrase, resolveRpcUrl } from "./network.js";
15
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
15
16
  export class ChannelChallengeError extends MalformedResponseError {
16
17
  constructor(message) {
17
18
  super(message);
@@ -106,6 +107,8 @@ export function serializeChannelCredential(parameters) {
106
107
  /** Signs `amount` for this challenge's channel and serialises the credential. */
107
108
  export async function buildChannelCredential(parameters) {
108
109
  const { challenge, amount, commitmentSecretHex, network, rpcUrl, action } = parameters;
110
+ // L0 at the signature itself, whoever calls it.
111
+ assertPaymentNetworkAllowed("mpp-channel", network);
109
112
  const signature = await signChannelCommitment({
110
113
  channelContract: challenge.channelContract,
111
114
  amount,