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.
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ /**
3
+ * Reference X402GuardStore backed by Upstash's REST API — plain `fetch`,
4
+ * no extra dependency. Any other Redis-compatible store can implement the
5
+ * three-method X402GuardStore interface instead; this one is provided
6
+ * because it's the store the production reference implementation this
7
+ * feature is modeled on actually uses. See x402-guard.ts.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.createUpstashX402GuardStore = createUpstashX402GuardStore;
11
+ function createUpstashX402GuardStore(opts) {
12
+ const base = opts.url.replace(/\/$/, '');
13
+ const call = async (cmd) => {
14
+ const r = await fetch(base, {
15
+ method: 'POST',
16
+ headers: { Authorization: `Bearer ${opts.token}`, 'Content-Type': 'application/json' },
17
+ body: JSON.stringify(cmd),
18
+ signal: AbortSignal.timeout(5000),
19
+ });
20
+ if (!r.ok)
21
+ throw new Error(`Upstash returned HTTP ${r.status}`);
22
+ const j = await r.json();
23
+ if (j.error)
24
+ throw new Error(`Upstash error: ${j.error}`);
25
+ return j.result;
26
+ };
27
+ return {
28
+ async claimOnce(key, ttlMs) {
29
+ const result = await call(['SET', key, '1', 'PX', ttlMs, 'NX']);
30
+ return result === 'OK';
31
+ },
32
+ async release(key) {
33
+ await call(['DEL', key]);
34
+ },
35
+ async slidingWindowHit(key, windowMs, member) {
36
+ const now = Date.now();
37
+ await call(['ZADD', key, now, member]);
38
+ await call(['ZREMRANGEBYSCORE', key, 0, now - windowMs]);
39
+ await call(['PEXPIRE', key, windowMs]);
40
+ const count = await call(['ZCARD', key]);
41
+ return Number(count);
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Optional replay/rate-limit protection for x402Serve() — off by default.
3
+ *
4
+ * x402Serve() verifies and settles a payment; on its own it does not stop
5
+ * the same signed payment proof from being replayed against a route (a
6
+ * concurrent-request "free shopping" window), and it does not rate-limit
7
+ * callers. See https://github.com/nirium-protocol/nirium/issues/91.
8
+ *
9
+ * The design here (single-use claim keyed on the payment proof + method +
10
+ * route, released only if the request did NOT end in 2xx so a legitimate
11
+ * retry after a facilitator hiccup still works; fail-closed for the replay
12
+ * guard and fail-open for rate limiting, both by the same reasoning) is
13
+ * generalized from a real production x402Serve() integration —
14
+ * Edgadafi/remesa-liquidez (commit 1e0cbd5902cb224d3c6a2320cc009cf4df84f513,
15
+ * `backend/src/middleware/paymentGuard.ts` and `backend/src/middleware/
16
+ * rateLimit.ts`) — credited here and in CHANGELOG.md. The store interface
17
+ * and this module's code are our own; nothing here is copied from theirs.
18
+ */
19
+ /**
20
+ * A pluggable KV backend. Implement this against Upstash, another
21
+ * Redis-compatible store, or anything else with the same semantics — see
22
+ * `createUpstashX402GuardStore()` for a ready-made Upstash implementation.
23
+ */
24
+ export interface X402GuardStore {
25
+ /**
26
+ * Atomically claims `key` for `ttlMs`. Returns `true` if THIS call made
27
+ * the claim, `false` if `key` was already claimed (and is still within
28
+ * its TTL) by an earlier call.
29
+ */
30
+ claimOnce(key: string, ttlMs: number): Promise<boolean>;
31
+ /**
32
+ * Releases a claim early. Used after a request that did not succeed, so
33
+ * a legitimate retry with the same payment proof is not blocked.
34
+ */
35
+ release(key: string): Promise<void>;
36
+ /**
37
+ * Registers one hit for `key` (a caller-unique `member` id, so repeat
38
+ * calls within the same millisecond don't collide) and returns how many
39
+ * hits are still inside the trailing `windowMs` sliding window.
40
+ */
41
+ slidingWindowHit(key: string, windowMs: number, member: string): Promise<number>;
42
+ }
43
+ export interface X402GuardConfig {
44
+ /**
45
+ * Backing store. Providing this is what turns the guard on — with no
46
+ * `guard` config at all, x402Serve() behaves exactly as before (no
47
+ * replay protection, no rate limiting, zero overhead).
48
+ */
49
+ store: X402GuardStore;
50
+ /** How long a used payment proof stays claimed. Default 15 minutes. */
51
+ replayTtlMs?: number;
52
+ /**
53
+ * Sliding-window rate limit per caller IP. Omit to skip rate limiting
54
+ * even with `store` configured — replay protection and rate limiting
55
+ * are independent knobs.
56
+ */
57
+ rateLimit?: {
58
+ max: number;
59
+ windowMs: number;
60
+ };
61
+ }
62
+ export interface GuardRequest {
63
+ method: string;
64
+ url: string;
65
+ headers: Record<string, string | string[] | undefined>;
66
+ ip?: string;
67
+ }
68
+ export interface GuardDenied {
69
+ status: number;
70
+ body: Record<string, unknown>;
71
+ headers?: Record<string, string>;
72
+ }
73
+ export interface ReplayCheck {
74
+ allowed: boolean;
75
+ denied?: GuardDenied;
76
+ /** Call after the response is known — releases the claim on non-2xx. */
77
+ release?: () => Promise<void>;
78
+ }
79
+ export interface RateLimitCheck {
80
+ allowed: boolean;
81
+ denied?: GuardDenied;
82
+ }
83
+ /** Single-use guard against replaying a payment proof. */
84
+ export declare function checkReplay(req: GuardRequest, config: X402GuardConfig): Promise<ReplayCheck>;
85
+ /** Sliding-window rate limit per caller IP. */
86
+ export declare function checkRateLimit(req: GuardRequest, config: X402GuardConfig): Promise<RateLimitCheck>;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Optional replay/rate-limit protection for x402Serve() — off by default.
4
+ *
5
+ * x402Serve() verifies and settles a payment; on its own it does not stop
6
+ * the same signed payment proof from being replayed against a route (a
7
+ * concurrent-request "free shopping" window), and it does not rate-limit
8
+ * callers. See https://github.com/nirium-protocol/nirium/issues/91.
9
+ *
10
+ * The design here (single-use claim keyed on the payment proof + method +
11
+ * route, released only if the request did NOT end in 2xx so a legitimate
12
+ * retry after a facilitator hiccup still works; fail-closed for the replay
13
+ * guard and fail-open for rate limiting, both by the same reasoning) is
14
+ * generalized from a real production x402Serve() integration —
15
+ * Edgadafi/remesa-liquidez (commit 1e0cbd5902cb224d3c6a2320cc009cf4df84f513,
16
+ * `backend/src/middleware/paymentGuard.ts` and `backend/src/middleware/
17
+ * rateLimit.ts`) — credited here and in CHANGELOG.md. The store interface
18
+ * and this module's code are our own; nothing here is copied from theirs.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.checkReplay = checkReplay;
22
+ exports.checkRateLimit = checkRateLimit;
23
+ const node_crypto_1 = require("node:crypto");
24
+ const DEFAULT_REPLAY_TTL_MS = 15 * 60 * 1000;
25
+ // @x402/express reads the payment proof from `payment-signature` (x402
26
+ // v2), falling back to `x-payment` (v1) — verified directly against the
27
+ // published @x402/express package (dist/cjs/index.js), not assumed from
28
+ // either header name alone. The guard has to hash the SAME header the real
29
+ // middleware will read, or it protects nothing.
30
+ function readPaymentHeader(headers) {
31
+ const v2 = headers['payment-signature'];
32
+ const v1 = headers['x-payment'];
33
+ const pick = (v) => (Array.isArray(v) ? v[0] : v);
34
+ return pick(v2) ?? pick(v1);
35
+ }
36
+ /** Single-use guard against replaying a payment proof. */
37
+ async function checkReplay(req, config) {
38
+ const raw = readPaymentHeader(req.headers);
39
+ if (!raw)
40
+ return { allowed: true }; // no proof yet — let x402Serve issue its 402
41
+ // The key binds the proof to method + route, same binding the exact
42
+ // scheme itself already puts on resource.url — a proof burned against
43
+ // route A doesn't block its own legitimate use against route B.
44
+ const digest = (0, node_crypto_1.createHash)('sha256').update(raw).update('\n').update(`${req.method} ${req.url}`).digest('hex');
45
+ const key = `nirium:x402guard:replay:${digest}`;
46
+ let claimed;
47
+ try {
48
+ claimed = await config.store.claimOnce(key, config.replayTtlMs ?? DEFAULT_REPLAY_TTL_MS);
49
+ }
50
+ catch {
51
+ // Fail-closed: once a store is configured, its failure must never
52
+ // silently become "no protection" — a payment gate that only
53
+ // protects when convenient isn't a payment gate.
54
+ return {
55
+ allowed: false,
56
+ denied: {
57
+ status: 503,
58
+ body: {
59
+ error: 'replay_protection_unavailable',
60
+ message: 'The payment replay guard\'s store is unavailable right now. Retry later.',
61
+ },
62
+ },
63
+ };
64
+ }
65
+ if (!claimed) {
66
+ return {
67
+ allowed: false,
68
+ denied: {
69
+ status: 409,
70
+ body: {
71
+ error: 'payment_replayed',
72
+ message: 'This payment proof was already used. Each request needs a freshly signed payment.',
73
+ },
74
+ },
75
+ };
76
+ }
77
+ return { allowed: true, release: () => config.store.release(key).catch(() => { }) };
78
+ }
79
+ /** Sliding-window rate limit per caller IP. */
80
+ async function checkRateLimit(req, config) {
81
+ if (!config.rateLimit)
82
+ return { allowed: true };
83
+ const ip = req.ip || 'unknown';
84
+ const key = `nirium:x402guard:rl:${ip}`;
85
+ const member = `${Date.now()}:${Math.random().toString(36).slice(2, 10)}`;
86
+ let count;
87
+ try {
88
+ count = await config.store.slidingWindowHit(key, config.rateLimit.windowMs, member);
89
+ }
90
+ catch {
91
+ // Fail-open: a store outage must not turn into a self-inflicted
92
+ // denial of service for every caller — rate limiting protects
93
+ // availability, and denying all traffic because the counter is
94
+ // unreachable would be the opposite of that.
95
+ return { allowed: true };
96
+ }
97
+ if (count > config.rateLimit.max) {
98
+ return {
99
+ allowed: false,
100
+ denied: {
101
+ status: 429,
102
+ headers: { 'Retry-After': String(Math.ceil(config.rateLimit.windowMs / 1000)) },
103
+ body: {
104
+ error: 'rate_limited',
105
+ message: `Max ${config.rateLimit.max} requests per ${Math.ceil(config.rateLimit.windowMs / 1000)}s.`,
106
+ },
107
+ },
108
+ };
109
+ }
110
+ return { allowed: true };
111
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Unit tests for the replay guard / rate limit checks that back
3
+ * X402ServeConfig['guard']. Pure functions against a fake in-memory store,
4
+ * no network or Express involved — the integration-level tests (guard
5
+ * wired through x402Serve() itself) live in x402serve-smoke.test.ts.
6
+ *
7
+ * These reproduce the exact scenarios a real production x402Serve() user
8
+ * (Edgadafi/remesa-liquidez) built their own version of this against, per
9
+ * https://github.com/nirium-protocol/nirium/issues/91.
10
+ */
11
+ export {};
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ /**
3
+ * Unit tests for the replay guard / rate limit checks that back
4
+ * X402ServeConfig['guard']. Pure functions against a fake in-memory store,
5
+ * no network or Express involved — the integration-level tests (guard
6
+ * wired through x402Serve() itself) live in x402serve-smoke.test.ts.
7
+ *
8
+ * These reproduce the exact scenarios a real production x402Serve() user
9
+ * (Edgadafi/remesa-liquidez) built their own version of this against, per
10
+ * https://github.com/nirium-protocol/nirium/issues/91.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const x402_guard_1 = require("./x402-guard");
14
+ function fakeStore() {
15
+ const claims = new Map();
16
+ return {
17
+ claims,
18
+ async claimOnce(key, ttlMs) {
19
+ const now = Date.now();
20
+ const expiresAt = claims.get(key);
21
+ if (expiresAt !== undefined && expiresAt > now)
22
+ return false;
23
+ claims.set(key, now + ttlMs);
24
+ return true;
25
+ },
26
+ async release(key) {
27
+ claims.delete(key);
28
+ },
29
+ async slidingWindowHit() {
30
+ throw new Error('slidingWindowHit not used by replay tests');
31
+ },
32
+ };
33
+ }
34
+ function req(overrides = {}) {
35
+ return {
36
+ method: 'GET',
37
+ url: '/signals',
38
+ headers: { 'payment-signature': 'proof-abc' },
39
+ ip: '203.0.113.1',
40
+ ...overrides,
41
+ };
42
+ }
43
+ describe('checkReplay', () => {
44
+ it('allows a request with no payment proof yet (lets x402Serve issue its 402)', async () => {
45
+ const store = fakeStore();
46
+ const config = { store };
47
+ const result = await (0, x402_guard_1.checkReplay)(req({ headers: {} }), config);
48
+ expect(result.allowed).toBe(true);
49
+ });
50
+ it('allows the first use of a payment proof', async () => {
51
+ const store = fakeStore();
52
+ const config = { store };
53
+ const result = await (0, x402_guard_1.checkReplay)(req(), config);
54
+ expect(result.allowed).toBe(true);
55
+ expect(store.claims.size).toBe(1);
56
+ });
57
+ it('rejects a reused payment proof against the same route with 409', async () => {
58
+ const store = fakeStore();
59
+ const config = { store };
60
+ const first = await (0, x402_guard_1.checkReplay)(req(), config);
61
+ expect(first.allowed).toBe(true);
62
+ const second = await (0, x402_guard_1.checkReplay)(req(), config);
63
+ expect(second.allowed).toBe(false);
64
+ expect(second.denied?.status).toBe(409);
65
+ expect(second.denied?.body.error).toBe('payment_replayed');
66
+ });
67
+ it('allows the same proof against a DIFFERENT route (binds proof + method + route)', async () => {
68
+ const store = fakeStore();
69
+ const config = { store };
70
+ await (0, x402_guard_1.checkReplay)(req({ url: '/signals' }), config);
71
+ const other = await (0, x402_guard_1.checkReplay)(req({ url: '/market' }), config);
72
+ expect(other.allowed).toBe(true);
73
+ });
74
+ it('reads the x402 v2 header "payment-signature" and the v1 fallback "x-payment"', async () => {
75
+ const store = fakeStore();
76
+ const config = { store };
77
+ const v2 = await (0, x402_guard_1.checkReplay)(req({ headers: { 'payment-signature': 'same-proof' } }), config);
78
+ expect(v2.allowed).toBe(true);
79
+ const v1Reuse = await (0, x402_guard_1.checkReplay)(req({ headers: { 'x-payment': 'same-proof' } }), config);
80
+ // Same underlying proof string, same method+url -> same digest -> replay.
81
+ expect(v1Reuse.allowed).toBe(false);
82
+ });
83
+ it('releases the claim when the caller reports the request did not succeed, allowing a legitimate retry', async () => {
84
+ const store = fakeStore();
85
+ const config = { store };
86
+ const first = await (0, x402_guard_1.checkReplay)(req(), config);
87
+ expect(first.allowed).toBe(true);
88
+ await first.release(); // simulates: response ended non-2xx (e.g. facilitator down)
89
+ const retry = await (0, x402_guard_1.checkReplay)(req(), config);
90
+ expect(retry.allowed).toBe(true);
91
+ });
92
+ it('fails CLOSED (503) when the store is unavailable, never silently letting the payment through unprotected', async () => {
93
+ const brokenStore = {
94
+ async claimOnce() { throw new Error('store down'); },
95
+ async release() { },
96
+ async slidingWindowHit() { throw new Error('store down'); },
97
+ };
98
+ const config = { store: brokenStore };
99
+ const result = await (0, x402_guard_1.checkReplay)(req(), config);
100
+ expect(result.allowed).toBe(false);
101
+ expect(result.denied?.status).toBe(503);
102
+ expect(result.denied?.body.error).toBe('replay_protection_unavailable');
103
+ });
104
+ });
105
+ describe('checkRateLimit', () => {
106
+ it('allows when no rateLimit config is set, even with a store present', async () => {
107
+ const store = fakeStore();
108
+ const config = { store };
109
+ const result = await (0, x402_guard_1.checkRateLimit)(req(), config);
110
+ expect(result.allowed).toBe(true);
111
+ });
112
+ it('allows requests under the limit', async () => {
113
+ let hits = 0;
114
+ const store = {
115
+ async claimOnce() { return true; },
116
+ async release() { },
117
+ async slidingWindowHit() { hits += 1; return hits; },
118
+ };
119
+ const config = { store, rateLimit: { max: 5, windowMs: 60_000 } };
120
+ const result = await (0, x402_guard_1.checkRateLimit)(req(), config);
121
+ expect(result.allowed).toBe(true);
122
+ });
123
+ it('rejects with 429 once the sliding window count exceeds max', async () => {
124
+ const store = {
125
+ async claimOnce() { return true; },
126
+ async release() { },
127
+ async slidingWindowHit() { return 6; },
128
+ };
129
+ const config = { store, rateLimit: { max: 5, windowMs: 60_000 } };
130
+ const result = await (0, x402_guard_1.checkRateLimit)(req(), config);
131
+ expect(result.allowed).toBe(false);
132
+ expect(result.denied?.status).toBe(429);
133
+ expect(result.denied?.headers?.['Retry-After']).toBe('60');
134
+ });
135
+ it('fails OPEN when the store errors, so a store outage never becomes a self-inflicted denial of service', async () => {
136
+ const store = {
137
+ async claimOnce() { return true; },
138
+ async release() { },
139
+ async slidingWindowHit() { throw new Error('store down'); },
140
+ };
141
+ const config = { store, rateLimit: { max: 5, windowMs: 60_000 } };
142
+ const result = await (0, x402_guard_1.checkRateLimit)(req(), config);
143
+ expect(result.allowed).toBe(true);
144
+ });
145
+ });
@@ -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 {};