@donotdev/functions 0.1.44 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/lib/chunks/chunk-3F4BWKQD.js +22 -0
- package/lib/chunks/chunk-3F4BWKQD.js.map +7 -0
- package/lib/chunks/chunk-5IPULSUX.js +22 -0
- package/lib/chunks/chunk-5IPULSUX.js.map +7 -0
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.js.map +7 -0
- package/lib/chunks/chunk-AYY7UXNI.js +22 -0
- package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
- package/lib/chunks/chunk-CXBSROEW.js +23 -0
- package/lib/chunks/chunk-CXBSROEW.js.map +7 -0
- package/lib/chunks/chunk-GYTCWMXV.js +22 -0
- package/lib/chunks/chunk-GYTCWMXV.js.map +7 -0
- package/lib/chunks/chunk-HLNYUAZH.js +22 -0
- package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
- package/lib/chunks/chunk-LCDLG4VG.js +151 -0
- package/lib/chunks/chunk-LCDLG4VG.js.map +7 -0
- package/lib/chunks/chunk-MQANUSY3.js +22 -0
- package/lib/chunks/chunk-MQANUSY3.js.map +7 -0
- package/lib/chunks/chunk-OFQVO3FD.js +22 -0
- package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/chunk-US2VOP4S.js +22 -0
- package/lib/chunks/chunk-US2VOP4S.js.map +7 -0
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js +22 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js.map +7 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js +22 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js.map +7 -0
- package/lib/chunks/server-IQ5JNJOM.js +22 -0
- package/lib/chunks/server-IQ5JNJOM.js.map +7 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +2 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
- package/lib/firebase/billing/webhookHandler.d.ts +17 -2
- package/lib/firebase/config/constants.d.ts +0 -0
- package/lib/firebase/config/index.d.ts +0 -0
- package/lib/firebase/config/secrets.d.ts +0 -0
- package/lib/firebase/crud/aggregate.d.ts +0 -9
- package/lib/firebase/crud/bulk.d.ts +2 -2
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/index.d.ts +0 -0
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/index.d.ts +0 -0
- package/lib/firebase/index.d.ts +0 -0
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +0 -0
- package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
- package/lib/firebase/oauth/getConnections.d.ts +0 -0
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
- package/lib/firebase/scheduled/index.d.ts +0 -0
- package/lib/shared/ai/classifyAIError.d.ts +0 -0
- package/lib/shared/ai/costTracker.d.ts +0 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- package/lib/shared/billing/apiVersion.d.ts +22 -0
- package/lib/shared/billing/checkoutPrice.d.ts +27 -0
- package/lib/shared/billing/checkoutValidation.d.ts +89 -0
- package/lib/shared/billing/createCheckout.d.ts +73 -24
- package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
- package/lib/shared/billing/helpers/index.d.ts +0 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
- package/lib/shared/billing/idempotency.d.ts +21 -10
- package/lib/shared/billing/idempotencyContract.d.ts +121 -0
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +75 -0
- package/lib/shared/billing/stripeClient.d.ts +45 -0
- package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +29 -20
- package/lib/shared/email/createEmailRoute.d.ts +0 -0
- package/lib/shared/email/index.d.ts +0 -0
- package/lib/shared/email/provider.d.ts +0 -0
- package/lib/shared/email/resendProvider.d.ts +0 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +0 -0
- package/lib/shared/index.d.ts +0 -0
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +0 -0
- package/lib/shared/oauth/exchangeToken.d.ts +0 -0
- package/lib/shared/oauth/grantAccess.d.ts +0 -0
- package/lib/shared/oauth/index.d.ts +0 -0
- package/lib/shared/schema.d.ts +0 -0
- package/lib/shared/utils/detectFirestore.d.ts +0 -0
- package/lib/shared/utils/external/date.d.ts +0 -0
- package/lib/shared/utils/external/index.d.ts +0 -0
- package/lib/shared/utils/external/references.d.ts +0 -0
- package/lib/shared/utils/external/subscription.d.ts +0 -0
- package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/firebase.d.ts +0 -0
- package/lib/shared/utils/internal/idempotency.d.ts +0 -0
- package/lib/shared/utils/internal/index.d.ts +0 -0
- package/lib/shared/utils/internal/monitoring.d.ts +0 -0
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -8
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +0 -56
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +0 -0
- package/lib/supabase/auth/deleteAccount.d.ts +0 -0
- package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +0 -0
- package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/crud/list.d.ts +0 -8
- package/lib/supabase/crud/update.d.ts +0 -0
- package/lib/supabase/edgeFunction.d.ts +0 -0
- package/lib/supabase/email/createEmailFunction.d.ts +0 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +11 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/oauth/disconnect.d.ts +0 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
- package/lib/supabase/oauth/getConnections.d.ts +0 -0
- package/lib/supabase/oauth/index.d.ts +0 -0
- package/lib/supabase/oauth/refreshToken.d.ts +0 -0
- package/lib/supabase/registerCrudFunctions.d.ts +0 -0
- package/lib/supabase/utils/idempotency.d.ts +0 -0
- package/lib/supabase/utils/monitoring.d.ts +0 -0
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/ai/index.d.ts +0 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
- package/lib/vercel/api/billing/backend.d.ts +39 -0
- package/lib/vercel/api/billing/cancel.d.ts +8 -0
- package/lib/vercel/api/billing/change-plan.d.ts +9 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
- package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
- package/lib/vercel/api/billing/index.d.ts +4 -2
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
- package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/bulk.d.ts +17 -0
- package/lib/vercel/api/crud/create.d.ts +8 -0
- package/lib/vercel/api/crud/delete.d.ts +8 -0
- package/lib/vercel/api/crud/get.d.ts +8 -0
- package/lib/vercel/api/crud/index.d.ts +0 -0
- package/lib/vercel/api/crud/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -0
- package/lib/vercel/api/index.d.ts +0 -0
- package/lib/vercel/api/index.js +1 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +4 -1
- package/lib/vercel/supabaseAdmin.d.ts +22 -0
- package/package.json +25 -26
- package/src/firebase/auth/getCustomClaims.ts +4 -5
- package/src/firebase/auth/getUserAuthStatus.ts +4 -5
- package/src/firebase/auth/removeCustomClaims.ts +4 -5
- package/src/firebase/auth/setCustomClaims.ts +4 -5
- package/src/firebase/baseFunction.ts +4 -5
- package/src/firebase/billing/cancelSubscription.ts +2 -3
- package/src/firebase/billing/changePlan.ts +3 -8
- package/src/firebase/billing/createCheckoutSession.ts +31 -61
- package/src/firebase/billing/createCustomerPortal.ts +5 -6
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -4
- package/src/firebase/billing/webhookHandler.ts +21 -5
- package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
- package/src/firebase/crud/aggregate.ts +1 -2
- package/src/firebase/crud/bulk.ts +5 -6
- package/src/firebase/crud/create.ts +5 -6
- package/src/firebase/crud/delete.ts +4 -5
- package/src/firebase/crud/get.ts +4 -5
- package/src/firebase/crud/list.ts +4 -5
- package/src/firebase/crud/update.ts +5 -6
- package/src/firebase/oauth/githubAccess.ts +2 -3
- package/src/firebase/registerCrudFunctions.ts +2 -2
- package/src/shared/__tests__/auth.test.ts +0 -3
- package/src/shared/__tests__/bulkCore.test.ts +3 -2
- package/src/shared/__tests__/errorHandling.test.ts +2 -2
- package/src/shared/__tests__/idempotency.test.ts +282 -55
- package/src/shared/__tests__/internalValidation.test.ts +3 -42
- package/src/shared/__tests__/logger.test.ts +31 -0
- package/src/shared/__tests__/rateLimiter.test.ts +2 -8
- package/src/shared/__tests__/schemaValidation.test.ts +1 -1
- package/src/shared/__tests__/utils.test.ts +3 -2
- package/src/shared/__tests__/validation-env.test.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +53 -30
- package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
- package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +370 -23
- package/src/shared/billing/apiVersion.ts +25 -0
- package/src/shared/billing/checkoutPrice.ts +125 -0
- package/src/shared/billing/checkoutValidation.ts +284 -0
- package/src/shared/billing/createCheckout.ts +332 -196
- package/src/shared/billing/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +8 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +104 -168
- package/src/shared/billing/idempotencyContract.ts +135 -0
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +269 -0
- package/src/shared/billing/stripeClient.ts +91 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +189 -386
- package/src/shared/logger.ts +4 -6
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +2 -3
- package/src/shared/utils/functionWrapper.ts +1 -2
- package/src/shared/utils/internal/auth.ts +55 -7
- package/src/shared/utils/internal/monitoring.ts +17 -9
- package/src/shared/utils/internal/rateLimiter.ts +14 -5
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +5 -99
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +3 -1
- package/src/supabase/__tests__/entityStore.test.ts +90 -0
- package/src/supabase/baseFunction.ts +1 -2
- package/src/supabase/billing/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +11 -41
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -7
- package/src/supabase/billing/stripeWebhook.ts +79 -0
- package/src/supabase/crud/aggregate.ts +1 -1
- package/src/supabase/crud/bulk.ts +3 -7
- package/src/supabase/crud/create.ts +1 -1
- package/src/supabase/crud/entityStore.ts +240 -0
- package/src/supabase/crud/index.ts +8 -0
- package/src/supabase/crud/list.ts +2 -0
- package/src/supabase/crud/update.ts +1 -1
- package/src/supabase/helpers/authProvider.ts +6 -5
- package/src/supabase/index.ts +26 -0
- package/src/supabase/utils/rateLimiter.ts +2 -2
- package/src/vercel/__tests__/bulk.test.ts +24 -21
- package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
- package/src/vercel/api/ai/chat.ts +2 -1
- package/src/vercel/api/auth/get-custom-claims.ts +2 -3
- package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
- package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
- package/src/vercel/api/auth/set-custom-claims.ts +3 -3
- package/src/vercel/api/billing/backend.ts +72 -0
- package/src/vercel/api/billing/cancel.ts +2 -4
- package/src/vercel/api/billing/change-plan.ts +4 -5
- package/src/vercel/api/billing/create-checkout-session.ts +43 -73
- package/src/vercel/api/billing/customer-portal.ts +3 -5
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +22 -7
- package/src/vercel/api/billing/webhook-handler.ts +32 -26
- package/src/vercel/api/config/firebase-admin.ts +2 -2
- package/src/vercel/api/crud/bulk.ts +6 -9
- package/src/vercel/api/crud/create.ts +6 -5
- package/src/vercel/api/crud/delete.ts +4 -3
- package/src/vercel/api/crud/get.ts +6 -5
- package/src/vercel/api/crud/list.ts +6 -5
- package/src/vercel/api/crud/update.ts +6 -5
- package/src/vercel/api/oauth/check-github-access.ts +5 -5
- package/src/vercel/api/oauth/exchange-token.ts +3 -3
- package/src/vercel/api/oauth/grant-github-access.ts +5 -5
- package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
- package/src/vercel/baseFunction.ts +23 -8
- package/src/vercel/supabaseAdmin.ts +45 -0
- package/lib/shared/ai/createAIHandler.d.ts +0 -39
- package/lib/shared/ai/providers/anthropic.d.ts +0 -12
- package/lib/shared/ai/providers/google.d.ts +0 -10
- package/lib/shared/ai/providers/index.d.ts +0 -23
- package/lib/shared/ai/providers/openai.d.ts +0 -10
- package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{a as n}from"./chunk-AYY7UXNI.js";function m(r){return{async getUser(o){let{data:t,error:e}=await r.auth.admin.getUserById(o);if(e)throw e;return{customClaims:t.user?.app_metadata??{}}},async setCustomUserClaims(o,t){let{error:e}=await r.auth.admin.updateUserById(o,{app_metadata:t});if(e)throw e}}}n(m,"createSupabaseAuthProvider");var w={api:{maxAttempts:100,windowMs:6e4,blockDurationMs:3e5},create:{maxAttempts:20,windowMs:6e4,blockDurationMs:3e5},update:{maxAttempts:30,windowMs:6e4,blockDurationMs:3e5},delete:{maxAttempts:10,windowMs:6e4,blockDurationMs:6e5},read:{maxAttempts:200,windowMs:6e4,blockDurationMs:3e5}};async function u(r,o,t){let e=Date.now(),l=n(()=>({allowed:!1,remaining:0,resetAt:new Date(e+t.windowMs),blockRemainingSeconds:Math.ceil(t.windowMs/1e3)}),"failClosed");try{let{data:s,error:i}=await r.rpc("rate_limit_check",{p_key:o,p_max_attempts:t.maxAttempts,p_window_ms:t.windowMs,p_block_duration_ms:t.blockDurationMs});if(i)return i.code==="42883"||i.message?.includes("function")&&i.message?.includes("does not exist")?console.error("[rateLimit] rate_limit_check function not found. Deploy the required SQL migration (see RATE_LIMIT_CHECK_SQL).",i.message):console.error("[rateLimit] rate_limit_check RPC failed (network/runtime error):",i.message,i.code),l();let a=s;return{allowed:a.allowed,remaining:a.remaining,resetAt:new Date(a.reset_at_epoch_ms),blockRemainingSeconds:a.block_remaining_seconds}}catch(s){return console.error("[rateLimit] Unexpected error in checkRateLimitWithPostgres:",s),l()}}n(u,"checkRateLimitWithPostgres");export{m as a,w as b,u as c};
|
|
22
|
+
//# sourceMappingURL=chunk-HLNYUAZH.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/supabase/helpers/authProvider.ts", "../../src/supabase/utils/rateLimiter.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/supabase/helpers/authProvider.ts\n\n/**\n * @fileoverview Supabase Auth Provider for shared billing logic\n * @description Maps Supabase Admin auth to the core `BillingAuthProvider` interface,\n * bridging `app_metadata` \u2194 `customClaims`.\n *\n * @version 0.1.0\n * @since 0.5.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type { SupabaseClient } from '@supabase/supabase-js';\n\nimport type { BillingAuthProvider } from '@donotdev/core/server';\n\n// =============================================================================\n// Factory\n// =============================================================================\n\n/**\n * Create a BillingAuthProvider backed by Supabase Admin.\n * `app_metadata` is used as the equivalent of Firebase custom claims.\n *\n * @param supabaseAdmin - Supabase client created with the service role key\n * @returns BillingAuthProvider compatible with shared billing helpers\n *\n * @version 0.1.0\n * @since 0.5.0\n */\nexport function createSupabaseAuthProvider(\n supabaseAdmin: SupabaseClient\n): BillingAuthProvider {\n return {\n async getUser(userId: string) {\n const { data, error } =\n await supabaseAdmin.auth.admin.getUserById(userId);\n if (error) throw error;\n return { customClaims: data.user?.app_metadata ?? {} };\n },\n async setCustomUserClaims(userId: string, claims: Record<string, unknown>) {\n const { error } = await supabaseAdmin.auth.admin.updateUserById(userId, {\n app_metadata: claims,\n });\n if (error) throw error;\n },\n };\n}\n", "// packages/functions/src/supabase/utils/rateLimiter.ts\n\n/**\n * @fileoverview Rate limiting utilities for Supabase Edge Functions\n * @description Postgres-based rate limiting via an atomic PostgreSQL function (RPC).\n *\n * **Why RPC?**\n * The previous SELECT \u2192 UPDATE pattern had a TOCTOU race condition: two concurrent\n * requests could both read `attempts < maxAttempts`, both increment, and both be allowed \u2014\n * effectively bypassing the rate limit under load. The PostgreSQL function executes as a\n * single atomic transaction, eliminating the race.\n *\n * **Required migration:**\n * Deploy `RATE_LIMIT_CHECK_SQL` to your Supabase project before using this function.\n * Run: `supabase migration new rate_limit_check` then paste the SQL into the file.\n *\n * **Fail behaviour:**\n * On RPC error or unexpected failure, this function FAILS CLOSED (blocks the request).\n * A broken rate limiter must not silently allow unlimited access to protected resources.\n *\n * @version 0.1.0\n * @since 0.5.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type { SupabaseClient } from '@supabase/supabase-js';\n\nimport type {\n ServerRateLimitConfig as RateLimitConfig,\n ServerRateLimitResult as RateLimitResult,\n} from '@donotdev/core';\n\nexport type { RateLimitConfig, RateLimitResult };\n\n/**\n * PostgreSQL function required for atomic rate limiting.\n * Deploy this SQL to your Supabase project via a migration.\n *\n * The function uses `INSERT \u2026 ON CONFLICT DO UPDATE` which executes as a single\n * atomic statement \u2014 no TOCTOU race between SELECT and UPDATE.\n *\n * @example\n * ```bash\n * supabase migration new rate_limit_check\n * # Paste RATE_LIMIT_CHECK_SQL into the generated migration file\n * supabase db push\n * ```\n */\nexport const RATE_LIMIT_CHECK_SQL = `\n-- Required table (create once if not already present)\nCREATE TABLE IF NOT EXISTS public.rate_limits (\n key TEXT PRIMARY KEY,\n attempts INT NOT NULL DEFAULT 0,\n window_start TIMESTAMPTZ NOT NULL DEFAULT now(),\n block_until TIMESTAMPTZ,\n last_updated TIMESTAMPTZ NOT NULL DEFAULT now()\n);\n\n-- Required atomic rate-limit function\nCREATE OR REPLACE FUNCTION public.rate_limit_check(\n p_key TEXT,\n p_max_attempts INT,\n p_window_ms BIGINT,\n p_block_duration_ms BIGINT\n)\nRETURNS jsonb\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n v_now TIMESTAMPTZ := clock_timestamp();\n v_window_interval INTERVAL := (p_window_ms || ' milliseconds')::INTERVAL;\n v_block_interval INTERVAL := (p_block_duration_ms || ' milliseconds')::INTERVAL;\n v_row public.rate_limits%ROWTYPE;\nBEGIN\n -- Single atomic upsert: INSERT on first call, conditional UPDATE thereafter.\n -- No separate SELECT \u2192 eliminates the TOCTOU race of the previous implementation.\n INSERT INTO public.rate_limits (key, attempts, window_start, block_until, last_updated)\n VALUES (p_key, 1, v_now, NULL, v_now)\n ON CONFLICT (key) DO UPDATE SET\n window_start = CASE\n WHEN rate_limits.window_start + v_window_interval <= v_now THEN v_now\n ELSE rate_limits.window_start\n END,\n attempts = CASE\n -- Currently blocked: do not increment (request will be rejected below)\n WHEN rate_limits.block_until IS NOT NULL AND v_now < rate_limits.block_until\n THEN rate_limits.attempts\n -- Window expired: reset counter\n WHEN rate_limits.window_start + v_window_interval <= v_now\n THEN 1\n -- Within window: increment\n ELSE rate_limits.attempts + 1\n END,\n block_until = CASE\n -- Preserve existing block\n WHEN rate_limits.block_until IS NOT NULL AND v_now < rate_limits.block_until\n THEN rate_limits.block_until\n -- Window just reset \u2014 no block\n WHEN rate_limits.window_start + v_window_interval <= v_now\n THEN NULL\n -- Threshold just exceeded \u2014 apply block\n WHEN rate_limits.attempts + 1 >= p_max_attempts\n THEN v_now + v_block_interval\n ELSE NULL\n END,\n last_updated = v_now\n RETURNING * INTO v_row;\n\n -- Blocked?\n IF v_row.block_until IS NOT NULL AND v_now < v_row.block_until THEN\n RETURN jsonb_build_object(\n 'allowed', false,\n 'remaining', 0,\n 'reset_at_epoch_ms', EXTRACT(EPOCH FROM v_row.block_until)::BIGINT * 1000,\n 'block_remaining_seconds', CEIL(EXTRACT(EPOCH FROM (v_row.block_until - v_now)))::INT\n );\n END IF;\n\n RETURN jsonb_build_object(\n 'allowed', true,\n 'remaining', GREATEST(0, p_max_attempts - v_row.attempts),\n 'reset_at_epoch_ms', EXTRACT(EPOCH FROM (v_row.window_start + v_window_interval))::BIGINT * 1000,\n 'block_remaining_seconds', NULL\n );\nEND;\n$$;\n`;\n\n/**\n * Default rate limits (same as Firebase equivalent).\n */\nexport const DEFAULT_RATE_LIMITS: Record<string, RateLimitConfig> = {\n api: {\n maxAttempts: 100,\n windowMs: 60 * 1000, // 1 minute\n blockDurationMs: 5 * 60 * 1000, // 5 minutes\n },\n create: {\n maxAttempts: 20,\n windowMs: 60 * 1000,\n blockDurationMs: 5 * 60 * 1000,\n },\n update: {\n maxAttempts: 30,\n windowMs: 60 * 1000,\n blockDurationMs: 5 * 60 * 1000,\n },\n delete: {\n maxAttempts: 10,\n windowMs: 60 * 1000,\n blockDurationMs: 10 * 60 * 1000,\n },\n read: {\n maxAttempts: 200,\n windowMs: 60 * 1000,\n blockDurationMs: 5 * 60 * 1000,\n },\n};\n\n/** Shape returned by the `rate_limit_check` PostgreSQL function. */\ninterface RpcResult {\n allowed: boolean;\n remaining: number;\n reset_at_epoch_ms: number;\n block_remaining_seconds: number | null;\n}\n\n/**\n * Atomically check and increment a rate limit counter using the `rate_limit_check`\n * PostgreSQL function. Requires the function to be deployed (see `RATE_LIMIT_CHECK_SQL`).\n *\n * **Fail behaviour:** FAILS CLOSED on any error \u2014 a broken rate limiter must not\n * allow unlimited access. Log the error and alert your team; do not suppress it.\n *\n * @param supabaseAdmin - Supabase admin client (service role key \u2014 never expose to clients)\n * @param key - Rate limit key, e.g. `\"create_userId\"` or `\"api_ip\"`\n * @param config - Rate limit configuration\n */\nexport async function checkRateLimitWithPostgres(\n supabaseAdmin: SupabaseClient,\n key: string,\n config: RateLimitConfig\n): Promise<RateLimitResult> {\n const now = Date.now();\n\n /** Fail-closed response \u2014 blocks the caller on any infrastructure error. */\n const failClosed = (): RateLimitResult => ({\n allowed: false,\n remaining: 0,\n resetAt: new Date(now + config.windowMs),\n blockRemainingSeconds: Math.ceil(config.windowMs / 1000),\n });\n\n try {\n const { data, error } = await supabaseAdmin.rpc('rate_limit_check', {\n p_key: key,\n p_max_attempts: config.maxAttempts,\n p_window_ms: config.windowMs,\n p_block_duration_ms: config.blockDurationMs,\n });\n\n if (error) {\n // G70: Distinguish missing function from network/other errors for clearer diagnostics\n const isNotFound =\n error.code === '42883' ||\n (error.message?.includes('function') &&\n error.message?.includes('does not exist'));\n if (isNotFound) {\n console.error(\n '[rateLimit] rate_limit_check function not found. ' +\n 'Deploy the required SQL migration (see RATE_LIMIT_CHECK_SQL).',\n error.message\n );\n } else {\n console.error(\n '[rateLimit] rate_limit_check RPC failed (network/runtime error):',\n error.message,\n error.code\n );\n }\n return failClosed();\n }\n\n const result = data as RpcResult;\n return {\n allowed: result.allowed,\n remaining: result.remaining,\n resetAt: new Date(result.reset_at_epoch_ms),\n blockRemainingSeconds: result.block_remaining_seconds,\n };\n } catch (error) {\n console.error(\n '[rateLimit] Unexpected error in checkRateLimitWithPostgres:',\n error\n );\n return failClosed();\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;wCA8BO,SAASA,EACdC,EACqB,CACrB,MAAO,CACL,MAAM,QAAQC,EAAgB,CAC5B,GAAM,CAAE,KAAAC,EAAM,MAAAC,CAAM,EAClB,MAAMH,EAAc,KAAK,MAAM,YAAYC,CAAM,EACnD,GAAIE,EAAO,MAAMA,EACjB,MAAO,CAAE,aAAcD,EAAK,MAAM,cAAgB,CAAC,CAAE,CACvD,EACA,MAAM,oBAAoBD,EAAgBG,EAAiC,CACzE,GAAM,CAAE,MAAAD,CAAM,EAAI,MAAMH,EAAc,KAAK,MAAM,eAAeC,EAAQ,CACtE,aAAcG,CAChB,CAAC,EACD,GAAID,EAAO,MAAMA,CACnB,CACF,CACF,CAjBgBE,EAAAN,EAAA,8BCsGT,IAAMO,EAAuD,CAClE,IAAK,CACH,YAAa,IACb,SAAU,IACV,gBAAiB,GACnB,EACA,OAAQ,CACN,YAAa,GACb,SAAU,IACV,gBAAiB,GACnB,EACA,OAAQ,CACN,YAAa,GACb,SAAU,IACV,gBAAiB,GACnB,EACA,OAAQ,CACN,YAAa,GACb,SAAU,IACV,gBAAiB,GACnB,EACA,KAAM,CACJ,YAAa,IACb,SAAU,IACV,gBAAiB,GACnB,CACF,EAqBA,eAAsBC,EACpBC,EACAC,EACAC,EAC0B,CAC1B,IAAMC,EAAM,KAAK,IAAI,EAGfC,EAAaC,EAAA,KAAwB,CACzC,QAAS,GACT,UAAW,EACX,QAAS,IAAI,KAAKF,EAAMD,EAAO,QAAQ,EACvC,sBAAuB,KAAK,KAAKA,EAAO,SAAW,GAAI,CACzD,GALmB,cAOnB,GAAI,CACF,GAAM,CAAE,KAAAI,EAAM,MAAAC,CAAM,EAAI,MAAMP,EAAc,IAAI,mBAAoB,CAClE,MAAOC,EACP,eAAgBC,EAAO,YACvB,YAAaA,EAAO,SACpB,oBAAqBA,EAAO,eAC9B,CAAC,EAED,GAAIK,EAMF,OAHEA,EAAM,OAAS,SACdA,EAAM,SAAS,SAAS,UAAU,GACjCA,EAAM,SAAS,SAAS,gBAAgB,EAE1C,QAAQ,MACN,iHAEAA,EAAM,OACR,EAEA,QAAQ,MACN,mEACAA,EAAM,QACNA,EAAM,IACR,EAEKH,EAAW,EAGpB,IAAMI,EAASF,EACf,MAAO,CACL,QAASE,EAAO,QAChB,UAAWA,EAAO,UAClB,QAAS,IAAI,KAAKA,EAAO,iBAAiB,EAC1C,sBAAuBA,EAAO,uBAChC,CACF,OAASD,EAAO,CACd,eAAQ,MACN,8DACAA,CACF,EACOH,EAAW,CACpB,CACF,CA3DsBC,EAAAN,EAAA",
|
|
6
|
+
"names": ["createSupabaseAuthProvider", "supabaseAdmin", "userId", "data", "error", "claims", "__name", "DEFAULT_RATE_LIMITS", "checkRateLimitWithPostgres", "supabaseAdmin", "key", "config", "now", "failClosed", "__name", "data", "error", "result"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{B as $,D as ne,E as ie,F as O,H as se,L as b,V as W,W as q,_ as L,a as ee,b as B,c as te,d as re,o as oe,t as U}from"./chunk-GYTCWMXV.js";import{a as p}from"./chunk-PWAGW4R6.js";import{a}from"./chunk-AYY7UXNI.js";function _(e){let t,r,o;if(e instanceof b)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new b(r,t,o?{details:o}:void 0)}a(_,"handleError");var ae=U(["firebase","supabase"]);function pt(e){let t=$(ae,e);if(!t.success){let r=ae.options.map(o=>`'${o}'`).join(", ");throw new b(`Invalid backend ${JSON.stringify(e)}: expected one of ${r}`,"invalid-argument")}return t.output}a(pt,"parseAuthBackend");async function K(){let{getFirebaseAdminAuth:e}=await import("./server-IQ5JNJOM.js");return e()}a(K,"getFirebaseAuth");function xe(e){if(!e||typeof e!="string")throw new Error("Authentication required");return e}a(xe,"assertAuthenticated");async function lt(e){xe(e);try{let t={};q("serverAuth")?t=(await W("serverAuth").getUser(e))?.customClaims??{}:t=(await(await K()).getUser(e)).customClaims??{};let r=t.role;if(!(r==="admin"||r==="super"||t.isAdmin===!0||t.isSuper===!0))throw new Error("Admin privileges required");return e}catch(t){throw t instanceof Error&&t.message==="Admin privileges required"?t:new Error("Failed to verify admin status")}}a(lt,"assertAdmin");function Oe(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}a(Oe,"extractBearerToken");async function Ne(e,t){try{return t==="supabase"?await Ue(e):t==="firebase"?{uid:(await(await K()).verifyIdToken(e)).uid}:q("serverAuth")?{uid:(await W("serverAuth").verifyToken(e)).uid}:{uid:(await(await K()).verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}a(Ne,"verifyToken");async function Ue(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let n=t(r,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:i},error:s}=await n.auth.getUser(e);if(s||!i)throw new Error("Invalid or expired token");return{uid:i.id}}a(Ue,"verifySupabaseToken");async function $e(e,t){let r=Oe(e.headers.authorization),{uid:o}=await Ne(r,t);return o}a($e,"verifyAuthToken");var mt=$e;function H(e,t,r=te){let o=re[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,i=e.completionTokens/1e6*o.completionPer1M,s=n+i;return{providerCost:s,billedCost:s*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:i}}}a(H,"calculateCost");async function Le(e,t){let o={anthropic:a(async()=>{let{createAnthropic:s}=await import("@ai-sdk/anthropic");return c=>s({apiKey:c})(t)},"anthropic"),openai:a(async()=>{let{createOpenAI:s}=await import("@ai-sdk/openai");return c=>s({apiKey:c})(t)},"openai"),google:a(async()=>{let{createGoogle:s}=await import("@ai-sdk/google");return c=>s({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=We(e);return(await o())(n)}a(Le,"resolveModel");var Me={maxRequests:30,windowMs:6e4},k=null;async function De(){if(k)return k;let e=D("UPSTASH_REDIS_REST_URL"),t=D("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),k={check:a(async()=>{},"check")},k;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),i=new Map;return k={check:a(async(s,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=i.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),i.set(u,d)),!(await d.limit(s)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},k}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),k={check:a(async()=>{},"check")},k}}a(De,"getRateLimiter");function Fe(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[i,s]of Object.entries(o))n[i]=e.tool({description:s.description,inputSchema:e.jsonSchema(s.parameters)});return n}a(Fe,"resolveTools");function j(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}a(j,"toAIUsage");async function Be(e,t,r){let o=ne(e);if(!o.success)return M(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",i=ee[n],s=e.model||t.model||i?.default||"claude-sonnet-4-20250514";if(i){let l=i.models;if(!l.includes(s))return M(`Model '${s}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await De()).check(r.userId,t.rateLimitConfig||Me)}catch(l){return M(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await Le(n,s)}catch(l){return M(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
|
|
22
|
+
`):void 0),m=e.messages.filter(l=>l.role!=="system").map(l=>({role:l.role,content:l.content})),h=e.maxTokens||t.maxTokens||4096,E=e.temperature??t.temperature??.7,y=r.requestId||crypto.randomUUID(),T=await import("ai"),{streamText:w,generateText:A,toUIMessageStream:P,createUIMessageStreamResponse:x}=T,v=Fe(T,e.tools,t.tools),g=a(async l=>{if(!r.onCostRecord)return;let I=t.cost?.markup??4,Q=H(l,s,I),Re={userId:r.userId,model:s,provider:n,usage:l,providerCost:Q.providerCost,billedCost:Q.billedCost,markup:I,timestamp:new Date().toISOString(),requestId:y};r.onCostRecord(Re).catch(Te=>{console.error("[AI] Failed to record cost:",Te)})},"recordCost");if(e.stream!==!1){let l=w({model:c,messages:m,instructions:d,maxOutputTokens:h,temperature:E,tools:v,onEnd:a(async({usage:I})=>{await g(j(I))},"onEnd")});return x({stream:P({stream:l.stream,messageMetadata:a(({part:I})=>I.type==="finish"?{usage:j(I.totalUsage)}:void 0,"messageMetadata")})})}let f=await A({model:c,messages:m,instructions:d,maxOutputTokens:h,temperature:E,tools:v}),S=j(f.usage);await g(S);let C=f.toolCalls.map(l=>({id:l.toolCallId,name:l.toolName,args:l.input}));return new Response(JSON.stringify({message:{role:"assistant",content:f.text},usage:S,finishReason:f.finishReason,toolCalls:C.length>0?C:void 0,model:s,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}a(Be,"handleAIRequest");function M(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}a(M,"jsonError");function D(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}a(D,"getEnv");function We(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=D(r);if(n)return n}let o=D("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}a(We,"getAIApiKey");function ce(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}a(ce,"getEnv");function qe(e,t){if(t){let n=ce(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=ce(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(B).find(n=>n.id===e)?.defaultModel??B.STANDARD.defaultModel)}a(qe,"resolveModelForTier");function Ke(e){let t=je(e),r=Ve(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:de(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:de(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}a(Ke,"classifyAIError");function He(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}a(He,"mapClassifiedToHTTP");function je(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error?.status=="number")return e.error.status}}a(je,"extractStatus");function Ve(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}a(Ve,"extractMessage");function de(e){if(e&&typeof e=="object"){let t=e.headers;if(t){let r=typeof t.get=="function"?t.get("retry-after"):t["retry-after"];if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}a(de,"extractRetryAfter");var ue="2025-02-24.acacia";var V=ue,N="orderId",F="productId";function G(e){return e===null?null:typeof e=="string"?e:e.id}a(G,"idOf");function pe(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}a(pe,"toAddress");function Ge(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:G(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?pe(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:pe(r.address)}:null,invoiceId:G(e.invoice),paymentIntentId:G(e.payment_intent),metadata:e.metadata??{}}}a(Ge,"toCheckoutSessionSnapshot");async function Xe(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,i=n&&typeof n!="string"&&!n.deleted?n.metadata[F]:void 0;if(!i)throw new Error(`Line item ${o.id} of session ${t} has no ${F} product metadata`);r.push({productId:i,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}a(Xe,"listPaidLineItems");async function le(e,t,r,o,n,i,s){if(!r||r.slice(0,10)<V.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[N]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${V} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${V}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[N];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},h=Ge(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let y=await Xe(s,o.id);await i.onOrderPaid(h,y,m),p.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":p.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":i.onOrderPaymentFailed&&await i.onOrderPaymentFailed(h,m),p.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":i.onOrderExpired&&await i.onOrderExpired(h,m),p.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}a(le,"handleOrderSessionEvent");function me(e,t){let{billingConfigKey:r,priceId:o,unitAmount:n,productName:i}=t,[s]=t.lineItems;if(t.lineItems.length!==1||!s||s.productId!==r||s.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let c=!o&&!!n&&!!i,u=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,dynamic:c,mode:u}}if(c){if(u==="subscription")throw new Error("Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.");if(!e.maxUnitAmount)throw new Error("Dynamic pricing requires maxUnitAmount in billing config for security");if(n>e.maxUnitAmount)throw new Error(`Unit amount ${n} exceeds maximum allowed: ${e.maxUnitAmount}`);if(n<100)throw new Error("Unit amount must be at least 100 cents (1.00)");return{dynamic:c,mode:u}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,dynamic:c,mode:u}}a(me,"resolvePricePlan");function fe(e){let t=e.mode||"payment";return{mode:t,line_items:[e.priceId?{price:e.priceId,quantity:1}:{price_data:{currency:e.currency||"eur",unit_amount:e.unitAmount,product_data:{name:e.productName}},quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}a(fe,"toStripeSessionParams");var Ye={maxKeys:50,maxKeyLength:40,maxValueLength:500};function Y(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}a(Y,"validateCheckoutUrl");function _e(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}a(_e,"sanitizeMetadata");function z(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=Ye,i=Object.entries(e);if(i.length>r)throw new Error(`${t}: ${i.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[s,c]of i){if(s.length>o)throw new Error(`${t}: metadata key '${s}' is too long (max ${o} characters)`);if(/[[\]]/.test(s))throw new Error(`${t}: metadata key '${s}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${s}' is too long (max ${n} characters)`)}}a(z,"assertStripeMetadata");function J(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&z(o,r)}a(J,"assertCheckoutSessionMetadata");function Ee(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&Ze(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`)}}a(Ee,"assertResolvedOrder");var ze={minSeconds:1800,maxSeconds:1440*60},he=5e3,Je=["card","sepa_debit"];function Ze(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:i,invoiceFooter:s}=e;if(o&&o.some(c=>typeof c!="string"||c.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let c of n)if(!Je.includes(c))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${c}'`)}if(i!==void 0){let{minSeconds:c,maxSeconds:u}=ze;if(!Number.isInteger(i)||i<r+c||i>r+u)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${i}`)}if(s!==void 0&&(s.length===0||s.length>he))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${he} characters`)}a(Ze,"assertResolvedOrderSession");var X=new Map;async function Z(e,t,r){for(let o of t){let n=X.get(o);if(n||(n=e(o).then(i=>i.inclusive),X.set(o,n),n.catch(()=>X.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}a(Z,"assertExclusiveTaxRates");function ge(e){return"createStripeSession"in e}a(ge,"isSessionProvider");function ye(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}a(ye,"resolveRedirectUrl");function Qe(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,i={...r.metadata,[N]:t.orderId};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(s=>({price_data:{currency:e.currency,unit_amount:s.unitAmount,tax_behavior:"exclusive",product_data:{name:s.name,...s.description&&{description:s.description},metadata:{[F]:s.productId}}},quantity:s.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:e.taxIdCollection==="disabled"?{enabled:!1}:{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(s=>({shipping_rate:s}))}},customer_creation:e.customerCreation,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:i,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,customer_email:r.customerEmail,metadata:i,payment_intent_data:{metadata:i}}}a(Qe,"buildOrderSessionParams");async function jt(e,...t){let r=t.length===3,[o,n,i,s]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=s[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",h=m?void 0:me(d,u);await i.getUser(o);let E=_e(u.metadata??{}),y={...E,userId:o,billingConfigKey:c};z(m?{...y,[N]:""}:y,"metadata");let T=u.allowPromotionCodes??!0,w=u.unitAmount,A=u.productName;if(d.beforeCheckout){let g={...u,userId:o,mode:h?.mode??"payment",priceId:h?.priceId,metadata:u.metadata??{},allowPromotionCodes:T},f=await d.beforeCheckout(o,g,E);if(!f.allowed)throw new Error(f.reason||"Checkout blocked by beforeCheckout hook");h?.dynamic&&f.overrides&&(w=f.overrides.unitAmount??w,A=f.overrides.productName??A)}let P=ye(u.successUrl,"success"),x=ye(u.cancelUrl,"cancel");Y(P,"success"),Y(x,"cancel");let v;if(d.type==="StripeOrder"){if(!ge(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await Z(C=>n.retrieveTaxRate(C),d.tax.taxRateIds,c);let g=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:E});Ee(g,c);let f=g.session;if(f?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await Z(C=>n.retrieveTaxRate(C),f.taxRateIds,c)}if(f?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let S=Qe(d,g,{successUrl:P,cancelUrl:x,customerEmail:u.customerEmail,metadata:y});J(S),v=await n.createStripeSession(S)}else{let g=!!h?.dynamic&&!!w&&!!A;if(g&&d.maxUnitAmount&&w>d.maxUnitAmount)throw new Error(`Hook-overridden unit amount ${w} exceeds maximum allowed: ${d.maxUnitAmount}`);let f={priceId:h?.priceId,unitAmount:g?w:void 0,productName:g?A:void 0,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:y,allowPromotionCodes:T,successUrl:P,cancelUrl:x,mode:h?.mode};if(ge(n)){let S=fe(f);J(S),v=await n.createStripeSession(S)}else v=await n.createCheckoutSession(f)}return{sessionId:v.id,sessionUrl:v.url}}a(jt,"createCheckoutAlgorithm");async function Xt(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let i={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},s={...n,subscription:i};await r.setCustomUserClaims(e,s)}a(Xt,"updateUserSubscription");var R=class extends Error{static{a(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},we=4200*1e3,Jt=720*60*60*1e3;function ve(){return crypto.randomUUID()}a(ve,"newOwnerToken");async function ke(e,t,r,o,n){let i={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){p.info("[Webhook] Purchase awaiting async payment",{...i,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw _(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await Se(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await Se(t,r,o,n);return;case"checkout.session.async_payment_failed":p.warn("[Webhook] Async purchase payment failed, nothing granted",{...i,operation:"purchase_payment_failed"});return;case"checkout.session.expired":p.debug("[Webhook] Checkout session expired",i);return}}a(ke,"handleTierCheckoutEvent");async function Se(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)throw _(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${i}`));let s=t[i];if(!s)throw _(new Error(`Unknown billing config key: ${i}`));if(p.info("[Webhook] Processing purchase",{userId:n,configKey:i,type:s.type,operation:"purchase_processing"}),s.type==="StripePayment"){if(!o)throw _(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:s.tier,status:O.ACTIVE,subscriptionEnd:L(s.duration),customerId:e.customer},o),s.onPurchaseSuccess)try{await s.onPurchaseSuccess(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(s.type==="StripeSubscription"){if(!o)throw _(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:s.tier,status:O.ACTIVE,subscriptionEnd:L(s.duration),subscriptionId:e.subscription,customerId:e.customer},o),s.onSubscriptionCreated)try{await s.onSubscriptionCreated(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}p.info("[Webhook] Purchase processed",{userId:n,configKey:i,operation:"purchase_processed"})}a(Se,"grantCheckoutPurchase");async function Ie(e,t,r,o,n){let i=e.subscription;if(!i)return;let s=await o.subscriptions.retrieve(i),{userId:c,billingConfigKey:u}=s.metadata||{};if(!c||!u){p.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:i,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw _(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:O.ACTIVE,subscriptionEnd:L(d.duration),subscriptionId:i,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,s.metadata||{})}catch(m){p.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}p.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}a(Ie,"handleInvoicePaymentSucceeded");async function be(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)return;let s=t[i];if(!(!s||s.type!=="StripeSubscription")){if(!o)throw _(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:ie.FREE,status:O.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),s.onSubscriptionCancelled)try{await s.onSubscriptionCancelled(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}p.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:i,operation:"subscription_cancelled"})}}a(be,"handleSubscriptionDeleted");async function Ae(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){p.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){p.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}p.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}a(Ae,"handlePaymentFailed");var et=3,tt=200;async function pr(e,t,r,o,n,i,s,c){try{se(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);p.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return p.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw p.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new b(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:h}=m;s||p.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await nt(d,u,i,o,s)}catch(E){throw p.error("[Webhook] Event processing failed, releasing reservation",{error:E instanceof Error?E:new Error(String(E)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await rt(c,d.id,h),E}return await ot(c,d.id,h),{success:!0,message:"Webhook processed"}}catch(u){throw _(u)}}a(pr,"processWebhook");async function rt(e,t,r){try{await e.release(t,r)||p.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){p.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}a(rt,"releaseReservation");async function ot(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let i=n instanceof Error?n:new Error(String(n));if(n instanceof R)throw p.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:i,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=et)throw p.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:i,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;p.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:i.message}),await new Promise(s=>setTimeout(s,tt*o))}}a(ot,"markProcessedWithRetry");async function nt(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await it(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await Ie(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await be(e.data.object,t,r,n);break;case"invoice.payment_failed":await Ae(e.data.object,t);break;default:p.debug("[Webhook] Unhandled event type",{type:e.type})}}a(nt,"routeEvent");async function it(e,t,r,o,n,i,s,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await le(e,t,r,o,u,d,s);return}await ke(e,o,n,i,c)}a(it,"handleCheckoutSessionEvent");var _r=`
|
|
23
|
+
CREATE TABLE IF NOT EXISTS public.webhook_events (
|
|
24
|
+
event_id TEXT PRIMARY KEY,
|
|
25
|
+
status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
|
|
26
|
+
owner_token UUID NOT NULL,
|
|
27
|
+
reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
28
|
+
processed_at TIMESTAMPTZ
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
-- Only service_role accesses this table
|
|
32
|
+
ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
|
|
33
|
+
|
|
34
|
+
CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
|
|
35
|
+
ON public.webhook_events (processed_at);
|
|
36
|
+
|
|
37
|
+
-- The functions below run as the caller (SECURITY INVOKER) and refuse every
|
|
38
|
+
-- role but service_role. EXECUTE is deliberately not revoked: on Supabase
|
|
39
|
+
-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
|
|
40
|
+
-- crashes the backend (signal 11), which restarts every connection.
|
|
41
|
+
CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
|
|
42
|
+
RETURNS VOID
|
|
43
|
+
LANGUAGE plpgsql
|
|
44
|
+
SET search_path = public
|
|
45
|
+
AS $$
|
|
46
|
+
BEGIN
|
|
47
|
+
IF current_user IS DISTINCT FROM 'service_role' THEN
|
|
48
|
+
RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
|
|
49
|
+
USING ERRCODE = 'insufficient_privilege';
|
|
50
|
+
END IF;
|
|
51
|
+
END;
|
|
52
|
+
$$;
|
|
53
|
+
|
|
54
|
+
-- Atomic reservation. Returns:
|
|
55
|
+
-- 'reserved' the caller now owns the event under p_owner_token
|
|
56
|
+
-- 'processed' the event was already processed (skip, answer 2xx)
|
|
57
|
+
-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
|
|
58
|
+
-- A 'processing' row older than the lease is retaken (abandoned worker).
|
|
59
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
|
|
60
|
+
p_event_id TEXT,
|
|
61
|
+
p_owner_token UUID,
|
|
62
|
+
p_lease_seconds INT
|
|
63
|
+
)
|
|
64
|
+
RETURNS TEXT
|
|
65
|
+
LANGUAGE plpgsql
|
|
66
|
+
SET search_path = public
|
|
67
|
+
AS $$
|
|
68
|
+
DECLARE
|
|
69
|
+
v_status TEXT;
|
|
70
|
+
BEGIN
|
|
71
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
72
|
+
|
|
73
|
+
INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
|
|
74
|
+
VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
|
|
75
|
+
ON CONFLICT (event_id) DO UPDATE
|
|
76
|
+
SET owner_token = EXCLUDED.owner_token,
|
|
77
|
+
reserved_at = clock_timestamp()
|
|
78
|
+
WHERE webhook_events.status = 'processing'
|
|
79
|
+
AND webhook_events.reserved_at
|
|
80
|
+
< clock_timestamp() - make_interval(secs => p_lease_seconds);
|
|
81
|
+
IF FOUND THEN
|
|
82
|
+
RETURN 'reserved';
|
|
83
|
+
END IF;
|
|
84
|
+
|
|
85
|
+
SELECT status INTO v_status
|
|
86
|
+
FROM public.webhook_events
|
|
87
|
+
WHERE event_id = p_event_id;
|
|
88
|
+
IF v_status = 'processed' THEN
|
|
89
|
+
RETURN 'processed';
|
|
90
|
+
END IF;
|
|
91
|
+
-- Live lease, or the row was released in between: Stripe retries either way
|
|
92
|
+
RETURN 'in_progress';
|
|
93
|
+
END;
|
|
94
|
+
$$;
|
|
95
|
+
|
|
96
|
+
-- Mark a reservation processed. Returns false when p_owner_token no longer owns
|
|
97
|
+
-- the row (lease retaken, released, or deleted). Repeating it for the same
|
|
98
|
+
-- owner is a no-op that returns true.
|
|
99
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
|
|
100
|
+
p_event_id TEXT,
|
|
101
|
+
p_owner_token UUID
|
|
102
|
+
)
|
|
103
|
+
RETURNS BOOLEAN
|
|
104
|
+
LANGUAGE plpgsql
|
|
105
|
+
SET search_path = public
|
|
106
|
+
AS $$
|
|
107
|
+
BEGIN
|
|
108
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
109
|
+
|
|
110
|
+
UPDATE public.webhook_events
|
|
111
|
+
SET status = 'processed',
|
|
112
|
+
processed_at = COALESCE(processed_at, clock_timestamp())
|
|
113
|
+
WHERE event_id = p_event_id
|
|
114
|
+
AND owner_token = p_owner_token;
|
|
115
|
+
RETURN FOUND;
|
|
116
|
+
END;
|
|
117
|
+
$$;
|
|
118
|
+
|
|
119
|
+
-- Drop a reservation after a processing failure. Returns false when
|
|
120
|
+
-- p_owner_token does not own a 'processing' row (nothing is deleted).
|
|
121
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_release(
|
|
122
|
+
p_event_id TEXT,
|
|
123
|
+
p_owner_token UUID
|
|
124
|
+
)
|
|
125
|
+
RETURNS BOOLEAN
|
|
126
|
+
LANGUAGE plpgsql
|
|
127
|
+
SET search_path = public
|
|
128
|
+
AS $$
|
|
129
|
+
BEGIN
|
|
130
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
131
|
+
|
|
132
|
+
DELETE FROM public.webhook_events
|
|
133
|
+
WHERE event_id = p_event_id
|
|
134
|
+
AND owner_token = p_owner_token
|
|
135
|
+
AND status = 'processing';
|
|
136
|
+
RETURN FOUND;
|
|
137
|
+
END;
|
|
138
|
+
$$;
|
|
139
|
+
|
|
140
|
+
-- Enable pg_cron extension (if not already enabled)
|
|
141
|
+
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
142
|
+
|
|
143
|
+
-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
|
|
144
|
+
-- Stripe retries an event for up to 3 days, so older rows are never read again.
|
|
145
|
+
SELECT cron.schedule(
|
|
146
|
+
'cleanup-webhook-events',
|
|
147
|
+
'0 5 * * *',
|
|
148
|
+
$$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
|
|
149
|
+
);
|
|
150
|
+
`,st=U(["reserved","processed","in_progress"]),Ce=oe();function Er(e){let t=a(async(r,o,n)=>{let{data:i,error:s}=await e.rpc(r,o);if(s)throw _(s);let c=$(n,i);if(!c.success)throw _(new Error(`${r} returned an unexpected result: ${JSON.stringify(i)}`));return c.output},"call");return{async reserve(r){let o=ve(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:we/1e3},st);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Ce))throw new R(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Ce)}}}a(Er,"createSupabaseIdempotencyStore");export{_ as a,ae as b,pt as c,xe as d,lt as e,Ne as f,$e as g,mt as h,H as i,Be as j,qe as k,Ke as l,He as m,J as n,ue as o,V as p,N as q,F as r,Ge as s,Xe as t,le as u,jt as v,Xt as w,R as x,we as y,Jt as z,ve as A,pr as B,_r as C,Er as D};
|
|
151
|
+
//# sourceMappingURL=chunk-LCDLG4VG.js.map
|