@donotdev/functions 0.0.20 → 0.1.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/LICENSE.md +3 -3
- package/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +260 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
- package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
- package/lib/firebase/auth/index.d.ts +1 -1
- package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
- package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
- package/lib/firebase/billing/changePlan.d.ts +1 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/index.d.ts +1 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
- package/lib/firebase/config/constants.d.ts +4 -4
- package/lib/firebase/config/index.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +2 -2
- 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 +1 -1
- package/lib/firebase/crud/update.d.ts +1 -1
- package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
- package/lib/firebase/helpers/index.d.ts +1 -1
- package/lib/firebase/index.d.ts +1 -1
- package/lib/firebase/index.js +3 -3
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +1 -1
- package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
- package/lib/firebase/oauth/getConnections.d.ts +1 -1
- package/lib/firebase/oauth/githubAccess.d.ts +6 -6
- package/lib/firebase/oauth/index.d.ts +1 -1
- package/lib/firebase/oauth/refreshToken.d.ts +1 -1
- package/lib/firebase/scheduled/index.d.ts +1 -1
- package/lib/shared/ai/classifyAIError.d.ts +35 -0
- package/lib/shared/ai/costTracker.d.ts +20 -0
- package/lib/shared/ai/createAIRoute.d.ts +20 -0
- package/lib/shared/ai/index.d.ts +6 -0
- package/lib/shared/ai/resolveModelTier.d.ts +14 -0
- package/lib/shared/billing/createCheckout.d.ts +11 -5
- package/lib/shared/billing/helpers/index.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
- package/lib/shared/billing/idempotency.d.ts +2 -2
- package/lib/shared/billing/index.d.ts +1 -1
- package/lib/shared/billing/webhookHandler.d.ts +1 -1
- 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 +1 -1
- package/lib/shared/firebase.d.ts +7 -7
- package/lib/shared/github.d.ts +16 -11
- package/lib/shared/index.d.ts +3 -1
- package/lib/shared/index.js +4 -3
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +8 -6
- package/lib/shared/metadata.d.ts +3 -3
- package/lib/shared/oauth/exchangeToken.d.ts +3 -2
- package/lib/shared/oauth/grantAccess.d.ts +3 -2
- package/lib/shared/oauth/index.d.ts +1 -1
- package/lib/shared/schema.d.ts +2 -2
- package/lib/shared/utils/detectFirestore.d.ts +3 -3
- package/lib/shared/utils/external/date.d.ts +2 -2
- package/lib/shared/utils/external/index.d.ts +1 -1
- package/lib/shared/utils/external/references.d.ts +1 -1
- package/lib/shared/utils/external/subscription.d.ts +5 -5
- package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
- package/lib/shared/utils/functionWrapper.d.ts +4 -4
- package/lib/shared/utils/index.d.ts +1 -1
- package/lib/shared/utils/internal/auth.d.ts +4 -4
- package/lib/shared/utils/internal/idempotency.d.ts +3 -2
- package/lib/shared/utils/internal/index.d.ts +1 -1
- package/lib/shared/utils/internal/monitoring.d.ts +7 -7
- package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
- package/lib/shared/utils/internal/validation.d.ts +4 -4
- package/lib/shared/utils/schemaValidation.d.ts +6 -6
- package/lib/shared/utils/validation.d.ts +9 -9
- package/lib/shared/utils/vercelHelpers.d.ts +2 -2
- package/lib/shared/utils.d.ts +19 -19
- package/lib/shared/validation.d.ts +2 -2
- package/lib/supabase/ai/createAIFunction.d.ts +30 -0
- package/lib/supabase/auth/deleteAccount.d.ts +1 -1
- package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/baseFunction.d.ts +2 -2
- package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
- package/lib/supabase/billing/changePlan.d.ts +2 -2
- package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
- package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
- package/lib/supabase/crud/aggregate.d.ts +2 -1
- 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 +2 -1
- package/lib/supabase/crud/index.d.ts +1 -1
- package/lib/supabase/crud/list.d.ts +2 -1
- package/lib/supabase/crud/update.d.ts +2 -1
- package/lib/supabase/edgeFunction.d.ts +56 -0
- package/lib/supabase/email/createEmailFunction.d.ts +31 -0
- package/lib/supabase/helpers/authProvider.d.ts +2 -2
- package/lib/supabase/index.d.ts +11 -2
- package/lib/supabase/index.js +3 -2
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/oauth/disconnect.d.ts +13 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
- package/lib/supabase/oauth/getConnections.d.ts +13 -0
- package/lib/supabase/oauth/index.d.ts +12 -0
- package/lib/supabase/oauth/refreshToken.d.ts +13 -0
- package/lib/supabase/utils/idempotency.d.ts +1 -1
- package/lib/supabase/utils/monitoring.d.ts +1 -1
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- 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/index.d.ts +1 -1
- package/lib/vercel/api/billing/cancel.d.ts +1 -1
- package/lib/vercel/api/billing/change-plan.d.ts +1 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
- package/lib/vercel/api/billing/index.d.ts +1 -1
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
- package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
- package/lib/vercel/api/config/constants.d.ts +9 -9
- package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
- package/lib/vercel/api/config/index.d.ts +1 -1
- package/lib/vercel/api/crud/index.d.ts +1 -1
- package/lib/vercel/api/index.d.ts +2 -1
- 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 +1 -1
- package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
- package/lib/vercel/api/oauth/index.d.ts +1 -1
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/api/utils/cors.d.ts +4 -4
- package/lib/vercel/baseFunction.d.ts +2 -2
- package/package.json +38 -5
- package/src/firebase/auth/getCustomClaims.ts +3 -3
- package/src/firebase/auth/getUserAuthStatus.ts +3 -3
- package/src/firebase/auth/index.ts +1 -1
- package/src/firebase/auth/removeCustomClaims.ts +3 -3
- package/src/firebase/auth/setCustomClaims.ts +70 -69
- package/src/firebase/baseFunction.ts +2 -2
- package/src/firebase/billing/cancelSubscription.ts +3 -3
- package/src/firebase/billing/changePlan.ts +3 -3
- package/src/firebase/billing/createCheckoutSession.ts +79 -187
- package/src/firebase/billing/createCustomerPortal.ts +1 -1
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/index.d.ts +11 -11
- package/src/firebase/billing/index.ts +1 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
- package/src/firebase/billing/webhookHandler.ts +1 -1
- package/src/firebase/config/constants.ts +4 -4
- package/src/firebase/config/index.ts +1 -1
- package/src/firebase/config/secrets.ts +1 -1
- package/src/firebase/crud/aggregate.ts +2 -2
- package/src/firebase/crud/create.ts +2 -2
- package/src/firebase/crud/delete.ts +3 -3
- package/src/firebase/crud/get.ts +1 -1
- package/src/firebase/crud/index.ts +1 -1
- package/src/firebase/crud/list.ts +1 -1
- package/src/firebase/crud/update.ts +2 -2
- package/src/firebase/helpers/githubAccessHelper.ts +4 -4
- package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
- package/src/firebase/helpers/index.ts +1 -1
- package/src/firebase/index.d.ts +9 -9
- package/src/firebase/index.ts +1 -1
- package/src/firebase/oauth/disconnect.ts +2 -2
- package/src/firebase/oauth/exchangeToken.ts +6 -6
- package/src/firebase/oauth/getConnections.ts +2 -2
- package/src/firebase/oauth/githubAccess.ts +10 -10
- package/src/firebase/oauth/index.ts +1 -1
- package/src/firebase/oauth/refreshToken.ts +6 -6
- package/src/firebase/registerCrudFunctions.ts +1 -1
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
- package/src/firebase/scheduled/index.ts +1 -1
- package/src/shared/__tests__/auth.test.ts +46 -0
- package/src/shared/__tests__/errorHandling.test.ts +66 -1
- package/src/shared/__tests__/firebase.test.ts +293 -0
- package/src/shared/__tests__/internalValidation.test.ts +190 -0
- package/src/shared/__tests__/metadata.test.ts +66 -0
- package/src/shared/__tests__/schema.test.ts +219 -0
- package/src/shared/__tests__/schemaValidation.test.ts +72 -0
- package/src/shared/__tests__/subscription.test.ts +45 -0
- package/src/shared/__tests__/utils.test.ts +281 -0
- package/src/shared/__tests__/validation-env.test.ts +73 -0
- package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
- package/src/shared/ai/classifyAIError.ts +163 -0
- package/src/shared/ai/costTracker.ts +51 -0
- package/src/shared/ai/createAIRoute.ts +397 -0
- package/src/shared/ai/index.ts +8 -0
- package/src/shared/ai/resolveModelTier.ts +58 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
- package/src/shared/billing/createCheckout.ts +156 -11
- package/src/shared/billing/helpers/index.ts +1 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +13 -4
- package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
- package/src/shared/billing/idempotency.ts +9 -4
- package/src/shared/billing/index.ts +1 -1
- package/src/shared/billing/webhookHandler.ts +7 -7
- 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 +12 -6
- package/src/shared/firebase.ts +7 -7
- package/src/shared/github.ts +49 -11
- package/src/shared/index.d.ts +9 -9
- package/src/shared/index.ts +3 -1
- package/src/shared/logger.ts +10 -8
- package/src/shared/metadata.ts +3 -3
- package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
- package/src/shared/oauth/exchangeToken.ts +3 -2
- package/src/shared/oauth/grantAccess.ts +3 -2
- package/src/shared/oauth/index.ts +1 -1
- package/src/shared/schema.ts +4 -4
- package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
- package/src/shared/utils/detectFirestore.ts +3 -3
- package/src/shared/utils/external/date.ts +5 -5
- package/src/shared/utils/external/index.ts +1 -1
- package/src/shared/utils/external/references.ts +2 -2
- package/src/shared/utils/external/subscription.ts +5 -5
- package/src/shared/utils/firebaseHelpers.ts +3 -3
- package/src/shared/utils/functionWrapper.ts +4 -4
- package/src/shared/utils/index.ts +1 -1
- package/src/shared/utils/internal/auth.ts +7 -7
- package/src/shared/utils/internal/firebase.ts +1 -1
- package/src/shared/utils/internal/idempotency.ts +4 -3
- package/src/shared/utils/internal/index.ts +1 -1
- package/src/shared/utils/internal/monitoring.ts +8 -8
- package/src/shared/utils/internal/rateLimiter.ts +12 -9
- package/src/shared/utils/internal/validation.ts +5 -5
- package/src/shared/utils/schemaValidation.ts +6 -6
- package/src/shared/utils/validation.ts +10 -10
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +19 -19
- package/src/shared/validation.ts +3 -3
- package/src/supabase/ai/createAIFunction.ts +75 -0
- package/src/supabase/auth/deleteAccount.ts +2 -2
- package/src/supabase/auth/getCustomClaims.ts +2 -2
- package/src/supabase/auth/getUserAuthStatus.ts +2 -2
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +66 -5
- package/src/supabase/baseFunction.ts +29 -5
- package/src/supabase/billing/cancelSubscription.ts +2 -2
- package/src/supabase/billing/changePlan.ts +8 -3
- package/src/supabase/billing/createCheckoutSession.ts +18 -4
- package/src/supabase/billing/createCustomerPortal.ts +2 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
- package/src/supabase/crud/aggregate.ts +2 -1
- package/src/supabase/crud/create.ts +2 -1
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/get.ts +2 -1
- package/src/supabase/crud/index.ts +1 -1
- package/src/supabase/crud/list.ts +2 -1
- package/src/supabase/crud/update.ts +2 -1
- package/src/supabase/edgeFunction.ts +195 -0
- package/src/supabase/email/createEmailFunction.ts +75 -0
- package/src/supabase/helpers/authProvider.ts +2 -2
- package/src/supabase/index.ts +22 -2
- package/src/supabase/oauth/disconnect.ts +104 -0
- package/src/supabase/oauth/exchangeToken.ts +183 -0
- package/src/supabase/oauth/getConnections.ts +85 -0
- package/src/supabase/oauth/index.ts +15 -0
- package/src/supabase/oauth/refreshToken.ts +130 -0
- package/src/supabase/registerCrudFunctions.ts +30 -42
- package/src/supabase/utils/idempotency.ts +7 -3
- package/src/supabase/utils/monitoring.ts +1 -1
- package/src/supabase/utils/rateLimiter.ts +1 -1
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +1 -0
- package/src/vercel/api/auth/get-custom-claims.ts +1 -1
- package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
- package/src/vercel/api/auth/index.ts +1 -1
- package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
- package/src/vercel/api/auth/set-custom-claims.ts +2 -4
- package/src/vercel/api/billing/cancel.ts +3 -3
- package/src/vercel/api/billing/change-plan.ts +3 -3
- package/src/vercel/api/billing/create-checkout-session.ts +30 -7
- package/src/vercel/api/billing/customer-portal.ts +1 -1
- package/src/vercel/api/billing/index.ts +1 -1
- package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
- package/src/vercel/api/billing/webhook-handler.ts +11 -4
- package/src/vercel/api/config/constants.ts +9 -9
- package/src/vercel/api/config/firebase-admin.ts +3 -3
- package/src/vercel/api/config/index.ts +1 -1
- package/src/vercel/api/crud/create.ts +1 -1
- package/src/vercel/api/crud/delete.ts +1 -1
- package/src/vercel/api/crud/get.ts +1 -1
- package/src/vercel/api/crud/index.ts +1 -1
- package/src/vercel/api/crud/list.ts +1 -1
- package/src/vercel/api/crud/update.ts +1 -1
- package/src/vercel/api/index.d.ts +1 -1
- package/src/vercel/api/index.ts +2 -1
- package/src/vercel/api/oauth/check-github-access.ts +3 -3
- package/src/vercel/api/oauth/exchange-token.ts +25 -2
- package/src/vercel/api/oauth/grant-github-access.ts +3 -3
- package/src/vercel/api/oauth/index.ts +1 -1
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
- package/src/vercel/api/utils/cors.ts +10 -4
- package/src/vercel/baseFunction.ts +2 -2
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// packages/functions/src/supabase/oauth/exchangeToken.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview OAuth token exchange Supabase Edge Function
|
|
5
|
+
* @description Supabase Edge Function for exchanging OAuth codes for tokens
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @since 0.1.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import * as v from 'valibot';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
OAUTH_PARTNERS,
|
|
16
|
+
exchangeTokenSchema,
|
|
17
|
+
sanitizeHref,
|
|
18
|
+
type ExchangeTokenRequest,
|
|
19
|
+
type OAuthPartnerId,
|
|
20
|
+
} from '@donotdev/core/server';
|
|
21
|
+
|
|
22
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
23
|
+
import type { SupabaseHandlerContext } from '../baseFunction.js';
|
|
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
|
+
|
|
49
|
+
/** Cross-runtime env var access (Deno Edge Functions + Node tests) */
|
|
50
|
+
function getEnv(key: string): string | undefined {
|
|
51
|
+
return typeof Deno !== 'undefined'
|
|
52
|
+
? Deno.env.get(key)
|
|
53
|
+
: process.env[key];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
declare const Deno:
|
|
57
|
+
| { env: { get(key: string): string | undefined } }
|
|
58
|
+
| undefined;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Create an OAuth token exchange Edge Function handler
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* import { createExchangeToken } from '@donotdev/functions/supabase';
|
|
66
|
+
* Deno.serve(createExchangeToken());
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* @version 0.1.0
|
|
70
|
+
* @since 0.1.0
|
|
71
|
+
*/
|
|
72
|
+
export function createExchangeToken() {
|
|
73
|
+
return createSupabaseHandler(
|
|
74
|
+
'exchange-token',
|
|
75
|
+
exchangeTokenSchema,
|
|
76
|
+
async (data: ExchangeTokenRequest, ctx: SupabaseHandlerContext) => {
|
|
77
|
+
const { provider, purpose, code, redirectUri, codeVerifier } = data;
|
|
78
|
+
|
|
79
|
+
// Validate redirectUri scheme (defense-in-depth over Valibot v.url())
|
|
80
|
+
if (!sanitizeHref(redirectUri)) {
|
|
81
|
+
throw new Error('Invalid redirect URI scheme');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Get provider endpoints
|
|
85
|
+
const endpoints = OAUTH_PARTNERS[provider];
|
|
86
|
+
if (!endpoints?.endpoints?.tokenUrl) {
|
|
87
|
+
throw new Error(`Provider ${provider} is not supported`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Get client credentials from env: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
|
|
91
|
+
const upper = provider.toUpperCase();
|
|
92
|
+
const clientId = getEnv(`${upper}_CLIENT_ID`);
|
|
93
|
+
const clientSecret = getEnv(`${upper}_CLIENT_SECRET`);
|
|
94
|
+
|
|
95
|
+
if (!clientId || !clientSecret) {
|
|
96
|
+
throw new Error(`Provider ${provider} is not configured`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Exchange code for token
|
|
100
|
+
const tokenResponse = await fetch(endpoints.endpoints.tokenUrl, {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: {
|
|
103
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
104
|
+
Accept: 'application/json',
|
|
105
|
+
},
|
|
106
|
+
body: new URLSearchParams({
|
|
107
|
+
grant_type: 'authorization_code',
|
|
108
|
+
client_id: clientId,
|
|
109
|
+
client_secret: clientSecret,
|
|
110
|
+
code,
|
|
111
|
+
redirect_uri: redirectUri,
|
|
112
|
+
...(codeVerifier ? { code_verifier: codeVerifier } : {}),
|
|
113
|
+
}).toString(),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
if (!tokenResponse.ok) {
|
|
117
|
+
const errorText = await tokenResponse.text();
|
|
118
|
+
console.error(
|
|
119
|
+
`Token exchange error for ${provider}: ${tokenResponse.status}`,
|
|
120
|
+
errorText
|
|
121
|
+
);
|
|
122
|
+
throw new Error(
|
|
123
|
+
`Failed to exchange code for token: ${tokenResponse.status}`
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const tokenData = (await tokenResponse.json()) as any;
|
|
128
|
+
|
|
129
|
+
// Format credentials
|
|
130
|
+
const credentials = {
|
|
131
|
+
accessToken: tokenData.access_token,
|
|
132
|
+
refreshToken: tokenData.refresh_token || null,
|
|
133
|
+
expiresAt: tokenData.expires_in
|
|
134
|
+
? Math.floor(Date.now() / 1000) + tokenData.expires_in
|
|
135
|
+
: null,
|
|
136
|
+
idToken: tokenData.id_token || null,
|
|
137
|
+
scope: tokenData.scope ? tokenData.scope.split(' ') : [],
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
// Get user profile
|
|
141
|
+
let profile: Record<string, unknown> | null = null;
|
|
142
|
+
if (credentials.accessToken && endpoints.endpoints.profileUrl) {
|
|
143
|
+
try {
|
|
144
|
+
const profileResponse = await fetch(endpoints.endpoints.profileUrl, {
|
|
145
|
+
headers: {
|
|
146
|
+
Authorization: `Bearer ${credentials.accessToken}`,
|
|
147
|
+
Accept: 'application/json',
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
if (profileResponse.ok) {
|
|
151
|
+
const rawProfile = await profileResponse.json();
|
|
152
|
+
// Sanitize profile data from external provider (prevent stored XSS)
|
|
153
|
+
profile = sanitizeProfileData(rawProfile);
|
|
154
|
+
}
|
|
155
|
+
} catch (e) {
|
|
156
|
+
console.warn(`Failed to fetch profile for ${provider}:`, e);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Save connection to Supabase
|
|
161
|
+
const { error: upsertError } = await ctx.supabaseAdmin
|
|
162
|
+
.from('oauth_connections')
|
|
163
|
+
.upsert(
|
|
164
|
+
{
|
|
165
|
+
user_id: ctx.uid,
|
|
166
|
+
provider,
|
|
167
|
+
purpose,
|
|
168
|
+
credentials,
|
|
169
|
+
profile,
|
|
170
|
+
connected: true,
|
|
171
|
+
updated_at: new Date().toISOString(),
|
|
172
|
+
},
|
|
173
|
+
{ onConflict: 'user_id,provider,purpose' }
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
if (upsertError) {
|
|
177
|
+
console.error('Error saving OAuth connection:', upsertError);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return { success: true, credentials, profile };
|
|
181
|
+
}
|
|
182
|
+
);
|
|
183
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// packages/functions/src/supabase/oauth/getConnections.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Get OAuth connections Supabase Edge Function
|
|
5
|
+
* @description Supabase Edge Function for retrieving user OAuth connections
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @since 0.1.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import * as v from 'valibot';
|
|
13
|
+
|
|
14
|
+
import type { OAuthPurpose } from '@donotdev/core/server';
|
|
15
|
+
|
|
16
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
17
|
+
import type { SupabaseHandlerContext } from '../baseFunction.js';
|
|
18
|
+
|
|
19
|
+
const getConnectionsSchema = v.object({
|
|
20
|
+
purpose: v.optional(
|
|
21
|
+
v.picklist(['authentication', 'api-access']) as v.BaseSchema<
|
|
22
|
+
unknown,
|
|
23
|
+
OAuthPurpose,
|
|
24
|
+
v.BaseIssue<unknown>
|
|
25
|
+
>
|
|
26
|
+
),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Create a get OAuth connections Edge Function handler
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* import { createGetConnections } from '@donotdev/functions/supabase';
|
|
35
|
+
* Deno.serve(createGetConnections());
|
|
36
|
+
* ```
|
|
37
|
+
*
|
|
38
|
+
* @version 0.1.0
|
|
39
|
+
* @since 0.1.0
|
|
40
|
+
*/
|
|
41
|
+
export function createGetConnections() {
|
|
42
|
+
return createSupabaseHandler(
|
|
43
|
+
'get-connections',
|
|
44
|
+
getConnectionsSchema,
|
|
45
|
+
async (
|
|
46
|
+
data: { purpose?: OAuthPurpose },
|
|
47
|
+
ctx: SupabaseHandlerContext
|
|
48
|
+
) => {
|
|
49
|
+
let query = ctx.supabaseAdmin
|
|
50
|
+
.from('oauth_connections')
|
|
51
|
+
.select('*')
|
|
52
|
+
.eq('user_id', ctx.uid);
|
|
53
|
+
|
|
54
|
+
if (data.purpose) {
|
|
55
|
+
query = query.eq('purpose', data.purpose);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const { data: rows, error } = await query;
|
|
59
|
+
|
|
60
|
+
if (error) {
|
|
61
|
+
throw new Error(`Failed to get connections: ${error.message}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const connections = (rows || []).map((row: any) => {
|
|
65
|
+
const isExpired = row.credentials?.expiresAt
|
|
66
|
+
? row.credentials.expiresAt < Math.floor(Date.now() / 1000)
|
|
67
|
+
: false;
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
id: row.id,
|
|
71
|
+
userId: row.user_id,
|
|
72
|
+
provider: row.provider,
|
|
73
|
+
purpose: row.purpose,
|
|
74
|
+
connected: !isExpired,
|
|
75
|
+
createdAt: row.created_at,
|
|
76
|
+
updatedAt: row.updated_at,
|
|
77
|
+
hasCredentials: !isExpired && !!row.credentials,
|
|
78
|
+
profile: row.profile,
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
return { connections };
|
|
83
|
+
}
|
|
84
|
+
);
|
|
85
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// packages/functions/src/supabase/oauth/index.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Supabase OAuth functions barrel exports
|
|
5
|
+
* @description Centralized exports for Supabase OAuth Edge Functions
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @since 0.1.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export { createExchangeToken } from './exchangeToken.js';
|
|
13
|
+
export { createDisconnect } from './disconnect.js';
|
|
14
|
+
export { createRefreshToken } from './refreshToken.js';
|
|
15
|
+
export { createGetConnections } from './getConnections.js';
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// packages/functions/src/supabase/oauth/refreshToken.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview OAuth token refresh Supabase Edge Function
|
|
5
|
+
* @description Supabase Edge Function for refreshing OAuth tokens
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @since 0.1.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import * as v from 'valibot';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
OAUTH_PARTNERS,
|
|
16
|
+
type OAuthRefreshRequest,
|
|
17
|
+
} from '@donotdev/core/server';
|
|
18
|
+
|
|
19
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
20
|
+
import type { SupabaseHandlerContext } from '../baseFunction.js';
|
|
21
|
+
|
|
22
|
+
/** Cross-runtime env var access (Deno Edge Functions + Node tests) */
|
|
23
|
+
function getEnv(key: string): string | undefined {
|
|
24
|
+
return typeof Deno !== 'undefined'
|
|
25
|
+
? Deno.env.get(key)
|
|
26
|
+
: process.env[key];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
declare const Deno:
|
|
30
|
+
| { env: { get(key: string): string | undefined } }
|
|
31
|
+
| undefined;
|
|
32
|
+
|
|
33
|
+
const refreshTokenSchema = v.object({
|
|
34
|
+
provider: v.string() as v.BaseSchema<
|
|
35
|
+
unknown,
|
|
36
|
+
OAuthRefreshRequest['provider'],
|
|
37
|
+
v.BaseIssue<unknown>
|
|
38
|
+
>,
|
|
39
|
+
refreshToken: v.pipe(
|
|
40
|
+
v.string(),
|
|
41
|
+
v.minLength(1, 'Refresh token is required')
|
|
42
|
+
),
|
|
43
|
+
redirectUri: v.pipe(v.string(), v.url('Valid redirect URI is required')),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Create an OAuth token refresh Edge Function handler
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* import { createRefreshToken } from '@donotdev/functions/supabase';
|
|
52
|
+
* Deno.serve(createRefreshToken());
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* @version 0.1.0
|
|
56
|
+
* @since 0.1.0
|
|
57
|
+
*/
|
|
58
|
+
export function createRefreshToken() {
|
|
59
|
+
return createSupabaseHandler(
|
|
60
|
+
'refresh-token',
|
|
61
|
+
refreshTokenSchema,
|
|
62
|
+
async (data: OAuthRefreshRequest, ctx: SupabaseHandlerContext) => {
|
|
63
|
+
const { provider, refreshToken: refreshTokenValue, redirectUri } = data;
|
|
64
|
+
|
|
65
|
+
// Get provider endpoints
|
|
66
|
+
const endpoints = OAUTH_PARTNERS[provider];
|
|
67
|
+
if (!endpoints?.endpoints?.tokenUrl) {
|
|
68
|
+
throw new Error(`Provider ${provider} does not support token refresh`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Get client credentials: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
|
|
72
|
+
const upper = provider.toUpperCase();
|
|
73
|
+
const clientId = getEnv(`${upper}_CLIENT_ID`);
|
|
74
|
+
const clientSecret = getEnv(`${upper}_CLIENT_SECRET`);
|
|
75
|
+
|
|
76
|
+
if (!clientId || !clientSecret) {
|
|
77
|
+
throw new Error(`Provider ${provider} is not configured`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Refresh the token
|
|
81
|
+
const response = await fetch(endpoints.endpoints.tokenUrl, {
|
|
82
|
+
method: 'POST',
|
|
83
|
+
headers: {
|
|
84
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
85
|
+
Accept: 'application/json',
|
|
86
|
+
},
|
|
87
|
+
body: new URLSearchParams({
|
|
88
|
+
grant_type: 'refresh_token',
|
|
89
|
+
client_id: clientId,
|
|
90
|
+
client_secret: clientSecret,
|
|
91
|
+
refresh_token: refreshTokenValue,
|
|
92
|
+
redirect_uri: redirectUri,
|
|
93
|
+
}).toString(),
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
if (!response.ok) {
|
|
97
|
+
const errorText = await response.text();
|
|
98
|
+
console.error(`Token refresh error for ${provider}:`, errorText);
|
|
99
|
+
throw new Error(`Failed to refresh token: ${response.status}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const tokenData = (await response.json()) as any;
|
|
103
|
+
|
|
104
|
+
const credentials = {
|
|
105
|
+
accessToken: tokenData.access_token,
|
|
106
|
+
refreshToken: tokenData.refresh_token || refreshTokenValue,
|
|
107
|
+
expiresAt: tokenData.expires_in
|
|
108
|
+
? Math.floor(Date.now() / 1000) + tokenData.expires_in
|
|
109
|
+
: null,
|
|
110
|
+
scope: tokenData.scope ? tokenData.scope.split(' ') : [],
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// Update connection in Supabase
|
|
114
|
+
const { error: updateError } = await ctx.supabaseAdmin
|
|
115
|
+
.from('oauth_connections')
|
|
116
|
+
.update({
|
|
117
|
+
credentials,
|
|
118
|
+
updated_at: new Date().toISOString(),
|
|
119
|
+
})
|
|
120
|
+
.eq('user_id', ctx.uid)
|
|
121
|
+
.eq('provider', provider);
|
|
122
|
+
|
|
123
|
+
if (updateError) {
|
|
124
|
+
console.error('Error updating OAuth connection:', updateError);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return { success: true, credentials };
|
|
128
|
+
}
|
|
129
|
+
);
|
|
130
|
+
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @fileoverview Auto-register CRUD handlers from entities for Supabase Edge Functions
|
|
5
5
|
* @description Utility to automatically generate CRUD Edge Function handlers for all entities
|
|
6
6
|
*
|
|
7
|
-
* @version 0.0
|
|
7
|
+
* @version 0.1.0
|
|
8
8
|
* @since 0.5.0
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
createSupabaseListEntities,
|
|
21
21
|
createSupabaseAggregateEntities,
|
|
22
22
|
} from './crud/index.js';
|
|
23
|
+
import { createEdgeFunction } from './edgeFunction.js';
|
|
23
24
|
|
|
24
25
|
type SupabaseHandler = (req: Request) => Promise<Response>;
|
|
25
26
|
|
|
@@ -122,49 +123,36 @@ export function createSupabaseCrudFunctions(
|
|
|
122
123
|
}
|
|
123
124
|
|
|
124
125
|
/**
|
|
125
|
-
* Serve dispatcher:
|
|
126
|
+
* Serve dispatcher: CORS via createEdgeFunction, then routes by _functionName.
|
|
127
|
+
* Auth is NOT checked here (requireAuth: false) — individual handlers
|
|
128
|
+
* use createSupabaseHandler which enforces auth + RBAC per operation.
|
|
126
129
|
*/
|
|
127
|
-
const serve = async (req
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
const handler = handlers[functionName];
|
|
141
|
-
if (!handler) {
|
|
142
|
-
return new Response(
|
|
143
|
-
JSON.stringify({ error: `Unknown function: ${functionName}` }),
|
|
144
|
-
{ status: 404, headers: { 'Content-Type': 'application/json' } }
|
|
145
|
-
);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// Remove _functionName from body before passing to handler
|
|
149
|
-
const { _functionName, ...handlerData } = body as Record<string, unknown>;
|
|
150
|
-
|
|
151
|
-
// Create new request with cleaned body
|
|
152
|
-
const handlerReq = new Request(req.url, {
|
|
153
|
-
method: req.method,
|
|
154
|
-
headers: req.headers,
|
|
155
|
-
body: JSON.stringify(handlerData),
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
return handler(handlerReq);
|
|
159
|
-
} catch (error) {
|
|
160
|
-
const message =
|
|
161
|
-
error instanceof Error ? error.message : 'Internal server error';
|
|
162
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
163
|
-
status: 500,
|
|
164
|
-
headers: { 'Content-Type': 'application/json' },
|
|
165
|
-
});
|
|
130
|
+
const serve = createEdgeFunction(async (req, ctx) => {
|
|
131
|
+
const body = await req.json().catch(() => ({}));
|
|
132
|
+
const functionName = (body as Record<string, unknown>)
|
|
133
|
+
._functionName as string;
|
|
134
|
+
|
|
135
|
+
if (!functionName) {
|
|
136
|
+
return ctx.error('Missing _functionName in request body', 400);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const handler = handlers[functionName];
|
|
140
|
+
if (!handler) {
|
|
141
|
+
return ctx.error(`Unknown function: ${functionName}`, 404);
|
|
166
142
|
}
|
|
167
|
-
|
|
143
|
+
|
|
144
|
+
// Remove _functionName from body before passing to handler
|
|
145
|
+
const { _functionName, ...handlerData } = body as Record<string, unknown>;
|
|
146
|
+
|
|
147
|
+
// Create new request with cleaned body
|
|
148
|
+
const handlerReq = new Request(req.url, {
|
|
149
|
+
method: req.method,
|
|
150
|
+
headers: req.headers,
|
|
151
|
+
body: JSON.stringify(handlerData),
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
return handler(handlerReq);
|
|
155
|
+
}, { requireAuth: false });
|
|
168
156
|
|
|
169
157
|
return { handlers, serve };
|
|
170
158
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @fileoverview Idempotency utilities for Supabase Edge Functions
|
|
5
5
|
* @description Provides idempotency checking and storage using Postgres table
|
|
6
6
|
*
|
|
7
|
-
* @version 0.0
|
|
7
|
+
* @version 0.1.0
|
|
8
8
|
* @since 0.5.0
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
@@ -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
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @fileoverview Monitoring and metrics utilities for Supabase Edge Functions
|
|
5
5
|
* @description Provides metrics collection and analytics queries using Postgres table
|
|
6
6
|
*
|
|
7
|
-
* @version 0.0
|
|
7
|
+
* @version 0.1.0
|
|
8
8
|
* @since 0.5.0
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* On RPC error or unexpected failure, this function FAILS CLOSED (blocks the request).
|
|
19
19
|
* A broken rate limiter must not silently allow unlimited access to protected resources.
|
|
20
20
|
*
|
|
21
|
-
* @version 0.0
|
|
21
|
+
* @version 0.1.0
|
|
22
22
|
* @since 0.5.0
|
|
23
23
|
* @author AMBROISE PARK Consulting
|
|
24
24
|
*/
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createAIChatRoute } from './chat.js';
|