@donotdev/functions 0.2.0 → 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/lib/chunks/{chunk-IFOYVSPU.js → chunk-3F4BWKQD.js} +2 -2
- package/lib/chunks/{chunk-JTAGPPPL.js → chunk-5IPULSUX.js} +2 -2
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.js.map +7 -0
- package/lib/chunks/{chunk-RM7DV6IQ.js → chunk-CXBSROEW.js} +2 -2
- package/lib/chunks/{chunk-5DTPEM64.js → chunk-GYTCWMXV.js} +1 -1
- package/lib/chunks/{chunk-5DTPEM64.js.map → chunk-GYTCWMXV.js.map} +1 -1
- package/lib/chunks/chunk-LCDLG4VG.js +151 -0
- package/lib/chunks/{chunk-UH4L3EF3.js.map → chunk-LCDLG4VG.js.map} +4 -4
- package/lib/chunks/{chunk-4U7QQWYG.js → chunk-MQANUSY3.js} +2 -2
- 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-QJAU2MWV.js → chunk-US2VOP4S.js} +2 -2
- package/lib/chunks/{chunk-QJAU2MWV.js.map → chunk-US2VOP4S.js.map} +3 -3
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/{monitoring-AGCSU3FI.js → monitoring-E7JBYBHQ.js} +2 -2
- package/lib/chunks/{rateLimiter-6KO7AIZP.js → rateLimiter-SQISLOP5.js} +2 -2
- package/lib/chunks/{server-32A5RH4C.js → server-IQ5JNJOM.js} +2 -2
- package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
- package/lib/firebase/baseFunction.d.ts +0 -0
- 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 +0 -0
- package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +0 -0
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/firebase/billing/webhookHandler.d.ts +0 -0
- 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 -0
- package/lib/firebase/crud/create.d.ts +0 -0
- package/lib/firebase/crud/delete.d.ts +0 -0
- package/lib/firebase/crud/get.d.ts +0 -0
- package/lib/firebase/crud/index.d.ts +0 -0
- package/lib/firebase/crud/list.d.ts +0 -0
- package/lib/firebase/crud/update.d.ts +0 -0
- 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 -1
- package/lib/firebase/index.js.map +2 -2
- 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 +0 -0
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +0 -0
- 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/createCheckout.d.ts +0 -0
- package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
- package/lib/shared/billing/helpers/index.d.ts +0 -0
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
- package/lib/shared/billing/idempotency.d.ts +1 -12
- package/lib/shared/billing/index.d.ts +0 -0
- package/lib/shared/billing/stripeClient.d.ts +45 -0
- package/lib/shared/billing/webhookHandler.d.ts +5 -4
- 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 -1
- package/lib/shared/index.js.map +0 -0
- 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 +0 -0
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +0 -0
- 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 +0 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -8
- package/lib/shared/utils/schemaValidation.d.ts +0 -0
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +0 -0
- package/lib/shared/utils.d.ts +0 -43
- 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 +0 -0
- 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/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +0 -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 +0 -0
- package/lib/supabase/index.d.ts +3 -2
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +3 -3
- 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 +0 -0
- package/lib/vercel/api/ai/chat.d.ts +0 -0
- package/lib/vercel/api/ai/index.d.ts +0 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
- package/lib/vercel/api/billing/cancel.d.ts +0 -0
- package/lib/vercel/api/billing/change-plan.d.ts +0 -0
- package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
- package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
- package/lib/vercel/api/billing/index.d.ts +0 -0
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
- package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/create.d.ts +0 -0
- package/lib/vercel/api/crud/delete.d.ts +0 -0
- package/lib/vercel/api/crud/get.d.ts +0 -0
- package/lib/vercel/api/crud/index.d.ts +0 -0
- package/lib/vercel/api/crud/list.d.ts +0 -0
- package/lib/vercel/api/crud/update.d.ts +0 -0
- package/lib/vercel/api/index.d.ts +0 -0
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +2 -2
- package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +0 -0
- package/package.json +2 -2
- package/src/firebase/billing/cancelSubscription.ts +1 -1
- package/src/firebase/billing/changePlan.ts +1 -5
- package/src/firebase/billing/createCheckoutSession.ts +1 -5
- package/src/firebase/billing/createCustomerPortal.ts +1 -1
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
- package/src/firebase/billing/webhookHandler.ts +2 -2
- package/src/shared/__tests__/internalValidation.test.ts +1 -40
- package/src/shared/__tests__/logger.test.ts +31 -0
- package/src/shared/__tests__/utils.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -38
- package/src/shared/billing/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +1 -1
- package/src/shared/billing/idempotency.ts +5 -172
- package/src/shared/billing/stripeClient.ts +91 -0
- package/src/shared/billing/webhookHandler.ts +5 -5
- package/src/shared/logger.ts +4 -6
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils.ts +0 -77
- package/src/supabase/billing/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +1 -5
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -5
- package/src/supabase/billing/stripeWebhook.ts +2 -2
- package/src/supabase/crud/list.ts +2 -0
- package/src/supabase/index.ts +3 -3
- package/src/vercel/api/billing/change-plan.ts +1 -1
- package/src/vercel/api/billing/create-checkout-session.ts +1 -5
- package/src/vercel/api/billing/customer-portal.ts +1 -1
- package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
- package/src/vercel/api/billing/webhook-handler.ts +1 -1
- package/lib/chunks/chunk-2JL3GDTO.js +0 -151
- package/lib/chunks/chunk-2JL3GDTO.js.map +0 -7
- package/lib/chunks/chunk-4TVLH2W2.js +0 -22
- package/lib/chunks/chunk-6CQXHNVL.js +0 -22
- package/lib/chunks/chunk-6CQXHNVL.js.map +0 -7
- package/lib/chunks/chunk-6DSCPZC6.js +0 -22
- package/lib/chunks/chunk-6DSCPZC6.js.map +0 -7
- package/lib/chunks/chunk-7E6TGWHU.js +0 -22
- package/lib/chunks/chunk-7E6TGWHU.js.map +0 -7
- package/lib/chunks/chunk-7LT32OWE.js +0 -22
- package/lib/chunks/chunk-7VH2GJXT.js +0 -151
- package/lib/chunks/chunk-7VH2GJXT.js.map +0 -7
- package/lib/chunks/chunk-API5A4BV.js +0 -22
- package/lib/chunks/chunk-API5A4BV.js.map +0 -7
- package/lib/chunks/chunk-BUP7SXPV.js +0 -23
- package/lib/chunks/chunk-BXKRI3JJ.js +0 -22
- package/lib/chunks/chunk-BXKRI3JJ.js.map +0 -7
- package/lib/chunks/chunk-FSLGZD7A.js +0 -21
- package/lib/chunks/chunk-GVLSPWDD.js +0 -151
- package/lib/chunks/chunk-GVLSPWDD.js.map +0 -7
- package/lib/chunks/chunk-GXQVWEFT.js +0 -22
- package/lib/chunks/chunk-GXQVWEFT.js.map +0 -7
- package/lib/chunks/chunk-HB7EGXVI.js +0 -22
- package/lib/chunks/chunk-HB7EGXVI.js.map +0 -7
- package/lib/chunks/chunk-HM7XCMWW.js +0 -22
- package/lib/chunks/chunk-HM7XCMWW.js.map +0 -7
- package/lib/chunks/chunk-I7IOIL6U.js +0 -151
- package/lib/chunks/chunk-I7IOIL6U.js.map +0 -7
- package/lib/chunks/chunk-IFOYVSPU.js.map +0 -7
- package/lib/chunks/chunk-JTAGPPPL.js.map +0 -7
- package/lib/chunks/chunk-MZ232FUE.js +0 -22
- package/lib/chunks/chunk-MZ232FUE.js.map +0 -7
- package/lib/chunks/chunk-NE5ZTUUZ.js +0 -22
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +0 -7
- package/lib/chunks/chunk-NP2AN2TV.js +0 -22
- package/lib/chunks/chunk-NP2AN2TV.js.map +0 -7
- package/lib/chunks/chunk-RM7DV6IQ.js.map +0 -7
- package/lib/chunks/chunk-RQZGIZHD.js +0 -151
- package/lib/chunks/chunk-RQZGIZHD.js.map +0 -7
- package/lib/chunks/chunk-TBEDQLOB.js +0 -23
- package/lib/chunks/chunk-TBEDQLOB.js.map +0 -7
- package/lib/chunks/chunk-TMHBP3HB.js +0 -22
- package/lib/chunks/chunk-TMHBP3HB.js.map +0 -7
- package/lib/chunks/chunk-UH4L3EF3.js +0 -151
- package/lib/chunks/chunk-UJBIU6TL.js +0 -22
- package/lib/chunks/chunk-UJBIU6TL.js.map +0 -7
- package/lib/chunks/chunk-VKEYW3NT.js +0 -22
- package/lib/chunks/chunk-VKEYW3NT.js.map +0 -7
- package/lib/chunks/chunk-XGXBMXJ6.js +0 -22
- package/lib/chunks/chunk-XGXBMXJ6.js.map +0 -7
- package/lib/chunks/chunk-Y44NEQQG.js +0 -22
- package/lib/chunks/chunk-Y44NEQQG.js.map +0 -7
- package/lib/chunks/chunk-ZVU3KPXI.js +0 -22
- package/lib/chunks/chunk-ZVU3KPXI.js.map +0 -7
- package/lib/chunks/monitoring-PVQMFL34.js +0 -22
- package/lib/chunks/monitoring-V7FZXTTW.js +0 -22
- package/lib/chunks/monitoring-V7FZXTTW.js.map +0 -7
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +0 -7
- package/lib/chunks/rateLimiter-OXVBFW5C.js +0 -22
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +0 -7
- package/lib/chunks/rateLimiter-U45OMTWR.js +0 -22
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +0 -7
- package/lib/chunks/server-32A5RH4C.js.map +0 -7
- package/lib/chunks/server-7HDAP5DL.js +0 -22
- package/lib/chunks/server-7HDAP5DL.js.map +0 -7
- package/lib/chunks/server-S2IMFOY7.js +0 -22
- package/lib/chunks/server-S2IMFOY7.js.map +0 -7
- 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
- /package/lib/chunks/{chunk-7LT32OWE.js.map → chunk-3F4BWKQD.js.map} +0 -0
- /package/lib/chunks/{chunk-4TVLH2W2.js.map → chunk-5IPULSUX.js.map} +0 -0
- /package/lib/chunks/{chunk-BUP7SXPV.js.map → chunk-CXBSROEW.js.map} +0 -0
- /package/lib/chunks/{chunk-4U7QQWYG.js.map → chunk-MQANUSY3.js.map} +0 -0
- /package/lib/chunks/{chunk-FSLGZD7A.js.map → monitoring-E7JBYBHQ.js.map} +0 -0
- /package/lib/chunks/{monitoring-AGCSU3FI.js.map → rateLimiter-SQISLOP5.js.map} +0 -0
- /package/lib/chunks/{monitoring-PVQMFL34.js.map → server-IQ5JNJOM.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as v from 'valibot';
|
|
2
|
-
import { describe, it, expect, vi
|
|
2
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
3
3
|
|
|
4
4
|
// Mock external deps
|
|
5
5
|
vi.mock('@donotdev/core/server', () => {
|
|
@@ -22,7 +22,6 @@ import {
|
|
|
22
22
|
safeJsonParse,
|
|
23
23
|
validateCollectionName,
|
|
24
24
|
validateDocument,
|
|
25
|
-
validateStripeEnvironment,
|
|
26
25
|
} from '../utils/internal/validation';
|
|
27
26
|
|
|
28
27
|
// ---------------------------------------------------------------------------
|
|
@@ -156,41 +155,3 @@ describe('validateDocument (internal)', () => {
|
|
|
156
155
|
expect(() => validateDocument({ anything: 'goes' })).not.toThrow();
|
|
157
156
|
});
|
|
158
157
|
});
|
|
159
|
-
|
|
160
|
-
// ---------------------------------------------------------------------------
|
|
161
|
-
// validateStripeEnvironment (internal version)
|
|
162
|
-
// ---------------------------------------------------------------------------
|
|
163
|
-
|
|
164
|
-
describe('validateStripeEnvironment (internal)', () => {
|
|
165
|
-
const originalEnv = { ...process.env };
|
|
166
|
-
|
|
167
|
-
beforeEach(() => {
|
|
168
|
-
delete process.env.STRIPE_SECRET_KEY;
|
|
169
|
-
delete process.env.STRIPE_WEBHOOK_SECRET;
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
afterEach(() => {
|
|
173
|
-
process.env = { ...originalEnv };
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
it('throws when both vars missing', () => {
|
|
177
|
-
expect(() => validateStripeEnvironment()).toThrow(
|
|
178
|
-
'Missing required environment variables'
|
|
179
|
-
);
|
|
180
|
-
expect(() => validateStripeEnvironment()).toThrow('STRIPE_SECRET_KEY');
|
|
181
|
-
expect(() => validateStripeEnvironment()).toThrow('STRIPE_WEBHOOK_SECRET');
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
it('throws when STRIPE_WEBHOOK_SECRET missing', () => {
|
|
185
|
-
process.env.STRIPE_SECRET_KEY = 'sk_test_x';
|
|
186
|
-
|
|
187
|
-
expect(() => validateStripeEnvironment()).toThrow('STRIPE_WEBHOOK_SECRET');
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
it('passes when all vars set', () => {
|
|
191
|
-
process.env.STRIPE_SECRET_KEY = 'sk_test_x';
|
|
192
|
-
process.env.STRIPE_WEBHOOK_SECRET = 'whsec_x';
|
|
193
|
-
|
|
194
|
-
expect(() => validateStripeEnvironment()).not.toThrow();
|
|
195
|
-
});
|
|
196
|
-
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { describe, it, expect, vi, afterEach } from 'vitest';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Regression: Supabase Edge Runtime defines `window` (= globalThis) but no
|
|
5
|
+
* `document`. A module-level `'window' in globalThis` guard made the logger
|
|
6
|
+
* throw on import, failing every Supabase edge function with WORKER_ERROR.
|
|
7
|
+
*/
|
|
8
|
+
describe('logger on a runtime that defines window (Supabase Edge shape)', () => {
|
|
9
|
+
const g = globalThis as Record<string, unknown>;
|
|
10
|
+
|
|
11
|
+
afterEach(() => {
|
|
12
|
+
delete g.window;
|
|
13
|
+
vi.restoreAllMocks();
|
|
14
|
+
vi.resetModules();
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('imports and logs when window is defined and document is not', async () => {
|
|
18
|
+
g.window = globalThis;
|
|
19
|
+
expect(typeof (globalThis as { document?: unknown }).document).toBe(
|
|
20
|
+
'undefined'
|
|
21
|
+
);
|
|
22
|
+
vi.resetModules();
|
|
23
|
+
|
|
24
|
+
const { logger } = await import('../logger');
|
|
25
|
+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
26
|
+
|
|
27
|
+
logger.error('edge boot ok');
|
|
28
|
+
|
|
29
|
+
expect(spy).toHaveBeenCalled();
|
|
30
|
+
});
|
|
31
|
+
});
|
|
@@ -47,8 +47,8 @@ import {
|
|
|
47
47
|
validateDocument,
|
|
48
48
|
validateCollectionName,
|
|
49
49
|
assertAuthenticated,
|
|
50
|
-
validateStripeEnvironment,
|
|
51
50
|
} from '../utils';
|
|
51
|
+
import { validateStripeEnvironment } from '../billing/stripeClient';
|
|
52
52
|
|
|
53
53
|
// Need to import DoNotDevError from the mocked module for instanceof checks
|
|
54
54
|
|
|
@@ -88,10 +88,7 @@ vi.mock('../../logger.js', () => ({
|
|
|
88
88
|
},
|
|
89
89
|
}));
|
|
90
90
|
|
|
91
|
-
import {
|
|
92
|
-
createInMemoryIdempotencyStore,
|
|
93
|
-
resetIdempotencyStore as resetLegacyIdempotencyStore,
|
|
94
|
-
} from '../idempotency.js';
|
|
91
|
+
import { createInMemoryIdempotencyStore } from '../idempotency.js';
|
|
95
92
|
import type { IdempotencyStore } from '../idempotency.js';
|
|
96
93
|
import { processWebhook } from '../webhookHandler.js';
|
|
97
94
|
import type { BillingAuthProvider, UpdateSubscriptionFn } from '@donotdev/core/server';
|
|
@@ -1531,37 +1528,3 @@ describe('event routing — StripeOrder', () => {
|
|
|
1531
1528
|
expect(updateSubscription).not.toHaveBeenCalled();
|
|
1532
1529
|
});
|
|
1533
1530
|
});
|
|
1534
|
-
|
|
1535
|
-
// ---------------------------------------------------------------------------
|
|
1536
|
-
|
|
1537
|
-
describe('processWebhook — 0.1.x call without a store', () => {
|
|
1538
|
-
beforeEach(() => {
|
|
1539
|
-
resetLegacyIdempotencyStore();
|
|
1540
|
-
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1541
|
-
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
1542
|
-
});
|
|
1543
|
-
|
|
1544
|
-
it('falls back to the deprecated auto-detected store and still deduplicates', async () => {
|
|
1545
|
-
const event = makeEvent('checkout.session.completed', {
|
|
1546
|
-
metadata: { userId: 'u_legacy', billingConfigKey: 'pro_monthly' },
|
|
1547
|
-
subscription: 'sub_legacy',
|
|
1548
|
-
customer: 'cus_legacy',
|
|
1549
|
-
});
|
|
1550
|
-
const updateSubscription = makeUpdateSubscription();
|
|
1551
|
-
const call = () =>
|
|
1552
|
-
processWebhook(
|
|
1553
|
-
RAW_BODY,
|
|
1554
|
-
SIGNATURE,
|
|
1555
|
-
WEBHOOK_SECRET,
|
|
1556
|
-
makeStripe(event),
|
|
1557
|
-
makeConfig(),
|
|
1558
|
-
updateSubscription,
|
|
1559
|
-
makeAuthProvider()
|
|
1560
|
-
);
|
|
1561
|
-
|
|
1562
|
-
await call();
|
|
1563
|
-
const second = await call();
|
|
1564
|
-
expect(second.message).toBe('Event already processed');
|
|
1565
|
-
expect(updateSubscription).toHaveBeenCalledOnce();
|
|
1566
|
-
});
|
|
1567
|
-
});
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/firestoreIdempotency.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Firestore webhook idempotency store
|
|
5
|
+
* @description `webhook_idempotency` collection, transactional reservations.
|
|
6
|
+
* Used by the Firebase and Vercel (Firestore backend) webhook entry points.
|
|
7
|
+
* Re-exported from `idempotency.ts`. Loads `@donotdev/firebase/server` on
|
|
8
|
+
* first use only.
|
|
9
|
+
*
|
|
10
|
+
* @version 0.2.1
|
|
11
|
+
* @since 0.2.0
|
|
12
|
+
* @author AMBROISE PARK Consulting
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import * as v from 'valibot';
|
|
16
|
+
|
|
17
|
+
import { handleError } from '../errorHandling.js';
|
|
18
|
+
import {
|
|
19
|
+
RESERVATION_LEASE_MS,
|
|
20
|
+
ReservationLostError,
|
|
21
|
+
WEBHOOK_EVENT_RETENTION_MS,
|
|
22
|
+
newOwnerToken,
|
|
23
|
+
} from './idempotencyContract.js';
|
|
24
|
+
import type {
|
|
25
|
+
LegacyIdempotencyStore,
|
|
26
|
+
ReservationResult,
|
|
27
|
+
} from './idempotencyContract.js';
|
|
28
|
+
|
|
29
|
+
/** Firestore collection holding webhook event reservations (name kept from 0.1.x). */
|
|
30
|
+
const FIRESTORE_COLLECTION = 'webhook_idempotency';
|
|
31
|
+
|
|
32
|
+
/** Millisecond reading of an `expiresAt` value: Timestamp (0.2.x) or number (0.1.x). */
|
|
33
|
+
const ExpiresAtSchema = v.union([
|
|
34
|
+
v.number(),
|
|
35
|
+
v.pipe(
|
|
36
|
+
v.custom<{ toMillis(): number }>(
|
|
37
|
+
(value) =>
|
|
38
|
+
typeof value === 'object' &&
|
|
39
|
+
value !== null &&
|
|
40
|
+
typeof (value as { toMillis?: unknown }).toMillis === 'function',
|
|
41
|
+
'expiresAt must be a Firestore Timestamp or a number'
|
|
42
|
+
),
|
|
43
|
+
v.transform((timestamp) => timestamp.toMillis())
|
|
44
|
+
),
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Stored reservation document. 0.1.x documents carry no `status` and mean processed.
|
|
49
|
+
*/
|
|
50
|
+
const FirestoreEventDocSchema = v.object({
|
|
51
|
+
status: v.optional(v.picklist(['processing', 'processed'])),
|
|
52
|
+
ownerToken: v.optional(v.string()),
|
|
53
|
+
reservedAt: v.optional(v.number()),
|
|
54
|
+
expiresAt: v.optional(ExpiresAtSchema),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
function parseEventDoc(eventId: string, data: unknown) {
|
|
58
|
+
const result = v.safeParse(FirestoreEventDocSchema, data);
|
|
59
|
+
if (!result.success) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Malformed ${FIRESTORE_COLLECTION}/${eventId}: ${result.issues.map((issue) => issue.message).join('; ')}`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return result.output;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Firestore-backed store (transactions). Collection: `webhook_idempotency`.
|
|
69
|
+
*
|
|
70
|
+
* `expiresAt` is a Firestore Timestamp {@link WEBHOOK_EVENT_RETENTION_MS} after
|
|
71
|
+
* the last write: enable a TTL policy on `webhook_idempotency.expiresAt` so
|
|
72
|
+
* Firestore deletes old documents.
|
|
73
|
+
*
|
|
74
|
+
* @version 0.2.0
|
|
75
|
+
* @since 0.2.0
|
|
76
|
+
* @author AMBROISE PARK Consulting
|
|
77
|
+
*/
|
|
78
|
+
export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
|
|
79
|
+
let firebase: typeof import('@donotdev/firebase/server') | null = null;
|
|
80
|
+
const load = async () => {
|
|
81
|
+
if (!firebase) firebase = await import('@donotdev/firebase/server');
|
|
82
|
+
const firestore = firebase.getFirebaseAdminFirestore();
|
|
83
|
+
return {
|
|
84
|
+
firestore,
|
|
85
|
+
Timestamp: firebase.Timestamp,
|
|
86
|
+
refOf: (eventId: string) =>
|
|
87
|
+
firestore.collection(FIRESTORE_COLLECTION).doc(eventId),
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const reserve = async (eventId: string): Promise<ReservationResult> => {
|
|
92
|
+
const { firestore, Timestamp, refOf } = await load();
|
|
93
|
+
const ref = refOf(eventId);
|
|
94
|
+
try {
|
|
95
|
+
return await firestore.runTransaction(async (tx) => {
|
|
96
|
+
const snapshot = await tx.get(ref);
|
|
97
|
+
const now = Date.now();
|
|
98
|
+
if (snapshot.exists) {
|
|
99
|
+
const data = parseEventDoc(eventId, snapshot.data());
|
|
100
|
+
if (data.status === 'processing') {
|
|
101
|
+
if (now - (data.reservedAt ?? 0) < RESERVATION_LEASE_MS) {
|
|
102
|
+
return { state: 'in_progress' } as const;
|
|
103
|
+
}
|
|
104
|
+
} else if ((data.expiresAt ?? 0) >= now) {
|
|
105
|
+
return { state: 'processed' } as const;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const ownerToken = newOwnerToken();
|
|
109
|
+
tx.set(ref, {
|
|
110
|
+
eventId,
|
|
111
|
+
status: 'processing',
|
|
112
|
+
ownerToken,
|
|
113
|
+
reservedAt: now,
|
|
114
|
+
expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
|
|
115
|
+
});
|
|
116
|
+
return { state: 'reserved', ownerToken } as const;
|
|
117
|
+
});
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw handleError(error);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
reserve,
|
|
125
|
+
async checkAndReserve(eventId) {
|
|
126
|
+
return (await reserve(eventId)).state !== 'reserved';
|
|
127
|
+
},
|
|
128
|
+
async markProcessed(eventId, ownerToken) {
|
|
129
|
+
const { firestore, Timestamp, refOf } = await load();
|
|
130
|
+
const ref = refOf(eventId);
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
const processed = {
|
|
133
|
+
eventId,
|
|
134
|
+
status: 'processed',
|
|
135
|
+
processedAt: now,
|
|
136
|
+
expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
|
|
137
|
+
};
|
|
138
|
+
try {
|
|
139
|
+
if (ownerToken === undefined) {
|
|
140
|
+
// 0.1.x call: unconditional write
|
|
141
|
+
await ref.set(processed);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
await firestore.runTransaction(async (tx) => {
|
|
145
|
+
const snapshot = await tx.get(ref);
|
|
146
|
+
const data = snapshot.exists
|
|
147
|
+
? parseEventDoc(eventId, snapshot.data())
|
|
148
|
+
: null;
|
|
149
|
+
if (data?.ownerToken !== ownerToken) {
|
|
150
|
+
throw new ReservationLostError(eventId);
|
|
151
|
+
}
|
|
152
|
+
tx.set(ref, { ...processed, ownerToken });
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error instanceof ReservationLostError) throw error;
|
|
156
|
+
throw handleError(error);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
async release(eventId, ownerToken) {
|
|
160
|
+
const { firestore, refOf } = await load();
|
|
161
|
+
const ref = refOf(eventId);
|
|
162
|
+
try {
|
|
163
|
+
return await firestore.runTransaction(async (tx) => {
|
|
164
|
+
const snapshot = await tx.get(ref);
|
|
165
|
+
if (!snapshot.exists) return false;
|
|
166
|
+
const data = parseEventDoc(eventId, snapshot.data());
|
|
167
|
+
if (data.status !== 'processing' || data.ownerToken !== ownerToken) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
tx.delete(ref);
|
|
171
|
+
return true;
|
|
172
|
+
});
|
|
173
|
+
} catch (error) {
|
|
174
|
+
throw handleError(error);
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
async isProcessed(eventId) {
|
|
178
|
+
const { refOf } = await load();
|
|
179
|
+
try {
|
|
180
|
+
const snapshot = await refOf(eventId).get();
|
|
181
|
+
if (!snapshot.exists) return false;
|
|
182
|
+
const data = parseEventDoc(eventId, snapshot.data());
|
|
183
|
+
return data.status !== 'processing' && (data.expiresAt ?? 0) >= Date.now();
|
|
184
|
+
} catch (error) {
|
|
185
|
+
throw handleError(error);
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
@@ -16,7 +16,7 @@ import type { BillingAuthProvider } from '@donotdev/core/server';
|
|
|
16
16
|
|
|
17
17
|
import { updateUserSubscription } from './updateUserSubscription.js';
|
|
18
18
|
import { handleError } from '../../errorHandling.js';
|
|
19
|
-
import { stripe, validateStripeEnvironment } from '
|
|
19
|
+
import { stripe, validateStripeEnvironment } from '../stripeClient.js';
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
22
|
* Cancel user subscription at period end
|
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
* @fileoverview Webhook idempotency stores
|
|
5
5
|
* @description Durable, atomic event reservation for Stripe webhooks. Every
|
|
6
6
|
* webhook entry point passes the store that matches its backend: Firestore
|
|
7
|
-
* (Firebase
|
|
8
|
-
* implicit fallback.
|
|
7
|
+
* (Firebase, Vercel: `firestoreIdempotency.ts`) or Postgres (Supabase:
|
|
8
|
+
* `supabaseIdempotency.ts`). There is no implicit fallback. This module
|
|
9
|
+
* aggregates the stores; backend entry points import their own store file.
|
|
9
10
|
*
|
|
10
11
|
* Lifecycle per event: `reserve` → process → `markProcessed(ownerToken)`, or
|
|
11
12
|
* `release(ownerToken)` when processing failed (so the provider's retry is
|
|
@@ -17,14 +18,11 @@
|
|
|
17
18
|
* @author AMBROISE PARK Consulting
|
|
18
19
|
*/
|
|
19
20
|
|
|
20
|
-
import * as v from 'valibot';
|
|
21
|
-
|
|
22
|
-
import { handleError } from '../errorHandling.js';
|
|
23
21
|
import { isFirestoreConfigured } from '../utils/detectFirestore.js';
|
|
22
|
+
import { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
|
|
24
23
|
import {
|
|
25
24
|
RESERVATION_LEASE_MS,
|
|
26
25
|
ReservationLostError,
|
|
27
|
-
WEBHOOK_EVENT_RETENTION_MS,
|
|
28
26
|
newOwnerToken,
|
|
29
27
|
} from './idempotencyContract.js';
|
|
30
28
|
import type {
|
|
@@ -42,9 +40,7 @@ export type {
|
|
|
42
40
|
LegacyIdempotencyStore,
|
|
43
41
|
ReservationResult,
|
|
44
42
|
} from './idempotencyContract.js';
|
|
45
|
-
|
|
46
|
-
/** Firestore collection holding webhook event reservations (name kept from 0.1.x). */
|
|
47
|
-
const FIRESTORE_COLLECTION = 'webhook_idempotency';
|
|
43
|
+
export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
|
|
48
44
|
|
|
49
45
|
// =============================================================================
|
|
50
46
|
// In-memory (tests only)
|
|
@@ -103,169 +99,6 @@ export function createInMemoryIdempotencyStore(): LegacyIdempotencyStore {
|
|
|
103
99
|
};
|
|
104
100
|
}
|
|
105
101
|
|
|
106
|
-
// =============================================================================
|
|
107
|
-
// Firestore
|
|
108
|
-
// =============================================================================
|
|
109
|
-
|
|
110
|
-
/** Millisecond reading of an `expiresAt` value: Timestamp (0.2.x) or number (0.1.x). */
|
|
111
|
-
const ExpiresAtSchema = v.union([
|
|
112
|
-
v.number(),
|
|
113
|
-
v.pipe(
|
|
114
|
-
v.custom<{ toMillis(): number }>(
|
|
115
|
-
(value) =>
|
|
116
|
-
typeof value === 'object' &&
|
|
117
|
-
value !== null &&
|
|
118
|
-
typeof (value as { toMillis?: unknown }).toMillis === 'function',
|
|
119
|
-
'expiresAt must be a Firestore Timestamp or a number'
|
|
120
|
-
),
|
|
121
|
-
v.transform((timestamp) => timestamp.toMillis())
|
|
122
|
-
),
|
|
123
|
-
]);
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Stored reservation document. 0.1.x documents carry no `status` and mean processed.
|
|
127
|
-
*/
|
|
128
|
-
const FirestoreEventDocSchema = v.object({
|
|
129
|
-
status: v.optional(v.picklist(['processing', 'processed'])),
|
|
130
|
-
ownerToken: v.optional(v.string()),
|
|
131
|
-
reservedAt: v.optional(v.number()),
|
|
132
|
-
expiresAt: v.optional(ExpiresAtSchema),
|
|
133
|
-
});
|
|
134
|
-
|
|
135
|
-
function parseEventDoc(eventId: string, data: unknown) {
|
|
136
|
-
const result = v.safeParse(FirestoreEventDocSchema, data);
|
|
137
|
-
if (!result.success) {
|
|
138
|
-
throw new Error(
|
|
139
|
-
`Malformed ${FIRESTORE_COLLECTION}/${eventId}: ${result.issues.map((issue) => issue.message).join('; ')}`
|
|
140
|
-
);
|
|
141
|
-
}
|
|
142
|
-
return result.output;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Firestore-backed store (transactions). Collection: `webhook_idempotency`.
|
|
147
|
-
*
|
|
148
|
-
* `expiresAt` is a Firestore Timestamp {@link WEBHOOK_EVENT_RETENTION_MS} after
|
|
149
|
-
* the last write: enable a TTL policy on `webhook_idempotency.expiresAt` so
|
|
150
|
-
* Firestore deletes old documents.
|
|
151
|
-
*
|
|
152
|
-
* @version 0.2.0
|
|
153
|
-
* @since 0.2.0
|
|
154
|
-
* @author AMBROISE PARK Consulting
|
|
155
|
-
*/
|
|
156
|
-
export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
|
|
157
|
-
let firebase: typeof import('@donotdev/firebase/server') | null = null;
|
|
158
|
-
const load = async () => {
|
|
159
|
-
if (!firebase) firebase = await import('@donotdev/firebase/server');
|
|
160
|
-
const firestore = firebase.getFirebaseAdminFirestore();
|
|
161
|
-
return {
|
|
162
|
-
firestore,
|
|
163
|
-
Timestamp: firebase.Timestamp,
|
|
164
|
-
refOf: (eventId: string) =>
|
|
165
|
-
firestore.collection(FIRESTORE_COLLECTION).doc(eventId),
|
|
166
|
-
};
|
|
167
|
-
};
|
|
168
|
-
|
|
169
|
-
const reserve = async (eventId: string): Promise<ReservationResult> => {
|
|
170
|
-
const { firestore, Timestamp, refOf } = await load();
|
|
171
|
-
const ref = refOf(eventId);
|
|
172
|
-
try {
|
|
173
|
-
return await firestore.runTransaction(async (tx) => {
|
|
174
|
-
const snapshot = await tx.get(ref);
|
|
175
|
-
const now = Date.now();
|
|
176
|
-
if (snapshot.exists) {
|
|
177
|
-
const data = parseEventDoc(eventId, snapshot.data());
|
|
178
|
-
if (data.status === 'processing') {
|
|
179
|
-
if (now - (data.reservedAt ?? 0) < RESERVATION_LEASE_MS) {
|
|
180
|
-
return { state: 'in_progress' } as const;
|
|
181
|
-
}
|
|
182
|
-
} else if ((data.expiresAt ?? 0) >= now) {
|
|
183
|
-
return { state: 'processed' } as const;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
const ownerToken = newOwnerToken();
|
|
187
|
-
tx.set(ref, {
|
|
188
|
-
eventId,
|
|
189
|
-
status: 'processing',
|
|
190
|
-
ownerToken,
|
|
191
|
-
reservedAt: now,
|
|
192
|
-
expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
|
|
193
|
-
});
|
|
194
|
-
return { state: 'reserved', ownerToken } as const;
|
|
195
|
-
});
|
|
196
|
-
} catch (error) {
|
|
197
|
-
throw handleError(error);
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
|
|
201
|
-
return {
|
|
202
|
-
reserve,
|
|
203
|
-
async checkAndReserve(eventId) {
|
|
204
|
-
return (await reserve(eventId)).state !== 'reserved';
|
|
205
|
-
},
|
|
206
|
-
async markProcessed(eventId, ownerToken) {
|
|
207
|
-
const { firestore, Timestamp, refOf } = await load();
|
|
208
|
-
const ref = refOf(eventId);
|
|
209
|
-
const now = Date.now();
|
|
210
|
-
const processed = {
|
|
211
|
-
eventId,
|
|
212
|
-
status: 'processed',
|
|
213
|
-
processedAt: now,
|
|
214
|
-
expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
|
|
215
|
-
};
|
|
216
|
-
try {
|
|
217
|
-
if (ownerToken === undefined) {
|
|
218
|
-
// 0.1.x call: unconditional write
|
|
219
|
-
await ref.set(processed);
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
await firestore.runTransaction(async (tx) => {
|
|
223
|
-
const snapshot = await tx.get(ref);
|
|
224
|
-
const data = snapshot.exists
|
|
225
|
-
? parseEventDoc(eventId, snapshot.data())
|
|
226
|
-
: null;
|
|
227
|
-
if (data?.ownerToken !== ownerToken) {
|
|
228
|
-
throw new ReservationLostError(eventId);
|
|
229
|
-
}
|
|
230
|
-
tx.set(ref, { ...processed, ownerToken });
|
|
231
|
-
});
|
|
232
|
-
} catch (error) {
|
|
233
|
-
if (error instanceof ReservationLostError) throw error;
|
|
234
|
-
throw handleError(error);
|
|
235
|
-
}
|
|
236
|
-
},
|
|
237
|
-
async release(eventId, ownerToken) {
|
|
238
|
-
const { firestore, refOf } = await load();
|
|
239
|
-
const ref = refOf(eventId);
|
|
240
|
-
try {
|
|
241
|
-
return await firestore.runTransaction(async (tx) => {
|
|
242
|
-
const snapshot = await tx.get(ref);
|
|
243
|
-
if (!snapshot.exists) return false;
|
|
244
|
-
const data = parseEventDoc(eventId, snapshot.data());
|
|
245
|
-
if (data.status !== 'processing' || data.ownerToken !== ownerToken) {
|
|
246
|
-
return false;
|
|
247
|
-
}
|
|
248
|
-
tx.delete(ref);
|
|
249
|
-
return true;
|
|
250
|
-
});
|
|
251
|
-
} catch (error) {
|
|
252
|
-
throw handleError(error);
|
|
253
|
-
}
|
|
254
|
-
},
|
|
255
|
-
async isProcessed(eventId) {
|
|
256
|
-
const { refOf } = await load();
|
|
257
|
-
try {
|
|
258
|
-
const snapshot = await refOf(eventId).get();
|
|
259
|
-
if (!snapshot.exists) return false;
|
|
260
|
-
const data = parseEventDoc(eventId, snapshot.data());
|
|
261
|
-
return data.status !== 'processing' && (data.expiresAt ?? 0) >= Date.now();
|
|
262
|
-
} catch (error) {
|
|
263
|
-
throw handleError(error);
|
|
264
|
-
}
|
|
265
|
-
},
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
|
|
269
102
|
// =============================================================================
|
|
270
103
|
// 0.1.x auto-detection (deprecated)
|
|
271
104
|
// =============================================================================
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/stripeClient.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Stripe client for billing functions
|
|
5
|
+
* @description Lazily initialized Stripe SDK instance shared by the Firebase,
|
|
6
|
+
* Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so
|
|
7
|
+
* code that does not bill (CRUD, auth) never loads the Stripe SDK.
|
|
8
|
+
*
|
|
9
|
+
* @version 0.2.1
|
|
10
|
+
* @since 0.0.1
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import Stripe from 'stripe';
|
|
15
|
+
|
|
16
|
+
import { STRIPE_API_VERSION_PIN } from './apiVersion.js';
|
|
17
|
+
|
|
18
|
+
// Lazy initialization of Stripe
|
|
19
|
+
let _stripe: Stripe | null = null;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Initialize Stripe explicitly (e.g. with a secret from defineSecret).
|
|
23
|
+
* API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.
|
|
24
|
+
* @param apiKey - Stripe secret key
|
|
25
|
+
*
|
|
26
|
+
* @version 0.2.0
|
|
27
|
+
* @since 0.0.1
|
|
28
|
+
* @author AMBROISE PARK Consulting
|
|
29
|
+
*/
|
|
30
|
+
export function initStripe(apiKey: string) {
|
|
31
|
+
if (!apiKey) throw new Error('Stripe API key is required');
|
|
32
|
+
|
|
33
|
+
// Unset: the framework pin (pre-basil fields are still read by subscription handlers)
|
|
34
|
+
const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
|
|
35
|
+
|
|
36
|
+
_stripe = new Stripe(apiKey, {
|
|
37
|
+
apiVersion: apiVersion as any,
|
|
38
|
+
});
|
|
39
|
+
return _stripe;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Get Stripe instance with lazy initialization
|
|
44
|
+
*
|
|
45
|
+
* @version 0.1.0
|
|
46
|
+
* @since 0.0.1
|
|
47
|
+
* @author AMBROISE PARK Consulting
|
|
48
|
+
*/
|
|
49
|
+
export function getStripe(): Stripe {
|
|
50
|
+
if (!_stripe) {
|
|
51
|
+
// Legacy/Vercel fallback: Try process.env
|
|
52
|
+
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
|
|
53
|
+
if (STRIPE_SECRET_KEY) {
|
|
54
|
+
initStripe(STRIPE_SECRET_KEY);
|
|
55
|
+
} else {
|
|
56
|
+
throw new Error(
|
|
57
|
+
'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// We know _stripe is set here or we threw
|
|
62
|
+
return _stripe!;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Lazy-initialized Stripe instance proxy
|
|
67
|
+
*
|
|
68
|
+
* @version 0.1.0
|
|
69
|
+
* @since 0.0.1
|
|
70
|
+
* @author AMBROISE PARK Consulting
|
|
71
|
+
*/
|
|
72
|
+
export const stripe = new Proxy({} as Stripe, {
|
|
73
|
+
get(target, prop) {
|
|
74
|
+
return getStripe()[prop as keyof Stripe];
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Validates that required Stripe environment variables are set
|
|
80
|
+
*
|
|
81
|
+
* @version 0.1.0
|
|
82
|
+
* @since 0.0.1
|
|
83
|
+
* @author AMBROISE PARK Consulting
|
|
84
|
+
*/
|
|
85
|
+
export function validateStripeEnvironment(): void {
|
|
86
|
+
// Functions v2 automatically injects secrets as process.env when declared in config
|
|
87
|
+
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
|
|
88
|
+
if (!STRIPE_SECRET_KEY) {
|
|
89
|
+
throw new Error('Missing STRIPE_SECRET_KEY environment variable');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -18,7 +18,6 @@ import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from
|
|
|
18
18
|
|
|
19
19
|
import { handleError } from '../errorHandling.js';
|
|
20
20
|
import { logger } from '../logger.js';
|
|
21
|
-
import { createIdempotencyStore } from './idempotency.js';
|
|
22
21
|
import { ReservationLostError } from './idempotencyContract.js';
|
|
23
22
|
import type { IdempotencyStore } from './idempotencyContract.js';
|
|
24
23
|
import { handleOrderSessionEvent } from './orderWebhook.js';
|
|
@@ -56,11 +55,12 @@ const MARK_PROCESSED_BACKOFF_MS = 200;
|
|
|
56
55
|
* @param billingConfig - Billing configuration
|
|
57
56
|
* @param updateSubscription - Function to update user subscription
|
|
58
57
|
* @param authProvider - Auth provider for subscription claims (null: subscription events fail)
|
|
59
|
-
* @param idempotencyStore - Durable store matching the backend
|
|
60
|
-
*
|
|
58
|
+
* @param idempotencyStore - Durable store matching the backend
|
|
59
|
+
* (`createFirestoreIdempotencyStore` / `createSupabaseIdempotencyStore`). Required:
|
|
60
|
+
* shared logic never picks a backend.
|
|
61
61
|
* @throws Any failure: the caller must answer non-2xx so Stripe retries
|
|
62
62
|
*
|
|
63
|
-
* @version 0.2.
|
|
63
|
+
* @version 0.2.1
|
|
64
64
|
* @since 0.0.1
|
|
65
65
|
* @author AMBROISE PARK Consulting
|
|
66
66
|
*/
|
|
@@ -72,7 +72,7 @@ export async function processWebhook(
|
|
|
72
72
|
billingConfig: StripeBackConfig,
|
|
73
73
|
updateSubscription: UpdateSubscriptionFn,
|
|
74
74
|
authProvider: BillingAuthProvider | null,
|
|
75
|
-
idempotencyStore: IdempotencyStore
|
|
75
|
+
idempotencyStore: IdempotencyStore
|
|
76
76
|
): Promise<{ success: boolean; message: string }> {
|
|
77
77
|
try {
|
|
78
78
|
// Validate data fields only. Valibot strips unknown keys (the hooks) from its
|