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
@@ -0,0 +1,152 @@
1
+ import type { Address, Hex } from 'viem';
2
+ import type * as Challenge from '../../../../Challenge.js';
3
+ import type * as Credential from '../../../../Credential.js';
4
+ import type * as Identity from '../../../../identity/Types.js';
5
+ import type { MaybePromise } from '../../../../internal/types.js';
6
+ import type * as Store from '../../../../Store.js';
7
+ import type * as Types from '../Types.js';
8
+ /**
9
+ * Creates a Persona client for one Persona organization and inquiry template.
10
+ *
11
+ * - `startInquiry` starts an inquiry for a reference ID and returns a one-time link to
12
+ * Persona's hosted flow.
13
+ * - `paymentCheck` requires an approved inquiry on a route's paid retry, keyed by the payer.
14
+ * - `verifier` requires one before any 402, keyed by your own session.
15
+ *
16
+ * Link a wallet to a person by proving they own it (`verifyWallet`) before you start an
17
+ * inquiry with its DID as the reference ID. Otherwise anyone can complete KYC as themselves
18
+ * for someone else's wallet.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const persona = Persona.Server.create({ apiKey: env.PERSONA_API_KEY, templateId: 'itmpl_…' })
23
+ *
24
+ * app.post('/kyc', async (request) => {
25
+ * const referenceId = await Persona.Server.verifyWallet({ ...(await request.json()), nonce })
26
+ * return Response.json(await persona.startInquiry({ referenceId }))
27
+ * })
28
+ *
29
+ * const kyc = persona.paymentCheck({
30
+ * referenceId: ({ request }) => session(request)?.wallet, // a DID from verifyWallet
31
+ * onboarding: 'https://api.example/kyc',
32
+ * cache: Store.memory(),
33
+ * })
34
+ * mppx.charge({ amount: '1', identity: { payment: kyc } })
35
+ * ```
36
+ */
37
+ export declare function create(config: create.Config): Persona;
38
+ export declare namespace create {
39
+ type Config = {
40
+ /** Persona API key. Keep it on the server. */
41
+ readonly apiKey: string;
42
+ /** Inquiry template (`itmpl_…`) to start inquiries from and to accept them from. */
43
+ readonly templateId?: string | undefined;
44
+ /** Persona API origin. @default 'https://api.withpersona.com' */
45
+ readonly apiUrl?: string | undefined;
46
+ /** `Persona-Version` header. @default '2023-01-05' */
47
+ readonly apiVersion?: string | undefined;
48
+ /** Fetch used for the Persona API. */
49
+ readonly fetch?: typeof globalThis.fetch | undefined;
50
+ /** Milliseconds before a Persona API call is abandoned. @default 5000 */
51
+ readonly timeout?: number | undefined;
52
+ };
53
+ /** What a payment check's `referenceId` receives. */
54
+ type PaymentParameters = {
55
+ readonly request: Request;
56
+ readonly challenge: Challenge.Challenge;
57
+ readonly credential?: Credential.Credential | undefined;
58
+ };
59
+ }
60
+ /** A Persona client from {@link create}. */
61
+ export type Persona = {
62
+ /** Starts an inquiry for a reference ID and returns a one-time link to Persona's hosted flow. */
63
+ readonly startInquiry: (parameters: {
64
+ /** Reference ID to match later, such as `Persona.did(…)` of a wallet the person proved they own. */
65
+ readonly referenceId: string;
66
+ /** Inquiry template, overriding the client's. */
67
+ readonly templateId?: string | undefined;
68
+ /** Where Persona sends the person after the flow. */
69
+ readonly redirectUri?: string | undefined;
70
+ }) => Promise<Types.StartedInquiry>;
71
+ /**
72
+ * Returns a payment check that requires the payer to have passed Persona KYC.
73
+ *
74
+ * Every 402 of the route advertises `Identity-Required: kyc;issuer="https://api.withpersona.com"`.
75
+ * On the paid retry, before the Credential settles, it accepts the most recent inquiry whose
76
+ * reference ID `referenceId` returns. Derive it from something your server authenticated, such
77
+ * as your own session, or a payer address your payment method verified. A Credential's
78
+ * `source` is client-supplied and some payment flows do not check it against the payer, so
79
+ * returning it as is lets a payer present another wallet's KYC. On a route with `authorize`,
80
+ * the check runs without a Credential.
81
+ *
82
+ * No payer is `missing` (401), no accepted inquiry `forbidden` (403), both with `onboarding`
83
+ * in a `Link` header; a Persona API failure is `unavailable` (503).
84
+ */
85
+ readonly paymentCheck: (options: LookupOptions & {
86
+ /** Returns the payer's authenticated reference ID, or `undefined` when there is none. */
87
+ readonly referenceId: (parameters: create.PaymentParameters) => MaybePromise<string | undefined>;
88
+ }) => Identity.PaymentCheck<Types.VerifiedInquiry>;
89
+ /**
90
+ * Returns a request-stage verifier that requires an approved inquiry before any 402, for a
91
+ * caller `referenceId` identifies from the request, such as by your own session.
92
+ */
93
+ readonly verifier: (options: LookupOptions & {
94
+ /** Returns the caller's reference ID, or `undefined` when there is none. */
95
+ readonly referenceId: (request: Request) => MaybePromise<string | undefined>;
96
+ }) => Identity.Verifier<Types.VerifiedInquiry>;
97
+ };
98
+ /** Options shared by {@link Persona.paymentCheck} and {@link Persona.verifier}. */
99
+ export type LookupOptions = {
100
+ /** Accepted inquiry statuses. @default ['approved'] */
101
+ readonly statuses?: readonly Types.InquiryStatus[] | undefined;
102
+ /** Oldest accepted verification, in seconds since the inquiry was decisioned or completed. */
103
+ readonly maxAge?: number | undefined;
104
+ /**
105
+ * Where a rejected payer starts KYC, sent as `Link: <url>; rel="kyc"` with 401 and 403
106
+ * responses, such as your endpoint that calls `startInquiry`.
107
+ */
108
+ readonly onboarding?: string | ((parameters: {
109
+ readonly request: Request;
110
+ readonly referenceId: string | undefined;
111
+ }) => MaybePromise<string | undefined>) | undefined;
112
+ /** Caches approvals by reference ID, so a paid request skips the Persona API. */
113
+ readonly cache?: Store.Store | undefined;
114
+ /** Seconds an approval stays cached. @default 300 */
115
+ readonly cacheTtl?: number | undefined;
116
+ };
117
+ /**
118
+ * Verifies that the signer of `message` owns `address` and returns the wallet's reference ID
119
+ * (`Persona.did`), to start an inquiry with. `message` must contain `nonce`, a single-use
120
+ * value your server issued for this person, so a signature cannot be replayed, and the wallet's
121
+ * DID, so the signer commits to the chain.
122
+ *
123
+ * Without `verify`, it accepts EOA signatures only. Pass `verify` for smart accounts, such as
124
+ * viem's `publicClient.verifyMessage` on `chainId`, which supports ERC-1271 and ERC-6492.
125
+ */
126
+ export declare function verifyWallet(parameters: verifyWallet.Parameters): Promise<string>;
127
+ export declare namespace verifyWallet {
128
+ type Parameters = {
129
+ /** Wallet address the person claims. */
130
+ readonly address: Address;
131
+ /** Chain ID of the wallet, such as `4217` for Tempo mainnet. */
132
+ readonly chainId: number;
133
+ /** Message the wallet signed, containing `nonce` and the wallet's DID (`Persona.did`). */
134
+ readonly message: string;
135
+ /** Signature over `message`. */
136
+ readonly signature: Hex;
137
+ /** Single-use value your server issued and the message must contain. */
138
+ readonly nonce: string;
139
+ /** Verifies the signature. Defaults to viem's `verifyMessage` (EOA only). */
140
+ readonly verify?: ((parameters: {
141
+ address: Address;
142
+ chainId: number;
143
+ message: string;
144
+ signature: Hex;
145
+ }) => Promise<boolean>) | undefined;
146
+ };
147
+ }
148
+ /** A failed or malformed Persona API call. */
149
+ export declare class PersonaError extends Error {
150
+ readonly name = "PersonaError";
151
+ }
152
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,263 @@
1
+ import { verifyMessage } from 'viem';
2
+ import { unwrapFetch } from '../../../../client/internal/Fetch.js';
3
+ import { Constants } from '../Constants.js';
4
+ import * as Did from '../Did.js';
5
+ /**
6
+ * Creates a Persona client for one Persona organization and inquiry template.
7
+ *
8
+ * - `startInquiry` starts an inquiry for a reference ID and returns a one-time link to
9
+ * Persona's hosted flow.
10
+ * - `paymentCheck` requires an approved inquiry on a route's paid retry, keyed by the payer.
11
+ * - `verifier` requires one before any 402, keyed by your own session.
12
+ *
13
+ * Link a wallet to a person by proving they own it (`verifyWallet`) before you start an
14
+ * inquiry with its DID as the reference ID. Otherwise anyone can complete KYC as themselves
15
+ * for someone else's wallet.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const persona = Persona.Server.create({ apiKey: env.PERSONA_API_KEY, templateId: 'itmpl_…' })
20
+ *
21
+ * app.post('/kyc', async (request) => {
22
+ * const referenceId = await Persona.Server.verifyWallet({ ...(await request.json()), nonce })
23
+ * return Response.json(await persona.startInquiry({ referenceId }))
24
+ * })
25
+ *
26
+ * const kyc = persona.paymentCheck({
27
+ * referenceId: ({ request }) => session(request)?.wallet, // a DID from verifyWallet
28
+ * onboarding: 'https://api.example/kyc',
29
+ * cache: Store.memory(),
30
+ * })
31
+ * mppx.charge({ amount: '1', identity: { payment: kyc } })
32
+ * ```
33
+ */
34
+ export function create(config) {
35
+ const { apiKey, apiUrl = Constants.apiUrl, apiVersion = Constants.apiVersion, templateId, timeout = Constants.timeout, } = config;
36
+ if (!apiKey)
37
+ throw new TypeError('Persona.Server.create needs an apiKey.');
38
+ // AbortSignal.timeout throws on these at request time, and Node clamps delays above 2^31 - 1 ms
39
+ // to 1 ms: either would read as a Persona outage.
40
+ if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647)
41
+ throw new TypeError('Persona.Server.create needs a positive integer timeout in milliseconds.');
42
+ // A digest of the API origin and key: identifies the Persona organization without storing the key.
43
+ const scope = digest(`${new URL(apiUrl).origin}\n${apiKey}`);
44
+ async function call(path, init = {}) {
45
+ // Unwrapped, and resolved per call: a Persona request must never pay a Payment Challenge,
46
+ // even when an mppx client polyfilled globalThis.fetch.
47
+ const fetch = unwrapFetch(config.fetch ?? globalThis.fetch);
48
+ const response = await fetch(new URL(path, apiUrl), {
49
+ ...init,
50
+ // A redirect is a failure: never send the bearer key on, nor read another origin's body.
51
+ redirect: 'manual',
52
+ headers: {
53
+ Accept: 'application/json',
54
+ Authorization: `Bearer ${apiKey}`,
55
+ 'Persona-Version': apiVersion,
56
+ ...(init.body !== undefined && { 'Content-Type': 'application/json' }),
57
+ },
58
+ signal: AbortSignal.timeout(timeout),
59
+ });
60
+ // Never surface the upstream body: it may carry request details.
61
+ if (!response.ok)
62
+ throw new PersonaError(`The Persona API returned ${response.status}.`);
63
+ return response.json();
64
+ }
65
+ /** Returns the most recent accepted inquiry for a reference ID, or `undefined`. */
66
+ async function find(referenceId, options) {
67
+ const url = new URL(Constants.inquiriesPath, apiUrl);
68
+ url.searchParams.set('filter[reference-id]', referenceId);
69
+ url.searchParams.set('filter[status]', options.statuses.join(','));
70
+ if (templateId)
71
+ url.searchParams.set('filter[inquiry-template-id]', templateId);
72
+ url.searchParams.set('page[size]', '25');
73
+ let next = url.pathname + url.search;
74
+ const now = Date.now();
75
+ for (let page = 0; next && page < Constants.maxPages; page++) {
76
+ const body = (await call(next));
77
+ if (!Array.isArray(body?.data))
78
+ throw new PersonaError('The Persona API response is malformed.');
79
+ // Persona lists the most recent inquiries first.
80
+ for (const inquiry of body.data) {
81
+ const attributes = inquiry?.attributes;
82
+ if (typeof inquiry?.id !== 'string' || !attributes)
83
+ continue;
84
+ // Recheck what the filters asked for, so an API or proxy that ignores them cannot widen them.
85
+ if (attributes['reference-id'] !== referenceId)
86
+ continue;
87
+ const status = attributes.status;
88
+ if (!options.statuses.includes(status))
89
+ continue;
90
+ // Fails closed when the inquiry does not name its template.
91
+ if (templateId && inquiry.relationships?.['inquiry-template']?.data?.id !== templateId)
92
+ continue;
93
+ const verifiedAt = date(attributes['decisioned-at'] ?? attributes['completed-at']);
94
+ if (!fresh(verifiedAt, options.maxAge, now))
95
+ continue;
96
+ return Object.freeze({ inquiryId: inquiry.id, referenceId, status, verifiedAt });
97
+ }
98
+ next = sameOrigin(body.links?.next, apiUrl);
99
+ }
100
+ return undefined;
101
+ }
102
+ /** Looks a reference ID up, through the cache when set, and maps the result to a verification. */
103
+ async function lookup(referenceId, options, request) {
104
+ const { cache, cacheTtl = Constants.cacheTtl, maxAge, statuses = Constants.statuses } = options;
105
+ if (statuses.length === 0)
106
+ throw new TypeError('Persona needs at least one accepted status.');
107
+ const headers = await onboardingHeaders(options.onboarding, request, referenceId);
108
+ if (!referenceId)
109
+ return { status: 'missing', headers, reason: 'Persona KYC requires a payer.' };
110
+ // Scoped to the Persona organization and environment, so clients sharing a Store never
111
+ // accept each other's approvals.
112
+ const key = `mppx:persona:${await scope}:${templateId ?? ''}:${referenceId}`;
113
+ const now = Date.now();
114
+ const cached = cache ? (await cache.get(key)) : null;
115
+ if (cached &&
116
+ // Each check applies its own lifetime, so a longer-lived check sharing the Store never
117
+ // extends a stricter one's revalidation window.
118
+ cached.cachedAt + cacheTtl * 1_000 > now &&
119
+ statuses.includes(cached.status) &&
120
+ fresh(date(cached.verifiedAt), maxAge, now))
121
+ return {
122
+ status: 'valid',
123
+ value: Object.freeze({
124
+ inquiryId: cached.inquiryId,
125
+ referenceId,
126
+ status: cached.status,
127
+ verifiedAt: date(cached.verifiedAt),
128
+ }),
129
+ };
130
+ let inquiry;
131
+ try {
132
+ inquiry = await find(referenceId, { statuses, maxAge });
133
+ }
134
+ catch {
135
+ return { status: 'unavailable', reason: 'Persona KYC verification is unavailable.' };
136
+ }
137
+ if (!inquiry)
138
+ return { status: 'forbidden', headers, reason: 'The payer has not passed Persona KYC.' };
139
+ // Only approvals are cached, so a person who just passed KYC is never kept waiting.
140
+ if (cache)
141
+ await cache.put(key, {
142
+ cachedAt: now,
143
+ inquiryId: inquiry.inquiryId,
144
+ status: inquiry.status,
145
+ verifiedAt: inquiry.verifiedAt?.toISOString(),
146
+ });
147
+ return { status: 'valid', value: inquiry };
148
+ }
149
+ return Object.freeze({
150
+ async startInquiry(parameters) {
151
+ const { redirectUri, referenceId } = parameters;
152
+ const inquiryTemplateId = parameters.templateId ?? templateId;
153
+ if (!referenceId)
154
+ throw new TypeError('startInquiry needs a referenceId.');
155
+ if (!inquiryTemplateId)
156
+ throw new TypeError('startInquiry needs a templateId.');
157
+ const created = (await call(Constants.inquiriesPath, {
158
+ method: 'POST',
159
+ body: JSON.stringify({
160
+ data: {
161
+ attributes: {
162
+ 'inquiry-template-id': inquiryTemplateId,
163
+ 'reference-id': referenceId,
164
+ ...(redirectUri && { 'redirect-uri': redirectUri }),
165
+ },
166
+ },
167
+ }),
168
+ }));
169
+ const inquiryId = created?.data?.id;
170
+ if (typeof inquiryId !== 'string')
171
+ throw new PersonaError('The Persona API response is malformed.');
172
+ const link = (await call(`${Constants.inquiriesPath}/${encodeURIComponent(inquiryId)}/generate-one-time-link`, { method: 'POST', body: '{}' }));
173
+ const url = link?.meta?.['one-time-link'];
174
+ if (typeof url !== 'string')
175
+ throw new PersonaError('The Persona API response is malformed.');
176
+ return Object.freeze({ inquiryId, url });
177
+ },
178
+ paymentCheck(options) {
179
+ const { referenceId } = options;
180
+ return Object.freeze({
181
+ requires: Object.freeze([
182
+ Object.freeze({ type: Constants.type, issuer: Constants.issuer }),
183
+ ]),
184
+ async verify(parameters) {
185
+ return lookup(await referenceId(parameters), options, parameters.request);
186
+ },
187
+ });
188
+ },
189
+ verifier(options) {
190
+ return Object.freeze({
191
+ async verify(request) {
192
+ return lookup(await options.referenceId(request), options, request);
193
+ },
194
+ });
195
+ },
196
+ });
197
+ }
198
+ /**
199
+ * Verifies that the signer of `message` owns `address` and returns the wallet's reference ID
200
+ * (`Persona.did`), to start an inquiry with. `message` must contain `nonce`, a single-use
201
+ * value your server issued for this person, so a signature cannot be replayed, and the wallet's
202
+ * DID, so the signer commits to the chain.
203
+ *
204
+ * Without `verify`, it accepts EOA signatures only. Pass `verify` for smart accounts, such as
205
+ * viem's `publicClient.verifyMessage` on `chainId`, which supports ERC-1271 and ERC-6492.
206
+ */
207
+ export async function verifyWallet(parameters) {
208
+ const { address, chainId, message, nonce, signature } = parameters;
209
+ if (!nonce || !message.includes(nonce))
210
+ throw new TypeError('The signed message must contain the nonce.');
211
+ const referenceId = Did.did({ address, chainId });
212
+ // The signer commits to the chain as well as the address: the same address can have different
213
+ // owners on different chains.
214
+ if (!message.toLowerCase().includes(referenceId.toLowerCase()))
215
+ throw new TypeError(`The signed message must contain the wallet's DID, ${referenceId}.`);
216
+ const verify = parameters.verify ?? verifyMessage;
217
+ const valid = await verify({ address, chainId, message, signature }).catch(() => false);
218
+ if (!valid)
219
+ throw new TypeError('The signature does not match the address.');
220
+ return referenceId;
221
+ }
222
+ /** A failed or malformed Persona API call. */
223
+ export class PersonaError extends Error {
224
+ name = 'PersonaError';
225
+ }
226
+ async function onboardingHeaders(onboarding, request, referenceId) {
227
+ const url = typeof onboarding === 'function' ? await onboarding({ request, referenceId }) : onboarding;
228
+ if (!url)
229
+ return undefined;
230
+ return { Link: `<${url}>; rel="${Constants.rel}"` };
231
+ }
232
+ function fresh(verifiedAt, maxAge, now) {
233
+ if (maxAge === undefined)
234
+ return true;
235
+ if (!(Number.isInteger(maxAge) && maxAge > 0))
236
+ throw new RangeError('Persona maxAge must be a positive integer.');
237
+ return verifiedAt !== undefined && now - verifiedAt.getTime() <= maxAge * 1_000;
238
+ }
239
+ function date(value) {
240
+ if (typeof value !== 'string')
241
+ return undefined;
242
+ const parsed = new Date(value);
243
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
244
+ }
245
+ async function digest(value) {
246
+ const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
247
+ return Array.from(new Uint8Array(hash).slice(0, 16), (byte) => byte.toString(16).padStart(2, '0')).join('');
248
+ }
249
+ /**
250
+ * Returns a pagination link as a path, or `undefined` unless it is on the Persona API origin, so
251
+ * the API key is never sent to an origin a response names.
252
+ */
253
+ function sameOrigin(link, apiUrl) {
254
+ if (typeof link !== 'string')
255
+ return undefined;
256
+ const base = new URL(apiUrl);
257
+ const url = new URL(link, base);
258
+ if (url.origin !== base.origin)
259
+ return undefined;
260
+ // The absolute URL, not its path: a path such as '//host/x' would resolve to another origin.
261
+ return url.href;
262
+ }
263
+ //# sourceMappingURL=index.js.map
@@ -7,7 +7,12 @@
7
7
  * never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
8
8
  * their own extra sensitive headers in `Prover.headers`.
9
9
  */
10
- export declare const request: readonly ["identity-attestation"];
10
+ export declare const request: readonly ["identity-attestation", "identity-presentation"];
11
+ /**
12
+ * `WWW-Authenticate` schemes that ask for an identity, lowercased. A proxy removes them from
13
+ * upstream responses: the proxy, not the upstream, decides which identity the client presents.
14
+ */
15
+ export declare const challenges: readonly ["privatetoken", "identity-presentation"];
11
16
  /**
12
17
  * Identity response headers a proxy must not pass on from upstream: they ask the client for an
13
18
  * identity the proxy, not the upstream, decides on.
@@ -7,7 +7,12 @@
7
7
  * never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
8
8
  * their own extra sensitive headers in `Prover.headers`.
9
9
  */
10
- export const request = Object.freeze(['identity-attestation']);
10
+ export const request = Object.freeze(['identity-attestation', 'identity-presentation']);
11
+ /**
12
+ * `WWW-Authenticate` schemes that ask for an identity, lowercased. A proxy removes them from
13
+ * upstream responses: the proxy, not the upstream, decides which identity the client presents.
14
+ */
15
+ export const challenges = Object.freeze(['privatetoken', 'identity-presentation']);
11
16
  /**
12
17
  * Identity response headers a proxy must not pass on from upstream: they ask the client for an
13
18
  * identity the proxy, not the upstream, decides on.
@@ -24,6 +24,8 @@ export function anyOf(...verifiers) {
24
24
  for (const verifier of verifiers)
25
25
  assertRequestStage(verifier);
26
26
  const verifier = Object.freeze({
27
+ // A member that reads Authorization makes the whole set need requiresAuth.
28
+ ...(verifiers.some((member) => member.authorization) ? { authorization: true } : {}),
27
29
  async verify(request) {
28
30
  // Every member runs, so each presented proof's replay nonce is consumed even when an
29
31
  // earlier member already verified.
@@ -77,6 +77,11 @@ export type Verifier<value = unknown> = {
77
77
  readonly challenge?: ((request: Request, context: {
78
78
  readonly nonce: string;
79
79
  }) => unknown) | undefined;
80
+ /**
81
+ * The verifier reads its credential from `Authorization`. A route that uses it needs a server
82
+ * created with `requiresAuth: true`, so Payment Credentials travel in `Payment-Authorization`.
83
+ */
84
+ readonly authorization?: boolean | undefined;
80
85
  /** Returns the protocol's verification outcome for the request. */
81
86
  readonly verify: (request: Request) => MaybePromise<Verification<value>>;
82
87
  };
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export * as BodyDigest from './BodyDigest.js';
2
2
  export * as Challenge from './Challenge.js';
3
3
  export * as Constants from './Constants.js';
4
4
  export * as Credential from './Credential.js';
5
+ export * as Currency from './Currency.js';
5
6
  export * as Errors from './Errors.js';
6
7
  export * as Expires from './Expires.js';
7
8
  export * as evm from './evm/index.js';
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ export * as BodyDigest from './BodyDigest.js';
2
2
  export * as Challenge from './Challenge.js';
3
3
  export * as Constants from './Constants.js';
4
4
  export * as Credential from './Credential.js';
5
+ export * as Currency from './Currency.js';
5
6
  export * as Errors from './Errors.js';
6
7
  export * as Expires from './Expires.js';
7
8
  export * as evm from './evm/index.js';
@@ -1,5 +1,5 @@
1
1
  /** Current mppx package version. */
2
- export declare const version = "0.18.0";
2
+ export declare const version = "0.18.1";
3
3
  /** Canonical SDK identifier for this mppx release. */
4
- export declare const sdkIdentifier = "mppx/0.18.0";
4
+ export declare const sdkIdentifier = "mppx/0.18.1";
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  // Generated by scripts/sync-version.ts.
2
2
  /** Current mppx package version. */
3
- export const version = '0.18.0';
3
+ export const version = '0.18.1';
4
4
  /** Canonical SDK identifier for this mppx release. */
5
5
  export const sdkIdentifier = `mppx/${version}`;
6
6
  //# sourceMappingURL=version.js.map
@@ -76,7 +76,7 @@ export function scrubResponse(response) {
76
76
  headers.delete('authorization');
77
77
  const authenticate = headers.get('www-authenticate');
78
78
  if (authenticate) {
79
- const remaining = removePaymentChallenges(authenticate);
79
+ const remaining = removeChallenges(authenticate);
80
80
  if (remaining)
81
81
  headers.set('www-authenticate', remaining);
82
82
  else
@@ -88,8 +88,8 @@ export function scrubResponse(response) {
88
88
  headers,
89
89
  });
90
90
  }
91
- /** Removes Payment authentication challenges while preserving other schemes. */
92
- function removePaymentChallenges(value) {
91
+ /** Removes Payment and identity authentication challenges while preserving other schemes. */
92
+ function removeChallenges(value) {
93
93
  const starts = [];
94
94
  let inQuotes = false;
95
95
  let escaped = false;
@@ -125,7 +125,7 @@ function removePaymentChallenges(value) {
125
125
  index = afterScheme - 1;
126
126
  }
127
127
  return starts
128
- .filter(({ scheme }) => scheme !== 'payment')
128
+ .filter(({ scheme }) => scheme !== 'payment' && !IdentityHeaders.challenges.includes(scheme))
129
129
  .map(({ index }) => {
130
130
  const originalPosition = starts.findIndex((start) => start.index === index);
131
131
  const end = starts[originalPosition + 1]?.index ?? value.length;
@@ -445,6 +445,10 @@ function createMethodFn(parameters) {
445
445
  const paymentCheck = identityRoute.payment;
446
446
  const identityRequirements = paymentCheck?.requires ?? [];
447
447
  const hasIdentity = identityRoute.request.length > 0 || paymentCheck !== undefined;
448
+ // A verifier that reads Authorization would lose its credential to the Payment Credential.
449
+ if (identityRoute.request.some((verifier) => verifier.authorization) &&
450
+ credentialHeader !== Constants.Headers.paymentAuthorization)
451
+ throw new TypeError('An identity verifier on this route reads Authorization: create the server with requiresAuth: true.');
448
452
  // Preflight hooks (e.g. session bootstrap) issue and settle their own challenges, which
449
453
  // the payment check cannot see; reject the combination instead of skipping identity.
450
454
  if (paymentCheck && preflight)
@@ -659,7 +663,6 @@ function createMethodFn(parameters) {
659
663
  if ('response' in routeChallenge)
660
664
  return { challenge: routeChallenge.response, status: 402 };
661
665
  const { challenge, parsedRequest, request } = routeChallenge;
662
- internal._canonicalRequest = parsedRequest;
663
666
  // A transport that builds the Credential's Challenge itself (x402, whose Credentials name
664
667
  // no Challenge) leaves nothing the client proved a payment check against.
665
668
  let challengeFromTransport = false;
@@ -2013,7 +2016,7 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
2013
2016
  function hasCheckedTwin(offers) {
2014
2017
  const checked = offers.filter((offer) => offer._paymentCheck !== undefined);
2015
2018
  const unchecked = offers.filter((offer) => offer._paymentCheck === undefined);
2016
- return checked.some((a) => unchecked.some((b) => a.name === b.name && a.intent === b.intent && sameTerms(a, b) && sameTerms(b, a)));
2019
+ return checked.some((a) => unchecked.some((b) => a.name === b.name && a.intent === b.intent && (sameTerms(a, b) || sameTerms(b, a))));
2017
2020
  }
2018
2021
  /** Whether a Credential for offer `b`'s terms passes offer `a`'s dispatch binding. */
2019
2022
  function sameTerms(a, b) {