nirium 0.14.1 → 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 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 (x402 + MPP) — in both directions, paying for other APIs with `initX402()` and charging for your own with `x402Serve()` — and real-time market data into their applications.
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 Payments | `initMpp()`, `mppFetch()` |
64
+ | MPP Charge client (experimental, see below) | `initMpp()`, `mppFetch()` |
65
65
 
66
66
  ## Authentication
67
67
 
@@ -93,27 +93,91 @@ 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
- ### MPP — Session-Based Budget Delegation
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
- agent.initMpp({
99
- secretKey: 'S...',
100
- network: 'stellar:testnet',
101
- mode: 'pull',
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
- const response = await agent.mppFetch('https://nirium-agent.fly.dev/api/v1/mpp/signals');
105
- const data = await response.json();
138
+ try {
139
+ await agent.x402Fetch(url);
140
+ } catch (e) {
141
+ if (e instanceof X402PolicyError) console.log(e.outcome); // DENY, WAIT, TIMEOUT, STALE, ...
142
+ }
143
+ ```
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');
106
163
  ```
107
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.
111
177
 
112
178
  ```typescript
113
179
  import { x402Serve } from 'nirium';
114
- import express from 'express';
115
180
 
116
- const app = express();
117
181
  app.use('/premium', x402Serve({
118
182
  payTo: 'G...', // your Stellar address — where payments land
119
183
  routes: { 'GET /signals': '$0.02' },
@@ -123,6 +187,8 @@ app.use('/premium', x402Serve({
123
187
 
124
188
  Runs on **your own server**, not Nirium's — `x402Serve()` is a client-side function you call from your own code; Nirium doesn't operate, host, or route through anything here, is never in the payment path, and never sees your end users' requests.
125
189
 
190
+ **Known limitation:** `x402Serve()` verifies and settles the payment; it does not deduplicate a payment proof across requests or rate-limit callers on its own. Add your own protection if you need either - see [issue #91](https://github.com/nirium-protocol/nirium/issues/91) for what's missing, why, and a real production reference implementation.
191
+
126
192
  **Usage telemetry — opt-in, off by default:** set `NIRIUM_X402SERVE_TELEMETRY=true` to send a small, non-blocking usage ping to Nirium — your `payTo` address, a SHA-256 hash of your `facilitatorApiKey` (never the key itself), network, route/request counts, and this SDK's version. It never blocks, delays, or fails a payment if the ping fails, times out, or isn't sent at all. Disabled by default since v0.14.0 — it's the only channel that would otherwise connect Nirium to how a specific integrator is using this locally-run function, and that isn't a decision this package should make for you.
127
193
 
128
194
  **Compliance is yours.** `x402Serve()` is a general-purpose library, not a service Nirium provides to your end users. You choose what to charge for, who your `payTo` is, and which jurisdiction you operate in — you remain solely responsible for complying with the financial, tax, and consumer-protection laws that apply to your own use of it.
@@ -135,7 +201,79 @@ 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)) |
205
+
206
+ ### x402 Metrics — Observability Wrapper
207
+
208
+ Wrap your `x402Serve` handler with `x402Metrics` to get Prometheus-format counters, histograms, and revenue tracking — no changes to your payment logic.
209
+
210
+ ```typescript
211
+ import express from 'express';
212
+ import { x402Serve, x402Metrics } from 'nirium';
213
+
214
+ const app = express();
215
+
216
+ const { handler, metricsHandler } = x402Metrics(
217
+ x402Serve({
218
+ payTo: 'G...',
219
+ routes: { 'GET /signals': '$0.02' },
220
+ facilitatorApiKey: 'oz_...',
221
+ }),
222
+ );
223
+
224
+ app.use('/premium', handler);
225
+ app.get('/metrics', metricsHandler); // no payment required
226
+
227
+ app.listen(3000);
228
+ ```
229
+
230
+ Scrape the endpoint with curl:
231
+
232
+ ```bash
233
+ curl -s http://localhost:3000/metrics
234
+ ```
235
+
236
+ Output:
237
+
238
+ ```
239
+ # HELP x402_challenges_total Total402 payment challenges issued
240
+ # TYPE x402_challenges_total counter
241
+ x402_challenges_total{route="GET /signals"} 12
242
+ # HELP x402_verify_success_total Total successful payment verifications
243
+ # TYPE x402_verify_success_total counter
244
+ x402_verify_success_total{route="GET /signals"} 8
245
+ # HELP x402_verify_fail_total Total failed payment verifications
246
+ # TYPE x402_verify_fail_total counter
247
+ x402_verify_fail_total{route="GET /signals"} 2
248
+ # HELP x402_settle_success_total Total successful settlements
249
+ # TYPE x402_settle_success_total counter
250
+ x402_settle_success_total{route="GET /signals"} 8
251
+ # HELP x402_settle_fail_total Total failed settlements
252
+ # TYPE x402_settle_fail_total counter
253
+ x402_settle_fail_total{route="GET /signals"} 1
254
+ # HELP x402_infra_errors_total Total facilitator/infrastructure errors (5xx)
255
+ # TYPE x402_infra_errors_total counter
256
+ x402_infra_errors_total{route="GET /signals"} 1
257
+ # HELP x402_rejections_total Total403 rejections from protected-request hooks
258
+ # TYPE x402_rejections_total counter
259
+ x402_rejections_total{route="GET /signals"} 1
260
+ # HELP x402_revenue_total Revenue collected per route and asset
261
+ # TYPE x402_revenue_total counter
262
+ x402_revenue_total{route="GET /signals",asset="USDC"} 160000
263
+ # HELP x402_settlement_latency_seconds Request latency in seconds (approximate settlement time)
264
+ # TYPE x402_settlement_latency_seconds histogram
265
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="0.1"} 5
266
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="0.5"} 7
267
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="1"} 8
268
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="2.5"} 8
269
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="5"} 8
270
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="10"} 8
271
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="+Inf"} 8
272
+ x402_settlement_latency_seconds_sum{route="GET /signals"} 3.42
273
+ x402_settlement_latency_seconds_count{route="GET /signals"} 8
274
+ ```
275
+
276
+ No payer addresses or PII are included in metrics output — aggregates only.
139
277
 
140
278
  ## Payouts
141
279
 
@@ -200,7 +338,7 @@ Anchor a **hash** rather than the data itself: IPFS content cannot be deleted, s
200
338
 
201
339
  ## Requirements
202
340
 
203
- - Node.js >= 18
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`)
204
342
  - TypeScript >= 5.0
205
343
 
206
344
  ## Links
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type X402GuardConfig } from './x402-guard';
2
+ import { type X402PolicyHook } from './x402-policy';
1
3
  export interface AgentConfig {
2
4
  apiKey: string;
3
5
  baseUrl?: string;
@@ -9,6 +11,10 @@ export interface AgentConfig {
9
11
  * SEP-43 signer. Only `address` and `signAuthEntry` are required — that is all
10
12
  * x402 needs, and it is what browser wallets expose (Freighter, Stellar Wallets
11
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.
12
18
  * @see https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md
13
19
  */
14
20
  export interface X402Signer {
@@ -38,6 +44,13 @@ export interface X402Config {
38
44
  network?: string;
39
45
  /** Soroban RPC endpoint override (defaults per network) */
40
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;
41
54
  }
42
55
  export interface MppConfig {
43
56
  /**
@@ -541,6 +554,7 @@ export declare class Agent {
541
554
  private logCallbacks;
542
555
  private token;
543
556
  private x402Client;
557
+ private x402Policy;
544
558
  private mppClient;
545
559
  constructor(config: AgentConfig);
546
560
  private request;
@@ -839,11 +853,22 @@ export declare class Agent {
839
853
  * Fetch a paid resource via x402 protocol.
840
854
  * The client automatically handles 402 negotiation, auth-entry signing, and payment.
841
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.
842
860
  */
843
861
  x402Fetch(url: string, init?: RequestInit): Promise<Response>;
862
+ private x402FetchWithPolicy;
844
863
  /**
845
864
  * Initialize the MPP Charge client for per-request Soroban SAC payments.
846
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.
847
872
  * In pull mode, the server assembles and broadcasts the transaction.
848
873
  *
849
874
  * @example
@@ -879,10 +904,22 @@ export interface X402ServeConfig {
879
904
  facilitatorAuthHeader?: string;
880
905
  appName?: string;
881
906
  appLogo?: string;
907
+ /**
908
+ * Optional replay/rate-limit protection - off by default. Providing
909
+ * `guard.store` turns it on; without it, x402Serve() behaves exactly
910
+ * as before. See x402-guard.ts and
911
+ * https://github.com/nirium-protocol/nirium/issues/91.
912
+ */
913
+ guard?: X402GuardConfig;
882
914
  }
883
915
  export declare function x402Serve(config: X402ServeConfig): any;
884
- export { x402Metrics } from './metrics.js';
885
- export type { X402MetricsResult, MetricsSnapshot } from './metrics.js';
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';
919
+ export { x402Metrics } from './metrics';
920
+ export type { X402MetricsResult, MetricsSnapshot } from './metrics';
921
+ export type { X402GuardStore, X402GuardConfig, GuardRequest, GuardDenied } from './x402-guard';
922
+ export { createUpstashX402GuardStore } from './x402-guard-upstash';
923
+ export type { UpstashX402GuardStoreOptions } from './x402-guard-upstash';
886
924
  export default Agent;
887
- export { ResilientSignalClient, type ResilientSignalClientOptions, type ConnectionStatus, type ConnectionStatusInfo, } from './resilient-ws.js';
888
- //# sourceMappingURL=index.d.ts.map
925
+ export { ResilientSignalClient, type ResilientSignalClientOptions, type ConnectionStatus, type ConnectionStatusInfo, } from './resilient-ws';
package/dist/index.js CHANGED
@@ -1,18 +1,63 @@
1
+ "use strict";
1
2
  // ═══════════════════════════════════════════════════════════════
2
3
  // nirium — Official TypeScript SDK (x402 + MPP)
3
4
  // Versión: solo en package.json (no aquí: un número en un comentario se
4
5
  // desincroniza y ya mintió antes — decía 0.6.2 estando en 0.7.0).
5
6
  // ═══════════════════════════════════════════════════════════════
6
- import WebSocket from 'ws';
7
- import { createHash } from 'node:crypto';
8
- import { createRequire } from 'node:module';
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ var __importDefault = (this && this.__importDefault) || function (mod) {
41
+ return (mod && mod.__esModule) ? mod : { "default": mod };
42
+ };
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.ResilientSignalClient = exports.createUpstashX402GuardStore = exports.x402Metrics = exports.X402SpendCapError = exports.X402PolicyError = exports.Agent = void 0;
45
+ exports.x402Serve = x402Serve;
46
+ const ws_1 = __importDefault(require("ws"));
47
+ const node_crypto_1 = require("node:crypto");
9
48
  // @ts-ignore — ESM subpath imports
10
- import { x402Client as X402ClientClass, wrapFetchWithPayment } from '@x402/fetch';
49
+ const fetch_1 = require("@x402/fetch");
50
+ // @ts-ignore
51
+ const stellar_1 = require("@x402/stellar");
11
52
  // @ts-ignore
12
- import { createEd25519Signer } from '@x402/stellar';
53
+ const client_1 = require("@x402/stellar/exact/client");
54
+ // @ts-ignore: ESM subpath imports (mismo patrón que los de @x402 de arriba)
55
+ const client_2 = require("mppx/client");
13
56
  // @ts-ignore
14
- import { ExactStellarScheme } from '@x402/stellar/exact/client';
15
- import * as MppxModule from 'mppx';
57
+ const client_3 = require("@stellar/mpp/charge/client");
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");
16
61
  /** Build a `?a=1&b=2` suffix, dropping undefined values. Returns '' when empty. */
17
62
  function queryString(params) {
18
63
  if (!params)
@@ -50,7 +95,7 @@ function queryString(params) {
50
95
  * });
51
96
  * ```
52
97
  */
53
- export class Agent {
98
+ class Agent {
54
99
  apiKey;
55
100
  baseUrl;
56
101
  wsUrl;
@@ -61,6 +106,7 @@ export class Agent {
61
106
  logCallbacks = [];
62
107
  token = null;
63
108
  x402Client = null;
109
+ x402Policy = null;
64
110
  mppClient = null;
65
111
  constructor(config) {
66
112
  this.apiKey = config.apiKey;
@@ -430,10 +476,10 @@ export class Agent {
430
476
  this.connectWebSocket();
431
477
  }
432
478
  connectWebSocket(subscriptionId) {
433
- if (this.ws?.readyState === WebSocket.OPEN)
479
+ if (this.ws?.readyState === ws_1.default.OPEN)
434
480
  return;
435
481
  const authQuery = this.token ? `?token=${this.token}` : '';
436
- this.ws = new WebSocket(`${this.wsUrl}${authQuery}`);
482
+ this.ws = new ws_1.default(`${this.wsUrl}${authQuery}`);
437
483
  this.ws.on('open', () => {
438
484
  console.log('[Nirium SDK] WebSocket connected');
439
485
  this.reconnectAttempts = 0;
@@ -506,31 +552,87 @@ export class Agent {
506
552
  if (config.signer && config.secretKey) {
507
553
  throw new Error('initX402 got both `secretKey` and `signer` — pass only one, so it is unambiguous which key signs.');
508
554
  }
509
- const signer = config.signer ?? createEd25519Signer(config.secretKey, network);
555
+ if (config.policy !== undefined)
556
+ (0, x402_policy_1.assertValidPolicyHook)(config.policy);
557
+ const signer = config.signer ?? stellar_1.createEd25519Signer(config.secretKey, network);
510
558
  // Pubnet: el SDF NO corre RPC público de mainnet — soroban.stellar.org no
511
559
  // existe. Default al RPC público de gateway.fm (mismo default que
512
560
  // @stellar/mpp); siempre overrideable por config.rpcUrl.
513
561
  const rpcUrl = config.rpcUrl || (network.includes('testnet')
514
562
  ? 'https://soroban-testnet.stellar.org'
515
563
  : 'https://soroban-rpc.mainnet.stellar.gateway.fm');
516
- const client = new X402ClientClass().register('stellar:*', new ExactStellarScheme(signer, { url: rpcUrl }));
517
- this.x402Client = { fetch: wrapFetchWithPayment(fetch, client) };
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 };
518
578
  }
519
579
  /**
520
580
  * Fetch a paid resource via x402 protocol.
521
581
  * The client automatically handles 402 negotiation, auth-entry signing, and payment.
522
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.
523
587
  */
524
588
  async x402Fetch(url, init) {
589
+ if (this.x402Policy)
590
+ return this.x402FetchWithPolicy(this.x402Policy, url, init);
525
591
  if (!this.x402Client) {
526
592
  throw new Error('x402 client not initialized. Call agent.initX402() first.');
527
593
  }
528
- return this.x402Client.fetch(url, init);
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
+ }
529
625
  }
530
626
  // ─── MPP Protocol (Charge Mode) ────────────────────────────
531
627
  /**
532
628
  * Initialize the MPP Charge client for per-request Soroban SAC payments.
533
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.
534
636
  * In pull mode, the server assembles and broadcasts the transaction.
535
637
  *
536
638
  * @example
@@ -540,17 +642,14 @@ export class Agent {
540
642
  * ```
541
643
  */
542
644
  initMpp(config) {
543
- const Mppx = MppxModule.default || MppxModule;
544
- const mppx = Mppx.create({
545
- stellar: {
546
- charge: {
547
- secretKey: config.secretKey,
548
- network: config.network || 'stellar:testnet',
549
- mode: config.mode || 'pull',
550
- },
551
- },
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,
552
652
  });
553
- this.mppClient = mppx;
554
653
  }
555
654
  /**
556
655
  * Fetch a paid resource via MPP Charge protocol.
@@ -574,6 +673,7 @@ export class Agent {
574
673
  this.logCallbacks = [];
575
674
  }
576
675
  }
676
+ exports.Agent = Agent;
577
677
  // ─── x402Serve — el otro lado del mostrador ────────────────────
578
678
  //
579
679
  // `initX402` te deja PAGAR por APIs ajenas. Esto te deja COBRAR por la tuya.
@@ -619,7 +719,8 @@ const pingX402ServeTelemetry = (body) => {
619
719
  };
620
720
  const sdkVersionForTelemetry = () => {
621
721
  try {
622
- return createRequire(import.meta.url)('../package.json').version;
722
+ // CommonJS build: plain `require` is already in scope, no import.meta needed.
723
+ return require('../package.json').version;
623
724
  }
624
725
  catch {
625
726
  return undefined;
@@ -629,7 +730,7 @@ const X402_FACILITATORS = {
629
730
  'stellar:pubnet': 'https://channels.openzeppelin.com/x402',
630
731
  'stellar:testnet': 'https://channels.openzeppelin.com/x402/testnet',
631
732
  };
632
- export function x402Serve(config) {
733
+ function x402Serve(config) {
633
734
  if (!config.payTo || !/^G[A-Z2-7]{55}$/.test(config.payTo)) {
634
735
  throw new Error('x402Serve: `payTo` must be a Stellar public key (G...). Without it there is nobody to pay.');
635
736
  }
@@ -658,7 +759,7 @@ export function x402Serve(config) {
658
759
  // formatos y distingue de verdad entre ausente y roto.
659
760
  const load = async (m) => {
660
761
  try {
661
- return await import(/* @vite-ignore */ m);
762
+ return await Promise.resolve(`${m}`).then(s => __importStar(require(s)));
662
763
  }
663
764
  catch (err) {
664
765
  const missing = /cannot find (module|package)/i.test(String(err?.message));
@@ -694,7 +795,7 @@ export function x402Serve(config) {
694
795
  };
695
796
  }
696
797
  const facilitatorKeyHash = config.facilitatorApiKey
697
- ? createHash('sha256').update(config.facilitatorApiKey).digest('hex').slice(0, 16)
798
+ ? (0, node_crypto_1.createHash)('sha256').update(config.facilitatorApiKey).digest('hex').slice(0, 16)
698
799
  : undefined;
699
800
  const sdkVersion = sdkVersionForTelemetry();
700
801
  pingX402ServeTelemetry({
@@ -783,8 +884,34 @@ export function x402Serve(config) {
783
884
  requestsSinceFlush = 0;
784
885
  lastFlush = Date.now();
785
886
  };
887
+ const sendDenied = (res, d) => {
888
+ if (d.headers)
889
+ for (const [k, v] of Object.entries(d.headers))
890
+ res.setHeader(k, v);
891
+ res.status(d.status).json(d.body);
892
+ };
786
893
  return async function niriumX402(req, res, next) {
787
894
  maybeFlushHeartbeat();
895
+ if (config.guard) {
896
+ const guardReq = { method: req.method, url: req.originalUrl ?? req.url, headers: req.headers, ip: req.ip };
897
+ const rl = await (0, x402_guard_1.checkRateLimit)(guardReq, config.guard);
898
+ if (!rl.allowed) {
899
+ sendDenied(res, rl.denied);
900
+ return;
901
+ }
902
+ const replay = await (0, x402_guard_1.checkReplay)(guardReq, config.guard);
903
+ if (!replay.allowed) {
904
+ sendDenied(res, replay.denied);
905
+ return;
906
+ }
907
+ if (replay.release) {
908
+ const release = replay.release;
909
+ res.on('finish', () => {
910
+ if (res.statusCode < 200 || res.statusCode >= 300)
911
+ release();
912
+ });
913
+ }
914
+ }
788
915
  try {
789
916
  if (!cached) {
790
917
  await preflight();
@@ -801,7 +928,14 @@ export function x402Serve(config) {
801
928
  // `.js` extension required even though the source is `.ts`: `module:
802
929
  // ESNext` emits these specifiers verbatim, and Node's native ESM resolver
803
930
  // (unlike a bundler) needs the real extension to find the compiled file.
804
- export { x402Metrics } from './metrics.js';
805
- export default Agent;
806
- export { ResilientSignalClient, } from './resilient-ws.js';
807
- //# sourceMappingURL=index.js.map
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; } });
935
+ var metrics_1 = require("./metrics");
936
+ Object.defineProperty(exports, "x402Metrics", { enumerable: true, get: function () { return metrics_1.x402Metrics; } });
937
+ var x402_guard_upstash_1 = require("./x402-guard-upstash");
938
+ Object.defineProperty(exports, "createUpstashX402GuardStore", { enumerable: true, get: function () { return x402_guard_upstash_1.createUpstashX402GuardStore; } });
939
+ exports.default = Agent;
940
+ var resilient_ws_1 = require("./resilient-ws");
941
+ Object.defineProperty(exports, "ResilientSignalClient", { enumerable: true, get: function () { return resilient_ws_1.ResilientSignalClient; } });
package/dist/metrics.d.ts CHANGED
@@ -105,4 +105,3 @@ export interface X402MetricsOptions {
105
105
  * @param options - Optional configuration for routes and histogram buckets
106
106
  */
107
107
  export declare function x402Metrics(inner: (req: any, res: any, next: any) => Promise<void>, options?: X402MetricsOptions): X402MetricsResult;
108
- //# sourceMappingURL=metrics.d.ts.map
package/dist/metrics.js CHANGED
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  /**
2
3
  * x402Metrics — Prometheus observability wrapper for x402Serve.
3
4
  *
@@ -44,6 +45,8 @@
44
45
  * app.get('/metrics', metricsHandler); // no payment required
45
46
  * ```
46
47
  */
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.x402Metrics = x402Metrics;
47
50
  // Histogram bucket boundaries (seconds) — matches Prometheus convention
48
51
  const DEFAULT_LATENCY_BUCKETS = [0.1, 0.5, 1, 2.5, 5, 10];
49
52
  /**
@@ -154,7 +157,7 @@ function renderPrometheus(state) {
154
157
  * @param inner - The Express middleware returned by x402Serve
155
158
  * @param options - Optional configuration for routes and histogram buckets
156
159
  */
157
- export function x402Metrics(inner, options) {
160
+ function x402Metrics(inner, options) {
158
161
  const state = {
159
162
  challenges: {},
160
163
  vSuccess: {},
@@ -343,4 +346,3 @@ export function x402Metrics(inner, options) {
343
346
  };
344
347
  return { handler: wrappedHandler, metricsHandler, snapshot, reset };
345
348
  }
346
- //# sourceMappingURL=metrics.js.map
@@ -0,0 +1 @@
1
+ export {};