@fantastic.dev/better-stripe 0.38.0 → 0.40.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 (167) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/MIGRATION.md +9 -0
  3. package/README.md +21 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +506 -2
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +253 -1
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +506 -2
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +253 -1
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  13. package/dist/client/costRecovery-invoices.js +3 -5
  14. package/dist/client/costRecovery-invoices.js.map +1 -1
  15. package/dist/client/costRecovery.d.ts +18 -0
  16. package/dist/client/costRecovery.d.ts.map +1 -1
  17. package/dist/client/costRecovery.js +4 -0
  18. package/dist/client/costRecovery.js.map +1 -1
  19. package/dist/client/index.d.ts +4 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +3 -2
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/paymentSource/client.d.ts +21 -0
  24. package/dist/client/paymentSource/client.d.ts.map +1 -0
  25. package/dist/client/paymentSource/client.js +8 -0
  26. package/dist/client/paymentSource/client.js.map +1 -0
  27. package/dist/client/paymentSource/contracts.d.ts +30 -0
  28. package/dist/client/paymentSource/contracts.d.ts.map +1 -0
  29. package/dist/client/paymentSource/contracts.js +16 -0
  30. package/dist/client/paymentSource/contracts.js.map +1 -0
  31. package/dist/client/paymentSource/economics.d.ts +12 -0
  32. package/dist/client/paymentSource/economics.d.ts.map +1 -0
  33. package/dist/client/paymentSource/economics.js +13 -0
  34. package/dist/client/paymentSource/economics.js.map +1 -0
  35. package/dist/client/paymentSource/funding.d.ts +10 -0
  36. package/dist/client/paymentSource/funding.d.ts.map +1 -0
  37. package/dist/client/paymentSource/funding.js +12 -0
  38. package/dist/client/paymentSource/funding.js.map +1 -0
  39. package/dist/client/paymentSource/history.d.ts +13 -0
  40. package/dist/client/paymentSource/history.d.ts.map +1 -0
  41. package/dist/client/paymentSource/history.js +41 -0
  42. package/dist/client/paymentSource/history.js.map +1 -0
  43. package/dist/client/paymentSource/resolver.d.ts +6 -0
  44. package/dist/client/paymentSource/resolver.d.ts.map +1 -0
  45. package/dist/client/paymentSource/resolver.js +222 -0
  46. package/dist/client/paymentSource/resolver.js.map +1 -0
  47. package/dist/client/processingCostDeficit/index.d.ts +27 -0
  48. package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
  49. package/dist/client/processingCostDeficit/index.js +54 -0
  50. package/dist/client/processingCostDeficit/index.js.map +1 -0
  51. package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
  52. package/dist/client/settlement/verifiedSale.js +4 -6
  53. package/dist/client/settlement/verifiedSale.js.map +1 -1
  54. package/dist/component/_generated/api.d.ts +284 -0
  55. package/dist/component/_generated/api.d.ts.map +1 -0
  56. package/dist/component/_generated/api.js +31 -0
  57. package/dist/component/_generated/api.js.map +1 -0
  58. package/dist/component/_generated/component.d.ts +527 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/balanceFunding/helpers.d.ts +86 -0
  61. package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
  62. package/dist/component/balanceFunding/helpers.js +68 -0
  63. package/dist/component/balanceFunding/helpers.js.map +1 -0
  64. package/dist/component/balanceFunding/importHandler.d.ts +13 -0
  65. package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
  66. package/dist/component/balanceFunding/importHandler.js +130 -0
  67. package/dist/component/balanceFunding/importHandler.js.map +1 -0
  68. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
  69. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
  70. package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
  71. package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
  72. package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
  73. package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
  74. package/dist/component/balanceFunding/mutationValidators.js +55 -0
  75. package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
  76. package/dist/component/balanceFunding/mutations.d.ts +335 -0
  77. package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
  78. package/dist/component/balanceFunding/mutations.js +106 -0
  79. package/dist/component/balanceFunding/mutations.js.map +1 -0
  80. package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
  81. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
  82. package/dist/component/balanceFunding/preparationHandlers.js +165 -0
  83. package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
  84. package/dist/component/balanceFunding/queries.d.ts +151 -0
  85. package/dist/component/balanceFunding/queries.d.ts.map +1 -0
  86. package/dist/component/balanceFunding/queries.js +180 -0
  87. package/dist/component/balanceFunding/queries.js.map +1 -0
  88. package/dist/component/balanceFunding/schema.d.ts +748 -0
  89. package/dist/component/balanceFunding/schema.d.ts.map +1 -0
  90. package/dist/component/balanceFunding/schema.js +124 -0
  91. package/dist/component/balanceFunding/schema.js.map +1 -0
  92. package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
  93. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
  94. package/dist/component/balanceFunding/stateHandlers.js +160 -0
  95. package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
  96. package/dist/component/convex.config.d.ts.map +1 -1
  97. package/dist/component/convex.config.js +2 -0
  98. package/dist/component/convex.config.js.map +1 -1
  99. package/dist/component/costRecovery/completion.d.ts +1 -0
  100. package/dist/component/costRecovery/completion.d.ts.map +1 -1
  101. package/dist/component/costRecovery/helpers.d.ts +1 -0
  102. package/dist/component/costRecovery/helpers.d.ts.map +1 -1
  103. package/dist/component/costRecovery/mutations.d.ts +5 -0
  104. package/dist/component/costRecovery/mutations.d.ts.map +1 -1
  105. package/dist/component/costRecovery/preparation.d.ts +50 -0
  106. package/dist/component/costRecovery/preparation.d.ts.map +1 -0
  107. package/dist/component/costRecovery/preparation.js +108 -0
  108. package/dist/component/costRecovery/preparation.js.map +1 -0
  109. package/dist/component/costRecovery/queries.d.ts +1 -0
  110. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  111. package/dist/component/costRecovery/reservations.d.ts +2 -0
  112. package/dist/component/costRecovery/reservations.d.ts.map +1 -1
  113. package/dist/component/costRecovery/schema.d.ts +7 -2
  114. package/dist/component/costRecovery/schema.d.ts.map +1 -1
  115. package/dist/component/costRecovery/schema.js +1 -0
  116. package/dist/component/costRecovery/schema.js.map +1 -1
  117. package/dist/component/durableExecution/runtime.d.ts +3 -0
  118. package/dist/component/durableExecution/runtime.d.ts.map +1 -0
  119. package/dist/component/durableExecution/runtime.js +12 -0
  120. package/dist/component/durableExecution/runtime.js.map +1 -0
  121. package/dist/component/earnings/triggers.d.ts +242 -2
  122. package/dist/component/earnings/triggers.d.ts.map +1 -1
  123. package/dist/component/schema.d.ts +253 -1
  124. package/dist/component/schema.js +4 -0
  125. package/dist/component/schema.js.map +1 -1
  126. package/docs/settlement.md +48 -0
  127. package/package.json +4 -2
  128. package/src/client/costRecovery-invoices.ts +3 -7
  129. package/src/client/costRecovery.test.ts +34 -0
  130. package/src/client/costRecovery.ts +21 -0
  131. package/src/client/index.ts +7 -2
  132. package/src/client/paymentSource/client.ts +13 -0
  133. package/src/client/paymentSource/contracts.ts +33 -0
  134. package/src/client/paymentSource/economics.ts +20 -0
  135. package/src/client/paymentSource/funding.ts +23 -0
  136. package/src/client/paymentSource/history.ts +48 -0
  137. package/src/client/paymentSource/resolver.test.ts +582 -0
  138. package/src/client/paymentSource/resolver.ts +350 -0
  139. package/src/client/processingCostDeficit/README.md +35 -0
  140. package/src/client/processingCostDeficit/calculator.test.ts +176 -0
  141. package/src/client/processingCostDeficit/index.ts +91 -0
  142. package/src/client/settlement/verifiedSale.ts +4 -10
  143. package/src/component/_generated/api.ts +23 -1
  144. package/src/component/_generated/component.ts +693 -0
  145. package/src/component/balanceFunding/failure.test.ts +116 -0
  146. package/src/component/balanceFunding/helpers.ts +102 -0
  147. package/src/component/balanceFunding/import.test.ts +221 -0
  148. package/src/component/balanceFunding/importHandler.ts +146 -0
  149. package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
  150. package/src/component/balanceFunding/lookup.test.ts +113 -0
  151. package/src/component/balanceFunding/mutationValidators.ts +63 -0
  152. package/src/component/balanceFunding/mutations.ts +136 -0
  153. package/src/component/balanceFunding/preparation.test.ts +146 -0
  154. package/src/component/balanceFunding/preparationHandlers.ts +204 -0
  155. package/src/component/balanceFunding/queries.ts +221 -0
  156. package/src/component/balanceFunding/requestLookup.test.ts +160 -0
  157. package/src/component/balanceFunding/schema.ts +169 -0
  158. package/src/component/balanceFunding/state.test.ts +352 -0
  159. package/src/component/balanceFunding/stateHandlers.ts +198 -0
  160. package/src/component/balanceFunding/validation.test.ts +100 -0
  161. package/src/component/convex.config.ts +2 -0
  162. package/src/component/costRecovery/preparation.test.ts +355 -0
  163. package/src/component/costRecovery/preparation.ts +124 -0
  164. package/src/component/costRecovery/schema.ts +1 -0
  165. package/src/component/durableExecution/composition.test.ts +568 -0
  166. package/src/component/durableExecution/runtime.ts +12 -0
  167. package/src/component/schema.ts +8 -0
@@ -0,0 +1,352 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ const m = (name: string) =>
7
+ makeFunctionReference<"mutation">(`balanceFunding/mutations:${name}`);
8
+ const q = (name: string) =>
9
+ makeFunctionReference<"query">(`balanceFunding/queries:${name}`);
10
+ const scope = { accountId: "acct_owner", scopeKey: "opaque-owner-scope" };
11
+ const snapshot = {
12
+ customerAccount: scope.accountId,
13
+ stripeSubscriptionId: "sub_plan",
14
+ paymentMethodId: "pm_balance",
15
+ previousPaymentMethodId: "pm_original",
16
+ previousPaymentMethodTypes: ["card"],
17
+ };
18
+ const preparation = {
19
+ ...scope,
20
+ preparation: snapshot,
21
+ consentAt: 100,
22
+ consentReference: "consent-record-1",
23
+ providerApiVersion: "2026-06-30.preview",
24
+ };
25
+ it("persists original restoration and consent once, and rejects replacement", async () => {
26
+ const t = convexTest(schema, modules);
27
+ const saved = await t.mutation(m("savePreparation"), preparation);
28
+ expect(saved.preparationId).toEqual(expect.any(String));
29
+ expect(await t.mutation(m("savePreparation"), preparation)).toEqual(saved);
30
+ const read = await t.query(q("readPreparation"), {
31
+ ...{
32
+ ...scope,
33
+ preparationId: saved.preparationId,
34
+ },
35
+ stripeSubscriptionId: "sub_plan",
36
+ });
37
+ expect(read.preparation).toEqual(snapshot);
38
+ expect(read.consentReference).toBe(preparation.consentReference);
39
+ expect(read.enabled).toBe(false);
40
+ await expect(
41
+ t.mutation(m("savePreparation"), {
42
+ ...preparation,
43
+ preparation: { ...snapshot, previousPaymentMethodId: "pm_changed" },
44
+ }),
45
+ ).rejects.toThrow(/identity|restoration|conflict/i);
46
+ });
47
+ it("reuses the same pending and completed request without changing restoration", async () => {
48
+ const t = convexTest(schema, modules);
49
+ const saved = await t.mutation(m("savePreparation"), preparation);
50
+ const args = {
51
+ ...scope,
52
+ preparationId: saved.preparationId,
53
+ enabled: true,
54
+ consent: true,
55
+ requestKey: "enable-request",
56
+ };
57
+ const first = await t.mutation(m("begin"), args);
58
+ expect(first.status).toBe("accepted");
59
+ expect(first.operation.version).toBe(1);
60
+ expect(await t.mutation(m("begin"), args)).toEqual(first);
61
+ const active = await t.query(q("inspectOperation"), {
62
+ ...first.operation,
63
+ stripeSubscriptionId: "sub_plan",
64
+ });
65
+ expect(active.state).toBe("pending");
66
+ expect(active.providerKeys.enable).toEqual(expect.any(String));
67
+ const receipt = {
68
+ customerAccount: scope.accountId,
69
+ stripeSubscriptionId: snapshot.stripeSubscriptionId,
70
+ paymentMethodId: snapshot.paymentMethodId,
71
+ paymentMethodTypes: ["stripe_balance"],
72
+ providerApiVersion: preparation.providerApiVersion,
73
+ };
74
+ await t.mutation(m("finish"), { ...first.operation, enabled: true, receipt });
75
+ expect(await t.mutation(m("begin"), args)).toEqual(first);
76
+ const status = await t.query(q("inspectOperation"), {
77
+ ...first.operation,
78
+ stripeSubscriptionId: "sub_plan",
79
+ });
80
+ expect(status.state).toBe("succeeded");
81
+ expect(status.providerKeys).toEqual(active.providerKeys);
82
+ expect(
83
+ (
84
+ await t.query(q("readPreparation"), {
85
+ ...{
86
+ ...scope,
87
+ preparationId: saved.preparationId,
88
+ },
89
+ stripeSubscriptionId: "sub_plan",
90
+ })
91
+ ).preparation,
92
+ ).toEqual(snapshot);
93
+ });
94
+ it("holds the account/subscription boundary against opposing targets and aliases", async () => {
95
+ const t = convexTest(schema, modules);
96
+ const saved = await t.mutation(m("savePreparation"), preparation);
97
+ const args = {
98
+ ...scope,
99
+ preparationId: saved.preparationId,
100
+ enabled: true,
101
+ consent: true,
102
+ requestKey: "enable",
103
+ };
104
+ await t.mutation(m("begin"), args);
105
+ expect(
106
+ await t.mutation(m("begin"), {
107
+ ...args,
108
+ enabled: false,
109
+ requestKey: "disable",
110
+ }),
111
+ ).toEqual({ status: "conflict", reason: "scope_busy", retryable: false });
112
+ await expect(
113
+ t.mutation(m("savePreparation"), { ...preparation, scopeKey: "alias" }),
114
+ ).rejects.toThrow(/scope|identity|conflict/i);
115
+ expect(
116
+ await t.mutation(m("begin"), {
117
+ ...args,
118
+ scopeKey: "alias",
119
+ requestKey: "alias-enable",
120
+ }),
121
+ ).toEqual({
122
+ status: "conflict",
123
+ reason: "identity_changed",
124
+ retryable: false,
125
+ });
126
+ });
127
+ it("keeps request payload immutable and rejects enable without consent", async () => {
128
+ const t = convexTest(schema, modules);
129
+ const saved = await t.mutation(m("savePreparation"), preparation);
130
+ const args = {
131
+ ...scope,
132
+ preparationId: saved.preparationId,
133
+ enabled: true,
134
+ requestKey: "enable",
135
+ };
136
+ expect(await t.mutation(m("begin"), args)).toEqual({
137
+ status: "rejected",
138
+ reason: "policy_invalid",
139
+ retryable: false,
140
+ });
141
+ const first = await t.mutation(m("begin"), { ...args, consent: true });
142
+ expect(first.status).toBe("accepted");
143
+ expect(await t.mutation(m("begin"), { ...args, enabled: false })).toEqual({
144
+ status: "conflict",
145
+ reason: "identity_changed",
146
+ retryable: false,
147
+ });
148
+ expect(
149
+ await t.mutation(m("begin"), {
150
+ ...args,
151
+ consent: true,
152
+ accountId: "foreign",
153
+ }),
154
+ ).toEqual({
155
+ status: "conflict",
156
+ reason: "identity_changed",
157
+ retryable: false,
158
+ });
159
+ await expect(
160
+ t.query(q("inspectOperation"), {
161
+ ...{ ...first.operation, scopeKey: "foreign" },
162
+ stripeSubscriptionId: "sub_plan",
163
+ }),
164
+ ).rejects.toThrow(/identity/i);
165
+ });
166
+ it("refuses stale completion and foreign receipts while preserving null versus empty settings", async () => {
167
+ const t = convexTest(schema, modules);
168
+ const prep = {
169
+ ...preparation,
170
+ preparation: {
171
+ ...snapshot,
172
+ previousPaymentMethodId: null,
173
+ previousPaymentMethodTypes: [],
174
+ },
175
+ };
176
+ const saved = await t.mutation(m("savePreparation"), prep);
177
+ const begin = (enabled: boolean, requestKey: string) =>
178
+ t.mutation(m("begin"), {
179
+ ...scope,
180
+ preparationId: saved.preparationId,
181
+ enabled,
182
+ consent: true,
183
+ requestKey,
184
+ });
185
+ const first = await begin(true, "on");
186
+ const receipt = {
187
+ customerAccount: scope.accountId,
188
+ stripeSubscriptionId: snapshot.stripeSubscriptionId,
189
+ paymentMethodId: snapshot.paymentMethodId,
190
+ paymentMethodTypes: ["stripe_balance"],
191
+ providerApiVersion: preparation.providerApiVersion,
192
+ };
193
+ await expect(
194
+ t.mutation(m("finish"), {
195
+ ...first.operation,
196
+ enabled: true,
197
+ receipt: { ...receipt, customerAccount: "foreign" },
198
+ }),
199
+ ).rejects.toThrow(/receipt/i);
200
+ await t.mutation(m("finish"), { ...first.operation, enabled: true, receipt });
201
+ const off = await begin(false, "off");
202
+ expect(off.operation.version).toBe(2);
203
+ await expect(
204
+ t.mutation(m("finish"), {
205
+ ...off.operation,
206
+ version: 1,
207
+ enabled: false,
208
+ receipt,
209
+ }),
210
+ ).rejects.toThrow(/identity/i);
211
+ await expect(
212
+ t.mutation(m("finish"), {
213
+ ...off.operation,
214
+ enabled: false,
215
+ receipt: { ...receipt, paymentMethodId: null, paymentMethodTypes: null },
216
+ }),
217
+ ).rejects.toThrow(/receipt/i);
218
+ await t.mutation(m("finish"), {
219
+ ...off.operation,
220
+ enabled: false,
221
+ receipt: { ...receipt, paymentMethodId: null, paymentMethodTypes: [] },
222
+ });
223
+ await t.mutation(m("finish"), { ...first.operation, enabled: true, receipt });
224
+ expect(
225
+ (
226
+ await t.query(q("readPreparation"), {
227
+ ...{
228
+ ...scope,
229
+ preparationId: saved.preparationId,
230
+ },
231
+ stripeSubscriptionId: "sub_plan",
232
+ })
233
+ ).enabled,
234
+ ).toBe(false);
235
+ });
236
+ it("cancels unstarted work and retains running or unknown scope claims until receipts reconcile", async () => {
237
+ const t = convexTest(schema, modules);
238
+ const saved = await t.mutation(m("savePreparation"), preparation);
239
+ const args = {
240
+ ...scope,
241
+ preparationId: saved.preparationId,
242
+ enabled: true,
243
+ consent: true,
244
+ requestKey: "cancel-before-start",
245
+ };
246
+ const first = await t.mutation(m("begin"), args);
247
+ const canceled = await t.mutation(m("requestCancel"), first.operation);
248
+ expect(canceled.state).toBe("canceled");
249
+ expect((await t.mutation(m("start"), first.operation)).state).toBe(
250
+ "canceled",
251
+ );
252
+ const second = await t.mutation(m("begin"), {
253
+ ...args,
254
+ requestKey: "running",
255
+ });
256
+ expect(second.operation.version).toBe(2);
257
+ expect((await t.mutation(m("start"), second.operation)).state).toBe(
258
+ "running",
259
+ );
260
+ expect((await t.mutation(m("requestCancel"), second.operation)).state).toBe(
261
+ "running",
262
+ );
263
+ expect((await t.mutation(m("markUnknown"), second.operation)).state).toBe(
264
+ "unknown",
265
+ );
266
+ expect(
267
+ await t.mutation(m("begin"), {
268
+ ...args,
269
+ enabled: false,
270
+ requestKey: "opposite",
271
+ }),
272
+ ).toEqual({ status: "conflict", reason: "scope_busy", retryable: false });
273
+ await t.mutation(m("finish"), {
274
+ ...second.operation,
275
+ enabled: true,
276
+ receipt: {
277
+ customerAccount: scope.accountId,
278
+ stripeSubscriptionId: snapshot.stripeSubscriptionId,
279
+ paymentMethodId: snapshot.paymentMethodId,
280
+ paymentMethodTypes: ["stripe_balance"],
281
+ providerApiVersion: preparation.providerApiVersion,
282
+ },
283
+ });
284
+ const done = await t.query(q("inspectOperation"), {
285
+ ...second.operation,
286
+ stripeSubscriptionId: "sub_plan",
287
+ });
288
+ expect(done.state).toBe("succeeded");
289
+ expect(done.cancelRequested).toBe(true);
290
+ });
291
+ it("pauses new starts while allowing original receipt reconciliation", async () => {
292
+ const t = convexTest(schema, modules);
293
+ const saved = await t.mutation(m("savePreparation"), preparation);
294
+ const args = {
295
+ ...scope,
296
+ preparationId: saved.preparationId,
297
+ enabled: true,
298
+ consent: true,
299
+ requestKey: "on",
300
+ };
301
+ const first = await t.mutation(m("begin"), args);
302
+ const binding = {
303
+ ...scope,
304
+ preparationId: saved.preparationId,
305
+ stripeSubscriptionId: snapshot.stripeSubscriptionId,
306
+ };
307
+ await t.mutation(m("setStartsPaused"), { ...binding, paused: true });
308
+ await expect(t.mutation(m("start"), first.operation)).rejects.toThrow(
309
+ /paused/i,
310
+ );
311
+ expect(await t.mutation(m("begin"), { ...args, requestKey: "new" })).toEqual({
312
+ status: "conflict",
313
+ reason: "scope_busy",
314
+ retryable: false,
315
+ });
316
+ await t.mutation(m("finish"), {
317
+ ...first.operation,
318
+ enabled: true,
319
+ receipt: {
320
+ customerAccount: scope.accountId,
321
+ stripeSubscriptionId: snapshot.stripeSubscriptionId,
322
+ paymentMethodId: snapshot.paymentMethodId,
323
+ paymentMethodTypes: ["stripe_balance"],
324
+ providerApiVersion: preparation.providerApiVersion,
325
+ },
326
+ });
327
+ expect(await t.mutation(m("begin"), args)).toEqual(first);
328
+ expect(
329
+ await t.mutation(m("begin"), {
330
+ ...args,
331
+ enabled: false,
332
+ requestKey: "off",
333
+ }),
334
+ ).toEqual({ status: "conflict", reason: "scope_busy", retryable: false });
335
+ await t.mutation(m("setStartsPaused"), { ...binding, paused: false });
336
+ expect(
337
+ (
338
+ await t.mutation(m("begin"), {
339
+ ...args,
340
+ enabled: false,
341
+ requestKey: "off",
342
+ })
343
+ ).status,
344
+ ).toBe("accepted");
345
+ await expect(
346
+ t.mutation(m("setStartsPaused"), {
347
+ ...binding,
348
+ stripeSubscriptionId: "foreign",
349
+ paused: true,
350
+ }),
351
+ ).rejects.toThrow(/identity/i);
352
+ });
@@ -0,0 +1,198 @@
1
+ import { validateOriginal } from "./helpers.js";
2
+ import type { Infer } from "convex/values";
3
+ import type { MutationCtx } from "../_generated/server.js";
4
+ import {
5
+ text,
6
+ integer,
7
+ validateScope,
8
+ same,
9
+ unavailable,
10
+ readOperation,
11
+ ref,
12
+ fingerprint,
13
+ } from "./helpers.js";
14
+ import {
15
+ savePreparationArgs,
16
+ beginArgs,
17
+ finishArgs,
18
+ } from "./mutationValidators.js";
19
+ export async function savePreparationHandler(
20
+ ctx: MutationCtx,
21
+ args: Infer<typeof savePreparationArgs>,
22
+ ) {
23
+ validateScope(args);
24
+ integer(args.consentAt);
25
+ text(args.consentReference);
26
+ text(args.providerApiVersion);
27
+ validateOriginal(args.preparation);
28
+ text(args.preparation.stripeSubscriptionId);
29
+ text(args.preparation.paymentMethodId);
30
+ if (args.preparation.customerAccount !== args.accountId)
31
+ throw new Error("Preparation account identity does not match.");
32
+ const existing = await ctx.db
33
+ .query("balanceFundingPreparations")
34
+ .withIndex("by_account_subscription", (q) =>
35
+ q
36
+ .eq("accountId", args.accountId)
37
+ .eq(
38
+ "preparation.stripeSubscriptionId",
39
+ args.preparation.stripeSubscriptionId,
40
+ ),
41
+ )
42
+ .unique();
43
+ if (existing) {
44
+ if (
45
+ existing.scopeKey !== args.scopeKey ||
46
+ !same(existing.preparation, args.preparation) ||
47
+ existing.consentAt !== args.consentAt ||
48
+ existing.consentReference !== args.consentReference ||
49
+ existing.providerApiVersion !== args.providerApiVersion
50
+ )
51
+ throw new Error("Preparation identity or restoration conflict.");
52
+ return { preparationId: existing._id };
53
+ }
54
+ const preparationId = await ctx.db.insert("balanceFundingPreparations", {
55
+ ...args,
56
+ enabled: false,
57
+ operationVersion: 0,
58
+ startsPaused: false,
59
+ verified: true,
60
+ });
61
+ return { preparationId };
62
+ }
63
+ export async function beginHandler(
64
+ ctx: MutationCtx,
65
+ args: Infer<typeof beginArgs>,
66
+ ) {
67
+ validateScope(args);
68
+ text(args.requestKey);
69
+ const payload = fingerprint({
70
+ accountId: args.accountId,
71
+ scopeKey: args.scopeKey,
72
+ preparationId: args.preparationId,
73
+ enabled: args.enabled,
74
+ consent: args.consent ?? null,
75
+ });
76
+ const prior = await ctx.db
77
+ .query("balanceFundingRequests")
78
+ .withIndex("by_request", (q) => q.eq("requestKey", args.requestKey))
79
+ .unique();
80
+ if (prior)
81
+ return prior.payload === payload && prior.result
82
+ ? prior.result
83
+ : unavailable("identity_changed");
84
+ const setting = await ctx.db.get(
85
+ "balanceFundingPreparations",
86
+ args.preparationId,
87
+ );
88
+ if (
89
+ !setting ||
90
+ setting.accountId !== args.accountId ||
91
+ setting.scopeKey !== args.scopeKey
92
+ )
93
+ return unavailable("identity_changed");
94
+ if (setting.startsPaused) return unavailable("scope_busy");
95
+ if (!setting.verified || !setting.preparation.paymentMethodId)
96
+ return {
97
+ status: "not_ready" as const,
98
+ reason: "provider_pending" as const,
99
+ retryable: true as const,
100
+ };
101
+ if (args.enabled && args.consent !== true)
102
+ return {
103
+ status: "rejected" as const,
104
+ reason: "policy_invalid" as const,
105
+ retryable: false as const,
106
+ };
107
+ let result;
108
+ if (setting.activeOperationId) {
109
+ const active = await ctx.db.get(
110
+ "balanceFundingOperations",
111
+ setting.activeOperationId,
112
+ );
113
+ if (!active || active.enabled !== args.enabled)
114
+ return unavailable("scope_busy");
115
+ result = { status: "accepted" as const, operation: ref(active) };
116
+ } else if (setting.enabled === args.enabled)
117
+ result = { status: "unchanged" as const, enabled: args.enabled };
118
+ else {
119
+ const version = setting.operationVersion + 1;
120
+ integer(version, 1);
121
+ const key = `betterstripe_balance_${setting._id}_${version}`;
122
+ const operationId = await ctx.db.insert("balanceFundingOperations", {
123
+ accountId: args.accountId,
124
+ scopeKey: args.scopeKey,
125
+ preparationId: setting._id,
126
+ enabled: args.enabled,
127
+ version,
128
+ state: "pending",
129
+ kind: "apply",
130
+ providerKey: key,
131
+ cancelRequested: false,
132
+ providerKeys: { enable: `${key}:enable`, disable: `${key}:disable` },
133
+ });
134
+ await ctx.db.patch("balanceFundingPreparations", setting._id, {
135
+ operationVersion: version,
136
+ activeOperationId: operationId,
137
+ });
138
+ result = {
139
+ status: "accepted" as const,
140
+ operation: {
141
+ accountId: args.accountId,
142
+ scopeKey: args.scopeKey,
143
+ operationId,
144
+ version,
145
+ },
146
+ };
147
+ }
148
+ await ctx.db.insert("balanceFundingRequests", {
149
+ requestKey: args.requestKey,
150
+ payload,
151
+ preparationId: setting._id,
152
+ result,
153
+ });
154
+ return result;
155
+ }
156
+ export async function finishHandler(
157
+ ctx: MutationCtx,
158
+ args: Infer<typeof finishArgs>,
159
+ ) {
160
+ const op = await readOperation(ctx, args);
161
+ if (!op || op.kind !== "apply" || op.enabled !== args.enabled)
162
+ throw new Error("Balance funding operation identity changed.");
163
+ const prep = await ctx.db.get("balanceFundingPreparations", op.preparationId);
164
+ if (!prep) throw new Error("Preparation is missing.");
165
+ const expected = {
166
+ customerAccount: prep.accountId,
167
+ stripeSubscriptionId: prep.preparation.stripeSubscriptionId,
168
+ paymentMethodId: op.enabled
169
+ ? prep.preparation.paymentMethodId
170
+ : prep.preparation.previousPaymentMethodId,
171
+ paymentMethodTypes: op.enabled
172
+ ? ["stripe_balance"]
173
+ : prep.preparation.previousPaymentMethodTypes,
174
+ providerApiVersion: prep.providerApiVersion,
175
+ };
176
+ if (!same(args.receipt, expected))
177
+ throw new Error("Provider receipt does not match intended settings.");
178
+ if (op.state === "succeeded") {
179
+ if (!same(op.receipt, args.receipt))
180
+ throw new Error("Provider receipt identity changed.");
181
+ return op;
182
+ }
183
+ if (
184
+ prep.activeOperationId !== op._id ||
185
+ prep.operationVersion !== op.version ||
186
+ op.state === "canceled"
187
+ )
188
+ throw new Error("Balance funding operation version changed.");
189
+ await ctx.db.patch("balanceFundingOperations", op._id, {
190
+ state: "succeeded",
191
+ receipt: args.receipt,
192
+ });
193
+ await ctx.db.patch("balanceFundingPreparations", prep._id, {
194
+ enabled: op.enabled,
195
+ activeOperationId: undefined,
196
+ });
197
+ return (await ctx.db.get("balanceFundingOperations", op._id))!;
198
+ }
@@ -0,0 +1,100 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ const m = (name: string) =>
7
+ makeFunctionReference<"mutation">(`balanceFunding/mutations:${name}`);
8
+ const q = (name: string) =>
9
+ makeFunctionReference<"query">(`balanceFunding/queries:${name}`);
10
+ const scope = { accountId: "acct_owner", scopeKey: "opaque" };
11
+ const preparation = {
12
+ customerAccount: scope.accountId,
13
+ stripeSubscriptionId: "sub_valid",
14
+ paymentMethodId: "pm_balance",
15
+ previousPaymentMethodId: null,
16
+ previousPaymentMethodTypes: null,
17
+ };
18
+ const initial = {
19
+ ...scope,
20
+ preparation,
21
+ consentAt: 10,
22
+ consentReference: "consent",
23
+ providerApiVersion: "preview",
24
+ };
25
+ it("rejects malformed restoration without inserting preparation data", async () => {
26
+ const t = convexTest(schema, modules);
27
+ for (const changed of [
28
+ { ...preparation, previousPaymentMethodId: "" },
29
+ { ...preparation, previousPaymentMethodId: preparation.paymentMethodId },
30
+ { ...preparation, previousPaymentMethodTypes: ["stripe_balance"] },
31
+ { ...preparation, previousPaymentMethodTypes: [""] },
32
+ { ...preparation, previousPaymentMethodTypes: Array(51).fill("card") },
33
+ ])
34
+ await expect(
35
+ t.mutation(m("savePreparation"), { ...initial, preparation: changed }),
36
+ ).rejects.toThrow(/invalid/i);
37
+ expect(
38
+ await t.run((ctx) => ctx.db.query("balanceFundingPreparations").take(1)),
39
+ ).toEqual([]);
40
+ });
41
+ it("validates opaque identities, consent time and imports before any write", async () => {
42
+ const t = convexTest(schema, modules);
43
+ for (const changed of [
44
+ { ...initial, scopeKey: " " },
45
+ { ...initial, consentAt: 1.5 },
46
+ { ...initial, consentReference: "" },
47
+ { ...initial, providerApiVersion: "" },
48
+ { ...initial, preparation: { ...preparation, customerAccount: "foreign" } },
49
+ ])
50
+ await expect(t.mutation(m("savePreparation"), changed)).rejects.toThrow(
51
+ /invalid|identity/i,
52
+ );
53
+ await expect(
54
+ t.mutation(m("importPreparation"), {
55
+ ...initial,
56
+ sourceKey: "legacy",
57
+ enabled: true,
58
+ operationVersion: 0,
59
+ pending: { enabled: false, providerKey: "old", requestKey: "old" },
60
+ }),
61
+ ).rejects.toThrow(/version/i);
62
+ expect(
63
+ await t.run((ctx) => ctx.db.query("balanceFundingPreparations").take(1)),
64
+ ).toEqual([]);
65
+ });
66
+ it("server-only readers reject foreign scope, subscription and operation version", async () => {
67
+ const t = convexTest(schema, modules);
68
+ const saved = await t.mutation(m("savePreparation"), initial);
69
+ const args = {
70
+ ...scope,
71
+ preparationId: saved.preparationId,
72
+ stripeSubscriptionId: "sub_valid",
73
+ };
74
+ await expect(
75
+ t.query(q("readPreparation"), { ...args, scopeKey: "foreign" }),
76
+ ).rejects.toThrow(/identity/i);
77
+ await expect(
78
+ t.query(q("readPreparation"), { ...args, stripeSubscriptionId: "foreign" }),
79
+ ).rejects.toThrow(/identity/i);
80
+ const accepted = await t.mutation(m("begin"), {
81
+ ...scope,
82
+ preparationId: saved.preparationId,
83
+ enabled: true,
84
+ consent: true,
85
+ requestKey: "on",
86
+ });
87
+ await expect(
88
+ t.query(q("inspectOperation"), {
89
+ ...accepted.operation,
90
+ stripeSubscriptionId: "foreign",
91
+ }),
92
+ ).rejects.toThrow(/identity/i);
93
+ await expect(
94
+ t.query(q("inspectOperation"), {
95
+ ...accepted.operation,
96
+ stripeSubscriptionId: "sub_valid",
97
+ version: 2,
98
+ }),
99
+ ).rejects.toThrow(/identity/i);
100
+ });
@@ -1,3 +1,4 @@
1
+ import workflow from "@convex-dev/workflow/convex.config";
1
2
  import { defineComponent } from "convex/server";
2
3
  import { v } from "convex/values";
3
4
 
@@ -15,4 +16,5 @@ const component = defineComponent("betterStripe", {
15
16
  STRIPE_PUBLISHABLE_KEY: v.optional(v.string()),
16
17
  },
17
18
  });
19
+ component.use(workflow);
18
20
  export default component;