@fantastic.dev/better-stripe 0.60.0 → 0.61.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 (193) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +26 -6
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +13 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +26 -6
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +13 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/creditCapacity.d.ts.map +1 -1
  12. package/dist/client/usage/creditCapacity.js +7 -1
  13. package/dist/client/usage/creditCapacity.js.map +1 -1
  14. package/dist/client/usage/creditClient.d.ts +3 -0
  15. package/dist/client/usage/creditClient.d.ts.map +1 -1
  16. package/dist/client/usage/creditDelivery.d.ts.map +1 -1
  17. package/dist/client/usage/creditDelivery.js +4 -1
  18. package/dist/client/usage/creditDelivery.js.map +1 -1
  19. package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
  20. package/dist/client/usage/creditLifecycle.js +2 -1
  21. package/dist/client/usage/creditLifecycle.js.map +1 -1
  22. package/dist/client/usage/creditNative.d.ts +3 -0
  23. package/dist/client/usage/creditNative.d.ts.map +1 -1
  24. package/dist/client/usage/creditNative.js +3 -0
  25. package/dist/client/usage/creditNative.js.map +1 -1
  26. package/dist/client/usage/creditProvider.d.ts.map +1 -1
  27. package/dist/client/usage/creditProvider.js +2 -1
  28. package/dist/client/usage/creditProvider.js.map +1 -1
  29. package/dist/client/usage/creditRead.d.ts +1 -0
  30. package/dist/client/usage/creditRead.d.ts.map +1 -1
  31. package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
  32. package/dist/client/usage/creditReconciliation.js +11 -3
  33. package/dist/client/usage/creditReconciliation.js.map +1 -1
  34. package/dist/client/usage/creditSettlement.fixtures.d.ts +1 -0
  35. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -1
  36. package/dist/client/usage/creditTransport.fixtures.d.ts +1 -0
  37. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  38. package/dist/client/usage/creditTransport.fixtures.js +2 -1
  39. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  40. package/dist/client/usage/index.d.ts +2 -0
  41. package/dist/client/usage/index.d.ts.map +1 -1
  42. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
  43. package/dist/client/usage/subscriptionCancellation.js +3 -2
  44. package/dist/client/usage/subscriptionCancellation.js.map +1 -1
  45. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
  46. package/dist/client/usage/subscriptionCheckout.js +3 -2
  47. package/dist/client/usage/subscriptionCheckout.js.map +1 -1
  48. package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
  49. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
  50. package/dist/client/usage/subscriptionLifecycle.js +3 -2
  51. package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
  52. package/dist/client/usage/subscriptionProvider.d.ts +2 -0
  53. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
  54. package/dist/client/usage/subscriptionProvider.js +9 -2
  55. package/dist/client/usage/subscriptionProvider.js.map +1 -1
  56. package/dist/component/_generated/component.d.ts +21 -0
  57. package/dist/component/_generated/component.d.ts.map +1 -1
  58. package/dist/component/earnings/triggers.d.ts +16 -6
  59. package/dist/component/earnings/triggers.d.ts.map +1 -1
  60. package/dist/component/schema.d.ts +13 -3
  61. package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
  62. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
  63. package/dist/component/usage/allowance.fixtures.js +67 -0
  64. package/dist/component/usage/allowance.fixtures.js.map +1 -0
  65. package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
  66. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
  67. package/dist/component/usageCredits/accounting.fixtures.js +89 -0
  68. package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
  69. package/dist/component/usageCredits/helpers.d.ts +7 -0
  70. package/dist/component/usageCredits/helpers.d.ts.map +1 -1
  71. package/dist/component/usageCredits/helpers.js +5 -0
  72. package/dist/component/usageCredits/helpers.js.map +1 -1
  73. package/dist/component/usageCredits/mutations.d.ts +6 -0
  74. package/dist/component/usageCredits/mutations.d.ts.map +1 -1
  75. package/dist/component/usageCredits/mutations.js +70 -7
  76. package/dist/component/usageCredits/mutations.js.map +1 -1
  77. package/dist/component/usageCredits/purchase.d.ts +1 -0
  78. package/dist/component/usageCredits/purchase.d.ts.map +1 -1
  79. package/dist/component/usageCredits/queries.d.ts +10 -0
  80. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  81. package/dist/component/usageCredits/schema.d.ts +24 -4
  82. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  83. package/dist/component/usageCredits/schema.js +4 -0
  84. package/dist/component/usageCredits/schema.js.map +1 -1
  85. package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
  86. package/dist/component/usageSubscriptions/history.js +3 -1
  87. package/dist/component/usageSubscriptions/history.js.map +1 -1
  88. package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
  89. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
  90. package/dist/component/usageSubscriptions/mutations.js +19 -0
  91. package/dist/component/usageSubscriptions/mutations.js.map +1 -1
  92. package/dist/component/usageSubscriptions/queries.d.ts +2 -0
  93. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
  94. package/dist/component/usageSubscriptions/schema.d.ts +7 -2
  95. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
  96. package/dist/component/usageSubscriptions/schema.js +1 -0
  97. package/dist/component/usageSubscriptions/schema.js.map +1 -1
  98. package/dist/react/index.d.ts +12 -0
  99. package/dist/react/index.d.ts.map +1 -1
  100. package/dist/react/index.js +7 -0
  101. package/dist/react/index.js.map +1 -1
  102. package/dist/react/workflows/Pagination.d.ts +1 -0
  103. package/dist/react/workflows/Pagination.d.ts.map +1 -1
  104. package/dist/react/workflows/Pagination.js +1 -0
  105. package/dist/react/workflows/Pagination.js.map +1 -1
  106. package/dist/react/workflows/Usage.fixtures.d.ts +17 -0
  107. package/dist/react/workflows/Usage.fixtures.d.ts.map +1 -0
  108. package/dist/react/workflows/Usage.fixtures.js +79 -0
  109. package/dist/react/workflows/Usage.fixtures.js.map +1 -0
  110. package/dist/react/workflows/Usage.types.d.ts +25 -0
  111. package/dist/react/workflows/Usage.types.d.ts.map +1 -0
  112. package/dist/react/workflows/Usage.types.js +11 -0
  113. package/dist/react/workflows/Usage.types.js.map +1 -0
  114. package/dist/react/workflows/UsageAllowance.d.ts +14 -0
  115. package/dist/react/workflows/UsageAllowance.d.ts.map +1 -0
  116. package/dist/react/workflows/UsageAllowance.js +21 -0
  117. package/dist/react/workflows/UsageAllowance.js.map +1 -0
  118. package/dist/react/workflows/UsageBilling.d.ts +20 -0
  119. package/dist/react/workflows/UsageBilling.d.ts.map +1 -0
  120. package/dist/react/workflows/UsageBilling.js +40 -0
  121. package/dist/react/workflows/UsageBilling.js.map +1 -0
  122. package/dist/react/workflows/UsageCredits.d.ts +14 -0
  123. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  124. package/dist/react/workflows/UsageCredits.js +25 -0
  125. package/dist/react/workflows/UsageCredits.js.map +1 -0
  126. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  127. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  128. package/dist/react/workflows/UsageHistory.js +74 -0
  129. package/dist/react/workflows/UsageHistory.js.map +1 -0
  130. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  131. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  132. package/dist/react/workflows/UsageSummary.js +54 -0
  133. package/dist/react/workflows/UsageSummary.js.map +1 -0
  134. package/dist/react/workflows/usage-format.d.ts +11 -0
  135. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  136. package/dist/react/workflows/usage-format.js +43 -0
  137. package/dist/react/workflows/usage-format.js.map +1 -0
  138. package/dist/react/workflows/usage-scope.d.ts +5 -0
  139. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  140. package/dist/react/workflows/usage-scope.js +26 -0
  141. package/dist/react/workflows/usage-scope.js.map +1 -0
  142. package/docs/README.md +4 -0
  143. package/docs/react-api.md +4 -0
  144. package/docs/usage-credits.md +6 -1
  145. package/docs/usage-react.md +182 -0
  146. package/docs/usage-security.md +130 -0
  147. package/package.json +3 -1
  148. package/src/client/usage/creditBackingIsolation.test.ts +110 -0
  149. package/src/client/usage/creditCapacity.test.ts +80 -1
  150. package/src/client/usage/creditCapacity.ts +10 -1
  151. package/src/client/usage/creditDelivery.ts +4 -0
  152. package/src/client/usage/creditLifecycle.ts +2 -0
  153. package/src/client/usage/creditNative.ts +5 -0
  154. package/src/client/usage/creditProofBounds.test.ts +187 -0
  155. package/src/client/usage/creditProvider.test.ts +74 -0
  156. package/src/client/usage/creditProvider.ts +2 -0
  157. package/src/client/usage/creditReconciliation.ts +18 -3
  158. package/src/client/usage/creditTransport.fixtures.ts +2 -1
  159. package/src/client/usage/index.ts +3 -0
  160. package/src/client/usage/subscriptionCancellation.ts +3 -2
  161. package/src/client/usage/subscriptionCheckout.ts +7 -2
  162. package/src/client/usage/subscriptionClient.test.ts +60 -1
  163. package/src/client/usage/subscriptionLifecycle.ts +3 -2
  164. package/src/client/usage/subscriptionProvider.ts +27 -3
  165. package/src/component/_generated/component.ts +40 -1
  166. package/src/component/usage/allowance.fixtures.ts +77 -0
  167. package/src/component/usage/allowance.test.ts +3 -66
  168. package/src/component/usage/allowanceBounds.test.ts +79 -0
  169. package/src/component/usage/historyIsolation.test.ts +124 -0
  170. package/src/component/usageCredits/accounting.fixtures.ts +96 -0
  171. package/src/component/usageCredits/accounting.test.ts +176 -82
  172. package/src/component/usageCredits/freshness.test.ts +33 -0
  173. package/src/component/usageCredits/helpers.ts +8 -0
  174. package/src/component/usageCredits/mutations.ts +83 -5
  175. package/src/component/usageCredits/quotas.test.ts +63 -0
  176. package/src/component/usageCredits/schema.ts +10 -0
  177. package/src/component/usageSubscriptions/history.test.ts +57 -0
  178. package/src/component/usageSubscriptions/history.ts +3 -1
  179. package/src/component/usageSubscriptions/mutations.ts +23 -0
  180. package/src/component/usageSubscriptions/schema.ts +1 -0
  181. package/src/react/index.ts +20 -0
  182. package/src/react/workflows/Pagination.tsx +2 -0
  183. package/src/react/workflows/Usage.fixtures.ts +88 -0
  184. package/src/react/workflows/Usage.test.tsx +373 -0
  185. package/src/react/workflows/Usage.types.ts +39 -0
  186. package/src/react/workflows/UsageAllowance.tsx +114 -0
  187. package/src/react/workflows/UsageBilling.tsx +90 -0
  188. package/src/react/workflows/UsageCredits.tsx +112 -0
  189. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  190. package/src/react/workflows/UsageHistory.tsx +154 -0
  191. package/src/react/workflows/UsageSummary.tsx +204 -0
  192. package/src/react/workflows/usage-format.ts +48 -0
  193. package/src/react/workflows/usage-scope.ts +42 -0
@@ -1,5 +1,5 @@
1
1
  import type Stripe from "stripe";
2
- import { creditRequire } from "./creditNative.js";
2
+ import { creditRequire, nativeCustomerId } from "./creditNative.js";
3
3
  import type { UsageCreditPurchaseTerms } from "./creditTerms.js";
4
4
  /** Read-only, bounded prepayment guard. Pending component intents reserve slots separately. */
5
5
  export async function verifyNativeCreditCapacity(
@@ -16,9 +16,16 @@ export async function verifyNativeCreditCapacity(
16
16
  limit: 100,
17
17
  ...(cursor ? { starting_after: cursor } : {}),
18
18
  });
19
+ creditRequire(
20
+ Array.isArray(result.data) &&
21
+ result.data.length <= 100 &&
22
+ typeof result.has_more === "boolean",
23
+ "Native credit inventory page exceeds proof budget",
24
+ );
19
25
  for (const grant of result.data) {
20
26
  creditRequire(
21
27
  grant.customer_account === terms.scope.customerAccount &&
28
+ nativeCustomerId(grant.customer) === terms.binding.stripeCustomerId &&
22
29
  grant.livemode === terms.scope.livemode,
23
30
  "Native credit inventory scope mismatch",
24
31
  );
@@ -58,6 +65,8 @@ export async function verifyNativeCreditCapacity(
58
65
  creditRequire(
59
66
  balance.livemode === terms.scope.livemode &&
60
67
  balance.customer_account === terms.scope.customerAccount &&
68
+ nativeCustomerId(balance.customer) ===
69
+ terms.binding.stripeCustomerId &&
61
70
  balance.balances.length === 1,
62
71
  "Native credit capacity balance unavailable",
63
72
  );
@@ -8,6 +8,7 @@ import type { PreparedUsageRecord } from "./records.js";
8
8
  import { creditNativeObservation } from "./creditProofs.js";
9
9
  import { creditPurchaseTerms } from "./creditTerms.js";
10
10
  import {
11
+ nativeCustomerId,
11
12
  creditRequire,
12
13
  paymentIdentity,
13
14
  verifiedCreditPayment,
@@ -84,6 +85,7 @@ export async function verifyCreditDelivery(
84
85
  grant.id === local.creditGrantId &&
85
86
  !grant.voided_at &&
86
87
  grant.customer_account === record.scope.customerAccount &&
88
+ nativeCustomerId(grant.customer) === record.binding.stripeCustomerId &&
87
89
  grant.livemode === record.scope.livemode &&
88
90
  grant.metadata?.bsUsageCredit === purchase.key &&
89
91
  (grant.expires_at === null ||
@@ -94,6 +96,8 @@ export async function verifyCreditDelivery(
94
96
  record.binding.stripePriceId &&
95
97
  summary.livemode === record.scope.livemode &&
96
98
  summary.customer_account === record.scope.customerAccount &&
99
+ nativeCustomerId(summary.customer) ===
100
+ record.binding.stripeCustomerId &&
97
101
  summary.balances.length === 1 &&
98
102
  native?.currency === terms.binding.plan.rate.currency &&
99
103
  native.value === expected &&
@@ -10,6 +10,7 @@ import {
10
10
  } from "./creditTerms.js";
11
11
  import {
12
12
  creditCall,
13
+ nativeCustomerId,
13
14
  creditRequire,
14
15
  verifyCreditRealm,
15
16
  discoverCredit,
@@ -140,6 +141,7 @@ export async function prepareCreditRefund(
140
141
  creditRequire(
141
142
  grant.id === row.creditGrantId &&
142
143
  grant.customer_account === terms.scope.customerAccount &&
144
+ nativeCustomerId(grant.customer) === terms.binding.stripeCustomerId &&
143
145
  grant.livemode === terms.scope.livemode &&
144
146
  grant.metadata?.bsUsageCredit === row.key,
145
147
  "Original credit grant identity mismatch",
@@ -4,6 +4,9 @@ import { UsageCreditError, UsageCreditRecoveryError } from "./creditTerms.js";
4
4
  import { verifyRealm } from "./catalogTypes.js";
5
5
  import { verifyPinnedUsagePrice } from "./catalogPrices.js";
6
6
  import { paymentCreditProof } from "./creditProofs.js";
7
+ export const nativeCustomerId = (
8
+ value: string | { id: string } | null | undefined,
9
+ ) => (typeof value === "string" ? value : value?.id);
7
10
  export async function creditCall<T>(call: () => Promise<T>): Promise<T> {
8
11
  try {
9
12
  return await call();
@@ -60,6 +63,7 @@ export function paymentIdentity(
60
63
  payment.object === "payment_intent" &&
61
64
  (!pinned || payment.id === pinned) &&
62
65
  payment.customer_account === terms.scope.customerAccount &&
66
+ nativeCustomerId(payment.customer) === terms.binding.stripeCustomerId &&
63
67
  payment.livemode === terms.scope.livemode &&
64
68
  payment.currency === terms.binding.plan.rate.currency &&
65
69
  payment.amount === terms.amount &&
@@ -82,6 +86,7 @@ export function verifiedCreditPayment(
82
86
  typeof charge !== "string" &&
83
87
  charge.object === "charge" &&
84
88
  charge.payment_intent === payment.id &&
89
+ nativeCustomerId(charge.customer) === terms.binding.stripeCustomerId &&
85
90
  charge.paid &&
86
91
  charge.captured &&
87
92
  charge.status === "succeeded" &&
@@ -0,0 +1,187 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { schema, modules } from "../../test.js";
3
+ import { mutation } from "../../component/_generated/server.js";
4
+ import { v } from "convex/values";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import { BetterStripe } from "../index.js";
7
+ import type { RunCtx } from "../helpers.js";
8
+ import { creditFixture } from "./creditTransport.fixtures.js";
9
+ afterEach(() => vi.useRealTimers());
10
+ function response(value: unknown) {
11
+ return new Response(JSON.stringify(value), {
12
+ headers: { "content-type": "application/json" },
13
+ });
14
+ }
15
+ async function setup(count: number, applications = false) {
16
+ let invoiceReads = 0;
17
+ const entries = Array.from({ length: count }, (_, i) => ({
18
+ id: `cbtxn_${i}`,
19
+ object: "billing.credit_balance_transaction",
20
+ credit_grant: "credgr_topup1",
21
+ livemode: false,
22
+ type: applications && i > 0 ? "debit" : "credit",
23
+ credit:
24
+ applications && i > 0
25
+ ? null
26
+ : {
27
+ type: "credits_granted",
28
+ amount: {
29
+ type: "monetary",
30
+ monetary: { currency: "usd", value: i === 0 ? 20 : 0 },
31
+ },
32
+ },
33
+ debit:
34
+ applications && i > 0
35
+ ? {
36
+ type: "credits_applied",
37
+ amount: {
38
+ type: "monetary",
39
+ monetary: { currency: "usd", value: i <= 10 ? 2 : 0 },
40
+ },
41
+ credits_applied: {
42
+ invoice: "in_usage",
43
+ invoice_line_item: "il_usage",
44
+ },
45
+ }
46
+ : null,
47
+ }));
48
+ const f = creditFixture(async (input) => {
49
+ const path = new URL(input).pathname;
50
+ if (path === "/v1/billing/credit_balance_transactions")
51
+ return response({ object: "list", data: entries, has_more: false });
52
+ if (path === "/v1/invoices/in_usage") {
53
+ invoiceReads++;
54
+ return response({
55
+ id: "in_usage",
56
+ livemode: false,
57
+ customer_account: "acct_buyer",
58
+ customer: "cus_buyer",
59
+ currency: "usd",
60
+ status: "paid",
61
+ amount_paid: 0,
62
+ status_transitions: { finalized_at: 1300 },
63
+ parent: { subscription_details: { subscription: "sub_calls" } },
64
+ lines: {
65
+ has_more: false,
66
+ data: [
67
+ {
68
+ id: "il_usage",
69
+ amount: 20,
70
+ currency: "usd",
71
+ quantity_decimal: "10",
72
+ period: { start: 600, end: 1200 },
73
+ pricing: {
74
+ price_details: { price: "price_calls" },
75
+ unit_amount_decimal: "2",
76
+ },
77
+ parent: {
78
+ subscription_item_details: {
79
+ subscription: "sub_calls",
80
+ subscription_item: "si_calls",
81
+ proration: false,
82
+ },
83
+ },
84
+ pretax_credit_amounts: entries.slice(1).map((tx, index) => ({
85
+ type: "credit_balance_transaction",
86
+ credit_balance_transaction: tx.id,
87
+ amount: index < 10 ? 2 : 0,
88
+ })),
89
+ },
90
+ ],
91
+ },
92
+ });
93
+ }
94
+ });
95
+ f.t.registerComponent("betterStripe", schema, {
96
+ ...modules,
97
+ "./component/proofBoundsFixture.ts": async () => ({
98
+ pinProvider: mutation({
99
+ args: {},
100
+ returns: v.null(),
101
+ handler: async (ctx) => {
102
+ const outbox = (await ctx.db.query("usageOutbox").first())!;
103
+ await ctx.db.patch(outbox._id, {
104
+ provider: "function://test-provider",
105
+ definitionVersion: 1,
106
+ });
107
+ return null;
108
+ },
109
+ }),
110
+ }),
111
+ });
112
+ const client = new BetterStripe(f.component),
113
+ provider = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
114
+ const view = await f.ready();
115
+ await f.t.action((ctx) =>
116
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, provider),
117
+ );
118
+ f.state.paid = true;
119
+ await f.t.action((ctx) =>
120
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, provider),
121
+ );
122
+ if (applications) {
123
+ const event = {
124
+ scope: f.purchase.scope,
125
+ binding: f.purchase.binding,
126
+ sourceEventId: "all_units",
127
+ quantity: "10",
128
+ occurredAt: 700,
129
+ },
130
+ subscription = view.bindings[0].subscription;
131
+ const reservation = await f.t.action((ctx) =>
132
+ client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
133
+ );
134
+ const receipt = await f.t.action((ctx) =>
135
+ client.usage.record(ctx as RunCtx, {
136
+ event,
137
+ subscription,
138
+ reservationId: reservation.reservationId,
139
+ }),
140
+ );
141
+ await f.t.action(async (ctx) => {
142
+ await ctx.runMutation(
143
+ componentRef(f.component, "proofBoundsFixture/pinProvider"),
144
+ {},
145
+ );
146
+ const claimed = (await ctx.runMutation(
147
+ componentRef(f.component, "usageDelivery/steps/claim"),
148
+ { scope: event.scope, eventId: receipt.eventId },
149
+ )) as { kind: string; request: Record<string, unknown> };
150
+ expect(claimed.kind).toBe("ready");
151
+ await ctx.runMutation(
152
+ componentRef(f.component, "usageDelivery/steps/save"),
153
+ { ...claimed.request, outcome: { status: "accepted", created: 700 } },
154
+ );
155
+ });
156
+ f.state.nativeApplied = 20;
157
+ }
158
+ const reconcile = () =>
159
+ f.t.action((ctx) =>
160
+ client.usage.reconcileCreditPurchase(ctx as RunCtx, f.purchase, provider),
161
+ );
162
+ return { f, reconcile, invoiceReads: () => invoiceReads };
163
+ }
164
+ it("accepts exactly 100 native credit transactions and rejects an oversized transaction proof", async () => {
165
+ expect(await (await setup(100)).reconcile()).toMatchObject({
166
+ status: "available",
167
+ value: { backing: "sufficient" },
168
+ });
169
+ await expect((await setup(101)).reconcile()).rejects.toThrow(
170
+ /budget|limit|unavailable/i,
171
+ );
172
+ });
173
+ it("proves ten original credit-funded invoice applications and holds an eleventh without guessing", async () => {
174
+ const exact = await setup(11, true);
175
+ const observed = await exact.reconcile();
176
+ expect(observed).toMatchObject({
177
+ status: "available",
178
+ value: { reason: null, backing: "sufficient", applied: 20 },
179
+ });
180
+ expect(exact.invoiceReads()).toBe(10);
181
+ const overflow = await setup(12, true);
182
+ expect(await overflow.reconcile()).toMatchObject({
183
+ status: "available",
184
+ value: { backing: "held", reason: "invoice_provenance_unavailable" },
185
+ });
186
+ expect(overflow.invoiceReads()).toBe(0);
187
+ });
@@ -200,3 +200,77 @@ it("cancels an unpaid original purchase and never recreates its payment intent",
200
200
  ),
201
201
  ).toHaveLength(1);
202
202
  });
203
+
204
+ it("rejects captured credit purchases whose payment or charge uses a foreign mapped Customer", async () => {
205
+ for (const field of ["paymentCustomer", "chargeCustomer"] as const) {
206
+ const f = creditFixture();
207
+ await f.ready();
208
+ await f.t.action((ctx) =>
209
+ ensureCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
210
+ );
211
+ f.state.paid = true;
212
+ f.state[field] = "cus_other";
213
+ await expect(
214
+ f.t.action((ctx) =>
215
+ observeCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
216
+ ),
217
+ ).rejects.toThrow(/scope|identity|verified/i);
218
+ expect(
219
+ f.calls.filter(
220
+ (c) => c.path === "/v1/billing/credit_grants" && c.method === "POST",
221
+ ),
222
+ ).toHaveLength(0);
223
+ }
224
+ });
225
+
226
+ it("rejects adoption of a paid grant whose mapped Customer differs from its original payer binding", async () => {
227
+ const f = creditFixture();
228
+ await f.ready();
229
+ await f.t.action((ctx) =>
230
+ ensureCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
231
+ );
232
+ f.state.paid = true;
233
+ let failed = false;
234
+ await expect(
235
+ f.t.action((ctx) =>
236
+ observeCreditPurchase(
237
+ f.stripe,
238
+ f.component,
239
+ {
240
+ runQuery: ctx.runQuery,
241
+ runAction: ctx.runAction,
242
+ runMutation: async (
243
+ reference: Parameters<NonNullable<RunCtx["runMutation"]>>[0],
244
+ args: Record<string, unknown>,
245
+ ) => {
246
+ if (
247
+ String(
248
+ (reference as unknown as Record<symbol, string>)[
249
+ Symbol.for("toReferencePath")
250
+ ],
251
+ ).endsWith("/usageCredits/mutations/pinGrant") &&
252
+ !failed
253
+ ) {
254
+ failed = true;
255
+ throw new Error("simulated persistence failure");
256
+ }
257
+ return ctx.runMutation(reference, args);
258
+ },
259
+ } as RunCtx,
260
+ f.purchase,
261
+ ),
262
+ ),
263
+ ).rejects.toThrow();
264
+ expect(f.state.grant).toBeDefined();
265
+ f.state.grant!.customer = "cus_other";
266
+ await expect(
267
+ f.t.action((ctx) =>
268
+ observeCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
269
+ ),
270
+ ).rejects.toThrow(/grant|identity/i);
271
+ expect(
272
+ f.calls.filter(
273
+ (c) => c.path === "/v1/billing/credit_grants" && c.method === "POST",
274
+ ),
275
+ ).toHaveLength(1);
276
+ });
@@ -15,6 +15,7 @@ import { grantCreditProof } from "./creditProofs.js";
15
15
  import {
16
16
  creditCall,
17
17
  creditCreateWindow,
18
+ nativeCustomerId,
18
19
  creditRequire,
19
20
  discoverCredit,
20
21
  paymentIdentity,
@@ -191,6 +192,7 @@ function grantProof(
191
192
  creditRequire(
192
193
  grant.object === "billing.credit_grant" &&
193
194
  grant.customer_account === terms.scope.customerAccount &&
195
+ nativeCustomerId(grant.customer) === terms.binding.stripeCustomerId &&
194
196
  grant.livemode === terms.scope.livemode &&
195
197
  grant.metadata?.bsUsageCredit === key &&
196
198
  grant.category === "paid" &&
@@ -11,6 +11,7 @@ import {
11
11
  } from "./creditTerms.js";
12
12
  import {
13
13
  creditCall,
14
+ nativeCustomerId,
14
15
  creditRequire,
15
16
  verifyCreditRealm,
16
17
  paymentIdentity,
@@ -29,8 +30,7 @@ export async function reconcileCreditPurchase(
29
30
  input: UsageCreditPurchaseOptions,
30
31
  ) {
31
32
  return creditCall(async () => {
32
- const terms = creditPurchaseTerms(input),
33
- startedAt = Date.now();
33
+ const terms = creditPurchaseTerms(input);
34
34
  let source = await findCreditPurchase(component, ctx, input);
35
35
  if (!source.row.creditGrantId) {
36
36
  await observeCreditPurchase(stripe, component, ctx, input);
@@ -43,6 +43,12 @@ export async function reconcileCreditPurchase(
43
43
  reason: "credit_purchase_not_ready",
44
44
  retryable: true,
45
45
  };
46
+ const proofStartedAt = Date.now();
47
+ const startedAt = (await runMutationOrThrow(
48
+ ctx,
49
+ componentRef(component, "usageCredits/mutations/beginObservation"),
50
+ { inputJson: JSON.stringify(input) },
51
+ )) as number;
46
52
  await verifyCreditRealm(stripe, terms, false);
47
53
  const payment = await stripe.paymentIntents.retrieve(
48
54
  purchase.paymentIntentId,
@@ -76,6 +82,8 @@ export async function reconcileCreditPurchase(
76
82
  creditRequire(
77
83
  nativeGrant.id === purchase.creditGrantId &&
78
84
  nativeGrant.customer_account === terms.scope.customerAccount &&
85
+ nativeCustomerId(nativeGrant.customer) ===
86
+ terms.binding.stripeCustomerId &&
79
87
  nativeGrant.livemode === terms.scope.livemode &&
80
88
  nativeGrant.metadata?.bsUsageCredit === purchase.key &&
81
89
  nativeGrant.amount.monetary?.value === terms.amount &&
@@ -114,6 +122,12 @@ export async function reconcileCreditPurchase(
114
122
  available.currency === ledger.currency,
115
123
  "Native credit summary currency mismatch",
116
124
  );
125
+ creditRequire(
126
+ Array.isArray(transactions.data) &&
127
+ transactions.data.length <= 100 &&
128
+ typeof transactions.has_more === "boolean",
129
+ "Native credit transaction proof budget exceeded",
130
+ );
117
131
  let granted = 0,
118
132
  applied = 0,
119
133
  expired = 0,
@@ -200,12 +214,13 @@ export async function reconcileCreditPurchase(
200
214
  inputJson: JSON.stringify(input),
201
215
  proofJson: JSON.stringify(proof),
202
216
  startedAt,
217
+ proofStartedAt,
203
218
  },
204
219
  )) as string;
205
220
  const result = JSON.parse(resultJson) as UsageCreditReconciliation;
206
221
  return {
207
222
  status: "available" as const,
208
- observedAt: Math.floor(startedAt / 1000),
223
+ observedAt: Math.floor(proofStartedAt / 1000),
209
224
  value: result,
210
225
  };
211
226
  });
@@ -36,6 +36,7 @@ export function creditFixture(
36
36
  processingFee: 1,
37
37
  paymentCustomer: "cus_buyer",
38
38
  chargeCustomer: "cus_buyer",
39
+ summaryCustomer: "cus_buyer",
39
40
  failGrant: false,
40
41
  wrongPayer: false,
41
42
  paymentId: "pi_topup1",
@@ -81,7 +82,7 @@ export function creditFixture(
81
82
  });
82
83
  if (path === "/v1/billing/credit_balance_summary")
83
84
  return response({
84
- customer: "cus_buyer",
85
+ customer: state.summaryCustomer,
85
86
  customer_account: "acct_buyer",
86
87
  livemode: false,
87
88
  balances: [
@@ -108,3 +108,6 @@ export type { UsageInvoiceSettlementOptions } from "./settlement.js";
108
108
  export type { UsageCreditRevenue } from "./creditRevenue.js";
109
109
 
110
110
  export type { UsageCreditSettlementOptions } from "./creditSettlement.js";
111
+
112
+ export type { UsageEventView } from "./client.js";
113
+ export type { UsageCreditReconciliation } from "./creditObservation.js";
@@ -11,6 +11,7 @@ import {
11
11
  } from "./subscriptionTerms.js";
12
12
  import {
13
13
  subscriptionCall,
14
+ beginSubscriptionObservation,
14
15
  UsageSubscriptionError,
15
16
  verifySubscriptionRealm,
16
17
  } from "./subscriptionProvider.js";
@@ -21,8 +22,8 @@ export async function changeManagedCancellation(
21
22
  row: Doc<"usageSubscriptionIntents">,
22
23
  input: { operationId: string; cancelAtPeriodEnd: boolean },
23
24
  ): Promise<UsageSubscriptionView> {
24
- const terms = subscriptionTerms(JSON.parse(row.termsJson)),
25
- startedAt = Date.now();
25
+ const terms = subscriptionTerms(JSON.parse(row.termsJson));
26
+ const startedAt = await beginSubscriptionObservation(component, ctx, row.key);
26
27
  return subscriptionCall(async () => {
27
28
  if (!row.providerId)
28
29
  throw new UsageSubscriptionError(
@@ -15,6 +15,7 @@ import {
15
15
  verifySubscriptionPrices,
16
16
  discoverSubscription,
17
17
  saveSubscription,
18
+ beginSubscriptionObservation,
18
19
  } from "./subscriptionProvider.js";
19
20
  export function managedCheckoutParams(
20
21
  terms: UsageSubscriptionTerms,
@@ -79,12 +80,16 @@ export async function ensureManagedCheckout(
79
80
  ctx: RunCtx,
80
81
  input: UsageSubscriptionOptions,
81
82
  ) {
82
- const terms = subscriptionTerms(input),
83
- startedAt = Date.now();
83
+ const terms = subscriptionTerms(input);
84
84
  const params = managedCheckoutParams(terms, "pending");
85
85
  return subscriptionCall(async () => {
86
86
  await verifySubscriptionRealm(stripe, terms);
87
87
  const row = await prepareSubscription(component, ctx, terms, "checkout");
88
+ const startedAt = await beginSubscriptionObservation(
89
+ component,
90
+ ctx,
91
+ row.key,
92
+ );
88
93
  await discoverSubscription(stripe, terms, row.key);
89
94
  let session = row.checkoutId
90
95
  ? await stripe.checkout.sessions.retrieve(row.checkoutId)
@@ -1,4 +1,4 @@
1
- import { expect, it } from "vitest";
1
+ import { afterEach, expect, it, vi } from "vitest";
2
2
  import { BetterStripe } from "../index.js";
3
3
  import type { RunCtx } from "../helpers.js";
4
4
  import { fixture } from "./subscriptionTransport.fixtures.js";
@@ -314,3 +314,62 @@ it("records terminal cancellation refusal without leaving a lock that prevents c
314
314
  ),
315
315
  ).toMatchObject({ retired: true });
316
316
  });
317
+
318
+ afterEach(() => vi.useRealTimers());
319
+ it("orders concurrent same-clock native refreshes and returns the retained newer projection", async () => {
320
+ vi.useFakeTimers();
321
+ vi.setSystemTime(700000);
322
+ let block = false,
323
+ signal!: () => void,
324
+ release!: () => void;
325
+ const entered = new Promise<void>((resolve) => {
326
+ signal = resolve;
327
+ }),
328
+ gate = new Promise<void>((resolve) => {
329
+ release = resolve;
330
+ });
331
+ const f = fixture(false, false, async (input, init) => {
332
+ if (
333
+ block &&
334
+ new URL(input).pathname === "/v1/subscriptions/sub_calls" &&
335
+ (init?.method ?? "GET") === "GET"
336
+ ) {
337
+ block = false;
338
+ signal();
339
+ await gate;
340
+ return new Response(JSON.stringify(nativeSubscription()), {
341
+ headers: { "content-type": "application/json" },
342
+ });
343
+ }
344
+ });
345
+ const client = new BetterStripe(f.component),
346
+ options = {
347
+ stripeSecretKey: "sk_test_subscription",
348
+ httpClient: f.httpClient,
349
+ };
350
+ await f.t.action((ctx) =>
351
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
352
+ );
353
+ block = true;
354
+ const older = f.t.action((ctx) =>
355
+ client.usage.observeSubscription(ctx as RunCtx, ref, options),
356
+ );
357
+ await entered;
358
+ f.state.native!.items.data.forEach((item) => {
359
+ item.current_period_start = 1200;
360
+ item.current_period_end = 1800;
361
+ });
362
+ const newer = await f.t.action((ctx) =>
363
+ client.usage.observeSubscription(ctx as RunCtx, ref, options),
364
+ );
365
+ release();
366
+ expect(newer.bindings[0].subscription.period.start).toBe(1200);
367
+ expect((await older).bindings[0].subscription.period.start).toBe(1200);
368
+ expect(
369
+ await f.t.query((ctx) => client.usage.getSubscription(ctx as RunCtx, ref)),
370
+ ).toMatchObject({
371
+ value: {
372
+ bindings: [{ subscription: { period: { start: 1200, end: 1800 } } }],
373
+ },
374
+ });
375
+ });
@@ -11,6 +11,7 @@ import {
11
11
  } from "./subscriptionTerms.js";
12
12
  import {
13
13
  saveSubscription,
14
+ beginSubscriptionObservation,
14
15
  subscriptionCall,
15
16
  UsageSubscriptionError,
16
17
  verifySubscriptionRealm,
@@ -51,8 +52,8 @@ export async function refreshManagedSubscription(
51
52
  ctx: RunCtx,
52
53
  row: Doc<"usageSubscriptionIntents">,
53
54
  ) {
54
- const terms = subscriptionTerms(JSON.parse(row.termsJson)),
55
- startedAt = Date.now();
55
+ const terms = subscriptionTerms(JSON.parse(row.termsJson));
56
+ const startedAt = await beginSubscriptionObservation(component, ctx, row.key);
56
57
  return subscriptionCall(async () => {
57
58
  if (!row.providerId)
58
59
  throw new UsageSubscriptionError(
@@ -159,6 +159,17 @@ export async function discoverSubscription(
159
159
  "Native subscription inventory exceeds bounded history",
160
160
  );
161
161
  }
162
+ export function beginSubscriptionObservation(
163
+ component: Component,
164
+ ctx: RunCtx,
165
+ key: string,
166
+ ) {
167
+ return runMutationOrThrow(
168
+ ctx,
169
+ componentRef(component, "usageSubscriptions/mutations/beginObservation"),
170
+ { key },
171
+ ) as Promise<number>;
172
+ }
162
173
  export async function saveSubscription(
163
174
  component: Component,
164
175
  ctx: RunCtx,
@@ -174,7 +185,16 @@ export async function saveSubscription(
174
185
  componentRef(component, "usageSubscriptions/mutations/save"),
175
186
  { key, nativeJson: JSON.stringify(evidence), startedAt },
176
187
  );
177
- return view;
188
+ const retained = (await ctx.runQuery(
189
+ componentRef(component, "usageSubscriptions/queries/lookup"),
190
+ { key },
191
+ )) as Doc<"usageSubscriptionIntents"> | null;
192
+ if (!retained?.viewJson || retained.providerId !== view.subscriptionId)
193
+ throw new UsageSubscriptionError(
194
+ "incompatible_terms",
195
+ "Retained subscription projection unavailable",
196
+ );
197
+ return JSON.parse(retained.viewJson) as ReturnType<typeof subscriptionView>;
178
198
  }
179
199
  export async function prepareSubscription(
180
200
  component: Component,
@@ -194,8 +214,7 @@ export async function ensureManagedSubscription(
194
214
  ctx: RunCtx,
195
215
  input: UsageSubscriptionOptions,
196
216
  ) {
197
- const terms = subscriptionTerms(input),
198
- startedAt = Date.now();
217
+ const terms = subscriptionTerms(input);
199
218
  return subscriptionCall(async () => {
200
219
  if (terms.collection.method === "checkout")
201
220
  throw new UsageSubscriptionError(
@@ -204,6 +223,11 @@ export async function ensureManagedSubscription(
204
223
  );
205
224
  await verifySubscriptionRealm(stripe, terms);
206
225
  const row = await prepareSubscription(component, ctx, terms, "direct");
226
+ const startedAt = await beginSubscriptionObservation(
227
+ component,
228
+ ctx,
229
+ row.key,
230
+ );
207
231
  if (!row.providerId) await verifySubscriptionPrices(stripe, terms);
208
232
  let sub = row.providerId
209
233
  ? await stripe.subscriptions.retrieve(row.providerId)