@donotdev/functions 0.1.42 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/README.md +25 -14
  2. package/lib/chunks/chunk-2JL3GDTO.js +151 -0
  3. package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
  4. package/lib/chunks/chunk-4TVLH2W2.js +22 -0
  5. package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
  6. package/lib/chunks/chunk-4U7QQWYG.js +22 -0
  7. package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
  8. package/lib/chunks/chunk-5DTPEM64.js +22 -0
  9. package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
  10. package/lib/chunks/chunk-6CQXHNVL.js +22 -0
  11. package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
  12. package/lib/chunks/chunk-6DSCPZC6.js +22 -0
  13. package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
  14. package/lib/chunks/chunk-7E6TGWHU.js +22 -0
  15. package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
  16. package/lib/chunks/chunk-7LT32OWE.js +22 -0
  17. package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
  18. package/lib/chunks/chunk-7VH2GJXT.js +151 -0
  19. package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
  20. package/lib/chunks/chunk-API5A4BV.js +22 -0
  21. package/lib/chunks/chunk-API5A4BV.js.map +7 -0
  22. package/lib/chunks/chunk-AYY7UXNI.js +22 -0
  23. package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
  24. package/lib/chunks/chunk-BUP7SXPV.js +23 -0
  25. package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
  26. package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
  27. package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
  28. package/lib/chunks/chunk-FSLGZD7A.js +21 -0
  29. package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
  30. package/lib/chunks/chunk-GVLSPWDD.js +151 -0
  31. package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
  32. package/lib/chunks/chunk-GXQVWEFT.js +22 -0
  33. package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
  34. package/lib/chunks/chunk-HB7EGXVI.js +22 -0
  35. package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
  36. package/lib/chunks/chunk-HLNYUAZH.js +22 -0
  37. package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
  38. package/lib/chunks/chunk-HM7XCMWW.js +22 -0
  39. package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
  40. package/lib/chunks/chunk-I7IOIL6U.js +151 -0
  41. package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
  42. package/lib/chunks/chunk-IFOYVSPU.js +22 -0
  43. package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
  44. package/lib/chunks/chunk-JTAGPPPL.js +22 -0
  45. package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
  46. package/lib/chunks/chunk-MZ232FUE.js +22 -0
  47. package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
  48. package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
  49. package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
  50. package/lib/chunks/chunk-NP2AN2TV.js +22 -0
  51. package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
  52. package/lib/chunks/chunk-QJAU2MWV.js +22 -0
  53. package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
  54. package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
  55. package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
  56. package/lib/chunks/chunk-RQZGIZHD.js +151 -0
  57. package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
  58. package/lib/chunks/chunk-TBEDQLOB.js +23 -0
  59. package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
  60. package/lib/chunks/chunk-TMHBP3HB.js +22 -0
  61. package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
  62. package/lib/chunks/chunk-UH4L3EF3.js +151 -0
  63. package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
  64. package/lib/chunks/chunk-UJBIU6TL.js +22 -0
  65. package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
  66. package/lib/chunks/chunk-VKEYW3NT.js +22 -0
  67. package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
  68. package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
  69. package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
  70. package/lib/chunks/chunk-Y44NEQQG.js +22 -0
  71. package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
  72. package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
  73. package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
  74. package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
  75. package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
  76. package/lib/chunks/monitoring-PVQMFL34.js +22 -0
  77. package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
  78. package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
  79. package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
  80. package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
  81. package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
  82. package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
  83. package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
  84. package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
  85. package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
  86. package/lib/chunks/server-32A5RH4C.js +22 -0
  87. package/lib/chunks/server-32A5RH4C.js.map +7 -0
  88. package/lib/chunks/server-7HDAP5DL.js +22 -0
  89. package/lib/chunks/server-7HDAP5DL.js.map +7 -0
  90. package/lib/chunks/server-S2IMFOY7.js +22 -0
  91. package/lib/chunks/server-S2IMFOY7.js.map +7 -0
  92. package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
  93. package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
  94. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  95. package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
  96. package/lib/firebase/baseFunction.d.ts +1 -1
  97. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
  98. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  99. package/lib/firebase/billing/index.d.ts +2 -1
  100. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
  101. package/lib/firebase/billing/webhookHandler.d.ts +17 -2
  102. package/lib/firebase/crud/aggregate.d.ts +0 -9
  103. package/lib/firebase/crud/bulk.d.ts +2 -2
  104. package/lib/firebase/crud/create.d.ts +1 -1
  105. package/lib/firebase/crud/delete.d.ts +1 -1
  106. package/lib/firebase/crud/get.d.ts +1 -1
  107. package/lib/firebase/crud/list.d.ts +1 -1
  108. package/lib/firebase/crud/update.d.ts +1 -9
  109. package/lib/firebase/index.js +1 -5
  110. package/lib/firebase/index.js.map +4 -4
  111. package/lib/firebase/oauth/githubAccess.d.ts +2 -2
  112. package/lib/firebase/registerCrudFunctions.d.ts +9 -1
  113. package/lib/shared/billing/apiVersion.d.ts +22 -0
  114. package/lib/shared/billing/checkoutPrice.d.ts +27 -0
  115. package/lib/shared/billing/checkoutValidation.d.ts +89 -0
  116. package/lib/shared/billing/createCheckout.d.ts +73 -24
  117. package/lib/shared/billing/helpers/index.d.ts +0 -1
  118. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
  119. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
  120. package/lib/shared/billing/idempotency.d.ts +32 -10
  121. package/lib/shared/billing/idempotencyContract.d.ts +121 -0
  122. package/lib/shared/billing/index.d.ts +2 -0
  123. package/lib/shared/billing/orderWebhook.d.ts +75 -0
  124. package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
  125. package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
  126. package/lib/shared/billing/webhookHandler.d.ts +28 -20
  127. package/lib/shared/index.js +1 -6
  128. package/lib/shared/index.js.map +4 -4
  129. package/lib/shared/utils/functionWrapper.d.ts +1 -1
  130. package/lib/shared/utils/internal/auth.d.ts +38 -1
  131. package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
  132. package/lib/shared/utils/schemaValidation.d.ts +1 -1
  133. package/lib/shared/utils/vercelHelpers.d.ts +8 -0
  134. package/lib/shared/utils.d.ts +4 -17
  135. package/lib/supabase/baseFunction.d.ts +1 -1
  136. package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
  137. package/lib/supabase/crud/bulk.d.ts +1 -1
  138. package/lib/supabase/crud/entityStore.d.ts +71 -0
  139. package/lib/supabase/crud/index.d.ts +2 -0
  140. package/lib/supabase/helpers/authProvider.d.ts +5 -5
  141. package/lib/supabase/index.d.ts +10 -2
  142. package/lib/supabase/index.js +1 -3
  143. package/lib/supabase/index.js.map +4 -4
  144. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  145. package/lib/vercel/api/ai/chat.d.ts +0 -9
  146. package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
  147. package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
  148. package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
  149. package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
  150. package/lib/vercel/api/billing/backend.d.ts +39 -0
  151. package/lib/vercel/api/billing/cancel.d.ts +8 -0
  152. package/lib/vercel/api/billing/change-plan.d.ts +9 -1
  153. package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
  154. package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
  155. package/lib/vercel/api/billing/index.d.ts +4 -2
  156. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
  157. package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
  158. package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
  159. package/lib/vercel/api/crud/bulk.d.ts +17 -0
  160. package/lib/vercel/api/crud/create.d.ts +8 -0
  161. package/lib/vercel/api/crud/delete.d.ts +8 -0
  162. package/lib/vercel/api/crud/get.d.ts +8 -0
  163. package/lib/vercel/api/crud/list.d.ts +8 -0
  164. package/lib/vercel/api/crud/update.d.ts +8 -0
  165. package/lib/vercel/api/index.js +1 -3
  166. package/lib/vercel/api/index.js.map +4 -4
  167. package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
  168. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  169. package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
  170. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  171. package/lib/vercel/baseFunction.d.ts +4 -1
  172. package/lib/vercel/supabaseAdmin.d.ts +22 -0
  173. package/package.json +25 -26
  174. package/src/firebase/auth/getCustomClaims.ts +4 -5
  175. package/src/firebase/auth/getUserAuthStatus.ts +4 -5
  176. package/src/firebase/auth/removeCustomClaims.ts +4 -5
  177. package/src/firebase/auth/setCustomClaims.ts +4 -5
  178. package/src/firebase/baseFunction.ts +4 -5
  179. package/src/firebase/billing/cancelSubscription.ts +1 -2
  180. package/src/firebase/billing/changePlan.ts +2 -3
  181. package/src/firebase/billing/createCheckoutSession.ts +30 -56
  182. package/src/firebase/billing/createCustomerPortal.ts +4 -5
  183. package/src/firebase/billing/healthCheck.ts +0 -0
  184. package/src/firebase/billing/index.ts +8 -1
  185. package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
  186. package/src/firebase/billing/webhookHandler.ts +20 -4
  187. package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
  188. package/src/firebase/crud/aggregate.ts +1 -2
  189. package/src/firebase/crud/bulk.ts +5 -6
  190. package/src/firebase/crud/create.ts +5 -6
  191. package/src/firebase/crud/delete.ts +4 -5
  192. package/src/firebase/crud/get.ts +4 -5
  193. package/src/firebase/crud/list.ts +4 -5
  194. package/src/firebase/crud/update.ts +5 -6
  195. package/src/firebase/oauth/githubAccess.ts +2 -3
  196. package/src/firebase/registerCrudFunctions.ts +2 -2
  197. package/src/shared/__tests__/auth.test.ts +0 -3
  198. package/src/shared/__tests__/bulkCore.test.ts +3 -2
  199. package/src/shared/__tests__/errorHandling.test.ts +2 -2
  200. package/src/shared/__tests__/idempotency.test.ts +282 -55
  201. package/src/shared/__tests__/internalValidation.test.ts +3 -3
  202. package/src/shared/__tests__/rateLimiter.test.ts +2 -8
  203. package/src/shared/__tests__/schemaValidation.test.ts +1 -1
  204. package/src/shared/__tests__/utils.test.ts +2 -1
  205. package/src/shared/__tests__/validation-env.test.ts +0 -0
  206. package/src/shared/ai/createAIRoute.ts +53 -30
  207. package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
  208. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
  209. package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
  210. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
  211. package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
  212. package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
  213. package/src/shared/billing/apiVersion.ts +25 -0
  214. package/src/shared/billing/checkoutPrice.ts +125 -0
  215. package/src/shared/billing/checkoutValidation.ts +284 -0
  216. package/src/shared/billing/createCheckout.ts +332 -196
  217. package/src/shared/billing/helpers/index.ts +0 -1
  218. package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
  219. package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
  220. package/src/shared/billing/idempotency.ts +253 -150
  221. package/src/shared/billing/idempotencyContract.ts +135 -0
  222. package/src/shared/billing/index.ts +2 -0
  223. package/src/shared/billing/orderWebhook.ts +269 -0
  224. package/src/shared/billing/supabaseIdempotency.ts +228 -0
  225. package/src/shared/billing/tierWebhookEvents.ts +432 -0
  226. package/src/shared/billing/webhookHandler.ts +188 -385
  227. package/src/shared/utils/external/subscription.ts +0 -0
  228. package/src/shared/utils/firebaseHelpers.ts +2 -3
  229. package/src/shared/utils/functionWrapper.ts +1 -2
  230. package/src/shared/utils/internal/auth.ts +55 -7
  231. package/src/shared/utils/internal/monitoring.ts +17 -9
  232. package/src/shared/utils/internal/rateLimiter.ts +14 -5
  233. package/src/shared/utils/schemaValidation.ts +1 -2
  234. package/src/shared/utils/vercelHelpers.ts +3 -3
  235. package/src/shared/utils.ts +14 -31
  236. package/src/shared/validation.ts +1 -1
  237. package/src/supabase/__tests__/bulk.test.ts +3 -1
  238. package/src/supabase/__tests__/entityStore.test.ts +90 -0
  239. package/src/supabase/baseFunction.ts +1 -2
  240. package/src/supabase/billing/createCheckoutSession.ts +10 -36
  241. package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
  242. package/src/supabase/billing/stripeWebhook.ts +79 -0
  243. package/src/supabase/crud/aggregate.ts +1 -1
  244. package/src/supabase/crud/bulk.ts +3 -7
  245. package/src/supabase/crud/create.ts +1 -1
  246. package/src/supabase/crud/entityStore.ts +240 -0
  247. package/src/supabase/crud/index.ts +8 -0
  248. package/src/supabase/crud/update.ts +1 -1
  249. package/src/supabase/helpers/authProvider.ts +6 -5
  250. package/src/supabase/index.ts +26 -0
  251. package/src/supabase/utils/rateLimiter.ts +2 -2
  252. package/src/vercel/__tests__/bulk.test.ts +24 -21
  253. package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
  254. package/src/vercel/api/ai/chat.ts +2 -1
  255. package/src/vercel/api/auth/get-custom-claims.ts +2 -3
  256. package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
  257. package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
  258. package/src/vercel/api/auth/set-custom-claims.ts +3 -3
  259. package/src/vercel/api/billing/backend.ts +72 -0
  260. package/src/vercel/api/billing/cancel.ts +2 -4
  261. package/src/vercel/api/billing/change-plan.ts +3 -4
  262. package/src/vercel/api/billing/create-checkout-session.ts +42 -68
  263. package/src/vercel/api/billing/customer-portal.ts +2 -4
  264. package/src/vercel/api/billing/index.ts +4 -2
  265. package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
  266. package/src/vercel/api/billing/webhook-handler.ts +31 -25
  267. package/src/vercel/api/config/firebase-admin.ts +2 -2
  268. package/src/vercel/api/crud/bulk.ts +6 -9
  269. package/src/vercel/api/crud/create.ts +6 -5
  270. package/src/vercel/api/crud/delete.ts +4 -3
  271. package/src/vercel/api/crud/get.ts +6 -5
  272. package/src/vercel/api/crud/list.ts +6 -5
  273. package/src/vercel/api/crud/update.ts +6 -5
  274. package/src/vercel/api/oauth/check-github-access.ts +5 -5
  275. package/src/vercel/api/oauth/exchange-token.ts +3 -3
  276. package/src/vercel/api/oauth/grant-github-access.ts +5 -5
  277. package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
  278. package/src/vercel/baseFunction.ts +23 -8
  279. package/src/vercel/supabaseAdmin.ts +45 -0
@@ -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,304 @@
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) or Postgres (Supabase, see `supabaseIdempotency.ts`). There is no
8
+ * implicit fallback.
6
9
  *
7
- * @version 0.1.0
10
+ * Lifecycle per event: `reserve` → process → `markProcessed(ownerToken)`, or
11
+ * `release(ownerToken)` when processing failed (so the provider's retry is
12
+ * processed). Only the owner of a reservation may change it. A reservation
13
+ * whose worker died is retaken after {@link RESERVATION_LEASE_MS}.
14
+ *
15
+ * @version 0.2.0
8
16
  * @since 0.0.1
9
17
  * @author AMBROISE PARK Consulting
10
18
  */
11
19
 
20
+ import * as v from 'valibot';
21
+
12
22
  import { handleError } from '../errorHandling.js';
13
23
  import { isFirestoreConfigured } from '../utils/detectFirestore.js';
24
+ import {
25
+ RESERVATION_LEASE_MS,
26
+ ReservationLostError,
27
+ WEBHOOK_EVENT_RETENTION_MS,
28
+ newOwnerToken,
29
+ } from './idempotencyContract.js';
30
+ import type {
31
+ LegacyIdempotencyStore,
32
+ ReservationResult,
33
+ } from './idempotencyContract.js';
34
+
35
+ export {
36
+ RESERVATION_LEASE_MS,
37
+ ReservationLostError,
38
+ WEBHOOK_EVENT_RETENTION_MS,
39
+ } from './idempotencyContract.js';
40
+ export type {
41
+ IdempotencyStore,
42
+ LegacyIdempotencyStore,
43
+ ReservationResult,
44
+ } from './idempotencyContract.js';
45
+
46
+ /** Firestore collection holding webhook event reservations (name kept from 0.1.x). */
47
+ const FIRESTORE_COLLECTION = 'webhook_idempotency';
48
+
49
+ // =============================================================================
50
+ // In-memory (tests only)
51
+ // =============================================================================
14
52
 
15
53
  /**
16
- * Idempotency store interface
54
+ * In-memory store. Single process only: for tests, never for a deployed webhook.
17
55
  *
18
- * @version 0.1.0
19
- * @since 0.0.1
56
+ * @version 0.2.0
57
+ * @since 0.2.0
20
58
  * @author AMBROISE PARK Consulting
21
59
  */
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>;
60
+ export function createInMemoryIdempotencyStore(): LegacyIdempotencyStore {
61
+ const events = new Map<
62
+ string,
63
+ { status: 'processing' | 'processed'; ownerToken: string; at: number }
64
+ >();
65
+ const reserve = async (eventId: string): Promise<ReservationResult> => {
66
+ const entry = events.get(eventId);
67
+ const now = Date.now();
68
+ if (entry?.status === 'processed') return { state: 'processed' };
69
+ if (entry && now - entry.at < RESERVATION_LEASE_MS) {
70
+ return { state: 'in_progress' };
71
+ }
72
+ const ownerToken = newOwnerToken();
73
+ events.set(eventId, { status: 'processing', ownerToken, at: now });
74
+ return { state: 'reserved', ownerToken };
75
+ };
76
+ return {
77
+ reserve,
78
+ async checkAndReserve(eventId) {
79
+ return (await reserve(eventId)).state !== 'reserved';
80
+ },
81
+ async markProcessed(eventId, ownerToken) {
82
+ const entry = events.get(eventId);
83
+ if (ownerToken !== undefined && entry?.ownerToken !== ownerToken) {
84
+ throw new ReservationLostError(eventId);
85
+ }
86
+ events.set(eventId, {
87
+ status: 'processed',
88
+ ownerToken: ownerToken ?? entry?.ownerToken ?? newOwnerToken(),
89
+ at: Date.now(),
90
+ });
91
+ },
92
+ async release(eventId, ownerToken) {
93
+ const entry = events.get(eventId);
94
+ if (entry?.status !== 'processing' || entry.ownerToken !== ownerToken) {
95
+ return false;
96
+ }
97
+ events.delete(eventId);
98
+ return true;
99
+ },
100
+ async isProcessed(eventId) {
101
+ return events.get(eventId)?.status === 'processed';
102
+ },
103
+ };
27
104
  }
28
105
 
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;
46
- }
47
- return this.store.has(eventId);
48
- }
106
+ // =============================================================================
107
+ // Firestore
108
+ // =============================================================================
49
109
 
50
- async markProcessed(eventId: string): Promise<void> {
51
- this.store.add(eventId);
110
+ /** Millisecond reading of an `expiresAt` value: Timestamp (0.2.x) or number (0.1.x). */
111
+ const ExpiresAtSchema = v.union([
112
+ v.number(),
113
+ v.pipe(
114
+ v.custom<{ toMillis(): number }>(
115
+ (value) =>
116
+ typeof value === 'object' &&
117
+ value !== null &&
118
+ typeof (value as { toMillis?: unknown }).toMillis === 'function',
119
+ 'expiresAt must be a Firestore Timestamp or a number'
120
+ ),
121
+ v.transform((timestamp) => timestamp.toMillis())
122
+ ),
123
+ ]);
52
124
 
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
- }
125
+ /**
126
+ * Stored reservation document. 0.1.x documents carry no `status` and mean processed.
127
+ */
128
+ const FirestoreEventDocSchema = v.object({
129
+ status: v.optional(v.picklist(['processing', 'processed'])),
130
+ ownerToken: v.optional(v.string()),
131
+ reservedAt: v.optional(v.number()),
132
+ expiresAt: v.optional(ExpiresAtSchema),
133
+ });
59
134
 
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;
135
+ function parseEventDoc(eventId: string, data: unknown) {
136
+ const result = v.safeParse(FirestoreEventDocSchema, data);
137
+ if (!result.success) {
138
+ throw new Error(
139
+ `Malformed ${FIRESTORE_COLLECTION}/${eventId}: ${result.issues.map((issue) => issue.message).join('; ')}`
140
+ );
69
141
  }
142
+ return result.output;
70
143
  }
71
144
 
72
145
  /**
73
- * Firestore idempotency (production)
146
+ * Firestore-backed store (transactions). Collection: `webhook_idempotency`.
147
+ *
148
+ * `expiresAt` is a Firestore Timestamp {@link WEBHOOK_EVENT_RETENTION_MS} after
149
+ * the last write: enable a TTL policy on `webhook_idempotency.expiresAt` so
150
+ * Firestore deletes old documents.
151
+ *
152
+ * @version 0.2.0
153
+ * @since 0.2.0
154
+ * @author AMBROISE PARK Consulting
74
155
  */
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
104
- return false;
105
- }
106
-
107
- return true;
108
- } catch (error) {
109
- throw handleError(error);
110
- }
111
- }
112
-
113
- async markProcessed(eventId: string): Promise<void> {
114
- await this.init();
156
+ export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
157
+ let firebase: typeof import('@donotdev/firebase/server') | null = null;
158
+ const load = async () => {
159
+ if (!firebase) firebase = await import('@donotdev/firebase/server');
160
+ const firestore = firebase.getFirebaseAdminFirestore();
161
+ return {
162
+ firestore,
163
+ Timestamp: firebase.Timestamp,
164
+ refOf: (eventId: string) =>
165
+ firestore.collection(FIRESTORE_COLLECTION).doc(eventId),
166
+ };
167
+ };
115
168
 
169
+ const reserve = async (eventId: string): Promise<ReservationResult> => {
170
+ const { firestore, Timestamp, refOf } = await load();
171
+ const ref = refOf(eventId);
116
172
  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;
173
+ return await firestore.runTransaction(async (tx) => {
174
+ const snapshot = await tx.get(ref);
175
+ const now = Date.now();
176
+ if (snapshot.exists) {
177
+ const data = parseEventDoc(eventId, snapshot.data());
178
+ if (data.status === 'processing') {
179
+ if (now - (data.reservedAt ?? 0) < RESERVATION_LEASE_MS) {
180
+ return { state: 'in_progress' } as const;
181
+ }
182
+ } else if ((data.expiresAt ?? 0) >= now) {
183
+ return { state: 'processed' } as const;
184
+ }
125
185
  }
126
-
127
- // Atomically set the document
128
- transaction.set(docRef, {
186
+ const ownerToken = newOwnerToken();
187
+ tx.set(ref, {
129
188
  eventId,
130
- processedAt: Date.now(),
131
- expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
189
+ status: 'processing',
190
+ ownerToken,
191
+ reservedAt: now,
192
+ expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
132
193
  });
194
+ return { state: 'reserved', ownerToken } as const;
133
195
  });
134
196
  } catch (error) {
135
197
  throw handleError(error);
136
198
  }
137
- }
138
-
139
- async checkAndReserve(eventId: string): Promise<boolean> {
140
- await this.init();
199
+ };
141
200
 
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);
147
-
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
- }
201
+ return {
202
+ reserve,
203
+ async checkAndReserve(eventId) {
204
+ return (await reserve(eventId)).state !== 'reserved';
205
+ },
206
+ async markProcessed(eventId, ownerToken) {
207
+ const { firestore, Timestamp, refOf } = await load();
208
+ const ref = refOf(eventId);
209
+ const now = Date.now();
210
+ const processed = {
211
+ eventId,
212
+ status: 'processed',
213
+ processedAt: now,
214
+ expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
215
+ };
216
+ try {
217
+ if (ownerToken === undefined) {
218
+ // 0.1.x call: unconditional write
219
+ await ref.set(processed);
220
+ return;
155
221
  }
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
222
+ await firestore.runTransaction(async (tx) => {
223
+ const snapshot = await tx.get(ref);
224
+ const data = snapshot.exists
225
+ ? parseEventDoc(eventId, snapshot.data())
226
+ : null;
227
+ if (data?.ownerToken !== ownerToken) {
228
+ throw new ReservationLostError(eventId);
229
+ }
230
+ tx.set(ref, { ...processed, ownerToken });
162
231
  });
163
- });
164
- return alreadyProcessed;
165
- } catch (error) {
166
- throw handleError(error);
167
- }
168
- }
232
+ } catch (error) {
233
+ if (error instanceof ReservationLostError) throw error;
234
+ throw handleError(error);
235
+ }
236
+ },
237
+ async release(eventId, ownerToken) {
238
+ const { firestore, refOf } = await load();
239
+ const ref = refOf(eventId);
240
+ try {
241
+ return await firestore.runTransaction(async (tx) => {
242
+ const snapshot = await tx.get(ref);
243
+ if (!snapshot.exists) return false;
244
+ const data = parseEventDoc(eventId, snapshot.data());
245
+ if (data.status !== 'processing' || data.ownerToken !== ownerToken) {
246
+ return false;
247
+ }
248
+ tx.delete(ref);
249
+ return true;
250
+ });
251
+ } catch (error) {
252
+ throw handleError(error);
253
+ }
254
+ },
255
+ async isProcessed(eventId) {
256
+ const { refOf } = await load();
257
+ try {
258
+ const snapshot = await refOf(eventId).get();
259
+ if (!snapshot.exists) return false;
260
+ const data = parseEventDoc(eventId, snapshot.data());
261
+ return data.status !== 'processing' && (data.expiresAt ?? 0) >= Date.now();
262
+ } catch (error) {
263
+ throw handleError(error);
264
+ }
265
+ },
266
+ };
169
267
  }
170
268
 
269
+ // =============================================================================
270
+ // 0.1.x auto-detection (deprecated)
271
+ // =============================================================================
272
+
273
+ let cachedStore: LegacyIdempotencyStore | null = null;
274
+
171
275
  /**
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
276
+ * 0.1.x store auto-detection: Firestore when configured, else in-memory.
177
277
  *
178
- * Falls back to in-memory if Firestore not available
179
- *
180
- * @version 0.1.0
278
+ * @deprecated In-memory is not durable across instances. Pass an explicit store:
279
+ * {@link createFirestoreIdempotencyStore} or `createSupabaseIdempotencyStore`.
280
+ * Framework webhook entry points already do.
281
+ * @version 0.2.0
181
282
  * @since 0.0.1
182
283
  * @author AMBROISE PARK Consulting
183
284
  */
184
- let cachedStore: IdempotencyStore | null = null;
185
-
186
- export function createIdempotencyStore(): IdempotencyStore {
187
- // Return cached instance (singleton per function instance)
285
+ export function createIdempotencyStore(): LegacyIdempotencyStore {
188
286
  if (cachedStore) return cachedStore;
189
-
190
287
  if (isFirestoreConfigured()) {
191
- console.log('✅ [Idempotency] Using Firestore (production-ready)');
192
- cachedStore = new FirestoreIdempotency();
288
+ cachedStore = createFirestoreIdempotencyStore();
193
289
  } else {
194
- console.warn('⚠️ [Idempotency] Firestore not configured, using in-memory');
195
- cachedStore = new InMemoryIdempotency();
290
+ console.warn(
291
+ '[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store.'
292
+ );
293
+ cachedStore = createInMemoryIdempotencyStore();
196
294
  }
197
-
198
295
  return cachedStore;
199
296
  }
200
297
 
201
298
  /**
202
- * Reset cached store (for testing only)
299
+ * Reset the store cached by {@link createIdempotencyStore} (tests).
203
300
  *
301
+ * @deprecated See {@link createIdempotencyStore}.
204
302
  * @version 0.1.0
205
303
  * @since 0.0.1
206
304
  * @author AMBROISE PARK Consulting
@@ -208,3 +306,8 @@ export function createIdempotencyStore(): IdempotencyStore {
208
306
  export function resetIdempotencyStore() {
209
307
  cachedStore = null;
210
308
  }
309
+
310
+ export {
311
+ WEBHOOK_EVENTS_SQL,
312
+ createSupabaseIdempotencyStore,
313
+ } from './supabaseIdempotency.js';
@@ -0,0 +1,135 @@
1
+ // packages/functions/src/shared/billing/idempotencyContract.ts
2
+
3
+ /**
4
+ * @fileoverview Webhook idempotency contract
5
+ * @description Store interface, reservation result, lease and retention shared
6
+ * by every idempotency store (in-memory, Firestore, Postgres).
7
+ *
8
+ * @version 0.2.0
9
+ * @since 0.2.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ /**
14
+ * Outcome of {@link IdempotencyStore.reserve}.
15
+ * - `reserved`: the caller owns the event and must process it, then call
16
+ * `markProcessed` or `release` with `ownerToken`
17
+ * - `processed`: already processed, skip (answer 2xx)
18
+ * - `in_progress`: another delivery holds a live lease (answer non-2xx so the
19
+ * provider retries later, when that worker finished or its lease expired)
20
+ *
21
+ * @version 0.2.0
22
+ * @since 0.2.0
23
+ * @author AMBROISE PARK Consulting
24
+ */
25
+ export type ReservationResult =
26
+ | { state: 'reserved'; ownerToken: string }
27
+ | { state: 'processed' }
28
+ | { state: 'in_progress' };
29
+
30
+ /**
31
+ * Idempotency store interface
32
+ *
33
+ * @version 0.2.0
34
+ * @since 0.0.1
35
+ * @author AMBROISE PARK Consulting
36
+ */
37
+ export interface IdempotencyStore {
38
+ /** Atomically reserve an event for processing. */
39
+ reserve(eventId: string): Promise<ReservationResult>;
40
+ /**
41
+ * Mark a reservation processed. Repeating it for the same owner succeeds.
42
+ * @throws {ReservationLostError} When `ownerToken` no longer owns the event
43
+ */
44
+ markProcessed(eventId: string, ownerToken: string): Promise<void>;
45
+ /**
46
+ * Drop a reservation after a processing failure.
47
+ * @returns `false` when `ownerToken` does not own a pending reservation (nothing changed)
48
+ */
49
+ release(eventId: string, ownerToken: string): Promise<boolean>;
50
+ }
51
+
52
+ /**
53
+ * Store with the 0.1.x accessors.
54
+ *
55
+ * @deprecated Use {@link IdempotencyStore}: `reserve` returns three states and
56
+ * an owner token; `checkAndReserve` and `isProcessed` do not.
57
+ * @version 0.2.0
58
+ * @since 0.2.0
59
+ * @author AMBROISE PARK Consulting
60
+ */
61
+ export interface LegacyIdempotencyStore extends IdempotencyStore {
62
+ /** 0.1.x: `true` when the event must be skipped (processed or live lease). */
63
+ checkAndReserve(eventId: string): Promise<boolean>;
64
+ /** Whether the event was processed (non-atomic read). */
65
+ isProcessed(eventId: string): Promise<boolean>;
66
+ /**
67
+ * Mark processed. Without `ownerToken` (0.1.x call) the write is unconditional.
68
+ * @throws {ReservationLostError} When `ownerToken` is given and no longer owns the event
69
+ */
70
+ markProcessed(eventId: string, ownerToken?: string): Promise<void>;
71
+ }
72
+
73
+ /**
74
+ * Thrown by `markProcessed` when the caller no longer owns the reservation:
75
+ * its lease expired and another delivery retook the event, or the row is gone.
76
+ * Retrying cannot succeed.
77
+ *
78
+ * @version 0.2.0
79
+ * @since 0.2.0
80
+ * @author AMBROISE PARK Consulting
81
+ */
82
+ export class ReservationLostError extends Error {
83
+ /** Event whose reservation was lost. */
84
+ readonly eventId: string;
85
+
86
+ constructor(eventId: string) {
87
+ super(
88
+ `Reservation of webhook event ${eventId} is no longer held by this worker (lease retaken or row removed)`
89
+ );
90
+ this.name = 'ReservationLostError';
91
+ this.eventId = eventId;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * How long a reservation blocks other deliveries of the same event before it
97
+ * is considered abandoned (worker crashed or timed out) and can be retaken.
98
+ *
99
+ * Must exceed the longest request timeout a webhook handler can run under, so
100
+ * a live worker is never overtaken. Official maximums (checked 2026-11-04):
101
+ * - Firebase Functions gen2 HTTP: 60 min
102
+ * (https://firebase.google.com/docs/functions/quotas#time_limits)
103
+ * - Vercel Functions: 800 s, 1800 s with extended max duration
104
+ * (https://vercel.com/docs/functions/configuring-functions/duration)
105
+ * - Supabase Edge Functions: 400 s wall clock on paid plans
106
+ * (https://supabase.com/docs/guides/functions/limits)
107
+ * 70 min = the 60 min maximum + 10 min margin. Stripe retries for up to 3 days.
108
+ *
109
+ * @version 0.2.0
110
+ * @since 0.2.0
111
+ * @author AMBROISE PARK Consulting
112
+ */
113
+ export const RESERVATION_LEASE_MS = 70 * 60 * 1000;
114
+
115
+ /**
116
+ * How long reservations and processed events are kept before a TTL policy
117
+ * (Firestore `expiresAt`) or the pg_cron cleanup (Postgres) deletes them.
118
+ * Stripe retries for days, not weeks.
119
+ *
120
+ * @version 0.2.0
121
+ * @since 0.2.0
122
+ * @author AMBROISE PARK Consulting
123
+ */
124
+ export const WEBHOOK_EVENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
125
+
126
+ /**
127
+ * New reservation owner token (random UUID). Internal to the stores.
128
+ *
129
+ * @version 0.2.0
130
+ * @since 0.2.0
131
+ * @author AMBROISE PARK Consulting
132
+ */
133
+ export function newOwnerToken(): string {
134
+ return crypto.randomUUID();
135
+ }
@@ -12,3 +12,5 @@
12
12
  export * from './createCheckout.js';
13
13
  export * from './helpers/index.js';
14
14
  export * from './webhookHandler.js';
15
+ export * from './idempotency.js';
16
+ export * from './orderWebhook.js';