@donotdev/functions 0.1.42 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/lib/chunks/chunk-2JL3GDTO.js +151 -0
- package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
- package/lib/chunks/chunk-4TVLH2W2.js +22 -0
- package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
- package/lib/chunks/chunk-4U7QQWYG.js +22 -0
- package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
- package/lib/chunks/chunk-5DTPEM64.js +22 -0
- package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
- package/lib/chunks/chunk-6CQXHNVL.js +22 -0
- package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
- package/lib/chunks/chunk-6DSCPZC6.js +22 -0
- package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
- package/lib/chunks/chunk-7E6TGWHU.js +22 -0
- package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
- package/lib/chunks/chunk-7LT32OWE.js +22 -0
- package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
- package/lib/chunks/chunk-7VH2GJXT.js +151 -0
- package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
- package/lib/chunks/chunk-API5A4BV.js +22 -0
- package/lib/chunks/chunk-API5A4BV.js.map +7 -0
- package/lib/chunks/chunk-AYY7UXNI.js +22 -0
- package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
- package/lib/chunks/chunk-BUP7SXPV.js +23 -0
- package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
- package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
- package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
- package/lib/chunks/chunk-FSLGZD7A.js +21 -0
- package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
- package/lib/chunks/chunk-GVLSPWDD.js +151 -0
- package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
- package/lib/chunks/chunk-GXQVWEFT.js +22 -0
- package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
- package/lib/chunks/chunk-HB7EGXVI.js +22 -0
- package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
- package/lib/chunks/chunk-HLNYUAZH.js +22 -0
- package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
- package/lib/chunks/chunk-HM7XCMWW.js +22 -0
- package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
- package/lib/chunks/chunk-I7IOIL6U.js +151 -0
- package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
- package/lib/chunks/chunk-IFOYVSPU.js +22 -0
- package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
- package/lib/chunks/chunk-JTAGPPPL.js +22 -0
- package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
- package/lib/chunks/chunk-MZ232FUE.js +22 -0
- package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
- package/lib/chunks/chunk-NP2AN2TV.js +22 -0
- package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
- package/lib/chunks/chunk-QJAU2MWV.js +22 -0
- package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
- package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
- package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
- package/lib/chunks/chunk-RQZGIZHD.js +151 -0
- package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
- package/lib/chunks/chunk-TBEDQLOB.js +23 -0
- package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
- package/lib/chunks/chunk-TMHBP3HB.js +22 -0
- package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
- package/lib/chunks/chunk-UH4L3EF3.js +151 -0
- package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
- package/lib/chunks/chunk-UJBIU6TL.js +22 -0
- package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
- package/lib/chunks/chunk-VKEYW3NT.js +22 -0
- package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
- package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
- package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
- package/lib/chunks/chunk-Y44NEQQG.js +22 -0
- package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
- package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
- package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
- package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
- package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
- package/lib/chunks/monitoring-PVQMFL34.js +22 -0
- package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
- package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
- package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
- package/lib/chunks/server-32A5RH4C.js +22 -0
- package/lib/chunks/server-32A5RH4C.js.map +7 -0
- package/lib/chunks/server-7HDAP5DL.js +22 -0
- package/lib/chunks/server-7HDAP5DL.js.map +7 -0
- package/lib/chunks/server-S2IMFOY7.js +22 -0
- package/lib/chunks/server-S2IMFOY7.js.map +7 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/index.d.ts +2 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
- package/lib/firebase/billing/webhookHandler.d.ts +17 -2
- package/lib/firebase/crud/aggregate.d.ts +0 -9
- package/lib/firebase/crud/bulk.d.ts +2 -2
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/shared/billing/apiVersion.d.ts +22 -0
- package/lib/shared/billing/checkoutPrice.d.ts +27 -0
- package/lib/shared/billing/checkoutValidation.d.ts +89 -0
- package/lib/shared/billing/createCheckout.d.ts +73 -24
- package/lib/shared/billing/helpers/index.d.ts +0 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
- package/lib/shared/billing/idempotency.d.ts +32 -10
- package/lib/shared/billing/idempotencyContract.d.ts +121 -0
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +75 -0
- package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +28 -20
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +4 -17
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +10 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
- package/lib/vercel/api/billing/backend.d.ts +39 -0
- package/lib/vercel/api/billing/cancel.d.ts +8 -0
- package/lib/vercel/api/billing/change-plan.d.ts +9 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
- package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
- package/lib/vercel/api/billing/index.d.ts +4 -2
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
- package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/crud/bulk.d.ts +17 -0
- package/lib/vercel/api/crud/create.d.ts +8 -0
- package/lib/vercel/api/crud/delete.d.ts +8 -0
- package/lib/vercel/api/crud/get.d.ts +8 -0
- package/lib/vercel/api/crud/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -0
- package/lib/vercel/api/index.js +1 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/baseFunction.d.ts +4 -1
- package/lib/vercel/supabaseAdmin.d.ts +22 -0
- package/package.json +25 -26
- package/src/firebase/auth/getCustomClaims.ts +4 -5
- package/src/firebase/auth/getUserAuthStatus.ts +4 -5
- package/src/firebase/auth/removeCustomClaims.ts +4 -5
- package/src/firebase/auth/setCustomClaims.ts +4 -5
- package/src/firebase/baseFunction.ts +4 -5
- package/src/firebase/billing/cancelSubscription.ts +1 -2
- package/src/firebase/billing/changePlan.ts +2 -3
- package/src/firebase/billing/createCheckoutSession.ts +30 -56
- package/src/firebase/billing/createCustomerPortal.ts +4 -5
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
- package/src/firebase/billing/webhookHandler.ts +20 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
- package/src/firebase/crud/aggregate.ts +1 -2
- package/src/firebase/crud/bulk.ts +5 -6
- package/src/firebase/crud/create.ts +5 -6
- package/src/firebase/crud/delete.ts +4 -5
- package/src/firebase/crud/get.ts +4 -5
- package/src/firebase/crud/list.ts +4 -5
- package/src/firebase/crud/update.ts +5 -6
- package/src/firebase/oauth/githubAccess.ts +2 -3
- package/src/firebase/registerCrudFunctions.ts +2 -2
- package/src/shared/__tests__/auth.test.ts +0 -3
- package/src/shared/__tests__/bulkCore.test.ts +3 -2
- package/src/shared/__tests__/errorHandling.test.ts +2 -2
- package/src/shared/__tests__/idempotency.test.ts +282 -55
- package/src/shared/__tests__/internalValidation.test.ts +3 -3
- package/src/shared/__tests__/rateLimiter.test.ts +2 -8
- package/src/shared/__tests__/schemaValidation.test.ts +1 -1
- package/src/shared/__tests__/utils.test.ts +2 -1
- package/src/shared/__tests__/validation-env.test.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +53 -30
- package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
- package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
- package/src/shared/billing/apiVersion.ts +25 -0
- package/src/shared/billing/checkoutPrice.ts +125 -0
- package/src/shared/billing/checkoutValidation.ts +284 -0
- package/src/shared/billing/createCheckout.ts +332 -196
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +253 -150
- package/src/shared/billing/idempotencyContract.ts +135 -0
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +269 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +188 -385
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +2 -3
- package/src/shared/utils/functionWrapper.ts +1 -2
- package/src/shared/utils/internal/auth.ts +55 -7
- package/src/shared/utils/internal/monitoring.ts +17 -9
- package/src/shared/utils/internal/rateLimiter.ts +14 -5
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +14 -31
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +3 -1
- package/src/supabase/__tests__/entityStore.test.ts +90 -0
- package/src/supabase/baseFunction.ts +1 -2
- package/src/supabase/billing/createCheckoutSession.ts +10 -36
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
- package/src/supabase/billing/stripeWebhook.ts +79 -0
- package/src/supabase/crud/aggregate.ts +1 -1
- package/src/supabase/crud/bulk.ts +3 -7
- package/src/supabase/crud/create.ts +1 -1
- package/src/supabase/crud/entityStore.ts +240 -0
- package/src/supabase/crud/index.ts +8 -0
- package/src/supabase/crud/update.ts +1 -1
- package/src/supabase/helpers/authProvider.ts +6 -5
- package/src/supabase/index.ts +26 -0
- package/src/supabase/utils/rateLimiter.ts +2 -2
- package/src/vercel/__tests__/bulk.test.ts +24 -21
- package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
- package/src/vercel/api/ai/chat.ts +2 -1
- package/src/vercel/api/auth/get-custom-claims.ts +2 -3
- package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
- package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
- package/src/vercel/api/auth/set-custom-claims.ts +3 -3
- package/src/vercel/api/billing/backend.ts +72 -0
- package/src/vercel/api/billing/cancel.ts +2 -4
- package/src/vercel/api/billing/change-plan.ts +3 -4
- package/src/vercel/api/billing/create-checkout-session.ts +42 -68
- package/src/vercel/api/billing/customer-portal.ts +2 -4
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
- package/src/vercel/api/billing/webhook-handler.ts +31 -25
- package/src/vercel/api/config/firebase-admin.ts +2 -2
- package/src/vercel/api/crud/bulk.ts +6 -9
- package/src/vercel/api/crud/create.ts +6 -5
- package/src/vercel/api/crud/delete.ts +4 -3
- package/src/vercel/api/crud/get.ts +6 -5
- package/src/vercel/api/crud/list.ts +6 -5
- package/src/vercel/api/crud/update.ts +6 -5
- package/src/vercel/api/oauth/check-github-access.ts +5 -5
- package/src/vercel/api/oauth/exchange-token.ts +3 -3
- package/src/vercel/api/oauth/grant-github-access.ts +5 -5
- package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
- package/src/vercel/baseFunction.ts +23 -8
- package/src/vercel/supabaseAdmin.ts +45 -0
|
@@ -10,16 +10,64 @@
|
|
|
10
10
|
* @author AMBROISE PARK Consulting
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import { hasProvider, getProvider } from '@donotdev/core/server';
|
|
14
|
-
import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
|
|
15
|
-
|
|
16
13
|
import type { NextApiRequest } from 'next';
|
|
14
|
+
import * as v from 'valibot';
|
|
15
|
+
|
|
16
|
+
import { DoNotDevError, hasProvider, getProvider } from '@donotdev/core/server';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Auth backends a server function can be explicitly configured with.
|
|
20
|
+
*
|
|
21
|
+
* @version 0.2.0
|
|
22
|
+
* @since 0.2.0
|
|
23
|
+
* @author AMBROISE PARK Consulting
|
|
24
|
+
*/
|
|
25
|
+
export const AuthBackendSchema = v.picklist(['firebase', 'supabase']);
|
|
17
26
|
|
|
18
27
|
/** Auth provider type for explicit configuration */
|
|
19
|
-
export type AuthProvider =
|
|
28
|
+
export type AuthProvider = v.InferOutput<typeof AuthBackendSchema>;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Validate an auth backend at runtime. Values typed as `AuthProvider` can
|
|
32
|
+
* still arrive as arbitrary strings from JS or env-driven config, and an
|
|
33
|
+
* unknown value must never silently run as Firebase.
|
|
34
|
+
*
|
|
35
|
+
* @param backend - Value to validate
|
|
36
|
+
* @returns The validated backend
|
|
37
|
+
* @throws DoNotDevError (`invalid-argument`) naming the allowed values
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```typescript
|
|
41
|
+
* const backend = parseAuthBackend(process.env.AUTH_BACKEND); // 'firebase' | 'supabase'
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* @version 0.2.0
|
|
45
|
+
* @since 0.2.0
|
|
46
|
+
* @author AMBROISE PARK Consulting
|
|
47
|
+
*/
|
|
48
|
+
export function parseAuthBackend(backend: unknown): AuthProvider {
|
|
49
|
+
const result = v.safeParse(AuthBackendSchema, backend);
|
|
50
|
+
if (!result.success) {
|
|
51
|
+
const allowed = AuthBackendSchema.options.map((o) => `'${o}'`).join(', ');
|
|
52
|
+
throw new DoNotDevError(
|
|
53
|
+
`Invalid backend ${JSON.stringify(backend)}: expected one of ${allowed}`,
|
|
54
|
+
'invalid-argument'
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
return result.output;
|
|
58
|
+
}
|
|
20
59
|
|
|
21
60
|
// IMPORTANT: Don't call getAuth() at module load - breaks Firebase deployment
|
|
22
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Firebase Admin Auth, loaded on first use. `firebase-admin` is an optional
|
|
64
|
+
* peer: Supabase deployments never load it.
|
|
65
|
+
*/
|
|
66
|
+
async function getFirebaseAuth() {
|
|
67
|
+
const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
|
|
68
|
+
return getFirebaseAdminAuth();
|
|
69
|
+
}
|
|
70
|
+
|
|
23
71
|
/**
|
|
24
72
|
* Validates that user is authenticated
|
|
25
73
|
*
|
|
@@ -54,7 +102,7 @@ export async function assertAdmin(uid: string): Promise<string> {
|
|
|
54
102
|
claims = (user?.customClaims as Record<string, unknown>) ?? {};
|
|
55
103
|
} else {
|
|
56
104
|
// Legacy Firebase path
|
|
57
|
-
const user = await
|
|
105
|
+
const user = await (await getFirebaseAuth()).getUser(uid);
|
|
58
106
|
claims = user.customClaims ?? {};
|
|
59
107
|
}
|
|
60
108
|
|
|
@@ -134,7 +182,7 @@ export async function verifyToken(
|
|
|
134
182
|
}
|
|
135
183
|
|
|
136
184
|
if (provider === 'firebase') {
|
|
137
|
-
const decodedToken = await
|
|
185
|
+
const decodedToken = await (await getFirebaseAuth()).verifyIdToken(token);
|
|
138
186
|
return { uid: decodedToken.uid };
|
|
139
187
|
}
|
|
140
188
|
|
|
@@ -145,7 +193,7 @@ export async function verifyToken(
|
|
|
145
193
|
}
|
|
146
194
|
|
|
147
195
|
// Legacy Firebase path
|
|
148
|
-
const decodedToken = await
|
|
196
|
+
const decodedToken = await (await getFirebaseAuth()).verifyIdToken(token);
|
|
149
197
|
return { uid: decodedToken.uid };
|
|
150
198
|
} catch (error) {
|
|
151
199
|
throw new Error('Invalid or expired token');
|
|
@@ -9,9 +9,17 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { logger } from '
|
|
12
|
+
import { logger } from '../../logger.js';
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Firestore, loaded on first use. `firebase-admin` is an optional peer:
|
|
16
|
+
* Supabase deployments never load it.
|
|
17
|
+
*/
|
|
18
|
+
async function getFirestore() {
|
|
19
|
+
const { getFirebaseAdminFirestore } =
|
|
20
|
+
await import('@donotdev/firebase/server');
|
|
21
|
+
return getFirebaseAdminFirestore();
|
|
22
|
+
}
|
|
15
23
|
|
|
16
24
|
/**
|
|
17
25
|
* Payment metrics data structure
|
|
@@ -54,7 +62,7 @@ export async function recordPaymentMetrics(
|
|
|
54
62
|
metrics: PaymentMetrics
|
|
55
63
|
): Promise<void> {
|
|
56
64
|
try {
|
|
57
|
-
const db =
|
|
65
|
+
const db = await getFirestore();
|
|
58
66
|
const metricsRef = db.collection('payment_metrics').doc();
|
|
59
67
|
await metricsRef.set({
|
|
60
68
|
...metrics,
|
|
@@ -86,7 +94,7 @@ export async function checkPaymentFailureRate(
|
|
|
86
94
|
timeWindowHours: number = 24
|
|
87
95
|
): Promise<{ failureRate: number; shouldAlert: boolean }> {
|
|
88
96
|
try {
|
|
89
|
-
const db =
|
|
97
|
+
const db = await getFirestore();
|
|
90
98
|
const cutoffTime = new Date();
|
|
91
99
|
cutoffTime.setHours(cutoffTime.getHours() - timeWindowHours);
|
|
92
100
|
|
|
@@ -135,7 +143,7 @@ export async function checkPaymentVolume(
|
|
|
135
143
|
volumeThreshold: number = 10000 // $10,000 default threshold
|
|
136
144
|
): Promise<{ totalVolume: number; shouldAlert: boolean }> {
|
|
137
145
|
try {
|
|
138
|
-
const db =
|
|
146
|
+
const db = await getFirestore();
|
|
139
147
|
const today = new Date();
|
|
140
148
|
today.setHours(0, 0, 0, 0);
|
|
141
149
|
const tomorrow = new Date(today);
|
|
@@ -180,7 +188,7 @@ async function triggerPaymentFailureAlert(
|
|
|
180
188
|
failedPayments: number
|
|
181
189
|
): Promise<void> {
|
|
182
190
|
try {
|
|
183
|
-
const db =
|
|
191
|
+
const db = await getFirestore();
|
|
184
192
|
const alertRef = db.collection('payment_alerts').doc();
|
|
185
193
|
await alertRef.set({
|
|
186
194
|
type: 'payment_failure_rate',
|
|
@@ -221,7 +229,7 @@ async function triggerHighVolumeAlert(
|
|
|
221
229
|
threshold: number
|
|
222
230
|
): Promise<void> {
|
|
223
231
|
try {
|
|
224
|
-
const db =
|
|
232
|
+
const db = await getFirestore();
|
|
225
233
|
const alertRef = db.collection('payment_alerts').doc();
|
|
226
234
|
await alertRef.set({
|
|
227
235
|
type: 'high_payment_volume',
|
|
@@ -264,7 +272,7 @@ export async function getPaymentMetricsSummary(
|
|
|
264
272
|
averageAmount: number;
|
|
265
273
|
}> {
|
|
266
274
|
try {
|
|
267
|
-
const db =
|
|
275
|
+
const db = await getFirestore();
|
|
268
276
|
const metricsRef = db.collection('payment_metrics');
|
|
269
277
|
const metrics = await metricsRef
|
|
270
278
|
.where('timestamp', '>=', startDate.toISOString())
|
|
@@ -326,7 +334,7 @@ export async function cleanupOldMetrics(
|
|
|
326
334
|
alertsRetentionDays: number = 30
|
|
327
335
|
): Promise<void> {
|
|
328
336
|
try {
|
|
329
|
-
const db =
|
|
337
|
+
const db = await getFirestore();
|
|
330
338
|
const now = new Date();
|
|
331
339
|
|
|
332
340
|
// Clean up old metrics
|
|
@@ -9,13 +9,12 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { logger } from 'firebase-functions/v2';
|
|
13
|
-
|
|
14
12
|
import type {
|
|
15
13
|
ServerRateLimitConfig as RateLimitConfig,
|
|
16
14
|
ServerRateLimitResult as RateLimitResult,
|
|
17
15
|
} from '@donotdev/core';
|
|
18
|
-
|
|
16
|
+
|
|
17
|
+
import { logger } from '../../logger.js';
|
|
19
18
|
|
|
20
19
|
export type { RateLimitConfig, RateLimitResult };
|
|
21
20
|
|
|
@@ -25,6 +24,16 @@ interface RateLimitEntry {
|
|
|
25
24
|
blockUntil: number | null;
|
|
26
25
|
}
|
|
27
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Firestore, loaded on first use. `firebase-admin` is an optional peer:
|
|
29
|
+
* Supabase deployments never load it.
|
|
30
|
+
*/
|
|
31
|
+
async function getFirestore() {
|
|
32
|
+
const { getFirebaseAdminFirestore } =
|
|
33
|
+
await import('@donotdev/firebase/server');
|
|
34
|
+
return getFirebaseAdminFirestore();
|
|
35
|
+
}
|
|
36
|
+
|
|
28
37
|
// In-memory storage for rate limiting (in production, use Redis or Firestore)
|
|
29
38
|
const rateLimitStore = new Map<string, RateLimitEntry>();
|
|
30
39
|
|
|
@@ -121,7 +130,7 @@ export async function checkRateLimitWithFirestore(
|
|
|
121
130
|
key: string,
|
|
122
131
|
config: RateLimitConfig
|
|
123
132
|
): Promise<RateLimitResult> {
|
|
124
|
-
const db =
|
|
133
|
+
const db = await getFirestore();
|
|
125
134
|
const rateLimitRef = db.collection('rateLimits').doc(key);
|
|
126
135
|
|
|
127
136
|
try {
|
|
@@ -258,7 +267,7 @@ export function resetRateLimit(key: string): void {
|
|
|
258
267
|
* @author AMBROISE PARK Consulting
|
|
259
268
|
*/
|
|
260
269
|
export async function resetRateLimitInFirestore(key: string): Promise<void> {
|
|
261
|
-
const db =
|
|
270
|
+
const db = await getFirestore();
|
|
262
271
|
const rateLimitRef = db.collection('rateLimits').doc(key);
|
|
263
272
|
|
|
264
273
|
try {
|
|
@@ -9,10 +9,9 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import * as v from 'valibot';
|
|
13
|
-
|
|
14
12
|
import type { CallableRequest } from 'firebase-functions/v2/https';
|
|
15
13
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
14
|
+
import * as v from 'valibot';
|
|
16
15
|
|
|
17
16
|
/**
|
|
18
17
|
* Validates request data using a schema with custom override support
|
|
@@ -9,14 +9,14 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
13
|
+
import type * as v from 'valibot';
|
|
14
|
+
|
|
12
15
|
import {
|
|
13
16
|
withVercelSchemaValidation,
|
|
14
17
|
validateRequestData,
|
|
15
18
|
} from './schemaValidation.js';
|
|
16
19
|
|
|
17
|
-
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
18
|
-
import type * as v from 'valibot';
|
|
19
|
-
|
|
20
20
|
/**
|
|
21
21
|
* Creates a Vercel API handler with schema validation
|
|
22
22
|
*
|
package/src/shared/utils.ts
CHANGED
|
@@ -14,12 +14,8 @@ import * as v from 'valibot';
|
|
|
14
14
|
|
|
15
15
|
import { DoNotDevError } from '@donotdev/core/server';
|
|
16
16
|
import type { OAuthPartnerId, UserRole } from '@donotdev/core/server';
|
|
17
|
-
import {
|
|
18
|
-
getFirebaseAdminAuth,
|
|
19
|
-
getFirebaseAdminFirestore,
|
|
20
|
-
initFirebaseAdmin,
|
|
21
|
-
} from '@donotdev/firebase/server';
|
|
22
17
|
|
|
18
|
+
import { STRIPE_API_VERSION_PIN } from './billing/apiVersion.js';
|
|
23
19
|
import {
|
|
24
20
|
assertAuthenticated as internalAssertAuthenticated,
|
|
25
21
|
assertAdmin as internalAssertAdmin,
|
|
@@ -28,41 +24,23 @@ import {
|
|
|
28
24
|
// Re-export DoNotDevError for external use
|
|
29
25
|
export { DoNotDevError };
|
|
30
26
|
|
|
31
|
-
/**
|
|
32
|
-
* Get Firestore instance using @donotdev/firebase/server
|
|
33
|
-
* Provider handles initialization and caching
|
|
34
|
-
*
|
|
35
|
-
* @version 0.1.0
|
|
36
|
-
* @since 0.0.1
|
|
37
|
-
* @author AMBROISE PARK Consulting
|
|
38
|
-
*/
|
|
39
|
-
export function getFirestore() {
|
|
40
|
-
return getFirebaseAdminFirestore();
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Get Auth instance using @donotdev/firebase/server
|
|
45
|
-
* Provider handles initialization and caching
|
|
46
|
-
*
|
|
47
|
-
* @version 0.1.0
|
|
48
|
-
* @since 0.0.1
|
|
49
|
-
* @author AMBROISE PARK Consulting
|
|
50
|
-
*/
|
|
51
|
-
export function getAuth() {
|
|
52
|
-
return getFirebaseAdminAuth();
|
|
53
|
-
}
|
|
54
|
-
|
|
55
27
|
// Lazy initialization of Stripe
|
|
56
28
|
let _stripe: Stripe | null = null;
|
|
57
29
|
|
|
58
30
|
/**
|
|
59
|
-
* Initialize Stripe explicitly (e.g. with a secret from defineSecret)
|
|
31
|
+
* Initialize Stripe explicitly (e.g. with a secret from defineSecret).
|
|
32
|
+
* API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.
|
|
60
33
|
* @param apiKey - Stripe secret key
|
|
34
|
+
*
|
|
35
|
+
* @version 0.2.0
|
|
36
|
+
* @since 0.0.1
|
|
37
|
+
* @author AMBROISE PARK Consulting
|
|
61
38
|
*/
|
|
62
39
|
export function initStripe(apiKey: string) {
|
|
63
40
|
if (!apiKey) throw new Error('Stripe API key is required');
|
|
64
41
|
|
|
65
|
-
|
|
42
|
+
// Unset: the framework pin (pre-basil fields are still read by subscription handlers)
|
|
43
|
+
const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
|
|
66
44
|
|
|
67
45
|
_stripe = new Stripe(apiKey, {
|
|
68
46
|
apiVersion: apiVersion as any,
|
|
@@ -414,6 +392,8 @@ export async function verifyFirebaseAuthToken(token: string): Promise<string> {
|
|
|
414
392
|
throw new DoNotDevError('Missing authentication token', 'unauthenticated');
|
|
415
393
|
}
|
|
416
394
|
|
|
395
|
+
// Lazy: the Vercel/Supabase entries must load without firebase-admin
|
|
396
|
+
const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
|
|
417
397
|
try {
|
|
418
398
|
const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);
|
|
419
399
|
return decodedToken.uid;
|
|
@@ -449,6 +429,9 @@ export async function findReferences(
|
|
|
449
429
|
return references;
|
|
450
430
|
}
|
|
451
431
|
|
|
432
|
+
// Lazy: the Vercel/Supabase entries must load without firebase-admin
|
|
433
|
+
const { getFirebaseAdminFirestore } =
|
|
434
|
+
await import('@donotdev/firebase/server');
|
|
452
435
|
const db = getFirebaseAdminFirestore();
|
|
453
436
|
|
|
454
437
|
for (const ref of referenceMetadata.incoming) {
|
package/src/shared/validation.ts
CHANGED
|
@@ -43,7 +43,7 @@ export function validateEnvironment(): void {
|
|
|
43
43
|
if (!apiVersion.match(/^\d{4}-\d{2}-\d{2}\./)) {
|
|
44
44
|
throw new Error(
|
|
45
45
|
`❌ Invalid STRIPE_API_VERSION format: "${apiVersion}"\n` +
|
|
46
|
-
`Expected format: YYYY-MM-DD.name (e.g., "2025-
|
|
46
|
+
`Expected format: YYYY-MM-DD.name (e.g., "2025-02-24.acacia")`
|
|
47
47
|
);
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* inner business logic directly without needing a mock Deno `Request`.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
10
9
|
import * as v from 'valibot';
|
|
10
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
11
11
|
|
|
12
12
|
// ---------------------------------------------------------------------------
|
|
13
13
|
// Mocks
|
|
@@ -79,6 +79,7 @@ function setup(opts?: {
|
|
|
79
79
|
const inner = createSupabaseBulkEntity(
|
|
80
80
|
'events',
|
|
81
81
|
CreateSchema,
|
|
82
|
+
CreateSchema,
|
|
82
83
|
UpdateSchema,
|
|
83
84
|
access
|
|
84
85
|
) as unknown as (data: any, ctx: any) => Promise<any>;
|
|
@@ -227,6 +228,7 @@ describe('createSupabaseBulkEntity', () => {
|
|
|
227
228
|
const inner = createSupabaseBulkEntity(
|
|
228
229
|
'events',
|
|
229
230
|
CreateSchema,
|
|
231
|
+
CreateSchema,
|
|
230
232
|
UpdateSchema,
|
|
231
233
|
{ ...access, delete: 'admin' }
|
|
232
234
|
) as unknown as (data: any, ctx: any) => Promise<any>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `createEntityStore`: field mapping both ways,
|
|
3
|
+
* publication filter, unknown-field rejection, single-row `find`, writes.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { describe, it, expect } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { createEntityStore } from '../crud/entityStore.js';
|
|
9
|
+
|
|
10
|
+
type Call = [string, ...unknown[]];
|
|
11
|
+
|
|
12
|
+
/** Records every builder call; awaiting the query resolves to `result`. */
|
|
13
|
+
function fakeClient(result: { data: unknown; error: { message: string } | null }) {
|
|
14
|
+
const calls: Call[] = [];
|
|
15
|
+
const query: Record<string, unknown> = {};
|
|
16
|
+
for (const m of ['select', 'insert', 'update', 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'not', 'contains', 'overlaps', 'order', 'limit']) {
|
|
17
|
+
query[m] = (...args: unknown[]) => {
|
|
18
|
+
calls.push([m, ...args]);
|
|
19
|
+
return query;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
query.then = (resolve: (r: unknown) => unknown) => Promise.resolve(result).then(resolve);
|
|
23
|
+
const client = {
|
|
24
|
+
from: (table: string) => {
|
|
25
|
+
calls.push(['from', table]);
|
|
26
|
+
return query;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
return { client: client as never, calls };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const entity = {
|
|
33
|
+
name: 'Product',
|
|
34
|
+
collection: 'products',
|
|
35
|
+
fields: { id: {}, status: {}, name: {}, weightGrams: {}, brandId: {} },
|
|
36
|
+
} as never;
|
|
37
|
+
|
|
38
|
+
describe('createEntityStore', () => {
|
|
39
|
+
it('lists with entity names in, snake_case columns out, hidden statuses excluded', async () => {
|
|
40
|
+
const { client, calls } = fakeClient({ data: [{ id: 'p1', name: 'A', weight_grams: 50 }], error: null });
|
|
41
|
+
const rows = await createEntityStore(client, entity).list({
|
|
42
|
+
where: [['brandId', 'in', ['b1']]],
|
|
43
|
+
select: ['name', 'weightGrams'],
|
|
44
|
+
orderBy: [['name', 'asc']],
|
|
45
|
+
});
|
|
46
|
+
expect(rows).toEqual([{ id: 'p1', name: 'A', weightGrams: 50 }]);
|
|
47
|
+
expect(calls).toEqual([
|
|
48
|
+
['from', 'products'],
|
|
49
|
+
['select', 'id, name, weight_grams'],
|
|
50
|
+
['in', 'brand_id', ['b1']],
|
|
51
|
+
['not', 'status', 'in', '("draft","deleted")'],
|
|
52
|
+
['order', 'name', { ascending: true }],
|
|
53
|
+
]);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('includeHidden drops the publication filter', async () => {
|
|
57
|
+
const { client, calls } = fakeClient({ data: [], error: null });
|
|
58
|
+
await createEntityStore(client, entity).list({ includeHidden: true });
|
|
59
|
+
expect(calls.some(([m]) => m === 'not')).toBe(false);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('rejects fields the entity does not define', async () => {
|
|
63
|
+
const { client } = fakeClient({ data: [], error: null });
|
|
64
|
+
await expect(createEntityStore(client, entity).list({ where: [['price', '==', 1]] })).rejects.toThrow("unknown field 'price'");
|
|
65
|
+
await expect(createEntityStore(client, entity).insert([{ price: 1 } as never])).rejects.toThrow("unknown field 'price'");
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('find returns null, one row, or fails on several', async () => {
|
|
69
|
+
const none = fakeClient({ data: [], error: null });
|
|
70
|
+
expect(await createEntityStore(none.client, entity).get('p1')).toBeNull();
|
|
71
|
+
const two = fakeClient({ data: [{ id: 'a' }, { id: 'b' }], error: null });
|
|
72
|
+
await expect(createEntityStore(two.client, entity).find({ where: [['name', '==', 'A']] })).rejects.toThrow('more than one row');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('insert and update map keys, skip undefined, return stored rows', async () => {
|
|
76
|
+
const { client, calls } = fakeClient({ data: [{ id: 'p1', weight_grams: 10 }], error: null });
|
|
77
|
+
const store = createEntityStore(client, entity);
|
|
78
|
+
expect(await store.insert([{ weightGrams: 10, name: undefined }])).toEqual([{ id: 'p1', weightGrams: 10 }]);
|
|
79
|
+
await store.update([['id', '==', 'p1']], { weightGrams: 10 });
|
|
80
|
+
expect(calls).toContainEqual(['insert', [{ weight_grams: 10 }]]);
|
|
81
|
+
expect(calls).toContainEqual(['update', { weight_grams: 10 }]);
|
|
82
|
+
expect(calls).toContainEqual(['eq', 'id', 'p1']);
|
|
83
|
+
await expect(store.update([], { weightGrams: 1 })).rejects.toThrow('update without a condition');
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('surfaces database errors', async () => {
|
|
87
|
+
const { client } = fakeClient({ data: null, error: { message: 'boom' } });
|
|
88
|
+
await expect(createEntityStore(client, entity).list()).rejects.toThrow('list products: boom');
|
|
89
|
+
});
|
|
90
|
+
});
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { createClient } from '@supabase/supabase-js';
|
|
14
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
14
15
|
import * as v from 'valibot';
|
|
15
16
|
|
|
16
17
|
import { hasRoleAccess } from '@donotdev/core/server';
|
|
@@ -21,9 +22,7 @@ import {
|
|
|
21
22
|
checkRateLimitWithPostgres,
|
|
22
23
|
DEFAULT_RATE_LIMITS,
|
|
23
24
|
} from './utils/rateLimiter.js';
|
|
24
|
-
|
|
25
25
|
import type { RateLimitConfig } from './utils/rateLimiter.js';
|
|
26
|
-
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
27
26
|
|
|
28
27
|
// =============================================================================
|
|
29
28
|
// Types
|
|
@@ -14,6 +14,7 @@ import type { StripeBackConfig } from '@donotdev/core/server';
|
|
|
14
14
|
import type { CreateCheckoutSessionRequest } from '@donotdev/core/server';
|
|
15
15
|
|
|
16
16
|
import { createCheckoutAlgorithm } from '../../shared/billing/createCheckout.js';
|
|
17
|
+
import type { StripeSessionProvider } from '../../shared/billing/createCheckout.js';
|
|
17
18
|
import {
|
|
18
19
|
initStripe,
|
|
19
20
|
stripe,
|
|
@@ -45,48 +46,21 @@ export function createCheckoutSession(billingConfig: StripeBackConfig) {
|
|
|
45
46
|
|
|
46
47
|
const authProvider = createSupabaseAuthProvider(ctx.supabaseAdmin);
|
|
47
48
|
|
|
48
|
-
const stripeProvider = {
|
|
49
|
-
async
|
|
50
|
-
|
|
51
|
-
unitAmount?: number;
|
|
52
|
-
productName?: string;
|
|
53
|
-
currency?: string;
|
|
54
|
-
customerEmail?: string;
|
|
55
|
-
metadata: Record<string, string>;
|
|
56
|
-
allowPromotionCodes: boolean;
|
|
57
|
-
successUrl: string;
|
|
58
|
-
cancelUrl: string;
|
|
59
|
-
mode?: 'payment' | 'subscription';
|
|
60
|
-
}) {
|
|
61
|
-
const session = await stripe.checkout.sessions.create({
|
|
62
|
-
mode: params.mode || 'payment',
|
|
63
|
-
line_items: [
|
|
64
|
-
params.priceId
|
|
65
|
-
? { price: params.priceId, quantity: 1 }
|
|
66
|
-
: {
|
|
67
|
-
price_data: {
|
|
68
|
-
currency: params.currency || 'eur',
|
|
69
|
-
unit_amount: params.unitAmount!,
|
|
70
|
-
product_data: { name: params.productName! },
|
|
71
|
-
},
|
|
72
|
-
quantity: 1,
|
|
73
|
-
},
|
|
74
|
-
],
|
|
75
|
-
customer_email: params.customerEmail || undefined,
|
|
76
|
-
success_url: params.successUrl,
|
|
77
|
-
cancel_url: params.cancelUrl,
|
|
78
|
-
allow_promotion_codes: params.allowPromotionCodes,
|
|
79
|
-
metadata: params.metadata,
|
|
80
|
-
...(params.mode === 'subscription' && {
|
|
81
|
-
subscription_data: { metadata: params.metadata },
|
|
82
|
-
}),
|
|
83
|
-
});
|
|
49
|
+
const stripeProvider: StripeSessionProvider = {
|
|
50
|
+
async createStripeSession(params) {
|
|
51
|
+
const session = await stripe.checkout.sessions.create(params);
|
|
84
52
|
return { id: session.id, url: session.url };
|
|
85
53
|
},
|
|
54
|
+
async retrieveTaxRate(id) {
|
|
55
|
+
const rate = await stripe.taxRates.retrieve(id);
|
|
56
|
+
return { id: rate.id, inclusive: rate.inclusive };
|
|
57
|
+
},
|
|
86
58
|
};
|
|
87
59
|
|
|
60
|
+
// userId comes from the verified JWT, never from the client
|
|
88
61
|
return createCheckoutAlgorithm(
|
|
89
62
|
data,
|
|
63
|
+
ctx.uid,
|
|
90
64
|
stripeProvider,
|
|
91
65
|
authProvider,
|
|
92
66
|
billingConfig
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import type Stripe from 'stripe';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import {
|
|
@@ -19,8 +20,6 @@ import {
|
|
|
19
20
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
20
21
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
21
22
|
|
|
22
|
-
import type Stripe from 'stripe';
|
|
23
|
-
|
|
24
23
|
// =============================================================================
|
|
25
24
|
// Schema
|
|
26
25
|
// =============================================================================
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// packages/functions/src/supabase/billing/stripeWebhook.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Stripe webhook Supabase Edge Function
|
|
5
|
+
* @description Verifies and routes Stripe webhook events through the shared
|
|
6
|
+
* processWebhook (SSOT). Idempotency is stored in Postgres (`webhook_events`).
|
|
7
|
+
*
|
|
8
|
+
* @version 0.2.0
|
|
9
|
+
* @since 0.2.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { StripeBackConfig } from '@donotdev/core/server';
|
|
14
|
+
|
|
15
|
+
import { updateUserSubscription } from '../../shared/billing/helpers/updateUserSubscription.js';
|
|
16
|
+
import { createSupabaseIdempotencyStore } from '../../shared/billing/idempotency.js';
|
|
17
|
+
import { processWebhook } from '../../shared/billing/webhookHandler.js';
|
|
18
|
+
import { initStripe, stripe } from '../../shared/utils.js';
|
|
19
|
+
import { createEdgeFunction } from '../edgeFunction.js';
|
|
20
|
+
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
21
|
+
|
|
22
|
+
declare const Deno:
|
|
23
|
+
| { env: { get(key: string): string | undefined } }
|
|
24
|
+
| undefined;
|
|
25
|
+
|
|
26
|
+
function getEnvOrThrow(key: string): string {
|
|
27
|
+
const value =
|
|
28
|
+
typeof Deno !== 'undefined' ? Deno.env.get(key) : process.env[key];
|
|
29
|
+
if (!value) throw new Error(`Missing ${key} environment variable`);
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Create a Supabase Edge Function handler for Stripe webhooks.
|
|
35
|
+
* Requires the `webhook_events` migration (see `WEBHOOK_EVENTS_SQL`).
|
|
36
|
+
* Deploy with JWT verification disabled for this function: Stripe authenticates
|
|
37
|
+
* with its signature, not a Supabase JWT.
|
|
38
|
+
* Any failure answers non-2xx so Stripe retries the event.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* // supabase/functions/stripe-webhook/index.ts
|
|
43
|
+
* import { createStripeWebhook } from '@donotdev/functions/supabase';
|
|
44
|
+
* import { billingConfig } from '../_shared/billingConfig.ts';
|
|
45
|
+
*
|
|
46
|
+
* Deno.serve(createStripeWebhook(billingConfig));
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* @param billingConfig - App back config
|
|
50
|
+
* @returns `(req: Request) => Promise<Response>` handler
|
|
51
|
+
*
|
|
52
|
+
* @version 0.2.0
|
|
53
|
+
* @since 0.2.0
|
|
54
|
+
* @author AMBROISE PARK Consulting
|
|
55
|
+
*/
|
|
56
|
+
export function createStripeWebhook(billingConfig: StripeBackConfig) {
|
|
57
|
+
return createEdgeFunction(
|
|
58
|
+
async (req, ctx) => {
|
|
59
|
+
const signature = req.headers.get('stripe-signature');
|
|
60
|
+
if (!signature) return ctx.error('Missing Stripe signature', 400);
|
|
61
|
+
|
|
62
|
+
initStripe(getEnvOrThrow('STRIPE_SECRET_KEY'));
|
|
63
|
+
|
|
64
|
+
const result = await processWebhook(
|
|
65
|
+
await req.text(),
|
|
66
|
+
signature,
|
|
67
|
+
getEnvOrThrow('STRIPE_WEBHOOK_SECRET'),
|
|
68
|
+
stripe,
|
|
69
|
+
billingConfig,
|
|
70
|
+
updateUserSubscription,
|
|
71
|
+
createSupabaseAuthProvider(ctx.supabaseAdmin),
|
|
72
|
+
createSupabaseIdempotencyStore(ctx.supabaseAdmin)
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
return ctx.json({ received: true, message: result.message });
|
|
76
|
+
},
|
|
77
|
+
{ requireAuth: false, extraHeaders: ['stripe-signature'] }
|
|
78
|
+
);
|
|
79
|
+
}
|
|
@@ -89,7 +89,7 @@ export function createSupabaseAggregateEntities(
|
|
|
89
89
|
const { supabaseAdmin } = ctx;
|
|
90
90
|
|
|
91
91
|
const aggregateColumn = mapper.toBackendField(aggregate.field);
|
|
92
|
-
|
|
92
|
+
|
|
93
93
|
let query: any = supabaseAdmin.from(collection);
|
|
94
94
|
|
|
95
95
|
for (const [field, operator, value] of where) {
|