mppx 0.18.0 → 0.18.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/Currency.d.ts +59 -0
  3. package/dist/Currency.js +60 -0
  4. package/dist/Errors.d.ts +13 -0
  5. package/dist/Errors.js +15 -6
  6. package/dist/cli/cli.js +135 -135
  7. package/dist/cli/plugins/index.js +12 -12
  8. package/dist/cli/plugins/tempo.js +13 -1
  9. package/dist/client/internal/Fetch.d.ts +5 -0
  10. package/dist/client/internal/Fetch.js +7 -0
  11. package/dist/cloudflare/ChannelStore.d.ts +1 -2
  12. package/dist/cloudflare/ChannelStore.js +14 -20
  13. package/dist/cloudflare/Channels.d.ts +20 -2
  14. package/dist/cloudflare/Channels.js +47 -4
  15. package/dist/cloudflare/index.d.ts +1 -1
  16. package/dist/cloudflare/index.js +1 -1
  17. package/dist/discovery/Discovery.d.ts +116 -9
  18. package/dist/discovery/Discovery.js +169 -0
  19. package/dist/evm/server/Charge.js +2 -3
  20. package/dist/evm/server/Methods.d.ts +1 -1
  21. package/dist/evm/server/Methods.js +3 -2
  22. package/dist/extensions/identity/email-otp/client/index.js +4 -4
  23. package/dist/extensions/identity/index.d.ts +4 -0
  24. package/dist/extensions/identity/index.js +4 -0
  25. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  26. package/dist/extensions/identity/link/Constants.js +16 -0
  27. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  28. package/dist/extensions/identity/link/client/index.js +211 -0
  29. package/dist/extensions/identity/link/index.d.ts +12 -0
  30. package/dist/extensions/identity/link/index.js +12 -0
  31. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  32. package/dist/extensions/identity/link/server/index.js +518 -0
  33. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  34. package/dist/extensions/identity/persona/Constants.js +24 -0
  35. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  36. package/dist/extensions/identity/persona/Did.js +24 -0
  37. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  38. package/dist/extensions/identity/persona/Types.js +2 -0
  39. package/dist/extensions/identity/persona/index.d.ts +10 -0
  40. package/dist/extensions/identity/persona/index.js +9 -0
  41. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  42. package/dist/extensions/identity/persona/server/index.js +263 -0
  43. package/dist/identity/Headers.d.ts +6 -1
  44. package/dist/identity/Headers.js +6 -1
  45. package/dist/identity/Server.js +2 -0
  46. package/dist/identity/Types.d.ts +5 -0
  47. package/dist/index.d.ts +1 -0
  48. package/dist/index.js +1 -0
  49. package/dist/internal/version.d.ts +2 -2
  50. package/dist/internal/version.js +1 -1
  51. package/dist/proxy/internal/Headers.js +4 -4
  52. package/dist/server/Mppx.js +5 -2
  53. package/dist/stripe/server/internal/html.gen.js +1 -1
  54. package/dist/tempo/client/Charge.d.ts +11 -8
  55. package/dist/tempo/client/Charge.js +53 -6
  56. package/dist/tempo/index.d.ts +4 -0
  57. package/dist/tempo/index.js +4 -0
  58. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  59. package/dist/tempo/internal/auto-swap.js +17 -2
  60. package/dist/tempo/internal/currencies.d.ts +5 -4
  61. package/dist/tempo/internal/currencies.js +13 -9
  62. package/dist/tempo/internal/defaults.d.ts +7 -0
  63. package/dist/tempo/internal/defaults.js +7 -0
  64. package/dist/tempo/internal/fee-payer.js +8 -2
  65. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  66. package/dist/tempo/internal/machine-token-charge.js +82 -1
  67. package/dist/tempo/server/Charge.js +59 -2
  68. package/dist/tempo/server/Methods.d.ts +1 -1
  69. package/dist/tempo/server/internal/html.gen.js +1 -1
  70. package/dist/tempo/server/internal/transport.d.ts +1 -1
  71. package/dist/tempo/server/internal/transport.js +9 -16
  72. package/dist/tempo/session/client/CredentialState.js +31 -0
  73. package/dist/tempo/session/client/Session.d.ts +12 -6
  74. package/dist/tempo/session/client/Session.js +64 -18
  75. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  76. package/dist/tempo/session/server/ChannelStore.js +58 -8
  77. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  78. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  79. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  80. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  81. package/dist/tempo/session/server/Session.js +6 -3
  82. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  83. package/dist/tempo/session/server/Settlement.js +36 -6
  84. package/dist/tempo/session/server/Sse.d.ts +2 -0
  85. package/dist/tempo/session/server/Sse.js +12 -12
  86. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  87. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  88. package/dist/x402/Assets.d.ts +14 -5
  89. package/dist/x402/Assets.js +11 -16
  90. package/package.json +15 -3
@@ -1,4 +1,5 @@
1
1
  import { getAddress, recoverTypedDataAddress } from 'viem';
2
+ import * as Currency from '../../Currency.js';
2
3
  import { VerificationFailedError } from '../../Errors.js';
3
4
  import * as Method from '../../Method.js';
4
5
  import * as Receipt from '../../Receipt.js';
@@ -116,9 +117,7 @@ function resolveConfig(config) {
116
117
  let authorization = config.authorization;
117
118
  let chainId = config.chainId;
118
119
  let decimals = config.decimals;
119
- if (Assets.isAsset(currency)) {
120
- chainId ??= Assets.toChainId(currency.network);
121
- }
120
+ chainId ??= Currency.chainIdOf(currency);
122
121
  if (chainId !== undefined) {
123
122
  const resolved = Assets.resolve(currency, Types.networkOf(chainId));
124
123
  if (!resolved)
@@ -219,7 +219,7 @@ export declare function evm<const parameters extends evm.Parameters>(parameters:
219
219
  };
220
220
  }, charge_.Defaults, import("../../server/Transport.js").Http, {}, string | undefined>];
221
221
  export declare namespace evm {
222
- /** Accepted EVM currency metadata, including chain-indexed definitions from `viem/tokens`. */
222
+ /** An accepted EVM currency: an address, a `viem/tokens` token (chain-indexed or resolved), or a known asset. */
223
223
  type Currency = Assets.Currency;
224
224
  /** Shared EVM settlement parameters and ordered accepted currencies. */
225
225
  type Parameters = Omit<charge_.Parameters, 'currency'> & ({
@@ -1,3 +1,4 @@
1
+ import * as Currency from '../../Currency.js';
1
2
  import * as Assets from '../Assets.js';
2
3
  import * as Chains from '../Chains.js';
3
4
  import { charge as charge_ } from './Charge.js';
@@ -34,14 +35,14 @@ export function evm(parameters) {
34
35
  const seen = new Set();
35
36
  const methods = [];
36
37
  for (const currency of currencies) {
37
- const chainId = shared.chainId ?? (Assets.isAsset(currency) ? Assets.toChainId(currency.network) : undefined);
38
+ const chainId = shared.chainId ?? Currency.chainIdOf(currency);
38
39
  if (chainId === undefined)
39
40
  throw new Error('EVM currencies require `chainId` or known asset metadata.');
40
41
  const resolved = Assets.resolve(currency, Assets.toNetwork(chainId));
41
42
  if (!resolved)
42
43
  continue;
43
44
  // One shared price cannot price non-USD or unknown-denomination token definitions.
44
- if (Assets.isToken(currency) && currency.currency !== 'USD')
45
+ if (typeof currency !== 'string' && !Assets.isAsset(currency) && currency.currency !== 'USD')
45
46
  continue;
46
47
  const key = `${chainId}:${resolved.address.toLowerCase()}`;
47
48
  if (seen.has(key))
@@ -1,4 +1,4 @@
1
- import { unwrapFetch } from '../../../../client/internal/Fetch.js';
1
+ import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
2
2
  import * as Attestation from '../../attestation/client/index.js';
3
3
  import { isIssuer } from '../../attestation/Token.js';
4
4
  import { Constants } from '../Constants.js';
@@ -115,14 +115,14 @@ async function post(issuer, path, fetch, body) {
115
115
  // The address and code never go over plaintext HTTP, except to localhost.
116
116
  if (!isIssuer(issuer))
117
117
  throw new EmailOtpError('The issuer must be an https URL (http only on localhost).');
118
- // The unwrapped fetch, so an issuer's 402 is never paid automatically.
119
- const response = await unwrapFetch(fetch ?? globalThis.fetch)(`${issuer.replace(/\/+$/, '')}${path}`, {
118
+ // Untagged forwarding wrappers survive unwrapping, so also opt out explicitly.
119
+ const response = await unwrapFetch(fetch ?? globalThis.fetch)(`${issuer.replace(/\/+$/, '')}${path}`, withoutPayment({
120
120
  body: JSON.stringify(body),
121
121
  headers: { 'content-type': 'application/json' },
122
122
  method: 'POST',
123
123
  // Workers reject 'error'; a redirect is not ok, so it fails below.
124
124
  redirect: 'manual',
125
- });
125
+ }));
126
126
  const json = (await response.json().catch(() => ({})));
127
127
  if (!response.ok)
128
128
  throw new EmailOtpError(typeof json.error === 'string' ? json.error : `The issuer answered ${response.status}.`, { status: response.status });
@@ -2,6 +2,10 @@
2
2
  export * as Attestation from './attestation/index.js';
3
3
  /** Email address verification with a one-time code. */
4
4
  export * as EmailOtp from './email-otp/index.js';
5
+ /** Link agent identity: attestation tokens and Link-signed claims. */
6
+ export * as Link from './link/index.js';
7
+ /** Persona KYC: a payment check that requires an approved Persona inquiry. */
8
+ export * as Persona from './persona/index.js';
5
9
  /** Client and server adapters for the TAP agent-recognition signature profile. */
6
10
  export * as Tap from './tap/index.js';
7
11
  /** Client and server adapters for the Web Bot Auth HTTPS-directory profile. */
@@ -2,6 +2,10 @@
2
2
  export * as Attestation from './attestation/index.js';
3
3
  /** Email address verification with a one-time code. */
4
4
  export * as EmailOtp from './email-otp/index.js';
5
+ /** Link agent identity: attestation tokens and Link-signed claims. */
6
+ export * as Link from './link/index.js';
7
+ /** Persona KYC: a payment check that requires an approved Persona inquiry. */
8
+ export * as Persona from './persona/index.js';
5
9
  /** Client and server adapters for the TAP agent-recognition signature profile. */
6
10
  export * as Tap from './tap/index.js';
7
11
  /** Client and server adapters for the Web Bot Auth HTTPS-directory profile. */
@@ -0,0 +1,102 @@
1
+ import type { MaybePromise } from '../../../internal/types.js';
2
+ /** Link agent identity values, as Link's Agent Identity SDK and Link CLI use them. */
3
+ export declare const Constants: {
4
+ /** Link's issuer, the only one the Agent Identity SDK trusts. */
5
+ readonly issuer: 'https://api.link.com';
6
+ /** `Authorization` scheme of an Agent Attestation Token (RFC 9577). */
7
+ readonly attestationScheme: 'PrivateToken';
8
+ /** Request header carrying an identity presentation, and its `WWW-Authenticate` scheme. */
9
+ readonly presentationHeader: 'Identity-Presentation';
10
+ /** `type` of the problem body of a claims challenge. */
11
+ readonly claimsRequiredType: 'urn:stripe:link:claims-required';
12
+ /** Presentation format of a claims challenge. */
13
+ readonly format: 'dc+sd-jwt';
14
+ /** Seconds a claims challenge's nonce is accepted for. */
15
+ readonly nonceTtl: 300;
16
+ };
17
+ /** One failure of a Link verification, as `@stripe/agent-identity` reports it. */
18
+ export type Failure = {
19
+ readonly code: string;
20
+ readonly message: string;
21
+ };
22
+ /** Verifies Link Agent Attestation Tokens: a `LinkVerifier`, or `Link.Server.tokenVerifier()`. */
23
+ export type AttestationVerifier = Pick<LinkVerifier, 'attestationChallenge' | 'verifyAttestation'>;
24
+ /** Verifies Link identity presentations: a `LinkVerifier`, or `Link.Server.presentationVerifier()`. */
25
+ export type ClaimsVerifier = Pick<LinkVerifier, 'verifyClaims'>;
26
+ /**
27
+ * The parts of `LinkVerifier` from `@stripe/agent-identity` the verifiers use. Pass one
28
+ * `new LinkVerifier({ origin })` per process, so every request shares its issuer key cache.
29
+ */
30
+ export type LinkVerifier = {
31
+ attestationChallenge(): Promise<{
32
+ wwwAuthenticate: string[];
33
+ }>;
34
+ verifyAttestation(authorization: string | null | undefined): Promise<{
35
+ valid: true;
36
+ issuer: string;
37
+ tokenKeyId: string;
38
+ bindingMode?: 'bearer';
39
+ } | {
40
+ valid: false;
41
+ failures: readonly Failure[];
42
+ }>;
43
+ verifyClaims(presentation: string | null | undefined, options: {
44
+ nonce: string;
45
+ requiredClaims: string[];
46
+ }): Promise<{
47
+ valid: true;
48
+ issuer: string;
49
+ vct: string;
50
+ claims: Record<string, unknown>;
51
+ holderKeyThumbprint: string;
52
+ } | {
53
+ valid: false;
54
+ failures: readonly Failure[];
55
+ }>;
56
+ };
57
+ /** A verified Link Agent Attestation Token: Link vouches for the agent, and says nothing else. */
58
+ export type VerifiedAttestation = {
59
+ /** Issuer whose key signed the token. */
60
+ readonly issuer: string;
61
+ /** base64url of the token's `token_key_id`. */
62
+ readonly tokenKeyId: string;
63
+ };
64
+ /** Claims Link signed and the holder disclosed to this server. */
65
+ export type VerifiedClaims = {
66
+ /** Issuer of the credential. */
67
+ readonly issuer: string;
68
+ /** Credential type (`vct`). */
69
+ readonly vct: string;
70
+ /** The disclosed claims, by name. */
71
+ readonly claims: Readonly<Record<string, unknown>>;
72
+ /** RFC 7638 thumbprint of the holder key that signed the presentation. */
73
+ readonly holderKeyThumbprint: string;
74
+ /** The verified email address, lowercased, when `email` and a true `email_verified` were disclosed. */
75
+ readonly email?: string | undefined;
76
+ };
77
+ /** A claims challenge: the problem body of a 401 with `WWW-Authenticate: Identity-Presentation`. */
78
+ export type ClaimsChallenge = {
79
+ readonly type: 'urn:stripe:link:claims-required';
80
+ /** Origin the presentation must be bound to. */
81
+ readonly aud: string;
82
+ /** Nonce the presentation must sign. */
83
+ readonly nonce: string;
84
+ /** Claims to disclose. */
85
+ readonly claims: readonly string[];
86
+ /** Why the server asks, for the person whose claims they are. */
87
+ readonly purpose?: string | undefined;
88
+ readonly formats: readonly string[];
89
+ readonly trusted_issuers: readonly string[];
90
+ };
91
+ /** Creates a presentation for a claims challenge, such as with `link-cli identity credentials present`. */
92
+ export type Present = (parameters: {
93
+ /** Origin the presentation is for: always the request's own origin. */
94
+ audience: string;
95
+ /** Nonce from the challenge. */
96
+ nonce: string;
97
+ /** Claims to disclose. */
98
+ claims: readonly string[];
99
+ /** Why the server asks. */
100
+ purpose?: string | undefined;
101
+ }) => MaybePromise<string | undefined>;
102
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,16 @@
1
+ /** Link agent identity values, as Link's Agent Identity SDK and Link CLI use them. */
2
+ export const Constants = {
3
+ /** Link's issuer, the only one the Agent Identity SDK trusts. */
4
+ issuer: 'https://api.link.com',
5
+ /** `Authorization` scheme of an Agent Attestation Token (RFC 9577). */
6
+ attestationScheme: 'PrivateToken',
7
+ /** Request header carrying an identity presentation, and its `WWW-Authenticate` scheme. */
8
+ presentationHeader: 'Identity-Presentation',
9
+ /** `type` of the problem body of a claims challenge. */
10
+ claimsRequiredType: 'urn:stripe:link:claims-required',
11
+ /** Presentation format of a claims challenge. */
12
+ format: 'dc+sd-jwt',
13
+ /** Seconds a claims challenge's nonce is accepted for. */
14
+ nonceTtl: 300,
15
+ };
16
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,80 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import type { MaybePromise } from '../../../../internal/types.js';
3
+ import type * as Types from '../Constants.js';
4
+ /**
5
+ * Creates a prover that answers Link attestation challenges with an Agent Attestation Token.
6
+ *
7
+ * When a server in `scope` answers 401 with `WWW-Authenticate: PrivateToken`, the prover gets a
8
+ * token from `token` (such as `link-cli identity attestations pop`), and resends the request
9
+ * with it in `Authorization`. Later requests to that origin, including paid retries, carry the
10
+ * same token; a rejected one is replaced once. A request that already has an `Authorization`
11
+ * header is left as it is.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const mppx = Mppx.create({
16
+ * identity: [
17
+ * Link.Client.attestation({
18
+ * scope: ['https://api.example'],
19
+ * token: async () => (await linkCli('identity', 'attestations', 'pop')).authorization,
20
+ * }),
21
+ * ],
22
+ * methods: [tempo({ account })],
23
+ * })
24
+ * ```
25
+ */
26
+ export declare function attestation(config: attestation.Config): Identity.Prover;
27
+ export declare namespace attestation {
28
+ type Config = {
29
+ /** Origins that may receive a token, or `'*'` for any origin. */
30
+ readonly scope: Identity.Prover['scope'];
31
+ /**
32
+ * Returns an unused token: Link CLI's `authorization` value (`PrivateToken token="…"`) or the
33
+ * bare token. `undefined` declines.
34
+ */
35
+ readonly token: (parameters: {
36
+ origin: string;
37
+ }) => MaybePromise<string | undefined>;
38
+ /**
39
+ * Gets a token before the first request to an origin instead of after its challenge, so a
40
+ * server that prices requests by the proofs they carry sees it from the start.
41
+ * @default false
42
+ */
43
+ readonly eager?: boolean | undefined;
44
+ };
45
+ }
46
+ /**
47
+ * Creates a prover that answers Link claims challenges with an identity presentation.
48
+ *
49
+ * When a server in `scope` answers 401 with `WWW-Authenticate: Identity-Presentation` and a
50
+ * `urn:stripe:link:claims-required` body, the prover checks that the challenge names the
51
+ * request's own origin as audience, trusts Link, and asks only for claims in `claims`. It then
52
+ * gets a presentation from `present` (such as `link-cli identity credentials present`) and
53
+ * resends the request with it in `Identity-Presentation`. Later requests to that origin carry
54
+ * it until the server asks again.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * Link.Client.claims({
59
+ * claims: ['email', 'email_verified'],
60
+ * present: ({ audience, nonce, claims }) => linkCliPresent({ audience, nonce, claims }),
61
+ * scope: ['https://api.example'],
62
+ * })
63
+ * ```
64
+ */
65
+ export declare function claims(config: claims.Config): Identity.Prover;
66
+ export declare namespace claims {
67
+ type Config = {
68
+ /** Origins that may receive a presentation, or `'*'` for any origin. */
69
+ readonly scope: Identity.Prover['scope'];
70
+ /** Claims the prover may disclose, such as `['email', 'email_verified']`. */
71
+ readonly claims: readonly string[];
72
+ /** Creates a presentation for a challenge, or returns `undefined` to decline. */
73
+ readonly present: Types.Present;
74
+ /** Issuers whose credentials may be presented. Override only for staging and tests. @default ['https://api.link.com'] */
75
+ readonly issuers?: readonly string[] | undefined;
76
+ };
77
+ }
78
+ /** Parses a claims challenge's problem body, or returns `undefined` when it is not one. */
79
+ export declare function claimsChallenge(response: Response): Promise<Types.ClaimsChallenge | undefined>;
80
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,211 @@
1
+ import { Constants } from '../Constants.js';
2
+ /**
3
+ * Creates a prover that answers Link attestation challenges with an Agent Attestation Token.
4
+ *
5
+ * When a server in `scope` answers 401 with `WWW-Authenticate: PrivateToken`, the prover gets a
6
+ * token from `token` (such as `link-cli identity attestations pop`), and resends the request
7
+ * with it in `Authorization`. Later requests to that origin, including paid retries, carry the
8
+ * same token; a rejected one is replaced once. A request that already has an `Authorization`
9
+ * header is left as it is.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const mppx = Mppx.create({
14
+ * identity: [
15
+ * Link.Client.attestation({
16
+ * scope: ['https://api.example'],
17
+ * token: async () => (await linkCli('identity', 'attestations', 'pop')).authorization,
18
+ * }),
19
+ * ],
20
+ * methods: [tempo({ account })],
21
+ * })
22
+ * ```
23
+ */
24
+ export function attestation(config) {
25
+ const tokens = new Map();
26
+ // Every token this prover attached, so a request carrying an older one still retries.
27
+ const sent = new Set();
28
+ // One refresh per origin, shared by concurrent rejections.
29
+ const refreshes = new Map();
30
+ const remember = (origin, authorization) => {
31
+ tokens.set(origin, authorization);
32
+ track(sent, tokens, authorization);
33
+ };
34
+ return {
35
+ scope: config.scope,
36
+ async prove(request) {
37
+ if (request.headers.has('Authorization'))
38
+ return request;
39
+ const origin = new URL(request.url).origin;
40
+ if (config.eager && !tokens.has(origin)) {
41
+ const token = await config.token({ origin });
42
+ if (token)
43
+ remember(origin, toAuthorization(token));
44
+ }
45
+ const token = tokens.get(origin);
46
+ if (!token)
47
+ return request;
48
+ const headers = new Headers(request.headers);
49
+ headers.set('Authorization', token);
50
+ return new Request(request, { headers });
51
+ },
52
+ async retry(response, { request }) {
53
+ if (response.status !== 401)
54
+ return undefined;
55
+ if (!hasChallenge(response, Constants.attestationScheme))
56
+ return undefined;
57
+ const origin = new URL(request.url).origin;
58
+ const authorization = request.headers.get('Authorization');
59
+ // Someone else's Authorization: the token can't be sent alongside it.
60
+ if (authorization && !owns(sent, tokens, authorization))
61
+ return undefined;
62
+ const current = tokens.get(origin);
63
+ // Another request already replaced the rejected token: retry with the new one.
64
+ if (current && current !== authorization)
65
+ return {};
66
+ let refresh = refreshes.get(origin);
67
+ if (!refresh) {
68
+ tokens.delete(origin);
69
+ refresh = Promise.resolve(config.token({ origin }))
70
+ .then((token) => {
71
+ if (!token)
72
+ return undefined;
73
+ const value = toAuthorization(token);
74
+ remember(origin, value);
75
+ return value;
76
+ })
77
+ .finally(() => refreshes.delete(origin));
78
+ refreshes.set(origin, refresh);
79
+ }
80
+ return (await refresh) ? {} : undefined;
81
+ },
82
+ };
83
+ }
84
+ /**
85
+ * Creates a prover that answers Link claims challenges with an identity presentation.
86
+ *
87
+ * When a server in `scope` answers 401 with `WWW-Authenticate: Identity-Presentation` and a
88
+ * `urn:stripe:link:claims-required` body, the prover checks that the challenge names the
89
+ * request's own origin as audience, trusts Link, and asks only for claims in `claims`. It then
90
+ * gets a presentation from `present` (such as `link-cli identity credentials present`) and
91
+ * resends the request with it in `Identity-Presentation`. Later requests to that origin carry
92
+ * it until the server asks again.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * Link.Client.claims({
97
+ * claims: ['email', 'email_verified'],
98
+ * present: ({ audience, nonce, claims }) => linkCliPresent({ audience, nonce, claims }),
99
+ * scope: ['https://api.example'],
100
+ * })
101
+ * ```
102
+ */
103
+ export function claims(config) {
104
+ const allowed = new Set(config.claims);
105
+ const issuers = config.issuers ?? [Constants.issuer];
106
+ const presentations = new Map();
107
+ // Every presentation this prover attached, so it never answers for one the caller set.
108
+ const sent = new Set();
109
+ return {
110
+ scope: config.scope,
111
+ headers: [Constants.presentationHeader.toLowerCase()],
112
+ prove(request) {
113
+ if (request.headers.has(Constants.presentationHeader))
114
+ return request;
115
+ const presentation = presentations.get(new URL(request.url).origin);
116
+ if (!presentation)
117
+ return request;
118
+ const headers = new Headers(request.headers);
119
+ headers.set(Constants.presentationHeader, presentation);
120
+ return new Request(request, { headers });
121
+ },
122
+ async retry(response, { request }) {
123
+ if (response.status !== 401)
124
+ return undefined;
125
+ if (!hasChallenge(response, Constants.presentationHeader))
126
+ return undefined;
127
+ const attached = request.headers.get(Constants.presentationHeader);
128
+ // The caller's own presentation: leave the challenge to them.
129
+ if (attached && !owns(sent, presentations, attached))
130
+ return undefined;
131
+ const origin = new URL(request.url).origin;
132
+ presentations.delete(origin);
133
+ const challenge = await claimsChallenge(response);
134
+ if (!challenge)
135
+ return undefined;
136
+ // Bound to this origin only: a server can't relay another audience's challenge.
137
+ if (challenge.aud.replace(/\/+$/, '') !== origin)
138
+ return undefined;
139
+ if (!challenge.trusted_issuers.some((issuer) => issuers.includes(issuer)))
140
+ return undefined;
141
+ if (!challenge.formats.includes(Constants.format))
142
+ return undefined;
143
+ if (!challenge.claims.every((claim) => allowed.has(claim)))
144
+ return undefined;
145
+ const presentation = await config.present({
146
+ audience: challenge.aud,
147
+ claims: challenge.claims,
148
+ nonce: challenge.nonce,
149
+ purpose: challenge.purpose,
150
+ });
151
+ if (!presentation)
152
+ return undefined;
153
+ presentations.set(origin, presentation);
154
+ track(sent, presentations, presentation);
155
+ return {};
156
+ },
157
+ };
158
+ }
159
+ /** Parses a claims challenge's problem body, or returns `undefined` when it is not one. */
160
+ export async function claimsChallenge(response) {
161
+ const body = (await response
162
+ .clone()
163
+ .json()
164
+ .catch(() => undefined));
165
+ if (!body || body.type !== Constants.claimsRequiredType)
166
+ return undefined;
167
+ const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
168
+ if (typeof body.aud !== 'string' || typeof body.nonce !== 'string' || !body.nonce)
169
+ return undefined;
170
+ if (!strings(body.claims) || body.claims.length === 0)
171
+ return undefined;
172
+ if (!strings(body.formats) || !strings(body.trusted_issuers))
173
+ return undefined;
174
+ return {
175
+ aud: body.aud,
176
+ claims: body.claims,
177
+ formats: body.formats,
178
+ nonce: body.nonce,
179
+ ...(typeof body.purpose === 'string' && { purpose: body.purpose }),
180
+ trusted_issuers: body.trusted_issuers,
181
+ type: body.type,
182
+ };
183
+ }
184
+ /** Whether the response challenges with `scheme`. */
185
+ function hasChallenge(response, scheme) {
186
+ const header = response.headers.get('WWW-Authenticate') ?? '';
187
+ return new RegExp(`(^|,)\\s*${scheme}(\\s|,|$)`, 'i').test(header);
188
+ }
189
+ /** Link CLI's `authorization` value as is, or a bare token in the `PrivateToken` scheme. */
190
+ function toAuthorization(token) {
191
+ const value = token.trim();
192
+ if (/^privatetoken\s/i.test(value))
193
+ return value;
194
+ return `${Constants.attestationScheme} token="${value}"`;
195
+ }
196
+ /** Whether this prover attached `value`: an origin's current one, or one it sent before. */
197
+ function owns(sent, current, value) {
198
+ return sent.has(value) || [...current.values()].includes(value);
199
+ }
200
+ /** Remembers a value this prover attached, keeping at most 64 that are no longer current. */
201
+ function track(sent, current, value) {
202
+ sent.add(value);
203
+ const live = new Set(current.values());
204
+ for (const old of sent) {
205
+ if (sent.size <= 64)
206
+ break;
207
+ if (!live.has(old))
208
+ sent.delete(old);
209
+ }
210
+ }
211
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Link agent identity (https://docs.link.com/concepts/agent-identity): Link Agent Attestation
3
+ * Tokens (Privacy Pass `PrivateToken`s in `Authorization`) and selectively disclosed identity
4
+ * presentations (SD-JWT in `Identity-Presentation`). The server verifies them with Link's Agent
5
+ * Identity SDK (`@stripe/agent-identity`); the client gets them from Link CLI or the Link SDK.
6
+ */
7
+ /** Client provers that answer Link attestation and claims challenges. */
8
+ export * as Client from './client/index.js';
9
+ /** Server verifiers that require a Link attestation or Link-signed claims. */
10
+ export * as Server from './server/index.js';
11
+ export * from './Constants.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Link agent identity (https://docs.link.com/concepts/agent-identity): Link Agent Attestation
3
+ * Tokens (Privacy Pass `PrivateToken`s in `Authorization`) and selectively disclosed identity
4
+ * presentations (SD-JWT in `Identity-Presentation`). The server verifies them with Link's Agent
5
+ * Identity SDK (`@stripe/agent-identity`); the client gets them from Link CLI or the Link SDK.
6
+ */
7
+ /** Client provers that answer Link attestation and claims challenges. */
8
+ export * as Client from './client/index.js';
9
+ /** Server verifiers that require a Link attestation or Link-signed claims. */
10
+ export * as Server from './server/index.js';
11
+ export * from './Constants.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,124 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import type { MaybePromise } from '../../../../internal/types.js';
3
+ import type * as Types from '../Constants.js';
4
+ /**
5
+ * Creates a request-stage verifier that requires a Link Agent Attestation Token: proof that
6
+ * Link vouches for the agent, with no personal details.
7
+ *
8
+ * A request without one gets 401 with Link's `WWW-Authenticate: PrivateToken` challenge. The
9
+ * token travels in `Authorization`, so create the server with `requiresAuth: true`: Payment
10
+ * credentials then use `Payment-Authorization` and the token stays on the paid retry.
11
+ *
12
+ * Tokens are bearer tokens: the verifier does not make them single use, and a valid one only
13
+ * says Link issued it. Tokens are checked with {@link tokenVerifier}, which needs only Web
14
+ * Crypto, unless `verifier` is set, such as to a `LinkVerifier` from `@stripe/agent-identity`
15
+ * on Node.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const mppx = Mppx.create({ methods, requiresAuth: true })
20
+ * const result = await mppx.charge({ amount: '1', identity: [Link.Server.attestation()] })(request)
21
+ * ```
22
+ */
23
+ export declare function attestation(config?: attestation.Config): Identity.Verifier<Types.VerifiedAttestation>;
24
+ export declare namespace attestation {
25
+ type Config = {
26
+ /**
27
+ * Verifies tokens, shared by every request: a `LinkVerifier` from `@stripe/agent-identity`, or
28
+ * {@link tokenVerifier} with options. @default tokenVerifier()
29
+ */
30
+ readonly verifier?: Types.AttestationVerifier | undefined;
31
+ };
32
+ }
33
+ /**
34
+ * Creates a request-stage verifier that requires claims Link signed, such as a verified email,
35
+ * presented by the credential holder for this server.
36
+ *
37
+ * A request without a presentation gets 401 with `WWW-Authenticate: Identity-Presentation` and
38
+ * Link's `urn:stripe:link:claims-required` problem body, whose nonce is signed with
39
+ * `secretKey` and expires after {@link Constants.nonceTtl} seconds, so no state is kept. The
40
+ * client presents the claims bound to `audience` and that nonce in `Identity-Presentation`.
41
+ * A presentation verifies again until its nonce expires, including on the paid retry.
42
+ *
43
+ * List it before other verifiers of the route: the rejection body is the first rejecting
44
+ * verifier's, and the client needs this one's.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * const email = Link.Server.claims({
49
+ * audience: 'https://api.example',
50
+ * claims: ['email', 'email_verified'],
51
+ * purpose: 'Write a haiku about you',
52
+ * secretKey: env.MPP_SECRET_KEY,
53
+ * verifier: link,
54
+ * })
55
+ * if (result.status === 200) result.identity?.get(email)?.email
56
+ * ```
57
+ */
58
+ export declare function claims(config: claims.Config): Identity.Verifier<Types.VerifiedClaims>;
59
+ export declare namespace claims {
60
+ type Config = {
61
+ /**
62
+ * Verifies presentations, shared by every request: a `LinkVerifier` from
63
+ * `@stripe/agent-identity`, or {@link presentationVerifier} with options.
64
+ * @default presentationVerifier({ audience, issuer })
65
+ */
66
+ readonly verifier?: Types.ClaimsVerifier | undefined;
67
+ /** This server's public origin, such as `https://api.example`: the presentation's audience. */
68
+ readonly audience: string;
69
+ /** Claims the presentation must disclose, such as `['email', 'email_verified']`. */
70
+ readonly claims: readonly string[];
71
+ /** Why the server asks, shown to the person whose claims they are. */
72
+ readonly purpose?: string | undefined;
73
+ /** Issuer the challenge names: the verifier's. Override only for staging and tests. @default 'https://api.link.com' */
74
+ readonly issuer?: string | undefined;
75
+ /** Secret that signs challenge nonces, such as the server's `MPP_SECRET_KEY`. */
76
+ readonly secretKey: string;
77
+ /** Seconds a challenge's nonce is accepted for. @default 300 */
78
+ readonly nonceTtl?: number | undefined;
79
+ /** Accepts or rejects (`forbidden`, 403) verified claims. Defaults to any. */
80
+ readonly allow?: ((claims: Types.VerifiedClaims, request: Request) => MaybePromise<boolean>) | undefined;
81
+ };
82
+ }
83
+ /**
84
+ * Creates a verifier of Link Agent Attestation Tokens that needs only Web Crypto and `fetch`,
85
+ * so it runs where `@stripe/agent-identity` can't import Link's RSASSA-PSS token key, such as
86
+ * Cloudflare Workers. It makes the same checks: the key is in the token-key directory of Link's
87
+ * issuer metadata, the token answers Link's stable bearer challenge, and its RSA-PSS (SHA-384)
88
+ * signature verifies. {@link attestation} uses it unless given another verifier.
89
+ */
90
+ export declare function tokenVerifier(config?: tokenVerifier.Config): Types.AttestationVerifier;
91
+ export declare namespace tokenVerifier {
92
+ type Config = {
93
+ /** Fetch used for Link's issuer documents. @default globalThis.fetch */
94
+ readonly fetch?: ((input: string, init: RequestInit) => MaybePromise<Response>) | undefined;
95
+ /** Issuer URL. Override only for staging and tests. @default 'https://api.link.com' */
96
+ readonly issuer?: string | undefined;
97
+ /** Seconds before the token keys are fetched again. @default 300 */
98
+ readonly maxKeyAge?: number | undefined;
99
+ /** Milliseconds each issuer request may take. @default 3000 */
100
+ readonly timeout?: number | undefined;
101
+ };
102
+ }
103
+ /**
104
+ * Creates a verifier of Link identity presentations (SD-JWT VC with a Key Binding JWT) that
105
+ * runs `verifyClaimsPresentation` from `@stripe/agent-identity` wherever `fetch` does,
106
+ * Cloudflare Workers included. It reads Link's issuer metadata itself, so the SDK's
107
+ * Node-only token key import never runs. {@link claims} uses it unless given another verifier.
108
+ */
109
+ export declare function presentationVerifier(config: presentationVerifier.Config): Types.ClaimsVerifier;
110
+ export declare namespace presentationVerifier {
111
+ type Config = {
112
+ /** This server's public origin: the presentation's audience. */
113
+ readonly audience: string;
114
+ /** Seconds a presentation is accepted after it is signed. @default 300, the nonce lifetime */
115
+ readonly maxAge?: number | undefined;
116
+ /** Fetch used for Link's issuer documents. @default globalThis.fetch */
117
+ readonly fetch?: ((input: string, init: RequestInit) => MaybePromise<Response>) | undefined;
118
+ /** Issuer URL. Override only for staging and tests. @default 'https://api.link.com' */
119
+ readonly issuer?: string | undefined;
120
+ /** Milliseconds each issuer request may take. @default 3000 */
121
+ readonly timeout?: number | undefined;
122
+ };
123
+ }
124
+ //# sourceMappingURL=index.d.ts.map