@donotdev/functions 0.1.44 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/lib/chunks/chunk-3F4BWKQD.js +22 -0
- package/lib/chunks/chunk-3F4BWKQD.js.map +7 -0
- package/lib/chunks/chunk-5IPULSUX.js +22 -0
- package/lib/chunks/chunk-5IPULSUX.js.map +7 -0
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.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-CXBSROEW.js +23 -0
- package/lib/chunks/chunk-CXBSROEW.js.map +7 -0
- package/lib/chunks/chunk-GYTCWMXV.js +22 -0
- package/lib/chunks/chunk-GYTCWMXV.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-LCDLG4VG.js +151 -0
- package/lib/chunks/chunk-LCDLG4VG.js.map +7 -0
- package/lib/chunks/chunk-MQANUSY3.js +22 -0
- package/lib/chunks/chunk-MQANUSY3.js.map +7 -0
- package/lib/chunks/chunk-OFQVO3FD.js +22 -0
- package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/chunk-US2VOP4S.js +22 -0
- package/lib/chunks/chunk-US2VOP4S.js.map +7 -0
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js +22 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js.map +7 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js +22 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js.map +7 -0
- package/lib/chunks/server-IQ5JNJOM.js +22 -0
- package/lib/chunks/server-IQ5JNJOM.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/index.d.ts +0 -0
- 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/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- 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/config/constants.d.ts +0 -0
- package/lib/firebase/config/index.d.ts +0 -0
- package/lib/firebase/config/secrets.d.ts +0 -0
- 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/index.d.ts +0 -0
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/index.d.ts +0 -0
- package/lib/firebase/index.d.ts +0 -0
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +0 -0
- package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
- package/lib/firebase/oauth/getConnections.d.ts +0 -0
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
- package/lib/firebase/scheduled/index.d.ts +0 -0
- package/lib/shared/ai/classifyAIError.d.ts +0 -0
- package/lib/shared/ai/costTracker.d.ts +0 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- 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/firestoreIdempotency.d.ts +13 -0
- 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 +21 -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/stripeClient.d.ts +45 -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 +29 -20
- package/lib/shared/email/createEmailRoute.d.ts +0 -0
- package/lib/shared/email/index.d.ts +0 -0
- package/lib/shared/email/provider.d.ts +0 -0
- package/lib/shared/email/resendProvider.d.ts +0 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +0 -0
- package/lib/shared/index.d.ts +0 -0
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +0 -0
- package/lib/shared/oauth/exchangeToken.d.ts +0 -0
- package/lib/shared/oauth/grantAccess.d.ts +0 -0
- package/lib/shared/oauth/index.d.ts +0 -0
- package/lib/shared/schema.d.ts +0 -0
- package/lib/shared/utils/detectFirestore.d.ts +0 -0
- package/lib/shared/utils/external/date.d.ts +0 -0
- package/lib/shared/utils/external/index.d.ts +0 -0
- package/lib/shared/utils/external/references.d.ts +0 -0
- package/lib/shared/utils/external/subscription.d.ts +0 -0
- package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/firebase.d.ts +0 -0
- package/lib/shared/utils/internal/idempotency.d.ts +0 -0
- package/lib/shared/utils/internal/index.d.ts +0 -0
- package/lib/shared/utils/internal/monitoring.d.ts +0 -0
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -8
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +0 -56
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +0 -0
- package/lib/supabase/auth/deleteAccount.d.ts +0 -0
- package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +0 -0
- package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/crud/list.d.ts +0 -8
- package/lib/supabase/crud/update.d.ts +0 -0
- package/lib/supabase/edgeFunction.d.ts +0 -0
- package/lib/supabase/email/createEmailFunction.d.ts +0 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +11 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/oauth/disconnect.d.ts +0 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
- package/lib/supabase/oauth/getConnections.d.ts +0 -0
- package/lib/supabase/oauth/index.d.ts +0 -0
- package/lib/supabase/oauth/refreshToken.d.ts +0 -0
- package/lib/supabase/registerCrudFunctions.d.ts +0 -0
- package/lib/supabase/utils/idempotency.d.ts +0 -0
- package/lib/supabase/utils/monitoring.d.ts +0 -0
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/ai/index.d.ts +0 -0
- 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/index.d.ts +0 -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/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/config/index.d.ts +0 -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/index.d.ts +0 -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.d.ts +0 -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/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- 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 +2 -3
- package/src/firebase/billing/changePlan.ts +3 -8
- package/src/firebase/billing/createCheckoutSession.ts +31 -61
- package/src/firebase/billing/createCustomerPortal.ts +5 -6
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -4
- package/src/firebase/billing/webhookHandler.ts +21 -5
- 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 -42
- package/src/shared/__tests__/logger.test.ts +31 -0
- 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 +3 -2
- 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 +370 -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/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +8 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +104 -168
- 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/stripeClient.ts +91 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +189 -386
- package/src/shared/logger.ts +4 -6
- 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/internal/validation.ts +0 -18
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +5 -99
- 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/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +11 -41
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -7
- 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/list.ts +2 -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 +4 -5
- package/src/vercel/api/billing/create-checkout-session.ts +43 -73
- package/src/vercel/api/billing/customer-portal.ts +3 -5
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +22 -7
- package/src/vercel/api/billing/webhook-handler.ts +32 -26
- 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
- package/lib/shared/ai/createAIHandler.d.ts +0 -39
- package/lib/shared/ai/providers/anthropic.d.ts +0 -12
- package/lib/shared/ai/providers/google.d.ts +0 -10
- package/lib/shared/ai/providers/index.d.ts +0 -23
- package/lib/shared/ai/providers/openai.d.ts +0 -10
- package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
|
@@ -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,10 @@ vi.mock('../../logger.js', () => ({
|
|
|
77
88
|
},
|
|
78
89
|
}));
|
|
79
90
|
|
|
80
|
-
|
|
81
|
-
import {
|
|
91
|
+
import { createInMemoryIdempotencyStore } from '../idempotency.js';
|
|
92
|
+
import type { IdempotencyStore } from '../idempotency.js';
|
|
82
93
|
import { processWebhook } from '../webhookHandler.js';
|
|
83
|
-
|
|
84
|
-
import type {
|
|
85
|
-
UpdateSubscriptionFn,
|
|
86
|
-
WebhookAuthProvider,
|
|
87
|
-
} from '../webhookHandler.js';
|
|
94
|
+
import type { BillingAuthProvider, UpdateSubscriptionFn } from '@donotdev/core/server';
|
|
88
95
|
|
|
89
96
|
// ---------------------------------------------------------------------------
|
|
90
97
|
// Shared test fixtures
|
|
@@ -113,8 +120,11 @@ const makeConfig = (overrides: Record<string, any> = {}) => ({
|
|
|
113
120
|
},
|
|
114
121
|
});
|
|
115
122
|
|
|
116
|
-
/** Build a minimal Stripe event object */
|
|
123
|
+
/** Build a minimal Stripe event object (Checkout Sessions default to payment_status 'paid') */
|
|
117
124
|
function makeEvent(type: string, dataObject: Record<string, any>): any {
|
|
125
|
+
if (type.startsWith('checkout.session.') && !('payment_status' in dataObject)) {
|
|
126
|
+
dataObject = { ...dataObject, payment_status: 'paid' };
|
|
127
|
+
}
|
|
118
128
|
return {
|
|
119
129
|
id: `evt_test_${Math.random().toString(36).slice(2)}`,
|
|
120
130
|
type,
|
|
@@ -122,7 +132,7 @@ function makeEvent(type: string, dataObject: Record<string, any>): any {
|
|
|
122
132
|
created: Date.now() / 1000,
|
|
123
133
|
livemode: false,
|
|
124
134
|
pending_webhooks: 1,
|
|
125
|
-
api_version: '
|
|
135
|
+
api_version: '2026-02-25.clover',
|
|
126
136
|
object: 'event',
|
|
127
137
|
};
|
|
128
138
|
}
|
|
@@ -131,7 +141,7 @@ function makeEvent(type: string, dataObject: Record<string, any>): any {
|
|
|
131
141
|
function makeStripe(eventOrFn?: any): any {
|
|
132
142
|
return {
|
|
133
143
|
webhooks: {
|
|
134
|
-
|
|
144
|
+
constructEventAsync: vi.fn(async (_body, _sig, _secret) => {
|
|
135
145
|
if (typeof eventOrFn === 'function') return eventOrFn();
|
|
136
146
|
return eventOrFn;
|
|
137
147
|
}),
|
|
@@ -143,7 +153,7 @@ function makeStripe(eventOrFn?: any): any {
|
|
|
143
153
|
}
|
|
144
154
|
|
|
145
155
|
/** Default mock auth provider */
|
|
146
|
-
function makeAuthProvider():
|
|
156
|
+
function makeAuthProvider(): BillingAuthProvider {
|
|
147
157
|
return {
|
|
148
158
|
getUser: vi.fn(async () => ({ customClaims: {} })),
|
|
149
159
|
setCustomUserClaims: vi.fn(async () => {}),
|
|
@@ -155,6 +165,12 @@ function makeUpdateSubscription(): UpdateSubscriptionFn {
|
|
|
155
165
|
return vi.fn(async () => {});
|
|
156
166
|
}
|
|
157
167
|
|
|
168
|
+
// Fresh store per test (beforeEach) so events are never pre-marked
|
|
169
|
+
let idempotencyStore: IdempotencyStore = createInMemoryIdempotencyStore();
|
|
170
|
+
function resetIdempotencyStore() {
|
|
171
|
+
idempotencyStore = createInMemoryIdempotencyStore();
|
|
172
|
+
}
|
|
173
|
+
|
|
158
174
|
const RAW_BODY = 'raw-body-bytes';
|
|
159
175
|
const SIGNATURE = 'stripe-sig-header';
|
|
160
176
|
const WEBHOOK_SECRET = 'whsec_test_secret';
|
|
@@ -172,7 +188,7 @@ async function callProcessWebhook({
|
|
|
172
188
|
stripe: any;
|
|
173
189
|
config?: any;
|
|
174
190
|
updateSubscription?: UpdateSubscriptionFn;
|
|
175
|
-
authProvider?:
|
|
191
|
+
authProvider?: BillingAuthProvider | null;
|
|
176
192
|
}) {
|
|
177
193
|
return processWebhook(
|
|
178
194
|
RAW_BODY,
|
|
@@ -181,7 +197,8 @@ async function callProcessWebhook({
|
|
|
181
197
|
stripe,
|
|
182
198
|
config,
|
|
183
199
|
updateSubscription,
|
|
184
|
-
authProvider
|
|
200
|
+
authProvider,
|
|
201
|
+
idempotencyStore
|
|
185
202
|
);
|
|
186
203
|
}
|
|
187
204
|
|
|
@@ -197,7 +214,7 @@ describe('processWebhook — signature verification', () => {
|
|
|
197
214
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
198
215
|
});
|
|
199
216
|
|
|
200
|
-
it('calls stripe.webhooks.
|
|
217
|
+
it('calls stripe.webhooks.constructEventAsync with raw body, signature and secret', async () => {
|
|
201
218
|
const event = makeEvent('checkout.session.completed', {
|
|
202
219
|
metadata: { userId: 'u1', billingConfigKey: 'pro_monthly' },
|
|
203
220
|
subscription: 'sub_abc',
|
|
@@ -210,17 +227,17 @@ describe('processWebhook — signature verification', () => {
|
|
|
210
227
|
|
|
211
228
|
await callProcessWebhook({ stripe, config, updateSubscription });
|
|
212
229
|
|
|
213
|
-
expect(stripe.webhooks.
|
|
230
|
+
expect(stripe.webhooks.constructEventAsync).toHaveBeenCalledWith(
|
|
214
231
|
RAW_BODY,
|
|
215
232
|
SIGNATURE,
|
|
216
233
|
WEBHOOK_SECRET
|
|
217
234
|
);
|
|
218
235
|
});
|
|
219
236
|
|
|
220
|
-
it('throws when
|
|
237
|
+
it('throws when constructEventAsync rejects (invalid signature)', async () => {
|
|
221
238
|
const stripe = {
|
|
222
239
|
webhooks: {
|
|
223
|
-
|
|
240
|
+
constructEventAsync: vi.fn(async () => {
|
|
224
241
|
throw new Error(
|
|
225
242
|
'No signatures found matching the expected signature'
|
|
226
243
|
);
|
|
@@ -327,6 +344,27 @@ describe('processWebhook — config validation', () => {
|
|
|
327
344
|
expect(validateStripeBackConfig).toHaveBeenCalledWith(config);
|
|
328
345
|
});
|
|
329
346
|
|
|
347
|
+
it('routes with the original config so hooks survive validation (valibot strips unknown keys)', async () => {
|
|
348
|
+
const { validateStripeBackConfig } = await import('@donotdev/core/server');
|
|
349
|
+
// Mimic valibot output: functions (hooks) are dropped from the parse result
|
|
350
|
+
(validateStripeBackConfig as any).mockImplementationOnce((c: unknown) =>
|
|
351
|
+
JSON.parse(JSON.stringify(c))
|
|
352
|
+
);
|
|
353
|
+
const onSubscriptionCreated = vi.fn(async () => {});
|
|
354
|
+
const event = makeEvent('checkout.session.completed', {
|
|
355
|
+
metadata: { userId: 'u_strip', billingConfigKey: 'pro_monthly' },
|
|
356
|
+
subscription: 'sub_strip',
|
|
357
|
+
customer: 'cus_strip',
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
await callProcessWebhook({
|
|
361
|
+
stripe: makeStripe(event),
|
|
362
|
+
config: makeConfig({ onSubscriptionCreated }),
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
expect(onSubscriptionCreated).toHaveBeenCalledOnce();
|
|
366
|
+
});
|
|
367
|
+
|
|
330
368
|
it('throws when validateStripeBackConfig throws', async () => {
|
|
331
369
|
const { validateStripeBackConfig } = await import('@donotdev/core/server');
|
|
332
370
|
(validateStripeBackConfig as any).mockImplementationOnce(() => {
|
|
@@ -1181,3 +1219,312 @@ describe('processWebhook — return value', () => {
|
|
|
1181
1219
|
});
|
|
1182
1220
|
});
|
|
1183
1221
|
});
|
|
1222
|
+
|
|
1223
|
+
// ---------------------------------------------------------------------------
|
|
1224
|
+
|
|
1225
|
+
describe('processWebhook — idempotency lifecycle', () => {
|
|
1226
|
+
beforeEach(() => {
|
|
1227
|
+
resetIdempotencyStore();
|
|
1228
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1229
|
+
vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
1230
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
1231
|
+
});
|
|
1232
|
+
|
|
1233
|
+
it('releases the reservation when routing throws, so the retry is processed', async () => {
|
|
1234
|
+
const event = makeEvent('checkout.session.completed', {
|
|
1235
|
+
metadata: { userId: 'u_retry', billingConfigKey: 'pro_monthly' },
|
|
1236
|
+
subscription: 'sub_retry',
|
|
1237
|
+
customer: 'cus_retry',
|
|
1238
|
+
});
|
|
1239
|
+
const failing = vi.fn(async () => {
|
|
1240
|
+
throw new Error('claims write failed');
|
|
1241
|
+
});
|
|
1242
|
+
|
|
1243
|
+
await expect(
|
|
1244
|
+
callProcessWebhook({ stripe: makeStripe(event), updateSubscription: failing })
|
|
1245
|
+
).rejects.toThrow();
|
|
1246
|
+
|
|
1247
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1248
|
+
const result = await callProcessWebhook({
|
|
1249
|
+
stripe: makeStripe(event),
|
|
1250
|
+
updateSubscription,
|
|
1251
|
+
});
|
|
1252
|
+
expect(result.message).toBe('Webhook processed');
|
|
1253
|
+
expect(updateSubscription).toHaveBeenCalledOnce();
|
|
1254
|
+
});
|
|
1255
|
+
|
|
1256
|
+
it('marks the event processed only after success, with the owner token', async () => {
|
|
1257
|
+
const markProcessed = vi.fn(async () => {});
|
|
1258
|
+
idempotencyStore = {
|
|
1259
|
+
reserve: vi.fn(async () => ({ state: 'reserved' as const, ownerToken: 'tok_1' })),
|
|
1260
|
+
markProcessed,
|
|
1261
|
+
release: vi.fn(async () => true),
|
|
1262
|
+
};
|
|
1263
|
+
const event = makeEvent('checkout.session.completed', {
|
|
1264
|
+
metadata: { userId: 'u_mark', billingConfigKey: 'pro_monthly' },
|
|
1265
|
+
subscription: 'sub_mark',
|
|
1266
|
+
customer: 'cus_mark',
|
|
1267
|
+
});
|
|
1268
|
+
|
|
1269
|
+
await callProcessWebhook({ stripe: makeStripe(event) });
|
|
1270
|
+
expect(markProcessed).toHaveBeenCalledWith(event.id, 'tok_1');
|
|
1271
|
+
});
|
|
1272
|
+
});
|
|
1273
|
+
|
|
1274
|
+
// ---------------------------------------------------------------------------
|
|
1275
|
+
|
|
1276
|
+
describe('event routing — StripeOrder', () => {
|
|
1277
|
+
const PAID_LINES = [
|
|
1278
|
+
{
|
|
1279
|
+
id: 'li_1',
|
|
1280
|
+
description: 'Serum 30ml',
|
|
1281
|
+
quantity: 24,
|
|
1282
|
+
amount_subtotal: 24000,
|
|
1283
|
+
amount_discount: 0,
|
|
1284
|
+
amount_tax: 4800,
|
|
1285
|
+
amount_total: 28800,
|
|
1286
|
+
price: {
|
|
1287
|
+
product: { id: 'prod_1', deleted: undefined, metadata: { productId: 'serum-30ml' } },
|
|
1288
|
+
},
|
|
1289
|
+
},
|
|
1290
|
+
];
|
|
1291
|
+
|
|
1292
|
+
function makeOrderConfig(hooks: Record<string, any> = {}) {
|
|
1293
|
+
return {
|
|
1294
|
+
...makeConfig(),
|
|
1295
|
+
shop_order: {
|
|
1296
|
+
type: 'StripeOrder' as const,
|
|
1297
|
+
name: 'Shop order',
|
|
1298
|
+
currency: 'eur',
|
|
1299
|
+
tax: { mode: 'manual' as const, taxRateIds: ['txr_fr_20'] },
|
|
1300
|
+
taxIdCollection: 'optional' as const,
|
|
1301
|
+
billingAddressCollection: 'required' as const,
|
|
1302
|
+
customerCreation: 'always' as const,
|
|
1303
|
+
invoiceCreation: true,
|
|
1304
|
+
resolveLineItems: vi.fn(),
|
|
1305
|
+
onOrderPaid: vi.fn(async () => {}),
|
|
1306
|
+
...hooks,
|
|
1307
|
+
},
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function makeOrderSession(overrides: Record<string, any> = {}) {
|
|
1312
|
+
return {
|
|
1313
|
+
id: 'cs_order_1',
|
|
1314
|
+
payment_status: 'paid',
|
|
1315
|
+
currency: 'eur',
|
|
1316
|
+
amount_subtotal: 24000,
|
|
1317
|
+
amount_total: 28800,
|
|
1318
|
+
total_details: { amount_discount: 0, amount_shipping: 0, amount_tax: 4800 },
|
|
1319
|
+
customer: 'cus_order',
|
|
1320
|
+
customer_details: {
|
|
1321
|
+
email: 'buyer@pro.example',
|
|
1322
|
+
name: 'Buyer',
|
|
1323
|
+
phone: null,
|
|
1324
|
+
business_name: 'Pro SARL',
|
|
1325
|
+
individual_name: null,
|
|
1326
|
+
address: { line1: '1 rue A', line2: null, postal_code: '75001', city: 'Paris', state: null, country: 'FR' },
|
|
1327
|
+
tax_exempt: 'none',
|
|
1328
|
+
tax_ids: [{ type: 'eu_vat', value: 'FR00123456789' }],
|
|
1329
|
+
},
|
|
1330
|
+
collected_information: null,
|
|
1331
|
+
invoice: 'in_order',
|
|
1332
|
+
payment_intent: 'pi_order',
|
|
1333
|
+
metadata: { userId: 'u_order', billingConfigKey: 'shop_order', orderId: 'ord_42' },
|
|
1334
|
+
...overrides,
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
function makeOrderStripe(event: any) {
|
|
1339
|
+
const stripe = makeStripe(event);
|
|
1340
|
+
stripe.checkout = {
|
|
1341
|
+
sessions: {
|
|
1342
|
+
listLineItems: vi.fn(() => ({
|
|
1343
|
+
async *[Symbol.asyncIterator]() {
|
|
1344
|
+
yield* PAID_LINES;
|
|
1345
|
+
},
|
|
1346
|
+
})),
|
|
1347
|
+
},
|
|
1348
|
+
};
|
|
1349
|
+
return stripe;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
beforeEach(() => {
|
|
1353
|
+
resetIdempotencyStore();
|
|
1354
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1355
|
+
vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
1356
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
1357
|
+
});
|
|
1358
|
+
|
|
1359
|
+
it('completed + paid → onOrderPaid with snapshot, paid lines and context; no subscription update', async () => {
|
|
1360
|
+
const config = makeOrderConfig();
|
|
1361
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1362
|
+
const stripe = makeOrderStripe(event);
|
|
1363
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1364
|
+
|
|
1365
|
+
await callProcessWebhook({ stripe, config, updateSubscription });
|
|
1366
|
+
|
|
1367
|
+
expect(stripe.checkout.sessions.listLineItems).toHaveBeenCalledWith(
|
|
1368
|
+
'cs_order_1',
|
|
1369
|
+
{ limit: 100, expand: ['data.price.product'] }
|
|
1370
|
+
);
|
|
1371
|
+
const onOrderPaid = config.shop_order.onOrderPaid;
|
|
1372
|
+
expect(onOrderPaid).toHaveBeenCalledOnce();
|
|
1373
|
+
const [snapshot, lines, ctx] = (onOrderPaid as any).mock.calls[0];
|
|
1374
|
+
expect(snapshot).toMatchObject({
|
|
1375
|
+
id: 'cs_order_1',
|
|
1376
|
+
paymentStatus: 'paid',
|
|
1377
|
+
amountTax: 4800,
|
|
1378
|
+
invoiceId: 'in_order',
|
|
1379
|
+
customer: {
|
|
1380
|
+
businessName: 'Pro SARL',
|
|
1381
|
+
taxIds: [{ type: 'eu_vat', value: 'FR00123456789' }],
|
|
1382
|
+
address: { postalCode: '75001', country: 'FR' },
|
|
1383
|
+
},
|
|
1384
|
+
});
|
|
1385
|
+
expect(lines).toEqual([
|
|
1386
|
+
{
|
|
1387
|
+
productId: 'serum-30ml',
|
|
1388
|
+
name: 'Serum 30ml',
|
|
1389
|
+
quantity: 24,
|
|
1390
|
+
amountSubtotal: 24000,
|
|
1391
|
+
amountDiscount: 0,
|
|
1392
|
+
amountTax: 4800,
|
|
1393
|
+
amountTotal: 28800,
|
|
1394
|
+
},
|
|
1395
|
+
]);
|
|
1396
|
+
expect(ctx).toEqual({
|
|
1397
|
+
userId: 'u_order',
|
|
1398
|
+
orderId: 'ord_42',
|
|
1399
|
+
billingConfigKey: 'shop_order',
|
|
1400
|
+
eventId: event.id,
|
|
1401
|
+
});
|
|
1402
|
+
expect(updateSubscription).not.toHaveBeenCalled();
|
|
1403
|
+
});
|
|
1404
|
+
|
|
1405
|
+
it('completed + unpaid (SEPA) → waits, onOrderPaid not called', async () => {
|
|
1406
|
+
const config = makeOrderConfig();
|
|
1407
|
+
const event = makeEvent(
|
|
1408
|
+
'checkout.session.completed',
|
|
1409
|
+
makeOrderSession({ payment_status: 'unpaid' })
|
|
1410
|
+
);
|
|
1411
|
+
|
|
1412
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1413
|
+
|
|
1414
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1415
|
+
});
|
|
1416
|
+
|
|
1417
|
+
it('async_payment_succeeded → onOrderPaid', async () => {
|
|
1418
|
+
const config = makeOrderConfig();
|
|
1419
|
+
const event = makeEvent(
|
|
1420
|
+
'checkout.session.async_payment_succeeded',
|
|
1421
|
+
makeOrderSession()
|
|
1422
|
+
);
|
|
1423
|
+
|
|
1424
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1425
|
+
|
|
1426
|
+
expect(config.shop_order.onOrderPaid).toHaveBeenCalledOnce();
|
|
1427
|
+
});
|
|
1428
|
+
|
|
1429
|
+
it('async_payment_failed → onOrderPaymentFailed', async () => {
|
|
1430
|
+
const onOrderPaymentFailed = vi.fn(async () => {});
|
|
1431
|
+
const config = makeOrderConfig({ onOrderPaymentFailed });
|
|
1432
|
+
const event = makeEvent(
|
|
1433
|
+
'checkout.session.async_payment_failed',
|
|
1434
|
+
makeOrderSession({ payment_status: 'unpaid' })
|
|
1435
|
+
);
|
|
1436
|
+
|
|
1437
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1438
|
+
|
|
1439
|
+
expect(onOrderPaymentFailed).toHaveBeenCalledOnce();
|
|
1440
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1441
|
+
});
|
|
1442
|
+
|
|
1443
|
+
it('expired → onOrderExpired', async () => {
|
|
1444
|
+
const onOrderExpired = vi.fn(async () => {});
|
|
1445
|
+
const config = makeOrderConfig({ onOrderExpired });
|
|
1446
|
+
const event = makeEvent(
|
|
1447
|
+
'checkout.session.expired',
|
|
1448
|
+
makeOrderSession({ payment_status: 'unpaid' })
|
|
1449
|
+
);
|
|
1450
|
+
|
|
1451
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1452
|
+
|
|
1453
|
+
expect(onOrderExpired).toHaveBeenCalledOnce();
|
|
1454
|
+
});
|
|
1455
|
+
|
|
1456
|
+
it('onOrderPaid failure rejects (Stripe retries) and the retry is processed once', async () => {
|
|
1457
|
+
const onOrderPaid = vi
|
|
1458
|
+
.fn()
|
|
1459
|
+
.mockRejectedValueOnce(new Error('db down'))
|
|
1460
|
+
.mockResolvedValueOnce(undefined);
|
|
1461
|
+
const config = makeOrderConfig({ onOrderPaid });
|
|
1462
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1463
|
+
|
|
1464
|
+
await expect(
|
|
1465
|
+
callProcessWebhook({ stripe: makeOrderStripe(event), config })
|
|
1466
|
+
).rejects.toThrow();
|
|
1467
|
+
await callProcessWebhook({ stripe: makeOrderStripe(event), config });
|
|
1468
|
+
const third = await callProcessWebhook({
|
|
1469
|
+
stripe: makeOrderStripe(event),
|
|
1470
|
+
config,
|
|
1471
|
+
});
|
|
1472
|
+
|
|
1473
|
+
expect(onOrderPaid).toHaveBeenCalledTimes(2);
|
|
1474
|
+
expect(third.message).toBe('Event already processed');
|
|
1475
|
+
});
|
|
1476
|
+
|
|
1477
|
+
it('rejects order events rendered with an API version older than collected_information', async () => {
|
|
1478
|
+
const config = makeOrderConfig();
|
|
1479
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1480
|
+
event.api_version = '2024-12-18.acacia';
|
|
1481
|
+
|
|
1482
|
+
await expect(
|
|
1483
|
+
callProcessWebhook({ stripe: makeOrderStripe(event), config })
|
|
1484
|
+
).rejects.toThrow();
|
|
1485
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1486
|
+
});
|
|
1487
|
+
|
|
1488
|
+
it('throws when the order session has no orderId', async () => {
|
|
1489
|
+
const config = makeOrderConfig();
|
|
1490
|
+
const event = makeEvent(
|
|
1491
|
+
'checkout.session.completed',
|
|
1492
|
+
makeOrderSession({ metadata: { userId: 'u_order', billingConfigKey: 'shop_order' } })
|
|
1493
|
+
);
|
|
1494
|
+
|
|
1495
|
+
await expect(
|
|
1496
|
+
callProcessWebhook({ stripe: makeOrderStripe(event), config })
|
|
1497
|
+
).rejects.toThrow();
|
|
1498
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1499
|
+
});
|
|
1500
|
+
|
|
1501
|
+
it('throws when a paid line carries no productId metadata', async () => {
|
|
1502
|
+
const config = makeOrderConfig();
|
|
1503
|
+
const event = makeEvent('checkout.session.completed', makeOrderSession());
|
|
1504
|
+
const stripe = makeOrderStripe(event);
|
|
1505
|
+
stripe.checkout.sessions.listLineItems = vi.fn(() => ({
|
|
1506
|
+
async *[Symbol.asyncIterator]() {
|
|
1507
|
+
yield { ...PAID_LINES[0], price: { product: { id: 'prod_x', metadata: {} } } };
|
|
1508
|
+
},
|
|
1509
|
+
}));
|
|
1510
|
+
|
|
1511
|
+
await expect(callProcessWebhook({ stripe, config })).rejects.toThrow();
|
|
1512
|
+
expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
|
|
1513
|
+
});
|
|
1514
|
+
|
|
1515
|
+
it('ignores async/expired events for non-order items', async () => {
|
|
1516
|
+
const updateSubscription = makeUpdateSubscription();
|
|
1517
|
+
const event = makeEvent('checkout.session.expired', {
|
|
1518
|
+
id: 'cs_sub',
|
|
1519
|
+
metadata: { userId: 'u_sub', billingConfigKey: 'pro_monthly' },
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
const result = await callProcessWebhook({
|
|
1523
|
+
stripe: makeStripe(event),
|
|
1524
|
+
updateSubscription,
|
|
1525
|
+
});
|
|
1526
|
+
|
|
1527
|
+
expect(result.message).toBe('Webhook processed');
|
|
1528
|
+
expect(updateSubscription).not.toHaveBeenCalled();
|
|
1529
|
+
});
|
|
1530
|
+
});
|
|
@@ -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
|
+
}
|