mppx 0.21.4 → 0.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -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/account.d.ts +2 -1
- package/dist/cli/account.js +22 -11
- 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/attestation/client/index.js +1 -0
- package/dist/extensions/identity/attestation/server/index.js +1 -0
- package/dist/extensions/identity/email-otp/server/index.js +1 -0
- package/dist/extensions/identity/erc8004/client/index.js +1 -0
- package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
- package/dist/extensions/identity/erc8004/server/index.js +16 -2
- package/dist/extensions/identity/link/client/index.js +57 -5
- package/dist/extensions/identity/link/server/index.js +1 -0
- package/dist/extensions/identity/poppy/server/index.js +1 -0
- package/dist/extensions/identity/tempo/client/index.js +1 -0
- package/dist/extensions/identity/tempo/server/index.js +7 -1
- package/dist/extensions/identity/world/server/index.js +1 -0
- package/dist/identity/Client.d.ts +7 -3
- package/dist/identity/Client.js +178 -13
- package/dist/identity/Headers.d.ts +3 -2
- package/dist/identity/Headers.js +3 -2
- package/dist/identity/Server.d.ts +8 -0
- package/dist/identity/Server.js +18 -0
- package/dist/identity/Types.d.ts +18 -3
- 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/proxy/Proxy.js +59 -46
- package/dist/proxy/internal/Headers.d.ts +9 -2
- package/dist/proxy/internal/Headers.js +16 -3
- package/dist/server/Mppx.d.ts +14 -1
- package/dist/server/Mppx.js +59 -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
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)
|
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
/**
|
|
6
6
|
* Bearer identity request headers. Anyone holding one can replay it until it expires, so it is
|
|
7
|
-
* never sent across origins on a redirect or forwarded upstream by a proxy
|
|
8
|
-
*
|
|
7
|
+
* never sent across origins on a redirect or forwarded upstream by a proxy, even when an app sets
|
|
8
|
+
* it by hand. Each protocol also declares its own, in `Prover.headers` and on its verifier or
|
|
9
|
+
* payment check, so a protocol outside mppx is stripped the same way.
|
|
9
10
|
*/
|
|
10
11
|
export declare const request: readonly ["agent-id", "agent-signature", "dpop", "identity-attestation", "identity-presentation", "poppy-session", "tempo-id-token"];
|
|
11
12
|
/**
|
package/dist/identity/Headers.js
CHANGED
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
/**
|
|
6
6
|
* Bearer identity request headers. Anyone holding one can replay it until it expires, so it is
|
|
7
|
-
* never sent across origins on a redirect or forwarded upstream by a proxy
|
|
8
|
-
*
|
|
7
|
+
* never sent across origins on a redirect or forwarded upstream by a proxy, even when an app sets
|
|
8
|
+
* it by hand. Each protocol also declares its own, in `Prover.headers` and on its verifier or
|
|
9
|
+
* payment check, so a protocol outside mppx is stripped the same way.
|
|
9
10
|
*/
|
|
10
11
|
export const request = Object.freeze([
|
|
11
12
|
'agent-id',
|
|
@@ -172,6 +172,14 @@ export type RouteConfig = {
|
|
|
172
172
|
readonly request: readonly Types.Verifier[];
|
|
173
173
|
readonly payment: Types.PaymentCheck | undefined;
|
|
174
174
|
};
|
|
175
|
+
/**
|
|
176
|
+
* Returns the protocol headers declared by identity verifiers and payment checks, lowercased and
|
|
177
|
+
* deduplicated, such as for a proxy to strip. Throws a `TypeError` for a name that is not an HTTP
|
|
178
|
+
* field name, checked before lowercasing so a Unicode name cannot fold into an ASCII one.
|
|
179
|
+
*/
|
|
180
|
+
export declare function headersOf(checks: readonly (Types.Verifier | Types.PaymentCheck | undefined)[]): Required<{
|
|
181
|
+
[key in keyof Types.ProtocolHeaders]: readonly string[];
|
|
182
|
+
}>;
|
|
175
183
|
/**
|
|
176
184
|
* Parses a route's `identity` option. Throws a `TypeError` for a payment-stage or unknown-stage
|
|
177
185
|
* verifier, and for payment requirements that cannot be serialized. @internal
|
package/dist/identity/Server.js
CHANGED
|
@@ -26,6 +26,7 @@ export function anyOf(...verifiers) {
|
|
|
26
26
|
const verifier = Object.freeze({
|
|
27
27
|
// A member that reads Authorization makes the whole set need requiresAuth.
|
|
28
28
|
...(verifiers.some((member) => member.authorization) ? { authorization: true } : {}),
|
|
29
|
+
headers: headersOf(verifiers),
|
|
29
30
|
async verify(request) {
|
|
30
31
|
// Every member runs, so each presented proof's replay nonce is consumed even when an
|
|
31
32
|
// earlier member already verified.
|
|
@@ -313,6 +314,23 @@ export function results(state) {
|
|
|
313
314
|
},
|
|
314
315
|
});
|
|
315
316
|
}
|
|
317
|
+
/**
|
|
318
|
+
* Returns the protocol headers declared by identity verifiers and payment checks, lowercased and
|
|
319
|
+
* deduplicated, such as for a proxy to strip. Throws a `TypeError` for a name that is not an HTTP
|
|
320
|
+
* field name, checked before lowercasing so a Unicode name cannot fold into an ASCII one.
|
|
321
|
+
*/
|
|
322
|
+
export function headersOf(checks) {
|
|
323
|
+
const names = (key) => Object.freeze([
|
|
324
|
+
...new Set(checks
|
|
325
|
+
.flatMap((check) => check?.headers?.[key] ?? [])
|
|
326
|
+
.map((name) => {
|
|
327
|
+
if (typeof name !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name))
|
|
328
|
+
throw new TypeError(`Invalid identity header name: ${JSON.stringify(name)}.`);
|
|
329
|
+
return name.toLowerCase();
|
|
330
|
+
})),
|
|
331
|
+
]);
|
|
332
|
+
return Object.freeze({ request: names('request'), response: names('response') });
|
|
333
|
+
}
|
|
316
334
|
/**
|
|
317
335
|
* Parses a route's `identity` option. Throws a `TypeError` for a payment-stage or unknown-stage
|
|
318
336
|
* verifier, and for payment requirements that cannot be serialized. @internal
|
package/dist/identity/Types.d.ts
CHANGED
|
@@ -62,8 +62,20 @@ export type Verification<value = unknown> = {
|
|
|
62
62
|
/** Human-readable reason. */
|
|
63
63
|
readonly reason: string;
|
|
64
64
|
};
|
|
65
|
+
/**
|
|
66
|
+
* Headers an identity protocol sends. A proxy serving a route that uses the protocol strips them:
|
|
67
|
+
* the proxy, not the upstream service, decides which identity the client presents.
|
|
68
|
+
*/
|
|
69
|
+
export type ProtocolHeaders = {
|
|
70
|
+
/** Request headers the client sends, never forwarded upstream, such as a proof. */
|
|
71
|
+
readonly request?: readonly string[] | undefined;
|
|
72
|
+
/** Response headers the server sends, never passed from upstream to the client. */
|
|
73
|
+
readonly response?: readonly string[] | undefined;
|
|
74
|
+
};
|
|
65
75
|
/** Verifies one identity protocol on the server, before any payment Challenge is issued. */
|
|
66
76
|
export type Verifier<value = unknown> = {
|
|
77
|
+
/** Headers the protocol sends, such as a bearer proof, stripped by a proxy. */
|
|
78
|
+
readonly headers?: ProtocolHeaders | undefined;
|
|
67
79
|
/**
|
|
68
80
|
* When the verifier runs.
|
|
69
81
|
*
|
|
@@ -117,6 +129,8 @@ export type PaymentCheck<value = unknown> = {
|
|
|
117
129
|
* created with `requiresAuth: true`, so Payment Credentials travel in `Payment-Authorization`.
|
|
118
130
|
*/
|
|
119
131
|
readonly authorization?: boolean | undefined;
|
|
132
|
+
/** Headers the check's protocol sends, such as a bearer proof, stripped by a proxy. */
|
|
133
|
+
readonly headers?: ProtocolHeaders | undefined;
|
|
120
134
|
/** Identities the check requires, advertised in every 402 of the route. */
|
|
121
135
|
readonly requires: readonly Requirement[];
|
|
122
136
|
/** Returns the check's outcome for the paid retry (or, without a Credential, for `authorize`). */
|
|
@@ -193,8 +207,8 @@ export type Prover = {
|
|
|
193
207
|
/** Origins the prover may run for, such as `['https://shop.example']`, or `'*'` for any origin. */
|
|
194
208
|
readonly scope: readonly string[] | '*';
|
|
195
209
|
/**
|
|
196
|
-
*
|
|
197
|
-
*
|
|
210
|
+
* Sensitive request headers the prover writes, such as a bearer token. The client strips them
|
|
211
|
+
* on a cross-origin redirect.
|
|
198
212
|
*/
|
|
199
213
|
readonly headers?: readonly string[] | undefined;
|
|
200
214
|
/** Returns a new request carrying the protocol's identity material. */
|
|
@@ -210,7 +224,8 @@ export type Prover = {
|
|
|
210
224
|
* Same-named headers returned by several provers are combined, comma-separated. Payment
|
|
211
225
|
* credential headers (`Authorization`, `Payment-Authorization`, `Payment-Signature`,
|
|
212
226
|
* `X-Payment`, the header the Challenge names, and any header holding a Payment credential) are
|
|
213
|
-
* ignored. Return `false` or `undefined` not to resend.
|
|
227
|
+
* ignored. Return `false` or `undefined` not to resend. A paid attempt is asked only after a
|
|
228
|
+
* 401 with no receipt, and resent with the same Payment credential while its Challenge has not expired. `true`
|
|
214
229
|
* resends with no extra headers and is deprecated: return `{}` instead.
|
|
215
230
|
*/
|
|
216
231
|
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' };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { HTTPRequestContext } from '@x402/core/server';
|
|
2
|
+
import type { PaymentRequired, PaymentRequirements } from '@x402/core/types';
|
|
3
|
+
import * as z from '../../zod.js';
|
|
4
|
+
import type { Config } from './Evm.js';
|
|
5
|
+
/**
|
|
6
|
+
* Solana clusters by CAIP-2 network, named as the `solana/charge` method names them
|
|
7
|
+
* (`methodDetails.network`).
|
|
8
|
+
*/
|
|
9
|
+
export declare const networks: {
|
|
10
|
+
readonly 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': 'mainnet';
|
|
11
|
+
readonly 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1': 'devnet';
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The fee-sponsored, server-broadcast subset of the `solana/charge` method (the same wire
|
|
15
|
+
* format as `@solana/mpp`'s `solana.charge`), so a client that pays `solana/charge` pays it.
|
|
16
|
+
* Only what an x402 `exact` facilitator can settle is offered: an SPL transfer the client
|
|
17
|
+
* partially signs, with the facilitator as fee payer.
|
|
18
|
+
*/
|
|
19
|
+
export declare const charge: {
|
|
20
|
+
readonly name: "solana";
|
|
21
|
+
readonly intent: "charge";
|
|
22
|
+
readonly schema: {
|
|
23
|
+
credential: {
|
|
24
|
+
payload: z.ZodMiniObject<{
|
|
25
|
+
transaction: z.ZodMiniString<string>;
|
|
26
|
+
type: z.ZodMiniLiteral<"transaction">;
|
|
27
|
+
}, z.core.$strip>;
|
|
28
|
+
};
|
|
29
|
+
request: z.ZodMiniObject<{
|
|
30
|
+
amount: z.ZodMiniString<string>;
|
|
31
|
+
currency: z.ZodMiniString<string>;
|
|
32
|
+
description: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
33
|
+
externalId: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
34
|
+
methodDetails: z.ZodMiniObject<{
|
|
35
|
+
decimals: z.ZodMiniNumber<number>;
|
|
36
|
+
feePayer: z.ZodMiniLiteral<true>;
|
|
37
|
+
feePayerKey: z.ZodMiniString<string>;
|
|
38
|
+
network: z.ZodMiniEnum<{
|
|
39
|
+
devnet: "devnet";
|
|
40
|
+
mainnet: "mainnet";
|
|
41
|
+
}>;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
recipient: z.ZodMiniString<string>;
|
|
44
|
+
}, z.core.$strip>;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Creates a native `solana/charge` MPP handler backed by a compatible x402 Solana `exact`
|
|
49
|
+
* requirement. The client's partially signed transaction is verified and settled by the route's
|
|
50
|
+
* x402 facilitator, exactly as an x402 payment would be.
|
|
51
|
+
*/
|
|
52
|
+
export declare function createHandler(parameters: {
|
|
53
|
+
config: Config;
|
|
54
|
+
context: HTTPRequestContext;
|
|
55
|
+
paymentRequired: PaymentRequired;
|
|
56
|
+
}): ((request: Request) => Promise<{
|
|
57
|
+
payment: {
|
|
58
|
+
challenge: Response;
|
|
59
|
+
rejection?: import("../../identity/Types.js").Rejection | undefined;
|
|
60
|
+
status: 402;
|
|
61
|
+
} | {
|
|
62
|
+
status: 200;
|
|
63
|
+
challenge?: import("../../Challenge.js").Challenge | undefined;
|
|
64
|
+
identity?: import("../../identity/Types.js").Results | undefined;
|
|
65
|
+
withReceipt: import("../../server/Transport.js").WithReceipt<import("../../server/Transport.js").Http>;
|
|
66
|
+
};
|
|
67
|
+
skipHandlerResponse: Response | undefined;
|
|
68
|
+
}>) | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* The first x402 requirement a `solana/charge` credential can satisfy: `exact` on a known
|
|
71
|
+
* Solana cluster, with a facilitator fee payer and no seller memo (a `solana/charge` client does
|
|
72
|
+
* not write x402's `extra.memo`). Routes with x402 extensions are left to x402.
|
|
73
|
+
*/
|
|
74
|
+
export declare function selectRequirement(paymentRequired: PaymentRequired): PaymentRequirements | undefined;
|
|
75
|
+
//# sourceMappingURL=Solana.d.ts.map
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { VerificationFailedError } from '../../Errors.js';
|
|
2
|
+
import * as Expires from '../../Expires.js';
|
|
3
|
+
import * as Method from '../../Method.js';
|
|
4
|
+
import * as Receipt from '../../Receipt.js';
|
|
5
|
+
import * as Mppx from '../../server/Mppx.js';
|
|
6
|
+
import * as z from '../../zod.js';
|
|
7
|
+
/**
|
|
8
|
+
* Solana clusters by CAIP-2 network, named as the `solana/charge` method names them
|
|
9
|
+
* (`methodDetails.network`).
|
|
10
|
+
*/
|
|
11
|
+
export const networks = {
|
|
12
|
+
'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': 'mainnet',
|
|
13
|
+
'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1': 'devnet',
|
|
14
|
+
};
|
|
15
|
+
const base58 = z.string().check(z.regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'Invalid Solana address'));
|
|
16
|
+
/**
|
|
17
|
+
* The fee-sponsored, server-broadcast subset of the `solana/charge` method (the same wire
|
|
18
|
+
* format as `@solana/mpp`'s `solana.charge`), so a client that pays `solana/charge` pays it.
|
|
19
|
+
* Only what an x402 `exact` facilitator can settle is offered: an SPL transfer the client
|
|
20
|
+
* partially signs, with the facilitator as fee payer.
|
|
21
|
+
*/
|
|
22
|
+
export const charge = Method.from({
|
|
23
|
+
name: 'solana',
|
|
24
|
+
intent: 'charge',
|
|
25
|
+
schema: {
|
|
26
|
+
credential: {
|
|
27
|
+
payload: z.object({
|
|
28
|
+
transaction: z.string().check(z.minLength(1)),
|
|
29
|
+
type: z.literal('transaction'),
|
|
30
|
+
}),
|
|
31
|
+
},
|
|
32
|
+
request: z.object({
|
|
33
|
+
amount: z.string().check(z.regex(/^\d+$/, 'Invalid atomic amount')),
|
|
34
|
+
currency: base58,
|
|
35
|
+
description: z.optional(z.string()),
|
|
36
|
+
externalId: z.optional(z.string()),
|
|
37
|
+
methodDetails: z.object({
|
|
38
|
+
decimals: z.number(),
|
|
39
|
+
feePayer: z.literal(true),
|
|
40
|
+
feePayerKey: base58,
|
|
41
|
+
network: z.enum(['devnet', 'mainnet']),
|
|
42
|
+
}),
|
|
43
|
+
recipient: base58,
|
|
44
|
+
}),
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* Creates a native `solana/charge` MPP handler backed by a compatible x402 Solana `exact`
|
|
49
|
+
* requirement. The client's partially signed transaction is verified and settled by the route's
|
|
50
|
+
* x402 facilitator, exactly as an x402 payment would be.
|
|
51
|
+
*/
|
|
52
|
+
export function createHandler(parameters) {
|
|
53
|
+
const requirement = selectRequirement(parameters.paymentRequired);
|
|
54
|
+
if (!requirement)
|
|
55
|
+
return undefined;
|
|
56
|
+
const decimals = parameters.config.server.getAssetDecimalsForRequirements(requirement);
|
|
57
|
+
const method = Method.toServer(charge, {
|
|
58
|
+
async verify({ credential }) {
|
|
59
|
+
const reference = await settle({
|
|
60
|
+
context: parameters.context,
|
|
61
|
+
paymentRequired: parameters.paymentRequired,
|
|
62
|
+
requirement,
|
|
63
|
+
server: parameters.config.server,
|
|
64
|
+
transaction: credential.payload.transaction,
|
|
65
|
+
});
|
|
66
|
+
return Receipt.from({
|
|
67
|
+
method: charge.name,
|
|
68
|
+
reference,
|
|
69
|
+
status: 'success',
|
|
70
|
+
timestamp: new Date().toISOString(),
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
const payment = Mppx.create({
|
|
75
|
+
methods: [method],
|
|
76
|
+
...(parameters.config.realm ? { realm: parameters.config.realm } : {}),
|
|
77
|
+
secretKey: parameters.config.secretKey,
|
|
78
|
+
});
|
|
79
|
+
const description = parameters.paymentRequired.resource.description;
|
|
80
|
+
const options = {
|
|
81
|
+
amount: requirement.amount,
|
|
82
|
+
currency: requirement.asset,
|
|
83
|
+
...(description ? { description } : {}),
|
|
84
|
+
expires: Expires.seconds(requirement.maxTimeoutSeconds),
|
|
85
|
+
methodDetails: {
|
|
86
|
+
decimals,
|
|
87
|
+
feePayer: true,
|
|
88
|
+
feePayerKey: requirement.extra.feePayer,
|
|
89
|
+
network: networks[requirement.network],
|
|
90
|
+
},
|
|
91
|
+
recipient: requirement.payTo,
|
|
92
|
+
scope: parameters.paymentRequired.resource.url,
|
|
93
|
+
};
|
|
94
|
+
const handler = payment.compose([payment.solana.charge, options]);
|
|
95
|
+
return async (request) => ({
|
|
96
|
+
payment: await handler(request),
|
|
97
|
+
skipHandlerResponse: undefined,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The first x402 requirement a `solana/charge` credential can satisfy: `exact` on a known
|
|
102
|
+
* Solana cluster, with a facilitator fee payer and no seller memo (a `solana/charge` client does
|
|
103
|
+
* not write x402's `extra.memo`). Routes with x402 extensions are left to x402.
|
|
104
|
+
*/
|
|
105
|
+
export function selectRequirement(paymentRequired) {
|
|
106
|
+
if (paymentRequired.extensions && Object.keys(paymentRequired.extensions).length > 0)
|
|
107
|
+
return undefined;
|
|
108
|
+
return paymentRequired.accepts.find((requirement) => {
|
|
109
|
+
if (requirement.scheme !== 'exact')
|
|
110
|
+
return false;
|
|
111
|
+
if (!(requirement.network in networks))
|
|
112
|
+
return false;
|
|
113
|
+
if (requirement.extra?.memo !== undefined)
|
|
114
|
+
return false;
|
|
115
|
+
const { feePayer } = requirement.extra ?? {};
|
|
116
|
+
return (typeof feePayer === 'string' &&
|
|
117
|
+
base58.safeParse(feePayer).success &&
|
|
118
|
+
base58.safeParse(requirement.asset).success &&
|
|
119
|
+
base58.safeParse(requirement.payTo).success &&
|
|
120
|
+
/^\d+$/.test(requirement.amount));
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
async function settle(parameters) {
|
|
124
|
+
const paymentPayload = {
|
|
125
|
+
accepted: parameters.requirement,
|
|
126
|
+
payload: { transaction: parameters.transaction },
|
|
127
|
+
resource: parameters.paymentRequired.resource,
|
|
128
|
+
x402Version: 2,
|
|
129
|
+
};
|
|
130
|
+
const transportContext = { request: parameters.context };
|
|
131
|
+
const verified = await parameters.server.verifyPayment(paymentPayload, parameters.requirement, parameters.paymentRequired.extensions, transportContext);
|
|
132
|
+
if (!verified.isValid)
|
|
133
|
+
throw new VerificationFailedError({
|
|
134
|
+
reason: verified.invalidMessage ?? verified.invalidReason ?? 'x402 verification failed',
|
|
135
|
+
});
|
|
136
|
+
const settled = await parameters.server.settlePayment(paymentPayload, parameters.requirement, parameters.paymentRequired.extensions, transportContext);
|
|
137
|
+
if (!settled.success)
|
|
138
|
+
throw new VerificationFailedError({
|
|
139
|
+
reason: settled.errorMessage ?? settled.errorReason ?? 'x402 settlement failed',
|
|
140
|
+
});
|
|
141
|
+
return settled.transaction;
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=Solana.js.map
|
|
@@ -1,5 +1,20 @@
|
|
|
1
|
-
/**
|
|
2
|
-
export declare
|
|
1
|
+
/** Reserved metadata key for HMAC-bound, per-issuance challenge randomness. */
|
|
2
|
+
export declare const nonceKey = "_mpp_nonce";
|
|
3
|
+
/**
|
|
4
|
+
* Adds fresh issuance randomness (16 random bytes, base64url without padding) under
|
|
5
|
+
* `_mpp_nonce` while preserving application and route metadata. With `enabled: false`,
|
|
6
|
+
* returns the metadata unchanged.
|
|
7
|
+
*/
|
|
8
|
+
export declare function withNonce(meta: Record<string, string> | undefined, enabled?: boolean): Record<string, string> | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Whether the challenge carries a per-issuance nonce (`_mpp_nonce`, or `_mppx_nonce` from
|
|
11
|
+
* earlier releases). Reads `opaque` when present, the value the challenge HMAC covers, and
|
|
12
|
+
* `meta` only otherwise.
|
|
13
|
+
*/
|
|
14
|
+
export declare function hasNonce(challenge: {
|
|
15
|
+
meta?: Record<string, string> | undefined;
|
|
16
|
+
opaque?: string | undefined;
|
|
17
|
+
}): boolean;
|
|
3
18
|
/** Sets the expiry grace marker when `grace` is true and removes any copy of it otherwise. */
|
|
4
19
|
export declare function withExpiryGrace(meta: Record<string, string> | undefined, grace: boolean): Record<string, string> | undefined;
|
|
5
20
|
/**
|