nirium 0.16.1 → 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 +36 -7
- 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 +16 -1
- 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
|
@@ -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,12 +193,12 @@ 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
203
|
### x402Serve(): Charging Your Own API
|
|
175
204
|
|
|
@@ -181,7 +210,7 @@ import { x402Serve } from 'nirium';
|
|
|
181
210
|
app.use('/premium', x402Serve({
|
|
182
211
|
payTo: 'G...', // your Stellar address - where payments land
|
|
183
212
|
routes: { 'GET /signals': '$0.02' },
|
|
184
|
-
facilitatorApiKey: '...', // required on
|
|
213
|
+
facilitatorApiKey: '...', // required on both networks; OpenZeppelin Channels by default
|
|
185
214
|
}));
|
|
186
215
|
```
|
|
187
216
|
|
|
@@ -259,7 +288,7 @@ No in-memory store ships with the package, and you do not need Upstash: any stor
|
|
|
259
288
|
| **Protected** (API key) | `execute`, `market`, `loop/start\|stop\|scan`, `subscriptions`, `skills/install`, `webhooks` |
|
|
260
289
|
| **WebSocket** (JWT) | `/ws/signals` - real-time signal stream |
|
|
261
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. |
|
|
262
|
-
| **MPP Charge** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` (testnet
|
|
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)) |
|
|
263
292
|
|
|
264
293
|
### x402 Metrics: Observability Wrapper
|
|
265
294
|
|
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;
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3
|
+
// Conformance suite for pre-sign policy engines (#226).
|
|
4
|
+
//
|
|
5
|
+
// Any engine that plugs into initX402({ policy }) can run the same seven
|
|
6
|
+
// cases through the SDK's real gate (createPolicyGatedSigner) and the real
|
|
7
|
+
// stellar-sdk: ALLOW with the exact contextHash, DENY, WAIT, a wrong
|
|
8
|
+
// contextHash, an expired expiresAt, a malformed answer and a timeout. Only
|
|
9
|
+
// the first one may end in a signature.
|
|
10
|
+
//
|
|
11
|
+
// The engine supplies two payments: one it must ALLOW and one it must DENY
|
|
12
|
+
// (and, optionally, one it must WAIT). The last four cases start from the
|
|
13
|
+
// engine's own ALLOW for the allow payment and change it in the way each case
|
|
14
|
+
// names, so they check that the engine's answer and the gate together still
|
|
15
|
+
// fail closed, without asking the engine to misbehave.
|
|
16
|
+
//
|
|
17
|
+
// No RPC, no network, nothing broadcast. Experimental, like the hook itself;
|
|
18
|
+
// not exported from the package index. Import it from
|
|
19
|
+
// `nirium/dist/x402-policy-conformance.js`.
|
|
20
|
+
// ═══════════════════════════════════════════════════════════════
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.policyConformanceCases = policyConformanceCases;
|
|
23
|
+
exports.runPolicyConformance = runPolicyConformance;
|
|
24
|
+
const node_test_1 = require("node:test");
|
|
25
|
+
const stellar_sdk_1 = require("@stellar/stellar-sdk");
|
|
26
|
+
const x402_policy_1 = require("./x402-policy");
|
|
27
|
+
const USDC_TESTNET = 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA';
|
|
28
|
+
class ConformanceFailure extends Error {
|
|
29
|
+
constructor(message) { super(message); this.name = 'ConformanceFailure'; }
|
|
30
|
+
}
|
|
31
|
+
const check = (cond, message) => {
|
|
32
|
+
if (!cond)
|
|
33
|
+
throw new ConformanceFailure(message);
|
|
34
|
+
};
|
|
35
|
+
let nonceSeq = BigInt(Date.now()) * 1000n;
|
|
36
|
+
/** The cases, as plain functions, so they can be run under any test runner. */
|
|
37
|
+
function policyConformanceCases(target, options = {}) {
|
|
38
|
+
const gate = options.gate ?? x402_policy_1.createPolicyGatedSigner;
|
|
39
|
+
const payer = target.payer ?? stellar_sdk_1.Keypair.random();
|
|
40
|
+
const defaultPayTo = stellar_sdk_1.Keypair.random().publicKey();
|
|
41
|
+
const timeoutMs = options.timeoutMs ?? 100;
|
|
42
|
+
const requirements = (p) => ({
|
|
43
|
+
scheme: 'exact', network: 'stellar:testnet', asset: p.asset ?? USDC_TESTNET,
|
|
44
|
+
payTo: p.payTo ?? defaultPayTo, amount: p.amount, maxTimeoutSeconds: 60,
|
|
45
|
+
});
|
|
46
|
+
/** The transfer(from,to,amount) auth entry ExactStellarScheme would ask to sign. */
|
|
47
|
+
const entry = (r) => new stellar_sdk_1.xdr.SorobanAuthorizationEntry({
|
|
48
|
+
credentials: stellar_sdk_1.xdr.SorobanCredentials.sorobanCredentialsAddress(new stellar_sdk_1.xdr.SorobanAddressCredentials({
|
|
49
|
+
address: new stellar_sdk_1.Address(payer.publicKey()).toScAddress(),
|
|
50
|
+
nonce: stellar_sdk_1.xdr.Int64.fromString(String(nonceSeq++)),
|
|
51
|
+
signatureExpirationLedger: 0,
|
|
52
|
+
signature: stellar_sdk_1.xdr.ScVal.scvVoid(),
|
|
53
|
+
})),
|
|
54
|
+
rootInvocation: new stellar_sdk_1.xdr.SorobanAuthorizedInvocation({
|
|
55
|
+
function: stellar_sdk_1.xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(new stellar_sdk_1.xdr.InvokeContractArgs({
|
|
56
|
+
contractAddress: new stellar_sdk_1.Address(r.asset).toScAddress(),
|
|
57
|
+
functionName: 'transfer',
|
|
58
|
+
args: [
|
|
59
|
+
(0, stellar_sdk_1.nativeToScVal)(payer.publicKey(), { type: 'address' }),
|
|
60
|
+
(0, stellar_sdk_1.nativeToScVal)(r.payTo, { type: 'address' }),
|
|
61
|
+
(0, stellar_sdk_1.nativeToScVal)(r.amount, { type: 'i128' }),
|
|
62
|
+
],
|
|
63
|
+
})),
|
|
64
|
+
subInvocations: [],
|
|
65
|
+
}),
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Runs one payment through the gate. `alter` changes the engine's answer
|
|
69
|
+
* (or the hook) the way a case needs; the engine is still asked first.
|
|
70
|
+
*/
|
|
71
|
+
const attempt = async (p, alter) => {
|
|
72
|
+
const seen = { signed: false, signerCalls: 0, records: [], engineDecisions: [], contextHashes: [] };
|
|
73
|
+
const engine = await target.createHook();
|
|
74
|
+
// Read each field explicitly and call methods on the engine itself:
|
|
75
|
+
// a spread would drop prototype methods of a class-based engine (so
|
|
76
|
+
// currentVersion, and with it the stale-version check, would vanish)
|
|
77
|
+
// and would call them without their `this`.
|
|
78
|
+
let hook = {
|
|
79
|
+
timeoutMs: engine.timeoutMs,
|
|
80
|
+
requireExpiry: engine.requireExpiry,
|
|
81
|
+
evaluate: async (ctx, opts) => {
|
|
82
|
+
seen.contextHashes.push(ctx.contextHash);
|
|
83
|
+
const d = await engine.evaluate(ctx, opts);
|
|
84
|
+
seen.engineDecisions.push(d);
|
|
85
|
+
return d;
|
|
86
|
+
},
|
|
87
|
+
onDecision: (r) => { seen.records.push(r); return engine.onDecision?.(r); },
|
|
88
|
+
};
|
|
89
|
+
if (engine.currentVersion !== undefined) {
|
|
90
|
+
hook.currentVersion = (ctx, opts) => engine.currentVersion(ctx, opts);
|
|
91
|
+
}
|
|
92
|
+
if (engine.now !== undefined)
|
|
93
|
+
hook.now = () => engine.now();
|
|
94
|
+
if (alter)
|
|
95
|
+
hook = alter(hook, seen);
|
|
96
|
+
const base = {
|
|
97
|
+
address: payer.publicKey(),
|
|
98
|
+
signAuthEntry: async (preimageXdr) => {
|
|
99
|
+
seen.signerCalls++;
|
|
100
|
+
const pre = stellar_sdk_1.xdr.HashIdPreimage.fromXDR(preimageXdr, 'base64');
|
|
101
|
+
return { signedAuthEntry: payer.sign((0, stellar_sdk_1.hash)(pre.toXDR())).toString('base64'), signerAddress: payer.publicKey() };
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
const r = requirements(p);
|
|
105
|
+
const call = { url: p.url ?? 'https://conformance.test/paid', method: p.method ?? 'GET', requirements: r };
|
|
106
|
+
const gated = gate(base, hook, () => call);
|
|
107
|
+
try {
|
|
108
|
+
// What stellar-sdk's signAuthEntries does: it also verifies the
|
|
109
|
+
// returned signature against sha256(preimage).
|
|
110
|
+
await (0, stellar_sdk_1.authorizeEntry)(entry(r), async (preimage) => {
|
|
111
|
+
const { signedAuthEntry } = await gated.signAuthEntry(preimage.toXDR('base64'), { address: payer.publicKey() });
|
|
112
|
+
return Buffer.from(signedAuthEntry, 'base64');
|
|
113
|
+
}, 1_000_000, stellar_sdk_1.Networks.TESTNET);
|
|
114
|
+
seen.signed = true;
|
|
115
|
+
}
|
|
116
|
+
catch (e) {
|
|
117
|
+
seen.error = e;
|
|
118
|
+
}
|
|
119
|
+
return seen;
|
|
120
|
+
};
|
|
121
|
+
const describeError = (e) => e instanceof x402_policy_1.X402PolicyError ? `${e.outcome}: ${e.message}` : String(e?.message ?? e);
|
|
122
|
+
/** A refusal case: nothing signed, the gate refused with `outcome`. */
|
|
123
|
+
const expectRefused = (a, outcome) => {
|
|
124
|
+
check(a.signerCalls === 0, `expected no signature (${outcome}), but the signer was called ${a.signerCalls} time(s)`);
|
|
125
|
+
check(!a.signed, `expected no signature (${outcome}), but the authorization was signed`);
|
|
126
|
+
check(a.error instanceof x402_policy_1.X402PolicyError, `expected X402PolicyError ${outcome}, got ${a.error === undefined ? 'no error' : describeError(a.error)}`);
|
|
127
|
+
check(a.error.outcome === outcome, `expected outcome ${outcome}, got ${describeError(a.error)}`);
|
|
128
|
+
check(!a.records.some((r) => r.outcome === 'SIGNED'), `onDecision saw SIGNED in a ${outcome} case`);
|
|
129
|
+
};
|
|
130
|
+
/** The altered cases only mean something if the engine allowed first. */
|
|
131
|
+
const expectEngineAllowed = (a) => {
|
|
132
|
+
const d = a.engineDecisions[0];
|
|
133
|
+
check(d?.decision === 'ALLOW', `the engine must ALLOW target.allow for this case to mean anything; it answered ${d ? JSON.stringify(d.decision) : 'nothing'}`);
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* Replaces the engine's ALLOW with `change(allow)`; other answers pass
|
|
137
|
+
* through. Unless the case is about the hash, the ALLOW is bound to this
|
|
138
|
+
* context first, so each case tests only the fault it names (an engine
|
|
139
|
+
* that gets the hash wrong already fails the ALLOW case).
|
|
140
|
+
*/
|
|
141
|
+
const rewriteAllow = (change, keepHash = false) => (hook) => ({
|
|
142
|
+
...hook,
|
|
143
|
+
evaluate: async (ctx, opts) => {
|
|
144
|
+
const d = await hook.evaluate(ctx, opts);
|
|
145
|
+
if (d?.decision !== 'ALLOW')
|
|
146
|
+
return d;
|
|
147
|
+
return change(keepHash ? d : { ...d, contextHash: ctx.contextHash });
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
const cases = [
|
|
151
|
+
{
|
|
152
|
+
name: 'ALLOW with the exact contextHash signs exactly once',
|
|
153
|
+
run: async () => {
|
|
154
|
+
const a = await attempt(target.allow);
|
|
155
|
+
const d = a.engineDecisions[0];
|
|
156
|
+
check(d !== undefined, 'the engine was never asked');
|
|
157
|
+
check(d.decision === 'ALLOW', `expected the engine to ALLOW target.allow, it answered ${JSON.stringify(d.decision)}${d.reason ? ` (${d.reason})` : ''}`);
|
|
158
|
+
check(d.contextHash === a.contextHashes[0], `ALLOW must echo ctx.contextHash exactly: got ${JSON.stringify(d.contextHash)}, expected ${a.contextHashes[0]}`);
|
|
159
|
+
check(a.signed && a.error === undefined, `expected a signature, got ${describeError(a.error)}`);
|
|
160
|
+
check(a.signerCalls === 1, `expected the signer to be called once, it was called ${a.signerCalls} time(s)`);
|
|
161
|
+
const outcomes = a.records.map((r) => r.outcome).join(',');
|
|
162
|
+
check(outcomes === 'ALLOWED,SIGNED', `expected onDecision ALLOWED,SIGNED, got ${outcomes || 'nothing'}`);
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
name: 'DENY signs nothing',
|
|
167
|
+
run: async () => {
|
|
168
|
+
const a = await attempt(target.deny);
|
|
169
|
+
check(a.engineDecisions[0]?.decision === 'DENY', `expected the engine to DENY target.deny, it answered ${JSON.stringify(a.engineDecisions[0]?.decision)}`);
|
|
170
|
+
expectRefused(a, 'DENY');
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
name: target.wait ? 'WAIT signs nothing' : 'WAIT signs nothing (engine ALLOW turned into WAIT)',
|
|
175
|
+
run: async () => {
|
|
176
|
+
if (target.wait) {
|
|
177
|
+
const a = await attempt(target.wait);
|
|
178
|
+
check(a.engineDecisions[0]?.decision === 'WAIT', `expected the engine to WAIT on target.wait, it answered ${JSON.stringify(a.engineDecisions[0]?.decision)}`);
|
|
179
|
+
expectRefused(a, 'WAIT');
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const a = await attempt(target.allow, rewriteAllow((d) => ({ ...d, decision: 'WAIT', reason: 'conformance: wait' })));
|
|
183
|
+
expectEngineAllowed(a);
|
|
184
|
+
expectRefused(a, 'WAIT');
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
name: 'ALLOW with a wrong contextHash signs nothing',
|
|
189
|
+
run: async () => {
|
|
190
|
+
const a = await attempt(target.allow, rewriteAllow((d) => ({
|
|
191
|
+
...d,
|
|
192
|
+
contextHash: typeof d.contextHash === 'string' && d.contextHash.length > 0
|
|
193
|
+
? (d.contextHash[0] === '0' ? '1' : '0') + d.contextHash.slice(1)
|
|
194
|
+
: '0'.repeat(64),
|
|
195
|
+
}), true));
|
|
196
|
+
expectEngineAllowed(a);
|
|
197
|
+
expectRefused(a, 'UNBOUND');
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
name: 'ALLOW with an expired expiresAt signs nothing',
|
|
202
|
+
run: async () => {
|
|
203
|
+
const a = await attempt(target.allow, rewriteAllow((d) => ({ ...d, expiresAt: Date.now() - 1 })));
|
|
204
|
+
expectEngineAllowed(a);
|
|
205
|
+
expectRefused(a, 'EXPIRED');
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
// Several shapes, each a separate gate run.
|
|
209
|
+
...[
|
|
210
|
+
['no decision object', () => null],
|
|
211
|
+
['an unknown verdict', (d) => ({ ...d, decision: 'allow' })],
|
|
212
|
+
['a non-numeric expiresAt', (d) => ({ ...d, expiresAt: 'soon' })],
|
|
213
|
+
].map(([what, change]) => ({
|
|
214
|
+
name: `a malformed answer (${what}) signs nothing`,
|
|
215
|
+
run: async () => {
|
|
216
|
+
const a = await attempt(target.allow, rewriteAllow(change));
|
|
217
|
+
expectEngineAllowed(a);
|
|
218
|
+
expectRefused(a, 'MALFORMED');
|
|
219
|
+
},
|
|
220
|
+
})),
|
|
221
|
+
{
|
|
222
|
+
name: 'an answer after the timeout signs nothing',
|
|
223
|
+
run: async () => {
|
|
224
|
+
let aborted = false;
|
|
225
|
+
// The engine is asked outside the gate's deadline, with its own
|
|
226
|
+
// signal and the budget it would get in real use (its own
|
|
227
|
+
// timeoutMs, else the gate's default 5000 ms), so a correct
|
|
228
|
+
// engine slower than this case's timeoutMs (a remote one, say)
|
|
229
|
+
// still gets to answer. The gate only sees that answer arrive
|
|
230
|
+
// after its deadline.
|
|
231
|
+
let engineAnswer = Promise.resolve();
|
|
232
|
+
const a = await attempt(target.allow, (hook) => ({
|
|
233
|
+
...hook,
|
|
234
|
+
timeoutMs,
|
|
235
|
+
evaluate: (ctx, opts) => {
|
|
236
|
+
const own = new AbortController();
|
|
237
|
+
const t = setTimeout(() => own.abort(), hook.timeoutMs ?? 5_000);
|
|
238
|
+
engineAnswer = hook.evaluate(ctx, { signal: own.signal })
|
|
239
|
+
.catch(() => undefined)
|
|
240
|
+
.finally(() => clearTimeout(t));
|
|
241
|
+
return new Promise((resolve) => {
|
|
242
|
+
opts.signal.addEventListener('abort', () => {
|
|
243
|
+
aborted = true;
|
|
244
|
+
void engineAnswer.then((d) => resolve(d));
|
|
245
|
+
}, { once: true });
|
|
246
|
+
});
|
|
247
|
+
},
|
|
248
|
+
}));
|
|
249
|
+
await engineAnswer;
|
|
250
|
+
expectEngineAllowed(a);
|
|
251
|
+
expectRefused(a, 'TIMEOUT');
|
|
252
|
+
check(aborted, 'the gate did not abort the engine signal on timeout');
|
|
253
|
+
},
|
|
254
|
+
},
|
|
255
|
+
];
|
|
256
|
+
return cases;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Registers every case as a node:test test. Call it at the top level of a
|
|
260
|
+
* test file:
|
|
261
|
+
*
|
|
262
|
+
* runPolicyConformance({ name: 'my engine', createHook, allow, deny });
|
|
263
|
+
*/
|
|
264
|
+
function runPolicyConformance(target, options = {}) {
|
|
265
|
+
const register = options.test ?? ((name, fn) => (0, node_test_1.test)(name, fn));
|
|
266
|
+
for (const c of policyConformanceCases(target, options)) {
|
|
267
|
+
register(`policy conformance (${target.name}): ${c.name}`, c.run);
|
|
268
|
+
}
|
|
269
|
+
}
|
package/dist/x402-spend-cap.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// ("Failed to create payment payload: All payment requirements were
|
|
9
9
|
// rejected by spendControls.maxAmountPerPayment (...)"), sin decir cuánto se
|
|
10
10
|
// pedía ni que nadie firmó nada. Este módulo reconoce ese caso y lo convierte
|
|
11
|
-
// en un error que lo dice.
|
|
11
|
+
// en un error que lo dice. El tope se configura con initX402({ maxAmountPerPayment }) (#106).
|
|
12
12
|
// ═══════════════════════════════════════════════════════════════
|
|
13
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
14
|
exports.X402SpendCapError = void 0;
|
|
@@ -40,7 +40,7 @@ class X402SpendCapError extends Error {
|
|
|
40
40
|
const cap = d.cap ? `the per-payment cap is ${d.cap}` : 'it is above the per-payment cap';
|
|
41
41
|
super(`x402Fetch refused to pay ${d.url}: the server asked for ${asked} and ${cap}. `
|
|
42
42
|
+ 'The signer was not called; nothing was signed or sent. '
|
|
43
|
-
+ 'The cap is enforced by @x402/core
|
|
43
|
+
+ 'The cap is enforced by @x402/core; raise it explicitly with initX402({ maxAmountPerPayment }).', d.cause !== undefined ? { cause: d.cause } : undefined);
|
|
44
44
|
this.name = 'X402SpendCapError';
|
|
45
45
|
this.url = d.url;
|
|
46
46
|
this.amount = d.amount;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nirium",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Autonomous treasury and agentic-payments infrastructure for Stellar (x402)",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
"files": [
|
|
23
23
|
"dist",
|
|
24
|
+
"!dist/**/*.test.*",
|
|
24
25
|
"README.md"
|
|
25
26
|
],
|
|
26
27
|
"engines": {
|
|
@@ -42,6 +43,20 @@
|
|
|
42
43
|
"viem": "^2.55.19",
|
|
43
44
|
"ws": "^8.21.3"
|
|
44
45
|
},
|
|
46
|
+
"overrides": {
|
|
47
|
+
"axios": ">=1.20.0",
|
|
48
|
+
"follow-redirects": ">=1.16.1",
|
|
49
|
+
"smol-toml": ">=1.9.0",
|
|
50
|
+
"mppx": {
|
|
51
|
+
"zod": "^4.6.6"
|
|
52
|
+
},
|
|
53
|
+
"@stellar/mpp": {
|
|
54
|
+
"zod": "^4.6.6"
|
|
55
|
+
},
|
|
56
|
+
"viem": {
|
|
57
|
+
"zod": "^4.6.6"
|
|
58
|
+
}
|
|
59
|
+
},
|
|
45
60
|
"devDependencies": {
|
|
46
61
|
"@types/jest": "^30.0.0",
|
|
47
62
|
"@types/node": "^26.2.0",
|
package/dist/metrics.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|