mppx 0.19.0 → 0.19.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 +9 -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/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 +1 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- 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/package.json +5 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Poppy (Personal Agent Protocol 1.0) values. */
|
|
2
|
+
export declare const Constants: {
|
|
3
|
+
/** Header that carries the Session JWT on every request. */
|
|
4
|
+
readonly sessionHeader: 'Poppy-Session';
|
|
5
|
+
/** Header that names the protocol version. */
|
|
6
|
+
readonly versionHeader: 'Poppy-Version';
|
|
7
|
+
/** Protocol version this adapter speaks. */
|
|
8
|
+
readonly version: '1.0';
|
|
9
|
+
/** `typ` of a Session JWT. */
|
|
10
|
+
readonly sessionType: 'poppy-session+jwt';
|
|
11
|
+
/** `typ` of a delegation JWT. */
|
|
12
|
+
readonly delegationType: 'poppy-delegation+jwt';
|
|
13
|
+
/** Longest a delegation may last, in seconds (spec 5.2). */
|
|
14
|
+
readonly maxDelegationLifetime: number;
|
|
15
|
+
/** Default delegation lifetime, in seconds. */
|
|
16
|
+
readonly defaultDelegationLifetime: number;
|
|
17
|
+
/** Default window, in seconds, around a Session JWT's `iat`. */
|
|
18
|
+
readonly maxAge: 60;
|
|
19
|
+
/** Seconds a client's metadata and keys are cached. */
|
|
20
|
+
readonly keyCacheTtl: 300;
|
|
21
|
+
/** Seconds before a failed load or an unknown key `kid` loads a client's keys again. */
|
|
22
|
+
readonly keyRetryAfter: 30;
|
|
23
|
+
/** Seconds a client's last loaded keys keep verifying while reloads fail. */
|
|
24
|
+
readonly keyStaleTtl: number;
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=Constants.d.ts.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Poppy (Personal Agent Protocol 1.0) values. */
|
|
2
|
+
export const Constants = {
|
|
3
|
+
/** Header that carries the Session JWT on every request. */
|
|
4
|
+
sessionHeader: 'Poppy-Session',
|
|
5
|
+
/** Header that names the protocol version. */
|
|
6
|
+
versionHeader: 'Poppy-Version',
|
|
7
|
+
/** Protocol version this adapter speaks. */
|
|
8
|
+
version: '1.0',
|
|
9
|
+
/** `typ` of a Session JWT. */
|
|
10
|
+
sessionType: 'poppy-session+jwt',
|
|
11
|
+
/** `typ` of a delegation JWT. */
|
|
12
|
+
delegationType: 'poppy-delegation+jwt',
|
|
13
|
+
/** Longest a delegation may last, in seconds (spec 5.2). */
|
|
14
|
+
maxDelegationLifetime: 24 * 60 * 60,
|
|
15
|
+
/** Default delegation lifetime, in seconds. */
|
|
16
|
+
defaultDelegationLifetime: 60 * 60,
|
|
17
|
+
/** Default window, in seconds, around a Session JWT's `iat`. */
|
|
18
|
+
maxAge: 60,
|
|
19
|
+
/** Seconds a client's metadata and keys are cached. */
|
|
20
|
+
keyCacheTtl: 300,
|
|
21
|
+
/** Seconds before a failed load or an unknown key `kid` loads a client's keys again. */
|
|
22
|
+
keyRetryAfter: 30,
|
|
23
|
+
/** Seconds a client's last loaded keys keep verifying while reloads fail. */
|
|
24
|
+
keyStaleTtl: 60 * 60,
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=Constants.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** A verified Poppy Session: who is calling, for whom, through which agent. */
|
|
2
|
+
export type Session = {
|
|
3
|
+
/** The Personal Agent's `client_id`: the URL of its client metadata document. */
|
|
4
|
+
readonly clientId: string;
|
|
5
|
+
/** The pseudonymous User ID the agent assigns this User for this Company. */
|
|
6
|
+
readonly userId: string;
|
|
7
|
+
/** The Session ID. */
|
|
8
|
+
readonly sessionId: string;
|
|
9
|
+
/** The optional Agent ID, when the Personal Agent runs several agents for the User. */
|
|
10
|
+
readonly agentId?: string | undefined;
|
|
11
|
+
};
|
|
12
|
+
/** An ES256 delegated key that signs Session JWTs, used for one User ID only (spec 5.2). */
|
|
13
|
+
export type DelegatedKey = {
|
|
14
|
+
/** The public key as a JWK. */
|
|
15
|
+
readonly jwk: JsonWebKey;
|
|
16
|
+
/** The private key that signs each Session JWT. */
|
|
17
|
+
readonly privateKey: CryptoKey;
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=Types.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type * as Identity from '../../../../identity/Types.js';
|
|
2
|
+
import type { MaybePromise } from '../../../../internal/types.js';
|
|
3
|
+
import type * as Types from '../Types.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 declare function prover(config: prover.Config): Identity.Prover;
|
|
29
|
+
export declare namespace prover {
|
|
30
|
+
type Config = {
|
|
31
|
+
/** The Company's identifier: its OAuth issuer, or `https://{organization.domain}`. */
|
|
32
|
+
readonly audience: string;
|
|
33
|
+
/** The Personal Agent's `client_id`, the HTTPS URL of its client metadata document. */
|
|
34
|
+
readonly clientId: string;
|
|
35
|
+
/** Returns a current delegation for `key`, signed by a key in the agent's `jwks_uri`. */
|
|
36
|
+
readonly delegation: () => MaybePromise<string>;
|
|
37
|
+
/** The delegated key that signs Session JWTs. Use it for this User ID only. */
|
|
38
|
+
readonly key: Types.DelegatedKey;
|
|
39
|
+
/** Origins of this Company that receive the header. */
|
|
40
|
+
readonly scope: Identity.Prover['scope'];
|
|
41
|
+
/** The User ID for this Company: stable, opaque and not derived from personal information. */
|
|
42
|
+
readonly userId: string;
|
|
43
|
+
/** The optional Agent ID, for a Personal Agent that runs several agents for the User. */
|
|
44
|
+
readonly agentId?: string | undefined;
|
|
45
|
+
/** The Session ID. @default a random ID per prover */
|
|
46
|
+
readonly sessionId?: string | undefined;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Signs a delegation (spec 5.2): a short-lived JWT in which a key from the agent's `jwks_uri`
|
|
51
|
+
* vouches for a delegated key. It names no User or Company.
|
|
52
|
+
*/
|
|
53
|
+
export declare function delegate(parameters: delegate.Parameters): Promise<string>;
|
|
54
|
+
export declare namespace delegate {
|
|
55
|
+
type Parameters = {
|
|
56
|
+
/** The Personal Agent's `client_id`. */
|
|
57
|
+
readonly clientId: string;
|
|
58
|
+
/** The ES256 key from `jwks_uri` that signs the delegation, with its `kid`. */
|
|
59
|
+
readonly key: {
|
|
60
|
+
readonly kid: string;
|
|
61
|
+
readonly privateKey: CryptoKey;
|
|
62
|
+
};
|
|
63
|
+
/** The delegated public key. */
|
|
64
|
+
readonly publicKey: JsonWebKey;
|
|
65
|
+
/** Lifetime in seconds, at most 24 hours. @default 3600 */
|
|
66
|
+
readonly expiresIn?: number | undefined;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -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 ["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.19.
|
|
2
|
+
export declare const version = "0.19.1";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.19.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.19.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.19.
|
|
3
|
+
export const version = '0.19.1';
|
|
4
4
|
/** Canonical SDK identifier for this mppx release. */
|
|
5
5
|
export const sdkIdentifier = `mppx/${version}`;
|
|
6
6
|
//# sourceMappingURL=version.js.map
|
|
@@ -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;
|