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,518 @@
1
+ import { Base64, Bytes } from 'ox';
2
+ import { unwrapFetch } from '../../../../client/internal/Fetch.js';
3
+ import { Constants } 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 function attestation(config = {}) {
24
+ const verifier = config.verifier ?? tokenVerifier();
25
+ async function challenge(status, reason) {
26
+ try {
27
+ const { wwwAuthenticate } = await verifier.attestationChallenge();
28
+ return {
29
+ status,
30
+ reason,
31
+ headers: wwwAuthenticate.map((value) => ['WWW-Authenticate', value]),
32
+ };
33
+ }
34
+ catch (error) {
35
+ return {
36
+ status: 'unavailable',
37
+ reason: `Link is unavailable: ${error instanceof Error ? error.message : error}`,
38
+ };
39
+ }
40
+ }
41
+ return {
42
+ authorization: true,
43
+ async verify(request) {
44
+ const authorization = request.headers.get('Authorization');
45
+ if (!authorization || !hasScheme(authorization, Constants.attestationScheme))
46
+ return challenge('missing', authorization && hasScheme(authorization, 'Payment')
47
+ ? 'A Link attestation needs Authorization: create the server with requiresAuth: true.'
48
+ : 'A Link attestation is required.');
49
+ const result = await verifier.verifyAttestation(authorization);
50
+ if (result.valid)
51
+ return {
52
+ status: 'valid',
53
+ value: Object.freeze({ issuer: result.issuer, tokenKeyId: result.tokenKeyId }),
54
+ };
55
+ if (unavailable(result.failures))
56
+ return { status: 'unavailable', reason: reason(result.failures, 'Link is unavailable.') };
57
+ return challenge('invalid', reason(result.failures, 'The Link attestation is invalid.'));
58
+ },
59
+ };
60
+ }
61
+ /**
62
+ * Creates a request-stage verifier that requires claims Link signed, such as a verified email,
63
+ * presented by the credential holder for this server.
64
+ *
65
+ * A request without a presentation gets 401 with `WWW-Authenticate: Identity-Presentation` and
66
+ * Link's `urn:stripe:link:claims-required` problem body, whose nonce is signed with
67
+ * `secretKey` and expires after {@link Constants.nonceTtl} seconds, so no state is kept. The
68
+ * client presents the claims bound to `audience` and that nonce in `Identity-Presentation`.
69
+ * A presentation verifies again until its nonce expires, including on the paid retry.
70
+ *
71
+ * List it before other verifiers of the route: the rejection body is the first rejecting
72
+ * verifier's, and the client needs this one's.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * const email = Link.Server.claims({
77
+ * audience: 'https://api.example',
78
+ * claims: ['email', 'email_verified'],
79
+ * purpose: 'Write a haiku about you',
80
+ * secretKey: env.MPP_SECRET_KEY,
81
+ * verifier: link,
82
+ * })
83
+ * if (result.status === 200) result.identity?.get(email)?.email
84
+ * ```
85
+ */
86
+ export function claims(config) {
87
+ const { allow, purpose } = config;
88
+ // One audience for the challenge and the verifier, whatever trailing slash the config has.
89
+ const audience = normalizeAudience(config.audience);
90
+ const verifier = config.verifier ??
91
+ presentationVerifier({
92
+ audience,
93
+ issuer: config.issuer,
94
+ maxAge: config.nonceTtl ?? Constants.nonceTtl,
95
+ });
96
+ const required = [...config.claims];
97
+ if (required.length === 0)
98
+ throw new TypeError('Link claims needs at least one claim.');
99
+ const ttl = config.nonceTtl ?? Constants.nonceTtl;
100
+ const key = crypto.subtle.importKey('raw', new TextEncoder().encode(config.secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
101
+ // Binds a nonce to this verifier's audience and claims.
102
+ const context = (expires, random) => new TextEncoder().encode(['mppx/link-claims', audience, required.join(' '), expires, random].join('\n'));
103
+ async function nonce() {
104
+ const expires = String(Math.floor(Date.now() / 1_000) + ttl);
105
+ const random = Base64.fromBytes(Bytes.random(16), { url: true, pad: false });
106
+ const mac = new Uint8Array(await crypto.subtle.sign('HMAC', await key, context(expires, random)));
107
+ return [expires, random, Base64.fromBytes(mac, { url: true, pad: false })].join('.');
108
+ }
109
+ /** Returns `value` when it is a nonce this verifier issued that has not expired. */
110
+ async function issued(value) {
111
+ if (typeof value !== 'string')
112
+ return undefined;
113
+ const [expires, random, mac, ...rest] = value.split('.');
114
+ if (!expires || !random || !mac || rest.length > 0 || !/^\d{1,12}$/.test(expires))
115
+ return undefined;
116
+ if (Number(expires) < Date.now() / 1_000)
117
+ return undefined;
118
+ try {
119
+ const signature = Uint8Array.from(Base64.toBytes(mac));
120
+ const valid = await crypto.subtle.verify('HMAC', await key, signature, context(expires, random));
121
+ return valid ? value : undefined;
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ }
127
+ async function challenge(status, detail) {
128
+ const body = {
129
+ type: Constants.claimsRequiredType,
130
+ aud: audience,
131
+ nonce: await nonce(),
132
+ claims: required,
133
+ ...(purpose && { purpose }),
134
+ formats: [Constants.format],
135
+ trusted_issuers: [config.issuer ?? Constants.issuer],
136
+ detail,
137
+ };
138
+ return {
139
+ status,
140
+ reason: JSON.stringify(body),
141
+ headers: [
142
+ ['WWW-Authenticate', Constants.presentationHeader],
143
+ ['Content-Type', 'application/problem+json'],
144
+ ],
145
+ };
146
+ }
147
+ return {
148
+ async verify(request) {
149
+ const presentation = request.headers.get(Constants.presentationHeader);
150
+ if (!presentation)
151
+ return challenge('missing', 'Link identity claims are required.');
152
+ const presented = await issued(nonceOf(presentation));
153
+ if (!presented)
154
+ return challenge('invalid', 'The presentation nonce is unknown or expired.');
155
+ const result = await verifier.verifyClaims(presentation, {
156
+ nonce: presented,
157
+ requiredClaims: required,
158
+ });
159
+ if (!result.valid) {
160
+ if (unavailable(result.failures))
161
+ return { status: 'unavailable', reason: reason(result.failures, 'Link is unavailable.') };
162
+ return challenge('invalid', reason(result.failures, 'The Link presentation is invalid.'));
163
+ }
164
+ const disclosed = result.claims;
165
+ // A verified email needs both claims, and email_verified must be true.
166
+ const verifiedEmail = typeof disclosed.email === 'string' && disclosed.email_verified === true
167
+ ? disclosed.email.toLowerCase()
168
+ : undefined;
169
+ if (required.includes('email_verified') && disclosed.email_verified !== true)
170
+ return { status: 'forbidden', reason: 'The email address is not verified.' };
171
+ const value = Object.freeze({
172
+ claims: Object.freeze({ ...disclosed }),
173
+ holderKeyThumbprint: result.holderKeyThumbprint,
174
+ issuer: result.issuer,
175
+ vct: result.vct,
176
+ ...(verifiedEmail && { email: verifiedEmail }),
177
+ });
178
+ if (allow && !(await allow(value, request)))
179
+ return { status: 'forbidden', reason: 'These claims are not allowed.' };
180
+ return { status: 'valid', value };
181
+ },
182
+ };
183
+ }
184
+ /** The nonce of a presentation's Key Binding JWT, its last `~` segment, unverified. */
185
+ function nonceOf(presentation) {
186
+ try {
187
+ const kb = presentation.slice(presentation.lastIndexOf('~') + 1);
188
+ const payload = kb.split('.')[1];
189
+ if (!payload)
190
+ return undefined;
191
+ return JSON.parse(Bytes.toString(Base64.toBytes(payload))).nonce;
192
+ }
193
+ catch {
194
+ return undefined;
195
+ }
196
+ }
197
+ /** Whether an `Authorization` value uses `scheme`. */
198
+ function hasScheme(value, scheme) {
199
+ return value.trimStart().toLowerCase().startsWith(`${scheme.toLowerCase()} `);
200
+ }
201
+ function unavailable(failures) {
202
+ return failures.some((failure) => failure.code === 'issuer_unavailable');
203
+ }
204
+ function reason(failures, fallback) {
205
+ const first = failures[0];
206
+ return first ? `${first.code}: ${first.message}` : fallback;
207
+ }
208
+ /** Privacy Pass token type of a Link attestation: blind RSA (RFC 9578). */
209
+ const tokenType = 0x0002;
210
+ /** Byte sizes of a token's fields. */
211
+ const sizes = { nonce: 32, digest: 32, keyId: 32, authenticator: 256 };
212
+ const tokenSize = 2 + sizes.nonce + sizes.digest + sizes.keyId + sizes.authenticator;
213
+ const inputSize = tokenSize - sizes.authenticator;
214
+ /** `AlgorithmIdentifier { rsaEncryption, NULL }`, the RSA key encoding Web Crypto imports. */
215
+ const rsaEncryption = [
216
+ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
217
+ ];
218
+ /** `AlgorithmIdentifier { id-RSASSA-PSS, SHA-384, MGF1-SHA-384, salt 48 }`, the one RFC 9578 allows. */
219
+ const rsaPss = [
220
+ 0x30, 0x3d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30, 0x30, 0xa0,
221
+ 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0xa1, 0x1a,
222
+ 0x30, 0x18, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0b, 0x06,
223
+ 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0xa2, 0x03, 0x02, 0x01, 0x30,
224
+ ];
225
+ /**
226
+ * Creates a verifier of Link Agent Attestation Tokens that needs only Web Crypto and `fetch`,
227
+ * so it runs where `@stripe/agent-identity` can't import Link's RSASSA-PSS token key, such as
228
+ * Cloudflare Workers. It makes the same checks: the key is in the token-key directory of Link's
229
+ * issuer metadata, the token answers Link's stable bearer challenge, and its RSA-PSS (SHA-384)
230
+ * signature verifies. {@link attestation} uses it unless given another verifier.
231
+ */
232
+ export function tokenVerifier(config = {}) {
233
+ const issuer = (config.issuer ?? Constants.issuer).replace(/\/+$/, '');
234
+ const issuerOrigin = new URL(issuer).origin;
235
+ const maxKeyAge = (config.maxKeyAge ?? 300) * 1_000;
236
+ // Unwrapped: fetching issuer documents must never pay a Payment challenge.
237
+ const fetch = unwrapFetch((config.fetch ?? globalThis.fetch));
238
+ let cache;
239
+ let loading;
240
+ // An unknown key ID is free to mint: refresh for one at most every 30 seconds.
241
+ const get = (url) => getJson(url, { fetch, origin: issuerOrigin, timeout: config.timeout ?? 3_000 });
242
+ async function load() {
243
+ const metadata = await get(`${issuer}/.well-known/aap-issuer`);
244
+ if (typeof metadata.issuer !== 'string' || metadata.issuer.replace(/\/+$/, '') !== issuer)
245
+ throw new Error('The issuer metadata names another issuer.');
246
+ if (typeof metadata.token_keys !== 'string')
247
+ throw new Error('The issuer metadata has no token_keys.');
248
+ const directory = await get(metadata.token_keys);
249
+ const entries = Array.isArray(directory['token-keys']) ? directory['token-keys'] : [];
250
+ const keys = new Map();
251
+ for (const entry of entries) {
252
+ if (entry?.['token-type'] !== tokenType || typeof entry['token-key'] !== 'string')
253
+ continue;
254
+ const spki = fromBase64(entry['token-key']);
255
+ const key = spki && (await importKey(spki));
256
+ if (!spki || !key)
257
+ continue;
258
+ const notBefore = typeof entry['not-before'] === 'number' ? entry['not-before'] : undefined;
259
+ keys.set(toBase64(await sha256(spki)), { key, notBefore, spki: toBase64(spki) });
260
+ }
261
+ if (keys.size === 0)
262
+ throw new Error(`${issuer} published no usable token key.`);
263
+ cache = { at: Date.now(), keys };
264
+ return keys;
265
+ }
266
+ function keys(force = false) {
267
+ if (!force && cache && Date.now() - cache.at < maxKeyAge)
268
+ return Promise.resolve(cache.keys);
269
+ loading ??= load().finally(() => {
270
+ loading = undefined;
271
+ });
272
+ return loading;
273
+ }
274
+ const challenge = encodeChallenge(new URL(issuer).host);
275
+ const failure = (code, message) => ({
276
+ valid: false,
277
+ failures: [{ code, message }],
278
+ });
279
+ return {
280
+ async attestationChallenge() {
281
+ const now = Date.now() / 1_000;
282
+ const encoded = toBase64(challenge, true);
283
+ const wwwAuthenticate = [...(await keys()).values()]
284
+ .filter((key) => key.notBefore === undefined || now >= key.notBefore)
285
+ .map((key) => `PrivateToken challenge="${encoded}", token-key="${pad(key.spki)}", max-age=300`);
286
+ return { wwwAuthenticate };
287
+ },
288
+ async verifyAttestation(authorization) {
289
+ if (!authorization)
290
+ return failure('incomplete_protocol_request', 'No PrivateToken credential.');
291
+ const raw = parseAuthorization(authorization);
292
+ if (typeof raw === 'string')
293
+ return failure('malformed_protocol_input', raw);
294
+ if (raw.length !== tokenSize)
295
+ return failure('malformed_protocol_input', `The token is ${raw.length} bytes, expected ${tokenSize}.`);
296
+ if (((raw[0] << 8) | raw[1]) !== tokenType)
297
+ return failure('malformed_protocol_input', 'The token is not a blind RSA token.');
298
+ const digest = raw.slice(2 + sizes.nonce, 2 + sizes.nonce + sizes.digest);
299
+ if (!equal(digest, await sha256(challenge)))
300
+ return failure('challenge_mismatch', 'The token answers another challenge.');
301
+ const keyId = toBase64(raw.slice(inputSize - sizes.keyId, inputSize));
302
+ let key;
303
+ try {
304
+ // No refresh for an unknown key id, which anyone can send: the short cache picks up
305
+ // keys Link publishes ahead of their activation.
306
+ key = (await keys()).get(keyId);
307
+ }
308
+ catch (error) {
309
+ return failure('issuer_unavailable', error instanceof Error ? error.message : String(error));
310
+ }
311
+ if (!key)
312
+ return failure('unknown_issuer', 'Link does not publish the token key.');
313
+ if (key.notBefore !== undefined && Date.now() / 1_000 < key.notBefore)
314
+ return failure('unknown_issuer', 'The token key is not active yet.');
315
+ const valid = await crypto.subtle.verify({ name: 'RSA-PSS', saltLength: 48 }, key.key, raw.slice(inputSize), raw.slice(0, inputSize));
316
+ if (!valid)
317
+ return failure('invalid_private_token', 'The token signature does not verify.');
318
+ return { valid: true, bindingMode: 'bearer', issuer, tokenKeyId: keyId };
319
+ },
320
+ };
321
+ }
322
+ /** The stable TokenChallenge for `issuerName`: no redemption context, no origin info. */
323
+ function encodeChallenge(issuerName) {
324
+ const name = new TextEncoder().encode(issuerName);
325
+ return new Uint8Array([
326
+ tokenType >> 8,
327
+ tokenType & 0xff,
328
+ name.length >> 8,
329
+ name.length & 0xff,
330
+ ...name,
331
+ 0,
332
+ 0,
333
+ 0,
334
+ ]);
335
+ }
336
+ /** Returns the token bytes of a `PrivateToken token="…"` credential, or why it is malformed. */
337
+ function parseAuthorization(value) {
338
+ if (value.length > 8_192)
339
+ return 'Authorization is too long.';
340
+ const match = /^\s*PrivateToken[ \t]+(.*)$/is.exec(value);
341
+ if (!match || /[\r\n]/.test(value))
342
+ return 'Authorization is not a PrivateToken credential.';
343
+ const tokens = [...match[1].matchAll(/(?:^|,)\s*token\s*=\s*(?:"([^"]*)"|([^,\s]*))/gi)];
344
+ if (tokens.length !== 1)
345
+ return 'The credential needs exactly one token parameter.';
346
+ const bytes = fromBase64(tokens[0][1] ?? tokens[0][2] ?? '');
347
+ return bytes ?? 'The token is not base64url.';
348
+ }
349
+ /** Imports an RSA token key, re-wrapping RFC 9578's id-RSASSA-PSS encoding for Web Crypto. */
350
+ async function importKey(spki) {
351
+ try {
352
+ const outer = tlv(spki, 0);
353
+ if (outer.tag !== 0x30 || outer.end !== spki.length)
354
+ return undefined;
355
+ const algorithm = tlv(spki, outer.start);
356
+ const bits = tlv(spki, algorithm.end);
357
+ if (bits.tag !== 0x03 || bits.end !== outer.end)
358
+ return undefined;
359
+ const identifier = [...spki.slice(outer.start, algorithm.end)];
360
+ const pss = equal(identifier, rsaPss);
361
+ if (!pss && !equal(identifier, rsaEncryption))
362
+ return undefined;
363
+ const importable = pss
364
+ ? sequence([...rsaEncryption, ...spki.slice(algorithm.end, bits.end)])
365
+ : spki;
366
+ const key = await crypto.subtle.importKey('spki', importable, { name: 'RSA-PSS', hash: 'SHA-384' }, false, ['verify']);
367
+ const { modulusLength } = key.algorithm;
368
+ return modulusLength === sizes.authenticator * 8 ? key : undefined;
369
+ }
370
+ catch {
371
+ return undefined;
372
+ }
373
+ }
374
+ /** Reads one DER tag-length-value at `offset`. */
375
+ function tlv(bytes, offset) {
376
+ const tag = bytes[offset];
377
+ let length = bytes[offset + 1];
378
+ let start = offset + 2;
379
+ if (length & 0x80) {
380
+ const count = length & 0x7f;
381
+ if (count === 0 || count > 2)
382
+ throw new Error('Unsupported DER length.');
383
+ length = 0;
384
+ for (let i = 0; i < count; i++)
385
+ length = (length << 8) | bytes[start + i];
386
+ start += count;
387
+ }
388
+ if (start + length > bytes.length)
389
+ throw new Error('Truncated DER.');
390
+ return { tag, start, end: start + length };
391
+ }
392
+ /** A DER SEQUENCE of `contents`. */
393
+ function sequence(contents) {
394
+ const length = contents.length < 0x80
395
+ ? [contents.length]
396
+ : contents.length < 0x100
397
+ ? [0x81, contents.length]
398
+ : [0x82, contents.length >> 8, contents.length & 0xff];
399
+ return new Uint8Array([0x30, ...length, ...contents]);
400
+ }
401
+ function pad(value) {
402
+ return value + '='.repeat((4 - (value.length % 4)) % 4);
403
+ }
404
+ /**
405
+ * Creates a verifier of Link identity presentations (SD-JWT VC with a Key Binding JWT) that
406
+ * runs `verifyClaimsPresentation` from `@stripe/agent-identity` wherever `fetch` does,
407
+ * Cloudflare Workers included. It reads Link's issuer metadata itself, so the SDK's
408
+ * Node-only token key import never runs. {@link claims} uses it unless given another verifier.
409
+ */
410
+ export function presentationVerifier(config) {
411
+ const issuer = (config.issuer ?? Constants.issuer).replace(/\/+$/, '');
412
+ const audience = normalizeAudience(config.audience);
413
+ const timeout = config.timeout ?? 3_000;
414
+ const maxAge = config.maxAge ?? Constants.nonceTtl;
415
+ const base = unwrapFetch((config.fetch ?? globalThis.fetch));
416
+ // The SDK refuses redirects with `redirect: 'error'`, which Workers reject: a 3xx is a failure either way.
417
+ const fetch = (input, init) => base(input, init.redirect === 'error' ? { ...init, redirect: 'manual' } : init);
418
+ const getMetadata = metadata({ fetch, issuer, maxAge: 3_600_000, timeout });
419
+ return {
420
+ async verifyClaims(presentation, options) {
421
+ if (!presentation)
422
+ return {
423
+ valid: false,
424
+ failures: [{ code: 'incomplete_protocol_request', message: 'No Identity-Presentation.' }],
425
+ };
426
+ const { verifyClaimsPresentation } = await import('@stripe/agent-identity');
427
+ return verifyClaimsPresentation({
428
+ audience,
429
+ fetchImpl: fetch,
430
+ issuer: { issuer, getMetadata: () => getMetadata() },
431
+ // The SDK never refetches Link's credential keys for an unknown key id, so a short
432
+ // cache bounds how long a rotated key is refused, without fetches a caller can trigger.
433
+ // The nonce bounds freshness; the presentation is resent on the paid retry, so it stays
434
+ // valid as long as its nonce rather than the SDK's 60 s default.
435
+ clockSkewSeconds: maxAge,
436
+ jwksTtlSeconds: 300,
437
+ nonce: options.nonce,
438
+ presentation,
439
+ requiredClaims: [...options.requiredClaims],
440
+ timeoutMs: timeout,
441
+ });
442
+ },
443
+ };
444
+ }
445
+ /** The audience as challenged and verified: the origin, without a trailing slash. */
446
+ function normalizeAudience(audience) {
447
+ return audience.replace(/\/+$/, '');
448
+ }
449
+ /** Decodes base64 or base64url, padded or not; `undefined` when it is neither. */
450
+ function fromBase64(value) {
451
+ if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(value))
452
+ return undefined;
453
+ try {
454
+ const binary = atob(value.replace(/=+$/, '').replace(/-/g, '+').replace(/_/g, '/'));
455
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
456
+ }
457
+ catch {
458
+ return undefined;
459
+ }
460
+ }
461
+ /** base64url, unpadded unless `padded` (RFC 9577 auth-params are padded). */
462
+ function toBase64(bytes, padded = false) {
463
+ let binary = '';
464
+ for (const byte of bytes)
465
+ binary += String.fromCharCode(byte);
466
+ const value = btoa(binary).replace(/\+/g, '-').replace(/\//g, '_');
467
+ return padded ? value : value.replace(/=+$/, '');
468
+ }
469
+ async function sha256(bytes) {
470
+ const input = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes;
471
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', input));
472
+ }
473
+ function equal(a, b) {
474
+ if (a.length !== b.length)
475
+ return false;
476
+ for (let i = 0; i < a.length; i++)
477
+ if (a[i] !== b[i])
478
+ return false;
479
+ return true;
480
+ }
481
+ /** Fetches a JSON object from Link's issuer origin, refusing redirects and other origins. */
482
+ async function getJson(url, options) {
483
+ if (new URL(url).origin !== options.origin)
484
+ throw new Error(`${url} is not on ${options.origin}.`);
485
+ const response = await options.fetch(url, {
486
+ headers: { accept: 'application/json' },
487
+ redirect: 'manual',
488
+ signal: AbortSignal.timeout(options.timeout),
489
+ });
490
+ if (!response.ok)
491
+ throw new Error(`${url} answered ${response.status}.`);
492
+ const body = (await response.json());
493
+ if (!body || typeof body !== 'object' || Array.isArray(body))
494
+ throw new Error(`${url} is not a JSON object.`);
495
+ return body;
496
+ }
497
+ /** Link's issuer metadata, cached for `maxAge` milliseconds. */
498
+ function metadata(options) {
499
+ const origin = new URL(options.issuer).origin;
500
+ let cache;
501
+ return (force = false) => {
502
+ if (!force && cache && Date.now() - cache.at < options.maxAge)
503
+ return cache.value;
504
+ const value = getJson(`${options.issuer}/.well-known/aap-issuer`, { ...options, origin }).then((body) => {
505
+ if (typeof body.issuer !== 'string' || body.issuer.replace(/\/+$/, '') !== options.issuer)
506
+ throw new Error('The issuer metadata names another issuer.');
507
+ return body;
508
+ });
509
+ cache = { at: Date.now(), value };
510
+ // A failed fetch is retried on the next call.
511
+ value.catch(() => {
512
+ if (cache?.value === value)
513
+ cache = undefined;
514
+ });
515
+ return value;
516
+ };
517
+ }
518
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,24 @@
1
+ /** Persona KYC values. */
2
+ export declare const Constants: {
3
+ /** Identity type advertised in the 402's `Identity-Required` header. */
4
+ readonly type: 'kyc';
5
+ /** Issuer advertised in the 402's `Identity-Required` header: Persona's API origin. */
6
+ readonly issuer: 'https://api.withpersona.com';
7
+ /** Persona API origin. */
8
+ readonly apiUrl: 'https://api.withpersona.com';
9
+ /** Persona API path for inquiries. */
10
+ readonly inquiriesPath: '/api/v1/inquiries';
11
+ /** Persona API version sent in `Persona-Version` by default. */
12
+ readonly apiVersion: '2023-01-05';
13
+ /** Inquiry statuses accepted by default: approved by your Persona workflow or reviewer. */
14
+ readonly statuses: readonly ['approved'];
15
+ /** Link relation of the onboarding URL sent with a rejection. */
16
+ readonly rel: 'kyc';
17
+ /** Milliseconds before a Persona API call is abandoned as `unavailable`. */
18
+ readonly timeout: 5000;
19
+ /** Seconds an approval stays cached when a `cache` is set. */
20
+ readonly cacheTtl: 300;
21
+ /** Most inquiry pages read per lookup. */
22
+ readonly maxPages: 3;
23
+ };
24
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,24 @@
1
+ /** Persona KYC values. */
2
+ export const Constants = {
3
+ /** Identity type advertised in the 402's `Identity-Required` header. */
4
+ type: 'kyc',
5
+ /** Issuer advertised in the 402's `Identity-Required` header: Persona's API origin. */
6
+ issuer: 'https://api.withpersona.com',
7
+ /** Persona API origin. */
8
+ apiUrl: 'https://api.withpersona.com',
9
+ /** Persona API path for inquiries. */
10
+ inquiriesPath: '/api/v1/inquiries',
11
+ /** Persona API version sent in `Persona-Version` by default. */
12
+ apiVersion: '2023-01-05',
13
+ /** Inquiry statuses accepted by default: approved by your Persona workflow or reviewer. */
14
+ statuses: ['approved'],
15
+ /** Link relation of the onboarding URL sent with a rejection. */
16
+ rel: 'kyc',
17
+ /** Milliseconds before a Persona API call is abandoned as `unavailable`. */
18
+ timeout: 5_000,
19
+ /** Seconds an approval stays cached when a `cache` is set. */
20
+ cacheTtl: 300,
21
+ /** Most inquiry pages read per lookup. */
22
+ maxPages: 3,
23
+ };
24
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Returns the reference ID for a wallet: its `did:pkh` DID, the form a Credential's `source`
3
+ * takes. EVM (`eip155`) addresses are lowercased, since they are case-insensitive; addresses on
4
+ * other chains, such as base58 Solana addresses, are kept as they are.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * Persona.did({ address: '0xAb…', chainId: 4217 }) // 'did:pkh:eip155:4217:0xab…'
9
+ * ```
10
+ */
11
+ export declare function did(parameters: did.Parameters): string;
12
+ export declare namespace did {
13
+ type Parameters = {
14
+ /** Wallet address. */
15
+ readonly address: string;
16
+ /** Chain reference, such as `4217` for Tempo mainnet. */
17
+ readonly chainId: number | string;
18
+ /** CAIP-2 namespace. @default 'eip155' */
19
+ readonly namespace?: string | undefined;
20
+ };
21
+ }
22
+ /** Normalizes a `did:pkh` DID: lowercases the scheme and an EVM address, keeps the rest. */
23
+ export declare function normalize(value: string): string;
24
+ //# sourceMappingURL=Did.d.ts.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Returns the reference ID for a wallet: its `did:pkh` DID, the form a Credential's `source`
3
+ * takes. EVM (`eip155`) addresses are lowercased, since they are case-insensitive; addresses on
4
+ * other chains, such as base58 Solana addresses, are kept as they are.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * Persona.did({ address: '0xAb…', chainId: 4217 }) // 'did:pkh:eip155:4217:0xab…'
9
+ * ```
10
+ */
11
+ export function did(parameters) {
12
+ const { address, chainId, namespace = 'eip155' } = parameters;
13
+ return normalize(`did:pkh:${namespace}:${chainId}:${address}`);
14
+ }
15
+ /** Normalizes a `did:pkh` DID: lowercases the scheme and an EVM address, keeps the rest. */
16
+ export function normalize(value) {
17
+ const parts = value.split(':');
18
+ if (parts.length !== 5 || parts[0].toLowerCase() !== 'did' || parts[1].toLowerCase() !== 'pkh')
19
+ return value;
20
+ const namespace = parts[2].toLowerCase();
21
+ const address = namespace === 'eip155' ? parts[4].toLowerCase() : parts[4];
22
+ return ['did', 'pkh', namespace, parts[3], address].join(':');
23
+ }
24
+ //# sourceMappingURL=Did.js.map
@@ -0,0 +1,21 @@
1
+ /** Status of a Persona inquiry. */
2
+ export type InquiryStatus = 'created' | 'pending' | 'completed' | 'approved' | 'declined' | 'failed' | 'expired' | 'needs_review';
3
+ /** A payer with an accepted Persona inquiry. */
4
+ export type VerifiedInquiry = {
5
+ /** Persona inquiry ID, such as `inq_…`. */
6
+ readonly inquiryId: string;
7
+ /** Reference ID the inquiry was created with, which the check matched. */
8
+ readonly referenceId: string;
9
+ /** Inquiry status, such as `approved`. */
10
+ readonly status: InquiryStatus;
11
+ /** When the inquiry was decisioned, or completed if it was never decisioned. */
12
+ readonly verifiedAt?: Date | undefined;
13
+ };
14
+ /** A started Persona inquiry. */
15
+ export type StartedInquiry = {
16
+ /** Persona inquiry ID, such as `inq_…`. */
17
+ readonly inquiryId: string;
18
+ /** One-time link to Persona's hosted flow, for the person to complete KYC. */
19
+ readonly url: string;
20
+ };
21
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Persona KYC identity: start a Persona inquiry for a person's wallet, then require an approved
3
+ * inquiry on paid requests, looked up with your Persona API key by the inquiry's reference ID.
4
+ */
5
+ /** Server helpers that start Persona inquiries and require a Persona-verified payer. */
6
+ export * as Server from './server/index.js';
7
+ export * from './Constants.js';
8
+ export { did, normalize } from './Did.js';
9
+ export type * from './Types.js';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Persona KYC identity: start a Persona inquiry for a person's wallet, then require an approved
3
+ * inquiry on paid requests, looked up with your Persona API key by the inquiry's reference ID.
4
+ */
5
+ /** Server helpers that start Persona inquiries and require a Persona-verified payer. */
6
+ export * as Server from './server/index.js';
7
+ export * from './Constants.js';
8
+ export { did, normalize } from './Did.js';
9
+ //# sourceMappingURL=index.js.map