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
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Cli, Errors, z } from 'incur';
|
|
2
2
|
import { createClient, http } from 'viem';
|
|
3
3
|
import { tempo as tempoMainnet, tempoModerato } from 'viem/tempo/chains';
|
|
4
|
+
import * as Challenge from '../../Challenge.js';
|
|
4
5
|
import { normalizeHeaders } from '../../client/internal/Fetch.js';
|
|
5
6
|
import { canSignDescriptor } from '../../tempo/session/client/CredentialState.js';
|
|
6
7
|
import * as Chain from '../../tempo/session/precompile/Chain.js';
|
|
@@ -257,6 +258,14 @@ const sessions = Cli.create('sessions', {
|
|
|
257
258
|
message: `Session ${channelId} was not found.`,
|
|
258
259
|
exitCode: 2,
|
|
259
260
|
});
|
|
261
|
+
// A session stored by an earlier version may hold a challenge that selects another
|
|
262
|
+
// credential header. It still lists, but no credential is sent in that header.
|
|
263
|
+
if (Challenge.hasUnsupportedCredentialHeader(record.challenge))
|
|
264
|
+
throw new Errors.IncurError({
|
|
265
|
+
code: 'SESSION_STATE_INVALID',
|
|
266
|
+
message: 'Stored session challenge selects a credential header other than Payment-Authorization.',
|
|
267
|
+
exitCode: 65,
|
|
268
|
+
});
|
|
260
269
|
const resolvedAccount = await resolveCloseAccount(record, options.account);
|
|
261
270
|
const client = await resolveCloseClient(record.channel.chainId, options);
|
|
262
271
|
const expectedId = Channel.computeId({
|
|
@@ -75,7 +75,8 @@ const storedSessionSchema = z.object({
|
|
|
75
75
|
channel: storedChannelSchema,
|
|
76
76
|
account: accountSchema,
|
|
77
77
|
endpoint: z.string(),
|
|
78
|
-
|
|
78
|
+
// Sessions stored before `header` was limited to Payment-Authorization must still load.
|
|
79
|
+
challenge: Challenge.LenientSchema,
|
|
79
80
|
receipt: z.optional(receiptSchema),
|
|
80
81
|
spent: z.string(),
|
|
81
82
|
units: z.number(),
|
|
@@ -458,7 +459,7 @@ function sanitizeStoredChannel(value, file) {
|
|
|
458
459
|
return parseStored(storedChannelSchema, value, file, 'Stored session channel is invalid.');
|
|
459
460
|
}
|
|
460
461
|
function parseSessionChallenge(value, file) {
|
|
461
|
-
const parsed = Challenge.
|
|
462
|
+
const parsed = Challenge.LenientSchema.safeParse(value);
|
|
462
463
|
if (!parsed.success || !isTempoSessionChallenge(parsed.data))
|
|
463
464
|
throw stateError(file, 'Stored session challenge is invalid.');
|
|
464
465
|
return parsed.data;
|
|
@@ -117,11 +117,25 @@ export async function validateChallenge(baseUrl, endpoint, verbose, options) {
|
|
|
117
117
|
return { results };
|
|
118
118
|
}
|
|
119
119
|
if (challenges.length === 0) {
|
|
120
|
-
|
|
120
|
+
// List parsing skips challenges it may not pay (such as an unsupported credential header);
|
|
121
|
+
// report why the first one was skipped.
|
|
122
|
+
let reason = 'No Payment challenges found in header';
|
|
123
|
+
try {
|
|
124
|
+
Challenge.fromResponse(response);
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
reason = error.message;
|
|
128
|
+
}
|
|
129
|
+
results.push(fail('Challenge parseable', reason));
|
|
121
130
|
return { results };
|
|
122
131
|
}
|
|
123
132
|
const methodList = challenges.map((c) => `${c.method}/${c.intent}`).join(', ');
|
|
124
133
|
results.push(check('Challenge parseable', challenges.length === 1 ? methodList : `${challenges.length} methods: ${methodList}`));
|
|
134
|
+
// List parsing skips a challenge that selects another credential header; report it even when
|
|
135
|
+
// another challenge is usable.
|
|
136
|
+
const skipped = Challenge.countUnsupportedCredentialHeaders(wwwAuth);
|
|
137
|
+
if (skipped > 0)
|
|
138
|
+
results.push(fail('Challenge credential header', `${skipped} of ${challenges.length + skipped} challenges select a credential header other than Payment-Authorization`, 'A challenge may only set header="Payment-Authorization"; omit header to use Authorization.'));
|
|
125
139
|
// Validate common fields across all challenges
|
|
126
140
|
const serverHost = new URL(baseUrl).hostname;
|
|
127
141
|
validateIds(challenges, results);
|
package/dist/client/Mppx.d.ts
CHANGED
package/dist/client/Mppx.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import * as Challenge from '../Challenge.js';
|
|
1
2
|
import * as Constants from '../Constants.js';
|
|
2
3
|
import * as Expires from '../Expires.js';
|
|
3
4
|
import * as IdentityClient from '../identity/Client.js';
|
|
@@ -93,7 +94,7 @@ export function create(config) {
|
|
|
93
94
|
const orderedCandidates = await resolveChallengeOrder(candidates, options?.orderChallenges ?? orderChallenges);
|
|
94
95
|
const selected = orderedCandidates[0];
|
|
95
96
|
if (!selected)
|
|
96
|
-
throw new Error(`No method found for challenges: ${challenges.map((challenge) => `${challenge.method}.${challenge.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}
|
|
97
|
+
throw new Error(Challenge.withSkippedChallenges(`No method found for challenges: ${challenges.map((challenge) => `${challenge.method}.${challenge.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`, Fetch.skippedChallengeCount(response)));
|
|
97
98
|
// Signing must use what the caller inspects, while attachment needs the adapter's original
|
|
98
99
|
// object identity to retain protocol provenance.
|
|
99
100
|
const transportChallenge = selected.challenge;
|
|
@@ -190,10 +190,11 @@ export declare function identityOf(fetch: typeof globalThis.fetch): IdentityClie
|
|
|
190
190
|
export declare function unwrapFetch(fetch: typeof globalThis.fetch): typeof globalThis.fetch;
|
|
191
191
|
/** @internal */
|
|
192
192
|
export declare function resolveRequestSignal(input: RequestInfo | URL, init: RequestInit | undefined): AbortSignal | undefined;
|
|
193
|
-
/** @internal */
|
|
194
193
|
export declare function validateCredentialHeaderValue(credential: string): void;
|
|
195
194
|
/** @internal */
|
|
196
195
|
/** @internal */
|
|
197
196
|
export declare function shouldInjectForPolicy(input: RequestInfo | URL, policy: NonNullable<from.Config['acceptPaymentPolicy']>): boolean;
|
|
197
|
+
/** Counts the challenges in a 402's `WWW-Authenticate` header that list parsing skipped. */
|
|
198
|
+
export declare function skippedChallengeCount(response: unknown): number;
|
|
198
199
|
export {};
|
|
199
200
|
//# sourceMappingURL=Fetch.d.ts.map
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as Challenge from '../../Challenge.js';
|
|
2
2
|
import * as Constants from '../../Constants.js';
|
|
3
|
+
import * as Credential from '../../Credential.js';
|
|
3
4
|
import { PaymentOutcomeUnknownError } from '../../Errors.js';
|
|
4
5
|
import * as Expires from '../../Expires.js';
|
|
5
6
|
import * as IdentityClient from '../../identity/Client.js';
|
|
@@ -7,6 +8,7 @@ import * as AcceptPayment from '../../internal/AcceptPayment.js';
|
|
|
7
8
|
import * as Transport from '../Transport.js';
|
|
8
9
|
import * as MethodChallenge from './MethodChallenge.js';
|
|
9
10
|
import * as MethodResponse from './MethodResponse.js';
|
|
11
|
+
import * as PendingSettlement from './PendingSettlement.js';
|
|
10
12
|
import * as ProofRealm from './ProofRealm.js';
|
|
11
13
|
import { adapterOwnsPayment } from './protocols/Mcp.js';
|
|
12
14
|
// We tag wrappers with a global symbol so we can recognize wrappers created by mppx,
|
|
@@ -125,7 +127,9 @@ export function from(config) {
|
|
|
125
127
|
// which can duplicate retries and make restore semantics fragile.
|
|
126
128
|
const baseFetch = unwrapFetch(fetch);
|
|
127
129
|
const send = async (input, init, context) => identity
|
|
128
|
-
? identity.send(
|
|
130
|
+
? identity.send((request, nextInit) => baseFetch(request, init?.[skipPayment]
|
|
131
|
+
? withoutPayment(nextInit)
|
|
132
|
+
: nextInit), new Request(input, init), context)
|
|
129
133
|
: { response: await baseFetch(input, init), headers: [] };
|
|
130
134
|
const request = async (input, init, canRefetch) => {
|
|
131
135
|
const callerHeaders = getCallerHeaders(input, init?.headers);
|
|
@@ -170,7 +174,7 @@ export function from(config) {
|
|
|
170
174
|
// is the server's final answer, not a new challenge round.
|
|
171
175
|
if (retry > 0)
|
|
172
176
|
return response;
|
|
173
|
-
throw new Error(`No method found for challenges: ${challenges.map((c) => `${c.method}.${c.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}
|
|
177
|
+
throw new Error(Challenge.withSkippedChallenges(`No method found for challenges: ${challenges.map((c) => `${c.method}.${c.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`, skippedChallengeCount(response)));
|
|
174
178
|
}
|
|
175
179
|
const selectedChallenge = selected.challenge;
|
|
176
180
|
challenge = selectedChallenge;
|
|
@@ -205,7 +209,8 @@ export function from(config) {
|
|
|
205
209
|
resolveRequestSignal(input, init)?.throwIfAborted();
|
|
206
210
|
const credentialContext = overrideContext ?? context;
|
|
207
211
|
if (!MethodChallenge.has(selected.method))
|
|
208
|
-
|
|
212
|
+
// A Zone withdrawal still settling is resumed for this challenge, not paid again.
|
|
213
|
+
return PendingSettlement.resume(() => resolveCredential(selectedChallenge, selected.method, credentialContext, requestOrigin(paymentInput)), { attempts: maxPaymentRetries, signal: resolveRequestSignal(input, init) });
|
|
209
214
|
const attempt = {
|
|
210
215
|
origin: resolveRequestUrl(paymentInput).origin,
|
|
211
216
|
prepare: () => MethodChallenge.handle(selected.method, {
|
|
@@ -256,6 +261,9 @@ export function from(config) {
|
|
|
256
261
|
}
|
|
257
262
|
const effectiveContext = preparedCredential ? preparedCredential.context : context;
|
|
258
263
|
validateCredentialHeaderValue(credential);
|
|
264
|
+
// Identity proofs bind to the Challenge the credential pays, which can be an earlier one
|
|
265
|
+
// (a resumed Zone withdrawal) rather than the one just selected.
|
|
266
|
+
const paidChallenge = credentialChallenge(credential, selectedChallenge);
|
|
259
267
|
await events.emit('credential.created', createCredentialCreatedPayload({
|
|
260
268
|
challenge: selectedChallenge,
|
|
261
269
|
credential,
|
|
@@ -279,7 +287,7 @@ export function from(config) {
|
|
|
279
287
|
}, credential, { challenge: selectedChallenge }),
|
|
280
288
|
// Runtimes do not strip custom payment headers on cross-origin redirects.
|
|
281
289
|
redirect: 'manual',
|
|
282
|
-
}, { challenge:
|
|
290
|
+
}, { challenge: paidChallenge, headers: identityHeaders }));
|
|
283
291
|
}
|
|
284
292
|
catch (cause) {
|
|
285
293
|
outcomeUnknown = unknownOutcome(cause);
|
|
@@ -760,6 +768,21 @@ function isWrappedFetch(fetch) {
|
|
|
760
768
|
return Boolean(fetch[MPPX_FETCH_WRAPPER]);
|
|
761
769
|
}
|
|
762
770
|
/** @internal */
|
|
771
|
+
/**
|
|
772
|
+
* Returns the Challenge a serialized credential pays: the selected one, or the earlier
|
|
773
|
+
* Challenge a method resumed a payment for (keeping the selected one's credential header).
|
|
774
|
+
*/
|
|
775
|
+
function credentialChallenge(credential, selected) {
|
|
776
|
+
try {
|
|
777
|
+
const { challenge } = Credential.deserialize(credential);
|
|
778
|
+
if (challenge.id === selected.id)
|
|
779
|
+
return selected;
|
|
780
|
+
return { ...challenge, ...(selected.header !== undefined && { header: selected.header }) };
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
return selected;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
763
786
|
export function validateCredentialHeaderValue(credential) {
|
|
764
787
|
if (!credential.trim())
|
|
765
788
|
throw new Error('Credential header value must be non-empty');
|
|
@@ -773,7 +796,7 @@ async function resolveCredential(challenge, mi, context, attempt) {
|
|
|
773
796
|
const parameters = parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge };
|
|
774
797
|
if (attempt?.origin)
|
|
775
798
|
MethodResponse.attachOrigin(parameters, attempt.origin);
|
|
776
|
-
if (attempt)
|
|
799
|
+
if (attempt && 'prepare' in attempt)
|
|
777
800
|
MethodResponse.attachAttempt(mi, parameters, attempt);
|
|
778
801
|
return mi.createCredential(parameters);
|
|
779
802
|
}
|
|
@@ -833,6 +856,15 @@ function resolveRequestUrl(input) {
|
|
|
833
856
|
return new URL(input.url);
|
|
834
857
|
return new URL(input, isBrowser() ? globalThis.location.href : undefined);
|
|
835
858
|
}
|
|
859
|
+
/** The request's origin, or `undefined` for a relative URL outside a browser. */
|
|
860
|
+
function requestOrigin(input) {
|
|
861
|
+
try {
|
|
862
|
+
return { origin: resolveRequestUrl(input).origin };
|
|
863
|
+
}
|
|
864
|
+
catch {
|
|
865
|
+
return undefined;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
836
868
|
/** Rejects Request modes whose paid retry cannot carry a credential to the server. */
|
|
837
869
|
function assertPayableRequest(input, init) {
|
|
838
870
|
const request = input instanceof Request ? input : undefined;
|
|
@@ -893,4 +925,10 @@ async function resolvePaymentRetryInput(response, fallback, initialInput, init)
|
|
|
893
925
|
}
|
|
894
926
|
return response.url;
|
|
895
927
|
}
|
|
928
|
+
/** Counts the challenges in a 402's `WWW-Authenticate` header that list parsing skipped. */
|
|
929
|
+
export function skippedChallengeCount(response) {
|
|
930
|
+
if (!(response instanceof Response) || response.status !== 402)
|
|
931
|
+
return 0;
|
|
932
|
+
return Challenge.countUnsupportedCredentialHeaders(response.headers.get(Constants.Headers.wwwAuthenticate));
|
|
933
|
+
}
|
|
896
934
|
//# sourceMappingURL=Fetch.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a credential and, while the Zone withdrawal that pays its challenge is still
|
|
3
|
+
* settling, creates it again for the same challenge, up to `attempts` times in all. Each
|
|
4
|
+
* attempt resumes waiting for that withdrawal; requesting a new challenge instead would not
|
|
5
|
+
* settle it sooner.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resume(create: () => Promise<string>, options: {
|
|
8
|
+
attempts: number;
|
|
9
|
+
signal?: AbortSignal | undefined;
|
|
10
|
+
}): Promise<string>;
|
|
11
|
+
//# sourceMappingURL=PendingSettlement.d.ts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ZoneSettlementPendingError } from '../../Errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a credential and, while the Zone withdrawal that pays its challenge is still
|
|
4
|
+
* settling, creates it again for the same challenge, up to `attempts` times in all. Each
|
|
5
|
+
* attempt resumes waiting for that withdrawal; requesting a new challenge instead would not
|
|
6
|
+
* settle it sooner.
|
|
7
|
+
*/
|
|
8
|
+
export async function resume(create, options) {
|
|
9
|
+
const { attempts, signal } = options;
|
|
10
|
+
for (let attempt = 1;; attempt++) {
|
|
11
|
+
signal?.throwIfAborted();
|
|
12
|
+
try {
|
|
13
|
+
return await create();
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (!(error instanceof ZoneSettlementPendingError) || attempt >= attempts)
|
|
17
|
+
throw error;
|
|
18
|
+
signal?.throwIfAborted();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=PendingSettlement.js.map
|
|
@@ -78,11 +78,19 @@ function paymentRequiredDataFromValue(data) {
|
|
|
78
78
|
return undefined;
|
|
79
79
|
const parsed = [];
|
|
80
80
|
for (const challenge of challenges) {
|
|
81
|
+
if (!Challenge.LenientSchema.safeParse(challenge).success)
|
|
82
|
+
return undefined;
|
|
83
|
+
// A well-formed challenge that selects an unsupported credential header gets no credential, but
|
|
84
|
+
// must not stop the client from paying another challenge.
|
|
85
|
+
if (Challenge.hasUnsupportedCredentialHeader(challenge))
|
|
86
|
+
continue;
|
|
81
87
|
const result = Challenge.Schema.safeParse(challenge);
|
|
82
88
|
if (!result.success)
|
|
83
89
|
return undefined;
|
|
84
90
|
parsed.push(result.data);
|
|
85
91
|
}
|
|
92
|
+
if (parsed.length === 0)
|
|
93
|
+
return undefined;
|
|
86
94
|
const { httpStatus, problem } = data;
|
|
87
95
|
return {
|
|
88
96
|
challenges: parsed,
|
|
@@ -128,6 +128,9 @@ function resolveAuthorization(parameters, request) {
|
|
|
128
128
|
};
|
|
129
129
|
if (parameters.authorization)
|
|
130
130
|
return parameters.authorization;
|
|
131
|
+
const known = Assets.lookup(acceptedCurrency, network)?.transfer;
|
|
132
|
+
if (known?.type === Types.eip3009)
|
|
133
|
+
return { name: known.name, version: known.version };
|
|
131
134
|
throw new Error('EVM authorization requires token name and version.');
|
|
132
135
|
}
|
|
133
136
|
function decimalsOfAcceptedCurrency(parameters, request) {
|
|
@@ -138,6 +141,9 @@ function decimalsOfAcceptedCurrency(parameters, request) {
|
|
|
138
141
|
const resolved = currency ? Assets.resolve(currency, network) : undefined;
|
|
139
142
|
if (resolved?.decimals !== undefined)
|
|
140
143
|
return resolved.decimals;
|
|
141
|
-
|
|
144
|
+
if (parameters.decimals !== undefined)
|
|
145
|
+
return parameters.decimals;
|
|
146
|
+
// Never `methodDetails.decimals`: a server could inflate decimals to raise the cap.
|
|
147
|
+
return Assets.lookup(acceptedCurrency, network)?.decimals;
|
|
142
148
|
}
|
|
143
149
|
//# sourceMappingURL=Charge.js.map
|
|
@@ -53,6 +53,11 @@ export declare namespace charge {
|
|
|
53
53
|
request: Types.ChargeRequest;
|
|
54
54
|
source: ReturnType<typeof Types.toSource>;
|
|
55
55
|
}) => Promise<{
|
|
56
|
+
/**
|
|
57
|
+
* Settlement data to pass through on the Receipt and the x402 `PAYMENT-RESPONSE`, such as
|
|
58
|
+
* an x402 facilitator's `SettleResponse.extensions`.
|
|
59
|
+
*/
|
|
60
|
+
extensions?: Record<string, unknown> | undefined;
|
|
56
61
|
reference: string;
|
|
57
62
|
timestamp?: string | undefined;
|
|
58
63
|
}>;
|
|
@@ -104,7 +104,9 @@ export function charge(parameters) {
|
|
|
104
104
|
chainId: request.methodDetails.chainId,
|
|
105
105
|
}),
|
|
106
106
|
});
|
|
107
|
+
const extensions = toJsonExtensions(settled.extensions);
|
|
107
108
|
return Receipt.from({
|
|
109
|
+
...(extensions ? { extensions } : {}),
|
|
108
110
|
method: Types.paymentMethod,
|
|
109
111
|
reference: settled.reference,
|
|
110
112
|
status: 'success',
|
|
@@ -315,4 +317,46 @@ function assertAddressEqual(actual, expected, reason) {
|
|
|
315
317
|
return;
|
|
316
318
|
throw new VerificationFailedError({ reason });
|
|
317
319
|
}
|
|
320
|
+
/** Largest serialized settle extensions a receipt carries; larger ones are dropped. */
|
|
321
|
+
const maxExtensionsBytes = 4096;
|
|
322
|
+
/** Deepest nesting settle extensions may have; deeper ones are dropped. */
|
|
323
|
+
const maxExtensionsDepth = 8;
|
|
324
|
+
/**
|
|
325
|
+
* Normalizes settler extensions to the JSON the receipt header carries. A value that isn't a
|
|
326
|
+
* plain JSON object, nests deeper than 8 levels or serializes past 4 KiB is dropped, so a settled
|
|
327
|
+
* payment never fails on its receipt or overflows a client's header limit.
|
|
328
|
+
*/
|
|
329
|
+
function toJsonExtensions(extensions) {
|
|
330
|
+
if (!extensions || typeof extensions !== 'object' || Array.isArray(extensions))
|
|
331
|
+
return undefined;
|
|
332
|
+
if (!withinDepth(extensions, maxExtensionsDepth))
|
|
333
|
+
return undefined;
|
|
334
|
+
try {
|
|
335
|
+
const serialized = JSON.stringify(extensions);
|
|
336
|
+
if (new TextEncoder().encode(serialized).byteLength > maxExtensionsBytes)
|
|
337
|
+
return undefined;
|
|
338
|
+
const json = JSON.parse(serialized);
|
|
339
|
+
if (!json || typeof json !== 'object' || Array.isArray(json))
|
|
340
|
+
return undefined;
|
|
341
|
+
return Object.keys(json).length ? json : undefined;
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** Checks nesting without recursion, so hostile depth can't overflow the stack. */
|
|
348
|
+
function withinDepth(value, limit) {
|
|
349
|
+
const stack = [[value, 1]];
|
|
350
|
+
let visited = 0;
|
|
351
|
+
while (stack.length) {
|
|
352
|
+
const [node, depth] = stack.pop();
|
|
353
|
+
if (!node || typeof node !== 'object')
|
|
354
|
+
continue;
|
|
355
|
+
if (depth > limit || ++visited > 10_000)
|
|
356
|
+
return false;
|
|
357
|
+
for (const child of Object.values(node))
|
|
358
|
+
stack.push([child, depth + 1]);
|
|
359
|
+
}
|
|
360
|
+
return true;
|
|
361
|
+
}
|
|
318
362
|
//# sourceMappingURL=Charge.js.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { NoExtraKeys } from '../../internal/types.js';
|
|
2
|
+
import * as Facilitator from '../../x402/server/Facilitator.js';
|
|
2
3
|
import * as Assets from '../Assets.js';
|
|
3
4
|
import * as Chains from '../Chains.js';
|
|
4
5
|
import { charge as charge_ } from './Charge.js';
|
|
@@ -237,5 +238,12 @@ export declare namespace evm {
|
|
|
237
238
|
const assets: typeof Assets;
|
|
238
239
|
/** Common EVM chain IDs for public config. */
|
|
239
240
|
const chains: typeof Chains;
|
|
241
|
+
/**
|
|
242
|
+
* Reads the `payTo` an x402 facilitator publishes in `GET /supported` (`kinds[].extra.payTo`),
|
|
243
|
+
* for facilitators that settle into an address of their own. Use it once at startup as `recipient`.
|
|
244
|
+
* Takes a URL, a `{ url, headers }` config or a client; pass `headers` in
|
|
245
|
+
* the parameters to authenticate a URL facilitator.
|
|
246
|
+
*/
|
|
247
|
+
const facilitatorPayTo: typeof Facilitator.payTo;
|
|
240
248
|
}
|
|
241
249
|
//# sourceMappingURL=Methods.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as Currency from '../../Currency.js';
|
|
2
|
+
import * as Facilitator from '../../x402/server/Facilitator.js';
|
|
2
3
|
import * as Assets from '../Assets.js';
|
|
3
4
|
import * as Chains from '../Chains.js';
|
|
4
5
|
import { charge as charge_ } from './Charge.js';
|
|
@@ -61,5 +62,12 @@ export function evm(parameters) {
|
|
|
61
62
|
evm.assets = Assets;
|
|
62
63
|
/** Common EVM chain IDs for public config. */
|
|
63
64
|
evm.chains = Chains;
|
|
65
|
+
/**
|
|
66
|
+
* Reads the `payTo` an x402 facilitator publishes in `GET /supported` (`kinds[].extra.payTo`),
|
|
67
|
+
* for facilitators that settle into an address of their own. Use it once at startup as `recipient`.
|
|
68
|
+
* Takes a URL, a `{ url, headers }` config or a client; pass `headers` in
|
|
69
|
+
* the parameters to authenticate a URL facilitator.
|
|
70
|
+
*/
|
|
71
|
+
evm.facilitatorPayTo = Facilitator.payTo;
|
|
64
72
|
})(evm || (evm = {}));
|
|
65
73
|
//# sourceMappingURL=Methods.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { unwrapFetch } from '../../../client/internal/Fetch.js';
|
|
1
|
+
import { unwrapFetch, withoutPayment } from '../../../client/internal/Fetch.js';
|
|
2
2
|
import { Constants } from './Constants.js';
|
|
3
3
|
/**
|
|
4
4
|
* Creates a key resolver that reads an issuer's JSON Web Key Set.
|
|
@@ -24,12 +24,12 @@ export function resolver(options = {}) {
|
|
|
24
24
|
function load(issuer) {
|
|
25
25
|
const startedAt = Date.now();
|
|
26
26
|
const keys = (async () => {
|
|
27
|
-
const response = await fetch(`${issuer.replace(/\/+$/, '')}${Constants.jwksPath}`, {
|
|
27
|
+
const response = await fetch(`${issuer.replace(/\/+$/, '')}${Constants.jwksPath}`, withoutPayment({
|
|
28
28
|
headers: { accept: 'application/json' },
|
|
29
29
|
signal: AbortSignal.timeout(timeout),
|
|
30
30
|
// Workers reject 'error'; a redirect is not ok, so it fails below.
|
|
31
31
|
redirect: 'manual',
|
|
32
|
-
});
|
|
32
|
+
}));
|
|
33
33
|
if (!response.ok)
|
|
34
34
|
throw new Error(`JWKS request failed with ${response.status}.`);
|
|
35
35
|
const body = (await response.json());
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Base64, Bytes } from 'ox';
|
|
2
|
-
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
2
|
+
import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
|
|
3
3
|
import { Constants } from '../Constants.js';
|
|
4
4
|
/**
|
|
5
5
|
* Creates a request-stage verifier that requires a Link Agent Attestation Token: proof that
|
|
@@ -414,7 +414,7 @@ export function presentationVerifier(config) {
|
|
|
414
414
|
const maxAge = config.maxAge ?? Constants.nonceTtl;
|
|
415
415
|
const base = unwrapFetch((config.fetch ?? globalThis.fetch));
|
|
416
416
|
// The SDK refuses redirects with `redirect: 'error'`, which Workers reject: a 3xx is a failure either way.
|
|
417
|
-
const fetch = (input, init) => base(input, init.redirect === 'error' ? { ...init, redirect: 'manual' } : init);
|
|
417
|
+
const fetch = (input, init) => base(input, withoutPayment(init.redirect === 'error' ? { ...init, redirect: 'manual' } : init));
|
|
418
418
|
const getMetadata = metadata({ fetch, issuer, maxAge: 3_600_000, timeout });
|
|
419
419
|
return {
|
|
420
420
|
async verifyClaims(presentation, options) {
|
|
@@ -482,11 +482,11 @@ function equal(a, b) {
|
|
|
482
482
|
async function getJson(url, options) {
|
|
483
483
|
if (new URL(url).origin !== options.origin)
|
|
484
484
|
throw new Error(`${url} is not on ${options.origin}.`);
|
|
485
|
-
const response = await options.fetch(url, {
|
|
485
|
+
const response = await options.fetch(url, withoutPayment({
|
|
486
486
|
headers: { accept: 'application/json' },
|
|
487
487
|
redirect: 'manual',
|
|
488
488
|
signal: AbortSignal.timeout(options.timeout),
|
|
489
|
-
});
|
|
489
|
+
}));
|
|
490
490
|
if (!response.ok)
|
|
491
491
|
throw new Error(`${url} answered ${response.status}.`);
|
|
492
492
|
const body = (await response.json());
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { verifyMessage } from 'viem';
|
|
2
|
-
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
2
|
+
import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
|
|
3
3
|
import { Constants } from '../Constants.js';
|
|
4
4
|
import * as Did from '../Did.js';
|
|
5
5
|
/**
|
|
@@ -45,7 +45,7 @@ export function create(config) {
|
|
|
45
45
|
// Unwrapped, and resolved per call: a Persona request must never pay a Payment Challenge,
|
|
46
46
|
// even when an mppx client polyfilled globalThis.fetch.
|
|
47
47
|
const fetch = unwrapFetch(config.fetch ?? globalThis.fetch);
|
|
48
|
-
const response = await fetch(new URL(path, apiUrl), {
|
|
48
|
+
const response = await fetch(new URL(path, apiUrl), withoutPayment({
|
|
49
49
|
...init,
|
|
50
50
|
// A redirect is a failure: never send the bearer key on, nor read another origin's body.
|
|
51
51
|
redirect: 'manual',
|
|
@@ -56,7 +56,7 @@ export function create(config) {
|
|
|
56
56
|
...(init.body !== undefined && { 'Content-Type': 'application/json' }),
|
|
57
57
|
},
|
|
58
58
|
signal: AbortSignal.timeout(timeout),
|
|
59
|
-
});
|
|
59
|
+
}));
|
|
60
60
|
// Never surface the upstream body: it may carry request details.
|
|
61
61
|
if (!response.ok)
|
|
62
62
|
throw new PersonaError(`The Persona API returned ${response.status}.`);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type * as Credential from '../Credential.js';
|
|
2
|
+
/**
|
|
3
|
+
* Lets a server method keep accepting some credentials for a bounded time after their
|
|
4
|
+
* challenge expires: for a payment that the method can prove completed before then, but
|
|
5
|
+
* whose credential only arrived later. The method enforces that proof itself.
|
|
6
|
+
*/
|
|
7
|
+
export type GraceFn = (credential: Credential.Credential) => number | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Registers `grace` on a server method without changing its public shape. Only challenges
|
|
10
|
+
* issued while `issue` is true carry the marker that grace requires, so a challenge issued
|
|
11
|
+
* without it (by an earlier release, or with no grace configured) never gets any.
|
|
12
|
+
*/
|
|
13
|
+
export declare function register<const method extends object>(method: method, grace: GraceFn, options: {
|
|
14
|
+
issue: boolean;
|
|
15
|
+
}): method;
|
|
16
|
+
/** Challenge metadata for a challenge `method` issues: with the expiry grace marker or without it. */
|
|
17
|
+
export declare function issuanceMeta(method: object | undefined, meta: Record<string, string> | undefined): Record<string, string> | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Milliseconds after its challenge's expiry that `method` still accepts `credential`, if any.
|
|
20
|
+
* None for a challenge issued without the expiry grace marker.
|
|
21
|
+
*/
|
|
22
|
+
export declare function getGraceMs(method: object | undefined, credential: Credential.Credential): number | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Asserts that the credential's challenge has a well-formed `expires` that has not passed, or
|
|
25
|
+
* that passed less than `graceMs` ago.
|
|
26
|
+
*/
|
|
27
|
+
export declare function assert(credential: Credential.Credential, graceMs: number | undefined): void;
|
|
28
|
+
/** Asserts the credential has not expired, allowing the grace `method` registered for it. */
|
|
29
|
+
export declare function assertFor(method: object | undefined, credential: Credential.Credential): void;
|
|
30
|
+
//# sourceMappingURL=CredentialExpiry.d.ts.map
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { PaymentExpiredError } from '../Errors.js';
|
|
2
|
+
import * as Expires from '../Expires.js';
|
|
3
|
+
import * as ChallengeMeta from '../server/internal/challengeMeta.js';
|
|
4
|
+
// A symbol-keyed property survives the spreads that copy and configure methods.
|
|
5
|
+
const graceKey = Symbol.for('mppx.credentialExpiryGrace');
|
|
6
|
+
/**
|
|
7
|
+
* Registers `grace` on a server method without changing its public shape. Only challenges
|
|
8
|
+
* issued while `issue` is true carry the marker that grace requires, so a challenge issued
|
|
9
|
+
* without it (by an earlier release, or with no grace configured) never gets any.
|
|
10
|
+
*/
|
|
11
|
+
export function register(method, grace, options) {
|
|
12
|
+
const registration = { grace, issue: options.issue };
|
|
13
|
+
return Object.assign(method, { [graceKey]: registration });
|
|
14
|
+
}
|
|
15
|
+
function getRegistration(method) {
|
|
16
|
+
return method?.[graceKey];
|
|
17
|
+
}
|
|
18
|
+
/** Challenge metadata for a challenge `method` issues: with the expiry grace marker or without it. */
|
|
19
|
+
export function issuanceMeta(method, meta) {
|
|
20
|
+
return ChallengeMeta.withExpiryGrace(meta, getRegistration(method)?.issue === true);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Milliseconds after its challenge's expiry that `method` still accepts `credential`, if any.
|
|
24
|
+
* None for a challenge issued without the expiry grace marker.
|
|
25
|
+
*/
|
|
26
|
+
export function getGraceMs(method, credential) {
|
|
27
|
+
if (!ChallengeMeta.hasExpiryGrace(credential.challenge))
|
|
28
|
+
return undefined;
|
|
29
|
+
return getRegistration(method)?.grace(credential);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Asserts that the credential's challenge has a well-formed `expires` that has not passed, or
|
|
33
|
+
* that passed less than `graceMs` ago.
|
|
34
|
+
*/
|
|
35
|
+
export function assert(credential, graceMs) {
|
|
36
|
+
const { expires, id } = credential.challenge;
|
|
37
|
+
try {
|
|
38
|
+
Expires.assert(expires, id);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (!(error instanceof PaymentExpiredError))
|
|
42
|
+
throw error;
|
|
43
|
+
if (!graceMs || Date.parse(expires) + graceMs <= Date.now())
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Asserts the credential has not expired, allowing the grace `method` registered for it. */
|
|
48
|
+
export function assertFor(method, credential) {
|
|
49
|
+
assert(credential, getGraceMs(method, credential));
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=CredentialExpiry.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Current mppx package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.21.0";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.21.0";
|
|
5
5
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/internal/version.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated by scripts/sync-version.ts.
|
|
2
2
|
/** Current mppx package version. */
|
|
3
|
-
export const version = '0.
|
|
3
|
+
export const version = '0.21.0';
|
|
4
4
|
/** Canonical SDK identifier for this mppx release. */
|
|
5
5
|
export const sdkIdentifier = `mppx/${version}`;
|
|
6
6
|
//# sourceMappingURL=version.js.map
|