nirium 0.16.0 → 0.17.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 +118 -33
- package/dist/index.d.ts +11 -2
- package/dist/index.js +21 -3
- package/dist/x402-policy-conformance.d.ts +64 -0
- package/dist/x402-policy-conformance.js +269 -0
- package/dist/x402-spend-cap.js +2 -2
- package/package.json +19 -3
- package/dist/metrics.test.d.ts +0 -1
- package/dist/metrics.test.js +0 -614
- package/dist/x402-guard.test.d.ts +0 -11
- package/dist/x402-guard.test.js +0 -145
- package/dist/x402serve-smoke.test.d.ts +0 -9
- package/dist/x402serve-smoke.test.js +0 -158
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ console.log('Agent alive:', alive);
|
|
|
28
28
|
const market = await agent.getMarket();
|
|
29
29
|
console.log('XLM Price:', market.xlmPrice);
|
|
30
30
|
|
|
31
|
-
// Trigger a demo strategy on Nirium's own shared testnet vault
|
|
31
|
+
// Trigger a demo strategy on Nirium's own shared testnet vault - a real,
|
|
32
32
|
// working transaction, not a simulation, but it moves Nirium's testnet
|
|
33
33
|
// funds, not yours. To rebalance YOUR OWN vault, see Treasury Rebalance below.
|
|
34
34
|
const result = await agent.execute('blend-yield', 'USDC', { amount: 5000 });
|
|
@@ -82,7 +82,7 @@ const agent = new Agent({
|
|
|
82
82
|
|
|
83
83
|
## Payment Protocols
|
|
84
84
|
|
|
85
|
-
### x402
|
|
85
|
+
### x402: Pay-Per-Request
|
|
86
86
|
```typescript
|
|
87
87
|
agent.initX402({
|
|
88
88
|
secretKey: 'S...', // Stellar secret key
|
|
@@ -109,7 +109,15 @@ try {
|
|
|
109
109
|
}
|
|
110
110
|
```
|
|
111
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
|
|
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`. Other `spendControls` rejections (for example a non-default asset) still surface as the original error.
|
|
113
|
+
|
|
114
|
+
To pay an API priced above $1, raise the cap explicitly with `maxAmountPerPayment` (a USD amount: `'$5'`, `'5'` or `5`; it applies to default assets such as USDC):
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
agent.initX402({ secretKey: 'S...', network: 'stellar:pubnet', maxAmountPerPayment: '$5' });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Why the default stays at $1: an agent pays whatever a server's 402 asks for, without a human in the loop, so a low cap limits the damage from a mispriced or malicious endpoint. Raising it is a choice the integrator makes on purpose; omitting the option keeps `@x402/core`'s $1. It must be a positive amount, checked when `initX402()` runs; `false` (no cap) is not accepted. The option also applies when a `policy` is set, and a payment above the cap is refused before the policy or the signer is reached.
|
|
113
121
|
|
|
114
122
|
#### Pre-sign policy hook (experimental)
|
|
115
123
|
|
|
@@ -154,6 +162,27 @@ Only an `ALLOW` that echoes this authorization's `contextHash`, and is still val
|
|
|
154
162
|
|
|
155
163
|
**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
164
|
|
|
165
|
+
**Conformance test for your engine.** The SDK ships one shared test any engine can run ([#226](https://github.com/nirium-protocol/nirium/issues/226)). It puts your hook through the real gate and the real `@stellar/stellar-sdk` signing path, with no RPC and no network, and checks seven cases. An `ALLOW` that echoes the exact `contextHash` must sign exactly once. `DENY`, `WAIT`, an `ALLOW` with a wrong `contextHash`, an `ALLOW` past its `expiresAt`, a malformed answer and an answer after the timeout must each sign nothing. You give it one payment your engine allows and one it denies, plus one it answers `WAIT` to if it ever does. The last four cases start from your engine's own `ALLOW` and change it the way each case names. It is experimental like the hook and is not exported from the package index, so import it from `dist`:
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
// test/conformance.test.ts, run with `node --test` (via tsx for TypeScript)
|
|
169
|
+
import { runPolicyConformance } from 'nirium/dist/x402-policy-conformance.js';
|
|
170
|
+
|
|
171
|
+
runPolicyConformance({
|
|
172
|
+
name: 'my engine',
|
|
173
|
+
createHook: () => myEngine.hook(), // called once per case: return a fresh one
|
|
174
|
+
allow: { amount: '2500000' }, // base units; payTo, asset, url, method are optional
|
|
175
|
+
deny: { amount: '50000000' },
|
|
176
|
+
// wait: { amount: '1', payTo: 'G...' }, // only if your engine answers WAIT
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
**What passing means.** Your engine answers correctly (allows what it should, denies what it should, binds its `ALLOW` to the exact `contextHash`) and the gate fails closed around it. It does **not** validate your policy logic: it only checks the two or three payments you give it, and several cases (wrong hash, expired, malformed, timeout) mostly exercise the gate on top of your engine's `ALLOW`. Test the rules themselves with your own tests.
|
|
181
|
+
|
|
182
|
+
Your hook is used as-is, so a class instance works: its prototype methods (`currentVersion`, `onDecision`) are called on the instance. The timeout case runs the gate with `timeoutMs` 100 (change it with `runPolicyConformance(target, { timeoutMs })`); your engine still gets its own `timeoutMs` (default 5000 ms) to answer, so a slow remote engine does not fail that case.
|
|
183
|
+
|
|
184
|
+
Each case is a `node:test` test. To use another runner, `policyConformanceCases(target)` returns the cases as `{ name, run }`. [`examples/x402-policy-daily-budget`](../../examples/x402-policy-daily-budget) runs it in CI.
|
|
185
|
+
|
|
157
186
|
### MPP Charge (experimental)
|
|
158
187
|
|
|
159
188
|
```typescript
|
|
@@ -164,14 +193,14 @@ const response = await agent.mppFetch('https://your-mpp-server.example/resource'
|
|
|
164
193
|
|
|
165
194
|
`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
195
|
|
|
167
|
-
**
|
|
196
|
+
**Testnet: verified. Mainnet: not tested. Still experimental, not for production.**
|
|
168
197
|
|
|
169
|
-
-
|
|
170
|
-
-
|
|
198
|
+
- On 15 October 2026 (UTC) we paid Nirium's hosted **testnet** endpoint with this client (`nirium@0.16.1`), once in `pull` and once in `push` mode. Both settled on Stellar testnet and the server returned the resource: [`b8c4ed56…`](https://stellar.expert/explorer/testnet/tx/b8c4ed568f6eb41321b97d251d7f3727c57570a226d187e3675a9df03496e3ed) (pull), [`96d43d6f…`](https://stellar.expert/explorer/testnet/tx/96d43d6f4cf38fbd3a4df2c2bb6625e650c0d0509184d86c1e42c7e6ebdf242c) (push). The `402 Verification Failed` we saw on 1 October no longer reproduces.
|
|
199
|
+
- We have **not tested the mainnet endpoint** (it would spend real USDC), so we cannot tell you it works there.
|
|
171
200
|
- In `push` mode the payment settles on-chain before the server verifies it, so a request the server rejects is **not refunded**.
|
|
172
|
-
-
|
|
201
|
+
- For paid endpoints in production, use x402 (`initX402()`). The `get_mpp_*` tools of the MCP server were not re-tested.
|
|
173
202
|
|
|
174
|
-
### x402Serve()
|
|
203
|
+
### x402Serve(): Charging Your Own API
|
|
175
204
|
|
|
176
205
|
`initX402()` above lets you *pay* for someone else's API. This is the other side: charging for yours.
|
|
177
206
|
|
|
@@ -179,19 +208,77 @@ const response = await agent.mppFetch('https://your-mpp-server.example/resource'
|
|
|
179
208
|
import { x402Serve } from 'nirium';
|
|
180
209
|
|
|
181
210
|
app.use('/premium', x402Serve({
|
|
182
|
-
payTo: 'G...', // your Stellar address
|
|
211
|
+
payTo: 'G...', // your Stellar address - where payments land
|
|
212
|
+
routes: { 'GET /signals': '$0.02' },
|
|
213
|
+
facilitatorApiKey: '...', // required on both networks; OpenZeppelin Channels by default
|
|
214
|
+
}));
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
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.
|
|
218
|
+
|
|
219
|
+
**Known limitation:** by default `x402Serve()` does not protect against replay and does not rate-limit callers. It is turned on by passing `guard` (see below).
|
|
220
|
+
|
|
221
|
+
#### Replay and rate-limit guard (optional)
|
|
222
|
+
|
|
223
|
+
Without `guard`, `x402Serve()` verifies and settles the payment and does nothing else. It does not stop the same signed payment from being sent twice, and it does not limit how often one caller can hit a route. Pass `guard` to get both:
|
|
224
|
+
|
|
225
|
+
- **Replay guard:** each payment proof can be used once per method and route (`replayTtlMs`, 15 minutes by default). A second use gets `409 payment_replayed`. If the request does not end in a 2xx, the claim is released, so a normal retry still works. If the store is down, the replay check refuses the request (`503`) instead of letting it through.
|
|
226
|
+
- **Rate limit:** optional, per caller IP (`req.ip`; set Express `trust proxy` if you run behind a proxy). Past `max` requests in `windowMs` the caller gets `429 rate_limited` with a `Retry-After` header. If the store is down, rate limiting lets traffic through.
|
|
227
|
+
|
|
228
|
+
The guard needs a store with three methods (`X402GuardStore`: `claimOnce`, `release`, `slidingWindowHit`). Two options:
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
import { x402Serve, createUpstashX402GuardStore, type X402GuardStore } from 'nirium';
|
|
232
|
+
|
|
233
|
+
// Option 1: Upstash (Redis over REST). Shared between several servers.
|
|
234
|
+
const store = createUpstashX402GuardStore({
|
|
235
|
+
url: process.env.UPSTASH_REDIS_REST_URL!,
|
|
236
|
+
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
// Option 2: your own store. This one lives in memory, so it only works for a
|
|
240
|
+
// single process. For more than one server, back the same three methods with a shared store.
|
|
241
|
+
function createMemoryGuardStore(): X402GuardStore {
|
|
242
|
+
const claims = new Map<string, number>(); // key -> expires at
|
|
243
|
+
const hits = new Map<string, { t: number; member: string }[]>();
|
|
244
|
+
return {
|
|
245
|
+
async claimOnce(key, ttlMs) {
|
|
246
|
+
const now = Date.now();
|
|
247
|
+
if ((claims.get(key) ?? 0) > now) return false;
|
|
248
|
+
claims.set(key, now + ttlMs);
|
|
249
|
+
return true;
|
|
250
|
+
},
|
|
251
|
+
async release(key) { claims.delete(key); },
|
|
252
|
+
async slidingWindowHit(key, windowMs, member) {
|
|
253
|
+
const now = Date.now();
|
|
254
|
+
const list = (hits.get(key) ?? []).filter((h) => h.t > now - windowMs);
|
|
255
|
+
list.push({ t: now, member });
|
|
256
|
+
hits.set(key, list);
|
|
257
|
+
return list.length;
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
app.use('/premium', x402Serve({
|
|
263
|
+
payTo: 'G...',
|
|
183
264
|
routes: { 'GET /signals': '$0.02' },
|
|
184
|
-
facilitatorApiKey: '...',
|
|
265
|
+
facilitatorApiKey: '...',
|
|
266
|
+
guard: {
|
|
267
|
+
store, // or createMemoryGuardStore()
|
|
268
|
+
rateLimit: { max: 60, windowMs: 60_000 }, // optional
|
|
269
|
+
},
|
|
185
270
|
}));
|
|
186
271
|
```
|
|
187
272
|
|
|
188
|
-
|
|
273
|
+
No in-memory store ships with the package, and you do not need Upstash: any store that implements the three methods works. The design comes from a real production integration by Edgadafi ([Edgadafi/remesa-liquidez](https://github.com/Edgadafi/remesa-liquidez)); see [issue #91](https://github.com/nirium-protocol/nirium/issues/91). The code here is ours. Thanks, Edgadafi.
|
|
274
|
+
|
|
275
|
+
**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.
|
|
189
276
|
|
|
190
|
-
**
|
|
277
|
+
**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.
|
|
191
278
|
|
|
192
|
-
|
|
279
|
+
### Resilient WebSocket client
|
|
193
280
|
|
|
194
|
-
|
|
281
|
+
`ResilientSignalClient` is a WebSocket client for `/ws/signals` that reconnects by itself with backoff, pings to detect dead connections, and drops duplicate signals. Create it with `{ url, token }`, call `connect()`, and listen with `onSignal()`, `onStatus()` and `onError()`; `close()` stops it.
|
|
195
282
|
|
|
196
283
|
### Endpoint Access Model
|
|
197
284
|
|
|
@@ -199,13 +286,13 @@ Runs on **your own server**, not Nirium's — `x402Serve()` is a client-side fun
|
|
|
199
286
|
|---|---|
|
|
200
287
|
| **Public** (no key) | `health`, `loop/status`, `execute-demo`, `signals/recent`, `skills` list |
|
|
201
288
|
| **Protected** (API key) | `execute`, `market`, `loop/start\|stop\|scan`, `subscriptions`, `skills/install`, `webhooks` |
|
|
202
|
-
| **WebSocket** (JWT) | `/ws/signals`
|
|
203
|
-
| **x402 Premium** | `/api/v1/premium/signals` ($0.02 USDC), `/api/v1/premium/market` ($0.05 USDC) |
|
|
204
|
-
| **MPP Charge** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` (testnet
|
|
289
|
+
| **WebSocket** (JWT) | `/ws/signals` - real-time signal stream |
|
|
290
|
+
| **x402 Premium** | `/api/v1/premium/signals` ($0.02 USDC), `/api/v1/premium/market` ($0.05 USDC). `/premium/signals` only exists on testnet: on mainnet it answers `501` (no signal source there) and does not charge. `/premium/market` is paid on both networks. |
|
|
291
|
+
| **MPP Charge** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` (testnet verified with settled payments on 15 Oct 2026, mainnet untested, see [MPP Charge](#mpp-charge-experimental)) |
|
|
205
292
|
|
|
206
|
-
### x402 Metrics
|
|
293
|
+
### x402 Metrics: Observability Wrapper
|
|
207
294
|
|
|
208
|
-
Wrap your `x402Serve` handler with `x402Metrics` to get Prometheus-format counters, histograms, and revenue tracking
|
|
295
|
+
Wrap your `x402Serve` handler with `x402Metrics` to get Prometheus-format counters, histograms, and revenue tracking - no changes to your payment logic.
|
|
209
296
|
|
|
210
297
|
```typescript
|
|
211
298
|
import express from 'express';
|
|
@@ -273,7 +360,7 @@ x402_settlement_latency_seconds_sum{route="GET /signals"} 3.42
|
|
|
273
360
|
x402_settlement_latency_seconds_count{route="GET /signals"} 8
|
|
274
361
|
```
|
|
275
362
|
|
|
276
|
-
No payer addresses or PII are included in metrics output
|
|
363
|
+
No payer addresses or PII are included in metrics output - aggregates only.
|
|
277
364
|
|
|
278
365
|
## Payouts
|
|
279
366
|
|
|
@@ -282,7 +369,7 @@ Batch disbursement, non-custodial: the node builds an **unsigned** transaction,
|
|
|
282
369
|
```typescript
|
|
283
370
|
const run = await agent.createPayoutRun({
|
|
284
371
|
recipients: [{ wallet: 'GABC...', amount: '250.00' }],
|
|
285
|
-
acknowledgeTerms: true, // required on every network
|
|
372
|
+
acknowledgeTerms: true, // required on every network - 403 without it
|
|
286
373
|
});
|
|
287
374
|
|
|
288
375
|
const signedXdr = await signWithYourWallet(run.xdr);
|
|
@@ -290,23 +377,23 @@ const settled = await agent.submitPayout(run.runId, signedXdr);
|
|
|
290
377
|
console.log(settled.txHash, settled.cid); // on-chain hash + IPFS receipt
|
|
291
378
|
```
|
|
292
379
|
|
|
293
|
-
Licensed for **independent service payments only**
|
|
380
|
+
Licensed for **independent service payments only** - contractors, freelancers, B2B. Not for subordinate-employee salary. Read `getPayoutTerms()` before integrating; classifying recipients and meeting tax and labor obligations is the client's responsibility.
|
|
294
381
|
|
|
295
382
|
Mainnet is invite-only during early access and additionally requires `clientInfo`.
|
|
296
383
|
|
|
297
384
|
## Treasury Rebalance
|
|
298
385
|
|
|
299
|
-
Two ways to rebalance a DeFindex vault between idle cash and an invested strategy. Neither is a swap
|
|
386
|
+
Two ways to rebalance a DeFindex vault between idle cash and an invested strategy. Neither is a swap - the contract's `rebalance()` exposes exactly two instructions, `Unwind` and `Invest`, and neither accepts a destination address, so withdrawing anywhere but back into the vault itself is not expressible.
|
|
300
387
|
|
|
301
|
-
### Propose
|
|
388
|
+
### Propose: you review and sign, available to everyone today
|
|
302
389
|
|
|
303
|
-
The agent decides what it would do, using the same decision logic as the autonomous signer below, but it never signs. Public, no allowlist, no invite required
|
|
390
|
+
The agent decides what it would do, using the same decision logic as the autonomous signer below, but it never signs. Public, no allowlist, no invite required - works for any vault where you're already the on-chain rebalance manager.
|
|
304
391
|
|
|
305
392
|
```typescript
|
|
306
393
|
const proposal = await agent.proposeTreasuryRebalance({
|
|
307
394
|
vault: 'CABC...',
|
|
308
395
|
caller: 'GABC...', // must already be this vault's rebalanceManager on-chain
|
|
309
|
-
enterAt: 2.5, // your own mandate
|
|
396
|
+
enterAt: 2.5, // your own mandate - Nirium never supplies a default here
|
|
310
397
|
exitAt: 2.0,
|
|
311
398
|
});
|
|
312
399
|
|
|
@@ -318,13 +405,13 @@ if (proposal.instructions.length) {
|
|
|
318
405
|
}
|
|
319
406
|
```
|
|
320
407
|
|
|
321
|
-
### Autonomous
|
|
408
|
+
### Autonomous: Nirium signs, invite-only during legal review
|
|
322
409
|
|
|
323
|
-
`executeTreasuryRebalance()` has Nirium sign and submit with its own RebalanceManager key
|
|
410
|
+
`executeTreasuryRebalance()` has Nirium sign and submit with its own RebalanceManager key - full autonomy, no per-cycle approval. **This is invite-only while a specific legal question stays open**: whether executing on a client's behalf without taking custody still counts as regulated facilitation under Mexican law. It only runs against vaults explicitly allowlisted server-side; calling it against any other vault returns 403, and Nirium's mainnet infrastructure returns 501 for it entirely, since that box holds no signing key by design. Ask if you want autonomous execution today - otherwise, `proposeTreasuryRebalance()` above gives you the same decision-making with you as the one who signs.
|
|
324
411
|
|
|
325
412
|
## Audit Trail
|
|
326
413
|
|
|
327
|
-
Anchor evidence to IPFS and get back a CID
|
|
414
|
+
Anchor evidence to IPFS and get back a CID - an integrity seal, not notarization.
|
|
328
415
|
|
|
329
416
|
```typescript
|
|
330
417
|
const anchor = await agent.anchorAuditRecord({
|
|
@@ -345,10 +432,8 @@ Anchor a **hash** rather than the data itself: IPFS content cannot be deleted, s
|
|
|
345
432
|
|
|
346
433
|
- [Documentation](https://nirium.xyz/docs)
|
|
347
434
|
- [Developer Sandbox](https://nirium.xyz/sandbox)
|
|
348
|
-
- [
|
|
349
|
-
- [MCP Server Integration](https://nirium.xyz/docs/mcp)
|
|
350
|
-
- [GitHub](https://github.com/nirium-protocol/nirium-sdk)
|
|
435
|
+
- [GitHub](https://github.com/nirium-protocol/nirium)
|
|
351
436
|
|
|
352
437
|
## License
|
|
353
438
|
|
|
354
|
-
Apache 2.0
|
|
439
|
+
Apache 2.0 - Nirium Protocol
|
package/dist/index.d.ts
CHANGED
|
@@ -51,6 +51,15 @@ export interface X402Config {
|
|
|
51
51
|
* x402Fetch behaves exactly as before. See X402PolicyHook.
|
|
52
52
|
*/
|
|
53
53
|
policy?: X402PolicyHook;
|
|
54
|
+
/**
|
|
55
|
+
* Per-payment cap for x402Fetch (#106), passed to @x402/core as
|
|
56
|
+
* `spendControls.maxAmountPerPayment`. USD amount as `'$5'`, `'5'` or `5`;
|
|
57
|
+
* it applies to default assets such as USDC. Defaults to @x402/core's `'$1'`.
|
|
58
|
+
* Raising it is an explicit choice: a payment above the cap is refused
|
|
59
|
+
* before anything is signed (`X402SpendCapError`). Must be a positive
|
|
60
|
+
* amount; `false` (no cap) is deliberately not accepted here.
|
|
61
|
+
*/
|
|
62
|
+
maxAmountPerPayment?: string | number;
|
|
54
63
|
}
|
|
55
64
|
export interface MppConfig {
|
|
56
65
|
/**
|
|
@@ -522,7 +531,7 @@ export interface TreasuryVaultSummary {
|
|
|
522
531
|
*
|
|
523
532
|
* const agent = new Agent({
|
|
524
533
|
* apiKey: 'nrm_your_key_here',
|
|
525
|
-
* baseUrl: 'http://localhost:
|
|
534
|
+
* baseUrl: 'http://localhost:3002',
|
|
526
535
|
* });
|
|
527
536
|
*
|
|
528
537
|
* // Check health
|
|
@@ -899,7 +908,7 @@ export interface X402ServeConfig {
|
|
|
899
908
|
network?: 'stellar:testnet' | 'stellar:pubnet';
|
|
900
909
|
/** Default: OpenZeppelin Channels, el facilitador canónico de Stellar. */
|
|
901
910
|
facilitatorUrl?: string;
|
|
902
|
-
/**
|
|
911
|
+
/** Las dos redes lo exigen - el facilitador rechaza un servidor sin llave también en testnet. */
|
|
903
912
|
facilitatorApiKey?: string;
|
|
904
913
|
facilitatorAuthHeader?: string;
|
|
905
914
|
appName?: string;
|
package/dist/index.js
CHANGED
|
@@ -58,6 +58,18 @@ const client_3 = require("@stellar/mpp/charge/client");
|
|
|
58
58
|
const x402_guard_1 = require("./x402-guard");
|
|
59
59
|
const x402_policy_1 = require("./x402-policy");
|
|
60
60
|
const x402_spend_cap_1 = require("./x402-spend-cap");
|
|
61
|
+
/** Validates and normalizes `maxAmountPerPayment` at initX402 time ("$5" form). */
|
|
62
|
+
function normalizeMaxAmountPerPayment(v) {
|
|
63
|
+
if (v === undefined)
|
|
64
|
+
return undefined;
|
|
65
|
+
const text = typeof v === 'number' ? (Number.isFinite(v) ? String(v) : '') : typeof v === 'string' ? v.trim() : '';
|
|
66
|
+
const m = /^\$?(\d+(?:\.\d+)?)$/.exec(text);
|
|
67
|
+
if (!m || !(Number(m[1]) > 0)) {
|
|
68
|
+
throw new Error('initX402: `maxAmountPerPayment` must be a positive USD amount such as \'$5\', \'5\' or 5 '
|
|
69
|
+
+ `(got ${JSON.stringify(v)}). Omit it to keep the $1 default.`);
|
|
70
|
+
}
|
|
71
|
+
return `$${m[1]}`;
|
|
72
|
+
}
|
|
61
73
|
/** Build a `?a=1&b=2` suffix, dropping undefined values. Returns '' when empty. */
|
|
62
74
|
function queryString(params) {
|
|
63
75
|
if (!params)
|
|
@@ -74,7 +86,7 @@ function queryString(params) {
|
|
|
74
86
|
*
|
|
75
87
|
* const agent = new Agent({
|
|
76
88
|
* apiKey: 'nrm_your_key_here',
|
|
77
|
-
* baseUrl: 'http://localhost:
|
|
89
|
+
* baseUrl: 'http://localhost:3002',
|
|
78
90
|
* });
|
|
79
91
|
*
|
|
80
92
|
* // Check health
|
|
@@ -110,7 +122,7 @@ class Agent {
|
|
|
110
122
|
mppClient = null;
|
|
111
123
|
constructor(config) {
|
|
112
124
|
this.apiKey = config.apiKey;
|
|
113
|
-
this.baseUrl = (config.baseUrl || 'http://localhost:
|
|
125
|
+
this.baseUrl = (config.baseUrl || 'http://localhost:3002').replace(/\/$/, '');
|
|
114
126
|
this.wsUrl = config.wsUrl || this.baseUrl.replace(/^http/, 'ws') + '/ws/signals';
|
|
115
127
|
this.token = config.token || null;
|
|
116
128
|
}
|
|
@@ -554,6 +566,7 @@ class Agent {
|
|
|
554
566
|
}
|
|
555
567
|
if (config.policy !== undefined)
|
|
556
568
|
(0, x402_policy_1.assertValidPolicyHook)(config.policy);
|
|
569
|
+
const maxAmountPerPayment = normalizeMaxAmountPerPayment(config.maxAmountPerPayment);
|
|
557
570
|
const signer = config.signer ?? stellar_1.createEd25519Signer(config.secretKey, network);
|
|
558
571
|
// Pubnet: el SDF NO corre RPC público de mainnet — soroban.stellar.org no
|
|
559
572
|
// existe. Default al RPC público de gateway.fm (mismo default que
|
|
@@ -565,13 +578,16 @@ class Agent {
|
|
|
565
578
|
// Con policy el cliente se arma en cada x402Fetch: el signer de
|
|
566
579
|
// stellar-sdk no recibe la URL, y un closure por llamada ata URL,
|
|
567
580
|
// método y requisitos a ese pago sin estado compartido.
|
|
568
|
-
this.x402Policy = { base: signer, rpcUrl, policy: config.policy };
|
|
581
|
+
this.x402Policy = { base: signer, rpcUrl, policy: config.policy, maxAmountPerPayment };
|
|
569
582
|
this.x402Client = null;
|
|
570
583
|
return;
|
|
571
584
|
}
|
|
572
585
|
this.x402Policy = null;
|
|
573
586
|
const scheme = new client_1.ExactStellarScheme(signer, { url: rpcUrl });
|
|
574
587
|
const client = new fetch_1.x402Client().register('stellar:*', scheme);
|
|
588
|
+
// Sin la opción no se toca spendControls: @x402/core aplica su $1.
|
|
589
|
+
if (maxAmountPerPayment)
|
|
590
|
+
client.setSpendControls({ maxAmountPerPayment });
|
|
575
591
|
// El cliente es uno solo; el fetch envuelto se arma en cada llamada
|
|
576
592
|
// (un closure barato) para que lo capturado de cada 402 sea de esa llamada.
|
|
577
593
|
this.x402Client = { client, scheme, baseFetch: fetch };
|
|
@@ -613,6 +629,8 @@ class Agent {
|
|
|
613
629
|
payTo: r.payTo, amount: r.amount, maxTimeoutSeconds: r.maxTimeoutSeconds,
|
|
614
630
|
};
|
|
615
631
|
});
|
|
632
|
+
if (cfg.maxAmountPerPayment)
|
|
633
|
+
client.setSpendControls({ maxAmountPerPayment: cfg.maxAmountPerPayment });
|
|
616
634
|
// NUNCA registrar onPaymentCreationFailure aquí: puede devolver un
|
|
617
635
|
// payload sin pasar por el signer, y el gate quedaría puenteado.
|
|
618
636
|
try {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Keypair } from '@stellar/stellar-sdk';
|
|
2
|
+
import { createPolicyGatedSigner, type X402PolicyHook } from './x402-policy';
|
|
3
|
+
/** One payment the engine is asked about. Unset fields get test defaults. */
|
|
4
|
+
export interface ConformancePayment {
|
|
5
|
+
/** Amount in the asset's base units (USDC has 7 decimals). */
|
|
6
|
+
amount: string;
|
|
7
|
+
/** Destination G... address. Default: a fresh random account. */
|
|
8
|
+
payTo?: string;
|
|
9
|
+
/** Asset contract C... address. Default: testnet USDC. */
|
|
10
|
+
asset?: string;
|
|
11
|
+
/** Default 'https://conformance.test/paid'. */
|
|
12
|
+
url?: string;
|
|
13
|
+
/** Default 'GET'. */
|
|
14
|
+
method?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface PolicyConformanceTarget {
|
|
17
|
+
/** Used in test names. */
|
|
18
|
+
name: string;
|
|
19
|
+
/**
|
|
20
|
+
* Returns the hook to test. Called once per case, so state such as a spent
|
|
21
|
+
* budget does not leak between cases.
|
|
22
|
+
*/
|
|
23
|
+
createHook: () => X402PolicyHook | Promise<X402PolicyHook>;
|
|
24
|
+
/** A payment the engine must ALLOW. */
|
|
25
|
+
allow: ConformancePayment;
|
|
26
|
+
/** A payment the engine must DENY. */
|
|
27
|
+
deny: ConformancePayment;
|
|
28
|
+
/**
|
|
29
|
+
* A payment the engine itself answers WAIT for. Engines that never wait
|
|
30
|
+
* leave it out; the WAIT case then turns the engine's ALLOW into a WAIT.
|
|
31
|
+
*/
|
|
32
|
+
wait?: ConformancePayment;
|
|
33
|
+
/** Payer keypair. Default: a fresh random one (never funded). */
|
|
34
|
+
payer?: Keypair;
|
|
35
|
+
}
|
|
36
|
+
export interface ConformanceOptions {
|
|
37
|
+
/**
|
|
38
|
+
* The gate under test. Default: the SDK's createPolicyGatedSigner. Only the
|
|
39
|
+
* suite's own meta-tests replace it, to prove the refusal cases catch a
|
|
40
|
+
* gate that signs when it should not.
|
|
41
|
+
*/
|
|
42
|
+
gate?: typeof createPolicyGatedSigner;
|
|
43
|
+
/**
|
|
44
|
+
* The gate's deadline in the timeout case. Default 100. The engine's own
|
|
45
|
+
* answer is awaited outside this deadline, so it does not need to be
|
|
46
|
+
* faster than this; it only bounds how long that case's gate waits.
|
|
47
|
+
*/
|
|
48
|
+
timeoutMs?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface ConformanceCase {
|
|
51
|
+
name: string;
|
|
52
|
+
run: () => Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
/** The cases, as plain functions, so they can be run under any test runner. */
|
|
55
|
+
export declare function policyConformanceCases(target: PolicyConformanceTarget, options?: ConformanceOptions): ConformanceCase[];
|
|
56
|
+
/**
|
|
57
|
+
* Registers every case as a node:test test. Call it at the top level of a
|
|
58
|
+
* test file:
|
|
59
|
+
*
|
|
60
|
+
* runPolicyConformance({ name: 'my engine', createHook, allow, deny });
|
|
61
|
+
*/
|
|
62
|
+
export declare function runPolicyConformance(target: PolicyConformanceTarget, options?: ConformanceOptions & {
|
|
63
|
+
test?: (name: string, fn: () => Promise<void>) => unknown;
|
|
64
|
+
}): void;
|