mppx 0.19.0 → 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 +19 -0
- package/dist/Errors.d.ts +29 -0
- package/dist/Errors.js +27 -2
- package/dist/cli/cli.js +96 -96
- package/dist/cli/plugins/index.js +12 -12
- 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/extensions/identity/poppy/Constants.d.ts +26 -0
- package/dist/extensions/identity/poppy/Constants.js +26 -0
- package/dist/extensions/identity/poppy/Types.d.ts +19 -0
- package/dist/extensions/identity/poppy/Types.js +2 -0
- package/dist/extensions/identity/poppy/client/index.d.ts +69 -0
- package/dist/extensions/identity/poppy/client/index.js +81 -0
- package/dist/extensions/identity/poppy/index.d.ts +7 -0
- package/dist/extensions/identity/poppy/index.js +7 -0
- package/dist/extensions/identity/poppy/internal/Jws.d.ts +12 -0
- package/dist/extensions/identity/poppy/internal/Jws.js +78 -0
- package/dist/extensions/identity/poppy/server/index.d.ts +40 -0
- package/dist/extensions/identity/poppy/server/index.js +181 -0
- package/dist/identity/Headers.d.ts +1 -1
- package/dist/identity/Headers.js +3 -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/client/Charge.js +7 -4
- package/dist/tempo/internal/simulation.d.ts +33 -0
- package/dist/tempo/internal/simulation.js +80 -0
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/client/ChannelOps.js +5 -2
- 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 +9 -1
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as Jwt from '../../tempo/internal/Jwt.js';
|
|
2
|
+
import { Constants } from '../Constants.js';
|
|
3
|
+
import * as Jws from '../internal/Jws.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates a prover that sends a Poppy `Poppy-Session` header with each request to one Company.
|
|
6
|
+
*
|
|
7
|
+
* A Session JWT is signed fresh for every attempt, including the paid retry, so it names the
|
|
8
|
+
* request's method and URL and, when the request carries an OAuth access token, binds to it with
|
|
9
|
+
* `ath`. The Payment Credential is not an access token: it is never bound.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* const mppx = Mppx.create({
|
|
14
|
+
* identity: [
|
|
15
|
+
* Poppy.Client.prover({
|
|
16
|
+
* audience: 'https://api.example.com',
|
|
17
|
+
* clientId: 'https://agent.example/agent.json',
|
|
18
|
+
* delegation: () => delegations.current(),
|
|
19
|
+
* key: delegatedKey,
|
|
20
|
+
* scope: ['https://api.example.com'],
|
|
21
|
+
* userId: 'usr_Q7c1vK',
|
|
22
|
+
* }),
|
|
23
|
+
* ],
|
|
24
|
+
* methods: [tempo({ account })],
|
|
25
|
+
* })
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export function prover(config) {
|
|
29
|
+
const sessionId = config.sessionId ?? crypto.randomUUID().replaceAll('-', '');
|
|
30
|
+
let kid;
|
|
31
|
+
return {
|
|
32
|
+
scope: config.scope,
|
|
33
|
+
headers: [Constants.sessionHeader.toLowerCase()],
|
|
34
|
+
async prove(request) {
|
|
35
|
+
const headers = new Headers(request.headers);
|
|
36
|
+
const token = Jws.accessToken(headers);
|
|
37
|
+
// The verifier rejects an access token it can't bind, so don't sign a Session it would refuse.
|
|
38
|
+
if (token === null)
|
|
39
|
+
throw new TypeError('Authorization must hold one Bearer or DPoP token, or none.');
|
|
40
|
+
const session = await Jws.sign({
|
|
41
|
+
alg: 'ES256',
|
|
42
|
+
kid: await (kid ??= Jwt.thumbprint(config.key.jwk)),
|
|
43
|
+
poppy_dlg: await config.delegation(),
|
|
44
|
+
typ: Constants.sessionType,
|
|
45
|
+
}, {
|
|
46
|
+
...(config.agentId && { agent_id: config.agentId }),
|
|
47
|
+
...(token && { ath: await Jwt.sha256(token) }),
|
|
48
|
+
aud: config.audience,
|
|
49
|
+
htm: request.method,
|
|
50
|
+
htu: Jwt.htu(request.url),
|
|
51
|
+
iat: Math.floor(Date.now() / 1_000),
|
|
52
|
+
iss: config.clientId,
|
|
53
|
+
jti: crypto.randomUUID(),
|
|
54
|
+
sid: sessionId,
|
|
55
|
+
sub: config.userId,
|
|
56
|
+
}, config.key.privateKey);
|
|
57
|
+
headers.set(Constants.sessionHeader, session);
|
|
58
|
+
headers.set(Constants.versionHeader, Constants.version);
|
|
59
|
+
return new Request(request, { headers });
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Signs a delegation (spec 5.2): a short-lived JWT in which a key from the agent's `jwks_uri`
|
|
65
|
+
* vouches for a delegated key. It names no User or Company.
|
|
66
|
+
*/
|
|
67
|
+
export function delegate(parameters) {
|
|
68
|
+
const { clientId, expiresIn = Constants.defaultDelegationLifetime, key, publicKey } = parameters;
|
|
69
|
+
if (!Number.isInteger(expiresIn) || expiresIn <= 0 || expiresIn > Constants.maxDelegationLifetime)
|
|
70
|
+
throw new RangeError('A delegation lasts between 1 second and 24 hours.');
|
|
71
|
+
const { crv, kty, x, y } = publicKey;
|
|
72
|
+
const iat = Math.floor(Date.now() / 1_000);
|
|
73
|
+
return Jws.sign({ alg: 'ES256', kid: key.kid, typ: Constants.delegationType }, {
|
|
74
|
+
cnf: { jwk: { crv, kty, x, y } },
|
|
75
|
+
exp: iat + expiresIn,
|
|
76
|
+
iat,
|
|
77
|
+
iss: clientId,
|
|
78
|
+
jti: crypto.randomUUID(),
|
|
79
|
+
}, key.privateKey);
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Client helpers for Poppy (Personal Agent Protocol) Sessions. */
|
|
2
|
+
export * as Client from './client/index.js';
|
|
3
|
+
/** Server helpers for Poppy (Personal Agent Protocol) Sessions. */
|
|
4
|
+
export * as Server from './server/index.js';
|
|
5
|
+
export * from './Constants.js';
|
|
6
|
+
export * from './Types.js';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Client helpers for Poppy (Personal Agent Protocol) Sessions. */
|
|
2
|
+
export * as Client from './client/index.js';
|
|
3
|
+
/** Server helpers for Poppy (Personal Agent Protocol) Sessions. */
|
|
4
|
+
export * as Server from './server/index.js';
|
|
5
|
+
export * from './Constants.js';
|
|
6
|
+
export * from './Types.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type * as Jwt from '../../tempo/internal/Jwt.js';
|
|
2
|
+
/** Signs a compact ES256 JWS. */
|
|
3
|
+
export declare function sign(header: object, claims: object, privateKey: CryptoKey): Promise<string>;
|
|
4
|
+
/** Verifies a decoded JWS with a public JWK, for `ES256` or `PS384` only. */
|
|
5
|
+
export declare function verify(jws: Jwt.Decoded, jwk: JsonWebKey, algs: readonly string[]): Promise<boolean>;
|
|
6
|
+
/**
|
|
7
|
+
* The OAuth access token a request carries as `Bearer` or `DPoP` (a Payment Credential is not
|
|
8
|
+
* one), `undefined` without one, or `null` when `Authorization` names one of those schemes in any
|
|
9
|
+
* other form, such as several combined values, so it can't skip the `ath` binding.
|
|
10
|
+
*/
|
|
11
|
+
export declare function accessToken(headers: Headers): string | null | undefined;
|
|
12
|
+
//# sourceMappingURL=Jws.d.ts.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Base64 } from 'ox';
|
|
2
|
+
/** Signs a compact ES256 JWS. */
|
|
3
|
+
export async function sign(header, claims, privateKey) {
|
|
4
|
+
const input = `${encode(header)}.${encode(claims)}`;
|
|
5
|
+
const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, new TextEncoder().encode(input));
|
|
6
|
+
return `${input}.${Base64.fromBytes(new Uint8Array(signature), { pad: false, url: true })}`;
|
|
7
|
+
}
|
|
8
|
+
/** Verifies a decoded JWS with a public JWK, for `ES256` or `PS384` only. */
|
|
9
|
+
export async function verify(jws, jwk, algs) {
|
|
10
|
+
const alg = jws.header.alg;
|
|
11
|
+
if (!algs.includes(alg))
|
|
12
|
+
return false;
|
|
13
|
+
try {
|
|
14
|
+
if (alg === 'ES256') {
|
|
15
|
+
if (jwk.kty !== 'EC' || jwk.crv !== 'P-256')
|
|
16
|
+
return false;
|
|
17
|
+
const { crv, kty, x, y } = jwk;
|
|
18
|
+
const key = await crypto.subtle.importKey('jwk', { crv, kty, x, y }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
|
|
19
|
+
return crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, jws.signature, jws.signingInput);
|
|
20
|
+
}
|
|
21
|
+
if (jwk.kty !== 'RSA')
|
|
22
|
+
return false;
|
|
23
|
+
const { e, kty, n } = jwk;
|
|
24
|
+
const key = await crypto.subtle.importKey('jwk', { e, kty, n }, { name: 'RSA-PSS', hash: 'SHA-384' }, false, ['verify']);
|
|
25
|
+
return crypto.subtle.verify({ name: 'RSA-PSS', saltLength: 48 }, key, jws.signature, jws.signingInput);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The OAuth access token a request carries as `Bearer` or `DPoP` (a Payment Credential is not
|
|
33
|
+
* one), `undefined` without one, or `null` when `Authorization` names one of those schemes in any
|
|
34
|
+
* other form, such as several combined values, so it can't skip the `ath` binding.
|
|
35
|
+
*/
|
|
36
|
+
export function accessToken(headers) {
|
|
37
|
+
const value = headers.get('Authorization')?.trim();
|
|
38
|
+
if (!value)
|
|
39
|
+
return undefined;
|
|
40
|
+
const match = /^(?:bearer|dpop)[ \t]+([^\s,"]+)$/i.exec(value);
|
|
41
|
+
if (match)
|
|
42
|
+
return match[1];
|
|
43
|
+
// Quoted auth-param values can contain anything, so a scheme name inside one doesn't count.
|
|
44
|
+
const unquoted = unquote(value);
|
|
45
|
+
// An unterminated quote could hide a scheme name, so it fails closed when one appears anywhere.
|
|
46
|
+
if (unquoted === undefined)
|
|
47
|
+
return /\b(?:bearer|dpop)\b/i.test(value) ? null : undefined;
|
|
48
|
+
return /(?:^|,)\s*(?:bearer|dpop)(?:\s|$)/i.test(unquoted) ? null : undefined;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Blanks the contents of quoted strings in one pass, so the input's length bounds the work.
|
|
52
|
+
* Returns `undefined` for an unterminated quoted string.
|
|
53
|
+
*/
|
|
54
|
+
function unquote(value) {
|
|
55
|
+
let result = '';
|
|
56
|
+
let quoted = false;
|
|
57
|
+
for (let i = 0; i < value.length; i++) {
|
|
58
|
+
const char = value[i];
|
|
59
|
+
if (quoted) {
|
|
60
|
+
if (char === '\\')
|
|
61
|
+
i++;
|
|
62
|
+
else if (char === '"') {
|
|
63
|
+
quoted = false;
|
|
64
|
+
result += char;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
if (char === '"')
|
|
69
|
+
quoted = true;
|
|
70
|
+
result += char;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return quoted ? undefined : result;
|
|
74
|
+
}
|
|
75
|
+
function encode(value) {
|
|
76
|
+
return Base64.fromString(JSON.stringify(value), { pad: false, url: true });
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=Jws.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type * as Identity from '../../../../identity/Types.js';
|
|
2
|
+
import type * as Types from '../Types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a verifier for Poppy's `Poppy-Session` header (Personal Agent Protocol 1.0, spec 5.3).
|
|
5
|
+
*
|
|
6
|
+
* It fetches the Personal Agent's client metadata from `client_id` and its keys from
|
|
7
|
+
* `jwks_uri`, verifies the delegation and the Session JWT, and checks the audience, method, URL,
|
|
8
|
+
* time and access-token binding. The verified value names the agent, the pseudonymous User and
|
|
9
|
+
* the Session, so a route can price or allow by them before any payment Challenge.
|
|
10
|
+
*
|
|
11
|
+
* A Session never grants account access. When the request also carries an access token, the
|
|
12
|
+
* verifier for that token must check it was issued to the Session's `clientId`.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* const poppy = Poppy.Server.verifier({
|
|
17
|
+
* audience: 'https://api.example.com',
|
|
18
|
+
* clients: ['https://agent.example/agent.json'],
|
|
19
|
+
* })
|
|
20
|
+
*
|
|
21
|
+
* mppx.charge({ amount: '0.01', identity: [poppy] })
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare function verifier(config: verifier.Config): Identity.Verifier<Types.Session>;
|
|
25
|
+
export declare namespace verifier {
|
|
26
|
+
type Config = {
|
|
27
|
+
/** This Company's identifier, compared with `aud`: its OAuth issuer, or `https://{organization.domain}`. */
|
|
28
|
+
audience: string;
|
|
29
|
+
/**
|
|
30
|
+
* Personal Agent `client_id`s to accept. The verifier fetches metadata and keys only for
|
|
31
|
+
* these, so callers can't make it request other URLs, and its key cache stays this size.
|
|
32
|
+
*/
|
|
33
|
+
clients: readonly string[];
|
|
34
|
+
/** Accepted seconds between a Session JWT's `iat` and now. @default 60 */
|
|
35
|
+
maxAge?: number | undefined;
|
|
36
|
+
/** Fetch for client metadata and keys. @default globalThis.fetch */
|
|
37
|
+
fetch?: typeof globalThis.fetch | undefined;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
2
|
+
import * as Jwt from '../../tempo/internal/Jwt.js';
|
|
3
|
+
import { Constants } from '../Constants.js';
|
|
4
|
+
import * as Jws from '../internal/Jws.js';
|
|
5
|
+
/**
|
|
6
|
+
* Creates a verifier for Poppy's `Poppy-Session` header (Personal Agent Protocol 1.0, spec 5.3).
|
|
7
|
+
*
|
|
8
|
+
* It fetches the Personal Agent's client metadata from `client_id` and its keys from
|
|
9
|
+
* `jwks_uri`, verifies the delegation and the Session JWT, and checks the audience, method, URL,
|
|
10
|
+
* time and access-token binding. The verified value names the agent, the pseudonymous User and
|
|
11
|
+
* the Session, so a route can price or allow by them before any payment Challenge.
|
|
12
|
+
*
|
|
13
|
+
* A Session never grants account access. When the request also carries an access token, the
|
|
14
|
+
* verifier for that token must check it was issued to the Session's `clientId`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const poppy = Poppy.Server.verifier({
|
|
19
|
+
* audience: 'https://api.example.com',
|
|
20
|
+
* clients: ['https://agent.example/agent.json'],
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* mppx.charge({ amount: '0.01', identity: [poppy] })
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export function verifier(config) {
|
|
27
|
+
const { audience, clients, maxAge = Constants.maxAge } = config;
|
|
28
|
+
if (!Array.isArray(clients) || !clients.every((client) => typeof client === 'string'))
|
|
29
|
+
throw new TypeError('Poppy clients must be an array of client_id URLs.');
|
|
30
|
+
if (!Number.isInteger(maxAge) || maxAge <= 0)
|
|
31
|
+
throw new RangeError('Poppy maxAge must be a positive integer.');
|
|
32
|
+
const fetch = unwrapFetch(config.fetch ?? globalThis.fetch);
|
|
33
|
+
const cache = new Map();
|
|
34
|
+
// The last key set that loaded for each client, which a failed reload keeps for a while.
|
|
35
|
+
const loaded = new Map();
|
|
36
|
+
// Spec 5.3: a failed Session check is HTTP 400 with `invalid_session`, not 401, so OAuth
|
|
37
|
+
// clients keep a valid access token.
|
|
38
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
39
|
+
const body = (description) => JSON.stringify({ error: 'invalid_session', error_description: description });
|
|
40
|
+
const invalid = (reason) => ({ status: 'invalid', code: 400, headers, reason: body(reason) });
|
|
41
|
+
/** Fetches a client's metadata, without following redirects, then its keys (spec 4.1). */
|
|
42
|
+
async function load(clientId) {
|
|
43
|
+
const options = { redirect: 'manual', signal: AbortSignal.timeout(5_000) };
|
|
44
|
+
const response = await fetch(clientId, options);
|
|
45
|
+
if (!response.ok)
|
|
46
|
+
throw new Error(`Client metadata request failed with ${response.status}.`);
|
|
47
|
+
const metadata = (await response.json());
|
|
48
|
+
if (metadata.client_id !== clientId)
|
|
49
|
+
throw new Error('client_id does not match its URL.');
|
|
50
|
+
const jwksUri = typeof metadata.jwks_uri === 'string' ? new URL(metadata.jwks_uri) : undefined;
|
|
51
|
+
if (jwksUri?.protocol !== 'https:' || jwksUri.hostname !== new URL(clientId).hostname)
|
|
52
|
+
throw new Error('jwks_uri must be HTTPS on the client_id domain.');
|
|
53
|
+
const jwks = await fetch(jwksUri, options);
|
|
54
|
+
if (!jwks.ok)
|
|
55
|
+
throw new Error(`Key set request failed with ${jwks.status}.`);
|
|
56
|
+
const { keys } = (await jwks.json());
|
|
57
|
+
if (!Array.isArray(keys))
|
|
58
|
+
throw new Error('The key set has no keys array.');
|
|
59
|
+
return keys.filter(isObject);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Returns a client's keys, loaded at most `maxAge` seconds ago. A load is cached for 5
|
|
63
|
+
* minutes, and a failed one for 30 seconds, so a failing agent isn't refetched per request.
|
|
64
|
+
* A failed reload keeps the keys that last loaded, so a request that forces a reload can't
|
|
65
|
+
* replace them with the failure, but only for an hour after they loaded, so a removed key
|
|
66
|
+
* stops verifying within an hour even while the agent is unreachable.
|
|
67
|
+
*/
|
|
68
|
+
function keys(clientId, maxAge = Constants.keyCacheTtl) {
|
|
69
|
+
const cached = cache.get(clientId);
|
|
70
|
+
if (cached && Date.now() - cached.at < Math.min(cached.ttl, maxAge) * 1_000)
|
|
71
|
+
return cached.keys;
|
|
72
|
+
const last = loaded.get(clientId);
|
|
73
|
+
const entry = { at: Date.now(), ttl: Constants.keyCacheTtl, keys: load(clientId) };
|
|
74
|
+
entry.keys = entry.keys.then((keys) => {
|
|
75
|
+
loaded.set(clientId, { at: Date.now(), keys });
|
|
76
|
+
return keys;
|
|
77
|
+
}, (error) => {
|
|
78
|
+
entry.ttl = Constants.keyRetryAfter;
|
|
79
|
+
const left = last ? Constants.keyStaleTtl - (Date.now() - last.at) / 1_000 : 0;
|
|
80
|
+
if (left <= 0)
|
|
81
|
+
throw error;
|
|
82
|
+
// Cache the fallback no longer than its hour lasts.
|
|
83
|
+
entry.ttl = Math.min(entry.ttl, left);
|
|
84
|
+
return last.keys;
|
|
85
|
+
});
|
|
86
|
+
cache.set(clientId, entry);
|
|
87
|
+
return entry.keys;
|
|
88
|
+
}
|
|
89
|
+
/** The published key with the delegation's `kid`, if it may verify the delegation's `alg`. */
|
|
90
|
+
function signer(jwks, header) {
|
|
91
|
+
if (typeof header.kid !== 'string')
|
|
92
|
+
return undefined;
|
|
93
|
+
return jwks.find((jwk) => {
|
|
94
|
+
const { alg, key_ops, kid, use } = jwk;
|
|
95
|
+
return (kid === header.kid &&
|
|
96
|
+
(use === undefined || use === 'sig') &&
|
|
97
|
+
(key_ops === undefined || (Array.isArray(key_ops) && key_ops.includes('verify'))) &&
|
|
98
|
+
(alg === undefined || alg === header.alg));
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
async verify(request) {
|
|
103
|
+
const token = request.headers.get(Constants.sessionHeader);
|
|
104
|
+
if (!token)
|
|
105
|
+
return {
|
|
106
|
+
status: 'missing',
|
|
107
|
+
code: 400,
|
|
108
|
+
headers,
|
|
109
|
+
reason: body('Send a Poppy-Session header.'),
|
|
110
|
+
};
|
|
111
|
+
const session = Jwt.decode(token);
|
|
112
|
+
if (session?.header.typ !== Constants.sessionType || session.header.alg !== 'ES256')
|
|
113
|
+
return invalid('The Poppy-Session header is not a Session JWT.');
|
|
114
|
+
const { agent_id, ath, aud, htm, htu, iat, iss, jti, sid, sub } = session.claims;
|
|
115
|
+
const strings = [iss, sid, sub, jti];
|
|
116
|
+
if (strings.some((value) => typeof value !== 'string' || !value))
|
|
117
|
+
return invalid('The Session JWT is missing a claim.');
|
|
118
|
+
if (agent_id !== undefined && typeof agent_id !== 'string')
|
|
119
|
+
return invalid('The Session JWT agent_id is not a string.');
|
|
120
|
+
if (!URL.canParse(iss) || new URL(iss).protocol !== 'https:')
|
|
121
|
+
return invalid('The Session JWT iss is not an HTTPS client_id.');
|
|
122
|
+
// Checked before any fetch, so callers can't make the verifier request other URLs.
|
|
123
|
+
if (!clients.includes(iss))
|
|
124
|
+
return invalid('This Personal Agent is not accepted.');
|
|
125
|
+
if (aud !== audience)
|
|
126
|
+
return invalid('The Session JWT is for another Company.');
|
|
127
|
+
if (htm !== request.method || htu !== Jwt.htu(request.url))
|
|
128
|
+
return invalid('The Session JWT is for another request.');
|
|
129
|
+
const now = Math.floor(Date.now() / 1_000);
|
|
130
|
+
if (typeof iat !== 'number' || Math.abs(now - iat) > maxAge)
|
|
131
|
+
return invalid('The Session JWT is outside its time window.');
|
|
132
|
+
const accessToken = Jws.accessToken(request.headers);
|
|
133
|
+
if (accessToken === null)
|
|
134
|
+
return invalid('The Authorization header is malformed.');
|
|
135
|
+
if (accessToken ? ath !== (await Jwt.sha256(accessToken)) : ath !== undefined)
|
|
136
|
+
return invalid('The Session JWT ath does not match the access token.');
|
|
137
|
+
const delegation = typeof session.header.poppy_dlg === 'string'
|
|
138
|
+
? Jwt.decode(session.header.poppy_dlg)
|
|
139
|
+
: undefined;
|
|
140
|
+
if (!delegation)
|
|
141
|
+
return invalid('The Session JWT has no delegation.');
|
|
142
|
+
const { cnf, exp, iat: issued, iss: delegator } = delegation.claims;
|
|
143
|
+
if (delegation.header.typ !== Constants.delegationType || delegator !== iss)
|
|
144
|
+
return invalid('The delegation is not for this Personal Agent.');
|
|
145
|
+
if (typeof exp !== 'number' ||
|
|
146
|
+
typeof issued !== 'number' ||
|
|
147
|
+
exp <= now ||
|
|
148
|
+
// A future `iat` would stretch the delegation past its 24-hour lifetime.
|
|
149
|
+
issued > now + maxAge ||
|
|
150
|
+
exp <= issued ||
|
|
151
|
+
exp - issued > Constants.maxDelegationLifetime)
|
|
152
|
+
return invalid('The delegation has expired.');
|
|
153
|
+
let key;
|
|
154
|
+
try {
|
|
155
|
+
key = signer(await keys(iss), delegation.header);
|
|
156
|
+
// An unknown key may be newly published: reload once the cache is 30 seconds old.
|
|
157
|
+
key ??= signer(await keys(iss, Constants.keyRetryAfter), delegation.header);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return { status: 'unavailable', reason: "The Personal Agent's keys are unavailable." };
|
|
161
|
+
}
|
|
162
|
+
if (!key || !(await Jws.verify(delegation, key, ['ES256', 'PS384'])))
|
|
163
|
+
return invalid('The delegation signature is invalid.');
|
|
164
|
+
const delegated = isObject(cnf) ? cnf.jwk : undefined;
|
|
165
|
+
if (!isObject(delegated) ||
|
|
166
|
+
'd' in delegated ||
|
|
167
|
+
session.header.kid !== (await Jwt.thumbprint(delegated)))
|
|
168
|
+
return invalid('The Session JWT key does not match its delegation.');
|
|
169
|
+
if (!(await Jws.verify(session, delegated, ['ES256'])))
|
|
170
|
+
return invalid('The Session JWT signature is invalid.');
|
|
171
|
+
return {
|
|
172
|
+
status: 'valid',
|
|
173
|
+
value: { agentId: agent_id, clientId: iss, sessionId: sid, userId: sub },
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function isObject(value) {
|
|
179
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
180
|
+
}
|
|
181
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -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", "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
|
@@ -8,9 +8,12 @@
|
|
|
8
8
|
* their own extra sensitive headers in `Prover.headers`.
|
|
9
9
|
*/
|
|
10
10
|
export const request = Object.freeze([
|
|
11
|
+
'agent-id',
|
|
12
|
+
'agent-signature',
|
|
11
13
|
'dpop',
|
|
12
14
|
'identity-attestation',
|
|
13
15
|
'identity-presentation',
|
|
16
|
+
'poppy-session',
|
|
14
17
|
'tempo-id-token',
|
|
15
18
|
]);
|
|
16
19
|
/**
|
|
@@ -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))
|
|
@@ -18,6 +18,7 @@ import * as defaults from '../internal/defaults.js';
|
|
|
18
18
|
import { defaultFeeTokens, resolveFeeToken } from '../internal/fee-token.js';
|
|
19
19
|
import * as MachineTokenCharge from '../internal/machine-token-charge.js';
|
|
20
20
|
import * as Proof from '../internal/proof.js';
|
|
21
|
+
import * as Simulation from '../internal/simulation.js';
|
|
21
22
|
import * as Zone from '../internal/zone.js';
|
|
22
23
|
import * as Methods from '../Methods.js';
|
|
23
24
|
/**
|
|
@@ -283,13 +284,13 @@ export function charge(parameters = {}) {
|
|
|
283
284
|
const { receipts } = account.type === 'local'
|
|
284
285
|
? {
|
|
285
286
|
receipts: [
|
|
286
|
-
await sendTransactionSync(client, {
|
|
287
|
+
await Simulation.run({ account }, () => sendTransactionSync(client, {
|
|
287
288
|
account,
|
|
288
289
|
calls,
|
|
289
290
|
...(feeToken ? { feeToken } : {}),
|
|
290
291
|
nonceKey: 'expiring',
|
|
291
292
|
validBefore,
|
|
292
|
-
}),
|
|
293
|
+
})),
|
|
293
294
|
],
|
|
294
295
|
}
|
|
295
296
|
: await sendCallsSync(client, {
|
|
@@ -324,13 +325,15 @@ export function charge(parameters = {}) {
|
|
|
324
325
|
throw new Error(`Sponsored transaction preparation took too long: less than ${defaults.minRemainingValiditySeconds} seconds of its validity window remain, so the fee payer would reject it.`);
|
|
325
326
|
};
|
|
326
327
|
assertSponsorable();
|
|
327
|
-
|
|
328
|
+
// Preparation estimates gas, which simulates the calls as the signing key. A spending-limit
|
|
329
|
+
// or balance revert there would also revert on chain, at the fee payer's cost, so stop here.
|
|
330
|
+
const prepared = await Simulation.run({ account }, () => prepareTransactionRequest(client, {
|
|
328
331
|
account,
|
|
329
332
|
calls,
|
|
330
333
|
...(feeToken ? { feeToken } : {}),
|
|
331
334
|
nonceKey: 'expiring',
|
|
332
335
|
validBefore,
|
|
333
|
-
});
|
|
336
|
+
}));
|
|
334
337
|
// Estimate before enabling fee-payer mode so Tempo includes sender
|
|
335
338
|
// signature and access-key verification costs in the gas budget.
|
|
336
339
|
prepared.gas = (prepared.gas ?? 0n) + 5000n;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Address } from 'viem';
|
|
2
|
+
import * as Errors from '../../Errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* Returns the revert data of a failed simulation (`eth_estimateGas` or `eth_call`), found anywhere
|
|
5
|
+
* in the error's `cause` chain.
|
|
6
|
+
*/
|
|
7
|
+
export declare function getRevertData(error: unknown): `0x${string}` | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Maps a failed pre-signing simulation to a typed client error.
|
|
10
|
+
*
|
|
11
|
+
* Tempo reverts with `SpendingLimitExceeded()` when the signing access key's remaining limit is
|
|
12
|
+
* below the payment, and with `InsufficientBalance(available, required, token)` when the account
|
|
13
|
+
* holds too little of a token. Both would fail on chain, and a fee payer would pay for the failed
|
|
14
|
+
* transaction, so the client stops before it signs. Returns `undefined` for any other error.
|
|
15
|
+
*/
|
|
16
|
+
export declare function toClientError(error: unknown, parameters: {
|
|
17
|
+
account: {
|
|
18
|
+
address: Address;
|
|
19
|
+
accessKeyAddress?: unknown;
|
|
20
|
+
};
|
|
21
|
+
}): Errors.SpendingLimitExceededError | Errors.InsufficientBalanceError | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Runs a step that simulates the transaction before it is signed, such as
|
|
24
|
+
* `prepareTransactionRequest` (which estimates gas), and rethrows a spending-limit or balance
|
|
25
|
+
* revert as a typed client error.
|
|
26
|
+
*/
|
|
27
|
+
export declare function run<value>(parameters: {
|
|
28
|
+
account: {
|
|
29
|
+
address: Address;
|
|
30
|
+
accessKeyAddress?: unknown;
|
|
31
|
+
};
|
|
32
|
+
}, fn: () => Promise<value>): Promise<value>;
|
|
33
|
+
//# sourceMappingURL=simulation.d.ts.map
|