Files
thrilltrack-explorer/supabase/functions/detect-location/index.ts
pac7 0f2219f849 Improve image handling, optimize hooks, and add rate limiting
This commit introduces several improvements:
- Enhances `RideModelCard` by safely accessing and displaying ride count and image data, preventing potential errors.
- Refactors `useEntityVersions` and `useSearch` hooks to use `useCallback` and improve performance and prevent race conditions.
- Introduces a `MAX_MAP_SIZE` and cleanup mechanism for the rate limiting map in `detect-location` Supabase function to prevent memory leaks.
- Adds robust error handling and cleanup for image uploads in `uploadPendingImages`.
- Modifies `ManufacturerModels` to correctly map and display ride counts.
- Includes error handling for topological sort in `process-selective-approval` Supabase function.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 39bb006b-d046-477f-a1f9-b7821836f3a1
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
2025-10-08 17:55:37 +00:00

179 lines
5.5 KiB
TypeScript

import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
interface IPLocationResponse {
country: string;
countryCode: string;
measurementSystem: 'metric' | 'imperial';
}
// Simple in-memory rate limiter
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
const RATE_LIMIT_WINDOW = 60000; // 1 minute in milliseconds
const MAX_REQUESTS = 10; // 10 requests per minute per IP
const MAX_MAP_SIZE = 10000; // Maximum number of IPs to track
function cleanupExpiredEntries() {
const now = Date.now();
for (const [ip, data] of rateLimitMap.entries()) {
if (now > data.resetAt) {
rateLimitMap.delete(ip);
}
}
}
function checkRateLimit(ip: string): { allowed: boolean; retryAfter?: number } {
const now = Date.now();
const existing = rateLimitMap.get(ip);
if (!existing || now > existing.resetAt) {
// If map is too large, clean up expired entries first
if (rateLimitMap.size >= MAX_MAP_SIZE) {
cleanupExpiredEntries();
// If still too large after cleanup, clear oldest entries
if (rateLimitMap.size >= MAX_MAP_SIZE) {
const toDelete = Math.floor(MAX_MAP_SIZE * 0.2); // Remove 20% of entries
let deleted = 0;
for (const key of rateLimitMap.keys()) {
if (deleted >= toDelete) break;
rateLimitMap.delete(key);
deleted++;
}
console.warn(`Rate limit map reached size limit. Cleared ${deleted} entries.`);
}
}
// Create new entry or reset expired entry
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
return { allowed: true };
}
if (existing.count >= MAX_REQUESTS) {
const retryAfter = Math.ceil((existing.resetAt - now) / 1000);
return { allowed: false, retryAfter };
}
existing.count++;
return { allowed: true };
}
// Clean up old entries periodically to prevent memory leak
setInterval(cleanupExpiredEntries, RATE_LIMIT_WINDOW);
serve(async (req) => {
// Handle CORS preflight requests
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
// Get the client's IP address
const forwarded = req.headers.get('x-forwarded-for');
const realIP = req.headers.get('x-real-ip');
const clientIP = forwarded?.split(',')[0] || realIP || '8.8.8.8'; // fallback to Google DNS for testing
// Check rate limit
const rateLimit = checkRateLimit(clientIP);
if (!rateLimit.allowed) {
return new Response(
JSON.stringify({
error: 'Rate limit exceeded',
message: 'Too many requests. Please try again later.',
retryAfter: rateLimit.retryAfter
}),
{
status: 429,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'Retry-After': String(rateLimit.retryAfter || 60)
}
}
);
}
console.log('Detecting location for IP:', clientIP);
// Use configurable geolocation service with proper error handling
// Defaults to ip-api.com if not configured
const geoApiUrl = Deno.env.get('GEOLOCATION_API_URL') || 'http://ip-api.com/json';
const geoApiFields = Deno.env.get('GEOLOCATION_API_FIELDS') || 'status,country,countryCode';
let geoResponse;
try {
geoResponse = await fetch(`${geoApiUrl}/${clientIP}?fields=${geoApiFields}`);
} catch (fetchError) {
console.error('Network error fetching location data:', fetchError);
throw new Error('Network error: Unable to reach geolocation service');
}
if (!geoResponse.ok) {
throw new Error(`Geolocation service returned ${geoResponse.status}: ${geoResponse.statusText}`);
}
let geoData;
try {
geoData = await geoResponse.json();
} catch (parseError) {
console.error('Failed to parse geolocation response:', parseError);
throw new Error('Invalid response format from geolocation service');
}
if (geoData.status !== 'success') {
throw new Error(`Geolocation failed: ${geoData.message || 'Invalid location data'}`);
}
// Countries that primarily use imperial system
const imperialCountries = ['US', 'LR', 'MM']; // USA, Liberia, Myanmar
const measurementSystem = imperialCountries.includes(geoData.countryCode) ? 'imperial' : 'metric';
const result: IPLocationResponse = {
country: geoData.country,
countryCode: geoData.countryCode,
measurementSystem
};
console.log('Location detected:', result);
return new Response(
JSON.stringify(result),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json'
}
}
);
} catch (error) {
console.error('Error detecting location:', error);
// Return default (metric) with 500 status to indicate error occurred
// This allows proper error monitoring while still providing fallback data
const defaultResult: IPLocationResponse = {
country: 'Unknown',
countryCode: 'XX',
measurementSystem: 'metric'
};
return new Response(
JSON.stringify({
...defaultResult,
error: error instanceof Error ? error.message : 'Failed to detect location',
fallback: true
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json'
},
status: 500
}
);
}
});