@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.
- package/README.md +25 -14
- package/lib/chunks/chunk-2JL3GDTO.js +151 -0
- package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
- package/lib/chunks/chunk-4TVLH2W2.js +22 -0
- package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
- package/lib/chunks/chunk-4U7QQWYG.js +22 -0
- package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
- package/lib/chunks/chunk-5DTPEM64.js +22 -0
- package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
- package/lib/chunks/chunk-6CQXHNVL.js +22 -0
- package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
- package/lib/chunks/chunk-6DSCPZC6.js +22 -0
- package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
- package/lib/chunks/chunk-7E6TGWHU.js +22 -0
- package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
- package/lib/chunks/chunk-7LT32OWE.js +22 -0
- package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
- package/lib/chunks/chunk-7VH2GJXT.js +151 -0
- package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
- package/lib/chunks/chunk-API5A4BV.js +22 -0
- package/lib/chunks/chunk-API5A4BV.js.map +7 -0
- package/lib/chunks/chunk-AYY7UXNI.js +22 -0
- package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
- package/lib/chunks/chunk-BUP7SXPV.js +23 -0
- package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
- package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
- package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
- package/lib/chunks/chunk-FSLGZD7A.js +21 -0
- package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
- package/lib/chunks/chunk-GVLSPWDD.js +151 -0
- package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
- package/lib/chunks/chunk-GXQVWEFT.js +22 -0
- package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
- package/lib/chunks/chunk-HB7EGXVI.js +22 -0
- package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
- package/lib/chunks/chunk-HLNYUAZH.js +22 -0
- package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
- package/lib/chunks/chunk-HM7XCMWW.js +22 -0
- package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
- package/lib/chunks/chunk-I7IOIL6U.js +151 -0
- package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
- package/lib/chunks/chunk-IFOYVSPU.js +22 -0
- package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
- package/lib/chunks/chunk-JTAGPPPL.js +22 -0
- package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
- package/lib/chunks/chunk-MZ232FUE.js +22 -0
- package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
- package/lib/chunks/chunk-NP2AN2TV.js +22 -0
- package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
- package/lib/chunks/chunk-QJAU2MWV.js +22 -0
- package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
- package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
- package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
- package/lib/chunks/chunk-RQZGIZHD.js +151 -0
- package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
- package/lib/chunks/chunk-TBEDQLOB.js +23 -0
- package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
- package/lib/chunks/chunk-TMHBP3HB.js +22 -0
- package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
- package/lib/chunks/chunk-UH4L3EF3.js +151 -0
- package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
- package/lib/chunks/chunk-UJBIU6TL.js +22 -0
- package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
- package/lib/chunks/chunk-VKEYW3NT.js +22 -0
- package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
- package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
- package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
- package/lib/chunks/chunk-Y44NEQQG.js +22 -0
- package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
- package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
- package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
- package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
- package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
- package/lib/chunks/monitoring-PVQMFL34.js +22 -0
- package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
- package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
- package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
- package/lib/chunks/server-32A5RH4C.js +22 -0
- package/lib/chunks/server-32A5RH4C.js.map +7 -0
- package/lib/chunks/server-7HDAP5DL.js +22 -0
- package/lib/chunks/server-7HDAP5DL.js.map +7 -0
- package/lib/chunks/server-S2IMFOY7.js +22 -0
- package/lib/chunks/server-S2IMFOY7.js.map +7 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/index.d.ts +2 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
- package/lib/firebase/billing/webhookHandler.d.ts +17 -2
- package/lib/firebase/crud/aggregate.d.ts +0 -9
- package/lib/firebase/crud/bulk.d.ts +2 -2
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/shared/billing/apiVersion.d.ts +22 -0
- package/lib/shared/billing/checkoutPrice.d.ts +27 -0
- package/lib/shared/billing/checkoutValidation.d.ts +89 -0
- package/lib/shared/billing/createCheckout.d.ts +73 -24
- package/lib/shared/billing/helpers/index.d.ts +0 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
- package/lib/shared/billing/idempotency.d.ts +32 -10
- package/lib/shared/billing/idempotencyContract.d.ts +121 -0
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +75 -0
- package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +28 -20
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +4 -17
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +10 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
- package/lib/vercel/api/billing/backend.d.ts +39 -0
- package/lib/vercel/api/billing/cancel.d.ts +8 -0
- package/lib/vercel/api/billing/change-plan.d.ts +9 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
- package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
- package/lib/vercel/api/billing/index.d.ts +4 -2
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
- package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/crud/bulk.d.ts +17 -0
- package/lib/vercel/api/crud/create.d.ts +8 -0
- package/lib/vercel/api/crud/delete.d.ts +8 -0
- package/lib/vercel/api/crud/get.d.ts +8 -0
- package/lib/vercel/api/crud/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -0
- package/lib/vercel/api/index.js +1 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/baseFunction.d.ts +4 -1
- package/lib/vercel/supabaseAdmin.d.ts +22 -0
- package/package.json +25 -26
- package/src/firebase/auth/getCustomClaims.ts +4 -5
- package/src/firebase/auth/getUserAuthStatus.ts +4 -5
- package/src/firebase/auth/removeCustomClaims.ts +4 -5
- package/src/firebase/auth/setCustomClaims.ts +4 -5
- package/src/firebase/baseFunction.ts +4 -5
- package/src/firebase/billing/cancelSubscription.ts +1 -2
- package/src/firebase/billing/changePlan.ts +2 -3
- package/src/firebase/billing/createCheckoutSession.ts +30 -56
- package/src/firebase/billing/createCustomerPortal.ts +4 -5
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
- package/src/firebase/billing/webhookHandler.ts +20 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
- package/src/firebase/crud/aggregate.ts +1 -2
- package/src/firebase/crud/bulk.ts +5 -6
- package/src/firebase/crud/create.ts +5 -6
- package/src/firebase/crud/delete.ts +4 -5
- package/src/firebase/crud/get.ts +4 -5
- package/src/firebase/crud/list.ts +4 -5
- package/src/firebase/crud/update.ts +5 -6
- package/src/firebase/oauth/githubAccess.ts +2 -3
- package/src/firebase/registerCrudFunctions.ts +2 -2
- package/src/shared/__tests__/auth.test.ts +0 -3
- package/src/shared/__tests__/bulkCore.test.ts +3 -2
- package/src/shared/__tests__/errorHandling.test.ts +2 -2
- package/src/shared/__tests__/idempotency.test.ts +282 -55
- package/src/shared/__tests__/internalValidation.test.ts +3 -3
- package/src/shared/__tests__/rateLimiter.test.ts +2 -8
- package/src/shared/__tests__/schemaValidation.test.ts +1 -1
- package/src/shared/__tests__/utils.test.ts +2 -1
- package/src/shared/__tests__/validation-env.test.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +53 -30
- package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
- package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
- package/src/shared/billing/apiVersion.ts +25 -0
- package/src/shared/billing/checkoutPrice.ts +125 -0
- package/src/shared/billing/checkoutValidation.ts +284 -0
- package/src/shared/billing/createCheckout.ts +332 -196
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +253 -150
- package/src/shared/billing/idempotencyContract.ts +135 -0
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +269 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +188 -385
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +2 -3
- package/src/shared/utils/functionWrapper.ts +1 -2
- package/src/shared/utils/internal/auth.ts +55 -7
- package/src/shared/utils/internal/monitoring.ts +17 -9
- package/src/shared/utils/internal/rateLimiter.ts +14 -5
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +14 -31
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +3 -1
- package/src/supabase/__tests__/entityStore.test.ts +90 -0
- package/src/supabase/baseFunction.ts +1 -2
- package/src/supabase/billing/createCheckoutSession.ts +10 -36
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
- package/src/supabase/billing/stripeWebhook.ts +79 -0
- package/src/supabase/crud/aggregate.ts +1 -1
- package/src/supabase/crud/bulk.ts +3 -7
- package/src/supabase/crud/create.ts +1 -1
- package/src/supabase/crud/entityStore.ts +240 -0
- package/src/supabase/crud/index.ts +8 -0
- package/src/supabase/crud/update.ts +1 -1
- package/src/supabase/helpers/authProvider.ts +6 -5
- package/src/supabase/index.ts +26 -0
- package/src/supabase/utils/rateLimiter.ts +2 -2
- package/src/vercel/__tests__/bulk.test.ts +24 -21
- package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
- package/src/vercel/api/ai/chat.ts +2 -1
- package/src/vercel/api/auth/get-custom-claims.ts +2 -3
- package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
- package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
- package/src/vercel/api/auth/set-custom-claims.ts +3 -3
- package/src/vercel/api/billing/backend.ts +72 -0
- package/src/vercel/api/billing/cancel.ts +2 -4
- package/src/vercel/api/billing/change-plan.ts +3 -4
- package/src/vercel/api/billing/create-checkout-session.ts +42 -68
- package/src/vercel/api/billing/customer-portal.ts +2 -4
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
- package/src/vercel/api/billing/webhook-handler.ts +31 -25
- package/src/vercel/api/config/firebase-admin.ts +2 -2
- package/src/vercel/api/crud/bulk.ts +6 -9
- package/src/vercel/api/crud/create.ts +6 -5
- package/src/vercel/api/crud/delete.ts +4 -3
- package/src/vercel/api/crud/get.ts +6 -5
- package/src/vercel/api/crud/list.ts +6 -5
- package/src/vercel/api/crud/update.ts +6 -5
- package/src/vercel/api/oauth/check-github-access.ts +5 -5
- package/src/vercel/api/oauth/exchange-token.ts +3 -3
- package/src/vercel/api/oauth/grant-github-access.ts +5 -5
- package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
- package/src/vercel/baseFunction.ts +23 -8
- package/src/vercel/supabaseAdmin.ts +45 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Firestore idempotency store against the Firestore emulator
|
|
5
|
+
* @description Runs only when FIRESTORE_EMULATOR_HOST is set, e.g.
|
|
6
|
+
* `bunx firebase-tools emulators:exec --only firestore --project demo-dndev
|
|
7
|
+
* "bun test src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts"`.
|
|
8
|
+
*
|
|
9
|
+
* @version 0.2.0
|
|
10
|
+
* @since 0.2.0
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { describe, expect, it } from 'vitest';
|
|
15
|
+
|
|
16
|
+
const enabled = Boolean(process.env.FIRESTORE_EMULATOR_HOST);
|
|
17
|
+
|
|
18
|
+
describe.skipIf(!enabled)('firestore idempotency store (emulator)', () => {
|
|
19
|
+
const load = async () => {
|
|
20
|
+
const { createFirestoreIdempotencyStore, ReservationLostError } =
|
|
21
|
+
await import('../idempotency.js');
|
|
22
|
+
const { getFirebaseAdminFirestore, Timestamp } =
|
|
23
|
+
await import('@donotdev/firebase/server');
|
|
24
|
+
return {
|
|
25
|
+
store: createFirestoreIdempotencyStore(),
|
|
26
|
+
ReservationLostError,
|
|
27
|
+
Timestamp,
|
|
28
|
+
collection: getFirebaseAdminFirestore().collection('webhook_idempotency'),
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
const id = (name: string) => `evt_emu_${name}_${crypto.randomUUID()}`;
|
|
32
|
+
|
|
33
|
+
it('reserve → in_progress → markProcessed → processed, expiresAt is a Timestamp', async () => {
|
|
34
|
+
const { store, Timestamp, collection } = await load();
|
|
35
|
+
const eventId = id('flow');
|
|
36
|
+
const first = await store.reserve(eventId);
|
|
37
|
+
expect(first.state).toBe('reserved');
|
|
38
|
+
if (first.state !== 'reserved') return;
|
|
39
|
+
expect(await store.reserve(eventId)).toEqual({ state: 'in_progress' });
|
|
40
|
+
|
|
41
|
+
const reserved = (await collection.doc(eventId).get()).data()!;
|
|
42
|
+
expect(reserved.expiresAt).toBeInstanceOf(Timestamp);
|
|
43
|
+
expect(reserved.ownerToken).toBe(first.ownerToken);
|
|
44
|
+
|
|
45
|
+
await store.markProcessed(eventId, first.ownerToken);
|
|
46
|
+
expect(await store.reserve(eventId)).toEqual({ state: 'processed' });
|
|
47
|
+
const processed = (await collection.doc(eventId).get()).data()!;
|
|
48
|
+
expect(processed.status).toBe('processed');
|
|
49
|
+
expect(processed.expiresAt).toBeInstanceOf(Timestamp);
|
|
50
|
+
const days =
|
|
51
|
+
(processed.expiresAt.toMillis() - processed.processedAt) / 86_400_000;
|
|
52
|
+
expect(days).toBe(30);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('concurrent deliveries: exactly one reserves', async () => {
|
|
56
|
+
const { store } = await load();
|
|
57
|
+
const eventId = id('race');
|
|
58
|
+
const results = await Promise.all(
|
|
59
|
+
Array.from({ length: 8 }, () => store.reserve(eventId))
|
|
60
|
+
);
|
|
61
|
+
expect(results.filter((r) => r.state === 'reserved')).toHaveLength(1);
|
|
62
|
+
expect(results.filter((r) => r.state === 'in_progress')).toHaveLength(7);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('owner token: foreign release is a no-op, foreign markProcessed fails loud', async () => {
|
|
66
|
+
const { store, ReservationLostError } = await load();
|
|
67
|
+
const eventId = id('owner');
|
|
68
|
+
const mine = await store.reserve(eventId);
|
|
69
|
+
if (mine.state !== 'reserved') throw new Error('expected reserved');
|
|
70
|
+
expect(await store.release(eventId, crypto.randomUUID())).toBe(false);
|
|
71
|
+
await expect(
|
|
72
|
+
store.markProcessed(eventId, crypto.randomUUID())
|
|
73
|
+
).rejects.toBeInstanceOf(ReservationLostError);
|
|
74
|
+
expect(await store.release(eventId, mine.ownerToken)).toBe(true);
|
|
75
|
+
expect((await store.reserve(eventId)).state).toBe('reserved');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('lease takeover: an expired reservation is retaken and the stale owner is locked out', async () => {
|
|
79
|
+
const { store, ReservationLostError, collection } = await load();
|
|
80
|
+
const eventId = id('lease');
|
|
81
|
+
const stale = await store.reserve(eventId);
|
|
82
|
+
if (stale.state !== 'reserved') throw new Error('expected reserved');
|
|
83
|
+
await collection.doc(eventId).update({ reservedAt: Date.now() - 71 * 60_000 });
|
|
84
|
+
|
|
85
|
+
const fresh = await store.reserve(eventId);
|
|
86
|
+
expect(fresh.state).toBe('reserved');
|
|
87
|
+
await expect(
|
|
88
|
+
store.markProcessed(eventId, stale.ownerToken)
|
|
89
|
+
).rejects.toBeInstanceOf(ReservationLostError);
|
|
90
|
+
expect(await store.release(eventId, stale.ownerToken)).toBe(false);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/__tests__/webhookCorrectness.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Webhook delivery correctness
|
|
5
|
+
* @description Three-state reservation (processed / in_progress / reserved),
|
|
6
|
+
* owner token, bounded markProcessed retry, payment_status matrix for tier
|
|
7
|
+
* items, and the order API version error.
|
|
8
|
+
*
|
|
9
|
+
* @version 0.2.0
|
|
10
|
+
* @since 0.2.0
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
15
|
+
|
|
16
|
+
vi.mock('../../utils/detectFirestore.js', () => ({
|
|
17
|
+
isFirestoreConfigured: vi.fn(() => false),
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
vi.mock('@donotdev/core/server', () => ({
|
|
21
|
+
validateStripeBackConfig: vi.fn((config: unknown) => config),
|
|
22
|
+
SUBSCRIPTION_STATUS: { ACTIVE: 'active', CANCELED: 'canceled' },
|
|
23
|
+
SUBSCRIPTION_TIERS: { FREE: 'free' },
|
|
24
|
+
calculateSubscriptionEndDate: vi.fn(() => '2026-03-18T00:00:00.000Z'),
|
|
25
|
+
DoNotDevError: class DoNotDevError extends Error {
|
|
26
|
+
code: string;
|
|
27
|
+
details?: Record<string, unknown>;
|
|
28
|
+
constructor(
|
|
29
|
+
message: string,
|
|
30
|
+
code = 'internal',
|
|
31
|
+
options?: { details?: Record<string, unknown> }
|
|
32
|
+
) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.details = options?.details;
|
|
36
|
+
this.name = 'DoNotDevError';
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
}));
|
|
40
|
+
|
|
41
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
42
|
+
getFirebaseAdminFirestore: vi.fn(),
|
|
43
|
+
}));
|
|
44
|
+
|
|
45
|
+
vi.mock('../../logger.js', () => ({
|
|
46
|
+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
|
47
|
+
}));
|
|
48
|
+
|
|
49
|
+
import { logger } from '../../logger.js';
|
|
50
|
+
import {
|
|
51
|
+
ReservationLostError,
|
|
52
|
+
createInMemoryIdempotencyStore,
|
|
53
|
+
} from '../idempotency.js';
|
|
54
|
+
import type { IdempotencyStore } from '../idempotency.js';
|
|
55
|
+
import { processWebhook } from '../webhookHandler.js';
|
|
56
|
+
|
|
57
|
+
const config = {
|
|
58
|
+
pro_monthly: {
|
|
59
|
+
type: 'StripeSubscription' as const,
|
|
60
|
+
name: 'Pro',
|
|
61
|
+
price: 999,
|
|
62
|
+
currency: 'usd',
|
|
63
|
+
priceId: 'price_pro',
|
|
64
|
+
tier: 'pro',
|
|
65
|
+
duration: '1month',
|
|
66
|
+
onSubscriptionCreated: vi.fn(async () => {}),
|
|
67
|
+
},
|
|
68
|
+
lifetime: {
|
|
69
|
+
type: 'StripePayment' as const,
|
|
70
|
+
name: 'Lifetime',
|
|
71
|
+
price: 19900,
|
|
72
|
+
currency: 'usd',
|
|
73
|
+
priceId: 'price_life',
|
|
74
|
+
tier: 'premium',
|
|
75
|
+
duration: 'lifetime',
|
|
76
|
+
onPurchaseSuccess: vi.fn(async () => {}),
|
|
77
|
+
},
|
|
78
|
+
shop_order: {
|
|
79
|
+
type: 'StripeOrder' as const,
|
|
80
|
+
name: 'Shop',
|
|
81
|
+
currency: 'eur',
|
|
82
|
+
resolveLineItems: vi.fn(),
|
|
83
|
+
onOrderPaid: vi.fn(async () => {}),
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
let counter = 0;
|
|
88
|
+
function makeEvent(type: string, session: Record<string, unknown>): any {
|
|
89
|
+
counter += 1;
|
|
90
|
+
return {
|
|
91
|
+
id: `evt_corr_${counter}`,
|
|
92
|
+
type,
|
|
93
|
+
api_version: '2025-02-24.acacia',
|
|
94
|
+
data: { object: { id: `cs_${counter}`, customer: 'cus_1', ...session } },
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function stripeFor(event: any): any {
|
|
99
|
+
return {
|
|
100
|
+
webhooks: { constructEventAsync: vi.fn(async () => event) },
|
|
101
|
+
subscriptions: { retrieve: vi.fn() },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const authProvider = {
|
|
106
|
+
getUser: vi.fn(async () => ({ customClaims: {} })),
|
|
107
|
+
setCustomUserClaims: vi.fn(async () => {}),
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
function run(
|
|
111
|
+
event: any,
|
|
112
|
+
store: IdempotencyStore,
|
|
113
|
+
updateSubscription = vi.fn(async () => {})
|
|
114
|
+
) {
|
|
115
|
+
return processWebhook(
|
|
116
|
+
'raw',
|
|
117
|
+
'sig',
|
|
118
|
+
'whsec',
|
|
119
|
+
stripeFor(event),
|
|
120
|
+
config as any,
|
|
121
|
+
updateSubscription,
|
|
122
|
+
authProvider,
|
|
123
|
+
store
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Store double recording calls, reserving with a fixed token. */
|
|
128
|
+
function makeStore(overrides: Partial<IdempotencyStore> = {}) {
|
|
129
|
+
return {
|
|
130
|
+
reserve: vi.fn(async () => ({
|
|
131
|
+
state: 'reserved' as const,
|
|
132
|
+
ownerToken: 'tok_a',
|
|
133
|
+
})),
|
|
134
|
+
markProcessed: vi.fn(async () => {}),
|
|
135
|
+
release: vi.fn(async () => true),
|
|
136
|
+
...overrides,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const tierSession = (key: 'pro_monthly' | 'lifetime', paymentStatus: string) => ({
|
|
141
|
+
payment_status: paymentStatus,
|
|
142
|
+
subscription: key === 'pro_monthly' ? 'sub_1' : null,
|
|
143
|
+
metadata: { userId: 'u1', billingConfigKey: key },
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
beforeEach(() => {
|
|
147
|
+
vi.clearAllMocks();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
describe('reservation states', () => {
|
|
151
|
+
it('processed → 2xx skip, nothing routed', async () => {
|
|
152
|
+
const store = makeStore({ reserve: vi.fn(async () => ({ state: 'processed' as const })) });
|
|
153
|
+
const update = vi.fn(async () => {});
|
|
154
|
+
const result = await run(
|
|
155
|
+
makeEvent('checkout.session.completed', tierSession('lifetime', 'paid')),
|
|
156
|
+
store,
|
|
157
|
+
update
|
|
158
|
+
);
|
|
159
|
+
expect(result).toEqual({ success: true, message: 'Event already processed' });
|
|
160
|
+
expect(update).not.toHaveBeenCalled();
|
|
161
|
+
expect(store.markProcessed).not.toHaveBeenCalled();
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('in_progress → rejects with unavailable (non-2xx), nothing routed, released or marked', async () => {
|
|
165
|
+
const store = makeStore({ reserve: vi.fn(async () => ({ state: 'in_progress' as const })) });
|
|
166
|
+
const update = vi.fn(async () => {});
|
|
167
|
+
const event = makeEvent('checkout.session.completed', tierSession('lifetime', 'paid'));
|
|
168
|
+
|
|
169
|
+
await expect(run(event, store, update)).rejects.toMatchObject({
|
|
170
|
+
code: 'unavailable',
|
|
171
|
+
details: { eventId: event.id, reason: 'webhook_event_in_progress' },
|
|
172
|
+
});
|
|
173
|
+
expect(update).not.toHaveBeenCalled();
|
|
174
|
+
expect(store.release).not.toHaveBeenCalled();
|
|
175
|
+
expect(store.markProcessed).not.toHaveBeenCalled();
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('a second delivery during a live lease is answered non-2xx, then 2xx once processed', async () => {
|
|
179
|
+
const store = createInMemoryIdempotencyStore();
|
|
180
|
+
const event = makeEvent('checkout.session.completed', tierSession('lifetime', 'paid'));
|
|
181
|
+
let release!: () => void;
|
|
182
|
+
const slow = vi.fn(
|
|
183
|
+
() => new Promise<void>((resolve) => (release = resolve))
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
const first = run(event, store, slow);
|
|
187
|
+
for (let i = 0; i < 50 && slow.mock.calls.length === 0; i++) {
|
|
188
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
189
|
+
}
|
|
190
|
+
expect(slow).toHaveBeenCalled();
|
|
191
|
+
await expect(run(event, store)).rejects.toMatchObject({ code: 'unavailable' });
|
|
192
|
+
release();
|
|
193
|
+
await expect(first).resolves.toEqual({ success: true, message: 'Webhook processed' });
|
|
194
|
+
await expect(run(event, store)).resolves.toEqual({
|
|
195
|
+
success: true,
|
|
196
|
+
message: 'Event already processed',
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it('routing failure releases with the owner token and rethrows', async () => {
|
|
201
|
+
const store = makeStore();
|
|
202
|
+
const failing = vi.fn(async () => {
|
|
203
|
+
throw new Error('claims write failed');
|
|
204
|
+
});
|
|
205
|
+
await expect(
|
|
206
|
+
run(makeEvent('checkout.session.completed', tierSession('lifetime', 'paid')), store, failing)
|
|
207
|
+
).rejects.toThrow();
|
|
208
|
+
expect(store.release).toHaveBeenCalledWith(expect.any(String), 'tok_a');
|
|
209
|
+
expect(store.markProcessed).not.toHaveBeenCalled();
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it('a stale release (not owner) is logged, the routing error still propagates', async () => {
|
|
213
|
+
const store = makeStore({ release: vi.fn(async () => false) });
|
|
214
|
+
await expect(
|
|
215
|
+
run(
|
|
216
|
+
makeEvent('checkout.session.completed', tierSession('lifetime', 'paid')),
|
|
217
|
+
store,
|
|
218
|
+
vi.fn(async () => {
|
|
219
|
+
throw new Error('boom');
|
|
220
|
+
})
|
|
221
|
+
)
|
|
222
|
+
).rejects.toThrow();
|
|
223
|
+
expect(logger.warn).toHaveBeenCalledWith(
|
|
224
|
+
'[Webhook] Reservation not released: no longer owned',
|
|
225
|
+
expect.objectContaining({ operation: 'idempotency_release_stale' })
|
|
226
|
+
);
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
describe('markProcessed after a successful hook', () => {
|
|
231
|
+
it('retries transient failures and succeeds', async () => {
|
|
232
|
+
const markProcessed = vi
|
|
233
|
+
.fn()
|
|
234
|
+
.mockRejectedValueOnce(new Error('firestore unavailable'))
|
|
235
|
+
.mockRejectedValueOnce(new Error('firestore unavailable'))
|
|
236
|
+
.mockResolvedValueOnce(undefined);
|
|
237
|
+
const store = makeStore({ markProcessed });
|
|
238
|
+
const result = await run(
|
|
239
|
+
makeEvent('checkout.session.completed', tierSession('lifetime', 'paid')),
|
|
240
|
+
store
|
|
241
|
+
);
|
|
242
|
+
expect(result.message).toBe('Webhook processed');
|
|
243
|
+
expect(markProcessed).toHaveBeenCalledTimes(3);
|
|
244
|
+
expect(markProcessed).toHaveBeenCalledWith(expect.any(String), 'tok_a');
|
|
245
|
+
expect(store.release).not.toHaveBeenCalled();
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it('after 3 failed attempts rejects (non-2xx) WITHOUT releasing; hook ran once', async () => {
|
|
249
|
+
const markProcessed = vi.fn(async () => {
|
|
250
|
+
throw new Error('postgrest 503');
|
|
251
|
+
});
|
|
252
|
+
const store = makeStore({ markProcessed });
|
|
253
|
+
const update = vi.fn(async () => {});
|
|
254
|
+
await expect(
|
|
255
|
+
run(makeEvent('checkout.session.completed', tierSession('lifetime', 'paid')), store, update)
|
|
256
|
+
).rejects.toThrow();
|
|
257
|
+
expect(markProcessed).toHaveBeenCalledTimes(3);
|
|
258
|
+
expect(store.release).not.toHaveBeenCalled();
|
|
259
|
+
expect(update).toHaveBeenCalledOnce();
|
|
260
|
+
expect(logger.error).toHaveBeenCalledWith(
|
|
261
|
+
expect.stringContaining('Event processed but not recorded'),
|
|
262
|
+
expect.objectContaining({ attempts: 3 })
|
|
263
|
+
);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it('does not retry a lost reservation', async () => {
|
|
267
|
+
const markProcessed = vi.fn(async (eventId: string) => {
|
|
268
|
+
throw new ReservationLostError(eventId);
|
|
269
|
+
});
|
|
270
|
+
const store = makeStore({ markProcessed });
|
|
271
|
+
await expect(
|
|
272
|
+
run(makeEvent('checkout.session.completed', tierSession('lifetime', 'paid')), store)
|
|
273
|
+
).rejects.toThrow();
|
|
274
|
+
expect(markProcessed).toHaveBeenCalledTimes(1);
|
|
275
|
+
expect(store.release).not.toHaveBeenCalled();
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it('the redelivery after the lease grants again with the same data (idempotent grant)', async () => {
|
|
279
|
+
const realNow = Date.now();
|
|
280
|
+
const now = vi.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
281
|
+
try {
|
|
282
|
+
const store = createInMemoryIdempotencyStore();
|
|
283
|
+
const realMark = store.markProcessed;
|
|
284
|
+
store.markProcessed = vi.fn(async () => {
|
|
285
|
+
throw new Error('down');
|
|
286
|
+
});
|
|
287
|
+
const update = vi.fn(async () => {});
|
|
288
|
+
const event = makeEvent('checkout.session.completed', tierSession('pro_monthly', 'paid'));
|
|
289
|
+
|
|
290
|
+
await expect(run(event, store, update)).rejects.toThrow();
|
|
291
|
+
await expect(run(event, store, update)).rejects.toMatchObject({ code: 'unavailable' });
|
|
292
|
+
|
|
293
|
+
store.markProcessed = realMark;
|
|
294
|
+
now.mockReturnValue(realNow + 70 * 60 * 1000 + 1);
|
|
295
|
+
await expect(run(event, store, update)).resolves.toEqual({
|
|
296
|
+
success: true,
|
|
297
|
+
message: 'Webhook processed',
|
|
298
|
+
});
|
|
299
|
+
expect(update).toHaveBeenCalledTimes(2);
|
|
300
|
+
expect((update.mock.calls as any[])[0].slice(0, 2)).toEqual(
|
|
301
|
+
(update.mock.calls as any[])[1].slice(0, 2)
|
|
302
|
+
);
|
|
303
|
+
} finally {
|
|
304
|
+
now.mockRestore();
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
describe('tier items: payment_status matrix', () => {
|
|
310
|
+
const cases: Array<[string, string, boolean]> = [
|
|
311
|
+
['checkout.session.completed', 'paid', true],
|
|
312
|
+
['checkout.session.completed', 'no_payment_required', true],
|
|
313
|
+
['checkout.session.completed', 'unpaid', false],
|
|
314
|
+
['checkout.session.async_payment_succeeded', 'paid', true],
|
|
315
|
+
['checkout.session.async_payment_failed', 'unpaid', false],
|
|
316
|
+
['checkout.session.expired', 'unpaid', false],
|
|
317
|
+
];
|
|
318
|
+
|
|
319
|
+
for (const key of ['lifetime', 'pro_monthly'] as const) {
|
|
320
|
+
for (const [type, status, grants] of cases) {
|
|
321
|
+
it(`${key}: ${type} + ${status} → ${grants ? 'grant' : 'no grant'}`, async () => {
|
|
322
|
+
const update = vi.fn(async () => {});
|
|
323
|
+
const result = await run(makeEvent(type, tierSession(key, status)), makeStore(), update);
|
|
324
|
+
expect(result.message).toBe('Webhook processed');
|
|
325
|
+
expect(update).toHaveBeenCalledTimes(grants ? 1 : 0);
|
|
326
|
+
const hook =
|
|
327
|
+
key === 'lifetime'
|
|
328
|
+
? config.lifetime.onPurchaseSuccess
|
|
329
|
+
: config.pro_monthly.onSubscriptionCreated;
|
|
330
|
+
expect(hook).toHaveBeenCalledTimes(grants ? 1 : 0);
|
|
331
|
+
if (grants) {
|
|
332
|
+
expect((update.mock.calls as any[])[0][1]).toMatchObject({ status: 'active' });
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
it('unpaid completion is logged as pending; async failure is logged as failed', async () => {
|
|
339
|
+
await run(makeEvent('checkout.session.completed', tierSession('lifetime', 'unpaid')), makeStore());
|
|
340
|
+
expect(logger.info).toHaveBeenCalledWith(
|
|
341
|
+
'[Webhook] Purchase awaiting async payment',
|
|
342
|
+
expect.objectContaining({ operation: 'purchase_payment_pending' })
|
|
343
|
+
);
|
|
344
|
+
await run(
|
|
345
|
+
makeEvent('checkout.session.async_payment_failed', tierSession('lifetime', 'unpaid')),
|
|
346
|
+
makeStore()
|
|
347
|
+
);
|
|
348
|
+
expect(logger.warn).toHaveBeenCalledWith(
|
|
349
|
+
'[Webhook] Async purchase payment failed, nothing granted',
|
|
350
|
+
expect.objectContaining({ operation: 'purchase_payment_failed' })
|
|
351
|
+
);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
it('unknown payment_status fails loud and releases the reservation', async () => {
|
|
355
|
+
const store = makeStore();
|
|
356
|
+
const update = vi.fn(async () => {});
|
|
357
|
+
await expect(
|
|
358
|
+
run(makeEvent('checkout.session.completed', tierSession('lifetime', 'mystery')), store, update)
|
|
359
|
+
).rejects.toThrow();
|
|
360
|
+
expect(update).not.toHaveBeenCalled();
|
|
361
|
+
expect(store.release).toHaveBeenCalledOnce();
|
|
362
|
+
});
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
describe('StripeOrder API version error', () => {
|
|
366
|
+
it('names the webhook endpoint version as the cause and logs the actionable message', async () => {
|
|
367
|
+
const event = makeEvent('checkout.session.completed', {
|
|
368
|
+
payment_status: 'paid',
|
|
369
|
+
metadata: { userId: 'u1', billingConfigKey: 'shop_order', orderId: 'ord_1' },
|
|
370
|
+
});
|
|
371
|
+
event.api_version = '2024-12-18.acacia';
|
|
372
|
+
const store = makeStore();
|
|
373
|
+
|
|
374
|
+
await expect(run(event, store)).rejects.toThrow();
|
|
375
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
376
|
+
expect(store.release).toHaveBeenCalledOnce();
|
|
377
|
+
const logged = (logger.error as any).mock.calls.find(
|
|
378
|
+
([message]: [string]) => message === '[Webhook] Event processing failed, releasing reservation'
|
|
379
|
+
);
|
|
380
|
+
const text: string = logged[1].error.message;
|
|
381
|
+
expect(text).toContain('2024-12-18.acacia');
|
|
382
|
+
expect(text).toContain('2025-02-24.acacia');
|
|
383
|
+
expect(text).toContain("webhook endpoint's API version");
|
|
384
|
+
expect(text).toContain('not STRIPE_API_VERSION');
|
|
385
|
+
expect(text).toContain('api_version=2025-02-24.acacia');
|
|
386
|
+
});
|
|
387
|
+
});
|