mppx 0.18.1 → 0.19.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/Errors.d.ts +11 -4
  3. package/dist/Errors.js +13 -4
  4. package/dist/cli/cli.js +25 -25
  5. package/dist/cli/plugins/index.js +12 -12
  6. package/dist/extensions/identity/Types.d.ts +26 -0
  7. package/dist/extensions/identity/attestation/Token.d.ts +6 -4
  8. package/dist/extensions/identity/attestation/Token.js +11 -5
  9. package/dist/extensions/identity/index.d.ts +2 -0
  10. package/dist/extensions/identity/index.js +2 -0
  11. package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
  12. package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
  13. package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
  14. package/dist/extensions/identity/internal/Signer.d.ts +20 -0
  15. package/dist/extensions/identity/internal/Signer.js +94 -0
  16. package/dist/extensions/identity/tap/client/index.d.ts +6 -2
  17. package/dist/extensions/identity/tap/client/index.js +2 -0
  18. package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
  19. package/dist/extensions/identity/tempo/Constants.js +14 -0
  20. package/dist/extensions/identity/tempo/Types.d.ts +31 -0
  21. package/dist/extensions/identity/tempo/Types.js +2 -0
  22. package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
  23. package/dist/extensions/identity/tempo/client/index.js +60 -0
  24. package/dist/extensions/identity/tempo/index.d.ts +5 -0
  25. package/dist/extensions/identity/tempo/index.js +4 -0
  26. package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
  27. package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
  28. package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
  29. package/dist/extensions/identity/tempo/server/index.js +247 -0
  30. package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
  31. package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
  32. package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
  33. package/dist/extensions/identity/world/Constants.d.ts +50 -0
  34. package/dist/extensions/identity/world/Constants.js +50 -0
  35. package/dist/extensions/identity/world/Types.d.ts +52 -0
  36. package/dist/extensions/identity/world/Types.js +2 -0
  37. package/dist/extensions/identity/world/client/index.d.ts +103 -0
  38. package/dist/extensions/identity/world/client/index.js +208 -0
  39. package/dist/extensions/identity/world/index.d.ts +6 -0
  40. package/dist/extensions/identity/world/index.js +5 -0
  41. package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
  42. package/dist/extensions/identity/world/internal/Idp.js +265 -0
  43. package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
  44. package/dist/extensions/identity/world/issuer/index.js +520 -0
  45. package/dist/extensions/identity/world/server/index.d.ts +49 -0
  46. package/dist/extensions/identity/world/server/index.js +63 -0
  47. package/dist/identity/Headers.d.ts +1 -1
  48. package/dist/identity/Headers.js +6 -1
  49. package/dist/identity/Types.d.ts +5 -0
  50. package/dist/internal/version.d.ts +2 -2
  51. package/dist/internal/version.js +1 -1
  52. package/dist/server/Mppx.js +2 -1
  53. package/dist/tempo/client/Charge.js +32 -12
  54. package/dist/tempo/internal/zone.d.ts +27 -0
  55. package/dist/tempo/internal/zone.js +54 -7
  56. package/dist/tempo/server/internal/html.gen.js +1 -1
  57. package/package.json +9 -1
  58. /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
@@ -2,6 +2,32 @@ import type { MaybePromise } from '../../internal/types.js';
2
2
  import type { Algorithms } from './Constants.js';
3
3
  /** RFC 9421 algorithms implemented by the HTTP message signature signer and verifier. */
4
4
  export type SignatureAlgorithm = (typeof Algorithms)[keyof typeof Algorithms];
5
+ /**
6
+ * A key pair whose private key stays outside this process, such as in a cloud KMS, an HSM or a
7
+ * wallet service like Turnkey.
8
+ *
9
+ * mppx checks every signature `sign` returns against `publicKey` before it uses it, so a wrong
10
+ * key, a DER- or base64-encoded signature or a wrong RSA-PSS salt fails on the client instead of
11
+ * at the server.
12
+ */
13
+ export type Signer = {
14
+ /**
15
+ * The public key of the remote private key: Ed25519 or RSA-PSS SHA-512, with the `verify`
16
+ * usage. Its algorithm is the signature algorithm, and identifiers that derive from the key
17
+ * (such as a Web Bot Auth `keyid`) are computed from it.
18
+ */
19
+ readonly publicKey: CryptoKey;
20
+ /**
21
+ * Signs `payload` (the complete message, not a digest: the RFC 9421 signature base or the JWS
22
+ * signing input) and resolves with the raw signature bytes: 64 bytes for Ed25519, or the RSA
23
+ * modulus length for RSA-PSS SHA-512 (SHA-512, MGF1 with SHA-512, 64-byte salt).
24
+ */
25
+ readonly sign: (parameters: {
26
+ readonly payload: Uint8Array;
27
+ }) => Promise<Uint8Array>;
28
+ };
29
+ /** A local `CryptoKeyPair`, or a {@link Signer} whose private key stays elsewhere. */
30
+ export type SigningKey = CryptoKeyPair | Signer;
5
31
  /** Resolves a trusted public key for a parsed request signature. */
6
32
  export type KeyResolver = (parameters: {
7
33
  /** RFC 9421 algorithm declared by the signature. */
@@ -1,3 +1,4 @@
1
+ import type { SigningKey } from '../Types.js';
1
2
  import type * as Types from './Types.js';
2
3
  /** A decoded, unverified attestation. */
3
4
  export type Decoded = {
@@ -28,12 +29,13 @@ export type VerifyResult = {
28
29
  /**
29
30
  * Signs attestation claims as a compact JWS (EdDSA over Ed25519).
30
31
  *
31
- * For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
32
- * published in the issuer's JSON Web Key Set.
32
+ * For issuers. `key` is an Ed25519 key pair, or a {@link SigningKey | Signer} whose private key
33
+ * stays in a KMS, HSM or wallet service. `keyId` defaults to the RFC 7638 thumbprint of its public
34
+ * key, the `kid` an issuer's JSON Web Key Set publishes for it.
33
35
  */
34
36
  export declare function sign(claims: Types.Claims, options: {
35
- readonly key: CryptoKey;
36
- readonly keyId: string;
37
+ readonly key: SigningKey;
38
+ readonly keyId?: string | undefined;
37
39
  }): Promise<string>;
38
40
  /** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
39
41
  export declare function decode(token: string): Decoded | undefined;
@@ -1,16 +1,22 @@
1
1
  import { Base64 } from 'ox';
2
+ import { Algorithms } from '../Constants.js';
3
+ import * as JwkThumbprint from '../internal/JwkThumbprint.js';
4
+ import * as Signer from '../internal/Signer.js';
2
5
  import { Constants } from './Constants.js';
3
6
  /**
4
7
  * Signs attestation claims as a compact JWS (EdDSA over Ed25519).
5
8
  *
6
- * For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
7
- * published in the issuer's JSON Web Key Set.
9
+ * For issuers. `key` is an Ed25519 key pair, or a {@link SigningKey | Signer} whose private key
10
+ * stays in a KMS, HSM or wallet service. `keyId` defaults to the RFC 7638 thumbprint of its public
11
+ * key, the `kid` an issuer's JSON Web Key Set publishes for it.
8
12
  */
9
13
  export async function sign(claims, options) {
10
- const header = { alg: Constants.algorithm, kid: options.keyId, typ: Constants.tokenType };
14
+ const signer = Signer.resolve(options.key, [Algorithms.ed25519]);
15
+ const keyId = options.keyId ?? (await JwkThumbprint.fromKey(signer.publicKey));
16
+ const header = { alg: Constants.algorithm, kid: keyId, typ: Constants.tokenType };
11
17
  const input = `${encode(header)}.${encode(claims)}`;
12
- const signature = await crypto.subtle.sign({ name: 'Ed25519' }, options.key, new TextEncoder().encode(input));
13
- return `${input}.${Base64.fromBytes(new Uint8Array(signature), { pad: false, url: true })}`;
18
+ const signature = await signer.sign(new TextEncoder().encode(input));
19
+ return `${input}.${Base64.fromBytes(signature, { pad: false, url: true })}`;
14
20
  }
15
21
  /** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
16
22
  export function decode(token) {
@@ -10,6 +10,8 @@ export * as Persona from './persona/index.js';
10
10
  export * as Tap from './tap/index.js';
11
11
  /** Client and server adapters for the Web Bot Auth HTTPS-directory profile. */
12
12
  export * as WebBotAuth from './web-bot-auth/index.js';
13
+ /** World ID: agents approved by a World ID-verified human, through World IdP (OpenID Connect). */
14
+ export * as World from './world/index.js';
13
15
  export * from './Constants.js';
14
16
  export type * from './Types.js';
15
17
  //# sourceMappingURL=index.d.ts.map
@@ -10,5 +10,7 @@ export * as Persona from './persona/index.js';
10
10
  export * as Tap from './tap/index.js';
11
11
  /** Client and server adapters for the Web Bot Auth HTTPS-directory profile. */
12
12
  export * as WebBotAuth from './web-bot-auth/index.js';
13
+ /** World ID: agents approved by a World ID-verified human, through World IdP (OpenID Connect). */
14
+ export * as World from './world/index.js';
13
15
  export * from './Constants.js';
14
16
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  import type { BareItem } from 'structured-headers';
2
2
  import type { MaybePromise } from '../../../internal/types.js';
3
3
  import * as Store from '../../../Store.js';
4
- import type { KeyResolver, SignatureAlgorithm, SigningContext } from '../Types.js';
4
+ import type { KeyResolver, SignatureAlgorithm, SigningContext, SigningKey } from '../Types.js';
5
5
  /** RFC 9421 constants used by identity signature profiles. */
6
6
  export declare const Constants: {
7
7
  /** Derived request components supported by this narrow request profile. */
@@ -54,7 +54,7 @@ export declare function sign(request: Request, options: {
54
54
  components: readonly ComponentInput[];
55
55
  expiresIn?: number | undefined;
56
56
  keyId: string;
57
- key: CryptoKey;
57
+ key: SigningKey;
58
58
  label: string;
59
59
  context?: SigningContext | undefined;
60
60
  tag: string;
@@ -1,6 +1,7 @@
1
1
  import { isInnerList, parseDictionary, serializeItem, serializeDictionary, serializeInnerList, serializeParameters, } from 'structured-headers';
2
2
  import * as Store from '../../../Store.js';
3
3
  import { Algorithms, Headers as SignatureHeaders } from '../Constants.js';
4
+ import * as Signer from './Signer.js';
4
5
  import * as SigningContextInternal from './SigningContext.js';
5
6
  /** RFC 9421 constants used by identity signature profiles. */
6
7
  export const Constants = {
@@ -33,7 +34,8 @@ export async function sign(request, options) {
33
34
  const context = options.context ?? SigningContextInternal.create();
34
35
  const created = context.created;
35
36
  const expires = created + (options.expiresIn ?? 60);
36
- const algorithm = algorithmFromKey(options.key);
37
+ const signer = Signer.resolve(options.key);
38
+ const algorithm = signer.algorithm;
37
39
  const parameters = new Map([
38
40
  ['created', created],
39
41
  ['expires', expires],
@@ -53,7 +55,7 @@ export async function sign(request, options) {
53
55
  parameters,
54
56
  tag: options.tag,
55
57
  };
56
- const signature = await crypto.subtle.sign(webCryptoAlgorithm(algorithm), options.key, toArrayBuffer(encode(signatureBase(request, input))));
58
+ // Check the existing signatures first, so a request this refuses never reaches a remote signer.
57
59
  const headers = new Headers(request.headers);
58
60
  const inputs = parseHeaderDictionary(headers, SignatureHeaders.signatureInput);
59
61
  const signatures = parseHeaderDictionary(headers, SignatureHeaders.signature);
@@ -61,9 +63,16 @@ export async function sign(request, options) {
61
63
  throw new Error('Signature-Input and Signature must contain the same labels.');
62
64
  if (inputs.has(input.label) || signatures.has(input.label))
63
65
  throw new Error(`HTTP message signature label "${input.label}" already exists.`);
66
+ // `new Request(request)` below throws on a read or locked body: refuse it before signing.
67
+ if (request.bodyUsed || request.body?.locked)
68
+ throw new TypeError('Cannot sign a request whose body has already been read or is locked.');
64
69
  inputs.set(input.label, toInnerList(input));
70
+ // Serializing validates the label and parameters before the signer is called.
71
+ const signatureInput = serializeDictionary(inputs);
72
+ const bytes = encode(signatureBase(request, input));
73
+ const signature = (await signer.sign(bytes)).buffer;
65
74
  signatures.set(input.label, [signature, new Map()]);
66
- headers.set(SignatureHeaders.signatureInput, serializeDictionary(inputs));
75
+ headers.set(SignatureHeaders.signatureInput, signatureInput);
67
76
  headers.set(SignatureHeaders.signature, serializeDictionary(signatures));
68
77
  return new Request(request, { headers });
69
78
  }
@@ -215,12 +224,6 @@ function toSignatureInput(label, entry) {
215
224
  tag,
216
225
  };
217
226
  }
218
- function algorithmFromKey(key) {
219
- for (const algorithm of Object.values(Algorithms))
220
- if (keySupportsAlgorithm(key, algorithm))
221
- return algorithm;
222
- throw new TypeError('HTTP message signatures require an Ed25519 or RSA-PSS SHA-512 signing key.');
223
- }
224
227
  function isInteger(value) {
225
228
  return typeof value === 'number' && Number.isInteger(value);
226
229
  }
@@ -317,6 +320,6 @@ function encode(value) {
317
320
  return new TextEncoder().encode(value);
318
321
  }
319
322
  function toArrayBuffer(value) {
320
- return value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
323
+ return Uint8Array.from(value).buffer;
321
324
  }
322
325
  //# sourceMappingURL=HttpMessageSignature.js.map
@@ -13,7 +13,7 @@ export async function fromKey(key) {
13
13
  else if (jwk.kty === 'RSA' && jwk.e && jwk.n)
14
14
  canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });
15
15
  else
16
- throw new TypeError('Web Bot Auth requires an Ed25519 or RSA public key.');
16
+ throw new TypeError('RFC 7638 thumbprints need an Ed25519 or RSA public key.');
17
17
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical));
18
18
  return Base64.fromBytes(new Uint8Array(digest), { pad: false, url: true });
19
19
  }
@@ -0,0 +1,20 @@
1
+ import type { SignatureAlgorithm, SigningKey } from '../Types.js';
2
+ /** A {@link SigningKey} checked and ready to sign. */
3
+ export type Resolved = {
4
+ /** Signature algorithm, from the public key. */
5
+ readonly algorithm: SignatureAlgorithm;
6
+ /** Public key that verifies every signature. */
7
+ readonly publicKey: CryptoKey;
8
+ /** Signs the complete message and resolves with the raw signature. */
9
+ readonly sign: (payload: Uint8Array) => Promise<Uint8Array<ArrayBuffer>>;
10
+ };
11
+ /**
12
+ * Checks a {@link SigningKey} and returns how to sign with it.
13
+ *
14
+ * Throws a `TypeError` unless the key is a `CryptoKeyPair` or a {@link Signer} whose public key
15
+ * is one of `algorithms`. A `Signer`'s signatures are verified against its public key before
16
+ * they are returned.
17
+ * @internal
18
+ */
19
+ export declare function resolve(key: SigningKey, algorithms?: readonly SignatureAlgorithm[]): Resolved;
20
+ //# sourceMappingURL=Signer.d.ts.map
@@ -0,0 +1,94 @@
1
+ import { Algorithms } from '../Constants.js';
2
+ const webCrypto = {
3
+ [Algorithms.ed25519]: { name: 'Ed25519' },
4
+ [Algorithms.rsaPssSha512]: { name: 'RSA-PSS', saltLength: 64 },
5
+ };
6
+ /**
7
+ * Checks a {@link SigningKey} and returns how to sign with it.
8
+ *
9
+ * Throws a `TypeError` unless the key is a `CryptoKeyPair` or a {@link Signer} whose public key
10
+ * is one of `algorithms`. A `Signer`'s signatures are verified against its public key before
11
+ * they are returned.
12
+ * @internal
13
+ */
14
+ export function resolve(key, algorithms = Object.values(Algorithms)) {
15
+ if (!isObject(key))
16
+ throw invalidKey();
17
+ const { publicKey } = key;
18
+ if (isCryptoKey(key))
19
+ throw new TypeError('Signing keys are key pairs: pass { privateKey, publicKey } or a Signer, not a private key alone.');
20
+ if (!isCryptoKey(publicKey) || publicKey.type !== 'public')
21
+ throw invalidKey();
22
+ const algorithm = algorithmOf(publicKey);
23
+ if (!algorithm || !algorithms.includes(algorithm))
24
+ throw new TypeError(`Signing keys must be ${describe(algorithms)}.`);
25
+ const parameters = webCrypto[algorithm];
26
+ if (typeof key.sign === 'function') {
27
+ const signer = key;
28
+ if (!publicKey.usages.includes('verify'))
29
+ throw new TypeError('A Signer publicKey must have the verify usage.');
30
+ return {
31
+ algorithm,
32
+ publicKey,
33
+ async sign(payload) {
34
+ const signature = await signer.sign({ payload: Uint8Array.from(payload) });
35
+ if (!isUint8Array(signature))
36
+ throw new TypeError('A Signer must resolve with the raw signature as a Uint8Array.');
37
+ // A copy, so the signer can't change the signature after it is checked.
38
+ const bytes = Uint8Array.from(signature);
39
+ let valid = false;
40
+ try {
41
+ valid = await crypto.subtle.verify(parameters, publicKey, bytes, Uint8Array.from(payload));
42
+ }
43
+ catch { }
44
+ if (!valid)
45
+ throw new Error('The Signer returned a signature that does not verify with its publicKey. Check that it signs the payload itself (not a digest) with that key, and returns raw signature bytes.');
46
+ return bytes;
47
+ },
48
+ };
49
+ }
50
+ const { privateKey } = key;
51
+ if (!isCryptoKey(privateKey) || privateKey.type !== 'private')
52
+ throw invalidKey();
53
+ if (algorithmOf(privateKey) !== algorithm)
54
+ throw new TypeError('The privateKey and publicKey of a signing key pair use different algorithms.');
55
+ return {
56
+ algorithm,
57
+ publicKey,
58
+ async sign(payload) {
59
+ return new Uint8Array(await crypto.subtle.sign(parameters, privateKey, Uint8Array.from(payload)));
60
+ },
61
+ };
62
+ }
63
+ /** The signature algorithm a key is for, or `undefined` when it is not supported. */
64
+ function algorithmOf(key) {
65
+ if (key.algorithm.name === 'Ed25519')
66
+ return Algorithms.ed25519;
67
+ if (key.algorithm.name === 'RSA-PSS' &&
68
+ key.algorithm.hash?.name === 'SHA-512')
69
+ return Algorithms.rsaPssSha512;
70
+ return undefined;
71
+ }
72
+ function describe(algorithms) {
73
+ return algorithms
74
+ .map((algorithm) => (algorithm === Algorithms.ed25519 ? 'Ed25519' : 'RSA-PSS SHA-512'))
75
+ .join(' or ');
76
+ }
77
+ function invalidKey() {
78
+ return new TypeError('A signing key must be a CryptoKeyPair or a Signer with publicKey and sign.');
79
+ }
80
+ /** Whether `value` is a `Uint8Array` (or `Buffer`), including one from another realm. */
81
+ function isUint8Array(value) {
82
+ return (ArrayBuffer.isView(value) && Object.prototype.toString.call(value) === '[object Uint8Array]');
83
+ }
84
+ function isObject(value) {
85
+ return typeof value === 'object' && value !== null;
86
+ }
87
+ function isCryptoKey(value) {
88
+ // Duck-typed so keys from another realm or a WebCrypto polyfill keep working.
89
+ return (isObject(value) &&
90
+ typeof value.type === 'string' &&
91
+ isObject(value.algorithm) &&
92
+ Array.isArray(value.usages));
93
+ }
94
+ //# sourceMappingURL=Signer.js.map
@@ -1,4 +1,5 @@
1
1
  import type * as Identity from '../../../../identity/Types.js';
2
+ import type { SigningKey } from '../../Types.js';
2
3
  import { Constants } from '../Constants.js';
3
4
  /**
4
5
  * Creates a TAP identity prover.
@@ -17,8 +18,11 @@ export declare namespace prover {
17
18
  type Config = {
18
19
  /** TAP signature type for the request. */
19
20
  intent: (typeof Constants.intents)[keyof typeof Constants.intents];
20
- /** Ed25519 or RSA-PSS SHA-512 private key provisioned to the agent provider. */
21
- key: CryptoKey;
21
+ /**
22
+ * Ed25519 or RSA-PSS SHA-512 key pair, or a {@link SigningKey | Signer} for a remote key,
23
+ * provisioned to the agent provider.
24
+ */
25
+ key: SigningKey;
22
26
  /** Identifier the merchant uses to resolve the signing public key. */
23
27
  keyId: string;
24
28
  /** Origins that receive TAP signatures, or `'*'` for any origin. */
@@ -1,4 +1,5 @@
1
1
  import * as HttpMessageSignature from '../../internal/HttpMessageSignature.js';
2
+ import * as Signer from '../../internal/Signer.js';
2
3
  import { Constants } from '../Constants.js';
3
4
  /**
4
5
  * Creates a TAP identity prover.
@@ -15,6 +16,7 @@ import { Constants } from '../Constants.js';
15
16
  export function prover(config) {
16
17
  const tag = config.intent === Constants.intents.payment ? Constants.tags.payment : Constants.tags.browse;
17
18
  const expiresIn = config.expiresIn ?? Constants.defaultSignatureLifetime;
19
+ Signer.resolve(config.key);
18
20
  if (!Number.isInteger(expiresIn) ||
19
21
  expiresIn <= 0 ||
20
22
  expiresIn > Constants.maximumSignatureLifetime)
@@ -0,0 +1,14 @@
1
+ /** Tempo ID values. */
2
+ export declare const Constants: {
3
+ /** Identity type advertised in the 402's `Identity-Required` header. */
4
+ readonly type: 'tempo-id';
5
+ /** Tempo ID in production: the issuer of every access token. */
6
+ readonly issuer: 'https://id.tempo.xyz';
7
+ /** Header that carries the user's ID token, for their email address. */
8
+ readonly idTokenHeader: 'Tempo-Id-Token';
9
+ /** Seconds a DPoP proof is accepted after its `iat`. */
10
+ readonly proofMaxAge: 300;
11
+ /** Seconds of clock skew allowed on token and proof times. */
12
+ readonly clockTolerance: 60;
13
+ };
14
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,14 @@
1
+ /** Tempo ID values. */
2
+ export const Constants = {
3
+ /** Identity type advertised in the 402's `Identity-Required` header. */
4
+ type: 'tempo-id',
5
+ /** Tempo ID in production: the issuer of every access token. */
6
+ issuer: 'https://id.tempo.xyz',
7
+ /** Header that carries the user's ID token, for their email address. */
8
+ idTokenHeader: 'Tempo-Id-Token',
9
+ /** Seconds a DPoP proof is accepted after its `iat`. */
10
+ proofMaxAge: 300,
11
+ /** Seconds of clock skew allowed on token and proof times. */
12
+ clockTolerance: 60,
13
+ };
14
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,31 @@
1
+ import type { Address } from 'ox';
2
+ /** The screening state of a Tempo Account: only `clear` may pay without limits. */
3
+ export type ComplianceState = 'clear' | 'exit_only' | 'blocked' | 'pending';
4
+ /** A Tempo ID user, as a verified access token (and, when sent, ID token) names them. */
5
+ export type Caller = {
6
+ /** The Tempo ID user ID: stable across every app on Tempo ID. */
7
+ readonly userId: string;
8
+ /** The app the user signed in to. */
9
+ readonly clientId: string;
10
+ /** The Tempo Accounts the token grants to the app on the configured chain, checksummed. */
11
+ readonly accounts: readonly Address.Address[];
12
+ /** The screening state of each account in the app's realms, by checksummed address. Empty for an unregistered app. */
13
+ readonly compliance: Readonly<Record<Address.Address, ComplianceState>>;
14
+ /** The user's email address, lowercased, from the ID token. Absent without one, or without the `email` scope. */
15
+ readonly email?: string | undefined;
16
+ /** Whether Tempo ID verified the email address. */
17
+ readonly emailVerified?: boolean | undefined;
18
+ };
19
+ /** A verified Tempo ID user and the Tempo Account that paid. */
20
+ export type Payer = Caller & {
21
+ /** The account that paid, checksummed. Absent when the check ran without a Credential. */
22
+ readonly account?: Address.Address | undefined;
23
+ };
24
+ /** An ES256 DPoP key (RFC 9449), such as the Tempo ID SDK's session key. */
25
+ export type DpopKey = {
26
+ /** The public key as a JWK. */
27
+ readonly jwk: JsonWebKey;
28
+ /** The private key that signs each proof. */
29
+ readonly privateKey: CryptoKey;
30
+ };
31
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1,34 @@
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 Tempo ID access token with each request: as `DPoP` with a new
6
+ * proof when `dpop` is set, else as `Bearer`.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const mppx = Mppx.create({
11
+ * identity: [
12
+ * TempoId.Client.prover({
13
+ * accessToken: () => accounts.session.accessToken(),
14
+ * scope: ['https://api.example'],
15
+ * }),
16
+ * ],
17
+ * methods: [tempo({ account })],
18
+ * })
19
+ * ```
20
+ */
21
+ export declare function prover(config: prover.Config): Identity.Prover;
22
+ export declare namespace prover {
23
+ type Config = {
24
+ /** Returns a live Tempo ID access token, such as `accounts.session.accessToken`. */
25
+ readonly accessToken: () => MaybePromise<string>;
26
+ /** The DPoP key that binds the token. Absent, the token is sent as a Bearer token. */
27
+ readonly dpop?: Types.DpopKey | undefined;
28
+ /** Returns the user's ID token, such as `accounts.session.get()?.idToken`, so the API reads their email. */
29
+ readonly idToken?: (() => MaybePromise<string | undefined>) | undefined;
30
+ /** Origins that receive the token. Send it only to the API it was issued for. */
31
+ readonly scope: Identity.Prover['scope'];
32
+ };
33
+ }
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,60 @@
1
+ import { Base64 } from 'ox';
2
+ import * as Credential from '../../../../Credential.js';
3
+ import { Constants } from '../Constants.js';
4
+ import * as Jwt from '../internal/Jwt.js';
5
+ /**
6
+ * Creates a prover that sends a Tempo ID access token with each request: as `DPoP` with a new
7
+ * proof when `dpop` is set, else as `Bearer`.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const mppx = Mppx.create({
12
+ * identity: [
13
+ * TempoId.Client.prover({
14
+ * accessToken: () => accounts.session.accessToken(),
15
+ * scope: ['https://api.example'],
16
+ * }),
17
+ * ],
18
+ * methods: [tempo({ account })],
19
+ * })
20
+ * ```
21
+ */
22
+ export function prover(config) {
23
+ const { dpop } = config;
24
+ return {
25
+ scope: config.scope,
26
+ headers: ['dpop', Constants.idTokenHeader.toLowerCase()],
27
+ async prove(request) {
28
+ const accessToken = await config.accessToken();
29
+ const headers = new Headers(request.headers);
30
+ // The access token would replace a Payment Credential in Authorization; a server created
31
+ // with `requiresAuth: true` takes the Credential in Payment-Authorization instead.
32
+ const authorization = headers.get('Authorization');
33
+ if (authorization && Credential.extractPaymentScheme(authorization) !== null)
34
+ throw new TypeError('The Tempo ID access token needs Authorization, which holds the Payment Credential: the server must set requiresAuth: true.');
35
+ headers.set('Authorization', `${dpop ? 'DPoP' : 'Bearer'} ${accessToken}`);
36
+ if (dpop)
37
+ headers.set('DPoP', await proof(dpop, accessToken, request));
38
+ const idToken = await config.idToken?.();
39
+ if (idToken)
40
+ headers.set(Constants.idTokenHeader, idToken);
41
+ return new Request(request, { headers });
42
+ },
43
+ };
44
+ }
45
+ /** Signs a DPoP proof (RFC 9449) of `accessToken` for one request. */
46
+ async function proof(dpop, accessToken, request) {
47
+ const { crv, kty, x, y } = dpop.jwk;
48
+ const header = Jwt.encode({ alg: 'ES256', jwk: { crv, kty, x, y }, typ: 'dpop+jwt' });
49
+ const claims = Jwt.encode({
50
+ ath: await Jwt.sha256(accessToken),
51
+ htm: request.method,
52
+ htu: Jwt.htu(request.url),
53
+ iat: Math.floor(Date.now() / 1_000),
54
+ jti: crypto.randomUUID(),
55
+ });
56
+ const input = `${header}.${claims}`;
57
+ const signature = await crypto.subtle.sign(Jwt.es256.sign, dpop.privateKey, new TextEncoder().encode(input));
58
+ return `${input}.${Base64.fromBytes(new Uint8Array(signature), { pad: false, url: true })}`;
59
+ }
60
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,5 @@
1
+ export * as Client from './client/index.js';
2
+ export { Constants } from './Constants.js';
3
+ export * as Server from './server/index.js';
4
+ export type * from './Types.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ export * as Client from './client/index.js';
2
+ export { Constants } from './Constants.js';
3
+ export * as Server from './server/index.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,36 @@
1
+ /** A decoded, unverified compact JWS. */
2
+ export type Decoded = {
3
+ readonly header: Record<string, any>;
4
+ readonly claims: Record<string, any>;
5
+ readonly signingInput: Uint8Array<ArrayBuffer>;
6
+ readonly signature: Uint8Array<ArrayBuffer>;
7
+ };
8
+ /** ES256 in Web Crypto: the only DPoP algorithm the Tempo ID SDK signs with. */
9
+ export declare const es256: {
10
+ readonly key: {
11
+ readonly name: 'ECDSA';
12
+ readonly namedCurve: 'P-256';
13
+ };
14
+ readonly sign: {
15
+ readonly name: 'ECDSA';
16
+ readonly hash: 'SHA-256';
17
+ };
18
+ };
19
+ /** Decodes a compact JWS without verifying it, or returns `undefined` if it is malformed. */
20
+ export declare function decode(token: string): Decoded | undefined;
21
+ /** Encodes a JSON value as unpadded base64url. */
22
+ export declare function encode(value: unknown): string;
23
+ /** Unpadded base64url SHA-256 of a string, as DPoP's `ath` uses. */
24
+ export declare function sha256(value: string): Promise<string>;
25
+ /** RFC 7638 thumbprint of a P-256 public JWK. */
26
+ export declare function thumbprint(jwk: JsonWebKey): Promise<string>;
27
+ /** A request URL without its query and fragment, as DPoP's `htu` names it. */
28
+ export declare function htu(url: string | URL): string;
29
+ /**
30
+ * Returns a lookup of an issuer's RS256 keys by key ID, from `<issuer>/oauth2/jwks`. The set is
31
+ * cached for five minutes, and an unknown key ID refetches it at most every 30 seconds. A failed
32
+ * fetch keeps the last set that loaded for up to one hour after it loaded, so a removed key stops
33
+ * verifying within an hour even while the issuer is unreachable.
34
+ */
35
+ export declare function keys(issuer: string, fetch: typeof globalThis.fetch): (kid: string) => Promise<CryptoKey | undefined>;
36
+ //# sourceMappingURL=Jwt.d.ts.map