@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,189 @@
1
+ // packages/functions/src/shared/billing/firestoreIdempotency.ts
2
+
3
+ /**
4
+ * @fileoverview Firestore webhook idempotency store
5
+ * @description `webhook_idempotency` collection, transactional reservations.
6
+ * Used by the Firebase and Vercel (Firestore backend) webhook entry points.
7
+ * Re-exported from `idempotency.ts`. Loads `@donotdev/firebase/server` on
8
+ * first use only.
9
+ *
10
+ * @version 0.2.1
11
+ * @since 0.2.0
12
+ * @author AMBROISE PARK Consulting
13
+ */
14
+
15
+ import * as v from 'valibot';
16
+
17
+ import { handleError } from '../errorHandling.js';
18
+ import {
19
+ RESERVATION_LEASE_MS,
20
+ ReservationLostError,
21
+ WEBHOOK_EVENT_RETENTION_MS,
22
+ newOwnerToken,
23
+ } from './idempotencyContract.js';
24
+ import type {
25
+ LegacyIdempotencyStore,
26
+ ReservationResult,
27
+ } from './idempotencyContract.js';
28
+
29
+ /** Firestore collection holding webhook event reservations (name kept from 0.1.x). */
30
+ const FIRESTORE_COLLECTION = 'webhook_idempotency';
31
+
32
+ /** Millisecond reading of an `expiresAt` value: Timestamp (0.2.x) or number (0.1.x). */
33
+ const ExpiresAtSchema = v.union([
34
+ v.number(),
35
+ v.pipe(
36
+ v.custom<{ toMillis(): number }>(
37
+ (value) =>
38
+ typeof value === 'object' &&
39
+ value !== null &&
40
+ typeof (value as { toMillis?: unknown }).toMillis === 'function',
41
+ 'expiresAt must be a Firestore Timestamp or a number'
42
+ ),
43
+ v.transform((timestamp) => timestamp.toMillis())
44
+ ),
45
+ ]);
46
+
47
+ /**
48
+ * Stored reservation document. 0.1.x documents carry no `status` and mean processed.
49
+ */
50
+ const FirestoreEventDocSchema = v.object({
51
+ status: v.optional(v.picklist(['processing', 'processed'])),
52
+ ownerToken: v.optional(v.string()),
53
+ reservedAt: v.optional(v.number()),
54
+ expiresAt: v.optional(ExpiresAtSchema),
55
+ });
56
+
57
+ function parseEventDoc(eventId: string, data: unknown) {
58
+ const result = v.safeParse(FirestoreEventDocSchema, data);
59
+ if (!result.success) {
60
+ throw new Error(
61
+ `Malformed ${FIRESTORE_COLLECTION}/${eventId}: ${result.issues.map((issue) => issue.message).join('; ')}`
62
+ );
63
+ }
64
+ return result.output;
65
+ }
66
+
67
+ /**
68
+ * Firestore-backed store (transactions). Collection: `webhook_idempotency`.
69
+ *
70
+ * `expiresAt` is a Firestore Timestamp {@link WEBHOOK_EVENT_RETENTION_MS} after
71
+ * the last write: enable a TTL policy on `webhook_idempotency.expiresAt` so
72
+ * Firestore deletes old documents.
73
+ *
74
+ * @version 0.2.0
75
+ * @since 0.2.0
76
+ * @author AMBROISE PARK Consulting
77
+ */
78
+ export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
79
+ let firebase: typeof import('@donotdev/firebase/server') | null = null;
80
+ const load = async () => {
81
+ if (!firebase) firebase = await import('@donotdev/firebase/server');
82
+ const firestore = firebase.getFirebaseAdminFirestore();
83
+ return {
84
+ firestore,
85
+ Timestamp: firebase.Timestamp,
86
+ refOf: (eventId: string) =>
87
+ firestore.collection(FIRESTORE_COLLECTION).doc(eventId),
88
+ };
89
+ };
90
+
91
+ const reserve = async (eventId: string): Promise<ReservationResult> => {
92
+ const { firestore, Timestamp, refOf } = await load();
93
+ const ref = refOf(eventId);
94
+ try {
95
+ return await firestore.runTransaction(async (tx) => {
96
+ const snapshot = await tx.get(ref);
97
+ const now = Date.now();
98
+ if (snapshot.exists) {
99
+ const data = parseEventDoc(eventId, snapshot.data());
100
+ if (data.status === 'processing') {
101
+ if (now - (data.reservedAt ?? 0) < RESERVATION_LEASE_MS) {
102
+ return { state: 'in_progress' } as const;
103
+ }
104
+ } else if ((data.expiresAt ?? 0) >= now) {
105
+ return { state: 'processed' } as const;
106
+ }
107
+ }
108
+ const ownerToken = newOwnerToken();
109
+ tx.set(ref, {
110
+ eventId,
111
+ status: 'processing',
112
+ ownerToken,
113
+ reservedAt: now,
114
+ expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
115
+ });
116
+ return { state: 'reserved', ownerToken } as const;
117
+ });
118
+ } catch (error) {
119
+ throw handleError(error);
120
+ }
121
+ };
122
+
123
+ return {
124
+ reserve,
125
+ async checkAndReserve(eventId) {
126
+ return (await reserve(eventId)).state !== 'reserved';
127
+ },
128
+ async markProcessed(eventId, ownerToken) {
129
+ const { firestore, Timestamp, refOf } = await load();
130
+ const ref = refOf(eventId);
131
+ const now = Date.now();
132
+ const processed = {
133
+ eventId,
134
+ status: 'processed',
135
+ processedAt: now,
136
+ expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
137
+ };
138
+ try {
139
+ if (ownerToken === undefined) {
140
+ // 0.1.x call: unconditional write
141
+ await ref.set(processed);
142
+ return;
143
+ }
144
+ await firestore.runTransaction(async (tx) => {
145
+ const snapshot = await tx.get(ref);
146
+ const data = snapshot.exists
147
+ ? parseEventDoc(eventId, snapshot.data())
148
+ : null;
149
+ if (data?.ownerToken !== ownerToken) {
150
+ throw new ReservationLostError(eventId);
151
+ }
152
+ tx.set(ref, { ...processed, ownerToken });
153
+ });
154
+ } catch (error) {
155
+ if (error instanceof ReservationLostError) throw error;
156
+ throw handleError(error);
157
+ }
158
+ },
159
+ async release(eventId, ownerToken) {
160
+ const { firestore, refOf } = await load();
161
+ const ref = refOf(eventId);
162
+ try {
163
+ return await firestore.runTransaction(async (tx) => {
164
+ const snapshot = await tx.get(ref);
165
+ if (!snapshot.exists) return false;
166
+ const data = parseEventDoc(eventId, snapshot.data());
167
+ if (data.status !== 'processing' || data.ownerToken !== ownerToken) {
168
+ return false;
169
+ }
170
+ tx.delete(ref);
171
+ return true;
172
+ });
173
+ } catch (error) {
174
+ throw handleError(error);
175
+ }
176
+ },
177
+ async isProcessed(eventId) {
178
+ const { refOf } = await load();
179
+ try {
180
+ const snapshot = await refOf(eventId).get();
181
+ if (!snapshot.exists) return false;
182
+ const data = parseEventDoc(eventId, snapshot.data());
183
+ return data.status !== 'processing' && (data.expiresAt ?? 0) >= Date.now();
184
+ } catch (error) {
185
+ throw handleError(error);
186
+ }
187
+ },
188
+ };
189
+ }
@@ -10,4 +10,3 @@
10
10
  */
11
11
 
12
12
  export { updateUserSubscription } from './updateUserSubscription.js';
13
- export type { SubscriptionData } from './updateUserSubscription.js';
@@ -9,16 +9,14 @@
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
- import { stripe, validateStripeEnvironment } from '../../utils.js';
20
-
21
- import type Stripe from 'stripe';
19
+ import { stripe, validateStripeEnvironment } from '../stripeClient.js';
22
20
 
23
21
  /**
24
22
  * Cancel user subscription at period end
@@ -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();
@@ -9,40 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- // Removed Firebase-specific import
13
-
14
- /**
15
- * Subscription data structure
16
- *
17
- * @version 0.1.0
18
- * @since 0.0.1
19
- * @author AMBROISE PARK Consulting
20
- */
21
- export interface SubscriptionData {
22
- tier: string;
23
- status: 'active' | 'canceled' | 'past_due' | 'trialing' | 'incomplete';
24
- subscriptionEnd: string | null;
25
- cancelAtPeriodEnd?: boolean;
26
- subscriptionId?: string | null;
27
- customerId?: string;
28
- }
29
-
30
- /**
31
- * Platform-agnostic auth provider interface
32
- *
33
- * @version 0.1.0
34
- * @since 0.0.1
35
- * @author AMBROISE PARK Consulting
36
- */
37
- export interface AuthProvider {
38
- getUser(userId: string): Promise<{
39
- customClaims?: Record<string, unknown>;
40
- }>;
41
- setCustomUserClaims(
42
- userId: string,
43
- claims: Record<string, unknown>
44
- ): Promise<void>;
45
- }
12
+ import type { BillingAuthProvider, SubscriptionUpdate } from '@donotdev/core/server';
46
13
 
47
14
  /**
48
15
  * Platform-agnostic subscription update using dependency injection
@@ -54,8 +21,8 @@ export interface AuthProvider {
54
21
  */
55
22
  export async function updateUserSubscription(
56
23
  userId: string,
57
- subscriptionData: SubscriptionData,
58
- authProvider: AuthProvider
24
+ subscriptionData: SubscriptionUpdate,
25
+ authProvider: BillingAuthProvider
59
26
  ): Promise<void> {
60
27
  const user = await authProvider.getUser(userId);
61
28
  const currentClaims = user.customClaims || {};
@@ -1,206 +1,137 @@
1
1
  // packages/functions/src/shared/billing/idempotency.ts
2
2
 
3
3
  /**
4
- * @fileoverview Adaptive Idempotency for Billing Webhooks
5
- * @description Auto-detects Firestore, gracefully degrades to in-memory
4
+ * @fileoverview Webhook idempotency stores
5
+ * @description Durable, atomic event reservation for Stripe webhooks. Every
6
+ * webhook entry point passes the store that matches its backend: Firestore
7
+ * (Firebase, Vercel: `firestoreIdempotency.ts`) or Postgres (Supabase:
8
+ * `supabaseIdempotency.ts`). There is no implicit fallback. This module
9
+ * aggregates the stores; backend entry points import their own store file.
6
10
  *
7
- * @version 0.1.0
11
+ * Lifecycle per event: `reserve` → process → `markProcessed(ownerToken)`, or
12
+ * `release(ownerToken)` when processing failed (so the provider's retry is
13
+ * processed). Only the owner of a reservation may change it. A reservation
14
+ * whose worker died is retaken after {@link RESERVATION_LEASE_MS}.
15
+ *
16
+ * @version 0.2.0
8
17
  * @since 0.0.1
9
18
  * @author AMBROISE PARK Consulting
10
19
  */
11
20
 
12
- import { handleError } from '../errorHandling.js';
13
21
  import { isFirestoreConfigured } from '../utils/detectFirestore.js';
22
+ import { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
23
+ import {
24
+ RESERVATION_LEASE_MS,
25
+ ReservationLostError,
26
+ newOwnerToken,
27
+ } from './idempotencyContract.js';
28
+ import type {
29
+ LegacyIdempotencyStore,
30
+ ReservationResult,
31
+ } from './idempotencyContract.js';
32
+
33
+ export {
34
+ RESERVATION_LEASE_MS,
35
+ ReservationLostError,
36
+ WEBHOOK_EVENT_RETENTION_MS,
37
+ } from './idempotencyContract.js';
38
+ export type {
39
+ IdempotencyStore,
40
+ LegacyIdempotencyStore,
41
+ ReservationResult,
42
+ } from './idempotencyContract.js';
43
+ export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
44
+
45
+ // =============================================================================
46
+ // In-memory (tests only)
47
+ // =============================================================================
14
48
 
15
49
  /**
16
- * Idempotency store interface
50
+ * In-memory store. Single process only: for tests, never for a deployed webhook.
17
51
  *
18
- * @version 0.1.0
19
- * @since 0.0.1
52
+ * @version 0.2.0
53
+ * @since 0.2.0
20
54
  * @author AMBROISE PARK Consulting
21
55
  */
22
- export interface IdempotencyStore {
23
- isProcessed(eventId: string): Promise<boolean>;
24
- markProcessed(eventId: string): Promise<void>;
25
- /** Atomic check-and-reserve: returns true if already processed, false if reserved for processing */
26
- checkAndReserve(eventId: string): Promise<boolean>;
27
- }
28
-
29
- /**
30
- * In-memory idempotency (fallback)
31
- */
32
- class InMemoryIdempotency implements IdempotencyStore {
33
- private store = new Set<string>();
34
- private warned = false;
35
-
36
- async isProcessed(eventId: string): Promise<boolean> {
37
- if (!this.warned) {
38
- // Use handleError for consistent error handling, but don't throw for warnings
39
- console.warn(
40
- '⚠️ [Idempotency] Using in-memory storage (not production-ready for scale)\n' +
41
- ' Enable Firestore for production: https://console.firebase.google.com\n' +
42
- ' Good for: Single instance, < 1K webhooks/month\n' +
43
- ' Upgrade when: Multiple instances, > 1K webhooks/month'
44
- );
45
- this.warned = true;
56
+ export function createInMemoryIdempotencyStore(): LegacyIdempotencyStore {
57
+ const events = new Map<
58
+ string,
59
+ { status: 'processing' | 'processed'; ownerToken: string; at: number }
60
+ >();
61
+ const reserve = async (eventId: string): Promise<ReservationResult> => {
62
+ const entry = events.get(eventId);
63
+ const now = Date.now();
64
+ if (entry?.status === 'processed') return { state: 'processed' };
65
+ if (entry && now - entry.at < RESERVATION_LEASE_MS) {
66
+ return { state: 'in_progress' };
46
67
  }
47
- return this.store.has(eventId);
48
- }
49
-
50
- async markProcessed(eventId: string): Promise<void> {
51
- this.store.add(eventId);
52
-
53
- // G58: FIFO cleanup — delete the oldest (first-inserted) entry via iterator
54
- if (this.store.size > 1000) {
55
- const oldest = this.store.values().next().value;
56
- if (oldest) this.store.delete(oldest);
57
- }
58
- }
59
-
60
- /**
61
- * @limitation Not truly atomic for concurrent async operations within the same event loop tick.
62
- * Two webhook retries arriving simultaneously could both pass the check.
63
- * For production billing, use the Firestore/Supabase implementations which provide true atomicity.
64
- */
65
- async checkAndReserve(eventId: string): Promise<boolean> {
66
- if (this.store.has(eventId)) return true;
67
- this.store.add(eventId);
68
- return false;
69
- }
70
- }
71
-
72
- /**
73
- * Firestore idempotency (production)
74
- */
75
- class FirestoreIdempotency implements IdempotencyStore {
76
- private db!: FirebaseFirestore.Firestore;
77
- private collection = 'webhook_idempotency';
78
- private initialized = false;
79
-
80
- private async init() {
81
- if (this.initialized) return;
82
-
83
- const { getFirebaseAdminFirestore } =
84
- await import('@donotdev/firebase/server');
85
- this.db = getFirebaseAdminFirestore();
86
- this.initialized = true;
87
- }
88
-
89
- async isProcessed(eventId: string): Promise<boolean> {
90
- await this.init();
91
-
92
- try {
93
- const doc = await this.db.collection(this.collection).doc(eventId).get();
94
-
95
- if (!doc.exists) return false;
96
-
97
- const data = doc.data();
98
- if (!data) return false;
99
-
100
- // Check expiration (30 days)
101
- const expiresAt = data.expiresAt || 0;
102
- if (expiresAt < Date.now()) {
103
- await doc.ref.delete(); // Clean up expired
68
+ const ownerToken = newOwnerToken();
69
+ events.set(eventId, { status: 'processing', ownerToken, at: now });
70
+ return { state: 'reserved', ownerToken };
71
+ };
72
+ return {
73
+ reserve,
74
+ async checkAndReserve(eventId) {
75
+ return (await reserve(eventId)).state !== 'reserved';
76
+ },
77
+ async markProcessed(eventId, ownerToken) {
78
+ const entry = events.get(eventId);
79
+ if (ownerToken !== undefined && entry?.ownerToken !== ownerToken) {
80
+ throw new ReservationLostError(eventId);
81
+ }
82
+ events.set(eventId, {
83
+ status: 'processed',
84
+ ownerToken: ownerToken ?? entry?.ownerToken ?? newOwnerToken(),
85
+ at: Date.now(),
86
+ });
87
+ },
88
+ async release(eventId, ownerToken) {
89
+ const entry = events.get(eventId);
90
+ if (entry?.status !== 'processing' || entry.ownerToken !== ownerToken) {
104
91
  return false;
105
92
  }
106
-
93
+ events.delete(eventId);
107
94
  return true;
108
- } catch (error) {
109
- throw handleError(error);
110
- }
111
- }
112
-
113
- async markProcessed(eventId: string): Promise<void> {
114
- await this.init();
115
-
116
- try {
117
- // Use atomic check-and-set to prevent race conditions
118
- await this.db.runTransaction(async (transaction) => {
119
- const docRef = this.db.collection(this.collection).doc(eventId);
120
- const doc = await transaction.get(docRef);
121
-
122
- if (doc.exists) {
123
- // Already processed, no need to set again
124
- return;
125
- }
126
-
127
- // Atomically set the document
128
- transaction.set(docRef, {
129
- eventId,
130
- processedAt: Date.now(),
131
- expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
132
- });
133
- });
134
- } catch (error) {
135
- throw handleError(error);
136
- }
137
- }
138
-
139
- async checkAndReserve(eventId: string): Promise<boolean> {
140
- await this.init();
95
+ },
96
+ async isProcessed(eventId) {
97
+ return events.get(eventId)?.status === 'processed';
98
+ },
99
+ };
100
+ }
141
101
 
142
- try {
143
- let alreadyProcessed = false;
144
- await this.db.runTransaction(async (transaction) => {
145
- const docRef = this.db.collection(this.collection).doc(eventId);
146
- const doc = await transaction.get(docRef);
102
+ // =============================================================================
103
+ // 0.1.x auto-detection (deprecated)
104
+ // =============================================================================
147
105
 
148
- if (doc.exists) {
149
- const data = doc.data();
150
- const expiresAt = data?.expiresAt || 0;
151
- if (expiresAt >= Date.now()) {
152
- alreadyProcessed = true;
153
- return;
154
- }
155
- }
156
-
157
- // Atomically reserve the event
158
- transaction.set(docRef, {
159
- eventId,
160
- processedAt: Date.now(),
161
- expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
162
- });
163
- });
164
- return alreadyProcessed;
165
- } catch (error) {
166
- throw handleError(error);
167
- }
168
- }
169
- }
106
+ let cachedStore: LegacyIdempotencyStore | null = null;
170
107
 
171
108
  /**
172
- * Create idempotency store with auto-detection
173
- *
174
- * Checks for Firestore availability:
175
- * 1. Running in Firebase Functions environment (auto-configured)
176
- * 2. Manual Firebase Admin SDK credentials in .env
109
+ * 0.1.x store auto-detection: Firestore when configured, else in-memory.
177
110
  *
178
- * Falls back to in-memory if Firestore not available
179
- *
180
- * @version 0.1.0
111
+ * @deprecated In-memory is not durable across instances. Pass an explicit store:
112
+ * {@link createFirestoreIdempotencyStore} or `createSupabaseIdempotencyStore`.
113
+ * Framework webhook entry points already do.
114
+ * @version 0.2.0
181
115
  * @since 0.0.1
182
116
  * @author AMBROISE PARK Consulting
183
117
  */
184
- let cachedStore: IdempotencyStore | null = null;
185
-
186
- export function createIdempotencyStore(): IdempotencyStore {
187
- // Return cached instance (singleton per function instance)
118
+ export function createIdempotencyStore(): LegacyIdempotencyStore {
188
119
  if (cachedStore) return cachedStore;
189
-
190
120
  if (isFirestoreConfigured()) {
191
- console.log('✅ [Idempotency] Using Firestore (production-ready)');
192
- cachedStore = new FirestoreIdempotency();
121
+ cachedStore = createFirestoreIdempotencyStore();
193
122
  } else {
194
- console.warn('⚠️ [Idempotency] Firestore not configured, using in-memory');
195
- cachedStore = new InMemoryIdempotency();
123
+ console.warn(
124
+ '[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store.'
125
+ );
126
+ cachedStore = createInMemoryIdempotencyStore();
196
127
  }
197
-
198
128
  return cachedStore;
199
129
  }
200
130
 
201
131
  /**
202
- * Reset cached store (for testing only)
132
+ * Reset the store cached by {@link createIdempotencyStore} (tests).
203
133
  *
134
+ * @deprecated See {@link createIdempotencyStore}.
204
135
  * @version 0.1.0
205
136
  * @since 0.0.1
206
137
  * @author AMBROISE PARK Consulting
@@ -208,3 +139,8 @@ export function createIdempotencyStore(): IdempotencyStore {
208
139
  export function resetIdempotencyStore() {
209
140
  cachedStore = null;
210
141
  }
142
+
143
+ export {
144
+ WEBHOOK_EVENTS_SQL,
145
+ createSupabaseIdempotencyStore,
146
+ } from './supabaseIdempotency.js';