@donotdev/functions 0.1.44 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/README.md +25 -14
  2. package/lib/chunks/chunk-3F4BWKQD.js +22 -0
  3. package/lib/chunks/chunk-3F4BWKQD.js.map +7 -0
  4. package/lib/chunks/chunk-5IPULSUX.js +22 -0
  5. package/lib/chunks/chunk-5IPULSUX.js.map +7 -0
  6. package/lib/chunks/chunk-6USHTJED.js +22 -0
  7. package/lib/chunks/chunk-6USHTJED.js.map +7 -0
  8. package/lib/chunks/chunk-AYY7UXNI.js +22 -0
  9. package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
  10. package/lib/chunks/chunk-CXBSROEW.js +23 -0
  11. package/lib/chunks/chunk-CXBSROEW.js.map +7 -0
  12. package/lib/chunks/chunk-GYTCWMXV.js +22 -0
  13. package/lib/chunks/chunk-GYTCWMXV.js.map +7 -0
  14. package/lib/chunks/chunk-HLNYUAZH.js +22 -0
  15. package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
  16. package/lib/chunks/chunk-LCDLG4VG.js +151 -0
  17. package/lib/chunks/chunk-LCDLG4VG.js.map +7 -0
  18. package/lib/chunks/chunk-MQANUSY3.js +22 -0
  19. package/lib/chunks/chunk-MQANUSY3.js.map +7 -0
  20. package/lib/chunks/chunk-OFQVO3FD.js +22 -0
  21. package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
  22. package/lib/chunks/chunk-PWAGW4R6.js +22 -0
  23. package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
  24. package/lib/chunks/chunk-US2VOP4S.js +22 -0
  25. package/lib/chunks/chunk-US2VOP4S.js.map +7 -0
  26. package/lib/chunks/chunk-YTKDNZNW.js +22 -0
  27. package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
  28. package/lib/chunks/monitoring-E7JBYBHQ.js +22 -0
  29. package/lib/chunks/monitoring-E7JBYBHQ.js.map +7 -0
  30. package/lib/chunks/rateLimiter-SQISLOP5.js +22 -0
  31. package/lib/chunks/rateLimiter-SQISLOP5.js.map +7 -0
  32. package/lib/chunks/server-IQ5JNJOM.js +22 -0
  33. package/lib/chunks/server-IQ5JNJOM.js.map +7 -0
  34. package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
  35. package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
  36. package/lib/firebase/auth/index.d.ts +0 -0
  37. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  38. package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
  39. package/lib/firebase/baseFunction.d.ts +1 -1
  40. package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
  41. package/lib/firebase/billing/changePlan.d.ts +0 -0
  42. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
  43. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  44. package/lib/firebase/billing/healthCheck.d.ts +0 -0
  45. package/lib/firebase/billing/index.d.ts +2 -1
  46. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
  47. package/lib/firebase/billing/webhookHandler.d.ts +17 -2
  48. package/lib/firebase/config/constants.d.ts +0 -0
  49. package/lib/firebase/config/index.d.ts +0 -0
  50. package/lib/firebase/config/secrets.d.ts +0 -0
  51. package/lib/firebase/crud/aggregate.d.ts +0 -9
  52. package/lib/firebase/crud/bulk.d.ts +2 -2
  53. package/lib/firebase/crud/create.d.ts +1 -1
  54. package/lib/firebase/crud/delete.d.ts +1 -1
  55. package/lib/firebase/crud/get.d.ts +1 -1
  56. package/lib/firebase/crud/index.d.ts +0 -0
  57. package/lib/firebase/crud/list.d.ts +1 -1
  58. package/lib/firebase/crud/update.d.ts +1 -9
  59. package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
  60. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
  61. package/lib/firebase/helpers/index.d.ts +0 -0
  62. package/lib/firebase/index.d.ts +0 -0
  63. package/lib/firebase/index.js +1 -5
  64. package/lib/firebase/index.js.map +4 -4
  65. package/lib/firebase/oauth/disconnect.d.ts +0 -0
  66. package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
  67. package/lib/firebase/oauth/getConnections.d.ts +0 -0
  68. package/lib/firebase/oauth/githubAccess.d.ts +2 -2
  69. package/lib/firebase/oauth/index.d.ts +0 -0
  70. package/lib/firebase/oauth/refreshToken.d.ts +0 -0
  71. package/lib/firebase/registerCrudFunctions.d.ts +9 -1
  72. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
  73. package/lib/firebase/scheduled/index.d.ts +0 -0
  74. package/lib/shared/ai/classifyAIError.d.ts +0 -0
  75. package/lib/shared/ai/costTracker.d.ts +0 -0
  76. package/lib/shared/ai/createAIRoute.d.ts +0 -0
  77. package/lib/shared/ai/index.d.ts +0 -0
  78. package/lib/shared/ai/resolveModelTier.d.ts +0 -0
  79. package/lib/shared/billing/apiVersion.d.ts +22 -0
  80. package/lib/shared/billing/checkoutPrice.d.ts +27 -0
  81. package/lib/shared/billing/checkoutValidation.d.ts +89 -0
  82. package/lib/shared/billing/createCheckout.d.ts +73 -24
  83. package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
  84. package/lib/shared/billing/helpers/index.d.ts +0 -1
  85. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
  86. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
  87. package/lib/shared/billing/idempotency.d.ts +21 -10
  88. package/lib/shared/billing/idempotencyContract.d.ts +121 -0
  89. package/lib/shared/billing/index.d.ts +2 -0
  90. package/lib/shared/billing/orderWebhook.d.ts +75 -0
  91. package/lib/shared/billing/stripeClient.d.ts +45 -0
  92. package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
  93. package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
  94. package/lib/shared/billing/webhookHandler.d.ts +29 -20
  95. package/lib/shared/email/createEmailRoute.d.ts +0 -0
  96. package/lib/shared/email/index.d.ts +0 -0
  97. package/lib/shared/email/provider.d.ts +0 -0
  98. package/lib/shared/email/resendProvider.d.ts +0 -0
  99. package/lib/shared/errorHandling.d.ts +0 -0
  100. package/lib/shared/firebase.d.ts +0 -0
  101. package/lib/shared/github.d.ts +0 -0
  102. package/lib/shared/index.d.ts +0 -0
  103. package/lib/shared/index.js +1 -6
  104. package/lib/shared/index.js.map +4 -4
  105. package/lib/shared/logger.d.ts +0 -0
  106. package/lib/shared/metadata.d.ts +0 -0
  107. package/lib/shared/oauth/exchangeToken.d.ts +0 -0
  108. package/lib/shared/oauth/grantAccess.d.ts +0 -0
  109. package/lib/shared/oauth/index.d.ts +0 -0
  110. package/lib/shared/schema.d.ts +0 -0
  111. package/lib/shared/utils/detectFirestore.d.ts +0 -0
  112. package/lib/shared/utils/external/date.d.ts +0 -0
  113. package/lib/shared/utils/external/index.d.ts +0 -0
  114. package/lib/shared/utils/external/references.d.ts +0 -0
  115. package/lib/shared/utils/external/subscription.d.ts +0 -0
  116. package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
  117. package/lib/shared/utils/functionWrapper.d.ts +1 -1
  118. package/lib/shared/utils/index.d.ts +0 -0
  119. package/lib/shared/utils/internal/auth.d.ts +38 -1
  120. package/lib/shared/utils/internal/firebase.d.ts +0 -0
  121. package/lib/shared/utils/internal/idempotency.d.ts +0 -0
  122. package/lib/shared/utils/internal/index.d.ts +0 -0
  123. package/lib/shared/utils/internal/monitoring.d.ts +0 -0
  124. package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
  125. package/lib/shared/utils/internal/validation.d.ts +0 -8
  126. package/lib/shared/utils/schemaValidation.d.ts +1 -1
  127. package/lib/shared/utils/validation.d.ts +0 -0
  128. package/lib/shared/utils/vercelHelpers.d.ts +8 -0
  129. package/lib/shared/utils.d.ts +0 -56
  130. package/lib/shared/validation.d.ts +0 -0
  131. package/lib/supabase/ai/createAIFunction.d.ts +0 -0
  132. package/lib/supabase/auth/deleteAccount.d.ts +0 -0
  133. package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
  134. package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
  135. package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
  136. package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
  137. package/lib/supabase/baseFunction.d.ts +1 -1
  138. package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
  139. package/lib/supabase/billing/changePlan.d.ts +0 -0
  140. package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
  141. package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
  142. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
  143. package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
  144. package/lib/supabase/crud/aggregate.d.ts +0 -0
  145. package/lib/supabase/crud/bulk.d.ts +1 -1
  146. package/lib/supabase/crud/create.d.ts +0 -0
  147. package/lib/supabase/crud/delete.d.ts +0 -0
  148. package/lib/supabase/crud/entityStore.d.ts +71 -0
  149. package/lib/supabase/crud/get.d.ts +0 -0
  150. package/lib/supabase/crud/index.d.ts +2 -0
  151. package/lib/supabase/crud/list.d.ts +0 -8
  152. package/lib/supabase/crud/update.d.ts +0 -0
  153. package/lib/supabase/edgeFunction.d.ts +0 -0
  154. package/lib/supabase/email/createEmailFunction.d.ts +0 -0
  155. package/lib/supabase/helpers/authProvider.d.ts +5 -5
  156. package/lib/supabase/index.d.ts +11 -2
  157. package/lib/supabase/index.js +1 -3
  158. package/lib/supabase/index.js.map +4 -4
  159. package/lib/supabase/oauth/disconnect.d.ts +0 -0
  160. package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
  161. package/lib/supabase/oauth/getConnections.d.ts +0 -0
  162. package/lib/supabase/oauth/index.d.ts +0 -0
  163. package/lib/supabase/oauth/refreshToken.d.ts +0 -0
  164. package/lib/supabase/registerCrudFunctions.d.ts +0 -0
  165. package/lib/supabase/utils/idempotency.d.ts +0 -0
  166. package/lib/supabase/utils/monitoring.d.ts +0 -0
  167. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  168. package/lib/vercel/api/ai/chat.d.ts +0 -9
  169. package/lib/vercel/api/ai/index.d.ts +0 -0
  170. package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
  171. package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
  172. package/lib/vercel/api/auth/index.d.ts +0 -0
  173. package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
  174. package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
  175. package/lib/vercel/api/billing/backend.d.ts +39 -0
  176. package/lib/vercel/api/billing/cancel.d.ts +8 -0
  177. package/lib/vercel/api/billing/change-plan.d.ts +9 -1
  178. package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
  179. package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
  180. package/lib/vercel/api/billing/index.d.ts +4 -2
  181. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
  182. package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
  183. package/lib/vercel/api/config/constants.d.ts +0 -0
  184. package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
  185. package/lib/vercel/api/config/index.d.ts +0 -0
  186. package/lib/vercel/api/crud/bulk.d.ts +17 -0
  187. package/lib/vercel/api/crud/create.d.ts +8 -0
  188. package/lib/vercel/api/crud/delete.d.ts +8 -0
  189. package/lib/vercel/api/crud/get.d.ts +8 -0
  190. package/lib/vercel/api/crud/index.d.ts +0 -0
  191. package/lib/vercel/api/crud/list.d.ts +8 -0
  192. package/lib/vercel/api/crud/update.d.ts +8 -0
  193. package/lib/vercel/api/index.d.ts +0 -0
  194. package/lib/vercel/api/index.js +1 -3
  195. package/lib/vercel/api/index.js.map +4 -4
  196. package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
  197. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  198. package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
  199. package/lib/vercel/api/oauth/index.d.ts +0 -0
  200. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  201. package/lib/vercel/api/utils/cors.d.ts +0 -0
  202. package/lib/vercel/baseFunction.d.ts +4 -1
  203. package/lib/vercel/supabaseAdmin.d.ts +22 -0
  204. package/package.json +25 -26
  205. package/src/firebase/auth/getCustomClaims.ts +4 -5
  206. package/src/firebase/auth/getUserAuthStatus.ts +4 -5
  207. package/src/firebase/auth/removeCustomClaims.ts +4 -5
  208. package/src/firebase/auth/setCustomClaims.ts +4 -5
  209. package/src/firebase/baseFunction.ts +4 -5
  210. package/src/firebase/billing/cancelSubscription.ts +2 -3
  211. package/src/firebase/billing/changePlan.ts +3 -8
  212. package/src/firebase/billing/createCheckoutSession.ts +31 -61
  213. package/src/firebase/billing/createCustomerPortal.ts +5 -6
  214. package/src/firebase/billing/healthCheck.ts +1 -1
  215. package/src/firebase/billing/index.ts +8 -1
  216. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -4
  217. package/src/firebase/billing/webhookHandler.ts +21 -5
  218. package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
  219. package/src/firebase/crud/aggregate.ts +1 -2
  220. package/src/firebase/crud/bulk.ts +5 -6
  221. package/src/firebase/crud/create.ts +5 -6
  222. package/src/firebase/crud/delete.ts +4 -5
  223. package/src/firebase/crud/get.ts +4 -5
  224. package/src/firebase/crud/list.ts +4 -5
  225. package/src/firebase/crud/update.ts +5 -6
  226. package/src/firebase/oauth/githubAccess.ts +2 -3
  227. package/src/firebase/registerCrudFunctions.ts +2 -2
  228. package/src/shared/__tests__/auth.test.ts +0 -3
  229. package/src/shared/__tests__/bulkCore.test.ts +3 -2
  230. package/src/shared/__tests__/errorHandling.test.ts +2 -2
  231. package/src/shared/__tests__/idempotency.test.ts +282 -55
  232. package/src/shared/__tests__/internalValidation.test.ts +3 -42
  233. package/src/shared/__tests__/logger.test.ts +31 -0
  234. package/src/shared/__tests__/rateLimiter.test.ts +2 -8
  235. package/src/shared/__tests__/schemaValidation.test.ts +1 -1
  236. package/src/shared/__tests__/utils.test.ts +3 -2
  237. package/src/shared/__tests__/validation-env.test.ts +0 -0
  238. package/src/shared/ai/createAIRoute.ts +53 -30
  239. package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
  240. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
  241. package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
  242. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
  243. package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
  244. package/src/shared/billing/__tests__/webhookHandler.test.ts +370 -23
  245. package/src/shared/billing/apiVersion.ts +25 -0
  246. package/src/shared/billing/checkoutPrice.ts +125 -0
  247. package/src/shared/billing/checkoutValidation.ts +284 -0
  248. package/src/shared/billing/createCheckout.ts +332 -196
  249. package/src/shared/billing/firestoreIdempotency.ts +189 -0
  250. package/src/shared/billing/helpers/index.ts +0 -1
  251. package/src/shared/billing/helpers/subscriptionManagement.ts +8 -10
  252. package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
  253. package/src/shared/billing/idempotency.ts +104 -168
  254. package/src/shared/billing/idempotencyContract.ts +135 -0
  255. package/src/shared/billing/index.ts +2 -0
  256. package/src/shared/billing/orderWebhook.ts +269 -0
  257. package/src/shared/billing/stripeClient.ts +91 -0
  258. package/src/shared/billing/supabaseIdempotency.ts +228 -0
  259. package/src/shared/billing/tierWebhookEvents.ts +432 -0
  260. package/src/shared/billing/webhookHandler.ts +189 -386
  261. package/src/shared/logger.ts +4 -6
  262. package/src/shared/utils/external/subscription.ts +0 -0
  263. package/src/shared/utils/firebaseHelpers.ts +2 -3
  264. package/src/shared/utils/functionWrapper.ts +1 -2
  265. package/src/shared/utils/internal/auth.ts +55 -7
  266. package/src/shared/utils/internal/monitoring.ts +17 -9
  267. package/src/shared/utils/internal/rateLimiter.ts +14 -5
  268. package/src/shared/utils/internal/validation.ts +0 -18
  269. package/src/shared/utils/schemaValidation.ts +1 -2
  270. package/src/shared/utils/vercelHelpers.ts +3 -3
  271. package/src/shared/utils.ts +5 -99
  272. package/src/shared/validation.ts +1 -1
  273. package/src/supabase/__tests__/bulk.test.ts +3 -1
  274. package/src/supabase/__tests__/entityStore.test.ts +90 -0
  275. package/src/supabase/baseFunction.ts +1 -2
  276. package/src/supabase/billing/cancelSubscription.ts +1 -1
  277. package/src/supabase/billing/changePlan.ts +1 -1
  278. package/src/supabase/billing/createCheckoutSession.ts +11 -41
  279. package/src/supabase/billing/createCustomerPortal.ts +1 -1
  280. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -7
  281. package/src/supabase/billing/stripeWebhook.ts +79 -0
  282. package/src/supabase/crud/aggregate.ts +1 -1
  283. package/src/supabase/crud/bulk.ts +3 -7
  284. package/src/supabase/crud/create.ts +1 -1
  285. package/src/supabase/crud/entityStore.ts +240 -0
  286. package/src/supabase/crud/index.ts +8 -0
  287. package/src/supabase/crud/list.ts +2 -0
  288. package/src/supabase/crud/update.ts +1 -1
  289. package/src/supabase/helpers/authProvider.ts +6 -5
  290. package/src/supabase/index.ts +26 -0
  291. package/src/supabase/utils/rateLimiter.ts +2 -2
  292. package/src/vercel/__tests__/bulk.test.ts +24 -21
  293. package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
  294. package/src/vercel/api/ai/chat.ts +2 -1
  295. package/src/vercel/api/auth/get-custom-claims.ts +2 -3
  296. package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
  297. package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
  298. package/src/vercel/api/auth/set-custom-claims.ts +3 -3
  299. package/src/vercel/api/billing/backend.ts +72 -0
  300. package/src/vercel/api/billing/cancel.ts +2 -4
  301. package/src/vercel/api/billing/change-plan.ts +4 -5
  302. package/src/vercel/api/billing/create-checkout-session.ts +43 -73
  303. package/src/vercel/api/billing/customer-portal.ts +3 -5
  304. package/src/vercel/api/billing/index.ts +4 -2
  305. package/src/vercel/api/billing/refresh-subscription-status.ts +22 -7
  306. package/src/vercel/api/billing/webhook-handler.ts +32 -26
  307. package/src/vercel/api/config/firebase-admin.ts +2 -2
  308. package/src/vercel/api/crud/bulk.ts +6 -9
  309. package/src/vercel/api/crud/create.ts +6 -5
  310. package/src/vercel/api/crud/delete.ts +4 -3
  311. package/src/vercel/api/crud/get.ts +6 -5
  312. package/src/vercel/api/crud/list.ts +6 -5
  313. package/src/vercel/api/crud/update.ts +6 -5
  314. package/src/vercel/api/oauth/check-github-access.ts +5 -5
  315. package/src/vercel/api/oauth/exchange-token.ts +3 -3
  316. package/src/vercel/api/oauth/grant-github-access.ts +5 -5
  317. package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
  318. package/src/vercel/baseFunction.ts +23 -8
  319. package/src/vercel/supabaseAdmin.ts +45 -0
  320. package/lib/shared/ai/createAIHandler.d.ts +0 -39
  321. package/lib/shared/ai/providers/anthropic.d.ts +0 -12
  322. package/lib/shared/ai/providers/google.d.ts +0 -10
  323. package/lib/shared/ai/providers/index.d.ts +0 -23
  324. package/lib/shared/ai/providers/openai.d.ts +0 -10
  325. package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
@@ -0,0 +1,135 @@
1
+ // packages/functions/src/shared/billing/idempotencyContract.ts
2
+
3
+ /**
4
+ * @fileoverview Webhook idempotency contract
5
+ * @description Store interface, reservation result, lease and retention shared
6
+ * by every idempotency store (in-memory, Firestore, Postgres).
7
+ *
8
+ * @version 0.2.0
9
+ * @since 0.2.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ /**
14
+ * Outcome of {@link IdempotencyStore.reserve}.
15
+ * - `reserved`: the caller owns the event and must process it, then call
16
+ * `markProcessed` or `release` with `ownerToken`
17
+ * - `processed`: already processed, skip (answer 2xx)
18
+ * - `in_progress`: another delivery holds a live lease (answer non-2xx so the
19
+ * provider retries later, when that worker finished or its lease expired)
20
+ *
21
+ * @version 0.2.0
22
+ * @since 0.2.0
23
+ * @author AMBROISE PARK Consulting
24
+ */
25
+ export type ReservationResult =
26
+ | { state: 'reserved'; ownerToken: string }
27
+ | { state: 'processed' }
28
+ | { state: 'in_progress' };
29
+
30
+ /**
31
+ * Idempotency store interface
32
+ *
33
+ * @version 0.2.0
34
+ * @since 0.0.1
35
+ * @author AMBROISE PARK Consulting
36
+ */
37
+ export interface IdempotencyStore {
38
+ /** Atomically reserve an event for processing. */
39
+ reserve(eventId: string): Promise<ReservationResult>;
40
+ /**
41
+ * Mark a reservation processed. Repeating it for the same owner succeeds.
42
+ * @throws {ReservationLostError} When `ownerToken` no longer owns the event
43
+ */
44
+ markProcessed(eventId: string, ownerToken: string): Promise<void>;
45
+ /**
46
+ * Drop a reservation after a processing failure.
47
+ * @returns `false` when `ownerToken` does not own a pending reservation (nothing changed)
48
+ */
49
+ release(eventId: string, ownerToken: string): Promise<boolean>;
50
+ }
51
+
52
+ /**
53
+ * Store with the 0.1.x accessors.
54
+ *
55
+ * @deprecated Use {@link IdempotencyStore}: `reserve` returns three states and
56
+ * an owner token; `checkAndReserve` and `isProcessed` do not.
57
+ * @version 0.2.0
58
+ * @since 0.2.0
59
+ * @author AMBROISE PARK Consulting
60
+ */
61
+ export interface LegacyIdempotencyStore extends IdempotencyStore {
62
+ /** 0.1.x: `true` when the event must be skipped (processed or live lease). */
63
+ checkAndReserve(eventId: string): Promise<boolean>;
64
+ /** Whether the event was processed (non-atomic read). */
65
+ isProcessed(eventId: string): Promise<boolean>;
66
+ /**
67
+ * Mark processed. Without `ownerToken` (0.1.x call) the write is unconditional.
68
+ * @throws {ReservationLostError} When `ownerToken` is given and no longer owns the event
69
+ */
70
+ markProcessed(eventId: string, ownerToken?: string): Promise<void>;
71
+ }
72
+
73
+ /**
74
+ * Thrown by `markProcessed` when the caller no longer owns the reservation:
75
+ * its lease expired and another delivery retook the event, or the row is gone.
76
+ * Retrying cannot succeed.
77
+ *
78
+ * @version 0.2.0
79
+ * @since 0.2.0
80
+ * @author AMBROISE PARK Consulting
81
+ */
82
+ export class ReservationLostError extends Error {
83
+ /** Event whose reservation was lost. */
84
+ readonly eventId: string;
85
+
86
+ constructor(eventId: string) {
87
+ super(
88
+ `Reservation of webhook event ${eventId} is no longer held by this worker (lease retaken or row removed)`
89
+ );
90
+ this.name = 'ReservationLostError';
91
+ this.eventId = eventId;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * How long a reservation blocks other deliveries of the same event before it
97
+ * is considered abandoned (worker crashed or timed out) and can be retaken.
98
+ *
99
+ * Must exceed the longest request timeout a webhook handler can run under, so
100
+ * a live worker is never overtaken. Official maximums (checked 2026-11-04):
101
+ * - Firebase Functions gen2 HTTP: 60 min
102
+ * (https://firebase.google.com/docs/functions/quotas#time_limits)
103
+ * - Vercel Functions: 800 s, 1800 s with extended max duration
104
+ * (https://vercel.com/docs/functions/configuring-functions/duration)
105
+ * - Supabase Edge Functions: 400 s wall clock on paid plans
106
+ * (https://supabase.com/docs/guides/functions/limits)
107
+ * 70 min = the 60 min maximum + 10 min margin. Stripe retries for up to 3 days.
108
+ *
109
+ * @version 0.2.0
110
+ * @since 0.2.0
111
+ * @author AMBROISE PARK Consulting
112
+ */
113
+ export const RESERVATION_LEASE_MS = 70 * 60 * 1000;
114
+
115
+ /**
116
+ * How long reservations and processed events are kept before a TTL policy
117
+ * (Firestore `expiresAt`) or the pg_cron cleanup (Postgres) deletes them.
118
+ * Stripe retries for days, not weeks.
119
+ *
120
+ * @version 0.2.0
121
+ * @since 0.2.0
122
+ * @author AMBROISE PARK Consulting
123
+ */
124
+ export const WEBHOOK_EVENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
125
+
126
+ /**
127
+ * New reservation owner token (random UUID). Internal to the stores.
128
+ *
129
+ * @version 0.2.0
130
+ * @since 0.2.0
131
+ * @author AMBROISE PARK Consulting
132
+ */
133
+ export function newOwnerToken(): string {
134
+ return crypto.randomUUID();
135
+ }
@@ -12,3 +12,5 @@
12
12
  export * from './createCheckout.js';
13
13
  export * from './helpers/index.js';
14
14
  export * from './webhookHandler.js';
15
+ export * from './idempotency.js';
16
+ export * from './orderWebhook.js';
@@ -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,91 @@
1
+ // packages/functions/src/shared/billing/stripeClient.ts
2
+
3
+ /**
4
+ * @fileoverview Stripe client for billing functions
5
+ * @description Lazily initialized Stripe SDK instance shared by the Firebase,
6
+ * Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so
7
+ * code that does not bill (CRUD, auth) never loads the Stripe SDK.
8
+ *
9
+ * @version 0.2.1
10
+ * @since 0.0.1
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+
14
+ import Stripe from 'stripe';
15
+
16
+ import { STRIPE_API_VERSION_PIN } from './apiVersion.js';
17
+
18
+ // Lazy initialization of Stripe
19
+ let _stripe: Stripe | null = null;
20
+
21
+ /**
22
+ * Initialize Stripe explicitly (e.g. with a secret from defineSecret).
23
+ * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.
24
+ * @param apiKey - Stripe secret key
25
+ *
26
+ * @version 0.2.0
27
+ * @since 0.0.1
28
+ * @author AMBROISE PARK Consulting
29
+ */
30
+ export function initStripe(apiKey: string) {
31
+ if (!apiKey) throw new Error('Stripe API key is required');
32
+
33
+ // Unset: the framework pin (pre-basil fields are still read by subscription handlers)
34
+ const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
35
+
36
+ _stripe = new Stripe(apiKey, {
37
+ apiVersion: apiVersion as any,
38
+ });
39
+ return _stripe;
40
+ }
41
+
42
+ /**
43
+ * Get Stripe instance with lazy initialization
44
+ *
45
+ * @version 0.1.0
46
+ * @since 0.0.1
47
+ * @author AMBROISE PARK Consulting
48
+ */
49
+ export function getStripe(): Stripe {
50
+ if (!_stripe) {
51
+ // Legacy/Vercel fallback: Try process.env
52
+ const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
53
+ if (STRIPE_SECRET_KEY) {
54
+ initStripe(STRIPE_SECRET_KEY);
55
+ } else {
56
+ throw new Error(
57
+ 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'
58
+ );
59
+ }
60
+ }
61
+ // We know _stripe is set here or we threw
62
+ return _stripe!;
63
+ }
64
+
65
+ /**
66
+ * Lazy-initialized Stripe instance proxy
67
+ *
68
+ * @version 0.1.0
69
+ * @since 0.0.1
70
+ * @author AMBROISE PARK Consulting
71
+ */
72
+ export const stripe = new Proxy({} as Stripe, {
73
+ get(target, prop) {
74
+ return getStripe()[prop as keyof Stripe];
75
+ },
76
+ });
77
+
78
+ /**
79
+ * Validates that required Stripe environment variables are set
80
+ *
81
+ * @version 0.1.0
82
+ * @since 0.0.1
83
+ * @author AMBROISE PARK Consulting
84
+ */
85
+ export function validateStripeEnvironment(): void {
86
+ // Functions v2 automatically injects secrets as process.env when declared in config
87
+ const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
88
+ if (!STRIPE_SECRET_KEY) {
89
+ throw new Error('Missing STRIPE_SECRET_KEY environment variable');
90
+ }
91
+ }