@donotdev/functions 0.1.0 → 0.1.42
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/LICENSE.md +21 -242
- package/README.md +4 -4
- package/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +286 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
- package/lib/firebase/baseFunction.d.ts +0 -0
- package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
- package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +0 -0
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/firebase/billing/webhookHandler.d.ts +0 -0
- package/lib/firebase/config/constants.d.ts +0 -0
- package/lib/firebase/config/index.d.ts +0 -0
- package/lib/firebase/config/secrets.d.ts +0 -0
- package/lib/firebase/crud/aggregate.d.ts +0 -0
- package/lib/firebase/crud/bulk.d.ts +107 -0
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +0 -0
- package/lib/firebase/crud/get.d.ts +0 -0
- package/lib/firebase/crud/index.d.ts +1 -0
- package/lib/firebase/crud/list.d.ts +0 -0
- package/lib/firebase/crud/update.d.ts +0 -0
- package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/index.d.ts +0 -0
- package/lib/firebase/index.d.ts +0 -0
- package/lib/firebase/index.js +3 -3
- 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 +0 -0
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +0 -0
- package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
- package/lib/firebase/scheduled/index.d.ts +0 -0
- package/lib/shared/ai/classifyAIError.d.ts +35 -0
- package/lib/shared/ai/costTracker.d.ts +20 -0
- package/lib/shared/ai/createAIHandler.d.ts +39 -0
- package/lib/shared/ai/createAIRoute.d.ts +20 -0
- package/lib/shared/ai/index.d.ts +6 -0
- package/lib/shared/ai/providers/anthropic.d.ts +12 -0
- package/lib/shared/ai/providers/google.d.ts +10 -0
- package/lib/shared/ai/providers/index.d.ts +23 -0
- package/lib/shared/ai/providers/openai.d.ts +10 -0
- package/lib/shared/ai/resolveModelTier.d.ts +14 -0
- package/lib/shared/ai/utils/parseSSE.d.ts +22 -0
- package/lib/shared/billing/createCheckout.d.ts +8 -2
- package/lib/shared/billing/helpers/index.d.ts +0 -0
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
- package/lib/shared/billing/idempotency.d.ts +0 -0
- package/lib/shared/billing/index.d.ts +0 -0
- package/lib/shared/billing/webhookHandler.d.ts +0 -0
- package/lib/shared/crud/bulkCore.d.ts +211 -0
- package/lib/shared/crud/index.d.ts +13 -0
- package/lib/shared/email/createEmailRoute.d.ts +30 -0
- package/lib/shared/email/index.d.ts +3 -0
- package/lib/shared/email/provider.d.ts +30 -0
- package/lib/shared/email/resendProvider.d.ts +22 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +5 -0
- package/lib/shared/index.d.ts +3 -0
- package/lib/shared/index.js +4 -3
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +2 -0
- package/lib/shared/metadata.d.ts +6 -6
- package/lib/shared/oauth/exchangeToken.d.ts +1 -0
- package/lib/shared/oauth/grantAccess.d.ts +1 -0
- package/lib/shared/oauth/index.d.ts +0 -0
- package/lib/shared/schema.d.ts +0 -0
- package/lib/shared/utils/detectFirestore.d.ts +0 -0
- package/lib/shared/utils/external/date.d.ts +0 -0
- package/lib/shared/utils/external/index.d.ts +0 -0
- package/lib/shared/utils/external/references.d.ts +0 -0
- package/lib/shared/utils/external/subscription.d.ts +0 -0
- package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
- package/lib/shared/utils/functionWrapper.d.ts +0 -0
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +0 -0
- package/lib/shared/utils/internal/firebase.d.ts +0 -0
- package/lib/shared/utils/internal/idempotency.d.ts +1 -0
- package/lib/shared/utils/internal/index.d.ts +0 -0
- package/lib/shared/utils/internal/monitoring.d.ts +0 -0
- package/lib/shared/utils/internal/rateLimiter.d.ts +0 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -0
- package/lib/shared/utils/schemaValidation.d.ts +0 -0
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +0 -0
- package/lib/shared/utils.d.ts +0 -0
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +30 -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 +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/baseFunction.d.ts +0 -0
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +1 -1
- package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/supabase/crud/aggregate.d.ts +1 -0
- package/lib/supabase/crud/bulk.d.ts +63 -0
- package/lib/supabase/crud/create.d.ts +2 -1
- package/lib/supabase/crud/delete.d.ts +1 -0
- package/lib/supabase/crud/get.d.ts +1 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/crud/list.d.ts +1 -0
- package/lib/supabase/crud/update.d.ts +1 -0
- package/lib/supabase/edgeFunction.d.ts +56 -0
- package/lib/supabase/email/createEmailFunction.d.ts +31 -0
- package/lib/supabase/helpers/authProvider.d.ts +0 -0
- package/lib/supabase/index.d.ts +8 -0
- package/lib/supabase/index.js +3 -2
- 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 +0 -0
- package/lib/vercel/api/ai/chat.d.ts +29 -0
- package/lib/vercel/api/ai/index.d.ts +1 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
- package/lib/vercel/api/billing/cancel.d.ts +0 -0
- package/lib/vercel/api/billing/change-plan.d.ts +0 -0
- package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
- package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
- package/lib/vercel/api/billing/index.d.ts +0 -0
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
- package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/bulk.d.ts +31 -0
- package/lib/vercel/api/crud/create.d.ts +0 -0
- package/lib/vercel/api/crud/delete.d.ts +0 -0
- package/lib/vercel/api/crud/get.d.ts +0 -0
- package/lib/vercel/api/crud/index.d.ts +1 -0
- package/lib/vercel/api/crud/list.d.ts +0 -0
- package/lib/vercel/api/crud/update.d.ts +0 -0
- package/lib/vercel/api/index.d.ts +1 -0
- package/lib/vercel/api/index.js +3 -2
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +0 -0
- package/package.json +40 -7
- package/src/firebase/auth/getCustomClaims.ts +0 -0
- package/src/firebase/auth/getUserAuthStatus.ts +0 -0
- package/src/firebase/auth/index.ts +0 -0
- package/src/firebase/auth/removeCustomClaims.ts +0 -0
- package/src/firebase/auth/setCustomClaims.ts +0 -0
- package/src/firebase/baseFunction.ts +0 -0
- package/src/firebase/billing/cancelSubscription.ts +0 -0
- package/src/firebase/billing/changePlan.ts +0 -0
- package/src/firebase/billing/createCheckoutSession.ts +82 -186
- package/src/firebase/billing/createCustomerPortal.ts +0 -0
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.d.ts +0 -0
- package/src/firebase/billing/index.ts +0 -0
- package/src/firebase/billing/refreshSubscriptionStatus.ts +0 -0
- package/src/firebase/billing/webhookHandler.ts +0 -0
- package/src/firebase/config/constants.ts +0 -0
- package/src/firebase/config/index.ts +0 -0
- package/src/firebase/config/secrets.ts +0 -0
- package/src/firebase/crud/__tests__/bulk.test.ts +322 -0
- package/src/firebase/crud/aggregate.ts +0 -0
- package/src/firebase/crud/bulk.ts +272 -0
- package/src/firebase/crud/create.ts +20 -33
- package/src/firebase/crud/delete.ts +0 -0
- package/src/firebase/crud/get.ts +0 -0
- package/src/firebase/crud/index.ts +1 -0
- package/src/firebase/crud/list.ts +0 -0
- package/src/firebase/crud/update.ts +0 -0
- package/src/firebase/helpers/githubAccessHelper.ts +0 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +0 -0
- package/src/firebase/helpers/index.ts +0 -0
- package/src/firebase/index.d.ts +0 -0
- package/src/firebase/index.ts +0 -0
- package/src/firebase/oauth/disconnect.ts +0 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -4
- package/src/firebase/oauth/getConnections.ts +0 -0
- package/src/firebase/oauth/githubAccess.ts +0 -0
- package/src/firebase/oauth/index.ts +0 -0
- package/src/firebase/oauth/refreshToken.ts +4 -4
- package/src/firebase/registerCrudFunctions.ts +13 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +0 -0
- package/src/firebase/scheduled/index.ts +0 -0
- package/src/shared/__tests__/auth.test.ts +0 -0
- package/src/shared/__tests__/bulkCore.test.ts +487 -0
- package/src/shared/__tests__/errorHandling.test.ts +0 -0
- package/src/shared/__tests__/firebase.test.ts +9 -3
- package/src/shared/__tests__/idempotency.test.ts +0 -0
- package/src/shared/__tests__/internalValidation.test.ts +9 -3
- package/src/shared/__tests__/metadata.test.ts +10 -10
- package/src/shared/__tests__/rateLimiter.test.ts +0 -0
- package/src/shared/__tests__/schema.test.ts +0 -0
- package/src/shared/__tests__/schemaValidation.test.ts +0 -0
- package/src/shared/__tests__/subscription.test.ts +0 -0
- package/src/shared/__tests__/utils.test.ts +10 -4
- package/src/shared/__tests__/validation-env.test.ts +9 -3
- package/src/shared/__tests__/validation.test.ts +0 -0
- package/src/shared/ai/__tests__/costTracker.test.ts +133 -0
- package/src/shared/ai/classifyAIError.ts +178 -0
- package/src/shared/ai/costTracker.ts +51 -0
- package/src/shared/ai/createAIRoute.ts +400 -0
- package/src/shared/ai/index.ts +8 -0
- package/src/shared/ai/resolveModelTier.ts +61 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +0 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +0 -0
- package/src/shared/billing/createCheckout.ts +168 -8
- package/src/shared/billing/helpers/index.ts +0 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
- package/src/shared/billing/helpers/updateUserSubscription.ts +0 -0
- package/src/shared/billing/idempotency.ts +5 -0
- package/src/shared/billing/index.ts +0 -0
- package/src/shared/billing/webhookHandler.ts +0 -0
- package/src/shared/crud/bulkCore.ts +483 -0
- package/src/shared/crud/index.ts +23 -0
- package/src/shared/email/createEmailRoute.ts +81 -0
- package/src/shared/email/index.ts +5 -0
- package/src/shared/email/provider.ts +31 -0
- package/src/shared/email/resendProvider.ts +56 -0
- package/src/shared/errorHandling.ts +10 -4
- package/src/shared/firebase.ts +0 -0
- package/src/shared/github.ts +38 -0
- package/src/shared/index.d.ts +9 -0
- package/src/shared/index.ts +3 -0
- package/src/shared/logger.ts +2 -0
- package/src/shared/metadata.ts +6 -6
- package/src/shared/oauth/__tests__/exchangeToken.test.ts +0 -0
- package/src/shared/oauth/__tests__/grantAccess.test.ts +0 -0
- package/src/shared/oauth/exchangeToken.ts +1 -0
- package/src/shared/oauth/grantAccess.ts +1 -0
- package/src/shared/oauth/index.ts +0 -0
- package/src/shared/schema.ts +0 -0
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -0
- package/src/shared/utils/detectFirestore.ts +0 -0
- package/src/shared/utils/external/date.ts +0 -0
- package/src/shared/utils/external/index.ts +0 -0
- package/src/shared/utils/external/references.ts +0 -0
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +0 -0
- package/src/shared/utils/functionWrapper.ts +0 -0
- package/src/shared/utils/index.ts +0 -0
- package/src/shared/utils/internal/auth.ts +0 -0
- package/src/shared/utils/internal/firebase.ts +0 -0
- package/src/shared/utils/internal/idempotency.ts +1 -0
- package/src/shared/utils/internal/index.ts +0 -0
- package/src/shared/utils/internal/monitoring.ts +0 -0
- package/src/shared/utils/internal/rateLimiter.ts +6 -3
- package/src/shared/utils/internal/validation.ts +0 -0
- package/src/shared/utils/schemaValidation.ts +0 -0
- package/src/shared/utils/validation.ts +0 -0
- package/src/shared/utils/vercelHelpers.ts +0 -0
- package/src/shared/utils.ts +0 -0
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +330 -0
- package/src/supabase/ai/createAIFunction.ts +76 -0
- package/src/supabase/auth/deleteAccount.ts +0 -0
- package/src/supabase/auth/getCustomClaims.ts +0 -0
- package/src/supabase/auth/getUserAuthStatus.ts +0 -0
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +64 -5
- package/src/supabase/baseFunction.ts +26 -2
- package/src/supabase/billing/cancelSubscription.ts +0 -0
- package/src/supabase/billing/changePlan.ts +6 -1
- package/src/supabase/billing/createCheckoutSession.ts +16 -2
- package/src/supabase/billing/createCustomerPortal.ts +0 -0
- package/src/supabase/billing/refreshSubscriptionStatus.ts +0 -0
- package/src/supabase/crud/aggregate.ts +1 -0
- package/src/supabase/crud/bulk.ts +244 -0
- package/src/supabase/crud/create.ts +16 -14
- package/src/supabase/crud/delete.ts +1 -0
- package/src/supabase/crud/get.ts +1 -0
- package/src/supabase/crud/index.ts +2 -0
- package/src/supabase/crud/list.ts +1 -0
- package/src/supabase/crud/update.ts +1 -0
- package/src/supabase/edgeFunction.ts +196 -0
- package/src/supabase/email/createEmailFunction.ts +72 -0
- package/src/supabase/helpers/authProvider.ts +0 -0
- package/src/supabase/index.ts +21 -0
- package/src/supabase/oauth/disconnect.ts +1 -2
- package/src/supabase/oauth/exchangeToken.ts +39 -10
- package/src/supabase/oauth/getConnections.ts +1 -4
- package/src/supabase/oauth/index.ts +0 -0
- package/src/supabase/oauth/refreshToken.ts +6 -12
- package/src/supabase/registerCrudFunctions.ts +20 -20
- package/src/supabase/utils/idempotency.ts +6 -2
- package/src/supabase/utils/monitoring.ts +0 -0
- package/src/supabase/utils/rateLimiter.ts +0 -0
- package/src/vercel/__tests__/bulk.test.ts +301 -0
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +3 -0
- package/src/vercel/api/auth/get-custom-claims.ts +0 -0
- package/src/vercel/api/auth/get-user-auth-status.ts +0 -0
- package/src/vercel/api/auth/index.ts +0 -0
- package/src/vercel/api/auth/remove-custom-claims.ts +0 -0
- package/src/vercel/api/auth/set-custom-claims.ts +0 -0
- package/src/vercel/api/billing/cancel.ts +0 -0
- package/src/vercel/api/billing/change-plan.ts +0 -0
- package/src/vercel/api/billing/create-checkout-session.ts +31 -4
- package/src/vercel/api/billing/customer-portal.ts +0 -0
- package/src/vercel/api/billing/index.ts +0 -0
- package/src/vercel/api/billing/refresh-subscription-status.ts +0 -0
- package/src/vercel/api/billing/webhook-handler.ts +8 -1
- package/src/vercel/api/config/constants.ts +0 -0
- package/src/vercel/api/config/firebase-admin.ts +0 -0
- package/src/vercel/api/config/index.ts +0 -0
- package/src/vercel/api/crud/bulk.ts +216 -0
- package/src/vercel/api/crud/create.ts +10 -9
- package/src/vercel/api/crud/delete.ts +0 -0
- package/src/vercel/api/crud/get.ts +0 -0
- package/src/vercel/api/crud/index.ts +1 -0
- package/src/vercel/api/crud/list.ts +0 -0
- package/src/vercel/api/crud/update.ts +0 -0
- package/src/vercel/api/index.d.ts +0 -0
- package/src/vercel/api/index.ts +1 -0
- package/src/vercel/api/oauth/check-github-access.ts +0 -0
- package/src/vercel/api/oauth/exchange-token.ts +27 -1
- package/src/vercel/api/oauth/grant-github-access.ts +0 -0
- package/src/vercel/api/oauth/index.ts +0 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +0 -0
- package/src/vercel/api/utils/cors.ts +8 -0
- package/src/vercel/baseFunction.ts +0 -0
|
@@ -67,8 +67,7 @@ export function createDisconnect() {
|
|
|
67
67
|
// Revoke token if possible
|
|
68
68
|
if (connection?.credentials?.accessToken) {
|
|
69
69
|
const endpoints = OAUTH_PARTNERS[provider];
|
|
70
|
-
const revokeUrl =
|
|
71
|
-
'revokeUrl' in endpoints ? endpoints.revokeUrl : null;
|
|
70
|
+
const revokeUrl = 'revokeUrl' in endpoints ? endpoints.revokeUrl : null;
|
|
72
71
|
if (revokeUrl) {
|
|
73
72
|
try {
|
|
74
73
|
await fetch(revokeUrl.toString(), {
|
|
@@ -14,6 +14,7 @@ import * as v from 'valibot';
|
|
|
14
14
|
import {
|
|
15
15
|
OAUTH_PARTNERS,
|
|
16
16
|
exchangeTokenSchema,
|
|
17
|
+
sanitizeHref,
|
|
17
18
|
type ExchangeTokenRequest,
|
|
18
19
|
type OAuthPartnerId,
|
|
19
20
|
} from '@donotdev/core/server';
|
|
@@ -21,11 +22,33 @@ import {
|
|
|
21
22
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
22
23
|
import type { SupabaseHandlerContext } from '../baseFunction.js';
|
|
23
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Sanitize profile data from external OAuth providers.
|
|
27
|
+
* Strips HTML tags and limits string length to prevent stored XSS.
|
|
28
|
+
*/
|
|
29
|
+
function sanitizeProfileData(
|
|
30
|
+
data: Record<string, unknown>
|
|
31
|
+
): Record<string, unknown> {
|
|
32
|
+
const result: Record<string, unknown> = {};
|
|
33
|
+
for (const [key, value] of Object.entries(data)) {
|
|
34
|
+
if (typeof value === 'string') {
|
|
35
|
+
result[key] = value.replace(/<[^>]*>/g, '').slice(0, 1000);
|
|
36
|
+
} else if (
|
|
37
|
+
typeof value === 'object' &&
|
|
38
|
+
value !== null &&
|
|
39
|
+
!Array.isArray(value)
|
|
40
|
+
) {
|
|
41
|
+
result[key] = sanitizeProfileData(value as Record<string, unknown>);
|
|
42
|
+
} else {
|
|
43
|
+
result[key] = value;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
|
|
24
49
|
/** Cross-runtime env var access (Deno Edge Functions + Node tests) */
|
|
25
50
|
function getEnv(key: string): string | undefined {
|
|
26
|
-
return typeof Deno !== 'undefined'
|
|
27
|
-
? Deno.env.get(key)
|
|
28
|
-
: process.env[key];
|
|
51
|
+
return typeof Deno !== 'undefined' ? Deno.env.get(key) : process.env[key];
|
|
29
52
|
}
|
|
30
53
|
|
|
31
54
|
declare const Deno:
|
|
@@ -51,17 +74,21 @@ export function createExchangeToken() {
|
|
|
51
74
|
async (data: ExchangeTokenRequest, ctx: SupabaseHandlerContext) => {
|
|
52
75
|
const { provider, purpose, code, redirectUri, codeVerifier } = data;
|
|
53
76
|
|
|
77
|
+
// Validate redirectUri scheme (defense-in-depth over Valibot v.url())
|
|
78
|
+
if (!sanitizeHref(redirectUri)) {
|
|
79
|
+
throw new Error('Invalid redirect URI scheme');
|
|
80
|
+
}
|
|
81
|
+
|
|
54
82
|
// Get provider endpoints
|
|
55
83
|
const endpoints = OAUTH_PARTNERS[provider];
|
|
56
84
|
if (!endpoints?.endpoints?.tokenUrl) {
|
|
57
85
|
throw new Error(`Provider ${provider} is not supported`);
|
|
58
86
|
}
|
|
59
87
|
|
|
60
|
-
// Get client credentials from env
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
const clientSecret =
|
|
64
|
-
getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_SECRET`);
|
|
88
|
+
// Get client credentials from env: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
|
|
89
|
+
const upper = provider.toUpperCase();
|
|
90
|
+
const clientId = getEnv(`${upper}_CLIENT_ID`);
|
|
91
|
+
const clientSecret = getEnv(`${upper}_CLIENT_SECRET`);
|
|
65
92
|
|
|
66
93
|
if (!clientId || !clientSecret) {
|
|
67
94
|
throw new Error(`Provider ${provider} is not configured`);
|
|
@@ -109,7 +136,7 @@ export function createExchangeToken() {
|
|
|
109
136
|
};
|
|
110
137
|
|
|
111
138
|
// Get user profile
|
|
112
|
-
let profile = null;
|
|
139
|
+
let profile: Record<string, unknown> | null = null;
|
|
113
140
|
if (credentials.accessToken && endpoints.endpoints.profileUrl) {
|
|
114
141
|
try {
|
|
115
142
|
const profileResponse = await fetch(endpoints.endpoints.profileUrl, {
|
|
@@ -119,7 +146,9 @@ export function createExchangeToken() {
|
|
|
119
146
|
},
|
|
120
147
|
});
|
|
121
148
|
if (profileResponse.ok) {
|
|
122
|
-
|
|
149
|
+
const rawProfile = await profileResponse.json();
|
|
150
|
+
// Sanitize profile data from external provider (prevent stored XSS)
|
|
151
|
+
profile = sanitizeProfileData(rawProfile);
|
|
123
152
|
}
|
|
124
153
|
} catch (e) {
|
|
125
154
|
console.warn(`Failed to fetch profile for ${provider}:`, e);
|
|
@@ -42,10 +42,7 @@ export function createGetConnections() {
|
|
|
42
42
|
return createSupabaseHandler(
|
|
43
43
|
'get-connections',
|
|
44
44
|
getConnectionsSchema,
|
|
45
|
-
async (
|
|
46
|
-
data: { purpose?: OAuthPurpose },
|
|
47
|
-
ctx: SupabaseHandlerContext
|
|
48
|
-
) => {
|
|
45
|
+
async (data: { purpose?: OAuthPurpose }, ctx: SupabaseHandlerContext) => {
|
|
49
46
|
let query = ctx.supabaseAdmin
|
|
50
47
|
.from('oauth_connections')
|
|
51
48
|
.select('*')
|
|
File without changes
|
|
@@ -21,9 +21,7 @@ import type { SupabaseHandlerContext } from '../baseFunction.js';
|
|
|
21
21
|
|
|
22
22
|
/** Cross-runtime env var access (Deno Edge Functions + Node tests) */
|
|
23
23
|
function getEnv(key: string): string | undefined {
|
|
24
|
-
return typeof Deno !== 'undefined'
|
|
25
|
-
? Deno.env.get(key)
|
|
26
|
-
: process.env[key];
|
|
24
|
+
return typeof Deno !== 'undefined' ? Deno.env.get(key) : process.env[key];
|
|
27
25
|
}
|
|
28
26
|
|
|
29
27
|
declare const Deno:
|
|
@@ -36,10 +34,7 @@ const refreshTokenSchema = v.object({
|
|
|
36
34
|
OAuthRefreshRequest['provider'],
|
|
37
35
|
v.BaseIssue<unknown>
|
|
38
36
|
>,
|
|
39
|
-
refreshToken: v.pipe(
|
|
40
|
-
v.string(),
|
|
41
|
-
v.minLength(1, 'Refresh token is required')
|
|
42
|
-
),
|
|
37
|
+
refreshToken: v.pipe(v.string(), v.minLength(1, 'Refresh token is required')),
|
|
43
38
|
redirectUri: v.pipe(v.string(), v.url('Valid redirect URI is required')),
|
|
44
39
|
});
|
|
45
40
|
|
|
@@ -68,11 +63,10 @@ export function createRefreshToken() {
|
|
|
68
63
|
throw new Error(`Provider ${provider} does not support token refresh`);
|
|
69
64
|
}
|
|
70
65
|
|
|
71
|
-
// Get client credentials
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
const clientSecret =
|
|
75
|
-
getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_SECRET`);
|
|
66
|
+
// Get client credentials: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
|
|
67
|
+
const upper = provider.toUpperCase();
|
|
68
|
+
const clientId = getEnv(`${upper}_CLIENT_ID`);
|
|
69
|
+
const clientSecret = getEnv(`${upper}_CLIENT_SECRET`);
|
|
76
70
|
|
|
77
71
|
if (!clientId || !clientSecret) {
|
|
78
72
|
throw new Error(`Provider ${provider} is not configured`);
|
|
@@ -19,7 +19,9 @@ import {
|
|
|
19
19
|
createSupabaseDeleteEntity,
|
|
20
20
|
createSupabaseListEntities,
|
|
21
21
|
createSupabaseAggregateEntities,
|
|
22
|
+
createSupabaseBulkEntity,
|
|
22
23
|
} from './crud/index.js';
|
|
24
|
+
import { createEdgeFunction } from './edgeFunction.js';
|
|
23
25
|
|
|
24
26
|
type SupabaseHandler = (req: Request) => Promise<Response>;
|
|
25
27
|
|
|
@@ -60,6 +62,7 @@ export function createSupabaseCrudFunctions(
|
|
|
60
62
|
handlers[`create_${col}`] = createSupabaseCreateEntity(
|
|
61
63
|
col,
|
|
62
64
|
schemas.create,
|
|
65
|
+
schemas.draft,
|
|
63
66
|
access.create
|
|
64
67
|
);
|
|
65
68
|
handlers[`get_${col}`] = createSupabaseGetEntity(
|
|
@@ -119,30 +122,33 @@ export function createSupabaseCrudFunctions(
|
|
|
119
122
|
schemas.get,
|
|
120
123
|
access.read
|
|
121
124
|
);
|
|
125
|
+
handlers[`bulk_${col}`] = createSupabaseBulkEntity(
|
|
126
|
+
col,
|
|
127
|
+
schemas.create,
|
|
128
|
+
schemas.draft,
|
|
129
|
+
schemas.update,
|
|
130
|
+
access
|
|
131
|
+
);
|
|
122
132
|
}
|
|
123
133
|
|
|
124
134
|
/**
|
|
125
|
-
* Serve dispatcher:
|
|
135
|
+
* Serve dispatcher: CORS via createEdgeFunction, then routes by _functionName.
|
|
136
|
+
* Auth is NOT checked here (requireAuth: false) — individual handlers
|
|
137
|
+
* use createSupabaseHandler which enforces auth + RBAC per operation.
|
|
126
138
|
*/
|
|
127
|
-
const serve =
|
|
128
|
-
|
|
139
|
+
const serve = createEdgeFunction(
|
|
140
|
+
async (req, ctx) => {
|
|
129
141
|
const body = await req.json().catch(() => ({}));
|
|
130
142
|
const functionName = (body as Record<string, unknown>)
|
|
131
143
|
._functionName as string;
|
|
132
144
|
|
|
133
145
|
if (!functionName) {
|
|
134
|
-
return
|
|
135
|
-
JSON.stringify({ error: 'Missing _functionName in request body' }),
|
|
136
|
-
{ status: 400, headers: { 'Content-Type': 'application/json' } }
|
|
137
|
-
);
|
|
146
|
+
return ctx.error('Missing _functionName in request body', 400);
|
|
138
147
|
}
|
|
139
148
|
|
|
140
149
|
const handler = handlers[functionName];
|
|
141
150
|
if (!handler) {
|
|
142
|
-
return
|
|
143
|
-
JSON.stringify({ error: `Unknown function: ${functionName}` }),
|
|
144
|
-
{ status: 404, headers: { 'Content-Type': 'application/json' } }
|
|
145
|
-
);
|
|
151
|
+
return ctx.error(`Unknown function: ${functionName}`, 404);
|
|
146
152
|
}
|
|
147
153
|
|
|
148
154
|
// Remove _functionName from body before passing to handler
|
|
@@ -156,15 +162,9 @@ export function createSupabaseCrudFunctions(
|
|
|
156
162
|
});
|
|
157
163
|
|
|
158
164
|
return handler(handlerReq);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
163
|
-
status: 500,
|
|
164
|
-
headers: { 'Content-Type': 'application/json' },
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
};
|
|
165
|
+
},
|
|
166
|
+
{ requireAuth: false }
|
|
167
|
+
);
|
|
168
168
|
|
|
169
169
|
return { handlers, serve };
|
|
170
170
|
}
|
|
@@ -56,9 +56,13 @@ export async function checkIdempotency<T>(
|
|
|
56
56
|
|
|
57
57
|
return data.result as T;
|
|
58
58
|
} catch (error) {
|
|
59
|
-
// Fail
|
|
59
|
+
// Fail closed — in billing context, allowing a duplicate operation is worse
|
|
60
|
+
// than rejecting a legitimate retry. Throw so the caller surfaces an error
|
|
61
|
+
// rather than silently double-processing a payment.
|
|
60
62
|
console.error('[idempotency] Check failed:', error);
|
|
61
|
-
|
|
63
|
+
throw new Error(
|
|
64
|
+
'[idempotency] Unable to verify idempotency. Operation rejected to prevent potential duplicate processing.'
|
|
65
|
+
);
|
|
62
66
|
}
|
|
63
67
|
}
|
|
64
68
|
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
// packages/functions/src/vercel/__tests__/bulk.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Tests for the Vercel bulk CRUD API handler.
|
|
5
|
+
* @description Unit tests for `POST /api/crud/:collection/bulk`. The Firebase
|
|
6
|
+
* Admin SDK is mocked — these tests exercise the handler's wire contract:
|
|
7
|
+
* parsing, collision rejection, transactional atomicity, method guard, and
|
|
8
|
+
* response shape.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
12
|
+
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
// Mocks — must be declared before importing the handler.
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
// Auth: resolve to a fixed uid for all tests.
|
|
18
|
+
vi.mock('../../shared/utils/internal/auth.js', () => ({
|
|
19
|
+
verifyAuthToken: vi.fn(() => Promise.resolve('user-1')),
|
|
20
|
+
}));
|
|
21
|
+
|
|
22
|
+
// Collection-name validator: accept everything in tests.
|
|
23
|
+
vi.mock('../../shared/utils.js', () => ({
|
|
24
|
+
validateCollectionName: vi.fn(),
|
|
25
|
+
DoNotDevError: class DoNotDevError extends Error {
|
|
26
|
+
code: string;
|
|
27
|
+
details: any;
|
|
28
|
+
constructor(message: string, code = 'internal', opts?: any) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = 'DoNotDevError';
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.details = opts?.details;
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
// Metadata helpers — deterministic output for snapshot-like assertions.
|
|
38
|
+
// `executeBulk` is the real orchestrator so end-to-end behaviour (collision
|
|
39
|
+
// detection, empty short-circuit, transact invocation) exercises the shared
|
|
40
|
+
// core.
|
|
41
|
+
vi.mock('../../shared/index.js', async () => {
|
|
42
|
+
const actual = await vi.importActual<typeof import('../../shared/index.js')>(
|
|
43
|
+
'../../shared/index.js'
|
|
44
|
+
);
|
|
45
|
+
return {
|
|
46
|
+
...actual,
|
|
47
|
+
prepareForFirestore: (obj: Record<string, unknown>) => ({ ...obj }),
|
|
48
|
+
transformFirestoreData: (obj: Record<string, unknown>) => ({ ...obj }),
|
|
49
|
+
createMetadata: (uid: string) => ({
|
|
50
|
+
createdAt: 'now',
|
|
51
|
+
updatedAt: 'now',
|
|
52
|
+
createdById: uid,
|
|
53
|
+
updatedById: uid,
|
|
54
|
+
}),
|
|
55
|
+
updateMetadata: (uid: string) => ({
|
|
56
|
+
updatedAt: 'now',
|
|
57
|
+
updatedById: uid,
|
|
58
|
+
}),
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Firebase Admin SDK — shared spy surface so each test can assert calls.
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
type TxSpy = {
|
|
67
|
+
get: ReturnType<typeof vi.fn>;
|
|
68
|
+
set: ReturnType<typeof vi.fn>;
|
|
69
|
+
update: ReturnType<typeof vi.fn>;
|
|
70
|
+
delete: ReturnType<typeof vi.fn>;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
let txSpy: TxSpy;
|
|
74
|
+
let existingDocIds: Set<string>;
|
|
75
|
+
let mintedIds: string[];
|
|
76
|
+
let mintedIdx: number;
|
|
77
|
+
|
|
78
|
+
vi.mock('@donotdev/firebase/server', () => {
|
|
79
|
+
const doc = (id?: string) => {
|
|
80
|
+
const docId = id ?? mintedIds[mintedIdx++] ?? `auto-${mintedIdx}`;
|
|
81
|
+
return { id: docId, _id: docId };
|
|
82
|
+
};
|
|
83
|
+
const collection = (_name: string) => ({ doc });
|
|
84
|
+
|
|
85
|
+
const runTransaction = vi.fn(async (work: (tx: any) => Promise<any>) => {
|
|
86
|
+
txSpy = {
|
|
87
|
+
get: vi.fn(async (ref: any) => ({
|
|
88
|
+
exists: existingDocIds.has(ref.id),
|
|
89
|
+
id: ref.id,
|
|
90
|
+
data: () => ({}),
|
|
91
|
+
})),
|
|
92
|
+
set: vi.fn(),
|
|
93
|
+
update: vi.fn(),
|
|
94
|
+
delete: vi.fn(),
|
|
95
|
+
};
|
|
96
|
+
return await work(txSpy);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
getFirebaseAdminFirestore: () => ({
|
|
101
|
+
collection,
|
|
102
|
+
runTransaction,
|
|
103
|
+
}),
|
|
104
|
+
};
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// Error handling: keep real `handleError` (throws DoNotDevError-shaped) so the
|
|
108
|
+
// response mapping in the handler runs end-to-end.
|
|
109
|
+
vi.mock('../../shared/errorHandling.js', async () => {
|
|
110
|
+
class DoNotDevError extends Error {
|
|
111
|
+
code: string;
|
|
112
|
+
constructor(message: string, code = 'internal') {
|
|
113
|
+
super(message);
|
|
114
|
+
this.name = 'DoNotDevError';
|
|
115
|
+
this.code = code;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
DoNotDevError,
|
|
120
|
+
handleError: (err: unknown) => {
|
|
121
|
+
if (err instanceof DoNotDevError) throw err;
|
|
122
|
+
if (err instanceof Error && err.name === 'BulkCollisionError') {
|
|
123
|
+
throw new DoNotDevError(err.message, 'invalid-argument');
|
|
124
|
+
}
|
|
125
|
+
if (err instanceof Error && err.name === 'ValiError') {
|
|
126
|
+
throw new DoNotDevError('Validation failed', 'invalid-argument');
|
|
127
|
+
}
|
|
128
|
+
throw new DoNotDevError(
|
|
129
|
+
err instanceof Error ? err.message : 'Internal',
|
|
130
|
+
'internal'
|
|
131
|
+
);
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// ---------------------------------------------------------------------------
|
|
137
|
+
// Import handler AFTER mocks.
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
import handler from '../api/crud/bulk.js';
|
|
141
|
+
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
// Test helpers.
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
function makeRes() {
|
|
147
|
+
const res: any = {};
|
|
148
|
+
res.status = vi.fn((code: number) => {
|
|
149
|
+
res._status = code;
|
|
150
|
+
return res;
|
|
151
|
+
});
|
|
152
|
+
res.json = vi.fn((body: unknown) => {
|
|
153
|
+
res._body = body;
|
|
154
|
+
return res;
|
|
155
|
+
});
|
|
156
|
+
return res;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function makeReq(opts: {
|
|
160
|
+
method?: string;
|
|
161
|
+
collection?: string | string[];
|
|
162
|
+
body?: unknown;
|
|
163
|
+
}) {
|
|
164
|
+
return {
|
|
165
|
+
method: opts.method ?? 'POST',
|
|
166
|
+
query: { collection: opts.collection ?? 'events' },
|
|
167
|
+
body: opts.body,
|
|
168
|
+
headers: { authorization: 'Bearer test' },
|
|
169
|
+
} as any;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
beforeEach(() => {
|
|
173
|
+
existingDocIds = new Set();
|
|
174
|
+
mintedIds = [];
|
|
175
|
+
mintedIdx = 0;
|
|
176
|
+
vi.clearAllMocks();
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Tests.
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
describe('vercel bulk handler — happy path', () => {
|
|
184
|
+
it('runs 2 inserts + 1 update + 1 delete in a single transaction', async () => {
|
|
185
|
+
existingDocIds = new Set(['u1', 'd1']);
|
|
186
|
+
mintedIds = ['new-1', 'new-2'];
|
|
187
|
+
|
|
188
|
+
const req = makeReq({
|
|
189
|
+
body: {
|
|
190
|
+
inserts: [{ title: 'A' }, { title: 'B' }],
|
|
191
|
+
updates: [{ id: 'u1', patch: { title: 'renamed' } }],
|
|
192
|
+
deletes: ['d1'],
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
const res = makeRes();
|
|
196
|
+
|
|
197
|
+
await handler(req, res);
|
|
198
|
+
|
|
199
|
+
expect(res._status).toBe(200);
|
|
200
|
+
expect(res._body).toEqual({
|
|
201
|
+
insertedIds: ['new-1', 'new-2'],
|
|
202
|
+
updatedIds: ['u1'],
|
|
203
|
+
deletedIds: ['d1'],
|
|
204
|
+
});
|
|
205
|
+
// One transaction, N writes inside it.
|
|
206
|
+
expect(txSpy.set).toHaveBeenCalledTimes(2);
|
|
207
|
+
expect(txSpy.update).toHaveBeenCalledTimes(1);
|
|
208
|
+
expect(txSpy.delete).toHaveBeenCalledTimes(1);
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
describe('vercel bulk handler — empty payload', () => {
|
|
213
|
+
it('returns zeroed response without touching the DB', async () => {
|
|
214
|
+
const req = makeReq({ body: {} });
|
|
215
|
+
const res = makeRes();
|
|
216
|
+
|
|
217
|
+
await handler(req, res);
|
|
218
|
+
|
|
219
|
+
expect(res._status).toBe(200);
|
|
220
|
+
expect(res._body).toEqual({
|
|
221
|
+
insertedIds: [],
|
|
222
|
+
updatedIds: [],
|
|
223
|
+
deletedIds: [],
|
|
224
|
+
});
|
|
225
|
+
// No transaction spy created → no DB work.
|
|
226
|
+
expect(txSpy).toBeUndefined();
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
describe('vercel bulk handler — collision rejection', () => {
|
|
231
|
+
it('rejects id present in both updates and deletes', async () => {
|
|
232
|
+
const req = makeReq({
|
|
233
|
+
body: {
|
|
234
|
+
updates: [{ id: 'x', patch: { a: 1 } }],
|
|
235
|
+
deletes: ['x'],
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
const res = makeRes();
|
|
239
|
+
|
|
240
|
+
await handler(req, res);
|
|
241
|
+
|
|
242
|
+
expect(res._status).toBe(400);
|
|
243
|
+
expect((res._body as any).error).toMatch(/BulkCollisionError/);
|
|
244
|
+
expect(txSpy).toBeUndefined();
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
describe('vercel bulk handler — validation failure', () => {
|
|
249
|
+
it('rolls back when an update targets a non-existent doc', async () => {
|
|
250
|
+
// `u1` not in existingDocIds → tx.get returns `exists: false` → throw.
|
|
251
|
+
existingDocIds = new Set();
|
|
252
|
+
mintedIds = ['new-1'];
|
|
253
|
+
|
|
254
|
+
const req = makeReq({
|
|
255
|
+
body: {
|
|
256
|
+
inserts: [{ title: 'A' }],
|
|
257
|
+
updates: [{ id: 'u1', patch: { title: 'x' } }],
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
const res = makeRes();
|
|
261
|
+
|
|
262
|
+
await handler(req, res);
|
|
263
|
+
|
|
264
|
+
expect(res._status).toBe(500);
|
|
265
|
+
// No writes issued — existence check runs before any tx.set/update/delete.
|
|
266
|
+
expect(txSpy.set).not.toHaveBeenCalled();
|
|
267
|
+
expect(txSpy.update).not.toHaveBeenCalled();
|
|
268
|
+
expect(txSpy.delete).not.toHaveBeenCalled();
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it('rejects structurally invalid body (ACL-equivalent schema check)', async () => {
|
|
272
|
+
// `updates[0]` missing required `id` — schema rejects before DB access.
|
|
273
|
+
const req = makeReq({
|
|
274
|
+
body: {
|
|
275
|
+
updates: [{ patch: { title: 'x' } }],
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
const res = makeRes();
|
|
279
|
+
|
|
280
|
+
await handler(req, res);
|
|
281
|
+
|
|
282
|
+
expect(res._status).toBe(400);
|
|
283
|
+
expect(txSpy).toBeUndefined();
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
describe('vercel bulk handler — method guard', () => {
|
|
288
|
+
it('rejects GET with 405', async () => {
|
|
289
|
+
const req = makeReq({ method: 'GET', body: {} });
|
|
290
|
+
const res = makeRes();
|
|
291
|
+
await handler(req, res);
|
|
292
|
+
expect(res._status).toBe(405);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it('rejects PUT with 405', async () => {
|
|
296
|
+
const req = makeReq({ method: 'PUT', body: {} });
|
|
297
|
+
const res = makeRes();
|
|
298
|
+
await handler(req, res);
|
|
299
|
+
expect(res._status).toBe(405);
|
|
300
|
+
});
|
|
301
|
+
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// packages/functions/src/vercel/api/ai/chat.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Chat - Vercel Route Handler
|
|
5
|
+
* @description Next.js App Router route handler for AI chat.
|
|
6
|
+
* Uses Vercel AI SDK via shared handleAIRequest.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { AIRouteConfig } from '@donotdev/core/server';
|
|
14
|
+
import { AIChatRequestSchema } from '@donotdev/core/server';
|
|
15
|
+
import * as v from 'valibot';
|
|
16
|
+
|
|
17
|
+
import { handleAIRequest } from '../../../shared/ai/index.js';
|
|
18
|
+
import { verifyToken } from '../../../shared/utils/internal/auth.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Create a Next.js App Router POST handler for AI chat.
|
|
22
|
+
*
|
|
23
|
+
* @param config - AI route configuration
|
|
24
|
+
* @returns `(req: Request) => Promise<Response>` handler
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```typescript
|
|
28
|
+
* // app/api/ai/chat/route.ts
|
|
29
|
+
* import { createAIChatRoute } from '@donotdev/functions/vercel';
|
|
30
|
+
*
|
|
31
|
+
* export const POST = createAIChatRoute({
|
|
32
|
+
* provider: 'anthropic',
|
|
33
|
+
* model: 'claude-sonnet-4-20250514',
|
|
34
|
+
* cost: { markup: 4.0, monthlyBudgetTokens: 0, showCostToUsers: false, displayCurrency: 'eur' },
|
|
35
|
+
* });
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function createAIChatRoute(config: AIRouteConfig) {
|
|
39
|
+
return async (req: Request): Promise<Response> => {
|
|
40
|
+
// Auth
|
|
41
|
+
const authHeader = req.headers.get('authorization');
|
|
42
|
+
if (!authHeader?.startsWith('Bearer ')) {
|
|
43
|
+
return new Response(
|
|
44
|
+
JSON.stringify({ error: 'Missing authorization header' }),
|
|
45
|
+
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const token = authHeader.slice(7);
|
|
50
|
+
let uid: string;
|
|
51
|
+
try {
|
|
52
|
+
const decoded = await verifyToken(token);
|
|
53
|
+
uid = decoded.uid;
|
|
54
|
+
} catch {
|
|
55
|
+
return new Response(
|
|
56
|
+
JSON.stringify({ error: 'Invalid or expired token' }),
|
|
57
|
+
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Parse + validate body
|
|
62
|
+
const body = await req.json().catch(() => ({}));
|
|
63
|
+
const validation = v.safeParse(AIChatRequestSchema, body);
|
|
64
|
+
if (!validation.success) {
|
|
65
|
+
const issues = validation.issues.map((i) => i.message).join(', ');
|
|
66
|
+
return new Response(
|
|
67
|
+
JSON.stringify({ error: `Validation failed: ${issues}` }),
|
|
68
|
+
{ status: 400, headers: { 'Content-Type': 'application/json' } }
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return handleAIRequest(validation.output, config, {
|
|
73
|
+
userId: uid,
|
|
74
|
+
requestId: crypto.randomUUID(),
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|