mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 11:51:14 -05:00
Migrate Phase 1 user-facing functions
Refactor export-user-data, notify-user-submission-status, and resend-deletion-code to use createEdgeFunction wrapper. Remove manual CORS, auth, rate limiting boilerplate; adopt standardized EdgeFunctionContext (supabase, user, span, requestId), and integrate built-in tracing, rate limiting, and logging through the wrapper. Update handlers to rely on wrapper context and ensure consistent error handling and observability.
This commit is contained in:
@@ -1,10 +1,7 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { rateLimiters, withRateLimit } from '../_shared/rateLimiter.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { sanitizeError } from '../_shared/errorSanitizer.ts';
|
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
|
||||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
|
||||||
|
|
||||||
interface ExportOptions {
|
interface ExportOptions {
|
||||||
include_reviews: boolean;
|
include_reviews: boolean;
|
||||||
@@ -14,76 +11,12 @@ interface ExportOptions {
|
|||||||
format: 'json';
|
format: 'json';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply strict rate limiting (5 req/min) for expensive data export operations
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
// This prevents abuse and manages server load from large data exports
|
addSpanEvent(span, 'processing_export_request', { userId: user.id });
|
||||||
serve(withRateLimit(async (req) => {
|
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
// Handle CORS preflight requests
|
// Additional rate limiting - max 1 export per hour
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, {
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseClient = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
||||||
{
|
|
||||||
global: {
|
|
||||||
headers: { Authorization: req.headers.get('Authorization')! },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Get authenticated user
|
|
||||||
const {
|
|
||||||
data: { user },
|
|
||||||
error: authError,
|
|
||||||
} = await supabaseClient.auth.getUser();
|
|
||||||
|
|
||||||
if (authError || !user) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Authentication failed', {
|
|
||||||
action: 'export_auth',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database
|
|
||||||
const authErrorSpan = startSpan('export-user-data-auth-error', 'SERVER');
|
|
||||||
endSpan(authErrorSpan, 'error', authError);
|
|
||||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
error: 'Unauthorized',
|
|
||||||
success: false,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 401,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Processing export request', {
|
|
||||||
action: 'export_start',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check rate limiting - max 1 export per hour
|
|
||||||
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
|
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
|
||||||
const { data: recentExports, error: rateLimitError } = await supabaseClient
|
const { data: recentExports, error: rateLimitError } = await supabase
|
||||||
.from('profile_audit_log')
|
.from('profile_audit_log')
|
||||||
.select('created_at')
|
.select('created_at')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -92,35 +25,21 @@ serve(withRateLimit(async (req) => {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (rateLimitError) {
|
if (rateLimitError) {
|
||||||
edgeLogger.error('Rate limit check failed', { action: 'export_rate_limit', requestId: tracking.requestId, error: rateLimitError });
|
addSpanEvent(span, 'rate_limit_check_failed', { error: rateLimitError.message });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (recentExports && recentExports.length > 0) {
|
if (recentExports && recentExports.length > 0) {
|
||||||
const duration = endRequest(tracking);
|
|
||||||
const nextAvailableAt = new Date(new Date(recentExports[0].created_at).getTime() + 60 * 60 * 1000).toISOString();
|
const nextAvailableAt = new Date(new Date(recentExports[0].created_at).getTime() + 60 * 60 * 1000).toISOString();
|
||||||
edgeLogger.warn('Rate limit exceeded for export', {
|
addSpanEvent(span, 'rate_limit_exceeded', { nextAvailableAt });
|
||||||
action: 'export_rate_limit',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
duration,
|
|
||||||
nextAvailableAt
|
|
||||||
});
|
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Rate limited. You can export your data once per hour.',
|
error: 'Rate limited. You can export your data once per hour.',
|
||||||
rate_limited: true,
|
rate_limited: true,
|
||||||
next_available_at: nextAvailableAt,
|
next_available_at: nextAvailableAt,
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
}),
|
||||||
{
|
{ status: 429 }
|
||||||
status: 429,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,40 +53,32 @@ serve(withRateLimit(async (req) => {
|
|||||||
format: 'json'
|
format: 'json'
|
||||||
};
|
};
|
||||||
|
|
||||||
edgeLogger.info('Export options', {
|
addSpanEvent(span, 'export_options_parsed', { options });
|
||||||
action: 'export_options',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch profile data
|
// Fetch profile data
|
||||||
const { data: profile, error: profileError } = await supabaseClient
|
const { data: profile, error: profileError } = await supabase
|
||||||
.from('profiles')
|
.from('profiles')
|
||||||
.select('username, display_name, bio, preferred_pronouns, personal_location, timezone, preferred_language, theme_preference, privacy_level, ride_count, coaster_count, park_count, review_count, reputation_score, created_at, updated_at')
|
.select('username, display_name, bio, preferred_pronouns, personal_location, timezone, preferred_language, theme_preference, privacy_level, ride_count, coaster_count, park_count, review_count, reputation_score, created_at, updated_at')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (profileError) {
|
if (profileError) {
|
||||||
edgeLogger.error('Profile fetch failed', {
|
addSpanEvent(span, 'profile_fetch_failed', { error: profileError.message });
|
||||||
action: 'export_profile',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
throw new Error('Failed to fetch profile data');
|
throw new Error('Failed to fetch profile data');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch statistics
|
// Fetch statistics
|
||||||
const { count: photoCount } = await supabaseClient
|
const { count: photoCount } = await supabase
|
||||||
.from('photos')
|
.from('photos')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('submitted_by', user.id);
|
.eq('submitted_by', user.id);
|
||||||
|
|
||||||
const { count: listCount } = await supabaseClient
|
const { count: listCount } = await supabase
|
||||||
.from('user_lists')
|
.from('user_lists')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('user_id', user.id);
|
.eq('user_id', user.id);
|
||||||
|
|
||||||
const { count: submissionCount } = await supabaseClient
|
const { count: submissionCount } = await supabase
|
||||||
.from('content_submissions')
|
.from('content_submissions')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('user_id', user.id);
|
.eq('user_id', user.id);
|
||||||
@@ -188,7 +99,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
// Fetch reviews if requested
|
// Fetch reviews if requested
|
||||||
let reviews = [];
|
let reviews = [];
|
||||||
if (options.include_reviews) {
|
if (options.include_reviews) {
|
||||||
const { data: reviewsData, error: reviewsError } = await supabaseClient
|
const { data: reviewsData, error: reviewsError } = await supabase
|
||||||
.from('reviews')
|
.from('reviews')
|
||||||
.select(`
|
.select(`
|
||||||
id,
|
id,
|
||||||
@@ -216,7 +127,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
// Fetch lists if requested
|
// Fetch lists if requested
|
||||||
let lists = [];
|
let lists = [];
|
||||||
if (options.include_lists) {
|
if (options.include_lists) {
|
||||||
const { data: listsData, error: listsError } = await supabaseClient
|
const { data: listsData, error: listsError } = await supabase
|
||||||
.from('user_lists')
|
.from('user_lists')
|
||||||
.select('id, name, description, is_public, created_at')
|
.select('id, name, description, is_public, created_at')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -225,7 +136,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
if (!listsError && listsData) {
|
if (!listsError && listsData) {
|
||||||
lists = await Promise.all(
|
lists = await Promise.all(
|
||||||
listsData.map(async (list) => {
|
listsData.map(async (list) => {
|
||||||
const { count } = await supabaseClient
|
const { count } = await supabase
|
||||||
.from('user_list_items')
|
.from('user_list_items')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('list_id', list.id);
|
.eq('list_id', list.id);
|
||||||
@@ -246,7 +157,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
// Fetch activity log if requested
|
// Fetch activity log if requested
|
||||||
let activity_log = [];
|
let activity_log = [];
|
||||||
if (options.include_activity_log) {
|
if (options.include_activity_log) {
|
||||||
const { data: activityData, error: activityError } = await supabaseClient
|
const { data: activityData, error: activityError } = await supabase
|
||||||
.from('profile_audit_log')
|
.from('profile_audit_log')
|
||||||
.select('id, action, changes, created_at, changed_by, ip_address_hash, user_agent')
|
.select('id, action, changes, created_at, changed_by, ip_address_hash, user_agent')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -267,7 +178,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (options.include_preferences) {
|
if (options.include_preferences) {
|
||||||
const { data: prefsData } = await supabaseClient
|
const { data: prefsData } = await supabase
|
||||||
.from('user_preferences')
|
.from('user_preferences')
|
||||||
.select('unit_preferences, accessibility_options, notification_preferences, privacy_settings')
|
.select('unit_preferences, accessibility_options, notification_preferences, privacy_settings')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -308,7 +219,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Log the export action
|
// Log the export action
|
||||||
await supabaseClient.from('profile_audit_log').insert([{
|
await supabase.from('profile_audit_log').insert([{
|
||||||
user_id: user.id,
|
user_id: user.id,
|
||||||
changed_by: user.id,
|
changed_by: user.id,
|
||||||
action: 'data_exported',
|
action: 'data_exported',
|
||||||
@@ -316,17 +227,11 @@ serve(withRateLimit(async (req) => {
|
|||||||
export_options: options,
|
export_options: options,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
data_size: JSON.stringify(exportData).length,
|
data_size: JSON.stringify(exportData).length,
|
||||||
requestId: tracking.requestId
|
requestId
|
||||||
}
|
}
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'export_completed', {
|
||||||
edgeLogger.info('Export completed successfully', {
|
|
||||||
action: 'export_complete',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
traceId: tracking.traceId,
|
|
||||||
userId: user.id,
|
|
||||||
duration,
|
|
||||||
dataSize: JSON.stringify(exportData).length
|
dataSize: JSON.stringify(exportData).length
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -334,47 +239,21 @@ serve(withRateLimit(async (req) => {
|
|||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: true,
|
success: true,
|
||||||
data: exportData,
|
data: exportData,
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
status: 200,
|
|
||||||
headers: {
|
headers: {
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Content-Disposition': `attachment; filename="thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json"`,
|
'Content-Disposition': `attachment; filename="thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json"`,
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
} catch (error) {
|
serve(createEdgeFunction({
|
||||||
const duration = endRequest(tracking);
|
name: 'export-user-data',
|
||||||
edgeLogger.error('Export error', {
|
requireAuth: true,
|
||||||
action: 'export_error',
|
corsHeaders,
|
||||||
requestId: tracking.requestId,
|
enableTracing: true,
|
||||||
duration,
|
logRequests: true,
|
||||||
error: formatEdgeError(error)
|
logResponses: true,
|
||||||
});
|
rateLimitTier: 'strict', // 5 requests per minute
|
||||||
|
}, handler));
|
||||||
// Persist error to database for monitoring
|
|
||||||
const errorSpan = startSpan('export-user-data-error', 'SERVER');
|
|
||||||
endSpan(errorSpan, 'error', error);
|
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
|
||||||
const sanitized = sanitizeError(error, 'export-user-data');
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
...sanitized,
|
|
||||||
success: false,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 500,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, rateLimiters.strict, corsHeaders));
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
|
||||||
interface RequestBody {
|
interface RequestBody {
|
||||||
submission_id: string;
|
submission_id: string;
|
||||||
@@ -81,21 +81,15 @@ async function constructEntityURL(
|
|||||||
return `${baseURL}`;
|
return `${baseURL}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
const tracking = startRequest('notify-user-submission-status');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
||||||
|
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
|
||||||
|
|
||||||
const { submission_id, user_id, submission_type, status, reviewer_notes } = await req.json() as RequestBody;
|
const { submission_id, user_id, submission_type, status, reviewer_notes } = await req.json() as RequestBody;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'notification_request', {
|
||||||
|
submissionId: submission_id,
|
||||||
|
userId: user_id,
|
||||||
|
status
|
||||||
|
});
|
||||||
|
|
||||||
// Fetch submission items to get entity data
|
// Fetch submission items to get entity data
|
||||||
const { data: items, error: itemsError } = await supabase
|
const { data: items, error: itemsError } = await supabase
|
||||||
.from('submission_items')
|
.from('submission_items')
|
||||||
@@ -126,7 +120,6 @@ serve(async (req) => {
|
|||||||
let payload: Record<string, string>;
|
let payload: Record<string, string>;
|
||||||
|
|
||||||
if (status === 'approved') {
|
if (status === 'approved') {
|
||||||
// Approval payload
|
|
||||||
payload = {
|
payload = {
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
entityType,
|
entityType,
|
||||||
@@ -136,7 +129,6 @@ serve(async (req) => {
|
|||||||
moderationNotes: reviewer_notes || '',
|
moderationNotes: reviewer_notes || '',
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// Rejection payload
|
|
||||||
payload = {
|
payload = {
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
rejectionReason: reviewer_notes || 'No reason provided',
|
rejectionReason: reviewer_notes || 'No reason provided',
|
||||||
@@ -172,42 +164,22 @@ serve(async (req) => {
|
|||||||
is_duplicate: true
|
is_duplicate: true
|
||||||
}).eq('id', existingLog.id);
|
}).eq('id', existingLog.id);
|
||||||
|
|
||||||
edgeLogger.info('Duplicate notification prevented', {
|
addSpanEvent(span, 'duplicate_notification_prevented', {
|
||||||
action: 'notify_user_submission_status',
|
|
||||||
userId: user_id,
|
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
submissionId: submission_id,
|
submissionId: submission_id
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
endRequest(tracking, 200);
|
return {
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Duplicate notification prevented',
|
message: 'Duplicate notification prevented',
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
requestId: tracking.requestId
|
};
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Sending notification to user', {
|
addSpanEvent(span, 'sending_notification', {
|
||||||
action: 'notify_user_submission_status',
|
|
||||||
userId: user_id,
|
|
||||||
workflowId,
|
workflowId,
|
||||||
entityName,
|
entityName,
|
||||||
status,
|
idempotencyKey
|
||||||
idempotencyKey,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Call trigger-notification function
|
// Call trigger-notification function
|
||||||
@@ -239,45 +211,21 @@ serve(async (req) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
edgeLogger.info('User notification sent successfully', { action: 'notify_user_submission_status', requestId: tracking.requestId, result: notificationResult });
|
addSpanEvent(span, 'notification_sent', {
|
||||||
|
transactionId: notificationResult?.transactionId
|
||||||
|
});
|
||||||
|
|
||||||
endRequest(tracking, 200);
|
return {
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
transactionId: notificationResult?.transactionId,
|
transactionId: notificationResult?.transactionId,
|
||||||
requestId: tracking.requestId
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
||||||
edgeLogger.error('Error notifying user about submission status', { action: 'notify_user_submission_status', requestId: tracking.requestId, error: errorMessage });
|
|
||||||
|
|
||||||
endRequest(tracking, 500, errorMessage);
|
serve(createEdgeFunction({
|
||||||
|
name: 'notify-user-submission-status',
|
||||||
return new Response(
|
requireAuth: false,
|
||||||
JSON.stringify({
|
useServiceRole: true,
|
||||||
success: false,
|
corsHeaders,
|
||||||
error: errorMessage,
|
enableTracing: true,
|
||||||
requestId: tracking.requestId
|
logRequests: true,
|
||||||
}),
|
}, handler));
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,63 +1,13 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { rateLimiters, withRateLimit } from '../_shared/rateLimiter.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
|
||||||
|
|
||||||
// Apply moderate rate limiting (10 req/min) to prevent deletion code spam
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
// Protects against abuse while allowing legitimate resend requests
|
addSpanEvent(span, 'resending_deletion_code', { userId: user.id });
|
||||||
serve(withRateLimit(async (req) => {
|
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, {
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseClient = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
||||||
{
|
|
||||||
global: {
|
|
||||||
headers: { Authorization: req.headers.get('Authorization')! },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Get authenticated user
|
|
||||||
const {
|
|
||||||
data: { user },
|
|
||||||
error: userError,
|
|
||||||
} = await supabaseClient.auth.getUser();
|
|
||||||
|
|
||||||
if (userError || !user) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Authentication failed', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database
|
|
||||||
const authErrorSpan = startSpan('resend-deletion-code-auth-error', 'SERVER');
|
|
||||||
endSpan(authErrorSpan, 'error', userError);
|
|
||||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
|
||||||
throw new Error('Unauthorized');
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Resending deletion code for user', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Find pending deletion request
|
// Find pending deletion request
|
||||||
const { data: deletionRequest, error: requestError } = await supabaseClient
|
const { data: deletionRequest, error: requestError } = await supabase
|
||||||
.from('account_deletion_requests')
|
.from('account_deletion_requests')
|
||||||
.select('*')
|
.select('*')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -68,17 +18,21 @@ serve(withRateLimit(async (req) => {
|
|||||||
throw new Error('No pending deletion request found');
|
throw new Error('No pending deletion request found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check rate limiting (max 3 resends per hour)
|
// Check rate limiting (max 3 resends per hour - ~20 minutes between resends)
|
||||||
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
|
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
|
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
|
||||||
|
|
||||||
if (hoursSinceLastSend < 0.33) { // ~20 minutes between resends
|
if (hoursSinceLastSend < 0.33) {
|
||||||
|
addSpanEvent(span, 'resend_rate_limited', {
|
||||||
|
hoursSinceLastSend,
|
||||||
|
minRequired: 0.33
|
||||||
|
});
|
||||||
throw new Error('Please wait at least 20 minutes between resend requests');
|
throw new Error('Please wait at least 20 minutes between resend requests');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate new confirmation code
|
// Generate new confirmation code
|
||||||
const { data: codeData, error: codeError } = await supabaseClient
|
const { data: codeData, error: codeError } = await supabase
|
||||||
.rpc('generate_deletion_confirmation_code');
|
.rpc('generate_deletion_confirmation_code');
|
||||||
|
|
||||||
if (codeError) {
|
if (codeError) {
|
||||||
@@ -88,7 +42,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
const confirmationCode = codeData as string;
|
const confirmationCode = codeData as string;
|
||||||
|
|
||||||
// Update deletion request with new code
|
// Update deletion request with new code
|
||||||
const { error: updateError } = await supabaseClient
|
const { error: updateError } = await supabase
|
||||||
.from('account_deletion_requests')
|
.from('account_deletion_requests')
|
||||||
.update({
|
.update({
|
||||||
confirmation_code: confirmationCode,
|
confirmation_code: confirmationCode,
|
||||||
@@ -102,6 +56,10 @@ serve(withRateLimit(async (req) => {
|
|||||||
|
|
||||||
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
|
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
|
||||||
|
|
||||||
|
addSpanEvent(span, 'new_code_generated', {
|
||||||
|
scheduledDeletionDate: scheduledDate.toISOString()
|
||||||
|
});
|
||||||
|
|
||||||
// Send email with new code
|
// Send email with new code
|
||||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||||
@@ -130,64 +88,27 @@ serve(withRateLimit(async (req) => {
|
|||||||
`,
|
`,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
edgeLogger.info('New confirmation code email sent', { requestId: tracking.requestId });
|
addSpanEvent(span, 'email_sent', { email: user.email });
|
||||||
} catch (emailError) {
|
} catch (emailError) {
|
||||||
edgeLogger.error('Failed to send email', {
|
addSpanEvent(span, 'email_send_failed', {
|
||||||
requestId: tracking.requestId,
|
error: emailError instanceof Error ? emailError.message : String(emailError)
|
||||||
error: emailError.message
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'resend_completed', { userId: user.id });
|
||||||
edgeLogger.info('New confirmation code sent successfully', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'New confirmation code sent successfully',
|
message: 'New confirmation code sent successfully',
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Error resending code', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: error.message
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database for monitoring
|
serve(createEdgeFunction({
|
||||||
const errorSpan = startSpan('resend-deletion-code-error', 'SERVER');
|
name: 'resend-deletion-code',
|
||||||
endSpan(errorSpan, 'error', error);
|
requireAuth: true,
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
corsHeaders,
|
||||||
return new Response(
|
enableTracing: true,
|
||||||
JSON.stringify({
|
logRequests: true,
|
||||||
error: error.message,
|
rateLimitTier: 'moderate', // 10 requests per minute
|
||||||
requestId: tracking.requestId
|
}, handler));
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 400,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, rateLimiters.moderate, corsHeaders));
|
|
||||||
|
|||||||
Reference in New Issue
Block a user