mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 07:11:12 -05:00
Compare commits
3 Commits
16a1fa756d
...
08926610b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08926610b9 | ||
|
|
a1280ddd05 | ||
|
|
19804ea9bd |
@@ -1,17 +1,15 @@
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts';
|
||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'cancel-account-deletion',
|
||||
requireAuth: true,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const { cancellation_reason } = await req.json();
|
||||
|
||||
const supabaseClient = createClient(
|
||||
@@ -24,23 +22,14 @@ serve(async (req) => {
|
||||
}
|
||||
);
|
||||
|
||||
// Get authenticated user
|
||||
const {
|
||||
data: { user },
|
||||
error: userError,
|
||||
} = await supabaseClient.auth.getUser();
|
||||
|
||||
if (userError || !user) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
edgeLogger.info('Cancelling deletion request', { action: 'cancel_deletion', userId: user.id, requestId: tracking.requestId });
|
||||
context.span.setAttribute('action', 'cancel_deletion');
|
||||
edgeLogger.info('Cancelling deletion request', { action: 'cancel_deletion', userId: context.userId, requestId: context.requestId });
|
||||
|
||||
// Find pending or confirmed deletion request
|
||||
const { data: deletionRequest, error: requestError } = await supabaseClient
|
||||
.from('account_deletion_requests')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('user_id', context.userId)
|
||||
.in('status', ['pending', 'confirmed'])
|
||||
.maybeSingle();
|
||||
|
||||
@@ -81,7 +70,7 @@ serve(async (req) => {
|
||||
deactivated_at: null,
|
||||
deactivation_reason: null,
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
.eq('user_id', context.userId);
|
||||
|
||||
if (profileError) {
|
||||
throw profileError;
|
||||
@@ -90,8 +79,9 @@ serve(async (req) => {
|
||||
// Send cancellation email
|
||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||
const userEmail = (await supabaseClient.auth.getUser()).data.user?.email;
|
||||
|
||||
if (forwardEmailKey) {
|
||||
if (forwardEmailKey && userEmail) {
|
||||
try {
|
||||
await fetch('https://api.forwardemail.net/v1/emails', {
|
||||
method: 'POST',
|
||||
@@ -101,7 +91,7 @@ serve(async (req) => {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from: fromEmail,
|
||||
to: user.email,
|
||||
to: userEmail,
|
||||
subject: 'Account Deletion Cancelled',
|
||||
html: `
|
||||
<h2>Account Deletion Cancelled</h2>
|
||||
@@ -112,35 +102,23 @@ serve(async (req) => {
|
||||
`,
|
||||
}),
|
||||
});
|
||||
edgeLogger.info('Cancellation confirmation email sent', { action: 'cancel_deletion_email', userId: user.id, requestId: tracking.requestId });
|
||||
edgeLogger.info('Cancellation confirmation email sent', { action: 'cancel_deletion_email', userId: context.userId, requestId: context.requestId });
|
||||
} catch (emailError) {
|
||||
edgeLogger.error('Failed to send email', { action: 'cancel_deletion_email', userId: user.id, requestId: tracking.requestId });
|
||||
edgeLogger.error('Failed to send email', { action: 'cancel_deletion_email', userId: context.userId, requestId: context.requestId });
|
||||
}
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Deletion cancelled successfully', { action: 'cancel_deletion_success', userId: user.id, requestId: tracking.requestId, duration });
|
||||
edgeLogger.info('Deletion cancelled successfully', { action: 'cancel_deletion_success', userId: context.userId, requestId: context.requestId });
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'Account deletion cancelled 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 cancelling deletion', { action: 'cancel_deletion_error', error: formatEdgeError(error), requestId: tracking.requestId, duration });
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message, requestId: tracking.requestId }),
|
||||
{
|
||||
status: 400,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,36 +1,21 @@
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts';
|
||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
// Handle CORS preflight requests
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'X-Request-ID': tracking.requestId
|
||||
}
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'cancel-email-change',
|
||||
requireAuth: true,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
context.span.setAttribute('action', 'cancel_email_change');
|
||||
edgeLogger.info('Cancelling email change for user', {
|
||||
action: 'cancel_email_change',
|
||||
requestId: context.requestId,
|
||||
userId: context.userId
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the user from the authorization header
|
||||
const authHeader = req.headers.get('Authorization');
|
||||
if (!authHeader) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Missing authorization header', {
|
||||
action: 'cancel_email_change',
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
});
|
||||
throw new Error('No authorization header provided. Please ensure you are logged in.');
|
||||
}
|
||||
|
||||
// Extract the JWT token from the Authorization header
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
|
||||
// SECURITY: Service Role Key Usage
|
||||
// ---------------------------------
|
||||
@@ -38,7 +23,7 @@ Deno.serve(async (req) => {
|
||||
// This is required because:
|
||||
// 1. The cancel_user_email_change() database function has SECURITY DEFINER privileges
|
||||
// 2. It needs to modify auth.users table which is not accessible with regular user tokens
|
||||
// 3. User authentication is still verified via JWT token (passed to getUser())
|
||||
// 3. User authentication is verified via the wrapper's requireAuth
|
||||
// Scope: Limited to cancelling the authenticated user's own email change
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL');
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
||||
@@ -54,50 +39,28 @@ Deno.serve(async (req) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Verify the user's JWT token by passing it explicitly to getUser()
|
||||
// Note: verify_jwt = true in config.toml means Supabase has already validated the JWT
|
||||
const { data: { user }, error: authError } = await supabaseAdmin.auth.getUser(token);
|
||||
|
||||
if (authError || !user) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Auth verification failed', {
|
||||
action: 'cancel_email_change',
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: authError
|
||||
});
|
||||
throw new Error('Invalid session token. Please refresh the page and try again.');
|
||||
}
|
||||
|
||||
const userId = user.id;
|
||||
edgeLogger.info('Cancelling email change for user', {
|
||||
action: 'cancel_email_change',
|
||||
requestId: tracking.requestId,
|
||||
userId
|
||||
});
|
||||
|
||||
// Call the database function to clear email change fields
|
||||
// This function has SECURITY DEFINER privileges to access auth.users
|
||||
const { data: cancelled, error: cancelError } = await supabaseAdmin
|
||||
.rpc('cancel_user_email_change', { _user_id: userId });
|
||||
.rpc('cancel_user_email_change', { _user_id: context.userId });
|
||||
|
||||
if (cancelError || !cancelled) {
|
||||
edgeLogger.error('Error cancelling email change', {
|
||||
error: cancelError?.message,
|
||||
userId,
|
||||
requestId: tracking.requestId
|
||||
userId: context.userId,
|
||||
requestId: context.requestId
|
||||
});
|
||||
throw new Error('Unable to cancel email change: ' + (cancelError?.message || 'Unknown error'));
|
||||
}
|
||||
|
||||
edgeLogger.info('Successfully cancelled email change', { userId, requestId: tracking.requestId });
|
||||
edgeLogger.info('Successfully cancelled email change', { userId: context.userId, requestId: context.requestId });
|
||||
|
||||
// Log the cancellation in admin_audit_log
|
||||
const { error: auditError } = await supabaseAdmin
|
||||
.from('admin_audit_log')
|
||||
.insert({
|
||||
admin_user_id: userId,
|
||||
target_user_id: userId,
|
||||
admin_user_id: context.userId,
|
||||
target_user_id: context.userId,
|
||||
action: 'email_change_cancelled',
|
||||
details: {
|
||||
cancelled_at: new Date().toISOString(),
|
||||
@@ -107,17 +70,15 @@ Deno.serve(async (req) => {
|
||||
if (auditError) {
|
||||
edgeLogger.error('Error logging audit', {
|
||||
error: auditError.message,
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
// Don't fail the request if audit logging fails
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Successfully cancelled email change', {
|
||||
action: 'cancel_email_change',
|
||||
requestId: tracking.requestId,
|
||||
userId,
|
||||
duration
|
||||
requestId: context.requestId,
|
||||
userId: context.userId
|
||||
});
|
||||
|
||||
return new Response(
|
||||
@@ -125,43 +86,17 @@ Deno.serve(async (req) => {
|
||||
success: true,
|
||||
message: 'Email change cancelled successfully',
|
||||
user: {
|
||||
id: userId,
|
||||
id: context.userId,
|
||||
email: null,
|
||||
new_email: null,
|
||||
},
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error in cancel-email-change function', {
|
||||
action: 'cancel_email_change',
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: formatEdgeError(error)
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'An unknown error occurred',
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { validateString } from '../_shared/typeValidation.ts';
|
||||
|
||||
interface StatusRequest {
|
||||
idempotencyKey: string;
|
||||
@@ -27,53 +29,29 @@ interface StatusResponse {
|
||||
submissionId?: string;
|
||||
}
|
||||
|
||||
const handler = async (req: Request): Promise<Response> => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest();
|
||||
|
||||
try {
|
||||
// Verify authentication
|
||||
const authHeader = req.headers.get('Authorization');
|
||||
if (!authHeader) {
|
||||
edgeLogger.warn('Missing authorization header', { requestId: tracking.requestId });
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Unauthorized', status: 'not_found' }),
|
||||
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'check-transaction-status',
|
||||
requireAuth: true,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_ANON_KEY')!,
|
||||
{ global: { headers: { Authorization: authHeader } } }
|
||||
{ global: { headers: { Authorization: req.headers.get('Authorization')! } } }
|
||||
);
|
||||
|
||||
// Verify user
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser();
|
||||
if (authError || !user) {
|
||||
edgeLogger.warn('Invalid auth token', { requestId: tracking.requestId, error: authError });
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Unauthorized', status: 'not_found' }),
|
||||
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
// Parse request
|
||||
const { idempotencyKey }: StatusRequest = await req.json();
|
||||
validateString(idempotencyKey, 'idempotencyKey', { userId: context.userId, requestId: context.requestId });
|
||||
|
||||
if (!idempotencyKey) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Missing idempotencyKey', status: 'not_found' }),
|
||||
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
context.span.setAttribute('action', 'check_transaction_status');
|
||||
context.span.setAttribute('idempotency_key', idempotencyKey);
|
||||
|
||||
edgeLogger.info('Checking transaction status', {
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
requestId: context.requestId,
|
||||
userId: context.userId,
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
@@ -86,7 +64,7 @@ const handler = async (req: Request): Promise<Response> => {
|
||||
|
||||
if (queryError || !keyRecord) {
|
||||
edgeLogger.info('Idempotency key not found', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
idempotencyKey,
|
||||
error: queryError,
|
||||
});
|
||||
@@ -98,22 +76,22 @@ const handler = async (req: Request): Promise<Response> => {
|
||||
} as StatusResponse),
|
||||
{
|
||||
status: 404,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Verify user owns this key
|
||||
if (keyRecord.user_id !== user.id) {
|
||||
if (keyRecord.user_id !== context.userId) {
|
||||
edgeLogger.warn('User does not own idempotency key', {
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
requestId: context.requestId,
|
||||
userId: context.userId,
|
||||
keyUserId: keyRecord.user_id,
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Unauthorized', status: 'not_found' }),
|
||||
{ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
{ status: 403, headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -138,10 +116,8 @@ const handler = async (req: Request): Promise<Response> => {
|
||||
response.completedAt = keyRecord.completed_at;
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Transaction status retrieved', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
requestId: context.requestId,
|
||||
status: response.status,
|
||||
});
|
||||
|
||||
@@ -149,31 +125,8 @@ const handler = async (req: Request): Promise<Response> => {
|
||||
JSON.stringify(response),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
const duration = endRequest(tracking);
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
|
||||
edgeLogger.error('Error checking transaction status', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: errorMessage,
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: 'Internal server error',
|
||||
status: 'not_found'
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
Deno.serve(handler);
|
||||
);
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { validateString } from '../_shared/typeValidation.ts';
|
||||
|
||||
// Simple request tracking
|
||||
const startRequest = () => ({ requestId: crypto.randomUUID(), start: Date.now() });
|
||||
const endRequest = (tracking: { start: number }) => Date.now() - tracking.start;
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'create-novu-subscriber',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
|
||||
if (!novuApiKey) {
|
||||
@@ -26,168 +22,53 @@ serve(async (req) => {
|
||||
secretKey: novuApiKey
|
||||
});
|
||||
|
||||
// Parse and validate request body
|
||||
let requestBody;
|
||||
try {
|
||||
requestBody = await req.json();
|
||||
} catch (parseError) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Invalid JSON in request body',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const { subscriberId, email, firstName, lastName, phone, avatar, data } = requestBody;
|
||||
const { subscriberId, email, firstName, lastName, phone, avatar, data } = await req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!subscriberId || typeof subscriberId !== 'string' || subscriberId.trim() === '') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'subscriberId is required and must be a non-empty string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
validateString(subscriberId, 'subscriberId', { requestId: context.requestId });
|
||||
validateString(email, 'email', { requestId: context.requestId });
|
||||
|
||||
if (!email || typeof email !== 'string' || email.trim() === '') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'email is required and must be a non-empty string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Validate email format using regex
|
||||
// Validate email format
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Invalid email format. Please provide a valid email address',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('Invalid email format. Please provide a valid email address');
|
||||
}
|
||||
|
||||
// Validate optional fields if provided
|
||||
if (firstName !== undefined && firstName !== null && (typeof firstName !== 'string' || firstName.length > 100)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'firstName must be a string with maximum 100 characters',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('firstName must be a string with maximum 100 characters');
|
||||
}
|
||||
|
||||
if (lastName !== undefined && lastName !== null && (typeof lastName !== 'string' || lastName.length > 100)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'lastName must be a string with maximum 100 characters',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('lastName must be a string with maximum 100 characters');
|
||||
}
|
||||
|
||||
if (phone !== undefined && phone !== null) {
|
||||
if (typeof phone !== 'string') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'phone must be a string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('phone must be a string');
|
||||
}
|
||||
// Validate phone format (basic validation for international numbers)
|
||||
const phoneRegex = /^\+?[1-9]\d{1,14}$/;
|
||||
if (!phoneRegex.test(phone.replace(/[\s\-\(\)]/g, ''))) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Invalid phone format. Please provide a valid international phone number',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('Invalid phone format. Please provide a valid international phone number');
|
||||
}
|
||||
}
|
||||
|
||||
if (avatar !== undefined && avatar !== null && (typeof avatar !== 'string' || !avatar.startsWith('http'))) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'avatar must be a valid URL',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('avatar must be a valid URL');
|
||||
}
|
||||
|
||||
// Validate data field if provided
|
||||
if (data !== undefined && data !== null) {
|
||||
if (typeof data !== 'object' || Array.isArray(data)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'data must be a valid object',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('data must be a valid object');
|
||||
}
|
||||
|
||||
// Check data size (limit to 10KB serialized)
|
||||
const dataSize = JSON.stringify(data).length;
|
||||
if (dataSize > 10240) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'data field is too large (maximum 10KB)',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('data field is too large (maximum 10KB)');
|
||||
}
|
||||
}
|
||||
|
||||
edgeLogger.info('Creating Novu subscriber', { subscriberId, email: '***', firstName, requestId: tracking.requestId });
|
||||
context.span.setAttribute('action', 'create_novu_subscriber');
|
||||
edgeLogger.info('Creating Novu subscriber', { subscriberId, email: '***', firstName, requestId: context.requestId });
|
||||
|
||||
const subscriber = await novu.subscribers.identify(subscriberId, {
|
||||
email,
|
||||
@@ -198,26 +79,24 @@ serve(async (req) => {
|
||||
data,
|
||||
});
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Subscriber created successfully', {
|
||||
subscriberId: subscriber.data._id,
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Add subscriber to "users" topic for global announcements
|
||||
try {
|
||||
edgeLogger.info('Adding subscriber to users topic', { subscriberId, requestId: tracking.requestId });
|
||||
edgeLogger.info('Adding subscriber to users topic', { subscriberId, requestId: context.requestId });
|
||||
await novu.topics.addSubscribers('users', {
|
||||
subscribers: [subscriberId],
|
||||
});
|
||||
edgeLogger.info('Successfully added subscriber to users topic', { subscriberId, requestId: tracking.requestId });
|
||||
edgeLogger.info('Successfully added subscriber to users topic', { subscriberId, requestId: context.requestId });
|
||||
} catch (topicError: unknown) {
|
||||
// Non-blocking - log error but don't fail the request
|
||||
edgeLogger.error('Failed to add subscriber to users topic', {
|
||||
error: formatEdgeError(topicError),
|
||||
subscriberId,
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
}
|
||||
|
||||
@@ -225,31 +104,11 @@ serve(async (req) => {
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
subscriberId: subscriber.data._id,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error creating Novu subscriber', {
|
||||
error: formatEdgeError(error),
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
});
|
||||
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
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 { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
const TOPICS = {
|
||||
MODERATION_SUBMISSIONS: 'moderation-submissions',
|
||||
MODERATION_REPORTS: 'moderation-reports',
|
||||
} as const;
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('manage-moderator-topic');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'manage-moderator-topic',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
if (!novuApiKey) {
|
||||
throw new Error('NOVU_API_KEY is not configured');
|
||||
@@ -35,7 +34,8 @@ serve(async (req) => {
|
||||
throw new Error('Action must be either "add" or "remove"');
|
||||
}
|
||||
|
||||
edgeLogger.info(`${action === 'add' ? 'Adding' : 'Removing'} user ${userId} ${action === 'add' ? 'to' : 'from'} moderator topics`, { action: 'manage_moderator_topic', requestId: tracking.requestId, userId, operation: action });
|
||||
context.span.setAttribute('action', 'manage_moderator_topic');
|
||||
edgeLogger.info(`${action === 'add' ? 'Adding' : 'Removing'} user ${userId} ${action === 'add' ? 'to' : 'from'} moderator topics`, { action: 'manage_moderator_topic', requestId: context.requestId, userId, operation: action });
|
||||
|
||||
const topics = [TOPICS.MODERATION_SUBMISSIONS, TOPICS.MODERATION_REPORTS];
|
||||
const results = [];
|
||||
@@ -49,17 +49,17 @@ serve(async (req) => {
|
||||
await novu.topics.addSubscribers(topicKey, {
|
||||
subscribers: [userId],
|
||||
});
|
||||
edgeLogger.info('Added user to topic', { action: 'manage_moderator_topic', requestId: tracking.requestId, userId, topicKey });
|
||||
edgeLogger.info('Added user to topic', { action: 'manage_moderator_topic', requestId: context.requestId, userId, topicKey });
|
||||
} else {
|
||||
// Remove subscriber from topic
|
||||
await novu.topics.removeSubscribers(topicKey, {
|
||||
subscribers: [userId],
|
||||
});
|
||||
edgeLogger.info('Removed user from topic', { action: 'manage_moderator_topic', requestId: tracking.requestId, userId, topicKey });
|
||||
edgeLogger.info('Removed user from topic', { action: 'manage_moderator_topic', requestId: context.requestId, userId, topicKey });
|
||||
}
|
||||
},
|
||||
{ maxAttempts: 3, baseDelay: 1000 },
|
||||
tracking.requestId,
|
||||
context.requestId,
|
||||
`${action}-topic-${topicKey}`
|
||||
);
|
||||
|
||||
@@ -67,7 +67,7 @@ serve(async (req) => {
|
||||
} catch (error: any) {
|
||||
edgeLogger.error(`Error ${action}ing user ${userId} ${action === 'add' ? 'to' : 'from'} topic ${topicKey}`, {
|
||||
action: 'manage_moderator_topic',
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
userId,
|
||||
topicKey,
|
||||
error: error.message
|
||||
@@ -83,44 +83,19 @@ serve(async (req) => {
|
||||
|
||||
const allSuccess = results.every(r => r.success);
|
||||
|
||||
endRequest(tracking, allSuccess ? 200 : 207);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: allSuccess,
|
||||
userId,
|
||||
action,
|
||||
results,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: allSuccess ? 200 : 207, // 207 = Multi-Status (partial success)
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
edgeLogger.error('Error managing moderator topic', { action: 'manage_moderator_topic', requestId: tracking.requestId, error: error.message });
|
||||
|
||||
endRequest(tracking, 500, error.message);
|
||||
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
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 { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('migrate-novu-users');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'migrate-novu-users',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
@@ -20,6 +19,8 @@ serve(async (req) => {
|
||||
throw new Error('NOVU_API_KEY is not configured');
|
||||
}
|
||||
|
||||
context.span.setAttribute('action', 'migrate_novu_users');
|
||||
|
||||
// Create Supabase client with service role for admin access
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
@@ -52,20 +53,15 @@ serve(async (req) => {
|
||||
if (profilesError) throw profilesError;
|
||||
|
||||
if (!profiles || profiles.length === 0) {
|
||||
endRequest(tracking, 200);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'No users to migrate',
|
||||
results: [],
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
@@ -133,43 +129,24 @@ serve(async (req) => {
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
endRequest(tracking, 200);
|
||||
edgeLogger.info('Migration complete', {
|
||||
requestId: context.requestId,
|
||||
total: profiles.length,
|
||||
successful: results.filter(r => r.success).length
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
total: profiles.length,
|
||||
results,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
edgeLogger.error('Error migrating Novu users', { action: 'migrate_novu_users', requestId: tracking.requestId, error: error.message });
|
||||
|
||||
endRequest(tracking, 500, error.message);
|
||||
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -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 { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
interface AnnouncementPayload {
|
||||
title: string;
|
||||
@@ -10,38 +10,25 @@ interface AnnouncementPayload {
|
||||
actionUrl?: string;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('notify-system-announcement');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'notify-system-announcement',
|
||||
requireAuth: true,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
// Get authorization header
|
||||
const authHeader = req.headers.get('authorization');
|
||||
if (!authHeader) {
|
||||
throw new Error('Authorization header required');
|
||||
}
|
||||
|
||||
// Verify user is admin or superuser
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser(token);
|
||||
|
||||
if (authError || !user) {
|
||||
throw new Error('Unauthorized: Invalid token');
|
||||
}
|
||||
context.span.setAttribute('action', 'notify_system_announcement');
|
||||
|
||||
// Check user role
|
||||
const { data: roles, error: roleError } = await supabase
|
||||
.from('user_roles')
|
||||
.select('role')
|
||||
.eq('user_id', user.id)
|
||||
.eq('user_id', context.userId)
|
||||
.in('role', ['admin', 'superuser']);
|
||||
|
||||
if (roleError || !roles || roles.length === 0) {
|
||||
@@ -52,7 +39,7 @@ serve(async (req) => {
|
||||
const { data: profile } = await supabase
|
||||
.from('profiles')
|
||||
.select('username, display_name')
|
||||
.eq('user_id', user.id)
|
||||
.eq('user_id', context.userId)
|
||||
.single();
|
||||
|
||||
const payload: AnnouncementPayload = await req.json();
|
||||
@@ -71,7 +58,7 @@ serve(async (req) => {
|
||||
title: payload.title,
|
||||
severity: payload.severity,
|
||||
publishedBy: profile?.username || 'unknown',
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Fetch the workflow ID for system announcements
|
||||
@@ -83,22 +70,13 @@ serve(async (req) => {
|
||||
.maybeSingle();
|
||||
|
||||
if (templateError) {
|
||||
edgeLogger.error('Error fetching workflow', { action: 'notify_system_announcement', requestId: tracking.requestId, error: templateError });
|
||||
edgeLogger.error('Error fetching workflow', { action: 'notify_system_announcement', requestId: context.requestId, error: templateError });
|
||||
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
||||
}
|
||||
|
||||
if (!template) {
|
||||
edgeLogger.warn('No active system-announcement workflow found', { action: 'notify_system_announcement', requestId: tracking.requestId });
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'No active system-announcement workflow configured',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
edgeLogger.warn('No active system-announcement workflow found', { action: 'notify_system_announcement', requestId: context.requestId });
|
||||
throw new Error('No active system-announcement workflow configured');
|
||||
}
|
||||
|
||||
const announcementId = crypto.randomUUID();
|
||||
@@ -117,7 +95,7 @@ serve(async (req) => {
|
||||
publishedBy,
|
||||
};
|
||||
|
||||
edgeLogger.info('Triggering announcement to all users via "users" topic', { action: 'notify_system_announcement', requestId: tracking.requestId });
|
||||
edgeLogger.info('Triggering announcement to all users via "users" topic', { action: 'notify_system_announcement', requestId: context.requestId });
|
||||
|
||||
// Invoke the trigger-notification function with users topic
|
||||
const { data: result, error: notifyError } = await supabase.functions.invoke(
|
||||
@@ -132,13 +110,11 @@ serve(async (req) => {
|
||||
);
|
||||
|
||||
if (notifyError) {
|
||||
edgeLogger.error('Error triggering notification', { action: 'notify_system_announcement', requestId: tracking.requestId, error: notifyError });
|
||||
edgeLogger.error('Error triggering notification', { action: 'notify_system_announcement', requestId: context.requestId, error: notifyError });
|
||||
throw notifyError;
|
||||
}
|
||||
|
||||
edgeLogger.info('System announcement triggered successfully', { action: 'notify_system_announcement', requestId: tracking.requestId, result });
|
||||
|
||||
endRequest(tracking, 200);
|
||||
edgeLogger.info('System announcement triggered successfully', { action: 'notify_system_announcement', requestId: context.requestId, result });
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
@@ -146,36 +122,13 @@ serve(async (req) => {
|
||||
transactionId: result?.transactionId,
|
||||
announcementId,
|
||||
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-system-announcement', { action: 'notify_system_announcement', requestId: tracking.requestId, error: error.message });
|
||||
|
||||
endRequest(tracking, error.message.includes('Unauthorized') ? 403 : 500, error.message);
|
||||
|
||||
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: error.message.includes('Unauthorized') ? 403 : 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { validateString } from '../_shared/typeValidation.ts';
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('remove-novu-subscriber');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'remove-novu-subscriber',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
|
||||
if (!novuApiKey) {
|
||||
@@ -26,83 +26,47 @@ serve(async (req) => {
|
||||
deleteSubscriber?: boolean;
|
||||
};
|
||||
|
||||
if (!subscriberId || typeof subscriberId !== 'string' || subscriberId.trim() === '') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'subscriberId is required and must be a non-empty string',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
validateString(subscriberId, 'subscriberId', { requestId: context.requestId });
|
||||
|
||||
edgeLogger.info('Removing subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, requestId: tracking.requestId });
|
||||
context.span.setAttribute('action', 'remove_novu_subscriber');
|
||||
edgeLogger.info('Removing subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
|
||||
|
||||
// Remove subscriber from "users" topic
|
||||
try {
|
||||
await novu.topics.removeSubscribers('users', {
|
||||
subscribers: [subscriberId],
|
||||
});
|
||||
edgeLogger.info('Successfully removed subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId });
|
||||
edgeLogger.info('Successfully removed subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
|
||||
} catch (topicError: any) {
|
||||
edgeLogger.error('Failed to remove subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, error: topicError.message });
|
||||
edgeLogger.error('Failed to remove subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, error: topicError.message, requestId: context.requestId });
|
||||
// Continue - we still want to delete the subscriber if requested
|
||||
}
|
||||
|
||||
// Optionally delete the subscriber entirely from Novu
|
||||
if (deleteSubscriber) {
|
||||
try {
|
||||
edgeLogger.info('Deleting subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId });
|
||||
edgeLogger.info('Deleting subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
|
||||
await novu.subscribers.delete(subscriberId);
|
||||
edgeLogger.info('Successfully deleted subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId });
|
||||
edgeLogger.info('Successfully deleted subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
|
||||
} catch (deleteError: any) {
|
||||
edgeLogger.error('Failed to delete subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, error: deleteError.message });
|
||||
edgeLogger.error('Failed to delete subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, error: deleteError.message, requestId: context.requestId });
|
||||
throw deleteError;
|
||||
}
|
||||
}
|
||||
|
||||
endRequest(tracking, 200);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
subscriberId,
|
||||
removedFromTopic: true,
|
||||
deleted: deleteSubscriber,
|
||||
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 removing Novu subscriber', { action: 'remove_novu_subscriber', error: errorMessage, requestId: tracking.requestId });
|
||||
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
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 { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
const TOPICS = {
|
||||
MODERATION_SUBMISSIONS: 'moderation-submissions',
|
||||
MODERATION_REPORTS: 'moderation-reports',
|
||||
} as const;
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'sync-all-moderators-to-topic',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL');
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
||||
@@ -29,8 +28,9 @@ serve(async (req) => {
|
||||
const novu = new Novu({ secretKey: novuApiKey });
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
context.span.setAttribute('action', 'sync_moderators');
|
||||
edgeLogger.info('Starting moderator sync to Novu topics', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
action: 'sync_moderators'
|
||||
});
|
||||
|
||||
@@ -48,7 +48,7 @@ serve(async (req) => {
|
||||
const uniqueUserIds = [...new Set(moderatorRoles.map(r => r.user_id))];
|
||||
|
||||
edgeLogger.info('Found unique moderators to sync', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
count: uniqueUserIds.length
|
||||
});
|
||||
|
||||
@@ -62,12 +62,12 @@ serve(async (req) => {
|
||||
try {
|
||||
// Ensure topic exists (Novu will create it if it doesn't)
|
||||
await novu.topics.create({ key: topicKey, name: topicKey });
|
||||
edgeLogger.info('Topic ready', { requestId: tracking.requestId, topicKey });
|
||||
edgeLogger.info('Topic ready', { requestId: context.requestId, topicKey });
|
||||
} catch (error: any) {
|
||||
// Topic might already exist, which is fine
|
||||
if (!error.message?.includes('already exists')) {
|
||||
edgeLogger.warn('Note about topic', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
topicKey,
|
||||
error: error.message
|
||||
});
|
||||
@@ -90,20 +90,20 @@ serve(async (req) => {
|
||||
});
|
||||
},
|
||||
{ maxAttempts: 3, baseDelay: 2000 },
|
||||
tracking.requestId,
|
||||
context.requestId,
|
||||
`sync-batch-${topicKey}-${i}`
|
||||
);
|
||||
|
||||
successCount += batch.length;
|
||||
edgeLogger.info('Added batch of users to topic', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
topicKey,
|
||||
batchSize: batch.length
|
||||
});
|
||||
} catch (error: any) {
|
||||
errorCount += batch.length;
|
||||
edgeLogger.error('Error adding batch to topic', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
topicKey,
|
||||
batchSize: batch.length,
|
||||
error: error.message
|
||||
@@ -118,10 +118,8 @@ serve(async (req) => {
|
||||
});
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Sync completed', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
requestId: context.requestId,
|
||||
results
|
||||
});
|
||||
|
||||
@@ -130,39 +128,13 @@ serve(async (req) => {
|
||||
success: true,
|
||||
message: 'Moderator sync completed',
|
||||
results,
|
||||
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 syncing moderators to topics', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: error.message
|
||||
});
|
||||
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
||||
import { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('trigger-notification');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'trigger-notification',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
|
||||
if (!novuApiKey) {
|
||||
@@ -38,10 +37,11 @@ serve(async (req) => {
|
||||
? { subscriberId }
|
||||
: { topicKey: topicKey! };
|
||||
|
||||
context.span.setAttribute('action', 'trigger_notification');
|
||||
edgeLogger.info('Triggering notification', {
|
||||
workflowId,
|
||||
recipient,
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
action: 'trigger_notification'
|
||||
});
|
||||
|
||||
@@ -53,50 +53,21 @@ serve(async (req) => {
|
||||
});
|
||||
|
||||
edgeLogger.info('Notification triggered successfully', {
|
||||
requestId: tracking.requestId,
|
||||
requestId: context.requestId,
|
||||
transactionId: result.data.transactionId
|
||||
});
|
||||
|
||||
endRequest(tracking, 200);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
transactionId: result.data.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 triggering notification', {
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
||||
import { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest('update-novu-preferences');
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'update-novu-preferences',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
@@ -28,33 +27,16 @@ serve(async (req) => {
|
||||
|
||||
const { userId, preferences } = await req.json();
|
||||
|
||||
edgeLogger.info('Updating preferences for user', { userId, requestId: tracking.requestId });
|
||||
context.span.setAttribute('action', 'update_novu_preferences');
|
||||
edgeLogger.info('Updating preferences for user', { userId, requestId: context.requestId });
|
||||
|
||||
// Validate input
|
||||
if (!userId) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'userId is required',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('userId is required');
|
||||
}
|
||||
|
||||
if (!preferences?.channelPreferences) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'channelPreferences is required in preferences object',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
throw new Error('channelPreferences is required in preferences object');
|
||||
}
|
||||
|
||||
// Get Novu subscriber ID from database
|
||||
@@ -96,7 +78,7 @@ serve(async (req) => {
|
||||
edgeLogger.error('Failed to update channel preference', {
|
||||
channel: channelType,
|
||||
error: channelError.message,
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
results.push({
|
||||
channel: channelType,
|
||||
@@ -114,54 +96,24 @@ serve(async (req) => {
|
||||
if (!allSucceeded) {
|
||||
edgeLogger.warn('Some channel preferences failed to update', {
|
||||
failedChannels: failedChannels.map(c => c.channel),
|
||||
requestId: tracking.requestId
|
||||
requestId: context.requestId
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Some channel preferences failed to update',
|
||||
results,
|
||||
failedChannels: failedChannels.map(c => c.channel),
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 502, // Bad Gateway - external service failure
|
||||
}
|
||||
);
|
||||
throw new Error('Some channel preferences failed to update: ' + failedChannels.map(c => c.channel).join(', '));
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('All preferences updated successfully', {
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
results,
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error updating Novu preferences', {
|
||||
error: error.message,
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error.message,
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
||||
import { Novu } from "npm:@novu/api@1.6.0";
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { edgeLogger } from "../_shared/logger.ts";
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('update-novu-subscriber');
|
||||
|
||||
try {
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'update-novu-subscriber',
|
||||
requireAuth: false,
|
||||
corsHeaders: corsHeaders
|
||||
},
|
||||
async (req, context) => {
|
||||
const novuApiKey = Deno.env.get('NOVU_API_KEY');
|
||||
|
||||
if (!novuApiKey) {
|
||||
@@ -31,7 +30,8 @@ serve(async (req) => {
|
||||
data?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
edgeLogger.info('Updating Novu subscriber', { action: 'update_novu_subscriber', subscriberId, email, firstName, requestId: tracking.requestId });
|
||||
context.span.setAttribute('action', 'update_novu_subscriber');
|
||||
edgeLogger.info('Updating Novu subscriber', { action: 'update_novu_subscriber', subscriberId, email, firstName, requestId: context.requestId });
|
||||
|
||||
const subscriber = await novu.subscribers.update(subscriberId, {
|
||||
email,
|
||||
@@ -42,45 +42,19 @@ serve(async (req) => {
|
||||
data,
|
||||
});
|
||||
|
||||
edgeLogger.info('Subscriber updated successfully', { action: 'update_novu_subscriber', subscriberId: subscriber.data._id });
|
||||
|
||||
endRequest(tracking, 200);
|
||||
edgeLogger.info('Subscriber updated successfully', { action: 'update_novu_subscriber', subscriberId: subscriber.data._id, requestId: context.requestId });
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
subscriberId: subscriber.data._id,
|
||||
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 updating Novu subscriber', { action: 'update_novu_subscriber', error: errorMessage, requestId: tracking.requestId });
|
||||
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user