@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.
- 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
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
14
14
|
|
|
15
|
-
//
|
|
15
|
+
// Deprecated auto-detected store (0.1.x call path) must resolve to in-memory
|
|
16
16
|
vi.mock('../../utils/detectFirestore.js', () => ({
|
|
17
17
|
isFirestoreConfigured: vi.fn(() => false),
|
|
18
18
|
}));
|
|
@@ -47,6 +47,22 @@ vi.mock('@donotdev/core/server', () => ({
|
|
|
47
47
|
PRO: 'pro',
|
|
48
48
|
PREMIUM: 'premium',
|
|
49
49
|
},
|
|
50
|
+
DoNotDevError: class DoNotDevError extends Error {
|
|
51
|
+
code: string;
|
|
52
|
+
details?: Record<string, unknown>;
|
|
53
|
+
constructor(
|
|
54
|
+
message: string,
|
|
55
|
+
code = 'internal',
|
|
56
|
+
options?: { details?: Record<string, unknown> }
|
|
57
|
+
) {
|
|
58
|
+
super(message);
|
|
59
|
+
this.code = code;
|
|
60
|
+
this.details = options?.details;
|
|
61
|
+
this.name = 'DoNotDevError';
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
// Fixed ISO string for deterministic assertions
|
|
65
|
+
calculateSubscriptionEndDate: vi.fn(() => '2026-03-18T00:00:00.000Z'),
|
|
50
66
|
EntityHookError: class EntityHookError extends Error {
|
|
51
67
|
type: string;
|
|
52
68
|
constructor(message: string, type: string) {
|
|
@@ -62,11 +78,6 @@ vi.mock('@donotdev/firebase/server', () => ({
|
|
|
62
78
|
getFirebaseAdminFirestore: vi.fn(),
|
|
63
79
|
}));
|
|
64
80
|
|
|
65
|
-
// Mock the date utility — return a fixed ISO string for deterministic assertions
|
|
66
|
-
vi.mock('../../utils/external/date.js', () => ({
|
|
67
|
-
calculateSubscriptionEndDate: vi.fn(() => '2026-03-18T00:00:00.000Z'),
|
|
68
|
-
}));
|
|
69
|
-
|
|
70
81
|
// Mock logger to silence output in tests
|
|
71
82
|
vi.mock('../../logger.js', () => ({
|
|
72
83
|
logger: {
|
|
@@ -77,14 +88,13 @@ vi.mock('../../logger.js', () => ({
|
|
|
77
88
|
},
|
|
78
89
|
}));
|
|
79
90
|
|
|
80
|
-
|
|
81
|
-
|
|
91
|
+
import {
|
|
92
|
+
createInMemoryIdempotencyStore,
|
|
93
|
+
resetIdempotencyStore as resetLegacyIdempotencyStore,
|
|
94
|
+
} from '../idempotency.js';
|
|
95
|
+
import type { IdempotencyStore } from '../idempotency.js';
|
|
82
96
|
import { processWebhook } from '../webhookHandler.js';
|
|
83
|
-
|
|
84
|
-
import type {
|
|
85
|
-
UpdateSubscriptionFn,
|
|
86
|
-
WebhookAuthProvider,
|
|
87
|
-
} from '../webhookHandler.js';
|
|
97
|
+
import type { BillingAuthProvider, UpdateSubscriptionFn } from '@donotdev/core/server';
|
|
88
98
|
|
|
89
99
|
// ---------------------------------------------------------------------------
|
|
90
100
|
// Shared test fixtures
|
|
@@ -113,8 +123,11 @@ const makeConfig = (overrides: Record<string, any> = {}) => ({
|
|
|
113
123
|
},
|
|
114
124
|
});
|
|
115
125
|
|
|
116
|
-
/** Build a minimal Stripe event object */
|
|
126
|
+
/** Build a minimal Stripe event object (Checkout Sessions default to payment_status 'paid') */
|
|
117
127
|
function makeEvent(type: string, dataObject: Record<string, any>): any {
|
|
128
|
+
if (type.startsWith('checkout.session.') && !('payment_status' in dataObject)) {
|
|
129
|
+
dataObject = { ...dataObject, payment_status: 'paid' };
|
|
130
|
+
}
|
|
118
131
|
return {
|
|
119
132
|
id: `evt_test_${Math.random().toString(36).slice(2)}`,
|
|
120
133
|
type,
|
|
@@ -122,7 +135,7 @@ function makeEvent(type: string, dataObject: Record<string, any>): any {
|
|
|
122
135
|
created: Date.now() / 1000,
|
|
123
136
|
livemode: false,
|
|
124
137
|
pending_webhooks: 1,
|
|
125
|
-
api_version: '
|
|
138
|
+
api_version: '2026-02-25.clover',
|
|
126
139
|
object: 'event',
|
|
127
140
|
};
|
|
128
141
|
}
|
|
@@ -131,7 +144,7 @@ function makeEvent(type: string, dataObject: Record<string, any>): any {
|
|
|
131
144
|
function makeStripe(eventOrFn?: any): any {
|
|
132
145
|
return {
|
|
133
146
|
webhooks: {
|
|
134
|
-
|
|
147
|
+
constructEventAsync: vi.fn(async (_body, _sig, _secret) => {
|
|
135
148
|
if (typeof eventOrFn === 'function') return eventOrFn();
|
|
136
149
|
return eventOrFn;
|
|
137
150
|
}),
|
|
@@ -143,7 +156,7 @@ function makeStripe(eventOrFn?: any): any {
|
|
|
143
156
|
}
|
|
144
157
|
|
|
145
158
|
/** Default mock auth provider */
|
|
146
|
-
function makeAuthProvider():
|
|
159
|
+
function makeAuthProvider(): BillingAuthProvider {
|
|
147
160
|
return {
|
|
148
161
|
getUser: vi.fn(async () => ({ customClaims: {} })),
|
|
149
162
|
setCustomUserClaims: vi.fn(async () => {}),
|
|
@@ -155,6 +168,12 @@ function makeUpdateSubscription(): UpdateSubscriptionFn {
|
|
|
155
168
|
return vi.fn(async () => {});
|
|
156
169
|
}
|
|
157
170
|
|
|
171
|
+
// Fresh store per test (beforeEach) so events are never pre-marked
|
|
172
|
+
let idempotencyStore: IdempotencyStore = createInMemoryIdempotencyStore();
|
|
173
|
+
function resetIdempotencyStore() {
|
|
174
|
+
idempotencyStore = createInMemoryIdempotencyStore();
|
|
175
|
+
}
|
|
176
|
+
|
|
158
177
|
const RAW_BODY = 'raw-body-bytes';
|
|
159
178
|
const SIGNATURE = 'stripe-sig-header';
|
|
160
179
|
const WEBHOOK_SECRET = 'whsec_test_secret';
|
|
@@ -172,7 +191,7 @@ async function callProcessWebhook({
|
|
|
172
191
|
stripe: any;
|
|
173
192
|
config?: any;
|
|
174
193
|
updateSubscription?: UpdateSubscriptionFn;
|
|
175
|
-
authProvider?:
|
|
194
|
+
authProvider?: BillingAuthProvider | null;
|
|
176
195
|
}) {
|
|
177
196
|
return processWebhook(
|
|
178
197
|
RAW_BODY,
|
|
@@ -181,7 +200,8 @@ async function callProcessWebhook({
|
|
|
181
200
|
stripe,
|
|
182
201
|
config,
|
|
183
202
|
updateSubscription,
|
|
184
|
-
authProvider
|
|
203
|
+
authProvider,
|
|
204
|
+
idempotencyStore
|
|
185
205
|
);
|
|
186
206
|
}
|
|
187
207
|
|
|
@@ -197,7 +217,7 @@ describe('processWebhook — signature verification', () => {
|
|
|
197
217
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
198
218
|
});
|
|
199
219
|
|
|
200
|
-
it('calls stripe.webhooks.
|
|
220
|
+
it('calls stripe.webhooks.constructEventAsync with raw body, signature and secret', async () => {
|
|
201
221
|
const event = makeEvent('checkout.session.completed', {
|
|
202
222
|
metadata: { userId: 'u1', billingConfigKey: 'pro_monthly' },
|
|
203
223
|
subscription: 'sub_abc',
|
|
@@ -210,17 +230,17 @@ describe('processWebhook — signature verification', () => {
|
|
|
210
230
|
|
|
211
231
|
await callProcessWebhook({ stripe, config, updateSubscription });
|
|
212
232
|
|
|
213
|
-
expect(stripe.webhooks.
|
|
233
|
+
expect(stripe.webhooks.constructEventAsync).toHaveBeenCalledWith(
|
|
214
234
|
RAW_BODY,
|
|
215
235
|
SIGNATURE,
|
|
216
236
|
WEBHOOK_SECRET
|
|
217
237
|
);
|
|
218
238
|
});
|
|
219
239
|
|
|
220
|
-
it('throws when
|
|
240
|
+
it('throws when constructEventAsync rejects (invalid signature)', async () => {
|
|
221
241
|
const stripe = {
|
|
222
242
|
webhooks: {
|
|
223
|
-
|
|
243
|
+
constructEventAsync: vi.fn(async () => {
|
|
224
244
|
throw new Error(
|
|
225
245
|
'No signatures found matching the expected signature'
|
|
226
246
|
);
|
|
@@ -327,6 +347,27 @@ describe('processWebhook — config validation', () => {
|
|
|
327
347
|
expect(validateStripeBackConfig).toHaveBeenCalledWith(config);
|
|
328
348
|
});
|
|
329
349
|
|
|
350
|
+
it('routes with the original config so hooks survive validation (valibot strips unknown keys)', async () => {
|
|
351
|
+
const { validateStripeBackConfig } = await import('@donotdev/core/server');
|
|
352
|
+
// Mimic valibot output: functions (hooks) are dropped from the parse result
|
|
353
|
+
(validateStripeBackConfig as any).mockImplementationOnce((c: unknown) =>
|
|
354
|
+
JSON.parse(JSON.stringify(c))
|
|
355
|
+
);
|
|
356
|
+
const onSubscriptionCreated = vi.fn(async () => {});
|
|
357
|
+
const event = makeEvent('checkout.session.completed', {
|
|
358
|
+
metadata: { userId: 'u_strip', billingConfigKey: 'pro_monthly' },
|
|
359
|
+
subscription: 'sub_strip',
|
|
360
|
+
customer: 'cus_strip',
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
await callProcessWebhook({
|
|
364
|
+
stripe: makeStripe(event),
|
|
365
|
+
config: makeConfig({ onSubscriptionCreated }),
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
expect(onSubscriptionCreated).toHaveBeenCalledOnce();
|
|
369
|
+
});
|
|
370
|
+
|
|
330
371
|
it('throws when validateStripeBackConfig throws', async () => {
|
|
331
372
|
const { validateStripeBackConfig } = await import('@donotdev/core/server');
|
|
332
373
|
(validateStripeBackConfig as any).mockImplementationOnce(() => {
|
|
@@ -1181,3 +1222,346 @@ describe('processWebhook — return value', () => {
|
|
|
1181
1222
|
});
|
|
1182
1223
|
});
|
|
1183
1224
|
});
|
|
1225
|
+
|
|
1226
|
+
// ---------------------------------------------------------------------------
|
|
1227
|
+
|
|
1228
|
+
describe('processWebhook — idempotency lifecycle', () => {
|
|
1229
|
+
beforeEach(() => {
|
|
1230
|
+
resetIdempotencyStore();
|
|
1231
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1232
|
+
vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
1233
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
1234
|
+
});
|
|
1235
|
+
|
|
1236
|
+
it('releases the reservation when routing throws, so the retry is processed', async () => {
|
|
1237
|
+
const event = makeEvent('checkout.session.completed', {
|
|
1238
|
+
metadata: { userId: 'u_retry', billingConfigKey: 'pro_monthly' },
|
|
1239
|
+
subscription: 'sub_retry',
|
|
1240
|
+
customer: 'cus_retry',
|
|
1241
|
+
});
|
|
1242
|
+
const failing = vi.fn(async () => {
|
|
1243
|
+
throw new Error('claims write failed');
|
|
1244
|
+
});
|
|
1245
|
+
|
|
1246
|
+
await expect(
|
|
1247
|
+
callProcessWebhook({ stripe: makeStripe(event), updateSubscription: failing })
|
|
1248
|
+
).rejects.toThrow();
|
|
1249
|
+
|
|
1250
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1251
|
+
const result = await callProcessWebhook({
|
|
1252
|
+
stripe: makeStripe(event),
|
|
1253
|
+
updateSubscription,
|
|
1254
|
+
});
|
|
1255
|
+
expect(result.message).toBe('Webhook processed');
|
|
1256
|
+
expect(updateSubscription).toHaveBeenCalledOnce();
|
|
1257
|
+
});
|
|
1258
|
+
|
|
1259
|
+
it('marks the event processed only after success, with the owner token', async () => {
|
|
1260
|
+
const markProcessed = vi.fn(async () => {});
|
|
1261
|
+
idempotencyStore = {
|
|
1262
|
+
reserve: vi.fn(async () => ({ state: 'reserved' as const, ownerToken: 'tok_1' })),
|
|
1263
|
+
markProcessed,
|
|
1264
|
+
release: vi.fn(async () => true),
|
|
1265
|
+
};
|
|
1266
|
+
const event = makeEvent('checkout.session.completed', {
|
|
1267
|
+
metadata: { userId: 'u_mark', billingConfigKey: 'pro_monthly' },
|
|
1268
|
+
subscription: 'sub_mark',
|
|
1269
|
+
customer: 'cus_mark',
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1272
|
+
await callProcessWebhook({ stripe: makeStripe(event) });
|
|
1273
|
+
expect(markProcessed).toHaveBeenCalledWith(event.id, 'tok_1');
|
|
1274
|
+
});
|
|
1275
|
+
});
|
|
1276
|
+
|
|
1277
|
+
// ---------------------------------------------------------------------------
|
|
1278
|
+
|
|
1279
|
+
describe('event routing — StripeOrder', () => {
|
|
1280
|
+
const PAID_LINES = [
|
|
1281
|
+
{
|
|
1282
|
+
id: 'li_1',
|
|
1283
|
+
description: 'Serum 30ml',
|
|
1284
|
+
quantity: 24,
|
|
1285
|
+
amount_subtotal: 24000,
|
|
1286
|
+
amount_discount: 0,
|
|
1287
|
+
amount_tax: 4800,
|
|
1288
|
+
amount_total: 28800,
|
|
1289
|
+
price: {
|
|
1290
|
+
product: { id: 'prod_1', deleted: undefined, metadata: { productId: 'serum-30ml' } },
|
|
1291
|
+
},
|
|
1292
|
+
},
|
|
1293
|
+
];
|
|
1294
|
+
|
|
1295
|
+
function makeOrderConfig(hooks: Record<string, any> = {}) {
|
|
1296
|
+
return {
|
|
1297
|
+
...makeConfig(),
|
|
1298
|
+
shop_order: {
|
|
1299
|
+
type: 'StripeOrder' as const,
|
|
1300
|
+
name: 'Shop order',
|
|
1301
|
+
currency: 'eur',
|
|
1302
|
+
tax: { mode: 'manual' as const, taxRateIds: ['txr_fr_20'] },
|
|
1303
|
+
taxIdCollection: 'optional' as const,
|
|
1304
|
+
billingAddressCollection: 'required' as const,
|
|
1305
|
+
customerCreation: 'always' as const,
|
|
1306
|
+
invoiceCreation: true,
|
|
1307
|
+
resolveLineItems: vi.fn(),
|
|
1308
|
+
onOrderPaid: vi.fn(async () => {}),
|
|
1309
|
+
...hooks,
|
|
1310
|
+
},
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
function makeOrderSession(overrides: Record<string, any> = {}) {
|
|
1315
|
+
return {
|
|
1316
|
+
id: 'cs_order_1',
|
|
1317
|
+
payment_status: 'paid',
|
|
1318
|
+
currency: 'eur',
|
|
1319
|
+
amount_subtotal: 24000,
|
|
1320
|
+
amount_total: 28800,
|
|
1321
|
+
total_details: { amount_discount: 0, amount_shipping: 0, amount_tax: 4800 },
|
|
1322
|
+
customer: 'cus_order',
|
|
1323
|
+
customer_details: {
|
|
1324
|
+
email: 'buyer@pro.example',
|
|
1325
|
+
name: 'Buyer',
|
|
1326
|
+
phone: null,
|
|
1327
|
+
business_name: 'Pro SARL',
|
|
1328
|
+
individual_name: null,
|
|
1329
|
+
address: { line1: '1 rue A', line2: null, postal_code: '75001', city: 'Paris', state: null, country: 'FR' },
|
|
1330
|
+
tax_exempt: 'none',
|
|
1331
|
+
tax_ids: [{ type: 'eu_vat', value: 'FR00123456789' }],
|
|
1332
|
+
},
|
|
1333
|
+
collected_information: null,
|
|
1334
|
+
invoice: 'in_order',
|
|
1335
|
+
payment_intent: 'pi_order',
|
|
1336
|
+
metadata: { userId: 'u_order', billingConfigKey: 'shop_order', orderId: 'ord_42' },
|
|
1337
|
+
...overrides,
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
function makeOrderStripe(event: any) {
|
|
1342
|
+
const stripe = makeStripe(event);
|
|
1343
|
+
stripe.checkout = {
|
|
1344
|
+
sessions: {
|
|
1345
|
+
listLineItems: vi.fn(() => ({
|
|
1346
|
+
async *[Symbol.asyncIterator]() {
|
|
1347
|
+
yield* PAID_LINES;
|
|
1348
|
+
},
|
|
1349
|
+
})),
|
|
1350
|
+
},
|
|
1351
|
+
};
|
|
1352
|
+
return stripe;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
beforeEach(() => {
|
|
1356
|
+
resetIdempotencyStore();
|
|
1357
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1358
|
+
vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
1359
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
1360
|
+
});
|
|
1361
|
+
|
|
1362
|
+
it('completed + paid → onOrderPaid with snapshot, paid lines and context; no subscription update', async () => {
|
|
1363
|
+
const config = makeOrderConfig();
|
|
1364
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1365
|
+
const stripe = makeOrderStripe(event);
|
|
1366
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1367
|
+
|
|
1368
|
+
await callProcessWebhook({ stripe, config, updateSubscription });
|
|
1369
|
+
|
|
1370
|
+
expect(stripe.checkout.sessions.listLineItems).toHaveBeenCalledWith(
|
|
1371
|
+
'cs_order_1',
|
|
1372
|
+
{ limit: 100, expand: ['data.price.product'] }
|
|
1373
|
+
);
|
|
1374
|
+
const onOrderPaid = config.shop_order.onOrderPaid;
|
|
1375
|
+
expect(onOrderPaid).toHaveBeenCalledOnce();
|
|
1376
|
+
const [snapshot, lines, ctx] = (onOrderPaid as any).mock.calls[0];
|
|
1377
|
+
expect(snapshot).toMatchObject({
|
|
1378
|
+
id: 'cs_order_1',
|
|
1379
|
+
paymentStatus: 'paid',
|
|
1380
|
+
amountTax: 4800,
|
|
1381
|
+
invoiceId: 'in_order',
|
|
1382
|
+
customer: {
|
|
1383
|
+
businessName: 'Pro SARL',
|
|
1384
|
+
taxIds: [{ type: 'eu_vat', value: 'FR00123456789' }],
|
|
1385
|
+
address: { postalCode: '75001', country: 'FR' },
|
|
1386
|
+
},
|
|
1387
|
+
});
|
|
1388
|
+
expect(lines).toEqual([
|
|
1389
|
+
{
|
|
1390
|
+
productId: 'serum-30ml',
|
|
1391
|
+
name: 'Serum 30ml',
|
|
1392
|
+
quantity: 24,
|
|
1393
|
+
amountSubtotal: 24000,
|
|
1394
|
+
amountDiscount: 0,
|
|
1395
|
+
amountTax: 4800,
|
|
1396
|
+
amountTotal: 28800,
|
|
1397
|
+
},
|
|
1398
|
+
]);
|
|
1399
|
+
expect(ctx).toEqual({
|
|
1400
|
+
userId: 'u_order',
|
|
1401
|
+
orderId: 'ord_42',
|
|
1402
|
+
billingConfigKey: 'shop_order',
|
|
1403
|
+
eventId: event.id,
|
|
1404
|
+
});
|
|
1405
|
+
expect(updateSubscription).not.toHaveBeenCalled();
|
|
1406
|
+
});
|
|
1407
|
+
|
|
1408
|
+
it('completed + unpaid (SEPA) → waits, onOrderPaid not called', async () => {
|
|
1409
|
+
const config = makeOrderConfig();
|
|
1410
|
+
const event = makeEvent(
|
|
1411
|
+
'checkout.session.completed',
|
|
1412
|
+
makeOrderSession({ payment_status: 'unpaid' })
|
|
1413
|
+
);
|
|
1414
|
+
|
|
1415
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1416
|
+
|
|
1417
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1418
|
+
});
|
|
1419
|
+
|
|
1420
|
+
it('async_payment_succeeded → onOrderPaid', async () => {
|
|
1421
|
+
const config = makeOrderConfig();
|
|
1422
|
+
const event = makeEvent(
|
|
1423
|
+
'checkout.session.async_payment_succeeded',
|
|
1424
|
+
makeOrderSession()
|
|
1425
|
+
);
|
|
1426
|
+
|
|
1427
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1428
|
+
|
|
1429
|
+
expect(config.shop_order.onOrderPaid).toHaveBeenCalledOnce();
|
|
1430
|
+
});
|
|
1431
|
+
|
|
1432
|
+
it('async_payment_failed → onOrderPaymentFailed', async () => {
|
|
1433
|
+
const onOrderPaymentFailed = vi.fn(async () => {});
|
|
1434
|
+
const config = makeOrderConfig({ onOrderPaymentFailed });
|
|
1435
|
+
const event = makeEvent(
|
|
1436
|
+
'checkout.session.async_payment_failed',
|
|
1437
|
+
makeOrderSession({ payment_status: 'unpaid' })
|
|
1438
|
+
);
|
|
1439
|
+
|
|
1440
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1441
|
+
|
|
1442
|
+
expect(onOrderPaymentFailed).toHaveBeenCalledOnce();
|
|
1443
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1444
|
+
});
|
|
1445
|
+
|
|
1446
|
+
it('expired → onOrderExpired', async () => {
|
|
1447
|
+
const onOrderExpired = vi.fn(async () => {});
|
|
1448
|
+
const config = makeOrderConfig({ onOrderExpired });
|
|
1449
|
+
const event = makeEvent(
|
|
1450
|
+
'checkout.session.expired',
|
|
1451
|
+
makeOrderSession({ payment_status: 'unpaid' })
|
|
1452
|
+
);
|
|
1453
|
+
|
|
1454
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1455
|
+
|
|
1456
|
+
expect(onOrderExpired).toHaveBeenCalledOnce();
|
|
1457
|
+
});
|
|
1458
|
+
|
|
1459
|
+
it('onOrderPaid failure rejects (Stripe retries) and the retry is processed once', async () => {
|
|
1460
|
+
const onOrderPaid = vi
|
|
1461
|
+
.fn()
|
|
1462
|
+
.mockRejectedValueOnce(new Error('db down'))
|
|
1463
|
+
.mockResolvedValueOnce(undefined);
|
|
1464
|
+
const config = makeOrderConfig({ onOrderPaid });
|
|
1465
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1466
|
+
|
|
1467
|
+
await expect(
|
|
1468
|
+
callProcessWebhook({ stripe: makeOrderStripe(event), config })
|
|
1469
|
+
).rejects.toThrow();
|
|
1470
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1471
|
+
const third = await callProcessWebhook({
|
|
1472
|
+
stripe: makeOrderStripe(event),
|
|
1473
|
+
config,
|
|
1474
|
+
});
|
|
1475
|
+
|
|
1476
|
+
expect(onOrderPaid).toHaveBeenCalledTimes(2);
|
|
1477
|
+
expect(third.message).toBe('Event already processed');
|
|
1478
|
+
});
|
|
1479
|
+
|
|
1480
|
+
it('rejects order events rendered with an API version older than collected_information', async () => {
|
|
1481
|
+
const config = makeOrderConfig();
|
|
1482
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1483
|
+
event.api_version = '2024-12-18.acacia';
|
|
1484
|
+
|
|
1485
|
+
await expect(
|
|
1486
|
+
callProcessWebhook({ stripe: makeOrderStripe(event), config })
|
|
1487
|
+
).rejects.toThrow();
|
|
1488
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1489
|
+
});
|
|
1490
|
+
|
|
1491
|
+
it('throws when the order session has no orderId', async () => {
|
|
1492
|
+
const config = makeOrderConfig();
|
|
1493
|
+
const event = makeEvent(
|
|
1494
|
+
'checkout.session.completed',
|
|
1495
|
+
makeOrderSession({ metadata: { userId: 'u_order', billingConfigKey: 'shop_order' } })
|
|
1496
|
+
);
|
|
1497
|
+
|
|
1498
|
+
await expect(
|
|
1499
|
+
callProcessWebhook({ stripe: makeOrderStripe(event), config })
|
|
1500
|
+
).rejects.toThrow();
|
|
1501
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1502
|
+
});
|
|
1503
|
+
|
|
1504
|
+
it('throws when a paid line carries no productId metadata', async () => {
|
|
1505
|
+
const config = makeOrderConfig();
|
|
1506
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1507
|
+
const stripe = makeOrderStripe(event);
|
|
1508
|
+
stripe.checkout.sessions.listLineItems = vi.fn(() => ({
|
|
1509
|
+
async *[Symbol.asyncIterator]() {
|
|
1510
|
+
yield { ...PAID_LINES[0], price: { product: { id: 'prod_x', metadata: {} } } };
|
|
1511
|
+
},
|
|
1512
|
+
}));
|
|
1513
|
+
|
|
1514
|
+
await expect(callProcessWebhook({ stripe, config })).rejects.toThrow();
|
|
1515
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1516
|
+
});
|
|
1517
|
+
|
|
1518
|
+
it('ignores async/expired events for non-order items', async () => {
|
|
1519
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1520
|
+
const event = makeEvent('checkout.session.expired', {
|
|
1521
|
+
id: 'cs_sub',
|
|
1522
|
+
metadata: { userId: 'u_sub', billingConfigKey: 'pro_monthly' },
|
|
1523
|
+
});
|
|
1524
|
+
|
|
1525
|
+
const result = await callProcessWebhook({
|
|
1526
|
+
stripe: makeStripe(event),
|
|
1527
|
+
updateSubscription,
|
|
1528
|
+
});
|
|
1529
|
+
|
|
1530
|
+
expect(result.message).toBe('Webhook processed');
|
|
1531
|
+
expect(updateSubscription).not.toHaveBeenCalled();
|
|
1532
|
+
});
|
|
1533
|
+
});
|
|
1534
|
+
|
|
1535
|
+
// ---------------------------------------------------------------------------
|
|
1536
|
+
|
|
1537
|
+
describe('processWebhook — 0.1.x call without a store', () => {
|
|
1538
|
+
beforeEach(() => {
|
|
1539
|
+
resetLegacyIdempotencyStore();
|
|
1540
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1541
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
1542
|
+
});
|
|
1543
|
+
|
|
1544
|
+
it('falls back to the deprecated auto-detected store and still deduplicates', async () => {
|
|
1545
|
+
const event = makeEvent('checkout.session.completed', {
|
|
1546
|
+
metadata: { userId: 'u_legacy', billingConfigKey: 'pro_monthly' },
|
|
1547
|
+
subscription: 'sub_legacy',
|
|
1548
|
+
customer: 'cus_legacy',
|
|
1549
|
+
});
|
|
1550
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1551
|
+
const call = () =>
|
|
1552
|
+
processWebhook(
|
|
1553
|
+
RAW_BODY,
|
|
1554
|
+
SIGNATURE,
|
|
1555
|
+
WEBHOOK_SECRET,
|
|
1556
|
+
makeStripe(event),
|
|
1557
|
+
makeConfig(),
|
|
1558
|
+
updateSubscription,
|
|
1559
|
+
makeAuthProvider()
|
|
1560
|
+
);
|
|
1561
|
+
|
|
1562
|
+
await call();
|
|
1563
|
+
const second = await call();
|
|
1564
|
+
expect(second.message).toBe('Event already processed');
|
|
1565
|
+
expect(updateSubscription).toHaveBeenCalledOnce();
|
|
1566
|
+
});
|
|
1567
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/apiVersion.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Stripe API version pin
|
|
5
|
+
* @description Single source of truth for the Stripe API version the framework
|
|
6
|
+
* reads. The subscription handlers still read pre-basil fields
|
|
7
|
+
* (`invoice.subscription`, `subscription.current_period_end`), so the pin stays
|
|
8
|
+
* on acacia; StripeOrder needs `collected_information` (2025-02-24.acacia).
|
|
9
|
+
*
|
|
10
|
+
* @version 0.2.0
|
|
11
|
+
* @since 0.2.0
|
|
12
|
+
* @author AMBROISE PARK Consulting
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Stripe API version used by `initStripe` when `STRIPE_API_VERSION` is unset,
|
|
17
|
+
* and the oldest version whose Checkout Session payload StripeOrder can read.
|
|
18
|
+
* Webhook event payloads follow the webhook ENDPOINT's API version (set when
|
|
19
|
+
* the endpoint is created in the Dashboard or API), not this value.
|
|
20
|
+
*
|
|
21
|
+
* @version 0.2.0
|
|
22
|
+
* @since 0.2.0
|
|
23
|
+
* @author AMBROISE PARK Consulting
|
|
24
|
+
*/
|
|
25
|
+
export const STRIPE_API_VERSION_PIN = '2025-02-24.acacia';
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/checkoutPrice.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Single-price checkout (StripePayment / StripeSubscription)
|
|
5
|
+
* @description 0.1.x pricing rules and the 0.1.x params → Stripe params mapping
|
|
6
|
+
* used by `createCheckoutAlgorithm`.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.2.0
|
|
9
|
+
* @since 0.2.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type Stripe from 'stripe';
|
|
14
|
+
|
|
15
|
+
import type {
|
|
16
|
+
CheckoutMode,
|
|
17
|
+
CheckoutSessionParams,
|
|
18
|
+
CreateCheckoutSessionRequest,
|
|
19
|
+
StripePaymentBackItem,
|
|
20
|
+
StripeSubscriptionBackItem,
|
|
21
|
+
} from '@donotdev/core/server';
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
/** Price resolved for a single-price item (0.1.x rules). */
|
|
25
|
+
export interface PricePlan {
|
|
26
|
+
/** Fixed price charged; undefined for dynamic pricing */
|
|
27
|
+
priceId?: string;
|
|
28
|
+
/** 0.1.x dynamic pricing (client unitAmount + productName) */
|
|
29
|
+
dynamic: boolean;
|
|
30
|
+
mode: CheckoutMode;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must
|
|
35
|
+
* match the config priceId when set), else 0.1.x dynamic pricing capped by
|
|
36
|
+
* `maxUnitAmount`, else the back-config priceId.
|
|
37
|
+
*/
|
|
38
|
+
export function resolvePricePlan(
|
|
39
|
+
item: StripePaymentBackItem | StripeSubscriptionBackItem,
|
|
40
|
+
request: CreateCheckoutSessionRequest
|
|
41
|
+
): PricePlan {
|
|
42
|
+
const { billingConfigKey: key, priceId, unitAmount, productName } = request;
|
|
43
|
+
const [line] = request.lineItems;
|
|
44
|
+
if (
|
|
45
|
+
request.lineItems.length !== 1 ||
|
|
46
|
+
!line ||
|
|
47
|
+
line.productId !== key ||
|
|
48
|
+
line.quantity !== 1
|
|
49
|
+
) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`'${key}' is a single-price item: lineItems must be [{ productId: '${key}', quantity: 1 }]`
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const dynamic = !priceId && !!unitAmount && !!productName;
|
|
56
|
+
const mode: CheckoutMode =
|
|
57
|
+
request.mode ?? (item.type === 'StripeSubscription' ? 'subscription' : 'payment');
|
|
58
|
+
|
|
59
|
+
if (priceId) {
|
|
60
|
+
if (item.priceId && item.priceId !== priceId) {
|
|
61
|
+
throw new Error('Price ID mismatch with configuration');
|
|
62
|
+
}
|
|
63
|
+
return { priceId, dynamic, mode };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (dynamic) {
|
|
67
|
+
if (mode === 'subscription') {
|
|
68
|
+
throw new Error(
|
|
69
|
+
'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
if (!item.maxUnitAmount) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
'Dynamic pricing requires maxUnitAmount in billing config for security'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (unitAmount! > item.maxUnitAmount) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`Unit amount ${unitAmount} exceeds maximum allowed: ${item.maxUnitAmount}`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
if (unitAmount! < 100) {
|
|
83
|
+
throw new Error('Unit amount must be at least 100 cents (1.00)');
|
|
84
|
+
}
|
|
85
|
+
return { dynamic, mode };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (!item.priceId) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
`'${key}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
return { priceId: item.priceId, dynamic, mode };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 0.1.x params → Stripe params (what the 0.1.x Firebase/Supabase providers sent). */
|
|
97
|
+
export function toStripeSessionParams(
|
|
98
|
+
params: CheckoutSessionParams
|
|
99
|
+
): Stripe.Checkout.SessionCreateParams {
|
|
100
|
+
const mode = params.mode || 'payment';
|
|
101
|
+
return {
|
|
102
|
+
mode,
|
|
103
|
+
line_items: [
|
|
104
|
+
params.priceId
|
|
105
|
+
? { price: params.priceId, quantity: 1 }
|
|
106
|
+
: {
|
|
107
|
+
price_data: {
|
|
108
|
+
currency: params.currency || 'eur',
|
|
109
|
+
unit_amount: params.unitAmount!,
|
|
110
|
+
product_data: { name: params.productName! },
|
|
111
|
+
},
|
|
112
|
+
quantity: 1,
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
allow_promotion_codes: params.allowPromotionCodes,
|
|
116
|
+
success_url: params.successUrl,
|
|
117
|
+
cancel_url: params.cancelUrl,
|
|
118
|
+
customer_email: params.customerEmail,
|
|
119
|
+
metadata: params.metadata,
|
|
120
|
+
// Renewal/cancellation events read the subscription's own metadata
|
|
121
|
+
...(mode === 'subscription' && {
|
|
122
|
+
subscription_data: { metadata: params.metadata },
|
|
123
|
+
}),
|
|
124
|
+
};
|
|
125
|
+
}
|