mppx 0.19.1 → 0.20.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 +10 -0
- package/dist/cli/cli.js +2 -2
- package/dist/extensions/identity/erc8004/Constants.d.ts +20 -0
- package/dist/extensions/identity/erc8004/Constants.js +20 -0
- package/dist/extensions/identity/erc8004/Types.d.ts +11 -0
- package/dist/extensions/identity/erc8004/Types.js +2 -0
- package/dist/extensions/identity/erc8004/client/index.d.ts +33 -0
- package/dist/extensions/identity/erc8004/client/index.js +33 -0
- package/dist/extensions/identity/erc8004/index.d.ts +5 -0
- package/dist/extensions/identity/erc8004/index.js +4 -0
- package/dist/extensions/identity/erc8004/internal/Agent.d.ts +21 -0
- package/dist/extensions/identity/erc8004/internal/Agent.js +24 -0
- package/dist/extensions/identity/erc8004/server/index.d.ts +44 -0
- package/dist/extensions/identity/erc8004/server/index.js +178 -0
- package/dist/extensions/identity/index.d.ts +2 -0
- package/dist/extensions/identity/index.js +2 -0
- package/dist/identity/Headers.d.ts +1 -1
- package/dist/identity/Headers.js +2 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/Proxy.js +47 -9
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
- package/dist/tempo/session/server/CredentialVerification.js +44 -0
- package/dist/tempo/session/server/MeteredStream.d.ts +2 -0
- package/dist/tempo/session/server/MeteredStream.js +11 -0
- package/dist/tempo/session/server/Sse.js +9 -4
- package/package.json +5 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { createClient, getAddress, hashMessage, http, isAddressEqual, recoverMessageAddress, zeroAddress, } from 'viem';
|
|
2
|
+
import { readContract } from 'viem/actions';
|
|
3
|
+
import * as Store from '../../../../Store.js';
|
|
4
|
+
import { Constants } from '../Constants.js';
|
|
5
|
+
import * as Agent from '../internal/Agent.js';
|
|
6
|
+
const abi = [
|
|
7
|
+
{
|
|
8
|
+
type: 'function',
|
|
9
|
+
name: 'getAgentWallet',
|
|
10
|
+
stateMutability: 'view',
|
|
11
|
+
inputs: [{ name: 'agentId', type: 'uint256' }],
|
|
12
|
+
outputs: [{ name: '', type: 'address' }],
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
type: 'function',
|
|
16
|
+
name: 'isValidSignature',
|
|
17
|
+
stateMutability: 'view',
|
|
18
|
+
inputs: [
|
|
19
|
+
{ name: 'hash', type: 'bytes32' },
|
|
20
|
+
{ name: 'signature', type: 'bytes' },
|
|
21
|
+
],
|
|
22
|
+
outputs: [{ name: '', type: 'bytes4' }],
|
|
23
|
+
},
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* Creates an ERC-8004 agent verifier for one API.
|
|
27
|
+
*
|
|
28
|
+
* - `verifier` requires a request signed by the agent's wallet, as the Identity Registry's
|
|
29
|
+
* `getAgentWallet` names it: an EOA signature, or ERC-1271 for a contract or configurable account.
|
|
30
|
+
* - `paymentCheck` accepts a `tempo` charge the agent's wallet signed (a transaction or proof), so
|
|
31
|
+
* the payment itself proves the agent. For anything else (no Credential, transaction hashes,
|
|
32
|
+
* sessions, Zones, other methods) it requires the signature.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* const agents = Erc8004.Server.create({ store })
|
|
37
|
+
* mppx.charge({ amount: '0.01', identity: { request: [agents.verifier], payment: agents.paymentCheck } })
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export function create(config = {}) {
|
|
41
|
+
const chainId = config.chainId ?? Constants.chainId;
|
|
42
|
+
const registry = getAddress(config.registry ?? Constants.identityRegistry);
|
|
43
|
+
if (!config.client && !config.rpcUrl && chainId !== Constants.chainId)
|
|
44
|
+
throw new TypeError('Pass `client` or `rpcUrl` for a chain other than Tempo mainnet.');
|
|
45
|
+
const client = config.client ?? createClient({ transport: http(config.rpcUrl ?? Constants.rpcUrl) });
|
|
46
|
+
const store = config.store;
|
|
47
|
+
// One lookup per request, so the verifier and payment check share it and spend a nonce once.
|
|
48
|
+
const agents = new WeakMap();
|
|
49
|
+
const signed = new WeakMap();
|
|
50
|
+
const invalid = (reason) => ({ status: 'invalid', reason });
|
|
51
|
+
/** Reads the request's agent and its wallet from the registry. */
|
|
52
|
+
async function lookup(request) {
|
|
53
|
+
const id = request.headers.get(Constants.idHeader);
|
|
54
|
+
if (!id)
|
|
55
|
+
return { status: 'missing', reason: 'Sign the request as an ERC-8004 agent.' };
|
|
56
|
+
const agent = Agent.parse(id);
|
|
57
|
+
if (!agent || agent.chainId !== chainId || !isAddressEqual(agent.registry, registry))
|
|
58
|
+
return invalid(`The agent must be in the Identity Registry ${registry} on chain ${chainId}.`);
|
|
59
|
+
let wallet;
|
|
60
|
+
try {
|
|
61
|
+
wallet = await readContract(client, {
|
|
62
|
+
abi,
|
|
63
|
+
address: registry,
|
|
64
|
+
args: [agent.agentId],
|
|
65
|
+
functionName: 'getAgentWallet',
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return { status: 'unavailable', reason: 'The Identity Registry is unavailable.' };
|
|
70
|
+
}
|
|
71
|
+
if (isAddressEqual(wallet, zeroAddress))
|
|
72
|
+
return { status: 'forbidden', reason: 'The agent has no wallet.' };
|
|
73
|
+
return {
|
|
74
|
+
status: 'valid',
|
|
75
|
+
value: { agentId: agent.agentId, id: Agent.format(agent), wallet: getAddress(wallet) },
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Checks that the agent's wallet signed this request. */
|
|
79
|
+
async function verifySignature(request) {
|
|
80
|
+
const result = await getAgent(request);
|
|
81
|
+
if (result.status !== 'valid')
|
|
82
|
+
return result;
|
|
83
|
+
const [created = '', nonce = '', signature = '', ...rest] = (request.headers.get(Constants.signatureHeader) ?? '').split('.');
|
|
84
|
+
if (rest.length > 0 ||
|
|
85
|
+
!/^\d{1,12}$/.test(created) ||
|
|
86
|
+
!nonce ||
|
|
87
|
+
!/^0x[0-9a-fA-F]+$/.test(signature))
|
|
88
|
+
return invalid('The agent signature is missing or malformed.');
|
|
89
|
+
const now = Math.floor(Date.now() / 1_000);
|
|
90
|
+
const expires = Number(created) + Constants.maxAge + Constants.clockTolerance;
|
|
91
|
+
if (Number(created) > now + Constants.clockTolerance || expires < now)
|
|
92
|
+
return invalid('The agent signature has expired.');
|
|
93
|
+
const message = Agent.message({
|
|
94
|
+
created: Number(created),
|
|
95
|
+
id: request.headers.get(Constants.idHeader),
|
|
96
|
+
nonce,
|
|
97
|
+
request,
|
|
98
|
+
});
|
|
99
|
+
if (!(await signedBy(result.value.wallet, message, signature)))
|
|
100
|
+
return invalid("The agent's wallet did not sign the request.");
|
|
101
|
+
if (store) {
|
|
102
|
+
const key = `mppx:erc8004:nonce:${hashMessage(`${result.value.id}:${nonce}`)}`;
|
|
103
|
+
const claimed = await Promise.resolve()
|
|
104
|
+
.then(() => Store.tryClaim(store, key, expires * 1_000))
|
|
105
|
+
.catch(() => null);
|
|
106
|
+
if (claimed === null)
|
|
107
|
+
return { status: 'unavailable', reason: 'The replay store is unavailable.' };
|
|
108
|
+
if (!claimed)
|
|
109
|
+
return invalid('The agent signature was already used.');
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
/** Returns whether `wallet` signed `message`: by EOA recovery, else by ERC-1271. */
|
|
114
|
+
async function signedBy(wallet, message, signature) {
|
|
115
|
+
const recovered = await recoverMessageAddress({ message, signature }).catch(() => undefined);
|
|
116
|
+
if (recovered && isAddressEqual(recovered, wallet))
|
|
117
|
+
return true;
|
|
118
|
+
const magic = await readContract(client, {
|
|
119
|
+
abi,
|
|
120
|
+
address: wallet,
|
|
121
|
+
args: [hashMessage(message), signature],
|
|
122
|
+
functionName: 'isValidSignature',
|
|
123
|
+
}).catch(() => undefined);
|
|
124
|
+
return magic === '0x1626ba7e';
|
|
125
|
+
}
|
|
126
|
+
function getAgent(request) {
|
|
127
|
+
let result = agents.get(request);
|
|
128
|
+
if (!result)
|
|
129
|
+
agents.set(request, (result = lookup(request)));
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
function getSigned(request) {
|
|
133
|
+
let result = signed.get(request);
|
|
134
|
+
if (!result)
|
|
135
|
+
signed.set(request, (result = verifySignature(request)));
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
/** Runs `allow` on a verified agent. */
|
|
139
|
+
async function allowed(result) {
|
|
140
|
+
if (result.status !== 'valid' || !config.allow || (await config.allow(result.value)))
|
|
141
|
+
return result;
|
|
142
|
+
return { status: 'forbidden', reason: 'This agent may not call this API.' };
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
verifier: { verify: async (request) => allowed(await getSigned(request)) },
|
|
146
|
+
paymentCheck: {
|
|
147
|
+
requires: [{ type: Constants.type }],
|
|
148
|
+
async verify({ challenge, credential, request }) {
|
|
149
|
+
// Only a tempo charge the source signed binds it to the payer: a transaction or a proof.
|
|
150
|
+
// A hash credential doesn't (the charge's validateSender can accept another payer), and
|
|
151
|
+
// neither do sessions, Zones or other methods, so they need the agent's signature instead.
|
|
152
|
+
const type = credential?.payload?.type;
|
|
153
|
+
if (!credential ||
|
|
154
|
+
challenge.method !== 'tempo' ||
|
|
155
|
+
challenge.intent !== 'charge' ||
|
|
156
|
+
(type !== 'transaction' && type !== 'proof'))
|
|
157
|
+
return allowed(await getSigned(request));
|
|
158
|
+
const agent = await getAgent(request);
|
|
159
|
+
if (agent.status !== 'valid')
|
|
160
|
+
return agent;
|
|
161
|
+
// The source is a did:pkh:eip155:<chainId>:<address>.
|
|
162
|
+
const parts = credential.source?.split(':') ?? [];
|
|
163
|
+
const [did, pkh, namespace, chain, address = ''] = parts;
|
|
164
|
+
if (parts.length !== 5 ||
|
|
165
|
+
did !== 'did' ||
|
|
166
|
+
pkh !== 'pkh' ||
|
|
167
|
+
namespace !== 'eip155' ||
|
|
168
|
+
chain !== String(chainId) ||
|
|
169
|
+
!/^0x[0-9a-fA-F]{40}$/.test(address))
|
|
170
|
+
return invalid(`The payment must name its source account on chain ${chainId}.`);
|
|
171
|
+
if (!isAddressEqual(address, agent.value.wallet))
|
|
172
|
+
return { status: 'forbidden', reason: "The payment is not from the agent's wallet." };
|
|
173
|
+
return allowed(agent);
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export * as Attestation from './attestation/index.js';
|
|
3
3
|
/** Email address verification with a one-time code. */
|
|
4
4
|
export * as EmailOtp from './email-otp/index.js';
|
|
5
|
+
/** ERC-8004 agents: requests signed, and payments made, by an agent's registered wallet. */
|
|
6
|
+
export * as Erc8004 from './erc8004/index.js';
|
|
5
7
|
/** Link agent identity: attestation tokens and Link-signed claims. */
|
|
6
8
|
export * as Link from './link/index.js';
|
|
7
9
|
/** Persona KYC: a payment check that requires an approved Persona inquiry. */
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export * as Attestation from './attestation/index.js';
|
|
3
3
|
/** Email address verification with a one-time code. */
|
|
4
4
|
export * as EmailOtp from './email-otp/index.js';
|
|
5
|
+
/** ERC-8004 agents: requests signed, and payments made, by an agent's registered wallet. */
|
|
6
|
+
export * as Erc8004 from './erc8004/index.js';
|
|
5
7
|
/** Link agent identity: attestation tokens and Link-signed claims. */
|
|
6
8
|
export * as Link from './link/index.js';
|
|
7
9
|
/** Persona KYC: a payment check that requires an approved Persona inquiry. */
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
|
|
8
8
|
* their own extra sensitive headers in `Prover.headers`.
|
|
9
9
|
*/
|
|
10
|
-
export declare const request: readonly ["dpop", "identity-attestation", "identity-presentation", "poppy-session", "tempo-id-token"];
|
|
10
|
+
export declare const request: readonly ["agent-id", "agent-signature", "dpop", "identity-attestation", "identity-presentation", "poppy-session", "tempo-id-token"];
|
|
11
11
|
/**
|
|
12
12
|
* `WWW-Authenticate` schemes that ask for an identity, lowercased. A proxy removes them from
|
|
13
13
|
* upstream responses: the proxy, not the upstream, decides which identity the client presents.
|
package/dist/identity/Headers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Current mppx package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.20.0";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.20.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.20.0';
|
|
4
4
|
/** Canonical SDK identifier for this mppx release. */
|
|
5
5
|
export const sdkIdentifier = `mppx/${version}`;
|
|
6
6
|
//# sourceMappingURL=version.js.map
|
package/dist/proxy/Proxy.js
CHANGED
|
@@ -3,6 +3,7 @@ import { generateProxy } from '../discovery/OpenApi.js';
|
|
|
3
3
|
import * as Scope from '../server/internal/scope.js';
|
|
4
4
|
import * as Mppx from '../server/Mppx.js';
|
|
5
5
|
import * as Request from '../server/Request.js';
|
|
6
|
+
import { captureRequestBodyProbe, isSessionContentRequest, } from '../tempo/server/internal/request-body.js';
|
|
6
7
|
import * as Headers from './internal/Headers.js';
|
|
7
8
|
import * as Replay from './internal/Replay.js';
|
|
8
9
|
import * as Route from './internal/Route.js';
|
|
@@ -127,13 +128,31 @@ export function create(config) {
|
|
|
127
128
|
proxy,
|
|
128
129
|
onUpstreamError: service.onUpstreamError ?? config.onUpstreamError,
|
|
129
130
|
});
|
|
131
|
+
let selected;
|
|
132
|
+
try {
|
|
133
|
+
selected = paymentCredential ? Credential.deserialize(paymentCredential) : undefined;
|
|
134
|
+
}
|
|
135
|
+
catch { }
|
|
136
|
+
const manualGeneration = requiresManualGeneration(handler, selected?.challenge);
|
|
137
|
+
const payload = selected?.payload;
|
|
138
|
+
const action = payload && typeof payload === 'object' && 'action' in payload ? payload.action : undefined;
|
|
139
|
+
// Unverified input only routes management to the verifier; it never authorizes upstream work.
|
|
140
|
+
const management = selected?.challenge.intent === 'session' &&
|
|
141
|
+
(action === 'close' ||
|
|
142
|
+
action === 'topUp' ||
|
|
143
|
+
!isSessionContentRequest(captureRequestBodyProbe(request)));
|
|
144
|
+
const unsupportedGeneration = () => new Response('Per-item session proxy routes require a manual-charge generator; use request pricing for automatic proxying.', { status: 500 });
|
|
145
|
+
if (manualGeneration && !management)
|
|
146
|
+
return unsupportedGeneration();
|
|
130
147
|
// With replay, a paid request whose credential already paid for this exact
|
|
131
148
|
// request collects its recorded delivery instead of paying again.
|
|
132
149
|
let paidRequest = request;
|
|
133
150
|
let replayBody;
|
|
134
151
|
let replayKey;
|
|
135
|
-
//
|
|
136
|
-
const credential = replay && !fallbackMatch && !
|
|
152
|
+
// Identity and session routes retain their normal verification and metered delivery.
|
|
153
|
+
const credential = replay && !fallbackMatch && !requiresFreshVerification(handler, selected?.challenge)
|
|
154
|
+
? paymentCredential
|
|
155
|
+
: undefined;
|
|
137
156
|
if (replay && credential) {
|
|
138
157
|
const body = boundedBody ??
|
|
139
158
|
(await Replay.readBody(request, Math.min(maxRequestBodySize, replay.maxRequestBodySize)));
|
|
@@ -197,6 +216,8 @@ export function create(config) {
|
|
|
197
216
|
return managementResponse;
|
|
198
217
|
if (fallbackMatch)
|
|
199
218
|
return new Response('Method Not Allowed', { status: 405 });
|
|
219
|
+
if (manualGeneration)
|
|
220
|
+
return unsupportedGeneration();
|
|
200
221
|
if (!boundedBody && !replayBody && request.body) {
|
|
201
222
|
const body = await Replay.readBody(request, maxRequestBodySize);
|
|
202
223
|
if (!body)
|
|
@@ -386,16 +407,33 @@ function credentialHeaders(handler) {
|
|
|
386
407
|
const names = [...new Set(headers.map((header) => header.toLowerCase()))];
|
|
387
408
|
return names.length > 0 ? names : ['authorization'];
|
|
388
409
|
}
|
|
389
|
-
|
|
390
|
-
function requiresIdentity(handler) {
|
|
410
|
+
function requiresManualGeneration(handler, selected) {
|
|
391
411
|
if (!('_internal' in handler))
|
|
392
|
-
return
|
|
412
|
+
return selected?.intent === 'session';
|
|
393
413
|
const internal = handler._internal;
|
|
394
|
-
|
|
414
|
+
const offers = internal?.offers ?? (internal ? [internal] : []);
|
|
415
|
+
const unsupported = (offer) => offer.intent === 'session' &&
|
|
416
|
+
offer._transport?.name !== 'http' &&
|
|
417
|
+
offer._canonicalRequest?.amount !== '0' &&
|
|
418
|
+
offer._canonicalRequest?.unitType !== 'request';
|
|
419
|
+
// Mixed methods can still challenge and serve their one-shot charge offer. A session's
|
|
420
|
+
// canonical route pricing is authoritative, never the unitType echoed by its credential.
|
|
421
|
+
if (!selected)
|
|
422
|
+
return offers.length > 0 && offers.every(unsupported);
|
|
423
|
+
const selectedOffers = offers.filter((offer) => (!offer.name || offer.name === selected.method) && offer.intent === selected.intent);
|
|
424
|
+
return ((selected.intent === 'session' && selectedOffers.length === 0) ||
|
|
425
|
+
selectedOffers.some(unsupported));
|
|
426
|
+
}
|
|
427
|
+
/** Identity and session offers must re-run authorization and delivery-time metering on every request. */
|
|
428
|
+
function requiresFreshVerification(handler, selected) {
|
|
429
|
+
if (selected?.intent === 'session')
|
|
430
|
+
return true;
|
|
431
|
+
if (!('_internal' in handler))
|
|
395
432
|
return false;
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
return
|
|
433
|
+
const internal = handler._internal;
|
|
434
|
+
const offers = internal?.offers ?? (internal ? [internal] : []);
|
|
435
|
+
return (offers.some((offer) => offer._identity) ||
|
|
436
|
+
(!selected && offers.some((offer) => offer.intent === 'session')));
|
|
399
437
|
}
|
|
400
438
|
function getConfiguredScope(handler) {
|
|
401
439
|
if (!('_internal' in handler))
|