nirium 0.14.1 → 0.15.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
@@ -111,9 +111,7 @@ const data = await response.json();
111
111
 
112
112
  ```typescript
113
113
  import { x402Serve } from 'nirium';
114
- import express from 'express';
115
114
 
116
- const app = express();
117
115
  app.use('/premium', x402Serve({
118
116
  payTo: 'G...', // your Stellar address — where payments land
119
117
  routes: { 'GET /signals': '$0.02' },
@@ -123,6 +121,8 @@ app.use('/premium', x402Serve({
123
121
 
124
122
  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
123
 
124
+ **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.
125
+
126
126
  **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
127
 
128
128
  **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.
@@ -137,6 +137,78 @@ Runs on **your own server**, not Nirium's — `x402Serve()` is a client-side fun
137
137
  | **x402 Premium** | `/api/v1/premium/signals` ($0.02 USDC), `/api/v1/premium/market` ($0.05 USDC) |
138
138
  | **MPP** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` |
139
139
 
140
+ ### x402 Metrics — Observability Wrapper
141
+
142
+ Wrap your `x402Serve` handler with `x402Metrics` to get Prometheus-format counters, histograms, and revenue tracking — no changes to your payment logic.
143
+
144
+ ```typescript
145
+ import express from 'express';
146
+ import { x402Serve, x402Metrics } from 'nirium';
147
+
148
+ const app = express();
149
+
150
+ const { handler, metricsHandler } = x402Metrics(
151
+ x402Serve({
152
+ payTo: 'G...',
153
+ routes: { 'GET /signals': '$0.02' },
154
+ facilitatorApiKey: 'oz_...',
155
+ }),
156
+ );
157
+
158
+ app.use('/premium', handler);
159
+ app.get('/metrics', metricsHandler); // no payment required
160
+
161
+ app.listen(3000);
162
+ ```
163
+
164
+ Scrape the endpoint with curl:
165
+
166
+ ```bash
167
+ curl -s http://localhost:3000/metrics
168
+ ```
169
+
170
+ Output:
171
+
172
+ ```
173
+ # HELP x402_challenges_total Total402 payment challenges issued
174
+ # TYPE x402_challenges_total counter
175
+ x402_challenges_total{route="GET /signals"} 12
176
+ # HELP x402_verify_success_total Total successful payment verifications
177
+ # TYPE x402_verify_success_total counter
178
+ x402_verify_success_total{route="GET /signals"} 8
179
+ # HELP x402_verify_fail_total Total failed payment verifications
180
+ # TYPE x402_verify_fail_total counter
181
+ x402_verify_fail_total{route="GET /signals"} 2
182
+ # HELP x402_settle_success_total Total successful settlements
183
+ # TYPE x402_settle_success_total counter
184
+ x402_settle_success_total{route="GET /signals"} 8
185
+ # HELP x402_settle_fail_total Total failed settlements
186
+ # TYPE x402_settle_fail_total counter
187
+ x402_settle_fail_total{route="GET /signals"} 1
188
+ # HELP x402_infra_errors_total Total facilitator/infrastructure errors (5xx)
189
+ # TYPE x402_infra_errors_total counter
190
+ x402_infra_errors_total{route="GET /signals"} 1
191
+ # HELP x402_rejections_total Total403 rejections from protected-request hooks
192
+ # TYPE x402_rejections_total counter
193
+ x402_rejections_total{route="GET /signals"} 1
194
+ # HELP x402_revenue_total Revenue collected per route and asset
195
+ # TYPE x402_revenue_total counter
196
+ x402_revenue_total{route="GET /signals",asset="USDC"} 160000
197
+ # HELP x402_settlement_latency_seconds Request latency in seconds (approximate settlement time)
198
+ # TYPE x402_settlement_latency_seconds histogram
199
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="0.1"} 5
200
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="0.5"} 7
201
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="1"} 8
202
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="2.5"} 8
203
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="5"} 8
204
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="10"} 8
205
+ x402_settlement_latency_seconds_bucket{route="GET /signals",le="+Inf"} 8
206
+ x402_settlement_latency_seconds_sum{route="GET /signals"} 3.42
207
+ x402_settlement_latency_seconds_count{route="GET /signals"} 8
208
+ ```
209
+
210
+ No payer addresses or PII are included in metrics output — aggregates only.
211
+
140
212
  ## Payouts
141
213
 
142
214
  Batch disbursement, non-custodial: the node builds an **unsigned** transaction, you sign it with your own wallet and broadcast it. Nirium never holds funds and never sees your keys.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type X402GuardConfig } from './x402-guard';
1
2
  export interface AgentConfig {
2
3
  apiKey: string;
3
4
  baseUrl?: string;
@@ -879,10 +880,19 @@ export interface X402ServeConfig {
879
880
  facilitatorAuthHeader?: string;
880
881
  appName?: string;
881
882
  appLogo?: string;
883
+ /**
884
+ * Optional replay/rate-limit protection - off by default. Providing
885
+ * `guard.store` turns it on; without it, x402Serve() behaves exactly
886
+ * as before. See x402-guard.ts and
887
+ * https://github.com/nirium-protocol/nirium/issues/91.
888
+ */
889
+ guard?: X402GuardConfig;
882
890
  }
883
891
  export declare function x402Serve(config: X402ServeConfig): any;
884
- export { x402Metrics } from './metrics.js';
885
- export type { X402MetricsResult, MetricsSnapshot } from './metrics.js';
892
+ export { x402Metrics } from './metrics';
893
+ export type { X402MetricsResult, MetricsSnapshot } from './metrics';
894
+ export type { X402GuardStore, X402GuardConfig, GuardRequest, GuardDenied } from './x402-guard';
895
+ export { createUpstashX402GuardStore } from './x402-guard-upstash';
896
+ export type { UpstashX402GuardStoreOptions } from './x402-guard-upstash';
886
897
  export default Agent;
887
- export { ResilientSignalClient, type ResilientSignalClientOptions, type ConnectionStatus, type ConnectionStatusInfo, } from './resilient-ws.js';
888
- //# sourceMappingURL=index.d.ts.map
898
+ export { ResilientSignalClient, type ResilientSignalClientOptions, type ConnectionStatus, type ConnectionStatusInfo, } from './resilient-ws';
package/dist/index.js CHANGED
@@ -1,18 +1,58 @@
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.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");
11
50
  // @ts-ignore
12
- import { createEd25519Signer } from '@x402/stellar';
51
+ const stellar_1 = require("@x402/stellar");
13
52
  // @ts-ignore
14
- import { ExactStellarScheme } from '@x402/stellar/exact/client';
15
- import * as MppxModule from 'mppx';
53
+ const client_1 = require("@x402/stellar/exact/client");
54
+ const MppxModule = __importStar(require("mppx"));
55
+ const x402_guard_1 = require("./x402-guard");
16
56
  /** Build a `?a=1&b=2` suffix, dropping undefined values. Returns '' when empty. */
17
57
  function queryString(params) {
18
58
  if (!params)
@@ -50,7 +90,7 @@ function queryString(params) {
50
90
  * });
51
91
  * ```
52
92
  */
53
- export class Agent {
93
+ class Agent {
54
94
  apiKey;
55
95
  baseUrl;
56
96
  wsUrl;
@@ -430,10 +470,10 @@ export class Agent {
430
470
  this.connectWebSocket();
431
471
  }
432
472
  connectWebSocket(subscriptionId) {
433
- if (this.ws?.readyState === WebSocket.OPEN)
473
+ if (this.ws?.readyState === ws_1.default.OPEN)
434
474
  return;
435
475
  const authQuery = this.token ? `?token=${this.token}` : '';
436
- this.ws = new WebSocket(`${this.wsUrl}${authQuery}`);
476
+ this.ws = new ws_1.default(`${this.wsUrl}${authQuery}`);
437
477
  this.ws.on('open', () => {
438
478
  console.log('[Nirium SDK] WebSocket connected');
439
479
  this.reconnectAttempts = 0;
@@ -506,15 +546,15 @@ export class Agent {
506
546
  if (config.signer && config.secretKey) {
507
547
  throw new Error('initX402 got both `secretKey` and `signer` — pass only one, so it is unambiguous which key signs.');
508
548
  }
509
- const signer = config.signer ?? createEd25519Signer(config.secretKey, network);
549
+ const signer = config.signer ?? stellar_1.createEd25519Signer(config.secretKey, network);
510
550
  // Pubnet: el SDF NO corre RPC público de mainnet — soroban.stellar.org no
511
551
  // existe. Default al RPC público de gateway.fm (mismo default que
512
552
  // @stellar/mpp); siempre overrideable por config.rpcUrl.
513
553
  const rpcUrl = config.rpcUrl || (network.includes('testnet')
514
554
  ? 'https://soroban-testnet.stellar.org'
515
555
  : '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) };
556
+ const client = new fetch_1.x402Client().register('stellar:*', new client_1.ExactStellarScheme(signer, { url: rpcUrl }));
557
+ this.x402Client = { fetch: (0, fetch_1.wrapFetchWithPayment)(fetch, client) };
518
558
  }
519
559
  /**
520
560
  * Fetch a paid resource via x402 protocol.
@@ -574,6 +614,7 @@ export class Agent {
574
614
  this.logCallbacks = [];
575
615
  }
576
616
  }
617
+ exports.Agent = Agent;
577
618
  // ─── x402Serve — el otro lado del mostrador ────────────────────
578
619
  //
579
620
  // `initX402` te deja PAGAR por APIs ajenas. Esto te deja COBRAR por la tuya.
@@ -619,7 +660,8 @@ const pingX402ServeTelemetry = (body) => {
619
660
  };
620
661
  const sdkVersionForTelemetry = () => {
621
662
  try {
622
- return createRequire(import.meta.url)('../package.json').version;
663
+ // CommonJS build: plain `require` is already in scope, no import.meta needed.
664
+ return require('../package.json').version;
623
665
  }
624
666
  catch {
625
667
  return undefined;
@@ -629,7 +671,7 @@ const X402_FACILITATORS = {
629
671
  'stellar:pubnet': 'https://channels.openzeppelin.com/x402',
630
672
  'stellar:testnet': 'https://channels.openzeppelin.com/x402/testnet',
631
673
  };
632
- export function x402Serve(config) {
674
+ function x402Serve(config) {
633
675
  if (!config.payTo || !/^G[A-Z2-7]{55}$/.test(config.payTo)) {
634
676
  throw new Error('x402Serve: `payTo` must be a Stellar public key (G...). Without it there is nobody to pay.');
635
677
  }
@@ -658,7 +700,7 @@ export function x402Serve(config) {
658
700
  // formatos y distingue de verdad entre ausente y roto.
659
701
  const load = async (m) => {
660
702
  try {
661
- return await import(/* @vite-ignore */ m);
703
+ return await Promise.resolve(`${m}`).then(s => __importStar(require(s)));
662
704
  }
663
705
  catch (err) {
664
706
  const missing = /cannot find (module|package)/i.test(String(err?.message));
@@ -694,7 +736,7 @@ export function x402Serve(config) {
694
736
  };
695
737
  }
696
738
  const facilitatorKeyHash = config.facilitatorApiKey
697
- ? createHash('sha256').update(config.facilitatorApiKey).digest('hex').slice(0, 16)
739
+ ? (0, node_crypto_1.createHash)('sha256').update(config.facilitatorApiKey).digest('hex').slice(0, 16)
698
740
  : undefined;
699
741
  const sdkVersion = sdkVersionForTelemetry();
700
742
  pingX402ServeTelemetry({
@@ -783,8 +825,34 @@ export function x402Serve(config) {
783
825
  requestsSinceFlush = 0;
784
826
  lastFlush = Date.now();
785
827
  };
828
+ const sendDenied = (res, d) => {
829
+ if (d.headers)
830
+ for (const [k, v] of Object.entries(d.headers))
831
+ res.setHeader(k, v);
832
+ res.status(d.status).json(d.body);
833
+ };
786
834
  return async function niriumX402(req, res, next) {
787
835
  maybeFlushHeartbeat();
836
+ if (config.guard) {
837
+ const guardReq = { method: req.method, url: req.originalUrl ?? req.url, headers: req.headers, ip: req.ip };
838
+ const rl = await (0, x402_guard_1.checkRateLimit)(guardReq, config.guard);
839
+ if (!rl.allowed) {
840
+ sendDenied(res, rl.denied);
841
+ return;
842
+ }
843
+ const replay = await (0, x402_guard_1.checkReplay)(guardReq, config.guard);
844
+ if (!replay.allowed) {
845
+ sendDenied(res, replay.denied);
846
+ return;
847
+ }
848
+ if (replay.release) {
849
+ const release = replay.release;
850
+ res.on('finish', () => {
851
+ if (res.statusCode < 200 || res.statusCode >= 300)
852
+ release();
853
+ });
854
+ }
855
+ }
788
856
  try {
789
857
  if (!cached) {
790
858
  await preflight();
@@ -801,7 +869,10 @@ export function x402Serve(config) {
801
869
  // `.js` extension required even though the source is `.ts`: `module:
802
870
  // ESNext` emits these specifiers verbatim, and Node's native ESM resolver
803
871
  // (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
872
+ var metrics_1 = require("./metrics");
873
+ Object.defineProperty(exports, "x402Metrics", { enumerable: true, get: function () { return metrics_1.x402Metrics; } });
874
+ var x402_guard_upstash_1 = require("./x402-guard-upstash");
875
+ Object.defineProperty(exports, "createUpstashX402GuardStore", { enumerable: true, get: function () { return x402_guard_upstash_1.createUpstashX402GuardStore; } });
876
+ exports.default = Agent;
877
+ var resilient_ws_1 = require("./resilient-ws");
878
+ 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 {};