@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,206 @@
1
+ /**
2
+ * The caps of spec B4, in code: at most $1 a payment and $5 a run, the run's
3
+ * total charged BEFORE each signature and never credited back (B3, B-A08).
4
+ *
5
+ * A cap in dollars needs an asset whose dollar value is known. Wasit pays only
6
+ * in USDC (the SDK client's default assets, plus Circle's USDC on Ethereum
7
+ * Sepolia), so the table below lists USDC on each test network with its
8
+ * decimals, and a payment in any other asset is refused: Wasit cannot hold it
9
+ * to the cap. On mainnet it lists Circle's USDC on Stellar mainnet only, the
10
+ * one asset a mainnet run pays in (B4); L0 refuses that network without the
11
+ * mainnet opt-in, so valuing it allows nothing by itself.
12
+ *
13
+ * Amounts in dollars are bigints at 10^-18 of a dollar, so 6 and 7 decimal
14
+ * tokens add up exactly.
15
+ *
16
+ * Pure: no network, no key.
17
+ */
18
+ import { CheckSetupError, ConfigurationError } from "../errors.js";
19
+ import { sanitizeText } from "../sanitize.js";
20
+ /** At most this many dollars in one payment. Fixed; nothing raises it. */
21
+ export const PER_PAYMENT_CAP_USD = 1;
22
+ /** At most this many dollars signed in one run. A config may only lower it (`maxRunUsd`). */
23
+ export const PER_RUN_CAP_USD = 5;
24
+ /** A dollar, in the units this module counts in. */
25
+ const DOLLAR = 10n ** 18n;
26
+ /**
27
+ * USDC on each test network. Sources (read 2026-11-16): `@x402/stellar` 2.28.0
28
+ * `USDC_TESTNET_ADDRESS`, `DEFAULT_TOKEN_DECIMALS = 7`; `@x402/evm` 2.28.0 default
29
+ * asset of `eip155:84532`, decimals 6; Circle's USDC on Ethereum Sepolia as
30
+ * `chains/evm.ts` (`ETHEREUM_SEPOLIA_USDC`, 6 decimals read from the contract
31
+ * 2026-10-05); `@x402/svm` 2.28.0 `USDC_DEVNET_ADDRESS`, decimals 6.
32
+ */
33
+ export const USD_ASSETS = [
34
+ { network: "stellar:testnet", asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", decimals: 7, symbol: "USDC" },
35
+ { network: "eip155:84532", asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", decimals: 6, symbol: "USDC" },
36
+ { network: "eip155:11155111", asset: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", decimals: 6, symbol: "USDC" },
37
+ { network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", decimals: 6, symbol: "USDC" },
38
+ // MAINNET_USDC of guard/mainnet-plan.ts (checked three ways there); a test asserts they are the same.
39
+ { network: "stellar:pubnet", asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", decimals: 7, symbol: "USDC" },
40
+ ];
41
+ /** Whether two addresses on `network` are the same: an EVM address in any letter case, others exactly. */
42
+ export function sameAddress(network, a, b) {
43
+ if (network.startsWith("eip155:"))
44
+ return a.toLowerCase() === b.toLowerCase();
45
+ return a === b;
46
+ }
47
+ /** The dollar asset `asset` is on `network`, if Wasit knows it. */
48
+ export function usdAsset(network, asset) {
49
+ return USD_ASSETS.find((entry) => entry.network === network && sameAddress(network, entry.asset, asset));
50
+ }
51
+ /** `amount` base units of a dollar token with `decimals` decimals, in this module's dollar units. */
52
+ export function usdFromBaseUnits(amount, decimals) {
53
+ return (amount * DOLLAR) / 10n ** BigInt(decimals);
54
+ }
55
+ /** `amount` base units of `asset`, in this module's dollar units. */
56
+ function toUsd(asset, amount) {
57
+ return usdFromBaseUnits(amount, asset.decimals);
58
+ }
59
+ /** Whole and fractional dollars, rounded down to a millionth: a cap is never rounded up. */
60
+ export function usdFromDollars(dollars) {
61
+ return (BigInt(Math.floor(dollars * 1_000_000)) * DOLLAR) / 1000000n;
62
+ }
63
+ /** "$4.50", "$0.0000001": exact, at least two decimals. */
64
+ export function formatUsd(amount) {
65
+ const sign = amount < 0n ? "-" : "";
66
+ const absolute = amount < 0n ? -amount : amount;
67
+ const whole = absolute / DOLLAR;
68
+ let fraction = (absolute % DOLLAR).toString().padStart(18, "0").replace(/0+$/, "");
69
+ if (fraction.length < 2)
70
+ fraction = fraction.padEnd(2, "0");
71
+ return `${sign}$${whole}.${fraction}`;
72
+ }
73
+ /**
74
+ * A payment the guard will not sign, or, with `signed`, a signed payment it
75
+ * will not send. A setup error: it says nothing about the target, and the
76
+ * check that hit it has no verdict.
77
+ */
78
+ export class PaymentGuardRefusedError extends CheckSetupError {
79
+ reason;
80
+ constructor(reason, message, options = {}) {
81
+ super(options.signed === true ? `${message} It was signed and discarded; it was not sent.` : `${message} Nothing was signed.`);
82
+ this.name = "PaymentGuardRefusedError";
83
+ this.reason = reason;
84
+ }
85
+ }
86
+ /** A value the target chose, for a message: one line, no control characters, bounded. */
87
+ export function shown(value) {
88
+ const text = sanitizeText(String(value)).replace(/\s+/g, " ");
89
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 77)}...` : text);
90
+ }
91
+ /** A base-unit amount as the challenge gives it: digits only, at most 78 (a uint256). */
92
+ const AMOUNT = /^\d{1,78}$/;
93
+ export function parseAmount(amount) {
94
+ if (typeof amount !== "string" || !AMOUNT.test(amount)) {
95
+ throw new PaymentGuardRefusedError("amount", `The amount to sign, ${shown(amount)}, is not a whole number of base units.`);
96
+ }
97
+ return BigInt(amount);
98
+ }
99
+ /**
100
+ * Refuses unless EVERY `exact` option on `network` pays the pinned `payTo` in
101
+ * the pinned asset (B-A02): the SDK picks among the options by its own rules,
102
+ * so a check of the first one alone would not cover what it signs. Options on
103
+ * other networks or schemes are never signed and are not judged.
104
+ */
105
+ export function assertPinned(network, accepts, pin) {
106
+ if (pin === undefined)
107
+ return;
108
+ for (const [index, requirement] of accepts.entries()) {
109
+ if (requirement.scheme !== "exact" || requirement.network !== network)
110
+ continue;
111
+ for (const field of ["payTo", "asset"]) {
112
+ if (!sameAddress(network, String(requirement[field]), pin[field])) {
113
+ throw new PaymentGuardRefusedError("pin", `Option ${index + 1} of the challenge (exact, ${network}) has ${field} ${shown(requirement[field])}, ` +
114
+ `not the pinned ${pin[field]}.`);
115
+ }
116
+ }
117
+ }
118
+ }
119
+ /**
120
+ * What the payment checks sign for an endpoint priced `price` (B0 fact 8):
121
+ * X402-06 the price (settles), X402-07 the price (signature then corrupted),
122
+ * X402-09 half the price, rounded down (none when there is no smaller amount),
123
+ * X402-10 the price with a short lifetime. X402-08 resends X402-06 and signs
124
+ * nothing. 3.5 times the price. With `rejectedRequest`, X402-11 the price as
125
+ * well (a valid payment sent with a request the service must refuse): 4.5 times.
126
+ */
127
+ export function plannedSignatures(price, options = {}) {
128
+ return [
129
+ { check: "X402-06", amount: price },
130
+ { check: "X402-07", amount: price },
131
+ ...(price >= 2n ? [{ check: "X402-09", amount: price / 2n }] : []),
132
+ { check: "X402-10", amount: price },
133
+ ...(options.rejectedRequest === true ? [{ check: "X402-11", amount: price }] : []),
134
+ ];
135
+ }
136
+ /**
137
+ * The dollars one run may sign. Every signature is charged here first; a
138
+ * charge that does not fit is refused and nothing is signed. Nothing is ever
139
+ * credited back: a payment that failed after it was signed may still settle.
140
+ * Once the cap refuses a payment, the budget is spent: every later charge is
141
+ * refused too, so a run never signs a smaller payment after a larger one did
142
+ * not fit.
143
+ */
144
+ export class RunBudget {
145
+ #cap;
146
+ #spent = 0n;
147
+ #exhausted;
148
+ #entries = [];
149
+ constructor(options = {}) {
150
+ const lower = options.maxRunUsd;
151
+ if (lower !== undefined && (!Number.isFinite(lower) || lower <= 0)) {
152
+ throw new ConfigurationError("maxRunUsd must be a number above 0: it can only lower the per-run cap.");
153
+ }
154
+ this.#cap = usdFromDollars(Math.min(lower ?? PER_RUN_CAP_USD, PER_RUN_CAP_USD));
155
+ }
156
+ /** The run's cap, in dollar units. */
157
+ get capUsd() {
158
+ return this.#cap;
159
+ }
160
+ /** What the run has charged so far, in dollar units. */
161
+ get spentUsd() {
162
+ return this.#spent;
163
+ }
164
+ get entries() {
165
+ return [...this.#entries];
166
+ }
167
+ /**
168
+ * Charges one payment, or refuses it. Called before the signature, with the
169
+ * amount that will be signed.
170
+ */
171
+ charge(charge) {
172
+ const amount = parseAmount(charge.amount);
173
+ const asset = usdAsset(charge.network, charge.asset);
174
+ if (asset === undefined) {
175
+ throw new PaymentGuardRefusedError("asset", `The target asks to be paid in ${shown(charge.asset)} on ${charge.network}, an asset Wasit does not ` +
176
+ `value in US dollars, so it cannot hold the payment to the $${PER_PAYMENT_CAP_USD}.00 cap.`);
177
+ }
178
+ const usd = toUsd(asset, amount);
179
+ const perPayment = usdFromDollars(PER_PAYMENT_CAP_USD);
180
+ if (usd > perPayment) {
181
+ throw new PaymentGuardRefusedError("price", `${charge.check} would sign ${amount} base units of ${asset.symbol} (${formatUsd(usd)}), above the ` +
182
+ `${formatUsd(perPayment)} per payment fixed in Wasit. A route priced at ` +
183
+ `${formatUsd(perPayment)} or less is checked as usual.`);
184
+ }
185
+ if (charge.planned !== undefined && amount > charge.planned) {
186
+ throw new PaymentGuardRefusedError("plan", `${charge.check} would sign ${amount} base units, more than the ${charge.planned} the plan allowed ` +
187
+ `for it before the run started: the service changed its price after the plan.`);
188
+ }
189
+ if (this.#exhausted !== undefined) {
190
+ throw new PaymentGuardRefusedError("run-cap", this.#exhausted);
191
+ }
192
+ if (this.#spent + usd > this.#cap) {
193
+ this.#exhausted =
194
+ `The run reached its ${formatUsd(this.#cap)} cap: ${charge.check} would have taken it from ` +
195
+ `${formatUsd(this.#spent)} to ${formatUsd(this.#spent + usd)}, so the run signs nothing more.`;
196
+ throw new PaymentGuardRefusedError("run-cap", this.#exhausted);
197
+ }
198
+ this.#spent += usd;
199
+ this.#entries.push({ check: charge.check, network: charge.network, asset: asset.asset, amount });
200
+ }
201
+ /** The dollar value of `amount` base units of `asset` on `network`, if Wasit can value it. */
202
+ static valueOf(network, asset, amount) {
203
+ const known = usdAsset(network, asset);
204
+ return known === undefined ? undefined : toUsd(known, amount);
205
+ }
206
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Which GitHub events may run the payment tier (D-022a option 2, D-032).
3
+ *
4
+ * The payment tier runs only where the code that runs is code that was merged:
5
+ * a push to the default branch, a schedule (GitHub runs it on the default
6
+ * branch), and workflow_dispatch on the default branch. Every pull request event
7
+ * is refused, a same-repository one too: its branch's code and new dependencies
8
+ * would run in the same job as the payer key before anyone reviewed them. Every
9
+ * other event is refused as well (merge_group and workflow_run run code that is
10
+ * not on the default branch yet). Outside GitHub Actions the gate is open: a run
11
+ * on a laptop is the builder's own choice.
12
+ *
13
+ * What this stops is a mistake in a workflow, not its author (B-A10): a step
14
+ * can hide the runner's variables from the CLI. The control that holds is
15
+ * where the workflow gives the secret, which the guide explains.
16
+ */
17
+ export interface PaymentEventGate {
18
+ readonly allowed: boolean;
19
+ /** Set when not allowed: the reason a skipped payment check gives, "payment checks not run: ...". */
20
+ readonly reason?: string;
21
+ /**
22
+ * Not allowed because the run is in a CI that is not GitHub Actions (`CI`
23
+ * set): there the service of the run would share its job with the key, and
24
+ * nothing keeps them apart. `wasit run` refuses the payment tier there.
25
+ */
26
+ readonly ciOutsideGithub?: true;
27
+ }
28
+ /**
29
+ * The default branch the event payload names (`repository.default_branch`),
30
+ * in a shape that is safe to echo; undefined otherwise. The mainnet job rules
31
+ * hold the run's ref to it (spec B17.4).
32
+ */
33
+ export declare function githubDefaultBranch(event: unknown): string | undefined;
34
+ /**
35
+ * True when the process runs as a step of GitHub Actions, or says it does.
36
+ * Fail closed: either variable counts, with any value that is not empty, as
37
+ * the CLI's own CI test reads `GITHUB_ACTIONS`.
38
+ */
39
+ export declare function inGithubActions(env: Readonly<Record<string, string | undefined>>): boolean;
40
+ /**
41
+ * May this run pay? `event` is the parsed payload of `GITHUB_EVENT_PATH`
42
+ * ({@link readGithubEvent}), or undefined when there is none.
43
+ */
44
+ export declare function paymentEventGate(env: Readonly<Record<string, string | undefined>>, event: unknown): PaymentEventGate;
45
+ /**
46
+ * The payload of the event that started the workflow, from the file
47
+ * `GITHUB_EVENT_PATH` names; undefined when there is none, it cannot be read,
48
+ * it is not JSON, or it is above 1 MiB.
49
+ */
50
+ export declare function readGithubEvent(env: Readonly<Record<string, string | undefined>>): unknown;
51
+ /**
52
+ * The key variables that hold a value, by their fixed names in upper case. A
53
+ * blank value is not a key: a pull request from a fork gets every secret as an
54
+ * empty string.
55
+ */
56
+ export declare function payerKeyVariables(env: Readonly<Record<string, string | undefined>>): string[];
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Which GitHub events may run the payment tier (D-022a option 2, D-032).
3
+ *
4
+ * The payment tier runs only where the code that runs is code that was merged:
5
+ * a push to the default branch, a schedule (GitHub runs it on the default
6
+ * branch), and workflow_dispatch on the default branch. Every pull request event
7
+ * is refused, a same-repository one too: its branch's code and new dependencies
8
+ * would run in the same job as the payer key before anyone reviewed them. Every
9
+ * other event is refused as well (merge_group and workflow_run run code that is
10
+ * not on the default branch yet). Outside GitHub Actions the gate is open: a run
11
+ * on a laptop is the builder's own choice.
12
+ *
13
+ * What this stops is a mistake in a workflow, not its author (B-A10): a step
14
+ * can hide the runner's variables from the CLI. The control that holds is
15
+ * where the workflow gives the secret, which the guide explains.
16
+ */
17
+ import { readFileSync, statSync } from "node:fs";
18
+ import { DENIED_ENV_NAMES } from "../denied-env.js";
19
+ const ALLOWED_EVENTS = "Wasit pays on push to the default branch, schedule and workflow_dispatch only";
20
+ /** An event name or a branch, as far as it is ever printed. Anything else is not echoed. */
21
+ const PRINTABLE_EVENT = /^[a-z_]{1,64}$/;
22
+ const PRINTABLE_REF = /^[A-Za-z0-9._/-]{1,200}$/;
23
+ const MAX_EVENT_BYTES = 1024 * 1024;
24
+ function nonEmpty(value) {
25
+ return typeof value === "string" && value !== "";
26
+ }
27
+ function shownEvent(event) {
28
+ return PRINTABLE_EVENT.test(event) ? event : "(an event name Wasit does not print)";
29
+ }
30
+ function shownRef(ref) {
31
+ if (ref === "")
32
+ return "no ref";
33
+ return PRINTABLE_REF.test(ref) ? ref : "(a ref Wasit does not print)";
34
+ }
35
+ /**
36
+ * The default branch the event payload names (`repository.default_branch`),
37
+ * in a shape that is safe to echo; undefined otherwise. The mainnet job rules
38
+ * hold the run's ref to it (spec B17.4).
39
+ */
40
+ export function githubDefaultBranch(event) {
41
+ if (event === null || typeof event !== "object")
42
+ return undefined;
43
+ const repository = event.repository;
44
+ if (repository === null || typeof repository !== "object")
45
+ return undefined;
46
+ const branch = repository.default_branch;
47
+ return typeof branch === "string" && PRINTABLE_REF.test(branch) ? branch : undefined;
48
+ }
49
+ /**
50
+ * True when the process runs as a step of GitHub Actions, or says it does.
51
+ * Fail closed: either variable counts, with any value that is not empty, as
52
+ * the CLI's own CI test reads `GITHUB_ACTIONS`.
53
+ */
54
+ export function inGithubActions(env) {
55
+ return nonEmpty(env["GITHUB_ACTIONS"]) || nonEmpty(env["GITHUB_EVENT_NAME"]);
56
+ }
57
+ /**
58
+ * May this run pay? `event` is the parsed payload of `GITHUB_EVENT_PATH`
59
+ * ({@link readGithubEvent}), or undefined when there is none.
60
+ */
61
+ export function paymentEventGate(env, event) {
62
+ if (!inGithubActions(env)) {
63
+ // Najmi, 2026-11-17 (review R9 a): outside GitHub Actions only a run outside CI pays.
64
+ if (nonEmpty(env["CI"])) {
65
+ return { allowed: false, reason: "payment checks not run: CI is set, and this is not GitHub Actions", ciOutsideGithub: true };
66
+ }
67
+ return { allowed: true };
68
+ }
69
+ const name = env["GITHUB_EVENT_NAME"] ?? "";
70
+ if (name.startsWith("pull_request"))
71
+ return { allowed: false, reason: "payment checks not run: pull request" };
72
+ if (name !== "push" && name !== "schedule" && name !== "workflow_dispatch") {
73
+ return {
74
+ allowed: false,
75
+ reason: `payment checks not run: the ${shownEvent(name)} event (${ALLOWED_EVENTS})`,
76
+ };
77
+ }
78
+ const ref = env["GITHUB_REF"] ?? "";
79
+ const branch = githubDefaultBranch(event);
80
+ if (branch === undefined) {
81
+ // GitHub runs a schedule on the default branch, and its payload may not name
82
+ // the repository; its ref must still be a branch.
83
+ if (name === "schedule" && ref.startsWith("refs/heads/"))
84
+ return { allowed: true };
85
+ return {
86
+ allowed: false,
87
+ reason: `payment checks not run: the ${name} event does not name the default branch, so Wasit cannot tell that ${shownRef(ref)} is it`,
88
+ };
89
+ }
90
+ if (ref !== `refs/heads/${branch}`) {
91
+ return {
92
+ allowed: false,
93
+ reason: `payment checks not run: ${name} on ${shownRef(ref)}, not the default branch ${branch} (${ALLOWED_EVENTS})`,
94
+ };
95
+ }
96
+ return { allowed: true };
97
+ }
98
+ /**
99
+ * The payload of the event that started the workflow, from the file
100
+ * `GITHUB_EVENT_PATH` names; undefined when there is none, it cannot be read,
101
+ * it is not JSON, or it is above 1 MiB.
102
+ */
103
+ export function readGithubEvent(env) {
104
+ const file = env["GITHUB_EVENT_PATH"];
105
+ if (!nonEmpty(file))
106
+ return undefined;
107
+ try {
108
+ if (statSync(file).size > MAX_EVENT_BYTES)
109
+ return undefined;
110
+ return JSON.parse(readFileSync(file, "utf-8"));
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ }
116
+ /**
117
+ * The key variables that hold a value, by their fixed names in upper case. A
118
+ * blank value is not a key: a pull request from a fork gets every secret as an
119
+ * empty string.
120
+ */
121
+ export function payerKeyVariables(env) {
122
+ const names = new Set();
123
+ for (const [name, value] of Object.entries(env)) {
124
+ const upper = name.toUpperCase();
125
+ if (DENIED_ENV_NAMES.includes(upper) && typeof value === "string" && value.trim() !== "")
126
+ names.add(upper);
127
+ }
128
+ return [...names];
129
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The rules for a mainnet job in GitHub Actions (spec B17.4).
3
+ *
4
+ * Inside one job, code that ran earlier as the runner's user can reach every
5
+ * later step: it can put a program of its own first on PATH, change files on
6
+ * disk, or leave a process running that reads the environment of the step
7
+ * that holds the key (and a GitHub-hosted runner's user has passwordless sudo).
8
+ * No check inside the job holds against such code, since that code can change
9
+ * the check. So these rules do not look for it: they refuse the workflows in
10
+ * which it would be there. A mainnet run in GitHub Actions is started by hand,
11
+ * on the default branch, on a GitHub-hosted runner (a fresh machine per job);
12
+ * it tests a deployed service, so no code of the service runs in the job; it
13
+ * runs where nothing was installed before Wasit; and the mainnet key is the
14
+ * only key variable set.
15
+ *
16
+ * They stop a wrong workflow, not a person or code that sets out to get past
17
+ * them. What holds against those is GitHub's: the mainnet key kept as the
18
+ * secret of a GitHub environment limited to the default branch, with a
19
+ * required reviewer. Outside GitHub Actions none of these rules applies: on a
20
+ * builder's own machine the CLI may test a local service.
21
+ *
22
+ * The opt-in (`openMainnetOptIn`) calls {@link assertMainnetJob} whenever
23
+ * `GITHUB_ACTIONS` is true, before the lock is taken and anything is sent.
24
+ */
25
+ import { ConfigurationError } from "../errors.js";
26
+ export interface MainnetJob {
27
+ /** The process environment. */
28
+ readonly env: Readonly<Record<string, string | undefined>>;
29
+ /** The repository's default branch, from the event; undefined when it cannot be read. */
30
+ readonly defaultBranch: string | undefined;
31
+ /** The run's environment starts a service in the job (`service.start`). */
32
+ readonly startsService: boolean;
33
+ /** The run's `baseUrl`. */
34
+ readonly baseUrl: string;
35
+ /** Where a `node_modules` would show that something was installed before Wasit, with a label for the message. */
36
+ readonly installDirs: ReadonlyArray<{
37
+ readonly label: string;
38
+ readonly dir: string;
39
+ }>;
40
+ }
41
+ /** A job that may not make a mainnet run, with every rule it breaks. */
42
+ export declare class MainnetJobRefusedError extends ConfigurationError {
43
+ readonly refusals: readonly string[];
44
+ constructor(refusals: readonly string[]);
45
+ }
46
+ /**
47
+ * A host only this machine or its own network reaches, as `URL.hostname`
48
+ * writes it: a loopback, private, link-local or shared address, `localhost`,
49
+ * a single-label name, or a `.local` or `.internal` name.
50
+ */
51
+ export declare function isLocalHost(hostname: string): boolean;
52
+ /**
53
+ * Every rule of a mainnet job that `job` breaks, one clause each; empty when it
54
+ * breaks none, and always empty outside GitHub Actions. No key, and no event
55
+ * name, ref or path in an odd shape, is echoed.
56
+ */
57
+ export declare function mainnetJobRefusals(job: MainnetJob, exists?: (file: string) => boolean): string[];
58
+ /** Throws {@link MainnetJobRefusedError} when `job` breaks any rule of a mainnet job. */
59
+ export declare function assertMainnetJob(job: MainnetJob, exists?: (file: string) => boolean): void;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The rules for a mainnet job in GitHub Actions (spec B17.4).
3
+ *
4
+ * Inside one job, code that ran earlier as the runner's user can reach every
5
+ * later step: it can put a program of its own first on PATH, change files on
6
+ * disk, or leave a process running that reads the environment of the step
7
+ * that holds the key (and a GitHub-hosted runner's user has passwordless sudo).
8
+ * No check inside the job holds against such code, since that code can change
9
+ * the check. So these rules do not look for it: they refuse the workflows in
10
+ * which it would be there. A mainnet run in GitHub Actions is started by hand,
11
+ * on the default branch, on a GitHub-hosted runner (a fresh machine per job);
12
+ * it tests a deployed service, so no code of the service runs in the job; it
13
+ * runs where nothing was installed before Wasit; and the mainnet key is the
14
+ * only key variable set.
15
+ *
16
+ * They stop a wrong workflow, not a person or code that sets out to get past
17
+ * them. What holds against those is GitHub's: the mainnet key kept as the
18
+ * secret of a GitHub environment limited to the default branch, with a
19
+ * required reviewer. Outside GitHub Actions none of these rules applies: on a
20
+ * builder's own machine the CLI may test a local service.
21
+ *
22
+ * The opt-in (`openMainnetOptIn`) calls {@link assertMainnetJob} whenever
23
+ * `GITHUB_ACTIONS` is true, before the lock is taken and anything is sent.
24
+ */
25
+ import { existsSync } from "node:fs";
26
+ import path from "node:path";
27
+ import { DENIED_ENV_NAMES } from "../denied-env.js";
28
+ import { ConfigurationError } from "../errors.js";
29
+ import { inGithubActions } from "./ci-event.js";
30
+ /** The variable a mainnet run reads its key from (spec B5). */
31
+ const MAINNET_KEY = "WASIT_MAINNET_PAYER_SECRET";
32
+ /** An event name as GitHub writes them; anything else is never echoed. */
33
+ const EVENT_NAME = /^[a-z_]{1,64}$/;
34
+ /** A branch or tag ref, and a branch name, in a shape that is safe to echo. */
35
+ const REF = /^refs\/(heads|tags)\/[A-Za-z0-9._/-]{1,200}$/;
36
+ const BRANCH = /^[A-Za-z0-9._/-]{1,200}$/;
37
+ /** A job that may not make a mainnet run, with every rule it breaks. */
38
+ export class MainnetJobRefusedError extends ConfigurationError {
39
+ refusals;
40
+ constructor(refusals) {
41
+ super(`This job may not make a mainnet run: ${refusals.join("; ")}. Nothing was started, sent or signed. These ` +
42
+ `rules stop a wrong workflow, not code that already ran in this job: keep the mainnet key as the secret of ` +
43
+ `a GitHub environment limited to the default branch, with a required reviewer.`);
44
+ this.name = "MainnetJobRefusedError";
45
+ this.refusals = refusals;
46
+ }
47
+ }
48
+ function nonEmpty(value) {
49
+ return typeof value === "string" && value.trim() !== "";
50
+ }
51
+ function listed(names) {
52
+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
53
+ }
54
+ function isLocalIpv4(a, b) {
55
+ return (a === 127 || // loopback
56
+ a === 0 ||
57
+ a === 10 ||
58
+ (a === 172 && b >= 16 && b <= 31) ||
59
+ (a === 192 && b === 168) ||
60
+ (a === 169 && b === 254) || // link-local
61
+ (a === 100 && b >= 64 && b <= 127) // shared address space
62
+ );
63
+ }
64
+ function isLocalIpv6(address) {
65
+ if (address === "::1" || address === "::")
66
+ return true;
67
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
68
+ if (mappedHex !== null) {
69
+ const high = Number.parseInt(mappedHex[1], 16);
70
+ return isLocalIpv4(high >> 8, high & 0xff);
71
+ }
72
+ const mappedDotted = /^::ffff:(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(address);
73
+ if (mappedDotted !== null)
74
+ return isLocalIpv4(Number(mappedDotted[1]), Number(mappedDotted[2]));
75
+ const first = Number.parseInt(address.split(":")[0] || "0", 16);
76
+ return (first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80; // unique local, link-local
77
+ }
78
+ /**
79
+ * A host only this machine or its own network reaches, as `URL.hostname`
80
+ * writes it: a loopback, private, link-local or shared address, `localhost`,
81
+ * a single-label name, or a `.local` or `.internal` name.
82
+ */
83
+ export function isLocalHost(hostname) {
84
+ const host = hostname.toLowerCase().replace(/\.$/, "");
85
+ if (host.startsWith("[") && host.endsWith("]"))
86
+ return isLocalIpv6(host.slice(1, -1));
87
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
88
+ if (v4 !== null)
89
+ return isLocalIpv4(Number(v4[1]), Number(v4[2]));
90
+ if (!host.includes("."))
91
+ return true;
92
+ return host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
93
+ }
94
+ /**
95
+ * Every rule of a mainnet job that `job` breaks, one clause each; empty when it
96
+ * breaks none, and always empty outside GitHub Actions. No key, and no event
97
+ * name, ref or path in an odd shape, is echoed.
98
+ */
99
+ export function mainnetJobRefusals(job, exists = existsSync) {
100
+ if (!inGithubActions(job.env))
101
+ return [];
102
+ const refusals = [];
103
+ const event = job.env["GITHUB_EVENT_NAME"] ?? "";
104
+ if (event !== "workflow_dispatch") {
105
+ refusals.push(`a mainnet run is started by hand (workflow_dispatch), and this run's event is ${EVENT_NAME.test(event) ? event : "another event"}`);
106
+ }
107
+ if (job.env["RUNNER_ENVIRONMENT"] !== "github-hosted") {
108
+ refusals.push("a mainnet run needs a GitHub-hosted runner (RUNNER_ENVIRONMENT github-hosted): a self-hosted runner keeps " +
109
+ "files and processes between jobs");
110
+ }
111
+ const ref = job.env["GITHUB_REF"] ?? "";
112
+ if (job.defaultBranch === undefined || !BRANCH.test(job.defaultBranch)) {
113
+ refusals.push("the repository's default branch could not be read from the event, so this run cannot be shown to be on it");
114
+ }
115
+ else if (ref !== `refs/heads/${job.defaultBranch}`) {
116
+ refusals.push(`a mainnet run runs on the default branch (${job.defaultBranch}), and this run's ref is ${REF.test(ref) ? ref : "another ref"}`);
117
+ }
118
+ if (job.startsService) {
119
+ refusals.push("the environment starts a service in the job (service.start): a mainnet run tests a deployed service, so that " +
120
+ "no code of the service runs in the job that holds the key");
121
+ }
122
+ let host;
123
+ try {
124
+ host = new URL(job.baseUrl).hostname;
125
+ }
126
+ catch {
127
+ host = undefined;
128
+ }
129
+ if (host === undefined || isLocalHost(host)) {
130
+ refusals.push("baseUrl is a local address (a loopback, private or single-label host): a mainnet run tests a deployed service");
131
+ }
132
+ for (const { label, dir } of job.installDirs) {
133
+ if (exists(path.join(dir, "node_modules"))) {
134
+ refusals.push(`a node_modules directory is in ${label}: code was installed in this job before Wasit, and a mainnet job ` +
135
+ `holds only checkout, setup-node and Wasit`);
136
+ }
137
+ }
138
+ const others = DENIED_ENV_NAMES.filter((name) => name !== MAINNET_KEY && nonEmpty(job.env[name]));
139
+ if (others.length > 0) {
140
+ refusals.push(`only ${MAINNET_KEY} may be set on a mainnet run, and ${listed(others)} ${others.length === 1 ? "is" : "are"} set too`);
141
+ }
142
+ return refusals;
143
+ }
144
+ /** Throws {@link MainnetJobRefusedError} when `job` breaks any rule of a mainnet job. */
145
+ export function assertMainnetJob(job, exists = existsSync) {
146
+ const refusals = mainnetJobRefusals(job, exists);
147
+ if (refusals.length > 0)
148
+ throw new MainnetJobRefusedError(refusals);
149
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The two reads a mainnet run makes on public Horizon (spec B5 point 4,
3
+ * B17.2, B17.12), each a second source beside the run's RPC:
4
+ *
5
+ * - the latest ledger, which the RPC's latest ledger (the anchor of every
6
+ * signature's expiration bound) must be near;
7
+ * - the payer's balances, which the RPC's USDC balance must equal, and which
8
+ * the run ledger records before and after the run (USDC and XLM).
9
+ *
10
+ * Both fail closed: an error status, a redirect (never followed), a body that
11
+ * is not JSON or is too large, a Horizon of another network, or an answer that
12
+ * cannot be read plainly is a {@link MainnetPlanRefusedError}. A message names
13
+ * Horizon by its origin only.
14
+ *
15
+ * Read-only: no key, nothing signed or sent but two GET requests. The plan of a
16
+ * mainnet run (L1) and its close (L4) call them.
17
+ */
18
+ import { type HorizonBalances } from "./mainnet-plan.js";
19
+ /**
20
+ * The latest ledger Horizon at `base` has ingested, from its root, when it
21
+ * says it serves Stellar mainnet.
22
+ */
23
+ export declare function readHorizonLatestLedger(base: string): Promise<number>;
24
+ /**
25
+ * The USDC (mainnet USDC's trustline; 0 without one) and XLM balances of the
26
+ * account `payer` on Horizon at `base`, in base units. An address that is not
27
+ * a Stellar account is refused before any request; so is an account Horizon
28
+ * does not have.
29
+ */
30
+ export declare function readHorizonAccount(base: string, payer: string): Promise<HorizonBalances>;