mppx 0.21.4 → 0.22.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 +20 -0
- package/dist/BodyDigest.d.ts +3 -3
- package/dist/BodyDigest.js +5 -3
- package/dist/Challenge.js +12 -2
- package/dist/Credential.js +9 -1
- package/dist/Errors.d.ts +62 -8
- package/dist/Errors.js +57 -6
- package/dist/Store.d.ts +7 -4
- package/dist/Store.js +18 -8
- package/dist/cli/cli.js +135 -135
- package/dist/cli/internal.js +1 -1
- package/dist/cli/plugins/index.js +12 -12
- package/dist/client/Budget.d.ts +49 -0
- package/dist/client/Budget.js +101 -0
- package/dist/client/Mppx.d.ts +8 -3
- package/dist/client/Mppx.js +55 -13
- package/dist/client/Spend.d.ts +134 -0
- package/dist/client/Spend.js +58 -0
- package/dist/client/core.d.ts +2 -0
- package/dist/client/core.js +2 -0
- package/dist/client/internal/Fetch.d.ts +23 -3
- package/dist/client/internal/Fetch.js +155 -37
- package/dist/client/internal/FundsMoved.d.ts +9 -0
- package/dist/client/internal/FundsMoved.js +18 -0
- package/dist/client/internal/SpendGate.d.ts +136 -0
- package/dist/client/internal/SpendGate.js +608 -0
- package/dist/client/internal/SpendHooks.d.ts +42 -0
- package/dist/client/internal/SpendHooks.js +36 -0
- package/dist/client/internal/protocols/Mcp.d.ts +9 -0
- package/dist/client/internal/protocols/Mcp.js +27 -0
- package/dist/client/internal/protocols/Mpp.js +20 -3
- package/dist/client/internal/protocols/Shared.js +29 -3
- package/dist/evm/client/Charge.js +20 -8
- package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
- package/dist/extensions/identity/erc8004/server/index.js +13 -1
- package/dist/extensions/identity/link/client/index.js +57 -5
- package/dist/identity/Client.d.ts +7 -3
- package/dist/identity/Client.js +178 -13
- package/dist/identity/Types.d.ts +2 -1
- package/dist/integrations/x402/Negotiator.js +4 -1
- package/dist/integrations/x402/Solana.d.ts +75 -0
- package/dist/integrations/x402/Solana.js +143 -0
- package/dist/internal/challengeMeta.d.ts +17 -2
- package/dist/internal/challengeMeta.js +35 -7
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.d.ts +6 -1
- package/dist/mcp/client/McpClient.js +48 -10
- package/dist/server/Mppx.d.ts +12 -1
- package/dist/server/Mppx.js +58 -6
- package/dist/server/Transport.js +46 -2
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/client/Charge.js +81 -17
- package/dist/tempo/server/Charge.d.ts +7 -1
- package/dist/tempo/server/Charge.js +98 -12
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/client/SessionManager.js +3 -0
- package/dist/x402/server/EvmCharge.js +3 -0
- package/package.json +1 -1
|
@@ -4,6 +4,8 @@ import type { Protocol } from './Protocol.js';
|
|
|
4
4
|
export declare const adapterPaymentMetaKey = "mppx/payment-client";
|
|
5
5
|
/** Whether the caller's MCP adapter owns approval and payment retry for this request. */
|
|
6
6
|
export declare function adapterOwnsPayment(request?: RequestInit): boolean;
|
|
7
|
+
/** Whether an MCP request already carries a Payment credential in its `_meta`. */
|
|
8
|
+
export declare function hasCredential(request?: RequestInit): boolean;
|
|
7
9
|
type CorePaymentRequiredData = NonNullable<Mcp.ErrorObject['data']>;
|
|
8
10
|
export type PaymentRequiredData = Pick<CorePaymentRequiredData, 'challenges'> & Partial<Pick<CorePaymentRequiredData, 'httpStatus' | 'problem'>>;
|
|
9
11
|
/** Extracts validated payment-required data from MCP errors or tool result metadata. */
|
|
@@ -13,5 +15,12 @@ export declare function paymentRequiredData(message: Mcp.Response | undefined):
|
|
|
13
15
|
* in a normal 200 body (often `text/event-stream`), and the credential rides back in `_meta`.
|
|
14
16
|
*/
|
|
15
17
|
export declare function mcp(): Protocol;
|
|
18
|
+
/**
|
|
19
|
+
* Whether an MCP-over-HTTP response answers the request with a payment-required error whose
|
|
20
|
+
* problem is `invalid-challenge` (a replayed or otherwise unusable Challenge).
|
|
21
|
+
*/
|
|
22
|
+
export declare function isInvalidChallenge(response: Response, request?: RequestInit): Promise<boolean>;
|
|
23
|
+
/** Problem type of an unusable (replayed, expired or unknown) Challenge. */
|
|
24
|
+
export declare const invalidChallengeType = "https://paymentauth.org/problems/invalid-challenge";
|
|
16
25
|
export {};
|
|
17
26
|
//# sourceMappingURL=Mcp.d.ts.map
|
|
@@ -34,6 +34,18 @@ export function adapterOwnsPayment(request) {
|
|
|
34
34
|
return false;
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
+
/** Whether an MCP request already carries a Payment credential in its `_meta`. */
|
|
38
|
+
export function hasCredential(request) {
|
|
39
|
+
if (typeof request?.body !== 'string')
|
|
40
|
+
return false;
|
|
41
|
+
try {
|
|
42
|
+
const message = JSON.parse(request.body);
|
|
43
|
+
return message?.jsonrpc === '2.0' && message.params?._meta?.[Mcp.credentialMetaKey] != null;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
37
49
|
// Bound automatic inspection; the caller retains the original response stream.
|
|
38
50
|
const maxInspectionBytes = 1024 * 1024;
|
|
39
51
|
const responseCache = new WeakMap();
|
|
@@ -227,4 +239,19 @@ export function mcp() {
|
|
|
227
239
|
},
|
|
228
240
|
};
|
|
229
241
|
}
|
|
242
|
+
/**
|
|
243
|
+
* Whether an MCP-over-HTTP response answers the request with a payment-required error whose
|
|
244
|
+
* problem is `invalid-challenge` (a replayed or otherwise unusable Challenge).
|
|
245
|
+
*/
|
|
246
|
+
export async function isInvalidChallenge(response, request) {
|
|
247
|
+
const id = mcpHttpRequestId(request);
|
|
248
|
+
if (response.status === paymentRequiredStatus || id === undefined)
|
|
249
|
+
return false;
|
|
250
|
+
const message = await parseJsonRpcResponse(response);
|
|
251
|
+
if (!message || message.id !== id)
|
|
252
|
+
return false;
|
|
253
|
+
return paymentRequiredData(message)?.problem?.type === invalidChallengeType;
|
|
254
|
+
}
|
|
255
|
+
/** Problem type of an unusable (replayed, expired or unknown) Challenge. */
|
|
256
|
+
export const invalidChallengeType = 'https://paymentauth.org/problems/invalid-challenge';
|
|
230
257
|
//# sourceMappingURL=Mcp.js.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 { paymentRequiredStatus, setCredentialHeader } from './Shared.js';
|
|
4
5
|
/** MPP — native HTTP Payment authentication. */
|
|
5
6
|
export function mpp() {
|
|
@@ -14,10 +15,26 @@ export function mpp() {
|
|
|
14
15
|
return Challenge.fromResponseList(response);
|
|
15
16
|
},
|
|
16
17
|
setCredential(request, credential, options) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
// A Payment credential echoes its challenge, so callers that attach one without passing the
|
|
19
|
+
// challenge still send it in the field that challenge selects (`Payment-Authorization`).
|
|
20
|
+
const challenge = options?.challenge ?? credentialChallenge(credential);
|
|
21
|
+
return setCredentialHeader(request, challenge ? Challenge.credentialHeader(challenge) : Constants.Headers.authorization, credential);
|
|
20
22
|
},
|
|
21
23
|
};
|
|
22
24
|
}
|
|
25
|
+
/** `Payment <base64url>`, as `Credential.serialize` writes it. */
|
|
26
|
+
const serializedCredential = /^Payment [A-Za-z0-9_-]+={0,2}$/;
|
|
27
|
+
/** Returns the challenge a serialized Payment credential echoes, or `undefined` for any other value. */
|
|
28
|
+
function credentialChallenge(credential) {
|
|
29
|
+
// Parse only values shaped like a serialized credential, checked in linear time, so arbitrary
|
|
30
|
+
// strings never reach the deserializer's regex.
|
|
31
|
+
if (!serializedCredential.test(credential))
|
|
32
|
+
return undefined;
|
|
33
|
+
try {
|
|
34
|
+
return Credential.deserialize(credential).challenge;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
23
40
|
//# sourceMappingURL=Mpp.js.map
|
|
@@ -5,6 +5,7 @@ export const paymentRequiredStatus = 402;
|
|
|
5
5
|
/** Credential headers purged before a fresh credential is attached. */
|
|
6
6
|
const credentialHeaders = [
|
|
7
7
|
Constants.Headers.authorization,
|
|
8
|
+
Constants.Headers.paymentAuthorization,
|
|
8
9
|
x402_Types.paymentRequiredHeader,
|
|
9
10
|
x402_Types.paymentResponseHeader,
|
|
10
11
|
x402_Types.paymentSignatureHeader,
|
|
@@ -13,12 +14,37 @@ const credentialHeaders = [
|
|
|
13
14
|
export function setCredentialHeader(request, header, credential) {
|
|
14
15
|
const headers = new Headers(request.headers);
|
|
15
16
|
for (const stale of credentialHeaders) {
|
|
16
|
-
|
|
17
|
-
if (
|
|
17
|
+
const value = headers.get(stale);
|
|
18
|
+
if (value === null)
|
|
18
19
|
continue;
|
|
19
|
-
|
|
20
|
+
if (!isPaymentField(stale)) {
|
|
21
|
+
headers.delete(stale);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
// Never erase ordinary application credentials: drop only the Payment members, so a retry
|
|
25
|
+
// never carries a stale credential in the field the new challenge did not select.
|
|
26
|
+
const kept = withoutPaymentMembers(value);
|
|
27
|
+
if (kept === value)
|
|
28
|
+
continue;
|
|
29
|
+
if (kept)
|
|
30
|
+
headers.set(stale, kept);
|
|
31
|
+
else
|
|
32
|
+
headers.delete(stale);
|
|
20
33
|
}
|
|
21
34
|
headers.set(header, credential);
|
|
22
35
|
return { ...request, headers };
|
|
23
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Removes the Payment members from a credential field, matched as servers match them
|
|
39
|
+
* (comma-separated, scheme case-insensitive). Returns `value` itself when it holds none.
|
|
40
|
+
*/
|
|
41
|
+
function withoutPaymentMembers(value) {
|
|
42
|
+
const members = value.split(',').map((member) => member.trim());
|
|
43
|
+
const kept = members.filter((member) => !paymentMember.test(member));
|
|
44
|
+
return kept.length === members.length ? value : kept.filter(Boolean).join(', ');
|
|
45
|
+
}
|
|
46
|
+
const paymentMember = new RegExp(`^${Constants.Schemes.payment}(?:\\s|$)`, 'i');
|
|
47
|
+
function isPaymentField(header) {
|
|
48
|
+
return (header === Constants.Headers.authorization || header === Constants.Headers.paymentAuthorization);
|
|
49
|
+
}
|
|
24
50
|
//# sourceMappingURL=Shared.js.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getAddress, parseUnits } from 'viem';
|
|
2
|
+
import * as SpendHooks from '../../client/internal/SpendHooks.js';
|
|
2
3
|
import * as Credential from '../../Credential.js';
|
|
3
4
|
import * as x402_ChallengeBrand from '../../internal/x402/ChallengeBrand.js';
|
|
4
5
|
import * as Method from '../../Method.js';
|
|
@@ -14,7 +15,7 @@ import * as Types from '../Types.js';
|
|
|
14
15
|
* also keeps x402 exact signing for x402 compatibility challenges.
|
|
15
16
|
*/
|
|
16
17
|
export function charge(parameters) {
|
|
17
|
-
|
|
18
|
+
const method = Method.toClient(Methods.charge, {
|
|
18
19
|
canHandleChallenge({ challenge }) {
|
|
19
20
|
if (!isX402Challenge(challenge))
|
|
20
21
|
return true;
|
|
@@ -37,13 +38,7 @@ export function charge(parameters) {
|
|
|
37
38
|
if (!account?.signTypedData)
|
|
38
39
|
throw new Error('EVM authorization requires a typed-data signer.');
|
|
39
40
|
const request = challenge.request;
|
|
40
|
-
|
|
41
|
-
if (!request.methodDetails.credentialTypes?.includes('authorization')) {
|
|
42
|
-
throw new Error('EVM authorization is not accepted by this challenge.');
|
|
43
|
-
}
|
|
44
|
-
if (request.methodDetails.splits?.length) {
|
|
45
|
-
throw new Error('EVM authorization does not support payment splits.');
|
|
46
|
-
}
|
|
41
|
+
assertOffer(parameters, request);
|
|
47
42
|
const authorization = resolveAuthorization(parameters, request);
|
|
48
43
|
const validBefore = challenge.expires
|
|
49
44
|
? Math.floor(new Date(challenge.expires).getTime() / 1000).toString()
|
|
@@ -84,12 +79,29 @@ export function charge(parameters) {
|
|
|
84
79
|
}));
|
|
85
80
|
},
|
|
86
81
|
});
|
|
82
|
+
// The client's spending options refuse what this method refuses before any funder runs.
|
|
83
|
+
return SpendHooks.register(method, {
|
|
84
|
+
assert(challenge) {
|
|
85
|
+
if (!isX402Challenge(challenge))
|
|
86
|
+
assertOffer(parameters, challenge.request);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
87
89
|
}
|
|
88
90
|
function isX402Challenge(challenge) {
|
|
89
91
|
return (x402_ChallengeBrand.is(challenge) &&
|
|
90
92
|
challenge.request.scheme === 'exact' &&
|
|
91
93
|
typeof challenge.request.network === 'string');
|
|
92
94
|
}
|
|
95
|
+
/** Throws for a native offer this client would refuse to sign: its policy, or what it cannot pay. */
|
|
96
|
+
function assertOffer(parameters, request) {
|
|
97
|
+
assertPolicy(parameters, request);
|
|
98
|
+
if (!request.methodDetails.credentialTypes?.includes('authorization')) {
|
|
99
|
+
throw new Error('EVM authorization is not accepted by this challenge.');
|
|
100
|
+
}
|
|
101
|
+
if (request.methodDetails.splits?.length) {
|
|
102
|
+
throw new Error('EVM authorization does not support payment splits.');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
93
105
|
function assertPolicy(parameters, request) {
|
|
94
106
|
const chainId = request.methodDetails.chainId;
|
|
95
107
|
const network = Types.networkOf(chainId);
|
|
@@ -13,7 +13,7 @@ import type * as Types from '../Types.js';
|
|
|
13
13
|
*
|
|
14
14
|
* @example
|
|
15
15
|
* ```ts
|
|
16
|
-
* const agents = Erc8004.Server.create({ store })
|
|
16
|
+
* const agents = Erc8004.Server.create({ origin: 'https://api.example', store })
|
|
17
17
|
* mppx.charge({ amount: '0.01', identity: { request: [agents.verifier], payment: agents.paymentCheck } })
|
|
18
18
|
* ```
|
|
19
19
|
*/
|
|
@@ -26,6 +26,12 @@ export declare namespace create {
|
|
|
26
26
|
readonly chainId?: number | undefined;
|
|
27
27
|
/** A viem client for the registry's chain. @default an HTTP client for `rpcUrl` */
|
|
28
28
|
readonly client?: Client | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Trusted receiving origin, independent of request headers (for example, `https://api.example`).
|
|
31
|
+
* Configure this when an adapter derives URLs from Host. Without it, trusted ingress must
|
|
32
|
+
* reject foreign hosts to prevent signed requests for another service from being accepted.
|
|
33
|
+
*/
|
|
34
|
+
readonly origin?: string | undefined;
|
|
29
35
|
/** The Identity Registry. @default '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432' */
|
|
30
36
|
readonly registry?: Address | undefined;
|
|
31
37
|
/** RPC URL of the registry's chain. @default 'https://rpc.tempo.xyz' */
|
|
@@ -33,11 +33,21 @@ const abi = [
|
|
|
33
33
|
*
|
|
34
34
|
* @example
|
|
35
35
|
* ```ts
|
|
36
|
-
* const agents = Erc8004.Server.create({ store })
|
|
36
|
+
* const agents = Erc8004.Server.create({ origin: 'https://api.example', store })
|
|
37
37
|
* mppx.charge({ amount: '0.01', identity: { request: [agents.verifier], payment: agents.paymentCheck } })
|
|
38
38
|
* ```
|
|
39
39
|
*/
|
|
40
40
|
export function create(config = {}) {
|
|
41
|
+
const origin = config.origin === undefined ? undefined : new URL(config.origin);
|
|
42
|
+
if (origin &&
|
|
43
|
+
(!['http:', 'https:'].includes(origin.protocol) ||
|
|
44
|
+
origin.username ||
|
|
45
|
+
origin.password ||
|
|
46
|
+
origin.pathname !== '/' ||
|
|
47
|
+
origin.search ||
|
|
48
|
+
origin.hash))
|
|
49
|
+
throw new TypeError('Pass an HTTP(S) origin without credentials, path, query, or fragment.');
|
|
50
|
+
const expectedOrigin = origin?.origin;
|
|
41
51
|
const chainId = config.chainId ?? Constants.chainId;
|
|
42
52
|
const registry = getAddress(config.registry ?? Constants.identityRegistry);
|
|
43
53
|
if (!config.client && !config.rpcUrl && chainId !== Constants.chainId)
|
|
@@ -50,6 +60,8 @@ export function create(config = {}) {
|
|
|
50
60
|
const invalid = (reason) => ({ status: 'invalid', reason });
|
|
51
61
|
/** Reads the request's agent and its wallet from the registry. */
|
|
52
62
|
async function lookup(request) {
|
|
63
|
+
if (expectedOrigin !== undefined && new URL(request.url).origin !== expectedOrigin)
|
|
64
|
+
return invalid('The request origin does not match this API.');
|
|
53
65
|
const id = request.headers.get(Constants.idHeader);
|
|
54
66
|
if (!id)
|
|
55
67
|
return { status: 'missing', reason: 'Sign the request as an ERC-8004 agent.' };
|
|
@@ -130,7 +130,7 @@ export function claims(config) {
|
|
|
130
130
|
return undefined;
|
|
131
131
|
const origin = new URL(request.url).origin;
|
|
132
132
|
presentations.delete(origin);
|
|
133
|
-
const challenge = await
|
|
133
|
+
const challenge = await readChallenge(response, request.signal);
|
|
134
134
|
if (!challenge)
|
|
135
135
|
return undefined;
|
|
136
136
|
// Bound to this origin only: a server can't relay another audience's challenge.
|
|
@@ -158,10 +158,11 @@ export function claims(config) {
|
|
|
158
158
|
}
|
|
159
159
|
/** Parses a claims challenge's problem body, or returns `undefined` when it is not one. */
|
|
160
160
|
export async function claimsChallenge(response) {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
161
|
+
return readChallenge(response);
|
|
162
|
+
}
|
|
163
|
+
/** {@link claimsChallenge}, giving up when `signal` aborts. */
|
|
164
|
+
async function readChallenge(response, signal) {
|
|
165
|
+
const body = (await readJson(response.clone(), signal));
|
|
165
166
|
if (!body || body.type !== Constants.claimsRequiredType)
|
|
166
167
|
return undefined;
|
|
167
168
|
const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
@@ -208,4 +209,55 @@ function track(sent, current, value) {
|
|
|
208
209
|
sent.delete(old);
|
|
209
210
|
}
|
|
210
211
|
}
|
|
212
|
+
/** Largest claims challenge body read; a larger one is not a claims challenge. */
|
|
213
|
+
const maxChallengeBytes = 64 * 1024;
|
|
214
|
+
/** Longest wait for a claims challenge body; a slower one is not a claims challenge. */
|
|
215
|
+
const challengeTimeoutMs = 2_000;
|
|
216
|
+
/**
|
|
217
|
+
* Parses a response body as JSON, reading at most {@link maxChallengeBytes} within
|
|
218
|
+
* {@link challengeTimeoutMs} and until `signal` aborts; `undefined` otherwise.
|
|
219
|
+
*/
|
|
220
|
+
async function readJson(response, signal) {
|
|
221
|
+
const length = Number(response.headers.get('content-length'));
|
|
222
|
+
if (!response.body || length > maxChallengeBytes || signal?.aborted) {
|
|
223
|
+
void response.body?.cancel().catch(() => { });
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
const reader = response.body.getReader();
|
|
227
|
+
const chunks = [];
|
|
228
|
+
let size = 0;
|
|
229
|
+
// Not awaited: a cloned body's cancel waits for its unread sibling.
|
|
230
|
+
let stopped = false;
|
|
231
|
+
const stop = () => {
|
|
232
|
+
stopped = true;
|
|
233
|
+
void reader.cancel().catch(() => { });
|
|
234
|
+
};
|
|
235
|
+
const timeout = setTimeout(stop, challengeTimeoutMs);
|
|
236
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
237
|
+
try {
|
|
238
|
+
for (;;) {
|
|
239
|
+
const { done, value } = await reader.read();
|
|
240
|
+
// A cancelled read ends as done: what arrived before the deadline is not the whole body.
|
|
241
|
+
if (stopped)
|
|
242
|
+
return undefined;
|
|
243
|
+
if (done)
|
|
244
|
+
break;
|
|
245
|
+
size += value.byteLength;
|
|
246
|
+
// Not awaited: a cloned body's cancel waits for its unread sibling.
|
|
247
|
+
if (size > maxChallengeBytes) {
|
|
248
|
+
void reader.cancel().catch(() => { });
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
chunks.push(value);
|
|
252
|
+
}
|
|
253
|
+
return JSON.parse(await new Blob(chunks).text());
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
return undefined;
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
clearTimeout(timeout);
|
|
260
|
+
signal?.removeEventListener('abort', stop);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
211
263
|
//# sourceMappingURL=index.js.map
|
|
@@ -20,8 +20,10 @@ export type Client = {
|
|
|
20
20
|
* Requests that carry proofs do not follow redirects: a redirect rejects
|
|
21
21
|
* (`redirect: 'error'`), so proofs never reach another URL. Requests with no
|
|
22
22
|
* prover in scope are sent unchanged. If a prover asks to retry a rejected
|
|
23
|
-
* (non-402) response, the request is proved again and resent once
|
|
24
|
-
*
|
|
23
|
+
* (non-402) response, the request is proved again and resent once. A paid
|
|
24
|
+
* attempt is resent only after a 401 with no receipt, with the same Payment
|
|
25
|
+
* credential and while its Challenge has not expired: servers check other authentication
|
|
26
|
+
* before verifying a Payment credential, so a 401 means nothing settled.
|
|
25
27
|
*/
|
|
26
28
|
readonly send: (fetch: typeof globalThis.fetch, request: Request, context?: SendContext) => Promise<{
|
|
27
29
|
request: Request;
|
|
@@ -44,7 +46,8 @@ export type Client = {
|
|
|
44
46
|
*
|
|
45
47
|
* - `unproved`: nothing sent yet.
|
|
46
48
|
* - `sent`: an unpaid attempt was sent; it may be resent once.
|
|
47
|
-
* - `paid`: a paid attempt was sent; it is
|
|
49
|
+
* - `paid`: a paid attempt was sent; it is resent once, with the same credential, only after a 401
|
|
50
|
+
* while its Challenge has not expired, since any other response may follow settlement.
|
|
48
51
|
* - `resent`: the request is proved again and resent once, with `headers` set.
|
|
49
52
|
* - `done`: the last response is final.
|
|
50
53
|
*
|
|
@@ -85,6 +88,7 @@ export declare const initial: Attempt;
|
|
|
85
88
|
* | `unproved` | `send` (paid) | `paid` |
|
|
86
89
|
* | `unproved` | `send` (unpaid) | `sent` |
|
|
87
90
|
* | `sent` | `response` with resend | `resent` |
|
|
91
|
+
* | `paid` (after a 401) | `response` with resend | `resent` |
|
|
88
92
|
* | `sent`, `paid`, `resent` | `response` without | `done` |
|
|
89
93
|
*
|
|
90
94
|
* @internal
|
package/dist/identity/Client.js
CHANGED
|
@@ -22,6 +22,7 @@ export const initial = Object.freeze({ phase: 'unproved' });
|
|
|
22
22
|
* | `unproved` | `send` (paid) | `paid` |
|
|
23
23
|
* | `unproved` | `send` (unpaid) | `sent` |
|
|
24
24
|
* | `sent` | `response` with resend | `resent` |
|
|
25
|
+
* | `paid` (after a 401) | `response` with resend | `resent` |
|
|
25
26
|
* | `sent`, `paid`, `resent` | `response` without | `done` |
|
|
26
27
|
*
|
|
27
28
|
* @internal
|
|
@@ -38,7 +39,7 @@ export function transition(attempt, event) {
|
|
|
38
39
|
break;
|
|
39
40
|
return Object.freeze({ phase: 'done' });
|
|
40
41
|
}
|
|
41
|
-
if (attempt.phase !== 'sent')
|
|
42
|
+
if (attempt.phase !== 'sent' && attempt.phase !== 'paid')
|
|
42
43
|
break;
|
|
43
44
|
return Object.freeze({ phase: 'resent', headers: event.resend });
|
|
44
45
|
}
|
|
@@ -71,13 +72,18 @@ export function from(provers) {
|
|
|
71
72
|
return provers.filter((prover) => prover.scope === '*' || prover.scope.includes(origin));
|
|
72
73
|
};
|
|
73
74
|
async function sendOnce(parameters) {
|
|
74
|
-
const { context, fetch, headers, keepReadable, request } = parameters;
|
|
75
|
+
const { context, fetch, headers, keepReadable, proceed, request } = parameters;
|
|
75
76
|
// Keep the original readable only when it may be resent; otherwise a clone would tee
|
|
76
77
|
// (and buffer) a streamed body that is never read again.
|
|
77
78
|
const source = keepReadable ? request.clone() : request;
|
|
78
79
|
const scoped = inScope(request.url);
|
|
79
|
-
if (scoped.length === 0)
|
|
80
|
+
if (scoped.length === 0) {
|
|
81
|
+
if (proceed && !proceed()) {
|
|
82
|
+
discard(source);
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
80
85
|
return { request: source, response: await fetch(source) };
|
|
86
|
+
}
|
|
81
87
|
const attempt = Object.freeze({
|
|
82
88
|
...SigningContext.create(),
|
|
83
89
|
...(context.challenge && { challenge: context.challenge }),
|
|
@@ -99,8 +105,18 @@ export function from(provers) {
|
|
|
99
105
|
headers: merged,
|
|
100
106
|
redirect: request.redirect === 'follow' ? 'error' : request.redirect,
|
|
101
107
|
});
|
|
102
|
-
|
|
103
|
-
|
|
108
|
+
try {
|
|
109
|
+
for (const prover of scoped)
|
|
110
|
+
sent = await prover.prove(sent, attempt);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
discard(sent);
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
if (proceed && !proceed()) {
|
|
117
|
+
discard(sent);
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
104
120
|
return { request: sent, response: await fetch(sent) };
|
|
105
121
|
}
|
|
106
122
|
return {
|
|
@@ -111,20 +127,71 @@ export function from(provers) {
|
|
|
111
127
|
payment: isPaid(request, context) ? 'paid' : 'unpaid',
|
|
112
128
|
});
|
|
113
129
|
const retriers = inScope(request.url).filter((prover) => prover.retry);
|
|
114
|
-
|
|
130
|
+
// A paid attempt may be resent only with the Payment credential for the transport's Challenge.
|
|
131
|
+
const paidChallenge = attempt.phase === 'paid' ? resendableChallenge(request, context) : undefined;
|
|
132
|
+
// A paid attempt whose Challenge already expired can never be resent, so it is not cloned.
|
|
133
|
+
const keepReadable = retriers.length > 0 &&
|
|
134
|
+
(attempt.phase === 'sent' || (paidChallenge !== undefined && isUnexpired(paidChallenge)));
|
|
115
135
|
const carried = context.headers ?? [];
|
|
116
|
-
const result = await sendOnce({ context, fetch, headers: carried, keepReadable, request });
|
|
136
|
+
const result = (await sendOnce({ context, fetch, headers: carried, keepReadable, request }));
|
|
117
137
|
const { response } = result;
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
138
|
+
let resend;
|
|
139
|
+
if (keepReadable && canResend(attempt, response, paidChallenge))
|
|
140
|
+
try {
|
|
141
|
+
resend = await resendHeaders(retriers, response, result.request);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
// The server's 401 to a paid attempt was received and nothing was resent, so a failing
|
|
145
|
+
// retry hook returns that 401 rather than leaving the payment's outcome unknown.
|
|
146
|
+
if (attempt.phase !== 'paid') {
|
|
147
|
+
discard(request);
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
121
151
|
attempt = transition(attempt, { type: 'response', resend });
|
|
122
|
-
if (attempt.phase !== 'resent')
|
|
152
|
+
if (attempt.phase !== 'resent') {
|
|
153
|
+
// The copy kept for a resend is never sent: release it so the upload source is cancelled.
|
|
154
|
+
if (keepReadable)
|
|
155
|
+
discard(request);
|
|
123
156
|
return { ...result, headers: carried };
|
|
124
|
-
|
|
157
|
+
}
|
|
158
|
+
// The rejected response is released before the provers run again, so a prover that awaits
|
|
159
|
+
// a request through the same connection pool is not blocked by it. A paid attempt keeps a
|
|
160
|
+
// bounded copy to return if it is not resent.
|
|
161
|
+
const fallback = paidChallenge ? await detach(response) : (release([response]), undefined);
|
|
162
|
+
const rejected = () => {
|
|
163
|
+
discard(request);
|
|
164
|
+
return { request: result.request, response: fallback, headers: carried };
|
|
165
|
+
};
|
|
125
166
|
const headers = mergeHeaders(carried, attempt.headers);
|
|
126
|
-
|
|
167
|
+
let started = false;
|
|
168
|
+
let resent;
|
|
169
|
+
try {
|
|
170
|
+
resent = await sendOnce({
|
|
171
|
+
context,
|
|
172
|
+
fetch,
|
|
173
|
+
headers,
|
|
174
|
+
keepReadable: false,
|
|
175
|
+
// The Challenge may expire while provers refresh identity: a paid attempt is checked
|
|
176
|
+
// again right before the resend, and an expired one returns the 401 instead.
|
|
177
|
+
proceed() {
|
|
178
|
+
if (paidChallenge && !isUnexpired(paidChallenge))
|
|
179
|
+
return false;
|
|
180
|
+
started = true;
|
|
181
|
+
return true;
|
|
182
|
+
},
|
|
183
|
+
request,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
// A prover failing before the paid resend was sent: the 401 stands.
|
|
188
|
+
if (fallback && !started)
|
|
189
|
+
return rejected();
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
127
192
|
transition(attempt, { type: 'response', resend: undefined });
|
|
193
|
+
if (!resent)
|
|
194
|
+
return rejected();
|
|
128
195
|
return { ...resent, headers };
|
|
129
196
|
},
|
|
130
197
|
async challenge(response, { challenge }, url) {
|
|
@@ -146,6 +213,52 @@ export function from(provers) {
|
|
|
146
213
|
},
|
|
147
214
|
};
|
|
148
215
|
}
|
|
216
|
+
/** Response headers that report a settled payment (MPP receipt, x402 settlement response). */
|
|
217
|
+
const settlementHeaders = ['payment-receipt', 'payment-response', 'x-payment-response'];
|
|
218
|
+
/**
|
|
219
|
+
* Whether a rejected response may be resent. An unpaid attempt may be resent after any non-402
|
|
220
|
+
* rejection. A paid attempt only after a 401, which never follows settlement, that carries no
|
|
221
|
+
* receipt or other settlement header, and only while the credential's Challenge has not expired,
|
|
222
|
+
* so the server processes the same credential afresh. A 403 can follow a settled payment, so it is
|
|
223
|
+
* never resent.
|
|
224
|
+
*/
|
|
225
|
+
function canResend(attempt, response, challenge) {
|
|
226
|
+
if (attempt.phase === 'sent')
|
|
227
|
+
return response.status >= 400 && response.status !== 402;
|
|
228
|
+
if (attempt.phase !== 'paid' || response.status !== 401 || !challenge)
|
|
229
|
+
return false;
|
|
230
|
+
if (settlementHeaders.some((name) => response.headers.has(name)))
|
|
231
|
+
return false;
|
|
232
|
+
return isUnexpired(challenge);
|
|
233
|
+
}
|
|
234
|
+
/** Whether a Challenge has an `expires` still in the future. */
|
|
235
|
+
function isUnexpired(challenge) {
|
|
236
|
+
return challenge.expires !== undefined && Date.parse(challenge.expires) > Date.now();
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Returns the Challenge a paid attempt may be resent for: the transport's Challenge (or, without
|
|
240
|
+
* one, the Challenge of the request's Payment credential), when a header holds a Payment credential
|
|
241
|
+
* for it. A request carrying an x402 credential header is never resent, nor one whose Payment
|
|
242
|
+
* credential answers another Challenge.
|
|
243
|
+
*/
|
|
244
|
+
function resendableChallenge(request, context) {
|
|
245
|
+
if (x402CredentialHeaders.some((name) => request.headers.has(name)))
|
|
246
|
+
return undefined;
|
|
247
|
+
const challenge = context.challenge ?? credentialChallenge(request.headers);
|
|
248
|
+
if (!challenge)
|
|
249
|
+
return undefined;
|
|
250
|
+
for (const [, value] of request.headers) {
|
|
251
|
+
const payment = Credential.extractPaymentScheme(value);
|
|
252
|
+
if (!payment)
|
|
253
|
+
continue;
|
|
254
|
+
try {
|
|
255
|
+
if (Credential.deserialize(payment).challenge.id === challenge.id)
|
|
256
|
+
return challenge;
|
|
257
|
+
}
|
|
258
|
+
catch { }
|
|
259
|
+
}
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
149
262
|
/**
|
|
150
263
|
* Whether a send is a paid attempt: a Challenge in context, or a Payment or x402 credential the
|
|
151
264
|
* caller attached. Its credential may already have settled, so replaying it could pay again.
|
|
@@ -190,6 +303,58 @@ async function resendHeaders(provers, response, request) {
|
|
|
190
303
|
return undefined;
|
|
191
304
|
return Object.freeze([...headers].map(([name, value]) => Object.freeze([name, value])));
|
|
192
305
|
}
|
|
306
|
+
/** Releases a request's unsent body, so a streamed upload source is cancelled. */
|
|
307
|
+
function discard(request) {
|
|
308
|
+
if (request.body && !request.bodyUsed && !request.body.locked)
|
|
309
|
+
void request.body.cancel().catch(() => { });
|
|
310
|
+
}
|
|
311
|
+
const maxFallbackBytes = 64 * 1024;
|
|
312
|
+
const fallbackTimeoutMs = 2_000;
|
|
313
|
+
/**
|
|
314
|
+
* Reads a rejected response into a copy, within a size and time bound, and releases its
|
|
315
|
+
* connection. A body larger than 64 KiB, or still arriving after 2 seconds, is cut off to what
|
|
316
|
+
* arrived, marked with an `Mppx-Body-Truncated: true` header.
|
|
317
|
+
*/
|
|
318
|
+
async function detach(response) {
|
|
319
|
+
const headers = new Headers(response.headers);
|
|
320
|
+
const init = { headers, status: response.status, statusText: response.statusText };
|
|
321
|
+
if (!response.body)
|
|
322
|
+
return new Response(null, init);
|
|
323
|
+
const reader = response.body.getReader();
|
|
324
|
+
const chunks = [];
|
|
325
|
+
let received = 0;
|
|
326
|
+
let truncated = false;
|
|
327
|
+
const timeout = setTimeout(() => {
|
|
328
|
+
truncated = true;
|
|
329
|
+
void reader.cancel().catch(() => { });
|
|
330
|
+
}, fallbackTimeoutMs);
|
|
331
|
+
try {
|
|
332
|
+
for (;;) {
|
|
333
|
+
const { done, value } = await reader.read();
|
|
334
|
+
if (done)
|
|
335
|
+
break;
|
|
336
|
+
chunks.push(value);
|
|
337
|
+
received += value.byteLength;
|
|
338
|
+
if (received > maxFallbackBytes) {
|
|
339
|
+
truncated = true;
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
truncated = true;
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
clearTimeout(timeout);
|
|
349
|
+
// A tee's cancellation can wait for the other branch; do not await it.
|
|
350
|
+
void reader.cancel().catch(() => { });
|
|
351
|
+
}
|
|
352
|
+
if (truncated) {
|
|
353
|
+
headers.delete('content-length');
|
|
354
|
+
headers.set('Mppx-Body-Truncated', 'true');
|
|
355
|
+
}
|
|
356
|
+
return new Response(new Blob(chunks).slice(0, maxFallbackBytes), init);
|
|
357
|
+
}
|
|
193
358
|
/** Releases unread response copies without waiting, so they neither buffer the body nor block a resend. */
|
|
194
359
|
function release(responses) {
|
|
195
360
|
for (const unread of responses)
|
package/dist/identity/Types.d.ts
CHANGED
|
@@ -210,7 +210,8 @@ export type Prover = {
|
|
|
210
210
|
* Same-named headers returned by several provers are combined, comma-separated. Payment
|
|
211
211
|
* credential headers (`Authorization`, `Payment-Authorization`, `Payment-Signature`,
|
|
212
212
|
* `X-Payment`, the header the Challenge names, and any header holding a Payment credential) are
|
|
213
|
-
* ignored. Return `false` or `undefined` not to resend.
|
|
213
|
+
* ignored. Return `false` or `undefined` not to resend. A paid attempt is asked only after a
|
|
214
|
+
* 401 with no receipt, and resent with the same Payment credential while its Challenge has not expired. `true`
|
|
214
215
|
* resends with no extra headers and is deprecated: return `{}` instead.
|
|
215
216
|
*/
|
|
216
217
|
readonly retry?: ((response: Response, context: RetryContext) => MaybePromise<HeadersInit | boolean | undefined>) | undefined;
|
|
@@ -5,6 +5,7 @@ import * as Credential from '../../Credential.js';
|
|
|
5
5
|
import * as Types from '../../internal/x402/Types.js';
|
|
6
6
|
import * as SecretKey from '../../server/internal/SecretKey.js';
|
|
7
7
|
import * as Evm from './Evm.js';
|
|
8
|
+
import * as Solana from './Solana.js';
|
|
8
9
|
/** Creates the native MPP side of an x402 compatibility integration. */
|
|
9
10
|
export function create(config) {
|
|
10
11
|
SecretKey.assert(config.secretKey);
|
|
@@ -36,8 +37,10 @@ export function create(config) {
|
|
|
36
37
|
throw new Error(`Expected x402 payment response, received ${result.type}.`);
|
|
37
38
|
const x402Response = responseFromInstructions(result.response);
|
|
38
39
|
const paymentRequired = getPaymentRequired(result);
|
|
40
|
+
// A native MPP rail is offered only when the route's x402 scheme can settle its credential.
|
|
39
41
|
const handler = paymentRequired
|
|
40
|
-
? Evm.createHandler({ config, context, paymentRequired })
|
|
42
|
+
? (Evm.createHandler({ config, context, paymentRequired }) ??
|
|
43
|
+
Solana.createHandler({ config, context, paymentRequired }))
|
|
41
44
|
: undefined;
|
|
42
45
|
if (!handler)
|
|
43
46
|
return { response: x402Response, status: 'handled' };
|