x402-warden 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) x402-warden contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ x402-warden
2
+ Copyright (c) x402-warden contributors
3
+
4
+ Licensed under the MIT License. See LICENSE.
5
+
6
+ Third-party dependencies are distributed under their own licenses.
7
+ This package does not bundle the official x402 SDK source.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # x402-warden for TypeScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Attach local payment policy and reservation accounting to the official x402 buyer
4
+ client. Blocks quotes when configured limits, recipient pins or observed URL
5
+ checks reject the proposed payment; retains capacity for unresolved authorizations.
6
+
7
+ Install `x402-warden` with `@x402/core` and your HTTP adapter. The npm peer
8
+ range is `@x402/core >=2.23.0 <3`.
9
+
10
+ Start with the runnable [fetch](../../docs/quickstart-fetch.md) or
11
+ [Axios](../../docs/quickstart-axios.md) guide. Supported SDK versions checked
12
+ 2026-11-14: npm 2.23, 2.28, 2.30.
13
+
14
+ Use one shared payer ledger and explicit per-call and daily caps. `MemoryStore`
15
+ is the default ephemeral store; `FileStore` uses a cooperating local filesystem
16
+ protocol. Capture the request URL on the HTTP client supplied to the adapter.
17
+ The observed URL is required by default. Transport settings belong in guard
18
+ options, separate from the payment policy.
19
+
20
+ Read [options and defaults](../../docs/options.md), [reason codes](../../docs/reason-codes.md),
21
+ [hold resolution](../../docs/holds.md), [trust boundary](../../docs/trust-boundary.md),
22
+ [limitations](../../docs/limitations.md) and [threat model](../../docs/threat-model.md).
23
+ The [SDK integration notes](../../docs/compared-with-sdk.md) describe responsibilities.
24
+
25
+ Source: [shared policy specification](../../spec/policy/README.md),
26
+ [TypeScript implementation](../x402-warden/src/index.ts),
27
+ [Python implementation](../x402-warden-py/src/x402_warden/guard.py).
28
+
29
+ The `Provider` interface accepts any signed audit provider. A reference signed
30
+ provider lives in the tests.
@@ -0,0 +1,2 @@
1
+ export { MemoryStore, FileStore, ObservedUrls, captureRequestUrl, evaluate, ProviderValidationError, ProviderError, quoteId, authorizationId, reconcileReservations, listUnresolvedReservations, resolveReservation, recordSettlement, recordPaymentFailure, guard } from './src/index.js';
2
+ export type { Terms, Policy, State, Reservation, ReserveOptions, Store, Decision, CreationContext, ResponseContext, GuardableClient, AuditResult, AuditChallenge, Provider, Options, Diagnostic, ResolutionEvidence, Resolution } from './src/index.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { MemoryStore, FileStore, ObservedUrls, captureRequestUrl, evaluate, ProviderValidationError, ProviderError, quoteId, authorizationId, reconcileReservations, listUnresolvedReservations, resolveReservation, recordSettlement, recordPaymentFailure, guard } from './src/index.js';
package/dist/spec.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { authorizationError, canonical, requirementDigest, resultPayload, personalHash, effectiveRequirements } from './src/index.js';
package/dist/spec.js ADDED
@@ -0,0 +1 @@
1
+ export { authorizationError, canonical, requirementDigest, resultPayload, personalHash, effectiveRequirements } from './src/index.js';
@@ -0,0 +1,220 @@
1
+ export { MemoryStore, FileStore } from './store.js';
2
+ export type Terms = Record<string, unknown>;
3
+ export interface Policy {
4
+ maxPerCallUsd?: string | number;
5
+ maxDailyUsd?: string | number;
6
+ allowedNetworks?: string[];
7
+ /** Configured assets must be six-decimal USDC. Otherwise the built-in USDC registry applies. */
8
+ allowedAssets?: Record<string, string[]>;
9
+ payToPins?: Record<string, string>;
10
+ maxPriceDriftPercent?: number;
11
+ expectedPriceUsd?: Record<string, string | number>;
12
+ /** At most four decimal places; equality passes. */
13
+ maxPriceDriftMultiple?: number;
14
+ /** Defaults to 300 seconds; includes advertised creation timeouts. */
15
+ maxAuthorizationSeconds?: number;
16
+ /** Permitted future validAfter offset; defaults to 30 seconds. */
17
+ authorizationClockSkewSeconds?: number;
18
+ /** UNSAFE accounting tradeoff: expiry does not prove no historical debit. Default false. */
19
+ releaseUnresolvedAfterExpiry?: boolean;
20
+ tofu?: 'settlement' | 'allowed' | 'off';
21
+ sanctionedAddresses?: string[];
22
+ }
23
+ export interface State {
24
+ schemaVersion?: number;
25
+ day?: string;
26
+ spentAtomic?: string;
27
+ pendingAtomic?: string;
28
+ unresolvedAtomic?: string;
29
+ payToPins?: Record<string, string>;
30
+ prices?: Record<string, string>;
31
+ reservations?: Record<string, Reservation>;
32
+ providerNonces?: Record<string, number>;
33
+ }
34
+ export interface ResolutionEvidence {
35
+ source: 'operator' | 'chain' | 'facilitator';
36
+ note: string;
37
+ transaction?: string;
38
+ resolvedBy?: string;
39
+ evidenceSource?: string;
40
+ observedAt?: number;
41
+ }
42
+ export interface Resolution extends ResolutionEvidence {
43
+ outcome: 'debited' | 'not_debited';
44
+ at: number;
45
+ }
46
+ export interface Reservation {
47
+ resolution?: Resolution;
48
+ resolutions?: Resolution[];
49
+ intentId?: string;
50
+ cancelUnknown?: boolean;
51
+ reservedAt?: number;
52
+ approvedTerms?: Terms;
53
+ authorizationLimitSeconds?: number;
54
+ authorizationError?: string;
55
+ duplicateOf?: string;
56
+ legacyAuthorizationId?: string;
57
+ identityObserved?: boolean;
58
+ key: string;
59
+ quoteId: string;
60
+ amount: string;
61
+ expiresAt: number;
62
+ status: 'reserved' | 'spent' | 'released' | 'uncertain' | 'unresolved';
63
+ signatureState?: 'unsigned' | 'possible' | 'signed';
64
+ releaseUnresolvedAfterExpiry?: boolean;
65
+ reason?: 'prior_day_unresolved' | 'authorization_expired_unresolved' | 'cancel_outcome_unknown';
66
+ observationKey?: string;
67
+ priceKey?: string;
68
+ url: string;
69
+ payTo: string;
70
+ authorizationId?: string;
71
+ settlementId?: string;
72
+ upstreamError?: {
73
+ code: string;
74
+ phase: 'verify' | 'settle' | 'cancel';
75
+ at: number;
76
+ };
77
+ tofu?: 'settlement' | 'allowed' | 'off';
78
+ }
79
+ export interface ReserveOptions {
80
+ now?: number | (() => number);
81
+ reservation: Omit<Reservation, 'key' | 'amount' | 'expiresAt' | 'status'>;
82
+ check: (state: State) => Decision;
83
+ commit?: (state: State) => void;
84
+ }
85
+ /** transaction and reserve must linearize across ALL users of the same payer store.
86
+ * Callbacks are synchronous. Commit all fields together or commit nothing. */
87
+ export interface Store {
88
+ get(): State | Promise<State>;
89
+ set(state: State): void | Promise<void>;
90
+ transaction<R>(update: (state: State) => R): R | Promise<R>;
91
+ reserve(key: string, amount: string, ttl: number, options: ReserveOptions): Decision | Promise<Decision>;
92
+ }
93
+ export interface Decision {
94
+ decision: 'allow' | 'block';
95
+ reasons: string[];
96
+ }
97
+ export interface CreationContext {
98
+ paymentRequired: object;
99
+ selectedRequirements: object;
100
+ requestUrl?: string;
101
+ }
102
+ export interface ResponseContext {
103
+ paymentPayload: unknown;
104
+ requirements: object;
105
+ settleResponse?: {
106
+ success: boolean;
107
+ transaction?: string;
108
+ errorReason?: string;
109
+ };
110
+ paymentRequired?: object;
111
+ error?: unknown;
112
+ /** Transport observations, never inferred from settlement success. */
113
+ status?: number;
114
+ bodyBytes?: number;
115
+ }
116
+ export interface GuardableClient {
117
+ onBeforePaymentCreation(hook: (ctx: CreationContext) => Promise<void | {
118
+ abort: true;
119
+ reason: string;
120
+ }>): unknown;
121
+ onAfterPaymentCreation(hook: (ctx: CreationContext & {
122
+ paymentPayload: unknown;
123
+ }) => Promise<void>): unknown;
124
+ onPaymentCreationFailure?(hook: (ctx: CreationContext & {
125
+ error: unknown;
126
+ }) => Promise<void>): unknown;
127
+ onPaymentResponse(hook: (ctx: ResponseContext) => Promise<void | {
128
+ recovered: true;
129
+ }>): unknown;
130
+ }
131
+ export interface AuditResult extends Terms {
132
+ verdict: string;
133
+ terms_digests: string[];
134
+ }
135
+ export interface AuditChallenge {
136
+ nonce: string;
137
+ now: number;
138
+ maxAgeSeconds?: number;
139
+ }
140
+ export interface Provider {
141
+ readonly maxAgeSeconds?: number;
142
+ audit(url: string, requirements: Terms, challenge?: AuditChallenge): Promise<AuditResult>;
143
+ }
144
+ export interface Options {
145
+ urlBinding?: 'origin' | 'path' | 'exact';
146
+ store?: Store;
147
+ provider?: Provider;
148
+ onProviderError?: 'block' | 'allow';
149
+ now?: () => Date;
150
+ requestUrl?: string | ((ctx: CreationContext) => string | undefined);
151
+ observedUrls?: ObservedUrls;
152
+ requireObservedUrl?: boolean;
153
+ providerMaxAgeSeconds?: number;
154
+ onDiagnostic?: (diagnostic: Diagnostic) => void;
155
+ /** Trusted evidence lookup for clients whose response dispatch cannot be wrapped. */
156
+ settlementEvidence?: (reservation: Reservation, payload: unknown) => Promise<ResponseContext | undefined>;
157
+ }
158
+ export interface Diagnostic {
159
+ code: string;
160
+ outcome: 'warn' | 'uncertain';
161
+ message: string;
162
+ reservationKey?: string;
163
+ }
164
+ /** Capture the transport URL, never a server assertion. Register BEFORE header-producing hooks.
165
+ * Challenge objects must be propagated by the transport; clones require explicit requestUrl. */
166
+ export declare class ObservedUrls {
167
+ private urls;
168
+ private responses;
169
+ captureResponse(payload: object, status: number, bodyBytes?: number): void;
170
+ response(payload: object): {
171
+ status: number;
172
+ bodyBytes?: number;
173
+ } | undefined;
174
+ capture(ctx: {
175
+ paymentRequired: object;
176
+ requestUrl: string;
177
+ }): void;
178
+ get(ctx: CreationContext): string | undefined;
179
+ }
180
+ export declare function captureRequestUrl<T extends {
181
+ onPaymentRequired(hook: (ctx: {
182
+ paymentRequired: object;
183
+ requestUrl: string;
184
+ }) => Promise<void>): unknown;
185
+ }>(http: T, observed?: ObservedUrls): ObservedUrls;
186
+ export declare function effectiveRequirements(req: Terms, pr: Terms): Terms;
187
+ /** Pure decision. State is a snapshot for the current UTC day; no mutation or I/O. */
188
+ export declare function evaluate(policy: Policy, state: State, requirements: object, paymentRequired: object, observedUrl?: string, nowSeconds?: number, urlBinding?: 'origin' | 'path' | 'exact'): Decision;
189
+ export declare function canonical(value: unknown): string;
190
+ export declare function requirementDigest(req: Terms): string;
191
+ export declare function resultPayload(result: Terms): string;
192
+ export declare function personalHash(text: string): Uint8Array;
193
+ export declare class ProviderValidationError extends Error {
194
+ }
195
+ export declare class ProviderError extends Error {
196
+ }
197
+ export declare function quoteId(requirements: object, paymentRequired?: object): string;
198
+ export declare function authorizationId(payload: unknown): string;
199
+ /** Structural revalidation of recognized signed fields, not signature verification. */
200
+ export declare function authorizationError(payload: unknown, approved: Terms, reservedAt: number, ceilingSeconds?: number): string | undefined;
201
+ /** Explicit reconciliation also serves transports which never dispatch response hooks. */
202
+ type Clock = Date | (() => Date);
203
+ export declare function reconcileReservations(store: Store, now?: Clock): Promise<void>;
204
+ /** Refresh under the lock; returned records are detached snapshots with reason codes. */
205
+ export declare function listUnresolvedReservations(store: Store, now?: Clock): Promise<Reservation[]>;
206
+ /** Trusted operator/chain evidence only. not_debited asserts definitive no debit. */
207
+ export declare function resolveReservation(store: Store, key: string, outcome: 'debited' | 'not_debited', evidence: ResolutionEvidence, now?: Clock): Promise<void>;
208
+ /** Record an upstream failure without treating a code as final no-debit evidence. */
209
+ export declare function recordPaymentFailure(store: Store, key: string, failure: {
210
+ phase: 'verify' | 'settle' | 'cancel';
211
+ code: string;
212
+ }, now?: Clock): Promise<void>;
213
+ /** Caller-supplied final settlement evidence, for v1/skipped callbacks/block-height
214
+ * validity. The caller is the trust boundary; never infer finality from a timeout. */
215
+ export declare function recordSettlement(store: Store, keyOrAuthorizationId: string, evidence: {
216
+ final: true;
217
+ success: boolean;
218
+ transaction?: string;
219
+ }, now?: Clock): Promise<void>;
220
+ export declare function guard<T extends GuardableClient>(client: T, policy: Policy, options?: Options): T;