@donotdev/functions 0.1.42 → 0.2.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 (279) hide show
  1. package/README.md +25 -14
  2. package/lib/chunks/chunk-2JL3GDTO.js +151 -0
  3. package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
  4. package/lib/chunks/chunk-4TVLH2W2.js +22 -0
  5. package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
  6. package/lib/chunks/chunk-4U7QQWYG.js +22 -0
  7. package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
  8. package/lib/chunks/chunk-5DTPEM64.js +22 -0
  9. package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
  10. package/lib/chunks/chunk-6CQXHNVL.js +22 -0
  11. package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
  12. package/lib/chunks/chunk-6DSCPZC6.js +22 -0
  13. package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
  14. package/lib/chunks/chunk-7E6TGWHU.js +22 -0
  15. package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
  16. package/lib/chunks/chunk-7LT32OWE.js +22 -0
  17. package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
  18. package/lib/chunks/chunk-7VH2GJXT.js +151 -0
  19. package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
  20. package/lib/chunks/chunk-API5A4BV.js +22 -0
  21. package/lib/chunks/chunk-API5A4BV.js.map +7 -0
  22. package/lib/chunks/chunk-AYY7UXNI.js +22 -0
  23. package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
  24. package/lib/chunks/chunk-BUP7SXPV.js +23 -0
  25. package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
  26. package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
  27. package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
  28. package/lib/chunks/chunk-FSLGZD7A.js +21 -0
  29. package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
  30. package/lib/chunks/chunk-GVLSPWDD.js +151 -0
  31. package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
  32. package/lib/chunks/chunk-GXQVWEFT.js +22 -0
  33. package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
  34. package/lib/chunks/chunk-HB7EGXVI.js +22 -0
  35. package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
  36. package/lib/chunks/chunk-HLNYUAZH.js +22 -0
  37. package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
  38. package/lib/chunks/chunk-HM7XCMWW.js +22 -0
  39. package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
  40. package/lib/chunks/chunk-I7IOIL6U.js +151 -0
  41. package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
  42. package/lib/chunks/chunk-IFOYVSPU.js +22 -0
  43. package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
  44. package/lib/chunks/chunk-JTAGPPPL.js +22 -0
  45. package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
  46. package/lib/chunks/chunk-MZ232FUE.js +22 -0
  47. package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
  48. package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
  49. package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
  50. package/lib/chunks/chunk-NP2AN2TV.js +22 -0
  51. package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
  52. package/lib/chunks/chunk-QJAU2MWV.js +22 -0
  53. package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
  54. package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
  55. package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
  56. package/lib/chunks/chunk-RQZGIZHD.js +151 -0
  57. package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
  58. package/lib/chunks/chunk-TBEDQLOB.js +23 -0
  59. package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
  60. package/lib/chunks/chunk-TMHBP3HB.js +22 -0
  61. package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
  62. package/lib/chunks/chunk-UH4L3EF3.js +151 -0
  63. package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
  64. package/lib/chunks/chunk-UJBIU6TL.js +22 -0
  65. package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
  66. package/lib/chunks/chunk-VKEYW3NT.js +22 -0
  67. package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
  68. package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
  69. package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
  70. package/lib/chunks/chunk-Y44NEQQG.js +22 -0
  71. package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
  72. package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
  73. package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
  74. package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
  75. package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
  76. package/lib/chunks/monitoring-PVQMFL34.js +22 -0
  77. package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
  78. package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
  79. package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
  80. package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
  81. package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
  82. package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
  83. package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
  84. package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
  85. package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
  86. package/lib/chunks/server-32A5RH4C.js +22 -0
  87. package/lib/chunks/server-32A5RH4C.js.map +7 -0
  88. package/lib/chunks/server-7HDAP5DL.js +22 -0
  89. package/lib/chunks/server-7HDAP5DL.js.map +7 -0
  90. package/lib/chunks/server-S2IMFOY7.js +22 -0
  91. package/lib/chunks/server-S2IMFOY7.js.map +7 -0
  92. package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
  93. package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
  94. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  95. package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
  96. package/lib/firebase/baseFunction.d.ts +1 -1
  97. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
  98. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  99. package/lib/firebase/billing/index.d.ts +2 -1
  100. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
  101. package/lib/firebase/billing/webhookHandler.d.ts +17 -2
  102. package/lib/firebase/crud/aggregate.d.ts +0 -9
  103. package/lib/firebase/crud/bulk.d.ts +2 -2
  104. package/lib/firebase/crud/create.d.ts +1 -1
  105. package/lib/firebase/crud/delete.d.ts +1 -1
  106. package/lib/firebase/crud/get.d.ts +1 -1
  107. package/lib/firebase/crud/list.d.ts +1 -1
  108. package/lib/firebase/crud/update.d.ts +1 -9
  109. package/lib/firebase/index.js +1 -5
  110. package/lib/firebase/index.js.map +4 -4
  111. package/lib/firebase/oauth/githubAccess.d.ts +2 -2
  112. package/lib/firebase/registerCrudFunctions.d.ts +9 -1
  113. package/lib/shared/billing/apiVersion.d.ts +22 -0
  114. package/lib/shared/billing/checkoutPrice.d.ts +27 -0
  115. package/lib/shared/billing/checkoutValidation.d.ts +89 -0
  116. package/lib/shared/billing/createCheckout.d.ts +73 -24
  117. package/lib/shared/billing/helpers/index.d.ts +0 -1
  118. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
  119. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
  120. package/lib/shared/billing/idempotency.d.ts +32 -10
  121. package/lib/shared/billing/idempotencyContract.d.ts +121 -0
  122. package/lib/shared/billing/index.d.ts +2 -0
  123. package/lib/shared/billing/orderWebhook.d.ts +75 -0
  124. package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
  125. package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
  126. package/lib/shared/billing/webhookHandler.d.ts +28 -20
  127. package/lib/shared/index.js +1 -6
  128. package/lib/shared/index.js.map +4 -4
  129. package/lib/shared/utils/functionWrapper.d.ts +1 -1
  130. package/lib/shared/utils/internal/auth.d.ts +38 -1
  131. package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
  132. package/lib/shared/utils/schemaValidation.d.ts +1 -1
  133. package/lib/shared/utils/vercelHelpers.d.ts +8 -0
  134. package/lib/shared/utils.d.ts +4 -17
  135. package/lib/supabase/baseFunction.d.ts +1 -1
  136. package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
  137. package/lib/supabase/crud/bulk.d.ts +1 -1
  138. package/lib/supabase/crud/entityStore.d.ts +71 -0
  139. package/lib/supabase/crud/index.d.ts +2 -0
  140. package/lib/supabase/helpers/authProvider.d.ts +5 -5
  141. package/lib/supabase/index.d.ts +10 -2
  142. package/lib/supabase/index.js +1 -3
  143. package/lib/supabase/index.js.map +4 -4
  144. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  145. package/lib/vercel/api/ai/chat.d.ts +0 -9
  146. package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
  147. package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
  148. package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
  149. package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
  150. package/lib/vercel/api/billing/backend.d.ts +39 -0
  151. package/lib/vercel/api/billing/cancel.d.ts +8 -0
  152. package/lib/vercel/api/billing/change-plan.d.ts +9 -1
  153. package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
  154. package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
  155. package/lib/vercel/api/billing/index.d.ts +4 -2
  156. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
  157. package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
  158. package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
  159. package/lib/vercel/api/crud/bulk.d.ts +17 -0
  160. package/lib/vercel/api/crud/create.d.ts +8 -0
  161. package/lib/vercel/api/crud/delete.d.ts +8 -0
  162. package/lib/vercel/api/crud/get.d.ts +8 -0
  163. package/lib/vercel/api/crud/list.d.ts +8 -0
  164. package/lib/vercel/api/crud/update.d.ts +8 -0
  165. package/lib/vercel/api/index.js +1 -3
  166. package/lib/vercel/api/index.js.map +4 -4
  167. package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
  168. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  169. package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
  170. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  171. package/lib/vercel/baseFunction.d.ts +4 -1
  172. package/lib/vercel/supabaseAdmin.d.ts +22 -0
  173. package/package.json +25 -26
  174. package/src/firebase/auth/getCustomClaims.ts +4 -5
  175. package/src/firebase/auth/getUserAuthStatus.ts +4 -5
  176. package/src/firebase/auth/removeCustomClaims.ts +4 -5
  177. package/src/firebase/auth/setCustomClaims.ts +4 -5
  178. package/src/firebase/baseFunction.ts +4 -5
  179. package/src/firebase/billing/cancelSubscription.ts +1 -2
  180. package/src/firebase/billing/changePlan.ts +2 -3
  181. package/src/firebase/billing/createCheckoutSession.ts +30 -56
  182. package/src/firebase/billing/createCustomerPortal.ts +4 -5
  183. package/src/firebase/billing/healthCheck.ts +0 -0
  184. package/src/firebase/billing/index.ts +8 -1
  185. package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
  186. package/src/firebase/billing/webhookHandler.ts +20 -4
  187. package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
  188. package/src/firebase/crud/aggregate.ts +1 -2
  189. package/src/firebase/crud/bulk.ts +5 -6
  190. package/src/firebase/crud/create.ts +5 -6
  191. package/src/firebase/crud/delete.ts +4 -5
  192. package/src/firebase/crud/get.ts +4 -5
  193. package/src/firebase/crud/list.ts +4 -5
  194. package/src/firebase/crud/update.ts +5 -6
  195. package/src/firebase/oauth/githubAccess.ts +2 -3
  196. package/src/firebase/registerCrudFunctions.ts +2 -2
  197. package/src/shared/__tests__/auth.test.ts +0 -3
  198. package/src/shared/__tests__/bulkCore.test.ts +3 -2
  199. package/src/shared/__tests__/errorHandling.test.ts +2 -2
  200. package/src/shared/__tests__/idempotency.test.ts +282 -55
  201. package/src/shared/__tests__/internalValidation.test.ts +3 -3
  202. package/src/shared/__tests__/rateLimiter.test.ts +2 -8
  203. package/src/shared/__tests__/schemaValidation.test.ts +1 -1
  204. package/src/shared/__tests__/utils.test.ts +2 -1
  205. package/src/shared/__tests__/validation-env.test.ts +0 -0
  206. package/src/shared/ai/createAIRoute.ts +53 -30
  207. package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
  208. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
  209. package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
  210. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
  211. package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
  212. package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
  213. package/src/shared/billing/apiVersion.ts +25 -0
  214. package/src/shared/billing/checkoutPrice.ts +125 -0
  215. package/src/shared/billing/checkoutValidation.ts +284 -0
  216. package/src/shared/billing/createCheckout.ts +332 -196
  217. package/src/shared/billing/helpers/index.ts +0 -1
  218. package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
  219. package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
  220. package/src/shared/billing/idempotency.ts +253 -150
  221. package/src/shared/billing/idempotencyContract.ts +135 -0
  222. package/src/shared/billing/index.ts +2 -0
  223. package/src/shared/billing/orderWebhook.ts +269 -0
  224. package/src/shared/billing/supabaseIdempotency.ts +228 -0
  225. package/src/shared/billing/tierWebhookEvents.ts +432 -0
  226. package/src/shared/billing/webhookHandler.ts +188 -385
  227. package/src/shared/utils/external/subscription.ts +0 -0
  228. package/src/shared/utils/firebaseHelpers.ts +2 -3
  229. package/src/shared/utils/functionWrapper.ts +1 -2
  230. package/src/shared/utils/internal/auth.ts +55 -7
  231. package/src/shared/utils/internal/monitoring.ts +17 -9
  232. package/src/shared/utils/internal/rateLimiter.ts +14 -5
  233. package/src/shared/utils/schemaValidation.ts +1 -2
  234. package/src/shared/utils/vercelHelpers.ts +3 -3
  235. package/src/shared/utils.ts +14 -31
  236. package/src/shared/validation.ts +1 -1
  237. package/src/supabase/__tests__/bulk.test.ts +3 -1
  238. package/src/supabase/__tests__/entityStore.test.ts +90 -0
  239. package/src/supabase/baseFunction.ts +1 -2
  240. package/src/supabase/billing/createCheckoutSession.ts +10 -36
  241. package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
  242. package/src/supabase/billing/stripeWebhook.ts +79 -0
  243. package/src/supabase/crud/aggregate.ts +1 -1
  244. package/src/supabase/crud/bulk.ts +3 -7
  245. package/src/supabase/crud/create.ts +1 -1
  246. package/src/supabase/crud/entityStore.ts +240 -0
  247. package/src/supabase/crud/index.ts +8 -0
  248. package/src/supabase/crud/update.ts +1 -1
  249. package/src/supabase/helpers/authProvider.ts +6 -5
  250. package/src/supabase/index.ts +26 -0
  251. package/src/supabase/utils/rateLimiter.ts +2 -2
  252. package/src/vercel/__tests__/bulk.test.ts +24 -21
  253. package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
  254. package/src/vercel/api/ai/chat.ts +2 -1
  255. package/src/vercel/api/auth/get-custom-claims.ts +2 -3
  256. package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
  257. package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
  258. package/src/vercel/api/auth/set-custom-claims.ts +3 -3
  259. package/src/vercel/api/billing/backend.ts +72 -0
  260. package/src/vercel/api/billing/cancel.ts +2 -4
  261. package/src/vercel/api/billing/change-plan.ts +3 -4
  262. package/src/vercel/api/billing/create-checkout-session.ts +42 -68
  263. package/src/vercel/api/billing/customer-portal.ts +2 -4
  264. package/src/vercel/api/billing/index.ts +4 -2
  265. package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
  266. package/src/vercel/api/billing/webhook-handler.ts +31 -25
  267. package/src/vercel/api/config/firebase-admin.ts +2 -2
  268. package/src/vercel/api/crud/bulk.ts +6 -9
  269. package/src/vercel/api/crud/create.ts +6 -5
  270. package/src/vercel/api/crud/delete.ts +4 -3
  271. package/src/vercel/api/crud/get.ts +6 -5
  272. package/src/vercel/api/crud/list.ts +6 -5
  273. package/src/vercel/api/crud/update.ts +6 -5
  274. package/src/vercel/api/oauth/check-github-access.ts +5 -5
  275. package/src/vercel/api/oauth/exchange-token.ts +3 -3
  276. package/src/vercel/api/oauth/grant-github-access.ts +5 -5
  277. package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
  278. package/src/vercel/baseFunction.ts +23 -8
  279. package/src/vercel/supabaseAdmin.ts +45 -0
@@ -4,22 +4,24 @@
4
4
  * @fileoverview Tests for createCheckoutAlgorithm
5
5
  * @description Unit tests using dependency injection — no real Stripe or Firebase calls.
6
6
  *
7
- * @version 0.1.0
7
+ * @version 0.2.0
8
8
  * @since 0.0.1
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { describe, it, expect, vi, beforeEach } from 'vitest';
12
+ import * as v from 'valibot';
13
+ import { describe, it, expect, vi } from 'vitest';
13
14
 
15
+ import { CreateCheckoutSessionRequestSchema } from '@donotdev/core/server';
14
16
  import type {
15
17
  CreateCheckoutSessionRequest,
16
18
  StripeBackConfig,
19
+ StripeOrderBackItem,
17
20
  } from '@donotdev/core/server';
18
21
 
19
22
  import { createCheckoutAlgorithm } from '../createCheckout.js';
20
-
21
23
  import type {
22
- StripeCheckoutProvider,
24
+ StripeSessionProvider,
23
25
  AuthCheckoutProvider,
24
26
  } from '../createCheckout.js';
25
27
 
@@ -27,470 +29,511 @@ import type {
27
29
  // Fixtures
28
30
  // ---------------------------------------------------------------------------
29
31
 
30
- const VALID_PRICE_ID = 'price_test_abc123';
31
-
32
- const BILLING_CONFIG: StripeBackConfig = {
33
- pro_monthly: {
34
- type: 'StripeSubscription',
35
- name: 'Pro Monthly',
36
- price: 1999,
37
- currency: 'EUR',
38
- priceId: VALID_PRICE_ID,
39
- tier: 'pro',
40
- duration: '1month',
41
- },
42
- starter_once: {
43
- type: 'StripePayment',
44
- name: 'Starter Pack',
45
- price: 4900,
46
- currency: 'EUR',
47
- priceId: 'price_starter_xyz',
48
- tier: 'starter',
49
- duration: 'lifetime',
50
- },
51
- };
52
-
53
- const BASE_REQUEST: CreateCheckoutSessionRequest = {
54
- userId: 'user_001',
55
- priceId: VALID_PRICE_ID,
32
+ const USER_ID = 'user_001';
33
+ const URLS = {
56
34
  successUrl: 'https://app.example.com/billing/success',
57
35
  cancelUrl: 'https://app.example.com/billing/cancel',
58
- metadata: { billingConfigKey: 'pro_monthly' },
59
- mode: 'subscription',
60
36
  };
61
37
 
62
- // ---------------------------------------------------------------------------
63
- // Mock factories
64
- // ---------------------------------------------------------------------------
65
-
66
- function makeStripeProvider(
67
- overrides?: Partial<StripeCheckoutProvider>
68
- ): StripeCheckoutProvider {
38
+ function makeOrderItem(
39
+ overrides: Partial<StripeOrderBackItem> = {}
40
+ ): StripeOrderBackItem {
69
41
  return {
70
- createCheckoutSession: vi.fn().mockResolvedValue({
71
- id: 'cs_test_session123',
72
- url: 'https://checkout.stripe.com/pay/cs_test_session123',
73
- }),
42
+ type: 'StripeOrder',
43
+ name: 'Shop order',
44
+ currency: 'eur',
45
+ tax: { mode: 'manual', taxRateIds: ['txr_fr_20'] },
46
+ taxIdCollection: 'optional',
47
+ billingAddressCollection: 'required',
48
+ customerCreation: 'always',
49
+ invoiceCreation: true,
50
+ resolveLineItems: vi.fn(async (items) => ({
51
+ orderId: 'ord_42',
52
+ lineItems: items.map((item) => ({
53
+ productId: item.productId,
54
+ name: `Product ${item.productId}`,
55
+ unitAmount: 1250,
56
+ quantity: item.quantity,
57
+ })),
58
+ })),
59
+ onOrderPaid: vi.fn(async () => {}),
74
60
  ...overrides,
75
61
  };
76
62
  }
77
63
 
78
- function makeAuthProvider(
79
- overrides?: Partial<AuthCheckoutProvider>
80
- ): AuthCheckoutProvider {
64
+ function makeConfig(order: StripeOrderBackItem = makeOrderItem()): StripeBackConfig {
81
65
  return {
82
- getUser: vi.fn().mockResolvedValue({ customClaims: {} }),
83
- ...overrides,
66
+ pro_monthly: {
67
+ type: 'StripeSubscription',
68
+ name: 'Pro Monthly',
69
+ price: 1999,
70
+ currency: 'EUR',
71
+ priceId: 'price_pro',
72
+ tier: 'pro',
73
+ duration: '1month',
74
+ },
75
+ starter_once: {
76
+ type: 'StripePayment',
77
+ name: 'Starter Pack',
78
+ price: 4900,
79
+ currency: 'EUR',
80
+ priceId: 'price_starter',
81
+ tier: 'starter',
82
+ duration: 'lifetime',
83
+ allowPromotionCodes: true,
84
+ },
85
+ shop_order: order,
86
+ };
87
+ }
88
+
89
+ function singleItemRequest(key: string): CreateCheckoutSessionRequest {
90
+ return {
91
+ billingConfigKey: key,
92
+ lineItems: [{ productId: key, quantity: 1 }],
93
+ ...URLS,
84
94
  };
85
95
  }
86
96
 
97
+ const ORDER_REQUEST: CreateCheckoutSessionRequest = {
98
+ billingConfigKey: 'shop_order',
99
+ lineItems: [
100
+ { productId: 'serum-30ml', quantity: 24 },
101
+ { productId: 'toner-150ml', quantity: 12 },
102
+ ],
103
+ ...URLS,
104
+ };
105
+
87
106
  // ---------------------------------------------------------------------------
88
- // Tests
107
+ // Mock factories
89
108
  // ---------------------------------------------------------------------------
90
109
 
91
- describe('createCheckoutAlgorithm', () => {
92
- let stripeProvider: StripeCheckoutProvider;
93
- let authProvider: AuthCheckoutProvider;
110
+ function makeStripeProvider() {
111
+ const createStripeSession = vi.fn<
112
+ StripeSessionProvider['createStripeSession']
113
+ >(async () => ({
114
+ id: 'cs_test_session123',
115
+ url: 'https://checkout.stripe.com/pay/cs_test_session123',
116
+ }));
117
+ const retrieveTaxRate = vi.fn<StripeSessionProvider['retrieveTaxRate']>(
118
+ async (id) => ({ id, inclusive: id.startsWith('txr_incl') })
119
+ );
120
+ return { createStripeSession, retrieveTaxRate };
121
+ }
94
122
 
95
- beforeEach(() => {
96
- stripeProvider = makeStripeProvider();
97
- authProvider = makeAuthProvider();
98
- vi.clearAllMocks();
99
- });
123
+ function makeAuthProvider(): AuthCheckoutProvider {
124
+ return { getUser: vi.fn(async () => ({ customClaims: {} })) };
125
+ }
100
126
 
101
- // -------------------------------------------------------------------------
102
- // Happy path
103
- // -------------------------------------------------------------------------
104
-
105
- describe('valid checkout creation', () => {
106
- it('returns sessionId and sessionUrl on success', async () => {
107
- const result = await createCheckoutAlgorithm(
108
- BASE_REQUEST,
109
- stripeProvider,
110
- authProvider,
111
- BILLING_CONFIG
112
- );
113
-
114
- expect(result).toEqual({
115
- sessionId: 'cs_test_session123',
116
- sessionUrl: 'https://checkout.stripe.com/pay/cs_test_session123',
117
- });
118
- });
127
+ async function run(
128
+ request: CreateCheckoutSessionRequest,
129
+ config: StripeBackConfig = makeConfig(),
130
+ stripe = makeStripeProvider(),
131
+ auth = makeAuthProvider()
132
+ ) {
133
+ const result = await createCheckoutAlgorithm(
134
+ request,
135
+ USER_ID,
136
+ stripe,
137
+ auth,
138
+ config
139
+ );
140
+ const params = stripe.createStripeSession.mock.calls[0]?.[0];
141
+ return { result, params, stripe, auth };
142
+ }
119
143
 
120
- it('verifies the user before creating the session', async () => {
121
- await createCheckoutAlgorithm(
122
- BASE_REQUEST,
123
- stripeProvider,
124
- authProvider,
125
- BILLING_CONFIG
126
- );
144
+ // ---------------------------------------------------------------------------
145
+ // Single-price items (StripePayment / StripeSubscription)
146
+ // ---------------------------------------------------------------------------
127
147
 
128
- expect(authProvider.getUser).toHaveBeenCalledOnce();
129
- expect(authProvider.getUser).toHaveBeenCalledWith('user_001');
148
+ describe('createCheckoutAlgorithm — single-price items', () => {
149
+ it('returns sessionId and sessionUrl', async () => {
150
+ const { result } = await run(singleItemRequest('pro_monthly'));
151
+ expect(result).toEqual({
152
+ sessionId: 'cs_test_session123',
153
+ sessionUrl: 'https://checkout.stripe.com/pay/cs_test_session123',
130
154
  });
155
+ });
131
156
 
132
- it('forwards priceId, mode, successUrl, cancelUrl to Stripe', async () => {
133
- await createCheckoutAlgorithm(
134
- BASE_REQUEST,
135
- stripeProvider,
136
- authProvider,
137
- BILLING_CONFIG
138
- );
139
-
140
- expect(stripeProvider.createCheckoutSession).toHaveBeenCalledWith(
141
- expect.objectContaining({
142
- priceId: VALID_PRICE_ID,
143
- mode: 'subscription',
144
- successUrl: 'https://app.example.com/billing/success',
145
- cancelUrl: 'https://app.example.com/billing/cancel',
146
- })
147
- );
157
+ it('subscription: config priceId, subscription mode, subscription metadata', async () => {
158
+ const { params } = await run(singleItemRequest('pro_monthly'));
159
+ expect(params).toMatchObject({
160
+ mode: 'subscription',
161
+ line_items: [{ price: 'price_pro', quantity: 1 }],
162
+ subscription_data: {
163
+ metadata: { userId: USER_ID, billingConfigKey: 'pro_monthly' },
164
+ },
148
165
  });
166
+ });
149
167
 
150
- it('ensures userId and billingConfigKey are set in session metadata', async () => {
151
- await createCheckoutAlgorithm(
152
- BASE_REQUEST,
153
- stripeProvider,
154
- authProvider,
155
- BILLING_CONFIG
156
- );
157
-
158
- expect(stripeProvider.createCheckoutSession).toHaveBeenCalledWith(
159
- expect.objectContaining({
160
- metadata: expect.objectContaining({
161
- userId: 'user_001',
162
- billingConfigKey: 'pro_monthly',
163
- }),
164
- })
165
- );
168
+ it('payment: config priceId, payment mode', async () => {
169
+ const { params } = await run(singleItemRequest('starter_once'));
170
+ expect(params).toMatchObject({
171
+ mode: 'payment',
172
+ line_items: [{ price: 'price_starter', quantity: 1 }],
166
173
  });
174
+ expect(params).not.toHaveProperty('subscription_data');
175
+ });
167
176
 
168
- it('passes customerEmail through when provided', async () => {
169
- const request: CreateCheckoutSessionRequest = {
170
- ...BASE_REQUEST,
171
- customerEmail: 'user@example.com',
172
- };
173
-
174
- await createCheckoutAlgorithm(
175
- request,
176
- stripeProvider,
177
- authProvider,
178
- BILLING_CONFIG
179
- );
180
-
181
- expect(stripeProvider.createCheckoutSession).toHaveBeenCalledWith(
182
- expect.objectContaining({ customerEmail: 'user@example.com' })
183
- );
184
- });
177
+ it('promotion codes: client choice, on by default (0.1.x behaviour)', async () => {
178
+ expect((await run(singleItemRequest('pro_monthly'))).params?.allow_promotion_codes).toBe(true);
179
+ expect(
180
+ (await run({ ...singleItemRequest('pro_monthly'), allowPromotionCodes: false }))
181
+ .params?.allow_promotion_codes
182
+ ).toBe(false);
183
+ });
185
184
 
186
- it('defaults allowPromotionCodes to true when not provided', async () => {
187
- const request: CreateCheckoutSessionRequest = {
188
- ...BASE_REQUEST,
189
- allowPromotionCodes: undefined,
190
- };
191
-
192
- await createCheckoutAlgorithm(
193
- request,
194
- stripeProvider,
195
- authProvider,
196
- BILLING_CONFIG
197
- );
198
-
199
- expect(stripeProvider.createCheckoutSession).toHaveBeenCalledWith(
200
- expect.objectContaining({ allowPromotionCodes: true })
201
- );
202
- });
185
+ it('fails loud when the back config item has no priceId', async () => {
186
+ const config = makeConfig();
187
+ const { priceId: _omit, ...noPrice } = config.starter_once as any;
188
+ config.starter_once = noPrice;
189
+ await expect(run(singleItemRequest('starter_once'), config)).rejects.toThrow(
190
+ /has no priceId/
191
+ );
192
+ });
203
193
 
204
- it('defaults mode to "payment" when not provided', async () => {
205
- const request: CreateCheckoutSessionRequest = {
206
- ...BASE_REQUEST,
207
- mode: undefined,
208
- };
209
-
210
- await createCheckoutAlgorithm(
211
- request,
212
- stripeProvider,
213
- authProvider,
214
- BILLING_CONFIG
215
- );
216
-
217
- expect(stripeProvider.createCheckoutSession).toHaveBeenCalledWith(
218
- expect.objectContaining({ mode: 'payment' })
219
- );
220
- });
194
+ it('rejects any line other than [{ productId: key, quantity: 1 }]', async () => {
195
+ await expect(
196
+ run({
197
+ ...singleItemRequest('starter_once'),
198
+ lineItems: [{ productId: 'starter_once', quantity: 3 }],
199
+ })
200
+ ).rejects.toThrow(/single-price item/);
201
+ await expect(
202
+ run({
203
+ ...singleItemRequest('starter_once'),
204
+ lineItems: [{ productId: 'other', quantity: 1 }],
205
+ })
206
+ ).rejects.toThrow(/single-price item/);
207
+ });
208
+ });
221
209
 
222
- it('handles null sessionUrl from Stripe', async () => {
223
- stripeProvider = makeStripeProvider({
224
- createCheckoutSession: vi.fn().mockResolvedValue({
225
- id: 'cs_test_no_url',
226
- url: null,
227
- }),
228
- });
229
-
230
- const result = await createCheckoutAlgorithm(
231
- BASE_REQUEST,
232
- stripeProvider,
233
- authProvider,
234
- BILLING_CONFIG
235
- );
236
-
237
- expect(result.sessionUrl).toBeNull();
238
- expect(result.sessionId).toBe('cs_test_no_url');
239
- });
210
+ // ---------------------------------------------------------------------------
211
+ // StripeOrder
212
+ // ---------------------------------------------------------------------------
213
+
214
+ describe('createCheckoutAlgorithm — StripeOrder', () => {
215
+ it('prices lines on the server and builds price_data excl. VAT with manual tax rates', async () => {
216
+ const order = makeOrderItem();
217
+ const { params } = await run(ORDER_REQUEST, makeConfig(order));
240
218
 
241
- it('works with a different valid billing config key', async () => {
242
- const request: CreateCheckoutSessionRequest = {
243
- ...BASE_REQUEST,
244
- priceId: 'price_starter_xyz',
245
- metadata: { billingConfigKey: 'starter_once' },
246
- mode: 'payment',
247
- };
248
-
249
- const result = await createCheckoutAlgorithm(
250
- request,
251
- stripeProvider,
252
- authProvider,
253
- BILLING_CONFIG
254
- );
255
-
256
- expect(result.sessionId).toBe('cs_test_session123');
219
+ expect(order.resolveLineItems).toHaveBeenCalledWith(ORDER_REQUEST.lineItems, {
220
+ userId: USER_ID,
221
+ billingConfigKey: 'shop_order',
222
+ metadata: {},
257
223
  });
224
+ expect(params?.mode).toBe('payment');
225
+ expect(params?.line_items).toEqual([
226
+ {
227
+ price_data: {
228
+ currency: 'eur',
229
+ unit_amount: 1250,
230
+ tax_behavior: 'exclusive',
231
+ product_data: {
232
+ name: 'Product serum-30ml',
233
+ metadata: { productId: 'serum-30ml' },
234
+ },
235
+ },
236
+ quantity: 24,
237
+ tax_rates: ['txr_fr_20'],
238
+ },
239
+ {
240
+ price_data: {
241
+ currency: 'eur',
242
+ unit_amount: 1250,
243
+ tax_behavior: 'exclusive',
244
+ product_data: {
245
+ name: 'Product toner-150ml',
246
+ metadata: { productId: 'toner-150ml' },
247
+ },
248
+ },
249
+ quantity: 12,
250
+ tax_rates: ['txr_fr_20'],
251
+ },
252
+ ]);
253
+ expect(params?.automatic_tax).toEqual({ enabled: false });
258
254
  });
259
255
 
260
- // -------------------------------------------------------------------------
261
- // Missing / invalid params
262
- // -------------------------------------------------------------------------
263
-
264
- describe('missing required params', () => {
265
- it('throws when billingConfigKey is absent from metadata', async () => {
266
- const request: CreateCheckoutSessionRequest = {
267
- ...BASE_REQUEST,
268
- metadata: {},
269
- };
270
-
271
- await expect(
272
- createCheckoutAlgorithm(
273
- request,
274
- stripeProvider,
275
- authProvider,
276
- BILLING_CONFIG
277
- )
278
- ).rejects.toThrow('Missing billingConfigKey in metadata');
256
+ it('applies the B2B options from the back config', async () => {
257
+ const order = makeOrderItem({
258
+ taxIdCollection: 'required',
259
+ shipping: { allowedCountries: ['FR', 'BE'], shippingRateIds: ['shr_std'] },
260
+ paymentMethodConfiguration: 'pmc_card_sepa',
279
261
  });
262
+ const { params } = await run(ORDER_REQUEST, makeConfig(order));
263
+
264
+ expect(params).toMatchObject({
265
+ client_reference_id: 'ord_42',
266
+ tax_id_collection: { enabled: true, required: 'if_supported' },
267
+ billing_address_collection: 'required',
268
+ shipping_address_collection: { allowed_countries: ['FR', 'BE'] },
269
+ shipping_options: [{ shipping_rate: 'shr_std' }],
270
+ customer_creation: 'always',
271
+ invoice_creation: {
272
+ enabled: true,
273
+ invoice_data: {
274
+ metadata: { userId: USER_ID, billingConfigKey: 'shop_order', orderId: 'ord_42' },
275
+ },
276
+ },
277
+ payment_method_configuration: 'pmc_card_sepa',
278
+ payment_intent_data: {
279
+ metadata: { userId: USER_ID, billingConfigKey: 'shop_order', orderId: 'ord_42' },
280
+ },
281
+ });
282
+ });
283
+
284
+ it('automatic tax: Stripe Tax on, no tax_rates on lines', async () => {
285
+ const order = makeOrderItem({ tax: { mode: 'automatic' } });
286
+ const { params } = await run(ORDER_REQUEST, makeConfig(order));
287
+
288
+ expect(params?.automatic_tax).toEqual({ enabled: true });
289
+ for (const line of params?.line_items ?? []) {
290
+ expect(line).not.toHaveProperty('tax_rates');
291
+ }
292
+ });
293
+
294
+ it('disabled tax ID collection and no shipping', async () => {
295
+ const order = makeOrderItem({ taxIdCollection: 'disabled', invoiceCreation: false });
296
+ const { params } = await run(ORDER_REQUEST, makeConfig(order));
297
+
298
+ expect(params?.tax_id_collection).toEqual({ enabled: false });
299
+ expect(params?.invoice_creation).toEqual({ enabled: false });
300
+ expect(params).not.toHaveProperty('shipping_address_collection');
301
+ expect(params).not.toHaveProperty('payment_method_configuration');
302
+ });
280
303
 
281
- it('throws when metadata itself is undefined', async () => {
282
- const request: CreateCheckoutSessionRequest = {
283
- ...BASE_REQUEST,
284
- metadata: undefined,
285
- };
286
-
287
- await expect(
288
- createCheckoutAlgorithm(
289
- request,
290
- stripeProvider,
291
- authProvider,
292
- BILLING_CONFIG
293
- )
294
- ).rejects.toThrow('Missing billingConfigKey in metadata');
304
+ it('server metadata (userId, billingConfigKey, orderId) cannot be overwritten by the client', async () => {
305
+ const { params } = await run({
306
+ ...ORDER_REQUEST,
307
+ metadata: { userId: 'attacker', orderId: 'ord_fake', billingConfigKey: 'x', note: 'ok' },
295
308
  });
309
+ expect(params?.metadata).toEqual({
310
+ note: 'ok',
311
+ userId: USER_ID,
312
+ billingConfigKey: 'shop_order',
313
+ orderId: 'ord_42',
314
+ });
315
+ });
296
316
 
297
- it('does not call Stripe when billingConfigKey is missing', async () => {
298
- const request: CreateCheckoutSessionRequest = {
299
- ...BASE_REQUEST,
300
- metadata: {},
301
- };
302
-
303
- await expect(
304
- createCheckoutAlgorithm(
305
- request,
306
- stripeProvider,
307
- authProvider,
308
- BILLING_CONFIG
309
- )
310
- ).rejects.toThrow();
311
-
312
- expect(stripeProvider.createCheckoutSession).not.toHaveBeenCalled();
317
+ it.each([
318
+ ['negative amount', { unitAmount: -1 }],
319
+ ['fractional amount', { unitAmount: 12.5 }],
320
+ ['zero quantity', { quantity: 0 }],
321
+ ['empty name', { name: '' }],
322
+ ])('fails loud on a malformed resolved line (%s)', async (_label, patch) => {
323
+ const order = makeOrderItem({
324
+ resolveLineItems: vi.fn(async () => ({
325
+ orderId: 'ord_bad',
326
+ lineItems: [
327
+ { productId: 'p', name: 'P', unitAmount: 100, quantity: 1, ...patch },
328
+ ],
329
+ })),
313
330
  });
331
+ const stripe = makeStripeProvider();
332
+ await expect(run(ORDER_REQUEST, makeConfig(order), stripe)).rejects.toThrow();
333
+ expect(stripe.createStripeSession).not.toHaveBeenCalled();
314
334
  });
315
335
 
316
- // -------------------------------------------------------------------------
317
- // Invalid plan / price
318
- // -------------------------------------------------------------------------
319
-
320
- describe('invalid plan / price', () => {
321
- it('throws when billingConfigKey does not exist in config', async () => {
322
- const request: CreateCheckoutSessionRequest = {
323
- ...BASE_REQUEST,
324
- metadata: { billingConfigKey: 'nonexistent_plan' },
325
- };
326
-
327
- await expect(
328
- createCheckoutAlgorithm(
329
- request,
330
- stripeProvider,
331
- authProvider,
332
- BILLING_CONFIG
333
- )
334
- ).rejects.toThrow('Invalid billing config key: nonexistent_plan');
336
+ it('fails loud when the resolver returns no orderId', async () => {
337
+ const order = makeOrderItem({
338
+ resolveLineItems: vi.fn(async () => ({
339
+ orderId: '',
340
+ lineItems: [{ productId: 'p', name: 'P', unitAmount: 100, quantity: 1 }],
341
+ })),
335
342
  });
343
+ await expect(run(ORDER_REQUEST, makeConfig(order))).rejects.toThrow(/orderId/);
344
+ });
336
345
 
337
- it('throws when priceId does not match the config entry', async () => {
338
- const request: CreateCheckoutSessionRequest = {
339
- ...BASE_REQUEST,
340
- priceId: 'price_wrong_one',
341
- metadata: { billingConfigKey: 'pro_monthly' },
342
- };
343
-
344
- await expect(
345
- createCheckoutAlgorithm(
346
- request,
347
- stripeProvider,
348
- authProvider,
349
- BILLING_CONFIG
350
- )
351
- ).rejects.toThrow('Price ID mismatch with configuration');
346
+ it('propagates resolver errors (unknown product, stock) without calling Stripe', async () => {
347
+ const order = makeOrderItem({
348
+ resolveLineItems: vi.fn(async () => {
349
+ throw new Error('Unknown product: serum-30ml');
350
+ }),
352
351
  });
352
+ const stripe = makeStripeProvider();
353
+ await expect(run(ORDER_REQUEST, makeConfig(order), stripe)).rejects.toThrow(
354
+ 'Unknown product: serum-30ml'
355
+ );
356
+ expect(stripe.createStripeSession).not.toHaveBeenCalled();
357
+ });
358
+ });
353
359
 
354
- it('does not call Stripe when priceId mismatches config', async () => {
355
- const request: CreateCheckoutSessionRequest = {
356
- ...BASE_REQUEST,
357
- priceId: 'price_totally_different',
358
- metadata: { billingConfigKey: 'pro_monthly' },
359
- };
360
-
361
- await expect(
362
- createCheckoutAlgorithm(
363
- request,
364
- stripeProvider,
365
- authProvider,
366
- BILLING_CONFIG
367
- )
368
- ).rejects.toThrow();
369
-
370
- expect(stripeProvider.createCheckoutSession).not.toHaveBeenCalled();
360
+ // ---------------------------------------------------------------------------
361
+ // StripeOrder per-order session options (ResolvedOrder.session)
362
+ // ---------------------------------------------------------------------------
363
+
364
+ describe('createCheckoutAlgorithm — StripeOrder session options', () => {
365
+ const line = { productId: 'p', name: 'P', unitAmount: 1000, quantity: 1 };
366
+ const withSession = (session: object, overrides: Partial<StripeOrderBackItem> = {}) =>
367
+ makeOrderItem({
368
+ paymentMethodConfiguration: 'pmc_default',
369
+ resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [line], session })),
370
+ ...overrides,
371
371
  });
372
+
373
+ it('per-order tax rates replace the configured ones; [] sends no tax_rates (reverse charge)', async () => {
374
+ const replaced = await run(ORDER_REQUEST, makeConfig(withSession({ taxRateIds: ['txr_fr_55'] })));
375
+ expect(replaced.params!.line_items![0]!.tax_rates).toEqual(['txr_fr_55']);
376
+ const none = await run(ORDER_REQUEST, makeConfig(withSession({ taxRateIds: [] })));
377
+ expect(none.params!.line_items![0]!.tax_rates).toBeUndefined();
378
+ });
379
+
380
+ it('rejects an inclusive per-order tax rate and per-order rates under automatic tax', async () => {
381
+ await expect(
382
+ run(ORDER_REQUEST, makeConfig(withSession({ taxRateIds: ['txr_incl_override'] })))
383
+ ).rejects.toThrow(/inclusive/);
384
+ await expect(
385
+ run(ORDER_REQUEST, makeConfig(withSession({ taxRateIds: [] }, { tax: { mode: 'automatic' } })))
386
+ ).rejects.toThrow(/tax.mode 'manual'/);
372
387
  });
373
388
 
374
- // -------------------------------------------------------------------------
375
- // Auth validation
376
- // -------------------------------------------------------------------------
389
+ it('payment method types replace the configuration; expiry and invoice footer are set', async () => {
390
+ const expiresAt = Math.floor(Date.now() / 1000) + 3600;
391
+ const { params } = await run(
392
+ ORDER_REQUEST,
393
+ makeConfig(withSession({ paymentMethodTypes: ['sepa_debit'], expiresAt, invoiceFooter: 'Autoliquidation' }))
394
+ );
395
+ expect(params!.payment_method_types).toEqual(['sepa_debit']);
396
+ expect(params!.payment_method_configuration).toBeUndefined();
397
+ expect(params!.expires_at).toBe(expiresAt);
398
+ expect(params!.invoice_creation!.invoice_data!.footer).toBe('Autoliquidation');
399
+ });
377
400
 
378
- describe('auth validation', () => {
379
- it('calls getUser with the request userId', async () => {
380
- await createCheckoutAlgorithm(
381
- BASE_REQUEST,
382
- stripeProvider,
383
- authProvider,
384
- BILLING_CONFIG
385
- );
401
+ it('without session options the back config applies unchanged', async () => {
402
+ const { params } = await run(ORDER_REQUEST, makeConfig(withSession({})));
403
+ expect(params!.payment_method_configuration).toBe('pmc_default');
404
+ expect(params!.payment_method_types).toBeUndefined();
405
+ expect(params!.expires_at).toBeUndefined();
406
+ expect(params!.line_items![0]!.tax_rates).toEqual(['txr_fr_20']);
407
+ });
386
408
 
387
- expect(authProvider.getUser).toHaveBeenCalledWith('user_001');
388
- });
409
+ it('fails loud on an expiry outside Stripe 30 min – 24 h, empty methods, or a footer without invoices', async () => {
410
+ const now = Math.floor(Date.now() / 1000);
411
+ await expect(run(ORDER_REQUEST, makeConfig(withSession({ expiresAt: now + 60 })))).rejects.toThrow(/expiresAt/);
412
+ await expect(run(ORDER_REQUEST, makeConfig(withSession({ expiresAt: now + 2 * 86400 })))).rejects.toThrow(/expiresAt/);
413
+ await expect(run(ORDER_REQUEST, makeConfig(withSession({ paymentMethodTypes: [] })))).rejects.toThrow(/paymentMethodTypes/);
414
+ await expect(
415
+ run(ORDER_REQUEST, makeConfig(withSession({ invoiceFooter: 'x' }, { invoiceCreation: false })))
416
+ ).rejects.toThrow(/invoiceCreation/);
417
+ });
418
+ });
389
419
 
390
- it('propagates error when getUser rejects', async () => {
391
- authProvider = makeAuthProvider({
392
- getUser: vi.fn().mockRejectedValue(new Error('User not found')),
393
- });
394
-
395
- await expect(
396
- createCheckoutAlgorithm(
397
- BASE_REQUEST,
398
- stripeProvider,
399
- authProvider,
400
- BILLING_CONFIG
401
- )
402
- ).rejects.toThrow('User not found');
403
- });
420
+ // ---------------------------------------------------------------------------
421
+ // Common validation
422
+ // ---------------------------------------------------------------------------
404
423
 
405
- it('does not call Stripe when auth fails', async () => {
406
- authProvider = makeAuthProvider({
407
- getUser: vi.fn().mockRejectedValue(new Error('Unauthenticated')),
408
- });
409
-
410
- await expect(
411
- createCheckoutAlgorithm(
412
- BASE_REQUEST,
413
- stripeProvider,
414
- authProvider,
415
- BILLING_CONFIG
416
- )
417
- ).rejects.toThrow();
418
-
419
- expect(stripeProvider.createCheckoutSession).not.toHaveBeenCalled();
420
- });
424
+ describe('createCheckoutAlgorithm — validation', () => {
425
+ it('throws on an unknown billing config key', async () => {
426
+ await expect(run(singleItemRequest('nope'))).rejects.toThrow(
427
+ /Invalid billing config key/
428
+ );
421
429
  });
422
430
 
423
- // -------------------------------------------------------------------------
424
- // Stripe error handling
425
- // -------------------------------------------------------------------------
426
-
427
- describe('Stripe error handling', () => {
428
- it('propagates Stripe API errors', async () => {
429
- stripeProvider = makeStripeProvider({
430
- createCheckoutSession: vi
431
- .fn()
432
- .mockRejectedValue(new Error('Stripe network error')),
433
- });
434
-
435
- await expect(
436
- createCheckoutAlgorithm(
437
- BASE_REQUEST,
438
- stripeProvider,
439
- authProvider,
440
- BILLING_CONFIG
441
- )
442
- ).rejects.toThrow('Stripe network error');
443
- });
431
+ it('throws without an authenticated userId', async () => {
432
+ await expect(
433
+ createCheckoutAlgorithm(
434
+ singleItemRequest('pro_monthly'),
435
+ '',
436
+ makeStripeProvider(),
437
+ makeAuthProvider(),
438
+ makeConfig()
439
+ )
440
+ ).rejects.toThrow(/userId/);
441
+ });
444
442
 
445
- it('propagates Stripe card declined errors', async () => {
446
- stripeProvider = makeStripeProvider({
447
- createCheckoutSession: vi
448
- .fn()
449
- .mockRejectedValue(new Error('Your card was declined')),
450
- });
451
-
452
- await expect(
453
- createCheckoutAlgorithm(
454
- BASE_REQUEST,
455
- stripeProvider,
456
- authProvider,
457
- BILLING_CONFIG
458
- )
459
- ).rejects.toThrow('Your card was declined');
460
- });
443
+ it('verifies the user before creating the session', async () => {
444
+ const { auth } = await run(singleItemRequest('pro_monthly'));
445
+ expect(auth.getUser).toHaveBeenCalledWith(USER_ID);
446
+ });
447
+
448
+ it('propagates getUser errors', async () => {
449
+ const auth: AuthCheckoutProvider = {
450
+ getUser: vi.fn(async () => {
451
+ throw new Error('auth/user-not-found');
452
+ }),
453
+ };
454
+ await expect(
455
+ run(singleItemRequest('pro_monthly'), makeConfig(), makeStripeProvider(), auth)
456
+ ).rejects.toThrow('auth/user-not-found');
457
+ });
458
+
459
+ it('beforeCheckout can block', async () => {
460
+ const config = makeConfig(
461
+ makeOrderItem({
462
+ beforeCheckout: vi.fn(async () => ({ allowed: false, reason: 'Account not approved' })),
463
+ })
464
+ );
465
+ await expect(run(ORDER_REQUEST, config)).rejects.toThrow('Account not approved');
466
+ });
461
467
 
462
- it('propagates Stripe rate limit errors', async () => {
463
- stripeProvider = makeStripeProvider({
464
- createCheckoutSession: vi
465
- .fn()
466
- .mockRejectedValue(new Error('Too many requests to the Stripe API')),
467
- });
468
-
469
- await expect(
470
- createCheckoutAlgorithm(
471
- BASE_REQUEST,
472
- stripeProvider,
473
- authProvider,
474
- BILLING_CONFIG
475
- )
476
- ).rejects.toThrow('Too many requests');
468
+ it('rejects non-http redirect URLs', async () => {
469
+ await expect(
470
+ run({ ...singleItemRequest('pro_monthly'), successUrl: 'javascript:alert(1)' })
471
+ ).rejects.toThrow(/Invalid success URL/);
472
+ });
473
+
474
+ it('rejects non-string metadata values', async () => {
475
+ await expect(
476
+ run({
477
+ ...singleItemRequest('pro_monthly'),
478
+ metadata: { n: 1 as unknown as string },
479
+ })
480
+ ).rejects.toThrow(/must be a string/);
481
+ });
482
+
483
+ it('propagates Stripe errors', async () => {
484
+ const stripe = makeStripeProvider();
485
+ stripe.createStripeSession.mockRejectedValueOnce(new Error('card_declined'));
486
+ await expect(
487
+ run(singleItemRequest('pro_monthly'), makeConfig(), stripe)
488
+ ).rejects.toThrow('card_declined');
489
+ });
490
+ });
491
+
492
+ // ---------------------------------------------------------------------------
493
+ // 0.1.x request compatibility (real schema)
494
+ // ---------------------------------------------------------------------------
495
+
496
+ describe('CreateCheckoutSessionRequestSchema — 0.1.x clients', () => {
497
+ it('normalizes a 0.1.x request (key in metadata, priceId/mode kept) to the single line', async () => {
498
+ const legacy = {
499
+ priceId: 'price_pro',
500
+ mode: 'subscription',
501
+ userId: 'spoofed',
502
+ ...URLS,
503
+ metadata: { billingConfigKey: 'pro_monthly' },
504
+ allowPromotionCodes: true,
505
+ };
506
+ const parsed = v.parse(CreateCheckoutSessionRequestSchema, legacy);
507
+ expect(parsed.billingConfigKey).toBe('pro_monthly');
508
+ expect(parsed.lineItems).toEqual([{ productId: 'pro_monthly', quantity: 1 }]);
509
+ expect(parsed.priceId).toBe('price_pro');
510
+ expect(parsed.mode).toBe('subscription');
511
+
512
+ // userId argument wins over the client value
513
+ const { params } = await run(parsed);
514
+ expect(params?.line_items).toEqual([{ price: 'price_pro', quantity: 1 }]);
515
+ expect(params?.metadata?.userId).toBe(USER_ID);
516
+ });
517
+
518
+ it('rejects a 0.1.x priceId that does not match the back config priceId', async () => {
519
+ const parsed = v.parse(CreateCheckoutSessionRequestSchema, {
520
+ priceId: 'price_client_supplied',
521
+ ...URLS,
522
+ metadata: { billingConfigKey: 'pro_monthly' },
477
523
  });
524
+ await expect(run(parsed)).rejects.toThrow('Price ID mismatch with configuration');
525
+ });
478
526
 
479
- it('does not swallow unknown errors from Stripe', async () => {
480
- const unexpected = new Error('Unexpected internal Stripe error');
481
-
482
- stripeProvider = makeStripeProvider({
483
- createCheckoutSession: vi.fn().mockRejectedValue(unexpected),
484
- });
485
-
486
- await expect(
487
- createCheckoutAlgorithm(
488
- BASE_REQUEST,
489
- stripeProvider,
490
- authProvider,
491
- BILLING_CONFIG
492
- )
493
- ).rejects.toBe(unexpected);
527
+ it('rejects a request with no billingConfigKey anywhere', () => {
528
+ const result = v.safeParse(CreateCheckoutSessionRequestSchema, {
529
+ priceId: 'price_x',
530
+ ...URLS,
494
531
  });
532
+ expect(result.success).toBe(false);
533
+ });
534
+
535
+ it('keeps an explicit order request as sent', () => {
536
+ const parsed = v.parse(CreateCheckoutSessionRequestSchema, ORDER_REQUEST);
537
+ expect(parsed.lineItems).toEqual(ORDER_REQUEST.lineItems);
495
538
  });
496
539
  });