@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
@@ -0,0 +1,269 @@
1
+ // packages/functions/src/shared/billing/orderWebhook.ts
2
+
3
+ /**
4
+ * @fileoverview StripeOrder webhook handling
5
+ * @description Maps Checkout Session events of one-time, multi-line orders to the
6
+ * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
7
+ * Hook errors propagate: the webhook answers non-2xx and Stripe retries.
8
+ *
9
+ * @version 0.2.0
10
+ * @since 0.2.0
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+
14
+ import type Stripe from 'stripe';
15
+
16
+ import type {
17
+ CheckoutAddress,
18
+ CheckoutSessionSnapshot,
19
+ OrderHookContext,
20
+ PaidLineItem,
21
+ StripeOrderBackItem,
22
+ } from '@donotdev/core/server';
23
+
24
+ import { logger } from '../logger.js';
25
+ import { STRIPE_API_VERSION_PIN } from './apiVersion.js';
26
+
27
+ /**
28
+ * Checkout Session events that concern orders.
29
+ *
30
+ * @version 0.2.0
31
+ * @since 0.2.0
32
+ * @author AMBROISE PARK Consulting
33
+ */
34
+ export type OrderSessionEventType =
35
+ | 'checkout.session.completed'
36
+ | 'checkout.session.async_payment_succeeded'
37
+ | 'checkout.session.async_payment_failed'
38
+ | 'checkout.session.expired';
39
+
40
+ /**
41
+ * Oldest Stripe API version whose Checkout Session payload StripeOrder can read
42
+ * (`collected_information` was added in 2025-02-24.acacia). Alias of
43
+ * {@link STRIPE_API_VERSION_PIN}.
44
+ *
45
+ * @version 0.2.0
46
+ * @since 0.2.0
47
+ * @author AMBROISE PARK Consulting
48
+ */
49
+ export const MIN_ORDER_API_VERSION = STRIPE_API_VERSION_PIN;
50
+
51
+ /** Metadata key carrying the app order ID on the Checkout Session. */
52
+ export const ORDER_ID_METADATA_KEY = 'orderId';
53
+
54
+ /** Product metadata key carrying the app product ID on each line. */
55
+ export const PRODUCT_ID_METADATA_KEY = 'productId';
56
+
57
+ function idOf(value: string | { id: string } | null): string | null {
58
+ if (value === null) return null;
59
+ return typeof value === 'string' ? value : value.id;
60
+ }
61
+
62
+ type StripeAddressFields = Pick<
63
+ Stripe.Address,
64
+ 'line1' | 'line2' | 'postal_code' | 'city' | 'state' | 'country'
65
+ >;
66
+
67
+ function toAddress(address: StripeAddressFields): CheckoutAddress {
68
+ return {
69
+ line1: address.line1,
70
+ line2: address.line2,
71
+ postalCode: address.postal_code,
72
+ city: address.city,
73
+ state: address.state,
74
+ country: address.country,
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Map a Stripe Checkout Session to the provider-neutral snapshot given to order hooks.
80
+ *
81
+ * @param session - Checkout Session from a webhook event
82
+ * @returns Snapshot (amounts in the smallest currency unit)
83
+ *
84
+ * @version 0.2.0
85
+ * @since 0.2.0
86
+ * @author AMBROISE PARK Consulting
87
+ */
88
+ export function toCheckoutSessionSnapshot(
89
+ session: Stripe.Checkout.Session
90
+ ): CheckoutSessionSnapshot {
91
+ const details = session.customer_details;
92
+ const shipping = session.collected_information?.shipping_details ?? null;
93
+ return {
94
+ id: session.id,
95
+ paymentStatus: session.payment_status,
96
+ currency: session.currency,
97
+ amountSubtotal: session.amount_subtotal,
98
+ amountTax: session.total_details?.amount_tax ?? null,
99
+ amountShipping: session.total_details?.amount_shipping ?? null,
100
+ amountDiscount: session.total_details?.amount_discount ?? null,
101
+ amountTotal: session.amount_total,
102
+ customerId: idOf(session.customer),
103
+ customer: details
104
+ ? {
105
+ email: details.email,
106
+ name: details.name,
107
+ phone: details.phone,
108
+ businessName: details.business_name,
109
+ address: details.address ? toAddress(details.address) : null,
110
+ taxIds: (details.tax_ids ?? []).map((taxId) => ({
111
+ type: taxId.type,
112
+ value: taxId.value,
113
+ })),
114
+ taxExempt: details.tax_exempt,
115
+ }
116
+ : null,
117
+ shipping: shipping
118
+ ? { name: shipping.name, address: toAddress(shipping.address) }
119
+ : null,
120
+ invoiceId: idOf(session.invoice),
121
+ paymentIntentId: idOf(session.payment_intent),
122
+ metadata: session.metadata ?? {},
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Read the charged lines of a session back from Stripe.
128
+ *
129
+ * @param stripe - Stripe client
130
+ * @param sessionId - Checkout Session ID
131
+ * @returns Lines with the app product ID and charged amounts
132
+ * @throws When a line carries no app product ID (not created by the framework)
133
+ *
134
+ * @version 0.2.0
135
+ * @since 0.2.0
136
+ * @author AMBROISE PARK Consulting
137
+ */
138
+ export async function listPaidLineItems(
139
+ stripe: Stripe,
140
+ sessionId: string
141
+ ): Promise<PaidLineItem[]> {
142
+ const lines: PaidLineItem[] = [];
143
+ for await (const item of stripe.checkout.sessions.listLineItems(sessionId, {
144
+ limit: 100,
145
+ expand: ['data.price.product'],
146
+ })) {
147
+ const product = item.price?.product;
148
+ const productId =
149
+ product && typeof product !== 'string' && !product.deleted
150
+ ? product.metadata[PRODUCT_ID_METADATA_KEY]
151
+ : undefined;
152
+ if (!productId) {
153
+ throw new Error(
154
+ `Line item ${item.id} of session ${sessionId} has no ${PRODUCT_ID_METADATA_KEY} product metadata`
155
+ );
156
+ }
157
+ lines.push({
158
+ productId,
159
+ name: item.description ?? '',
160
+ quantity: item.quantity ?? 0,
161
+ amountSubtotal: item.amount_subtotal,
162
+ amountDiscount: item.amount_discount,
163
+ amountTax: item.amount_tax,
164
+ amountTotal: item.amount_total,
165
+ });
166
+ }
167
+ return lines;
168
+ }
169
+
170
+ /**
171
+ * Route one Checkout Session event of a StripeOrder item to the app hooks.
172
+ *
173
+ * - `completed` + `paid` / `no_payment_required` → `onOrderPaid`
174
+ * - `completed` + `unpaid` (async method, e.g. SEPA debit) → wait for the async event
175
+ * - `async_payment_succeeded` → `onOrderPaid`
176
+ * - `async_payment_failed` → `onOrderPaymentFailed`
177
+ * - `expired` → `onOrderExpired`
178
+ *
179
+ * @throws When the event API version is older than {@link MIN_ORDER_API_VERSION},
180
+ * when metadata is incomplete, or when a hook throws
181
+ *
182
+ * @version 0.2.0
183
+ * @since 0.2.0
184
+ * @author AMBROISE PARK Consulting
185
+ */
186
+ export async function handleOrderSessionEvent(
187
+ eventType: OrderSessionEventType,
188
+ eventId: string,
189
+ apiVersion: string | null,
190
+ session: Stripe.Checkout.Session,
191
+ billingConfigKey: string,
192
+ orderItem: StripeOrderBackItem,
193
+ stripe: Stripe
194
+ ): Promise<void> {
195
+ // API versions are date-prefixed (YYYY-MM-DD.name): compare the dates.
196
+ // event.api_version is the webhook ENDPOINT's version, not STRIPE_API_VERSION.
197
+ if (
198
+ !apiVersion ||
199
+ apiVersion.slice(0, 10) < MIN_ORDER_API_VERSION.slice(0, 10)
200
+ ) {
201
+ throw new Error(
202
+ `Stripe event ${eventId} (order ${session.metadata?.[ORDER_ID_METADATA_KEY] ?? 'unknown'}) was rendered with API version ${apiVersion}; ` +
203
+ `StripeOrder requires ${MIN_ORDER_API_VERSION} or later. Webhook payloads follow the webhook endpoint's API version, ` +
204
+ `not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint ` +
205
+ `(POST /v1/webhook_endpoints with api_version=${MIN_ORDER_API_VERSION}), set STRIPE_WEBHOOK_SECRET to its signing secret, ` +
206
+ `disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`
207
+ );
208
+ }
209
+
210
+ const metadata = session.metadata ?? {};
211
+ const userId = metadata.userId;
212
+ const orderId = metadata[ORDER_ID_METADATA_KEY];
213
+ if (!userId || !orderId) {
214
+ throw new Error(
215
+ `Order session ${session.id} is missing metadata: userId=${userId}, orderId=${orderId}`
216
+ );
217
+ }
218
+
219
+ const ctx: OrderHookContext = { userId, orderId, billingConfigKey, eventId };
220
+ const snapshot = toCheckoutSessionSnapshot(session);
221
+
222
+ const isPaidNow =
223
+ eventType === 'checkout.session.async_payment_succeeded' ||
224
+ (eventType === 'checkout.session.completed' &&
225
+ session.payment_status !== 'unpaid');
226
+
227
+ if (isPaidNow) {
228
+ const lineItems = await listPaidLineItems(stripe, session.id);
229
+ await orderItem.onOrderPaid(snapshot, lineItems, ctx);
230
+ logger.info('[Webhook] Order paid', {
231
+ orderId,
232
+ billingConfigKey,
233
+ operation: 'order_paid',
234
+ });
235
+ return;
236
+ }
237
+
238
+ switch (eventType) {
239
+ case 'checkout.session.completed':
240
+ logger.info('[Webhook] Order awaiting async payment', {
241
+ orderId,
242
+ billingConfigKey,
243
+ operation: 'order_payment_pending',
244
+ });
245
+ return;
246
+ case 'checkout.session.async_payment_failed':
247
+ if (orderItem.onOrderPaymentFailed) {
248
+ await orderItem.onOrderPaymentFailed(snapshot, ctx);
249
+ }
250
+ logger.warn('[Webhook] Order payment failed', {
251
+ orderId,
252
+ billingConfigKey,
253
+ operation: 'order_payment_failed',
254
+ });
255
+ return;
256
+ case 'checkout.session.expired':
257
+ if (orderItem.onOrderExpired) {
258
+ await orderItem.onOrderExpired(snapshot, ctx);
259
+ }
260
+ logger.info('[Webhook] Order checkout expired', {
261
+ orderId,
262
+ billingConfigKey,
263
+ operation: 'order_expired',
264
+ });
265
+ return;
266
+ default:
267
+ return;
268
+ }
269
+ }
@@ -0,0 +1,228 @@
1
+ // packages/functions/src/shared/billing/supabaseIdempotency.ts
2
+
3
+ /**
4
+ * @fileoverview Postgres (Supabase) webhook idempotency store
5
+ * @description `webhook_events` table and its RPCs. Re-exported from
6
+ * `idempotency.ts`.
7
+ *
8
+ * @version 0.2.0
9
+ * @since 0.2.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type { SupabaseClient } from '@supabase/supabase-js';
14
+ import * as v from 'valibot';
15
+
16
+ import { handleError } from '../errorHandling.js';
17
+ import {
18
+ RESERVATION_LEASE_MS,
19
+ ReservationLostError,
20
+ newOwnerToken,
21
+ } from './idempotencyContract.js';
22
+ import type {
23
+ IdempotencyStore,
24
+ ReservationResult,
25
+ } from './idempotencyContract.js';
26
+
27
+ /**
28
+ * SQL required by {@link createSupabaseIdempotencyStore}: table, the
29
+ * service_role-only RPCs `webhook_event_reserve` / `webhook_event_mark_processed`
30
+ * / `webhook_event_release`, and a daily pg_cron cleanup (30 days). Shipped
31
+ * verbatim as the CLI Supabase template migration `*_webhook_events.sql`.
32
+ *
33
+ * @version 0.2.0
34
+ * @since 0.2.0
35
+ * @author AMBROISE PARK Consulting
36
+ */
37
+ export const WEBHOOK_EVENTS_SQL = `
38
+ CREATE TABLE IF NOT EXISTS public.webhook_events (
39
+ event_id TEXT PRIMARY KEY,
40
+ status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
41
+ owner_token UUID NOT NULL,
42
+ reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
43
+ processed_at TIMESTAMPTZ
44
+ );
45
+
46
+ -- Only service_role accesses this table
47
+ ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
48
+
49
+ CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
50
+ ON public.webhook_events (processed_at);
51
+
52
+ -- The functions below run as the caller (SECURITY INVOKER) and refuse every
53
+ -- role but service_role. EXECUTE is deliberately not revoked: on Supabase
54
+ -- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
55
+ -- crashes the backend (signal 11), which restarts every connection.
56
+ CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
57
+ RETURNS VOID
58
+ LANGUAGE plpgsql
59
+ SET search_path = public
60
+ AS $$
61
+ BEGIN
62
+ IF current_user IS DISTINCT FROM 'service_role' THEN
63
+ RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
64
+ USING ERRCODE = 'insufficient_privilege';
65
+ END IF;
66
+ END;
67
+ $$;
68
+
69
+ -- Atomic reservation. Returns:
70
+ -- 'reserved' the caller now owns the event under p_owner_token
71
+ -- 'processed' the event was already processed (skip, answer 2xx)
72
+ -- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
73
+ -- A 'processing' row older than the lease is retaken (abandoned worker).
74
+ CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
75
+ p_event_id TEXT,
76
+ p_owner_token UUID,
77
+ p_lease_seconds INT
78
+ )
79
+ RETURNS TEXT
80
+ LANGUAGE plpgsql
81
+ SET search_path = public
82
+ AS $$
83
+ DECLARE
84
+ v_status TEXT;
85
+ BEGIN
86
+ PERFORM public.webhook_events_assert_service_role();
87
+
88
+ INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
89
+ VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
90
+ ON CONFLICT (event_id) DO UPDATE
91
+ SET owner_token = EXCLUDED.owner_token,
92
+ reserved_at = clock_timestamp()
93
+ WHERE webhook_events.status = 'processing'
94
+ AND webhook_events.reserved_at
95
+ < clock_timestamp() - make_interval(secs => p_lease_seconds);
96
+ IF FOUND THEN
97
+ RETURN 'reserved';
98
+ END IF;
99
+
100
+ SELECT status INTO v_status
101
+ FROM public.webhook_events
102
+ WHERE event_id = p_event_id;
103
+ IF v_status = 'processed' THEN
104
+ RETURN 'processed';
105
+ END IF;
106
+ -- Live lease, or the row was released in between: Stripe retries either way
107
+ RETURN 'in_progress';
108
+ END;
109
+ $$;
110
+
111
+ -- Mark a reservation processed. Returns false when p_owner_token no longer owns
112
+ -- the row (lease retaken, released, or deleted). Repeating it for the same
113
+ -- owner is a no-op that returns true.
114
+ CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
115
+ p_event_id TEXT,
116
+ p_owner_token UUID
117
+ )
118
+ RETURNS BOOLEAN
119
+ LANGUAGE plpgsql
120
+ SET search_path = public
121
+ AS $$
122
+ BEGIN
123
+ PERFORM public.webhook_events_assert_service_role();
124
+
125
+ UPDATE public.webhook_events
126
+ SET status = 'processed',
127
+ processed_at = COALESCE(processed_at, clock_timestamp())
128
+ WHERE event_id = p_event_id
129
+ AND owner_token = p_owner_token;
130
+ RETURN FOUND;
131
+ END;
132
+ $$;
133
+
134
+ -- Drop a reservation after a processing failure. Returns false when
135
+ -- p_owner_token does not own a 'processing' row (nothing is deleted).
136
+ CREATE OR REPLACE FUNCTION public.webhook_event_release(
137
+ p_event_id TEXT,
138
+ p_owner_token UUID
139
+ )
140
+ RETURNS BOOLEAN
141
+ LANGUAGE plpgsql
142
+ SET search_path = public
143
+ AS $$
144
+ BEGIN
145
+ PERFORM public.webhook_events_assert_service_role();
146
+
147
+ DELETE FROM public.webhook_events
148
+ WHERE event_id = p_event_id
149
+ AND owner_token = p_owner_token
150
+ AND status = 'processing';
151
+ RETURN FOUND;
152
+ END;
153
+ $$;
154
+
155
+ -- Enable pg_cron extension (if not already enabled)
156
+ CREATE EXTENSION IF NOT EXISTS pg_cron;
157
+
158
+ -- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
159
+ -- Stripe retries an event for up to 3 days, so older rows are never read again.
160
+ SELECT cron.schedule(
161
+ 'cleanup-webhook-events',
162
+ '0 5 * * *',
163
+ $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
164
+ );
165
+ `;
166
+
167
+ const ReserveResultSchema = v.picklist(['reserved', 'processed', 'in_progress']);
168
+ const OwnedResultSchema = v.boolean();
169
+
170
+ /**
171
+ * Postgres-backed store (Supabase). Requires {@link WEBHOOK_EVENTS_SQL}.
172
+ *
173
+ * @param supabaseAdmin - Supabase client created with the service role key
174
+ *
175
+ * @version 0.2.0
176
+ * @since 0.2.0
177
+ * @author AMBROISE PARK Consulting
178
+ */
179
+ export function createSupabaseIdempotencyStore(
180
+ supabaseAdmin: SupabaseClient
181
+ ): IdempotencyStore {
182
+ const call = async <T>(
183
+ fn: string,
184
+ args: Record<string, unknown>,
185
+ schema: v.GenericSchema<unknown, T>
186
+ ): Promise<T> => {
187
+ const { data, error } = await supabaseAdmin.rpc(fn, args);
188
+ if (error) throw handleError(error);
189
+ const result = v.safeParse(schema, data);
190
+ if (!result.success) {
191
+ throw handleError(
192
+ new Error(`${fn} returned an unexpected result: ${JSON.stringify(data)}`)
193
+ );
194
+ }
195
+ return result.output;
196
+ };
197
+
198
+ return {
199
+ async reserve(eventId): Promise<ReservationResult> {
200
+ const ownerToken = newOwnerToken();
201
+ const state = await call(
202
+ 'webhook_event_reserve',
203
+ {
204
+ p_event_id: eventId,
205
+ p_owner_token: ownerToken,
206
+ p_lease_seconds: RESERVATION_LEASE_MS / 1000,
207
+ },
208
+ ReserveResultSchema
209
+ );
210
+ return state === 'reserved' ? { state, ownerToken } : { state };
211
+ },
212
+ async markProcessed(eventId, ownerToken) {
213
+ const owned = await call(
214
+ 'webhook_event_mark_processed',
215
+ { p_event_id: eventId, p_owner_token: ownerToken },
216
+ OwnedResultSchema
217
+ );
218
+ if (!owned) throw new ReservationLostError(eventId);
219
+ },
220
+ async release(eventId, ownerToken) {
221
+ return call(
222
+ 'webhook_event_release',
223
+ { p_event_id: eventId, p_owner_token: ownerToken },
224
+ OwnedResultSchema
225
+ );
226
+ },
227
+ };
228
+ }