@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
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import * as v from 'valibot';
|
|
2
|
-
import { type GrantGitHubAccessRequest, type RevokeGitHubAccessRequest, type CheckGitHubAccessRequest } from '@donotdev/core/server';
|
|
3
1
|
import type { CallableRequest } from 'firebase-functions/v2/https';
|
|
4
2
|
import type { CallableFunction } from 'firebase-functions/v2/https';
|
|
3
|
+
import * as v from 'valibot';
|
|
4
|
+
import { type GrantGitHubAccessRequest, type RevokeGitHubAccessRequest, type CheckGitHubAccessRequest } from '@donotdev/core/server';
|
|
5
5
|
/**
|
|
6
6
|
* Grant GitHub repository access to a user
|
|
7
7
|
*
|
|
@@ -1,5 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Auto-register CRUD functions from entities
|
|
3
|
+
* @description Utility to automatically generate CRUD Cloud Functions for all entities
|
|
4
|
+
*
|
|
5
|
+
* @version 0.1.0
|
|
6
|
+
* @since 0.0.1
|
|
7
|
+
* @author AMBROISE PARK Consulting
|
|
8
|
+
*/
|
|
2
9
|
import type { HttpsFunction } from 'firebase-functions/v2/https';
|
|
10
|
+
import type { Entity } from '@donotdev/core/server';
|
|
3
11
|
interface RegisterOptions {
|
|
4
12
|
prefix?: string;
|
|
5
13
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Stripe API version pin
|
|
3
|
+
* @description Single source of truth for the Stripe API version the framework
|
|
4
|
+
* reads. The subscription handlers still read pre-basil fields
|
|
5
|
+
* (`invoice.subscription`, `subscription.current_period_end`), so the pin stays
|
|
6
|
+
* on acacia; StripeOrder needs `collected_information` (2025-02-24.acacia).
|
|
7
|
+
*
|
|
8
|
+
* @version 0.2.0
|
|
9
|
+
* @since 0.2.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Stripe API version used by `initStripe` when `STRIPE_API_VERSION` is unset,
|
|
14
|
+
* and the oldest version whose Checkout Session payload StripeOrder can read.
|
|
15
|
+
* Webhook event payloads follow the webhook ENDPOINT's API version (set when
|
|
16
|
+
* the endpoint is created in the Dashboard or API), not this value.
|
|
17
|
+
*
|
|
18
|
+
* @version 0.2.0
|
|
19
|
+
* @since 0.2.0
|
|
20
|
+
* @author AMBROISE PARK Consulting
|
|
21
|
+
*/
|
|
22
|
+
export declare const STRIPE_API_VERSION_PIN = "2025-02-24.acacia";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Single-price checkout (StripePayment / StripeSubscription)
|
|
3
|
+
* @description 0.1.x pricing rules and the 0.1.x params → Stripe params mapping
|
|
4
|
+
* used by `createCheckoutAlgorithm`.
|
|
5
|
+
*
|
|
6
|
+
* @version 0.2.0
|
|
7
|
+
* @since 0.2.0
|
|
8
|
+
* @author AMBROISE PARK Consulting
|
|
9
|
+
*/
|
|
10
|
+
import type Stripe from 'stripe';
|
|
11
|
+
import type { CheckoutMode, CheckoutSessionParams, CreateCheckoutSessionRequest, StripePaymentBackItem, StripeSubscriptionBackItem } from '@donotdev/core/server';
|
|
12
|
+
/** Price resolved for a single-price item (0.1.x rules). */
|
|
13
|
+
export interface PricePlan {
|
|
14
|
+
/** Fixed price charged; undefined for dynamic pricing */
|
|
15
|
+
priceId?: string;
|
|
16
|
+
/** 0.1.x dynamic pricing (client unitAmount + productName) */
|
|
17
|
+
dynamic: boolean;
|
|
18
|
+
mode: CheckoutMode;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must
|
|
22
|
+
* match the config priceId when set), else 0.1.x dynamic pricing capped by
|
|
23
|
+
* `maxUnitAmount`, else the back-config priceId.
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolvePricePlan(item: StripePaymentBackItem | StripeSubscriptionBackItem, request: CreateCheckoutSessionRequest): PricePlan;
|
|
26
|
+
/** 0.1.x params → Stripe params (what the 0.1.x Firebase/Supabase providers sent). */
|
|
27
|
+
export declare function toStripeSessionParams(params: CheckoutSessionParams): Stripe.Checkout.SessionCreateParams;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Checkout validation helpers
|
|
3
|
+
* @description Fail-loud checks run by `createCheckoutAlgorithm` before calling
|
|
4
|
+
* Stripe: redirect URLs, client metadata, Stripe metadata limits, resolved
|
|
5
|
+
* StripeOrder lines and manual Tax Rates.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.2.0
|
|
8
|
+
* @since 0.2.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
import type Stripe from 'stripe';
|
|
12
|
+
import type { ResolvedOrder, ResolvedOrderSession } from '@donotdev/core/server';
|
|
13
|
+
/**
|
|
14
|
+
* Stripe metadata limits (https://docs.stripe.com/metadata): 50 keys, keys up
|
|
15
|
+
* to 40 characters without square brackets, values up to 500 characters.
|
|
16
|
+
*
|
|
17
|
+
* @version 0.2.0
|
|
18
|
+
* @since 0.2.0
|
|
19
|
+
* @author AMBROISE PARK Consulting
|
|
20
|
+
*/
|
|
21
|
+
export declare const STRIPE_METADATA_LIMITS: {
|
|
22
|
+
readonly maxKeys: 50;
|
|
23
|
+
readonly maxKeyLength: 40;
|
|
24
|
+
readonly maxValueLength: 500;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Validate URL has http/https protocol.
|
|
28
|
+
* Platform-agnostic (no firebase logger dependency).
|
|
29
|
+
*/
|
|
30
|
+
export declare function validateCheckoutUrl(url: string, name: string): void;
|
|
31
|
+
/**
|
|
32
|
+
* Sanitize client metadata: enforce string values, strip script injection.
|
|
33
|
+
* Length limits are checked on the final metadata ({@link assertStripeMetadata}).
|
|
34
|
+
*/
|
|
35
|
+
export declare function sanitizeMetadata(metadata: Record<string, any>): Record<string, string>;
|
|
36
|
+
/**
|
|
37
|
+
* Throw a validation error when metadata exceeds Stripe's limits
|
|
38
|
+
* ({@link STRIPE_METADATA_LIMITS}), instead of letting Stripe answer 400.
|
|
39
|
+
*
|
|
40
|
+
* @param metadata - Metadata as it will be sent to Stripe
|
|
41
|
+
* @param target - Stripe param the metadata goes to (shown in the error)
|
|
42
|
+
*
|
|
43
|
+
* @version 0.2.0
|
|
44
|
+
* @since 0.2.0
|
|
45
|
+
* @author AMBROISE PARK Consulting
|
|
46
|
+
*/
|
|
47
|
+
export declare function assertStripeMetadata(metadata: Record<string, string | number | null>, target: string): void;
|
|
48
|
+
/**
|
|
49
|
+
* Check every metadata map of Checkout Session params (session, subscription,
|
|
50
|
+
* payment intent, invoice, line products) against Stripe's limits.
|
|
51
|
+
*
|
|
52
|
+
* @param params - Session params about to be sent to Stripe
|
|
53
|
+
*
|
|
54
|
+
* @version 0.2.0
|
|
55
|
+
* @since 0.2.0
|
|
56
|
+
* @author AMBROISE PARK Consulting
|
|
57
|
+
*/
|
|
58
|
+
export declare function assertCheckoutSessionMetadata(params: Stripe.Checkout.SessionCreateParams): void;
|
|
59
|
+
/**
|
|
60
|
+
* Validate the output of an app `resolveLineItems` hook. Fails loud on any
|
|
61
|
+
* malformed line instead of sending it to Stripe.
|
|
62
|
+
*/
|
|
63
|
+
export declare function assertResolvedOrder(order: ResolvedOrder, configKey: string): void;
|
|
64
|
+
/** Stripe Checkout `expires_at` window (seconds after creation). */
|
|
65
|
+
export declare const CHECKOUT_EXPIRY_WINDOW: {
|
|
66
|
+
readonly minSeconds: number;
|
|
67
|
+
readonly maxSeconds: number;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Validate per-order session options returned by `resolveLineItems`.
|
|
71
|
+
* Item-dependent checks (manual tax, invoice creation) run in `createCheckoutAlgorithm`.
|
|
72
|
+
*
|
|
73
|
+
* @param session - `ResolvedOrder.session`
|
|
74
|
+
* @param configKey - Back config key (shown in errors)
|
|
75
|
+
* @param nowSeconds - Current Unix time (injectable for tests)
|
|
76
|
+
*
|
|
77
|
+
* @version 0.2.0
|
|
78
|
+
* @since 0.2.0
|
|
79
|
+
* @author AMBROISE PARK Consulting
|
|
80
|
+
*/
|
|
81
|
+
export declare function assertResolvedOrderSession(session: ResolvedOrderSession, configKey: string, nowSeconds?: number): void;
|
|
82
|
+
/**
|
|
83
|
+
* StripeOrder manual tax: unit amounts are excl. VAT, but an inclusive Tax Rate
|
|
84
|
+
* overrides `price_data.tax_behavior: 'exclusive'` and carves the tax out of
|
|
85
|
+
* the amount. Throws when any configured rate is inclusive.
|
|
86
|
+
*/
|
|
87
|
+
export declare function assertExclusiveTaxRates(retrieveTaxRate: (id: string) => Promise<{
|
|
88
|
+
inclusive: boolean;
|
|
89
|
+
}>, taxRateIds: string[], configKey: string): Promise<void>;
|
|
@@ -1,39 +1,53 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @fileoverview Create Checkout Session Algorithm
|
|
3
|
-
* @description Platform-agnostic algorithm for creating Stripe checkout sessions
|
|
3
|
+
* @description Platform-agnostic algorithm for creating Stripe checkout sessions.
|
|
4
|
+
* StripePayment/StripeSubscription items keep the 0.1.x behaviour (request or
|
|
5
|
+
* back-config priceId, 0.1.x dynamic pricing). StripeOrder items are priced on
|
|
6
|
+
* the server (`resolveLineItems`) and need a {@link StripeSessionProvider}.
|
|
4
7
|
*
|
|
5
|
-
* @version 0.
|
|
8
|
+
* @version 0.2.0
|
|
6
9
|
* @since 0.0.1
|
|
7
10
|
* @author AMBROISE PARK Consulting
|
|
8
11
|
*/
|
|
9
|
-
import type
|
|
12
|
+
import type Stripe from 'stripe';
|
|
13
|
+
import type { CheckoutSessionResult, CreateCheckoutSessionRequestInput, CreateCheckoutSessionResponse, StripeBackConfig, StripeCheckoutProvider } from '@donotdev/core/server';
|
|
10
14
|
/**
|
|
11
|
-
* Provider
|
|
15
|
+
* Provider that sends full Stripe session params (every item type, StripeOrder included).
|
|
12
16
|
*
|
|
13
|
-
* @
|
|
14
|
-
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* const provider: StripeSessionProvider = {
|
|
20
|
+
* async createStripeSession(params) {
|
|
21
|
+
* const session = await stripe.checkout.sessions.create(params);
|
|
22
|
+
* return { id: session.id, url: session.url };
|
|
23
|
+
* },
|
|
24
|
+
* async retrieveTaxRate(id) {
|
|
25
|
+
* const rate = await stripe.taxRates.retrieve(id);
|
|
26
|
+
* return { id: rate.id, inclusive: rate.inclusive };
|
|
27
|
+
* },
|
|
28
|
+
* };
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @version 0.2.0
|
|
32
|
+
* @since 0.2.0
|
|
15
33
|
* @author AMBROISE PARK Consulting
|
|
16
34
|
*/
|
|
17
|
-
export interface
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
unitAmount?: number;
|
|
22
|
-
/** Product name for Stripe checkout (dynamic pricing mode) */
|
|
23
|
-
productName?: string;
|
|
24
|
-
/** Currency code, defaults to 'eur' */
|
|
25
|
-
currency?: string;
|
|
26
|
-
customerEmail?: string;
|
|
27
|
-
metadata: Record<string, string>;
|
|
28
|
-
allowPromotionCodes: boolean;
|
|
29
|
-
successUrl: string;
|
|
30
|
-
cancelUrl: string;
|
|
31
|
-
mode?: 'payment' | 'subscription';
|
|
32
|
-
}): Promise<{
|
|
35
|
+
export interface StripeSessionProvider {
|
|
36
|
+
createStripeSession(params: Stripe.Checkout.SessionCreateParams): Promise<CheckoutSessionResult>;
|
|
37
|
+
/** Used to reject inclusive Tax Rates on StripeOrder manual tax (cached per instance). */
|
|
38
|
+
retrieveTaxRate(taxRateId: string): Promise<{
|
|
33
39
|
id: string;
|
|
34
|
-
|
|
40
|
+
inclusive: boolean;
|
|
35
41
|
}>;
|
|
36
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Any provider accepted by {@link createCheckoutAlgorithm}.
|
|
45
|
+
*
|
|
46
|
+
* @version 0.2.0
|
|
47
|
+
* @since 0.2.0
|
|
48
|
+
* @author AMBROISE PARK Consulting
|
|
49
|
+
*/
|
|
50
|
+
export type CheckoutProvider = StripeCheckoutProvider | StripeSessionProvider;
|
|
37
51
|
/**
|
|
38
52
|
* Provider interface for authentication operations
|
|
39
53
|
*
|
|
@@ -49,8 +63,43 @@ export interface AuthCheckoutProvider {
|
|
|
49
63
|
/**
|
|
50
64
|
* Create checkout session algorithm
|
|
51
65
|
*
|
|
66
|
+
* 1. Resolve the billing config item and verify the user
|
|
67
|
+
* 2. Single-price items: 0.1.x pricing (request/back-config priceId, dynamic pricing)
|
|
68
|
+
* 3. `beforeCheckout` hook (block/allow; 0.1.x dynamic-pricing overrides)
|
|
69
|
+
* 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
|
|
70
|
+
* and may set per-order session options (`ResolvedOrder.session`: tax rates,
|
|
71
|
+
* payment methods, expiry, invoice footer)
|
|
72
|
+
* 5. Validate metadata against Stripe limits, create the session through the provider
|
|
73
|
+
*
|
|
74
|
+
* Server-owned metadata (`userId`, `billingConfigKey`, `orderId`) is written after
|
|
75
|
+
* the client metadata and cannot be overwritten by it.
|
|
76
|
+
*
|
|
77
|
+
* Two call shapes:
|
|
78
|
+
* - `(request, userId, stripeProvider, authProvider, billingConfig)`: userId from
|
|
79
|
+
* the provider's auth context (framework providers use this).
|
|
80
|
+
* - 0.1.x `(request, stripeProvider, authProvider, billingConfig)`: userId read from
|
|
81
|
+
* `request.userId` (the caller must set it from its auth context).
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```typescript
|
|
85
|
+
* const result = await createCheckoutAlgorithm(
|
|
86
|
+
* request,
|
|
87
|
+
* context.uid,
|
|
88
|
+
* stripeSessionProvider,
|
|
89
|
+
* authProvider,
|
|
90
|
+
* billingConfig
|
|
91
|
+
* );
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* @param request - Validated client request (0.1.x shape accepted)
|
|
95
|
+
* @param userId - Authenticated user ID (omit in the 0.1.x call shape)
|
|
96
|
+
* @param stripeProvider - {@link StripeSessionProvider}, or 0.1.x {@link StripeCheckoutProvider} (single-price items only)
|
|
97
|
+
* @param authProvider - Verifies the user exists
|
|
98
|
+
* @param billingConfig - App back config
|
|
99
|
+
*
|
|
52
100
|
* @version 0.2.0
|
|
53
101
|
* @since 0.0.1
|
|
54
102
|
* @author AMBROISE PARK Consulting
|
|
55
103
|
*/
|
|
56
|
-
export declare function createCheckoutAlgorithm(request:
|
|
104
|
+
export declare function createCheckoutAlgorithm(request: CreateCheckoutSessionRequestInput, userId: string, stripeProvider: CheckoutProvider, authProvider: AuthCheckoutProvider, billingConfig: StripeBackConfig): Promise<CreateCheckoutSessionResponse>;
|
|
105
|
+
export declare function createCheckoutAlgorithm(request: CreateCheckoutSessionRequestInput, stripeProvider: CheckoutProvider, authProvider: AuthCheckoutProvider, billingConfig: StripeBackConfig): Promise<CreateCheckoutSessionResponse>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { BillingAuthProvider } from '@donotdev/core/server';
|
|
2
2
|
/**
|
|
3
3
|
* Cancel user subscription at period end
|
|
4
4
|
*
|
|
@@ -6,7 +6,7 @@ import { type AuthProvider } from './updateUserSubscription.js';
|
|
|
6
6
|
* @since 0.0.1
|
|
7
7
|
* @author AMBROISE PARK Consulting
|
|
8
8
|
*/
|
|
9
|
-
export declare function cancelUserSubscription(userId: string, authProvider:
|
|
9
|
+
export declare function cancelUserSubscription(userId: string, authProvider: BillingAuthProvider): Promise<{
|
|
10
10
|
success: boolean;
|
|
11
11
|
endsAt: string;
|
|
12
12
|
}>;
|
|
@@ -17,7 +17,7 @@ export declare function cancelUserSubscription(userId: string, authProvider: Aut
|
|
|
17
17
|
* @since 0.0.1
|
|
18
18
|
* @author AMBROISE PARK Consulting
|
|
19
19
|
*/
|
|
20
|
-
export declare function changeUserPlan(userId: string, newPriceId: string, billingConfigKey: string, billingConfig: Record<string, any>, authProvider:
|
|
20
|
+
export declare function changeUserPlan(userId: string, newPriceId: string, billingConfigKey: string, billingConfig: Record<string, any>, authProvider: BillingAuthProvider): Promise<{
|
|
21
21
|
success: boolean;
|
|
22
22
|
newTier: string;
|
|
23
23
|
newPrice: number;
|
|
@@ -29,6 +29,6 @@ export declare function changeUserPlan(userId: string, newPriceId: string, billi
|
|
|
29
29
|
* @since 0.0.1
|
|
30
30
|
* @author AMBROISE PARK Consulting
|
|
31
31
|
*/
|
|
32
|
-
export declare function createCustomerPortalSession(userId: string, authProvider:
|
|
32
|
+
export declare function createCustomerPortalSession(userId: string, authProvider: BillingAuthProvider, returnUrl?: string): Promise<{
|
|
33
33
|
url: string;
|
|
34
34
|
}>;
|
|
@@ -6,34 +6,7 @@
|
|
|
6
6
|
* @since 0.0.1
|
|
7
7
|
* @author AMBROISE PARK Consulting
|
|
8
8
|
*/
|
|
9
|
-
|
|
10
|
-
* Subscription data structure
|
|
11
|
-
*
|
|
12
|
-
* @version 0.1.0
|
|
13
|
-
* @since 0.0.1
|
|
14
|
-
* @author AMBROISE PARK Consulting
|
|
15
|
-
*/
|
|
16
|
-
export interface SubscriptionData {
|
|
17
|
-
tier: string;
|
|
18
|
-
status: 'active' | 'canceled' | 'past_due' | 'trialing' | 'incomplete';
|
|
19
|
-
subscriptionEnd: string | null;
|
|
20
|
-
cancelAtPeriodEnd?: boolean;
|
|
21
|
-
subscriptionId?: string | null;
|
|
22
|
-
customerId?: string;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Platform-agnostic auth provider interface
|
|
26
|
-
*
|
|
27
|
-
* @version 0.1.0
|
|
28
|
-
* @since 0.0.1
|
|
29
|
-
* @author AMBROISE PARK Consulting
|
|
30
|
-
*/
|
|
31
|
-
export interface AuthProvider {
|
|
32
|
-
getUser(userId: string): Promise<{
|
|
33
|
-
customClaims?: Record<string, unknown>;
|
|
34
|
-
}>;
|
|
35
|
-
setCustomUserClaims(userId: string, claims: Record<string, unknown>): Promise<void>;
|
|
36
|
-
}
|
|
9
|
+
import type { BillingAuthProvider, SubscriptionUpdate } from '@donotdev/core/server';
|
|
37
10
|
/**
|
|
38
11
|
* Platform-agnostic subscription update using dependency injection
|
|
39
12
|
* Works on Firebase Functions, Vercel, AWS Lambda, etc.
|
|
@@ -42,4 +15,4 @@ export interface AuthProvider {
|
|
|
42
15
|
* @since 0.0.1
|
|
43
16
|
* @author AMBROISE PARK Consulting
|
|
44
17
|
*/
|
|
45
|
-
export declare function updateUserSubscription(userId: string, subscriptionData:
|
|
18
|
+
export declare function updateUserSubscription(userId: string, subscriptionData: SubscriptionUpdate, authProvider: BillingAuthProvider): Promise<void>;
|
|
@@ -1,22 +1,44 @@
|
|
|
1
|
+
import type { LegacyIdempotencyStore } from './idempotencyContract.js';
|
|
2
|
+
export { RESERVATION_LEASE_MS, ReservationLostError, WEBHOOK_EVENT_RETENTION_MS, } from './idempotencyContract.js';
|
|
3
|
+
export type { IdempotencyStore, LegacyIdempotencyStore, ReservationResult, } from './idempotencyContract.js';
|
|
1
4
|
/**
|
|
2
|
-
*
|
|
5
|
+
* In-memory store. Single process only: for tests, never for a deployed webhook.
|
|
3
6
|
*
|
|
4
|
-
* @version 0.
|
|
7
|
+
* @version 0.2.0
|
|
8
|
+
* @since 0.2.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
export declare function createInMemoryIdempotencyStore(): LegacyIdempotencyStore;
|
|
12
|
+
/**
|
|
13
|
+
* Firestore-backed store (transactions). Collection: `webhook_idempotency`.
|
|
14
|
+
*
|
|
15
|
+
* `expiresAt` is a Firestore Timestamp {@link WEBHOOK_EVENT_RETENTION_MS} after
|
|
16
|
+
* the last write: enable a TTL policy on `webhook_idempotency.expiresAt` so
|
|
17
|
+
* Firestore deletes old documents.
|
|
18
|
+
*
|
|
19
|
+
* @version 0.2.0
|
|
20
|
+
* @since 0.2.0
|
|
21
|
+
* @author AMBROISE PARK Consulting
|
|
22
|
+
*/
|
|
23
|
+
export declare function createFirestoreIdempotencyStore(): LegacyIdempotencyStore;
|
|
24
|
+
/**
|
|
25
|
+
* 0.1.x store auto-detection: Firestore when configured, else in-memory.
|
|
26
|
+
*
|
|
27
|
+
* @deprecated In-memory is not durable across instances. Pass an explicit store:
|
|
28
|
+
* {@link createFirestoreIdempotencyStore} or `createSupabaseIdempotencyStore`.
|
|
29
|
+
* Framework webhook entry points already do.
|
|
30
|
+
* @version 0.2.0
|
|
5
31
|
* @since 0.0.1
|
|
6
32
|
* @author AMBROISE PARK Consulting
|
|
7
33
|
*/
|
|
8
|
-
export
|
|
9
|
-
isProcessed(eventId: string): Promise<boolean>;
|
|
10
|
-
markProcessed(eventId: string): Promise<void>;
|
|
11
|
-
/** Atomic check-and-reserve: returns true if already processed, false if reserved for processing */
|
|
12
|
-
checkAndReserve(eventId: string): Promise<boolean>;
|
|
13
|
-
}
|
|
14
|
-
export declare function createIdempotencyStore(): IdempotencyStore;
|
|
34
|
+
export declare function createIdempotencyStore(): LegacyIdempotencyStore;
|
|
15
35
|
/**
|
|
16
|
-
* Reset
|
|
36
|
+
* Reset the store cached by {@link createIdempotencyStore} (tests).
|
|
17
37
|
*
|
|
38
|
+
* @deprecated See {@link createIdempotencyStore}.
|
|
18
39
|
* @version 0.1.0
|
|
19
40
|
* @since 0.0.1
|
|
20
41
|
* @author AMBROISE PARK Consulting
|
|
21
42
|
*/
|
|
22
43
|
export declare function resetIdempotencyStore(): void;
|
|
44
|
+
export { WEBHOOK_EVENTS_SQL, createSupabaseIdempotencyStore, } from './supabaseIdempotency.js';
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Webhook idempotency contract
|
|
3
|
+
* @description Store interface, reservation result, lease and retention shared
|
|
4
|
+
* by every idempotency store (in-memory, Firestore, Postgres).
|
|
5
|
+
*
|
|
6
|
+
* @version 0.2.0
|
|
7
|
+
* @since 0.2.0
|
|
8
|
+
* @author AMBROISE PARK Consulting
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Outcome of {@link IdempotencyStore.reserve}.
|
|
12
|
+
* - `reserved`: the caller owns the event and must process it, then call
|
|
13
|
+
* `markProcessed` or `release` with `ownerToken`
|
|
14
|
+
* - `processed`: already processed, skip (answer 2xx)
|
|
15
|
+
* - `in_progress`: another delivery holds a live lease (answer non-2xx so the
|
|
16
|
+
* provider retries later, when that worker finished or its lease expired)
|
|
17
|
+
*
|
|
18
|
+
* @version 0.2.0
|
|
19
|
+
* @since 0.2.0
|
|
20
|
+
* @author AMBROISE PARK Consulting
|
|
21
|
+
*/
|
|
22
|
+
export type ReservationResult = {
|
|
23
|
+
state: 'reserved';
|
|
24
|
+
ownerToken: string;
|
|
25
|
+
} | {
|
|
26
|
+
state: 'processed';
|
|
27
|
+
} | {
|
|
28
|
+
state: 'in_progress';
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Idempotency store interface
|
|
32
|
+
*
|
|
33
|
+
* @version 0.2.0
|
|
34
|
+
* @since 0.0.1
|
|
35
|
+
* @author AMBROISE PARK Consulting
|
|
36
|
+
*/
|
|
37
|
+
export interface IdempotencyStore {
|
|
38
|
+
/** Atomically reserve an event for processing. */
|
|
39
|
+
reserve(eventId: string): Promise<ReservationResult>;
|
|
40
|
+
/**
|
|
41
|
+
* Mark a reservation processed. Repeating it for the same owner succeeds.
|
|
42
|
+
* @throws {ReservationLostError} When `ownerToken` no longer owns the event
|
|
43
|
+
*/
|
|
44
|
+
markProcessed(eventId: string, ownerToken: string): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Drop a reservation after a processing failure.
|
|
47
|
+
* @returns `false` when `ownerToken` does not own a pending reservation (nothing changed)
|
|
48
|
+
*/
|
|
49
|
+
release(eventId: string, ownerToken: string): Promise<boolean>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Store with the 0.1.x accessors.
|
|
53
|
+
*
|
|
54
|
+
* @deprecated Use {@link IdempotencyStore}: `reserve` returns three states and
|
|
55
|
+
* an owner token; `checkAndReserve` and `isProcessed` do not.
|
|
56
|
+
* @version 0.2.0
|
|
57
|
+
* @since 0.2.0
|
|
58
|
+
* @author AMBROISE PARK Consulting
|
|
59
|
+
*/
|
|
60
|
+
export interface LegacyIdempotencyStore extends IdempotencyStore {
|
|
61
|
+
/** 0.1.x: `true` when the event must be skipped (processed or live lease). */
|
|
62
|
+
checkAndReserve(eventId: string): Promise<boolean>;
|
|
63
|
+
/** Whether the event was processed (non-atomic read). */
|
|
64
|
+
isProcessed(eventId: string): Promise<boolean>;
|
|
65
|
+
/**
|
|
66
|
+
* Mark processed. Without `ownerToken` (0.1.x call) the write is unconditional.
|
|
67
|
+
* @throws {ReservationLostError} When `ownerToken` is given and no longer owns the event
|
|
68
|
+
*/
|
|
69
|
+
markProcessed(eventId: string, ownerToken?: string): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Thrown by `markProcessed` when the caller no longer owns the reservation:
|
|
73
|
+
* its lease expired and another delivery retook the event, or the row is gone.
|
|
74
|
+
* Retrying cannot succeed.
|
|
75
|
+
*
|
|
76
|
+
* @version 0.2.0
|
|
77
|
+
* @since 0.2.0
|
|
78
|
+
* @author AMBROISE PARK Consulting
|
|
79
|
+
*/
|
|
80
|
+
export declare class ReservationLostError extends Error {
|
|
81
|
+
/** Event whose reservation was lost. */
|
|
82
|
+
readonly eventId: string;
|
|
83
|
+
constructor(eventId: string);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* How long a reservation blocks other deliveries of the same event before it
|
|
87
|
+
* is considered abandoned (worker crashed or timed out) and can be retaken.
|
|
88
|
+
*
|
|
89
|
+
* Must exceed the longest request timeout a webhook handler can run under, so
|
|
90
|
+
* a live worker is never overtaken. Official maximums (checked 2026-11-04):
|
|
91
|
+
* - Firebase Functions gen2 HTTP: 60 min
|
|
92
|
+
* (https://firebase.google.com/docs/functions/quotas#time_limits)
|
|
93
|
+
* - Vercel Functions: 800 s, 1800 s with extended max duration
|
|
94
|
+
* (https://vercel.com/docs/functions/configuring-functions/duration)
|
|
95
|
+
* - Supabase Edge Functions: 400 s wall clock on paid plans
|
|
96
|
+
* (https://supabase.com/docs/guides/functions/limits)
|
|
97
|
+
* 70 min = the 60 min maximum + 10 min margin. Stripe retries for up to 3 days.
|
|
98
|
+
*
|
|
99
|
+
* @version 0.2.0
|
|
100
|
+
* @since 0.2.0
|
|
101
|
+
* @author AMBROISE PARK Consulting
|
|
102
|
+
*/
|
|
103
|
+
export declare const RESERVATION_LEASE_MS: number;
|
|
104
|
+
/**
|
|
105
|
+
* How long reservations and processed events are kept before a TTL policy
|
|
106
|
+
* (Firestore `expiresAt`) or the pg_cron cleanup (Postgres) deletes them.
|
|
107
|
+
* Stripe retries for days, not weeks.
|
|
108
|
+
*
|
|
109
|
+
* @version 0.2.0
|
|
110
|
+
* @since 0.2.0
|
|
111
|
+
* @author AMBROISE PARK Consulting
|
|
112
|
+
*/
|
|
113
|
+
export declare const WEBHOOK_EVENT_RETENTION_MS: number;
|
|
114
|
+
/**
|
|
115
|
+
* New reservation owner token (random UUID). Internal to the stores.
|
|
116
|
+
*
|
|
117
|
+
* @version 0.2.0
|
|
118
|
+
* @since 0.2.0
|
|
119
|
+
* @author AMBROISE PARK Consulting
|
|
120
|
+
*/
|
|
121
|
+
export declare function newOwnerToken(): string;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview StripeOrder webhook handling
|
|
3
|
+
* @description Maps Checkout Session events of one-time, multi-line orders to the
|
|
4
|
+
* app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
|
|
5
|
+
* Hook errors propagate: the webhook answers non-2xx and Stripe retries.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.2.0
|
|
8
|
+
* @since 0.2.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
import type Stripe from 'stripe';
|
|
12
|
+
import type { CheckoutSessionSnapshot, PaidLineItem, StripeOrderBackItem } from '@donotdev/core/server';
|
|
13
|
+
/**
|
|
14
|
+
* Checkout Session events that concern orders.
|
|
15
|
+
*
|
|
16
|
+
* @version 0.2.0
|
|
17
|
+
* @since 0.2.0
|
|
18
|
+
* @author AMBROISE PARK Consulting
|
|
19
|
+
*/
|
|
20
|
+
export type OrderSessionEventType = 'checkout.session.completed' | 'checkout.session.async_payment_succeeded' | 'checkout.session.async_payment_failed' | 'checkout.session.expired';
|
|
21
|
+
/**
|
|
22
|
+
* Oldest Stripe API version whose Checkout Session payload StripeOrder can read
|
|
23
|
+
* (`collected_information` was added in 2025-02-24.acacia). Alias of
|
|
24
|
+
* {@link STRIPE_API_VERSION_PIN}.
|
|
25
|
+
*
|
|
26
|
+
* @version 0.2.0
|
|
27
|
+
* @since 0.2.0
|
|
28
|
+
* @author AMBROISE PARK Consulting
|
|
29
|
+
*/
|
|
30
|
+
export declare const MIN_ORDER_API_VERSION = "2025-02-24.acacia";
|
|
31
|
+
/** Metadata key carrying the app order ID on the Checkout Session. */
|
|
32
|
+
export declare const ORDER_ID_METADATA_KEY = "orderId";
|
|
33
|
+
/** Product metadata key carrying the app product ID on each line. */
|
|
34
|
+
export declare const PRODUCT_ID_METADATA_KEY = "productId";
|
|
35
|
+
/**
|
|
36
|
+
* Map a Stripe Checkout Session to the provider-neutral snapshot given to order hooks.
|
|
37
|
+
*
|
|
38
|
+
* @param session - Checkout Session from a webhook event
|
|
39
|
+
* @returns Snapshot (amounts in the smallest currency unit)
|
|
40
|
+
*
|
|
41
|
+
* @version 0.2.0
|
|
42
|
+
* @since 0.2.0
|
|
43
|
+
* @author AMBROISE PARK Consulting
|
|
44
|
+
*/
|
|
45
|
+
export declare function toCheckoutSessionSnapshot(session: Stripe.Checkout.Session): CheckoutSessionSnapshot;
|
|
46
|
+
/**
|
|
47
|
+
* Read the charged lines of a session back from Stripe.
|
|
48
|
+
*
|
|
49
|
+
* @param stripe - Stripe client
|
|
50
|
+
* @param sessionId - Checkout Session ID
|
|
51
|
+
* @returns Lines with the app product ID and charged amounts
|
|
52
|
+
* @throws When a line carries no app product ID (not created by the framework)
|
|
53
|
+
*
|
|
54
|
+
* @version 0.2.0
|
|
55
|
+
* @since 0.2.0
|
|
56
|
+
* @author AMBROISE PARK Consulting
|
|
57
|
+
*/
|
|
58
|
+
export declare function listPaidLineItems(stripe: Stripe, sessionId: string): Promise<PaidLineItem[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Route one Checkout Session event of a StripeOrder item to the app hooks.
|
|
61
|
+
*
|
|
62
|
+
* - `completed` + `paid` / `no_payment_required` → `onOrderPaid`
|
|
63
|
+
* - `completed` + `unpaid` (async method, e.g. SEPA debit) → wait for the async event
|
|
64
|
+
* - `async_payment_succeeded` → `onOrderPaid`
|
|
65
|
+
* - `async_payment_failed` → `onOrderPaymentFailed`
|
|
66
|
+
* - `expired` → `onOrderExpired`
|
|
67
|
+
*
|
|
68
|
+
* @throws When the event API version is older than {@link MIN_ORDER_API_VERSION},
|
|
69
|
+
* when metadata is incomplete, or when a hook throws
|
|
70
|
+
*
|
|
71
|
+
* @version 0.2.0
|
|
72
|
+
* @since 0.2.0
|
|
73
|
+
* @author AMBROISE PARK Consulting
|
|
74
|
+
*/
|
|
75
|
+
export declare function handleOrderSessionEvent(eventType: OrderSessionEventType, eventId: string, apiVersion: string | null, session: Stripe.Checkout.Session, billingConfigKey: string, orderItem: StripeOrderBackItem, stripe: Stripe): Promise<void>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Postgres (Supabase) webhook idempotency store
|
|
3
|
+
* @description `webhook_events` table and its RPCs. Re-exported from
|
|
4
|
+
* `idempotency.ts`.
|
|
5
|
+
*
|
|
6
|
+
* @version 0.2.0
|
|
7
|
+
* @since 0.2.0
|
|
8
|
+
* @author AMBROISE PARK Consulting
|
|
9
|
+
*/
|
|
10
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
11
|
+
import type { IdempotencyStore } from './idempotencyContract.js';
|
|
12
|
+
/**
|
|
13
|
+
* SQL required by {@link createSupabaseIdempotencyStore}: table, the
|
|
14
|
+
* service_role-only RPCs `webhook_event_reserve` / `webhook_event_mark_processed`
|
|
15
|
+
* / `webhook_event_release`, and a daily pg_cron cleanup (30 days). Shipped
|
|
16
|
+
* verbatim as the CLI Supabase template migration `*_webhook_events.sql`.
|
|
17
|
+
*
|
|
18
|
+
* @version 0.2.0
|
|
19
|
+
* @since 0.2.0
|
|
20
|
+
* @author AMBROISE PARK Consulting
|
|
21
|
+
*/
|
|
22
|
+
export declare const WEBHOOK_EVENTS_SQL = "\nCREATE TABLE IF NOT EXISTS public.webhook_events (\n event_id TEXT PRIMARY KEY,\n status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),\n owner_token UUID NOT NULL,\n reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n processed_at TIMESTAMPTZ\n);\n\n-- Only service_role accesses this table\nALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;\n\nCREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at\n ON public.webhook_events (processed_at);\n\n-- The functions below run as the caller (SECURITY INVOKER) and refuse every\n-- role but service_role. EXECUTE is deliberately not revoked: on Supabase\n-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated\n-- crashes the backend (signal 11), which restarts every connection.\nCREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()\nRETURNS VOID\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n IF current_user IS DISTINCT FROM 'service_role' THEN\n RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user\n USING ERRCODE = 'insufficient_privilege';\n END IF;\nEND;\n$$;\n\n-- Atomic reservation. Returns:\n-- 'reserved' the caller now owns the event under p_owner_token\n-- 'processed' the event was already processed (skip, answer 2xx)\n-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)\n-- A 'processing' row older than the lease is retaken (abandoned worker).\nCREATE OR REPLACE FUNCTION public.webhook_event_reserve(\n p_event_id TEXT,\n p_owner_token UUID,\n p_lease_seconds INT\n)\nRETURNS TEXT\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nDECLARE\n v_status TEXT;\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)\n VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())\n ON CONFLICT (event_id) DO UPDATE\n SET owner_token = EXCLUDED.owner_token,\n reserved_at = clock_timestamp()\n WHERE webhook_events.status = 'processing'\n AND webhook_events.reserved_at\n < clock_timestamp() - make_interval(secs => p_lease_seconds);\n IF FOUND THEN\n RETURN 'reserved';\n END IF;\n\n SELECT status INTO v_status\n FROM public.webhook_events\n WHERE event_id = p_event_id;\n IF v_status = 'processed' THEN\n RETURN 'processed';\n END IF;\n -- Live lease, or the row was released in between: Stripe retries either way\n RETURN 'in_progress';\nEND;\n$$;\n\n-- Mark a reservation processed. Returns false when p_owner_token no longer owns\n-- the row (lease retaken, released, or deleted). Repeating it for the same\n-- owner is a no-op that returns true.\nCREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(\n p_event_id TEXT,\n p_owner_token UUID\n)\nRETURNS BOOLEAN\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n UPDATE public.webhook_events\n SET status = 'processed',\n processed_at = COALESCE(processed_at, clock_timestamp())\n WHERE event_id = p_event_id\n AND owner_token = p_owner_token;\n RETURN FOUND;\nEND;\n$$;\n\n-- Drop a reservation after a processing failure. Returns false when\n-- p_owner_token does not own a 'processing' row (nothing is deleted).\nCREATE OR REPLACE FUNCTION public.webhook_event_release(\n p_event_id TEXT,\n p_owner_token UUID\n)\nRETURNS BOOLEAN\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n DELETE FROM public.webhook_events\n WHERE event_id = p_event_id\n AND owner_token = p_owner_token\n AND status = 'processing';\n RETURN FOUND;\nEND;\n$$;\n\n-- Enable pg_cron extension (if not already enabled)\nCREATE EXTENSION IF NOT EXISTS pg_cron;\n\n-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).\n-- Stripe retries an event for up to 3 days, so older rows are never read again.\nSELECT cron.schedule(\n 'cleanup-webhook-events',\n '0 5 * * *',\n $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$\n);\n";
|
|
23
|
+
/**
|
|
24
|
+
* Postgres-backed store (Supabase). Requires {@link WEBHOOK_EVENTS_SQL}.
|
|
25
|
+
*
|
|
26
|
+
* @param supabaseAdmin - Supabase client created with the service role key
|
|
27
|
+
*
|
|
28
|
+
* @version 0.2.0
|
|
29
|
+
* @since 0.2.0
|
|
30
|
+
* @author AMBROISE PARK Consulting
|
|
31
|
+
*/
|
|
32
|
+
export declare function createSupabaseIdempotencyStore(supabaseAdmin: SupabaseClient): IdempotencyStore;
|