@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
@@ -0,0 +1,349 @@
1
+ /**
2
+ * What `wasit init` reads from a route (spec C2, C7 row 4; W3-2 slice 3).
3
+ *
4
+ * One unpaid request with the method and body the route takes: no payment,
5
+ * no signature, no key. A redirect is followed once inside the origin, and
6
+ * only when it keeps the request, the rule of the unpaid request a payment
7
+ * check reads (`fetchPaymentChallenge`, spec A8 row 5); any other redirect is
8
+ * reported and nothing is sent to its Location. The answer is data: read,
9
+ * never followed or run (rule 3). What a message takes from it passes through
10
+ * the sanitiser (A8 row 6), on one line and bounded; what the config takes
11
+ * from it is held to the config's own rules before it is written.
12
+ *
13
+ * Reading. A `PAYMENT-REQUIRED` header (or `X-Payment`, which the read checks
14
+ * also accept) is x402, one offer per payment option. A `WWW-Authenticate`
15
+ * header with `Payment` challenges is MPP: the intent tells charge from
16
+ * channel, and a channel challenge names its channel. MPP's network is read
17
+ * the way the Stellar MPP client reads it, so a challenge that names none is
18
+ * stellar:testnet (`@stellar/mpp` 0.7.1 `resolveNetworkId`,
19
+ * dist/shared/validation.js; the charge and the channel client both call it).
20
+ * An x402 v1 challenge in the body is reported as v1.
21
+ *
22
+ * Choosing. init writes one protocol on one network per route, and only what
23
+ * is certain (Najmi, 2026-11-15): with several ways to pay on test networks
24
+ * and no flag to choose, it does not choose; a network that is mainnet or
25
+ * that Wasit does not know is not written in this version.
26
+ */
27
+ import { StrKey } from "@stellar/stellar-sdk";
28
+ import { Challenge } from "mppx";
29
+ import { RedirectRefusedError, TargetUnreachableError, fetchPaymentChallenge } from "./errors.js";
30
+ import { RunBudget, formatUsd, shown, usdAsset } from "./guard/budget.js";
31
+ import { NETWORK_CLASSES, networkClass } from "./guard/networks.js";
32
+ import { isMppNetwork } from "./mpp/network.js";
33
+ import { sanitizeText } from "./sanitize.js";
34
+ import { acceptsOf } from "./x402/requirements.js";
35
+ import { buildInit, readV1BodyChallenge } from "./x402/simulator.js";
36
+ /** How long init waits for the route's answer. */
37
+ export const ROUTE_READ_TIMEOUT_MS = 15_000;
38
+ /** The most of a body init reads: enough for an x402 v1 challenge. */
39
+ const BODY_LIMIT_BYTES = 64 * 1024;
40
+ /** The most notes a reading keeps: a hostile header cannot flood the terminal. */
41
+ const MAX_NOTES = 10;
42
+ /** The loader's rule for a pinned address (config.ts, ADDRESS). */
43
+ const PIN_ADDRESS = /^[A-Za-z0-9]{20,128}$/;
44
+ /** The loader refuses a file with a value of this shape anywhere (config.ts, STELLAR_SECRET). */
45
+ const STELLAR_SECRET_SHAPE = /S[A-Z2-7]{55}/;
46
+ function asRecord(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
48
+ }
49
+ function text(value) {
50
+ return typeof value === "string" && value !== "" ? value : undefined;
51
+ }
52
+ /** A value of the service's for a line of output: sanitised, one line, bounded, unquoted. */
53
+ function brief(value) {
54
+ const line = sanitizeText(String(value)).replace(/\s+/g, " ").trim();
55
+ return line.length > 80 ? `${line.slice(0, 77)}...` : line;
56
+ }
57
+ /** A message for a line of output: sanitised and on one line, not cut. */
58
+ function oneLine(message) {
59
+ return sanitizeText(message).replace(/\s+/g, " ").trim();
60
+ }
61
+ function capped(notes) {
62
+ return notes.length <= MAX_NOTES ? notes : [...notes.slice(0, MAX_NOTES), `... and ${notes.length - MAX_NOTES} more.`];
63
+ }
64
+ function offerFields(fields) {
65
+ const out = {};
66
+ for (const key of ["amount", "asset", "payTo", "channel"]) {
67
+ const value = text(fields[key]);
68
+ if (value !== undefined)
69
+ out[key] = value;
70
+ }
71
+ return out;
72
+ }
73
+ function x402Offers(header, notes) {
74
+ let payload;
75
+ try {
76
+ payload = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
77
+ }
78
+ catch {
79
+ notes.push("The PAYMENT-REQUIRED header does not decode to JSON: x402 v2 sends the base64 of a JSON object.");
80
+ return [];
81
+ }
82
+ const accepts = acceptsOf(payload);
83
+ if (accepts === undefined || accepts.length === 0) {
84
+ notes.push("The PAYMENT-REQUIRED header lists no payment options (accepts).");
85
+ return [];
86
+ }
87
+ const offers = [];
88
+ accepts.forEach((option, index) => {
89
+ const network = text(option?.["network"]);
90
+ if (network === undefined) {
91
+ notes.push(`Payment option ${index + 1} of the PAYMENT-REQUIRED header names no network.`);
92
+ return;
93
+ }
94
+ offers.push({
95
+ protocol: "x402",
96
+ network,
97
+ networkNamed: true,
98
+ ...offerFields({ amount: option?.["amount"], asset: option?.["asset"], payTo: option?.["payTo"], channel: undefined }),
99
+ });
100
+ });
101
+ return offers;
102
+ }
103
+ function mppOffers(header, notes) {
104
+ let challenges;
105
+ try {
106
+ challenges = Challenge.deserializeList(header);
107
+ }
108
+ catch (error) {
109
+ notes.push(`The WWW-Authenticate header is not an MPP payment challenge Wasit can read (${brief(error.message)}).`);
110
+ return [];
111
+ }
112
+ const offers = [];
113
+ for (const challenge of challenges) {
114
+ if (challenge.method !== "stellar") {
115
+ notes.push(`An MPP challenge for the payment method ${shown(challenge.method)}: Wasit tests MPP on Stellar only.`);
116
+ continue;
117
+ }
118
+ const request = asRecord(challenge.request) ?? {};
119
+ const named = asRecord(request["methodDetails"])?.["network"];
120
+ let network;
121
+ if (named === undefined || named === null)
122
+ network = "stellar:testnet";
123
+ else if (typeof named === "string" && isMppNetwork(named))
124
+ network = named;
125
+ else {
126
+ notes.push(`An MPP ${brief(challenge.intent)} challenge names the network ${shown(named)}: a Stellar network is ` +
127
+ "stellar:testnet or stellar:pubnet.");
128
+ continue;
129
+ }
130
+ const networkNamed = named !== undefined && named !== null;
131
+ if (challenge.intent === "charge") {
132
+ offers.push({
133
+ protocol: "mpp-charge",
134
+ network,
135
+ networkNamed,
136
+ ...offerFields({ amount: request["amount"], asset: request["currency"], payTo: request["recipient"], channel: undefined }),
137
+ });
138
+ }
139
+ else if (challenge.intent === "channel") {
140
+ const fields = offerFields({ amount: request["amount"], asset: undefined, payTo: undefined, channel: request["channel"] });
141
+ if (fields.channel === undefined) {
142
+ notes.push("An MPP channel challenge names no channel.");
143
+ continue;
144
+ }
145
+ offers.push({ protocol: "mpp-channel", network, networkNamed, ...fields });
146
+ }
147
+ else {
148
+ notes.push(`An MPP challenge with the intent ${shown(challenge.intent)}: Wasit tests the intents charge and channel.`);
149
+ }
150
+ }
151
+ return offers;
152
+ }
153
+ /**
154
+ * What an answer says, without a network: the recorded answers of the tests
155
+ * go through the same reading as a live one.
156
+ */
157
+ export function interpretRouteAnswer(answer) {
158
+ const { status, headers, body, url } = answer;
159
+ if (status !== 402)
160
+ return { kind: "status", url, status };
161
+ const notes = [];
162
+ const offers = [];
163
+ const x402 = headers.get("PAYMENT-REQUIRED") ?? headers.get("X-Payment");
164
+ const mpp = headers.get("WWW-Authenticate");
165
+ if (x402 !== null)
166
+ offers.push(...x402Offers(x402, notes));
167
+ if (mpp !== null)
168
+ offers.push(...mppOffers(mpp, notes));
169
+ if (offers.length > 0)
170
+ return { kind: "challenge", url, offers, notes: capped(notes) };
171
+ if (x402 === null && mpp === null) {
172
+ if (readV1BodyChallenge(body) !== undefined)
173
+ return { kind: "x402-v1", url };
174
+ notes.push("The 402 carries no PAYMENT-REQUIRED header (x402 v2), no WWW-Authenticate header (MPP) and no x402 v1 challenge in its body.");
175
+ }
176
+ return { kind: "unreadable", url, notes: capped(notes) };
177
+ }
178
+ /** Reads at most `limit` bytes of a body, then lets the rest go. */
179
+ async function readBounded(response, limit) {
180
+ const reader = response.body?.getReader();
181
+ if (reader === undefined)
182
+ return "";
183
+ const chunks = [];
184
+ let size = 0;
185
+ try {
186
+ while (size < limit) {
187
+ const { done, value } = await reader.read();
188
+ if (done)
189
+ break;
190
+ chunks.push(value);
191
+ size += value.byteLength;
192
+ }
193
+ }
194
+ catch {
195
+ // What was read is the body.
196
+ }
197
+ finally {
198
+ await reader.cancel().catch(() => undefined);
199
+ }
200
+ return Buffer.concat(chunks).subarray(0, limit).toString("utf-8");
201
+ }
202
+ /**
203
+ * Sends the route one unpaid request and reads its answer.
204
+ *
205
+ * @throws {ConfigurationError} For a URL or a request shape that cannot be sent (checked before anything is sent).
206
+ */
207
+ export async function readRoute(url, shape, options = {}) {
208
+ const timeoutMs = options.timeoutMs ?? ROUTE_READ_TIMEOUT_MS;
209
+ const signal = AbortSignal.timeout(timeoutMs);
210
+ const init = { ...buildInit(shape), signal };
211
+ let answer;
212
+ try {
213
+ answer = await fetchPaymentChallenge(url, init);
214
+ }
215
+ catch (error) {
216
+ // Wasit's own messages, which name the origins already sanitised: one line, not cut.
217
+ if (error instanceof RedirectRefusedError)
218
+ return { kind: "redirect", message: oneLine(error.message) };
219
+ if (error instanceof TargetUnreachableError) {
220
+ return {
221
+ kind: "unreachable",
222
+ message: signal.aborted ? `It did not answer within ${timeoutMs / 1000} s.` : oneLine(error.message),
223
+ };
224
+ }
225
+ throw error;
226
+ }
227
+ const { response } = answer;
228
+ const plain = response.status === 402 &&
229
+ !response.headers.has("PAYMENT-REQUIRED") &&
230
+ !response.headers.has("X-Payment") &&
231
+ !response.headers.has("WWW-Authenticate");
232
+ let body = "";
233
+ if (plain)
234
+ body = await readBounded(response, BODY_LIMIT_BYTES);
235
+ else
236
+ await response.body?.cancel().catch(() => undefined);
237
+ return interpretRouteAnswer({ status: response.status, headers: response.headers, body, url: answer.url });
238
+ }
239
+ function testNetworks() {
240
+ return [...NETWORK_CLASSES]
241
+ .filter(([, kind]) => kind === "test")
242
+ .map(([network]) => network)
243
+ .join(", ");
244
+ }
245
+ const PROTOCOL_LABEL = {
246
+ x402: "x402",
247
+ "mpp-charge": "MPP charge",
248
+ "mpp-channel": "MPP channel",
249
+ };
250
+ /** One offer for a line of output. Sanitised. */
251
+ export function describeOffer(offer) {
252
+ const parts = [];
253
+ if (offer.amount !== undefined) {
254
+ const valued = /^\d{1,78}$/.test(offer.amount) && offer.asset !== undefined
255
+ ? RunBudget.valueOf(offer.network, offer.asset, BigInt(offer.amount))
256
+ : undefined;
257
+ const symbol = offer.asset === undefined ? undefined : usdAsset(offer.network, offer.asset)?.symbol;
258
+ parts.push(`price ${brief(offer.amount)} base units${offer.protocol === "mpp-channel" ? " a request" : ""}` +
259
+ (valued !== undefined && symbol !== undefined ? ` (${formatUsd(valued)} in ${symbol})` : ""));
260
+ }
261
+ if (offer.asset !== undefined)
262
+ parts.push(`${offer.protocol === "x402" ? "asset" : "currency"} ${brief(offer.asset)}`);
263
+ if (offer.payTo !== undefined)
264
+ parts.push(`${offer.protocol === "x402" ? "payTo" : "recipient"} ${brief(offer.payTo)}`);
265
+ if (offer.channel !== undefined)
266
+ parts.push(`channel ${brief(offer.channel)}`);
267
+ const where = `${PROTOCOL_LABEL[offer.protocol]} on ${brief(offer.network)}${offer.networkNamed ? "" : " (the challenge names no network; the Stellar MPP client reads that as stellar:testnet)"}`;
268
+ return parts.length === 0 ? where : `${where}: ${parts.join(", ")}`;
269
+ }
270
+ function way(offer) {
271
+ return `${PROTOCOL_LABEL[offer.protocol]} on ${brief(offer.network)}`;
272
+ }
273
+ function ways(offers) {
274
+ return [...new Set(offers.map(way))];
275
+ }
276
+ function wantedText(wanted) {
277
+ return [
278
+ ...(wanted.protocol === undefined ? [] : [PROTOCOL_LABEL[wanted.protocol]]),
279
+ ...(wanted.network === undefined ? [] : [`on ${brief(wanted.network)}`]),
280
+ ].join(" ");
281
+ }
282
+ /**
283
+ * The one way to pay init writes for this route, or why it writes none.
284
+ * Pure: the same offers and flags always give the same answer.
285
+ */
286
+ export function chooseOffer(offers, wanted = {}) {
287
+ const matching = offers.filter((offer) => (wanted.protocol === undefined || offer.protocol === wanted.protocol) &&
288
+ (wanted.network === undefined || offer.network === wanted.network));
289
+ if (matching.length === 0) {
290
+ return {
291
+ ok: false,
292
+ reason: `The route offers ${ways(offers).join("; ")}, and nothing as ${wantedText(wanted)}. Name one of those, or leave the flag out.`,
293
+ };
294
+ }
295
+ const onTest = matching.filter((offer) => networkClass(offer.network) === "test");
296
+ const testWays = ways(onTest);
297
+ if (testWays.length > 1) {
298
+ return {
299
+ ok: false,
300
+ reason: `The route offers more than one way to pay on a test network: ${testWays.join("; ")}. init writes one per ` +
301
+ "route and does not choose: name it with --protocol, --network or both.",
302
+ };
303
+ }
304
+ if (testWays.length === 0) {
305
+ const mainnet = matching.every((offer) => networkClass(offer.network) === "mainnet-optin");
306
+ return {
307
+ ok: false,
308
+ reason: mainnet
309
+ ? `The route asks to be paid on stellar:pubnet (mainnet): ${ways(matching).join("; ")}. init writes test networks only in this version.`
310
+ : `The route asks to be paid on ${ways(matching).join("; ")}, and none is a test network Wasit knows (${testNetworks()}).`,
311
+ };
312
+ }
313
+ const first = onTest[0];
314
+ const chosen = onTest.filter((offer) => offer.protocol === first.protocol && offer.network === first.network);
315
+ const left = offers.filter((offer) => !chosen.includes(offer));
316
+ const base = { ok: true, protocol: first.protocol, network: first.network, offers: chosen, left };
317
+ if (first.protocol === "mpp-channel") {
318
+ const channels = [...new Set(chosen.map((offer) => offer.channel ?? ""))];
319
+ if (channels.length > 1) {
320
+ return {
321
+ ok: false,
322
+ reason: `The route's channel challenges name ${channels.length} channels (${channels.map(brief).join(", ")}): init cannot tell which one it bills through.`,
323
+ };
324
+ }
325
+ const channel = channels[0];
326
+ if (!StrKey.isValidContract(channel)) {
327
+ return { ok: false, reason: `The channel challenge names the channel ${shown(channel)}, which is not a Soroban contract address (C...).` };
328
+ }
329
+ return { ...base, channel };
330
+ }
331
+ const payTos = [...new Set(chosen.map((offer) => offer.payTo))];
332
+ const assets = [...new Set(chosen.map((offer) => offer.asset))];
333
+ const payTo = payTos[0];
334
+ const asset = assets[0];
335
+ if (payTos.length > 1 || assets.length > 1) {
336
+ return { ...base, noPin: `the route offers more than one receiving address or asset on ${brief(first.network)}` };
337
+ }
338
+ if (payTo === undefined || asset === undefined || !PIN_ADDRESS.test(payTo) || !PIN_ADDRESS.test(asset)) {
339
+ return { ...base, noPin: "the challenge's receiving address or asset is missing or is not an address" };
340
+ }
341
+ if (STELLAR_SECRET_SHAPE.test(payTo) || STELLAR_SECRET_SHAPE.test(asset)) {
342
+ return {
343
+ ...base,
344
+ noPin: "the challenge's receiving address or asset is shaped like a Stellar secret key, so init does not write it " +
345
+ "(if it is a real key, the service is giving it away: rotate it)",
346
+ };
347
+ }
348
+ return { ...base, pin: { payTo, asset } };
349
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The one sanitiser. Everything Wasit prints, writes into a report, or puts in
3
+ * a pull request comment or job summary passes through here when it can carry
4
+ * text a service chose.
5
+ *
6
+ * A service answers with whatever it likes, and a pull request can change what
7
+ * that is. Two sinks are dangerous:
8
+ *
9
+ * - a terminal or a CI job log: control characters move the cursor or hide
10
+ * text, and a line that starts with `::` is a workflow command to the
11
+ * GitHub runner (set an output, add a mask, stop all commands);
12
+ * - a Markdown comment: HTML, links, mentions and table syntax change what the
13
+ * reader sees and who gets notified.
14
+ *
15
+ * `sanitizeText` is the plain level for the first, `sanitizeForMarkdown` adds
16
+ * the second. Neither is a security boundary on its own against a renderer
17
+ * Wasit does not control; they make the common attacks inert and are tested
18
+ * against the CommonMark rules, not against GitHub's renderer.
19
+ */
20
+ /** The longest a service-supplied value may be in a comment or summary. */
21
+ export declare const MARKDOWN_VALUE_MAX = 300;
22
+ export interface SanitizeOptions {
23
+ /**
24
+ * Values that must never appear in the output, such as the value of a
25
+ * `WASIT_HEADER_*` variable or a payer key. Matched as literals, after
26
+ * control characters are stripped, so a control character cannot hide one.
27
+ */
28
+ readonly redact?: readonly string[];
29
+ }
30
+ export interface MarkdownOptions extends SanitizeOptions {
31
+ /** Longest value, in characters, ellipsis included. Default {@link MARKDOWN_VALUE_MAX}. */
32
+ readonly maxLength?: number;
33
+ }
34
+ /**
35
+ * Plain level, for the terminal, the job log and report text.
36
+ *
37
+ * Strips control characters (keeping newline and tab), masks secrets, and
38
+ * breaks a `::` or `##[` at the start of a line by putting a space inside it.
39
+ * Idempotent. Newlines stay: this level does not reflow text.
40
+ */
41
+ export declare function sanitizeText(input: string, options?: SanitizeOptions): string;
42
+ /**
43
+ * Markdown level, for a value placed in a pull request comment or job summary.
44
+ *
45
+ * Returns one line: the plain level first, then whitespace (newlines too)
46
+ * collapsed so the value cannot open a heading, list or table row; links,
47
+ * issue references and mentions removed; the value cut to `maxLength`
48
+ * characters (300 by default); then Markdown and HTML escaped. The cut comes
49
+ * before the escaping, so an escape or an entity is never split. Not
50
+ * idempotent: apply it once, to text that has only had the plain level.
51
+ */
52
+ export declare function sanitizeForMarkdown(input: string, options?: MarkdownOptions): string;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The one sanitiser. Everything Wasit prints, writes into a report, or puts in
3
+ * a pull request comment or job summary passes through here when it can carry
4
+ * text a service chose.
5
+ *
6
+ * A service answers with whatever it likes, and a pull request can change what
7
+ * that is. Two sinks are dangerous:
8
+ *
9
+ * - a terminal or a CI job log: control characters move the cursor or hide
10
+ * text, and a line that starts with `::` is a workflow command to the
11
+ * GitHub runner (set an output, add a mask, stop all commands);
12
+ * - a Markdown comment: HTML, links, mentions and table syntax change what the
13
+ * reader sees and who gets notified.
14
+ *
15
+ * `sanitizeText` is the plain level for the first, `sanitizeForMarkdown` adds
16
+ * the second. Neither is a security boundary on its own against a renderer
17
+ * Wasit does not control; they make the common attacks inert and are tested
18
+ * against the CommonMark rules, not against GitHub's renderer.
19
+ */
20
+ /** The longest a service-supplied value may be in a comment or summary. */
21
+ export const MARKDOWN_VALUE_MAX = 300;
22
+ /** What replaces a secret, or a value that looks like one. */
23
+ const REDACTED = "[redacted]";
24
+ /** A redact entry shorter than this would blank ordinary words, and is not a secret. */
25
+ const MIN_REDACT_LENGTH = 4;
26
+ /**
27
+ * C0 controls except tab (U+0009) and newline (U+000A), DEL, C1 controls, and
28
+ * the bidirectional overrides that make text read in another order than it is
29
+ * stored. A carriage return is stripped too: .NET readers, the GitHub runner
30
+ * among them, split lines on it, so it could start a line of its own.
31
+ */
32
+ const CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f‪-‮⁦-⁩]/g;
33
+ /** The shape of a Stellar secret key. Public keys, contract ids and hashes do not match. */
34
+ const STELLAR_SECRET = /S[A-Z2-7]{55}/g;
35
+ /**
36
+ * A line the GitHub runner reads as a command: `::name::`, or the older
37
+ * `##[name]`. The runner trims leading whitespace first, and .NET counts more
38
+ * characters as whitespace than a space and a tab, so any whitespace but the
39
+ * line break is allowed before it.
40
+ */
41
+ const LINE_START_COMMAND = /^([^\S\n]*)(::|##\[)/gm;
42
+ /**
43
+ * Plain level, for the terminal, the job log and report text.
44
+ *
45
+ * Strips control characters (keeping newline and tab), masks secrets, and
46
+ * breaks a `::` or `##[` at the start of a line by putting a space inside it.
47
+ * Idempotent. Newlines stay: this level does not reflow text.
48
+ */
49
+ export function sanitizeText(input, options = {}) {
50
+ let text = String(input).replace(CONTROL_CHARACTERS, "");
51
+ const secrets = [...(options.redact ?? [])]
52
+ .filter((secret) => secret.length >= MIN_REDACT_LENGTH)
53
+ .sort((a, b) => b.length - a.length);
54
+ for (const secret of secrets)
55
+ text = text.split(secret).join(REDACTED);
56
+ return text
57
+ .replace(STELLAR_SECRET, REDACTED)
58
+ .replace(LINE_START_COMMAND, (_match, space, command) => space + (command === "::" ? ": :" : "# #["));
59
+ }
60
+ /** A link a Markdown renderer would make clickable: a scheme with an authority, `www.`, mailto and xmpp. */
61
+ const LINK = /\b[a-z][a-z0-9+.-]*:\/\/\S*|\b(?:www\.|mailto:|xmpp:)\S*/gi;
62
+ /** `#123` and `owner/repo#123`: GitHub turns both into links, the second one on another repository. */
63
+ const ISSUE_REFERENCE = /(?:[\w.-]+\/[\w.-]+)?#\d+/g;
64
+ /** An `@` that GitHub would read as the start of a mention. */
65
+ const MENTION = /@(?=[A-Za-z0-9_])/g;
66
+ const LINK_REMOVED = "[link removed]";
67
+ /** Cuts to `max` characters, counting code points, with an ellipsis in the last place. */
68
+ function truncate(text, max) {
69
+ const characters = Array.from(text);
70
+ if (characters.length <= max)
71
+ return text;
72
+ return `${characters.slice(0, Math.max(0, max - 1)).join("")}…`;
73
+ }
74
+ /**
75
+ * Backslash-escapes what could still format text inside a cell or a line, and
76
+ * HTML-escapes the rest. Newlines are already gone, so only the start of the
77
+ * string can open a heading, a list or a block quote.
78
+ */
79
+ function escapeMarkdown(text) {
80
+ return text
81
+ .replace(/[\\`*_~[\]()|]/g, "\\$&")
82
+ .replace(/^([-+=#])/, "\\$1")
83
+ .replace(/^(\d+)\./, "$1\\.")
84
+ .replace(/&/g, "&amp;")
85
+ .replace(/</g, "&lt;")
86
+ .replace(/>/g, "&gt;");
87
+ }
88
+ /**
89
+ * Markdown level, for a value placed in a pull request comment or job summary.
90
+ *
91
+ * Returns one line: the plain level first, then whitespace (newlines too)
92
+ * collapsed so the value cannot open a heading, list or table row; links,
93
+ * issue references and mentions removed; the value cut to `maxLength`
94
+ * characters (300 by default); then Markdown and HTML escaped. The cut comes
95
+ * before the escaping, so an escape or an entity is never split. Not
96
+ * idempotent: apply it once, to text that has only had the plain level.
97
+ */
98
+ export function sanitizeForMarkdown(input, options = {}) {
99
+ const max = Math.max(1, Math.floor(options.maxLength ?? MARKDOWN_VALUE_MAX));
100
+ const plain = sanitizeText(input, options).replace(/\s+/g, " ").trim();
101
+ const stripped = plain
102
+ .replace(LINK, LINK_REMOVED)
103
+ .replace(ISSUE_REFERENCE, LINK_REMOVED)
104
+ .replace(MENTION, "[at]");
105
+ return escapeMarkdown(truncate(stripped, max));
106
+ }
@@ -22,6 +22,20 @@ export interface TransferEvent {
22
22
  readonly amount: bigint;
23
23
  readonly contract: string;
24
24
  }
25
+ /**
26
+ * Reads the amount, and the destination's muxed id if any, from a `transfer`
27
+ * event's data.
28
+ *
29
+ * CAP-46 made the data a bare `i128` amount. CAP-67 keeps that when no muxed
30
+ * information is emitted, and otherwise makes it a map
31
+ * `{ amount: i128, to_muxed_id: u64 | bytes | string }`. Reading only the bare
32
+ * form would drop every payment to a muxed address, and report a settlement
33
+ * that happened as one that did not.
34
+ */
35
+ export declare function readTransferData(data: xdr.ScVal): {
36
+ amount: bigint;
37
+ toMuxedId?: string;
38
+ } | undefined;
25
39
  /**
26
40
  * Extracts CAP-46 `transfer` events from a settled transaction.
27
41
  *
@@ -36,7 +36,7 @@ function asRecord(value) {
36
36
  * form would drop every payment to a muxed address, and report a settlement
37
37
  * that happened as one that did not.
38
38
  */
39
- function readTransferData(data) {
39
+ export function readTransferData(data) {
40
40
  const native = scValToNative(data);
41
41
  if (typeof native === "bigint")
42
42
  return { amount: native };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The exit code of a run of several endpoints (spec A2 with A8 #3, D-021).
3
+ *
4
+ * - 1: an endpoint is non-conformant, or an endpoint that was graded on the
5
+ * default branch is not graded now (the baseline says so). A service that
6
+ * drops below the standard of its chain must not be green.
7
+ * - 2: no verdict. Nothing could be graded, a check could not run, or payment
8
+ * checks were asked for and none could be graded on an endpoint's network. A
9
+ * service that was never graded is here: not green, and not labelled FAIL.
10
+ * - 0: at least one endpoint was graded, none failed, no check errored.
11
+ *
12
+ * The reason carries the counts ("0 graded, 1 unsupported"), so a green run
13
+ * cannot be read as a pass of something that was not graded.
14
+ */
15
+ import { type Regression } from "./baseline.js";
16
+ import { type RunReport } from "./report.js";
17
+ export interface RunVerdict {
18
+ readonly code: 0 | 1 | 2;
19
+ /** One line, for the terminal, the job summary and the report notes. */
20
+ readonly reason: string;
21
+ /** Endpoints that were graded on the baseline and are not now. Empty without a baseline. */
22
+ readonly regressions: readonly Regression[];
23
+ }
24
+ export declare function runExitCode(report: RunReport, baseline?: RunReport): RunVerdict;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The exit code of a run of several endpoints (spec A2 with A8 #3, D-021).
3
+ *
4
+ * - 1: an endpoint is non-conformant, or an endpoint that was graded on the
5
+ * default branch is not graded now (the baseline says so). A service that
6
+ * drops below the standard of its chain must not be green.
7
+ * - 2: no verdict. Nothing could be graded, a check could not run, or payment
8
+ * checks were asked for and none could be graded on an endpoint's network. A
9
+ * service that was never graded is here: not green, and not labelled FAIL.
10
+ * - 0: at least one endpoint was graded, none failed, no check errored.
11
+ *
12
+ * The reason carries the counts ("0 graded, 1 unsupported"), so a green run
13
+ * cannot be read as a pass of something that was not graded.
14
+ */
15
+ import { findRegressions } from "./baseline.js";
16
+ import { describeTotals, paymentGroupUnsupported } from "./report.js";
17
+ export function runExitCode(report, baseline) {
18
+ const regressions = baseline === undefined ? [] : findRegressions(report, baseline);
19
+ const counts = describeTotals(report.totals);
20
+ const errored = report.endpoints.reduce((total, endpoint) => total + endpoint.results.filter((result) => result.status === "ERROR").length, 0);
21
+ if (report.totals.nonConformant > 0) {
22
+ const n = report.totals.nonConformant;
23
+ return { code: 1, reason: `${n} endpoint${n === 1 ? " is" : "s are"} non-conformant (${counts})`, regressions };
24
+ }
25
+ if (regressions.length > 0) {
26
+ const list = regressions.map((item) => `${item.endpoint} (${item.was} on main, now ${item.now})`).join(", ");
27
+ return { code: 1, reason: `regression against main: ${list} (${counts})`, regressions };
28
+ }
29
+ if (report.totals.graded === 0) {
30
+ return { code: 2, reason: `nothing could be graded: ${counts}`, regressions };
31
+ }
32
+ if (errored > 0) {
33
+ return { code: 2, reason: `${errored} check${errored === 1 ? "" : "s"} could not run (${counts})`, regressions };
34
+ }
35
+ // Payment checks were asked for and none could be graded on an endpoint's network (Najmi, 2026-11-15).
36
+ const unsupportedPayment = report.endpoints.filter((endpoint) => paymentGroupUnsupported(endpoint.results, endpoint.protocol)).length;
37
+ if (unsupportedPayment > 0) {
38
+ return {
39
+ code: 2,
40
+ reason: `payment checks were asked for and could not be graded on ${unsupportedPayment} ` +
41
+ `endpoint${unsupportedPayment === 1 ? "" : "s"} (${counts})`,
42
+ regressions,
43
+ };
44
+ }
45
+ return { code: 0, reason: counts, regressions };
46
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The versions a result names: Wasit core and the CLI, the x402 version Wasit
3
+ * grades, and the SDK packages the checks run through.
4
+ *
5
+ * Read at run time from the installed packages' own `package.json`, by path,
6
+ * never typed by hand: a constant drifts from what is installed, and the point
7
+ * of printing a version is that it is the one that ran. They are read by path
8
+ * and not through `require.resolve("<pkg>/package.json")` because the SDK
9
+ * packages' export maps do not list it (checked on 2026-11-15 for all five:
10
+ * ERR_PACKAGE_PATH_NOT_EXPORTED).
11
+ */
12
+ /**
13
+ * The installed version of `name`, found the way Node finds a dependency: in
14
+ * `node_modules` of `from` or of any directory above it.
15
+ *
16
+ * Returns "unknown" when the package is not there, its name does not match, or
17
+ * its version is not a version.
18
+ */
19
+ export declare function readPackageVersion(name: string, from: string): string;
20
+ /** True for exactly seven lower-case hex characters: the only build text that reaches a comment. */
21
+ export declare function isShortCommit(value: unknown): value is string;
22
+ /**
23
+ * The commit this build of Wasit was made from, when the Action says so: the
24
+ * action ref (`WASIT_BUILD_COMMIT`) if it is a full commit id. A tag or a branch
25
+ * name is not a commit, and says nothing here: a pinned tag already names the
26
+ * version, and a result must not name a build it cannot show.
27
+ */
28
+ export declare function readBuildCommit(env: Readonly<Record<string, string | undefined>>): string | undefined;
29
+ export interface ToolVersions {
30
+ readonly wasit: {
31
+ readonly cli: string;
32
+ readonly core: string;
33
+ /** The first seven characters of the commit an Action build came from. Absent for an installed package. */
34
+ readonly build?: string;
35
+ };
36
+ readonly sdk: {
37
+ /** The x402 version Wasit grades. */
38
+ readonly x402Version: 2;
39
+ readonly "@x402/core": string;
40
+ readonly "@x402/stellar": string;
41
+ readonly "@stellar/mpp": string;
42
+ readonly mppx: string;
43
+ readonly "@stellar/stellar-sdk": string;
44
+ };
45
+ }
46
+ /**
47
+ * The versions of this run. The CLI knows its own version (core cannot read the
48
+ * CLI's `package.json`), so it passes it in.
49
+ */
50
+ export declare function readToolVersions(cliVersion?: string, build?: string): ToolVersions;