nirium 0.15.0 → 0.16.0
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.
- package/README.md +77 -11
- package/dist/index.d.ts +27 -0
- package/dist/index.js +78 -15
- package/dist/x402-policy.d.ts +178 -0
- package/dist/x402-policy.js +334 -0
- package/dist/x402-spend-cap.d.ts +65 -0
- package/dist/x402-spend-cap.js +129 -0
- package/dist/x402serve-smoke.test.js +10 -2
- package/package.json +9 -6
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Autonomous treasury and agentic-payments infrastructure for **Nirium Protocol** on Stellar/Soroban.
|
|
4
4
|
|
|
5
|
-
Nirium agents rebalance USDC ↔ CETES (tokenized Mexican T-bills via Etherfuse) 24/7 without human intervention. Built for developers who want to integrate autonomous treasury management, agentic payments
|
|
5
|
+
Nirium agents rebalance USDC ↔ CETES (tokenized Mexican T-bills via Etherfuse) 24/7 without human intervention. Built for developers who want to integrate autonomous treasury management, agentic payments with x402 (in both directions: paying for other APIs with `initX402()` and charging for your own with `x402Serve()`), an experimental MPP Charge client, and real-time market data into their applications.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -61,7 +61,7 @@ agent.subscribe((signal) => {
|
|
|
61
61
|
| Admin | `configureLLM()` |
|
|
62
62
|
| WebSocket | `subscribe()`, `onLog()`, `disconnect()` |
|
|
63
63
|
| x402 Payments | `initX402()`, `x402Fetch()` |
|
|
64
|
-
| MPP
|
|
64
|
+
| MPP Charge client (experimental, see below) | `initMpp()`, `mppFetch()` |
|
|
65
65
|
|
|
66
66
|
## Authentication
|
|
67
67
|
|
|
@@ -93,18 +93,84 @@ const response = await agent.x402Fetch('https://nirium-agent.fly.dev/api/v1/prem
|
|
|
93
93
|
const data = await response.json();
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
#### Per-payment cap
|
|
97
|
+
|
|
98
|
+
`@x402/core` 2.23.0 and later refuse any payment above a default cap of **$1** per request (a default asset such as USDC), before anything is signed. `x402Fetch()` now says so with an `X402SpendCapError` instead of a generic error:
|
|
99
|
+
|
|
97
100
|
```typescript
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
101
|
+
import { X402SpendCapError } from 'nirium';
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
await agent.x402Fetch(url);
|
|
105
|
+
} catch (e) {
|
|
106
|
+
if (e instanceof X402SpendCapError) {
|
|
107
|
+
console.log(e.formattedAmount, e.cap, e.signerCalled); // '2 USDC' '$1' false
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The error carries `url`, `amount` (atomic units, the cheapest offer when the server lists several), `formattedAmount`, `asset`, `network` and `cap`, and `signerCalled` is always `false`: nothing was signed or sent. The cap is enforced by `@x402/core` and cannot be changed from `initX402()` yet. Other `spendControls` rejections (for example a non-default asset) still surface as the original error.
|
|
113
|
+
|
|
114
|
+
#### Pre-sign policy hook (experimental)
|
|
115
|
+
|
|
116
|
+
Pass `policy` to `initX402()` and every `x402Fetch()` asks your policy before anything is signed. The question is asked after the Stellar authorization is built, so the policy sees exactly what would be signed: amount, destination, asset, nonce, expiration ledger and network, decoded from the bytes.
|
|
117
|
+
|
|
118
|
+
**Experimental, new in 0.16.0.** The shape of `policy` (the context object, the outcomes, the records `onDecision` receives) can still change in a minor release before 1.0.0. Its scope is the agent-side cases that [#96](https://github.com/nirium-protocol/nirium/issues/96) groups as G1 (they come from the harness of @CodeDeityX), and nothing beyond them. What it does not cover is listed in the last paragraph of this section: code in the same process that holds the raw signer (L02 in that discussion), and pending-capacity reservation (L01: concurrent requests that observe the same remaining capacity). Neither is solved.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
import { X402PolicyError } from 'nirium';
|
|
122
|
+
|
|
123
|
+
agent.initX402({
|
|
124
|
+
signer: walletSigner,
|
|
125
|
+
network: 'stellar:pubnet',
|
|
126
|
+
policy: {
|
|
127
|
+
evaluate: async (ctx) => {
|
|
128
|
+
const ok = BigInt(ctx.authorization.amount) <= myLimit;
|
|
129
|
+
return ok
|
|
130
|
+
? { decision: 'ALLOW', contextHash: ctx.contextHash, policyVersion: 'v7', expiresAt: Date.now() + 2_000 }
|
|
131
|
+
: { decision: 'DENY', reason: 'over limit' };
|
|
132
|
+
},
|
|
133
|
+
// Optional: the policy version in force right now.
|
|
134
|
+
currentVersion: async () => myPolicyStore.version(),
|
|
135
|
+
},
|
|
102
136
|
});
|
|
103
137
|
|
|
104
|
-
|
|
105
|
-
|
|
138
|
+
try {
|
|
139
|
+
await agent.x402Fetch(url);
|
|
140
|
+
} catch (e) {
|
|
141
|
+
if (e instanceof X402PolicyError) console.log(e.outcome); // DENY, WAIT, TIMEOUT, STALE, ...
|
|
142
|
+
}
|
|
106
143
|
```
|
|
107
144
|
|
|
145
|
+
Only an `ALLOW` that echoes this authorization's `contextHash`, and is still valid, reaches the signer. Everything else signs nothing: `DENY`, `WAIT`, an exception, no answer before the deadline (`timeoutMs`, default 5 s, never more than half the payment's `maxTimeoutSeconds`), a malformed answer, an `ALLOW` past its `expiresAt`, a signer whose address changed while the policy was being asked, or a clock (`now`) that does not return a finite number (`CLOCK_INVALID`). Without `policy`, `x402Fetch()` behaves exactly as before.
|
|
146
|
+
|
|
147
|
+
**Stale ALLOW.** With `currentVersion` set, it is read after the `ALLOW` and right before signing, and the `ALLOW` signs only if its `policyVersion` matches. A rejected, empty or late read signs nothing. This check is **not atomic with signing**: the version can change after it is read, or while the signer runs. It narrows the window to the synchronous step between the read and the signer call; it does not close it. `expiresAt` is checked again after the read.
|
|
148
|
+
|
|
149
|
+
**Receipts (`onDecision`).** A payment whose `ALLOW` is accepted produces an `ALLOWED` record. `ALLOWED` does **not** mean every check has passed: it is a notice, sent before the policy-version read and the final clock and identity checks. What follows it is either a refusal from those checks (`STALE`, `EXPIRED`, `TIMEOUT`, `CLOCK_INVALID`, `SIGNER_CHANGED`, ...) or the signer's result: `SIGNED` (the signer returned a signature) or `SIGNER_ERROR` (it rejected, threw, or returned no `signedAuthEntry`; its own error is rethrown untouched). `SIGNED` therefore means a signature exists. The observer cannot change the outcome. A synchronous throw from it is swallowed. If it returns a promise (or any thenable), that is not awaited, so it cannot delay a payment, and its rejection is swallowed so it never becomes an unhandled rejection. It runs before the final clock and identity checks, so what it changes there is detected.
|
|
150
|
+
|
|
151
|
+
**Rejected before the policy is consulted.** An authorization that is not a single `transfer(from, to, amount)` matching the selected payment requirements (asset, destination, amount, network, no sub-invocations, `from` equal to the signer) is refused without calling `evaluate`. A CAP-71 preimage must be bound to the signer's own address.
|
|
152
|
+
|
|
153
|
+
**Signature check.** The hook only checks that the signer returned a non-empty `signedAuthEntry`; it does not verify the signature itself. That check comes from `@stellar/stellar-sdk`: `authorizeEntry` verifies the signature against sha256 of the preimage before it enters the transaction (verified in 16.3.0, the version this package requires). A signature over different bytes, or by a different key, never reaches the merchant; a test in this package pins that.
|
|
154
|
+
|
|
155
|
+
**What this does not do.** It is a check on the agent side, not account-level enforcement: code in the same process that holds the raw signer can still call it directly (the L02 limit in #96; so can code that replaces its `signAuthEntry`, which is looked up at call time), and nothing on-chain enforces the policy. It does not solve pending-capacity reservation (L01 in #96: concurrent requests that observe the same remaining capacity): two calls evaluated at the same time can each fit a limit that together they exceed, and an aggregate cap has to be held by your policy. Discussed in [#96](https://github.com/nirium-protocol/nirium/issues/96), where @CodeDeityX laid out the agent-side cases this hook is built against.
|
|
156
|
+
|
|
157
|
+
### MPP Charge (experimental)
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
agent.initMpp({ secretKey: 'S...', mode: 'pull' }); // 'pull' (default) or 'push'
|
|
161
|
+
|
|
162
|
+
const response = await agent.mppFetch('https://your-mpp-server.example/resource');
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`initMpp()` builds an MPP Charge client: the server answers `402` with a challenge, the client signs a USDC transfer on Stellar, and the server verifies and settles it. The network comes from the server's challenge, so `network` in the config is accepted but unused.
|
|
166
|
+
|
|
167
|
+
**Do not use it in production, and do not point it at Nirium's hosted endpoints yet.**
|
|
168
|
+
|
|
169
|
+
- The client works against a compliant MPP Charge server. We checked it against Nirium's own MPP middleware running locally against testnet, in `pull` and in `push` mode.
|
|
170
|
+
- When we tested on 1 October 2026, Nirium's hosted **testnet** endpoint (`/api/v1/mpp/*`) rejected MPP payments with `402 Verification Failed`, in `pull` and in `push` mode. We have **not tested the mainnet endpoint** (it would spend real USDC), so we cannot tell you it works there. We have not found the cause yet.
|
|
171
|
+
- In `push` mode the payment settles on-chain before the server verifies it, so a request the server rejects is **not refunded**.
|
|
172
|
+
- Until this is diagnosed, use x402 (`initX402()`) for paid endpoints. The `get_mpp_*` tools of the MCP server have the same limitation.
|
|
173
|
+
|
|
108
174
|
### x402Serve() — Charging Your Own API
|
|
109
175
|
|
|
110
176
|
`initX402()` above lets you *pay* for someone else's API. This is the other side: charging for yours.
|
|
@@ -135,7 +201,7 @@ Runs on **your own server**, not Nirium's — `x402Serve()` is a client-side fun
|
|
|
135
201
|
| **Protected** (API key) | `execute`, `market`, `loop/start\|stop\|scan`, `subscriptions`, `skills/install`, `webhooks` |
|
|
136
202
|
| **WebSocket** (JWT) | `/ws/signals` — real-time signal stream |
|
|
137
203
|
| **x402 Premium** | `/api/v1/premium/signals` ($0.02 USDC), `/api/v1/premium/market` ($0.05 USDC) |
|
|
138
|
-
| **MPP** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` |
|
|
204
|
+
| **MPP Charge** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` (testnet endpoint rejected MPP payments when tested, mainnet untested, see [MPP Charge](#mpp-charge-experimental)) |
|
|
139
205
|
|
|
140
206
|
### x402 Metrics — Observability Wrapper
|
|
141
207
|
|
|
@@ -272,7 +338,7 @@ Anchor a **hash** rather than the data itself: IPFS content cannot be deleted, s
|
|
|
272
338
|
|
|
273
339
|
## Requirements
|
|
274
340
|
|
|
275
|
-
- Node.js >=
|
|
341
|
+
- Node.js >= 22.12.0. `@stellar/stellar-sdk` 16 and `@x402/stellar` 2.28 declare `>=22.0.0`, but stellar-sdk 16 depends on `@noble/hashes` 2.x, which is ESM-only, and this package is published as CommonJS: `require('nirium')` only works without a flag from Node 22.12.0 (on 22.11 it throws `ERR_REQUIRE_ESM`)
|
|
276
342
|
- TypeScript >= 5.0
|
|
277
343
|
|
|
278
344
|
## Links
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type X402GuardConfig } from './x402-guard';
|
|
2
|
+
import { type X402PolicyHook } from './x402-policy';
|
|
2
3
|
export interface AgentConfig {
|
|
3
4
|
apiKey: string;
|
|
4
5
|
baseUrl?: string;
|
|
@@ -10,6 +11,10 @@ export interface AgentConfig {
|
|
|
10
11
|
* SEP-43 signer. Only `address` and `signAuthEntry` are required — that is all
|
|
11
12
|
* x402 needs, and it is what browser wallets expose (Freighter, Stellar Wallets
|
|
12
13
|
* Kit, Pollar). Lets the SDK pay from a browser without ever holding a secret.
|
|
14
|
+
*
|
|
15
|
+
* Note: what `signAuthEntry` receives is the base64 `HashIdPreimage` of the
|
|
16
|
+
* Soroban authorization (the bytes whose sha256 gets signed), not the
|
|
17
|
+
* `SorobanAuthorizationEntry` itself.
|
|
13
18
|
* @see https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md
|
|
14
19
|
*/
|
|
15
20
|
export interface X402Signer {
|
|
@@ -39,6 +44,13 @@ export interface X402Config {
|
|
|
39
44
|
network?: string;
|
|
40
45
|
/** Soroban RPC endpoint override (defaults per network) */
|
|
41
46
|
rpcUrl?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Pre-sign policy hook (#96). Runs after the Stellar authorization is
|
|
49
|
+
* built and before anything is signed; only an ALLOW bound to that exact
|
|
50
|
+
* authorization, and still valid, reaches the signer. Without it,
|
|
51
|
+
* x402Fetch behaves exactly as before. See X402PolicyHook.
|
|
52
|
+
*/
|
|
53
|
+
policy?: X402PolicyHook;
|
|
42
54
|
}
|
|
43
55
|
export interface MppConfig {
|
|
44
56
|
/**
|
|
@@ -542,6 +554,7 @@ export declare class Agent {
|
|
|
542
554
|
private logCallbacks;
|
|
543
555
|
private token;
|
|
544
556
|
private x402Client;
|
|
557
|
+
private x402Policy;
|
|
545
558
|
private mppClient;
|
|
546
559
|
constructor(config: AgentConfig);
|
|
547
560
|
private request;
|
|
@@ -840,11 +853,22 @@ export declare class Agent {
|
|
|
840
853
|
* Fetch a paid resource via x402 protocol.
|
|
841
854
|
* The client automatically handles 402 negotiation, auth-entry signing, and payment.
|
|
842
855
|
* Returns the Response object — call .json() or .text() for the payload.
|
|
856
|
+
*
|
|
857
|
+
* Throws `X402SpendCapError` when @x402/core refuses a payment for being above
|
|
858
|
+
* its per-payment cap (before anything is signed), and `X402PolicyError` when
|
|
859
|
+
* a `policy` refuses it.
|
|
843
860
|
*/
|
|
844
861
|
x402Fetch(url: string, init?: RequestInit): Promise<Response>;
|
|
862
|
+
private x402FetchWithPolicy;
|
|
845
863
|
/**
|
|
846
864
|
* Initialize the MPP Charge client for per-request Soroban SAC payments.
|
|
847
865
|
* Uses canonical @stellar/mpp charge mode with mppx.
|
|
866
|
+
*
|
|
867
|
+
* EXPERIMENTAL. The client works against a compliant MPP Charge server, but
|
|
868
|
+
* Nirium's hosted testnet `/api/v1/mpp/*` endpoint rejected MPP payments when
|
|
869
|
+
* tested on 2026-10-01 (`402 Verification Failed`), and in `push` mode the
|
|
870
|
+
* payment has already settled on-chain when that happens. The mainnet
|
|
871
|
+
* endpoint was not tested. Use `initX402()` for paid endpoints. See the README.
|
|
848
872
|
* In pull mode, the server assembles and broadcasts the transaction.
|
|
849
873
|
*
|
|
850
874
|
* @example
|
|
@@ -889,6 +913,9 @@ export interface X402ServeConfig {
|
|
|
889
913
|
guard?: X402GuardConfig;
|
|
890
914
|
}
|
|
891
915
|
export declare function x402Serve(config: X402ServeConfig): any;
|
|
916
|
+
export { X402PolicyError } from './x402-policy';
|
|
917
|
+
export { X402SpendCapError } from './x402-spend-cap';
|
|
918
|
+
export type { X402PolicyHook, X402PolicyContext, X402PolicyDecision, X402PolicyVerdict, X402PolicyOutcome, X402PolicyRecord, X402PaymentRequirementsView, } from './x402-policy';
|
|
892
919
|
export { x402Metrics } from './metrics';
|
|
893
920
|
export type { X402MetricsResult, MetricsSnapshot } from './metrics';
|
|
894
921
|
export type { X402GuardStore, X402GuardConfig, GuardRequest, GuardDenied } from './x402-guard';
|
package/dist/index.js
CHANGED
|
@@ -41,7 +41,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
41
41
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
42
42
|
};
|
|
43
43
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
44
|
-
exports.ResilientSignalClient = exports.createUpstashX402GuardStore = exports.x402Metrics = exports.Agent = void 0;
|
|
44
|
+
exports.ResilientSignalClient = exports.createUpstashX402GuardStore = exports.x402Metrics = exports.X402SpendCapError = exports.X402PolicyError = exports.Agent = void 0;
|
|
45
45
|
exports.x402Serve = x402Serve;
|
|
46
46
|
const ws_1 = __importDefault(require("ws"));
|
|
47
47
|
const node_crypto_1 = require("node:crypto");
|
|
@@ -51,8 +51,13 @@ const fetch_1 = require("@x402/fetch");
|
|
|
51
51
|
const stellar_1 = require("@x402/stellar");
|
|
52
52
|
// @ts-ignore
|
|
53
53
|
const client_1 = require("@x402/stellar/exact/client");
|
|
54
|
-
|
|
54
|
+
// @ts-ignore: ESM subpath imports (mismo patrón que los de @x402 de arriba)
|
|
55
|
+
const client_2 = require("mppx/client");
|
|
56
|
+
// @ts-ignore
|
|
57
|
+
const client_3 = require("@stellar/mpp/charge/client");
|
|
55
58
|
const x402_guard_1 = require("./x402-guard");
|
|
59
|
+
const x402_policy_1 = require("./x402-policy");
|
|
60
|
+
const x402_spend_cap_1 = require("./x402-spend-cap");
|
|
56
61
|
/** Build a `?a=1&b=2` suffix, dropping undefined values. Returns '' when empty. */
|
|
57
62
|
function queryString(params) {
|
|
58
63
|
if (!params)
|
|
@@ -101,6 +106,7 @@ class Agent {
|
|
|
101
106
|
logCallbacks = [];
|
|
102
107
|
token = null;
|
|
103
108
|
x402Client = null;
|
|
109
|
+
x402Policy = null;
|
|
104
110
|
mppClient = null;
|
|
105
111
|
constructor(config) {
|
|
106
112
|
this.apiKey = config.apiKey;
|
|
@@ -546,6 +552,8 @@ class Agent {
|
|
|
546
552
|
if (config.signer && config.secretKey) {
|
|
547
553
|
throw new Error('initX402 got both `secretKey` and `signer` — pass only one, so it is unambiguous which key signs.');
|
|
548
554
|
}
|
|
555
|
+
if (config.policy !== undefined)
|
|
556
|
+
(0, x402_policy_1.assertValidPolicyHook)(config.policy);
|
|
549
557
|
const signer = config.signer ?? stellar_1.createEd25519Signer(config.secretKey, network);
|
|
550
558
|
// Pubnet: el SDF NO corre RPC público de mainnet — soroban.stellar.org no
|
|
551
559
|
// existe. Default al RPC público de gateway.fm (mismo default que
|
|
@@ -553,24 +561,78 @@ class Agent {
|
|
|
553
561
|
const rpcUrl = config.rpcUrl || (network.includes('testnet')
|
|
554
562
|
? 'https://soroban-testnet.stellar.org'
|
|
555
563
|
: 'https://soroban-rpc.mainnet.stellar.gateway.fm');
|
|
556
|
-
|
|
557
|
-
|
|
564
|
+
if (config.policy) {
|
|
565
|
+
// Con policy el cliente se arma en cada x402Fetch: el signer de
|
|
566
|
+
// stellar-sdk no recibe la URL, y un closure por llamada ata URL,
|
|
567
|
+
// método y requisitos a ese pago sin estado compartido.
|
|
568
|
+
this.x402Policy = { base: signer, rpcUrl, policy: config.policy };
|
|
569
|
+
this.x402Client = null;
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
this.x402Policy = null;
|
|
573
|
+
const scheme = new client_1.ExactStellarScheme(signer, { url: rpcUrl });
|
|
574
|
+
const client = new fetch_1.x402Client().register('stellar:*', scheme);
|
|
575
|
+
// El cliente es uno solo; el fetch envuelto se arma en cada llamada
|
|
576
|
+
// (un closure barato) para que lo capturado de cada 402 sea de esa llamada.
|
|
577
|
+
this.x402Client = { client, scheme, baseFetch: fetch };
|
|
558
578
|
}
|
|
559
579
|
/**
|
|
560
580
|
* Fetch a paid resource via x402 protocol.
|
|
561
581
|
* The client automatically handles 402 negotiation, auth-entry signing, and payment.
|
|
562
582
|
* Returns the Response object — call .json() or .text() for the payload.
|
|
583
|
+
*
|
|
584
|
+
* Throws `X402SpendCapError` when @x402/core refuses a payment for being above
|
|
585
|
+
* its per-payment cap (before anything is signed), and `X402PolicyError` when
|
|
586
|
+
* a `policy` refuses it.
|
|
563
587
|
*/
|
|
564
588
|
async x402Fetch(url, init) {
|
|
589
|
+
if (this.x402Policy)
|
|
590
|
+
return this.x402FetchWithPolicy(this.x402Policy, url, init);
|
|
565
591
|
if (!this.x402Client) {
|
|
566
592
|
throw new Error('x402 client not initialized. Call agent.initX402() first.');
|
|
567
593
|
}
|
|
568
|
-
|
|
594
|
+
const { client, scheme, baseFetch } = this.x402Client;
|
|
595
|
+
const sink = {};
|
|
596
|
+
try {
|
|
597
|
+
return await (0, fetch_1.wrapFetchWithPayment)((0, x402_spend_cap_1.captureRequirements)(baseFetch, sink), client)(url, init);
|
|
598
|
+
}
|
|
599
|
+
catch (e) {
|
|
600
|
+
throw (0, x402_spend_cap_1.toSpendCapError)(e, url, sink.offered, scheme.findDefaultAsset?.bind(scheme)) ?? e;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async x402FetchWithPolicy(cfg, url, init) {
|
|
604
|
+
const slot = {};
|
|
605
|
+
const gated = (0, x402_policy_1.createPolicyGatedSigner)(cfg.base, cfg.policy, () => ({ url, method: (init?.method ?? 'GET').toUpperCase(), requirements: slot.requirements }), (err) => { slot.error = err; });
|
|
606
|
+
const scheme = new client_1.ExactStellarScheme(gated, { url: cfg.rpcUrl });
|
|
607
|
+
const sink = {};
|
|
608
|
+
const client = new fetch_1.x402Client()
|
|
609
|
+
.register('stellar:*', scheme)
|
|
610
|
+
.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
|
|
611
|
+
slot.requirements = {
|
|
612
|
+
scheme: r.scheme, network: r.network, asset: r.asset,
|
|
613
|
+
payTo: r.payTo, amount: r.amount, maxTimeoutSeconds: r.maxTimeoutSeconds,
|
|
614
|
+
};
|
|
615
|
+
});
|
|
616
|
+
// NUNCA registrar onPaymentCreationFailure aquí: puede devolver un
|
|
617
|
+
// payload sin pasar por el signer, y el gate quedaría puenteado.
|
|
618
|
+
try {
|
|
619
|
+
return await (0, fetch_1.wrapFetchWithPayment)((0, x402_spend_cap_1.captureRequirements)(globalThis.fetch, sink), client)(url, init);
|
|
620
|
+
}
|
|
621
|
+
catch (e) {
|
|
622
|
+
// @x402/fetch reenvuelve el error y pierde la clase.
|
|
623
|
+
throw slot.error ?? (0, x402_spend_cap_1.toSpendCapError)(e, url, sink.offered, scheme.findDefaultAsset?.bind(scheme)) ?? e;
|
|
624
|
+
}
|
|
569
625
|
}
|
|
570
626
|
// ─── MPP Protocol (Charge Mode) ────────────────────────────
|
|
571
627
|
/**
|
|
572
628
|
* Initialize the MPP Charge client for per-request Soroban SAC payments.
|
|
573
629
|
* Uses canonical @stellar/mpp charge mode with mppx.
|
|
630
|
+
*
|
|
631
|
+
* EXPERIMENTAL. The client works against a compliant MPP Charge server, but
|
|
632
|
+
* Nirium's hosted testnet `/api/v1/mpp/*` endpoint rejected MPP payments when
|
|
633
|
+
* tested on 2026-10-01 (`402 Verification Failed`), and in `push` mode the
|
|
634
|
+
* payment has already settled on-chain when that happens. The mainnet
|
|
635
|
+
* endpoint was not tested. Use `initX402()` for paid endpoints. See the README.
|
|
574
636
|
* In pull mode, the server assembles and broadcasts the transaction.
|
|
575
637
|
*
|
|
576
638
|
* @example
|
|
@@ -580,17 +642,14 @@ class Agent {
|
|
|
580
642
|
* ```
|
|
581
643
|
*/
|
|
582
644
|
initMpp(config) {
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
},
|
|
591
|
-
},
|
|
645
|
+
// La red la dicta el reto 402 del servidor (methodDetails.network), no el cliente:
|
|
646
|
+
// `config.network` se acepta por compatibilidad pero ya no se usa.
|
|
647
|
+
// polyfill:false es obligatorio: sin él mppx reemplaza globalThis.fetch y
|
|
648
|
+
// pasaría a interceptar también los 402 de x402Fetch.
|
|
649
|
+
this.mppClient = client_2.Mppx.create({
|
|
650
|
+
methods: [client_3.stellar.charge({ secretKey: config.secretKey, mode: config.mode || 'pull' })],
|
|
651
|
+
polyfill: false,
|
|
592
652
|
});
|
|
593
|
-
this.mppClient = mppx;
|
|
594
653
|
}
|
|
595
654
|
/**
|
|
596
655
|
* Fetch a paid resource via MPP Charge protocol.
|
|
@@ -869,6 +928,10 @@ function x402Serve(config) {
|
|
|
869
928
|
// `.js` extension required even though the source is `.ts`: `module:
|
|
870
929
|
// ESNext` emits these specifiers verbatim, and Node's native ESM resolver
|
|
871
930
|
// (unlike a bundler) needs the real extension to find the compiled file.
|
|
931
|
+
var x402_policy_2 = require("./x402-policy");
|
|
932
|
+
Object.defineProperty(exports, "X402PolicyError", { enumerable: true, get: function () { return x402_policy_2.X402PolicyError; } });
|
|
933
|
+
var x402_spend_cap_2 = require("./x402-spend-cap");
|
|
934
|
+
Object.defineProperty(exports, "X402SpendCapError", { enumerable: true, get: function () { return x402_spend_cap_2.X402SpendCapError; } });
|
|
872
935
|
var metrics_1 = require("./metrics");
|
|
873
936
|
Object.defineProperty(exports, "x402Metrics", { enumerable: true, get: function () { return metrics_1.x402Metrics; } });
|
|
874
937
|
var x402_guard_upstash_1 = require("./x402-guard-upstash");
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
export type X402PolicyVerdict = 'ALLOW' | 'DENY' | 'WAIT';
|
|
2
|
+
export interface X402PaymentRequirementsView {
|
|
3
|
+
scheme: string;
|
|
4
|
+
network: string;
|
|
5
|
+
asset: string;
|
|
6
|
+
payTo: string;
|
|
7
|
+
amount: string;
|
|
8
|
+
maxTimeoutSeconds: number;
|
|
9
|
+
}
|
|
10
|
+
export interface X402PolicyContext {
|
|
11
|
+
/** Version of this object's shape, so an engine knows what it is reading. */
|
|
12
|
+
contextVersion: 1;
|
|
13
|
+
/** URL and method exactly as passed to x402Fetch. */
|
|
14
|
+
url: string;
|
|
15
|
+
method: string;
|
|
16
|
+
/** The requirements the server asked for and x402 selected. */
|
|
17
|
+
requirements: Readonly<X402PaymentRequirementsView>;
|
|
18
|
+
/** What is actually about to be signed, decoded from the bytes. */
|
|
19
|
+
authorization: Readonly<{
|
|
20
|
+
preimageXdr: string;
|
|
21
|
+
/** 'legacy' (ENVELOPE_TYPE_SOROBAN_AUTHORIZATION) or 'cap71' (…WithAddress). */
|
|
22
|
+
preimageType: 'legacy' | 'cap71';
|
|
23
|
+
/** sha256(preimage) in hex: exactly the payload ed25519 signs. */
|
|
24
|
+
payloadHash: string;
|
|
25
|
+
networkPassphrase: string;
|
|
26
|
+
nonce: string;
|
|
27
|
+
signatureExpirationLedger: number;
|
|
28
|
+
contractId: string;
|
|
29
|
+
functionName: string;
|
|
30
|
+
from: string;
|
|
31
|
+
to: string;
|
|
32
|
+
amount: string;
|
|
33
|
+
}>;
|
|
34
|
+
signer: string;
|
|
35
|
+
/** sha256 of {url, method, payloadHash}. An ALLOW must echo it back unchanged. */
|
|
36
|
+
contextHash: string;
|
|
37
|
+
}
|
|
38
|
+
export interface X402PolicyDecision {
|
|
39
|
+
decision: X402PolicyVerdict;
|
|
40
|
+
/** Required on ALLOW: binds the decision to this authorization and no other. */
|
|
41
|
+
contextHash?: string;
|
|
42
|
+
reason?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Opaque to Nirium. Preserved in errors and onDecision. Required on ALLOW
|
|
45
|
+
* when `currentVersion` is configured: it is what gets compared.
|
|
46
|
+
*/
|
|
47
|
+
policyVersion?: string;
|
|
48
|
+
/** Epoch ms. If it has passed by signing time, nothing is signed. Equality counts as expired. */
|
|
49
|
+
expiresAt?: number;
|
|
50
|
+
decisionId?: string;
|
|
51
|
+
}
|
|
52
|
+
export type X402PolicyOutcome = 'ALLOWED' | 'SIGNED' | 'SIGNER_ERROR' | 'DENY' | 'WAIT' | 'TIMEOUT' | 'ENGINE_ERROR' | 'EXPIRED' | 'UNBOUND' | 'MALFORMED' | 'CONTEXT_MISMATCH' | 'STALE' | 'VERSION_UNAVAILABLE' | 'SIGNER_CHANGED' | 'CLOCK_INVALID';
|
|
53
|
+
/**
|
|
54
|
+
* `ALLOWED`: the engine's ALLOW is well formed, bound to this authorization
|
|
55
|
+
* and not expired yet. It is a notice, not a result: the observer runs here,
|
|
56
|
+
* and the freshness and identity checks that follow it can still refuse
|
|
57
|
+
* (STALE, EXPIRED, TIMEOUT, CLOCK_INVALID, VERSION_UNAVAILABLE, SIGNER_CHANGED).
|
|
58
|
+
* `SIGNED`: the signer returned a signature. `SIGNER_ERROR`: the signer
|
|
59
|
+
* rejected, threw, or returned no `signedAuthEntry`. Every other value is a
|
|
60
|
+
* refusal and nothing was signed.
|
|
61
|
+
* Sequence: `ALLOWED`, then either a refusal, or exactly one of `SIGNED` or
|
|
62
|
+
* `SIGNER_ERROR`. Refusals that happen before the ALLOW is accepted (DENY, WAIT,
|
|
63
|
+
* UNBOUND, MALFORMED, TIMEOUT or ENGINE_ERROR while evaluating, CONTEXT_MISMATCH)
|
|
64
|
+
* are a single record with no `ALLOWED`.
|
|
65
|
+
*/
|
|
66
|
+
export interface X402PolicyRecord {
|
|
67
|
+
outcome: X402PolicyOutcome;
|
|
68
|
+
context?: X402PolicyContext;
|
|
69
|
+
decision?: X402PolicyDecision;
|
|
70
|
+
error?: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Pre-sign policy hook (#96). Runs after the Stellar authorization is built
|
|
74
|
+
* and before anything is signed. Only an ALLOW bound to this exact
|
|
75
|
+
* authorization, and still valid, reaches the signer. Anything else (DENY,
|
|
76
|
+
* WAIT, error, timeout, malformed or stale answer) signs nothing. Nirium never
|
|
77
|
+
* stores or owns the policy; it asks and obeys.
|
|
78
|
+
*
|
|
79
|
+
* Authorizations that are not a single `transfer(from, to, amount)` matching
|
|
80
|
+
* the selected requirements are rejected before the policy is consulted.
|
|
81
|
+
*/
|
|
82
|
+
export interface X402PolicyHook {
|
|
83
|
+
evaluate: (ctx: X402PolicyContext, opts: {
|
|
84
|
+
signal: AbortSignal;
|
|
85
|
+
}) => Promise<X402PolicyDecision>;
|
|
86
|
+
/**
|
|
87
|
+
* Optional source of the policy version currently in force. When set, it is
|
|
88
|
+
* read after an ALLOW and right before signing; the ALLOW signs only if its
|
|
89
|
+
* `policyVersion` equals what this returns. A rejection, an empty answer or
|
|
90
|
+
* running past the deadline signs nothing.
|
|
91
|
+
*
|
|
92
|
+
* This check is NOT atomic with signing: the version can change after it is
|
|
93
|
+
* read, or while the signer runs. It narrows the stale-ALLOW window to the
|
|
94
|
+
* synchronous step between this read and the signer call; it does not close it.
|
|
95
|
+
* The `onDecision` observer runs before this read, so a version change it
|
|
96
|
+
* causes is seen by it.
|
|
97
|
+
*/
|
|
98
|
+
currentVersion?: (ctx: X402PolicyContext, opts: {
|
|
99
|
+
signal: AbortSignal;
|
|
100
|
+
}) => Promise<string>;
|
|
101
|
+
/**
|
|
102
|
+
* Hard deadline for the whole pre-sign phase (evaluate + currentVersion).
|
|
103
|
+
* Default 5000 ms, and never more than half the payment's maxTimeoutSeconds.
|
|
104
|
+
*/
|
|
105
|
+
timeoutMs?: number;
|
|
106
|
+
/** If true, an ALLOW without expiresAt is treated as unsignable. Default false. */
|
|
107
|
+
requireExpiry?: boolean;
|
|
108
|
+
/**
|
|
109
|
+
* Observer for receipts (see X402PolicyRecord for the sequence). Cannot
|
|
110
|
+
* change the outcome. A synchronous throw is swallowed. If it returns a
|
|
111
|
+
* promise (or any thenable) it is not awaited, so it cannot delay or block a
|
|
112
|
+
* payment, and its rejection is swallowed so it never becomes an
|
|
113
|
+
* unhandledRejection.
|
|
114
|
+
*/
|
|
115
|
+
onDecision?: (record: X402PolicyRecord) => void;
|
|
116
|
+
/**
|
|
117
|
+
* Injectable clock (epoch ms), for tests. It must return a finite number
|
|
118
|
+
* every time it is read: anything else (NaN, undefined, a string, a throw)
|
|
119
|
+
* refuses the payment with CLOCK_INVALID, because every comparison against
|
|
120
|
+
* NaN is false and a deadline that can never be reached would sign.
|
|
121
|
+
*/
|
|
122
|
+
now?: () => number;
|
|
123
|
+
}
|
|
124
|
+
/** Outcomes that mean no signature was released (the payment is refused). */
|
|
125
|
+
export type X402PolicyRefusal = Exclude<X402PolicyOutcome, 'ALLOWED' | 'SIGNED'>;
|
|
126
|
+
export declare class X402PolicyError extends Error {
|
|
127
|
+
readonly outcome: X402PolicyRefusal;
|
|
128
|
+
readonly decision?: X402PolicyDecision;
|
|
129
|
+
readonly contextHash?: string;
|
|
130
|
+
constructor(outcome: X402PolicyRefusal, message: string, extra?: {
|
|
131
|
+
decision?: X402PolicyDecision;
|
|
132
|
+
contextHash?: string;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
type SignOpts = {
|
|
136
|
+
networkPassphrase?: string;
|
|
137
|
+
address?: string;
|
|
138
|
+
};
|
|
139
|
+
type SignFn = (authEntry: string, opts?: SignOpts) => Promise<{
|
|
140
|
+
signedAuthEntry: string;
|
|
141
|
+
signerAddress?: string;
|
|
142
|
+
}>;
|
|
143
|
+
export type X402BaseSigner = {
|
|
144
|
+
address: string;
|
|
145
|
+
signAuthEntry: SignFn;
|
|
146
|
+
};
|
|
147
|
+
/** Validates a policy hook at initX402 time, so bad config fails before any payment. */
|
|
148
|
+
export declare function assertValidPolicyHook(policy: X402PolicyHook): void;
|
|
149
|
+
/**
|
|
150
|
+
* Decodes the preimage and checks it describes exactly the payment x402
|
|
151
|
+
* selected. This is not policy (that belongs to the engine): it is context
|
|
152
|
+
* integrity, so that what the engine evaluates is what gets signed.
|
|
153
|
+
*/
|
|
154
|
+
export declare function describeAuthorization(preimageXdr: string, requirements: X402PaymentRequirementsView, signerAddress: string): X402PolicyContext['authorization'];
|
|
155
|
+
/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
|
|
156
|
+
export declare function effectiveTimeoutMs(policy: X402PolicyHook, maxTimeoutSeconds?: number): number;
|
|
157
|
+
/**
|
|
158
|
+
* Wraps a signer so it only signs with a current ALLOW bound to this auth
|
|
159
|
+
* entry. Anything else ends without a signature.
|
|
160
|
+
*
|
|
161
|
+
* `getCall` supplies the per-call context (URL, method, requirements): one
|
|
162
|
+
* gated signer is created per x402Fetch, so two concurrent payments never
|
|
163
|
+
* share state. `onRefused` receives the error before it is thrown, because
|
|
164
|
+
* @x402/fetch re-wraps errors and loses their class.
|
|
165
|
+
*
|
|
166
|
+
* Not a security boundary against code in the same process: anyone holding
|
|
167
|
+
* the base signer can still call it directly. Callbacks (`evaluate`,
|
|
168
|
+
* `currentVersion`, `onDecision`) all run before the final clock and identity
|
|
169
|
+
* checks, so what they change in the clock, the version source or the base
|
|
170
|
+
* signer's `address` is detected. Replacing `base.signAuthEntry` itself is not:
|
|
171
|
+
* it is looked up at call time, after those checks.
|
|
172
|
+
*/
|
|
173
|
+
export declare function createPolicyGatedSigner(base: X402BaseSigner, policy: X402PolicyHook, getCall: () => {
|
|
174
|
+
url: string;
|
|
175
|
+
method: string;
|
|
176
|
+
requirements?: X402PaymentRequirementsView;
|
|
177
|
+
}, onRefused?: (error: X402PolicyError) => void): X402BaseSigner;
|
|
178
|
+
export {};
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3
|
+
// Pre-sign policy hook for x402Fetch (#96).
|
|
4
|
+
//
|
|
5
|
+
// El punto de evaluación envuelve al signer SEP-43 porque es el único lugar
|
|
6
|
+
// donde existe la autorización que se va a firmar: ExactStellarScheme la arma
|
|
7
|
+
// dentro de createPaymentPayload (simulación RPC incluida) y stellar-sdk la
|
|
8
|
+
// entrega a signAuthEntry como HashIdPreimage en base64. El hook
|
|
9
|
+
// onBeforePaymentCreation de @x402/core corre ANTES de eso: ve los requisitos,
|
|
10
|
+
// pero todavía no hay nonce, expiración ni invocación que atar.
|
|
11
|
+
// ═══════════════════════════════════════════════════════════════
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.X402PolicyError = void 0;
|
|
14
|
+
exports.assertValidPolicyHook = assertValidPolicyHook;
|
|
15
|
+
exports.describeAuthorization = describeAuthorization;
|
|
16
|
+
exports.effectiveTimeoutMs = effectiveTimeoutMs;
|
|
17
|
+
exports.createPolicyGatedSigner = createPolicyGatedSigner;
|
|
18
|
+
const stellar_sdk_1 = require("@stellar/stellar-sdk");
|
|
19
|
+
class X402PolicyError extends Error {
|
|
20
|
+
outcome;
|
|
21
|
+
decision;
|
|
22
|
+
contextHash;
|
|
23
|
+
constructor(outcome, message, extra = {}) {
|
|
24
|
+
super(`x402 policy ${outcome}: ${message}`);
|
|
25
|
+
this.name = 'X402PolicyError';
|
|
26
|
+
this.outcome = outcome;
|
|
27
|
+
this.decision = extra.decision;
|
|
28
|
+
this.contextHash = extra.contextHash;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
exports.X402PolicyError = X402PolicyError;
|
|
32
|
+
const PASSPHRASES = {
|
|
33
|
+
'stellar:testnet': stellar_sdk_1.Networks.TESTNET,
|
|
34
|
+
'stellar:pubnet': stellar_sdk_1.Networks.PUBLIC,
|
|
35
|
+
};
|
|
36
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
37
|
+
const hex = (b) => Buffer.from(b).toString('hex');
|
|
38
|
+
const sha256hex = (s) => hex((0, stellar_sdk_1.hash)(Buffer.from(s, 'utf8')));
|
|
39
|
+
const nonempty = (v) => typeof v === 'string' && v.trim().length > 0;
|
|
40
|
+
/** Validates a policy hook at initX402 time, so bad config fails before any payment. */
|
|
41
|
+
function assertValidPolicyHook(policy) {
|
|
42
|
+
if (!policy || typeof policy !== 'object' || typeof policy.evaluate !== 'function') {
|
|
43
|
+
throw new Error('initX402: `policy.evaluate` must be a function.');
|
|
44
|
+
}
|
|
45
|
+
if (policy.currentVersion !== undefined && typeof policy.currentVersion !== 'function') {
|
|
46
|
+
throw new Error('initX402: `policy.currentVersion`, when set, must be a function.');
|
|
47
|
+
}
|
|
48
|
+
if (policy.timeoutMs !== undefined
|
|
49
|
+
&& (!Number.isSafeInteger(policy.timeoutMs) || policy.timeoutMs <= 0)) {
|
|
50
|
+
throw new Error('initX402: `policy.timeoutMs` must be a positive integer (ms).');
|
|
51
|
+
}
|
|
52
|
+
if (policy.now !== undefined && typeof policy.now !== 'function') {
|
|
53
|
+
throw new Error('initX402: `policy.now`, when set, must be a function returning epoch milliseconds.');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Decodes the preimage and checks it describes exactly the payment x402
|
|
58
|
+
* selected. This is not policy (that belongs to the engine): it is context
|
|
59
|
+
* integrity, so that what the engine evaluates is what gets signed.
|
|
60
|
+
*/
|
|
61
|
+
function describeAuthorization(preimageXdr, requirements, signerAddress) {
|
|
62
|
+
let pre;
|
|
63
|
+
try {
|
|
64
|
+
pre = stellar_sdk_1.xdr.HashIdPreimage.fromXDR(preimageXdr, 'base64');
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `undecodable auth preimage (${e?.message})`);
|
|
68
|
+
}
|
|
69
|
+
// Dos variantes: la clásica, y la de CAP-71 que además ata la dirección
|
|
70
|
+
// dentro de lo firmado. En la segunda, esa dirección tiene que ser el signer.
|
|
71
|
+
let auth;
|
|
72
|
+
let preimageType;
|
|
73
|
+
switch (pre.switch().name) {
|
|
74
|
+
case 'envelopeTypeSorobanAuthorization':
|
|
75
|
+
auth = pre.sorobanAuthorization();
|
|
76
|
+
preimageType = 'legacy';
|
|
77
|
+
break;
|
|
78
|
+
case 'envelopeTypeSorobanAuthorizationWithAddress':
|
|
79
|
+
auth = pre.sorobanAuthorizationWithAddress();
|
|
80
|
+
preimageType = 'cap71';
|
|
81
|
+
if (stellar_sdk_1.Address.fromScAddress(auth.address()).toString() !== signerAddress) {
|
|
82
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'CAP-71 preimage is bound to a different address than the signer');
|
|
83
|
+
}
|
|
84
|
+
break;
|
|
85
|
+
default:
|
|
86
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `unsupported preimage type ${pre.switch().name}`);
|
|
87
|
+
}
|
|
88
|
+
const passphrase = PASSPHRASES[requirements.network];
|
|
89
|
+
if (!passphrase)
|
|
90
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `unknown network ${requirements.network}`);
|
|
91
|
+
if (hex(auth.networkId()) !== hex((0, stellar_sdk_1.hash)(Buffer.from(passphrase)))) {
|
|
92
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'auth entry is for a different network than requirements.network');
|
|
93
|
+
}
|
|
94
|
+
const inv = auth.invocation();
|
|
95
|
+
if (inv.subInvocations().length !== 0) {
|
|
96
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'auth entry carries sub-invocations');
|
|
97
|
+
}
|
|
98
|
+
const fn = inv.function();
|
|
99
|
+
if (fn.switch().name !== 'sorobanAuthorizedFunctionTypeContractFn') {
|
|
100
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `unexpected authorized function ${fn.switch().name}`);
|
|
101
|
+
}
|
|
102
|
+
const call = fn.contractFn();
|
|
103
|
+
const contractId = stellar_sdk_1.Address.fromScAddress(call.contractAddress()).toString();
|
|
104
|
+
const functionName = call.functionName().toString();
|
|
105
|
+
const rawArgs = call.args();
|
|
106
|
+
if (functionName !== 'transfer' || rawArgs.length !== 3) {
|
|
107
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `expected transfer(from,to,amount), got ${functionName}/${rawArgs.length}`);
|
|
108
|
+
}
|
|
109
|
+
if (rawArgs[0].switch().name !== 'scvAddress' || rawArgs[1].switch().name !== 'scvAddress'
|
|
110
|
+
|| rawArgs[2].switch().name !== 'scvI128') {
|
|
111
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'transfer arguments have unexpected types');
|
|
112
|
+
}
|
|
113
|
+
const from = stellar_sdk_1.Address.fromScAddress(rawArgs[0].address()).toString();
|
|
114
|
+
const to = stellar_sdk_1.Address.fromScAddress(rawArgs[1].address()).toString();
|
|
115
|
+
const amount = BigInt((0, stellar_sdk_1.scValToNative)(rawArgs[2])).toString();
|
|
116
|
+
if (contractId !== requirements.asset)
|
|
117
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'asset contract differs from requirements.asset');
|
|
118
|
+
if (to !== requirements.payTo)
|
|
119
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'destination differs from requirements.payTo');
|
|
120
|
+
if (amount !== requirements.amount)
|
|
121
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'amount differs from requirements.amount');
|
|
122
|
+
if (from !== signerAddress)
|
|
123
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'from differs from signer address');
|
|
124
|
+
return Object.freeze({
|
|
125
|
+
preimageXdr,
|
|
126
|
+
preimageType,
|
|
127
|
+
payloadHash: hex((0, stellar_sdk_1.hash)(pre.toXDR())),
|
|
128
|
+
networkPassphrase: passphrase,
|
|
129
|
+
nonce: auth.nonce().toString(),
|
|
130
|
+
signatureExpirationLedger: auth.signatureExpirationLedger(),
|
|
131
|
+
contractId, functionName, from, to, amount,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
|
|
135
|
+
function effectiveTimeoutMs(policy, maxTimeoutSeconds) {
|
|
136
|
+
const base = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
137
|
+
if (typeof maxTimeoutSeconds === 'number' && Number.isFinite(maxTimeoutSeconds) && maxTimeoutSeconds > 0) {
|
|
138
|
+
return Math.max(1, Math.min(base, Math.floor((maxTimeoutSeconds * 1000) / 2)));
|
|
139
|
+
}
|
|
140
|
+
return base;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Wraps a signer so it only signs with a current ALLOW bound to this auth
|
|
144
|
+
* entry. Anything else ends without a signature.
|
|
145
|
+
*
|
|
146
|
+
* `getCall` supplies the per-call context (URL, method, requirements): one
|
|
147
|
+
* gated signer is created per x402Fetch, so two concurrent payments never
|
|
148
|
+
* share state. `onRefused` receives the error before it is thrown, because
|
|
149
|
+
* @x402/fetch re-wraps errors and loses their class.
|
|
150
|
+
*
|
|
151
|
+
* Not a security boundary against code in the same process: anyone holding
|
|
152
|
+
* the base signer can still call it directly. Callbacks (`evaluate`,
|
|
153
|
+
* `currentVersion`, `onDecision`) all run before the final clock and identity
|
|
154
|
+
* checks, so what they change in the clock, the version source or the base
|
|
155
|
+
* signer's `address` is detected. Replacing `base.signAuthEntry` itself is not:
|
|
156
|
+
* it is looked up at call time, after those checks.
|
|
157
|
+
*/
|
|
158
|
+
function createPolicyGatedSigner(base, policy, getCall, onRefused) {
|
|
159
|
+
// La identidad se fija aquí. Si el signer base cambia de dirección a mitad
|
|
160
|
+
// del pago, no se firma: lo evaluado se evaluó para esta cuenta.
|
|
161
|
+
const account = base.address;
|
|
162
|
+
const now = policy.now ?? Date.now;
|
|
163
|
+
// Un reloj que no devuelve un número finito cierra: NaN hace falsa cada
|
|
164
|
+
// comparación (`t >= deadline`), y un plazo que nunca se alcanza firmaría.
|
|
165
|
+
const readClock = (context, decision) => {
|
|
166
|
+
let t;
|
|
167
|
+
try {
|
|
168
|
+
t = now();
|
|
169
|
+
}
|
|
170
|
+
catch (e) {
|
|
171
|
+
return refuse('CLOCK_INVALID', `clock threw (${e?.message ?? String(e)})`, context, decision);
|
|
172
|
+
}
|
|
173
|
+
if (typeof t !== 'number' || !Number.isFinite(t)) {
|
|
174
|
+
return refuse('CLOCK_INVALID', `clock returned ${String(t)}, not epoch milliseconds`, context, decision);
|
|
175
|
+
}
|
|
176
|
+
return t;
|
|
177
|
+
};
|
|
178
|
+
const report = (r) => {
|
|
179
|
+
try {
|
|
180
|
+
const out = policy.onDecision?.(r);
|
|
181
|
+
// Un observador async que rechaza no puede tumbar el proceso con un
|
|
182
|
+
// unhandledRejection. No se espera: el signer no depende de él.
|
|
183
|
+
if (out !== null && (typeof out === 'object' || typeof out === 'function')) {
|
|
184
|
+
Promise.resolve(out).catch(() => { });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch { /* un observador no decide nada */ }
|
|
188
|
+
};
|
|
189
|
+
const refuse = (outcome, msg, context, decision) => {
|
|
190
|
+
report({ outcome, context, decision, error: msg });
|
|
191
|
+
const err = new X402PolicyError(outcome, msg, { decision, contextHash: context?.contextHash });
|
|
192
|
+
try {
|
|
193
|
+
onRefused?.(err);
|
|
194
|
+
}
|
|
195
|
+
catch { /* idem */ }
|
|
196
|
+
throw err;
|
|
197
|
+
};
|
|
198
|
+
const signAuthEntry = async (preimageXdr, opts) => {
|
|
199
|
+
const call = getCall();
|
|
200
|
+
if (!call.requirements)
|
|
201
|
+
refuse('CONTEXT_MISMATCH', 'no payment requirements bound to this signing call');
|
|
202
|
+
if (base.address !== account)
|
|
203
|
+
refuse('SIGNER_CHANGED', 'base signer address changed after the gate was created');
|
|
204
|
+
if (opts?.address && opts.address !== account)
|
|
205
|
+
refuse('CONTEXT_MISMATCH', 'asked to sign for a different address');
|
|
206
|
+
let authorization;
|
|
207
|
+
try {
|
|
208
|
+
authorization = describeAuthorization(preimageXdr, call.requirements, account);
|
|
209
|
+
}
|
|
210
|
+
catch (e) {
|
|
211
|
+
return refuse(e instanceof X402PolicyError ? e.outcome : 'CONTEXT_MISMATCH', e?.message ?? String(e));
|
|
212
|
+
}
|
|
213
|
+
const contextHash = sha256hex(JSON.stringify({ v: 1, url: call.url, method: call.method, payloadHash: authorization.payloadHash }));
|
|
214
|
+
// Congelado: el engine lee, no reescribe lo que se firma.
|
|
215
|
+
const context = Object.freeze({
|
|
216
|
+
contextVersion: 1, url: call.url, method: call.method,
|
|
217
|
+
requirements: Object.freeze({ ...call.requirements }),
|
|
218
|
+
authorization,
|
|
219
|
+
signer: account, contextHash,
|
|
220
|
+
});
|
|
221
|
+
const timeoutMs = effectiveTimeoutMs(policy, call.requirements.maxTimeoutSeconds);
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
// Un solo plazo para toda la fase previa a la firma (evaluate + currentVersion).
|
|
224
|
+
const deadline = readClock(context) + timeoutMs;
|
|
225
|
+
let timer;
|
|
226
|
+
const TIMED_OUT = Symbol('timeout');
|
|
227
|
+
const timeout = new Promise((_, reject) => {
|
|
228
|
+
timer = setTimeout(() => { controller.abort(); reject(TIMED_OUT); }, timeoutMs);
|
|
229
|
+
});
|
|
230
|
+
timeout.catch(() => { });
|
|
231
|
+
try {
|
|
232
|
+
let decision;
|
|
233
|
+
try {
|
|
234
|
+
decision = await Promise.race([
|
|
235
|
+
Promise.resolve().then(() => policy.evaluate(context, { signal: controller.signal })),
|
|
236
|
+
timeout,
|
|
237
|
+
]);
|
|
238
|
+
}
|
|
239
|
+
catch (e) {
|
|
240
|
+
if (e === TIMED_OUT)
|
|
241
|
+
return refuse('TIMEOUT', `no decision within ${timeoutMs} ms`, context);
|
|
242
|
+
return refuse('ENGINE_ERROR', e?.message ?? String(e), context);
|
|
243
|
+
}
|
|
244
|
+
// Todo lo que no sea un ALLOW bien formado cierra.
|
|
245
|
+
if (!decision || typeof decision !== 'object')
|
|
246
|
+
return refuse('MALFORMED', 'engine returned no decision object', context);
|
|
247
|
+
if (decision.decision === 'DENY')
|
|
248
|
+
return refuse('DENY', decision.reason ?? 'denied', context, decision);
|
|
249
|
+
if (decision.decision === 'WAIT')
|
|
250
|
+
return refuse('WAIT', decision.reason ?? 'wait', context, decision);
|
|
251
|
+
if (decision.decision !== 'ALLOW')
|
|
252
|
+
return refuse('MALFORMED', `unknown verdict ${String(decision.decision)}`, context, decision);
|
|
253
|
+
// Se copian los campos antes de cualquier await: mutar el objeto del
|
|
254
|
+
// engine después no extiende ni cambia esta decisión.
|
|
255
|
+
const allow = Object.freeze({ ...decision });
|
|
256
|
+
if (allow.contextHash !== contextHash)
|
|
257
|
+
return refuse('UNBOUND', 'ALLOW is not bound to this authorization', context, allow);
|
|
258
|
+
if (allow.expiresAt !== undefined
|
|
259
|
+
&& (typeof allow.expiresAt !== 'number' || !Number.isFinite(allow.expiresAt))) {
|
|
260
|
+
return refuse('MALFORMED', 'expiresAt must be epoch milliseconds', context, allow);
|
|
261
|
+
}
|
|
262
|
+
if (allow.expiresAt === undefined && policy.requireExpiry) {
|
|
263
|
+
return refuse('EXPIRED', 'ALLOW without expiresAt while requireExpiry is set', context, allow);
|
|
264
|
+
}
|
|
265
|
+
const checkClock = () => {
|
|
266
|
+
const t = readClock(context, allow);
|
|
267
|
+
if (t >= deadline)
|
|
268
|
+
refuse('TIMEOUT', 'decision arrived after the deadline', context, allow);
|
|
269
|
+
if (allow.expiresAt !== undefined && t >= allow.expiresAt)
|
|
270
|
+
refuse('EXPIRED', 'ALLOW expired before signing', context, allow);
|
|
271
|
+
};
|
|
272
|
+
if (policy.currentVersion && !nonempty(allow.policyVersion)) {
|
|
273
|
+
return refuse('MALFORMED', 'ALLOW has no policyVersion to check against currentVersion', context, allow);
|
|
274
|
+
}
|
|
275
|
+
checkClock();
|
|
276
|
+
// El observador corre AQUI y no junto al signer: todo lo que provoque
|
|
277
|
+
// (adelantar el reloj, cambiar la versión de la política, cambiar la
|
|
278
|
+
// dirección del signer) lo ven las comprobaciones que siguen. Lo que
|
|
279
|
+
// hace un callback después de la última de ellas ya no existe: entre
|
|
280
|
+
// la última comprobación y el signer no corre código ajeno.
|
|
281
|
+
report({ outcome: 'ALLOWED', context, decision: allow });
|
|
282
|
+
if (policy.currentVersion) {
|
|
283
|
+
let current;
|
|
284
|
+
try {
|
|
285
|
+
current = await Promise.race([
|
|
286
|
+
Promise.resolve().then(() => policy.currentVersion(context, { signal: controller.signal })),
|
|
287
|
+
timeout,
|
|
288
|
+
]);
|
|
289
|
+
}
|
|
290
|
+
catch (e) {
|
|
291
|
+
if (e === TIMED_OUT)
|
|
292
|
+
return refuse('TIMEOUT', `no current policy version within ${timeoutMs} ms`, context, allow);
|
|
293
|
+
return refuse('VERSION_UNAVAILABLE', `currentVersion failed (${e?.message ?? String(e)})`, context, allow);
|
|
294
|
+
}
|
|
295
|
+
if (!nonempty(current))
|
|
296
|
+
return refuse('VERSION_UNAVAILABLE', 'currentVersion returned no version', context, allow);
|
|
297
|
+
if (current !== allow.policyVersion) {
|
|
298
|
+
return refuse('STALE', `ALLOW was issued under policy ${allow.policyVersion}, current is ${current}`, context, allow);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// Comprobaciones finales, siempre, y sin ningún await antes del signer:
|
|
302
|
+
// el reloj se vuelve a leer (después del observador y del await de la
|
|
303
|
+
// versión) y la identidad se compara por última vez.
|
|
304
|
+
checkClock();
|
|
305
|
+
if (base.address !== account)
|
|
306
|
+
return refuse('SIGNER_CHANGED', 'base signer address changed while the policy was evaluated', context, allow);
|
|
307
|
+
// La fase previa terminó: la firma no tiene plazo propio, así que el
|
|
308
|
+
// temporizador ya no pinta nada.
|
|
309
|
+
if (timer)
|
|
310
|
+
clearTimeout(timer);
|
|
311
|
+
// SIGNED solo existe si el signer devolvió una firma. Los bytes son
|
|
312
|
+
// los del parámetro original, no una copia que alguien pudo tocar.
|
|
313
|
+
let signed;
|
|
314
|
+
try {
|
|
315
|
+
signed = await base.signAuthEntry(preimageXdr, opts);
|
|
316
|
+
}
|
|
317
|
+
catch (e) {
|
|
318
|
+
// El error del signer se relanza tal cual: no es una negativa de la política.
|
|
319
|
+
report({ outcome: 'SIGNER_ERROR', context, decision: allow, error: e?.message ?? String(e) });
|
|
320
|
+
throw e;
|
|
321
|
+
}
|
|
322
|
+
if (!signed || typeof signed !== 'object' || !nonempty(signed.signedAuthEntry)) {
|
|
323
|
+
return refuse('SIGNER_ERROR', 'signer returned no signedAuthEntry', context, allow);
|
|
324
|
+
}
|
|
325
|
+
report({ outcome: 'SIGNED', context, decision: allow });
|
|
326
|
+
return signed;
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
if (timer)
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
return { address: account, signAuthEntry };
|
|
334
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** One payment option from the server's 402 response, as x402 v2 sends it. */
|
|
2
|
+
export interface X402OfferedRequirement {
|
|
3
|
+
scheme?: string;
|
|
4
|
+
network?: string;
|
|
5
|
+
asset?: string;
|
|
6
|
+
amount?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface X402SpendCapErrorDetails {
|
|
9
|
+
url: string;
|
|
10
|
+
/** Atomic units the server asked for (the cheapest offer when there are several). */
|
|
11
|
+
amount?: string;
|
|
12
|
+
asset?: string;
|
|
13
|
+
network?: string;
|
|
14
|
+
/** The cap as @x402/core states it, e.g. "$1". */
|
|
15
|
+
cap?: string;
|
|
16
|
+
/** Human reading of `amount` when the asset is a known default asset, e.g. "2 USDC". */
|
|
17
|
+
formattedAmount?: string;
|
|
18
|
+
cause?: unknown;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* x402Fetch refused to pay because the amount the server asked for is above
|
|
22
|
+
* the per-payment cap enforced by @x402/core. Thrown before the signer is
|
|
23
|
+
* reached: nothing was signed, nothing was sent.
|
|
24
|
+
*/
|
|
25
|
+
export declare class X402SpendCapError extends Error {
|
|
26
|
+
readonly code: "X402_SPEND_CAP_EXCEEDED";
|
|
27
|
+
/** Always false for this error: the cap is checked before any signing. */
|
|
28
|
+
readonly signerCalled: false;
|
|
29
|
+
readonly url: string;
|
|
30
|
+
readonly amount?: string;
|
|
31
|
+
readonly asset?: string;
|
|
32
|
+
readonly network?: string;
|
|
33
|
+
readonly cap?: string;
|
|
34
|
+
readonly formattedAmount?: string;
|
|
35
|
+
constructor(d: X402SpendCapErrorDetails);
|
|
36
|
+
}
|
|
37
|
+
/** `20000000` with 7 decimals and `USDC` -> `2 USDC`. */
|
|
38
|
+
export declare function formatAtomic(amount: string, decimals: number, symbol: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* Reads the `accepts` list out of a 402 response's PAYMENT-REQUIRED header
|
|
41
|
+
* (base64 JSON, x402 v2). Returns undefined if it is absent or unreadable;
|
|
42
|
+
* the error is still produced, just without the amount.
|
|
43
|
+
*/
|
|
44
|
+
export declare function readOfferedRequirements(response: {
|
|
45
|
+
headers: {
|
|
46
|
+
get(name: string): string | null;
|
|
47
|
+
};
|
|
48
|
+
}): X402OfferedRequirement[] | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Wraps a fetch so the requirements of every 402 it sees are written to
|
|
51
|
+
* `sink`. Passive: the response is returned untouched.
|
|
52
|
+
*/
|
|
53
|
+
export declare function captureRequirements(base: typeof fetch, sink: {
|
|
54
|
+
offered?: X402OfferedRequirement[];
|
|
55
|
+
}): typeof fetch;
|
|
56
|
+
/**
|
|
57
|
+
* If `error` is @x402/core refusing a payment for being above its
|
|
58
|
+
* per-payment USD cap, returns the clear error; otherwise null so the caller
|
|
59
|
+
* rethrows the original. Other spendControls rejections (for example a
|
|
60
|
+
* non-default asset) are deliberately left alone.
|
|
61
|
+
*/
|
|
62
|
+
export declare function toSpendCapError(error: unknown, url: string, offered: X402OfferedRequirement[] | undefined, describeAsset?: (asset: string, network: string) => {
|
|
63
|
+
decimals: number;
|
|
64
|
+
symbol: string;
|
|
65
|
+
} | undefined): X402SpendCapError | null;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3
|
+
// Error claro para el tope por pago de @x402/core.
|
|
4
|
+
//
|
|
5
|
+
// Desde @x402/core 2.23.0 el cliente rechaza, al seleccionar los requisitos
|
|
6
|
+
// y antes de crear el payload, todo pago por encima de un tope por defecto
|
|
7
|
+
// ($1). Lo hace con un Error genérico que x402Fetch re-envuelve
|
|
8
|
+
// ("Failed to create payment payload: All payment requirements were
|
|
9
|
+
// rejected by spendControls.maxAmountPerPayment (...)"), sin decir cuánto se
|
|
10
|
+
// pedía ni que nadie firmó nada. Este módulo reconoce ese caso y lo convierte
|
|
11
|
+
// en un error que lo dice. No cambia el tope ni lo expone: solo lo explica.
|
|
12
|
+
// ═══════════════════════════════════════════════════════════════
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.X402SpendCapError = void 0;
|
|
15
|
+
exports.formatAtomic = formatAtomic;
|
|
16
|
+
exports.readOfferedRequirements = readOfferedRequirements;
|
|
17
|
+
exports.captureRequirements = captureRequirements;
|
|
18
|
+
exports.toSpendCapError = toSpendCapError;
|
|
19
|
+
/**
|
|
20
|
+
* x402Fetch refused to pay because the amount the server asked for is above
|
|
21
|
+
* the per-payment cap enforced by @x402/core. Thrown before the signer is
|
|
22
|
+
* reached: nothing was signed, nothing was sent.
|
|
23
|
+
*/
|
|
24
|
+
class X402SpendCapError extends Error {
|
|
25
|
+
code = 'X402_SPEND_CAP_EXCEEDED';
|
|
26
|
+
/** Always false for this error: the cap is checked before any signing. */
|
|
27
|
+
signerCalled = false;
|
|
28
|
+
url;
|
|
29
|
+
amount;
|
|
30
|
+
asset;
|
|
31
|
+
network;
|
|
32
|
+
cap;
|
|
33
|
+
formattedAmount;
|
|
34
|
+
constructor(d) {
|
|
35
|
+
const asked = d.formattedAmount
|
|
36
|
+
? `${d.formattedAmount} (${d.amount} atomic units)`
|
|
37
|
+
: d.amount !== undefined
|
|
38
|
+
? `${d.amount} atomic units${d.asset ? ` of ${d.asset}` : ''}`
|
|
39
|
+
: 'more than the cap';
|
|
40
|
+
const cap = d.cap ? `the per-payment cap is ${d.cap}` : 'it is above the per-payment cap';
|
|
41
|
+
super(`x402Fetch refused to pay ${d.url}: the server asked for ${asked} and ${cap}. `
|
|
42
|
+
+ 'The signer was not called; nothing was signed or sent. '
|
|
43
|
+
+ 'The cap is enforced by @x402/core and cannot be changed from initX402() yet.', d.cause !== undefined ? { cause: d.cause } : undefined);
|
|
44
|
+
this.name = 'X402SpendCapError';
|
|
45
|
+
this.url = d.url;
|
|
46
|
+
this.amount = d.amount;
|
|
47
|
+
this.asset = d.asset;
|
|
48
|
+
this.network = d.network;
|
|
49
|
+
this.cap = d.cap;
|
|
50
|
+
this.formattedAmount = d.formattedAmount;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.X402SpendCapError = X402SpendCapError;
|
|
54
|
+
const isAtomic = (v) => typeof v === 'string' && /^\d+$/.test(v);
|
|
55
|
+
/** `20000000` with 7 decimals and `USDC` -> `2 USDC`. */
|
|
56
|
+
function formatAtomic(amount, decimals, symbol) {
|
|
57
|
+
const raw = BigInt(amount);
|
|
58
|
+
const base = 10n ** BigInt(decimals);
|
|
59
|
+
const whole = raw / base;
|
|
60
|
+
const frac = (raw % base).toString().padStart(decimals, '0').replace(/0+$/, '');
|
|
61
|
+
return `${frac ? `${whole}.${frac}` : whole.toString()} ${symbol}`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Reads the `accepts` list out of a 402 response's PAYMENT-REQUIRED header
|
|
65
|
+
* (base64 JSON, x402 v2). Returns undefined if it is absent or unreadable;
|
|
66
|
+
* the error is still produced, just without the amount.
|
|
67
|
+
*/
|
|
68
|
+
function readOfferedRequirements(response) {
|
|
69
|
+
try {
|
|
70
|
+
const header = response.headers.get('payment-required');
|
|
71
|
+
if (!header)
|
|
72
|
+
return undefined;
|
|
73
|
+
const bytes = Uint8Array.from(atob(header), (c) => c.charCodeAt(0));
|
|
74
|
+
const accepts = JSON.parse(new TextDecoder().decode(bytes))?.accepts;
|
|
75
|
+
return Array.isArray(accepts) ? accepts : undefined;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Wraps a fetch so the requirements of every 402 it sees are written to
|
|
83
|
+
* `sink`. Passive: the response is returned untouched.
|
|
84
|
+
*/
|
|
85
|
+
function captureRequirements(base, sink) {
|
|
86
|
+
return (async (input, init) => {
|
|
87
|
+
const response = await base(input, init);
|
|
88
|
+
if (response.status === 402) {
|
|
89
|
+
const offered = readOfferedRequirements(response);
|
|
90
|
+
if (offered)
|
|
91
|
+
sink.offered = offered;
|
|
92
|
+
}
|
|
93
|
+
return response;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
// El mensaje de @x402/core que reconocemos. Si una versión futura lo cambia,
|
|
97
|
+
// el error genérico vuelve a salir tal cual (sin perder nada) y el test que lo
|
|
98
|
+
// fija (test/x402-spend-cap.test.ts) falla al subir la dependencia.
|
|
99
|
+
const CAP_REJECTION = /rejected by spendControls\.maxAmountPerPayment(?: \(([^)]*)\))?/;
|
|
100
|
+
/**
|
|
101
|
+
* If `error` is @x402/core refusing a payment for being above its
|
|
102
|
+
* per-payment USD cap, returns the clear error; otherwise null so the caller
|
|
103
|
+
* rethrows the original. Other spendControls rejections (for example a
|
|
104
|
+
* non-default asset) are deliberately left alone.
|
|
105
|
+
*/
|
|
106
|
+
function toSpendCapError(error, url, offered, describeAsset) {
|
|
107
|
+
const message = error instanceof Error ? error.message : '';
|
|
108
|
+
const hit = CAP_REJECTION.exec(message);
|
|
109
|
+
if (!hit)
|
|
110
|
+
return null;
|
|
111
|
+
// "($1, including USDC)" -> "$1"
|
|
112
|
+
const cap = hit[1]?.split(',')[0]?.trim() || undefined;
|
|
113
|
+
const cheapest = (offered ?? [])
|
|
114
|
+
.filter((o) => isAtomic(o.amount))
|
|
115
|
+
.sort((a, b) => (BigInt(a.amount) < BigInt(b.amount) ? -1 : BigInt(a.amount) > BigInt(b.amount) ? 1 : 0))[0];
|
|
116
|
+
let formattedAmount;
|
|
117
|
+
if (cheapest?.asset && cheapest.network) {
|
|
118
|
+
try {
|
|
119
|
+
const info = describeAsset?.(cheapest.asset, cheapest.network);
|
|
120
|
+
if (info)
|
|
121
|
+
formattedAmount = formatAtomic(cheapest.amount, info.decimals, info.symbol);
|
|
122
|
+
}
|
|
123
|
+
catch { /* sin formato legible: se informan las unidades atómicas */ }
|
|
124
|
+
}
|
|
125
|
+
return new X402SpendCapError({
|
|
126
|
+
url, cap, formattedAmount, cause: error,
|
|
127
|
+
amount: cheapest?.amount, asset: cheapest?.asset, network: cheapest?.network,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
@@ -27,8 +27,16 @@ jest.mock('@x402/stellar/exact/client', () => ({
|
|
|
27
27
|
ExactStellarScheme: class {
|
|
28
28
|
},
|
|
29
29
|
}));
|
|
30
|
-
jest.mock('mppx', () => ({
|
|
31
|
-
|
|
30
|
+
jest.mock('mppx/client', () => ({
|
|
31
|
+
Mppx: { create: () => ({ fetch: async () => new Response('{}') }) },
|
|
32
|
+
}));
|
|
33
|
+
jest.mock('@stellar/mpp/charge/client', () => ({
|
|
34
|
+
stellar: { charge: () => ({}) },
|
|
35
|
+
}));
|
|
36
|
+
// stellar-sdk 16 loads ESM-only @noble/hashes; index.ts pulls it in through
|
|
37
|
+
// x402-policy.ts. Only the constants read at module load are needed here.
|
|
38
|
+
jest.mock('@stellar/stellar-sdk', () => ({
|
|
39
|
+
Networks: { TESTNET: 'Test SDF Network ; September 2015', PUBLIC: 'Public Global Stellar Network ; September 2015' },
|
|
32
40
|
}));
|
|
33
41
|
const index_1 = require("./index");
|
|
34
42
|
const metrics_1 = require("./metrics");
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nirium",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Autonomous treasury and agentic-payments infrastructure for Stellar (x402
|
|
3
|
+
"version": "0.16.0",
|
|
4
|
+
"description": "Autonomous treasury and agentic-payments infrastructure for Stellar (x402)",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"homepage": "https://nirium.xyz",
|
|
@@ -22,6 +22,9 @@
|
|
|
22
22
|
"dist",
|
|
23
23
|
"README.md"
|
|
24
24
|
],
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22.12.0"
|
|
27
|
+
},
|
|
25
28
|
"scripts": {
|
|
26
29
|
"build": "tsc",
|
|
27
30
|
"prepublishOnly": "npm run build",
|
|
@@ -31,9 +34,9 @@
|
|
|
31
34
|
},
|
|
32
35
|
"dependencies": {
|
|
33
36
|
"@stellar/mpp": "^0.7.1",
|
|
34
|
-
"@stellar/stellar-sdk": "^
|
|
35
|
-
"@x402/fetch": "^2.
|
|
36
|
-
"@x402/stellar": "^2.
|
|
37
|
+
"@stellar/stellar-sdk": "^16.3.0",
|
|
38
|
+
"@x402/fetch": "^2.28.0",
|
|
39
|
+
"@x402/stellar": "^2.28.0",
|
|
37
40
|
"mppx": "^0.6.31",
|
|
38
41
|
"viem": "^2.55.19",
|
|
39
42
|
"ws": "^8.21.3"
|
|
@@ -42,7 +45,7 @@
|
|
|
42
45
|
"@types/jest": "^30.0.0",
|
|
43
46
|
"@types/node": "^26.2.0",
|
|
44
47
|
"@types/ws": "^8.18.1",
|
|
45
|
-
"@x402/core": "^2.
|
|
48
|
+
"@x402/core": "^2.28.0",
|
|
46
49
|
"jest": "^30.4.2",
|
|
47
50
|
"ts-jest": "^29.4.12",
|
|
48
51
|
"typescript": "^5.9.3"
|