@donotdev/functions 0.1.0 → 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.
Files changed (95) hide show
  1. package/guidelines/FUNCTIONS.md +9 -0
  2. package/guidelines/VERCEL.md +260 -0
  3. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  4. package/lib/firebase/index.js +3 -3
  5. package/lib/firebase/index.js.map +4 -4
  6. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  7. package/lib/shared/ai/costTracker.d.ts +20 -0
  8. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  9. package/lib/shared/ai/index.d.ts +6 -0
  10. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  11. package/lib/shared/billing/createCheckout.d.ts +8 -2
  12. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  13. package/lib/shared/email/index.d.ts +3 -0
  14. package/lib/shared/email/provider.d.ts +30 -0
  15. package/lib/shared/email/resendProvider.d.ts +22 -0
  16. package/lib/shared/github.d.ts +5 -0
  17. package/lib/shared/index.d.ts +2 -0
  18. package/lib/shared/index.js +4 -3
  19. package/lib/shared/index.js.map +4 -4
  20. package/lib/shared/logger.d.ts +2 -0
  21. package/lib/shared/oauth/exchangeToken.d.ts +1 -0
  22. package/lib/shared/oauth/grantAccess.d.ts +1 -0
  23. package/lib/shared/utils/internal/idempotency.d.ts +1 -0
  24. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  25. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  26. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  27. package/lib/supabase/billing/changePlan.d.ts +1 -1
  28. package/lib/supabase/crud/aggregate.d.ts +1 -0
  29. package/lib/supabase/crud/create.d.ts +1 -0
  30. package/lib/supabase/crud/delete.d.ts +1 -0
  31. package/lib/supabase/crud/get.d.ts +1 -0
  32. package/lib/supabase/crud/list.d.ts +1 -0
  33. package/lib/supabase/crud/update.d.ts +1 -0
  34. package/lib/supabase/edgeFunction.d.ts +56 -0
  35. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  36. package/lib/supabase/index.d.ts +8 -0
  37. package/lib/supabase/index.js +3 -2
  38. package/lib/supabase/index.js.map +4 -4
  39. package/lib/vercel/api/ai/chat.d.ts +29 -0
  40. package/lib/vercel/api/ai/index.d.ts +1 -0
  41. package/lib/vercel/api/index.d.ts +1 -0
  42. package/lib/vercel/api/index.js +3 -2
  43. package/lib/vercel/api/index.js.map +4 -4
  44. package/package.json +38 -5
  45. package/src/firebase/billing/createCheckoutSession.ts +79 -187
  46. package/src/firebase/oauth/exchangeToken.ts +4 -4
  47. package/src/firebase/oauth/refreshToken.ts +4 -4
  48. package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
  49. package/src/shared/ai/classifyAIError.ts +163 -0
  50. package/src/shared/ai/costTracker.ts +51 -0
  51. package/src/shared/ai/createAIRoute.ts +397 -0
  52. package/src/shared/ai/index.ts +8 -0
  53. package/src/shared/ai/resolveModelTier.ts +58 -0
  54. package/src/shared/billing/createCheckout.ts +153 -8
  55. package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
  56. package/src/shared/billing/idempotency.ts +5 -0
  57. package/src/shared/email/createEmailRoute.ts +81 -0
  58. package/src/shared/email/index.ts +5 -0
  59. package/src/shared/email/provider.ts +31 -0
  60. package/src/shared/email/resendProvider.ts +56 -0
  61. package/src/shared/errorHandling.ts +10 -4
  62. package/src/shared/github.ts +38 -0
  63. package/src/shared/index.ts +2 -0
  64. package/src/shared/logger.ts +2 -0
  65. package/src/shared/oauth/exchangeToken.ts +1 -0
  66. package/src/shared/oauth/grantAccess.ts +1 -0
  67. package/src/shared/utils/internal/idempotency.ts +1 -0
  68. package/src/shared/utils/internal/rateLimiter.ts +6 -3
  69. package/src/shared/validation.ts +1 -1
  70. package/src/supabase/ai/createAIFunction.ts +75 -0
  71. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  72. package/src/supabase/auth/setCustomClaims.ts +66 -5
  73. package/src/supabase/baseFunction.ts +26 -2
  74. package/src/supabase/billing/changePlan.ts +6 -1
  75. package/src/supabase/billing/createCheckoutSession.ts +16 -2
  76. package/src/supabase/crud/aggregate.ts +1 -0
  77. package/src/supabase/crud/create.ts +1 -0
  78. package/src/supabase/crud/delete.ts +1 -0
  79. package/src/supabase/crud/get.ts +1 -0
  80. package/src/supabase/crud/list.ts +1 -0
  81. package/src/supabase/crud/update.ts +1 -0
  82. package/src/supabase/edgeFunction.ts +195 -0
  83. package/src/supabase/email/createEmailFunction.ts +75 -0
  84. package/src/supabase/index.ts +12 -0
  85. package/src/supabase/oauth/exchangeToken.ts +38 -7
  86. package/src/supabase/oauth/refreshToken.ts +4 -5
  87. package/src/supabase/registerCrudFunctions.ts +29 -41
  88. package/src/supabase/utils/idempotency.ts +6 -2
  89. package/src/vercel/api/ai/chat.ts +77 -0
  90. package/src/vercel/api/ai/index.ts +1 -0
  91. package/src/vercel/api/billing/create-checkout-session.ts +27 -4
  92. package/src/vercel/api/billing/webhook-handler.ts +8 -1
  93. package/src/vercel/api/index.ts +1 -0
  94. package/src/vercel/api/oauth/exchange-token.ts +24 -1
  95. package/src/vercel/api/utils/cors.ts +6 -0
@@ -12,6 +12,8 @@
12
12
  // Base
13
13
  export { createSupabaseHandler } from './baseFunction.js';
14
14
  export type { SupabaseHandlerContext } from './baseFunction.js';
15
+ export { createEdgeFunction } from './edgeFunction.js';
16
+ export type { EdgeFunctionContext, EdgeFunctionOptions } from './edgeFunction.js';
15
17
 
16
18
  // Helpers
17
19
  export { createSupabaseAuthProvider } from './helpers/authProvider.js';
@@ -19,6 +21,7 @@ export { createSupabaseAuthProvider } from './helpers/authProvider.js';
19
21
  // Auth
20
22
  export { createDeleteAccount } from './auth/deleteAccount.js';
21
23
  export { createSetCustomClaims } from './auth/setCustomClaims.js';
24
+ export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
22
25
  export { createGetCustomClaims } from './auth/getCustomClaims.js';
23
26
  export { createRemoveCustomClaims } from './auth/removeCustomClaims.js';
24
27
  export { createGetUserAuthStatus } from './auth/getUserAuthStatus.js';
@@ -38,6 +41,15 @@ export {
38
41
  createGetConnections,
39
42
  } from './oauth/index.js';
40
43
 
44
+ // AI
45
+ export { createAIFunction } from './ai/createAIFunction.js';
46
+ export { resolveModelForTier } from '../shared/ai/resolveModelTier.js';
47
+ export { classifyAIError, mapClassifiedToHTTP } from '../shared/ai/classifyAIError.js';
48
+ export type { AIErrorCode, ClassifiedAIError } from '../shared/ai/classifyAIError.js';
49
+
50
+ // Email
51
+ export { createEmailFunction } from './email/createEmailFunction.js';
52
+
41
53
  // CRUD
42
54
  export {
43
55
  createSupabaseGetEntity,
@@ -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,6 +22,30 @@ 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
51
  return typeof Deno !== 'undefined'
@@ -51,17 +76,21 @@ export function createExchangeToken() {
51
76
  async (data: ExchangeTokenRequest, ctx: SupabaseHandlerContext) => {
52
77
  const { provider, purpose, code, redirectUri, codeVerifier } = data;
53
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
+
54
84
  // Get provider endpoints
55
85
  const endpoints = OAUTH_PARTNERS[provider];
56
86
  if (!endpoints?.endpoints?.tokenUrl) {
57
87
  throw new Error(`Provider ${provider} is not supported`);
58
88
  }
59
89
 
60
- // Get client credentials from env
61
- const clientId =
62
- getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_ID`);
63
- const clientSecret =
64
- getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_SECRET`);
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`);
65
94
 
66
95
  if (!clientId || !clientSecret) {
67
96
  throw new Error(`Provider ${provider} is not configured`);
@@ -109,7 +138,7 @@ export function createExchangeToken() {
109
138
  };
110
139
 
111
140
  // Get user profile
112
- let profile = null;
141
+ let profile: Record<string, unknown> | null = null;
113
142
  if (credentials.accessToken && endpoints.endpoints.profileUrl) {
114
143
  try {
115
144
  const profileResponse = await fetch(endpoints.endpoints.profileUrl, {
@@ -119,7 +148,9 @@ export function createExchangeToken() {
119
148
  },
120
149
  });
121
150
  if (profileResponse.ok) {
122
- profile = await profileResponse.json();
151
+ const rawProfile = await profileResponse.json();
152
+ // Sanitize profile data from external provider (prevent stored XSS)
153
+ profile = sanitizeProfileData(rawProfile);
123
154
  }
124
155
  } catch (e) {
125
156
  console.warn(`Failed to fetch profile for ${provider}:`, e);
@@ -68,11 +68,10 @@ export function createRefreshToken() {
68
68
  throw new Error(`Provider ${provider} does not support token refresh`);
69
69
  }
70
70
 
71
- // Get client credentials
72
- const clientId =
73
- getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_ID`);
74
- const clientSecret =
75
- getEnv(`OAUTH_${provider.toUpperCase()}_CLIENT_SECRET`);
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`);
76
75
 
77
76
  if (!clientId || !clientSecret) {
78
77
  throw new Error(`Provider ${provider} is not configured`);
@@ -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: reads _functionName from request body, routes to correct handler
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: Request): Promise<Response> => {
128
- try {
129
- const body = await req.json().catch(() => ({}));
130
- const functionName = (body as Record<string, unknown>)
131
- ._functionName as string;
132
-
133
- if (!functionName) {
134
- return new Response(
135
- JSON.stringify({ error: 'Missing _functionName in request body' }),
136
- { status: 400, headers: { 'Content-Type': 'application/json' } }
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
  }
@@ -56,9 +56,13 @@ export async function checkIdempotency<T>(
56
56
 
57
57
  return data.result as T;
58
58
  } catch (error) {
59
- // Fail open - allow the operation if idempotency check fails
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
- return null;
63
+ throw new Error(
64
+ '[idempotency] Unable to verify idempotency. Operation rejected to prevent potential duplicate processing.'
65
+ );
62
66
  }
63
67
  }
64
68
 
@@ -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';
@@ -17,7 +17,7 @@ import type {
17
17
  import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
18
18
 
19
19
  import { createCheckoutAlgorithm } from '../../../shared/billing/createCheckout.js';
20
- import { stripe, validateStripeEnvironment } from '../../../shared/utils.js';
20
+ import { initStripe, stripe, validateStripeEnvironment } from '../../../shared/utils.js';
21
21
  import { createVercelBaseFunction } from '../../baseFunction.js';
22
22
 
23
23
  import type { NextApiRequest, NextApiResponse } from 'next';
@@ -38,15 +38,38 @@ async function createCheckoutSessionLogic(
38
38
  context: { uid: string },
39
39
  billingConfig: StripeBackConfig
40
40
  ) {
41
- // Validate environment
41
+ // Initialize Stripe with env var
42
+ initStripe(process.env.STRIPE_SECRET_KEY || '');
42
43
  validateStripeEnvironment();
43
44
 
44
45
  // Create Stripe provider
45
46
  const stripeProvider = {
46
- async createCheckoutSession(params: any) {
47
+ async createCheckoutSession(params: {
48
+ priceId?: string;
49
+ unitAmount?: number;
50
+ productName?: string;
51
+ currency?: string;
52
+ customerEmail?: string;
53
+ metadata: Record<string, string>;
54
+ allowPromotionCodes: boolean;
55
+ successUrl: string;
56
+ cancelUrl: string;
57
+ mode?: 'payment' | 'subscription';
58
+ }) {
47
59
  const session = await stripe.checkout.sessions.create({
48
60
  payment_method_types: ['card'],
49
- line_items: [{ price: params.priceId, quantity: 1 }],
61
+ line_items: [
62
+ params.priceId
63
+ ? { price: params.priceId, quantity: 1 }
64
+ : {
65
+ price_data: {
66
+ currency: params.currency || 'eur',
67
+ unit_amount: params.unitAmount!,
68
+ product_data: { name: params.productName! },
69
+ },
70
+ quantity: 1,
71
+ },
72
+ ],
50
73
  mode: params.mode || 'payment',
51
74
  allow_promotion_codes: params.allowPromotionCodes,
52
75
  success_url: params.successUrl,
@@ -45,6 +45,13 @@ export function createStripeWebhook(billingConfig: StripeBackConfig) {
45
45
  throw new Error('STRIPE_WEBHOOK_SECRET not configured');
46
46
  }
47
47
 
48
+ // Content-Length pre-check before streaming body
49
+ const contentLength = parseInt(req.headers['content-length'] || '0', 10);
50
+ if (contentLength > MAX_BODY_BYTES) {
51
+ res.status(413).json({ error: 'Payload too large' });
52
+ return;
53
+ }
54
+
48
55
  // Get raw body
49
56
  const rawBody = await getRawBody(req);
50
57
 
@@ -80,7 +87,7 @@ export function createStripeWebhook(billingConfig: StripeBackConfig) {
80
87
  error: error instanceof Error ? error.message : String(error),
81
88
  });
82
89
  res.status(400).json({
83
- error: error instanceof Error ? error.message : 'Webhook failed',
90
+ error: 'Webhook processing failed',
84
91
  });
85
92
  }
86
93
  };
@@ -9,6 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ export * from './ai/index.js';
12
13
  export * from './auth/index.js';
13
14
  export * from './billing/index.js';
14
15
  export * from './config/index.js';
@@ -25,6 +25,28 @@ import { createVercelBaseFunction } from '../../baseFunction.js';
25
25
  import type { NextApiRequest, NextApiResponse } from 'next';
26
26
  import type * as v from 'valibot';
27
27
 
28
+ /** Validate Mastodon instance URL to prevent SSRF */
29
+ function validateInstanceUrl(url: string): void {
30
+ const parsed = new URL(url);
31
+ if (parsed.protocol !== 'https:') {
32
+ throw new Error('Instance URL must use HTTPS');
33
+ }
34
+ const hostname = parsed.hostname;
35
+ if (
36
+ hostname === 'localhost' ||
37
+ hostname === '127.0.0.1' ||
38
+ hostname === '::1' ||
39
+ hostname.startsWith('10.') ||
40
+ hostname.startsWith('192.168.') ||
41
+ hostname.startsWith('172.') ||
42
+ hostname === '169.254.169.254' ||
43
+ hostname.endsWith('.internal') ||
44
+ hostname.endsWith('.local')
45
+ ) {
46
+ throw new Error('Instance URL must not point to internal addresses');
47
+ }
48
+ }
49
+
28
50
  /**
29
51
  * Business logic for exchanging OAuth tokens
30
52
  * Base function handles: validation, auth, rate limiting, monitoring
@@ -42,6 +64,7 @@ async function exchangeTokenLogic(
42
64
 
43
65
  // Special handling for Mastodon instances
44
66
  if (provider === 'mastodon' && instance) {
67
+ validateInstanceUrl(instance);
45
68
  tokenUrl = `${instance.replace(/\/$/, '')}/oauth/token` as any;
46
69
  }
47
70
 
@@ -131,7 +154,7 @@ async function exchangeTokenLogic(
131
154
 
132
155
  // Validate required fields
133
156
  if (!tokenData.access_token) {
134
- console.error(`Invalid token response`, { provider, tokenData });
157
+ console.error(`Invalid token response`, { provider, hasAccessToken: !!tokenData?.access_token });
135
158
  throw new Error('Provider returned invalid token format');
136
159
  }
137
160
 
@@ -51,6 +51,12 @@ export function handleCors(req: NextApiRequest, res: NextApiResponse): boolean {
51
51
  res.setHeader(key, value);
52
52
  });
53
53
 
54
+ // Warn if wildcard origin is used in production — consumers should override
55
+ const origin = corsHeaders['Access-Control-Allow-Origin'];
56
+ if (process.env.NODE_ENV === 'production' && origin === '*') {
57
+ console.warn('[DoNotDev] CORS origin is set to wildcard (*) in production. Override in your cors config.');
58
+ }
59
+
54
60
  // Handle preflight OPTIONS request
55
61
  if (req.method === 'OPTIONS') {
56
62
  res.status(200).end();