mppx 0.21.4 → 0.22.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 (59) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/BodyDigest.d.ts +3 -3
  3. package/dist/BodyDigest.js +5 -3
  4. package/dist/Challenge.js +12 -2
  5. package/dist/Credential.js +9 -1
  6. package/dist/Errors.d.ts +62 -8
  7. package/dist/Errors.js +57 -6
  8. package/dist/Store.d.ts +7 -4
  9. package/dist/Store.js +18 -8
  10. package/dist/cli/cli.js +135 -135
  11. package/dist/cli/internal.js +1 -1
  12. package/dist/cli/plugins/index.js +12 -12
  13. package/dist/client/Budget.d.ts +49 -0
  14. package/dist/client/Budget.js +101 -0
  15. package/dist/client/Mppx.d.ts +8 -3
  16. package/dist/client/Mppx.js +55 -13
  17. package/dist/client/Spend.d.ts +134 -0
  18. package/dist/client/Spend.js +58 -0
  19. package/dist/client/core.d.ts +2 -0
  20. package/dist/client/core.js +2 -0
  21. package/dist/client/internal/Fetch.d.ts +23 -3
  22. package/dist/client/internal/Fetch.js +155 -37
  23. package/dist/client/internal/FundsMoved.d.ts +9 -0
  24. package/dist/client/internal/FundsMoved.js +18 -0
  25. package/dist/client/internal/SpendGate.d.ts +136 -0
  26. package/dist/client/internal/SpendGate.js +608 -0
  27. package/dist/client/internal/SpendHooks.d.ts +42 -0
  28. package/dist/client/internal/SpendHooks.js +36 -0
  29. package/dist/client/internal/protocols/Mcp.d.ts +9 -0
  30. package/dist/client/internal/protocols/Mcp.js +27 -0
  31. package/dist/client/internal/protocols/Mpp.js +20 -3
  32. package/dist/client/internal/protocols/Shared.js +29 -3
  33. package/dist/evm/client/Charge.js +20 -8
  34. package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
  35. package/dist/extensions/identity/erc8004/server/index.js +13 -1
  36. package/dist/extensions/identity/link/client/index.js +57 -5
  37. package/dist/identity/Client.d.ts +7 -3
  38. package/dist/identity/Client.js +178 -13
  39. package/dist/identity/Types.d.ts +2 -1
  40. package/dist/integrations/x402/Negotiator.js +4 -1
  41. package/dist/integrations/x402/Solana.d.ts +75 -0
  42. package/dist/integrations/x402/Solana.js +143 -0
  43. package/dist/internal/challengeMeta.d.ts +17 -2
  44. package/dist/internal/challengeMeta.js +35 -7
  45. package/dist/internal/version.d.ts +2 -2
  46. package/dist/internal/version.js +1 -1
  47. package/dist/mcp/client/McpClient.d.ts +6 -1
  48. package/dist/mcp/client/McpClient.js +48 -10
  49. package/dist/server/Mppx.d.ts +12 -1
  50. package/dist/server/Mppx.js +58 -6
  51. package/dist/server/Transport.js +46 -2
  52. package/dist/stripe/server/internal/html.gen.js +1 -1
  53. package/dist/tempo/client/Charge.js +81 -17
  54. package/dist/tempo/server/Charge.d.ts +7 -1
  55. package/dist/tempo/server/Charge.js +98 -12
  56. package/dist/tempo/server/internal/html.gen.js +1 -1
  57. package/dist/tempo/session/client/SessionManager.js +3 -0
  58. package/dist/x402/server/EvmCharge.js +3 -0
  59. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # mppx
2
2
 
3
+ ## 0.22.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0f6955d: Required custom replay stores to support atomic owner-aware cleanup before Tempo charge uses them. Protected owned replay claims against expiry-only replacements during shard rollback; shard upgrades require draining in-flight owned attempts.
8
+ - 66dc9ff: The x402 middlewares now offer a native `solana/charge` MPP challenge beside a Solana `exact` requirement, as they already do for EVM `exact`. The client's partially signed transfer is verified and settled through the route's x402 facilitator, with the facilitator as fee payer, so one route takes x402 and MPP payments on Solana. Clients pay it with `@solana/mpp`'s `solana.charge`.
9
+
10
+ ### Patch Changes
11
+
12
+ - 8a31e2d: Fixed `Challenge.deserialize` to reject auth-params that are not separated by commas, text after a quoted value, and unquoted values that are not tokens.
13
+ - 54fc48d: Changed Tempo charge to reject push (hash, Zone) and proof credentials for a challenge issued without a per-issuance nonce (challengeNonce: false); only pull (transaction) credentials are accepted then. Kept a settled payment when deleting its broadcast record fails, and answered a body digest mismatch with the problem instead of the payment page.
14
+ - 54fc48d: Fixed Tempo charge so a retry that overlaps an unknown broadcast outcome recovers the server's own transaction: the broadcast record is written before the replay claims are released, and ownership is checked again once the receipt arrives.
15
+ - 4c32b2d: Added `maxPayment`, `authorize` (with `Budget.create`), `funders` and `tokens` options to the client and to `McpClient.wrap`, checked before any credential is created. They accept only `charge` challenges: while one is set, the client refuses sessions and subscriptions with `PaymentLimitExceededError` (`reason: 'intent'`). A credential an event handler or `onChallenge` returns, MPP or x402, is checked against the one offered challenge it pays, and a fetch built on a limited mppx fetch keeps its limits. A fetch with these options refuses the MCP tool calls `McpClient.wrap` pays itself with a `TypeError`. Added the decoded receipt, amount (a decimal string) and normalized requirement of the offer the credential pays to `payment.response` events.
16
+ - 34e6d4c: Fixed `Transport.http().setCredential` sending a Payment credential in `Authorization` when called without `options.challenge` for a challenge that selects `Payment-Authorization`: it now reads the field from the challenge the credential echoes. It also clears a stale Payment credential from `Payment-Authorization` before attaching a new one.
17
+ - 7c2c519: Fixed `Credential.deserialize` to reject credentials whose `payload` is not a JSON object or whose `source` is not a string.
18
+ - 54fc48d: Aligned with the MPP core and Tempo charge specs: replayed credentials now get 402 with a fresh Challenge (`invalid-challenge`), Challenges carry an `_mpp_nonce` (`challengeNonce: false` turns it off), the Tempo attribution memo is optional on the server for pull (`transaction`) credentials, method identifiers are a-z only, requests with more than one Payment credential get 400, body digest mismatches get `invalid-challenge`, and `onChallenge` can return `false` to decline payment.
19
+ - 54fc48d: Kept the challenge-bound attribution memo required for Tempo push payments (`hash` and Zone credentials); pull (`transaction`) credentials accept a plain transfer or a memo not in attribution format, and reject any attribution memo for another realm or Challenge. Clients no longer pay again when a credential they attached themselves, or one sent through the MCP client or MCP over HTTP, gets an `invalid-challenge` answer. The HTTP transport no longer counts commas inside another scheme's quoted parameters as extra Payment credentials and checks the 64 KiB limit before parsing, session bootstrap routes answer more than one Payment credential with 400, and EVM charge routes no longer attach an x402 offer to a rejection without a Challenge. A synchronous pull broadcast that the node already holds (`already known`, `known transaction` or `ExpiringNonceReplay`) now settles only a transfer that carries this Challenge's attribution memo, so a pending transaction someone else submitted can't pay it.
20
+ - c1d91f6: Changed the identity client to resend a paid request once after a 401, when a prover's `retry` asks to, with refreshed identity and the same Payment credential while its Challenge has not expired, unless the 401 carries a receipt. A 401 never follows settlement, so this recovers from expired identity without paying twice. Paid requests are still never resent after a 403 or any other response. If a retry hook or re-proving fails, or the Challenge expires first, the 401 is returned without resending. The rejected response is released before re-proving, and the Link claims prover reads at most 64 KiB of a challenge body, giving up after 2 seconds or when the request aborts.
21
+ - 813085d: Added trusted receiving-origin configuration for ERC-8004 verification to reject signed requests intended for another service.
22
+
3
23
  ## 0.21.4
4
24
 
5
25
  ### Patch Changes
@@ -12,7 +12,7 @@ export type BodyDigest = `sha-256=${string}`;
12
12
  /**
13
13
  * Computes a SHA-256 digest of the given body.
14
14
  *
15
- * @param body - The body to digest (string or object).
15
+ * @param body - The body to digest (string, object or raw bytes).
16
16
  * @returns A digest string in the format "sha-256=base64hash".
17
17
  *
18
18
  * @example
@@ -23,7 +23,7 @@ export type BodyDigest = `sha-256=${string}`;
23
23
  * // => 'sha-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE'
24
24
  * ```
25
25
  */
26
- export declare function compute(body: Record<string, unknown> | string): BodyDigest;
26
+ export declare function compute(body: Record<string, unknown> | string | Uint8Array): BodyDigest;
27
27
  /**
28
28
  * Verifies that a digest matches the given body.
29
29
  *
@@ -38,5 +38,5 @@ export declare function compute(body: Record<string, unknown> | string): BodyDig
38
38
  * const isValid = BodyDigest.verify(digest, '{"amount":"1000"}')
39
39
  * ```
40
40
  */
41
- export declare function verify(digest: BodyDigest, body: Record<string, unknown> | string): boolean;
41
+ export declare function verify(digest: BodyDigest, body: Record<string, unknown> | string | Uint8Array): boolean;
42
42
  //# sourceMappingURL=BodyDigest.d.ts.map
@@ -3,7 +3,7 @@ import { constantTimeEqual } from './internal/constantTimeEqual.js';
3
3
  /**
4
4
  * Computes a SHA-256 digest of the given body.
5
5
  *
6
- * @param body - The body to digest (string or object).
6
+ * @param body - The body to digest (string, object or raw bytes).
7
7
  * @returns A digest string in the format "sha-256=base64hash".
8
8
  *
9
9
  * @example
@@ -15,8 +15,10 @@ import { constantTimeEqual } from './internal/constantTimeEqual.js';
15
15
  * ```
16
16
  */
17
17
  export function compute(body) {
18
- const str = typeof body === 'object' ? JSON.stringify(body) : body;
19
- const bytes = Bytes.fromString(str);
18
+ // Raw bytes are hashed as is, so binary bodies and a leading BOM keep their digest.
19
+ const bytes = body instanceof Uint8Array
20
+ ? body
21
+ : Bytes.fromString(typeof body === 'object' ? JSON.stringify(body) : body);
20
22
  const hash = Hash.sha256(bytes, { as: 'Bytes' });
21
23
  const base64 = Base64.fromBytes(hash);
22
24
  return `sha-256=${base64}`;
package/dist/Challenge.js CHANGED
@@ -382,6 +382,11 @@ function parseAuthParams(input, legacyEscaped) {
382
382
  i = nextIndex;
383
383
  if (legacy)
384
384
  legacyEscaped?.add(key);
385
+ // auth-params = auth-param *( OWS "," OWS auth-param ): a value ends at OWS, then "," or the end.
386
+ while (i < input.length && /\s/.test(input[i] ?? ''))
387
+ i++;
388
+ if (i < input.length && input[i] !== ',')
389
+ throw new Error('Malformed auth-param.');
385
390
  if (key in result)
386
391
  throw new Error(`Duplicate parameter: ${key}`);
387
392
  result[key] = value;
@@ -392,11 +397,16 @@ function parseAuthParams(input, legacyEscaped) {
392
397
  function readAuthParamValue(input, start) {
393
398
  if (input[start] === '"')
394
399
  return readQuotedAuthParamValue(input, start + 1);
400
+ // token = 1*tchar (RFC 9110)
395
401
  let i = start;
396
- while (i < input.length && input[i] !== ',')
402
+ while (i < input.length && tcharPattern.test(input[i] ?? ''))
397
403
  i++;
398
- return [input.slice(start, i).trim(), i];
404
+ if (i === start)
405
+ throw new Error('Malformed auth-param.');
406
+ return [input.slice(start, i), i];
399
407
  }
408
+ /** @internal RFC 9110 `tchar`. */
409
+ const tcharPattern = /[!#$%&'*+\-.^_`|~0-9A-Za-z]/;
400
410
  /** @internal */
401
411
  function readQuotedAuthParamValue(input, start) {
402
412
  let i = start;
@@ -47,6 +47,11 @@ export function deserialize(value) {
47
47
  try {
48
48
  const json = Base64.toString(prefixMatch[1]);
49
49
  const parsed = JSON.parse(json);
50
+ // The payload is a required JSON object and the source an optional string.
51
+ if (!isObject(parsed.payload))
52
+ throw new Error('Invalid payload.');
53
+ if (parsed.source !== undefined && typeof parsed.source !== 'string')
54
+ throw new Error('Invalid source.');
50
55
  const { opaque: challengeOpaque, request, meta: _meta, ...challengeFields } = parsed.challenge;
51
56
  const { meta, opaque } = normalizeCredentialOpaque(challengeOpaque);
52
57
  const challenge = Challenge.Schema.parse({
@@ -80,8 +85,11 @@ function normalizeCredentialOpaque(value) {
80
85
  opaque: PaymentRequest.serialize(value),
81
86
  };
82
87
  }
88
+ function isObject(value) {
89
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
90
+ }
83
91
  function isStringRecord(value) {
84
- if (typeof value !== 'object' || value === null || Array.isArray(value))
92
+ if (!isObject(value))
85
93
  return false;
86
94
  return Object.values(value).every((entry) => typeof entry === 'string');
87
95
  }
package/dist/Errors.d.ts CHANGED
@@ -76,7 +76,7 @@ export declare namespace MalformedCredentialError {
76
76
  * Challenge ID is unknown, expired, or already used.
77
77
  */
78
78
  export declare class InvalidChallengeError extends PaymentError {
79
- readonly name = "InvalidChallengeError";
79
+ readonly name: string;
80
80
  readonly title = "Invalid Challenge";
81
81
  readonly status = 402;
82
82
  readonly type = "https://paymentauth.org/problems/invalid-challenge";
@@ -112,15 +112,13 @@ export declare namespace VerificationFailedError {
112
112
  /**
113
113
  * The payment behind a credential is already used or bound elsewhere: the
114
114
  * credential was consumed by an earlier request, is being settled by a
115
- * concurrent one, or its settled transfer is bound to another challenge.
115
+ * concurrent one, or its Challenge was already answered.
116
116
  *
117
- * Answered with 403 and no challenge (the payment was valid, but policy
118
- * denies access), since a fresh 402 challenge would invite an auto-paying
119
- * client to pay again. The problem type stays `verification-failed`.
117
+ * Answered with 402, a fresh Challenge and problem type `invalid-challenge`,
118
+ * as the core spec specifies for a replayed Credential.
120
119
  */
121
- export declare class CredentialReplayedError extends VerificationFailedError {
120
+ export declare class CredentialReplayedError extends InvalidChallengeError {
122
121
  readonly name = "CredentialReplayedError";
123
- readonly status = 403;
124
122
  constructor(options?: CredentialReplayedError.Options);
125
123
  }
126
124
  export declare namespace CredentialReplayedError {
@@ -212,6 +210,10 @@ export declare namespace PaymentOutcomeUnknownError {
212
210
  * the node accepted it, and no receipt appeared before settlement stopped polling. The transaction
213
211
  * may still be included until `validBefore`.
214
212
  *
213
+ * A `tempo.charge` client also throws it when a Zone withdrawal it sent to pay a challenge has no
214
+ * send response or receipt: the withdrawal may have moved funds, so the client's spending limits
215
+ * keep counting the payment, and retrying the challenge resumes it rather than withdrawing again.
216
+ *
215
217
  * Settle it by looking up the receipt for `transactionHash`: once `validBefore` has passed, the
216
218
  * transaction can no longer be included, so one lookup after it is final. This is not a
217
219
  * `PaymentError`: HTTP handlers still answer with a generic 500 `InternalPaymentError`, whose
@@ -437,6 +439,49 @@ export declare namespace ZoneSettlementPendingError {
437
439
  zoneId: number;
438
440
  };
439
441
  }
442
+ /**
443
+ * A payment is over the client's `maxPayment` or its budget, or it cannot be checked against
444
+ * them, so the client did not create or sign a credential.
445
+ *
446
+ * `reason` is `amount` when the payment is larger than the limit allows, and `asset` when the
447
+ * limit cannot count it: no per-asset limit names its asset, or a currency limit meets a token
448
+ * whose currency and decimals the client did not configure. Currency limits never trust the
449
+ * currency or decimals a server sends, so add the token to the client's `tokens`, set a
450
+ * per-asset limit, or raise the limit.
451
+ *
452
+ * `reason` is `credential` when a credential an event handler or `onChallenge` returned cannot
453
+ * be read or bound to exactly one challenge the response offered, so it was not used; `limit` is
454
+ * then `maxPayment` when it is set, else `budget`.
455
+ *
456
+ * `reason` is `intent` when the selected challenge is not a `charge`: spending options bound one
457
+ * payment, while a session or subscription keeps paying after it is checked, so the client refuses
458
+ * every other intent while `maxPayment`, `authorize` or `funders` is set.
459
+ */
460
+ export declare class PaymentLimitExceededError extends Error {
461
+ readonly name = "PaymentLimitExceededError";
462
+ /** The limit that refused the payment. */
463
+ readonly limit: PaymentLimitExceededError.Limit;
464
+ /** Why the limit refused it. */
465
+ readonly reason: PaymentLimitExceededError.Reason;
466
+ constructor(options: PaymentLimitExceededError.Options);
467
+ }
468
+ export declare namespace PaymentLimitExceededError {
469
+ /** `maxPayment`: the per-payment limit. `budget`: a `Budget` passed as `authorize`. */
470
+ type Limit = 'maxPayment' | 'budget';
471
+ /**
472
+ * `amount`: over the limit. `asset`: the limit cannot count the payment's asset. `credential`:
473
+ * a credential an event handler or `onChallenge` returned cannot be read, or pays no single
474
+ * challenge the response offered, so its payment cannot be checked. `intent`: the challenge is
475
+ * not a `charge`, such as a session or subscription, which a limit cannot bound.
476
+ */
477
+ type Reason = 'amount' | 'asset' | 'credential' | 'intent';
478
+ type Options = {
479
+ /** The limit that refused the payment. */
480
+ limit: Limit;
481
+ /** Why the limit refused it. */
482
+ reason: Reason;
483
+ };
484
+ }
440
485
  /**
441
486
  * No credential was provided but payment is required.
442
487
  */
@@ -472,7 +517,7 @@ export declare namespace InvalidPayloadError {
472
517
  * Request is malformed or contains invalid parameters.
473
518
  */
474
519
  export declare class BadRequestError extends PaymentError {
475
- readonly name = "BadRequestError";
520
+ readonly name: string;
476
521
  readonly title = "Bad Request";
477
522
  readonly status = 400;
478
523
  readonly type = "https://paymentauth.org/problems/bad-request";
@@ -484,6 +529,15 @@ export declare namespace BadRequestError {
484
529
  reason?: string;
485
530
  };
486
531
  }
532
+ /**
533
+ * The request carries more than one Payment credential (across `Authorization` and
534
+ * `Payment-Authorization`, or comma-joined in one field). Answered with 400 and no
535
+ * Challenge, as the core spec requires.
536
+ */
537
+ export declare class MultipleCredentialsError extends BadRequestError {
538
+ readonly name = "MultipleCredentialsError";
539
+ constructor();
540
+ }
487
541
  /**
488
542
  * Payment amount is insufficient (too low).
489
543
  */
package/dist/Errors.js CHANGED
@@ -93,15 +93,13 @@ export class VerificationFailedError extends PaymentError {
93
93
  /**
94
94
  * The payment behind a credential is already used or bound elsewhere: the
95
95
  * credential was consumed by an earlier request, is being settled by a
96
- * concurrent one, or its settled transfer is bound to another challenge.
96
+ * concurrent one, or its Challenge was already answered.
97
97
  *
98
- * Answered with 403 and no challenge (the payment was valid, but policy
99
- * denies access), since a fresh 402 challenge would invite an auto-paying
100
- * client to pay again. The problem type stays `verification-failed`.
98
+ * Answered with 402, a fresh Challenge and problem type `invalid-challenge`,
99
+ * as the core spec specifies for a replayed Credential.
101
100
  */
102
- export class CredentialReplayedError extends VerificationFailedError {
101
+ export class CredentialReplayedError extends InvalidChallengeError {
103
102
  name = 'CredentialReplayedError';
104
- status = 403;
105
103
  constructor(options = {}) {
106
104
  const { reason = 'Credential has already been used' } = options;
107
105
  super({ reason });
@@ -174,6 +172,10 @@ export class PaymentOutcomeUnknownError extends PaymentError {
174
172
  * the node accepted it, and no receipt appeared before settlement stopped polling. The transaction
175
173
  * may still be included until `validBefore`.
176
174
  *
175
+ * A `tempo.charge` client also throws it when a Zone withdrawal it sent to pay a challenge has no
176
+ * send response or receipt: the withdrawal may have moved funds, so the client's spending limits
177
+ * keep counting the payment, and retrying the challenge resumes it rather than withdrawing again.
178
+ *
177
179
  * Settle it by looking up the receipt for `transactionHash`: once `validBefore` has passed, the
178
180
  * transaction can no longer be included, so one lookup after it is final. This is not a
179
181
  * `PaymentError`: HTTP handlers still answer with a generic 500 `InternalPaymentError`, whose
@@ -387,6 +389,44 @@ export class ZoneSettlementPendingError extends Error {
387
389
  Object.defineProperty(this, 'cause', { configurable: true, value: cause, writable: true });
388
390
  }
389
391
  }
392
+ /**
393
+ * A payment is over the client's `maxPayment` or its budget, or it cannot be checked against
394
+ * them, so the client did not create or sign a credential.
395
+ *
396
+ * `reason` is `amount` when the payment is larger than the limit allows, and `asset` when the
397
+ * limit cannot count it: no per-asset limit names its asset, or a currency limit meets a token
398
+ * whose currency and decimals the client did not configure. Currency limits never trust the
399
+ * currency or decimals a server sends, so add the token to the client's `tokens`, set a
400
+ * per-asset limit, or raise the limit.
401
+ *
402
+ * `reason` is `credential` when a credential an event handler or `onChallenge` returned cannot
403
+ * be read or bound to exactly one challenge the response offered, so it was not used; `limit` is
404
+ * then `maxPayment` when it is set, else `budget`.
405
+ *
406
+ * `reason` is `intent` when the selected challenge is not a `charge`: spending options bound one
407
+ * payment, while a session or subscription keeps paying after it is checked, so the client refuses
408
+ * every other intent while `maxPayment`, `authorize` or `funders` is set.
409
+ */
410
+ export class PaymentLimitExceededError extends Error {
411
+ name = 'PaymentLimitExceededError';
412
+ /** The limit that refused the payment. */
413
+ limit;
414
+ /** Why the limit refused it. */
415
+ reason;
416
+ constructor(options) {
417
+ const { limit, reason } = options;
418
+ const name = limit === 'budget' ? 'the remaining budget' : 'maxPayment';
419
+ super(reason === 'amount'
420
+ ? `Payment exceeds ${name}, so no credential was created.`
421
+ : reason === 'credential'
422
+ ? `Credential cannot be checked against ${name}: it is unreadable or pays no single challenge the response offered, so it was not used.`
423
+ : reason === 'intent'
424
+ ? `Payment intent cannot be checked against ${name}: spending options accept only charges, so no credential was created.`
425
+ : `Payment asset cannot be checked against ${name}: no limit names it, or the client does not configure its currency and decimals. No credential was created.`);
426
+ this.limit = limit;
427
+ this.reason = reason;
428
+ }
429
+ }
390
430
  /**
391
431
  * No credential was provided but payment is required.
392
432
  */
@@ -428,6 +468,17 @@ export class BadRequestError extends PaymentError {
428
468
  super(reason ? `Bad request: ${reason}.` : 'Bad request.');
429
469
  }
430
470
  }
471
+ /**
472
+ * The request carries more than one Payment credential (across `Authorization` and
473
+ * `Payment-Authorization`, or comma-joined in one field). Answered with 400 and no
474
+ * Challenge, as the core spec requires.
475
+ */
476
+ export class MultipleCredentialsError extends BadRequestError {
477
+ name = 'MultipleCredentialsError';
478
+ constructor() {
479
+ super({ reason: 'request carries more than one Payment credential' });
480
+ }
481
+ }
431
482
  /**
432
483
  * Payment amount is insufficient (too low).
433
484
  */
package/dist/Store.d.ts CHANGED
@@ -74,16 +74,19 @@ export type AtomicStore<itemMap extends StoreItemMap = StoreItemMap> = Store<ite
74
74
  * Returns `true` when this call recorded the key and `false` when it was already
75
75
  * recorded and unexpired, or the proposed expiry has passed. `expires` is a Unix timestamp in milliseconds.
76
76
  * An optional owner permits conditional release through {@link releaseClaim}.
77
- * Custom optimized stores opt into ownership by implementing `releaseClaim`; otherwise
78
- * their claims remain consumed until expiry. Deploy upgraded Durable Object classes
79
- * before clients that use owned claims.
77
+ * Custom optimized stores must implement owner-aware `tryClaim` and atomic `releaseClaim`
78
+ * before using owned claims. Unsupported stores are rejected before recording a claim. Deploy upgraded Durable Object classes
79
+ * before clients that use owned claims. Drain owner-unaware verifier workers before enabling
80
+ * owned claims; do not run them against stores with live owned claims. Before upgrading replay
81
+ * shards from an owner-only schema, quiesce traffic and drain all in-flight owned attempts.
82
+ * Existing owned rows cannot be safely backfilled and remain consumed until expiry.
80
83
  * Uses the adapter's optimized primitive when available and otherwise falls
81
84
  * back to {@link AtomicStore.update}.
82
85
  */
83
86
  export declare function tryClaim<itemMap extends StoreItemMap, key extends keyof itemMap & string>(store: AtomicStore<itemMap>, key: key, expires: number, owner?: string): MaybePromise<boolean>;
84
87
  /**
85
88
  * Releases a replay claim only while it belongs to `owner`.
86
- * Custom optimized stores without ownership support retain claims until expiry.
89
+ * Custom optimized stores without ownership support are rejected.
87
90
  */
88
91
  export declare function releaseClaim<itemMap extends StoreItemMap, key extends keyof itemMap & string>(store: AtomicStore<itemMap>, key: key, owner: string): Promise<void>;
89
92
  /** Options shared by store constructors. */
package/dist/Store.js CHANGED
@@ -21,17 +21,22 @@ import { Json } from 'ox';
21
21
  * Returns `true` when this call recorded the key and `false` when it was already
22
22
  * recorded and unexpired, or the proposed expiry has passed. `expires` is a Unix timestamp in milliseconds.
23
23
  * An optional owner permits conditional release through {@link releaseClaim}.
24
- * Custom optimized stores opt into ownership by implementing `releaseClaim`; otherwise
25
- * their claims remain consumed until expiry. Deploy upgraded Durable Object classes
26
- * before clients that use owned claims.
24
+ * Custom optimized stores must implement owner-aware `tryClaim` and atomic `releaseClaim`
25
+ * before using owned claims. Unsupported stores are rejected before recording a claim. Deploy upgraded Durable Object classes
26
+ * before clients that use owned claims. Drain owner-unaware verifier workers before enabling
27
+ * owned claims; do not run them against stores with live owned claims. Before upgrading replay
28
+ * shards from an owner-only schema, quiesce traffic and drain all in-flight owned attempts.
29
+ * Existing owned rows cannot be safely backfilled and remain consumed until expiry.
27
30
  * Uses the adapter's optimized primitive when available and otherwise falls
28
31
  * back to {@link AtomicStore.update}.
29
32
  */
30
33
  export function tryClaim(store, key, expires, owner) {
34
+ if (owner !== undefined && store.tryClaim && !store.releaseClaim)
35
+ throw new Error('Owned replay claims require a custom store with atomic releaseClaim support. Migrate the store before use.');
31
36
  if (!Number.isFinite(expires) || expires <= Date.now())
32
37
  return false;
33
38
  if (store.tryClaim) {
34
- const result = store.tryClaim(key, expires, store.releaseClaim ? owner : undefined);
39
+ const result = store.tryClaim(key, expires, owner);
35
40
  return typeof result === 'boolean'
36
41
  ? result && expires > Date.now()
37
42
  : result.then((claimed) => claimed && expires > Date.now());
@@ -56,13 +61,13 @@ export function tryClaim(store, key, expires, owner) {
56
61
  }
57
62
  /**
58
63
  * Releases a replay claim only while it belongs to `owner`.
59
- * Custom optimized stores without ownership support retain claims until expiry.
64
+ * Custom optimized stores without ownership support are rejected.
60
65
  */
61
66
  export async function releaseClaim(store, key, owner) {
62
67
  if (store.releaseClaim)
63
68
  return store.releaseClaim(key, owner);
64
69
  if (store.tryClaim)
65
- return;
70
+ throw new Error('Owned replay claims require a custom store with atomic releaseClaim support. Migrate the store before use.');
66
71
  await store.update(key, (current) => ({
67
72
  op: isReplayMarker(current) && current.owner === owner ? 'delete' : 'noop',
68
73
  result: undefined,
@@ -686,7 +691,7 @@ export class DurableObjectStore {
686
691
  if (!Number.isFinite(expires) || expires <= now)
687
692
  return false;
688
693
  const claimed = sql
689
- .exec('INSERT INTO mppx_replay_claims (key, expires, owner) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET expires = excluded.expires, owner = excluded.owner WHERE mppx_replay_claims.expires <= ? RETURNING key', key, expires, owner ?? null, now)
694
+ .exec('INSERT INTO mppx_replay_claims (key, expires, owner, owner_expires) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO UPDATE SET expires = excluded.expires, owner = excluded.owner, owner_expires = excluded.owner_expires WHERE mppx_replay_claims.expires <= ? RETURNING key', key, expires, owner ?? null, owner === undefined ? null : expires, now)
690
695
  .toArray().length === 1;
691
696
  if (claimed) {
692
697
  const { storage } = this.state;
@@ -713,7 +718,7 @@ export class DurableObjectStore {
713
718
  if (owner === undefined)
714
719
  sql.exec('DELETE FROM mppx_replay_claims WHERE key = ? AND owner IS NULL', key);
715
720
  else
716
- sql.exec('DELETE FROM mppx_replay_claims WHERE key = ? AND owner = ?', key, owner);
721
+ sql.exec('DELETE FROM mppx_replay_claims WHERE key = ? AND owner = ? AND owner_expires = expires', key, owner);
717
722
  }
718
723
  // The store's operations are named `store*`, not `get`, `put` and `delete`: on a Worker
719
724
  // with the `fetcher_has_get_put_delete` flag (or the `rpc` flag before 2024-03-26), a stub's
@@ -816,6 +821,11 @@ export class DurableObjectStore {
816
821
  .toArray()
817
822
  .some((column) => column.name === 'owner'))
818
823
  sql.exec('ALTER TABLE mppx_replay_claims ADD COLUMN owner TEXT');
824
+ if (!sql
825
+ .exec('PRAGMA table_info(mppx_replay_claims)')
826
+ .toArray()
827
+ .some((column) => column.name === 'owner_expires'))
828
+ sql.exec('ALTER TABLE mppx_replay_claims ADD COLUMN owner_expires INTEGER');
819
829
  sql.exec('CREATE INDEX IF NOT EXISTS mppx_replay_claims_by_expiry ON mppx_replay_claims (expires)');
820
830
  return sql;
821
831
  }