@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,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
+ }
@@ -0,0 +1,432 @@
1
+ // packages/functions/src/shared/billing/tierWebhookEvents.ts
2
+
3
+ /**
4
+ * @fileoverview Stripe webhook handlers for tier items
5
+ * @description StripePayment / StripeSubscription event handlers routed by
6
+ * `processWebhook`: checkout grant (payment_status aware), renewal,
7
+ * cancellation and payment failure.
8
+ *
9
+ * @version 0.2.0
10
+ * @since 0.0.1
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+
14
+ import type Stripe from 'stripe';
15
+
16
+ import {
17
+ calculateSubscriptionEndDate,
18
+ SUBSCRIPTION_STATUS,
19
+ SUBSCRIPTION_TIERS,
20
+ } from '@donotdev/core/server';
21
+ import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';
22
+
23
+ import { handleError } from '../errorHandling.js';
24
+ import { logger } from '../logger.js';
25
+ import type { OrderSessionEventType } from './orderWebhook.js';
26
+
27
+ /**
28
+ * Checkout Session event of a StripePayment / StripeSubscription item.
29
+ * Grants only once the payment is settled (Stripe fulfillment guide,
30
+ * https://docs.stripe.com/checkout/fulfillment):
31
+ * - `completed` + `paid` / `no_payment_required` → grant
32
+ * - `completed` + `unpaid` (delayed method, e.g. SEPA debit) → log, wait
33
+ * - `async_payment_succeeded` → grant
34
+ * - `async_payment_failed` → log (nothing was granted)
35
+ * - `expired` → ignored
36
+ *
37
+ * @throws When `payment_status` is not a known value, or when the grant fails
38
+ *
39
+ * @version 0.2.0
40
+ * @since 0.2.0
41
+ * @author AMBROISE PARK Consulting
42
+ */
43
+ export async function handleTierCheckoutEvent(
44
+ eventType: OrderSessionEventType,
45
+ session: Stripe.Checkout.Session,
46
+ config: StripeBackConfig,
47
+ updateSubscription: UpdateSubscriptionFn,
48
+ authProvider: BillingAuthProvider | null
49
+ ): Promise<void> {
50
+ const logContext = {
51
+ sessionId: session.id,
52
+ billingConfigKey: session.metadata?.billingConfigKey,
53
+ userId: session.metadata?.userId,
54
+ paymentStatus: session.payment_status,
55
+ };
56
+ switch (eventType) {
57
+ case 'checkout.session.completed':
58
+ if (session.payment_status === 'unpaid') {
59
+ logger.info('[Webhook] Purchase awaiting async payment', {
60
+ ...logContext,
61
+ operation: 'purchase_payment_pending',
62
+ });
63
+ return;
64
+ }
65
+ if (
66
+ session.payment_status !== 'paid' &&
67
+ session.payment_status !== 'no_payment_required'
68
+ ) {
69
+ throw handleError(
70
+ new Error(
71
+ `Checkout session ${session.id} has unknown payment_status ${String(session.payment_status)}`
72
+ )
73
+ );
74
+ }
75
+ await grantCheckoutPurchase(
76
+ session,
77
+ config,
78
+ updateSubscription,
79
+ authProvider
80
+ );
81
+ return;
82
+ case 'checkout.session.async_payment_succeeded':
83
+ await grantCheckoutPurchase(
84
+ session,
85
+ config,
86
+ updateSubscription,
87
+ authProvider
88
+ );
89
+ return;
90
+ case 'checkout.session.async_payment_failed':
91
+ logger.warn('[Webhook] Async purchase payment failed, nothing granted', {
92
+ ...logContext,
93
+ operation: 'purchase_payment_failed',
94
+ });
95
+ return;
96
+ case 'checkout.session.expired':
97
+ logger.debug('[Webhook] Checkout session expired', logContext);
98
+ return;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Grant the tier bought in a paid Checkout Session, then run the item hook.
104
+ * Idempotent: it writes the same subscription state again on a replay.
105
+ */
106
+ async function grantCheckoutPurchase(
107
+ session: Stripe.Checkout.Session,
108
+ config: StripeBackConfig,
109
+ updateSubscription: UpdateSubscriptionFn,
110
+ authProvider: BillingAuthProvider | null
111
+ ): Promise<void> {
112
+ const { userId, billingConfigKey } = session.metadata || {};
113
+
114
+ if (!userId || !billingConfigKey) {
115
+ throw handleError(
116
+ new Error(
117
+ `Missing required metadata: userId=${userId}, billingConfigKey=${billingConfigKey}`
118
+ )
119
+ );
120
+ }
121
+
122
+ const billingItem = config[billingConfigKey];
123
+ if (!billingItem) {
124
+ throw handleError(
125
+ new Error(`Unknown billing config key: ${billingConfigKey}`)
126
+ );
127
+ }
128
+
129
+ logger.info('[Webhook] Processing purchase', {
130
+ userId,
131
+ configKey: billingConfigKey,
132
+ type: billingItem.type,
133
+ operation: 'purchase_processing',
134
+ });
135
+
136
+ // Update subscription
137
+ if (billingItem.type === 'StripePayment') {
138
+ if (!authProvider) {
139
+ throw handleError(
140
+ new Error('Auth provider required for subscription updates')
141
+ );
142
+ }
143
+ await updateSubscription(
144
+ userId,
145
+ {
146
+ tier: billingItem.tier,
147
+ status: SUBSCRIPTION_STATUS.ACTIVE,
148
+ subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
149
+ customerId: session.customer as string,
150
+ },
151
+ authProvider
152
+ );
153
+
154
+ // Execute hook with graceful error handling
155
+ if (billingItem.onPurchaseSuccess) {
156
+ try {
157
+ await billingItem.onPurchaseSuccess(userId, session.metadata || {});
158
+ } catch (error) {
159
+ // Hook failures are non-critical - payment already processed
160
+ // Log for manual intervention but don't fail the webhook
161
+ logger.error('[Webhook] Hook failed (non-critical)', {
162
+ error: error instanceof Error ? error : new Error(String(error)),
163
+ hookName: 'onPurchaseSuccess',
164
+ userId,
165
+ operation: 'hook_execution',
166
+ });
167
+ }
168
+ }
169
+ }
170
+
171
+ if (billingItem.type === 'StripeSubscription') {
172
+ if (!authProvider) {
173
+ throw handleError(
174
+ new Error('Auth provider required for subscription updates')
175
+ );
176
+ }
177
+ await updateSubscription(
178
+ userId,
179
+ {
180
+ tier: billingItem.tier,
181
+ status: SUBSCRIPTION_STATUS.ACTIVE,
182
+ subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
183
+ subscriptionId: session.subscription as string,
184
+ customerId: session.customer as string,
185
+ },
186
+ authProvider
187
+ );
188
+
189
+ // Execute hook with graceful error handling
190
+ if (billingItem.onSubscriptionCreated) {
191
+ try {
192
+ await billingItem.onSubscriptionCreated(userId, session.metadata || {});
193
+ } catch (error) {
194
+ // Hook failures are non-critical - subscription already created
195
+ // Log for manual intervention but don't fail the webhook
196
+ logger.error('[Webhook] Hook failed (non-critical)', {
197
+ error: error instanceof Error ? error : new Error(String(error)),
198
+ hookName: 'onSubscriptionCreated',
199
+ userId,
200
+ operation: 'hook_execution',
201
+ });
202
+ }
203
+ }
204
+ }
205
+
206
+ logger.info('[Webhook] Purchase processed', {
207
+ userId,
208
+ configKey: billingConfigKey,
209
+ operation: 'purchase_processed',
210
+ });
211
+ }
212
+
213
+ /**
214
+ * Handle subscription renewal
215
+ *
216
+ * @version 0.1.0
217
+ * @since 0.0.1
218
+ * @author AMBROISE PARK Consulting
219
+ */
220
+ export async function handleInvoicePaymentSucceeded(
221
+ invoice: Stripe.Invoice,
222
+ config: StripeBackConfig,
223
+ updateSubscription: UpdateSubscriptionFn,
224
+ stripe: Stripe,
225
+ authProvider: BillingAuthProvider | null
226
+ ): Promise<void> {
227
+ const subscriptionId = (invoice as any).subscription as string;
228
+ if (!subscriptionId) return;
229
+
230
+ // ✅ FIX: Fetch subscription to get metadata
231
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
232
+ const { userId, billingConfigKey } = subscription.metadata || {};
233
+ if (!userId || !billingConfigKey) {
234
+ // G60: Log when subscription metadata is missing — silent return loses the event
235
+ logger.error(
236
+ '[Webhook] Subscription metadata missing userId or billingConfigKey',
237
+ {
238
+ subscriptionId,
239
+ hasUserId: !!userId,
240
+ hasBillingConfigKey: !!billingConfigKey,
241
+ operation: 'invoice_payment_succeeded_metadata_missing',
242
+ }
243
+ );
244
+ return;
245
+ }
246
+
247
+ const billingItem = config[billingConfigKey];
248
+ if (!billingItem || billingItem.type !== 'StripeSubscription') return;
249
+
250
+ // Renew subscription
251
+ if (!authProvider) {
252
+ throw handleError(
253
+ new Error('Auth provider required for subscription updates')
254
+ );
255
+ }
256
+ await updateSubscription(
257
+ userId,
258
+ {
259
+ tier: billingItem.tier,
260
+ status: SUBSCRIPTION_STATUS.ACTIVE,
261
+ subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
262
+ subscriptionId: subscriptionId,
263
+ customerId: invoice.customer as string,
264
+ },
265
+ authProvider
266
+ );
267
+
268
+ // Execute hook with graceful error handling
269
+ if (billingItem.onSubscriptionRenewed) {
270
+ try {
271
+ await billingItem.onSubscriptionRenewed(
272
+ userId,
273
+ subscription.metadata || {}
274
+ );
275
+ } catch (error) {
276
+ // Hook failures are non-critical - subscription already renewed
277
+ // Log for manual intervention but don't fail the webhook
278
+ logger.error('[Webhook] Hook failed (non-critical)', {
279
+ error: error instanceof Error ? error : new Error(String(error)),
280
+ hookName: 'onSubscriptionRenewed',
281
+ userId,
282
+ operation: 'hook_execution',
283
+ });
284
+ }
285
+ }
286
+
287
+ logger.info('[Webhook] Subscription renewed', {
288
+ userId,
289
+ billingConfigKey,
290
+ operation: 'subscription_renewed',
291
+ });
292
+ }
293
+
294
+ /**
295
+ * Handle subscription cancellation
296
+ *
297
+ * @version 0.1.0
298
+ * @since 0.0.1
299
+ * @author AMBROISE PARK Consulting
300
+ */
301
+ export async function handleSubscriptionDeleted(
302
+ subscription: Stripe.Subscription,
303
+ config: StripeBackConfig,
304
+ updateSubscription: UpdateSubscriptionFn,
305
+ authProvider: BillingAuthProvider | null
306
+ ): Promise<void> {
307
+ const { userId, billingConfigKey } = subscription.metadata || {};
308
+ if (!userId || !billingConfigKey) return;
309
+
310
+ const billingItem = config[billingConfigKey];
311
+ if (!billingItem || billingItem.type !== 'StripeSubscription') return;
312
+
313
+ // Update to cancelled
314
+ if (!authProvider) {
315
+ throw handleError(
316
+ new Error('Auth provider required for subscription updates')
317
+ );
318
+ }
319
+ await updateSubscription(
320
+ userId,
321
+ {
322
+ tier: SUBSCRIPTION_TIERS.FREE,
323
+ status: SUBSCRIPTION_STATUS.CANCELED,
324
+ subscriptionEnd: new Date(
325
+ (subscription as any).current_period_end * 1000
326
+ ).toISOString(),
327
+ subscriptionId: subscription.id,
328
+ customerId: subscription.customer as string,
329
+ },
330
+ authProvider
331
+ );
332
+
333
+ // Execute hook with graceful error handling
334
+ if (billingItem.onSubscriptionCancelled) {
335
+ try {
336
+ await billingItem.onSubscriptionCancelled(
337
+ userId,
338
+ subscription.metadata || {}
339
+ );
340
+ } catch (error) {
341
+ // Hook failures are non-critical - subscription already cancelled
342
+ // Log for manual intervention but don't fail the webhook
343
+ logger.error('[Webhook] Hook failed (non-critical)', {
344
+ error: error instanceof Error ? error : new Error(String(error)),
345
+ hookName: 'onSubscriptionCancelled',
346
+ userId,
347
+ operation: 'hook_execution',
348
+ });
349
+ }
350
+ }
351
+
352
+ logger.info('[Webhook] Subscription cancelled', {
353
+ userId,
354
+ billingConfigKey,
355
+ operation: 'subscription_cancelled',
356
+ });
357
+ }
358
+
359
+ /**
360
+ * Handle payment failure
361
+ *
362
+ * @version 0.1.0
363
+ * @since 0.0.1
364
+ * @author AMBROISE PARK Consulting
365
+ */
366
+ export async function handlePaymentFailed(
367
+ invoice: Stripe.Invoice,
368
+ config: StripeBackConfig
369
+ ): Promise<void> {
370
+ const { userId, billingConfigKey } = invoice.metadata || {};
371
+ if (!userId || !billingConfigKey) {
372
+ logger.warn('[Webhook] Payment failed - missing metadata', {
373
+ invoiceId: invoice.id,
374
+ hasUserId: !!userId,
375
+ hasBillingConfigKey: !!billingConfigKey,
376
+ operation: 'payment_failed_metadata_missing',
377
+ });
378
+ return;
379
+ }
380
+
381
+ const billingItem = config[billingConfigKey];
382
+ if (!billingItem) {
383
+ logger.error('[Webhook] Payment failed - unknown billing config', {
384
+ error: new Error(`Unknown billing config key: ${billingConfigKey}`),
385
+ userId,
386
+ billingConfigKey,
387
+ operation: 'payment_failed_unknown_config',
388
+ });
389
+ return;
390
+ }
391
+
392
+ // Execute hooks with graceful error handling
393
+ if (billingItem.type === 'StripePayment' && billingItem.onPurchaseFailure) {
394
+ try {
395
+ // Pass the actual metadata - we've already validated it exists
396
+ await billingItem.onPurchaseFailure(userId, invoice.metadata || {});
397
+ } catch (error) {
398
+ // Hook failures are non-critical - payment already failed
399
+ // Log for manual intervention but don't fail the webhook
400
+ logger.error('[Webhook] Hook failed (non-critical)', {
401
+ error: error instanceof Error ? error : new Error(String(error)),
402
+ hookName: 'onPurchaseFailure',
403
+ userId,
404
+ operation: 'hook_execution',
405
+ });
406
+ }
407
+ }
408
+
409
+ if (
410
+ billingItem.type === 'StripeSubscription' &&
411
+ billingItem.onPaymentFailed
412
+ ) {
413
+ try {
414
+ await billingItem.onPaymentFailed(userId, invoice.metadata || {});
415
+ } catch (error) {
416
+ // Hook failures are non-critical - payment already failed
417
+ // Log for manual intervention but don't fail the webhook
418
+ logger.error('[Webhook] Hook failed (non-critical)', {
419
+ error: error instanceof Error ? error : new Error(String(error)),
420
+ hookName: 'onPaymentFailed',
421
+ userId,
422
+ operation: 'hook_execution',
423
+ });
424
+ }
425
+ }
426
+
427
+ logger.warn('[Webhook] Payment failed', {
428
+ userId,
429
+ billingConfigKey,
430
+ operation: 'payment_failed',
431
+ });
432
+ }