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
|
@@ -1,11 +1,39 @@
|
|
|
1
|
-
import { Secp256k1 } from 'ox';
|
|
1
|
+
import { Base64, Secp256k1 } from 'ox';
|
|
2
2
|
import * as PaymentRequest from '../PaymentRequest.js';
|
|
3
3
|
/** Reserved metadata key for HMAC-bound, per-issuance challenge randomness. */
|
|
4
|
-
const nonceKey = '
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
export const nonceKey = '_mpp_nonce';
|
|
5
|
+
/** Nonce key of earlier mppx releases: still ignored when comparing route metadata. */
|
|
6
|
+
const legacyNonceKey = '_mppx_nonce';
|
|
7
|
+
/**
|
|
8
|
+
* Adds fresh issuance randomness (16 random bytes, base64url without padding) under
|
|
9
|
+
* `_mpp_nonce` while preserving application and route metadata. With `enabled: false`,
|
|
10
|
+
* returns the metadata unchanged.
|
|
11
|
+
*/
|
|
12
|
+
export function withNonce(meta, enabled = true) {
|
|
13
|
+
if (!enabled)
|
|
14
|
+
return meta;
|
|
15
|
+
// Ox's key generation uses runtime-specific secure randomness, including Node without global
|
|
16
|
+
// Web Crypto; 16 of its 32 uniformly random bytes make the nonce.
|
|
17
|
+
const random = Secp256k1.randomPrivateKey({ as: 'Bytes' }).slice(0, 16);
|
|
18
|
+
const nonce = Base64.fromBytes(random, { url: true, pad: false });
|
|
19
|
+
return { ...meta, [nonceKey]: nonce };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Whether the challenge carries a per-issuance nonce (`_mpp_nonce`, or `_mppx_nonce` from
|
|
23
|
+
* earlier releases). Reads `opaque` when present, the value the challenge HMAC covers, and
|
|
24
|
+
* `meta` only otherwise.
|
|
25
|
+
*/
|
|
26
|
+
export function hasNonce(challenge) {
|
|
27
|
+
const { meta, opaque } = challenge;
|
|
28
|
+
const has = (value) => typeof value?.[nonceKey] === 'string' || typeof value?.[legacyNonceKey] === 'string';
|
|
29
|
+
if (opaque === undefined)
|
|
30
|
+
return has(meta);
|
|
31
|
+
try {
|
|
32
|
+
return has(PaymentRequest.deserialize(opaque));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
9
37
|
}
|
|
10
38
|
/**
|
|
11
39
|
* Reserved metadata key marking a challenge whose method accepts some of its credentials for a
|
|
@@ -40,7 +68,7 @@ export function hasExpiryGrace(challenge) {
|
|
|
40
68
|
const legacyIdentityKey = '_mppx_identity';
|
|
41
69
|
/** Removes issuance-only metadata when comparing stable route requirements. */
|
|
42
70
|
export function routeMeta(meta) {
|
|
43
|
-
const { [nonceKey]: _, [
|
|
71
|
+
const { [nonceKey]: _, [legacyNonceKey]: __, [legacyIdentityKey]: ___, [expiryGraceKey]: ____, ...rest } = meta ?? {};
|
|
44
72
|
return Object.keys(rest).length ? rest : undefined;
|
|
45
73
|
}
|
|
46
74
|
//# sourceMappingURL=challengeMeta.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Current mppx package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.22.1";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.22.1";
|
|
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.22.1';
|
|
4
4
|
/** Canonical SDK identifier for this mppx release. */
|
|
5
5
|
export const sdkIdentifier = `mppx/${version}`;
|
|
6
6
|
//# sourceMappingURL=version.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
2
|
import type { McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
3
3
|
import * as Challenge from '../../Challenge.js';
|
|
4
|
+
import * as SpendGate from '../../client/internal/SpendGate.js';
|
|
4
5
|
import * as AcceptPayment from '../../internal/AcceptPayment.js';
|
|
5
6
|
import * as core_Mcp from '../../Mcp.js';
|
|
6
7
|
import type * as Method from '../../Method.js';
|
|
@@ -35,6 +36,10 @@ export type CallToolResult = Awaited<ReturnType<Client['callTool']>> & {
|
|
|
35
36
|
* errors or as tool results carrying payment-required metadata. Calling
|
|
36
37
|
* `wrap()` again replaces the payment configuration.
|
|
37
38
|
*
|
|
39
|
+
* `maxPayment`, `authorize`, `funders` and `tokens` limit its payments as they do on
|
|
40
|
+
* `Mppx.create`. Set them here: an mppx fetch with spending options refuses the tool calls this
|
|
41
|
+
* client pays itself.
|
|
42
|
+
*
|
|
38
43
|
* @example
|
|
39
44
|
* ```ts
|
|
40
45
|
* import { Client } from '@modelcontextprotocol/sdk/client'
|
|
@@ -74,7 +79,7 @@ export declare namespace wrap {
|
|
|
74
79
|
* own a realm, so these signatures are refused unless their realm is listed here.
|
|
75
80
|
*/
|
|
76
81
|
trustedTempoProofRealms?: readonly string[] | undefined;
|
|
77
|
-
};
|
|
82
|
+
} & SpendGate.Config;
|
|
78
83
|
type McpClient<client extends Pick<Client, 'callTool'> = Pick<Client, 'callTool'>, methods extends Methods = DefaultMethods> = Omit<client, 'callTool'> & {
|
|
79
84
|
/** Call a tool with automatic payment handling. Preserves the MCP SDK signature. */
|
|
80
85
|
callTool: (params: CallToolParams, resultSchema?: CallToolResultSchema, options?: CallToolOptions<methods>) => Promise<CallToolResult>;
|
|
@@ -2,6 +2,8 @@ import * as Challenge from '../../Challenge.js';
|
|
|
2
2
|
import * as PendingSettlement from '../../client/internal/PendingSettlement.js';
|
|
3
3
|
import * as ProofRealm from '../../client/internal/ProofRealm.js';
|
|
4
4
|
import { adapterPaymentMetaKey } from '../../client/internal/protocols/Mcp.js';
|
|
5
|
+
import * as SpendGate from '../../client/internal/SpendGate.js';
|
|
6
|
+
import * as SpendHooks from '../../client/internal/SpendHooks.js';
|
|
5
7
|
import * as Credential from '../../Credential.js';
|
|
6
8
|
import * as Expires from '../../Expires.js';
|
|
7
9
|
import * as AcceptPayment from '../../internal/AcceptPayment.js';
|
|
@@ -22,6 +24,10 @@ const maxPaymentAttempts = 3;
|
|
|
22
24
|
* errors or as tool results carrying payment-required metadata. Calling
|
|
23
25
|
* `wrap()` again replaces the payment configuration.
|
|
24
26
|
*
|
|
27
|
+
* `maxPayment`, `authorize`, `funders` and `tokens` limit its payments as they do on
|
|
28
|
+
* `Mppx.create`. Set them here: an mppx fetch with spending options refuses the tool calls this
|
|
29
|
+
* client pays itself.
|
|
30
|
+
*
|
|
25
31
|
* @example
|
|
26
32
|
* ```ts
|
|
27
33
|
* import { Client } from '@modelcontextprotocol/sdk/client'
|
|
@@ -88,18 +94,23 @@ export function isPaymentRequiredError(error) {
|
|
|
88
94
|
}
|
|
89
95
|
/** @internal */
|
|
90
96
|
async function createCredential(challenge, config) {
|
|
91
|
-
const { context, method, signal } = config;
|
|
97
|
+
const { constraints, context, method, signal } = config;
|
|
92
98
|
if (challenge.expires)
|
|
93
99
|
Expires.assert(challenge.expires, challenge.id);
|
|
94
100
|
const parsedContext = method.context && context !== undefined ? method.context.parse(context) : undefined;
|
|
95
101
|
// A Zone withdrawal still settling is resumed for this challenge, not paid again.
|
|
96
|
-
return PendingSettlement.resume(() =>
|
|
97
|
-
? { challenge, context: parsedContext }
|
|
98
|
-
|
|
102
|
+
return PendingSettlement.resume(() => {
|
|
103
|
+
const parameters = parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge };
|
|
104
|
+
if (constraints)
|
|
105
|
+
SpendHooks.constrain(parameters, constraints);
|
|
106
|
+
return method.createCredential(parameters);
|
|
107
|
+
}, { attempts: maxPaymentAttempts, signal });
|
|
99
108
|
}
|
|
100
109
|
function createPaymentAwareCallTool(callTool, config) {
|
|
101
110
|
const methods = config.methods.flat();
|
|
102
111
|
const paymentPreferences = AcceptPayment.resolve(methods, config.paymentPreferences);
|
|
112
|
+
// Validated here, so invalid spending options fail at `wrap()`.
|
|
113
|
+
const spender = SpendGate.from(SpendGate.pick(config));
|
|
103
114
|
const retryWithPayment = async (params, call, paymentRequired, cause, attemptsRemaining = maxPaymentAttempts) => {
|
|
104
115
|
const challenges = usableChallenges(paymentRequired.challenges);
|
|
105
116
|
const candidates = AcceptPayment.selectChallengeCandidates(challenges, methods, paymentPreferences.entries, call.context);
|
|
@@ -120,11 +131,23 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
120
131
|
if (!approved)
|
|
121
132
|
throw new Error('Payment declined.', { cause });
|
|
122
133
|
}
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
134
|
+
const signal = call.requestOptions?.signal;
|
|
135
|
+
// Spending limits, authorization and funding run before any signing work.
|
|
136
|
+
const spend = SpendGate.payment(spender, selected.challenge, signal, selected.method);
|
|
137
|
+
let credential;
|
|
138
|
+
try {
|
|
139
|
+
credential = await spend.track((constraints) => createCredential(selected.challenge, {
|
|
140
|
+
constraints,
|
|
141
|
+
context: call.context,
|
|
142
|
+
method: selected.method,
|
|
143
|
+
signal,
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
// A no-op once the credential committed it.
|
|
148
|
+
await spend.release();
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
128
151
|
const parsed = Credential.deserialize(credential);
|
|
129
152
|
try {
|
|
130
153
|
const retryResult = await callTool({
|
|
@@ -135,6 +158,10 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
135
158
|
},
|
|
136
159
|
}, call.resultSchema, call.requestOptions);
|
|
137
160
|
const nextPaymentRequired = getPaymentRequiredMeta(retryResult);
|
|
161
|
+
// invalid-challenge answering the credential just sent can mean it was already settled
|
|
162
|
+
// (a replay): paying the fresh Challenge would pay twice, so the result is final.
|
|
163
|
+
if (nextPaymentRequired && isInvalidChallenge(nextPaymentRequired))
|
|
164
|
+
return withReceipt(retryResult);
|
|
138
165
|
if (nextPaymentRequired && attemptsRemaining > 1)
|
|
139
166
|
return retryWithPayment(params, call, nextPaymentRequired, retryResult, attemptsRemaining - 1);
|
|
140
167
|
return withReceipt(retryResult);
|
|
@@ -142,20 +169,26 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
142
169
|
catch (error) {
|
|
143
170
|
if (!isPaymentRequiredError(error) || attemptsRemaining <= 1)
|
|
144
171
|
throw error;
|
|
172
|
+
if (isInvalidChallenge(error.data))
|
|
173
|
+
throw error;
|
|
145
174
|
return retryWithPayment(params, call, error.data, error, attemptsRemaining - 1);
|
|
146
175
|
}
|
|
147
176
|
};
|
|
148
177
|
return async (params, call) => {
|
|
178
|
+
// A credential the caller attached to the first call gets the same no-repay rule.
|
|
179
|
+
const credentialSent = params._meta?.[core_Mcp.credentialMetaKey] != null;
|
|
149
180
|
try {
|
|
150
181
|
const result = await callTool(params, call.resultSchema, call.requestOptions);
|
|
151
182
|
const paymentRequired = getPaymentRequiredMeta(result);
|
|
152
|
-
if (paymentRequired)
|
|
183
|
+
if (paymentRequired && !(credentialSent && isInvalidChallenge(paymentRequired)))
|
|
153
184
|
return retryWithPayment(params, call, paymentRequired, result);
|
|
154
185
|
return withReceipt(result);
|
|
155
186
|
}
|
|
156
187
|
catch (error) {
|
|
157
188
|
if (!isPaymentRequiredError(error))
|
|
158
189
|
throw error;
|
|
190
|
+
if (credentialSent && isInvalidChallenge(error.data))
|
|
191
|
+
throw error;
|
|
159
192
|
return retryWithPayment(params, call, error.data, error);
|
|
160
193
|
}
|
|
161
194
|
};
|
|
@@ -164,6 +197,11 @@ function getPaymentRequiredMeta(result) {
|
|
|
164
197
|
const data = result._meta?.[core_Mcp.paymentRequiredMetaKey];
|
|
165
198
|
return isPaymentRequiredData(data) ? data : undefined;
|
|
166
199
|
}
|
|
200
|
+
/** Whether payment-required data carries an invalid-challenge problem (such as a replayed credential). */
|
|
201
|
+
function isInvalidChallenge(data) {
|
|
202
|
+
return (data.problem?.type ===
|
|
203
|
+
'https://paymentauth.org/problems/invalid-challenge');
|
|
204
|
+
}
|
|
167
205
|
/**
|
|
168
206
|
* Validates payment-required data: challenges are validated, extra fields pass through. A
|
|
169
207
|
* well-formed challenge that selects an unsupported credential header is allowed here and skipped
|
package/dist/proxy/Proxy.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as Credential from '../Credential.js';
|
|
2
|
+
import * as Metadata from '../discovery/internal/Metadata.js';
|
|
2
3
|
import { generateProxy } from '../discovery/OpenApi.js';
|
|
3
4
|
import * as Scope from '../server/internal/scope.js';
|
|
4
5
|
import * as Mppx from '../server/Mppx.js';
|
|
@@ -40,6 +41,16 @@ export function create(config) {
|
|
|
40
41
|
throw new RangeError('maxRequestBodySize must be a non-negative safe integer');
|
|
41
42
|
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
42
43
|
const replay = config.replay ? Replay.resolve(config.replay) : undefined;
|
|
44
|
+
const strip = stripHeadersOf(config.services);
|
|
45
|
+
/** Forwards a request to a service's upstream, with the proxy's header stripping and retries. */
|
|
46
|
+
const forward = (service, proxy, request, ctx) => proxyUpstream({
|
|
47
|
+
ctx,
|
|
48
|
+
onUpstreamError: service.onUpstreamError ?? config.onUpstreamError,
|
|
49
|
+
proxy,
|
|
50
|
+
request,
|
|
51
|
+
service,
|
|
52
|
+
strip,
|
|
53
|
+
});
|
|
43
54
|
const services = new Map(config.services.map((s) => {
|
|
44
55
|
const proxy = createFetchProxy(s.baseUrl, { fetch: fetchImpl });
|
|
45
56
|
return [s.id, { service: s, proxy }];
|
|
@@ -121,13 +132,7 @@ export function create(config) {
|
|
|
121
132
|
}
|
|
122
133
|
const ctx = { request, service, upstreamPath };
|
|
123
134
|
if (!handler)
|
|
124
|
-
return
|
|
125
|
-
request,
|
|
126
|
-
service,
|
|
127
|
-
ctx: { ...ctx, ...Service.getOptions(endpoint) },
|
|
128
|
-
proxy,
|
|
129
|
-
onUpstreamError: service.onUpstreamError ?? config.onUpstreamError,
|
|
130
|
-
});
|
|
135
|
+
return forward(service, proxy, request, { ...ctx, ...Service.getOptions(endpoint) });
|
|
131
136
|
let selected;
|
|
132
137
|
try {
|
|
133
138
|
selected = paymentCredential ? Credential.deserialize(paymentCredential) : undefined;
|
|
@@ -190,13 +195,7 @@ export function create(config) {
|
|
|
190
195
|
run: (signal) => {
|
|
191
196
|
// Send the headers of the request that was paid for, not the retry's.
|
|
192
197
|
const upstream = Replay.withBody(paidRequest, body, signal, found.requestHeaders);
|
|
193
|
-
return
|
|
194
|
-
request: upstream,
|
|
195
|
-
service,
|
|
196
|
-
ctx: { ...ctx, request: upstream, ...options },
|
|
197
|
-
proxy,
|
|
198
|
-
onUpstreamError: service.onUpstreamError ?? config.onUpstreamError,
|
|
199
|
-
});
|
|
198
|
+
return forward(service, proxy, upstream, { ...ctx, request: upstream, ...options });
|
|
200
199
|
},
|
|
201
200
|
});
|
|
202
201
|
}
|
|
@@ -241,26 +240,14 @@ export function create(config) {
|
|
|
241
240
|
attempts: 1,
|
|
242
241
|
replay,
|
|
243
242
|
replayKey,
|
|
244
|
-
requestHeaders: [...Headers.scrub(paidRequest.headers).entries()],
|
|
243
|
+
requestHeaders: [...Headers.scrub(paidRequest.headers, strip).entries()],
|
|
245
244
|
run: (signal) => {
|
|
246
245
|
const upstream = Replay.withBody(paidRequest, body, signal);
|
|
247
|
-
return
|
|
248
|
-
request: upstream,
|
|
249
|
-
service,
|
|
250
|
-
ctx: { ...ctx, request: upstream, ...options },
|
|
251
|
-
proxy,
|
|
252
|
-
onUpstreamError: service.onUpstreamError ?? config.onUpstreamError,
|
|
253
|
-
});
|
|
246
|
+
return forward(service, proxy, upstream, { ...ctx, request: upstream, ...options });
|
|
254
247
|
},
|
|
255
248
|
});
|
|
256
249
|
}
|
|
257
|
-
const upstreamRes = await
|
|
258
|
-
request,
|
|
259
|
-
service,
|
|
260
|
-
ctx: { ...ctx, ...options },
|
|
261
|
-
proxy,
|
|
262
|
-
onUpstreamError: service.onUpstreamError ?? config.onUpstreamError,
|
|
263
|
-
});
|
|
250
|
+
const upstreamRes = await forward(service, proxy, request, { ...ctx, ...options });
|
|
264
251
|
return result.withReceipt(upstreamRes);
|
|
265
252
|
}
|
|
266
253
|
return {
|
|
@@ -270,9 +257,9 @@ export function create(config) {
|
|
|
270
257
|
}
|
|
271
258
|
/** @internal */
|
|
272
259
|
async function proxyUpstream(options) {
|
|
273
|
-
const { request, service, ctx, proxy, onUpstreamError } = options;
|
|
260
|
+
const { request, service, ctx, proxy, onUpstreamError, strip } = options;
|
|
274
261
|
const url = ctx.upstreamPath + new URL(request.url).search;
|
|
275
|
-
const headers = Headers.scrub(request.headers);
|
|
262
|
+
const headers = Headers.scrub(request.headers, strip);
|
|
276
263
|
const method = request.method.toUpperCase();
|
|
277
264
|
const hasBody = method !== 'GET' && method !== 'HEAD';
|
|
278
265
|
const init = {
|
|
@@ -290,6 +277,7 @@ async function proxyUpstream(options) {
|
|
|
290
277
|
ctx,
|
|
291
278
|
proxy,
|
|
292
279
|
service,
|
|
280
|
+
strip,
|
|
293
281
|
upstreamRequest,
|
|
294
282
|
});
|
|
295
283
|
for (let attempt = 1;; attempt++) {
|
|
@@ -297,6 +285,7 @@ async function proxyUpstream(options) {
|
|
|
297
285
|
ctx,
|
|
298
286
|
proxy,
|
|
299
287
|
service,
|
|
288
|
+
strip,
|
|
300
289
|
upstreamRequest,
|
|
301
290
|
});
|
|
302
291
|
let response = outcome.response;
|
|
@@ -331,28 +320,29 @@ async function proxyUpstream(options) {
|
|
|
331
320
|
await waitForRetry(action.delay, request.signal);
|
|
332
321
|
}
|
|
333
322
|
}
|
|
323
|
+
/** Applies the service's request rewrite, if any. */
|
|
324
|
+
async function rewrite(options) {
|
|
325
|
+
const { ctx, service, upstreamRequest } = options;
|
|
326
|
+
return service.rewriteRequest ? service.rewriteRequest(upstreamRequest, ctx) : upstreamRequest;
|
|
327
|
+
}
|
|
328
|
+
/** Sends a rewritten request upstream and strips the response's headers. */
|
|
329
|
+
async function send(options, request) {
|
|
330
|
+
return Headers.scrubResponse(await options.proxy(request), options.strip);
|
|
331
|
+
}
|
|
334
332
|
/** Proxies one request without retaining a replay copy of its body. */
|
|
335
333
|
async function proxyUpstreamOnce(options) {
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
let response = await proxy(upstreamRequest);
|
|
341
|
-
response = Headers.scrubResponse(response);
|
|
342
|
-
if (service.rewriteResponse)
|
|
343
|
-
response = await service.rewriteResponse(response, ctx);
|
|
344
|
-
return response;
|
|
334
|
+
const response = await send(options, await rewrite(options));
|
|
335
|
+
return options.service.rewriteResponse
|
|
336
|
+
? options.service.rewriteResponse(response, options.ctx)
|
|
337
|
+
: response;
|
|
345
338
|
}
|
|
346
339
|
/** Performs one independently replayable upstream request attempt. */
|
|
347
340
|
async function proxyUpstreamAttempt(options) {
|
|
348
|
-
|
|
341
|
+
// The result carries the request as rewritten, as `onUpstreamError` documents.
|
|
349
342
|
let upstreamRequest = options.upstreamRequest.clone();
|
|
350
343
|
try {
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
let response = await proxy(upstreamRequest);
|
|
354
|
-
response = Headers.scrubResponse(response);
|
|
355
|
-
return { error: undefined, response, upstreamRequest };
|
|
344
|
+
upstreamRequest = await rewrite({ ...options, upstreamRequest });
|
|
345
|
+
return { error: undefined, response: await send(options, upstreamRequest), upstreamRequest };
|
|
356
346
|
}
|
|
357
347
|
catch (error) {
|
|
358
348
|
return { error, response: undefined, upstreamRequest };
|
|
@@ -432,6 +422,29 @@ function requiresManualGeneration(handler, selected) {
|
|
|
432
422
|
return ((selected.intent === 'session' && selectedOffers.length === 0) ||
|
|
433
423
|
selectedOffers.some(unsupported));
|
|
434
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* Headers the proxy strips beyond the built-in ones: those declared by the identity verifiers and
|
|
427
|
+
* payment checks of its routes (`headers` on each), so a route that uses an identity extension
|
|
428
|
+
* never needs them listed by hand. The names are validated and lowercased when each route is
|
|
429
|
+
* created (`IdentityServer.headersOf`), so a bad declaration fails before the proxy starts.
|
|
430
|
+
*/
|
|
431
|
+
function stripHeadersOf(services) {
|
|
432
|
+
const request = new Set();
|
|
433
|
+
const response = new Set();
|
|
434
|
+
for (const service of services)
|
|
435
|
+
for (const endpoint of Object.values(service.routes)) {
|
|
436
|
+
const handler = endpoint === undefined ? undefined : Service.getHandler(endpoint);
|
|
437
|
+
if (!handler || !('_internal' in handler) || !handler._internal)
|
|
438
|
+
continue;
|
|
439
|
+
for (const offer of Metadata.offers(handler._internal)) {
|
|
440
|
+
for (const name of offer._identityHeaders?.request ?? [])
|
|
441
|
+
request.add(name);
|
|
442
|
+
for (const name of offer._identityHeaders?.response ?? [])
|
|
443
|
+
response.add(name);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return { request: [...request], response: [...response] };
|
|
447
|
+
}
|
|
435
448
|
/** Identity and session offers must re-run authorization and delivery-time metering on every request. */
|
|
436
449
|
function requiresFreshVerification(handler, selected) {
|
|
437
450
|
if (selected?.intent === 'session')
|
|
@@ -1,5 +1,12 @@
|
|
|
1
|
+
/** Headers the proxy strips beyond the built-in ones, declared by its routes' identity protocols. */
|
|
2
|
+
export type Strip = {
|
|
3
|
+
/** Request headers never forwarded upstream, such as an identity proof. */
|
|
4
|
+
readonly request?: readonly string[] | undefined;
|
|
5
|
+
/** Upstream response headers never returned to the client, such as an identity request. */
|
|
6
|
+
readonly response?: readonly string[] | undefined;
|
|
7
|
+
};
|
|
1
8
|
/** Strips hop-by-hop, auth, identity, encoding, cookie, and forwarding headers from a request before proxying upstream. */
|
|
2
|
-
export declare function scrub(headers: Headers): Headers;
|
|
9
|
+
export declare function scrub(headers: Headers, strip?: Strip | undefined): Headers;
|
|
3
10
|
/**
|
|
4
11
|
* Strips re-streaming headers (`content-encoding`, `content-length`) and
|
|
5
12
|
* security-sensitive headers (`set-cookie`) from an upstream response.
|
|
@@ -13,5 +20,5 @@ export declare function scrub(headers: Headers): Headers;
|
|
|
13
20
|
* primitive. Proxied services authenticate via bearer tokens / signed
|
|
14
21
|
* payloads, never cookies, so dropping `set-cookie` is purely defensive.
|
|
15
22
|
*/
|
|
16
|
-
export declare function scrubResponse(response: Response): Response;
|
|
23
|
+
export declare function scrubResponse(response: Response, strip?: Strip | undefined): Response;
|
|
17
24
|
//# sourceMappingURL=Headers.d.ts.map
|
|
@@ -9,6 +9,14 @@ const hopByHopHeaders = new Set([
|
|
|
9
9
|
'te',
|
|
10
10
|
'trailer',
|
|
11
11
|
]);
|
|
12
|
+
// Client-supplied forwarding headers: a client could claim any address or path through them.
|
|
13
|
+
const forwardingHeaders = new Set([
|
|
14
|
+
'cf-connecting-ip',
|
|
15
|
+
'forwarded',
|
|
16
|
+
'true-client-ip',
|
|
17
|
+
'via',
|
|
18
|
+
'x-real-ip',
|
|
19
|
+
]);
|
|
12
20
|
// Payment credentials are consumed by the proxy and must never reach upstream services.
|
|
13
21
|
const paymentHeaders = new Set([
|
|
14
22
|
'accept-payment',
|
|
@@ -24,14 +32,17 @@ const paymentHeaders = new Set([
|
|
|
24
32
|
'www-authenticate',
|
|
25
33
|
]);
|
|
26
34
|
/** Strips hop-by-hop, auth, identity, encoding, cookie, and forwarding headers from a request before proxying upstream. */
|
|
27
|
-
export function scrub(headers) {
|
|
35
|
+
export function scrub(headers, strip) {
|
|
28
36
|
const scrubbed = new Headers();
|
|
37
|
+
const extra = new Set(strip?.request?.map((name) => name.toLowerCase()));
|
|
29
38
|
for (const [name, value] of headers) {
|
|
30
39
|
const lower = name.toLowerCase();
|
|
31
40
|
if (paymentHeaders.has(lower))
|
|
32
41
|
continue;
|
|
33
42
|
if (IdentityHeaders.request.includes(lower))
|
|
34
43
|
continue;
|
|
44
|
+
if (extra.has(lower))
|
|
45
|
+
continue;
|
|
35
46
|
if (lower === 'accept-encoding')
|
|
36
47
|
continue;
|
|
37
48
|
if (lower === 'content-length')
|
|
@@ -40,7 +51,7 @@ export function scrub(headers) {
|
|
|
40
51
|
continue;
|
|
41
52
|
if (hopByHopHeaders.has(lower))
|
|
42
53
|
continue;
|
|
43
|
-
if (lower.startsWith('x-forwarded-'))
|
|
54
|
+
if (forwardingHeaders.has(lower) || lower.startsWith('x-forwarded-'))
|
|
44
55
|
continue;
|
|
45
56
|
scrubbed.append(name, value);
|
|
46
57
|
}
|
|
@@ -59,7 +70,7 @@ export function scrub(headers) {
|
|
|
59
70
|
* primitive. Proxied services authenticate via bearer tokens / signed
|
|
60
71
|
* payloads, never cookies, so dropping `set-cookie` is purely defensive.
|
|
61
72
|
*/
|
|
62
|
-
export function scrubResponse(response) {
|
|
73
|
+
export function scrubResponse(response, strip) {
|
|
63
74
|
const headers = new Headers(response.headers);
|
|
64
75
|
headers.delete('content-encoding');
|
|
65
76
|
headers.delete('content-length');
|
|
@@ -72,6 +83,8 @@ export function scrubResponse(response) {
|
|
|
72
83
|
// The proxy decides which identity the client presents, so upstream identity headers never pass.
|
|
73
84
|
for (const name of [...IdentityHeaders.request, ...IdentityHeaders.response])
|
|
74
85
|
headers.delete(name);
|
|
86
|
+
for (const name of strip?.response ?? [])
|
|
87
|
+
headers.delete(name);
|
|
75
88
|
const authorization = headers.get('authorization');
|
|
76
89
|
if (authorization && /^\s*Payment(?:\s|$)/i.test(authorization))
|
|
77
90
|
headers.delete('authorization');
|
package/dist/server/Mppx.d.ts
CHANGED
|
@@ -352,6 +352,17 @@ type ChallengeFn<method extends Method.Method, defaults extends Record<string, u
|
|
|
352
352
|
export declare function create<const methods extends Methods, const transport extends Transport.AnyTransport = Transport.Http>(config: create.Config<methods, transport>): Mppx<methods, transport>;
|
|
353
353
|
export declare namespace create {
|
|
354
354
|
type Config<methods extends Methods = Methods, transport extends Transport.AnyTransport = Transport.Http> = {
|
|
355
|
+
/**
|
|
356
|
+
* Adds a fresh random nonce to every Challenge's `opaque` under `_mpp_nonce`, so each
|
|
357
|
+
* Challenge gets a unique ID. Route matching ignores it.
|
|
358
|
+
*
|
|
359
|
+
* With `false`, requests for the same route with the same `expires` get the same Challenge
|
|
360
|
+
* ID, so a payment bound to that ID could be redeemed by whichever requester presents it
|
|
361
|
+
* first. Tempo charge then accepts only pull (`transaction`) credentials and rejects push
|
|
362
|
+
* (`hash`, Zone) and proof credentials, so set its `supportedModes` to `['pull']`.
|
|
363
|
+
* @default true
|
|
364
|
+
*/
|
|
365
|
+
challengeNonce?: boolean | undefined;
|
|
355
366
|
/** Array of configured methods. @example [tempo()] */
|
|
356
367
|
methods: methods;
|
|
357
368
|
/** Uses `Payment-Authorization` for Payment credentials so `Authorization` remains available for application authentication. */
|
|
@@ -383,7 +394,7 @@ declare namespace MethodFn {
|
|
|
383
394
|
description?: string | undefined;
|
|
384
395
|
/** Optional challenge expiration timestamp (ISO 8601) or Date. */
|
|
385
396
|
expires?: z.DatetimeInput | undefined;
|
|
386
|
-
/** Optional server-defined correlation data serialized as `opaque`. `
|
|
397
|
+
/** Optional server-defined correlation data serialized as `opaque`. `_mpp_nonce` is reserved for a fresh server-generated issuance nonce, and `_mppx_expiry_grace` marks a challenge whose method accepts some credentials after it expires; clients MUST echo opaque unchanged. */
|
|
387
398
|
meta?: Record<string, string> | undefined;
|
|
388
399
|
/** Optional route/resource scope bound via reserved challenge metadata. */
|
|
389
400
|
scope?: string | undefined;
|
|
@@ -422,6 +433,8 @@ type ConfiguredHandler<transport extends Transport.AnyTransport = Transport.Http
|
|
|
422
433
|
_stableBinding?: Method.StableBindingFn<Method.Method> | undefined;
|
|
423
434
|
/** Whether the route requires identity (request-stage verifiers or a payment check). */
|
|
424
435
|
_identity?: boolean | undefined;
|
|
436
|
+
/** Headers the route's identity protocols send, which a proxy strips. */
|
|
437
|
+
_identityHeaders?: Identity.ProtocolHeaders | undefined;
|
|
425
438
|
/** The route's payment check, compared across composed offers. */
|
|
426
439
|
_paymentCheck?: Identity.PaymentCheck | undefined;
|
|
427
440
|
_transport: Transport.AnyTransport;
|