@donotdev/functions 0.1.44 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/README.md +25 -14
  2. package/lib/chunks/chunk-2JL3GDTO.js +151 -0
  3. package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
  4. package/lib/chunks/chunk-4TVLH2W2.js +22 -0
  5. package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
  6. package/lib/chunks/chunk-4U7QQWYG.js +22 -0
  7. package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
  8. package/lib/chunks/chunk-5DTPEM64.js +22 -0
  9. package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
  10. package/lib/chunks/chunk-6CQXHNVL.js +22 -0
  11. package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
  12. package/lib/chunks/chunk-6DSCPZC6.js +22 -0
  13. package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
  14. package/lib/chunks/chunk-7E6TGWHU.js +22 -0
  15. package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
  16. package/lib/chunks/chunk-7LT32OWE.js +22 -0
  17. package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
  18. package/lib/chunks/chunk-7VH2GJXT.js +151 -0
  19. package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
  20. package/lib/chunks/chunk-API5A4BV.js +22 -0
  21. package/lib/chunks/chunk-API5A4BV.js.map +7 -0
  22. package/lib/chunks/chunk-AYY7UXNI.js +22 -0
  23. package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
  24. package/lib/chunks/chunk-BUP7SXPV.js +23 -0
  25. package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
  26. package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
  27. package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
  28. package/lib/chunks/chunk-FSLGZD7A.js +21 -0
  29. package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
  30. package/lib/chunks/chunk-GVLSPWDD.js +151 -0
  31. package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
  32. package/lib/chunks/chunk-GXQVWEFT.js +22 -0
  33. package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
  34. package/lib/chunks/chunk-HB7EGXVI.js +22 -0
  35. package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
  36. package/lib/chunks/chunk-HLNYUAZH.js +22 -0
  37. package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
  38. package/lib/chunks/chunk-HM7XCMWW.js +22 -0
  39. package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
  40. package/lib/chunks/chunk-I7IOIL6U.js +151 -0
  41. package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
  42. package/lib/chunks/chunk-IFOYVSPU.js +22 -0
  43. package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
  44. package/lib/chunks/chunk-JTAGPPPL.js +22 -0
  45. package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
  46. package/lib/chunks/chunk-MZ232FUE.js +22 -0
  47. package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
  48. package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
  49. package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
  50. package/lib/chunks/chunk-NP2AN2TV.js +22 -0
  51. package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
  52. package/lib/chunks/chunk-QJAU2MWV.js +22 -0
  53. package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
  54. package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
  55. package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
  56. package/lib/chunks/chunk-RQZGIZHD.js +151 -0
  57. package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
  58. package/lib/chunks/chunk-TBEDQLOB.js +23 -0
  59. package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
  60. package/lib/chunks/chunk-TMHBP3HB.js +22 -0
  61. package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
  62. package/lib/chunks/chunk-UH4L3EF3.js +151 -0
  63. package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
  64. package/lib/chunks/chunk-UJBIU6TL.js +22 -0
  65. package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
  66. package/lib/chunks/chunk-VKEYW3NT.js +22 -0
  67. package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
  68. package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
  69. package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
  70. package/lib/chunks/chunk-Y44NEQQG.js +22 -0
  71. package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
  72. package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
  73. package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
  74. package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
  75. package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
  76. package/lib/chunks/monitoring-PVQMFL34.js +22 -0
  77. package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
  78. package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
  79. package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
  80. package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
  81. package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
  82. package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
  83. package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
  84. package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
  85. package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
  86. package/lib/chunks/server-32A5RH4C.js +22 -0
  87. package/lib/chunks/server-32A5RH4C.js.map +7 -0
  88. package/lib/chunks/server-7HDAP5DL.js +22 -0
  89. package/lib/chunks/server-7HDAP5DL.js.map +7 -0
  90. package/lib/chunks/server-S2IMFOY7.js +22 -0
  91. package/lib/chunks/server-S2IMFOY7.js.map +7 -0
  92. package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
  93. package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
  94. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  95. package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
  96. package/lib/firebase/baseFunction.d.ts +1 -1
  97. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
  98. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  99. package/lib/firebase/billing/index.d.ts +2 -1
  100. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
  101. package/lib/firebase/billing/webhookHandler.d.ts +17 -2
  102. package/lib/firebase/crud/aggregate.d.ts +0 -9
  103. package/lib/firebase/crud/bulk.d.ts +2 -2
  104. package/lib/firebase/crud/create.d.ts +1 -1
  105. package/lib/firebase/crud/delete.d.ts +1 -1
  106. package/lib/firebase/crud/get.d.ts +1 -1
  107. package/lib/firebase/crud/list.d.ts +1 -1
  108. package/lib/firebase/crud/update.d.ts +1 -9
  109. package/lib/firebase/index.js +1 -5
  110. package/lib/firebase/index.js.map +4 -4
  111. package/lib/firebase/oauth/githubAccess.d.ts +2 -2
  112. package/lib/firebase/registerCrudFunctions.d.ts +9 -1
  113. package/lib/shared/billing/apiVersion.d.ts +22 -0
  114. package/lib/shared/billing/checkoutPrice.d.ts +27 -0
  115. package/lib/shared/billing/checkoutValidation.d.ts +89 -0
  116. package/lib/shared/billing/createCheckout.d.ts +73 -24
  117. package/lib/shared/billing/helpers/index.d.ts +0 -1
  118. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
  119. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
  120. package/lib/shared/billing/idempotency.d.ts +32 -10
  121. package/lib/shared/billing/idempotencyContract.d.ts +121 -0
  122. package/lib/shared/billing/index.d.ts +2 -0
  123. package/lib/shared/billing/orderWebhook.d.ts +75 -0
  124. package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
  125. package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
  126. package/lib/shared/billing/webhookHandler.d.ts +28 -20
  127. package/lib/shared/index.js +1 -6
  128. package/lib/shared/index.js.map +4 -4
  129. package/lib/shared/utils/functionWrapper.d.ts +1 -1
  130. package/lib/shared/utils/internal/auth.d.ts +38 -1
  131. package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
  132. package/lib/shared/utils/schemaValidation.d.ts +1 -1
  133. package/lib/shared/utils/vercelHelpers.d.ts +8 -0
  134. package/lib/shared/utils.d.ts +4 -17
  135. package/lib/supabase/baseFunction.d.ts +1 -1
  136. package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
  137. package/lib/supabase/crud/bulk.d.ts +1 -1
  138. package/lib/supabase/crud/entityStore.d.ts +71 -0
  139. package/lib/supabase/crud/index.d.ts +2 -0
  140. package/lib/supabase/helpers/authProvider.d.ts +5 -5
  141. package/lib/supabase/index.d.ts +10 -2
  142. package/lib/supabase/index.js +1 -3
  143. package/lib/supabase/index.js.map +4 -4
  144. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  145. package/lib/vercel/api/ai/chat.d.ts +0 -9
  146. package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
  147. package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
  148. package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
  149. package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
  150. package/lib/vercel/api/billing/backend.d.ts +39 -0
  151. package/lib/vercel/api/billing/cancel.d.ts +8 -0
  152. package/lib/vercel/api/billing/change-plan.d.ts +9 -1
  153. package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
  154. package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
  155. package/lib/vercel/api/billing/index.d.ts +4 -2
  156. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
  157. package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
  158. package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
  159. package/lib/vercel/api/crud/bulk.d.ts +17 -0
  160. package/lib/vercel/api/crud/create.d.ts +8 -0
  161. package/lib/vercel/api/crud/delete.d.ts +8 -0
  162. package/lib/vercel/api/crud/get.d.ts +8 -0
  163. package/lib/vercel/api/crud/list.d.ts +8 -0
  164. package/lib/vercel/api/crud/update.d.ts +8 -0
  165. package/lib/vercel/api/index.js +1 -3
  166. package/lib/vercel/api/index.js.map +4 -4
  167. package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
  168. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  169. package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
  170. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  171. package/lib/vercel/baseFunction.d.ts +4 -1
  172. package/lib/vercel/supabaseAdmin.d.ts +22 -0
  173. package/package.json +25 -26
  174. package/src/firebase/auth/getCustomClaims.ts +4 -5
  175. package/src/firebase/auth/getUserAuthStatus.ts +4 -5
  176. package/src/firebase/auth/removeCustomClaims.ts +4 -5
  177. package/src/firebase/auth/setCustomClaims.ts +4 -5
  178. package/src/firebase/baseFunction.ts +4 -5
  179. package/src/firebase/billing/cancelSubscription.ts +1 -2
  180. package/src/firebase/billing/changePlan.ts +2 -3
  181. package/src/firebase/billing/createCheckoutSession.ts +30 -56
  182. package/src/firebase/billing/createCustomerPortal.ts +4 -5
  183. package/src/firebase/billing/healthCheck.ts +0 -0
  184. package/src/firebase/billing/index.ts +8 -1
  185. package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
  186. package/src/firebase/billing/webhookHandler.ts +20 -4
  187. package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
  188. package/src/firebase/crud/aggregate.ts +1 -2
  189. package/src/firebase/crud/bulk.ts +5 -6
  190. package/src/firebase/crud/create.ts +5 -6
  191. package/src/firebase/crud/delete.ts +4 -5
  192. package/src/firebase/crud/get.ts +4 -5
  193. package/src/firebase/crud/list.ts +4 -5
  194. package/src/firebase/crud/update.ts +5 -6
  195. package/src/firebase/oauth/githubAccess.ts +2 -3
  196. package/src/firebase/registerCrudFunctions.ts +2 -2
  197. package/src/shared/__tests__/auth.test.ts +0 -3
  198. package/src/shared/__tests__/bulkCore.test.ts +3 -2
  199. package/src/shared/__tests__/errorHandling.test.ts +2 -2
  200. package/src/shared/__tests__/idempotency.test.ts +282 -55
  201. package/src/shared/__tests__/internalValidation.test.ts +3 -3
  202. package/src/shared/__tests__/rateLimiter.test.ts +2 -8
  203. package/src/shared/__tests__/schemaValidation.test.ts +1 -1
  204. package/src/shared/__tests__/utils.test.ts +2 -1
  205. package/src/shared/__tests__/validation-env.test.ts +0 -0
  206. package/src/shared/ai/createAIRoute.ts +53 -30
  207. package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
  208. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
  209. package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
  210. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
  211. package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
  212. package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
  213. package/src/shared/billing/apiVersion.ts +25 -0
  214. package/src/shared/billing/checkoutPrice.ts +125 -0
  215. package/src/shared/billing/checkoutValidation.ts +284 -0
  216. package/src/shared/billing/createCheckout.ts +332 -196
  217. package/src/shared/billing/helpers/index.ts +0 -1
  218. package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
  219. package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
  220. package/src/shared/billing/idempotency.ts +253 -150
  221. package/src/shared/billing/idempotencyContract.ts +135 -0
  222. package/src/shared/billing/index.ts +2 -0
  223. package/src/shared/billing/orderWebhook.ts +269 -0
  224. package/src/shared/billing/supabaseIdempotency.ts +228 -0
  225. package/src/shared/billing/tierWebhookEvents.ts +432 -0
  226. package/src/shared/billing/webhookHandler.ts +188 -385
  227. package/src/shared/utils/external/subscription.ts +0 -0
  228. package/src/shared/utils/firebaseHelpers.ts +2 -3
  229. package/src/shared/utils/functionWrapper.ts +1 -2
  230. package/src/shared/utils/internal/auth.ts +55 -7
  231. package/src/shared/utils/internal/monitoring.ts +17 -9
  232. package/src/shared/utils/internal/rateLimiter.ts +14 -5
  233. package/src/shared/utils/schemaValidation.ts +1 -2
  234. package/src/shared/utils/vercelHelpers.ts +3 -3
  235. package/src/shared/utils.ts +14 -31
  236. package/src/shared/validation.ts +1 -1
  237. package/src/supabase/__tests__/bulk.test.ts +3 -1
  238. package/src/supabase/__tests__/entityStore.test.ts +90 -0
  239. package/src/supabase/baseFunction.ts +1 -2
  240. package/src/supabase/billing/createCheckoutSession.ts +10 -36
  241. package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
  242. package/src/supabase/billing/stripeWebhook.ts +79 -0
  243. package/src/supabase/crud/aggregate.ts +1 -1
  244. package/src/supabase/crud/bulk.ts +3 -7
  245. package/src/supabase/crud/create.ts +1 -1
  246. package/src/supabase/crud/entityStore.ts +240 -0
  247. package/src/supabase/crud/index.ts +8 -0
  248. package/src/supabase/crud/update.ts +1 -1
  249. package/src/supabase/helpers/authProvider.ts +6 -5
  250. package/src/supabase/index.ts +26 -0
  251. package/src/supabase/utils/rateLimiter.ts +2 -2
  252. package/src/vercel/__tests__/bulk.test.ts +24 -21
  253. package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
  254. package/src/vercel/api/ai/chat.ts +2 -1
  255. package/src/vercel/api/auth/get-custom-claims.ts +2 -3
  256. package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
  257. package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
  258. package/src/vercel/api/auth/set-custom-claims.ts +3 -3
  259. package/src/vercel/api/billing/backend.ts +72 -0
  260. package/src/vercel/api/billing/cancel.ts +2 -4
  261. package/src/vercel/api/billing/change-plan.ts +3 -4
  262. package/src/vercel/api/billing/create-checkout-session.ts +42 -68
  263. package/src/vercel/api/billing/customer-portal.ts +2 -4
  264. package/src/vercel/api/billing/index.ts +4 -2
  265. package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
  266. package/src/vercel/api/billing/webhook-handler.ts +31 -25
  267. package/src/vercel/api/config/firebase-admin.ts +2 -2
  268. package/src/vercel/api/crud/bulk.ts +6 -9
  269. package/src/vercel/api/crud/create.ts +6 -5
  270. package/src/vercel/api/crud/delete.ts +4 -3
  271. package/src/vercel/api/crud/get.ts +6 -5
  272. package/src/vercel/api/crud/list.ts +6 -5
  273. package/src/vercel/api/crud/update.ts +6 -5
  274. package/src/vercel/api/oauth/check-github-access.ts +5 -5
  275. package/src/vercel/api/oauth/exchange-token.ts +3 -3
  276. package/src/vercel/api/oauth/grant-github-access.ts +5 -5
  277. package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
  278. package/src/vercel/baseFunction.ts +23 -8
  279. package/src/vercel/supabaseAdmin.ts +45 -0
@@ -2,66 +2,52 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview Stripe webhook handler
5
- * @description Handles Stripe webhook events for subscription management
5
+ * @description Verifies, deduplicates and routes Stripe webhook events for
6
+ * one-time payments, subscriptions (`tierWebhookEvents.ts`) and multi-line
7
+ * orders (`orderWebhook.ts`).
6
8
  *
7
- * @version 0.1.0
9
+ * @version 0.2.0
8
10
  * @since 0.0.1
9
11
  * @author AMBROISE PARK Consulting
10
12
  */
11
13
 
12
- import {
13
- validateStripeBackConfig,
14
- SUBSCRIPTION_STATUS,
15
- SUBSCRIPTION_TIERS,
16
- } from '@donotdev/core/server';
17
- import type { StripeBackConfig } from '@donotdev/core/server';
14
+ import type Stripe from 'stripe';
15
+
16
+ import { DoNotDevError, validateStripeBackConfig } from '@donotdev/core/server';
17
+ import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';
18
18
 
19
19
  import { handleError } from '../errorHandling.js';
20
20
  import { logger } from '../logger.js';
21
21
  import { createIdempotencyStore } from './idempotency.js';
22
- import { calculateSubscriptionEndDate } from '../utils/external/date.js';
23
-
24
- import type {
25
- SubscriptionData,
26
- AuthProvider,
27
- } from './helpers/updateUserSubscription.js';
28
- import type Stripe from 'stripe';
29
-
30
- // W7: Lazy singleton — resolving at import time reads env vars / Firebase Admin
31
- // before they are fully injected (e.g., defineSecret values on Firebase Functions v2).
32
- // Resolved on first use instead.
33
- let _idempotencyStore: ReturnType<typeof createIdempotencyStore> | null = null;
34
- function getIdempotencyStore() {
35
- if (!_idempotencyStore) {
36
- _idempotencyStore = createIdempotencyStore();
37
- }
38
- return _idempotencyStore;
39
- }
22
+ import { ReservationLostError } from './idempotencyContract.js';
23
+ import type { IdempotencyStore } from './idempotencyContract.js';
24
+ import { handleOrderSessionEvent } from './orderWebhook.js';
25
+ import type { OrderSessionEventType } from './orderWebhook.js';
26
+ import {
27
+ handleInvoicePaymentSucceeded,
28
+ handlePaymentFailed,
29
+ handleSubscriptionDeleted,
30
+ handleTierCheckoutEvent,
31
+ } from './tierWebhookEvents.js';
40
32
 
41
- /**
42
- * Platform-agnostic auth provider interface for webhook handlers
43
- */
44
- export interface WebhookAuthProvider {
45
- getUser(userId: string): Promise<{
46
- customClaims?: Record<string, unknown>;
47
- }>;
48
- setCustomUserClaims(
49
- userId: string,
50
- claims: Record<string, unknown>
51
- ): Promise<void>;
52
- }
33
+ /** Attempts to record a processed event before answering non-2xx. */
34
+ const MARK_PROCESSED_ATTEMPTS = 3;
53
35
 
54
- /**
55
- * Subscription update function type
56
- */
57
- export type UpdateSubscriptionFn = (
58
- userId: string,
59
- data: SubscriptionData,
60
- authProvider: AuthProvider
61
- ) => Promise<void>;
36
+ /** Backoff between markProcessed attempts (multiplied by the attempt number). */
37
+ const MARK_PROCESSED_BACKOFF_MS = 200;
62
38
 
63
39
  /**
64
- * Process webhook with automatic idempotency detection
40
+ * Verify, deduplicate and route one Stripe webhook event.
41
+ *
42
+ * Idempotency (at-least-once): the event is reserved before routing.
43
+ * - Already processed → resolves "Event already processed" (answer 2xx).
44
+ * - Another delivery holds a live lease → throws `unavailable` (answer non-2xx,
45
+ * Stripe retries later; an abandoned lease is retaken after it expires).
46
+ * - Routing throws → the reservation is released and the error rethrown, so
47
+ * Stripe's retry is processed.
48
+ * - Routing succeeds → the event is marked processed, retried a bounded number
49
+ * of times; if it still fails the error is rethrown WITHOUT releasing, so the
50
+ * event is re-run after the lease. Hooks must therefore be idempotent.
65
51
  *
66
52
  * @param rawBody - Raw request body
67
53
  * @param signature - Stripe signature
@@ -69,8 +55,12 @@ export type UpdateSubscriptionFn = (
69
55
  * @param stripe - Stripe instance
70
56
  * @param billingConfig - Billing configuration
71
57
  * @param updateSubscription - Function to update user subscription
58
+ * @param authProvider - Auth provider for subscription claims (null: subscription events fail)
59
+ * @param idempotencyStore - Durable store matching the backend (Firestore / Supabase).
60
+ * Omitted: deprecated 0.1.x auto-detection ({@link createIdempotencyStore}).
61
+ * @throws Any failure: the caller must answer non-2xx so Stripe retries
72
62
  *
73
- * @version 0.1.0
63
+ * @version 0.2.0
74
64
  * @since 0.0.1
75
65
  * @author AMBROISE PARK Consulting
76
66
  */
@@ -79,33 +69,49 @@ export async function processWebhook(
79
69
  signature: string,
80
70
  webhookSecret: string,
81
71
  stripe: Stripe,
82
- billingConfig: unknown,
72
+ billingConfig: StripeBackConfig,
83
73
  updateSubscription: UpdateSubscriptionFn,
84
- authProvider: WebhookAuthProvider | null
74
+ authProvider: BillingAuthProvider | null,
75
+ idempotencyStore: IdempotencyStore = createIdempotencyStore()
85
76
  ): Promise<{ success: boolean; message: string }> {
86
77
  try {
87
- // Validate billing config
88
- const config = validateStripeBackConfig(billingConfig);
78
+ // Validate data fields only. Valibot strips unknown keys (the hooks) from its
79
+ // output, so routing must use the original config object, never the parse result.
80
+ validateStripeBackConfig(billingConfig);
81
+ const config = billingConfig;
89
82
 
90
83
  // Verify webhook signature
91
- const event = stripe.webhooks.constructEvent(
84
+ // Async variant: works on Node and on Web Crypto runtimes (Deno, Workers)
85
+ const event = await stripe.webhooks.constructEventAsync(
92
86
  rawBody,
93
87
  signature,
94
88
  webhookSecret
95
89
  );
96
90
 
97
- // Log event processing (non-critical, so we don't throw)
98
91
  logger.info('[Webhook] Processing event', {
99
92
  eventType: event.type,
100
93
  eventId: event.id,
101
94
  operation: 'webhook_processing',
102
95
  });
103
96
 
104
- // ✅ CHECK+RESERVE: Atomic idempotency (eliminates TOCTOU race between check and mark)
105
- if (await getIdempotencyStore().checkAndReserve(event.id)) {
97
+ const reservation = await idempotencyStore.reserve(event.id);
98
+ if (reservation.state === 'processed') {
106
99
  logger.info('[Webhook] Already processed', { eventId: event.id });
107
100
  return { success: true, message: 'Event already processed' };
108
101
  }
102
+ if (reservation.state === 'in_progress') {
103
+ logger.warn('[Webhook] Event in progress in another delivery', {
104
+ eventId: event.id,
105
+ eventType: event.type,
106
+ operation: 'webhook_in_progress',
107
+ });
108
+ throw new DoNotDevError(
109
+ `Stripe event ${event.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,
110
+ 'unavailable',
111
+ { details: { eventId: event.id, reason: 'webhook_event_in_progress' } }
112
+ );
113
+ }
114
+ const { ownerToken } = reservation;
109
115
 
110
116
  // G59: Warn when authProvider is null — subscription update events will fail
111
117
  if (!authProvider) {
@@ -118,15 +124,103 @@ export async function processWebhook(
118
124
  );
119
125
  }
120
126
 
121
- // Route to handler
122
- await routeEvent(event, config, updateSubscription, stripe, authProvider);
127
+ // Route to handler. On failure, release the reservation so the retry runs.
128
+ try {
129
+ await routeEvent(event, config, updateSubscription, stripe, authProvider);
130
+ } catch (routingError) {
131
+ logger.error('[Webhook] Event processing failed, releasing reservation', {
132
+ error:
133
+ routingError instanceof Error
134
+ ? routingError
135
+ : new Error(String(routingError)),
136
+ eventId: event.id,
137
+ eventType: event.type,
138
+ operation: 'webhook_routing',
139
+ });
140
+ await releaseReservation(idempotencyStore, event.id, ownerToken);
141
+ throw routingError;
142
+ }
123
143
 
144
+ await markProcessedWithRetry(idempotencyStore, event.id, ownerToken);
124
145
  return { success: true, message: 'Webhook processed' };
125
146
  } catch (error) {
126
147
  throw handleError(error);
127
148
  }
128
149
  }
129
150
 
151
+ /** Release after a routing failure. Never masks the routing error. */
152
+ async function releaseReservation(
153
+ store: IdempotencyStore,
154
+ eventId: string,
155
+ ownerToken: string
156
+ ): Promise<void> {
157
+ try {
158
+ if (!(await store.release(eventId, ownerToken))) {
159
+ logger.warn('[Webhook] Reservation not released: no longer owned', {
160
+ eventId,
161
+ operation: 'idempotency_release_stale',
162
+ });
163
+ }
164
+ } catch (releaseError) {
165
+ logger.error('[Webhook] Failed to release idempotency reservation', {
166
+ error:
167
+ releaseError instanceof Error
168
+ ? releaseError
169
+ : new Error(String(releaseError)),
170
+ eventId,
171
+ operation: 'idempotency_release',
172
+ });
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Record a processed event. Transient store errors are retried; a lost
178
+ * reservation is not (another delivery owns the event). The final error is
179
+ * rethrown without releasing: Stripe retries after the lease and the event is
180
+ * processed again (at-least-once).
181
+ */
182
+ async function markProcessedWithRetry(
183
+ store: IdempotencyStore,
184
+ eventId: string,
185
+ ownerToken: string
186
+ ): Promise<void> {
187
+ for (let attempt = 1; ; attempt++) {
188
+ try {
189
+ await store.markProcessed(eventId, ownerToken);
190
+ return;
191
+ } catch (error) {
192
+ const err = error instanceof Error ? error : new Error(String(error));
193
+ if (error instanceof ReservationLostError) {
194
+ logger.error(
195
+ '[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice',
196
+ { error: err, eventId, operation: 'idempotency_mark_processed_lost' }
197
+ );
198
+ throw error;
199
+ }
200
+ if (attempt >= MARK_PROCESSED_ATTEMPTS) {
201
+ logger.error(
202
+ '[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run',
203
+ {
204
+ error: err,
205
+ eventId,
206
+ attempts: attempt,
207
+ operation: 'idempotency_mark_processed_failed',
208
+ }
209
+ );
210
+ throw error;
211
+ }
212
+ logger.warn('[Webhook] markProcessed failed, retrying', {
213
+ eventId,
214
+ attempt,
215
+ error: err.message,
216
+ });
217
+ await new Promise((resolve) =>
218
+ setTimeout(resolve, MARK_PROCESSED_BACKOFF_MS * attempt)
219
+ );
220
+ }
221
+ }
222
+ }
223
+
130
224
  /**
131
225
  * Route events to appropriate handlers
132
226
  *
@@ -139,14 +233,21 @@ async function routeEvent(
139
233
  config: StripeBackConfig,
140
234
  updateSubscription: UpdateSubscriptionFn,
141
235
  stripe: Stripe,
142
- authProvider: WebhookAuthProvider | null
236
+ authProvider: BillingAuthProvider | null
143
237
  ): Promise<void> {
144
238
  switch (event.type) {
145
239
  case 'checkout.session.completed':
146
- await handleCheckoutCompleted(
147
- event.data.object as Stripe.Checkout.Session,
240
+ case 'checkout.session.async_payment_succeeded':
241
+ case 'checkout.session.async_payment_failed':
242
+ case 'checkout.session.expired':
243
+ await handleCheckoutSessionEvent(
244
+ event.type,
245
+ event.id,
246
+ event.api_version,
247
+ event.data.object,
148
248
  config,
149
249
  updateSubscription,
250
+ stripe,
150
251
  authProvider
151
252
  );
152
253
  break;
@@ -181,342 +282,44 @@ async function routeEvent(
181
282
  }
182
283
 
183
284
  /**
184
- * Handle checkout completed with graceful hook execution
285
+ * Route Checkout Session events: StripeOrder items go to the order hooks,
286
+ * StripePayment / StripeSubscription items to the tier handlers.
185
287
  *
186
- * @version 0.1.0
187
- * @since 0.0.1
288
+ * @version 0.2.0
289
+ * @since 0.2.0
188
290
  * @author AMBROISE PARK Consulting
189
291
  */
190
- async function handleCheckoutCompleted(
292
+ async function handleCheckoutSessionEvent(
293
+ eventType: OrderSessionEventType,
294
+ eventId: string,
295
+ apiVersion: string | null,
191
296
  session: Stripe.Checkout.Session,
192
297
  config: StripeBackConfig,
193
298
  updateSubscription: UpdateSubscriptionFn,
194
- authProvider: WebhookAuthProvider | null
195
- ): Promise<void> {
196
- const { userId, billingConfigKey } = session.metadata || {};
197
-
198
- if (!userId || !billingConfigKey) {
199
- throw handleError(
200
- new Error(
201
- `Missing required metadata: userId=${userId}, billingConfigKey=${billingConfigKey}`
202
- )
203
- );
204
- }
205
-
206
- const billingItem = config[billingConfigKey];
207
- if (!billingItem) {
208
- throw handleError(
209
- new Error(`Unknown billing config key: ${billingConfigKey}`)
210
- );
211
- }
212
-
213
- logger.info('[Webhook] Processing purchase', {
214
- userId,
215
- configKey: billingConfigKey,
216
- type: billingItem.type,
217
- operation: 'purchase_processing',
218
- });
219
-
220
- // Update subscription
221
- if (billingItem.type === 'StripePayment') {
222
- if (!authProvider) {
223
- throw handleError(
224
- new Error('Auth provider required for subscription updates')
225
- );
226
- }
227
- await updateSubscription(
228
- userId,
229
- {
230
- tier: billingItem.tier,
231
- status: SUBSCRIPTION_STATUS.ACTIVE,
232
- subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
233
- customerId: session.customer as string,
234
- },
235
- authProvider
236
- );
237
-
238
- // Execute hook with graceful error handling
239
- if (billingItem.onPurchaseSuccess) {
240
- try {
241
- await billingItem.onPurchaseSuccess(userId, session.metadata || {});
242
- } catch (error) {
243
- // Hook failures are non-critical - payment already processed
244
- // Log for manual intervention but don't fail the webhook
245
- logger.error('[Webhook] Hook failed (non-critical)', {
246
- error: error instanceof Error ? error : new Error(String(error)),
247
- hookName: 'onPurchaseSuccess',
248
- userId,
249
- operation: 'hook_execution',
250
- });
251
- }
252
- }
253
- }
254
-
255
- if (billingItem.type === 'StripeSubscription') {
256
- if (!authProvider) {
257
- throw handleError(
258
- new Error('Auth provider required for subscription updates')
259
- );
260
- }
261
- await updateSubscription(
262
- userId,
263
- {
264
- tier: billingItem.tier,
265
- status: SUBSCRIPTION_STATUS.ACTIVE,
266
- subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
267
- subscriptionId: session.subscription as string,
268
- customerId: session.customer as string,
269
- },
270
- authProvider
271
- );
272
-
273
- // Execute hook with graceful error handling
274
- if (billingItem.onSubscriptionCreated) {
275
- try {
276
- await billingItem.onSubscriptionCreated(userId, session.metadata || {});
277
- } catch (error) {
278
- // Hook failures are non-critical - subscription already created
279
- // Log for manual intervention but don't fail the webhook
280
- logger.error('[Webhook] Hook failed (non-critical)', {
281
- error: error instanceof Error ? error : new Error(String(error)),
282
- hookName: 'onSubscriptionCreated',
283
- userId,
284
- operation: 'hook_execution',
285
- });
286
- }
287
- }
288
- }
289
-
290
- logger.info('[Webhook] Purchase processed', {
291
- userId,
292
- configKey: billingConfigKey,
293
- operation: 'purchase_processed',
294
- });
295
- }
296
-
297
- /**
298
- * Handle subscription renewal
299
- *
300
- * @version 0.1.0
301
- * @since 0.0.1
302
- * @author AMBROISE PARK Consulting
303
- */
304
- async function handleInvoicePaymentSucceeded(
305
- invoice: Stripe.Invoice,
306
- config: StripeBackConfig,
307
- updateSubscription: UpdateSubscriptionFn,
308
299
  stripe: Stripe,
309
- authProvider: WebhookAuthProvider | null
300
+ authProvider: BillingAuthProvider | null
310
301
  ): Promise<void> {
311
- const subscriptionId = (invoice as any).subscription as string;
312
- if (!subscriptionId) return;
313
-
314
- // ✅ FIX: Fetch subscription to get metadata
315
- const subscription = await stripe.subscriptions.retrieve(subscriptionId);
316
- const { userId, billingConfigKey } = subscription.metadata || {};
317
- if (!userId || !billingConfigKey) {
318
- // G60: Log when subscription metadata is missing — silent return loses the event
319
- logger.error(
320
- '[Webhook] Subscription metadata missing userId or billingConfigKey',
321
- {
322
- subscriptionId,
323
- hasUserId: !!userId,
324
- hasBillingConfigKey: !!billingConfigKey,
325
- operation: 'invoice_payment_succeeded_metadata_missing',
326
- }
302
+ const billingConfigKey = session.metadata?.billingConfigKey;
303
+ const billingItem = billingConfigKey ? config[billingConfigKey] : undefined;
304
+
305
+ if (billingConfigKey && billingItem?.type === 'StripeOrder') {
306
+ await handleOrderSessionEvent(
307
+ eventType,
308
+ eventId,
309
+ apiVersion,
310
+ session,
311
+ billingConfigKey,
312
+ billingItem,
313
+ stripe
327
314
  );
328
315
  return;
329
316
  }
330
317
 
331
- const billingItem = config[billingConfigKey];
332
- if (!billingItem || billingItem.type !== 'StripeSubscription') return;
333
-
334
- // Renew subscription
335
- if (!authProvider) {
336
- throw handleError(
337
- new Error('Auth provider required for subscription updates')
338
- );
339
- }
340
- await updateSubscription(
341
- userId,
342
- {
343
- tier: billingItem.tier,
344
- status: SUBSCRIPTION_STATUS.ACTIVE,
345
- subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
346
- subscriptionId: subscriptionId,
347
- customerId: invoice.customer as string,
348
- },
318
+ await handleTierCheckoutEvent(
319
+ eventType,
320
+ session,
321
+ config,
322
+ updateSubscription,
349
323
  authProvider
350
324
  );
351
-
352
- // Execute hook with graceful error handling
353
- if (billingItem.onSubscriptionRenewed) {
354
- try {
355
- await billingItem.onSubscriptionRenewed(
356
- userId,
357
- subscription.metadata || {}
358
- );
359
- } catch (error) {
360
- // Hook failures are non-critical - subscription already renewed
361
- // Log for manual intervention but don't fail the webhook
362
- logger.error('[Webhook] Hook failed (non-critical)', {
363
- error: error instanceof Error ? error : new Error(String(error)),
364
- hookName: 'onSubscriptionRenewed',
365
- userId,
366
- operation: 'hook_execution',
367
- });
368
- }
369
- }
370
-
371
- logger.info('[Webhook] Subscription renewed', {
372
- userId,
373
- billingConfigKey,
374
- operation: 'subscription_renewed',
375
- });
376
- }
377
-
378
- /**
379
- * Handle subscription cancellation
380
- *
381
- * @version 0.1.0
382
- * @since 0.0.1
383
- * @author AMBROISE PARK Consulting
384
- */
385
- async function handleSubscriptionDeleted(
386
- subscription: Stripe.Subscription,
387
- config: StripeBackConfig,
388
- updateSubscription: UpdateSubscriptionFn,
389
- authProvider: WebhookAuthProvider | null
390
- ): Promise<void> {
391
- const { userId, billingConfigKey } = subscription.metadata || {};
392
- if (!userId || !billingConfigKey) return;
393
-
394
- const billingItem = config[billingConfigKey];
395
- if (!billingItem || billingItem.type !== 'StripeSubscription') return;
396
-
397
- // Update to cancelled
398
- if (!authProvider) {
399
- throw handleError(
400
- new Error('Auth provider required for subscription updates')
401
- );
402
- }
403
- await updateSubscription(
404
- userId,
405
- {
406
- tier: SUBSCRIPTION_TIERS.FREE,
407
- status: SUBSCRIPTION_STATUS.CANCELED,
408
- subscriptionEnd: new Date(
409
- (subscription as any).current_period_end * 1000
410
- ).toISOString(),
411
- subscriptionId: subscription.id,
412
- customerId: subscription.customer as string,
413
- },
414
- authProvider
415
- );
416
-
417
- // Execute hook with graceful error handling
418
- if (billingItem.onSubscriptionCancelled) {
419
- try {
420
- await billingItem.onSubscriptionCancelled(
421
- userId,
422
- subscription.metadata || {}
423
- );
424
- } catch (error) {
425
- // Hook failures are non-critical - subscription already cancelled
426
- // Log for manual intervention but don't fail the webhook
427
- logger.error('[Webhook] Hook failed (non-critical)', {
428
- error: error instanceof Error ? error : new Error(String(error)),
429
- hookName: 'onSubscriptionCancelled',
430
- userId,
431
- operation: 'hook_execution',
432
- });
433
- }
434
- }
435
-
436
- logger.info('[Webhook] Subscription cancelled', {
437
- userId,
438
- billingConfigKey,
439
- operation: 'subscription_cancelled',
440
- });
441
325
  }
442
-
443
- /**
444
- * Handle payment failure
445
- *
446
- * @version 0.1.0
447
- * @since 0.0.1
448
- * @author AMBROISE PARK Consulting
449
- */
450
- async function handlePaymentFailed(
451
- invoice: Stripe.Invoice,
452
- config: StripeBackConfig
453
- ): Promise<void> {
454
- const { userId, billingConfigKey } = invoice.metadata || {};
455
- if (!userId || !billingConfigKey) {
456
- logger.warn('[Webhook] Payment failed - missing metadata', {
457
- invoiceId: invoice.id,
458
- hasUserId: !!userId,
459
- hasBillingConfigKey: !!billingConfigKey,
460
- operation: 'payment_failed_metadata_missing',
461
- });
462
- return;
463
- }
464
-
465
- const billingItem = config[billingConfigKey];
466
- if (!billingItem) {
467
- logger.error('[Webhook] Payment failed - unknown billing config', {
468
- error: new Error(`Unknown billing config key: ${billingConfigKey}`),
469
- userId,
470
- billingConfigKey,
471
- operation: 'payment_failed_unknown_config',
472
- });
473
- return;
474
- }
475
-
476
- // Execute hooks with graceful error handling
477
- if (billingItem.type === 'StripePayment' && billingItem.onPurchaseFailure) {
478
- try {
479
- // Pass the actual metadata - we've already validated it exists
480
- await billingItem.onPurchaseFailure(userId, invoice.metadata || {});
481
- } catch (error) {
482
- // Hook failures are non-critical - payment already failed
483
- // Log for manual intervention but don't fail the webhook
484
- logger.error('[Webhook] Hook failed (non-critical)', {
485
- error: error instanceof Error ? error : new Error(String(error)),
486
- hookName: 'onPurchaseFailure',
487
- userId,
488
- operation: 'hook_execution',
489
- });
490
- }
491
- }
492
-
493
- if (
494
- billingItem.type === 'StripeSubscription' &&
495
- billingItem.onPaymentFailed
496
- ) {
497
- try {
498
- await billingItem.onPaymentFailed(userId, invoice.metadata || {});
499
- } catch (error) {
500
- // Hook failures are non-critical - payment already failed
501
- // Log for manual intervention but don't fail the webhook
502
- logger.error('[Webhook] Hook failed (non-critical)', {
503
- error: error instanceof Error ? error : new Error(String(error)),
504
- hookName: 'onPaymentFailed',
505
- userId,
506
- operation: 'hook_execution',
507
- });
508
- }
509
- }
510
-
511
- logger.warn('[Webhook] Payment failed', {
512
- userId,
513
- billingConfigKey,
514
- operation: 'payment_failed',
515
- });
516
- }
517
-
518
- /**
519
- * Calculate subscription end date with proper edge case handling
520
- * Fixes issues like Jan 31 + 1 month = March 3 (should be Feb 28/29)
521
- */
522
- // Removed - now using calculateSubscriptionEndDate from @donotdev/core/server
File without changes
@@ -10,12 +10,11 @@
10
10
  */
11
11
 
12
12
  import { onCall } from 'firebase-functions/v2/https';
13
-
14
- import { withSchemaValidation } from './schemaValidation.js';
15
-
16
13
  import type { CallableRequest } from 'firebase-functions/v2/https';
17
14
  import type * as v from 'valibot';
18
15
 
16
+ import { withSchemaValidation } from './schemaValidation.js';
17
+
19
18
  /**
20
19
  * Creates a Firebase onCall function with schema validation
21
20
  *
@@ -9,10 +9,9 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import * as v from 'valibot';
13
-
14
12
  import type { CallableRequest } from 'firebase-functions/v2/https';
15
13
  import type { NextApiRequest, NextApiResponse } from 'next';
14
+ import * as v from 'valibot';
16
15
 
17
16
  /**
18
17
  * Simple wrapper that validates data against schema and calls the handler