Compare commits

...

3 Commits

Author SHA1 Message Date
gpt-engineer-app[bot]
96b7594738 Migrate Phase 2 admin edges
Migrate five admin/moderator edge functions (merge-contact-tickets, send-escalation-notification, notify-moderators-report, notify-moderators-submission, send-password-added-email) to use createEdgeFunction wrapper. Remove manual CORS, auth, service-client setup, logging, and error handling. Implement handler with EdgeFunctionContext, apply appropriate wrapper config (requireAuth, requiredRoles/useServiceRole, corsEnabled, enableTracing, rateLimitTier). Replace edgeLogger with span events, maintain core business logic and retry/email integration patterns.
2025-11-11 20:39:10 +00:00
gpt-engineer-app[bot]
8ee548fd27 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.
2025-11-11 20:35:45 +00:00
gpt-engineer-app[bot]
de921a5fcf Migrate remaining edge functions to wrapper
Refactor process-expired-bans, detect-location, detect-anomalies, rate-limit-metrics, and collect-metrics to use createEdgeFunction wrapper with standardized error handling, tracing, and reduced boilerplate. Update signatures to receive { supabase, span, requestId } (and user where applicable), replace manual logging with span events, remove per-function boilerplate, and ensure consistent wrapper configuration (cors, auth, rate limits, and tracing).
2025-11-11 20:30:24 +00:00
13 changed files with 1505 additions and 2300 deletions

View File

@@ -1,6 +1,7 @@
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { corsHeaders } from '../_shared/cors.ts';
interface MetricRecord {
metric_name: string;
@@ -9,13 +10,8 @@ interface MetricRecord {
timestamp: string;
}
export default createEdgeFunction(
{
name: 'collect-metrics',
requireAuth: false,
},
async (req, context, supabase) => {
edgeLogger.info('Starting metrics collection', { requestId: context.requestId });
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
addSpanEvent(span, 'starting_metrics_collection', { requestId });
const metrics: MetricRecord[] = [];
const timestamp = new Date().toISOString();
@@ -151,27 +147,24 @@ export default createEdgeFunction(
.from('metric_time_series')
.insert(metrics);
if (insertError) {
edgeLogger.error('Error inserting metrics', {
error: insertError,
requestId: context.requestId
});
throw insertError;
}
edgeLogger.info('Successfully recorded metrics', {
count: metrics.length,
requestId: context.requestId
});
if (insertError) {
addSpanEvent(span, 'error_inserting_metrics', { error: insertError.message });
throw insertError;
}
return new Response(
JSON.stringify({
success: true,
metrics_collected: metrics.length,
metrics: metrics.map(m => ({ name: m.metric_name, value: m.metric_value })),
}),
{ headers: { 'Content-Type': 'application/json' } }
);
addSpanEvent(span, 'metrics_recorded', { count: metrics.length });
}
);
return {
success: true,
metrics_collected: metrics.length,
metrics: metrics.map(m => ({ name: m.metric_name, value: m.metric_value })),
};
};
serve(createEdgeFunction({
name: 'collect-metrics',
requireAuth: false,
corsHeaders,
enableTracing: true,
}, handler));

View File

@@ -1,6 +1,7 @@
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { corsHeaders } from '../_shared/cors.ts';
interface MetricData {
timestamp: string;
@@ -288,13 +289,8 @@ class AnomalyDetector {
}
}
export default createEdgeFunction(
{
name: 'detect-anomalies',
requireAuth: false,
},
async (req, context, supabase) => {
edgeLogger.info('Starting anomaly detection run', { requestId: context.requestId });
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
addSpanEvent(span, 'starting_anomaly_detection', { requestId });
// Get all enabled anomaly detection configurations
const { data: configs, error: configError } = await supabase
@@ -303,14 +299,11 @@ export default createEdgeFunction(
.eq('enabled', true);
if (configError) {
console.error('Error fetching configs:', configError);
addSpanEvent(span, 'error_fetching_configs', { error: configError.message });
throw configError;
}
edgeLogger.info('Processing metric configurations', {
count: configs?.length || 0,
requestId: context.requestId
});
addSpanEvent(span, 'processing_metric_configs', { count: configs?.length || 0 });
const anomaliesDetected: any[] = [];
@@ -327,17 +320,19 @@ export default createEdgeFunction(
.order('timestamp', { ascending: true });
if (metricError) {
console.error(`Error fetching metric data for ${config.metric_name}:`, metricError);
addSpanEvent(span, 'error_fetching_metric_data', {
metric: config.metric_name,
error: metricError.message
});
continue;
}
const data = metricData as MetricData[];
if (!data || data.length < config.min_data_points) {
edgeLogger.info('Insufficient data for metric', {
addSpanEvent(span, 'insufficient_data', {
metric: config.metric_name,
points: data?.length || 0,
requestId: context.requestId
points: data?.length || 0
});
continue;
}
@@ -421,7 +416,10 @@ export default createEdgeFunction(
.single();
if (anomalyError) {
console.error(`Error inserting anomaly for ${config.metric_name}:`, anomalyError);
addSpanEvent(span, 'error_inserting_anomaly', {
metric: config.metric_name,
error: anomalyError.message
});
continue;
}
@@ -453,29 +451,39 @@ export default createEdgeFunction(
.update({ alert_created: true, alert_id: alert.id })
.eq('id', anomaly.id);
console.log(`Created alert for anomaly in ${config.metric_name}`);
addSpanEvent(span, 'alert_created', {
metric: config.metric_name,
alertId: alert.id
});
}
}
console.log(`Anomaly detected: ${config.metric_name} - ${bestResult.anomalyType} (${bestResult.deviationScore.toFixed(2)}σ)`);
addSpanEvent(span, 'anomaly_detected', {
metric: config.metric_name,
type: bestResult.anomalyType,
deviation: bestResult.deviationScore.toFixed(2)
});
}
} catch (error) {
console.error(`Error processing metric ${config.metric_name}:`, error);
addSpanEvent(span, 'error_processing_metric', {
metric: config.metric_name,
error: error instanceof Error ? error.message : String(error)
});
}
}
edgeLogger.info('Anomaly detection complete', {
detected: anomaliesDetected.length,
requestId: context.requestId
});
addSpanEvent(span, 'anomaly_detection_complete', { detected: anomaliesDetected.length });
return new Response(
JSON.stringify({
success: true,
anomalies_detected: anomaliesDetected.length,
anomalies: anomaliesDetected,
}),
{ headers: { 'Content-Type': 'application/json' } }
);
}
);
return {
success: true,
anomalies_detected: anomaliesDetected.length,
anomalies: anomaliesDetected,
};
};
serve(createEdgeFunction({
name: 'detect-anomalies',
requireAuth: false,
corsHeaders,
enableTracing: true,
}, handler));

View File

@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from "../_shared/logger.ts";
import { formatEdgeError } from "../_shared/errorFormatter.ts";
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import { addSpanEvent } from '../_shared/logger.ts';
interface IPLocationResponse {
country: string;
@@ -11,86 +11,47 @@ interface IPLocationResponse {
// Simple in-memory rate limiter
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
const RATE_LIMIT_WINDOW = 60000; // 1 minute in milliseconds
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const MAX_REQUESTS = 10; // 10 requests per minute per IP
const MAX_MAP_SIZE = 10000; // Maximum number of IPs to track
const MAX_MAP_SIZE = 10000;
// Cleanup failure tracking to prevent silent failures
let cleanupFailureCount = 0;
const MAX_CLEANUP_FAILURES = 5; // Threshold before forcing drastic cleanup
const CLEANUP_FAILURE_RESET_INTERVAL = 300000; // Reset failure count every 5 minutes
const MAX_CLEANUP_FAILURES = 5;
const CLEANUP_FAILURE_RESET_INTERVAL = 300000; // 5 minutes
function cleanupExpiredEntries() {
try {
const now = Date.now();
let deletedCount = 0;
const mapSizeBefore = rateLimitMap.size;
for (const [ip, data] of rateLimitMap.entries()) {
if (now > data.resetAt) {
rateLimitMap.delete(ip);
deletedCount++;
}
}
// Cleanup runs silently unless there are issues
if (cleanupFailureCount > 0) {
cleanupFailureCount = 0;
}
} catch (error: unknown) {
// CRITICAL: Increment failure counter and log detailed error information
cleanupFailureCount++;
const errorMessage = formatEdgeError(error);
edgeLogger.error('Cleanup error', {
attempt: cleanupFailureCount,
maxAttempts: MAX_CLEANUP_FAILURES,
error: errorMessage,
mapSize: rateLimitMap.size
});
// FALLBACK MECHANISM: If cleanup fails repeatedly, force clear to prevent memory leak
if (cleanupFailureCount >= MAX_CLEANUP_FAILURES) {
edgeLogger.error('Cleanup critical - forcing emergency cleanup', {
consecutiveFailures: cleanupFailureCount,
mapSize: rateLimitMap.size
});
try {
// Emergency: Clear oldest 50% of entries to prevent unbounded growth
const entriesToClear = Math.floor(rateLimitMap.size * 0.5);
const sortedEntries = Array.from(rateLimitMap.entries())
.sort((a, b) => a[1].resetAt - b[1].resetAt);
let clearedCount = 0;
for (let i = 0; i < entriesToClear && i < sortedEntries.length; i++) {
rateLimitMap.delete(sortedEntries[i][0]);
clearedCount++;
}
edgeLogger.warn('Emergency cleanup completed', { clearedCount, newMapSize: rateLimitMap.size });
// Reset failure count after emergency cleanup
cleanupFailureCount = 0;
} catch (emergencyError) {
// Last resort: If even emergency cleanup fails, clear everything
const originalSize = rateLimitMap.size;
} catch {
rateLimitMap.clear();
edgeLogger.error('Emergency cleanup failed - cleared entire map', {
originalSize,
error: emergencyError instanceof Error ? emergencyError.message : String(emergencyError)
});
cleanupFailureCount = 0;
}
}
}
}
// Reset cleanup failure count periodically to avoid permanent emergency state
setInterval(() => {
if (cleanupFailureCount > 0) {
cleanupFailureCount = 0;
@@ -101,7 +62,6 @@ function checkRateLimit(ip: string): { allowed: boolean; retryAfter?: number } {
const now = Date.now();
const existing = rateLimitMap.get(ip);
// Handle existing entries (most common case - early return for performance)
if (existing && now <= existing.resetAt) {
if (existing.count >= MAX_REQUESTS) {
const retryAfter = Math.ceil((existing.resetAt - now) / 1000);
@@ -111,213 +71,108 @@ function checkRateLimit(ip: string): { allowed: boolean; retryAfter?: number } {
return { allowed: true };
}
// Need to add new entry or reset expired one
// Only perform cleanup if we're at capacity AND adding a new IP
if (!existing && rateLimitMap.size >= MAX_MAP_SIZE) {
// First try cleaning expired entries
cleanupExpiredEntries();
// If still at capacity after cleanup, remove oldest entries (LRU eviction)
if (rateLimitMap.size >= MAX_MAP_SIZE) {
try {
const toDelete = Math.floor(MAX_MAP_SIZE * 0.3); // Remove 30% of entries
const toDelete = Math.floor(MAX_MAP_SIZE * 0.3);
const sortedEntries = Array.from(rateLimitMap.entries())
.sort((a, b) => a[1].resetAt - b[1].resetAt);
let deletedCount = 0;
for (let i = 0; i < toDelete && i < sortedEntries.length; i++) {
rateLimitMap.delete(sortedEntries[i][0]);
deletedCount++;
}
edgeLogger.warn('Rate limit map at capacity - evicted entries', {
maxSize: MAX_MAP_SIZE,
deletedCount,
newSize: rateLimitMap.size
});
} catch (evictionError) {
// CRITICAL: LRU eviction failed - log error and attempt emergency clear
edgeLogger.error('LRU eviction failed', {
error: evictionError instanceof Error ? evictionError.message : String(evictionError),
mapSize: rateLimitMap.size
});
try {
// Emergency: Clear first 30% of entries without sorting
const targetSize = Math.floor(MAX_MAP_SIZE * 0.7);
const keysToDelete: string[] = [];
for (const [key] of rateLimitMap.entries()) {
if (rateLimitMap.size <= targetSize) break;
keysToDelete.push(key);
}
keysToDelete.forEach(key => rateLimitMap.delete(key));
edgeLogger.warn('Emergency eviction completed', {
clearedCount: keysToDelete.length,
newSize: rateLimitMap.size
});
} catch (emergencyError) {
edgeLogger.error('Emergency eviction failed - clearing entire map', {
error: emergencyError instanceof Error ? emergencyError.message : String(emergencyError)
});
rateLimitMap.clear();
}
} catch {
rateLimitMap.clear();
}
}
}
// Create new entry or reset expired entry
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
return { allowed: true };
}
// Clean up old entries periodically to prevent memory leak
// Run cleanup more frequently to catch expired entries sooner
setInterval(cleanupExpiredEntries, Math.min(RATE_LIMIT_WINDOW / 2, 30000)); // Every 30 seconds or half the window
setInterval(cleanupExpiredEntries, Math.min(RATE_LIMIT_WINDOW / 2, 30000));
serve(async (req) => {
// Handle CORS preflight requests
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
const tracking = startRequest('detect-location');
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)
}
}
);
}
// PII Note: Do not log full IP addresses in production
edgeLogger.info('Detecting location for request', { requestId: tracking.requestId });
// 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) {
edgeLogger.error('Network error fetching location data', {
error: fetchError instanceof Error ? fetchError.message : String(fetchError),
requestId: tracking.requestId
});
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) {
edgeLogger.error('Failed to parse geolocation response', {
error: parseError instanceof Error ? parseError.message : String(parseError),
requestId: tracking.requestId
});
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
};
edgeLogger.info('Location detected', {
country: result.country,
countryCode: result.countryCode,
measurementSystem: result.measurementSystem,
requestId: tracking.requestId
});
endRequest(tracking);
return new Response(
JSON.stringify({ ...result, requestId: tracking.requestId }),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
}
}
);
} catch (error: unknown) {
// Enhanced error logging for better visibility and debugging
const errorMessage = formatEdgeError(error);
edgeLogger.error('Location detection error', {
error: errorMessage,
requestId: tracking.requestId
});
// Persist error to database for monitoring
const errorSpan = startSpan('detect-location-error', 'SERVER');
endSpan(errorSpan, 'error', error);
logSpanToDatabase(errorSpan, tracking.requestId);
endRequest(tracking);
// 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'
};
const handler = async (req: Request, { span, requestId }: EdgeFunctionContext) => {
// Get client IP
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';
// Check rate limit
const rateLimit = checkRateLimit(clientIP);
if (!rateLimit.allowed) {
addSpanEvent(span, 'rate_limit_exceeded', { clientIP: clientIP.substring(0, 8) + '...' });
return new Response(
JSON.stringify({
...defaultResult,
error: errorMessage,
fallback: true,
requestId: tracking.requestId
error: 'Rate limit exceeded',
message: 'Too many requests. Please try again later.',
retryAfter: rateLimit.retryAfter
}),
{
status: 429,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 500
'Retry-After': String(rateLimit.retryAfter || 60)
}
}
);
}
});
addSpanEvent(span, 'detecting_location', { requestId });
// Use configurable geolocation service
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) {
addSpanEvent(span, 'network_error', { error: fetchError instanceof Error ? fetchError.message : String(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) {
addSpanEvent(span, 'parse_error', { error: parseError instanceof Error ? parseError.message : String(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'];
const measurementSystem = imperialCountries.includes(geoData.countryCode) ? 'imperial' : 'metric';
const result: IPLocationResponse = {
country: geoData.country,
countryCode: geoData.countryCode,
measurementSystem
};
addSpanEvent(span, 'location_detected', {
country: result.country,
countryCode: result.countryCode,
measurementSystem: result.measurementSystem
});
return result;
};
serve(createEdgeFunction({
name: 'detect-location',
requireAuth: false,
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));

View File

@@ -1,10 +1,7 @@
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import { rateLimiters, withRateLimit } from '../_shared/rateLimiter.ts';
import { sanitizeError } from '../_shared/errorSanitizer.ts';
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
import { formatEdgeError } from '../_shared/errorFormatter.ts';
import { addSpanEvent } from '../_shared/logger.ts';
interface ExportOptions {
include_reviews: boolean;
@@ -14,367 +11,249 @@ interface ExportOptions {
format: 'json';
}
// Apply strict rate limiting (5 req/min) for expensive data export operations
// This prevents abuse and manages server load from large data exports
serve(withRateLimit(async (req) => {
const tracking = startRequest();
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
addSpanEvent(span, 'processing_export_request', { userId: user.id });
// Handle CORS preflight requests
if (req.method === 'OPTIONS') {
return new Response(null, {
headers: {
...corsHeaders,
'X-Request-ID': tracking.requestId
}
});
// Additional rate limiting - max 1 export per hour
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
const { data: recentExports, error: rateLimitError } = await supabase
.from('profile_audit_log')
.select('created_at')
.eq('user_id', user.id)
.eq('action', 'data_exported')
.gte('created_at', oneHourAgo)
.limit(1);
if (rateLimitError) {
addSpanEvent(span, 'rate_limit_check_failed', { error: rateLimitError.message });
}
try {
const supabaseClient = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
{
global: {
headers: { Authorization: req.headers.get('Authorization')! },
},
}
if (recentExports && recentExports.length > 0) {
const nextAvailableAt = new Date(new Date(recentExports[0].created_at).getTime() + 60 * 60 * 1000).toISOString();
addSpanEvent(span, 'rate_limit_exceeded', { nextAvailableAt });
return new Response(
JSON.stringify({
success: false,
error: 'Rate limited. You can export your data once per hour.',
rate_limited: true,
next_available_at: nextAvailableAt,
}),
{ status: 429 }
);
}
// Get authenticated user
const {
data: { user },
error: authError,
} = await supabaseClient.auth.getUser();
// Parse export options
const body = await req.json();
const options: ExportOptions = {
include_reviews: body.include_reviews ?? true,
include_lists: body.include_lists ?? true,
include_activity_log: body.include_activity_log ?? true,
include_preferences: body.include_preferences ?? true,
format: 'json'
};
if (authError || !user) {
const duration = endRequest(tracking);
edgeLogger.error('Authentication failed', {
action: 'export_auth',
requestId: tracking.requestId,
duration
});
addSpanEvent(span, 'export_options_parsed', { options });
// 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
}
}
);
}
// Fetch profile data
const { data: profile, error: profileError } = await supabase
.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')
.eq('user_id', user.id)
.single();
edgeLogger.info('Processing export request', {
action: 'export_start',
requestId: tracking.requestId,
userId: user.id
});
if (profileError) {
addSpanEvent(span, 'profile_fetch_failed', { error: profileError.message });
throw new Error('Failed to fetch profile data');
}
// Check rate limiting - max 1 export per hour
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
const { data: recentExports, error: rateLimitError } = await supabaseClient
.from('profile_audit_log')
.select('created_at')
// Fetch statistics
const { count: photoCount } = await supabase
.from('photos')
.select('*', { count: 'exact', head: true })
.eq('submitted_by', user.id);
const { count: listCount } = await supabase
.from('user_lists')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id);
const { count: submissionCount } = await supabase
.from('content_submissions')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id);
const statistics = {
ride_count: profile.ride_count || 0,
coaster_count: profile.coaster_count || 0,
park_count: profile.park_count || 0,
review_count: profile.review_count || 0,
reputation_score: profile.reputation_score || 0,
photo_count: photoCount || 0,
list_count: listCount || 0,
submission_count: submissionCount || 0,
account_created: profile.created_at,
last_updated: profile.updated_at
};
// Fetch reviews if requested
let reviews = [];
if (options.include_reviews) {
const { data: reviewsData, error: reviewsError } = await supabase
.from('reviews')
.select(`
id,
rating,
review_text,
created_at,
rides(name),
parks(name)
`)
.eq('user_id', user.id)
.eq('action', 'data_exported')
.gte('created_at', oneHourAgo)
.limit(1);
.order('created_at', { ascending: false });
if (rateLimitError) {
edgeLogger.error('Rate limit check failed', { action: 'export_rate_limit', requestId: tracking.requestId, error: rateLimitError });
if (!reviewsError && reviewsData) {
reviews = reviewsData.map(r => ({
id: r.id,
rating: r.rating,
review_text: r.review_text,
ride_name: r.rides?.name,
park_name: r.parks?.name,
created_at: r.created_at
}));
}
}
if (recentExports && recentExports.length > 0) {
const duration = endRequest(tracking);
const nextAvailableAt = new Date(new Date(recentExports[0].created_at).getTime() + 60 * 60 * 1000).toISOString();
edgeLogger.warn('Rate limit exceeded for export', {
action: 'export_rate_limit',
requestId: tracking.requestId,
userId: user.id,
duration,
nextAvailableAt
});
return new Response(
JSON.stringify({
success: false,
error: 'Rate limited. You can export your data once per hour.',
rate_limited: true,
next_available_at: nextAvailableAt,
requestId: tracking.requestId
}),
{
status: 429,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
}
}
// Fetch lists if requested
let lists = [];
if (options.include_lists) {
const { data: listsData, error: listsError } = await supabase
.from('user_lists')
.select('id, name, description, is_public, created_at')
.eq('user_id', user.id)
.order('created_at', { ascending: false });
if (!listsError && listsData) {
lists = await Promise.all(
listsData.map(async (list) => {
const { count } = await supabase
.from('user_list_items')
.select('*', { count: 'exact', head: true })
.eq('list_id', list.id);
return {
id: list.id,
name: list.name,
description: list.description,
is_public: list.is_public,
item_count: count || 0,
created_at: list.created_at
};
})
);
}
}
// Parse export options
const body = await req.json();
const options: ExportOptions = {
include_reviews: body.include_reviews ?? true,
include_lists: body.include_lists ?? true,
include_activity_log: body.include_activity_log ?? true,
include_preferences: body.include_preferences ?? true,
format: 'json'
};
// Fetch activity log if requested
let activity_log = [];
if (options.include_activity_log) {
const { data: activityData, error: activityError } = await supabase
.from('profile_audit_log')
.select('id, action, changes, created_at, changed_by, ip_address_hash, user_agent')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
.limit(100);
edgeLogger.info('Export options', {
action: 'export_options',
requestId: tracking.requestId,
userId: user.id
});
if (!activityError && activityData) {
activity_log = activityData;
}
}
// Fetch profile data
const { data: profile, error: profileError } = await supabaseClient
.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')
// Fetch preferences if requested
let preferences = {
unit_preferences: null,
accessibility_options: null,
notification_preferences: null,
privacy_settings: null
};
if (options.include_preferences) {
const { data: prefsData } = await supabase
.from('user_preferences')
.select('unit_preferences, accessibility_options, notification_preferences, privacy_settings')
.eq('user_id', user.id)
.single();
if (profileError) {
edgeLogger.error('Profile fetch failed', {
action: 'export_profile',
requestId: tracking.requestId,
userId: user.id
});
throw new Error('Failed to fetch profile data');
if (prefsData) {
preferences = prefsData;
}
// Fetch statistics
const { count: photoCount } = await supabaseClient
.from('photos')
.select('*', { count: 'exact', head: true })
.eq('submitted_by', user.id);
const { count: listCount } = await supabaseClient
.from('user_lists')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id);
const { count: submissionCount } = await supabaseClient
.from('content_submissions')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id);
const statistics = {
ride_count: profile.ride_count || 0,
coaster_count: profile.coaster_count || 0,
park_count: profile.park_count || 0,
review_count: profile.review_count || 0,
reputation_score: profile.reputation_score || 0,
photo_count: photoCount || 0,
list_count: listCount || 0,
submission_count: submissionCount || 0,
account_created: profile.created_at,
last_updated: profile.updated_at
};
// Fetch reviews if requested
let reviews = [];
if (options.include_reviews) {
const { data: reviewsData, error: reviewsError } = await supabaseClient
.from('reviews')
.select(`
id,
rating,
review_text,
created_at,
rides(name),
parks(name)
`)
.eq('user_id', user.id)
.order('created_at', { ascending: false });
if (!reviewsError && reviewsData) {
reviews = reviewsData.map(r => ({
id: r.id,
rating: r.rating,
review_text: r.review_text,
ride_name: r.rides?.name,
park_name: r.parks?.name,
created_at: r.created_at
}));
}
}
// Fetch lists if requested
let lists = [];
if (options.include_lists) {
const { data: listsData, error: listsError } = await supabaseClient
.from('user_lists')
.select('id, name, description, is_public, created_at')
.eq('user_id', user.id)
.order('created_at', { ascending: false });
if (!listsError && listsData) {
lists = await Promise.all(
listsData.map(async (list) => {
const { count } = await supabaseClient
.from('user_list_items')
.select('*', { count: 'exact', head: true })
.eq('list_id', list.id);
return {
id: list.id,
name: list.name,
description: list.description,
is_public: list.is_public,
item_count: count || 0,
created_at: list.created_at
};
})
);
}
}
// Fetch activity log if requested
let activity_log = [];
if (options.include_activity_log) {
const { data: activityData, error: activityError } = await supabaseClient
.from('profile_audit_log')
.select('id, action, changes, created_at, changed_by, ip_address_hash, user_agent')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
.limit(100);
if (!activityError && activityData) {
activity_log = activityData;
}
}
// Fetch preferences if requested
let preferences = {
unit_preferences: null,
accessibility_options: null,
notification_preferences: null,
privacy_settings: null
};
if (options.include_preferences) {
const { data: prefsData } = await supabaseClient
.from('user_preferences')
.select('unit_preferences, accessibility_options, notification_preferences, privacy_settings')
.eq('user_id', user.id)
.single();
if (prefsData) {
preferences = prefsData;
}
}
// Build export data structure
const exportData = {
export_date: new Date().toISOString(),
user_id: user.id,
profile: {
username: profile.username,
display_name: profile.display_name,
bio: profile.bio,
preferred_pronouns: profile.preferred_pronouns,
personal_location: profile.personal_location,
timezone: profile.timezone,
preferred_language: profile.preferred_language,
theme_preference: profile.theme_preference,
privacy_level: profile.privacy_level,
created_at: profile.created_at,
updated_at: profile.updated_at
},
statistics,
reviews,
lists,
activity_log,
preferences,
metadata: {
export_version: '1.0.0',
data_retention_info: 'Your data is retained according to our privacy policy. You can request deletion at any time from your account settings.',
instructions: 'This file contains all your personal data stored in ThrillWiki. You can use this for backup purposes or to migrate to another service. For questions, contact support@thrillwiki.com'
}
};
// Log the export action
await supabaseClient.from('profile_audit_log').insert([{
user_id: user.id,
changed_by: user.id,
action: 'data_exported',
changes: {
export_options: options,
timestamp: new Date().toISOString(),
data_size: JSON.stringify(exportData).length,
requestId: tracking.requestId
}
}]);
const duration = endRequest(tracking);
edgeLogger.info('Export completed successfully', {
action: 'export_complete',
requestId: tracking.requestId,
traceId: tracking.traceId,
userId: user.id,
duration,
dataSize: JSON.stringify(exportData).length
});
return new Response(
JSON.stringify({
success: true,
data: exportData,
requestId: tracking.requestId
}),
{
status: 200,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'Content-Disposition': `attachment; filename="thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json"`,
'X-Request-ID': tracking.requestId
}
}
);
} catch (error) {
const duration = endRequest(tracking);
edgeLogger.error('Export error', {
action: 'export_error',
requestId: tracking.requestId,
duration,
error: formatEdgeError(error)
});
// 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));
// Build export data structure
const exportData = {
export_date: new Date().toISOString(),
user_id: user.id,
profile: {
username: profile.username,
display_name: profile.display_name,
bio: profile.bio,
preferred_pronouns: profile.preferred_pronouns,
personal_location: profile.personal_location,
timezone: profile.timezone,
preferred_language: profile.preferred_language,
theme_preference: profile.theme_preference,
privacy_level: profile.privacy_level,
created_at: profile.created_at,
updated_at: profile.updated_at
},
statistics,
reviews,
lists,
activity_log,
preferences,
metadata: {
export_version: '1.0.0',
data_retention_info: 'Your data is retained according to our privacy policy. You can request deletion at any time from your account settings.',
instructions: 'This file contains all your personal data stored in ThrillWiki. You can use this for backup purposes or to migrate to another service. For questions, contact support@thrillwiki.com'
}
};
// Log the export action
await supabase.from('profile_audit_log').insert([{
user_id: user.id,
changed_by: user.id,
action: 'data_exported',
changes: {
export_options: options,
timestamp: new Date().toISOString(),
data_size: JSON.stringify(exportData).length,
requestId
}
}]);
addSpanEvent(span, 'export_completed', {
dataSize: JSON.stringify(exportData).length
});
return new Response(
JSON.stringify({
success: true,
data: exportData,
}),
{
headers: {
'Content-Disposition': `attachment; filename="thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json"`,
}
}
);
};
serve(createEdgeFunction({
name: 'export-user-data',
requireAuth: true,
corsHeaders,
enableTracing: true,
logRequests: true,
logResponses: true,
rateLimitTier: 'strict', // 5 requests per minute
}, handler));

View File

@@ -1,8 +1,7 @@
import { serve } from 'https://deno.land/std@0.168.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 { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
import { createErrorResponse, sanitizeError } from '../_shared/errorSanitizer.ts';
import { addSpanEvent } from '../_shared/logger.ts';
interface MergeTicketsRequest {
primaryTicketId: string;
@@ -18,273 +17,189 @@ interface MergeTicketsResponse {
deletedTickets: string[];
}
serve(async (req) => {
const tracking = startRequest();
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
// Parse request body
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
// Validation
if (!primaryTicketId || !mergeTicketIds || mergeTicketIds.length === 0) {
throw new Error('Invalid request: primaryTicketId and mergeTicketIds required');
}
try {
const authHeader = req.headers.get('Authorization');
if (!authHeader) {
throw new Error('Missing authorization header');
}
const supabase = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
{ global: { headers: { Authorization: authHeader } } }
);
// Authenticate user
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
throw new Error('Unauthorized');
}
edgeLogger.info('Merge tickets request started', {
requestId: tracking.requestId,
userId: user.id,
});
// Check if user has moderator/admin role
const { data: hasRole, error: roleError } = await supabase.rpc('has_role', {
_user_id: user.id,
_role: 'moderator'
});
const { data: isAdmin, error: adminError } = await supabase.rpc('has_role', {
_user_id: user.id,
_role: 'admin'
});
const { data: isSuperuser, error: superuserError } = await supabase.rpc('has_role', {
_user_id: user.id,
_role: 'superuser'
});
if (roleError || adminError || superuserError || (!hasRole && !isAdmin && !isSuperuser)) {
throw new Error('Insufficient permissions. Moderator role required.');
}
// Parse request body
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
// Validation
if (!primaryTicketId || !mergeTicketIds || mergeTicketIds.length === 0) {
throw new Error('Invalid request: primaryTicketId and mergeTicketIds required');
}
if (mergeTicketIds.includes(primaryTicketId)) {
throw new Error('Cannot merge a ticket into itself');
}
if (mergeTicketIds.length > 10) {
throw new Error('Maximum 10 tickets can be merged at once');
}
// Start transaction-like operations
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
// Fetch all tickets
const { data: tickets, error: fetchError } = await supabase
.from('contact_submissions')
.select('id, ticket_number, admin_notes, merged_ticket_numbers')
.in('id', allTicketIds);
if (fetchError) throw fetchError;
if (!tickets || tickets.length !== allTicketIds.length) {
throw new Error('One or more tickets not found');
}
const primaryTicket = tickets.find(t => t.id === primaryTicketId);
const mergeTickets = tickets.filter(t => mergeTicketIds.includes(t.id));
if (!primaryTicket) {
throw new Error('Primary ticket not found');
}
// Check if any ticket already has merged_ticket_numbers (prevent re-merging)
const alreadyMerged = tickets.find(t =>
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
);
if (alreadyMerged) {
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
}
edgeLogger.info('Starting merge process', {
requestId: tracking.requestId,
primaryTicket: primaryTicket.ticket_number,
mergeTicketCount: mergeTickets.length,
});
// Step 1: Move all email threads to primary ticket
edgeLogger.info('Step 1: Moving email threads', {
requestId: tracking.requestId,
fromTickets: mergeTickets.map(t => t.ticket_number)
});
const { data: movedThreads, error: moveError } = await supabase
.from('contact_email_threads')
.update({ submission_id: primaryTicketId })
.in('submission_id', mergeTicketIds)
.select('id');
if (moveError) throw moveError;
const threadsMovedCount = movedThreads?.length || 0;
edgeLogger.info('Threads moved successfully', {
requestId: tracking.requestId,
threadsMovedCount
});
if (threadsMovedCount === 0) {
edgeLogger.warn('No email threads found to move', {
requestId: tracking.requestId,
mergeTicketIds
});
}
// Step 2: Consolidate admin notes
edgeLogger.info('Step 2: Consolidating admin notes', { requestId: tracking.requestId });
let consolidatedNotes = primaryTicket.admin_notes || '';
for (const ticket of mergeTickets) {
if (ticket.admin_notes) {
consolidatedNotes = consolidatedNotes.trim()
? `${consolidatedNotes}\n\n${ticket.admin_notes}`
: ticket.admin_notes;
}
}
// Step 3: Recalculate metadata from consolidated threads
edgeLogger.info('Step 3: Recalculating metadata from threads', { requestId: tracking.requestId });
const { data: threadStats, error: statsError } = await supabase
.from('contact_email_threads')
.select('direction, created_at')
.eq('submission_id', primaryTicketId);
if (statsError) throw statsError;
const outboundCount = threadStats?.filter(t => t.direction === 'outbound').length || 0;
const lastAdminResponse = threadStats
?.filter(t => t.direction === 'outbound')
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
const lastUserResponse = threadStats
?.filter(t => t.direction === 'inbound')
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
edgeLogger.info('Metadata recalculated', {
requestId: tracking.requestId,
outboundCount,
lastAdminResponse,
lastUserResponse
});
// Get merged ticket numbers
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
// Step 4: Update primary ticket with consolidated data
edgeLogger.info('Step 4: Updating primary ticket', { requestId: tracking.requestId });
const { error: updateError } = await supabase
.from('contact_submissions')
.update({
admin_notes: consolidatedNotes,
response_count: outboundCount,
last_admin_response_at: lastAdminResponse || null,
merged_ticket_numbers: [
...(primaryTicket.merged_ticket_numbers || []),
...mergedTicketNumbers
],
updated_at: new Date().toISOString(),
})
.eq('id', primaryTicketId);
if (updateError) throw updateError;
edgeLogger.info('Primary ticket updated successfully', { requestId: tracking.requestId });
// Step 5: Delete merged tickets
edgeLogger.info('Step 5: Deleting merged tickets', {
requestId: tracking.requestId,
ticketsToDelete: mergeTicketIds.length
});
const { error: deleteError } = await supabase
.from('contact_submissions')
.delete()
.in('id', mergeTicketIds);
if (deleteError) throw deleteError;
edgeLogger.info('Merged tickets deleted successfully', { requestId: tracking.requestId });
// Step 6: Audit log
edgeLogger.info('Step 6: Creating audit log', { requestId: tracking.requestId });
const { error: auditError } = await supabase.from('admin_audit_log').insert({
admin_user_id: user.id,
target_user_id: user.id, // No specific target user for this action
action: 'merge_contact_tickets',
details: {
primary_ticket_id: primaryTicketId,
primary_ticket_number: primaryTicket.ticket_number,
merged_ticket_ids: mergeTicketIds,
merged_ticket_numbers: mergedTicketNumbers,
merge_reason: mergeReason || null,
threads_moved: threadsMovedCount,
merged_count: mergeTickets.length,
}
});
if (auditError) {
edgeLogger.warn('Failed to create audit log for merge', {
requestId: tracking.requestId,
error: auditError.message,
primaryTicket: primaryTicket.ticket_number
});
// Don't throw - merge already succeeded
}
const duration = endRequest(tracking);
edgeLogger.info('Merge tickets completed successfully', {
requestId: tracking.requestId,
duration,
primaryTicket: primaryTicket.ticket_number,
mergedCount: mergeTickets.length,
});
const response: MergeTicketsResponse = {
success: true,
primaryTicketNumber: primaryTicket.ticket_number,
mergedCount: mergeTickets.length,
threadsConsolidated: threadsMovedCount,
deletedTickets: mergedTicketNumbers,
};
return new Response(JSON.stringify(response), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
});
} catch (error) {
const duration = endRequest(tracking);
edgeLogger.error('Merge tickets failed', {
requestId: tracking.requestId,
duration,
error: error instanceof Error ? error.message : 'Unknown error',
});
// Persist error to database for monitoring
const errorSpan = startSpan('merge-contact-tickets-error', 'SERVER');
endSpan(errorSpan, 'error', error);
logSpanToDatabase(errorSpan, tracking.requestId);
return createErrorResponse(error, 500, corsHeaders, 'merge_contact_tickets');
if (mergeTicketIds.includes(primaryTicketId)) {
throw new Error('Cannot merge a ticket into itself');
}
});
if (mergeTicketIds.length > 10) {
throw new Error('Maximum 10 tickets can be merged at once');
}
addSpanEvent(span, 'merge_tickets_started', {
primaryTicketId,
mergeCount: mergeTicketIds.length
});
// Start transaction-like operations
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
// Fetch all tickets
const { data: tickets, error: fetchError } = await supabase
.from('contact_submissions')
.select('id, ticket_number, admin_notes, merged_ticket_numbers')
.in('id', allTicketIds);
if (fetchError) throw fetchError;
if (!tickets || tickets.length !== allTicketIds.length) {
throw new Error('One or more tickets not found');
}
const primaryTicket = tickets.find(t => t.id === primaryTicketId);
const mergeTickets = tickets.filter(t => mergeTicketIds.includes(t.id));
if (!primaryTicket) {
throw new Error('Primary ticket not found');
}
// Check if any ticket already has merged_ticket_numbers
const alreadyMerged = tickets.find(t =>
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
);
if (alreadyMerged) {
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
}
addSpanEvent(span, 'tickets_validated', {
primaryTicket: primaryTicket.ticket_number,
mergeTicketCount: mergeTickets.length
});
// Step 1: Move all email threads to primary ticket
addSpanEvent(span, 'moving_email_threads', {
fromTickets: mergeTickets.map(t => t.ticket_number)
});
const { data: movedThreads, error: moveError } = await supabase
.from('contact_email_threads')
.update({ submission_id: primaryTicketId })
.in('submission_id', mergeTicketIds)
.select('id');
if (moveError) throw moveError;
const threadsMovedCount = movedThreads?.length || 0;
addSpanEvent(span, 'threads_moved', { threadsMovedCount });
if (threadsMovedCount === 0) {
addSpanEvent(span, 'no_threads_found', { mergeTicketIds });
}
// Step 2: Consolidate admin notes
let consolidatedNotes = primaryTicket.admin_notes || '';
for (const ticket of mergeTickets) {
if (ticket.admin_notes) {
consolidatedNotes = consolidatedNotes.trim()
? `${consolidatedNotes}\n\n${ticket.admin_notes}`
: ticket.admin_notes;
}
}
// Step 3: Recalculate metadata from consolidated threads
const { data: threadStats, error: statsError } = await supabase
.from('contact_email_threads')
.select('direction, created_at')
.eq('submission_id', primaryTicketId);
if (statsError) throw statsError;
const outboundCount = threadStats?.filter(t => t.direction === 'outbound').length || 0;
const lastAdminResponse = threadStats
?.filter(t => t.direction === 'outbound')
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
const lastUserResponse = threadStats
?.filter(t => t.direction === 'inbound')
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
addSpanEvent(span, 'metadata_recalculated', {
outboundCount,
lastAdminResponse,
lastUserResponse
});
// Get merged ticket numbers
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
// Step 4: Update primary ticket with consolidated data
const { error: updateError } = await supabase
.from('contact_submissions')
.update({
admin_notes: consolidatedNotes,
response_count: outboundCount,
last_admin_response_at: lastAdminResponse || null,
merged_ticket_numbers: [
...(primaryTicket.merged_ticket_numbers || []),
...mergedTicketNumbers
],
updated_at: new Date().toISOString(),
})
.eq('id', primaryTicketId);
if (updateError) throw updateError;
addSpanEvent(span, 'primary_ticket_updated', { primaryTicket: primaryTicket.ticket_number });
// Step 5: Delete merged tickets
const { error: deleteError } = await supabase
.from('contact_submissions')
.delete()
.in('id', mergeTicketIds);
if (deleteError) throw deleteError;
addSpanEvent(span, 'merged_tickets_deleted', { count: mergeTicketIds.length });
// Step 6: Audit log
const { error: auditError } = await supabase.from('admin_audit_log').insert({
admin_user_id: user.id,
target_user_id: user.id,
action: 'merge_contact_tickets',
details: {
primary_ticket_id: primaryTicketId,
primary_ticket_number: primaryTicket.ticket_number,
merged_ticket_ids: mergeTicketIds,
merged_ticket_numbers: mergedTicketNumbers,
merge_reason: mergeReason || null,
threads_moved: threadsMovedCount,
merged_count: mergeTickets.length,
}
});
if (auditError) {
addSpanEvent(span, 'audit_log_failed', { error: auditError.message });
}
addSpanEvent(span, 'merge_completed', {
primaryTicket: primaryTicket.ticket_number,
mergedCount: mergeTickets.length
});
const response: MergeTicketsResponse = {
success: true,
primaryTicketNumber: primaryTicket.ticket_number,
mergedCount: mergeTickets.length,
threadsConsolidated: threadsMovedCount,
deletedTickets: mergedTicketNumbers,
};
return response;
};
serve(createEdgeFunction({
name: 'merge-contact-tickets',
requireAuth: true,
requiredRoles: ['superuser', 'admin', 'moderator'],
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));

View File

@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { withEdgeRetry } from '../_shared/retryHelper.ts';
interface NotificationPayload {
@@ -15,204 +15,166 @@ interface NotificationPayload {
entityPreview: string;
}
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
const payload: NotificationPayload = await req.json();
addSpanEvent(span, 'processing_report_notification', {
reportId: payload.reportId,
reportType: payload.reportType,
reportedEntityType: payload.reportedEntityType
});
// Calculate relative time
const reportedAt = new Date(payload.reportedAt);
const now = new Date();
const diffMs = now.getTime() - reportedAt.getTime();
const diffMins = Math.floor(diffMs / 60000);
let relativeTime: string;
if (diffMins < 1) {
relativeTime = 'just now';
} else if (diffMins < 60) {
relativeTime = `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
} else {
const diffHours = Math.floor(diffMins / 60);
relativeTime = `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
}
const tracking = startRequest('notify-moderators-report');
// Determine priority based on report type and age
let priority: string;
const criticalTypes = ['harassment', 'offensive'];
const isUrgent = diffMins < 5;
try {
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
if (criticalTypes.includes(payload.reportType) || isUrgent) {
priority = 'high';
} else if (diffMins < 30) {
priority = 'medium';
} else {
priority = 'low';
}
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Fetch the workflow ID for report alerts
const { data: template, error: templateError } = await supabase
.from('notification_templates')
.select('workflow_id')
.eq('workflow_id', 'report-alert')
.eq('is_active', true)
.maybeSingle();
const payload: NotificationPayload = await req.json();
edgeLogger.info('Processing report notification', {
action: 'notify_moderators_report',
reportId: payload.reportId,
reportType: payload.reportType,
reportedEntityType: payload.reportedEntityType,
requestId: tracking.requestId
});
// Calculate relative time
const reportedAt = new Date(payload.reportedAt);
const now = new Date();
const diffMs = now.getTime() - reportedAt.getTime();
const diffMins = Math.floor(diffMs / 60000);
let relativeTime: string;
if (diffMins < 1) {
relativeTime = 'just now';
} else if (diffMins < 60) {
relativeTime = `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
} else {
const diffHours = Math.floor(diffMins / 60);
relativeTime = `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
}
// Determine priority based on report type and age
let priority: string;
const criticalTypes = ['harassment', 'offensive'];
const isUrgent = diffMins < 5;
if (criticalTypes.includes(payload.reportType) || isUrgent) {
priority = 'high';
} else if (diffMins < 30) {
priority = 'medium';
} else {
priority = 'low';
}
// Fetch the workflow ID for report alerts
const { data: template, error: templateError } = await supabase
.from('notification_templates')
.select('workflow_id')
.eq('workflow_id', 'report-alert')
.eq('is_active', true)
.maybeSingle();
if (templateError) {
edgeLogger.error('Error fetching workflow', { action: 'notify_moderators_report', requestId: tracking.requestId, error: templateError });
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
}
if (!template) {
edgeLogger.warn('No active report-alert workflow found', { action: 'notify_moderators_report', requestId: tracking.requestId });
return new Response(
JSON.stringify({
success: false,
error: 'No active report-alert workflow configured',
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
// Fetch reported entity name
let reportedEntityName = 'Unknown';
try {
if (payload.reportedEntityType === 'review') {
const { data: review } = await supabase
.from('reviews')
.select('ride:rides(name), park:parks(name)')
.eq('id', payload.reportedEntityId)
.maybeSingle();
reportedEntityName = review?.ride?.name || review?.park?.name || 'Review';
} else if (payload.reportedEntityType === 'profile') {
const { data: profile } = await supabase
.from('profiles')
.select('display_name, username')
.eq('user_id', payload.reportedEntityId)
.maybeSingle();
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
} else if (payload.reportedEntityType === 'content_submission') {
// Query submission_metadata table for the name instead of dropped content JSONB column
const { data: metadata } = await supabase
.from('submission_metadata')
.select('metadata_value')
.eq('submission_id', payload.reportedEntityId)
.eq('metadata_key', 'name')
.maybeSingle();
reportedEntityName = metadata?.metadata_value || 'Submission';
}
} catch (error) {
edgeLogger.warn('Could not fetch entity name', { action: 'notify_moderators_report', requestId: tracking.requestId, error });
}
// Build enhanced notification payload
const notificationPayload = {
baseUrl: 'https://www.thrillwiki.com',
reportId: payload.reportId,
reportType: payload.reportType,
reportedEntityType: payload.reportedEntityType,
reportedEntityId: payload.reportedEntityId,
reporterName: payload.reporterName,
reason: payload.reason,
entityPreview: payload.entityPreview,
reportedEntityName,
reportedAt: payload.reportedAt,
relativeTime,
priority,
};
edgeLogger.info('Triggering notification with payload', { action: 'notify_moderators_report', requestId: tracking.requestId });
// Invoke the trigger-notification function with retry
const result = await withEdgeRetry(
async () => {
const { data, error } = await supabase.functions.invoke(
'trigger-notification',
{
body: {
workflowId: template.workflow_id,
topicKey: 'moderation-reports',
payload: notificationPayload,
},
}
);
if (error) {
const enhancedError = new Error(error.message || 'Notification trigger failed');
(enhancedError as any).status = error.status;
throw enhancedError;
}
return data;
},
{ maxAttempts: 3, baseDelay: 1000 },
tracking.requestId,
'trigger-report-notification'
);
edgeLogger.info('Notification triggered successfully', { action: 'notify_moderators_report', requestId: tracking.requestId, result });
endRequest(tracking, 200);
return new Response(
JSON.stringify({
success: true,
transactionId: result?.transactionId,
payload: notificationPayload,
requestId: tracking.requestId
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 200,
}
);
} catch (error: any) {
edgeLogger.error('Error in notify-moderators-report', { action: 'notify_moderators_report', requestId: tracking.requestId, error: error.message });
endRequest(tracking, 500, error.message);
if (templateError) {
addSpanEvent(span, 'workflow_fetch_failed', { error: templateError.message });
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
}
if (!template) {
addSpanEvent(span, 'no_active_workflow', {});
return new Response(
JSON.stringify({
success: false,
error: error.message,
requestId: tracking.requestId
error: 'No active report-alert workflow configured',
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 500,
}
{ status: 400 }
);
}
});
// Fetch reported entity name
let reportedEntityName = 'Unknown';
try {
if (payload.reportedEntityType === 'review') {
const { data: review } = await supabase
.from('reviews')
.select('ride:rides(name), park:parks(name)')
.eq('id', payload.reportedEntityId)
.maybeSingle();
reportedEntityName = review?.ride?.name || review?.park?.name || 'Review';
} else if (payload.reportedEntityType === 'profile') {
const { data: profile } = await supabase
.from('profiles')
.select('display_name, username')
.eq('user_id', payload.reportedEntityId)
.maybeSingle();
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
} else if (payload.reportedEntityType === 'content_submission') {
const { data: metadata } = await supabase
.from('submission_metadata')
.select('metadata_value')
.eq('submission_id', payload.reportedEntityId)
.eq('metadata_key', 'name')
.maybeSingle();
reportedEntityName = metadata?.metadata_value || 'Submission';
}
} catch (error) {
addSpanEvent(span, 'entity_name_fetch_failed', {
error: error instanceof Error ? error.message : String(error)
});
}
// Build enhanced notification payload
const notificationPayload = {
baseUrl: 'https://www.thrillwiki.com',
reportId: payload.reportId,
reportType: payload.reportType,
reportedEntityType: payload.reportedEntityType,
reportedEntityId: payload.reportedEntityId,
reporterName: payload.reporterName,
reason: payload.reason,
entityPreview: payload.entityPreview,
reportedEntityName,
reportedAt: payload.reportedAt,
relativeTime,
priority,
};
addSpanEvent(span, 'triggering_notification', {
workflowId: template.workflow_id,
priority
});
// Invoke the trigger-notification function with retry
const result = await withEdgeRetry(
async () => {
const { data, error } = await supabase.functions.invoke(
'trigger-notification',
{
body: {
workflowId: template.workflow_id,
topicKey: 'moderation-reports',
payload: notificationPayload,
},
}
);
if (error) {
const enhancedError = new Error(error.message || 'Notification trigger failed');
(enhancedError as any).status = error.status;
throw enhancedError;
}
return data;
},
{ maxAttempts: 3, baseDelay: 1000 },
requestId,
'trigger-report-notification'
);
addSpanEvent(span, 'notification_sent', { transactionId: result?.transactionId });
return {
success: true,
transactionId: result?.transactionId,
payload: notificationPayload,
};
};
serve(createEdgeFunction({
name: 'notify-moderators-report',
requireAuth: false,
useServiceRole: true,
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));

View File

@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { withEdgeRetry } from '../_shared/retryHelper.ts';
interface NotificationPayload {
@@ -16,275 +16,177 @@ interface NotificationPayload {
is_escalated: boolean;
}
serve(async (req) => {
const tracking = startRequest();
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
const payload: NotificationPayload = await req.json();
const {
submission_id,
submission_type,
submitter_name,
action,
content_preview,
submitted_at,
has_photos,
item_count,
is_escalated
} = payload;
if (req.method === 'OPTIONS') {
return new Response(null, {
headers: {
...corsHeaders,
'X-Request-ID': tracking.requestId
}
});
addSpanEvent(span, 'processing_moderator_notification', {
submission_id,
submission_type
});
// Calculate relative time and priority
const submittedDate = new Date(submitted_at);
const now = new Date();
const waitTimeMs = now.getTime() - submittedDate.getTime();
const waitTimeHours = waitTimeMs / (1000 * 60 * 60);
// Format relative time
const relativeTime = (() => {
const minutes = Math.floor(waitTimeMs / (1000 * 60));
const hours = Math.floor(waitTimeMs / (1000 * 60 * 60));
const days = Math.floor(waitTimeMs / (1000 * 60 * 60 * 24));
if (minutes < 1) return 'just now';
if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
return `${days} day${days !== 1 ? 's' : ''} ago`;
})();
// Determine priority based on wait time
const priority = waitTimeHours >= 24 ? 'urgent' : 'normal';
// Get the moderation-alert workflow
const { data: workflow, error: workflowError } = await supabase
.from('notification_templates')
.select('workflow_id')
.eq('category', 'moderation')
.eq('is_active', true)
.single();
if (workflowError || !workflow) {
addSpanEvent(span, 'workflow_fetch_failed', { error: workflowError?.message });
throw new Error('Workflow not found or not active');
}
try {
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
const payload: NotificationPayload = await req.json();
const {
submission_id,
submission_type,
submitter_name,
action,
content_preview,
submitted_at,
has_photos,
item_count,
is_escalated
} = payload;
edgeLogger.info('Notifying moderators about submission via topic', {
action: 'notify_moderators',
requestId: tracking.requestId,
submission_id,
submission_type,
content_preview
// Generate idempotency key for duplicate prevention
const { data: keyData, error: keyError } = await supabase
.rpc('generate_notification_idempotency_key', {
p_notification_type: 'moderation_submission',
p_entity_id: submission_id,
p_recipient_id: '00000000-0000-0000-0000-000000000000',
p_event_data: { submission_type, action }
});
// Calculate relative time and priority
const submittedDate = new Date(submitted_at);
const now = new Date();
const waitTimeMs = now.getTime() - submittedDate.getTime();
const waitTimeHours = waitTimeMs / (1000 * 60 * 60);
const idempotencyKey = keyData || `mod_sub_${submission_id}_${Date.now()}`;
// Format relative time
const relativeTime = (() => {
const minutes = Math.floor(waitTimeMs / (1000 * 60));
const hours = Math.floor(waitTimeMs / (1000 * 60 * 60));
const days = Math.floor(waitTimeMs / (1000 * 60 * 60 * 24));
// Check for duplicate within 24h window
const { data: existingLog, error: logCheckError } = await supabase
.from('notification_logs')
.select('id')
.eq('idempotency_key', idempotencyKey)
.gte('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
.maybeSingle();
if (minutes < 1) return 'just now';
if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
return `${days} day${days !== 1 ? 's' : ''} ago`;
})();
if (existingLog) {
// Duplicate detected
await supabase.from('notification_logs').update({
is_duplicate: true
}).eq('id', existingLog.id);
// Determine priority based on wait time
const priority = waitTimeHours >= 24 ? 'urgent' : 'normal';
addSpanEvent(span, 'duplicate_notification_prevented', {
idempotencyKey,
submission_id
});
// Get the moderation-alert workflow
const { data: workflow, error: workflowError } = await supabase
.from('notification_templates')
.select('workflow_id')
.eq('category', 'moderation')
.eq('is_active', true)
.single();
if (workflowError || !workflow) {
const duration = endRequest(tracking);
edgeLogger.error('Error fetching workflow', {
action: 'notify_moderators',
requestId: tracking.requestId,
duration,
error: workflowError
});
return new Response(
JSON.stringify({
success: false,
error: 'Workflow not found or not active',
requestId: tracking.requestId
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 500,
}
);
}
// Generate idempotency key for duplicate prevention
const { data: keyData, error: keyError } = await supabase
.rpc('generate_notification_idempotency_key', {
p_notification_type: 'moderation_submission',
p_entity_id: submission_id,
p_recipient_id: '00000000-0000-0000-0000-000000000000', // Topic-based, use placeholder
p_event_data: { submission_type, action }
});
const idempotencyKey = keyData || `mod_sub_${submission_id}_${Date.now()}`;
// Check for duplicate within 24h window
const { data: existingLog, error: logCheckError } = await supabase
.from('notification_logs')
.select('id')
.eq('idempotency_key', idempotencyKey)
.gte('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
.maybeSingle();
if (existingLog) {
// Duplicate detected - log and skip
await supabase.from('notification_logs').update({
is_duplicate: true
}).eq('id', existingLog.id);
edgeLogger.info('Duplicate notification prevented', {
action: 'notify_moderators',
requestId: tracking.requestId,
idempotencyKey,
submission_id
});
return new Response(
JSON.stringify({
success: true,
message: 'Duplicate notification prevented',
idempotencyKey,
requestId: tracking.requestId,
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 200,
}
);
}
// Prepare enhanced notification payload
const notificationPayload = {
baseUrl: 'https://www.thrillwiki.com',
// Basic info
itemType: submission_type,
submitterName: submitter_name,
submissionId: submission_id,
action: action || 'create',
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
// Enhanced content
contentPreview: content_preview,
// Timing information
submittedAt: submitted_at,
relativeTime: relativeTime,
priority: priority,
// Additional metadata
hasPhotos: has_photos,
itemCount: item_count,
isEscalated: is_escalated,
return {
success: true,
message: 'Duplicate notification prevented',
idempotencyKey,
};
// Send ONE notification to the moderation-submissions topic with retry
// All subscribers (moderators) will receive it automatically
const data = await withEdgeRetry(
async () => {
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
body: {
workflowId: workflow.workflow_id,
topicKey: 'moderation-submissions',
payload: notificationPayload,
},
});
if (error) {
const enhancedError = new Error(error.message || 'Notification trigger failed');
(enhancedError as any).status = error.status;
throw enhancedError;
}
return result;
},
{ maxAttempts: 3, baseDelay: 1000 },
tracking.requestId,
'trigger-submission-notification'
);
// Log notification in notification_logs with idempotency key
const { error: logError } = await supabase.from('notification_logs').insert({
user_id: '00000000-0000-0000-0000-000000000000', // Topic-based
notification_type: 'moderation_submission',
idempotency_key: idempotencyKey,
is_duplicate: false,
metadata: {
submission_id,
submission_type,
transaction_id: data?.transactionId
}
});
if (logError) {
// Non-blocking - notification was sent successfully, log failure shouldn't fail the request
edgeLogger.warn('Failed to log notification in notification_logs', {
action: 'notify_moderators',
requestId: tracking.requestId,
error: logError.message,
submissionId: submission_id
});
}
const duration = endRequest(tracking);
edgeLogger.info('Successfully notified all moderators via topic', {
action: 'notify_moderators',
requestId: tracking.requestId,
traceId: tracking.traceId,
duration,
transactionId: data?.transactionId
});
return new Response(
JSON.stringify({
success: true,
message: 'Moderator notifications sent via topic',
topicKey: 'moderation-submissions',
transactionId: data?.transactionId,
requestId: tracking.requestId,
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 200,
}
);
} catch (error: any) {
const duration = endRequest(tracking);
edgeLogger.error('Error in notify-moderators-submission', {
action: 'notify_moderators',
requestId: tracking.requestId,
duration,
error: error.message
});
// Persist error to database for monitoring
const errorSpan = startSpan('notify-moderators-submission-error', 'SERVER');
endSpan(errorSpan, 'error', error);
logSpanToDatabase(errorSpan, tracking.requestId);
return new Response(
JSON.stringify({
success: false,
error: error.message,
requestId: tracking.requestId,
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 500,
}
);
}
});
// Prepare enhanced notification payload
const notificationPayload = {
baseUrl: 'https://www.thrillwiki.com',
itemType: submission_type,
submitterName: submitter_name,
submissionId: submission_id,
action: action || 'create',
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
contentPreview: content_preview,
submittedAt: submitted_at,
relativeTime: relativeTime,
priority: priority,
hasPhotos: has_photos,
itemCount: item_count,
isEscalated: is_escalated,
};
addSpanEvent(span, 'triggering_notification', {
workflowId: workflow.workflow_id,
priority
});
// Send ONE notification to the moderation-submissions topic with retry
const data = await withEdgeRetry(
async () => {
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
body: {
workflowId: workflow.workflow_id,
topicKey: 'moderation-submissions',
payload: notificationPayload,
},
});
if (error) {
const enhancedError = new Error(error.message || 'Notification trigger failed');
(enhancedError as any).status = error.status;
throw enhancedError;
}
return result;
},
{ maxAttempts: 3, baseDelay: 1000 },
requestId,
'trigger-submission-notification'
);
// Log notification with idempotency key
const { error: logError } = await supabase.from('notification_logs').insert({
user_id: '00000000-0000-0000-0000-000000000000',
notification_type: 'moderation_submission',
idempotency_key: idempotencyKey,
is_duplicate: false,
metadata: {
submission_id,
submission_type,
transaction_id: data?.transactionId
}
});
if (logError) {
addSpanEvent(span, 'log_insertion_failed', { error: logError.message });
}
addSpanEvent(span, 'notification_sent', {
transactionId: data?.transactionId,
topicKey: 'moderation-submissions'
});
return {
success: true,
message: 'Moderator notifications sent via topic',
topicKey: 'moderation-submissions',
transactionId: data?.transactionId,
};
};
serve(createEdgeFunction({
name: 'notify-moderators-submission',
requireAuth: false,
useServiceRole: true,
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));

View File

@@ -1,7 +1,7 @@
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 { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import { addSpanEvent } from '../_shared/logger.ts';
interface RequestBody {
submission_id: string;
@@ -81,203 +81,151 @@ async function constructEntityURL(
return `${baseURL}`;
}
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
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
const { data: items, error: itemsError } = await supabase
.from('submission_items')
.select('item_data')
.eq('submission_id', submission_id)
.order('order_index', { ascending: true })
.limit(1)
.maybeSingle();
if (itemsError) {
throw new Error(`Failed to fetch submission items: ${itemsError.message}`);
}
const tracking = startRequest('notify-user-submission-status');
if (!items || !items.item_data) {
throw new Error('No submission items found');
}
try {
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
// Extract entity data
const entityName = items.item_data.name || 'your submission';
const entityType = submission_type.replace('_', ' ');
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Construct entity URL
const entityURL = await constructEntityURL(supabase, submission_type, items.item_data);
const { submission_id, user_id, submission_type, status, reviewer_notes } = await req.json() as RequestBody;
// Determine workflow and build payload based on status
const workflowId = status === 'approved' ? 'submission-approved' : 'submission-rejected';
// Fetch submission items to get entity data
const { data: items, error: itemsError } = await supabase
.from('submission_items')
.select('item_data')
.eq('submission_id', submission_id)
.order('order_index', { ascending: true })
.limit(1)
.maybeSingle();
let payload: Record<string, string>;
if (itemsError) {
throw new Error(`Failed to fetch submission items: ${itemsError.message}`);
}
if (!items || !items.item_data) {
throw new Error('No submission items found');
}
// Extract entity data
const entityName = items.item_data.name || 'your submission';
const entityType = submission_type.replace('_', ' ');
// Construct entity URL
const entityURL = await constructEntityURL(supabase, submission_type, items.item_data);
// Determine workflow and build payload based on status
const workflowId = status === 'approved' ? 'submission-approved' : 'submission-rejected';
let payload: Record<string, string>;
if (status === 'approved') {
// Approval payload
payload = {
baseUrl: 'https://www.thrillwiki.com',
entityType,
entityName,
submissionId: submission_id,
entityURL,
moderationNotes: reviewer_notes || '',
};
} else {
// Rejection payload
payload = {
baseUrl: 'https://www.thrillwiki.com',
rejectionReason: reviewer_notes || 'No reason provided',
entityType,
entityName,
entityURL,
actualStatus: 'rejected',
};
}
// Generate idempotency key for duplicate prevention
const { data: keyData, error: keyError } = await supabase
.rpc('generate_notification_idempotency_key', {
p_notification_type: `submission_${status}`,
p_entity_id: submission_id,
p_recipient_id: user_id,
});
const idempotencyKey = keyData || `user_sub_${submission_id}_${user_id}_${status}_${Date.now()}`;
// Check for duplicate within 24h window
const { data: existingLog, error: logCheckError } = await supabase
.from('notification_logs')
.select('id')
.eq('user_id', user_id)
.eq('idempotency_key', idempotencyKey)
.gte('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
.maybeSingle();
if (existingLog) {
// Duplicate detected - log and skip
await supabase.from('notification_logs').update({
is_duplicate: true
}).eq('id', existingLog.id);
edgeLogger.info('Duplicate notification prevented', {
action: 'notify_user_submission_status',
userId: user_id,
idempotencyKey,
submissionId: submission_id,
requestId: tracking.requestId
});
endRequest(tracking, 200);
return new Response(
JSON.stringify({
success: true,
message: 'Duplicate notification prevented',
idempotencyKey,
requestId: tracking.requestId
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 200,
}
);
}
edgeLogger.info('Sending notification to user', {
action: 'notify_user_submission_status',
userId: user_id,
workflowId,
if (status === 'approved') {
payload = {
baseUrl: 'https://www.thrillwiki.com',
entityType,
entityName,
status,
idempotencyKey,
requestId: tracking.requestId
});
// Call trigger-notification function
const { data: notificationResult, error: notificationError } = await supabase.functions.invoke(
'trigger-notification',
{
body: {
workflowId,
subscriberId: user_id,
payload,
},
}
);
if (notificationError) {
throw new Error(`Failed to trigger notification: ${notificationError.message}`);
}
// Log notification in notification_logs with idempotency key
await supabase.from('notification_logs').insert({
user_id,
notification_type: `submission_${status}`,
idempotency_key: idempotencyKey,
is_duplicate: false,
metadata: {
submission_id,
submission_type,
transaction_id: notificationResult?.transactionId
}
});
edgeLogger.info('User notification sent successfully', { action: 'notify_user_submission_status', requestId: tracking.requestId, result: notificationResult });
endRequest(tracking, 200);
return new Response(
JSON.stringify({
success: true,
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);
return new Response(
JSON.stringify({
success: false,
error: errorMessage,
requestId: tracking.requestId
}),
{
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
status: 500,
}
);
submissionId: submission_id,
entityURL,
moderationNotes: reviewer_notes || '',
};
} else {
payload = {
baseUrl: 'https://www.thrillwiki.com',
rejectionReason: reviewer_notes || 'No reason provided',
entityType,
entityName,
entityURL,
actualStatus: 'rejected',
};
}
});
// Generate idempotency key for duplicate prevention
const { data: keyData, error: keyError } = await supabase
.rpc('generate_notification_idempotency_key', {
p_notification_type: `submission_${status}`,
p_entity_id: submission_id,
p_recipient_id: user_id,
});
const idempotencyKey = keyData || `user_sub_${submission_id}_${user_id}_${status}_${Date.now()}`;
// Check for duplicate within 24h window
const { data: existingLog, error: logCheckError } = await supabase
.from('notification_logs')
.select('id')
.eq('user_id', user_id)
.eq('idempotency_key', idempotencyKey)
.gte('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
.maybeSingle();
if (existingLog) {
// Duplicate detected - log and skip
await supabase.from('notification_logs').update({
is_duplicate: true
}).eq('id', existingLog.id);
addSpanEvent(span, 'duplicate_notification_prevented', {
idempotencyKey,
submissionId: submission_id
});
return {
success: true,
message: 'Duplicate notification prevented',
idempotencyKey,
};
}
addSpanEvent(span, 'sending_notification', {
workflowId,
entityName,
idempotencyKey
});
// Call trigger-notification function
const { data: notificationResult, error: notificationError } = await supabase.functions.invoke(
'trigger-notification',
{
body: {
workflowId,
subscriberId: user_id,
payload,
},
}
);
if (notificationError) {
throw new Error(`Failed to trigger notification: ${notificationError.message}`);
}
// Log notification in notification_logs with idempotency key
await supabase.from('notification_logs').insert({
user_id,
notification_type: `submission_${status}`,
idempotency_key: idempotencyKey,
is_duplicate: false,
metadata: {
submission_id,
submission_type,
transaction_id: notificationResult?.transactionId
}
});
addSpanEvent(span, 'notification_sent', {
transactionId: notificationResult?.transactionId
});
return {
success: true,
transactionId: notificationResult?.transactionId,
};
};
serve(createEdgeFunction({
name: 'notify-user-submission-status',
requireAuth: false,
useServiceRole: true,
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));

View File

@@ -1,16 +1,10 @@
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { corsHeaders } from '../_shared/cors.ts';
export default createEdgeFunction(
{
name: 'process-expired-bans',
requireAuth: false,
},
async (req, context, supabase) => {
edgeLogger.info('Processing expired bans', {
requestId: context.requestId
});
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
addSpanEvent(span, 'processing_expired_bans', { requestId });
const now = new Date().toISOString();
@@ -23,25 +17,18 @@ export default createEdgeFunction(
.lte('ban_expires_at', now);
if (fetchError) {
edgeLogger.error('Error fetching expired bans', {
error: fetchError,
requestId: context.requestId
});
addSpanEvent(span, 'error_fetching_expired_bans', { error: fetchError.message });
throw fetchError;
}
edgeLogger.info('Found expired bans to process', {
count: expiredBans?.length || 0,
requestId: context.requestId
});
addSpanEvent(span, 'found_expired_bans', { count: expiredBans?.length || 0 });
// Unban users with expired bans
const unbannedUsers: string[] = [];
for (const profile of expiredBans || []) {
edgeLogger.info('Unbanning user', {
addSpanEvent(span, 'unbanning_user', {
username: profile.username,
userId: profile.user_id,
requestId: context.requestId
userId: profile.user_id
});
const { error: unbanError } = await supabase
@@ -54,10 +41,9 @@ export default createEdgeFunction(
.eq('user_id', profile.user_id);
if (unbanError) {
edgeLogger.error('Failed to unban user', {
addSpanEvent(span, 'failed_to_unban_user', {
username: profile.username,
error: unbanError,
requestId: context.requestId
error: unbanError.message
});
continue;
}
@@ -76,29 +62,28 @@ export default createEdgeFunction(
});
if (logError) {
edgeLogger.error('Failed to log auto-unban', {
addSpanEvent(span, 'failed_to_log_auto_unban', {
username: profile.username,
error: logError,
requestId: context.requestId
error: logError.message
});
}
unbannedUsers.push(profile.username);
}
edgeLogger.info('Successfully unbanned users', {
count: unbannedUsers.length,
requestId: context.requestId
});
addSpanEvent(span, 'successfully_unbanned_users', { count: unbannedUsers.length });
return new Response(
JSON.stringify({
success: true,
unbanned_count: unbannedUsers.length,
unbanned_users: unbannedUsers,
processed_at: now
}),
{ headers: { 'Content-Type': 'application/json' } }
);
}
);
return {
success: true,
unbanned_count: unbannedUsers.length,
unbanned_users: unbannedUsers,
processed_at: now
};
};
serve(createEdgeFunction({
name: 'process-expired-bans',
requireAuth: false,
corsHeaders,
enableTracing: true,
}, handler));

View File

@@ -1,11 +1,6 @@
/**
* Rate Limit Metrics API
*
* Exposes rate limiting metrics for monitoring and analysis.
* Requires admin/moderator authentication.
*/
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import {
getRecentMetrics,
getMetricsStats,
@@ -15,18 +10,7 @@ import {
clearMetrics,
} from '../_shared/rateLimitMetrics.ts';
interface QueryParams {
action?: string;
limit?: string;
timeWindow?: string;
functionName?: string;
userId?: string;
clientIP?: string;
}
const handler = async (req: Request, context: { supabase: any; user: any; span: any; requestId: string }) => {
const { supabase, user } = context;
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
// Check if user has admin or moderator role
const { data: roles } = await supabase
.from('user_roles')
@@ -116,14 +100,10 @@ const handler = async (req: Request, context: { supabase: any; user: any; span:
return responseData;
};
// Create edge function with automatic error handling, CORS, auth, and logging
createEdgeFunction(
{
name: 'rate-limit-metrics',
requireAuth: true,
corsEnabled: true,
enableTracing: false,
rateLimitTier: 'lenient'
},
handler
);
serve(createEdgeFunction({
name: 'rate-limit-metrics',
requireAuth: true,
corsHeaders,
enableTracing: true,
rateLimitTier: 'lenient',
}, handler));

View File

@@ -1,193 +1,114 @@
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { corsHeaders } from '../_shared/cors.ts';
import { rateLimiters, withRateLimit } from '../_shared/rateLimiter.ts';
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
import { addSpanEvent } from '../_shared/logger.ts';
// Apply moderate rate limiting (10 req/min) to prevent deletion code spam
// Protects against abuse while allowing legitimate resend requests
serve(withRateLimit(async (req) => {
const tracking = startRequest();
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
addSpanEvent(span, 'resending_deletion_code', { userId: user.id });
if (req.method === 'OPTIONS') {
return new Response(null, {
headers: {
...corsHeaders,
'X-Request-ID': tracking.requestId
}
});
// Find pending deletion request
const { data: deletionRequest, error: requestError } = await supabase
.from('account_deletion_requests')
.select('*')
.eq('user_id', user.id)
.eq('status', 'pending')
.maybeSingle();
if (requestError || !deletionRequest) {
throw new Error('No pending deletion request found');
}
try {
const supabaseClient = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
{
global: {
headers: { Authorization: req.headers.get('Authorization')! },
// Check rate limiting (max 3 resends per hour - ~20 minutes between resends)
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
const now = new Date();
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
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');
}
// Generate new confirmation code
const { data: codeData, error: codeError } = await supabase
.rpc('generate_deletion_confirmation_code');
if (codeError) {
throw codeError;
}
const confirmationCode = codeData as string;
// Update deletion request with new code
const { error: updateError } = await supabase
.from('account_deletion_requests')
.update({
confirmation_code: confirmationCode,
confirmation_code_sent_at: now.toISOString(),
})
.eq('id', deletionRequest.id);
if (updateError) {
throw updateError;
}
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
addSpanEvent(span, 'new_code_generated', {
scheduledDeletionDate: scheduledDate.toISOString()
});
// Send email with new code
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
if (forwardEmailKey) {
try {
await fetch('https://api.forwardemail.net/v1/emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
},
}
);
body: JSON.stringify({
from: fromEmail,
to: user.email,
subject: 'Account Deletion - New Confirmation Code',
html: `
<h2>New Confirmation Code</h2>
<p>You requested a new confirmation code for your account deletion.</p>
<p>Your account will be permanently deleted on <strong>${scheduledDate.toLocaleDateString()}</strong>.</p>
// Get authenticated user
const {
data: { user },
error: userError,
} = await supabaseClient.auth.getUser();
<h3>CONFIRMATION CODE: <strong>${confirmationCode}</strong></h3>
<p>To confirm deletion after the waiting period, you'll need to enter this 6-digit code.</p>
if (userError || !user) {
const duration = endRequest(tracking);
edgeLogger.error('Authentication failed', {
action: 'resend_deletion_code',
requestId: tracking.requestId,
duration
<p><strong>Need to cancel?</strong> Log in and visit your account settings to reactivate your account.</p>
`,
}),
});
addSpanEvent(span, 'email_sent', { email: user.email });
} catch (emailError) {
addSpanEvent(span, 'email_send_failed', {
error: emailError instanceof Error ? emailError.message : String(emailError)
});
// 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
const { data: deletionRequest, error: requestError } = await supabaseClient
.from('account_deletion_requests')
.select('*')
.eq('user_id', user.id)
.eq('status', 'pending')
.maybeSingle();
if (requestError || !deletionRequest) {
throw new Error('No pending deletion request found');
}
// Check rate limiting (max 3 resends per hour)
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
const now = new Date();
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
if (hoursSinceLastSend < 0.33) { // ~20 minutes between resends
throw new Error('Please wait at least 20 minutes between resend requests');
}
// Generate new confirmation code
const { data: codeData, error: codeError } = await supabaseClient
.rpc('generate_deletion_confirmation_code');
if (codeError) {
throw codeError;
}
const confirmationCode = codeData as string;
// Update deletion request with new code
const { error: updateError } = await supabaseClient
.from('account_deletion_requests')
.update({
confirmation_code: confirmationCode,
confirmation_code_sent_at: now.toISOString(),
})
.eq('id', deletionRequest.id);
if (updateError) {
throw updateError;
}
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
// Send email with new code
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
if (forwardEmailKey) {
try {
await fetch('https://api.forwardemail.net/v1/emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
},
body: JSON.stringify({
from: fromEmail,
to: user.email,
subject: 'Account Deletion - New Confirmation Code',
html: `
<h2>New Confirmation Code</h2>
<p>You requested a new confirmation code for your account deletion.</p>
<p>Your account will be permanently deleted on <strong>${scheduledDate.toLocaleDateString()}</strong>.</p>
<h3>CONFIRMATION CODE: <strong>${confirmationCode}</strong></h3>
<p>To confirm deletion after the waiting period, you'll need to enter this 6-digit code.</p>
<p><strong>Need to cancel?</strong> Log in and visit your account settings to reactivate your account.</p>
`,
}),
});
edgeLogger.info('New confirmation code email sent', { requestId: tracking.requestId });
} catch (emailError) {
edgeLogger.error('Failed to send email', {
requestId: tracking.requestId,
error: emailError.message
});
}
}
const duration = endRequest(tracking);
edgeLogger.info('New confirmation code sent successfully', {
action: 'resend_deletion_code',
requestId: tracking.requestId,
userId: user.id,
duration
});
return new Response(
JSON.stringify({
success: true,
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
const errorSpan = startSpan('resend-deletion-code-error', 'SERVER');
endSpan(errorSpan, 'error', error);
logSpanToDatabase(errorSpan, tracking.requestId);
return new Response(
JSON.stringify({
error: error.message,
requestId: tracking.requestId
}),
{
status: 400,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
}
);
}
}, rateLimiters.moderate, corsHeaders));
addSpanEvent(span, 'resend_completed', { userId: user.id });
return {
success: true,
message: 'New confirmation code sent successfully',
};
};
serve(createEdgeFunction({
name: 'resend-deletion-code',
requireAuth: true,
corsHeaders,
enableTracing: true,
logRequests: true,
rateLimitTier: 'moderate', // 10 requests per minute
}, handler));

View File

@@ -1,7 +1,7 @@
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 { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { withEdgeRetry } from '../_shared/retryHelper.ts';
interface EscalationRequest {
@@ -10,276 +10,219 @@ interface EscalationRequest {
escalatedBy: string;
}
serve(async (req) => {
const tracking = startRequest();
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
addSpanEvent(span, 'processing_escalation', { submissionId, escalatedBy });
// Fetch submission details
const { data: submission, error: submissionError } = await supabase
.from('content_submissions')
.select('*, profiles:user_id(username, display_name, id)')
.eq('id', submissionId)
.single();
if (submissionError || !submission) {
throw new Error(`Failed to fetch submission: ${submissionError?.message || 'Not found'}`);
}
try {
const supabase = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
);
// Fetch escalator details
const { data: escalator, error: escalatorError } = await supabase
.from('profiles')
.select('username, display_name')
.eq('user_id', escalatedBy)
.single();
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
if (escalatorError) {
addSpanEvent(span, 'escalator_profile_fetch_failed', { error: escalatorError.message });
}
edgeLogger.info('Processing escalation notification', {
requestId: tracking.requestId,
submissionId,
escalatedBy,
action: 'send_escalation'
});
// Fetch submission items count
const { count: itemsCount, error: countError } = await supabase
.from('submission_items')
.select('*', { count: 'exact', head: true })
.eq('submission_id', submissionId);
// Fetch submission details
const { data: submission, error: submissionError } = await supabase
.from('content_submissions')
.select('*, profiles:user_id(username, display_name, id)')
.eq('id', submissionId)
.single();
if (countError) {
addSpanEvent(span, 'items_count_fetch_failed', { error: countError.message });
}
if (submissionError || !submission) {
throw new Error(`Failed to fetch submission: ${submissionError?.message || 'Not found'}`);
}
// Prepare email content
const escalatorName = escalator?.display_name || escalator?.username || 'Unknown User';
const submitterName = submission.profiles?.display_name || submission.profiles?.username || 'Unknown User';
const submissionType = submission.submission_type || 'Unknown';
const itemCount = itemsCount || 0;
// Fetch escalator details
const { data: escalator, error: escalatorError } = await supabase
.from('profiles')
.select('username, display_name')
.eq('user_id', escalatedBy)
.single();
const emailSubject = `🚨 Submission Escalated: ${submissionType} - ID: ${submissionId.substring(0, 8)}`;
if (escalatorError) {
edgeLogger.error('Failed to fetch escalator profile', {
requestId: tracking.requestId,
error: escalatorError.message,
escalatedBy
});
}
const emailHtml = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background-color: #ef4444; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
.content { background-color: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
.info-row { margin: 10px 0; padding: 10px; background: white; border-radius: 4px; }
.label { font-weight: bold; color: #374151; }
.value { color: #1f2937; }
.reason { background-color: #fef3c7; padding: 15px; border-left: 4px solid #f59e0b; margin: 15px 0; }
.footer { text-align: center; padding: 20px; color: #6b7280; font-size: 14px; }
.button { display: inline-block; padding: 12px 24px; background-color: #3b82f6; color: white; text-decoration: none; border-radius: 6px; margin: 15px 0; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1 style="margin: 0;">⚠️ Submission Escalated</h1>
<p style="margin: 5px 0 0 0;">Admin review required</p>
</div>
// Fetch submission items count
const { count: itemsCount, error: countError } = await supabase
.from('submission_items')
.select('*', { count: 'exact', head: true })
.eq('submission_id', submissionId);
if (countError) {
edgeLogger.error('Failed to fetch items count', {
requestId: tracking.requestId,
error: countError.message,
submissionId
});
}
// Prepare email content
const escalatorName = escalator?.display_name || escalator?.username || 'Unknown User';
const submitterName = submission.profiles?.display_name || submission.profiles?.username || 'Unknown User';
const submissionType = submission.submission_type || 'Unknown';
const itemCount = itemsCount || 0;
const emailSubject = `🚨 Submission Escalated: ${submissionType} - ID: ${submissionId.substring(0, 8)}`;
const emailHtml = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background-color: #ef4444; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
.content { background-color: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
.info-row { margin: 10px 0; padding: 10px; background: white; border-radius: 4px; }
.label { font-weight: bold; color: #374151; }
.value { color: #1f2937; }
.reason { background-color: #fef3c7; padding: 15px; border-left: 4px solid #f59e0b; margin: 15px 0; }
.footer { text-align: center; padding: 20px; color: #6b7280; font-size: 14px; }
.button { display: inline-block; padding: 12px 24px; background-color: #3b82f6; color: white; text-decoration: none; border-radius: 6px; margin: 15px 0; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1 style="margin: 0;">⚠️ Submission Escalated</h1>
<p style="margin: 5px 0 0 0;">Admin review required</p>
<div class="content">
<div class="info-row">
<span class="label">Submission ID:</span>
<span class="value">${submissionId}</span>
</div>
<div class="content">
<div class="info-row">
<span class="label">Submission ID:</span>
<span class="value">${submissionId}</span>
</div>
<div class="info-row">
<span class="label">Submission Type:</span>
<span class="value">${submissionType}</span>
</div>
<div class="info-row">
<span class="label">Items Count:</span>
<span class="value">${itemCount}</span>
</div>
<div class="info-row">
<span class="label">Submitted By:</span>
<span class="value">${submitterName}</span>
</div>
<div class="info-row">
<span class="label">Escalated By:</span>
<span class="value">${escalatorName}</span>
</div>
<div class="reason">
<strong>📝 Escalation Reason:</strong>
<p style="margin: 10px 0 0 0;">${escalationReason}</p>
</div>
<div style="text-align: center;">
<a href="${Deno.env.get('SUPABASE_URL')?.replace('.supabase.co', '.lovable.app')}/admin" class="button">
Review Submission →
</a>
</div>
<div class="info-row">
<span class="label">Submission Type:</span>
<span class="value">${submissionType}</span>
</div>
<div class="footer">
<p>This is an automated notification from your moderation system.</p>
<p>Please review and take appropriate action.</p>
<div class="info-row">
<span class="label">Items Count:</span>
<span class="value">${itemCount}</span>
</div>
<div class="info-row">
<span class="label">Submitted By:</span>
<span class="value">${submitterName}</span>
</div>
<div class="info-row">
<span class="label">Escalated By:</span>
<span class="value">${escalatorName}</span>
</div>
<div class="reason">
<strong>📝 Escalation Reason:</strong>
<p style="margin: 10px 0 0 0;">${escalationReason}</p>
</div>
<div style="text-align: center;">
<a href="${Deno.env.get('SUPABASE_URL')?.replace('.supabase.co', '.lovable.app')}/admin" class="button">
Review Submission →
</a>
</div>
</div>
</body>
</html>
`;
const emailText = `
SUBMISSION ESCALATED - Admin Review Required
<div class="footer">
<p>This is an automated notification from your moderation system.</p>
<p>Please review and take appropriate action.</p>
</div>
</div>
</body>
</html>
`;
Submission ID: ${submissionId}
Submission Type: ${submissionType}
Items Count: ${itemCount}
Submitted By: ${submitterName}
Escalated By: ${escalatorName}
const emailText = `
SUBMISSION ESCALATED - Admin Review Required
Escalation Reason:
${escalationReason}
Submission ID: ${submissionId}
Submission Type: ${submissionType}
Items Count: ${itemCount}
Submitted By: ${submitterName}
Escalated By: ${escalatorName}
Please review this submission in the admin panel.
`;
Escalation Reason:
${escalationReason}
// Send email via ForwardEmail API with retry
const forwardEmailApiKey = Deno.env.get('FORWARDEMAIL_API_KEY');
const adminEmail = Deno.env.get('ADMIN_EMAIL_ADDRESS');
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS');
Please review this submission in the admin panel.
`;
if (!forwardEmailApiKey || !adminEmail || !fromEmail) {
throw new Error('Email configuration is incomplete. Please check environment variables.');
}
// Send email via ForwardEmail API with retry
const forwardEmailApiKey = Deno.env.get('FORWARDEMAIL_API_KEY');
const adminEmail = Deno.env.get('ADMIN_EMAIL_ADDRESS');
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS');
const emailResult = await withEdgeRetry(
async () => {
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(forwardEmailApiKey + ':'),
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: fromEmail,
to: adminEmail,
subject: emailSubject,
html: emailHtml,
text: emailText,
}),
});
if (!forwardEmailApiKey || !adminEmail || !fromEmail) {
throw new Error('Email configuration is incomplete. Please check environment variables.');
}
if (!emailResponse.ok) {
let errorText;
try {
errorText = await emailResponse.text();
} catch (parseError) {
errorText = 'Unable to parse error response';
}
addSpanEvent(span, 'sending_escalation_email', { adminEmail });
const error = new Error(`Failed to send email: ${emailResponse.status} - ${errorText}`);
(error as any).status = emailResponse.status;
throw error;
const emailResult = await withEdgeRetry(
async () => {
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(forwardEmailApiKey + ':'),
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: fromEmail,
to: adminEmail,
subject: emailSubject,
html: emailHtml,
text: emailText,
}),
});
if (!emailResponse.ok) {
let errorText;
try {
errorText = await emailResponse.text();
} catch {
errorText = 'Unable to parse error response';
}
const result = await emailResponse.json();
return result;
},
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
tracking.requestId,
'send-escalation-email'
);
edgeLogger.info('Email sent successfully', {
requestId: tracking.requestId,
emailId: emailResult.id
});
const error = new Error(`Failed to send email: ${emailResponse.status} - ${errorText}`);
(error as any).status = emailResponse.status;
throw error;
}
// Update submission with notification status
const { error: updateError } = await supabase
.from('content_submissions')
.update({
escalated: true,
escalated_at: new Date().toISOString(),
escalated_by: escalatedBy,
escalation_reason: escalationReason
})
.eq('id', submissionId);
return await emailResponse.json();
},
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
requestId,
'send-escalation-email'
);
if (updateError) {
edgeLogger.error('Failed to update submission escalation status', {
requestId: tracking.requestId,
error: updateError.message,
submissionId
});
}
addSpanEvent(span, 'email_sent', { emailId: emailResult.id });
const duration = endRequest(tracking);
edgeLogger.info('Escalation notification sent', {
requestId: tracking.requestId,
duration,
emailId: emailResult.id,
submissionId
});
// Update submission with escalation status
const { error: updateError } = await supabase
.from('content_submissions')
.update({
escalated: true,
escalated_at: new Date().toISOString(),
escalated_by: escalatedBy,
escalation_reason: escalationReason
})
.eq('id', submissionId);
return new Response(
JSON.stringify({
success: true,
message: 'Escalation notification sent successfully',
emailId: emailResult.id,
requestId: tracking.requestId
}),
{ headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
} }
);
} catch (error) {
const duration = endRequest(tracking);
edgeLogger.error('Error in send-escalation-notification', {
requestId: tracking.requestId,
duration,
error: error instanceof Error ? error.message : 'Unknown error'
});
// Persist error to database for monitoring
const errorSpan = startSpan('send-escalation-notification-error', 'SERVER');
endSpan(errorSpan, 'error', error);
logSpanToDatabase(errorSpan, tracking.requestId);
return new Response(
JSON.stringify({
error: error instanceof Error ? error.message : 'Unknown error occurred',
details: 'Failed to send escalation notification',
requestId: tracking.requestId
}),
{ status: 500, headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
} }
);
if (updateError) {
addSpanEvent(span, 'submission_update_failed', { error: updateError.message });
}
});
addSpanEvent(span, 'escalation_notification_complete', {
emailId: emailResult.id,
submissionId
});
return {
success: true,
message: 'Escalation notification sent successfully',
emailId: emailResult.id,
};
};
serve(createEdgeFunction({
name: 'send-escalation-notification',
requireAuth: false,
useServiceRole: true,
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));

View File

@@ -1,7 +1,7 @@
import { serve } from 'https://deno.land/std@0.168.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 { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
import { addSpanEvent } from '../_shared/logger.ts';
interface EmailRequest {
email: string;
@@ -9,217 +9,131 @@ interface EmailRequest {
username?: string;
}
serve(async (req) => {
const tracking = startRequest();
const handler = async (req: Request, { user, span, requestId }: EdgeFunctionContext) => {
const { email, displayName, username }: EmailRequest = await req.json();
if (req.method === 'OPTIONS') {
return new Response(null, {
headers: {
...corsHeaders,
'X-Request-ID': tracking.requestId
}
});
if (!email) {
throw new Error('Email is required');
}
try {
const supabaseClient = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
{
global: {
headers: { Authorization: req.headers.get('Authorization')! },
},
}
);
addSpanEvent(span, 'sending_password_email', { userId: user.id, email });
const { data: { user }, error: userError } = await supabaseClient.auth.getUser();
const recipientName = displayName || username || 'there';
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
if (userError || !user) {
const duration = endRequest(tracking);
edgeLogger.error('Authentication failed', {
action: 'send_password_email',
requestId: tracking.requestId,
duration
});
// Persist error to database
const authErrorSpan = startSpan('send-password-added-email-auth-error', 'SERVER');
endSpan(authErrorSpan, 'error', userError);
logSpanToDatabase(authErrorSpan, tracking.requestId);
throw new Error('Unauthorized');
}
const { email, displayName, username }: EmailRequest = await req.json();
if (!email) {
throw new Error('Email is required');
}
edgeLogger.info('Sending password added email', {
action: 'send_password_email',
requestId: tracking.requestId,
userId: user.id,
email
});
const recipientName = displayName || username || 'there';
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
const emailHTML = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
.content { background: white; padding: 30px; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
.button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
.security-notice { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
.footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
ul { line-height: 1.8; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Password Successfully Added</h1>
</div>
<div class="content">
<p>Hi ${recipientName},</p>
<p>Great news! A password has been successfully added to your ThrillWiki account (<strong>${email}</strong>).</p>
<h3>✅ What This Means</h3>
<p>You now have an additional way to access your account. You can sign in using:</p>
<ul>
<li>Your email address and the password you just created</li>
<li>Any social login methods you've connected (Google, Discord, etc.)</li>
</ul>
<h3>🔐 Complete Your Setup</h3>
<p><strong>Important:</strong> To complete your password setup, you need to confirm your email address.</p>
<ol style="padding-left: 20px; margin: 15px 0; line-height: 1.8;">
<li style="margin-bottom: 8px;">Check your inbox for a <strong>confirmation email</strong> from ThrillWiki</li>
<li style="margin-bottom: 8px;">Click the confirmation link in that email</li>
<li style="margin-bottom: 8px;">Return to the sign-in page and log in with your email and password</li>
</ol>
<a href="${siteUrl}/auth?email=${encodeURIComponent(email)}&message=complete-password-setup" class="button">
Go to Sign In Page
</a>
<p style="margin-top: 15px; font-size: 14px; color: #666;">
<strong>Note:</strong> You must confirm your email before you can sign in with your password.
</p>
<div class="security-notice">
<strong>⚠️ Security Notice</strong><br>
If you didn't add a password to your account, please contact our support team immediately at <strong>support@thrillwiki.com</strong>
</div>
<p>Thanks for being part of the ThrillWiki community!</p>
<p>
Best regards,<br>
The ThrillWiki Team
</p>
</div>
<div class="footer">
<p>© ${new Date().getFullYear()} ThrillWiki. All rights reserved.</p>
<p>This is an automated security notification. Please do not reply to this email.</p>
</div>
const emailHTML = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
.content { background: white; padding: 30px; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
.button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
.security-notice { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
.footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
ul { line-height: 1.8; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Password Successfully Added</h1>
</div>
</body>
</html>
`;
<div class="content">
<p>Hi ${recipientName},</p>
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
<p>Great news! A password has been successfully added to your ThrillWiki account (<strong>${email}</strong>).</p>
if (!forwardEmailKey) {
edgeLogger.error('FORWARDEMAIL_API_KEY not configured', { requestId: tracking.requestId });
throw new Error('Email service not configured');
}
<h3>✅ What This Means</h3>
<p>You now have an additional way to access your account. You can sign in using:</p>
<ul>
<li>Your email address and the password you just created</li>
<li>Any social login methods you've connected (Google, Discord, etc.)</li>
</ul>
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
},
body: JSON.stringify({
from: fromEmail,
to: email,
subject: 'Password Added to Your ThrillWiki Account',
html: emailHTML,
}),
});
<h3>🔐 Complete Your Setup</h3>
<p><strong>Important:</strong> To complete your password setup, you need to confirm your email address.</p>
if (!emailResponse.ok) {
const errorText = await emailResponse.text();
edgeLogger.error('ForwardEmail API error', {
requestId: tracking.requestId,
status: emailResponse.status,
errorText
});
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
}
<ol style="padding-left: 20px; margin: 15px 0; line-height: 1.8;">
<li style="margin-bottom: 8px;">Check your inbox for a <strong>confirmation email</strong> from ThrillWiki</li>
<li style="margin-bottom: 8px;">Click the confirmation link in that email</li>
<li style="margin-bottom: 8px;">Return to the sign-in page and log in with your email and password</li>
</ol>
const duration = endRequest(tracking);
edgeLogger.info('Password addition email sent successfully', {
action: 'send_password_email',
requestId: tracking.requestId,
userId: user.id,
email,
duration
});
<a href="${siteUrl}/auth?email=${encodeURIComponent(email)}&message=complete-password-setup" class="button">
Go to Sign In Page
</a>
return new Response(
JSON.stringify({
success: true,
message: 'Password addition email sent successfully',
requestId: tracking.requestId,
}),
{
status: 200,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
}
);
<p style="margin-top: 15px; font-size: 14px; color: #666;">
<strong>Note:</strong> You must confirm your email before you can sign in with your password.
</p>
} catch (error) {
const duration = endRequest(tracking);
edgeLogger.error('Error in send-password-added-email function', {
action: 'send_password_email',
requestId: tracking.requestId,
duration,
error: error instanceof Error ? error.message : 'Unknown error'
});
<div class="security-notice">
<strong>⚠️ Security Notice</strong><br>
If you didn't add a password to your account, please contact our support team immediately at <strong>support@thrillwiki.com</strong>
</div>
// Persist error to database for monitoring
const errorSpan = startSpan('send-password-added-email-error', 'SERVER');
endSpan(errorSpan, 'error', error);
logSpanToDatabase(errorSpan, tracking.requestId);
<p>Thanks for being part of the ThrillWiki community!</p>
return new Response(
JSON.stringify({
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
requestId: tracking.requestId,
}),
{
status: 500,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
'X-Request-ID': tracking.requestId
},
}
);
<p>
Best regards,<br>
The ThrillWiki Team
</p>
</div>
<div class="footer">
<p>© ${new Date().getFullYear()} ThrillWiki. All rights reserved.</p>
<p>This is an automated security notification. Please do not reply to this email.</p>
</div>
</div>
</body>
</html>
`;
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
if (!forwardEmailKey) {
addSpanEvent(span, 'email_config_missing', {});
throw new Error('Email service not configured');
}
});
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
},
body: JSON.stringify({
from: fromEmail,
to: email,
subject: 'Password Added to Your ThrillWiki Account',
html: emailHTML,
}),
});
if (!emailResponse.ok) {
const errorText = await emailResponse.text();
addSpanEvent(span, 'email_send_failed', {
status: emailResponse.status,
error: errorText
});
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
}
addSpanEvent(span, 'email_sent_successfully', { email });
return {
success: true,
message: 'Password addition email sent successfully',
};
};
serve(createEdgeFunction({
name: 'send-password-added-email',
requireAuth: true,
corsHeaders,
enableTracing: true,
logRequests: true,
}, handler));