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.
@@ -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
+ }
@@ -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. No cambia el tope ni lo expone: solo lo explica.
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 and cannot be changed from initX402() yet.', d.cause !== undefined ? { cause: d.cause } : undefined);
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,16 +1,17 @@
1
1
  {
2
2
  "name": "nirium",
3
- "version": "0.16.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",
7
7
  "homepage": "https://nirium.xyz",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/nirium-protocol/nirium-sdk.git"
10
+ "url": "git+https://github.com/nirium-protocol/nirium.git",
11
+ "directory": "packages/sdk"
11
12
  },
12
13
  "bugs": {
13
- "url": "https://github.com/nirium-protocol/nirium-sdk/issues",
14
+ "url": "https://github.com/nirium-protocol/nirium/issues",
14
15
  "email": "niriumprotocol@gmail.com"
15
16
  },
16
17
  "author": {
@@ -20,6 +21,7 @@
20
21
  },
21
22
  "files": [
22
23
  "dist",
24
+ "!dist/**/*.test.*",
23
25
  "README.md"
24
26
  ],
25
27
  "engines": {
@@ -41,6 +43,20 @@
41
43
  "viem": "^2.55.19",
42
44
  "ws": "^8.21.3"
43
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
+ },
44
60
  "devDependencies": {
45
61
  "@types/jest": "^30.0.0",
46
62
  "@types/node": "^26.2.0",
@@ -1 +0,0 @@
1
- export {};