mppx 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/Challenge.d.ts +59 -3
- package/dist/Challenge.js +162 -21
- package/dist/Errors.d.ts +35 -1
- package/dist/Errors.js +41 -3
- package/dist/Method.js +2 -2
- package/dist/Receipt.d.ts +2 -0
- package/dist/Receipt.js +5 -0
- package/dist/Store.d.ts +39 -10
- package/dist/Store.js +136 -29
- package/dist/cli/cli.d.ts +5 -0
- package/dist/cli/cli.js +135 -135
- package/dist/cli/plugins/index.js +12 -12
- package/dist/cli/sessions/commands.js +9 -0
- package/dist/cli/sessions/store.js +3 -2
- package/dist/cli/validate/challenge.js +15 -1
- package/dist/client/Mppx.d.ts +1 -1
- package/dist/client/Mppx.js +2 -1
- package/dist/client/internal/Fetch.d.ts +2 -1
- package/dist/client/internal/Fetch.js +43 -5
- package/dist/client/internal/PendingSettlement.d.ts +11 -0
- package/dist/client/internal/PendingSettlement.js +22 -0
- package/dist/client/internal/protocols/Mcp.js +8 -0
- package/dist/evm/client/Charge.js +7 -1
- package/dist/evm/server/Charge.d.ts +5 -0
- package/dist/evm/server/Charge.js +148 -0
- package/dist/evm/server/Methods.d.ts +8 -0
- package/dist/evm/server/Methods.js +8 -0
- package/dist/extensions/identity/attestation/Issuer.d.ts +91 -0
- package/dist/extensions/identity/attestation/Issuer.js +159 -0
- package/dist/extensions/identity/attestation/Jwks.js +3 -3
- package/dist/extensions/identity/attestation/Token.js +7 -0
- package/dist/extensions/identity/attestation/Types.d.ts +31 -3
- package/dist/extensions/identity/attestation/index.d.ts +3 -1
- package/dist/extensions/identity/attestation/index.js +3 -1
- package/dist/extensions/identity/link/server/index.js +4 -4
- package/dist/extensions/identity/persona/server/index.js +3 -3
- package/dist/extensions/identity/tempo/Constants.d.ts +4 -0
- package/dist/extensions/identity/tempo/Constants.js +4 -0
- package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
- package/dist/extensions/identity/tempo/client/index.js +151 -0
- package/dist/extensions/identity/tempo/index.d.ts +1 -0
- package/dist/extensions/identity/tempo/index.js +1 -0
- package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
- package/dist/extensions/identity/tempo/issuer/index.js +183 -0
- package/dist/internal/CredentialExpiry.d.ts +30 -0
- package/dist/internal/CredentialExpiry.js +51 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.js +29 -10
- package/dist/middlewares/express.d.ts +7 -2
- package/dist/middlewares/express.js +20 -23
- package/dist/middlewares/internal/express.d.ts +9 -1
- package/dist/middlewares/internal/express.js +348 -2
- package/dist/proxy/Proxy.js +15 -3
- package/dist/proxy/internal/Headers.js +1 -0
- package/dist/proxy/internal/Replay.d.ts +10 -0
- package/dist/proxy/internal/Replay.js +5 -0
- package/dist/server/Mppx.d.ts +1 -1
- package/dist/server/Mppx.js +47 -15
- package/dist/server/NodeListener.js +7 -0
- package/dist/server/Request.d.ts +6 -0
- package/dist/server/Request.js +43 -22
- package/dist/server/internal/challengeMeta.d.ts +10 -0
- package/dist/server/internal/challengeMeta.js +31 -1
- package/dist/server/internal/host.d.ts +4 -0
- package/dist/server/internal/host.js +41 -0
- package/dist/tempo/client/Charge.d.ts +5 -4
- package/dist/tempo/client/Charge.js +210 -38
- package/dist/tempo/client/Subscription.js +3 -0
- package/dist/tempo/internal/zone.d.ts +8 -0
- package/dist/tempo/internal/zone.js +15 -0
- package/dist/tempo/server/Charge.d.ts +19 -0
- package/dist/tempo/server/Charge.js +60 -15
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/transport.js +10 -54
- package/dist/tempo/session/client/ChannelOps.js +1 -1
- package/dist/tempo/session/client/SessionManager.d.ts +4 -1
- package/dist/tempo/session/client/SessionManager.js +8 -2
- package/dist/tempo/session/server/CredentialVerification.js +2 -3
- package/dist/viem/Client.d.ts +2 -0
- package/dist/viem/Client.js +4 -1
- package/dist/x402/Assets.d.ts +6 -0
- package/dist/x402/Assets.js +10 -0
- package/dist/x402/Siwx.d.ts +270 -0
- package/dist/x402/Siwx.js +458 -0
- package/dist/x402/Types.d.ts +72 -12
- package/dist/x402/Types.js +18 -3
- package/dist/x402/client/Exact.js +4 -1
- package/dist/x402/index.d.ts +1 -0
- package/dist/x402/index.js +1 -0
- package/dist/x402/middlewares/express.js +10 -1
- package/dist/x402/server/EvmCharge.d.ts +27 -3
- package/dist/x402/server/EvmCharge.js +27 -2
- package/dist/x402/server/Facilitator.d.ts +42 -3
- package/dist/x402/server/Facilitator.js +126 -16
- package/package.json +1 -1
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import * as JwkThumbprint from '../internal/JwkThumbprint.js';
|
|
2
|
+
import * as Signer from '../internal/Signer.js';
|
|
3
|
+
import { Constants } from './Constants.js';
|
|
4
|
+
import { isIssuer, sign as signToken } from './Token.js';
|
|
5
|
+
/**
|
|
6
|
+
* Creates an attestation issuer: signs audience-bound `Identity-Attestation` tokens with one
|
|
7
|
+
* Ed25519 key and publishes that key as a JSON Web Key Set.
|
|
8
|
+
*
|
|
9
|
+
* It is the building block for any identity provider that already knows who its user is (an
|
|
10
|
+
* OpenID Connect sign-in, a wallet service, Tempo ID): after its own check, it calls `sign` with
|
|
11
|
+
* the fact it verified, one attestation per type, and serves `handle` so servers can fetch its
|
|
12
|
+
* key. `signingKey` may be a {@link SigningKey | Signer} whose private key stays in a KMS, HSM or
|
|
13
|
+
* wallet service.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const issuer = Attestation.Issuer.create({ issuer: 'https://issuer.example', signingKey })
|
|
18
|
+
*
|
|
19
|
+
* // After the user signed in with GitHub:
|
|
20
|
+
* const attestation = await issuer.sign({
|
|
21
|
+
* audience: 'https://api.example',
|
|
22
|
+
* type: 'github',
|
|
23
|
+
* sub: String(user.id),
|
|
24
|
+
* uid: user.accountId,
|
|
25
|
+
* })
|
|
26
|
+
*
|
|
27
|
+
* // In the issuer's fetch handler, before its routes:
|
|
28
|
+
* const answered = await issuer.handle(request)
|
|
29
|
+
* if (answered) return answered
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export function create(config) {
|
|
33
|
+
const issuer = config.issuer.replace(/\/+$/, '');
|
|
34
|
+
// Key discovery appends a path to the issuer, which a query or fragment would swallow.
|
|
35
|
+
if (!isIssuer(issuer) || /[?#]/.test(issuer))
|
|
36
|
+
throw new TypeError('Attestation issuer must be an https URL (http only on localhost) without a query or fragment.');
|
|
37
|
+
if (config.keyId !== undefined && (typeof config.keyId !== 'string' || config.keyId === ''))
|
|
38
|
+
throw new TypeError('Attestation issuer keyId must be a non-empty string.');
|
|
39
|
+
const ttl = config.ttl ?? defaultTtl;
|
|
40
|
+
if (!isTtl(ttl))
|
|
41
|
+
throw new TypeError('Attestation issuer ttl must be a positive integer of seconds.');
|
|
42
|
+
const { publicKey } = Signer.resolve(config.signingKey, ['ed25519']);
|
|
43
|
+
const jwksPath = new URL(issuer).pathname.replace(/\/+$/, '') + Constants.jwksPath;
|
|
44
|
+
const key = (async () => {
|
|
45
|
+
const keyId = config.keyId ?? (await JwkThumbprint.fromKey(publicKey));
|
|
46
|
+
const { crv, kty, x } = await crypto.subtle.exportKey('jwk', publicKey);
|
|
47
|
+
if (kty !== 'OKP' || crv !== 'Ed25519' || !x)
|
|
48
|
+
throw new TypeError('Attestation issuer signingKey must be an Ed25519 key.');
|
|
49
|
+
const jwk = Object.freeze({ alg: Constants.algorithm, crv, kid: keyId, kty, use: 'sig', x });
|
|
50
|
+
return { jwk, keyId };
|
|
51
|
+
})();
|
|
52
|
+
// Fails on the first call rather than as an unhandled rejection.
|
|
53
|
+
key.catch(() => { });
|
|
54
|
+
return {
|
|
55
|
+
issuer,
|
|
56
|
+
async sign(parameters) {
|
|
57
|
+
const { audience, sub, type, uid, cnf, claims } = parameters;
|
|
58
|
+
if (!isIssuer(audience))
|
|
59
|
+
throw new InvalidParametersError('Attestation audience must be an https origin (http only on localhost).');
|
|
60
|
+
if (!isType(type))
|
|
61
|
+
throw new InvalidParametersError('Attestation type must be a structured-field token.');
|
|
62
|
+
if (typeof sub !== 'string' || sub === '')
|
|
63
|
+
throw new InvalidParametersError('Attestation subject must be a non-empty string.');
|
|
64
|
+
const lifetime = parameters.ttl ?? ttl;
|
|
65
|
+
if (!isTtl(lifetime))
|
|
66
|
+
throw new InvalidParametersError('Attestation ttl must be a positive integer of seconds.');
|
|
67
|
+
if (uid !== undefined && (typeof uid !== 'string' || uid === ''))
|
|
68
|
+
throw new InvalidParametersError('Attestation uid must be a non-empty string.');
|
|
69
|
+
if (cnf !== undefined && !isConfirmation(cnf))
|
|
70
|
+
throw new InvalidParametersError('Attestation cnf must be an object whose jkt and addr are strings.');
|
|
71
|
+
if (claims !== undefined &&
|
|
72
|
+
(typeof claims !== 'object' || claims === null || Array.isArray(claims)))
|
|
73
|
+
throw new InvalidParametersError('Attestation claims must be an object.');
|
|
74
|
+
const now = Math.floor(Date.now() / 1_000);
|
|
75
|
+
const payload = {
|
|
76
|
+
...claims,
|
|
77
|
+
...(uid !== undefined && { uid }),
|
|
78
|
+
...(cnf !== undefined && { cnf }),
|
|
79
|
+
aud: new URL(audience).origin,
|
|
80
|
+
exp: now + lifetime,
|
|
81
|
+
iat: now,
|
|
82
|
+
iss: issuer,
|
|
83
|
+
jti: crypto.randomUUID(),
|
|
84
|
+
sub,
|
|
85
|
+
type,
|
|
86
|
+
};
|
|
87
|
+
// Extra claims may carry uid or cnf too: check what is signed, as verify will.
|
|
88
|
+
if (payload.uid !== undefined && (typeof payload.uid !== 'string' || payload.uid === ''))
|
|
89
|
+
throw new InvalidParametersError('Attestation uid must be a non-empty string.');
|
|
90
|
+
if (payload.cnf !== undefined && !isConfirmation(payload.cnf))
|
|
91
|
+
throw new InvalidParametersError('Attestation cnf must be an object whose jkt and addr are strings.');
|
|
92
|
+
// A toJSON hook would make JSON.stringify sign something other than this payload.
|
|
93
|
+
if ('toJSON' in payload ||
|
|
94
|
+
(typeof payload.cnf === 'object' && payload.cnf !== null && 'toJSON' in payload.cnf))
|
|
95
|
+
throw new InvalidParametersError('Attestation claims must not define toJSON.');
|
|
96
|
+
try {
|
|
97
|
+
JSON.stringify(payload);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
throw new InvalidParametersError('Attestation claims must be JSON-serializable.');
|
|
101
|
+
}
|
|
102
|
+
const { keyId } = await key;
|
|
103
|
+
// Anything thrown from here on, other than the length check, is the signer's failure.
|
|
104
|
+
const token = await signToken(payload, { key: config.signingKey, keyId });
|
|
105
|
+
// Servers reject longer tokens, so never hand one out.
|
|
106
|
+
if (token.length > Constants.maxLength)
|
|
107
|
+
throw new InvalidParametersError(`Attestation is longer than ${Constants.maxLength} characters.`);
|
|
108
|
+
return token;
|
|
109
|
+
},
|
|
110
|
+
async jwks() {
|
|
111
|
+
return { keys: [(await key).jwk] };
|
|
112
|
+
},
|
|
113
|
+
async keyResolver({ issuer: claimed, keyId }) {
|
|
114
|
+
const current = await key;
|
|
115
|
+
if (claimed.replace(/\/+$/, '') !== issuer || keyId !== current.keyId)
|
|
116
|
+
return undefined;
|
|
117
|
+
return publicKey;
|
|
118
|
+
},
|
|
119
|
+
async handle(request) {
|
|
120
|
+
if (new URL(request.url).pathname !== jwksPath)
|
|
121
|
+
return undefined;
|
|
122
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
123
|
+
return undefined;
|
|
124
|
+
return Response.json({ keys: [(await key).jwk] }, {
|
|
125
|
+
headers: {
|
|
126
|
+
'Access-Control-Allow-Origin': '*',
|
|
127
|
+
'Cache-Control': 'public, max-age=300',
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Thrown by {@link Issuer.sign} for parameters it cannot sign, such as a malformed claim or a token
|
|
135
|
+
* longer than servers accept. Any other error comes from the signing key, such as a remote signer
|
|
136
|
+
* that is unavailable.
|
|
137
|
+
*/
|
|
138
|
+
export class InvalidParametersError extends TypeError {
|
|
139
|
+
name = 'Attestation.Issuer.InvalidParametersError';
|
|
140
|
+
}
|
|
141
|
+
/** Whether a value can be sent as a structured-field token in `Identity-Attestation-Required`. */
|
|
142
|
+
function isType(value) {
|
|
143
|
+
return typeof value === 'string' && /^[A-Za-z*][A-Za-z0-9!#$%&'*+\-.^_`|~:/]*$/.test(value);
|
|
144
|
+
}
|
|
145
|
+
/** Whether a value is a usable attestation lifetime: a positive integer of seconds, at most a year. */
|
|
146
|
+
function isTtl(value) {
|
|
147
|
+
return (typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= 31_536_000);
|
|
148
|
+
}
|
|
149
|
+
/** Whether a value is a `cnf` object whose `jkt` and `addr`, when present, are strings. */
|
|
150
|
+
export function isConfirmation(value) {
|
|
151
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
152
|
+
return false;
|
|
153
|
+
const { addr, jkt } = value;
|
|
154
|
+
return ((jkt === undefined || typeof jkt === 'string') &&
|
|
155
|
+
(addr === undefined || typeof addr === 'string'));
|
|
156
|
+
}
|
|
157
|
+
/** Default attestation lifetime, in seconds. */
|
|
158
|
+
const defaultTtl = 3_600;
|
|
159
|
+
//# sourceMappingURL=Issuer.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { unwrapFetch } from '../../../client/internal/Fetch.js';
|
|
1
|
+
import { unwrapFetch, withoutPayment } from '../../../client/internal/Fetch.js';
|
|
2
2
|
import { Constants } from './Constants.js';
|
|
3
3
|
/**
|
|
4
4
|
* Creates a key resolver that reads an issuer's JSON Web Key Set.
|
|
@@ -24,12 +24,12 @@ export function resolver(options = {}) {
|
|
|
24
24
|
function load(issuer) {
|
|
25
25
|
const startedAt = Date.now();
|
|
26
26
|
const keys = (async () => {
|
|
27
|
-
const response = await fetch(`${issuer.replace(/\/+$/, '')}${Constants.jwksPath}`, {
|
|
27
|
+
const response = await fetch(`${issuer.replace(/\/+$/, '')}${Constants.jwksPath}`, withoutPayment({
|
|
28
28
|
headers: { accept: 'application/json' },
|
|
29
29
|
signal: AbortSignal.timeout(timeout),
|
|
30
30
|
// Workers reject 'error'; a redirect is not ok, so it fails below.
|
|
31
31
|
redirect: 'manual',
|
|
32
|
-
});
|
|
32
|
+
}));
|
|
33
33
|
if (!response.ok)
|
|
34
34
|
throw new Error(`JWKS request failed with ${response.status}.`);
|
|
35
35
|
const body = (await response.json());
|
|
@@ -70,6 +70,13 @@ export async function verify(token, options) {
|
|
|
70
70
|
return invalid('The attestation has no subject.');
|
|
71
71
|
if (claims.jti !== undefined && typeof claims.jti !== 'string')
|
|
72
72
|
return invalid('The attestation ID is malformed.');
|
|
73
|
+
if (claims.uid !== undefined && (typeof claims.uid !== 'string' || claims.uid === ''))
|
|
74
|
+
return invalid('The attestation user ID is malformed.');
|
|
75
|
+
if (claims.cnf !== undefined &&
|
|
76
|
+
(!isObject(claims.cnf) ||
|
|
77
|
+
(claims.cnf.jkt !== undefined && typeof claims.cnf.jkt !== 'string') ||
|
|
78
|
+
(claims.cnf.addr !== undefined && typeof claims.cnf.addr !== 'string')))
|
|
79
|
+
return invalid('The attestation confirmation is malformed.');
|
|
73
80
|
if (!isTime(claims.iat) || !isTime(claims.exp))
|
|
74
81
|
return invalid('The attestation times are malformed.');
|
|
75
82
|
const now = options.now ?? Math.floor(Date.now() / 1_000);
|
|
@@ -11,9 +11,16 @@ export type Claims = {
|
|
|
11
11
|
readonly iss: string;
|
|
12
12
|
/** Origin of the server the attestation is for, such as `https://api.example`. */
|
|
13
13
|
readonly aud: string;
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Attested subject: an email address or phone number, or the provider's stable identifier for
|
|
16
|
+
* an account (such as a GitHub user ID), never a handle that can change.
|
|
17
|
+
*/
|
|
15
18
|
readonly sub: string;
|
|
16
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Attestation type: any structured-field token the issuer and server agree on, such as
|
|
21
|
+
* `email`, `phone`, `github`, `x` or `tempo-id`. One attestation states one fact; an issuer
|
|
22
|
+
* that knows several of a user's accounts signs one attestation of each type.
|
|
23
|
+
*/
|
|
17
24
|
readonly type: string;
|
|
18
25
|
/** Issued-at time, in Unix seconds. */
|
|
19
26
|
readonly iat: number;
|
|
@@ -21,7 +28,28 @@ export type Claims = {
|
|
|
21
28
|
readonly exp: number;
|
|
22
29
|
/** Unique attestation identifier. */
|
|
23
30
|
readonly jti?: string | undefined;
|
|
24
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The issuer's identifier for the user behind the subject, the same across that issuer's
|
|
33
|
+
* attestations of every type, so a server can tell that an `email` and a `github`
|
|
34
|
+
* attestation from one issuer name the same user.
|
|
35
|
+
*/
|
|
36
|
+
readonly uid?: string | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Confirmation (RFC 7800): what the attestation is bound to, such as the key that must sign
|
|
39
|
+
* each request (`jkt`, an RFC 7638 thumbprint) or the account that pays (`addr`).
|
|
40
|
+
*/
|
|
41
|
+
readonly cnf?: Confirmation | undefined;
|
|
42
|
+
} & Readonly<Record<string, unknown>>;
|
|
43
|
+
/**
|
|
44
|
+
* What an attestation is bound to (RFC 7800 `cnf`). Issuers may add other members; a server
|
|
45
|
+
* enforces the ones it understands.
|
|
46
|
+
*/
|
|
47
|
+
export type Confirmation = {
|
|
48
|
+
/** RFC 7638 thumbprint of the key that must sign each request. */
|
|
49
|
+
readonly jkt?: string | undefined;
|
|
50
|
+
/** Address of the account that must pay, such as a Tempo Account. */
|
|
51
|
+
readonly addr?: string | undefined;
|
|
52
|
+
} & Readonly<Record<string, unknown>>;
|
|
25
53
|
/**
|
|
26
54
|
* Resolves the issuer's public key for an attestation's `kid`. Returns
|
|
27
55
|
* `undefined` for an unknown or malformed `kid`, and throws only when the keys
|
|
@@ -4,11 +4,13 @@
|
|
|
4
4
|
* to and sent in `Identity-Attestation`.
|
|
5
5
|
*
|
|
6
6
|
* Servers require one with `Server.verifier`, clients present and obtain them with
|
|
7
|
-
* `Client.prover`, and issuers sign them with `sign` and publish their keys as a JSON Web Key
|
|
7
|
+
* `Client.prover`, and issuers sign them with `Issuer.create` (or `sign`) and publish their keys as a JSON Web Key
|
|
8
8
|
* Set that `Jwks.resolver` reads.
|
|
9
9
|
*/
|
|
10
10
|
/** Client prover that presents and obtains attestations. */
|
|
11
11
|
export * as Client from './client/index.js';
|
|
12
|
+
/** Issuer that signs attestations and publishes its key. */
|
|
13
|
+
export * as Issuer from './Issuer.js';
|
|
12
14
|
/** Issuer JSON Web Key Set resolver. */
|
|
13
15
|
export * as Jwks from './Jwks.js';
|
|
14
16
|
/** Server verifier that requires an attestation. */
|
|
@@ -4,11 +4,13 @@
|
|
|
4
4
|
* to and sent in `Identity-Attestation`.
|
|
5
5
|
*
|
|
6
6
|
* Servers require one with `Server.verifier`, clients present and obtain them with
|
|
7
|
-
* `Client.prover`, and issuers sign them with `sign` and publish their keys as a JSON Web Key
|
|
7
|
+
* `Client.prover`, and issuers sign them with `Issuer.create` (or `sign`) and publish their keys as a JSON Web Key
|
|
8
8
|
* Set that `Jwks.resolver` reads.
|
|
9
9
|
*/
|
|
10
10
|
/** Client prover that presents and obtains attestations. */
|
|
11
11
|
export * as Client from './client/index.js';
|
|
12
|
+
/** Issuer that signs attestations and publishes its key. */
|
|
13
|
+
export * as Issuer from './Issuer.js';
|
|
12
14
|
/** Issuer JSON Web Key Set resolver. */
|
|
13
15
|
export * as Jwks from './Jwks.js';
|
|
14
16
|
/** Server verifier that requires an attestation. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Base64, Bytes } from 'ox';
|
|
2
|
-
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
2
|
+
import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
|
|
3
3
|
import { Constants } from '../Constants.js';
|
|
4
4
|
/**
|
|
5
5
|
* Creates a request-stage verifier that requires a Link Agent Attestation Token: proof that
|
|
@@ -414,7 +414,7 @@ export function presentationVerifier(config) {
|
|
|
414
414
|
const maxAge = config.maxAge ?? Constants.nonceTtl;
|
|
415
415
|
const base = unwrapFetch((config.fetch ?? globalThis.fetch));
|
|
416
416
|
// The SDK refuses redirects with `redirect: 'error'`, which Workers reject: a 3xx is a failure either way.
|
|
417
|
-
const fetch = (input, init) => base(input, init.redirect === 'error' ? { ...init, redirect: 'manual' } : init);
|
|
417
|
+
const fetch = (input, init) => base(input, withoutPayment(init.redirect === 'error' ? { ...init, redirect: 'manual' } : init));
|
|
418
418
|
const getMetadata = metadata({ fetch, issuer, maxAge: 3_600_000, timeout });
|
|
419
419
|
return {
|
|
420
420
|
async verifyClaims(presentation, options) {
|
|
@@ -482,11 +482,11 @@ function equal(a, b) {
|
|
|
482
482
|
async function getJson(url, options) {
|
|
483
483
|
if (new URL(url).origin !== options.origin)
|
|
484
484
|
throw new Error(`${url} is not on ${options.origin}.`);
|
|
485
|
-
const response = await options.fetch(url, {
|
|
485
|
+
const response = await options.fetch(url, withoutPayment({
|
|
486
486
|
headers: { accept: 'application/json' },
|
|
487
487
|
redirect: 'manual',
|
|
488
488
|
signal: AbortSignal.timeout(options.timeout),
|
|
489
|
-
});
|
|
489
|
+
}));
|
|
490
490
|
if (!response.ok)
|
|
491
491
|
throw new Error(`${url} answered ${response.status}.`);
|
|
492
492
|
const body = (await response.json());
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { verifyMessage } from 'viem';
|
|
2
|
-
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
2
|
+
import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
|
|
3
3
|
import { Constants } from '../Constants.js';
|
|
4
4
|
import * as Did from '../Did.js';
|
|
5
5
|
/**
|
|
@@ -45,7 +45,7 @@ export function create(config) {
|
|
|
45
45
|
// Unwrapped, and resolved per call: a Persona request must never pay a Payment Challenge,
|
|
46
46
|
// even when an mppx client polyfilled globalThis.fetch.
|
|
47
47
|
const fetch = unwrapFetch(config.fetch ?? globalThis.fetch);
|
|
48
|
-
const response = await fetch(new URL(path, apiUrl), {
|
|
48
|
+
const response = await fetch(new URL(path, apiUrl), withoutPayment({
|
|
49
49
|
...init,
|
|
50
50
|
// A redirect is a failure: never send the bearer key on, nor read another origin's body.
|
|
51
51
|
redirect: 'manual',
|
|
@@ -56,7 +56,7 @@ export function create(config) {
|
|
|
56
56
|
...(init.body !== undefined && { 'Content-Type': 'application/json' }),
|
|
57
57
|
},
|
|
58
58
|
signal: AbortSignal.timeout(timeout),
|
|
59
|
-
});
|
|
59
|
+
}));
|
|
60
60
|
// Never surface the upstream body: it may carry request details.
|
|
61
61
|
if (!response.ok)
|
|
62
62
|
throw new PersonaError(`The Persona API returned ${response.status}.`);
|
|
@@ -4,6 +4,10 @@ export declare const Constants: {
|
|
|
4
4
|
readonly type: 'tempo-id';
|
|
5
5
|
/** Tempo ID in production: the issuer of every access token. */
|
|
6
6
|
readonly issuer: 'https://id.tempo.xyz';
|
|
7
|
+
/** Path, relative to a Tempo ID attestation issuer's URL, that exchanges a token for an attestation. */
|
|
8
|
+
readonly attestPath: '/tempo-id/attest';
|
|
9
|
+
/** Attestation types a Tempo ID attestation issuer signs: the user's Tempo ID and verified email. */
|
|
10
|
+
readonly attestationTypes: readonly ('tempo-id' | 'email')[];
|
|
7
11
|
/** Header that carries the user's ID token, for their email address. */
|
|
8
12
|
readonly idTokenHeader: 'Tempo-Id-Token';
|
|
9
13
|
/** Seconds a DPoP proof is accepted after its `iat`. */
|
|
@@ -4,6 +4,10 @@ export const Constants = {
|
|
|
4
4
|
type: 'tempo-id',
|
|
5
5
|
/** Tempo ID in production: the issuer of every access token. */
|
|
6
6
|
issuer: 'https://id.tempo.xyz',
|
|
7
|
+
/** Path, relative to a Tempo ID attestation issuer's URL, that exchanges a token for an attestation. */
|
|
8
|
+
attestPath: '/tempo-id/attest',
|
|
9
|
+
/** Attestation types a Tempo ID attestation issuer signs: the user's Tempo ID and verified email. */
|
|
10
|
+
attestationTypes: ['tempo-id', 'email'],
|
|
7
11
|
/** Header that carries the user's ID token, for their email address. */
|
|
8
12
|
idTokenHeader: 'Tempo-Id-Token',
|
|
9
13
|
/** Seconds a DPoP proof is accepted after its `iat`. */
|
|
@@ -31,4 +31,67 @@ export declare namespace prover {
|
|
|
31
31
|
readonly scope: Identity.Prover['scope'];
|
|
32
32
|
};
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates a prover that presents Tempo ID attestations, obtaining them from a Tempo ID
|
|
36
|
+
* attestation issuer (`TempoId.Issuer`) when a server asks: an `Attestation.Client.prover` whose
|
|
37
|
+
* `acquire` exchanges the user's access token (and ID token, for `email`) at the issuer.
|
|
38
|
+
*
|
|
39
|
+
* Unlike {@link prover}, the access token goes only to the issuer: servers get short-lived
|
|
40
|
+
* attestations bound to their origin, and verify them like any other issuer's.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* const mppx = Mppx.create({
|
|
45
|
+
* identity: [
|
|
46
|
+
* TempoId.Client.attestations({
|
|
47
|
+
* accessToken: () => accounts.session.accessToken(),
|
|
48
|
+
* idToken: () => accounts.session.get()?.idToken,
|
|
49
|
+
* issuer: 'https://attest.example',
|
|
50
|
+
* scope: ['https://api.example'],
|
|
51
|
+
* }),
|
|
52
|
+
* ],
|
|
53
|
+
* methods: [tempo({ account })],
|
|
54
|
+
* })
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare function attestations(config: attestations.Config): Identity.Prover;
|
|
58
|
+
export declare namespace attestations {
|
|
59
|
+
type Config = Omit<attest.Parameters, 'audience' | 'type'> & {
|
|
60
|
+
/** Origins that may receive attestations and ask for new ones. */
|
|
61
|
+
readonly scope: Identity.Prover['scope'];
|
|
62
|
+
/** Attestation types to obtain. @default ['tempo-id', 'email'] */
|
|
63
|
+
readonly types?: readonly string[] | undefined;
|
|
64
|
+
/** Attestations already held, such as from storage. */
|
|
65
|
+
readonly attestations?: readonly string[] | undefined;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Exchanges a Tempo ID access token for one attestation at a Tempo ID attestation issuer.
|
|
70
|
+
* Resolves with `undefined` when the issuer refuses this user that type (403, such as `email`
|
|
71
|
+
* without a verified address), and throws on any other failure.
|
|
72
|
+
*/
|
|
73
|
+
export declare function attest(parameters: attest.Parameters): Promise<{
|
|
74
|
+
readonly attestation: string;
|
|
75
|
+
readonly expiresAt: Date;
|
|
76
|
+
} | undefined>;
|
|
77
|
+
export declare namespace attest {
|
|
78
|
+
type Parameters = {
|
|
79
|
+
/** The Tempo ID attestation issuer's URL. */
|
|
80
|
+
readonly issuer: string;
|
|
81
|
+
/** Origin of the server the attestation is for. */
|
|
82
|
+
readonly audience: string;
|
|
83
|
+
/** Attestation type, such as `tempo-id` or `email`. */
|
|
84
|
+
readonly type: string;
|
|
85
|
+
/** Returns a live Tempo ID access token, such as `accounts.session.accessToken`. */
|
|
86
|
+
readonly accessToken: () => MaybePromise<string>;
|
|
87
|
+
/** The DPoP key that binds the token. Absent, the token is sent as a Bearer token. */
|
|
88
|
+
readonly dpop?: Types.DpopKey | undefined;
|
|
89
|
+
/** Seconds to wait for the issuer before the exchange fails. @default 10 */
|
|
90
|
+
readonly timeout?: number | undefined;
|
|
91
|
+
/** Returns the user's ID token, which `email` needs and an issuer's policy may read. */
|
|
92
|
+
readonly idToken?: (() => MaybePromise<string | undefined>) | undefined;
|
|
93
|
+
/** Fetch implementation. @default globalThis.fetch */
|
|
94
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
34
97
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { Base64 } from 'ox';
|
|
2
|
+
import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
|
|
2
3
|
import * as Credential from '../../../../Credential.js';
|
|
4
|
+
import * as Attestation from '../../attestation/client/index.js';
|
|
5
|
+
import { Constants as AttestationConstants } from '../../attestation/Constants.js';
|
|
6
|
+
import { decode as decodeAttestation, isIssuer, parseHeader } from '../../attestation/Token.js';
|
|
3
7
|
import { Constants } from '../Constants.js';
|
|
4
8
|
import * as Jwt from '../internal/Jwt.js';
|
|
5
9
|
/**
|
|
@@ -42,6 +46,153 @@ export function prover(config) {
|
|
|
42
46
|
},
|
|
43
47
|
};
|
|
44
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* Creates a prover that presents Tempo ID attestations, obtaining them from a Tempo ID
|
|
51
|
+
* attestation issuer (`TempoId.Issuer`) when a server asks: an `Attestation.Client.prover` whose
|
|
52
|
+
* `acquire` exchanges the user's access token (and ID token, for `email`) at the issuer.
|
|
53
|
+
*
|
|
54
|
+
* Unlike {@link prover}, the access token goes only to the issuer: servers get short-lived
|
|
55
|
+
* attestations bound to their origin, and verify them like any other issuer's.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* const mppx = Mppx.create({
|
|
60
|
+
* identity: [
|
|
61
|
+
* TempoId.Client.attestations({
|
|
62
|
+
* accessToken: () => accounts.session.accessToken(),
|
|
63
|
+
* idToken: () => accounts.session.get()?.idToken,
|
|
64
|
+
* issuer: 'https://attest.example',
|
|
65
|
+
* scope: ['https://api.example'],
|
|
66
|
+
* }),
|
|
67
|
+
* ],
|
|
68
|
+
* methods: [tempo({ account })],
|
|
69
|
+
* })
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
export function attestations(config) {
|
|
73
|
+
assertIssuer(config.issuer);
|
|
74
|
+
const issuer = config.issuer.replace(/\/+$/, '');
|
|
75
|
+
const types = config.types ?? Constants.attestationTypes;
|
|
76
|
+
let current;
|
|
77
|
+
// Only the latest lookup may replace `current`, so a slow lookup cannot roll it back.
|
|
78
|
+
let latest = 0;
|
|
79
|
+
// Used while the access token cannot be read: presents nothing, keeps the cache.
|
|
80
|
+
const unavailable = { user: undefined, prover: create(undefined, undefined) };
|
|
81
|
+
function create(user, held) {
|
|
82
|
+
return Attestation.prover({
|
|
83
|
+
attestations: held,
|
|
84
|
+
issuers: [config.issuer],
|
|
85
|
+
scope: config.scope,
|
|
86
|
+
types,
|
|
87
|
+
async acquire({ audience, issuer, type }) {
|
|
88
|
+
const result = await attest({ ...config, audience, issuer, type });
|
|
89
|
+
if (!result)
|
|
90
|
+
return undefined;
|
|
91
|
+
// Only keep an attestation for the user this cache belongs to.
|
|
92
|
+
const uid = decodeAttestation(result.attestation)?.claims.uid;
|
|
93
|
+
return user !== undefined && uid === user ? result.attestation : undefined;
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async function resolve() {
|
|
98
|
+
const lookup = ++latest;
|
|
99
|
+
let user;
|
|
100
|
+
try {
|
|
101
|
+
const sub = Jwt.decode(await config.accessToken())?.claims.sub;
|
|
102
|
+
user = typeof sub === 'string' && sub ? sub : undefined;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// The token could not be read this time: present nothing, but keep the user's cache.
|
|
106
|
+
return unavailable;
|
|
107
|
+
}
|
|
108
|
+
if (current && current.user === user)
|
|
109
|
+
return current;
|
|
110
|
+
// Stored attestations are restored only for this issuer and the user they name.
|
|
111
|
+
const held = current
|
|
112
|
+
? undefined
|
|
113
|
+
: config.attestations?.filter((token) => {
|
|
114
|
+
const claims = decodeAttestation(token)?.claims;
|
|
115
|
+
return user !== undefined && claims?.iss === issuer && claims.uid === user;
|
|
116
|
+
});
|
|
117
|
+
const entry = { user, prover: create(user, held) };
|
|
118
|
+
if (lookup === latest)
|
|
119
|
+
current = entry;
|
|
120
|
+
return entry;
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
scope: config.scope,
|
|
124
|
+
async prove(request, context) {
|
|
125
|
+
const { prover, user } = await resolve();
|
|
126
|
+
// A request already in flight (such as a payment retry) may still carry the previous
|
|
127
|
+
// user's attestations from this prover: drop those, and only those, naming another user.
|
|
128
|
+
const sent = parseHeader(request.headers.get(AttestationConstants.header));
|
|
129
|
+
const kept = sent.filter((token) => {
|
|
130
|
+
const claims = decodeAttestation(token)?.claims;
|
|
131
|
+
const ours = claims?.iss === issuer && types.includes(claims.type) && claims.uid !== undefined;
|
|
132
|
+
return !ours || (user !== undefined && claims.uid === user);
|
|
133
|
+
});
|
|
134
|
+
if (kept.length !== sent.length) {
|
|
135
|
+
const headers = new Headers(request.headers);
|
|
136
|
+
if (kept.length > 0)
|
|
137
|
+
headers.set(AttestationConstants.header, kept.join(', '));
|
|
138
|
+
else
|
|
139
|
+
headers.delete(AttestationConstants.header);
|
|
140
|
+
request = new Request(request, { headers });
|
|
141
|
+
}
|
|
142
|
+
return prover.prove(request, context);
|
|
143
|
+
},
|
|
144
|
+
async prepare(response, context) {
|
|
145
|
+
return (await resolve()).prover.prepare?.(response, context);
|
|
146
|
+
},
|
|
147
|
+
async retry(response, context) {
|
|
148
|
+
return (await resolve()).prover.retry?.(response, context);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Exchanges a Tempo ID access token for one attestation at a Tempo ID attestation issuer.
|
|
154
|
+
* Resolves with `undefined` when the issuer refuses this user that type (403, such as `email`
|
|
155
|
+
* without a verified address), and throws on any other failure.
|
|
156
|
+
*/
|
|
157
|
+
export async function attest(parameters) {
|
|
158
|
+
const { audience, dpop, type } = parameters;
|
|
159
|
+
assertIssuer(parameters.issuer);
|
|
160
|
+
const issuer = parameters.issuer.replace(/\/+$/, '');
|
|
161
|
+
const fetch = unwrapFetch(parameters.fetch ?? globalThis.fetch);
|
|
162
|
+
const accessToken = await parameters.accessToken();
|
|
163
|
+
const url = issuer + Constants.attestPath;
|
|
164
|
+
const headers = new Headers({
|
|
165
|
+
Authorization: `${dpop ? 'DPoP' : 'Bearer'} ${accessToken}`,
|
|
166
|
+
'Content-Type': 'application/json',
|
|
167
|
+
});
|
|
168
|
+
if (dpop)
|
|
169
|
+
headers.set('DPoP', await proof(dpop, accessToken, new Request(url, { method: 'POST' })));
|
|
170
|
+
// Sent on every exchange: an issuer's `allow` may read the verified email for any type.
|
|
171
|
+
const idToken = await parameters.idToken?.();
|
|
172
|
+
if (idToken)
|
|
173
|
+
headers.set(Constants.idTokenHeader, idToken);
|
|
174
|
+
// Never pays: an issuer that answers 402 fails the exchange.
|
|
175
|
+
const response = await fetch(url, withoutPayment({
|
|
176
|
+
body: JSON.stringify({ audience, type }),
|
|
177
|
+
headers,
|
|
178
|
+
method: 'POST',
|
|
179
|
+
redirect: 'manual',
|
|
180
|
+
signal: AbortSignal.timeout((parameters.timeout ?? 10) * 1_000),
|
|
181
|
+
}));
|
|
182
|
+
const body = (await response.json().catch(() => ({})));
|
|
183
|
+
if (response.status === 403)
|
|
184
|
+
return undefined;
|
|
185
|
+
if (!response.ok)
|
|
186
|
+
throw new Error(typeof body.error === 'string' ? body.error : `The issuer answered ${response.status}.`);
|
|
187
|
+
if (typeof body.attestation !== 'string' || typeof body.expires_at !== 'string')
|
|
188
|
+
throw new Error('The issuer returned a malformed attestation.');
|
|
189
|
+
return { attestation: body.attestation, expiresAt: new Date(body.expires_at) };
|
|
190
|
+
}
|
|
191
|
+
/** Throws unless `issuer` is https (http only on localhost), since it receives the user's tokens. */
|
|
192
|
+
function assertIssuer(issuer) {
|
|
193
|
+
if (!isIssuer(issuer.replace(/\/+$/, '')) || /[?#]/.test(issuer))
|
|
194
|
+
throw new TypeError('The Tempo ID attestation issuer must be an https URL (http only on localhost) without a query or fragment.');
|
|
195
|
+
}
|
|
45
196
|
/** Signs a DPoP proof (RFC 9449) of `accessToken` for one request. */
|
|
46
197
|
async function proof(dpop, accessToken, request) {
|
|
47
198
|
const { crv, kty, x, y } = dpop.jwk;
|