|
|
@@ -8,20 +8,42 @@
|
|
|
/**
|
|
|
* Get CORS headers with allowed origins from environment
|
|
|
*
|
|
|
+ * @param requestOrigin - The Origin header from the request (optional)
|
|
|
* @param additionalMethods - Additional HTTP methods to allow (default: GET, POST, OPTIONS)
|
|
|
* @returns CORS headers object
|
|
|
*/
|
|
|
-export function getCorsHeaders(additionalMethods: string[] = []): Record<string, string> {
|
|
|
+export function getCorsHeaders(requestOrigin?: string, additionalMethods: string[] = []): Record<string, string> {
|
|
|
// Get allowed origins from environment variable
|
|
|
// Format: comma-separated list, e.g., "https://shopcall.ai,http://192.168.2.112:8081"
|
|
|
const allowedOriginsEnv = Deno.env.get('EDGE_FUNCTION_ALLOWED_ORIGINS') || '*';
|
|
|
|
|
|
+ // Determine the Access-Control-Allow-Origin value
|
|
|
+ let allowOrigin = '*';
|
|
|
+
|
|
|
+ if (allowedOriginsEnv !== '*' && requestOrigin) {
|
|
|
+ // Parse allowed origins
|
|
|
+ const allowedOrigins = allowedOriginsEnv.split(',').map(o => o.trim());
|
|
|
+
|
|
|
+ // Check if request origin is in allowed list
|
|
|
+ if (allowedOrigins.includes(requestOrigin)) {
|
|
|
+ allowOrigin = requestOrigin;
|
|
|
+ } else {
|
|
|
+ // Request origin not allowed - return first allowed origin as fallback
|
|
|
+ // This will cause CORS error on browser side, which is expected behavior
|
|
|
+ allowOrigin = allowedOrigins[0] || '*';
|
|
|
+ }
|
|
|
+ } else if (allowedOriginsEnv !== '*') {
|
|
|
+ // No request origin provided, use first allowed origin
|
|
|
+ const allowedOrigins = allowedOriginsEnv.split(',').map(o => o.trim());
|
|
|
+ allowOrigin = allowedOrigins[0] || '*';
|
|
|
+ }
|
|
|
+
|
|
|
// Default methods
|
|
|
const defaultMethods = ['GET', 'POST', 'OPTIONS'];
|
|
|
const allMethods = [...new Set([...defaultMethods, ...additionalMethods])];
|
|
|
|
|
|
return {
|
|
|
- 'Access-Control-Allow-Origin': allowedOriginsEnv,
|
|
|
+ 'Access-Control-Allow-Origin': allowOrigin,
|
|
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
|
'Access-Control-Allow-Methods': allMethods.join(', '),
|
|
|
};
|
|
|
@@ -30,11 +52,12 @@ export function getCorsHeaders(additionalMethods: string[] = []): Record<string,
|
|
|
/**
|
|
|
* Handle CORS preflight request
|
|
|
*
|
|
|
+ * @param requestOrigin - The Origin header from the request (optional)
|
|
|
* @param additionalMethods - Additional HTTP methods to allow
|
|
|
* @returns Response for OPTIONS request
|
|
|
*/
|
|
|
-export function handleCorsPreflightRequest(additionalMethods: string[] = []): Response {
|
|
|
+export function handleCorsPreflightRequest(requestOrigin?: string, additionalMethods: string[] = []): Response {
|
|
|
return new Response(null, {
|
|
|
- headers: getCorsHeaders(additionalMethods)
|
|
|
+ headers: getCorsHeaders(requestOrigin, additionalMethods)
|
|
|
});
|
|
|
}
|