diff --git a/supabase/functions/upload-image/index.ts b/supabase/functions/upload-image/index.ts index 36d8eb5d..aeabc63f 100644 --- a/supabase/functions/upload-image/index.ts +++ b/supabase/functions/upload-image/index.ts @@ -1,16 +1,51 @@ import { serve } from "https://deno.land/std@0.168.0/http/server.ts" import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' -// TODO: In production, restrict CORS to specific domains -// For now, allowing all origins for development flexibility -// Example production config: 'Access-Control-Allow-Origin': 'https://yourdomain.com' -const corsHeaders = { - 'Access-Control-Allow-Origin': '*', +// Environment-aware CORS configuration +const getAllowedOrigin = (requestOrigin: string | null): string => { + const environment = Deno.env.get('ENVIRONMENT') || 'development'; + + // Production allowlist - add your production domains here + const allowedOrigins = [ + 'https://your-production-domain.com', + 'https://www.your-production-domain.com', + ]; + + // In development, allow localhost and Replit domains + if (environment === 'development') { + if (requestOrigin) { + if ( + requestOrigin.includes('localhost') || + requestOrigin.includes('127.0.0.1') || + requestOrigin.includes('.repl.co') || + requestOrigin.includes('.replit.dev') + ) { + return requestOrigin; + } + } + return '*'; + } + + // In production, only allow specific domains + if (requestOrigin && allowedOrigins.includes(requestOrigin)) { + return requestOrigin; + } + + // Default to first allowed origin for production + return allowedOrigins[0]; +}; + +const getCorsHeaders = (requestOrigin: string | null) => ({ + 'Access-Control-Allow-Origin': getAllowedOrigin(requestOrigin), 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type', 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS', -} + 'Access-Control-Allow-Credentials': 'true', +}); serve(async (req) => { + const requestOrigin = req.headers.get('origin'); + const corsHeaders = getCorsHeaders(requestOrigin); + // Handle CORS preflight requests if (req.method === 'OPTIONS') { return new Response(null, { headers: corsHeaders })