@fantastic.dev/better-stripe 0.59.0 → 0.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +676 -50
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +322 -9
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +644 -18
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +338 -25
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/paymentSource/resolver.d.ts +12 -1
  14. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  15. package/dist/client/paymentSource/resolver.fixtures.d.ts +220 -0
  16. package/dist/client/paymentSource/resolver.fixtures.d.ts.map +1 -0
  17. package/dist/client/paymentSource/resolver.fixtures.js +189 -0
  18. package/dist/client/paymentSource/resolver.fixtures.js.map +1 -0
  19. package/dist/client/paymentSource/resolver.js +28 -3
  20. package/dist/client/paymentSource/resolver.js.map +1 -1
  21. package/dist/client/settlement/execution.d.ts +25 -0
  22. package/dist/client/settlement/execution.d.ts.map +1 -1
  23. package/dist/client/settlement/execution.js +2 -0
  24. package/dist/client/settlement/execution.js.map +1 -1
  25. package/dist/client/usage/catalogPrices.d.ts +1 -1
  26. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  27. package/dist/client/usage/catalogPrices.js +4 -4
  28. package/dist/client/usage/catalogPrices.js.map +1 -1
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.js +2 -2
  31. package/dist/client/usage/creditCapacity.d.ts.map +1 -1
  32. package/dist/client/usage/creditCapacity.js +7 -1
  33. package/dist/client/usage/creditCapacity.js.map +1 -1
  34. package/dist/client/usage/creditClient.d.ts +3 -0
  35. package/dist/client/usage/creditClient.d.ts.map +1 -1
  36. package/dist/client/usage/creditDelivery.d.ts.map +1 -1
  37. package/dist/client/usage/creditDelivery.js +4 -1
  38. package/dist/client/usage/creditDelivery.js.map +1 -1
  39. package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
  40. package/dist/client/usage/creditLifecycle.js +2 -1
  41. package/dist/client/usage/creditLifecycle.js.map +1 -1
  42. package/dist/client/usage/creditNative.d.ts +3 -0
  43. package/dist/client/usage/creditNative.d.ts.map +1 -1
  44. package/dist/client/usage/creditNative.js +3 -0
  45. package/dist/client/usage/creditNative.js.map +1 -1
  46. package/dist/client/usage/creditProvider.d.ts.map +1 -1
  47. package/dist/client/usage/creditProvider.js +2 -1
  48. package/dist/client/usage/creditProvider.js.map +1 -1
  49. package/dist/client/usage/creditRead.d.ts +1 -0
  50. package/dist/client/usage/creditRead.d.ts.map +1 -1
  51. package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
  52. package/dist/client/usage/creditReconciliation.js +11 -3
  53. package/dist/client/usage/creditReconciliation.js.map +1 -1
  54. package/dist/client/usage/creditRevenue.d.ts +22 -0
  55. package/dist/client/usage/creditRevenue.d.ts.map +1 -0
  56. package/dist/client/usage/creditRevenue.js +118 -0
  57. package/dist/client/usage/creditRevenue.js.map +1 -0
  58. package/dist/client/usage/creditSettlement.d.ts +29 -0
  59. package/dist/client/usage/creditSettlement.d.ts.map +1 -0
  60. package/dist/client/usage/creditSettlement.fixtures.d.ts +216 -0
  61. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -0
  62. package/dist/client/usage/creditSettlement.fixtures.js +59 -0
  63. package/dist/client/usage/creditSettlement.fixtures.js.map +1 -0
  64. package/dist/client/usage/creditSettlement.js +70 -0
  65. package/dist/client/usage/creditSettlement.js.map +1 -0
  66. package/dist/client/usage/creditTransport.fixtures.d.ts +8 -1
  67. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  68. package/dist/client/usage/creditTransport.fixtures.js +27 -5
  69. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  70. package/dist/client/usage/index.d.ts +4 -0
  71. package/dist/client/usage/index.d.ts.map +1 -1
  72. package/dist/client/usage/invoiceSale.d.ts +22 -0
  73. package/dist/client/usage/invoiceSale.d.ts.map +1 -0
  74. package/dist/client/usage/invoiceSale.fixtures.d.ts +285 -0
  75. package/dist/client/usage/invoiceSale.fixtures.d.ts.map +1 -0
  76. package/dist/client/usage/invoiceSale.fixtures.js +104 -0
  77. package/dist/client/usage/invoiceSale.fixtures.js.map +1 -0
  78. package/dist/client/usage/invoiceSale.js +117 -0
  79. package/dist/client/usage/invoiceSale.js.map +1 -0
  80. package/dist/client/usage/observationClient.d.ts +2 -2
  81. package/dist/client/usage/observationClient.d.ts.map +1 -1
  82. package/dist/client/usage/settlement.d.ts +32 -0
  83. package/dist/client/usage/settlement.d.ts.map +1 -0
  84. package/dist/client/usage/settlement.js +60 -0
  85. package/dist/client/usage/settlement.js.map +1 -0
  86. package/dist/client/usage/settlementClient.d.ts +51 -0
  87. package/dist/client/usage/settlementClient.d.ts.map +1 -0
  88. package/dist/client/usage/settlementClient.js +35 -0
  89. package/dist/client/usage/settlementClient.js.map +1 -0
  90. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
  91. package/dist/client/usage/subscriptionCancellation.js +3 -2
  92. package/dist/client/usage/subscriptionCancellation.js.map +1 -1
  93. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
  94. package/dist/client/usage/subscriptionCheckout.js +3 -2
  95. package/dist/client/usage/subscriptionCheckout.js.map +1 -1
  96. package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
  97. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
  98. package/dist/client/usage/subscriptionLifecycle.js +3 -2
  99. package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
  100. package/dist/client/usage/subscriptionProvider.d.ts +2 -0
  101. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
  102. package/dist/client/usage/subscriptionProvider.js +9 -2
  103. package/dist/client/usage/subscriptionProvider.js.map +1 -1
  104. package/dist/component/_generated/component.d.ts +146 -0
  105. package/dist/component/_generated/component.d.ts.map +1 -1
  106. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  107. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  108. package/dist/component/earnings/triggers.d.ts +172 -12
  109. package/dist/component/earnings/triggers.d.ts.map +1 -1
  110. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -1
  111. package/dist/component/financialObservations/settlementHelpers.js +2 -0
  112. package/dist/component/financialObservations/settlementHelpers.js.map +1 -1
  113. package/dist/component/recoveryWorkflow/helpers.d.ts +25 -0
  114. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  115. package/dist/component/recoveryWorkflow/mutations.d.ts +25 -0
  116. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  117. package/dist/component/recoveryWorkflow/queries.d.ts +50 -0
  118. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  119. package/dist/component/recoveryWorkflow/schema.d.ts +566 -10
  120. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  121. package/dist/component/schema.d.ts +322 -9
  122. package/dist/component/settlement/mutations.d.ts +50 -0
  123. package/dist/component/settlement/mutations.d.ts.map +1 -1
  124. package/dist/component/settlement/mutations.js +8 -1
  125. package/dist/component/settlement/mutations.js.map +1 -1
  126. package/dist/component/settlement/queries.d.ts +25 -0
  127. package/dist/component/settlement/queries.d.ts.map +1 -1
  128. package/dist/component/settlement/schema.d.ts +128 -1
  129. package/dist/component/settlement/schema.d.ts.map +1 -1
  130. package/dist/component/settlement/schema.js +22 -0
  131. package/dist/component/settlement/schema.js.map +1 -1
  132. package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
  133. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
  134. package/dist/component/usage/allowance.fixtures.js +67 -0
  135. package/dist/component/usage/allowance.fixtures.js.map +1 -0
  136. package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
  137. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
  138. package/dist/component/usageCredits/accounting.fixtures.js +89 -0
  139. package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
  140. package/dist/component/usageCredits/helpers.d.ts +7 -0
  141. package/dist/component/usageCredits/helpers.d.ts.map +1 -1
  142. package/dist/component/usageCredits/helpers.js +5 -0
  143. package/dist/component/usageCredits/helpers.js.map +1 -1
  144. package/dist/component/usageCredits/mutations.d.ts +6 -0
  145. package/dist/component/usageCredits/mutations.d.ts.map +1 -1
  146. package/dist/component/usageCredits/mutations.js +70 -7
  147. package/dist/component/usageCredits/mutations.js.map +1 -1
  148. package/dist/component/usageCredits/purchase.d.ts +1 -0
  149. package/dist/component/usageCredits/purchase.d.ts.map +1 -1
  150. package/dist/component/usageCredits/queries.d.ts +10 -0
  151. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  152. package/dist/component/usageCredits/schema.d.ts +24 -4
  153. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  154. package/dist/component/usageCredits/schema.js +4 -0
  155. package/dist/component/usageCredits/schema.js.map +1 -1
  156. package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
  157. package/dist/component/usageSubscriptions/history.js +3 -1
  158. package/dist/component/usageSubscriptions/history.js.map +1 -1
  159. package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
  160. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
  161. package/dist/component/usageSubscriptions/mutations.js +19 -0
  162. package/dist/component/usageSubscriptions/mutations.js.map +1 -1
  163. package/dist/component/usageSubscriptions/queries.d.ts +2 -0
  164. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
  165. package/dist/component/usageSubscriptions/schema.d.ts +7 -2
  166. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
  167. package/dist/component/usageSubscriptions/schema.js +1 -0
  168. package/dist/component/usageSubscriptions/schema.js.map +1 -1
  169. package/docs/README.md +4 -0
  170. package/docs/settlement.md +4 -0
  171. package/docs/usage-credits.md +6 -1
  172. package/docs/usage-security.md +130 -0
  173. package/docs/usage-settlement.md +162 -0
  174. package/package.json +3 -1
  175. package/src/client/index.ts +9 -0
  176. package/src/client/paymentSource/resolver.fixtures.ts +216 -0
  177. package/src/client/paymentSource/resolver.test.ts +11 -207
  178. package/src/client/paymentSource/resolver.ts +54 -2
  179. package/src/client/settlement/execution.ts +24 -0
  180. package/src/client/usage/catalogPrices.ts +4 -2
  181. package/src/client/usage/client.ts +2 -2
  182. package/src/client/usage/creditBackingIsolation.test.ts +110 -0
  183. package/src/client/usage/creditCapacity.test.ts +80 -1
  184. package/src/client/usage/creditCapacity.ts +10 -1
  185. package/src/client/usage/creditDelivery.ts +4 -0
  186. package/src/client/usage/creditLifecycle.ts +2 -0
  187. package/src/client/usage/creditNative.ts +5 -0
  188. package/src/client/usage/creditProofBounds.test.ts +187 -0
  189. package/src/client/usage/creditProvider.test.ts +74 -0
  190. package/src/client/usage/creditProvider.ts +2 -0
  191. package/src/client/usage/creditReconciliation.ts +18 -3
  192. package/src/client/usage/creditRevenue.test.ts +105 -0
  193. package/src/client/usage/creditRevenue.ts +163 -0
  194. package/src/client/usage/creditSettlement.fixtures.ts +70 -0
  195. package/src/client/usage/creditSettlement.test.ts +66 -0
  196. package/src/client/usage/creditSettlement.ts +94 -0
  197. package/src/client/usage/creditSettlementRecovery.test.ts +173 -0
  198. package/src/client/usage/creditTransport.fixtures.ts +31 -5
  199. package/src/client/usage/index.ts +9 -0
  200. package/src/client/usage/invoiceSale.fixtures.ts +103 -0
  201. package/src/client/usage/invoiceSale.test.ts +184 -0
  202. package/src/client/usage/invoiceSale.ts +155 -0
  203. package/src/client/usage/settlement.test.ts +179 -0
  204. package/src/client/usage/settlement.ts +81 -0
  205. package/src/client/usage/settlementClient.ts +84 -0
  206. package/src/client/usage/subscriptionCancellation.ts +3 -2
  207. package/src/client/usage/subscriptionCheckout.ts +7 -2
  208. package/src/client/usage/subscriptionClient.test.ts +60 -1
  209. package/src/client/usage/subscriptionLifecycle.ts +3 -2
  210. package/src/client/usage/subscriptionProvider.ts +27 -3
  211. package/src/component/_generated/component.ts +150 -1
  212. package/src/component/financialObservations/settlementHelpers.ts +2 -0
  213. package/src/component/settlement/mutations.ts +10 -1
  214. package/src/component/settlement/schema.ts +26 -0
  215. package/src/component/settlement/settlement-claims.test.ts +54 -0
  216. package/src/component/usage/allowance.fixtures.ts +77 -0
  217. package/src/component/usage/allowance.test.ts +3 -66
  218. package/src/component/usage/allowanceBounds.test.ts +79 -0
  219. package/src/component/usage/historyIsolation.test.ts +124 -0
  220. package/src/component/usageCredits/accounting.fixtures.ts +96 -0
  221. package/src/component/usageCredits/accounting.test.ts +176 -82
  222. package/src/component/usageCredits/freshness.test.ts +33 -0
  223. package/src/component/usageCredits/helpers.ts +8 -0
  224. package/src/component/usageCredits/mutations.ts +83 -5
  225. package/src/component/usageCredits/quotas.test.ts +63 -0
  226. package/src/component/usageCredits/schema.ts +10 -0
  227. package/src/component/usageSubscriptions/history.test.ts +57 -0
  228. package/src/component/usageSubscriptions/history.ts +3 -1
  229. package/src/component/usageSubscriptions/mutations.ts +23 -0
  230. package/src/component/usageSubscriptions/schema.ts +1 -0
@@ -48,6 +48,15 @@ const integer = (value: number) => Number.isSafeInteger(value) && value >= 0;
48
48
  export async function resolveVerifiedPaymentSource(
49
49
  stripe: Stripe,
50
50
  input: VerifiedPaymentSourceOptions,
51
+ eligibility?: {
52
+ requirePayable: true;
53
+ customerId: string;
54
+ invoiceLine?: {
55
+ id: string;
56
+ subscriptionItemId: string;
57
+ period: { start: number; end: number };
58
+ };
59
+ },
51
60
  ): Promise<FinancialOutcome<VerifiedPaymentSource>> {
52
61
  const parsed = paymentSourceOptions.safeParse(input);
53
62
  if (!parsed.success) return reject("invalid_scope");
@@ -120,6 +129,26 @@ export async function resolveVerifiedPaymentSource(
120
129
  identity(),
121
130
  );
122
131
  const customerAccountId = payment.customer_account!;
132
+ if (eligibility) {
133
+ requireSource(
134
+ charge.amount_refunded === 0 &&
135
+ charge.disputed === false &&
136
+ charge.refunded === false,
137
+ reject("payment_not_payable"),
138
+ );
139
+ requireSource(
140
+ objectId(payment.customer) === eligibility.customerId &&
141
+ objectId(charge.customer) === eligibility.customerId,
142
+ identity(),
143
+ );
144
+ requireSource(
145
+ !payment.transfer_data &&
146
+ !payment.on_behalf_of &&
147
+ !payment.application_fee_amount &&
148
+ !charge.transfer,
149
+ reject("unsupported_source"),
150
+ );
151
+ }
123
152
  const balanceRef = charge.balance_transaction;
124
153
  if (!balanceRef)
125
154
  return { status: "not_ready", reason: "fee_pending", retryable: true };
@@ -201,6 +230,11 @@ export async function resolveVerifiedPaymentSource(
201
230
  invoice.livemode === payment.livemode,
202
231
  identity(),
203
232
  );
233
+ if (eligibility)
234
+ requireSource(
235
+ objectId(invoice.customer) === eligibility.customerId,
236
+ identity(),
237
+ );
204
238
  requireSource(
205
239
  invoice.currency === opts.currency,
206
240
  reject("currency_mismatch"),
@@ -269,6 +303,11 @@ export async function resolveVerifiedPaymentSource(
269
303
  {},
270
304
  requestOptions,
271
305
  );
306
+ if (eligibility)
307
+ requireSource(
308
+ objectId(subscription.customer) === eligibility.customerId,
309
+ identity(),
310
+ );
272
311
  requireSource(
273
312
  subscription.object === "subscription" &&
274
313
  subscription.id === subscriptionId &&
@@ -297,11 +336,24 @@ export async function resolveVerifiedPaymentSource(
297
336
  requireSource(
298
337
  integer(line.amount) &&
299
338
  line.amount > 0 &&
300
- Number.isSafeInteger(line.quantity) &&
301
- line.quantity! > 0,
339
+ (line.quantity_decimal != null
340
+ ? /^\d{1,30}(\.\d{1,12})?$/.test(line.quantity_decimal.toString()) &&
341
+ /[1-9]/.test(line.quantity_decimal.toString())
342
+ : Number.isSafeInteger(line.quantity) && line.quantity! > 0),
302
343
  reject("unsupported_source"),
303
344
  );
304
345
  const parent = line.parent;
346
+ if (eligibility?.invoiceLine) {
347
+ const expected = eligibility.invoiceLine;
348
+ requireSource(
349
+ line.id === expected.id &&
350
+ line.parent?.subscription_item_details?.subscription_item ===
351
+ expected.subscriptionItemId &&
352
+ line.period.start === expected.period.start &&
353
+ line.period.end === expected.period.end,
354
+ identity(),
355
+ );
356
+ }
305
357
  const lineSubscription =
306
358
  parent?.subscription_item_details?.subscription ??
307
359
  parent?.invoice_item_details?.subscription ??
@@ -13,6 +13,28 @@ export type ResolvedSettlement = {
13
13
  sourceChargeId: string;
14
14
  paymentIntentId?: string;
15
15
  sourceInvoiceId?: string;
16
+ usageSource?: {
17
+ stripeAccountId: string;
18
+ customerAccount: string;
19
+ livemode: boolean;
20
+ meterId: string;
21
+ stripePriceId: string;
22
+ stripeProductId: string;
23
+ subscriptionId: string;
24
+ subscriptionItemId: string;
25
+ invoicePaymentId: string;
26
+ period: { start: number; end: number };
27
+ model: "pay_as_you_go" | "included_overage";
28
+ };
29
+ creditSource?: {
30
+ stripeAccountId: string;
31
+ customerAccount: string;
32
+ livemode: boolean;
33
+ purchaseId: string;
34
+ creditGrantId: string;
35
+ stripePriceId: string;
36
+ stripeProductId: string;
37
+ };
16
38
  gross: number;
17
39
  currency: string;
18
40
  processingFee: number;
@@ -53,6 +75,8 @@ export async function executeResolvedTransfers(
53
75
  sourceChargeId: saved.sourceChargeId,
54
76
  paymentIntentId: saved.paymentIntentId,
55
77
  sourceInvoiceId: saved.sourceInvoiceId,
78
+ usageSource: saved.usageSource,
79
+ creditSource: saved.creditSource,
56
80
  gross: saved.gross,
57
81
  currency: saved.currency,
58
82
  processingFee: saved.processingFee,
@@ -83,11 +83,12 @@ function verifyPrice(
83
83
  opts: UsagePriceOptions,
84
84
  rate: string,
85
85
  included: number | undefined,
86
+ requireActive = true,
86
87
  ) {
87
88
  const product =
88
89
  typeof price.product === "string" ? price.product : price.product.id;
89
90
  if (
90
- !price.active ||
91
+ (requireActive && !price.active) ||
91
92
  price.livemode !== opts.scope.livemode ||
92
93
  price.lookup_key !== opts.lookupKey ||
93
94
  product !== opts.stripeProductId ||
@@ -256,6 +257,7 @@ export function verifyPinnedUsagePrice(
256
257
  scope: UsagePriceOptions["scope"],
257
258
  plan: UsagePriceOptions["plan"],
258
259
  meterId: string,
260
+ requireActive = true,
259
261
  ) {
260
262
  const productId =
261
263
  typeof price.product === "string" ? price.product : price.product.id;
@@ -268,5 +270,5 @@ export function verifyPinnedUsagePrice(
268
270
  lookupKey: price.lookup_key,
269
271
  };
270
272
  const { rate, included } = termsFor(opts);
271
- verifyPrice(price, opts, rate, included);
273
+ verifyPrice(price, opts, rate, included, requireActive);
272
274
  }
@@ -1,4 +1,4 @@
1
- import { UsageCorrectionClient } from "./correctionClient.js";
1
+ import { UsageSettlementClient } from "./settlementClient.js";
2
2
  import type { Component, RunCtx } from "../helpers.js";
3
3
  import { runMutationOrThrow } from "../helpers.js";
4
4
  import { componentRef } from "../webhooks/helpers.js";
@@ -46,7 +46,7 @@ function decode({ event, delivery }: StoredView): UsageEventView {
46
46
  };
47
47
  }
48
48
  /** Trusted host facade. Authenticate and authorize each exact scope first. */
49
- export class UsageLedgerClient extends UsageCorrectionClient {
49
+ export class UsageLedgerClient extends UsageSettlementClient {
50
50
  constructor(component: Component) {
51
51
  super(component);
52
52
  }
@@ -0,0 +1,110 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { creditFixture } from "./creditTransport.fixtures.js";
6
+ import { verifyCreditDelivery } from "./creditDelivery.js";
7
+ import type { Doc } from "../../component/_generated/dataModel.js";
8
+ import type { PreparedUsageRecord } from "./records.js";
9
+ afterEach(() => vi.useRealTimers());
10
+ it("rejects a foreign mapped Customer on native grant or summary during reconciliation and delivery", async () => {
11
+ for (const condition of ["grant", "summary"]) {
12
+ const f = creditFixture(),
13
+ client = new BetterStripe(f.component),
14
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
15
+ const view = await f.ready();
16
+ await f.t.action((ctx) =>
17
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
18
+ );
19
+ f.state.paid = true;
20
+ await f.t.action((ctx) =>
21
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
22
+ );
23
+ const event = {
24
+ scope: f.purchase.scope,
25
+ binding: f.purchase.binding,
26
+ sourceEventId: "work1",
27
+ quantity: "6",
28
+ occurredAt: 700,
29
+ },
30
+ subscription = view.bindings[0].subscription;
31
+ const reservation = await f.t.action((ctx) =>
32
+ client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
33
+ );
34
+ const receipt = await f.t.action((ctx) =>
35
+ client.usage.record(ctx as RunCtx, {
36
+ event,
37
+ subscription,
38
+ reservationId: reservation.reservationId,
39
+ }),
40
+ );
41
+ if (condition === "grant") f.state.grant!.customer = "cus_other";
42
+ else f.state.summaryCustomer = "cus_other";
43
+ await expect(
44
+ f.t.action(async (ctx) => {
45
+ const saved = (await ctx.runQuery(
46
+ componentRef(f.component, "usageDelivery/queries/snapshot"),
47
+ { scope: event.scope, eventId: receipt.eventId },
48
+ )) as { event: Doc<"usageEvents"> };
49
+ await verifyCreditDelivery(
50
+ f.stripe,
51
+ f.component,
52
+ ctx as RunCtx,
53
+ saved.event,
54
+ JSON.parse(saved.event.recordJson) as PreparedUsageRecord,
55
+ );
56
+ }),
57
+ ).rejects.toThrow(/scope|identity|reconciliation/i);
58
+ await expect(
59
+ f.t.action((ctx) =>
60
+ client.usage.reconcileCreditPurchase(
61
+ ctx as RunCtx,
62
+ f.purchase,
63
+ options,
64
+ ),
65
+ ),
66
+ ).rejects.toThrow(/identity|scope|mismatch/i);
67
+ }
68
+ });
69
+
70
+ it("rechecks the original mapped Customer immediately before native grant expiration", async () => {
71
+ let checking = false,
72
+ reads = 0,
73
+ expirations = 0;
74
+ const f = creditFixture(async (input, init) => {
75
+ const path = new URL(input).pathname;
76
+ if (path.endsWith("/expire") && init?.method === "POST") expirations++;
77
+ if (
78
+ checking &&
79
+ path === "/v1/billing/credit_grants/credgr_topup1" &&
80
+ ++reads === 2
81
+ )
82
+ return new Response(
83
+ JSON.stringify({ ...f.state.grant, customer: "cus_other" }),
84
+ { headers: { "content-type": "application/json" } },
85
+ );
86
+ });
87
+ const client = new BetterStripe(f.component),
88
+ provider = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
89
+ await f.ready();
90
+ await f.t.action((ctx) =>
91
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, provider),
92
+ );
93
+ f.state.paid = true;
94
+ await f.t.action((ctx) =>
95
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, provider),
96
+ );
97
+ checking = true;
98
+ await expect(
99
+ f.t.action((ctx) =>
100
+ client.usage.prepareCreditRefund(ctx as RunCtx, f.purchase, provider),
101
+ ),
102
+ ).rejects.toThrow(/identity/i);
103
+ expect(reads).toBe(2);
104
+ expect(expirations).toBe(0);
105
+ expect(
106
+ await f.t.action((ctx) =>
107
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
108
+ ),
109
+ ).toMatchObject({ availableQuantity: "0", frozenQuantity: "10" });
110
+ });
@@ -27,7 +27,12 @@ const terms = creditPurchaseTerms({
27
27
  ownership: "issuer",
28
28
  rollover: "retain_original_terms",
29
29
  });
30
- function fixture(ledger: number, more = false, foreign = false) {
30
+ function fixture(
31
+ ledger: number,
32
+ more = false,
33
+ foreign = false,
34
+ mapped = false,
35
+ ) {
31
36
  const methods: string[] = [];
32
37
  const stripe = new Stripe("sk_test_credit_capacity", {
33
38
  httpClient: Stripe.createFetchHttpClient(async (input, init) => {
@@ -39,6 +44,7 @@ function fixture(ledger: number, more = false, foreign = false) {
39
44
  : [
40
45
  {
41
46
  id: "credgr_existing",
47
+ customer: mapped ? "cus_other" : "cus_buyer",
42
48
  customer_account: foreign ? "acct_other" : "acct_buyer",
43
49
  livemode: false,
44
50
  expires_at: null,
@@ -48,6 +54,7 @@ function fixture(ledger: number, more = false, foreign = false) {
48
54
  has_more: more,
49
55
  }
50
56
  : {
57
+ customer: mapped ? "cus_other" : "cus_buyer",
51
58
  customer_account: "acct_buyer",
52
59
  livemode: false,
53
60
  balances: [
@@ -81,3 +88,75 @@ it("permits verified depleted grants but holds incomplete or foreign native inve
81
88
  verifyNativeCreditCapacity(fixture(0, false, true).stripe, terms, 1),
82
89
  ).rejects.toThrow(/scope/i);
83
90
  });
91
+
92
+ it("rejects foreign mapped Customer inventory even when its Accounts v2 payer matches", async () => {
93
+ await expect(
94
+ verifyNativeCreditCapacity(fixture(0, false, false, true).stripe, terms, 1),
95
+ ).rejects.toThrow(/scope|customer/i);
96
+ });
97
+
98
+ function inventory(total: number, unexpired: number, size = 100) {
99
+ let lists = 0,
100
+ balances = 0;
101
+ const stripe = new Stripe("sk_test_inventory_bounds", {
102
+ maxNetworkRetries: 0,
103
+ httpClient: Stripe.createFetchHttpClient(async (input) => {
104
+ const url = new URL(String(input));
105
+ let value: unknown;
106
+ if (url.pathname.endsWith("/credit_grants")) {
107
+ lists++;
108
+ const cursor = url.searchParams.get("starting_after");
109
+ const start = cursor
110
+ ? Number(cursor.slice(cursor.lastIndexOf("_") + 1)) + 1
111
+ : 0;
112
+ const count = Math.min(size, total - start);
113
+ value = {
114
+ data: Array.from({ length: count }, (_, offset) => ({
115
+ id: `credgr_${start + offset}`,
116
+ customer_account: "acct_buyer",
117
+ customer: "cus_buyer",
118
+ livemode: false,
119
+ voided_at: start + offset < unexpired ? null : 1,
120
+ expires_at: null,
121
+ })),
122
+ has_more: start + count < total,
123
+ };
124
+ } else {
125
+ balances++;
126
+ value = {
127
+ customer_account: "acct_buyer",
128
+ customer: "cus_buyer",
129
+ livemode: false,
130
+ balances: [{ ledger_balance: { monetary: { value: 0 } } }],
131
+ };
132
+ }
133
+ return new Response(JSON.stringify(value), {
134
+ headers: { "content-type": "application/json" },
135
+ });
136
+ }),
137
+ });
138
+ return { stripe, counts: () => ({ lists, balances }) };
139
+ }
140
+ it("accepts exact native inventory and balance-read bounds and holds one-over proofs", async () => {
141
+ const exact = inventory(1000, 0);
142
+ await verifyNativeCreditCapacity(exact.stripe, terms, 1);
143
+ expect(exact.counts()).toEqual({ lists: 10, balances: 0 });
144
+ const overflow = inventory(1001, 0);
145
+ await expect(
146
+ verifyNativeCreditCapacity(overflow.stripe, terms, 1),
147
+ ).rejects.toThrow(/incomplete/i);
148
+ expect(overflow.counts()).toEqual({ lists: 10, balances: 0 });
149
+ const balances = inventory(100, 100);
150
+ await verifyNativeCreditCapacity(balances.stripe, terms, 1);
151
+ expect(balances.counts()).toEqual({ lists: 1, balances: 100 });
152
+ const excessive = inventory(101, 101);
153
+ await expect(
154
+ verifyNativeCreditCapacity(excessive.stripe, terms, 1),
155
+ ).rejects.toThrow(/budget/i);
156
+ expect(excessive.counts()).toEqual({ lists: 2, balances: 0 });
157
+ });
158
+ it("rejects native inventory pages exceeding the requested proof size", async () => {
159
+ await expect(
160
+ verifyNativeCreditCapacity(inventory(101, 0, 101).stripe, terms, 1),
161
+ ).rejects.toThrow(/budget|page|inventory/i);
162
+ });
@@ -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
+ });