nirium 0.14.1 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -13
- package/dist/index.d.ts +41 -4
- package/dist/index.js +166 -32
- package/dist/metrics.d.ts +0 -1
- package/dist/metrics.js +4 -2
- package/dist/metrics.test.d.ts +1 -0
- package/dist/metrics.test.js +614 -0
- package/dist/resilient-ws.d.ts +0 -1
- package/dist/resilient-ws.js +10 -4
- package/dist/x402-guard-upstash.d.ts +14 -0
- package/dist/x402-guard-upstash.js +44 -0
- package/dist/x402-guard.d.ts +86 -0
- package/dist/x402-guard.js +111 -0
- package/dist/x402-guard.test.d.ts +11 -0
- package/dist/x402-guard.test.js +145 -0
- package/dist/x402-policy.d.ts +178 -0
- package/dist/x402-policy.js +334 -0
- package/dist/x402-spend-cap.d.ts +65 -0
- package/dist/x402-spend-cap.js +129 -0
- package/dist/x402serve-smoke.test.d.ts +9 -0
- package/dist/x402serve-smoke.test.js +158 -0
- package/package.json +19 -11
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/metrics.d.ts.map +0 -1
- package/dist/metrics.js.map +0 -1
- package/dist/resilient-ws.d.ts.map +0 -1
- package/dist/resilient-ws.js.map +0 -1
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3
|
+
// Pre-sign policy hook for x402Fetch (#96).
|
|
4
|
+
//
|
|
5
|
+
// El punto de evaluación envuelve al signer SEP-43 porque es el único lugar
|
|
6
|
+
// donde existe la autorización que se va a firmar: ExactStellarScheme la arma
|
|
7
|
+
// dentro de createPaymentPayload (simulación RPC incluida) y stellar-sdk la
|
|
8
|
+
// entrega a signAuthEntry como HashIdPreimage en base64. El hook
|
|
9
|
+
// onBeforePaymentCreation de @x402/core corre ANTES de eso: ve los requisitos,
|
|
10
|
+
// pero todavía no hay nonce, expiración ni invocación que atar.
|
|
11
|
+
// ═══════════════════════════════════════════════════════════════
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.X402PolicyError = void 0;
|
|
14
|
+
exports.assertValidPolicyHook = assertValidPolicyHook;
|
|
15
|
+
exports.describeAuthorization = describeAuthorization;
|
|
16
|
+
exports.effectiveTimeoutMs = effectiveTimeoutMs;
|
|
17
|
+
exports.createPolicyGatedSigner = createPolicyGatedSigner;
|
|
18
|
+
const stellar_sdk_1 = require("@stellar/stellar-sdk");
|
|
19
|
+
class X402PolicyError extends Error {
|
|
20
|
+
outcome;
|
|
21
|
+
decision;
|
|
22
|
+
contextHash;
|
|
23
|
+
constructor(outcome, message, extra = {}) {
|
|
24
|
+
super(`x402 policy ${outcome}: ${message}`);
|
|
25
|
+
this.name = 'X402PolicyError';
|
|
26
|
+
this.outcome = outcome;
|
|
27
|
+
this.decision = extra.decision;
|
|
28
|
+
this.contextHash = extra.contextHash;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
exports.X402PolicyError = X402PolicyError;
|
|
32
|
+
const PASSPHRASES = {
|
|
33
|
+
'stellar:testnet': stellar_sdk_1.Networks.TESTNET,
|
|
34
|
+
'stellar:pubnet': stellar_sdk_1.Networks.PUBLIC,
|
|
35
|
+
};
|
|
36
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
37
|
+
const hex = (b) => Buffer.from(b).toString('hex');
|
|
38
|
+
const sha256hex = (s) => hex((0, stellar_sdk_1.hash)(Buffer.from(s, 'utf8')));
|
|
39
|
+
const nonempty = (v) => typeof v === 'string' && v.trim().length > 0;
|
|
40
|
+
/** Validates a policy hook at initX402 time, so bad config fails before any payment. */
|
|
41
|
+
function assertValidPolicyHook(policy) {
|
|
42
|
+
if (!policy || typeof policy !== 'object' || typeof policy.evaluate !== 'function') {
|
|
43
|
+
throw new Error('initX402: `policy.evaluate` must be a function.');
|
|
44
|
+
}
|
|
45
|
+
if (policy.currentVersion !== undefined && typeof policy.currentVersion !== 'function') {
|
|
46
|
+
throw new Error('initX402: `policy.currentVersion`, when set, must be a function.');
|
|
47
|
+
}
|
|
48
|
+
if (policy.timeoutMs !== undefined
|
|
49
|
+
&& (!Number.isSafeInteger(policy.timeoutMs) || policy.timeoutMs <= 0)) {
|
|
50
|
+
throw new Error('initX402: `policy.timeoutMs` must be a positive integer (ms).');
|
|
51
|
+
}
|
|
52
|
+
if (policy.now !== undefined && typeof policy.now !== 'function') {
|
|
53
|
+
throw new Error('initX402: `policy.now`, when set, must be a function returning epoch milliseconds.');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Decodes the preimage and checks it describes exactly the payment x402
|
|
58
|
+
* selected. This is not policy (that belongs to the engine): it is context
|
|
59
|
+
* integrity, so that what the engine evaluates is what gets signed.
|
|
60
|
+
*/
|
|
61
|
+
function describeAuthorization(preimageXdr, requirements, signerAddress) {
|
|
62
|
+
let pre;
|
|
63
|
+
try {
|
|
64
|
+
pre = stellar_sdk_1.xdr.HashIdPreimage.fromXDR(preimageXdr, 'base64');
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `undecodable auth preimage (${e?.message})`);
|
|
68
|
+
}
|
|
69
|
+
// Dos variantes: la clásica, y la de CAP-71 que además ata la dirección
|
|
70
|
+
// dentro de lo firmado. En la segunda, esa dirección tiene que ser el signer.
|
|
71
|
+
let auth;
|
|
72
|
+
let preimageType;
|
|
73
|
+
switch (pre.switch().name) {
|
|
74
|
+
case 'envelopeTypeSorobanAuthorization':
|
|
75
|
+
auth = pre.sorobanAuthorization();
|
|
76
|
+
preimageType = 'legacy';
|
|
77
|
+
break;
|
|
78
|
+
case 'envelopeTypeSorobanAuthorizationWithAddress':
|
|
79
|
+
auth = pre.sorobanAuthorizationWithAddress();
|
|
80
|
+
preimageType = 'cap71';
|
|
81
|
+
if (stellar_sdk_1.Address.fromScAddress(auth.address()).toString() !== signerAddress) {
|
|
82
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'CAP-71 preimage is bound to a different address than the signer');
|
|
83
|
+
}
|
|
84
|
+
break;
|
|
85
|
+
default:
|
|
86
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `unsupported preimage type ${pre.switch().name}`);
|
|
87
|
+
}
|
|
88
|
+
const passphrase = PASSPHRASES[requirements.network];
|
|
89
|
+
if (!passphrase)
|
|
90
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `unknown network ${requirements.network}`);
|
|
91
|
+
if (hex(auth.networkId()) !== hex((0, stellar_sdk_1.hash)(Buffer.from(passphrase)))) {
|
|
92
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'auth entry is for a different network than requirements.network');
|
|
93
|
+
}
|
|
94
|
+
const inv = auth.invocation();
|
|
95
|
+
if (inv.subInvocations().length !== 0) {
|
|
96
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'auth entry carries sub-invocations');
|
|
97
|
+
}
|
|
98
|
+
const fn = inv.function();
|
|
99
|
+
if (fn.switch().name !== 'sorobanAuthorizedFunctionTypeContractFn') {
|
|
100
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `unexpected authorized function ${fn.switch().name}`);
|
|
101
|
+
}
|
|
102
|
+
const call = fn.contractFn();
|
|
103
|
+
const contractId = stellar_sdk_1.Address.fromScAddress(call.contractAddress()).toString();
|
|
104
|
+
const functionName = call.functionName().toString();
|
|
105
|
+
const rawArgs = call.args();
|
|
106
|
+
if (functionName !== 'transfer' || rawArgs.length !== 3) {
|
|
107
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', `expected transfer(from,to,amount), got ${functionName}/${rawArgs.length}`);
|
|
108
|
+
}
|
|
109
|
+
if (rawArgs[0].switch().name !== 'scvAddress' || rawArgs[1].switch().name !== 'scvAddress'
|
|
110
|
+
|| rawArgs[2].switch().name !== 'scvI128') {
|
|
111
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'transfer arguments have unexpected types');
|
|
112
|
+
}
|
|
113
|
+
const from = stellar_sdk_1.Address.fromScAddress(rawArgs[0].address()).toString();
|
|
114
|
+
const to = stellar_sdk_1.Address.fromScAddress(rawArgs[1].address()).toString();
|
|
115
|
+
const amount = BigInt((0, stellar_sdk_1.scValToNative)(rawArgs[2])).toString();
|
|
116
|
+
if (contractId !== requirements.asset)
|
|
117
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'asset contract differs from requirements.asset');
|
|
118
|
+
if (to !== requirements.payTo)
|
|
119
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'destination differs from requirements.payTo');
|
|
120
|
+
if (amount !== requirements.amount)
|
|
121
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'amount differs from requirements.amount');
|
|
122
|
+
if (from !== signerAddress)
|
|
123
|
+
throw new X402PolicyError('CONTEXT_MISMATCH', 'from differs from signer address');
|
|
124
|
+
return Object.freeze({
|
|
125
|
+
preimageXdr,
|
|
126
|
+
preimageType,
|
|
127
|
+
payloadHash: hex((0, stellar_sdk_1.hash)(pre.toXDR())),
|
|
128
|
+
networkPassphrase: passphrase,
|
|
129
|
+
nonce: auth.nonce().toString(),
|
|
130
|
+
signatureExpirationLedger: auth.signatureExpirationLedger(),
|
|
131
|
+
contractId, functionName, from, to, amount,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
|
|
135
|
+
function effectiveTimeoutMs(policy, maxTimeoutSeconds) {
|
|
136
|
+
const base = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
137
|
+
if (typeof maxTimeoutSeconds === 'number' && Number.isFinite(maxTimeoutSeconds) && maxTimeoutSeconds > 0) {
|
|
138
|
+
return Math.max(1, Math.min(base, Math.floor((maxTimeoutSeconds * 1000) / 2)));
|
|
139
|
+
}
|
|
140
|
+
return base;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Wraps a signer so it only signs with a current ALLOW bound to this auth
|
|
144
|
+
* entry. Anything else ends without a signature.
|
|
145
|
+
*
|
|
146
|
+
* `getCall` supplies the per-call context (URL, method, requirements): one
|
|
147
|
+
* gated signer is created per x402Fetch, so two concurrent payments never
|
|
148
|
+
* share state. `onRefused` receives the error before it is thrown, because
|
|
149
|
+
* @x402/fetch re-wraps errors and loses their class.
|
|
150
|
+
*
|
|
151
|
+
* Not a security boundary against code in the same process: anyone holding
|
|
152
|
+
* the base signer can still call it directly. Callbacks (`evaluate`,
|
|
153
|
+
* `currentVersion`, `onDecision`) all run before the final clock and identity
|
|
154
|
+
* checks, so what they change in the clock, the version source or the base
|
|
155
|
+
* signer's `address` is detected. Replacing `base.signAuthEntry` itself is not:
|
|
156
|
+
* it is looked up at call time, after those checks.
|
|
157
|
+
*/
|
|
158
|
+
function createPolicyGatedSigner(base, policy, getCall, onRefused) {
|
|
159
|
+
// La identidad se fija aquí. Si el signer base cambia de dirección a mitad
|
|
160
|
+
// del pago, no se firma: lo evaluado se evaluó para esta cuenta.
|
|
161
|
+
const account = base.address;
|
|
162
|
+
const now = policy.now ?? Date.now;
|
|
163
|
+
// Un reloj que no devuelve un número finito cierra: NaN hace falsa cada
|
|
164
|
+
// comparación (`t >= deadline`), y un plazo que nunca se alcanza firmaría.
|
|
165
|
+
const readClock = (context, decision) => {
|
|
166
|
+
let t;
|
|
167
|
+
try {
|
|
168
|
+
t = now();
|
|
169
|
+
}
|
|
170
|
+
catch (e) {
|
|
171
|
+
return refuse('CLOCK_INVALID', `clock threw (${e?.message ?? String(e)})`, context, decision);
|
|
172
|
+
}
|
|
173
|
+
if (typeof t !== 'number' || !Number.isFinite(t)) {
|
|
174
|
+
return refuse('CLOCK_INVALID', `clock returned ${String(t)}, not epoch milliseconds`, context, decision);
|
|
175
|
+
}
|
|
176
|
+
return t;
|
|
177
|
+
};
|
|
178
|
+
const report = (r) => {
|
|
179
|
+
try {
|
|
180
|
+
const out = policy.onDecision?.(r);
|
|
181
|
+
// Un observador async que rechaza no puede tumbar el proceso con un
|
|
182
|
+
// unhandledRejection. No se espera: el signer no depende de él.
|
|
183
|
+
if (out !== null && (typeof out === 'object' || typeof out === 'function')) {
|
|
184
|
+
Promise.resolve(out).catch(() => { });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch { /* un observador no decide nada */ }
|
|
188
|
+
};
|
|
189
|
+
const refuse = (outcome, msg, context, decision) => {
|
|
190
|
+
report({ outcome, context, decision, error: msg });
|
|
191
|
+
const err = new X402PolicyError(outcome, msg, { decision, contextHash: context?.contextHash });
|
|
192
|
+
try {
|
|
193
|
+
onRefused?.(err);
|
|
194
|
+
}
|
|
195
|
+
catch { /* idem */ }
|
|
196
|
+
throw err;
|
|
197
|
+
};
|
|
198
|
+
const signAuthEntry = async (preimageXdr, opts) => {
|
|
199
|
+
const call = getCall();
|
|
200
|
+
if (!call.requirements)
|
|
201
|
+
refuse('CONTEXT_MISMATCH', 'no payment requirements bound to this signing call');
|
|
202
|
+
if (base.address !== account)
|
|
203
|
+
refuse('SIGNER_CHANGED', 'base signer address changed after the gate was created');
|
|
204
|
+
if (opts?.address && opts.address !== account)
|
|
205
|
+
refuse('CONTEXT_MISMATCH', 'asked to sign for a different address');
|
|
206
|
+
let authorization;
|
|
207
|
+
try {
|
|
208
|
+
authorization = describeAuthorization(preimageXdr, call.requirements, account);
|
|
209
|
+
}
|
|
210
|
+
catch (e) {
|
|
211
|
+
return refuse(e instanceof X402PolicyError ? e.outcome : 'CONTEXT_MISMATCH', e?.message ?? String(e));
|
|
212
|
+
}
|
|
213
|
+
const contextHash = sha256hex(JSON.stringify({ v: 1, url: call.url, method: call.method, payloadHash: authorization.payloadHash }));
|
|
214
|
+
// Congelado: el engine lee, no reescribe lo que se firma.
|
|
215
|
+
const context = Object.freeze({
|
|
216
|
+
contextVersion: 1, url: call.url, method: call.method,
|
|
217
|
+
requirements: Object.freeze({ ...call.requirements }),
|
|
218
|
+
authorization,
|
|
219
|
+
signer: account, contextHash,
|
|
220
|
+
});
|
|
221
|
+
const timeoutMs = effectiveTimeoutMs(policy, call.requirements.maxTimeoutSeconds);
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
// Un solo plazo para toda la fase previa a la firma (evaluate + currentVersion).
|
|
224
|
+
const deadline = readClock(context) + timeoutMs;
|
|
225
|
+
let timer;
|
|
226
|
+
const TIMED_OUT = Symbol('timeout');
|
|
227
|
+
const timeout = new Promise((_, reject) => {
|
|
228
|
+
timer = setTimeout(() => { controller.abort(); reject(TIMED_OUT); }, timeoutMs);
|
|
229
|
+
});
|
|
230
|
+
timeout.catch(() => { });
|
|
231
|
+
try {
|
|
232
|
+
let decision;
|
|
233
|
+
try {
|
|
234
|
+
decision = await Promise.race([
|
|
235
|
+
Promise.resolve().then(() => policy.evaluate(context, { signal: controller.signal })),
|
|
236
|
+
timeout,
|
|
237
|
+
]);
|
|
238
|
+
}
|
|
239
|
+
catch (e) {
|
|
240
|
+
if (e === TIMED_OUT)
|
|
241
|
+
return refuse('TIMEOUT', `no decision within ${timeoutMs} ms`, context);
|
|
242
|
+
return refuse('ENGINE_ERROR', e?.message ?? String(e), context);
|
|
243
|
+
}
|
|
244
|
+
// Todo lo que no sea un ALLOW bien formado cierra.
|
|
245
|
+
if (!decision || typeof decision !== 'object')
|
|
246
|
+
return refuse('MALFORMED', 'engine returned no decision object', context);
|
|
247
|
+
if (decision.decision === 'DENY')
|
|
248
|
+
return refuse('DENY', decision.reason ?? 'denied', context, decision);
|
|
249
|
+
if (decision.decision === 'WAIT')
|
|
250
|
+
return refuse('WAIT', decision.reason ?? 'wait', context, decision);
|
|
251
|
+
if (decision.decision !== 'ALLOW')
|
|
252
|
+
return refuse('MALFORMED', `unknown verdict ${String(decision.decision)}`, context, decision);
|
|
253
|
+
// Se copian los campos antes de cualquier await: mutar el objeto del
|
|
254
|
+
// engine después no extiende ni cambia esta decisión.
|
|
255
|
+
const allow = Object.freeze({ ...decision });
|
|
256
|
+
if (allow.contextHash !== contextHash)
|
|
257
|
+
return refuse('UNBOUND', 'ALLOW is not bound to this authorization', context, allow);
|
|
258
|
+
if (allow.expiresAt !== undefined
|
|
259
|
+
&& (typeof allow.expiresAt !== 'number' || !Number.isFinite(allow.expiresAt))) {
|
|
260
|
+
return refuse('MALFORMED', 'expiresAt must be epoch milliseconds', context, allow);
|
|
261
|
+
}
|
|
262
|
+
if (allow.expiresAt === undefined && policy.requireExpiry) {
|
|
263
|
+
return refuse('EXPIRED', 'ALLOW without expiresAt while requireExpiry is set', context, allow);
|
|
264
|
+
}
|
|
265
|
+
const checkClock = () => {
|
|
266
|
+
const t = readClock(context, allow);
|
|
267
|
+
if (t >= deadline)
|
|
268
|
+
refuse('TIMEOUT', 'decision arrived after the deadline', context, allow);
|
|
269
|
+
if (allow.expiresAt !== undefined && t >= allow.expiresAt)
|
|
270
|
+
refuse('EXPIRED', 'ALLOW expired before signing', context, allow);
|
|
271
|
+
};
|
|
272
|
+
if (policy.currentVersion && !nonempty(allow.policyVersion)) {
|
|
273
|
+
return refuse('MALFORMED', 'ALLOW has no policyVersion to check against currentVersion', context, allow);
|
|
274
|
+
}
|
|
275
|
+
checkClock();
|
|
276
|
+
// El observador corre AQUI y no junto al signer: todo lo que provoque
|
|
277
|
+
// (adelantar el reloj, cambiar la versión de la política, cambiar la
|
|
278
|
+
// dirección del signer) lo ven las comprobaciones que siguen. Lo que
|
|
279
|
+
// hace un callback después de la última de ellas ya no existe: entre
|
|
280
|
+
// la última comprobación y el signer no corre código ajeno.
|
|
281
|
+
report({ outcome: 'ALLOWED', context, decision: allow });
|
|
282
|
+
if (policy.currentVersion) {
|
|
283
|
+
let current;
|
|
284
|
+
try {
|
|
285
|
+
current = await Promise.race([
|
|
286
|
+
Promise.resolve().then(() => policy.currentVersion(context, { signal: controller.signal })),
|
|
287
|
+
timeout,
|
|
288
|
+
]);
|
|
289
|
+
}
|
|
290
|
+
catch (e) {
|
|
291
|
+
if (e === TIMED_OUT)
|
|
292
|
+
return refuse('TIMEOUT', `no current policy version within ${timeoutMs} ms`, context, allow);
|
|
293
|
+
return refuse('VERSION_UNAVAILABLE', `currentVersion failed (${e?.message ?? String(e)})`, context, allow);
|
|
294
|
+
}
|
|
295
|
+
if (!nonempty(current))
|
|
296
|
+
return refuse('VERSION_UNAVAILABLE', 'currentVersion returned no version', context, allow);
|
|
297
|
+
if (current !== allow.policyVersion) {
|
|
298
|
+
return refuse('STALE', `ALLOW was issued under policy ${allow.policyVersion}, current is ${current}`, context, allow);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// Comprobaciones finales, siempre, y sin ningún await antes del signer:
|
|
302
|
+
// el reloj se vuelve a leer (después del observador y del await de la
|
|
303
|
+
// versión) y la identidad se compara por última vez.
|
|
304
|
+
checkClock();
|
|
305
|
+
if (base.address !== account)
|
|
306
|
+
return refuse('SIGNER_CHANGED', 'base signer address changed while the policy was evaluated', context, allow);
|
|
307
|
+
// La fase previa terminó: la firma no tiene plazo propio, así que el
|
|
308
|
+
// temporizador ya no pinta nada.
|
|
309
|
+
if (timer)
|
|
310
|
+
clearTimeout(timer);
|
|
311
|
+
// SIGNED solo existe si el signer devolvió una firma. Los bytes son
|
|
312
|
+
// los del parámetro original, no una copia que alguien pudo tocar.
|
|
313
|
+
let signed;
|
|
314
|
+
try {
|
|
315
|
+
signed = await base.signAuthEntry(preimageXdr, opts);
|
|
316
|
+
}
|
|
317
|
+
catch (e) {
|
|
318
|
+
// El error del signer se relanza tal cual: no es una negativa de la política.
|
|
319
|
+
report({ outcome: 'SIGNER_ERROR', context, decision: allow, error: e?.message ?? String(e) });
|
|
320
|
+
throw e;
|
|
321
|
+
}
|
|
322
|
+
if (!signed || typeof signed !== 'object' || !nonempty(signed.signedAuthEntry)) {
|
|
323
|
+
return refuse('SIGNER_ERROR', 'signer returned no signedAuthEntry', context, allow);
|
|
324
|
+
}
|
|
325
|
+
report({ outcome: 'SIGNED', context, decision: allow });
|
|
326
|
+
return signed;
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
if (timer)
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
return { address: account, signAuthEntry };
|
|
334
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** One payment option from the server's 402 response, as x402 v2 sends it. */
|
|
2
|
+
export interface X402OfferedRequirement {
|
|
3
|
+
scheme?: string;
|
|
4
|
+
network?: string;
|
|
5
|
+
asset?: string;
|
|
6
|
+
amount?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface X402SpendCapErrorDetails {
|
|
9
|
+
url: string;
|
|
10
|
+
/** Atomic units the server asked for (the cheapest offer when there are several). */
|
|
11
|
+
amount?: string;
|
|
12
|
+
asset?: string;
|
|
13
|
+
network?: string;
|
|
14
|
+
/** The cap as @x402/core states it, e.g. "$1". */
|
|
15
|
+
cap?: string;
|
|
16
|
+
/** Human reading of `amount` when the asset is a known default asset, e.g. "2 USDC". */
|
|
17
|
+
formattedAmount?: string;
|
|
18
|
+
cause?: unknown;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* x402Fetch refused to pay because the amount the server asked for is above
|
|
22
|
+
* the per-payment cap enforced by @x402/core. Thrown before the signer is
|
|
23
|
+
* reached: nothing was signed, nothing was sent.
|
|
24
|
+
*/
|
|
25
|
+
export declare class X402SpendCapError extends Error {
|
|
26
|
+
readonly code: "X402_SPEND_CAP_EXCEEDED";
|
|
27
|
+
/** Always false for this error: the cap is checked before any signing. */
|
|
28
|
+
readonly signerCalled: false;
|
|
29
|
+
readonly url: string;
|
|
30
|
+
readonly amount?: string;
|
|
31
|
+
readonly asset?: string;
|
|
32
|
+
readonly network?: string;
|
|
33
|
+
readonly cap?: string;
|
|
34
|
+
readonly formattedAmount?: string;
|
|
35
|
+
constructor(d: X402SpendCapErrorDetails);
|
|
36
|
+
}
|
|
37
|
+
/** `20000000` with 7 decimals and `USDC` -> `2 USDC`. */
|
|
38
|
+
export declare function formatAtomic(amount: string, decimals: number, symbol: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* Reads the `accepts` list out of a 402 response's PAYMENT-REQUIRED header
|
|
41
|
+
* (base64 JSON, x402 v2). Returns undefined if it is absent or unreadable;
|
|
42
|
+
* the error is still produced, just without the amount.
|
|
43
|
+
*/
|
|
44
|
+
export declare function readOfferedRequirements(response: {
|
|
45
|
+
headers: {
|
|
46
|
+
get(name: string): string | null;
|
|
47
|
+
};
|
|
48
|
+
}): X402OfferedRequirement[] | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Wraps a fetch so the requirements of every 402 it sees are written to
|
|
51
|
+
* `sink`. Passive: the response is returned untouched.
|
|
52
|
+
*/
|
|
53
|
+
export declare function captureRequirements(base: typeof fetch, sink: {
|
|
54
|
+
offered?: X402OfferedRequirement[];
|
|
55
|
+
}): typeof fetch;
|
|
56
|
+
/**
|
|
57
|
+
* If `error` is @x402/core refusing a payment for being above its
|
|
58
|
+
* per-payment USD cap, returns the clear error; otherwise null so the caller
|
|
59
|
+
* rethrows the original. Other spendControls rejections (for example a
|
|
60
|
+
* non-default asset) are deliberately left alone.
|
|
61
|
+
*/
|
|
62
|
+
export declare function toSpendCapError(error: unknown, url: string, offered: X402OfferedRequirement[] | undefined, describeAsset?: (asset: string, network: string) => {
|
|
63
|
+
decimals: number;
|
|
64
|
+
symbol: string;
|
|
65
|
+
} | undefined): X402SpendCapError | null;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3
|
+
// Error claro para el tope por pago de @x402/core.
|
|
4
|
+
//
|
|
5
|
+
// Desde @x402/core 2.23.0 el cliente rechaza, al seleccionar los requisitos
|
|
6
|
+
// y antes de crear el payload, todo pago por encima de un tope por defecto
|
|
7
|
+
// ($1). Lo hace con un Error genérico que x402Fetch re-envuelve
|
|
8
|
+
// ("Failed to create payment payload: All payment requirements were
|
|
9
|
+
// rejected by spendControls.maxAmountPerPayment (...)"), sin decir cuánto se
|
|
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.
|
|
12
|
+
// ═══════════════════════════════════════════════════════════════
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.X402SpendCapError = void 0;
|
|
15
|
+
exports.formatAtomic = formatAtomic;
|
|
16
|
+
exports.readOfferedRequirements = readOfferedRequirements;
|
|
17
|
+
exports.captureRequirements = captureRequirements;
|
|
18
|
+
exports.toSpendCapError = toSpendCapError;
|
|
19
|
+
/**
|
|
20
|
+
* x402Fetch refused to pay because the amount the server asked for is above
|
|
21
|
+
* the per-payment cap enforced by @x402/core. Thrown before the signer is
|
|
22
|
+
* reached: nothing was signed, nothing was sent.
|
|
23
|
+
*/
|
|
24
|
+
class X402SpendCapError extends Error {
|
|
25
|
+
code = 'X402_SPEND_CAP_EXCEEDED';
|
|
26
|
+
/** Always false for this error: the cap is checked before any signing. */
|
|
27
|
+
signerCalled = false;
|
|
28
|
+
url;
|
|
29
|
+
amount;
|
|
30
|
+
asset;
|
|
31
|
+
network;
|
|
32
|
+
cap;
|
|
33
|
+
formattedAmount;
|
|
34
|
+
constructor(d) {
|
|
35
|
+
const asked = d.formattedAmount
|
|
36
|
+
? `${d.formattedAmount} (${d.amount} atomic units)`
|
|
37
|
+
: d.amount !== undefined
|
|
38
|
+
? `${d.amount} atomic units${d.asset ? ` of ${d.asset}` : ''}`
|
|
39
|
+
: 'more than the cap';
|
|
40
|
+
const cap = d.cap ? `the per-payment cap is ${d.cap}` : 'it is above the per-payment cap';
|
|
41
|
+
super(`x402Fetch refused to pay ${d.url}: the server asked for ${asked} and ${cap}. `
|
|
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);
|
|
44
|
+
this.name = 'X402SpendCapError';
|
|
45
|
+
this.url = d.url;
|
|
46
|
+
this.amount = d.amount;
|
|
47
|
+
this.asset = d.asset;
|
|
48
|
+
this.network = d.network;
|
|
49
|
+
this.cap = d.cap;
|
|
50
|
+
this.formattedAmount = d.formattedAmount;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.X402SpendCapError = X402SpendCapError;
|
|
54
|
+
const isAtomic = (v) => typeof v === 'string' && /^\d+$/.test(v);
|
|
55
|
+
/** `20000000` with 7 decimals and `USDC` -> `2 USDC`. */
|
|
56
|
+
function formatAtomic(amount, decimals, symbol) {
|
|
57
|
+
const raw = BigInt(amount);
|
|
58
|
+
const base = 10n ** BigInt(decimals);
|
|
59
|
+
const whole = raw / base;
|
|
60
|
+
const frac = (raw % base).toString().padStart(decimals, '0').replace(/0+$/, '');
|
|
61
|
+
return `${frac ? `${whole}.${frac}` : whole.toString()} ${symbol}`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Reads the `accepts` list out of a 402 response's PAYMENT-REQUIRED header
|
|
65
|
+
* (base64 JSON, x402 v2). Returns undefined if it is absent or unreadable;
|
|
66
|
+
* the error is still produced, just without the amount.
|
|
67
|
+
*/
|
|
68
|
+
function readOfferedRequirements(response) {
|
|
69
|
+
try {
|
|
70
|
+
const header = response.headers.get('payment-required');
|
|
71
|
+
if (!header)
|
|
72
|
+
return undefined;
|
|
73
|
+
const bytes = Uint8Array.from(atob(header), (c) => c.charCodeAt(0));
|
|
74
|
+
const accepts = JSON.parse(new TextDecoder().decode(bytes))?.accepts;
|
|
75
|
+
return Array.isArray(accepts) ? accepts : undefined;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Wraps a fetch so the requirements of every 402 it sees are written to
|
|
83
|
+
* `sink`. Passive: the response is returned untouched.
|
|
84
|
+
*/
|
|
85
|
+
function captureRequirements(base, sink) {
|
|
86
|
+
return (async (input, init) => {
|
|
87
|
+
const response = await base(input, init);
|
|
88
|
+
if (response.status === 402) {
|
|
89
|
+
const offered = readOfferedRequirements(response);
|
|
90
|
+
if (offered)
|
|
91
|
+
sink.offered = offered;
|
|
92
|
+
}
|
|
93
|
+
return response;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
// El mensaje de @x402/core que reconocemos. Si una versión futura lo cambia,
|
|
97
|
+
// el error genérico vuelve a salir tal cual (sin perder nada) y el test que lo
|
|
98
|
+
// fija (test/x402-spend-cap.test.ts) falla al subir la dependencia.
|
|
99
|
+
const CAP_REJECTION = /rejected by spendControls\.maxAmountPerPayment(?: \(([^)]*)\))?/;
|
|
100
|
+
/**
|
|
101
|
+
* If `error` is @x402/core refusing a payment for being above its
|
|
102
|
+
* per-payment USD cap, returns the clear error; otherwise null so the caller
|
|
103
|
+
* rethrows the original. Other spendControls rejections (for example a
|
|
104
|
+
* non-default asset) are deliberately left alone.
|
|
105
|
+
*/
|
|
106
|
+
function toSpendCapError(error, url, offered, describeAsset) {
|
|
107
|
+
const message = error instanceof Error ? error.message : '';
|
|
108
|
+
const hit = CAP_REJECTION.exec(message);
|
|
109
|
+
if (!hit)
|
|
110
|
+
return null;
|
|
111
|
+
// "($1, including USDC)" -> "$1"
|
|
112
|
+
const cap = hit[1]?.split(',')[0]?.trim() || undefined;
|
|
113
|
+
const cheapest = (offered ?? [])
|
|
114
|
+
.filter((o) => isAtomic(o.amount))
|
|
115
|
+
.sort((a, b) => (BigInt(a.amount) < BigInt(b.amount) ? -1 : BigInt(a.amount) > BigInt(b.amount) ? 1 : 0))[0];
|
|
116
|
+
let formattedAmount;
|
|
117
|
+
if (cheapest?.asset && cheapest.network) {
|
|
118
|
+
try {
|
|
119
|
+
const info = describeAsset?.(cheapest.asset, cheapest.network);
|
|
120
|
+
if (info)
|
|
121
|
+
formattedAmount = formatAtomic(cheapest.amount, info.decimals, info.symbol);
|
|
122
|
+
}
|
|
123
|
+
catch { /* sin formato legible: se informan las unidades atómicas */ }
|
|
124
|
+
}
|
|
125
|
+
return new X402SpendCapError({
|
|
126
|
+
url, cap, formattedAmount, cause: error,
|
|
127
|
+
amount: cheapest?.amount, asset: cheapest?.asset, network: cheapest?.network,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Smoke tests for x402Serve — verifies synchronous validation is intact.
|
|
3
|
+
*
|
|
4
|
+
* These tests do NOT call the real middleware (which dynamically imports
|
|
5
|
+
* @x402/express, @x402/core, and @x402/stellar at first request). They only
|
|
6
|
+
* verify that x402Serve rejects bad config the same way with or without the
|
|
7
|
+
* metrics wrapper applied.
|
|
8
|
+
*/
|
|
9
|
+
export {};
|