mppx 0.20.0 → 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 +31 -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 +148 -0
- package/dist/evm/server/Methods.d.ts +8 -0
- package/dist/evm/server/Methods.js +8 -0
- package/dist/extensions/identity/attestation/Issuer.d.ts +91 -0
- package/dist/extensions/identity/attestation/Issuer.js +159 -0
- package/dist/extensions/identity/attestation/Jwks.js +3 -3
- package/dist/extensions/identity/attestation/Token.js +7 -0
- package/dist/extensions/identity/attestation/Types.d.ts +31 -3
- package/dist/extensions/identity/attestation/index.d.ts +3 -1
- package/dist/extensions/identity/attestation/index.js +3 -1
- package/dist/extensions/identity/link/server/index.js +4 -4
- package/dist/extensions/identity/persona/server/index.js +3 -3
- package/dist/extensions/identity/tempo/Constants.d.ts +4 -0
- package/dist/extensions/identity/tempo/Constants.js +4 -0
- package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
- package/dist/extensions/identity/tempo/client/index.js +151 -0
- package/dist/extensions/identity/tempo/index.d.ts +1 -0
- package/dist/extensions/identity/tempo/index.js +1 -0
- package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
- package/dist/extensions/identity/tempo/issuer/index.js +183 -0
- 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/Headers.js +1 -0
- 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 +47 -15
- 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/Siwx.d.ts +270 -0
- package/dist/x402/Siwx.js +458 -0
- package/dist/x402/Types.d.ts +72 -12
- package/dist/x402/Types.js +18 -3
- package/dist/x402/client/Exact.js +4 -1
- package/dist/x402/index.d.ts +1 -0
- package/dist/x402/index.js +1 -0
- package/dist/x402/middlewares/express.js +10 -1
- package/dist/x402/server/EvmCharge.d.ts +27 -3
- package/dist/x402/server/EvmCharge.js +27 -2
- package/dist/x402/server/Facilitator.d.ts +42 -3
- package/dist/x402/server/Facilitator.js +126 -16
- package/package.json +1 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { MaybePromise } from '../../../../internal/types.js';
|
|
2
|
+
import type * as Store from '../../../../Store.js';
|
|
3
|
+
import * as Attestation from '../../attestation/Issuer.js';
|
|
4
|
+
import type { SigningKey } from '../../Types.js';
|
|
5
|
+
import { Constants } from '../Constants.js';
|
|
6
|
+
import type * as Types from '../Types.js';
|
|
7
|
+
/**
|
|
8
|
+
* Creates a Tempo ID attestation issuer: exchanges a signed-in user's Tempo ID access token for
|
|
9
|
+
* `Identity-Attestation` tokens that any MPP server verifies with `Attestation.Server.verifier`,
|
|
10
|
+
* like those of any other issuer.
|
|
11
|
+
*
|
|
12
|
+
* - `tempo-id`: `sub` is the user's Tempo ID user ID.
|
|
13
|
+
* - `email`: `sub` is the user's email address, only when the client sends an ID token
|
|
14
|
+
* (`Tempo-Id-Token`) and Tempo ID verified the address.
|
|
15
|
+
*
|
|
16
|
+
* Every attestation carries the user ID as `uid`, so a server can tell that attestations of
|
|
17
|
+
* several types name one user, and the app that exchanged the token as `azp`. The access token is checked as `TempoId.Server` checks it,
|
|
18
|
+
* including its DPoP proof, which the client signs for this endpoint.
|
|
19
|
+
*
|
|
20
|
+
* `handle` answers, relative to `url`:
|
|
21
|
+
* - `POST /tempo-id/attest` (`Constants.attestPath`) with `{ audience, type }`: `200`
|
|
22
|
+
* `{ attestation, expires_at }`; `400`, `401`, `403` or `503` `{ error }`.
|
|
23
|
+
* - `GET /.well-known/jwks.json`: the attestation key.
|
|
24
|
+
*
|
|
25
|
+
* Run it as a shared service many servers trust, or inside an app's own backend.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const issuer = TempoId.Issuer.create({
|
|
30
|
+
* clientId: 'app_…',
|
|
31
|
+
* signingKey,
|
|
32
|
+
* store,
|
|
33
|
+
* url: 'https://attest.example',
|
|
34
|
+
* })
|
|
35
|
+
* // In the fetch handler, before its routes:
|
|
36
|
+
* const answered = await issuer.handle(request)
|
|
37
|
+
* if (answered) return answered
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function create(config: create.Config): Issuer;
|
|
41
|
+
export declare namespace create {
|
|
42
|
+
type Config = {
|
|
43
|
+
/** This issuer's URL, which attestations carry as `iss`. */
|
|
44
|
+
readonly url: string;
|
|
45
|
+
/** Ed25519 key pair, or a remote Signer, that signs attestations. */
|
|
46
|
+
readonly signingKey: SigningKey;
|
|
47
|
+
/** Attestation types this issuer signs. @default ['tempo-id', 'email'] */
|
|
48
|
+
readonly types?: readonly Type[] | undefined;
|
|
49
|
+
/** Seconds each attestation is valid. @default 3600 */
|
|
50
|
+
readonly ttl?: number | undefined;
|
|
51
|
+
/** The app or apps whose access tokens may be exchanged. Required. */
|
|
52
|
+
readonly clientId: string | readonly string[];
|
|
53
|
+
/** Decides whether a verified user may get attestations. */
|
|
54
|
+
readonly allow?: ((user: Types.Payer) => MaybePromise<boolean>) | undefined;
|
|
55
|
+
/** Accepts each DPoP proof once. Required, so a captured proof cannot be exchanged again. */
|
|
56
|
+
readonly store: Store.AtomicStore;
|
|
57
|
+
/**
|
|
58
|
+
* The audience access tokens must name. Defaults to this issuer's `url`, so a token Tempo ID
|
|
59
|
+
* issued for another API cannot be exchanged here.
|
|
60
|
+
*/
|
|
61
|
+
readonly tokenAudience?: string | undefined;
|
|
62
|
+
/** Tempo ID's origin. @default 'https://id.tempo.xyz' */
|
|
63
|
+
readonly issuer?: string | undefined;
|
|
64
|
+
/** Fetch used for Tempo ID's keys. */
|
|
65
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
66
|
+
/** Chain whose accounts `allow` sees, such as Moderato `42431`. @default 4217 */
|
|
67
|
+
readonly chainId?: number | undefined;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** An attestation type a Tempo ID attestation issuer signs. */
|
|
71
|
+
export type Type = (typeof Constants.attestationTypes)[number];
|
|
72
|
+
/** A Tempo ID attestation issuer from {@link create}. */
|
|
73
|
+
export type Issuer = {
|
|
74
|
+
/** This issuer's URL, without a trailing slash. */
|
|
75
|
+
readonly issuer: string;
|
|
76
|
+
/** Resolves this issuer's key in process, for a server that runs beside it. */
|
|
77
|
+
readonly keyResolver: Attestation.Issuer['keyResolver'];
|
|
78
|
+
/** This issuer's JSON Web Key Set. */
|
|
79
|
+
readonly jwks: Attestation.Issuer['jwks'];
|
|
80
|
+
/** Answers the issuer's routes, and returns `undefined` for any other request. */
|
|
81
|
+
readonly handle: (request: Request) => Promise<Response | undefined>;
|
|
82
|
+
};
|
|
83
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import * as Attestation from '../../attestation/Issuer.js';
|
|
2
|
+
import { decode, isIssuer } from '../../attestation/Token.js';
|
|
3
|
+
import { Constants } from '../Constants.js';
|
|
4
|
+
import * as Server from '../server/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* Creates a Tempo ID attestation issuer: exchanges a signed-in user's Tempo ID access token for
|
|
7
|
+
* `Identity-Attestation` tokens that any MPP server verifies with `Attestation.Server.verifier`,
|
|
8
|
+
* like those of any other issuer.
|
|
9
|
+
*
|
|
10
|
+
* - `tempo-id`: `sub` is the user's Tempo ID user ID.
|
|
11
|
+
* - `email`: `sub` is the user's email address, only when the client sends an ID token
|
|
12
|
+
* (`Tempo-Id-Token`) and Tempo ID verified the address.
|
|
13
|
+
*
|
|
14
|
+
* Every attestation carries the user ID as `uid`, so a server can tell that attestations of
|
|
15
|
+
* several types name one user, and the app that exchanged the token as `azp`. The access token is checked as `TempoId.Server` checks it,
|
|
16
|
+
* including its DPoP proof, which the client signs for this endpoint.
|
|
17
|
+
*
|
|
18
|
+
* `handle` answers, relative to `url`:
|
|
19
|
+
* - `POST /tempo-id/attest` (`Constants.attestPath`) with `{ audience, type }`: `200`
|
|
20
|
+
* `{ attestation, expires_at }`; `400`, `401`, `403` or `503` `{ error }`.
|
|
21
|
+
* - `GET /.well-known/jwks.json`: the attestation key.
|
|
22
|
+
*
|
|
23
|
+
* Run it as a shared service many servers trust, or inside an app's own backend.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const issuer = TempoId.Issuer.create({
|
|
28
|
+
* clientId: 'app_…',
|
|
29
|
+
* signingKey,
|
|
30
|
+
* store,
|
|
31
|
+
* url: 'https://attest.example',
|
|
32
|
+
* })
|
|
33
|
+
* // In the fetch handler, before its routes:
|
|
34
|
+
* const answered = await issuer.handle(request)
|
|
35
|
+
* if (answered) return answered
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function create(config) {
|
|
39
|
+
const url = config.url.replace(/\/+$/, '');
|
|
40
|
+
if (!isIssuer(url) || /[?#]/.test(url))
|
|
41
|
+
throw new TypeError('Tempo ID attestation issuer url must be an https URL without a query or fragment.');
|
|
42
|
+
const types = config.types ?? Constants.attestationTypes;
|
|
43
|
+
for (const type of types)
|
|
44
|
+
if (!Constants.attestationTypes.includes(type))
|
|
45
|
+
throw new TypeError(`Tempo ID attestation issuer cannot sign type "${type}".`);
|
|
46
|
+
const attestation = Attestation.create({
|
|
47
|
+
issuer: url,
|
|
48
|
+
signingKey: config.signingKey,
|
|
49
|
+
ttl: config.ttl,
|
|
50
|
+
});
|
|
51
|
+
if (!config.store)
|
|
52
|
+
throw new TypeError('Tempo ID attestation issuer requires store, so each DPoP proof is accepted once.');
|
|
53
|
+
if (!config.clientId || (Array.isArray(config.clientId) && config.clientId.length === 0))
|
|
54
|
+
throw new TypeError('Tempo ID attestation issuer requires clientId: the apps that may exchange tokens.');
|
|
55
|
+
const tempoId = Server.create({
|
|
56
|
+
allow: config.allow,
|
|
57
|
+
chainId: config.chainId,
|
|
58
|
+
// Only tokens issued for this issuer: a token another API received cannot be exchanged here.
|
|
59
|
+
audience: config.tokenAudience ?? url,
|
|
60
|
+
clientId: config.clientId,
|
|
61
|
+
fetch: config.fetch,
|
|
62
|
+
issuer: config.issuer,
|
|
63
|
+
store: config.store,
|
|
64
|
+
});
|
|
65
|
+
const attestPath = new URL(url).pathname.replace(/\/+$/, '') + Constants.attestPath;
|
|
66
|
+
// DPoP proofs must name this issuer's configured endpoint, never one built from the Host header.
|
|
67
|
+
const attestUrl = new URL(url).origin + attestPath;
|
|
68
|
+
async function attest(request) {
|
|
69
|
+
const body = await readJson(request);
|
|
70
|
+
if (body === undefined)
|
|
71
|
+
return error(400, `The body must be JSON of at most ${maxBody} bytes.`);
|
|
72
|
+
const { audience, type } = (typeof body === 'object' && body !== null ? body : {});
|
|
73
|
+
if (typeof audience !== 'string' || audience.length > 2_048 || !isIssuer(audience))
|
|
74
|
+
return error(400, 'audience must be an https origin.');
|
|
75
|
+
if (typeof type !== 'string' || !types.includes(type))
|
|
76
|
+
return error(400, `type must be one of ${types.join(', ')}.`);
|
|
77
|
+
const verified = await tempoId.verifier.verify(new Request(attestUrl, { headers: request.headers, method: request.method }));
|
|
78
|
+
if (verified.status !== 'valid')
|
|
79
|
+
return error(statusCodes[verified.status], verified.reason ?? 'Sign in with Tempo ID.', {
|
|
80
|
+
...(verified.status === 'missing' || verified.status === 'invalid'
|
|
81
|
+
? Object.fromEntries(new Headers(verified.headers))
|
|
82
|
+
: {}),
|
|
83
|
+
});
|
|
84
|
+
const user = verified.value;
|
|
85
|
+
let sub;
|
|
86
|
+
if (type === 'email') {
|
|
87
|
+
if (!user.email || user.emailVerified !== true)
|
|
88
|
+
return error(403, 'Send an ID token naming an email address Tempo ID verified.');
|
|
89
|
+
sub = user.email;
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
sub = user.userId;
|
|
93
|
+
let token;
|
|
94
|
+
try {
|
|
95
|
+
token = await attestation.sign({
|
|
96
|
+
audience,
|
|
97
|
+
// The app that exchanged the token, so a server can restrict which apps it accepts.
|
|
98
|
+
claims: { azp: user.clientId },
|
|
99
|
+
sub,
|
|
100
|
+
type,
|
|
101
|
+
uid: user.userId,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (cause) {
|
|
105
|
+
// Bad input is the caller's to fix; anything else is the signer's outage, worth a retry.
|
|
106
|
+
if (cause instanceof Attestation.InvalidParametersError)
|
|
107
|
+
return error(400, 'The attestation cannot be signed for this request.');
|
|
108
|
+
return error(503, 'The attestation signer is unavailable.', { 'Retry-After': '5' });
|
|
109
|
+
}
|
|
110
|
+
const exp = decode(token)?.claims.exp;
|
|
111
|
+
if (typeof exp !== 'number')
|
|
112
|
+
return error(400, 'The attestation cannot be signed for this request.');
|
|
113
|
+
return Response.json({ attestation: token, expires_at: new Date(exp * 1_000).toISOString() }, { headers: { ...cors, 'Cache-Control': 'no-store' } });
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
issuer: url,
|
|
117
|
+
keyResolver: attestation.keyResolver,
|
|
118
|
+
jwks: attestation.jwks,
|
|
119
|
+
async handle(request) {
|
|
120
|
+
const { pathname } = new URL(request.url);
|
|
121
|
+
if (pathname === attestPath) {
|
|
122
|
+
if (request.method === 'OPTIONS')
|
|
123
|
+
return new Response(null, {
|
|
124
|
+
status: 204,
|
|
125
|
+
headers: {
|
|
126
|
+
...cors,
|
|
127
|
+
'Access-Control-Allow-Headers': 'authorization, content-type, dpop, tempo-id-token',
|
|
128
|
+
'Access-Control-Allow-Methods': 'POST',
|
|
129
|
+
'Access-Control-Max-Age': '600',
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
if (request.method !== 'POST')
|
|
133
|
+
return error(405, 'Use POST.', { Allow: 'POST' });
|
|
134
|
+
return attest(request);
|
|
135
|
+
}
|
|
136
|
+
return attestation.handle(request);
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
const cors = { 'Access-Control-Allow-Origin': '*' };
|
|
141
|
+
/** The largest request body the issuer reads, in bytes. */
|
|
142
|
+
const maxBody = 4_096;
|
|
143
|
+
/**
|
|
144
|
+
* Reads a JSON body of at most {@link maxBody} bytes before anything else runs, cancelling the
|
|
145
|
+
* stream once it is over, or returns `undefined`.
|
|
146
|
+
*/
|
|
147
|
+
async function readJson(request) {
|
|
148
|
+
if (Number(request.headers.get('content-length') ?? 0) > maxBody)
|
|
149
|
+
return undefined;
|
|
150
|
+
if (!request.body)
|
|
151
|
+
return undefined;
|
|
152
|
+
const reader = request.body.getReader();
|
|
153
|
+
const chunks = [];
|
|
154
|
+
let size = 0;
|
|
155
|
+
try {
|
|
156
|
+
while (true) {
|
|
157
|
+
const { done, value } = await reader.read();
|
|
158
|
+
if (done)
|
|
159
|
+
break;
|
|
160
|
+
size += value.byteLength;
|
|
161
|
+
if (size > maxBody) {
|
|
162
|
+
reader.cancel().catch(() => { });
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
chunks.push(value);
|
|
166
|
+
}
|
|
167
|
+
const bytes = new Uint8Array(size);
|
|
168
|
+
let offset = 0;
|
|
169
|
+
for (const chunk of chunks) {
|
|
170
|
+
bytes.set(chunk, offset);
|
|
171
|
+
offset += chunk.byteLength;
|
|
172
|
+
}
|
|
173
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
return undefined;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const statusCodes = { missing: 401, invalid: 401, forbidden: 403, unavailable: 503 };
|
|
180
|
+
function error(status, message, headers = {}) {
|
|
181
|
+
return Response.json({ error: message }, { status, headers: { ...cors, ...headers } });
|
|
182
|
+
}
|
|
183
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -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
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import * as Challenge from '../../Challenge.js';
|
|
2
|
+
import * as PendingSettlement from '../../client/internal/PendingSettlement.js';
|
|
2
3
|
import * as ProofRealm from '../../client/internal/ProofRealm.js';
|
|
3
4
|
import { adapterPaymentMetaKey } from '../../client/internal/protocols/Mcp.js';
|
|
4
5
|
import * as Credential from '../../Credential.js';
|
|
5
6
|
import * as Expires from '../../Expires.js';
|
|
6
7
|
import * as AcceptPayment from '../../internal/AcceptPayment.js';
|
|
7
8
|
import * as core_Mcp from '../../Mcp.js';
|
|
8
|
-
import * as z from '../../zod.js';
|
|
9
9
|
const MPPX_MCP_CLIENT_WRAPPER = Symbol.for('mppx.mcp.client.wrapper');
|
|
10
10
|
const maxPaymentAttempts = 3;
|
|
11
11
|
/**
|
|
@@ -73,10 +73,6 @@ export function wrap(client, config) {
|
|
|
73
73
|
});
|
|
74
74
|
return target;
|
|
75
75
|
}
|
|
76
|
-
/** Minimal wire shape of payment-required data; challenges are validated, extra fields pass through. */
|
|
77
|
-
const PaymentRequiredSchema = z.object({
|
|
78
|
-
challenges: z.array(Challenge.Schema).check(z.minLength(1)),
|
|
79
|
-
});
|
|
80
76
|
/**
|
|
81
77
|
* Checks if an error is a payment required error.
|
|
82
78
|
*/
|
|
@@ -92,17 +88,20 @@ export function isPaymentRequiredError(error) {
|
|
|
92
88
|
}
|
|
93
89
|
/** @internal */
|
|
94
90
|
async function createCredential(challenge, config) {
|
|
95
|
-
const { context, method } = config;
|
|
91
|
+
const { context, method, signal } = config;
|
|
96
92
|
if (challenge.expires)
|
|
97
93
|
Expires.assert(challenge.expires, challenge.id);
|
|
98
94
|
const parsedContext = method.context && context !== undefined ? method.context.parse(context) : undefined;
|
|
99
|
-
|
|
95
|
+
// A Zone withdrawal still settling is resumed for this challenge, not paid again.
|
|
96
|
+
return PendingSettlement.resume(() => method.createCredential(parsedContext !== undefined
|
|
97
|
+
? { challenge, context: parsedContext }
|
|
98
|
+
: { challenge }), { attempts: maxPaymentAttempts, signal });
|
|
100
99
|
}
|
|
101
100
|
function createPaymentAwareCallTool(callTool, config) {
|
|
102
101
|
const methods = config.methods.flat();
|
|
103
102
|
const paymentPreferences = AcceptPayment.resolve(methods, config.paymentPreferences);
|
|
104
103
|
const retryWithPayment = async (params, call, paymentRequired, cause, attemptsRemaining = maxPaymentAttempts) => {
|
|
105
|
-
const challenges = paymentRequired.challenges;
|
|
104
|
+
const challenges = usableChallenges(paymentRequired.challenges);
|
|
106
105
|
const candidates = AcceptPayment.selectChallengeCandidates(challenges, methods, paymentPreferences.entries, call.context);
|
|
107
106
|
const orderedCandidates = config.orderChallenges
|
|
108
107
|
? await config.orderChallenges(candidates)
|
|
@@ -111,7 +110,7 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
111
110
|
if (!selected) {
|
|
112
111
|
const available = challenges.map((challenge) => `${challenge.method}.${challenge.intent}`);
|
|
113
112
|
const installed = methods.map((method) => `${method.name}.${method.intent}`);
|
|
114
|
-
throw new Error(`No compatible payment method. Server offers: ${available.join(', ')}. Client has: ${installed.join(', ')}`, { cause });
|
|
113
|
+
throw new Error(Challenge.withSkippedChallenges(`No compatible payment method. Server offers: ${available.join(', ')}. Client has: ${installed.join(', ')}`, paymentRequired.challenges.length - challenges.length), { cause });
|
|
115
114
|
}
|
|
116
115
|
if (selected.challenge.expires)
|
|
117
116
|
Expires.assert(selected.challenge.expires, selected.challenge.id);
|
|
@@ -124,6 +123,7 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
124
123
|
const credential = await createCredential(selected.challenge, {
|
|
125
124
|
context: call.context,
|
|
126
125
|
method: selected.method,
|
|
126
|
+
signal: call.requestOptions?.signal,
|
|
127
127
|
});
|
|
128
128
|
const parsed = Credential.deserialize(credential);
|
|
129
129
|
try {
|
|
@@ -164,8 +164,27 @@ function getPaymentRequiredMeta(result) {
|
|
|
164
164
|
const data = result._meta?.[core_Mcp.paymentRequiredMetaKey];
|
|
165
165
|
return isPaymentRequiredData(data) ? data : undefined;
|
|
166
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* Validates payment-required data: challenges are validated, extra fields pass through. A
|
|
169
|
+
* well-formed challenge that selects an unsupported credential header is allowed here and skipped
|
|
170
|
+
* when paying.
|
|
171
|
+
*/
|
|
167
172
|
function isPaymentRequiredData(value) {
|
|
168
|
-
|
|
173
|
+
if (typeof value !== 'object' || value === null)
|
|
174
|
+
return false;
|
|
175
|
+
const { challenges } = value;
|
|
176
|
+
if (!Array.isArray(challenges) || challenges.length === 0)
|
|
177
|
+
return false;
|
|
178
|
+
return challenges.every((challenge) => Challenge.LenientSchema.safeParse(challenge).success);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Returns the challenges a client may pay: a challenge that selects an unsupported credential
|
|
182
|
+
* header gets no credential, but does not stop the client from paying another challenge.
|
|
183
|
+
*/
|
|
184
|
+
function usableChallenges(challenges) {
|
|
185
|
+
return challenges.flatMap((challenge) => Challenge.hasUnsupportedCredentialHeader(challenge)
|
|
186
|
+
? []
|
|
187
|
+
: [Challenge.Schema.parse(challenge)]);
|
|
169
188
|
}
|
|
170
189
|
function withReceipt(result) {
|
|
171
190
|
return {
|
|
@@ -21,8 +21,13 @@ export declare namespace Mppx {
|
|
|
21
21
|
* })
|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
|
-
function create<const methods extends Mppx_core.Methods>(config: Mppx_core.create.Config<methods>): Mppx_internal.Wrap<Mppx_core.Mppx<methods>, RequestHandler>;
|
|
24
|
+
function create<const methods extends Mppx_core.Methods>(config: Mppx_core.create.Config<methods> & AdapterOptions): Mppx_internal.Wrap<Mppx_core.Mppx<methods>, RequestHandler>;
|
|
25
25
|
}
|
|
26
|
+
/** Optional ingress validation shared by Express payment handlers. */
|
|
27
|
+
export type AdapterOptions = {
|
|
28
|
+
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it. Omitted preserves existing behavior; an empty list rejects all hosts. Configure trusted ingress to enforce the same list. */
|
|
29
|
+
allowedHosts?: readonly string[] | undefined;
|
|
30
|
+
};
|
|
26
31
|
/**
|
|
27
32
|
* Express middleware that gates a route behind a payment intent.
|
|
28
33
|
*
|
|
@@ -43,7 +48,7 @@ export declare namespace Mppx {
|
|
|
43
48
|
* })
|
|
44
49
|
* ```
|
|
45
50
|
*/
|
|
46
|
-
export declare function payment<const intent extends Mppx_internal.AnyMethodFn>(intent: intent, options: intent extends (options: infer options) => any ? options : never): RequestHandler;
|
|
51
|
+
export declare function payment<const intent extends Mppx_internal.AnyMethodFn>(intent: intent, options: intent extends (options: infer options) => any ? options : never, adapterOptions?: AdapterOptions): RequestHandler;
|
|
47
52
|
export type DiscoveryConfig = Omit<GenerateConfig, 'routes'> & {
|
|
48
53
|
path?: string;
|
|
49
54
|
routes?: RouteConfig[];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { generate } from '../discovery/OpenApi.js';
|
|
2
|
+
import * as Host from '../server/internal/host.js';
|
|
2
3
|
import * as Scope from '../server/internal/scope.js';
|
|
3
4
|
import * as Mppx_core from '../server/Mppx.js';
|
|
4
5
|
import * as ExpressAdapter from './internal/express.js';
|
|
@@ -24,7 +25,7 @@ export var Mppx;
|
|
|
24
25
|
* ```
|
|
25
26
|
*/
|
|
26
27
|
function create(config) {
|
|
27
|
-
return Mppx_internal.wrap(Mppx_core.create(config), payment);
|
|
28
|
+
return Mppx_internal.wrap(Mppx_core.create(config), (method, options) => payment(method, options, config));
|
|
28
29
|
}
|
|
29
30
|
Mppx.create = create;
|
|
30
31
|
})(Mppx || (Mppx = {}));
|
|
@@ -48,9 +49,24 @@ export var Mppx;
|
|
|
48
49
|
* })
|
|
49
50
|
* ```
|
|
50
51
|
*/
|
|
51
|
-
export function payment(intent, options) {
|
|
52
|
+
export function payment(intent, options, adapterOptions = {}) {
|
|
52
53
|
return async (req, res, next) => {
|
|
53
|
-
const
|
|
54
|
+
const protocol = req.protocol.toLowerCase();
|
|
55
|
+
if (!Host.isAllowed(req, adapterOptions.allowedHosts, req.get('host')) ||
|
|
56
|
+
(adapterOptions.allowedHosts !== undefined && protocol !== 'http' && protocol !== 'https')) {
|
|
57
|
+
res.status(421).send('Misdirected Request');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
let rawRequest;
|
|
61
|
+
try {
|
|
62
|
+
rawRequest = ExpressAdapter.toRequest(req, protocol);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (!(error instanceof ExpressAdapter.InvalidRequestTargetError))
|
|
66
|
+
throw error;
|
|
67
|
+
res.status(400).send('Bad Request');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
54
70
|
const routePath = typeof req.route?.path === 'string' ? req.route.path : req.path;
|
|
55
71
|
const request = options.scope === undefined && Scope.read(options.meta) === undefined
|
|
56
72
|
? Scope.attach(rawRequest, `${req.method.toUpperCase()} ${req.baseUrl}${routePath}`)
|
|
@@ -81,26 +97,7 @@ export function payment(intent, options) {
|
|
|
81
97
|
res.send(Buffer.from(await managementResponse.arrayBuffer()));
|
|
82
98
|
return;
|
|
83
99
|
}
|
|
84
|
-
|
|
85
|
-
res.json = (body) => {
|
|
86
|
-
const originalSend = res.send;
|
|
87
|
-
// Let Express serialize with the application's replacer, spacing, and
|
|
88
|
-
// escaping settings, but defer sending until the payment transport wraps it.
|
|
89
|
-
res.send = (serialized) => {
|
|
90
|
-
const response = new Response([204, 205, 304].includes(res.statusCode) ? null : serialized, { status: res.statusCode, headers: { 'Content-Type': res.get('Content-Type') } });
|
|
91
|
-
void Promise.resolve()
|
|
92
|
-
.then(() => result.withReceipt(response))
|
|
93
|
-
.then((wrapped) => ExpressAdapter.sendResponse(res, wrapped))
|
|
94
|
-
.catch(next);
|
|
95
|
-
return res;
|
|
96
|
-
};
|
|
97
|
-
try {
|
|
98
|
-
return originalJson.call(res, body);
|
|
99
|
-
}
|
|
100
|
-
finally {
|
|
101
|
-
res.send = originalSend;
|
|
102
|
-
}
|
|
103
|
-
};
|
|
100
|
+
ExpressAdapter.wrapResponse(res, (response) => result.withReceipt(response), next);
|
|
104
101
|
next();
|
|
105
102
|
};
|
|
106
103
|
}
|
|
@@ -3,6 +3,14 @@ import type { Request as ExpressRequest, Response as ExpressResponse } from 'exp
|
|
|
3
3
|
export declare function copyHeaders(response: ExpressResponse, headers: Headers): void;
|
|
4
4
|
/** Sends a Fetch response through Express without changing its status, headers, or bytes. */
|
|
5
5
|
export declare function sendResponse(response: ExpressResponse, fetchResponse: Response): Promise<ExpressResponse<any, Record<string, any>>>;
|
|
6
|
+
export declare class InvalidRequestTargetError extends Error {
|
|
7
|
+
}
|
|
6
8
|
/** Converts an Express parsed request into the Fetch request consumed by mppx core. */
|
|
7
|
-
export declare function toRequest(request: ExpressRequest): Request;
|
|
9
|
+
export declare function toRequest(request: ExpressRequest, protocol?: string): Request;
|
|
10
|
+
/**
|
|
11
|
+
* Gates every Express output path through the payment transport before sending
|
|
12
|
+
* headers or bytes. The bounded stream preserves pipe backpressure while the
|
|
13
|
+
* transport validates and meters the response.
|
|
14
|
+
*/
|
|
15
|
+
export declare function wrapResponse(response: ExpressResponse, withReceipt: (response: Response) => Response | Promise<Response>, onError: (error: unknown) => void): void;
|
|
8
16
|
//# sourceMappingURL=express.d.ts.map
|