mppx 0.20.1 → 0.21.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/CHANGELOG.md +24 -0
- package/dist/Challenge.d.ts +59 -3
- package/dist/Challenge.js +162 -21
- package/dist/Errors.d.ts +35 -1
- package/dist/Errors.js +41 -3
- package/dist/Method.js +2 -2
- package/dist/Receipt.d.ts +2 -0
- package/dist/Receipt.js +5 -0
- package/dist/Store.d.ts +39 -10
- package/dist/Store.js +136 -29
- package/dist/cli/cli.d.ts +5 -0
- package/dist/cli/cli.js +135 -135
- package/dist/cli/plugins/index.js +12 -12
- package/dist/cli/sessions/commands.js +9 -0
- package/dist/cli/sessions/store.js +3 -2
- package/dist/cli/validate/challenge.js +15 -1
- package/dist/client/Mppx.d.ts +1 -1
- package/dist/client/Mppx.js +2 -1
- package/dist/client/internal/Fetch.d.ts +2 -1
- package/dist/client/internal/Fetch.js +43 -5
- package/dist/client/internal/PendingSettlement.d.ts +11 -0
- package/dist/client/internal/PendingSettlement.js +22 -0
- package/dist/client/internal/protocols/Mcp.js +8 -0
- package/dist/evm/client/Charge.js +7 -1
- package/dist/evm/server/Charge.d.ts +5 -0
- package/dist/evm/server/Charge.js +44 -0
- package/dist/evm/server/Methods.d.ts +8 -0
- package/dist/evm/server/Methods.js +8 -0
- package/dist/extensions/identity/attestation/Jwks.js +3 -3
- package/dist/extensions/identity/link/server/index.js +4 -4
- package/dist/extensions/identity/persona/server/index.js +3 -3
- package/dist/internal/CredentialExpiry.d.ts +30 -0
- package/dist/internal/CredentialExpiry.js +51 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.js +29 -10
- package/dist/middlewares/express.d.ts +7 -2
- package/dist/middlewares/express.js +20 -23
- package/dist/middlewares/internal/express.d.ts +9 -1
- package/dist/middlewares/internal/express.js +348 -2
- package/dist/proxy/Proxy.js +15 -3
- package/dist/proxy/internal/Replay.d.ts +10 -0
- package/dist/proxy/internal/Replay.js +5 -0
- package/dist/server/Mppx.d.ts +1 -1
- package/dist/server/Mppx.js +19 -14
- package/dist/server/NodeListener.js +7 -0
- package/dist/server/Request.d.ts +6 -0
- package/dist/server/Request.js +43 -22
- package/dist/server/internal/challengeMeta.d.ts +10 -0
- package/dist/server/internal/challengeMeta.js +31 -1
- package/dist/server/internal/host.d.ts +4 -0
- package/dist/server/internal/host.js +41 -0
- package/dist/tempo/client/Charge.d.ts +5 -4
- package/dist/tempo/client/Charge.js +210 -38
- package/dist/tempo/client/Subscription.js +3 -0
- package/dist/tempo/internal/zone.d.ts +8 -0
- package/dist/tempo/internal/zone.js +15 -0
- package/dist/tempo/server/Charge.d.ts +19 -0
- package/dist/tempo/server/Charge.js +60 -15
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/transport.js +10 -54
- package/dist/tempo/session/client/ChannelOps.js +1 -1
- package/dist/tempo/session/client/SessionManager.d.ts +4 -1
- package/dist/tempo/session/client/SessionManager.js +8 -2
- package/dist/tempo/session/server/CredentialVerification.js +2 -3
- package/dist/viem/Client.d.ts +2 -0
- package/dist/viem/Client.js +4 -1
- package/dist/x402/Assets.d.ts +6 -0
- package/dist/x402/Assets.js +10 -0
- package/dist/x402/Types.d.ts +68 -8
- package/dist/x402/Types.js +17 -2
- package/dist/x402/client/Exact.js +4 -1
- package/dist/x402/middlewares/express.js +10 -1
- package/dist/x402/server/EvmCharge.d.ts +20 -3
- package/dist/x402/server/EvmCharge.js +13 -1
- package/dist/x402/server/Facilitator.d.ts +42 -3
- package/dist/x402/server/Facilitator.js +126 -16
- package/package.json +1 -1
|
@@ -145,12 +145,19 @@ export function sse(options) {
|
|
|
145
145
|
const available = BigInt(currentReceipt.acceptedCumulative) - BigInt(currentReceipt.spent);
|
|
146
146
|
if (available < tickCost)
|
|
147
147
|
return paymentRequired(available);
|
|
148
|
+
// Plain content authorizes its headers as well as its body. Commit before
|
|
149
|
+
// returning the response so adapters can safely honor an explicit flush.
|
|
150
|
+
const result = await ChannelStore.deductFromChannel(store, channelId, tickCost);
|
|
151
|
+
if (!result.ok)
|
|
152
|
+
return paymentRequired(result.channel.highestVoucherAmount - result.channel.spent);
|
|
153
|
+
await options.settleCharged?.(result.channel);
|
|
148
154
|
const chargedReceipt = {
|
|
149
155
|
...currentReceipt,
|
|
150
|
-
|
|
151
|
-
|
|
156
|
+
acceptedCumulative: result.channel.highestVoucherAmount.toString(),
|
|
157
|
+
spent: result.channel.spent.toString(),
|
|
158
|
+
units: result.channel.units,
|
|
152
159
|
};
|
|
153
|
-
|
|
160
|
+
return base.respondReceipt({
|
|
154
161
|
credential: verifiedCredential,
|
|
155
162
|
envelope,
|
|
156
163
|
input,
|
|
@@ -158,54 +165,6 @@ export function sse(options) {
|
|
|
158
165
|
response: response,
|
|
159
166
|
challengeId: verifiedChallengeId,
|
|
160
167
|
});
|
|
161
|
-
const chargePlainResponse = async () => {
|
|
162
|
-
const result = await ChannelStore.deductFromChannel(store, channelId, tickCost);
|
|
163
|
-
if (result.ok)
|
|
164
|
-
await options.settleCharged?.(result.channel);
|
|
165
|
-
return result;
|
|
166
|
-
};
|
|
167
|
-
// Non-SSE response (e.g. upstream returned JSON instead of event-stream).
|
|
168
|
-
// Need to deduct tickCost so request isn't free.
|
|
169
|
-
// For null-body statuses, the request shape determines whether the
|
|
170
|
-
// response is management (no charge) or plain content (charge one tick).
|
|
171
|
-
if (isNullBodyStatus(chargedResponse.status)) {
|
|
172
|
-
const result = await chargePlainResponse();
|
|
173
|
-
if (!result.ok)
|
|
174
|
-
return paymentRequired(result.channel.highestVoucherAmount - result.channel.spent);
|
|
175
|
-
return chargedResponse;
|
|
176
|
-
}
|
|
177
|
-
const stream = new ReadableStream({
|
|
178
|
-
async start(controller) {
|
|
179
|
-
// deduction completes before consumer reads
|
|
180
|
-
const result = await chargePlainResponse();
|
|
181
|
-
if (!result.ok) {
|
|
182
|
-
controller.error(insufficientBalance(result.channel.highestVoucherAmount - result.channel.spent));
|
|
183
|
-
return;
|
|
184
|
-
}
|
|
185
|
-
if (!chargedResponse.body) {
|
|
186
|
-
controller.close();
|
|
187
|
-
return;
|
|
188
|
-
}
|
|
189
|
-
const reader = chargedResponse.body.getReader();
|
|
190
|
-
try {
|
|
191
|
-
while (true) {
|
|
192
|
-
const { done, value } = await reader.read();
|
|
193
|
-
if (done)
|
|
194
|
-
break;
|
|
195
|
-
controller.enqueue(value);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
finally {
|
|
199
|
-
reader.releaseLock();
|
|
200
|
-
controller.close();
|
|
201
|
-
}
|
|
202
|
-
},
|
|
203
|
-
});
|
|
204
|
-
return new Response(stream, {
|
|
205
|
-
status: chargedResponse.status,
|
|
206
|
-
statusText: chargedResponse.statusText,
|
|
207
|
-
headers: chargedResponse.headers,
|
|
208
|
-
});
|
|
209
168
|
},
|
|
210
169
|
});
|
|
211
170
|
}
|
|
@@ -256,7 +215,4 @@ function isAsyncGeneratorFunction(value) {
|
|
|
256
215
|
function isAsyncIterable(value) {
|
|
257
216
|
return value !== null && typeof value === 'object' && Symbol.asyncIterator in value;
|
|
258
217
|
}
|
|
259
|
-
function isNullBodyStatus(status) {
|
|
260
|
-
return [101, 204, 205, 304].includes(status);
|
|
261
|
-
}
|
|
262
218
|
//# sourceMappingURL=transport.js.map
|
|
@@ -82,7 +82,7 @@ export function serializeCredential(challenge, payload, chainId, account) {
|
|
|
82
82
|
return Credential.serialize({
|
|
83
83
|
challenge,
|
|
84
84
|
payload,
|
|
85
|
-
source: `did:pkh:eip155:${chainId}:${account.address}`,
|
|
85
|
+
source: `did:pkh:eip155:${chainId}:${payload.descriptor?.payer ?? account.address}`,
|
|
86
86
|
});
|
|
87
87
|
}
|
|
88
88
|
/** Case-insensitive EVM address equality. */
|
|
@@ -26,7 +26,10 @@ export type SessionManager = {
|
|
|
26
26
|
readonly state: SessionState;
|
|
27
27
|
/** Runs the HTTP 402 probe, signs/open/top-ups as needed, retries, and returns receipt metadata. */
|
|
28
28
|
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<PaymentResponse>;
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Opens a paid SSE stream and auto-posts vouchers/top-ups when the server requests more headroom.
|
|
31
|
+
* Rejects `Fetch.withoutPayment` requests; use `fetch` to read an unpaid stream without session management.
|
|
32
|
+
*/
|
|
30
33
|
sse(input: RequestInfo | URL, init?: SessionManagerSseOptions): Promise<AsyncIterable<string>>;
|
|
31
34
|
/** Opens a paid WebSocket session after an HTTP challenge probe and manages in-band voucher frames. */
|
|
32
35
|
ws(input: string | URL, init?: SessionManagerWebSocketOptions): Promise<SessionManagedWebSocket>;
|
|
@@ -672,10 +672,11 @@ export function sessionManager(parameters) {
|
|
|
672
672
|
if (runtime.channel?.opened)
|
|
673
673
|
await persistChannel(runtime.channel);
|
|
674
674
|
}
|
|
675
|
-
function toPaymentResponse(response) {
|
|
675
|
+
function toPaymentResponse(response, acceptReceipt = true) {
|
|
676
676
|
const receiptHeader = response.headers.get(Constants.Headers.paymentReceipt);
|
|
677
677
|
const receipt = receiptHeader ? deserializeSessionReceipt(receiptHeader) : null;
|
|
678
|
-
|
|
678
|
+
if (acceptReceipt)
|
|
679
|
+
updateSpentFromReceipt(receipt);
|
|
679
680
|
return Object.assign(response, {
|
|
680
681
|
receipt,
|
|
681
682
|
challenge: runtime.lastChallenge,
|
|
@@ -684,6 +685,9 @@ export function sessionManager(parameters) {
|
|
|
684
685
|
});
|
|
685
686
|
}
|
|
686
687
|
async function doFetch(input, init) {
|
|
688
|
+
// Opted-out requests must not bootstrap, restore, top up, or retry a session.
|
|
689
|
+
if (init?.[Fetch.skipPayment])
|
|
690
|
+
return toPaymentResponse(await config.fetch(input, Fetch.withoutPayment(init)), false);
|
|
687
691
|
// The manager drives one shared `runtime` state machine, so requests are
|
|
688
692
|
// single-flight. Reject overlap loudly instead of letting concurrent calls
|
|
689
693
|
// corrupt each other's runtime and channel tracking.
|
|
@@ -855,6 +859,8 @@ export function sessionManager(parameters) {
|
|
|
855
859
|
});
|
|
856
860
|
},
|
|
857
861
|
async sse(input, init) {
|
|
862
|
+
if (init?.[Fetch.skipPayment])
|
|
863
|
+
throw new Error('SessionManager.sse requires payment; use fetch for unpaid streams.');
|
|
858
864
|
return openSseSession(input, init, sseDriver);
|
|
859
865
|
},
|
|
860
866
|
async ws(input, init) {
|
|
@@ -92,11 +92,10 @@ export function assertOpenCredentialCoversRequest(parameters) {
|
|
|
92
92
|
/** Verifies that the credential source is authorized to spend from the channel. */
|
|
93
93
|
export function assertCredentialSourceCanSpend(parameters) {
|
|
94
94
|
const sourceAddress = readCredentialSourceAddress(parameters.source, parameters.chainId);
|
|
95
|
-
if (isAddressEqual(sourceAddress, parameters.channel.payer)
|
|
96
|
-
isAddressEqual(sourceAddress, parameters.channel.authorizedSigner))
|
|
95
|
+
if (isAddressEqual(sourceAddress, parameters.channel.payer))
|
|
97
96
|
return;
|
|
98
97
|
throw new VerificationFailedError({
|
|
99
|
-
reason: 'credential source does not match channel payer
|
|
98
|
+
reason: 'credential source does not match channel payer',
|
|
100
99
|
});
|
|
101
100
|
}
|
|
102
101
|
/** Binds an opening payment to the payer authenticated by its signed transaction. */
|
package/dist/viem/Client.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export declare function remoteFeePayerTransport(config: RemoteFeePayer.Config, o
|
|
|
6
6
|
retryCount?: number | undefined;
|
|
7
7
|
}): import("viem").HttpTransport<undefined, false>;
|
|
8
8
|
export declare function getResolver(parameters: getResolver.Parameters & {
|
|
9
|
+
/** Require custom clients to declare the requested chain before applying defaults. */
|
|
10
|
+
requireChain?: boolean | undefined;
|
|
9
11
|
/** Default chain to use if not provided. */
|
|
10
12
|
chain?: Chain | undefined;
|
|
11
13
|
/** Remote fee-payer configuration. When set, the transport is wrapped with `withFeePayer`. */
|
package/dist/viem/Client.js
CHANGED
|
@@ -21,10 +21,13 @@ export function getResolver(parameters) {
|
|
|
21
21
|
// ensure user-provided clients inherit those serializers. Without this, clients
|
|
22
22
|
// created without the Tempo chain config will use the default viem serializer,
|
|
23
23
|
// causing errors like "maxFeePerGas is not a valid Legacy Transaction attribute".
|
|
24
|
-
if (!chain?.serializers && !remoteFeePayer)
|
|
24
|
+
if (!chain?.serializers && !remoteFeePayer && !parameters.requireChain)
|
|
25
25
|
return getClient;
|
|
26
26
|
return async (params) => {
|
|
27
27
|
const client = await getClient(params);
|
|
28
|
+
if (parameters.requireChain &&
|
|
29
|
+
(client.chain?.id === undefined || client.chain.id !== params.chainId))
|
|
30
|
+
throw new Error(`Subscription chain mismatch: expected ${params.chainId}, got ${client.chain?.id ?? 'unknown'}.`);
|
|
28
31
|
let resolvedClient = client;
|
|
29
32
|
// Wrap the client's transport with `withFeePayer` when a fee payer URL is provided.
|
|
30
33
|
if (remoteFeePayer && client.transport.key !== 'feePayer') {
|
package/dist/x402/Assets.d.ts
CHANGED
|
@@ -61,6 +61,12 @@ export declare const celo: {
|
|
|
61
61
|
export declare const celoSepolia: {
|
|
62
62
|
readonly USDC: KnownAsset;
|
|
63
63
|
};
|
|
64
|
+
/**
|
|
65
|
+
* Returns the known asset mppx ships for `address` on `network` (such as `base.USDC`), compared
|
|
66
|
+
* case-insensitively. Clients use it for trusted decimals when no currency allowlist names the
|
|
67
|
+
* asset.
|
|
68
|
+
*/
|
|
69
|
+
export declare function lookup(address: string, network: EvmNetwork): KnownAsset | undefined;
|
|
64
70
|
/** Returns true when a value is known x402 asset metadata. */
|
|
65
71
|
export declare function isAsset(value: unknown): value is KnownAsset;
|
|
66
72
|
/** Returns true when a value is a `viem/tokens` token definition. */
|
package/dist/x402/Assets.js
CHANGED
|
@@ -88,6 +88,16 @@ export const celoSepolia = {
|
|
|
88
88
|
},
|
|
89
89
|
}),
|
|
90
90
|
};
|
|
91
|
+
const knownAssets = [base, baseSepolia, celo, celoSepolia].flatMap((assets) => Object.values(assets));
|
|
92
|
+
/**
|
|
93
|
+
* Returns the known asset mppx ships for `address` on `network` (such as `base.USDC`), compared
|
|
94
|
+
* case-insensitively. Clients use it for trusted decimals when no currency allowlist names the
|
|
95
|
+
* asset.
|
|
96
|
+
*/
|
|
97
|
+
export function lookup(address, network) {
|
|
98
|
+
const normalized = address.toLowerCase();
|
|
99
|
+
return knownAssets.find((asset) => asset.network === network && asset.address.toLowerCase() === normalized);
|
|
100
|
+
}
|
|
91
101
|
/** Returns true when a value is known x402 asset metadata. */
|
|
92
102
|
export function isAsset(value) {
|
|
93
103
|
if (typeof value !== 'object' || value === null)
|
package/dist/x402/Types.d.ts
CHANGED
|
@@ -252,10 +252,7 @@ export declare const PaymentPayloadSchema: z.ZodMiniObject<{
|
|
|
252
252
|
export type PaymentPayload = z.infer<typeof PaymentPayloadSchema>;
|
|
253
253
|
/** Facilitator verification response. */
|
|
254
254
|
export declare const VerifyResponseSchema: z.ZodMiniObject<{
|
|
255
|
-
extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.
|
|
256
|
-
info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
257
|
-
schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
258
|
-
}, z.core.$loose>>>;
|
|
255
|
+
extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
|
|
259
256
|
extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
|
|
260
257
|
invalidMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
261
258
|
invalidReason: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
@@ -269,10 +266,7 @@ export declare const SettleResponseSchema: z.ZodMiniObject<{
|
|
|
269
266
|
amount: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
270
267
|
errorMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
271
268
|
errorReason: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
272
|
-
extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.
|
|
273
|
-
info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
274
|
-
schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
275
|
-
}, z.core.$loose>>>;
|
|
269
|
+
extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
|
|
276
270
|
extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
|
|
277
271
|
network: z.ZodMiniString<string>;
|
|
278
272
|
payer: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
@@ -281,10 +275,76 @@ export declare const SettleResponseSchema: z.ZodMiniObject<{
|
|
|
281
275
|
}, z.core.$strip>;
|
|
282
276
|
/** Facilitator settlement response and x402 `PAYMENT-RESPONSE` body. */
|
|
283
277
|
export type SettleResponse = z.infer<typeof SettleResponseSchema>;
|
|
278
|
+
/** One payment kind a facilitator supports, from `GET /supported`. */
|
|
279
|
+
export declare const SupportedKindSchema: z.ZodMiniObject<{
|
|
280
|
+
extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
|
|
281
|
+
network: z.ZodMiniString<string>;
|
|
282
|
+
scheme: z.ZodMiniString<string>;
|
|
283
|
+
x402Version: z.ZodMiniNumber<number>;
|
|
284
|
+
}, z.core.$strip>;
|
|
285
|
+
/** One payment kind a facilitator supports, from `GET /supported`. */
|
|
286
|
+
export type SupportedKind = z.infer<typeof SupportedKindSchema>;
|
|
287
|
+
/** Facilitator `GET /supported` response. */
|
|
288
|
+
export declare const SupportedResponseSchema: z.ZodMiniObject<{
|
|
289
|
+
extensions: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniString<string>>>;
|
|
290
|
+
kinds: z.ZodMiniArray<z.ZodMiniObject<{
|
|
291
|
+
extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
|
|
292
|
+
network: z.ZodMiniString<string>;
|
|
293
|
+
scheme: z.ZodMiniString<string>;
|
|
294
|
+
x402Version: z.ZodMiniNumber<number>;
|
|
295
|
+
}, z.core.$strip>>;
|
|
296
|
+
signers: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniArray<z.ZodMiniString<string>>>>;
|
|
297
|
+
}, z.core.$strip>;
|
|
298
|
+
/** Facilitator `GET /supported` response. */
|
|
299
|
+
export type SupportedResponse = z.infer<typeof SupportedResponseSchema>;
|
|
284
300
|
/** x402 facilitator client interface used by server exact config. */
|
|
285
301
|
export type Facilitator = {
|
|
286
302
|
settle: (paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements) => Promise<SettleResponse>;
|
|
287
303
|
verify: (paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements) => Promise<VerifyResponse>;
|
|
304
|
+
/**
|
|
305
|
+
* Lists the payment kinds the facilitator supports (`GET /supported`). Optional: needed only to
|
|
306
|
+
* read a `payTo` the facilitator publishes in `kinds[].extra.payTo`.
|
|
307
|
+
*/
|
|
308
|
+
supported?: (() => Promise<SupportedResponse>) | undefined;
|
|
309
|
+
};
|
|
310
|
+
/**
|
|
311
|
+
* Headers an HTTP facilitator client sends with each request, keyed by facilitator path, the
|
|
312
|
+
* shape `createAuthHeaders` returns in `@x402/core`'s `FacilitatorConfig`. A path left out
|
|
313
|
+
* sends no extra headers.
|
|
314
|
+
*/
|
|
315
|
+
export type FacilitatorPathHeaders = {
|
|
316
|
+
settle?: Record<string, string> | undefined;
|
|
317
|
+
supported?: Record<string, string> | undefined;
|
|
318
|
+
verify?: Record<string, string> | undefined;
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* Headers an HTTP facilitator client sends: either a flat record sent on every request, or a
|
|
322
|
+
* {@link FacilitatorPathHeaders} object keyed by path. A value counts as per-path only when it has
|
|
323
|
+
* at least one key, every key is `verify`, `settle` or `supported`, and every value is an object;
|
|
324
|
+
* anything else is a flat record.
|
|
325
|
+
*/
|
|
326
|
+
export type FacilitatorHeaders = Record<string, string> | FacilitatorPathHeaders;
|
|
327
|
+
/**
|
|
328
|
+
* An HTTP facilitator that needs authentication, in the shape `@x402/core`'s
|
|
329
|
+
* `HTTPFacilitatorClient` takes, so one config works with both SDKs.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* ```ts
|
|
333
|
+
* const facilitator = {
|
|
334
|
+
* url: 'https://facilitator.example',
|
|
335
|
+
* headers: async () => ({ Authorization: `Bearer ${process.env.FACILITATOR_API_KEY}` }),
|
|
336
|
+
* }
|
|
337
|
+
* ```
|
|
338
|
+
*/
|
|
339
|
+
export type FacilitatorConfig = {
|
|
340
|
+
/** Base URL of the facilitator. */
|
|
341
|
+
url: string;
|
|
342
|
+
/**
|
|
343
|
+
* Headers to send, such as an API key: a flat record for every request, or an object keyed by
|
|
344
|
+
* `verify`, `settle` and `supported` (the shape `createAuthHeaders` returns in `@x402/core`). A
|
|
345
|
+
* function is called before every request, so it can refresh short-lived tokens.
|
|
346
|
+
*/
|
|
347
|
+
headers?: FacilitatorHeaders | (() => FacilitatorHeaders | Promise<FacilitatorHeaders>) | undefined;
|
|
288
348
|
};
|
|
289
349
|
/** Extracts x402 `PaymentRequirements` from a canonical exact request. */
|
|
290
350
|
export declare function toPaymentRequirements(request: ExactRequest): PaymentRequirements;
|
package/dist/x402/Types.js
CHANGED
|
@@ -114,7 +114,8 @@ export const PaymentPayloadSchema = z.object({
|
|
|
114
114
|
});
|
|
115
115
|
/** Facilitator verification response. */
|
|
116
116
|
export const VerifyResponseSchema = z.object({
|
|
117
|
-
|
|
117
|
+
// Response extension data is shaped by each extension, unlike PAYMENT-REQUIRED's { info, schema }.
|
|
118
|
+
extensions: z.optional(z.record(z.string(), z.unknown())),
|
|
118
119
|
extra: z.optional(z.record(z.string(), z.unknown())),
|
|
119
120
|
invalidMessage: z.optional(z.string()),
|
|
120
121
|
invalidReason: z.optional(z.string()),
|
|
@@ -126,13 +127,27 @@ export const SettleResponseSchema = z.object({
|
|
|
126
127
|
amount: z.optional(atomicAmount),
|
|
127
128
|
errorMessage: z.optional(z.string()),
|
|
128
129
|
errorReason: z.optional(z.string()),
|
|
129
|
-
|
|
130
|
+
// Response extension data is shaped by each extension, unlike PAYMENT-REQUIRED's { info, schema }.
|
|
131
|
+
extensions: z.optional(z.record(z.string(), z.unknown())),
|
|
130
132
|
extra: z.optional(z.record(z.string(), z.unknown())),
|
|
131
133
|
network: nonEmptyString,
|
|
132
134
|
payer: z.optional(z.string()),
|
|
133
135
|
success: z.boolean(),
|
|
134
136
|
transaction: z.string(),
|
|
135
137
|
});
|
|
138
|
+
/** One payment kind a facilitator supports, from `GET /supported`. */
|
|
139
|
+
export const SupportedKindSchema = z.object({
|
|
140
|
+
extra: z.optional(z.record(z.string(), z.unknown())),
|
|
141
|
+
network: nonEmptyString,
|
|
142
|
+
scheme: nonEmptyString,
|
|
143
|
+
x402Version: z.number(),
|
|
144
|
+
});
|
|
145
|
+
/** Facilitator `GET /supported` response. */
|
|
146
|
+
export const SupportedResponseSchema = z.object({
|
|
147
|
+
extensions: z.optional(z.array(z.string())),
|
|
148
|
+
kinds: z.array(SupportedKindSchema),
|
|
149
|
+
signers: z.optional(z.record(z.string(), z.array(z.string()))),
|
|
150
|
+
});
|
|
136
151
|
/** Extracts x402 `PaymentRequirements` from a canonical exact request. */
|
|
137
152
|
export function toPaymentRequirements(request) {
|
|
138
153
|
const { extensions: _extensions, resource: _resource, ...paymentRequirements } = request;
|
|
@@ -131,7 +131,10 @@ function decimalsOfAcceptedCurrency(parameters, accepted) {
|
|
|
131
131
|
const resolved = currency ? Assets.resolve(currency, accepted.network) : undefined;
|
|
132
132
|
if (resolved?.decimals !== undefined)
|
|
133
133
|
return resolved.decimals;
|
|
134
|
-
|
|
134
|
+
if (parameters.decimals !== undefined)
|
|
135
|
+
return parameters.decimals;
|
|
136
|
+
// Never the challenge's own metadata: a server could inflate decimals to raise the cap.
|
|
137
|
+
return Assets.lookup(acceptedCurrency, accepted.network)?.decimals;
|
|
135
138
|
}
|
|
136
139
|
function withNonceSalt(extensions) {
|
|
137
140
|
const mppx = extensions.mppx;
|
|
@@ -21,7 +21,16 @@ export function mpp(routes, server, config) {
|
|
|
21
21
|
const mpp = Negotiator.create({ ...config, routes, server });
|
|
22
22
|
const x402 = paymentMiddlewareFromHTTPServer(mpp.httpServer, config.paywallConfig, undefined, false);
|
|
23
23
|
return async (req, res, next) => {
|
|
24
|
-
|
|
24
|
+
let request;
|
|
25
|
+
try {
|
|
26
|
+
request = ExpressAdapter_.toRequest(req);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (!(error instanceof ExpressAdapter_.InvalidRequestTargetError))
|
|
30
|
+
return next(error);
|
|
31
|
+
res.status(400).send('Bad Request');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
25
34
|
const paymentHeader = Negotiator.getX402Credential(request);
|
|
26
35
|
const context = {
|
|
27
36
|
adapter: new ExpressAdapter(req),
|
|
@@ -4,8 +4,23 @@ import * as ServerTransport from '../../server/Transport.js';
|
|
|
4
4
|
import * as Siwx from '../Siwx.js';
|
|
5
5
|
import * as x402_Types from '../Types.js';
|
|
6
6
|
export type Options = {
|
|
7
|
-
/**
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Extra fields added to every x402 payment requirement's `extra`, for facilitators that read
|
|
9
|
+
* their own keys there. They can't override `assetTransferMethod`, `name` or `version`.
|
|
10
|
+
*/
|
|
11
|
+
extra?: Record<string, unknown> | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Headers to send with each request to a URL `facilitator`, such as an API key: a flat record,
|
|
14
|
+
* or an object keyed by `verify`, `settle` and `supported`; a function is called before every
|
|
15
|
+
* request. A `{ url, headers }` facilitator's own `headers` win.
|
|
16
|
+
*/
|
|
17
|
+
headers?: x402_Types.FacilitatorConfig['headers'];
|
|
18
|
+
/**
|
|
19
|
+
* Facilitator used for x402-compatible settlement: a base URL, a `{ url, headers }`
|
|
20
|
+
* config (the shape `@x402/core`'s `HTTPFacilitatorClient` takes) for one that needs
|
|
21
|
+
* authentication, or a client.
|
|
22
|
+
*/
|
|
23
|
+
facilitator?: string | x402_Types.FacilitatorConfig | x402_Types.Facilitator | undefined;
|
|
9
24
|
/** Fetch implementation used for facilitator RPCs. */
|
|
10
25
|
fetch?: typeof globalThis.fetch | undefined;
|
|
11
26
|
/** Maximum time in seconds allowed for x402-compatible payment completion. @default 300 */
|
|
@@ -39,6 +54,7 @@ export type Options = {
|
|
|
39
54
|
export type RouteBindingMode = 'required' | 'resource';
|
|
40
55
|
export type ResolvedOptions = {
|
|
41
56
|
authorization: Types.AuthorizationConfig;
|
|
57
|
+
extra?: Record<string, unknown> | undefined;
|
|
42
58
|
facilitator?: x402_Types.Facilitator | undefined;
|
|
43
59
|
maxTimeoutSeconds: number;
|
|
44
60
|
routeBinding: RouteBindingMode;
|
|
@@ -69,6 +85,7 @@ export type SettleWithFacilitator = (parameters: {
|
|
|
69
85
|
request: Types.ChargeRequest;
|
|
70
86
|
source: ReturnType<typeof Types.toSource>;
|
|
71
87
|
}) => Promise<{
|
|
88
|
+
extensions?: Record<string, unknown> | undefined;
|
|
72
89
|
reference: string;
|
|
73
90
|
timestamp?: string | undefined;
|
|
74
91
|
}>;
|
|
@@ -77,7 +94,7 @@ export declare function isCredential(credential: Credential.Credential): boolean
|
|
|
77
94
|
/** Returns whether a credential was parsed from the x402 payment header. */
|
|
78
95
|
export declare function isPendingCredential(credential: Credential.Credential): boolean;
|
|
79
96
|
/** Converts a native EVM charge request to x402 exact payment requirements. */
|
|
80
|
-
export declare function toPaymentRequirements(request: Types.ChargeRequest, config: Pick<ResolvedOptions, 'authorization' | 'maxTimeoutSeconds'>): x402_Types.PaymentRequirements;
|
|
97
|
+
export declare function toPaymentRequirements(request: Types.ChargeRequest, config: Pick<ResolvedOptions, 'authorization' | 'extra' | 'maxTimeoutSeconds'>): x402_Types.PaymentRequirements;
|
|
81
98
|
/** Converts an x402 EIP-3009 payment payload to the native EVM authorization payload. */
|
|
82
99
|
export declare function payloadToAuthorization(paymentPayload: x402_Types.PaymentPayload): Types.AuthorizationPayload;
|
|
83
100
|
//# sourceMappingURL=EvmCharge.d.ts.map
|
|
@@ -33,9 +33,18 @@ const mppxRouteBindingSchema = {
|
|
|
33
33
|
export function resolveOptions(parameters) {
|
|
34
34
|
return {
|
|
35
35
|
authorization: parameters.authorization,
|
|
36
|
+
...(parameters.options?.extra
|
|
37
|
+
? {
|
|
38
|
+
// Normalize to the JSON the challenge carries, so credentials echoing it match exactly.
|
|
39
|
+
extra: JSON.parse(JSON.stringify(parameters.options.extra)),
|
|
40
|
+
}
|
|
41
|
+
: {}),
|
|
36
42
|
...(parameters.options?.facilitator
|
|
37
43
|
? {
|
|
38
|
-
facilitator: x402_Facilitator.resolve(parameters.options.facilitator, 'EVM authorization x402 requires `facilitator`.', {
|
|
44
|
+
facilitator: x402_Facilitator.resolve(parameters.options.facilitator, 'EVM authorization x402 requires `facilitator`.', {
|
|
45
|
+
headers: parameters.options.headers,
|
|
46
|
+
fetch: parameters.options.fetch,
|
|
47
|
+
}),
|
|
39
48
|
}
|
|
40
49
|
: {}),
|
|
41
50
|
maxTimeoutSeconds: parameters.options?.maxTimeoutSeconds ?? 300,
|
|
@@ -191,6 +200,7 @@ export function createPath(config) {
|
|
|
191
200
|
payer: payload.from,
|
|
192
201
|
success: true,
|
|
193
202
|
transaction: options.receipt.reference,
|
|
203
|
+
...(options.receipt.extensions ? { extensions: options.receipt.extensions } : {}),
|
|
194
204
|
}));
|
|
195
205
|
return new Response(response.body, {
|
|
196
206
|
headers,
|
|
@@ -213,6 +223,7 @@ export function settleWithFacilitator(parameters) {
|
|
|
213
223
|
reason: settled.errorMessage ?? settled.errorReason ?? 'EVM facilitator settlement failed',
|
|
214
224
|
});
|
|
215
225
|
return {
|
|
226
|
+
...(settled.extensions ? { extensions: settled.extensions } : {}),
|
|
216
227
|
reference: settled.transaction,
|
|
217
228
|
};
|
|
218
229
|
};
|
|
@@ -262,6 +273,7 @@ export function toPaymentRequirements(request, config) {
|
|
|
262
273
|
amount: request.amount,
|
|
263
274
|
asset: request.currency,
|
|
264
275
|
extra: {
|
|
276
|
+
...config.extra,
|
|
265
277
|
assetTransferMethod: Types.eip3009,
|
|
266
278
|
name: config.authorization.name,
|
|
267
279
|
version: config.authorization.version,
|
|
@@ -1,12 +1,51 @@
|
|
|
1
1
|
import * as Types from '../Types.js';
|
|
2
|
+
/** Headers to send with facilitator requests: a flat record, or one keyed by path. */
|
|
3
|
+
export type FacilitatorHeaders = Types.FacilitatorHeaders;
|
|
2
4
|
export type HttpOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Headers to send with facilitator requests, such as an API key: a flat record for every
|
|
7
|
+
* request, or an object keyed by `verify`, `settle` and `supported`. A function is called before
|
|
8
|
+
* every request.
|
|
9
|
+
*/
|
|
10
|
+
headers?: Types.FacilitatorConfig['headers'];
|
|
3
11
|
/** Fetch implementation used for facilitator RPCs. */
|
|
4
12
|
fetch?: typeof globalThis.fetch | undefined;
|
|
5
13
|
};
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Resolves an x402 facilitator URL, `{ url, headers }` config or client into a
|
|
16
|
+
* facilitator client. A config's `headers` take precedence over `options`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolve(facilitator: string | Types.FacilitatorConfig | Types.Facilitator, errorMessage?: string, options?: HttpOptions | undefined): Types.Facilitator;
|
|
19
|
+
/**
|
|
20
|
+
* Creates an x402 facilitator client from an HTTP base URL.
|
|
21
|
+
*
|
|
22
|
+
* A non-2xx response throws `Errors.FacilitatorResponseError`, except a `/verify` or `/settle`
|
|
23
|
+
* error whose body is a failed result (`isValid: false` or `success: false`), which is returned
|
|
24
|
+
* as that result, the way `@x402/core` reads it.
|
|
25
|
+
*/
|
|
9
26
|
export declare function http(url: string, options?: HttpOptions | undefined): Types.Facilitator;
|
|
27
|
+
/**
|
|
28
|
+
* Reads the `payTo` a facilitator publishes for a scheme and network in `GET /supported`
|
|
29
|
+
* (`kinds[].extra.payTo`), for facilitators that settle into an address of their own, the way
|
|
30
|
+
* Solana facilitators publish `extra.feePayer`. Call it once at startup and pass the result as
|
|
31
|
+
* `recipient`. Accepts the same facilitator forms as `x402.facilitator`.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* evm({
|
|
36
|
+
* currency: evm.assets.base.USDC,
|
|
37
|
+
* recipient: await x402.Facilitator.payTo(FACILITATOR_URL, { network: 'eip155:8453' }),
|
|
38
|
+
* x402: { facilitator: FACILITATOR_URL, extra: { tempoSettlement: '0x…' } },
|
|
39
|
+
* })
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function payTo(facilitator: string | Types.FacilitatorConfig | Types.Facilitator, parameters: {
|
|
43
|
+
/** Headers to send with `GET /supported` when `facilitator` is a URL. */
|
|
44
|
+
headers?: HttpOptions['headers'];
|
|
45
|
+
fetch?: typeof globalThis.fetch | undefined;
|
|
46
|
+
network: string;
|
|
47
|
+
scheme?: string | undefined;
|
|
48
|
+
}): Promise<`0x${string}`>;
|
|
10
49
|
/** Returns the underlying raw fetch implementation when given an mppx wrapper. */
|
|
11
50
|
export declare function unwrapFetch(fetch: typeof globalThis.fetch): typeof globalThis.fetch;
|
|
12
51
|
//# sourceMappingURL=Facilitator.d.ts.map
|