@donotdev/functions 0.1.44 → 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
@@ -2,47 +2,83 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview Create Checkout Session Algorithm
5
- * @description Platform-agnostic algorithm for creating Stripe checkout sessions
5
+ * @description Platform-agnostic algorithm for creating Stripe checkout sessions.
6
+ * StripePayment/StripeSubscription items keep the 0.1.x behaviour (request or
7
+ * back-config priceId, 0.1.x dynamic pricing). StripeOrder items are priced on
8
+ * the server (`resolveLineItems`) and need a {@link StripeSessionProvider}.
6
9
  *
7
- * @version 0.1.0
10
+ * @version 0.2.0
8
11
  * @since 0.0.1
9
12
  * @author AMBROISE PARK Consulting
10
13
  */
11
14
 
15
+ import type Stripe from 'stripe';
16
+
12
17
  import type {
18
+ BeforeCheckoutOptions,
19
+ CheckoutSessionParams,
20
+ CheckoutSessionResult,
13
21
  CreateCheckoutSessionRequest,
22
+ CreateCheckoutSessionRequestInput,
14
23
  CreateCheckoutSessionResponse,
24
+ ResolvedOrder,
15
25
  StripeBackConfig,
26
+ StripeCheckoutProvider,
27
+ StripeOrderBackItem,
16
28
  } from '@donotdev/core/server';
17
29
 
30
+ import { resolvePricePlan, toStripeSessionParams } from './checkoutPrice.js';
31
+ import {
32
+ assertCheckoutSessionMetadata,
33
+ assertExclusiveTaxRates,
34
+ assertResolvedOrder,
35
+ assertStripeMetadata,
36
+ sanitizeMetadata,
37
+ validateCheckoutUrl,
38
+ } from './checkoutValidation.js';
39
+ import {
40
+ ORDER_ID_METADATA_KEY,
41
+ PRODUCT_ID_METADATA_KEY,
42
+ } from './orderWebhook.js';
43
+
18
44
  /**
19
- * Provider interface for Stripe checkout operations
45
+ * Provider that sends full Stripe session params (every item type, StripeOrder included).
20
46
  *
21
- * @version 0.1.0
22
- * @since 0.0.1
47
+ * @example
48
+ * ```typescript
49
+ * const provider: StripeSessionProvider = {
50
+ * async createStripeSession(params) {
51
+ * const session = await stripe.checkout.sessions.create(params);
52
+ * return { id: session.id, url: session.url };
53
+ * },
54
+ * async retrieveTaxRate(id) {
55
+ * const rate = await stripe.taxRates.retrieve(id);
56
+ * return { id: rate.id, inclusive: rate.inclusive };
57
+ * },
58
+ * };
59
+ * ```
60
+ *
61
+ * @version 0.2.0
62
+ * @since 0.2.0
23
63
  * @author AMBROISE PARK Consulting
24
64
  */
25
- export interface StripeCheckoutProvider {
26
- createCheckoutSession(params: {
27
- priceId?: string;
28
- /** Amount in cents (dynamic pricing mode) */
29
- unitAmount?: number;
30
- /** Product name for Stripe checkout (dynamic pricing mode) */
31
- productName?: string;
32
- /** Currency code, defaults to 'eur' */
33
- currency?: string;
34
- customerEmail?: string;
35
- metadata: Record<string, string>;
36
- allowPromotionCodes: boolean;
37
- successUrl: string;
38
- cancelUrl: string;
39
- mode?: 'payment' | 'subscription';
40
- }): Promise<{
41
- id: string;
42
- url: string | null;
43
- }>;
65
+ export interface StripeSessionProvider {
66
+ createStripeSession(
67
+ params: Stripe.Checkout.SessionCreateParams
68
+ ): Promise<CheckoutSessionResult>;
69
+ /** Used to reject inclusive Tax Rates on StripeOrder manual tax (cached per instance). */
70
+ retrieveTaxRate(taxRateId: string): Promise<{ id: string; inclusive: boolean }>;
44
71
  }
45
72
 
73
+ /**
74
+ * Any provider accepted by {@link createCheckoutAlgorithm}.
75
+ *
76
+ * @version 0.2.0
77
+ * @since 0.2.0
78
+ * @author AMBROISE PARK Consulting
79
+ */
80
+ export type CheckoutProvider = StripeCheckoutProvider | StripeSessionProvider;
81
+
46
82
  /**
47
83
  * Provider interface for authentication operations
48
84
  *
@@ -56,223 +92,323 @@ export interface AuthCheckoutProvider {
56
92
  }>;
57
93
  }
58
94
 
59
- /**
60
- * Validate URL has http/https protocol.
61
- * Platform-agnostic (no firebase logger dependency).
62
- */
63
- function validateCheckoutUrl(url: string, name: string): void {
64
- try {
65
- const parsed = new URL(url);
66
- if (!['http:', 'https:'].includes(parsed.protocol)) {
67
- throw new Error(`Invalid protocol: ${parsed.protocol}`);
68
- }
69
- } catch (error) {
70
- throw new Error(
71
- `Invalid ${name} URL: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`
72
- );
95
+ function isSessionProvider(
96
+ provider: CheckoutProvider
97
+ ): provider is StripeSessionProvider {
98
+ return 'createStripeSession' in provider;
99
+ }
100
+
101
+ /** 0.1.x: empty redirect URLs default to FRONTEND_URL pages. */
102
+ function resolveRedirectUrl(url: string, path: string): string {
103
+ if (url) return url;
104
+ const frontendUrl = process.env.FRONTEND_URL;
105
+ if (!frontendUrl) {
106
+ throw new Error(`Missing ${path} redirect URL and FRONTEND_URL is not set`);
73
107
  }
108
+ return `${frontendUrl}/billing/${path}`;
109
+ }
110
+
111
+ /** Common session params for StripeOrder. */
112
+ interface BaseSessionParams {
113
+ successUrl: string;
114
+ cancelUrl: string;
115
+ customerEmail: string | undefined;
116
+ metadata: Record<string, string>;
74
117
  }
75
118
 
76
119
  /**
77
- * Sanitize metadata: enforce string values, strip script injection, cap lengths.
78
- * Platform-agnostic (no firebase logger dependency).
120
+ * Session params for a StripeOrder: server-priced lines (excl. VAT) and the
121
+ * item's B2B options.
79
122
  */
80
- function sanitizeMetadata(
81
- metadata: Record<string, any>
82
- ): Record<string, string> {
83
- const sanitized: Record<string, string> = {};
84
-
85
- for (const [key, value] of Object.entries(metadata)) {
86
- if (typeof value !== 'string') {
87
- throw new Error(
88
- `Metadata value for key '${key}' must be a string, got ${typeof value}`
89
- );
90
- }
91
-
92
- const sanitizedValue = value
93
- .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
94
- .replace(/javascript:/gi, '')
95
- .replace(/on\w+\s*=/gi, '');
96
-
97
- if (sanitizedValue.length > 1000) {
98
- throw new Error(
99
- `Metadata value for key '${key}' is too long (max 1000 characters)`
100
- );
101
- }
102
-
103
- if (key.length > 100) {
104
- throw new Error(`Metadata key '${key}' is too long (max 100 characters)`);
105
- }
106
-
107
- sanitized[key] = sanitizedValue;
108
- }
123
+ function buildOrderSessionParams(
124
+ item: StripeOrderBackItem,
125
+ order: ResolvedOrder,
126
+ base: BaseSessionParams
127
+ ): Stripe.Checkout.SessionCreateParams {
128
+ const options = order.session ?? {};
129
+ const taxRates =
130
+ item.tax.mode === 'manual'
131
+ ? (options.taxRateIds ?? item.tax.taxRateIds)
132
+ : undefined;
133
+ const metadata = { ...base.metadata, [ORDER_ID_METADATA_KEY]: order.orderId };
109
134
 
110
- return sanitized;
135
+ return {
136
+ mode: 'payment',
137
+ client_reference_id: order.orderId,
138
+ line_items: order.lineItems.map((line) => ({
139
+ price_data: {
140
+ currency: item.currency,
141
+ unit_amount: line.unitAmount,
142
+ tax_behavior: 'exclusive',
143
+ product_data: {
144
+ name: line.name,
145
+ ...(line.description && { description: line.description }),
146
+ metadata: { [PRODUCT_ID_METADATA_KEY]: line.productId },
147
+ },
148
+ },
149
+ quantity: line.quantity,
150
+ ...(taxRates && taxRates.length > 0 && { tax_rates: taxRates }),
151
+ })),
152
+ automatic_tax: { enabled: item.tax.mode === 'automatic' },
153
+ tax_id_collection:
154
+ item.taxIdCollection === 'disabled'
155
+ ? { enabled: false }
156
+ : {
157
+ enabled: true,
158
+ required:
159
+ item.taxIdCollection === 'required' ? 'if_supported' : 'never',
160
+ },
161
+ billing_address_collection: item.billingAddressCollection,
162
+ ...(item.shipping && {
163
+ shipping_address_collection: {
164
+ // Config validated as uppercase ISO 3166-1 alpha-2; stripe@20 types the param as a closed enum
165
+ allowed_countries: item.shipping
166
+ .allowedCountries as Stripe.Checkout.SessionCreateParams.ShippingAddressCollection.AllowedCountry[],
167
+ },
168
+ ...(item.shipping.shippingRateIds && {
169
+ shipping_options: item.shipping.shippingRateIds.map((id) => ({
170
+ shipping_rate: id,
171
+ })),
172
+ }),
173
+ }),
174
+ customer_creation: item.customerCreation,
175
+ invoice_creation: {
176
+ enabled: item.invoiceCreation,
177
+ ...(item.invoiceCreation && {
178
+ invoice_data: {
179
+ metadata,
180
+ ...(options.invoiceFooter && { footer: options.invoiceFooter }),
181
+ },
182
+ }),
183
+ },
184
+ // Per-order methods replace the configuration (Stripe accepts one or the other)
185
+ ...(options.paymentMethodTypes
186
+ ? { payment_method_types: options.paymentMethodTypes }
187
+ : item.paymentMethodConfiguration && {
188
+ payment_method_configuration: item.paymentMethodConfiguration,
189
+ }),
190
+ ...(options.expiresAt !== undefined && { expires_at: options.expiresAt }),
191
+ // Orders: merchant policy from the back config only
192
+ allow_promotion_codes: item.allowPromotionCodes === true,
193
+ success_url: base.successUrl,
194
+ cancel_url: base.cancelUrl,
195
+ customer_email: base.customerEmail,
196
+ metadata,
197
+ payment_intent_data: { metadata },
198
+ };
111
199
  }
112
200
 
201
+ type CheckoutArgs =
202
+ | [CheckoutProvider, AuthCheckoutProvider, StripeBackConfig]
203
+ | [string, CheckoutProvider, AuthCheckoutProvider, StripeBackConfig];
204
+
113
205
  /**
114
206
  * Create checkout session algorithm
115
207
  *
208
+ * 1. Resolve the billing config item and verify the user
209
+ * 2. Single-price items: 0.1.x pricing (request/back-config priceId, dynamic pricing)
210
+ * 3. `beforeCheckout` hook (block/allow; 0.1.x dynamic-pricing overrides)
211
+ * 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
212
+ * and may set per-order session options (`ResolvedOrder.session`: tax rates,
213
+ * payment methods, expiry, invoice footer)
214
+ * 5. Validate metadata against Stripe limits, create the session through the provider
215
+ *
216
+ * Server-owned metadata (`userId`, `billingConfigKey`, `orderId`) is written after
217
+ * the client metadata and cannot be overwritten by it.
218
+ *
219
+ * Two call shapes:
220
+ * - `(request, userId, stripeProvider, authProvider, billingConfig)`: userId from
221
+ * the provider's auth context (framework providers use this).
222
+ * - 0.1.x `(request, stripeProvider, authProvider, billingConfig)`: userId read from
223
+ * `request.userId` (the caller must set it from its auth context).
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * const result = await createCheckoutAlgorithm(
228
+ * request,
229
+ * context.uid,
230
+ * stripeSessionProvider,
231
+ * authProvider,
232
+ * billingConfig
233
+ * );
234
+ * ```
235
+ *
236
+ * @param request - Validated client request (0.1.x shape accepted)
237
+ * @param userId - Authenticated user ID (omit in the 0.1.x call shape)
238
+ * @param stripeProvider - {@link StripeSessionProvider}, or 0.1.x {@link StripeCheckoutProvider} (single-price items only)
239
+ * @param authProvider - Verifies the user exists
240
+ * @param billingConfig - App back config
241
+ *
116
242
  * @version 0.2.0
117
243
  * @since 0.0.1
118
244
  * @author AMBROISE PARK Consulting
119
245
  */
120
246
  export async function createCheckoutAlgorithm(
121
- request: CreateCheckoutSessionRequest,
122
- stripeProvider: StripeCheckoutProvider,
247
+ request: CreateCheckoutSessionRequestInput,
248
+ userId: string,
249
+ stripeProvider: CheckoutProvider,
123
250
  authProvider: AuthCheckoutProvider,
124
251
  billingConfig: StripeBackConfig
252
+ ): Promise<CreateCheckoutSessionResponse>;
253
+ export async function createCheckoutAlgorithm(
254
+ request: CreateCheckoutSessionRequestInput,
255
+ stripeProvider: CheckoutProvider,
256
+ authProvider: AuthCheckoutProvider,
257
+ billingConfig: StripeBackConfig
258
+ ): Promise<CreateCheckoutSessionResponse>;
259
+ export async function createCheckoutAlgorithm(
260
+ input: CreateCheckoutSessionRequestInput,
261
+ ...args: CheckoutArgs
125
262
  ): Promise<CreateCheckoutSessionResponse> {
126
- if (!process.env.FRONTEND_URL) {
127
- throw new Error('FRONTEND_URL environment variable is required');
128
- }
129
-
130
- const {
131
- priceId,
132
- unitAmount,
133
- productName,
134
- currency,
135
- userId,
136
- customerEmail,
137
- metadata = {},
138
- allowPromotionCodes = true,
139
- successUrl,
140
- cancelUrl,
141
- mode = 'payment',
142
- } = request;
143
-
144
- // ✅ VALIDATE: billingConfigKey exists
145
- const configKey = metadata.billingConfigKey;
146
- if (!configKey) {
147
- throw new Error('Missing billingConfigKey in metadata');
148
- }
149
-
150
- // ✅ VALIDATE: config key is valid
151
- const billingItem = billingConfig[configKey];
152
- if (!billingItem) {
153
- throw new Error(`Invalid billing config key: ${configKey}`);
154
- }
155
-
156
- // ✅ VALIDATE: either priceId or (unitAmount + productName)
157
- const useDynamicPricing = !priceId && unitAmount && productName;
158
- if (!priceId && !useDynamicPricing) {
159
- throw new Error('Either priceId or (unitAmount + productName) is required');
160
- }
161
-
162
- // ✅ VALIDATE: price_data not supported for subscriptions
163
- if (useDynamicPricing && mode === 'subscription') {
263
+ const legacyCall = args.length === 3;
264
+ const [userId, stripeProvider, authProvider, billingConfig] =
265
+ args.length === 3 ? [input.userId, ...args] : args;
266
+ if (!userId) {
164
267
  throw new Error(
165
- 'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
268
+ legacyCall ? 'Missing userId in request' : 'Missing authenticated userId'
166
269
  );
167
270
  }
168
271
 
169
- if (priceId) {
170
- // Fixed pricing: validate priceId matches config (if config has one)
171
- if (billingItem.priceId && billingItem.priceId !== priceId) {
172
- throw new Error('Price ID mismatch with configuration');
173
- }
174
- } else {
175
- // Dynamic pricing: maxUnitAmount is required as a security cap
176
- if (!billingItem.maxUnitAmount) {
177
- throw new Error(
178
- 'Dynamic pricing requires maxUnitAmount in billing config for security'
179
- );
180
- }
181
- if (unitAmount! > billingItem.maxUnitAmount) {
182
- throw new Error(
183
- `Unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
184
- );
185
- }
186
- if (unitAmount! < 100) {
187
- throw new Error('Unit amount must be at least 100 cents (1.00)');
188
- }
272
+ const billingConfigKey =
273
+ input.billingConfigKey || input.metadata?.billingConfigKey;
274
+ if (!billingConfigKey) {
275
+ throw new Error('Missing billingConfigKey (request or metadata)');
189
276
  }
277
+ const request: CreateCheckoutSessionRequest = {
278
+ ...input,
279
+ billingConfigKey,
280
+ lineItems: input.lineItems ?? [{ productId: billingConfigKey, quantity: 1 }],
281
+ };
190
282
 
191
- // ✅ VALIDATE: userId exists
192
- if (!userId) {
193
- throw new Error('Missing userId in request');
283
+ const billingItem = billingConfig[billingConfigKey];
284
+ if (!billingItem) {
285
+ throw new Error(`Invalid billing config key: ${billingConfigKey}`);
194
286
  }
195
287
 
288
+ const isOrder = billingItem.type === 'StripeOrder';
289
+ const plan = isOrder ? undefined : resolvePricePlan(billingItem, request);
290
+
196
291
  // Verify user exists
197
292
  await authProvider.getUser(userId);
198
293
 
199
- // ✅ HOOK: beforeCheckout (ownership check, status validation, server-resolved pricing)
200
- let finalUnitAmount = unitAmount;
201
- let finalProductName = productName;
294
+ const clientMetadata = sanitizeMetadata(request.metadata ?? {});
295
+ // Server values AFTER spread — cannot be overwritten by client
296
+ const metadata = { ...clientMetadata, userId, billingConfigKey };
297
+ // Fail before any hook side effect (StripeOrder creates a pending order)
298
+ assertStripeMetadata(
299
+ isOrder ? { ...metadata, [ORDER_ID_METADATA_KEY]: '' } : metadata,
300
+ 'metadata'
301
+ );
302
+
303
+ const allowPromotionCodes = request.allowPromotionCodes ?? true;
304
+ let unitAmount = request.unitAmount;
305
+ let productName = request.productName;
202
306
 
203
307
  if (billingItem.beforeCheckout) {
308
+ const options: BeforeCheckoutOptions = {
309
+ ...request,
310
+ userId,
311
+ mode: plan?.mode ?? 'payment',
312
+ priceId: plan?.priceId,
313
+ metadata: request.metadata ?? {},
314
+ allowPromotionCodes,
315
+ };
204
316
  const hookResult = await billingItem.beforeCheckout(
205
317
  userId,
206
- {
207
- priceId,
208
- unitAmount,
209
- productName,
210
- currency,
211
- mode,
212
- metadata,
213
- allowPromotionCodes,
214
- },
215
- sanitizeMetadata(metadata)
318
+ options,
319
+ clientMetadata
216
320
  );
217
-
218
321
  if (!hookResult.allowed) {
219
322
  throw new Error(
220
323
  hookResult.reason || 'Checkout blocked by beforeCheckout hook'
221
324
  );
222
325
  }
223
-
224
- if (hookResult.overrides) {
225
- if (hookResult.overrides.unitAmount !== undefined) {
226
- finalUnitAmount = hookResult.overrides.unitAmount;
227
- }
228
- if (hookResult.overrides.productName !== undefined) {
229
- finalProductName = hookResult.overrides.productName;
230
- }
326
+ // 0.1.x: overrides apply to dynamic pricing only
327
+ if (plan?.dynamic && hookResult.overrides) {
328
+ unitAmount = hookResult.overrides.unitAmount ?? unitAmount;
329
+ productName = hookResult.overrides.productName ?? productName;
231
330
  }
232
331
  }
233
332
 
234
- const finalUseDynamicPricing =
235
- !priceId && finalUnitAmount && finalProductName;
236
-
237
- // ✅ VALIDATE: overridden amount still respects security cap
238
- if (
239
- finalUseDynamicPricing &&
240
- billingItem.maxUnitAmount &&
241
- finalUnitAmount! > billingItem.maxUnitAmount
242
- ) {
243
- throw new Error(
244
- `Hook-overridden unit amount ${finalUnitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
245
- );
246
- }
247
-
248
- // ✅ VALIDATE: URLs are valid http/https
249
- const resolvedSuccessUrl =
250
- successUrl || `${process.env.FRONTEND_URL}/billing/success`;
251
- const resolvedCancelUrl =
252
- cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`;
253
- validateCheckoutUrl(resolvedSuccessUrl, 'success');
254
- validateCheckoutUrl(resolvedCancelUrl, 'cancel');
333
+ const successUrl = resolveRedirectUrl(request.successUrl, 'success');
334
+ const cancelUrl = resolveRedirectUrl(request.cancelUrl, 'cancel');
335
+ validateCheckoutUrl(successUrl, 'success');
336
+ validateCheckoutUrl(cancelUrl, 'cancel');
255
337
 
256
- // ✅ SANITIZE: metadata values (strip scripts, cap lengths)
257
- const sanitizedMetadata = sanitizeMetadata(metadata);
258
-
259
- // Create checkout session
260
- const session = await stripeProvider.createCheckoutSession({
261
- priceId,
262
- unitAmount: finalUseDynamicPricing ? finalUnitAmount : undefined,
263
- productName: finalUseDynamicPricing ? finalProductName : undefined,
264
- currency: currency || billingItem.currency || 'eur',
265
- customerEmail,
266
- metadata: {
267
- ...sanitizedMetadata,
338
+ let session: CheckoutSessionResult;
339
+ if (billingItem.type === 'StripeOrder') {
340
+ if (!isSessionProvider(stripeProvider)) {
341
+ throw new Error(
342
+ `'${billingConfigKey}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`
343
+ );
344
+ }
345
+ if (billingItem.tax.mode === 'manual') {
346
+ await assertExclusiveTaxRates(
347
+ (id) => stripeProvider.retrieveTaxRate(id),
348
+ billingItem.tax.taxRateIds,
349
+ billingConfigKey
350
+ );
351
+ }
352
+ const order = await billingItem.resolveLineItems(request.lineItems, {
268
353
  userId,
269
- billingConfigKey: configKey as string, // ✅ Server values AFTER spread — cannot be overwritten by client
270
- },
271
- allowPromotionCodes,
272
- successUrl: resolvedSuccessUrl,
273
- cancelUrl: resolvedCancelUrl,
274
- mode,
275
- });
354
+ billingConfigKey,
355
+ metadata: clientMetadata,
356
+ });
357
+ assertResolvedOrder(order, billingConfigKey);
358
+ const sessionOptions = order.session;
359
+ if (sessionOptions?.taxRateIds) {
360
+ if (billingItem.tax.mode !== 'manual') {
361
+ throw new Error(
362
+ `resolveLineItems for '${billingConfigKey}': session.taxRateIds needs tax.mode 'manual'`
363
+ );
364
+ }
365
+ await assertExclusiveTaxRates(
366
+ (id) => stripeProvider.retrieveTaxRate(id),
367
+ sessionOptions.taxRateIds,
368
+ billingConfigKey
369
+ );
370
+ }
371
+ if (sessionOptions?.invoiceFooter && !billingItem.invoiceCreation) {
372
+ throw new Error(
373
+ `resolveLineItems for '${billingConfigKey}': session.invoiceFooter needs invoiceCreation`
374
+ );
375
+ }
376
+ const params = buildOrderSessionParams(billingItem, order, {
377
+ successUrl,
378
+ cancelUrl,
379
+ customerEmail: request.customerEmail,
380
+ metadata,
381
+ });
382
+ assertCheckoutSessionMetadata(params);
383
+ session = await stripeProvider.createStripeSession(params);
384
+ } else {
385
+ const dynamic = !!plan?.dynamic && !!unitAmount && !!productName;
386
+ // 0.1.x: an overridden amount still respects the security cap
387
+ if (dynamic && billingItem.maxUnitAmount && unitAmount! > billingItem.maxUnitAmount) {
388
+ throw new Error(
389
+ `Hook-overridden unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
390
+ );
391
+ }
392
+ const params: CheckoutSessionParams = {
393
+ priceId: plan?.priceId,
394
+ unitAmount: dynamic ? unitAmount : undefined,
395
+ productName: dynamic ? productName : undefined,
396
+ currency: request.currency || billingItem.currency || 'eur',
397
+ customerEmail: request.customerEmail,
398
+ metadata,
399
+ allowPromotionCodes,
400
+ successUrl,
401
+ cancelUrl,
402
+ mode: plan?.mode,
403
+ };
404
+ if (isSessionProvider(stripeProvider)) {
405
+ const stripeParams = toStripeSessionParams(params);
406
+ assertCheckoutSessionMetadata(stripeParams);
407
+ session = await stripeProvider.createStripeSession(stripeParams);
408
+ } else {
409
+ session = await stripeProvider.createCheckoutSession(params);
410
+ }
411
+ }
276
412
 
277
413
  return {
278
414
  sessionId: session.id,
@@ -10,4 +10,3 @@
10
10
  */
11
11
 
12
12
  export { updateUserSubscription } from './updateUserSubscription.js';
13
- export type { SubscriptionData } from './updateUserSubscription.js';
@@ -9,17 +9,15 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type Stripe from 'stripe';
13
+
12
14
  import { SUBSCRIPTION_STATUS } from '@donotdev/core/server';
15
+ import type { BillingAuthProvider } from '@donotdev/core/server';
13
16
 
14
- import {
15
- updateUserSubscription,
16
- type AuthProvider,
17
- } from './updateUserSubscription.js';
17
+ import { updateUserSubscription } from './updateUserSubscription.js';
18
18
  import { handleError } from '../../errorHandling.js';
19
19
  import { stripe, validateStripeEnvironment } from '../../utils.js';
20
20
 
21
- import type Stripe from 'stripe';
22
-
23
21
  /**
24
22
  * Cancel user subscription at period end
25
23
  *
@@ -29,7 +27,7 @@ import type Stripe from 'stripe';
29
27
  */
30
28
  export async function cancelUserSubscription(
31
29
  userId: string,
32
- authProvider: AuthProvider
30
+ authProvider: BillingAuthProvider
33
31
  ): Promise<{ success: boolean; endsAt: string }> {
34
32
  validateStripeEnvironment();
35
33
 
@@ -101,7 +99,7 @@ export async function changeUserPlan(
101
99
  newPriceId: string,
102
100
  billingConfigKey: string,
103
101
  billingConfig: Record<string, any>,
104
- authProvider: AuthProvider
102
+ authProvider: BillingAuthProvider
105
103
  ): Promise<{ success: boolean; newTier: string; newPrice: number }> {
106
104
  validateStripeEnvironment();
107
105
 
@@ -191,7 +189,7 @@ export async function changeUserPlan(
191
189
  */
192
190
  export async function createCustomerPortalSession(
193
191
  userId: string,
194
- authProvider: AuthProvider,
192
+ authProvider: BillingAuthProvider,
195
193
  returnUrl?: string
196
194
  ): Promise<{ url: string }> {
197
195
  validateStripeEnvironment();