@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,62 @@
1
+ /**
2
+ * The lock file of a mainnet run (spec B4, B17.5).
3
+ *
4
+ * The caps hold one run to $5 (`budget.ts`). A second mainnet run started on
5
+ * the same machine while one is open would get its own $5. So a mainnet run
6
+ * takes this lock in its ledger's folder before it reads its payer's balance,
7
+ * and a run that finds a lock there does not start.
8
+ *
9
+ * Any file in the lock's place refuses the run, whoever left it: a run that is
10
+ * still open; a run that was stopped or crashed, whose authorizations may still
11
+ * be open, so a person reads its ledger before deleting the file; or a file
12
+ * that is not a lock Wasit can read. No run takes over or deletes another's
13
+ * lock. The file is created exclusively (it fails when anything is at its path,
14
+ * a symbolic link included), so two runs started at once cannot both take it.
15
+ *
16
+ * What it does not see: a run on another machine or runner, and a run whose
17
+ * ledger is in another folder (spec B4). The payer account's $10
18
+ * (`mainnet-payer.ts`) is the limit there.
19
+ *
20
+ * The opt-in (`openMainnetOptIn`) takes the lock before L1, and its close
21
+ * (`closeMainnetRun`) releases it when the run has ended.
22
+ */
23
+ import { ConfigurationError } from "../errors.js";
24
+ /** The lock's name in the ledger's folder. */
25
+ export declare const MAINNET_RUN_LOCK_FILE = "wasit-mainnet.lock";
26
+ /** Who holds the lock a run found. */
27
+ export type LockHolder =
28
+ /** A process that is still running. */
29
+ "running"
30
+ /** A process that has ended without releasing it. */
31
+ | "gone"
32
+ /** The file is not a lock Wasit can read. */
33
+ | "unknown";
34
+ /**
35
+ * A mainnet run does not start: a lock is already in its ledger's folder. A
36
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
37
+ */
38
+ export declare class MainnetRunLockedError extends ConfigurationError {
39
+ readonly lockPath: string;
40
+ readonly holder: LockHolder;
41
+ constructor(lockPath: string, holder: LockHolder, message: string);
42
+ }
43
+ /** A lock this run holds. */
44
+ export interface MainnetRunLock {
45
+ /** The lock file. */
46
+ readonly path: string;
47
+ /**
48
+ * Deletes the lock file when it is still this run's. Safe to call more than
49
+ * once, and after the file is gone. It is also called when the process exits
50
+ * (`exit`), but not when the process is killed: then the file stays, and the
51
+ * next run is refused until a person deletes it.
52
+ */
53
+ release(): void;
54
+ }
55
+ /**
56
+ * Takes the lock of a mainnet run in `dir`, the folder of the run's ledger,
57
+ * creating the folder when it is missing.
58
+ *
59
+ * @throws {MainnetRunLockedError} When anything is already at the lock's path.
60
+ * @throws {ConfigurationError} When the lock cannot be created.
61
+ */
62
+ export declare function acquireMainnetRunLock(dir: string): MainnetRunLock;
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The lock file of a mainnet run (spec B4, B17.5).
3
+ *
4
+ * The caps hold one run to $5 (`budget.ts`). A second mainnet run started on
5
+ * the same machine while one is open would get its own $5. So a mainnet run
6
+ * takes this lock in its ledger's folder before it reads its payer's balance,
7
+ * and a run that finds a lock there does not start.
8
+ *
9
+ * Any file in the lock's place refuses the run, whoever left it: a run that is
10
+ * still open; a run that was stopped or crashed, whose authorizations may still
11
+ * be open, so a person reads its ledger before deleting the file; or a file
12
+ * that is not a lock Wasit can read. No run takes over or deletes another's
13
+ * lock. The file is created exclusively (it fails when anything is at its path,
14
+ * a symbolic link included), so two runs started at once cannot both take it.
15
+ *
16
+ * What it does not see: a run on another machine or runner, and a run whose
17
+ * ledger is in another folder (spec B4). The payer account's $10
18
+ * (`mainnet-payer.ts`) is the limit there.
19
+ *
20
+ * The opt-in (`openMainnetOptIn`) takes the lock before L1, and its close
21
+ * (`closeMainnetRun`) releases it when the run has ended.
22
+ */
23
+ import { randomUUID } from "node:crypto";
24
+ import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
25
+ import path from "node:path";
26
+ import { ConfigurationError } from "../errors.js";
27
+ import { sanitizeText } from "../sanitize.js";
28
+ import { PER_RUN_CAP_USD, formatUsd, usdFromDollars } from "./budget.js";
29
+ /** The lock's name in the ledger's folder. */
30
+ export const MAINNET_RUN_LOCK_FILE = "wasit-mainnet.lock";
31
+ /** What the lock file says it is. */
32
+ const TAG = "mainnet-run-lock";
33
+ /** A lock Wasit writes is far smaller; a larger file is not read. */
34
+ const MAX_LOCK_BYTES = 4096;
35
+ /** A start time as `Date.toISOString` writes it; anything else is never echoed. */
36
+ const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
37
+ /** An error code as Node writes them; anything else is never echoed. */
38
+ const ERROR_CODE = /^E[A-Z]{2,20}$/;
39
+ /**
40
+ * A mainnet run does not start: a lock is already in its ledger's folder. A
41
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
42
+ */
43
+ export class MainnetRunLockedError extends ConfigurationError {
44
+ lockPath;
45
+ holder;
46
+ constructor(lockPath, holder, message) {
47
+ super(`${message} Nothing was signed.`);
48
+ this.name = "MainnetRunLockedError";
49
+ this.lockPath = lockPath;
50
+ this.holder = holder;
51
+ }
52
+ }
53
+ /** The lock at `file`, when it is a regular file Wasit wrote; undefined otherwise. */
54
+ function readLock(file) {
55
+ try {
56
+ const stat = lstatSync(file);
57
+ if (!stat.isFile() || stat.size > MAX_LOCK_BYTES)
58
+ return undefined;
59
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
60
+ if (typeof parsed !== "object" || parsed === null)
61
+ return undefined;
62
+ const { wasit, pid, startedAt, token } = parsed;
63
+ if (wasit !== TAG || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
64
+ return undefined;
65
+ if (typeof startedAt !== "string" || !ISO_TIME.test(startedAt) || typeof token !== "string")
66
+ return undefined;
67
+ return { pid, startedAt, token };
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ /** Whether process `pid` runs on this machine; undefined when that cannot be told. */
74
+ function isRunning(pid) {
75
+ try {
76
+ process.kill(pid, 0);
77
+ return true;
78
+ }
79
+ catch (error) {
80
+ const code = error.code;
81
+ if (code === "EPERM")
82
+ return true;
83
+ if (code === "ESRCH")
84
+ return false;
85
+ return undefined;
86
+ }
87
+ }
88
+ function lockedError(file) {
89
+ const shownFile = sanitizeText(file);
90
+ const lock = readLock(file);
91
+ const running = lock === undefined ? undefined : isRunning(lock.pid);
92
+ if (lock === undefined || running === undefined) {
93
+ return new MainnetRunLockedError(file, "unknown", `${shownFile} is there and is not a lock Wasit can read, so this mainnet run does not start. If no mainnet run ` +
94
+ `is open, read the latest ledger in that folder, wait until the last authorization in it has expired, then ` +
95
+ `delete ${shownFile}.`);
96
+ }
97
+ const holder = `process ${lock.pid}, started ${lock.startedAt}`;
98
+ if (running) {
99
+ return new MainnetRunLockedError(file, "running", `Another mainnet run (${holder}) holds ${shownFile}. One mainnet run at a time on this machine: the ` +
100
+ `${formatUsd(usdFromDollars(PER_RUN_CAP_USD))} cap holds each run, not two at once on one account. Wait until ` +
101
+ `it has ended.`);
102
+ }
103
+ return new MainnetRunLockedError(file, "gone", `${shownFile} was left by a mainnet run (${holder}) that is no longer running: it ended without releasing the ` +
104
+ `lock, and authorizations it signed may still be open. Read that run's ledger, wait until the last ` +
105
+ `authorization in it has expired, then delete ${shownFile}.`);
106
+ }
107
+ function notCreated(dir, error) {
108
+ const code = error?.code;
109
+ return new ConfigurationError(`The lock file of a mainnet run could not be created in ${sanitizeText(dir)}` +
110
+ `${typeof code === "string" && ERROR_CODE.test(code) ? ` (${code})` : ""}, so the run does not start. ` +
111
+ `Nothing was signed.`);
112
+ }
113
+ /**
114
+ * Takes the lock of a mainnet run in `dir`, the folder of the run's ledger,
115
+ * creating the folder when it is missing.
116
+ *
117
+ * @throws {MainnetRunLockedError} When anything is already at the lock's path.
118
+ * @throws {ConfigurationError} When the lock cannot be created.
119
+ */
120
+ export function acquireMainnetRunLock(dir) {
121
+ const file = path.join(dir, MAINNET_RUN_LOCK_FILE);
122
+ const token = randomUUID();
123
+ const content = `${JSON.stringify({ wasit: TAG, pid: process.pid, startedAt: new Date().toISOString(), token })}\n`;
124
+ try {
125
+ // Apart from the open: mkdir also says EEXIST, for a file where the folder should be.
126
+ mkdirSync(dir, { recursive: true });
127
+ }
128
+ catch (error) {
129
+ throw notCreated(dir, error);
130
+ }
131
+ let fd;
132
+ try {
133
+ fd = openSync(file, "wx", 0o600);
134
+ }
135
+ catch (error) {
136
+ if (error.code === "EEXIST")
137
+ throw lockedError(file);
138
+ throw notCreated(dir, error);
139
+ }
140
+ try {
141
+ writeSync(fd, content);
142
+ fsyncSync(fd);
143
+ }
144
+ catch (error) {
145
+ closeSync(fd);
146
+ try {
147
+ unlinkSync(file);
148
+ }
149
+ catch {
150
+ // nothing more to do: the run does not start either way
151
+ }
152
+ throw notCreated(dir, error);
153
+ }
154
+ closeSync(fd);
155
+ let released = false;
156
+ const release = () => {
157
+ if (released)
158
+ return;
159
+ released = true;
160
+ process.removeListener("exit", release);
161
+ if (readLock(file)?.token !== token)
162
+ return;
163
+ try {
164
+ unlinkSync(file);
165
+ }
166
+ catch {
167
+ // gone already
168
+ }
169
+ };
170
+ process.once("exit", release);
171
+ return { path: file, release };
172
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The signed-terms gate (spec B17.2): what the payer's key signs is checked,
3
+ * not only what the x402 client was asked to pay.
4
+ *
5
+ * L2 checks the terms Wasit hands the client: the pin, the plan, the $1 and
6
+ * the run's cap. On Stellar the client then builds the transfer by simulating
7
+ * it on the RPC and signs the authorization entries the simulation returns
8
+ * (`@x402/stellar` `ExactStellarScheme.createPaymentPayload`, through
9
+ * `AssembledTransaction.signAuthEntries`). The RPC chooses the contract, the
10
+ * function, the arguments, the sub-invocations, how many entries name the
11
+ * payer and the ledger the expiration is counted from. So the payer's signer
12
+ * is wrapped: each request to sign is decoded, and the key signs only when the
13
+ * preimage, which is exactly what the signature covers, authorizes
14
+ * `transfer(payer, payTo, amount)` on the asset that was checked, on the run's
15
+ * network, with no further call, once per payment, and expires no later than
16
+ * the payment's lifetime allows. Otherwise nothing is signed.
17
+ *
18
+ * What the cap then rests on: a signature authorizes that one transfer, once
19
+ * (its nonce), whoever submits it. The expiration bound keeps a signature from
20
+ * outliving the run; the cap does not depend on it.
21
+ */
22
+ /** What one payment may be signed for: the terms L2 checked and charged. */
23
+ export interface SigningTerms {
24
+ /** The run's CAIP-2 network. */
25
+ readonly network: string;
26
+ /** The payer's address, derived from the key Wasit holds. */
27
+ readonly payer: string;
28
+ /** The asset contract that was checked. */
29
+ readonly asset: string;
30
+ /** The payee that was checked. */
31
+ readonly payTo: string;
32
+ /** The amount charged to the run, in base units. */
33
+ readonly amount: string;
34
+ /** The latest ledger (the chain's unit) the signature may stay valid to. */
35
+ readonly maxExpiration: number;
36
+ }
37
+ /** A signature the gate let through, with the preimage it covers (base64 XDR). */
38
+ export interface SignedRecord {
39
+ readonly preimage: string;
40
+ readonly signature: Buffer;
41
+ }
42
+ /**
43
+ * One payment's permission to sign. `preparePayment` arms it with the terms
44
+ * it checked, right before the client builds the payment; the payer's signer
45
+ * takes the terms once. A request to sign before it is armed, or a second one
46
+ * in the same payment, is refused.
47
+ */
48
+ export declare class SigningGate {
49
+ #private;
50
+ arm(terms: SigningTerms): void;
51
+ /** The terms it was armed with, if any. */
52
+ get terms(): SigningTerms | undefined;
53
+ /** Called by the signer before it signs: the terms, once. */
54
+ take(): SigningTerms;
55
+ /** Called by the signer after it signed. */
56
+ record(signed: SignedRecord): void;
57
+ /** The signature it let through, if any. */
58
+ get signed(): SignedRecord | undefined;
59
+ }
60
+ /**
61
+ * The ledger a signature the gate let through expires at, decoded from the
62
+ * preimage the key signed (spec B5: the expiry is read, never computed);
63
+ * undefined when it does not decode as the address credential's preimage.
64
+ */
65
+ export declare function expirationOfSigned(record: SignedRecord): number | undefined;
66
+ /**
67
+ * The run's first reading of the chain's latest unit (a ledger on Stellar),
68
+ * and when it was read on a monotonic clock. A signature made later may stay
69
+ * valid only for the units that can have closed since, plus its lifetime: so
70
+ * an RPC that answers a later ledger after this reading cannot stretch it.
71
+ */
72
+ export declare class SigningAnchor {
73
+ #private;
74
+ get reading(): {
75
+ readonly unit: number;
76
+ readonly at: number;
77
+ } | undefined;
78
+ /** Keeps the first reading only. `at` is `performance.now()` milliseconds. */
79
+ set(unit: number, at?: number): void;
80
+ /**
81
+ * The latest unit a signature made `now` may expire at, for a lifetime of
82
+ * `lifetimeSeconds`, with units of `unitSeconds` (the shortest a unit takes:
83
+ * a faster chain only tightens the bound) and 2 units of slack.
84
+ */
85
+ maxExpiration(unitSeconds: number, lifetimeSeconds: number, now?: number): number;
86
+ }
87
+ /**
88
+ * Throws, so that nothing is signed, unless the Soroban authorization preimage
89
+ * `preimage` (base64 XDR, as the SDK hands it to the signer) authorizes exactly
90
+ * `transfer(payer, payTo, amount)` on `asset`, on the run's network, with no
91
+ * sub-invocation, expiring no later than `maxExpiration`.
92
+ *
93
+ * Only the address credential's preimage is signed: the address-bound form
94
+ * (`AddressV2`, delegates) is refused, as is anything that does not decode.
95
+ */
96
+ export declare function checkStellarPreimage(preimage: string, terms: SigningTerms): void;
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The signed-terms gate (spec B17.2): what the payer's key signs is checked,
3
+ * not only what the x402 client was asked to pay.
4
+ *
5
+ * L2 checks the terms Wasit hands the client: the pin, the plan, the $1 and
6
+ * the run's cap. On Stellar the client then builds the transfer by simulating
7
+ * it on the RPC and signs the authorization entries the simulation returns
8
+ * (`@x402/stellar` `ExactStellarScheme.createPaymentPayload`, through
9
+ * `AssembledTransaction.signAuthEntries`). The RPC chooses the contract, the
10
+ * function, the arguments, the sub-invocations, how many entries name the
11
+ * payer and the ledger the expiration is counted from. So the payer's signer
12
+ * is wrapped: each request to sign is decoded, and the key signs only when the
13
+ * preimage, which is exactly what the signature covers, authorizes
14
+ * `transfer(payer, payTo, amount)` on the asset that was checked, on the run's
15
+ * network, with no further call, once per payment, and expires no later than
16
+ * the payment's lifetime allows. Otherwise nothing is signed.
17
+ *
18
+ * What the cap then rests on: a signature authorizes that one transfer, once
19
+ * (its nonce), whoever submits it. The expiration bound keeps a signature from
20
+ * outliving the run; the cap does not depend on it.
21
+ */
22
+ import { performance } from "node:perf_hooks";
23
+ import { Address, hash, scValToNative, xdr } from "@stellar/stellar-sdk";
24
+ import { networkPassphrase } from "../mpp/network.js";
25
+ import { PaymentGuardRefusedError, shown } from "./budget.js";
26
+ function refuse(message, options = {}) {
27
+ return new PaymentGuardRefusedError("signed-terms", message, options);
28
+ }
29
+ /**
30
+ * One payment's permission to sign. `preparePayment` arms it with the terms
31
+ * it checked, right before the client builds the payment; the payer's signer
32
+ * takes the terms once. A request to sign before it is armed, or a second one
33
+ * in the same payment, is refused.
34
+ */
35
+ export class SigningGate {
36
+ #terms;
37
+ #taken = false;
38
+ #signed;
39
+ arm(terms) {
40
+ if (this.#terms !== undefined)
41
+ throw new Error("A signing gate is armed once, for one payment.");
42
+ this.#terms = terms;
43
+ }
44
+ /** The terms it was armed with, if any. */
45
+ get terms() {
46
+ return this.#terms;
47
+ }
48
+ /** Called by the signer before it signs: the terms, once. */
49
+ take() {
50
+ if (this.#terms === undefined) {
51
+ throw refuse("The payer's key was asked to sign when Wasit expected no signature.");
52
+ }
53
+ if (this.#taken) {
54
+ throw refuse("The x402 client asked the payer's key for a second signature in one payment; Wasit signs one per payment.");
55
+ }
56
+ this.#taken = true;
57
+ return this.#terms;
58
+ }
59
+ /** Called by the signer after it signed. */
60
+ record(signed) {
61
+ if (this.#signed !== undefined)
62
+ throw new Error("A signing gate records one signature.");
63
+ this.#signed = signed;
64
+ }
65
+ /** The signature it let through, if any. */
66
+ get signed() {
67
+ return this.#signed;
68
+ }
69
+ }
70
+ /**
71
+ * The ledger a signature the gate let through expires at, decoded from the
72
+ * preimage the key signed (spec B5: the expiry is read, never computed);
73
+ * undefined when it does not decode as the address credential's preimage.
74
+ */
75
+ export function expirationOfSigned(record) {
76
+ try {
77
+ const decoded = xdr.HashIdPreimage.fromXDR(record.preimage, "base64");
78
+ if (decoded.switch().name !== "envelopeTypeSorobanAuthorization")
79
+ return undefined;
80
+ return decoded.sorobanAuthorization().signatureExpirationLedger();
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
86
+ /**
87
+ * The run's first reading of the chain's latest unit (a ledger on Stellar),
88
+ * and when it was read on a monotonic clock. A signature made later may stay
89
+ * valid only for the units that can have closed since, plus its lifetime: so
90
+ * an RPC that answers a later ledger after this reading cannot stretch it.
91
+ */
92
+ export class SigningAnchor {
93
+ #reading;
94
+ get reading() {
95
+ return this.#reading;
96
+ }
97
+ /** Keeps the first reading only. `at` is `performance.now()` milliseconds. */
98
+ set(unit, at = performance.now()) {
99
+ if (this.#reading === undefined)
100
+ this.#reading = { unit, at };
101
+ }
102
+ /**
103
+ * The latest unit a signature made `now` may expire at, for a lifetime of
104
+ * `lifetimeSeconds`, with units of `unitSeconds` (the shortest a unit takes:
105
+ * a faster chain only tightens the bound) and 2 units of slack.
106
+ */
107
+ maxExpiration(unitSeconds, lifetimeSeconds, now = performance.now()) {
108
+ const reading = this.#reading;
109
+ if (reading === undefined)
110
+ throw new Error("The anchor has no reading yet.");
111
+ if (typeof lifetimeSeconds !== "number" || !Number.isFinite(lifetimeSeconds) || lifetimeSeconds <= 0) {
112
+ throw refuse(`The payment's lifetime (${shown(lifetimeSeconds)} s) is not a positive number of seconds, so how long its ` +
113
+ `signature would stay valid cannot be bounded.`);
114
+ }
115
+ const elapsed = Math.max(0, now - reading.at);
116
+ return reading.unit + Math.ceil(elapsed / (unitSeconds * 1000)) + Math.ceil(lifetimeSeconds / unitSeconds) + 2;
117
+ }
118
+ }
119
+ const ASKED = "The authorization the x402 client asked the payer to sign";
120
+ function addressOf(value) {
121
+ if (value.switch().name !== "scvAddress")
122
+ return undefined;
123
+ try {
124
+ return Address.fromScVal(value).toString();
125
+ }
126
+ catch {
127
+ return undefined;
128
+ }
129
+ }
130
+ /**
131
+ * Throws, so that nothing is signed, unless the Soroban authorization preimage
132
+ * `preimage` (base64 XDR, as the SDK hands it to the signer) authorizes exactly
133
+ * `transfer(payer, payTo, amount)` on `asset`, on the run's network, with no
134
+ * sub-invocation, expiring no later than `maxExpiration`.
135
+ *
136
+ * Only the address credential's preimage is signed: the address-bound form
137
+ * (`AddressV2`, delegates) is refused, as is anything that does not decode.
138
+ */
139
+ export function checkStellarPreimage(preimage, terms) {
140
+ let decoded;
141
+ try {
142
+ decoded = xdr.HashIdPreimage.fromXDR(preimage, "base64");
143
+ }
144
+ catch {
145
+ throw refuse(`${ASKED} does not decode as a Soroban authorization.`);
146
+ }
147
+ if (decoded.switch().name !== "envelopeTypeSorobanAuthorization") {
148
+ throw refuse(`${ASKED} is a form of authorization Wasit does not sign (it signs the address credential only).`);
149
+ }
150
+ const authorization = decoded.sorobanAuthorization();
151
+ const networkId = hash(Buffer.from(networkPassphrase(terms.network)));
152
+ if (!Buffer.from(authorization.networkId()).equals(networkId)) {
153
+ throw refuse(`${ASKED} is for another network than this run's (${terms.network}).`);
154
+ }
155
+ const invocation = authorization.invocation();
156
+ const fn = invocation.function();
157
+ if (fn.switch().name !== "sorobanAuthorizedFunctionTypeContractFn") {
158
+ throw refuse(`${ASKED} is not a contract call.`);
159
+ }
160
+ const call = fn.contractFn();
161
+ let contract;
162
+ try {
163
+ contract = Address.fromScAddress(call.contractAddress()).toString();
164
+ }
165
+ catch {
166
+ throw refuse(`${ASKED} calls a contract whose address does not decode.`);
167
+ }
168
+ if (contract !== terms.asset) {
169
+ throw refuse(`${ASKED} calls the contract ${shown(contract)}, not the asset ${terms.asset} that was checked.`);
170
+ }
171
+ const name = call.functionName().toString();
172
+ if (name !== "transfer") {
173
+ throw refuse(`${ASKED} calls ${shown(name)} instead of transfer.`);
174
+ }
175
+ const args = call.args();
176
+ if (args.length !== 3) {
177
+ throw refuse(`${ASKED} gives transfer ${args.length} arguments instead of 3 (from, to, amount).`);
178
+ }
179
+ const from = addressOf(args[0]);
180
+ if (from !== terms.payer) {
181
+ throw refuse(`${ASKED} transfers from ${from === undefined ? "something that is not an address" : shown(from)}, not from the payer.`);
182
+ }
183
+ const to = addressOf(args[1]);
184
+ if (to !== terms.payTo) {
185
+ throw refuse(`${ASKED} pays ${to === undefined ? "something that is not an address" : shown(to)}, not ${terms.payTo}, ` +
186
+ `the payee that was checked.`);
187
+ }
188
+ if (!/^[1-9][0-9]*$/.test(terms.amount)) {
189
+ throw refuse(`The amount checked for this payment (${shown(terms.amount)}) is not a positive number of base units.`);
190
+ }
191
+ if (args[2].switch().name !== "scvI128") {
192
+ throw refuse(`${ASKED} gives the amount as ${args[2].switch().name}, not as the i128 of base units transfer takes.`);
193
+ }
194
+ const amount = scValToNative(args[2]);
195
+ if (amount !== BigInt(terms.amount)) {
196
+ throw refuse(`${ASKED} is for ${shown(String(amount))} base units, not the ${terms.amount} that was checked.`);
197
+ }
198
+ const further = invocation.subInvocations().length;
199
+ if (further !== 0) {
200
+ throw refuse(`${ASKED} also authorizes ${further} further call${further === 1 ? "" : "s"} beside the transfer.`);
201
+ }
202
+ const expiration = authorization.signatureExpirationLedger();
203
+ if (expiration > terms.maxExpiration) {
204
+ throw refuse(`${ASKED} stays valid until ledger ${expiration}, past ledger ${terms.maxExpiration}, the latest this ` +
205
+ `payment's lifetime allows.`);
206
+ }
207
+ }
package/dist/index.d.ts CHANGED
@@ -1,14 +1,54 @@
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 { ConfigWriteError, writeConfigText } from "./config-writer.js";
8
+ export type { ConfigWriteInput, ConfigWriteOptions, ConfigWriteResult, InitEndpointInput, InitEnvironmentInput, InitRejectInput, InitServiceInput, } from "./config-writer.js";
9
+ export { ROUTE_READ_TIMEOUT_MS, chooseOffer, describeOffer, interpretRouteAnswer, readRoute } from "./route-reader.js";
10
+ export type { OfferChoice, OfferWanted, ReadRouteOptions, RouteAnswer, RouteOffer, RouteProtocol, RouteReading, } from "./route-reader.js";
11
+ export { buildEndpointReport, buildRunReport, checkGroup, describeTotals, endpointOutcome, paymentGroupUnsupported, exitCodeForEndpoint, groupCounts, redactReport, redactValue, reportTotals, paymentChecksSkipped, skippedPaymentChecks, toGradedRun, } from "./report.js";
12
+ export type { CheckGroup, EndpointInput, EndpointOutcome, EndpointReport, GroupCounts, RunReport, RunReportInput, RunTotals, } from "./report.js";
13
+ export { readBuildCommit, readPackageVersion, readToolVersions } from "./versions.js";
14
+ export type { ToolVersions } from "./versions.js";
15
+ export { HISTORY_LIMIT, MAX_BASELINE_BYTES, ReportFormatError, baselineProblem, diffReports, findRegressions, parseRunReport, readBaseline, recentFailures, selectBaseline, serializeBaseline, updateHistory, } from "./baseline.js";
16
+ export type { Baseline, BaselineResult, Change, ChangeKind, History, RecentFailure, Regression, } from "./baseline.js";
17
+ export { runExitCode } from "./verdict.js";
18
+ export type { RunVerdict } from "./verdict.js";
19
+ export { COMMENT_MARKER, renderCheckRun, renderComment, renderNoReportCheckRun, renderNoReportComment, renderNoReportSummary, renderRunningComment, renderSummary, } from "./ci-report.js";
20
+ export type { CheckRunOutput, RunningCommentInput } from "./ci-report.js";
21
+ export type { CiReportInput } from "./ci-report.js";
22
+ export { DENIED_ENV_NAMES, deniedEnvValues, isDeniedEnvName, scrubEnv } from "./denied-env.js";
3
23
  export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js";
4
24
  export type { CheckCatalogueEntry, ProtocolId } from "./catalogue.js";
5
25
  export * from "./errors.js";
26
+ export { NETWORK_CLASSES, PaymentNetworkRefusedError, assertPaymentNetworkAllowed, networkClass, } from "./guard/networks.js";
27
+ export type { NetworkClass, PaymentProtocol } from "./guard/networks.js";
28
+ export { MainnetJobRefusedError, assertMainnetJob, isLocalHost, mainnetJobRefusals, type MainnetJob } from "./guard/ci-mainnet.js";
29
+ export { MAINNET_PAYER_MAX_BASE_UNITS, MAINNET_PAYER_MAX_USD, MainnetPayerRefusedError, assertMainnetPayerBalance, type MainnetPayerAccount, type MainnetPayerRefusal, } from "./guard/mainnet-payer.js";
30
+ export { MAINNET_RUN_LOCK_FILE, MainnetRunLockedError, acquireMainnetRunLock, type LockHolder, type MainnetRunLock, } from "./guard/run-lock.js";
31
+ export { MAINNET_ANCHOR_MAX_GAP_LEDGERS, MAINNET_MAX_TIMEOUT_SECONDS, MAINNET_USDC, MainnetPlanRefusedError, PUBNET_HORIZON_URL, assertAnchorNearHorizon, assertBalancesAgree, assertMainnetDecimals, assertMainnetOption, assertMainnetPin, horizonBalances, parseHorizonAmount, type ClassicAsset, type HorizonBalances, type MainnetOption, type MainnetPlanRefusal, } from "./guard/mainnet-plan.js";
32
+ export { readHorizonAccount, readHorizonLatestLedger } from "./guard/horizon.js";
33
+ export { RUN_LEDGER_FORMAT, RunLedger, RunLedgerError, ledgerConsistency, openAuthorizationsUntil, runLedgerFileName, type LedgerBalances, type LedgerConsistency, type LedgerEntry, type LedgerEntryHandle, type LedgerEntryState, type LedgerResult, type LedgerVerdict, type PaymentLedger, type RunLedgerHeader, } from "./guard/run-ledger.js";
34
+ export { RPC_LOCK_VARIABLE, describeRpcInUse, readRpcLock, rpcInUse } from "./guard/rpc-in-use.js";
35
+ export { RpcIdentityError, assertRpcServesNetwork } from "./guard/rpc-identity.js";
36
+ export type { RpcInUse, RpcSource } from "./guard/rpc-in-use.js";
37
+ export { githubDefaultBranch, inGithubActions, payerKeyVariables, paymentEventGate, readGithubEvent } from "./guard/ci-event.js";
38
+ export type { PaymentEventGate } from "./guard/ci-event.js";
39
+ export { PER_PAYMENT_CAP_USD, PER_RUN_CAP_USD, PaymentGuardRefusedError, RunBudget, formatUsd, } from "./guard/budget.js";
40
+ export type { GuardRefusal, PinTerms, PlannedSignature } from "./guard/budget.js";
41
+ export { describePlan, mainnetFirstLine, mainnetOpeningLine, planMainnetDryRun, planX402Run } from "./x402/plan.js";
42
+ export type { EndpointPlan, EndpointPlanStatus, MainnetDryRunOptions, MainnetFunding, MainnetReadings, PlannedOption, RunPlan, X402PlanOptions, } from "./x402/plan.js";
43
+ export { MAINNET_PAYER_KEY_ENV, MainnetRunRefusedError, closeMainnetRun, openMainnetOptIn, type MainnetCloseOptions, type MainnetCloseResult, type MainnetOptInInput, type MainnetRunRefusal, } from "./guard/mainnet-run.js";
44
+ export type { MainnetFrontEnd, MainnetOptIn } from "./guard/optin.js";
6
45
  export * from "./x402/simulator.js";
7
46
  export * from "./mpp/channel.js";
8
47
  export * from "./mpp/charge.js";
9
48
  export * from "./mpp/charge-suite.js";
10
49
  export * from "./mpp/suite.js";
11
- export { createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, testnetUsdcAsset, TESTNET_USDC_ISSUER, } from "./wallet.js";
12
- export type { AssetBalance, FriendbotOutcome, GeneratedCommitmentKey, GeneratedWallet, WalletStatus, } from "./wallet.js";
50
+ export { MPP_CHARGE_SCHEME, assertMppPaymentRpc, combinePaymentPlan, describePaymentPlan, planMppChargeEndpoint, planPaymentRun, plannedChargeOf, type MppChargePlanInput, type PaymentRunPlanOptions, } from "./mpp/plan.js";
51
+ export { addTestnetUsdc, createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, swapQuoteFrom, testnetUsdcAsset, TESTNET_SWAP_XLM, TESTNET_USDC_ISSUER, usdcSetupTransaction, } from "./wallet.js";
52
+ export type { AssetBalance, FriendbotOutcome, GeneratedCommitmentKey, GeneratedWallet, SwapPathRecord, UsdcSetupOutcome, UsdcSwapQuote, WalletStatus, } from "./wallet.js";
13
53
  export { paymentChainFor, paymentNetworks } from "./x402/chains/index.js";
14
54
  export type { PaymentChain } from "./x402/chains/index.js";
package/dist/index.js CHANGED
@@ -1,16 +1,56 @@
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 config writer of `wasit init`: data that is certain in, a config `wasit run` accepts out.
7
+ export { ConfigWriteError, writeConfigText } from "./config-writer.js";
8
+ // What `wasit init` reads from a route: one unpaid request, and the one way to pay it writes.
9
+ export { ROUTE_READ_TIMEOUT_MS, chooseOffer, describeOffer, interpretRouteAnswer, readRoute } from "./route-reader.js";
10
+ // The run report, the endpoint outcome and the versions a result names.
11
+ export { buildEndpointReport, buildRunReport, checkGroup, describeTotals, endpointOutcome, paymentGroupUnsupported, exitCodeForEndpoint, groupCounts, redactReport, redactValue, reportTotals, paymentChecksSkipped, skippedPaymentChecks, toGradedRun, } from "./report.js";
12
+ export { readBuildCommit, readPackageVersion, readToolVersions } from "./versions.js";
13
+ // The baseline of the default branch, the diff against it, and the exit rule of a run.
14
+ export { HISTORY_LIMIT, MAX_BASELINE_BYTES, ReportFormatError, baselineProblem, diffReports, findRegressions, parseRunReport, readBaseline, recentFailures, selectBaseline, serializeBaseline, updateHistory, } from "./baseline.js";
15
+ export { runExitCode } from "./verdict.js";
16
+ // The pull request comment and the job summary.
17
+ export { COMMENT_MARKER, renderCheckRun, renderComment, renderNoReportCheckRun, renderNoReportComment, renderNoReportSummary, renderRunningComment, renderSummary, } from "./ci-report.js";
18
+ // Variables kept away from a service Wasit starts, and values kept out of output.
19
+ export { DENIED_ENV_NAMES, deniedEnvValues, isDeniedEnvName, scrubEnv } from "./denied-env.js";
2
20
  export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js";
3
21
  export * from "./errors.js";
22
+ // L0, the network guard every signing entry point runs.
23
+ export { NETWORK_CLASSES, PaymentNetworkRefusedError, assertPaymentNetworkAllowed, networkClass, } from "./guard/networks.js";
24
+ export { MainnetJobRefusedError, assertMainnetJob, isLocalHost, mainnetJobRefusals } from "./guard/ci-mainnet.js";
25
+ // The mainnet payer's $10 and the lock of a mainnet run (spec B17.5): rules that only refuse; the opt-in and its plan call them.
26
+ export { MAINNET_PAYER_MAX_BASE_UNITS, MAINNET_PAYER_MAX_USD, MainnetPayerRefusedError, assertMainnetPayerBalance, } from "./guard/mainnet-payer.js";
27
+ export { MAINNET_RUN_LOCK_FILE, MainnetRunLockedError, acquireMainnetRunLock, } from "./guard/run-lock.js";
28
+ // L1's mainnet rules and the two reads on public Horizon (spec B3, B4, B17.2): rules that only refuse; the plan and the close call them.
29
+ export { MAINNET_ANCHOR_MAX_GAP_LEDGERS, MAINNET_MAX_TIMEOUT_SECONDS, MAINNET_USDC, MainnetPlanRefusedError, PUBNET_HORIZON_URL, assertAnchorNearHorizon, assertBalancesAgree, assertMainnetDecimals, assertMainnetOption, assertMainnetPin, horizonBalances, parseHorizonAmount, } from "./guard/mainnet-plan.js";
30
+ export { readHorizonAccount, readHorizonLatestLedger } from "./guard/horizon.js";
31
+ // The run ledger (spec B5): every signature's intent written before the key signs, then its outcome.
32
+ export { RUN_LEDGER_FORMAT, RunLedger, RunLedgerError, ledgerConsistency, openAuthorizationsUntil, runLedgerFileName, } from "./guard/run-ledger.js";
33
+ // Which RPC a result read the chain through, and the MCP server's start-up RPC lock (D-023c).
34
+ export { RPC_LOCK_VARIABLE, describeRpcInUse, readRpcLock, rpcInUse } from "./guard/rpc-in-use.js";
35
+ export { RpcIdentityError, assertRpcServesNetwork } from "./guard/rpc-identity.js";
36
+ // Which GitHub events may run the payment tier (D-022a), and which key variables are set.
37
+ export { githubDefaultBranch, inGithubActions, payerKeyVariables, paymentEventGate, readGithubEvent } from "./guard/ci-event.js";
38
+ // L1 and L2: the plan, and the caps every signature is charged against.
39
+ export { PER_PAYMENT_CAP_USD, PER_RUN_CAP_USD, PaymentGuardRefusedError, RunBudget, formatUsd, } from "./guard/budget.js";
40
+ export { describePlan, mainnetFirstLine, mainnetOpeningLine, planMainnetDryRun, planX402Run } from "./x402/plan.js";
41
+ // The mainnet opt-in (spec B5): made by openMainnetOptIn only, for one run. The type is exported, the class is not.
42
+ export { MAINNET_PAYER_KEY_ENV, MainnetRunRefusedError, closeMainnetRun, openMainnetOptIn, } from "./guard/mainnet-run.js";
4
43
  export * from "./x402/simulator.js";
5
44
  export * from "./mpp/channel.js";
6
45
  export * from "./mpp/charge.js";
7
46
  export * from "./mpp/charge-suite.js";
8
47
  export * from "./mpp/suite.js";
48
+ export { MPP_CHARGE_SCHEME, assertMppPaymentRpc, combinePaymentPlan, describePaymentPlan, planMppChargeEndpoint, planPaymentRun, plannedChargeOf, } from "./mpp/plan.js";
9
49
  // Wallet tooling is exported by name rather than with `export *`: it is a
10
50
  // convenience layer for setting up testnet keys, not part of the check
11
51
  // surface, and naming each entry keeps the rest of wallet.ts free to change
12
52
  // without that being a breaking change to @wasit-dev/core.
13
- export { createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, testnetUsdcAsset, TESTNET_USDC_ISSUER, } from "./wallet.js";
53
+ export { addTestnetUsdc, createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, swapQuoteFrom, testnetUsdcAsset, TESTNET_SWAP_XLM, TESTNET_USDC_ISSUER, usdcSetupTransaction, } from "./wallet.js";
14
54
  // Which networks the x402 payment checks pay on, and which payer key each
15
55
  // reads: front ends pick the key by the run's network.
16
56
  export { paymentChainFor, paymentNetworks } from "./x402/chains/index.js";