nirium 0.15.0 → 0.16.1

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,178 @@
1
+ export type X402PolicyVerdict = 'ALLOW' | 'DENY' | 'WAIT';
2
+ export interface X402PaymentRequirementsView {
3
+ scheme: string;
4
+ network: string;
5
+ asset: string;
6
+ payTo: string;
7
+ amount: string;
8
+ maxTimeoutSeconds: number;
9
+ }
10
+ export interface X402PolicyContext {
11
+ /** Version of this object's shape, so an engine knows what it is reading. */
12
+ contextVersion: 1;
13
+ /** URL and method exactly as passed to x402Fetch. */
14
+ url: string;
15
+ method: string;
16
+ /** The requirements the server asked for and x402 selected. */
17
+ requirements: Readonly<X402PaymentRequirementsView>;
18
+ /** What is actually about to be signed, decoded from the bytes. */
19
+ authorization: Readonly<{
20
+ preimageXdr: string;
21
+ /** 'legacy' (ENVELOPE_TYPE_SOROBAN_AUTHORIZATION) or 'cap71' (…WithAddress). */
22
+ preimageType: 'legacy' | 'cap71';
23
+ /** sha256(preimage) in hex: exactly the payload ed25519 signs. */
24
+ payloadHash: string;
25
+ networkPassphrase: string;
26
+ nonce: string;
27
+ signatureExpirationLedger: number;
28
+ contractId: string;
29
+ functionName: string;
30
+ from: string;
31
+ to: string;
32
+ amount: string;
33
+ }>;
34
+ signer: string;
35
+ /** sha256 of {url, method, payloadHash}. An ALLOW must echo it back unchanged. */
36
+ contextHash: string;
37
+ }
38
+ export interface X402PolicyDecision {
39
+ decision: X402PolicyVerdict;
40
+ /** Required on ALLOW: binds the decision to this authorization and no other. */
41
+ contextHash?: string;
42
+ reason?: string;
43
+ /**
44
+ * Opaque to Nirium. Preserved in errors and onDecision. Required on ALLOW
45
+ * when `currentVersion` is configured: it is what gets compared.
46
+ */
47
+ policyVersion?: string;
48
+ /** Epoch ms. If it has passed by signing time, nothing is signed. Equality counts as expired. */
49
+ expiresAt?: number;
50
+ decisionId?: string;
51
+ }
52
+ export type X402PolicyOutcome = 'ALLOWED' | 'SIGNED' | 'SIGNER_ERROR' | 'DENY' | 'WAIT' | 'TIMEOUT' | 'ENGINE_ERROR' | 'EXPIRED' | 'UNBOUND' | 'MALFORMED' | 'CONTEXT_MISMATCH' | 'STALE' | 'VERSION_UNAVAILABLE' | 'SIGNER_CHANGED' | 'CLOCK_INVALID';
53
+ /**
54
+ * `ALLOWED`: the engine's ALLOW is well formed, bound to this authorization
55
+ * and not expired yet. It is a notice, not a result: the observer runs here,
56
+ * and the freshness and identity checks that follow it can still refuse
57
+ * (STALE, EXPIRED, TIMEOUT, CLOCK_INVALID, VERSION_UNAVAILABLE, SIGNER_CHANGED).
58
+ * `SIGNED`: the signer returned a signature. `SIGNER_ERROR`: the signer
59
+ * rejected, threw, or returned no `signedAuthEntry`. Every other value is a
60
+ * refusal and nothing was signed.
61
+ * Sequence: `ALLOWED`, then either a refusal, or exactly one of `SIGNED` or
62
+ * `SIGNER_ERROR`. Refusals that happen before the ALLOW is accepted (DENY, WAIT,
63
+ * UNBOUND, MALFORMED, TIMEOUT or ENGINE_ERROR while evaluating, CONTEXT_MISMATCH)
64
+ * are a single record with no `ALLOWED`.
65
+ */
66
+ export interface X402PolicyRecord {
67
+ outcome: X402PolicyOutcome;
68
+ context?: X402PolicyContext;
69
+ decision?: X402PolicyDecision;
70
+ error?: string;
71
+ }
72
+ /**
73
+ * Pre-sign policy hook (#96). Runs after the Stellar authorization is built
74
+ * and before anything is signed. Only an ALLOW bound to this exact
75
+ * authorization, and still valid, reaches the signer. Anything else (DENY,
76
+ * WAIT, error, timeout, malformed or stale answer) signs nothing. Nirium never
77
+ * stores or owns the policy; it asks and obeys.
78
+ *
79
+ * Authorizations that are not a single `transfer(from, to, amount)` matching
80
+ * the selected requirements are rejected before the policy is consulted.
81
+ */
82
+ export interface X402PolicyHook {
83
+ evaluate: (ctx: X402PolicyContext, opts: {
84
+ signal: AbortSignal;
85
+ }) => Promise<X402PolicyDecision>;
86
+ /**
87
+ * Optional source of the policy version currently in force. When set, it is
88
+ * read after an ALLOW and right before signing; the ALLOW signs only if its
89
+ * `policyVersion` equals what this returns. A rejection, an empty answer or
90
+ * running past the deadline signs nothing.
91
+ *
92
+ * This check is NOT atomic with signing: the version can change after it is
93
+ * read, or while the signer runs. It narrows the stale-ALLOW window to the
94
+ * synchronous step between this read and the signer call; it does not close it.
95
+ * The `onDecision` observer runs before this read, so a version change it
96
+ * causes is seen by it.
97
+ */
98
+ currentVersion?: (ctx: X402PolicyContext, opts: {
99
+ signal: AbortSignal;
100
+ }) => Promise<string>;
101
+ /**
102
+ * Hard deadline for the whole pre-sign phase (evaluate + currentVersion).
103
+ * Default 5000 ms, and never more than half the payment's maxTimeoutSeconds.
104
+ */
105
+ timeoutMs?: number;
106
+ /** If true, an ALLOW without expiresAt is treated as unsignable. Default false. */
107
+ requireExpiry?: boolean;
108
+ /**
109
+ * Observer for receipts (see X402PolicyRecord for the sequence). Cannot
110
+ * change the outcome. A synchronous throw is swallowed. If it returns a
111
+ * promise (or any thenable) it is not awaited, so it cannot delay or block a
112
+ * payment, and its rejection is swallowed so it never becomes an
113
+ * unhandledRejection.
114
+ */
115
+ onDecision?: (record: X402PolicyRecord) => void;
116
+ /**
117
+ * Injectable clock (epoch ms), for tests. It must return a finite number
118
+ * every time it is read: anything else (NaN, undefined, a string, a throw)
119
+ * refuses the payment with CLOCK_INVALID, because every comparison against
120
+ * NaN is false and a deadline that can never be reached would sign.
121
+ */
122
+ now?: () => number;
123
+ }
124
+ /** Outcomes that mean no signature was released (the payment is refused). */
125
+ export type X402PolicyRefusal = Exclude<X402PolicyOutcome, 'ALLOWED' | 'SIGNED'>;
126
+ export declare class X402PolicyError extends Error {
127
+ readonly outcome: X402PolicyRefusal;
128
+ readonly decision?: X402PolicyDecision;
129
+ readonly contextHash?: string;
130
+ constructor(outcome: X402PolicyRefusal, message: string, extra?: {
131
+ decision?: X402PolicyDecision;
132
+ contextHash?: string;
133
+ });
134
+ }
135
+ type SignOpts = {
136
+ networkPassphrase?: string;
137
+ address?: string;
138
+ };
139
+ type SignFn = (authEntry: string, opts?: SignOpts) => Promise<{
140
+ signedAuthEntry: string;
141
+ signerAddress?: string;
142
+ }>;
143
+ export type X402BaseSigner = {
144
+ address: string;
145
+ signAuthEntry: SignFn;
146
+ };
147
+ /** Validates a policy hook at initX402 time, so bad config fails before any payment. */
148
+ export declare function assertValidPolicyHook(policy: X402PolicyHook): void;
149
+ /**
150
+ * Decodes the preimage and checks it describes exactly the payment x402
151
+ * selected. This is not policy (that belongs to the engine): it is context
152
+ * integrity, so that what the engine evaluates is what gets signed.
153
+ */
154
+ export declare function describeAuthorization(preimageXdr: string, requirements: X402PaymentRequirementsView, signerAddress: string): X402PolicyContext['authorization'];
155
+ /** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
156
+ export declare function effectiveTimeoutMs(policy: X402PolicyHook, maxTimeoutSeconds?: number): number;
157
+ /**
158
+ * Wraps a signer so it only signs with a current ALLOW bound to this auth
159
+ * entry. Anything else ends without a signature.
160
+ *
161
+ * `getCall` supplies the per-call context (URL, method, requirements): one
162
+ * gated signer is created per x402Fetch, so two concurrent payments never
163
+ * share state. `onRefused` receives the error before it is thrown, because
164
+ * @x402/fetch re-wraps errors and loses their class.
165
+ *
166
+ * Not a security boundary against code in the same process: anyone holding
167
+ * the base signer can still call it directly. Callbacks (`evaluate`,
168
+ * `currentVersion`, `onDecision`) all run before the final clock and identity
169
+ * checks, so what they change in the clock, the version source or the base
170
+ * signer's `address` is detected. Replacing `base.signAuthEntry` itself is not:
171
+ * it is looked up at call time, after those checks.
172
+ */
173
+ export declare function createPolicyGatedSigner(base: X402BaseSigner, policy: X402PolicyHook, getCall: () => {
174
+ url: string;
175
+ method: string;
176
+ requirements?: X402PaymentRequirementsView;
177
+ }, onRefused?: (error: X402PolicyError) => void): X402BaseSigner;
178
+ export {};
@@ -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;