@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
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/orderWebhook.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview StripeOrder webhook handling
|
|
5
|
+
* @description Maps Checkout Session events of one-time, multi-line orders to the
|
|
6
|
+
* app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
|
|
7
|
+
* Hook errors propagate: the webhook answers non-2xx and Stripe retries.
|
|
8
|
+
*
|
|
9
|
+
* @version 0.2.0
|
|
10
|
+
* @since 0.2.0
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type Stripe from 'stripe';
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
CheckoutAddress,
|
|
18
|
+
CheckoutSessionSnapshot,
|
|
19
|
+
OrderHookContext,
|
|
20
|
+
PaidLineItem,
|
|
21
|
+
StripeOrderBackItem,
|
|
22
|
+
} from '@donotdev/core/server';
|
|
23
|
+
|
|
24
|
+
import { logger } from '../logger.js';
|
|
25
|
+
import { STRIPE_API_VERSION_PIN } from './apiVersion.js';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Checkout Session events that concern orders.
|
|
29
|
+
*
|
|
30
|
+
* @version 0.2.0
|
|
31
|
+
* @since 0.2.0
|
|
32
|
+
* @author AMBROISE PARK Consulting
|
|
33
|
+
*/
|
|
34
|
+
export type OrderSessionEventType =
|
|
35
|
+
| 'checkout.session.completed'
|
|
36
|
+
| 'checkout.session.async_payment_succeeded'
|
|
37
|
+
| 'checkout.session.async_payment_failed'
|
|
38
|
+
| 'checkout.session.expired';
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Oldest Stripe API version whose Checkout Session payload StripeOrder can read
|
|
42
|
+
* (`collected_information` was added in 2025-02-24.acacia). Alias of
|
|
43
|
+
* {@link STRIPE_API_VERSION_PIN}.
|
|
44
|
+
*
|
|
45
|
+
* @version 0.2.0
|
|
46
|
+
* @since 0.2.0
|
|
47
|
+
* @author AMBROISE PARK Consulting
|
|
48
|
+
*/
|
|
49
|
+
export const MIN_ORDER_API_VERSION = STRIPE_API_VERSION_PIN;
|
|
50
|
+
|
|
51
|
+
/** Metadata key carrying the app order ID on the Checkout Session. */
|
|
52
|
+
export const ORDER_ID_METADATA_KEY = 'orderId';
|
|
53
|
+
|
|
54
|
+
/** Product metadata key carrying the app product ID on each line. */
|
|
55
|
+
export const PRODUCT_ID_METADATA_KEY = 'productId';
|
|
56
|
+
|
|
57
|
+
function idOf(value: string | { id: string } | null): string | null {
|
|
58
|
+
if (value === null) return null;
|
|
59
|
+
return typeof value === 'string' ? value : value.id;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type StripeAddressFields = Pick<
|
|
63
|
+
Stripe.Address,
|
|
64
|
+
'line1' | 'line2' | 'postal_code' | 'city' | 'state' | 'country'
|
|
65
|
+
>;
|
|
66
|
+
|
|
67
|
+
function toAddress(address: StripeAddressFields): CheckoutAddress {
|
|
68
|
+
return {
|
|
69
|
+
line1: address.line1,
|
|
70
|
+
line2: address.line2,
|
|
71
|
+
postalCode: address.postal_code,
|
|
72
|
+
city: address.city,
|
|
73
|
+
state: address.state,
|
|
74
|
+
country: address.country,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Map a Stripe Checkout Session to the provider-neutral snapshot given to order hooks.
|
|
80
|
+
*
|
|
81
|
+
* @param session - Checkout Session from a webhook event
|
|
82
|
+
* @returns Snapshot (amounts in the smallest currency unit)
|
|
83
|
+
*
|
|
84
|
+
* @version 0.2.0
|
|
85
|
+
* @since 0.2.0
|
|
86
|
+
* @author AMBROISE PARK Consulting
|
|
87
|
+
*/
|
|
88
|
+
export function toCheckoutSessionSnapshot(
|
|
89
|
+
session: Stripe.Checkout.Session
|
|
90
|
+
): CheckoutSessionSnapshot {
|
|
91
|
+
const details = session.customer_details;
|
|
92
|
+
const shipping = session.collected_information?.shipping_details ?? null;
|
|
93
|
+
return {
|
|
94
|
+
id: session.id,
|
|
95
|
+
paymentStatus: session.payment_status,
|
|
96
|
+
currency: session.currency,
|
|
97
|
+
amountSubtotal: session.amount_subtotal,
|
|
98
|
+
amountTax: session.total_details?.amount_tax ?? null,
|
|
99
|
+
amountShipping: session.total_details?.amount_shipping ?? null,
|
|
100
|
+
amountDiscount: session.total_details?.amount_discount ?? null,
|
|
101
|
+
amountTotal: session.amount_total,
|
|
102
|
+
customerId: idOf(session.customer),
|
|
103
|
+
customer: details
|
|
104
|
+
? {
|
|
105
|
+
email: details.email,
|
|
106
|
+
name: details.name,
|
|
107
|
+
phone: details.phone,
|
|
108
|
+
businessName: details.business_name,
|
|
109
|
+
address: details.address ? toAddress(details.address) : null,
|
|
110
|
+
taxIds: (details.tax_ids ?? []).map((taxId) => ({
|
|
111
|
+
type: taxId.type,
|
|
112
|
+
value: taxId.value,
|
|
113
|
+
})),
|
|
114
|
+
taxExempt: details.tax_exempt,
|
|
115
|
+
}
|
|
116
|
+
: null,
|
|
117
|
+
shipping: shipping
|
|
118
|
+
? { name: shipping.name, address: toAddress(shipping.address) }
|
|
119
|
+
: null,
|
|
120
|
+
invoiceId: idOf(session.invoice),
|
|
121
|
+
paymentIntentId: idOf(session.payment_intent),
|
|
122
|
+
metadata: session.metadata ?? {},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Read the charged lines of a session back from Stripe.
|
|
128
|
+
*
|
|
129
|
+
* @param stripe - Stripe client
|
|
130
|
+
* @param sessionId - Checkout Session ID
|
|
131
|
+
* @returns Lines with the app product ID and charged amounts
|
|
132
|
+
* @throws When a line carries no app product ID (not created by the framework)
|
|
133
|
+
*
|
|
134
|
+
* @version 0.2.0
|
|
135
|
+
* @since 0.2.0
|
|
136
|
+
* @author AMBROISE PARK Consulting
|
|
137
|
+
*/
|
|
138
|
+
export async function listPaidLineItems(
|
|
139
|
+
stripe: Stripe,
|
|
140
|
+
sessionId: string
|
|
141
|
+
): Promise<PaidLineItem[]> {
|
|
142
|
+
const lines: PaidLineItem[] = [];
|
|
143
|
+
for await (const item of stripe.checkout.sessions.listLineItems(sessionId, {
|
|
144
|
+
limit: 100,
|
|
145
|
+
expand: ['data.price.product'],
|
|
146
|
+
})) {
|
|
147
|
+
const product = item.price?.product;
|
|
148
|
+
const productId =
|
|
149
|
+
product && typeof product !== 'string' && !product.deleted
|
|
150
|
+
? product.metadata[PRODUCT_ID_METADATA_KEY]
|
|
151
|
+
: undefined;
|
|
152
|
+
if (!productId) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`Line item ${item.id} of session ${sessionId} has no ${PRODUCT_ID_METADATA_KEY} product metadata`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
lines.push({
|
|
158
|
+
productId,
|
|
159
|
+
name: item.description ?? '',
|
|
160
|
+
quantity: item.quantity ?? 0,
|
|
161
|
+
amountSubtotal: item.amount_subtotal,
|
|
162
|
+
amountDiscount: item.amount_discount,
|
|
163
|
+
amountTax: item.amount_tax,
|
|
164
|
+
amountTotal: item.amount_total,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return lines;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Route one Checkout Session event of a StripeOrder item to the app hooks.
|
|
172
|
+
*
|
|
173
|
+
* - `completed` + `paid` / `no_payment_required` → `onOrderPaid`
|
|
174
|
+
* - `completed` + `unpaid` (async method, e.g. SEPA debit) → wait for the async event
|
|
175
|
+
* - `async_payment_succeeded` → `onOrderPaid`
|
|
176
|
+
* - `async_payment_failed` → `onOrderPaymentFailed`
|
|
177
|
+
* - `expired` → `onOrderExpired`
|
|
178
|
+
*
|
|
179
|
+
* @throws When the event API version is older than {@link MIN_ORDER_API_VERSION},
|
|
180
|
+
* when metadata is incomplete, or when a hook throws
|
|
181
|
+
*
|
|
182
|
+
* @version 0.2.0
|
|
183
|
+
* @since 0.2.0
|
|
184
|
+
* @author AMBROISE PARK Consulting
|
|
185
|
+
*/
|
|
186
|
+
export async function handleOrderSessionEvent(
|
|
187
|
+
eventType: OrderSessionEventType,
|
|
188
|
+
eventId: string,
|
|
189
|
+
apiVersion: string | null,
|
|
190
|
+
session: Stripe.Checkout.Session,
|
|
191
|
+
billingConfigKey: string,
|
|
192
|
+
orderItem: StripeOrderBackItem,
|
|
193
|
+
stripe: Stripe
|
|
194
|
+
): Promise<void> {
|
|
195
|
+
// API versions are date-prefixed (YYYY-MM-DD.name): compare the dates.
|
|
196
|
+
// event.api_version is the webhook ENDPOINT's version, not STRIPE_API_VERSION.
|
|
197
|
+
if (
|
|
198
|
+
!apiVersion ||
|
|
199
|
+
apiVersion.slice(0, 10) < MIN_ORDER_API_VERSION.slice(0, 10)
|
|
200
|
+
) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`Stripe event ${eventId} (order ${session.metadata?.[ORDER_ID_METADATA_KEY] ?? 'unknown'}) was rendered with API version ${apiVersion}; ` +
|
|
203
|
+
`StripeOrder requires ${MIN_ORDER_API_VERSION} or later. Webhook payloads follow the webhook endpoint's API version, ` +
|
|
204
|
+
`not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint ` +
|
|
205
|
+
`(POST /v1/webhook_endpoints with api_version=${MIN_ORDER_API_VERSION}), set STRIPE_WEBHOOK_SECRET to its signing secret, ` +
|
|
206
|
+
`disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const metadata = session.metadata ?? {};
|
|
211
|
+
const userId = metadata.userId;
|
|
212
|
+
const orderId = metadata[ORDER_ID_METADATA_KEY];
|
|
213
|
+
if (!userId || !orderId) {
|
|
214
|
+
throw new Error(
|
|
215
|
+
`Order session ${session.id} is missing metadata: userId=${userId}, orderId=${orderId}`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const ctx: OrderHookContext = { userId, orderId, billingConfigKey, eventId };
|
|
220
|
+
const snapshot = toCheckoutSessionSnapshot(session);
|
|
221
|
+
|
|
222
|
+
const isPaidNow =
|
|
223
|
+
eventType === 'checkout.session.async_payment_succeeded' ||
|
|
224
|
+
(eventType === 'checkout.session.completed' &&
|
|
225
|
+
session.payment_status !== 'unpaid');
|
|
226
|
+
|
|
227
|
+
if (isPaidNow) {
|
|
228
|
+
const lineItems = await listPaidLineItems(stripe, session.id);
|
|
229
|
+
await orderItem.onOrderPaid(snapshot, lineItems, ctx);
|
|
230
|
+
logger.info('[Webhook] Order paid', {
|
|
231
|
+
orderId,
|
|
232
|
+
billingConfigKey,
|
|
233
|
+
operation: 'order_paid',
|
|
234
|
+
});
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
switch (eventType) {
|
|
239
|
+
case 'checkout.session.completed':
|
|
240
|
+
logger.info('[Webhook] Order awaiting async payment', {
|
|
241
|
+
orderId,
|
|
242
|
+
billingConfigKey,
|
|
243
|
+
operation: 'order_payment_pending',
|
|
244
|
+
});
|
|
245
|
+
return;
|
|
246
|
+
case 'checkout.session.async_payment_failed':
|
|
247
|
+
if (orderItem.onOrderPaymentFailed) {
|
|
248
|
+
await orderItem.onOrderPaymentFailed(snapshot, ctx);
|
|
249
|
+
}
|
|
250
|
+
logger.warn('[Webhook] Order payment failed', {
|
|
251
|
+
orderId,
|
|
252
|
+
billingConfigKey,
|
|
253
|
+
operation: 'order_payment_failed',
|
|
254
|
+
});
|
|
255
|
+
return;
|
|
256
|
+
case 'checkout.session.expired':
|
|
257
|
+
if (orderItem.onOrderExpired) {
|
|
258
|
+
await orderItem.onOrderExpired(snapshot, ctx);
|
|
259
|
+
}
|
|
260
|
+
logger.info('[Webhook] Order checkout expired', {
|
|
261
|
+
orderId,
|
|
262
|
+
billingConfigKey,
|
|
263
|
+
operation: 'order_expired',
|
|
264
|
+
});
|
|
265
|
+
return;
|
|
266
|
+
default:
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/supabaseIdempotency.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Postgres (Supabase) webhook idempotency store
|
|
5
|
+
* @description `webhook_events` table and its RPCs. Re-exported from
|
|
6
|
+
* `idempotency.ts`.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.2.0
|
|
9
|
+
* @since 0.2.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
14
|
+
import * as v from 'valibot';
|
|
15
|
+
|
|
16
|
+
import { handleError } from '../errorHandling.js';
|
|
17
|
+
import {
|
|
18
|
+
RESERVATION_LEASE_MS,
|
|
19
|
+
ReservationLostError,
|
|
20
|
+
newOwnerToken,
|
|
21
|
+
} from './idempotencyContract.js';
|
|
22
|
+
import type {
|
|
23
|
+
IdempotencyStore,
|
|
24
|
+
ReservationResult,
|
|
25
|
+
} from './idempotencyContract.js';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* SQL required by {@link createSupabaseIdempotencyStore}: table, the
|
|
29
|
+
* service_role-only RPCs `webhook_event_reserve` / `webhook_event_mark_processed`
|
|
30
|
+
* / `webhook_event_release`, and a daily pg_cron cleanup (30 days). Shipped
|
|
31
|
+
* verbatim as the CLI Supabase template migration `*_webhook_events.sql`.
|
|
32
|
+
*
|
|
33
|
+
* @version 0.2.0
|
|
34
|
+
* @since 0.2.0
|
|
35
|
+
* @author AMBROISE PARK Consulting
|
|
36
|
+
*/
|
|
37
|
+
export const WEBHOOK_EVENTS_SQL = `
|
|
38
|
+
CREATE TABLE IF NOT EXISTS public.webhook_events (
|
|
39
|
+
event_id TEXT PRIMARY KEY,
|
|
40
|
+
status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
|
|
41
|
+
owner_token UUID NOT NULL,
|
|
42
|
+
reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
43
|
+
processed_at TIMESTAMPTZ
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
-- Only service_role accesses this table
|
|
47
|
+
ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
|
|
48
|
+
|
|
49
|
+
CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
|
|
50
|
+
ON public.webhook_events (processed_at);
|
|
51
|
+
|
|
52
|
+
-- The functions below run as the caller (SECURITY INVOKER) and refuse every
|
|
53
|
+
-- role but service_role. EXECUTE is deliberately not revoked: on Supabase
|
|
54
|
+
-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
|
|
55
|
+
-- crashes the backend (signal 11), which restarts every connection.
|
|
56
|
+
CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
|
|
57
|
+
RETURNS VOID
|
|
58
|
+
LANGUAGE plpgsql
|
|
59
|
+
SET search_path = public
|
|
60
|
+
AS $$
|
|
61
|
+
BEGIN
|
|
62
|
+
IF current_user IS DISTINCT FROM 'service_role' THEN
|
|
63
|
+
RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
|
|
64
|
+
USING ERRCODE = 'insufficient_privilege';
|
|
65
|
+
END IF;
|
|
66
|
+
END;
|
|
67
|
+
$$;
|
|
68
|
+
|
|
69
|
+
-- Atomic reservation. Returns:
|
|
70
|
+
-- 'reserved' the caller now owns the event under p_owner_token
|
|
71
|
+
-- 'processed' the event was already processed (skip, answer 2xx)
|
|
72
|
+
-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
|
|
73
|
+
-- A 'processing' row older than the lease is retaken (abandoned worker).
|
|
74
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
|
|
75
|
+
p_event_id TEXT,
|
|
76
|
+
p_owner_token UUID,
|
|
77
|
+
p_lease_seconds INT
|
|
78
|
+
)
|
|
79
|
+
RETURNS TEXT
|
|
80
|
+
LANGUAGE plpgsql
|
|
81
|
+
SET search_path = public
|
|
82
|
+
AS $$
|
|
83
|
+
DECLARE
|
|
84
|
+
v_status TEXT;
|
|
85
|
+
BEGIN
|
|
86
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
87
|
+
|
|
88
|
+
INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
|
|
89
|
+
VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
|
|
90
|
+
ON CONFLICT (event_id) DO UPDATE
|
|
91
|
+
SET owner_token = EXCLUDED.owner_token,
|
|
92
|
+
reserved_at = clock_timestamp()
|
|
93
|
+
WHERE webhook_events.status = 'processing'
|
|
94
|
+
AND webhook_events.reserved_at
|
|
95
|
+
< clock_timestamp() - make_interval(secs => p_lease_seconds);
|
|
96
|
+
IF FOUND THEN
|
|
97
|
+
RETURN 'reserved';
|
|
98
|
+
END IF;
|
|
99
|
+
|
|
100
|
+
SELECT status INTO v_status
|
|
101
|
+
FROM public.webhook_events
|
|
102
|
+
WHERE event_id = p_event_id;
|
|
103
|
+
IF v_status = 'processed' THEN
|
|
104
|
+
RETURN 'processed';
|
|
105
|
+
END IF;
|
|
106
|
+
-- Live lease, or the row was released in between: Stripe retries either way
|
|
107
|
+
RETURN 'in_progress';
|
|
108
|
+
END;
|
|
109
|
+
$$;
|
|
110
|
+
|
|
111
|
+
-- Mark a reservation processed. Returns false when p_owner_token no longer owns
|
|
112
|
+
-- the row (lease retaken, released, or deleted). Repeating it for the same
|
|
113
|
+
-- owner is a no-op that returns true.
|
|
114
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
|
|
115
|
+
p_event_id TEXT,
|
|
116
|
+
p_owner_token UUID
|
|
117
|
+
)
|
|
118
|
+
RETURNS BOOLEAN
|
|
119
|
+
LANGUAGE plpgsql
|
|
120
|
+
SET search_path = public
|
|
121
|
+
AS $$
|
|
122
|
+
BEGIN
|
|
123
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
124
|
+
|
|
125
|
+
UPDATE public.webhook_events
|
|
126
|
+
SET status = 'processed',
|
|
127
|
+
processed_at = COALESCE(processed_at, clock_timestamp())
|
|
128
|
+
WHERE event_id = p_event_id
|
|
129
|
+
AND owner_token = p_owner_token;
|
|
130
|
+
RETURN FOUND;
|
|
131
|
+
END;
|
|
132
|
+
$$;
|
|
133
|
+
|
|
134
|
+
-- Drop a reservation after a processing failure. Returns false when
|
|
135
|
+
-- p_owner_token does not own a 'processing' row (nothing is deleted).
|
|
136
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_release(
|
|
137
|
+
p_event_id TEXT,
|
|
138
|
+
p_owner_token UUID
|
|
139
|
+
)
|
|
140
|
+
RETURNS BOOLEAN
|
|
141
|
+
LANGUAGE plpgsql
|
|
142
|
+
SET search_path = public
|
|
143
|
+
AS $$
|
|
144
|
+
BEGIN
|
|
145
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
146
|
+
|
|
147
|
+
DELETE FROM public.webhook_events
|
|
148
|
+
WHERE event_id = p_event_id
|
|
149
|
+
AND owner_token = p_owner_token
|
|
150
|
+
AND status = 'processing';
|
|
151
|
+
RETURN FOUND;
|
|
152
|
+
END;
|
|
153
|
+
$$;
|
|
154
|
+
|
|
155
|
+
-- Enable pg_cron extension (if not already enabled)
|
|
156
|
+
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
157
|
+
|
|
158
|
+
-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
|
|
159
|
+
-- Stripe retries an event for up to 3 days, so older rows are never read again.
|
|
160
|
+
SELECT cron.schedule(
|
|
161
|
+
'cleanup-webhook-events',
|
|
162
|
+
'0 5 * * *',
|
|
163
|
+
$$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
|
|
164
|
+
);
|
|
165
|
+
`;
|
|
166
|
+
|
|
167
|
+
const ReserveResultSchema = v.picklist(['reserved', 'processed', 'in_progress']);
|
|
168
|
+
const OwnedResultSchema = v.boolean();
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Postgres-backed store (Supabase). Requires {@link WEBHOOK_EVENTS_SQL}.
|
|
172
|
+
*
|
|
173
|
+
* @param supabaseAdmin - Supabase client created with the service role key
|
|
174
|
+
*
|
|
175
|
+
* @version 0.2.0
|
|
176
|
+
* @since 0.2.0
|
|
177
|
+
* @author AMBROISE PARK Consulting
|
|
178
|
+
*/
|
|
179
|
+
export function createSupabaseIdempotencyStore(
|
|
180
|
+
supabaseAdmin: SupabaseClient
|
|
181
|
+
): IdempotencyStore {
|
|
182
|
+
const call = async <T>(
|
|
183
|
+
fn: string,
|
|
184
|
+
args: Record<string, unknown>,
|
|
185
|
+
schema: v.GenericSchema<unknown, T>
|
|
186
|
+
): Promise<T> => {
|
|
187
|
+
const { data, error } = await supabaseAdmin.rpc(fn, args);
|
|
188
|
+
if (error) throw handleError(error);
|
|
189
|
+
const result = v.safeParse(schema, data);
|
|
190
|
+
if (!result.success) {
|
|
191
|
+
throw handleError(
|
|
192
|
+
new Error(`${fn} returned an unexpected result: ${JSON.stringify(data)}`)
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
return result.output;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
return {
|
|
199
|
+
async reserve(eventId): Promise<ReservationResult> {
|
|
200
|
+
const ownerToken = newOwnerToken();
|
|
201
|
+
const state = await call(
|
|
202
|
+
'webhook_event_reserve',
|
|
203
|
+
{
|
|
204
|
+
p_event_id: eventId,
|
|
205
|
+
p_owner_token: ownerToken,
|
|
206
|
+
p_lease_seconds: RESERVATION_LEASE_MS / 1000,
|
|
207
|
+
},
|
|
208
|
+
ReserveResultSchema
|
|
209
|
+
);
|
|
210
|
+
return state === 'reserved' ? { state, ownerToken } : { state };
|
|
211
|
+
},
|
|
212
|
+
async markProcessed(eventId, ownerToken) {
|
|
213
|
+
const owned = await call(
|
|
214
|
+
'webhook_event_mark_processed',
|
|
215
|
+
{ p_event_id: eventId, p_owner_token: ownerToken },
|
|
216
|
+
OwnedResultSchema
|
|
217
|
+
);
|
|
218
|
+
if (!owned) throw new ReservationLostError(eventId);
|
|
219
|
+
},
|
|
220
|
+
async release(eventId, ownerToken) {
|
|
221
|
+
return call(
|
|
222
|
+
'webhook_event_release',
|
|
223
|
+
{ p_event_id: eventId, p_owner_token: ownerToken },
|
|
224
|
+
OwnedResultSchema
|
|
225
|
+
);
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
}
|