mppx 0.17.5 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/cli/cli.js +141 -139
  3. package/dist/cli/plugins/index.js +6 -6
  4. package/dist/cli/stripe.d.ts +6 -1
  5. package/dist/cli/stripe.js +89 -5
  6. package/dist/client/Mppx.js +13 -3
  7. package/dist/client/internal/Fetch.js +9 -5
  8. package/dist/extensions/identity/attestation/Constants.d.ts +23 -0
  9. package/dist/extensions/identity/attestation/Constants.js +23 -0
  10. package/dist/extensions/identity/attestation/Jwks.d.ts +30 -0
  11. package/dist/extensions/identity/attestation/Jwks.js +114 -0
  12. package/dist/extensions/identity/attestation/Token.d.ts +80 -0
  13. package/dist/extensions/identity/attestation/Token.js +143 -0
  14. package/dist/extensions/identity/attestation/Types.d.ts +48 -0
  15. package/dist/extensions/identity/attestation/Types.js +2 -0
  16. package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
  17. package/dist/extensions/identity/attestation/client/index.js +273 -0
  18. package/dist/extensions/identity/attestation/index.d.ts +20 -0
  19. package/dist/extensions/identity/attestation/index.js +18 -0
  20. package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
  21. package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
  22. package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
  23. package/dist/extensions/identity/attestation/server/index.js +119 -0
  24. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  25. package/dist/extensions/identity/email-otp/Constants.js +17 -0
  26. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  27. package/dist/extensions/identity/email-otp/Types.js +2 -0
  28. package/dist/extensions/identity/email-otp/client/index.d.ts +123 -0
  29. package/dist/extensions/identity/email-otp/client/index.js +131 -0
  30. package/dist/extensions/identity/email-otp/index.d.ts +12 -0
  31. package/dist/extensions/identity/email-otp/index.js +11 -0
  32. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  33. package/dist/extensions/identity/email-otp/server/index.js +59 -0
  34. package/dist/extensions/identity/index.d.ts +4 -0
  35. package/dist/extensions/identity/index.js +4 -0
  36. package/dist/extensions/identity/internal/Verification.js +9 -5
  37. package/dist/identity/Callback.d.ts +66 -0
  38. package/dist/identity/Callback.js +88 -0
  39. package/dist/identity/Client.d.ts +78 -5
  40. package/dist/identity/Client.js +165 -48
  41. package/dist/identity/Headers.d.ts +16 -0
  42. package/dist/identity/Headers.js +19 -0
  43. package/dist/identity/Server.d.ts +159 -37
  44. package/dist/identity/Server.js +307 -138
  45. package/dist/identity/Status.d.ts +14 -0
  46. package/dist/identity/Status.js +19 -0
  47. package/dist/identity/Types.d.ts +161 -65
  48. package/dist/identity/index.d.ts +3 -0
  49. package/dist/identity/index.js +3 -0
  50. package/dist/identity/internal/Requirements.d.ts +28 -0
  51. package/dist/identity/internal/Requirements.js +78 -0
  52. package/dist/integrations/x402/Evm.d.ts +1 -0
  53. package/dist/internal/env.d.ts +14 -0
  54. package/dist/internal/env.js +38 -0
  55. package/dist/internal/version.d.ts +2 -2
  56. package/dist/internal/version.js +1 -1
  57. package/dist/proxy/internal/Headers.d.ts +1 -1
  58. package/dist/proxy/internal/Headers.js +7 -1
  59. package/dist/server/Mppx.d.ts +14 -6
  60. package/dist/server/Mppx.js +252 -148
  61. package/dist/server/internal/challengeMeta.d.ts +0 -6
  62. package/dist/server/internal/challengeMeta.js +3 -17
  63. package/dist/tempo/server/Charge.d.ts +14 -9
  64. package/dist/tempo/server/Charge.js +5 -1
  65. package/dist/tempo/server/Methods.js +4 -1
  66. package/dist/tempo/server/Subscription.d.ts +8 -0
  67. package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
  68. package/dist/tempo/server/internal/fallback-store.js +12 -3
  69. package/dist/tempo/server/internal/html.gen.js +1 -1
  70. package/dist/tempo/session/server/Session.d.ts +5 -1
  71. package/package.json +9 -1
@@ -4,6 +4,7 @@ import * as Constants from '../Constants.js';
4
4
  import * as Credential from '../Credential.js';
5
5
  import * as Errors from '../Errors.js';
6
6
  import * as Expires from '../Expires.js';
7
+ import * as IdentityRequirements from '../identity/internal/Requirements.js';
7
8
  import * as IdentityServer from '../identity/Server.js';
8
9
  import * as AcceptPayment from '../internal/AcceptPayment.js';
9
10
  import * as Env from '../internal/env.js';
@@ -439,16 +440,18 @@ export function create(config) {
439
440
  function createMethodFn(parameters) {
440
441
  const { authorize, credentialHeader, defaults, events, method, preflight, realm, respond, secretKey, broadcast, stableBinding, transport, validate, verify, } = parameters;
441
442
  return (routeOptions) => {
442
- const { identity = [], ...options } = routeOptions;
443
- const requestVerifiers = identity.filter((verifier) => IdentityServer.stageOf(verifier) === 'request');
444
- const paymentVerifiers = identity.filter((verifier) => IdentityServer.stageOf(verifier) === 'payment');
443
+ const { identity, ...options } = routeOptions;
444
+ const identityRoute = IdentityServer.route(identity);
445
+ const paymentCheck = identityRoute.payment;
446
+ const identityRequirements = paymentCheck?.requires ?? [];
447
+ const hasIdentity = identityRoute.request.length > 0 || paymentCheck !== undefined;
445
448
  // Preflight hooks (e.g. session bootstrap) issue and settle their own challenges, which
446
- // payment-stage verifiers cannot see; reject the combination instead of skipping identity.
447
- if (paymentVerifiers.length > 0 && preflight)
449
+ // the payment check cannot see; reject the combination instead of skipping identity.
450
+ if (paymentCheck && preflight)
448
451
  throw new TypeError(`Payment-stage identity is not supported on ${method.name}/${method.intent} routes with a preflight hook.`);
449
- // The HTML checkout cannot answer identity challenges, and it pays before resubmitting, so
452
+ // The HTML checkout cannot answer identity requirements, and it pays before resubmitting, so
450
453
  // a browser would pay and then be rejected.
451
- if (paymentVerifiers.length > 0 && method.html)
454
+ if (paymentCheck && method.html)
452
455
  throw new TypeError(`Payment-stage identity is not supported on ${method.name}/${method.intent} routes with the HTML checkout.`);
453
456
  const { description, meta, scope, ...rest } = options;
454
457
  const staticMeta = Scope.merge({ meta, scope });
@@ -467,28 +470,54 @@ function createMethodFn(parameters) {
467
470
  ]),
468
471
  ],
469
472
  _canonicalRequest: PaymentRequest.fromMethod(method, { ...defaults, ...rest }),
470
- _paymentIdentity: paymentVerifiers.length > 0 ? paymentVerifiers : undefined,
471
- _identity: identity.length > 0,
473
+ _identity: hasIdentity,
474
+ _paymentCheck: paymentCheck,
472
475
  _stableBinding: stableBinding,
473
476
  _transport: transport,
474
477
  };
475
478
  Object.defineProperty(internal, '_method', { value: method });
476
- const handler = async (input) => {
477
- const identityValues = new Map();
478
- if (identity.length > 0) {
479
- if (!(input instanceof globalThis.Request))
480
- throw new TypeError('Route identity requires the HTTP transport.');
481
- const outcome = await IdentityServer.verify(input, requestVerifiers);
482
- if (outcome.status !== 'valid') {
483
- // Returned on the non-200 branch so callers never run paid work: like an early
484
- // rejection, `challenge` holds the identity response (401/403) to send as is.
485
- const rejection = IdentityServer.toResponse(outcome);
486
- identityRejections.add(rejection);
487
- return { challenge: rejection, status: 402 };
488
- }
489
- for (const [verifier, value] of outcome.values)
490
- identityValues.set(verifier, value);
491
- }
479
+ const handler = async (input, context) => {
480
+ // `compose` passes one identity context to every offer it calls, so each verifier runs
481
+ // at most once per request; a route called directly creates its own.
482
+ const identityContext = IdentityServer.contextOf(context);
483
+ if (hasIdentity && !(input instanceof globalThis.Request))
484
+ throw new TypeError('Route identity requires the HTTP transport.');
485
+ let identityState = IdentityServer.transition(IdentityServer.initial, {
486
+ type: 'verified',
487
+ outcome: identityRoute.request.length > 0
488
+ ? await IdentityServer.verify(identityContext, input, identityRoute.request)
489
+ : IdentityServer.none,
490
+ });
491
+ if (identityState.phase === 'rejected')
492
+ return identityRejection(identityState);
493
+ // Runs the payment check (if any) for a Challenge: on the paid retry with its Credential,
494
+ // or without one before `authorize`.
495
+ const checkIdentity = async (challenge, credential, options = {}) => {
496
+ identityState = IdentityServer.transition(identityState, {
497
+ type: 'pay',
498
+ challenge,
499
+ credential,
500
+ });
501
+ identityState = IdentityServer.transition(identityState, {
502
+ type: 'checked',
503
+ outcome: !paymentCheck
504
+ ? IdentityServer.none
505
+ : options.challengeFromTransport
506
+ ? // Fails closed before settlement: the client proved nothing bound to this Challenge.
507
+ IdentityServer.decide([
508
+ {
509
+ status: 'invalid',
510
+ reason: "This route's identity payment check does not accept x402 credentials.",
511
+ },
512
+ ])
513
+ : await IdentityServer.check(identityContext, paymentCheck, {
514
+ challenge,
515
+ credential,
516
+ request: input,
517
+ }),
518
+ });
519
+ return identityState;
520
+ };
492
521
  if (method.html && isServiceWorkerRequest(input))
493
522
  return {
494
523
  status: 402,
@@ -501,12 +530,7 @@ function createMethodFn(parameters) {
501
530
  const effectiveMeta = scope === undefined && input instanceof globalThis.Request
502
531
  ? Scope.merge({ meta: staticMeta, scope: Scope.get(input) })
503
532
  : staticMeta;
504
- // Every offer of one 402 shares the identity nonce (composed routes pass each offer the
505
- // same request), so a payment-stage proof is bound to the 402, whichever offer is paid.
506
- const identityNonce = paymentVerifiers.length > 0 && input instanceof globalThis.Request
507
- ? IdentityServer.nonceFor(input, ChallengeMeta.createNonce)
508
- : undefined;
509
- const challengeMeta = ChallengeMeta.withIdentity(effectiveMeta, identityNonce);
533
+ const challengeMeta = effectiveMeta;
510
534
  // Extract credential once — getCredential may have side effects (e.g. SSE transports).
511
535
  let [credential, credentialError] = (() => {
512
536
  try {
@@ -532,7 +556,7 @@ function createMethodFn(parameters) {
532
556
  return { challenge: response, status: 402 };
533
557
  return {
534
558
  status: 200,
535
- identity: IdentityServer.results(identityValues),
559
+ identity: IdentityServer.results(identityState),
536
560
  withReceipt() {
537
561
  return response;
538
562
  },
@@ -546,25 +570,21 @@ function createMethodFn(parameters) {
546
570
  ...(parameters.error && { error: parameters.error }),
547
571
  ...(parameters.html && { html: parameters.html }),
548
572
  });
549
- // Payment-stage verifiers add their own challenge headers to the 402.
550
- if (identityNonce !== undefined &&
551
- input instanceof globalThis.Request &&
552
- response instanceof globalThis.Response) {
553
- const identityHeaders = await IdentityServer.challenge(input, paymentVerifiers, identityNonce);
554
- if ([...identityHeaders].length > 0) {
555
- const paymentChallenge = response.headers.get(paymentAuthChallengeHeader);
556
- const headers = new Headers(response.headers);
557
- for (const [name, value] of identityHeaders)
558
- headers.append(name, value);
559
- response = new globalThis.Response(response.body, {
560
- headers,
561
- status: response.status,
562
- statusText: response.statusText,
563
- });
564
- identityChallenges.set(response, identityHeaders);
565
- paymentChallenges.set(response, paymentChallenge);
566
- }
567
- }
573
+ // A route with a payment check rejects x402 Credentials, so it does not offer x402.
574
+ if (paymentCheck &&
575
+ response instanceof globalThis.Response &&
576
+ response.headers.has(x402_Types.paymentRequiredHeader))
577
+ response = withoutX402Offer(response);
578
+ // Every 402 of a route with a payment check lists the identities it requires.
579
+ const challenged = IdentityServer.transition(identityState, {
580
+ type: 'challenge',
581
+ requirements: identityRequirements,
582
+ });
583
+ identityState = challenged;
584
+ if (challenged.phase === 'challenged' &&
585
+ challenged.requirements.length > 0 &&
586
+ response instanceof globalThis.Response)
587
+ response = withIdentityRequirements(response, challenged.requirements);
568
588
  if (isIssuedChallengeResponse(response))
569
589
  await events.emit('challenge.created', createChallengeContext({
570
590
  capturedRequest,
@@ -640,13 +660,18 @@ function createMethodFn(parameters) {
640
660
  return { challenge: routeChallenge.response, status: 402 };
641
661
  const { challenge, parsedRequest, request } = routeChallenge;
642
662
  internal._canonicalRequest = parsedRequest;
663
+ // A transport that builds the Credential's Challenge itself (x402, whose Credentials name
664
+ // no Challenge) leaves nothing the client proved a payment check against.
665
+ let challengeFromTransport = false;
643
666
  if (credential && transport.bindCredential) {
667
+ const submitted = credential.challenge;
644
668
  try {
645
669
  credential = hydrateCredentialMeta((await transport.bindCredential({
646
670
  challenge,
647
671
  credential,
648
672
  input,
649
673
  })));
674
+ challengeFromTransport = credential.challenge.id !== submitted.id;
650
675
  }
651
676
  catch (e) {
652
677
  credential = null;
@@ -682,7 +707,7 @@ function createMethodFn(parameters) {
682
707
  const result = {
683
708
  status: 200,
684
709
  challenge,
685
- identity: IdentityServer.results(identityValues),
710
+ identity: IdentityServer.results(identityState),
686
711
  withReceipt(response) {
687
712
  if (managementResponse) {
688
713
  return transport.respondReceipt({
@@ -712,17 +737,12 @@ function createMethodFn(parameters) {
712
737
  };
713
738
  // No credential provided—issue challenge
714
739
  if (!credential) {
715
- // Authorization without a payment credential still requires payment-stage identity;
716
- // a verifier that needs the credential reports missing, so the route issues its 402.
717
- const authorizeIdentity = authorize && input instanceof globalThis.Request && paymentVerifiers.length > 0
718
- ? await IdentityServer.verify(input, paymentVerifiers, { challenge })
719
- : undefined;
740
+ // Authorization without a payment credential still requires the payment check: it runs
741
+ // without a Credential, and only a valid result lets authorize run; otherwise the route
742
+ // issues its 402.
720
743
  if (authorize &&
721
744
  input instanceof globalThis.Request &&
722
- (!authorizeIdentity || authorizeIdentity.status === 'valid')) {
723
- if (authorizeIdentity?.status === 'valid')
724
- for (const [verifier, value] of authorizeIdentity.values)
725
- identityValues.set(verifier, value);
745
+ (await checkIdentity(challenge, undefined)).phase === 'accepted') {
726
746
  try {
727
747
  const authorized = await authorize({
728
748
  challenge,
@@ -895,33 +915,23 @@ function createMethodFn(parameters) {
895
915
  credential: parsedCredential,
896
916
  request: parsedRequest,
897
917
  });
898
- // Payment-stage identity is checked against the answered challenge before settlement.
899
- if (paymentVerifiers.length > 0) {
900
- const outcome = await IdentityServer.verify(input, paymentVerifiers, {
901
- challenge: credential.challenge,
918
+ // The payment check runs once against the answered Challenge, before settlement.
919
+ const checked = await checkIdentity(credential.challenge, parsedCredential, {
920
+ challengeFromTransport,
921
+ });
922
+ if (checked.phase === 'rejected') {
923
+ const error = new Errors.VerificationFailedError({ reason: checked.rejection.reason });
924
+ await emitPaymentFailed({
925
+ challenge,
902
926
  credential: parsedCredential,
903
- nonce: ChallengeMeta.identity(credential.challenge.meta),
927
+ error,
928
+ request: parsedRequest,
929
+ retryChallenge: challenge,
930
+ submittedChallenge: credential.challenge,
904
931
  });
905
- if (outcome.status !== 'valid') {
906
- const error = new Errors.VerificationFailedError({ reason: outcome.reason });
907
- await emitPaymentFailed({
908
- challenge,
909
- credential: parsedCredential,
910
- error,
911
- request: parsedRequest,
912
- retryChallenge: challenge,
913
- submittedChallenge: credential.challenge,
914
- });
915
- // The client may already have pushed this payment, so a fresh 402 would invite
916
- // it to pay again. Reject without a challenge, like a replayed credential.
917
- // Returned on the non-200 branch so callers never run paid work: like an early
918
- // rejection, `challenge` holds the identity response (401/403) to send as is.
919
- const rejection = IdentityServer.toResponse(outcome);
920
- identityRejections.add(rejection);
921
- return { challenge: rejection, status: 402 };
922
- }
923
- for (const [verifier, value] of outcome.values)
924
- identityValues.set(verifier, value);
932
+ // The client may already have pushed this payment, so a fresh 402 would invite it to
933
+ // pay again. Reject without a Challenge, like a replayed Credential.
934
+ return identityRejection(checked);
925
935
  }
926
936
  // User-provided verification (e.g., check signature, submit tx, verify payment).
927
937
  // If verification fails, re-issue the challenge so the client can retry.
@@ -1589,34 +1599,77 @@ function withParsedCredentialPayload(credential, payload) {
1589
1599
  };
1590
1600
  }
1591
1601
  const paymentAuthChallengeHeader = Constants.Headers.wwwAuthenticate;
1592
- /** Payment-stage identity headers added to issued 402 responses, keyed by response. @internal */
1593
- const identityChallenges = new WeakMap();
1594
- /** Identity rejections (401/403) returned on a route's non-success branch. @internal */
1595
- const identityRejections = new WeakSet();
1602
+ /** Builds the result of an identity rejection: the rejection response on the non-200 branch. */
1603
+ function identityRejection(state) {
1604
+ return {
1605
+ challenge: IdentityServer.toResponse(state),
1606
+ rejection: state.rejection,
1607
+ status: 402,
1608
+ };
1609
+ }
1610
+ /** Returns a 402 with an `Identity-Required` header listing `requirements`. */
1611
+ function withIdentityRequirements(response, requirements) {
1612
+ return withHeaders(response, (headers) => headers.set(IdentityRequirements.header, IdentityRequirements.serialize(requirements)));
1613
+ }
1614
+ /** Rebuilds a 402 with edited headers, keeping the x402 requirements it withholds. */
1615
+ function withHeaders(response, edit) {
1616
+ const headers = new Headers(response.headers);
1617
+ edit(headers);
1618
+ const result = new Response(response.body, {
1619
+ headers,
1620
+ status: response.status,
1621
+ statusText: response.statusText,
1622
+ });
1623
+ const withheld = withheldX402.get(response);
1624
+ if (withheld)
1625
+ withheldX402.set(result, withheld);
1626
+ return result;
1627
+ }
1596
1628
  /**
1597
- * A 402's Payment `WWW-Authenticate` value without its identity challenge, keyed by response.
1598
- * Composers merge these and append the shared identity challenge once. @internal
1629
+ * The x402 requirements a 402 withholds because its route has a payment check. A composer drops
1630
+ * the same requirements from every other offer's PAYMENT-REQUIRED: a Credential for them is
1631
+ * dispatched to the checked offer first, which rejects x402, so advertising them elsewhere would
1632
+ * offer a payment that always fails.
1599
1633
  */
1600
- const paymentChallenges = new WeakMap();
1601
- /** Records a merged 402's identity challenge so an outer composer can forward it. @internal */
1602
- function withIdentityChallenge(response, headers, paymentChallenge) {
1603
- if (headers) {
1604
- identityChallenges.set(response, headers);
1605
- paymentChallenges.set(response, paymentChallenge);
1606
- }
1634
+ const withheldX402 = new WeakMap();
1635
+ /** Removes a 402's x402 offer, recording the requirements it withholds. */
1636
+ function withoutX402Offer(response) {
1637
+ const value = response.headers.get(x402_Types.paymentRequiredHeader);
1638
+ const result = withHeaders(response, (headers) => headers.delete(x402_Types.paymentRequiredHeader));
1639
+ const accepts = (() => {
1640
+ try {
1641
+ return value ? x402_Header.decodePaymentRequiredEnvelope(value).accepts : [];
1642
+ }
1643
+ catch {
1644
+ return [];
1645
+ }
1646
+ })();
1647
+ withheldX402.set(result, [...(withheldX402.get(response) ?? []), ...accepts]);
1648
+ return result;
1649
+ }
1650
+ /** Records the requirements a composed 402 withholds, so an outer composer withholds them too. */
1651
+ function withWithheldX402(response, withheld) {
1652
+ if (withheld.length > 0)
1653
+ withheldX402.set(response, withheld);
1607
1654
  return response;
1608
1655
  }
1656
+ /** Removes withheld requirements from an x402 PAYMENT-REQUIRED value; undefined when none remain. */
1657
+ function withoutWithheldX402(value, withheld) {
1658
+ if (withheld.length === 0)
1659
+ return value;
1660
+ const paymentRequired = x402_Header.decodePaymentRequired(value);
1661
+ const accepts = paymentRequired.accepts.filter((accept) => !withheld.some((requirement) => isDeepStrictEqual(accept, requirement)));
1662
+ if (accepts.length === paymentRequired.accepts.length)
1663
+ return value;
1664
+ if (accepts.length === 0)
1665
+ return undefined;
1666
+ return x402_Header.encodePaymentRequired({ ...paymentRequired, accepts });
1667
+ }
1609
1668
  const challengeHeaderMerges = [
1610
1669
  {
1611
1670
  name: paymentAuthChallengeHeader,
1612
1671
  values: (context) => context.challengeEntries
1613
- .map((entry) => {
1614
- const response = entry.result.challenge;
1615
- // Identity challenges are appended once by the composer, not once per offer.
1616
- return paymentChallenges.has(response)
1617
- ? paymentChallenges.get(response)
1618
- : response.headers.get(paymentAuthChallengeHeader);
1619
- })
1672
+ .map((entry) => entry.result.challenge.headers.get(paymentAuthChallengeHeader))
1620
1673
  .filter((value) => value !== null),
1621
1674
  merge: (values) => values,
1622
1675
  },
@@ -1624,7 +1677,9 @@ const challengeHeaderMerges = [
1624
1677
  name: x402_Types.paymentRequiredHeader,
1625
1678
  values: (context) => context.negotiatedChallengeResponses
1626
1679
  .map((response) => response.headers.get(x402_Types.paymentRequiredHeader))
1627
- .filter((value) => value !== null),
1680
+ .filter((value) => value !== null)
1681
+ .map((value) => withoutWithheldX402(value, context.withheldX402))
1682
+ .filter((value) => value !== undefined),
1628
1683
  merge: mergeX402PaymentRequiredHeaders,
1629
1684
  },
1630
1685
  ];
@@ -1657,13 +1712,19 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1657
1712
  });
1658
1713
  if (handlers.length === 0)
1659
1714
  throw new Error('compose() requires at least one handler');
1660
- // A 402 carries one identity challenge, shared by its offers through the identity nonce, so
1661
- // every offer that requires payment-stage identity must require the same verifiers.
1662
- const identityOffers = handlers
1663
- .flatMap(getConfiguredOffers)
1664
- .flatMap((offer) => (offer._paymentIdentity ? [offer._paymentIdentity] : []));
1665
- if (identityOffers.some((verifiers) => !sameVerifiers(verifiers, identityOffers[0])))
1666
- throw new TypeError('Offers in a composed route must require the same payment-stage identity verifiers.');
1715
+ // A Credential names no offer, so dispatch may send it to any offer with the same terms: every
1716
+ // offer with a payment check must use the same one, or a stricter check could be skipped.
1717
+ const paymentChecks = new Set(handlers
1718
+ .flatMap((handler) => getConfiguredOffers(handler))
1719
+ .flatMap((offer) => offer._paymentCheck ?? []));
1720
+ if (paymentChecks.size > 1)
1721
+ throw new TypeError('Offers in a composed route must use the same identity payment check.');
1722
+ // A Credential names no offer, so one for terms shared by a checked and an unchecked offer could
1723
+ // reach either: the checked offer would ask for identities a 402 may never have listed (an
1724
+ // offer-selection policy, a request-stage rejection), or the unchecked one would skip the check.
1725
+ // Such a pair is ambiguous, so it is refused.
1726
+ if (hasCheckedTwin(handlers.flatMap((handler) => getConfiguredOffers(handler))))
1727
+ throw new TypeError('A composed route cannot pair offers with the same payment terms where only one has an identity payment check.');
1667
1728
  const offerSelector = selectOffers;
1668
1729
  const offerEntries = handlers.map((handler) => {
1669
1730
  const internal = handler._internal;
@@ -1672,7 +1733,11 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1672
1733
  return { handler, method, offer };
1673
1734
  });
1674
1735
  const hasOfferPolicy = offerSelector !== undefined || offerEntries.some(({ method }) => method?.canOffer !== undefined);
1675
- const composed = async (input) => {
1736
+ const composed = async (input, context) => {
1737
+ // One identity context for every offer called with this request, so each verifier runs at
1738
+ // most once. Offers are called through `call`, which passes it on.
1739
+ const identityContext = IdentityServer.contextOf(context);
1740
+ const call = (handler) => handler(input, identityContext);
1676
1741
  // Serve service worker for html-enabled compose
1677
1742
  if (new URL(input.url).searchParams.has(Html.params.serviceWorker)) {
1678
1743
  const hasHtml = handlers.some((h) => h._internal?.html);
@@ -1712,7 +1777,7 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1712
1777
  // Uses the schema-parsed canonical form (not raw options) so that
1713
1778
  // transformed fields (e.g. amount with decimals) match correctly.
1714
1779
  // Also checks inside methodDetails for fields moved there by transforms.
1715
- const candidates = handlers.filter((handler) => getConfiguredOffers(handler).some((internal) => {
1780
+ const matches = (internal) => {
1716
1781
  try {
1717
1782
  if (internal.name !== credMethod || internal.intent !== credIntent)
1718
1783
  return false;
@@ -1728,11 +1793,16 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1728
1793
  catch {
1729
1794
  return false;
1730
1795
  }
1731
- }));
1732
- const match = candidates[0] ??
1796
+ };
1797
+ const candidates = handlers.filter((handler) => getConfiguredOffers(handler).some(matches));
1798
+ // Offers with the same terms are indistinguishable, so a handler whose matching offer has
1799
+ // a payment check (all share the same one) is preferred and an unchecked twin cannot skip
1800
+ // it, including one inside a nested composer.
1801
+ const match = candidates.find((handler) => getConfiguredOffers(handler).some((internal) => matches(internal) && internal._paymentCheck !== undefined)) ??
1802
+ candidates[0] ??
1733
1803
  handlers.find((handler) => getConfiguredOffers(handler).some((internal) => internal.name === credMethod && internal.intent === credIntent));
1734
1804
  if (match)
1735
- return match(input);
1805
+ return call(match);
1736
1806
  }
1737
1807
  // Unrecognized or malformed credentials still use the currently eligible
1738
1808
  // offer set before the first handler issues its rejection challenge.
@@ -1745,22 +1815,40 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1745
1815
  })
1746
1816
  : handlers;
1747
1817
  const transportResults = new Map();
1818
+ // A transport Credential (x402) names no offer, so a handler whose matching offer has a payment
1819
+ // check tries it first, judged per offer so a nested composer counts by the offer that
1820
+ // matched, and its identity rejection is final: an unchecked offer with the same terms
1821
+ // cannot settle it instead.
1822
+ const transportMatches = [];
1748
1823
  for (const handler of selectedHandlers) {
1824
+ let matched = false;
1825
+ let checked = false;
1749
1826
  for (const internal of getConfiguredOffers(handler)) {
1750
1827
  const matchCredential = internal._transport.matchCredential;
1751
1828
  if (!matchCredential)
1752
1829
  continue;
1753
1830
  try {
1754
- if (await matchCredential({ input, request: internal._canonicalRequest })) {
1755
- const result = await handler(input);
1756
- transportResults.set(handler, result);
1757
- if (result.status === 200)
1758
- return result;
1759
- break;
1760
- }
1831
+ if (!(await matchCredential({ input, request: internal._canonicalRequest })))
1832
+ continue;
1833
+ }
1834
+ catch {
1835
+ continue;
1761
1836
  }
1762
- catch { }
1837
+ matched = true;
1838
+ if (internal._paymentCheck !== undefined)
1839
+ checked = true;
1763
1840
  }
1841
+ if (matched)
1842
+ transportMatches.push({ handler, checked });
1843
+ }
1844
+ for (const { handler } of [
1845
+ ...transportMatches.filter(({ checked }) => checked),
1846
+ ...transportMatches.filter(({ checked }) => !checked),
1847
+ ]) {
1848
+ const result = await call(handler);
1849
+ transportResults.set(handler, result);
1850
+ if (result.status === 200 || result.rejection)
1851
+ return result;
1764
1852
  }
1765
1853
  const transportCredentialHandler = selectedHandlers.find((handler) => getConfiguredOffers(handler).some((internal) => internal.credentialHeaders?.some((header) => {
1766
1854
  const value = input.headers.get(header);
@@ -1769,22 +1857,21 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1769
1857
  Credential.extractPaymentScheme(value) === null);
1770
1858
  })));
1771
1859
  if (transportCredentialHandler)
1772
- return transportCredentialHandler(input);
1860
+ return call(transportCredentialHandler);
1773
1861
  // No credential — evaluate handlers sequentially so authorize()/renewal hooks
1774
1862
  // can safely claim the request without racing each other.
1775
1863
  // An identity rejection from one offer does not hide the others: it is returned only
1776
1864
  // when no offer issued a payment challenge.
1777
1865
  const results = [];
1778
1866
  for (const handler of selectedHandlers) {
1779
- const result = transportResults.get(handler) ?? (await handler(input));
1867
+ const result = transportResults.get(handler) ?? (await call(handler));
1780
1868
  if (result.status === 200)
1781
1869
  return result;
1782
- const rejected = identityRejections.has(result.challenge);
1783
- if (result.challenge.status !== 402 && !rejected)
1870
+ if (result.challenge.status !== 402 && !result.rejection)
1784
1871
  return result;
1785
1872
  results.push(result);
1786
1873
  }
1787
- const offers = results.filter((result) => result.status === 402 && !identityRejections.has(result.challenge));
1874
+ const offers = results.filter((result) => result.status === 402 && !result.rejection);
1788
1875
  if (offers.length === 0 && results[0])
1789
1876
  return results[0];
1790
1877
  const challengeEntries = (() => {
@@ -1794,7 +1881,7 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1794
1881
  if (result?.status !== 402)
1795
1882
  continue;
1796
1883
  // Identity rejections may carry non-Payment challenges (e.g. Bearer); they are not offers.
1797
- if (identityRejections.has(result.challenge))
1884
+ if (result.rejection)
1798
1885
  continue;
1799
1886
  const response = result.challenge;
1800
1887
  const wwwAuth = response.headers.get(paymentAuthChallengeHeader);
@@ -1831,11 +1918,14 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1831
1918
  ...unnegotiatedX402Responses,
1832
1919
  ]
1833
1920
  : challengeResponses;
1834
- // Offers share one identity challenge (enforced when composing); forward it only if an
1835
- // offer that carries it is still advertised after negotiation.
1836
- const identityHeaders = negotiatedChallengeResponses
1837
- .map((response) => identityChallenges.get(response))
1838
- .find((headers) => headers !== undefined);
1921
+ // The identities required by the negotiated responses, merged into one Identity-Required
1922
+ // header. Read from each response, so a nested composer's own negotiation is respected.
1923
+ const identityRequirements = IdentityRequirements.merge(negotiatedChallengeResponses.map((response) => IdentityRequirements.parse(response.headers.get(IdentityRequirements.header))));
1924
+ // x402 requirements withheld by any offer with a payment check, including a nested
1925
+ // composer's, are not advertised by another offer either.
1926
+ const withheld = results.flatMap((result) => result.status === 402 && result.challenge instanceof globalThis.Response
1927
+ ? (withheldX402.get(result.challenge) ?? [])
1928
+ : []);
1839
1929
  // Merge challenge headers from the negotiated 402 responses.
1840
1930
  const mergedHeaders = new Headers();
1841
1931
  mergedHeaders.set('Cache-Control', 'no-store');
@@ -1844,15 +1934,13 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1844
1934
  challengeEntries,
1845
1935
  challengeResponses,
1846
1936
  negotiatedChallengeResponses,
1937
+ withheldX402: withheld,
1847
1938
  }))) {
1848
1939
  mergedHeaders.append(header.name, value);
1849
1940
  }
1850
1941
  }
1851
- // The merged offer values above exclude identity challenges; append the shared one once.
1852
- const paymentChallenge = mergedHeaders.get(paymentAuthChallengeHeader);
1853
- if (identityHeaders)
1854
- for (const [name, value] of identityHeaders)
1855
- mergedHeaders.append(name, value);
1942
+ if (identityRequirements.length > 0)
1943
+ mergedHeaders.set(IdentityRequirements.header, IdentityRequirements.serialize(identityRequirements));
1856
1944
  // Collect html-enabled handlers and their challenges
1857
1945
  const htmlEntries = challengeEntries.filter((entry) => entry.handler._internal?.html);
1858
1946
  const wantsHtml = input.headers.get('Accept')?.includes('text/html');
@@ -1890,7 +1978,7 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1890
1978
  });
1891
1979
  return {
1892
1980
  status: 402,
1893
- challenge: withIdentityChallenge(new Response(body, { status: 402, headers: mergedHeaders }), identityHeaders, paymentChallenge),
1981
+ challenge: withWithheldX402(new Response(body, { status: 402, headers: mergedHeaders }), withheld),
1894
1982
  };
1895
1983
  }
1896
1984
  // Non-HTML fallback: prefer the first Payment-auth body, otherwise use
@@ -1910,7 +1998,7 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1910
1998
  }
1911
1999
  return {
1912
2000
  status: 402,
1913
- challenge: withIdentityChallenge(new Response(body, { status: 402, headers: mergedHeaders }), identityHeaders, paymentChallenge),
2001
+ challenge: withWithheldX402(new Response(body, { status: 402, headers: mergedHeaders }), withheld),
1914
2002
  };
1915
2003
  };
1916
2004
  const offers = handlers.flatMap(getConfiguredOffers);
@@ -1918,9 +2006,25 @@ function composeHandlers(handlers, composeOptions, selectOffers) {
1918
2006
  composed._internal = { offers, handlers: handlers, selectOffers };
1919
2007
  return composed;
1920
2008
  }
1921
- /** Whether two verifier lists hold the same verifiers in the same order. */
1922
- function sameVerifiers(a, b) {
1923
- return a.length === b.length && a.every((verifier, i) => verifier === b[i]);
2009
+ /**
2010
+ * Whether an offer with a payment check has a twin without one: the same method, intent and
2011
+ * payment terms. Scope and meta are not compared: an x402 Credential carries neither.
2012
+ */
2013
+ function hasCheckedTwin(offers) {
2014
+ const checked = offers.filter((offer) => offer._paymentCheck !== undefined);
2015
+ 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)));
2017
+ }
2018
+ /** Whether a Credential for offer `b`'s terms passes offer `a`'s dispatch binding. */
2019
+ function sameTerms(a, b) {
2020
+ try {
2021
+ return !(a._stableBinding
2022
+ ? getConfiguredStableBindingMismatch(getStableBinding(a._canonicalRequest, a._stableBinding), getStableBinding(b._canonicalRequest, a._stableBinding))
2023
+ : getConfiguredRequestBindingMismatch(a._canonicalRequest, b._canonicalRequest));
2024
+ }
2025
+ catch {
2026
+ return false;
2027
+ }
1924
2028
  }
1925
2029
  /** Returns the flattened configured offers accepted by a handler. */
1926
2030
  function getConfiguredOffers(handler) {
@@ -1,11 +1,5 @@
1
1
  /** Adds fresh issuance randomness while preserving application and route metadata. */
2
2
  export declare function withNonce(meta: Record<string, string> | undefined): Record<string, string>;
3
- /** Returns fresh randomness for an identity nonce. */
4
- export declare function createNonce(): string;
5
- /** Adds an identity nonce to challenge metadata. */
6
- export declare function withIdentity(meta: Record<string, string> | undefined, nonce: string | undefined): Record<string, string> | undefined;
7
- /** Reads the identity nonce from challenge metadata. */
8
- export declare function identity(meta: Record<string, string> | undefined): string | undefined;
9
3
  /** Removes issuance-only metadata when comparing stable route requirements. */
10
4
  export declare function routeMeta(meta: Record<string, string> | undefined): Record<string, string> | undefined;
11
5
  //# sourceMappingURL=challengeMeta.d.ts.map