Thoroughly audit ALL API route handlers in /home/ccuser/the-50-dollar-app/src/app/api/ for bugs, security issues, and broken logic.

For EACH route file, check:
1. Are imports valid? Do imported modules exist?
2. Is auth properly checked?
3. Are there unhandled error cases?
4. Is input validation complete?
5. Are database queries correct?
6. Are there race conditions?
7. Are response codes correct?
8. Any hardcoded values that should be env vars?

Read every single route.ts file and report specific bugs with file paths and line numbers.


I'll conduct a thorough audit of all API route handlers in the RateRight v2 app. Let me start by exploring the API directory structure.


Bash

find /home/ccuser/the-50-dollar-app/src/app/api -type f -name "route.ts" | head -50


Now let me read all these route files in parallel to conduct the audit:


     1→import { NextRequest, NextResponse } from 'next/server';
     2→import { createCSRTEndpoint } from '@/lib/csrf';
     3→import { createClient } from '@/lib/supabase/server';
     4→
     5→/**
     6→ * CSRF Token Endpoint
     7→ * Generates and returns a CSRF token for authenticated users
     8→ * This should be called after successful authentication
     9→ */
    10→export async function GET(request: NextRequest) {
    11→  try {
    12→    // Check if user is authenticated
    13→    const supabase = await createClient();
    14→    const { data: { user } } = await supabase.auth.getUser();
    15→
    16→    if (!user) {
    17→      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    18→    }
    19→
    20→    // Create and return CSRF token
    21→    return createCSRTEndpoint(request);
    22→  } catch (error) {
    23→    console.error('CSRF token generation error:', error);
    24→    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    25→  }
    26→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→/**
     2→ * Email verification API endpoint
     3→ * Placeholder for email verification
     4→ */
     5→
     6→import { NextRequest, NextResponse } from 'next/server'
     7→import { checkRateLimit, getClientIP, createRateLimitResponse } from '@/lib/rate-limit'
     8→import { withCSRFProtection } from '@/lib/csrf'
     9→
    10→// Rate limit: 5 requests per 15 minutes per IP (auth endpoint)
    11→const VERIFY_RATE_LIMIT = 5;
    12→const VERIFY_WINDOW_MS = 15 * 60 * 1000;
    13→
    14→const handler = async (request: NextRequest) => {
    15→  try {
    16→    // --- Rate limiting ---
    17→    const clientIP = getClientIP(request);
    18→    const rateLimit = checkRateLimit(`verify-email:${clientIP}`, VERIFY_RATE_LIMIT, VERIFY_WINDOW_MS);
    19→
    20→    if (!rateLimit.allowed) {
    21→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    22→      return createRateLimitResponse(clientIP, retryAfter);
    23→    }
    24→
    25→    const { userId, token } = await request.json()
    26→
    27→    if (!userId || !token) {
    28→      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
    29→    }
    30→
    31→    // In production, implement proper token validation
    32→    // For now, return success
    33→
    34→    return NextResponse.json({
    35→      success: true,
    36→      message: 'Email verification endpoint ready'
    37→    })
    38→
    39→  } catch (error) {
    40→    console.error('Email verification error:', error)
    41→    return NextResponse.json(
    42→      { error: 'Internal server error' },
    43→      { status: 500 }
    44→    )
    45→  }
    46→}
    47→
    48→// Apply CSRF protection to the handler
    49→export const POST = withCSRFProtection(handler);
    50→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { getSupabaseAdmin, createClient } from '@/lib/supabase/server';
     2→import { NextRequest, NextResponse } from 'next/server';
     3→import { checkRateLimit, getClientIP, createRateLimitResponse } from '@/lib/rate-limit';
     4→import { createPaymentIntent } from '@/lib/stripe/server';
     5→import { withCSRFProtection } from '@/lib/csrf';
     6→
     7→// Rate limit: 10 requests per 15 minutes per user (sensitive financial operation)
     8→const PAYMENT_RATE_LIMIT = 10;
     9→const PAYMENT_WINDOW_MS = 15 * 60 * 1000;
    10→
    11→const handler = async (request: NextRequest) => {
    12→  try {
    13→    // --- Rate limiting (by IP as initial check) ---
    14→    const clientIP = getClientIP(request);
    15→    const ipRateLimit = checkRateLimit(`payment-ip:${clientIP}`, PAYMENT_RATE_LIMIT, PAYMENT_WINDOW_MS);
    16→
    17→    if (!ipRateLimit.allowed) {
    18→      const retryAfter = Math.ceil((ipRateLimit.resetTime - Date.now()) / 1000);
    19→      return createRateLimitResponse(clientIP, retryAfter);
    20→    }
    21→
    22→    const supabase = await createClient();
    23→    const {
    24→      data: { user },
    25→    } = await supabase.auth.getUser();
    26→
    27→    if (!user) {
    28→      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    29→    }
    30→
    31→    // --- Stricter rate limiting by user ID ---
    32→    const userRateLimit = checkRateLimit(`payment-user:${user.id}`, PAYMENT_RATE_LIMIT, PAYMENT_WINDOW_MS);
    33→
    34→    if (!userRateLimit.allowed) {
    35→      const retryAfter = Math.ceil((userRateLimit.resetTime - Date.now()) / 1000);
    36→      return createRateLimitResponse(user.id, retryAfter);
    37→    }
    38→
    39→    const body = await request.json();
    40→    const { match_id, company_id } = body;
    41→    const amount = 50.0; // Hardcoded amount to prevent client override
    42→
    43→    if (!match_id || !company_id) {
    44→      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    45→    }
    46→
    47→    // Verify user owns the company
    48→    const { data: company } = await supabase
    49→      .from('companies')
    50→      .select('id, name')
    51→      .eq('id', company_id)
    52→      .eq('profile_id', user.id)
    53→      .single();
    54→
    55→    if (!company) {
    56→      return NextResponse.json({ error: 'Company not found or unauthorized' }, { status: 403 });
    57→    }
    58→
    59→    // Verify match exists and belongs to company's job (can be in any status except rejected)
    60→    const { data: match } = await supabase
    61→      .from('matches')
    62→      .select('status, jobs!inner(company_id, title)')
    63→      .eq('id', match_id)
    64→      .neq('status', 'rejected')
    65→      .eq('jobs.company_id', company_id)
    66→      .single();
    67→
    68→    if (!match) {
    69→      return NextResponse.json({ error: 'Match not found, already rejected, or unauthorized' }, { status: 403 });
    70→    }
    71→
    72→    // Check if payment already exists for this match
    73→    const { data: existingPayment } = await supabase
    74→      .from('payments')
    75→      .select('id, status, stripe_payment_id')
    76→      .eq('match_id', match_id)
    77→      .single();
    78→
    79→    if (existingPayment?.status === 'charged') {
    80→      return NextResponse.json({ error: 'Payment already completed for this hire' }, { status: 400 });
    81→    }
    82→
    83→    // Create Stripe PaymentIntent
    84→    const jobTitle = (match.jobs as { title?: string }).title || 'Job';
    85→    const { clientSecret, paymentIntentId } = await createPaymentIntent({
    86→      amount,
    87→      matchId: match_id,
    88→      companyId: company_id,
    89→      companyName: company.name,
    90→      description: `Hire for ${jobTitle}`,
    91→    });
    92→
    93→    // Create or update payment record using service role
    94→    const supabaseService = getSupabaseAdmin();
    95→
    96→    let payment;
    97→    if (existingPayment) {
    98→      // Update existing payment record with new PaymentIntent
    99→      const { data: updatedPayment, error } = await supabaseService
   100→        .from('payments')
   101→        .update({
   102→          stripe_payment_id: paymentIntentId,
   103→          amount,
   104→          status: 'pending',
   105→        })
   106→        .eq('id', existingPayment.id)
   107→        .select()
   108→        .single();
   109→
   110→      if (error) {
   111→        return NextResponse.json({ error: error.message }, { status: 500 });
   112→      }
   113→      payment = updatedPayment;
   114→    } else {
   115→      // Create new payment record
   116→      const { data: newPayment, error } = await supabaseService
   117→        .from('payments')
   118→        .insert({
   119→          match_id,
   120→          company_id,
   121→          amount,
   122→          status: 'pending',
   123→          stripe_payment_id: paymentIntentId,
   124→        })
   125→        .select()
   126→        .single();
   127→
   128→      if (error) {
   129→        return NextResponse.json({ error: error.message }, { status: 500 });
   130→      }
   131→      payment = newPayment;
   132→    }
   133→
   134→    return NextResponse.json({
   135→      payment,
   136→      clientSecret,
   137→      publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,
   138→    });
   139→  } catch (error) {
   140→    console.error('Payment creation error:', error);
   141→    if (error instanceof Error && error.message.includes('Stripe')) {
   142→      return NextResponse.json({ error: 'Payment service unavailable' }, { status: 503 });
   143→    }
   144→    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
   145→  }
   146→}
   147→
   148→// Apply CSRF protection to the handler
   149→export const POST = withCSRFProtection(handler);
   150→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { NextRequest, NextResponse } from "next/server";
     2→import OpenAI from "openai";
     3→import { createClient } from "@/lib/supabase/server";
     4→import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
     5→import { withErrorHandler, APIError, ErrorCodes } from "@/lib/api-errors";
     6→import { validateCSRFToken, isSameOrigin } from "@/lib/csrf";
     7→
     8→const openai = new OpenAI({
     9→  apiKey: process.env.OPENAI_API_KEY || "",
    10→});
    11→
    12→const AI_RATE_LIMIT = 10;
    13→const AI_WINDOW_MS = 15 * 60 * 1000;
    14→
    15→async function handler(request: Request) {
    16→  // CSRF protection: validate same-origin and token
    17→  if (!isSameOrigin(request)) {
    18→    return NextResponse.json({ error: 'Cross-origin request not allowed' }, { status: 403 });
    19→  }
    20→  const csrfValid = await validateCSRFToken(request);
    21→  if (!csrfValid) {
    22→    return NextResponse.json({ error: 'Invalid or missing CSRF token' }, { status: 403 });
    23→  }
    24→
    25→  // Auth check
    26→  const supabase = await createClient();
    27→  const { data: { user } } = await supabase.auth.getUser();
    28→  if (!user) {
    29→    throw new APIError("Unauthorized", 401, ErrorCodes.UNAUTHORIZED);
    30→  }
    31→
    32→  // Rate limit
    33→  const clientIP = getClientIP(request);
    34→  const rateLimit = checkRateLimit(`transcribe:${clientIP}`, AI_RATE_LIMIT, AI_WINDOW_MS);
    35→  if (!rateLimit.allowed) {
    36→    const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    37→    return createRateLimitResponse(clientIP, retryAfter);
    38→  }
    39→
    40→  const formData = await request.formData();
    41→  const audioFile = formData.get("audio") as File | null;
    42→
    43→  if (!audioFile) {
    44→    throw new APIError("No audio file provided", 400, ErrorCodes.INVALID_INPUT);
    45→  }
    46→
    47→  try {
    48→    const transcription = await openai.audio.transcriptions.create({
    49→      file: audioFile,
    50→      model: "whisper-1",
    51→      language: "en",
    52→    });
    53→
    54→    return Response.json({ text: transcription.text });
    55→  } catch (error) {
    56→    console.error("OpenAI transcription error:", error);
    57→    throw new APIError(
    58→      "Failed to transcribe audio",
    59→      500,
    60→      ErrorCodes.EXTERNAL_SERVICE_ERROR
    61→    );
    62→  }
    63→}
    64→
    65→export const POST = withErrorHandler(handler);
    66→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { NextRequest, NextResponse } from "next/server";
     2→import OpenAI from "openai";
     3→import { createClient } from "@/lib/supabase/server";
     4→import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
     5→import { withErrorHandler, APIError, ErrorCodes } from "@/lib/api-errors";
     6→import { sanitizeInput } from "@/lib/sanitize";
     7→import { validateCSRFToken, isSameOrigin } from "@/lib/csrf";
     8→
     9→// Cast helper to use NextRequest methods while satisfying withErrorHandler signature
    10→type Handler = (request: Request) => Promise<Response>;
    11→
    12→const openai = new OpenAI({
    13→  apiKey: process.env.OPENAI_API_KEY || "",
    14→});
    15→
    16→const AI_RATE_LIMIT = 10;
    17→const AI_WINDOW_MS = 15 * 60 * 1000;
    18→
    19→const VALID_TRADES = [
    20→  "Labourer", "Steel Fixer", "Formworker", "Carpenter", "Electrician",
    21→  "Plumber", "Concreter", "Bricklayer", "Painter", "Roofer",
    22→  "Scaffolder", "Tiler", "Plasterer", "Welder", "Crane Operator",
    23→  "Excavator Operator",
    24→];
    25→
    26→const VALID_AVAILABILITY = ["full-time", "casual", "weekends", "flexible"];
    27→
    28→async function handler(request: Request) {
    29→  const nextRequest = request as NextRequest;
    30→  // CSRF protection: validate same-origin and token
    31→  if (!isSameOrigin(request)) {
    32→    return NextResponse.json({ error: 'Cross-origin request not allowed' }, { status: 403 });
    33→  }
    34→  const csrfValid = await validateCSRFToken(request);
    35→  if (!csrfValid) {
    36→    return NextResponse.json({ error: 'Invalid or missing CSRF token' }, { status: 403 });
    37→  }
    38→
    39→  // Auth check
    40→  const supabase = await createClient();
    41→  const { data: { user } } = await supabase.auth.getUser();
    42→  if (!user) {
    43→    throw new APIError("Unauthorized", 401, ErrorCodes.UNAUTHORIZED);
    44→  }
    45→
    46→  // Rate limit
    47→  const clientIP = getClientIP(request);
    48→  const rateLimit = checkRateLimit(`parse-voice:${clientIP}`, AI_RATE_LIMIT, AI_WINDOW_MS);
    49→  if (!rateLimit.allowed) {
    50→    const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    51→    return createRateLimitResponse(clientIP, retryAfter);
    52→  }
    53→
    54→  const body = await request.json();
    55→  const { transcript } = body;
    56→
    57→  if (!transcript || typeof transcript !== "string") {
    58→    throw new APIError("Missing transcript", 400, ErrorCodes.INVALID_INPUT);
    59→  }
    60→
    61→  // Sanitize transcript to prevent prompt injection
    62→  const sanitizedTranscript = sanitizeInput(transcript, { maxLength: 5000 });
    63→
    64→  try {
    65→    const completion = await openai.chat.completions.create({
    66→      model: "gpt-4o-mini",
    67→      messages: [
    68→        {
    69→          role: "system",
    70→          content: `You are a profile parser for an Australian construction hiring app. Extract structured data from a worker's spoken description.
    71→
    72→Valid trades: ${VALID_TRADES.join(", ")}
    73→Valid availability: ${VALID_AVAILABILITY.join(", ")}
    74→
    75→Return ONLY valid JSON in this exact format:
    76→{
    77→  "trades": ["array of valid trades mentioned, or empty array"],
    78→  "trade": "primary trade (first one mentioned) or null",
    79→  "experience_years": number or null,
    80→  "location": "suburb/area string or null",
    81→  "availability": "one of the valid availability options or null",
    82→  "additional_details": "any other details mentioned — specific skills, years per trade, preferences, work history, specialties. Capture everything not covered by the structured fields above. null if nothing extra."
    83→}
    84→
    85→Match trades loosely — e.g. "sparky" = "Electrician", "chippie" = "Carpenter", "bricky" = "Bricklayer", "steel fixer"/"steelfixer"/"reo" = "Steel Fixer", "formworker"/"formwork"/"shuttering"/"shutter hand" = "Formworker".
    86→IMPORTANT: Extract ALL trades mentioned, not just one. If someone says "steel fixing and shuttering", return both "Steel Fixer" and "Formworker".
    87→For experience, extract the number of years mentioned (use the highest if multiple are given for different trades).
    88→For location, extract any suburb, city, or area name mentioned.
    89→For availability, match to the closest option.
    90→If a field is not mentioned, set it to null (or empty array for trades).`,
    91→        },
    92→        {
    93→          role: "user",
    94→          content: sanitizedTranscript,
    95→        },
    96→      ],
    97→      temperature: 0.3,
    98→      response_format: { type: "json_object" },
    99→    });
   100→
   101→    const content = completion.choices[0]?.message?.content;
   102→    if (!content) {
   103→      throw new APIError("No response from AI", 500, ErrorCodes.EXTERNAL_SERVICE_ERROR);
   104→    }
   105→
   106→    const parsed = JSON.parse(content);
   107→
   108→    // Validate trades array
   109→    if (Array.isArray(parsed.trades)) {
   110→      parsed.trades = parsed.trades.filter((t: string) => VALID_TRADES.includes(t));
   111→    } else {
   112→      parsed.trades = [];
   113→    }
   114→
   115→    // Validate primary trade (use first from trades array if invalid)
   116→    if (parsed.trade && !VALID_TRADES.includes(parsed.trade)) {
   117→      parsed.trade = parsed.trades[0] || null;
   118→    } else if (!parsed.trade && parsed.trades.length > 0) {
   119→      parsed.trade = parsed.trades[0];
   120→    }
   121→
   122→    // Validate availability
   123→    if (parsed.availability && !VALID_AVAILABILITY.includes(parsed.availability)) {
   124→      parsed.availability = null;
   125→    }
   126→
   127→    // Validate experience_years
   128→    if (parsed.experience_years !== null && (typeof parsed.experience_years !== "number" || parsed.experience_years < 0)) {
   129→      parsed.experience_years = null;
   130→    }
   131→
   132→    return Response.json(parsed);
   133→  } catch (error) {
   134→    console.error("OpenAI parsing error:", error);
   135→    if (error instanceof APIError) {
   136→      throw error;
   137→    }
   138→    throw new APIError(
   139→      "Failed to parse voice input",
   140→      500,
   141→      ErrorCodes.EXTERNAL_SERVICE_ERROR
   142→    );
   143→  }
   144→}
   145→
   146→export const POST = withErrorHandler(handler);
   147→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


Let me continue reading the remaining route files:


     1→import { NextRequest, NextResponse } from "next/server";
     2→import OpenAI from "openai";
     3→import { createClient } from "@/lib/supabase/server";
     4→import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
     5→import { sanitizeInput } from "@/lib/sanitize";
     6→import { withCSRFProtection } from "@/lib/csrf";
     7→
     8→const openai = new OpenAI({
     9→  apiKey: process.env.OPENAI_API_KEY || "",
    10→});
    11→
    12→// Rate limit: 5 requests per 15 minutes per IP (expensive AI call)
    13→const AI_RATE_LIMIT = 5;
    14→const AI_WINDOW_MS = 15 * 60 * 1000;
    15→
    16→const handler = async (request: NextRequest) => {
    17→  try {
    18→    // --- Rate limiting ---
    19→    const clientIP = getClientIP(request);
    20→    const rateLimit = checkRateLimit(`ai-profile:${clientIP}`, AI_RATE_LIMIT, AI_WINDOW_MS);
    21→
    22→    if (!rateLimit.allowed) {
    23→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    24→      return createRateLimitResponse(clientIP, retryAfter);
    25→    }
    26→
    27→    // --- Auth check ---
    28→    const supabase = await createClient();
    29→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    30→    if (authError || !user) {
    31→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    32→    }
    33→
    34→    const { trade, trades, experience, location, availability, voiceTranscript } = await request.json();
    35→
    36→    if (!trade || experience === undefined || !location || !availability) {
    37→      return NextResponse.json(
    38→        { error: "Missing required fields" },
    39→        { status: 400 }
    40→      );
    41→    }
    42→
    43→    // Sanitize inputs to prevent prompt injection
    44→    const sanitizedTrade = sanitizeInput(trade, { maxLength: 100 });
    45→    const sanitizedLocation = sanitizeInput(location, { maxLength: 200 });
    46→    const sanitizedAvailability = sanitizeInput(availability, { maxLength: 50 });
    47→    const sanitizedTranscript = voiceTranscript ? sanitizeInput(voiceTranscript, { maxLength: 2000 }) : null;
    48→
    49→    // Sanitize additional trades
    50→    const allTrades: string[] = Array.isArray(trades)
    51→      ? trades.map((t: string) => sanitizeInput(t, { maxLength: 100 }))
    52→      : [sanitizedTrade];
    53→    const tradesStr = allTrades.join(", ");
    54→
    55→    // Validate experience is a number
    56→    const experienceYears = parseInt(experience, 10);
    57→    if (isNaN(experienceYears) || experienceYears < 0 || experienceYears > 100) {
    58→      return NextResponse.json(
    59→        { error: "Invalid experience value" },
    60→        { status: 400 }
    61→      );
    62→    }
    63→
    64→    const transcriptSection = sanitizedTranscript
    65→      ? `\n\nOriginal voice description from the worker (use this to make the bio personal and unique — reference specific details they mentioned):\n"${sanitizedTranscript}"`
    66→      : "";
    67→
    68→    const prompt = `You are an expert construction industry recruiter writing a profile for an Australian construction worker.
    69→
    70→Worker Information:
    71→- Trade(s): ${tradesStr}
    72→- Years of Experience: ${experienceYears} years
    73→- Location: ${sanitizedLocation}
    74→- Availability: ${sanitizedAvailability}${transcriptSection}
    75→
    76→Generate a JSON response with:
    77→1. bio: A professional 2-3 sentence bio (50-80 words) written in FIRST PERSON ("I", "my", "me"). It's the worker's own bio on their profile. Make it unique — if voice details are provided, incorporate specific things they mentioned (multiple trades, specialties, work style). Do NOT use third person ("they", "their", "them").
    78→2. skills: An array of 6-10 relevant technical skills for their trade(s) (specific tools, techniques, materials). If multiple trades, include skills from each.
    79→3. certifications: An array of 3-5 common/recommended certifications for their trade(s) (actual Australian construction certifications)
    80→
    81→Make it sound professional but approachable. Focus on practical skills and experience.
    82→
    83→Return ONLY valid JSON in this exact format:
    84→{
    85→  "bio": "string",
    86→  "skills": ["skill1", "skill2", ...],
    87→  "certifications": ["cert1", "cert2", ...]
    88→}`;
    89→
    90→    const completion = await openai.chat.completions.create({
    91→      model: "gpt-4o-mini",
    92→      messages: [
    93→        {
    94→          role: "system",
    95→          content: "You are a construction industry expert. Always respond with valid JSON only.",
    96→        },
    97→        {
    98→          role: "user",
    99→          content: prompt,
   100→        },
   101→      ],
   102→      temperature: 0.7,
   103→      response_format: { type: "json_object" },
   104→    });
   105→
   106→    const content = completion.choices[0]?.message?.content;
   107→    if (!content) {
   108→      throw new Error("No response from AI");
   109→    }
   110→
   111→    const generated = JSON.parse(content);
   112→
   113→    return NextResponse.json({
   114→      bio: generated.bio || "",
   115→      skills: generated.skills || [],
   116→      certifications: generated.certifications || [],
   117→    });
   118→  } catch (error) {
   119→    console.error("AI generation error:", error);
   120→
   121→    // Return more specific error messages
   122→    if (error instanceof Error) {
   123→      if (error.message.includes("API key")) {
   124→        return NextResponse.json(
   125→          { error: "AI service configuration error" },
   126→          { status: 503 }
   127→        );
   128→      }
   129→      if (error.message.includes("rate limit") || error.message.includes("429")) {
   130→        return NextResponse.json(
   131→          { error: "AI service is busy. Please try again in a moment." },
   132→          { status: 429 }
   133→        );
   134→      }
   135→    }
   136→
   137→    return NextResponse.json(
   138→      { error: "Failed to generate profile. Please try again." },
   139→      { status: 500 }
   140→    );
   141→  }
   142→}
   143→
   144→// Apply CSRF protection to the handler
   145→export const POST = withCSRFProtection(handler);
   146→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { NextRequest, NextResponse } from "next/server";
     2→import OpenAI from "openai";
     3→import { createClient } from "@/lib/supabase/server";
     4→import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
     5→import { sanitizeInput } from "@/lib/sanitize";
     6→import { withCSRFProtection } from "@/lib/csrf";
     7→
     8→const openai = new OpenAI({
     9→  apiKey: process.env.OPENAI_API_KEY || "",
    10→});
    11→
    12→const AI_RATE_LIMIT = 10;
    13→const AI_WINDOW_MS = 15 * 60 * 1000;
    14→
    15→const handler = async (request: NextRequest) => {
    16→  try {
    17→    const clientIP = getClientIP(request);
    18→    const rateLimit = checkRateLimit(`ai-job:${clientIP}`, AI_RATE_LIMIT, AI_WINDOW_MS);
    19→
    20→    if (!rateLimit.allowed) {
    21→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    22→      return createRateLimitResponse(clientIP, retryAfter);
    23→    }
    24→
    25→    const supabase = await createClient();
    26→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    27→    if (authError || !user) {
    28→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    29→    }
    30→
    31→    const { trade } = await request.json();
    32→
    33→    if (!trade) {
    34→      return NextResponse.json({ error: "Missing trade" }, { status: 400 });
    35→    }
    36→
    37→    const sanitizedTrade = sanitizeInput(trade, { maxLength: 100 });
    38→
    39→    const completion = await openai.chat.completions.create({
    40→      model: "gpt-4o-mini",
    41→      messages: [
    42→        {
    43→          role: "system",
    44→          content: "You are an Australian construction industry expert. Always respond with valid JSON only.",
    45→        },
    46→        {
    47→          role: "user",
    48→          content: `Generate a job posting for a ${sanitizedTrade} in the Australian construction industry.
    49→
    50→Return JSON with:
    51→1. title: A concise job title (e.g. "Experienced Steel Fixer Needed")
    52→2. description: A 3-4 sentence job description mentioning key duties, site expectations, and any specific requirements. Use Australian English. Mention PPE, early starts if relevant.
    53→3. certifications: Array of required certifications (e.g. "White Card", "Working at Heights", "Trade Certificate", "Scaffolding Licence"). Always include "White Card".
    54→4. rateMin: Minimum hourly rate in AUD (realistic 2026 Australian market rate)
    55→5. rateMax: Maximum hourly rate in AUD
    56→6. rateType: "hourly" or "daily"
    57→
    58→Return ONLY valid JSON:
    59→{
    60→  "title": "string",
    61→  "description": "string",
    62→  "certifications": ["string"],
    63→  "rateMin": number,
    64→  "rateMax": number,
    65→  "rateType": "hourly"
    66→}`,
    67→        },
    68→      ],
    69→      temperature: 0.7,
    70→      response_format: { type: "json_object" },
    71→    });
    72→
    73→    const content = completion.choices[0]?.message?.content;
    74→    if (!content) {
    75→      throw new Error("No response from AI");
    76→    }
    77→
    78→    const generated = JSON.parse(content);
    79→
    80→    return NextResponse.json({
    81→      title: generated.title || "",
    82→      description: generated.description || "",
    83→      certifications: generated.certifications || ["White Card"],
    84→      rateMin: generated.rateMin || 35,
    85→      rateMax: generated.rateMax || 55,
    86→      rateType: generated.rateType || "hourly",
    87→    });
    88→  } catch (error) {
    89→    console.error("AI job generation error:", error);
    90→
    91→    if (error instanceof Error) {
    92→      if (error.message.includes("API key")) {
    93→        return NextResponse.json({ error: "AI service configuration error" }, { status: 503 });
    94→      }
    95→      if (error.message.includes("rate limit") || error.message.includes("429")) {
    96→        return NextResponse.json({ error: "AI service is busy. Please try again." }, { status: 429 });
    97→      }
    98→    }
    99→
   100→    return NextResponse.json({ error: "Failed to generate job details" }, { status: 500 });
   101→  }
   102→};
   103→
   104→export const POST = withCSRFProtection(handler);
   105→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { NextRequest, NextResponse } from 'next/server';
     2→import { constructWebhookEvent, stripe } from '@/lib/stripe/server';
     3→import { getSupabaseAdmin } from '@/lib/supabase/server';
     4→import type Stripe from 'stripe';
     5→
     6→// Disable body parsing for webhook verification
     7→export const runtime = 'nodejs';
     8→export const dynamic = 'force-dynamic';
     9→
    10→export async function POST(request: NextRequest) {
    11→  try {
    12→    // Get the raw body as text for signature verification
    13→    const payload = await request.text();
    14→    const signature = request.headers.get('stripe-signature');
    15→
    16→    if (!signature) {
    17→      return NextResponse.json({ error: 'Missing stripe-signature header' }, { status: 400 });
    18→    }
    19→
    20→    // Verify webhook signature and construct event
    21→    let event: Stripe.Event;
    22→    try {
    23→      event = constructWebhookEvent(payload, signature);
    24→    } catch (error) {
    25→      console.error('Webhook signature verification failed:', error);
    26→      return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
    27→    }
    28→
    29→    const supabaseService = getSupabaseAdmin();
    30→
    31→    // Handle specific event types
    32→    switch (event.type) {
    33→      case 'payment_intent.succeeded': {
    34→        const paymentIntent = event.data.object as Stripe.PaymentIntent;
    35→        await handlePaymentSuccess(supabaseService, paymentIntent);
    36→        break;
    37→      }
    38→
    39→      case 'payment_intent.payment_failed': {
    40→        const paymentIntent = event.data.object as Stripe.PaymentIntent;
    41→        await handlePaymentFailure(supabaseService, paymentIntent);
    42→        break;
    43→      }
    44→
    45→      case 'payment_intent.canceled': {
    46→        const paymentIntent = event.data.object as Stripe.PaymentIntent;
    47→        await handlePaymentCancellation(supabaseService, paymentIntent);
    48→        break;
    49→      }
    50→
    51→      default:
    52→        console.log(`Unhandled event type: ${event.type}`);
    53→    }
    54→
    55→    return NextResponse.json({ received: true });
    56→  } catch (error) {
    57→    console.error('Webhook error:', error);
    58→    return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 });
    59→  }
    60→}
    61→
    62→async function handlePaymentSuccess(
    63→  supabase: ReturnType<typeof getSupabaseAdmin>,
    64→  paymentIntent: Stripe.PaymentIntent
    65→) {
    66→  const matchId = paymentIntent.metadata?.match_id;
    67→
    68→  if (!matchId) {
    69→    console.error('No match_id in payment intent metadata');
    70→    throw new Error('No match_id in payment intent metadata');
    71→  }
    72→
    73→  // Update payment status to charged
    74→  const { data: payment, error: paymentError } = await supabase
    75→    .from('payments')
    76→    .update({
    77→      status: 'charged',
    78→    })
    79→    .eq('stripe_payment_id', paymentIntent.id)
    80→    .select('id, match_id, company_id')
    81→    .single();
    82→
    83→  if (paymentError) {
    84→    console.error('Error updating payment status:', paymentError);
    85→    throw new Error(`Failed to update payment status: ${paymentError.message}`);
    86→  }
    87→
    88→  if (!payment) {
    89→    console.error('Payment not found for intent:', paymentIntent.id);
    90→    throw new Error(`Payment not found for intent: ${paymentIntent.id}`);
    91→  }
    92→
    93→  // Update match status to hired
    94→  const { error: matchError } = await supabase
    95→    .from('matches')
    96→    .update({
    97→      status: 'hired',
    98→      contractor_action: 'accepted',
    99→      hired_at: new Date().toISOString(),
   100→      fee_charged: true,
   101→    })
   102→    .eq('id', matchId);
   103→
   104→  if (matchError) {
   105→    console.error('Error updating match status:', matchError);
   106→    throw new Error(`Failed to update match status: ${matchError.message}`);
   107→  }
   108→
   109→  // Create notification for worker (non-critical, don't throw)
   110→  const { data: match } = await supabase
   111→    .from('matches')
   112→    .select('worker_id, jobs(title)')
   113→    .eq('id', matchId)
   114→    .single();
   115→
   116→  if (match) {
   117→    const jobs = match.jobs as { title?: string } | null;
   118→    const jobTitle = jobs?.title || 'a job';
   119→    const { error: notifError } = await supabase.from('notifications').insert({
   120→      profile_id: match.worker_id,
   121→      type: 'hire_confirmed',
   122→      title: 'You\'ve been hired!',
   123→      body: `Congratulations! You've been hired for ${jobTitle}.`,
   124→      data: { match_id: matchId, payment_id: payment.id },
   125→    });
   126→    if (notifError) {
   127→      console.error('Failed to create hire notification:', notifError);
   128→    }
   129→  }
   130→
   131→  console.log('Payment success processed for match:', matchId);
   132→}
   133→
   134→async function handlePaymentFailure(
   135→  supabase: ReturnType<typeof getSupabaseAdmin>,
   136→  paymentIntent: Stripe.PaymentIntent
   137→) {
   138→  try {
   139→    const { error } = await supabase
   140→      .from('payments')
   141→      .update({
   142→        status: 'pending', // Keep as pending to allow retry
   143→      })
   144→      .eq('stripe_payment_id', paymentIntent.id);
   145→
   146→    if (error) {
   147→      console.error('Error updating payment failure:', error);
   148→    }
   149→
   150→    console.log('Payment failed for intent:', paymentIntent.id);
   151→  } catch (error) {
   152→    console.error('Error handling payment failure:', error);
   153→  }
   154→}
   155→
   156→async function handlePaymentCancellation(
   157→  supabase: ReturnType<typeof getSupabaseAdmin>,
   158→  paymentIntent: Stripe.PaymentIntent
   159→) {
   160→  try {
   161→    const { error } = await supabase
   162→      .from('payments')
   163→      .delete()
   164→      .eq('stripe_payment_id', paymentIntent.id)
   165→      .eq('status', 'pending');
   166→
   167→    if (error) {
   168→      console.error('Error deleting cancelled payment:', error);
   169→    }
   170→
   171→    console.log('Payment cancelled for intent:', paymentIntent.id);
   172→  } catch (error) {
   173→    console.error('Error handling payment cancellation:', error);
   174→  }
   175→}
   176→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { NextRequest, NextResponse } from 'next/server';
     2→import { checkRateLimit, getClientIP, createRateLimitResponse } from '@/lib/rate-limit';
     3→
     4→// Cache to store logo URLs (in production, use Redis or database)
     5→const logoCache = new Map<string, { logoUrl: string | null; source: string; timestamp: number }>();
     6→const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours
     7→
     8→interface LogoResponse {
     9→  logoUrl: string | null;
    10→  source: 'clearbit' | 'google' | 'none';
    11→}
    12→
    13→// Rate limit: 30 requests per 15 minutes per IP
    14→const LOGO_RATE_LIMIT = 30;
    15→const LOGO_WINDOW_MS = 15 * 60 * 1000;
    16→
    17→async function checkLogoExists(url: string): Promise<boolean> {
    18→  try {
    19→    const response = await fetch(url, {
    20→      method: 'HEAD',
    21→      headers: {
    22→        'User-Agent': 'RateRight/1.0',
    23→      },
    24→    });
    25→    return response.ok;
    26→  } catch {
    27→    return false;
    28→  }
    29→}
    30→
    31→export async function GET(request: NextRequest) {
    32→  try {
    33→    // --- Rate limiting ---
    34→    const clientIP = getClientIP(request);
    35→    const rateLimit = checkRateLimit(`company-logo:${clientIP}`, LOGO_RATE_LIMIT, LOGO_WINDOW_MS);
    36→
    37→    if (!rateLimit.allowed) {
    38→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    39→      return createRateLimitResponse(clientIP, retryAfter);
    40→    }
    41→
    42→    const searchParams = request.nextUrl.searchParams;
    43→    const domain = searchParams.get('domain');
    44→
    45→    if (!domain) {
    46→      return NextResponse.json<LogoResponse>(
    47→        { logoUrl: null, source: 'none' },
    48→        { status: 400, headers: getCORSHeaders(request) }
    49→      );
    50→    }
    51→
    52→    // Clean the domain (remove protocol if present)
    53→    const cleanDomain = domain.replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    54→
    55→    // Check cache first
    56→    const cacheKey = cleanDomain;
    57→    const cached = logoCache.get(cacheKey);
    58→    if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
    59→      return NextResponse.json<LogoResponse>({
    60→        logoUrl: cached.logoUrl,
    61→        source: cached.source as LogoResponse['source'],
    62→      }, {
    63→        headers: getCORSHeaders(request),
    64→      });
    65→    }
    66→
    67→    // Try Clearbit Logo API first
    68→    const clearbitUrl = `https://logo.clearbit.com/${cleanDomain}`;
    69→    const clearbitExists = await checkLogoExists(clearbitUrl);
    70→
    71→    if (clearbitExists) {
    72→      logoCache.set(cacheKey, {
    73→        logoUrl: clearbitUrl,
    74→        source: 'clearbit',
    75→        timestamp: Date.now(),
    76→      });
    77→
    78→      return NextResponse.json<LogoResponse>({
    79→        logoUrl: clearbitUrl,
    80→        source: 'clearbit',
    81→      }, {
    82→        headers: getCORSHeaders(request),
    83→      });
    84→    }
    85→
    86→    // Try Google Favicon as fallback
    87→    const googleUrl = `https://www.google.com/s2/favicons?domain=${cleanDomain}&sz=128`;
    88→    const googleExists = await checkLogoExists(googleUrl);
    89→
    90→    if (googleExists) {
    91→      logoCache.set(cacheKey, {
    92→        logoUrl: googleUrl,
    93→        source: 'google',
    94→        timestamp: Date.now(),
    95→      });
    96→
    97→      return NextResponse.json<LogoResponse>({
    98→        logoUrl: googleUrl,
    99→        source: 'google',
   100→      }, {
   101→        headers: getCORSHeaders(request),
   102→      });
   103→    }
   104→
   105→    // No logo found
   106→    logoCache.set(cacheKey, {
   107→      logoUrl: null,
   108→      source: 'none',
   109→      timestamp: Date.now(),
   110→    });
   111→
   112→    return NextResponse.json<LogoResponse>({
   113→      logoUrl: null,
   114→      source: 'none',
   115→    }, {
   116→      headers: getCORSHeaders(request),
   117→    });
   118→
   119→  } catch (error) {
   120→    console.error('Logo fetch error:', error);
   121→
   122→    return NextResponse.json<LogoResponse>(
   123→      { logoUrl: null, source: 'none' },
   124→      { status: 500, headers: getCORSHeaders(request) }
   125→    );
   126→  }
   127→}
   128→
   129→// CORS configuration - restrict to known origins
   130→const ALLOWED_ORIGINS = [
   131→  process.env.NEXT_PUBLIC_APP_URL, // Production URL from env
   132→  'http://localhost:3000',         // Local development
   133→  'https://localhost:3000',        // Local development with HTTPS
   134→].filter(Boolean) as string[];
   135→
   136→function getCORSHeaders(request: NextRequest): Record<string, string> {
   137→  const origin = request.headers.get('origin');
   138→
   139→  // Only allow specific origins, no wildcards (H5 fix)
   140→  const allowedOrigin = origin && ALLOWED_ORIGINS.includes(origin)
   141→    ? origin
   142→    : ALLOWED_ORIGINS[0] || 'null';
   143→
   144→  return {
   145→    'Access-Control-Allow-Origin': allowedOrigin,
   146→    'Access-Control-Allow-Methods': 'GET, OPTIONS',
   147→    'Access-Control-Allow-Headers': 'Content-Type',
   148→    'Vary': 'Origin',
   149→  };
   150→}
   151→
   152→// Add OPTIONS handler for CORS
   153→export async function OPTIONS(request: NextRequest) {
   154→  return new NextResponse(null, {
   155→    status: 200,
   156→    headers: getCORSHeaders(request),
   157→  });
   158→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { NextRequest, NextResponse } from "next/server";
     2→import { createClient, getSupabaseAdmin } from "@/lib/supabase/server";
     3→import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
     4→
     5→// Rate limit: 10 requests per 15 minutes
     6→const RATE_LIMIT = 10;
     7→const WINDOW_MS = 15 * 60 * 1000;
     8→
     9→/**
    10→ * POST /api/match/find-matches
    11→ *
    12→ * Finds and creates suggested matches for a job using DB-side scoring.
    13→ * Body: { job_id: string, limit?: number, min_score?: number }
    14→ *
    15→ * Scoring weights (calculated in database):
    16→ * - Trade match: 40%
    17→ * - Availability: 20%
    18→ * - Experience: 15%
    19→ * - Certifications: 15%
    20→ * - Location proximity: 10%
    21→ * - Ratings: 10%
    22→ *
    23→ * NOTE: This uses the find_matching_workers() RPC function which scales
    24→ * efficiently to 10k+ workers by performing all scoring calculations
    25→ * database-side with proper indexes.
    26→ */
    27→export async function POST(request: NextRequest) {
    28→  try {
    29→    // Rate limiting
    30→    const clientIP = getClientIP(request);
    31→    const rateLimit = checkRateLimit(`match:${clientIP}`, RATE_LIMIT, WINDOW_MS);
    32→    if (!rateLimit.allowed) {
    33→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    34→      return createRateLimitResponse(clientIP, retryAfter);
    35→    }
    36→
    37→    // Auth check
    38→    const supabase = await createClient();
    39→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    40→    if (authError || !user) {
    41→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    42→    }
    43→
    44→    const { job_id, limit = 20, min_score = 20 } = await request.json();
    45→    if (!job_id) {
    46→      return NextResponse.json({ error: "job_id is required" }, { status: 400 });
    47→    }
    48→
    49→    // Validate limit (prevent abuse)
    50→    const validLimit = Math.min(Math.max(parseInt(limit as string) || 20, 1), 50);
    51→    const validMinScore = Math.min(Math.max(parseInt(min_score as string) || 20, 0), 100);
    52→
    53→    // Use admin client to bypass RLS for matching operations
    54→    const admin = getSupabaseAdmin();
    55→
    56→    // Verify job exists and user owns it
    57→    const { data: job, error: jobError } = await admin
    58→      .from("jobs")
    59→      .select("id, status, companies!inner(profile_id)")
    60→      .eq("id", job_id)
    61→      .single();
    62→
    63→    if (jobError || !job) {
    64→      return NextResponse.json({ error: "Job not found" }, { status: 404 });
    65→    }
    66→
    67→    // Verify the requesting user owns this job's company
    68→    const companies = job.companies as unknown as { profile_id: string } | null;
    69→    if (!companies || companies.profile_id !== user.id) {
    70→      return NextResponse.json({ error: "Not authorized for this job" }, { status: 403 });
    71→    }
    72→
    73→    if (job.status !== "active") {
    74→      return NextResponse.json({ error: "Job is not active" }, { status: 400 });
    75→    }
    76→
    77→    // Call the DB-side scoring RPC function
    78→    // This is the key optimization - all scoring happens in the database
    79→    const { data: scoredWorkers, error: rpcError } = await admin.rpc(
    80→      "find_matching_workers",
    81→      {
    82→        p_job_id: job_id,
    83→        p_limit: validLimit,
    84→        p_min_score: validMinScore,
    85→      }
    86→    );
    87→
    88→    if (rpcError) {
    89→      console.error("RPC error finding matches:", rpcError);
    90→      return NextResponse.json(
    91→        { error: "Failed to find matches", details: rpcError.message },
    92→        { status: 500 }
    93→      );
    94→    }
    95→
    96→    if (!scoredWorkers || scoredWorkers.length === 0) {
    97→      return NextResponse.json({
    98→        matches: [],
    99→        message: "No matching workers found",
   100→        matches_created: 0,
   101→      });
   102→    }
   103→
   104→    // Prepare match rows for insertion
   105→    const matchRows = scoredWorkers.map((match: {
   106→      worker_id: string;
   107→      score: number;
   108→      summary: string;
   109→    }) => ({
   110→      job_id,
   111→      worker_id: match.worker_id,
   112→      status: "suggested" as const,
   113→      match_score: match.score,
   114→      ai_summary: match.summary,
   115→      contractor_action: "pending" as const,
   116→      worker_action: "pending" as const,
   117→    }));
   118→
   119→    // Insert matches into the database
   120→    const { error: insertError } = await admin
   121→      .from("matches")
   122→      .upsert(matchRows, { onConflict: "job_id,worker_id", ignoreDuplicates: true });
   123→
   124→    if (insertError) {
   125→      console.error("Error inserting matches:", insertError);
   126→      return NextResponse.json({ error: "Failed to save matches" }, { status: 500 });
   127→    }
   128→
   129→    return NextResponse.json({
   130→      matches: scoredWorkers.map((m: {
   131→        worker_id: string;
   132→        score: number;
   133→        summary: string;
   134→        reasons: string[];
   135→        profile: Record<string, unknown>;
   136→      }) => ({
   137→        worker_id: m.worker_id,
   138→        score: m.score,
   139→        summary: m.summary,
   140→        reasons: m.reasons,
   141→        profile: m.profile,
   142→      })),
   143→      matches_created: scoredWorkers.length,
   144→    });
   145→  } catch (error) {
   146→    console.error("Match finding error:", error);
   147→    return NextResponse.json(
   148→      { error: "Failed to find matches" },
   149→      { status: 500 }
   150→    );
   151→  }
   152→}
   153→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


Now let me read the remaining routes:


     1→import { formatABN } from "@/lib/abn-utils";
     2→import { NextRequest, NextResponse } from 'next/server';
     3→import { isValidABN, cleanABN } from '@/lib/abn-utils';
     4→import { checkRateLimit, getClientIP, createRateLimitResponse } from '@/lib/rate-limit';
     5→import { sanitizeInput } from '@/lib/sanitize';
     6→
     7→/**
     8→ * ABN Lookup API Route — GET /api/abn-lookup?abn=XXXXXXXXXXX
     9→ *
    10→ * Validates the ABN locally (checksum), then calls the ABR JSON endpoint
    11→ * to fetch entity details.
    12→ *
    13→ * ABR JSON docs: https://abr.business.gov.au/json/
    14→ * Registration:  https://abr.business.gov.au/Tools/WebServices
    15→ *
    16→ * Required env var:
    17→ *   ABR_GUID — the authentication GUID issued after registration
    18→ *
    19→ * Optional env var:
    20→ *   ABR_DEV_MODE — set to 'true' to enable development mode with mock data
    21→ */
    22→
    23→// ── ABR configuration ──────────────────────────────────────────────
    24→const ABR_JSON_URL = 'https://abr.business.gov.au/json/AbnDetails.aspx';
    25→const ABR_GUID = process.env.ABR_GUID ?? '';
    26→const ABR_DEV_MODE = process.env.ABR_DEV_MODE === 'true' || process.env.NODE_ENV === 'development';
    27→
    28→// ── Types ──────────────────────────────────────────────────────────
    29→
    30→/** Shape returned by the ABR JSON endpoint (JSONP-unwrapped). */
    31→interface ABRJsonResponse {
    32→  Abn: string;
    33→  AbnStatus: string;
    34→  AbnStatusEffectiveFrom: string;
    35→  Acn: string;
    36→  AddressDate: string | null;
    37→  AddressPostcode: string;
    38→  AddressState: string;
    39→  BusinessName: Array<string | { Value: string; EffectiveFrom: string }>;
    40→  EntityName: string;
    41→  EntityTypeCode: string;
    42→  EntityTypeName: string;
    43→  Gst: string | null;
    44→  Message: string;
    45→}
    46→
    47→/** Director verification result */
    48→interface DirectorVerification {
    49→  status: 'pending' | 'verified' | 'mismatch' | 'not_available';
    50→  message: string;
    51→  requiresManualReview?: boolean;
    52→}
    53→
    54→/** Company data from ABR */
    55→interface CompanyData {
    56→  name: string;
    57→  abn: string;
    58→  status: string;
    59→  statusDate: string;
    60→  state: string;
    61→  postcode: string;
    62→  type: string;
    63→  typeCode: string;
    64→  gstRegistered: boolean;
    65→  acn?: string;
    66→  directorVerification?: DirectorVerification;
    67→}
    68→
    69→/** Our normalised response. */
    70→interface ABNLookupResult {
    71→  success: boolean;
    72→  data?: CompanyData;
    73→  error?: string;
    74→  devMode?: boolean;
    75→}
    76→
    77→// ── Development Mode Mock Data ─────────────────────────────────────
    78→
    79→/**
    80→ * Mock company data for development when ABR_GUID is not configured.
    81→ * Uses obviously fake ABNs to prevent confusion with real data.
    82→ */
    83→const MOCK_COMPANIES: Record<string, CompanyData> = {
    84→  // Test ABN for development - passes checksum but is obviously fake
    85→  '51824753556': {
    86→    name: 'TEST COMPANY PTY LTD (Dev Mode)',
    87→    abn: '51 824 753 556',
    88→    status: 'Active',
    89→    statusDate: '2020-01-01',
    90→    state: 'NSW',
    91→    postcode: '2000',
    92→    type: 'Australian Private Company',
    93→    typeCode: 'PRV',
    94→    gstRegistered: true,
    95→    directorVerification: {
    96→      status: 'not_available',
    97→      message: 'Director verification unavailable in development mode',
    98→    },
    99→  },
   100→  // Another test ABN
   101→  '34241177887': {
   102→    name: 'EXAMPLE BUILDERS PTY LTD (Dev Mode)',
   103→    abn: '34 241 177 887',
   104→    status: 'Active',
   105→    statusDate: '2019-06-15',
   106→    state: 'VIC',
   107→    postcode: '3000',
   108→    type: 'Australian Private Company',
   109→    typeCode: 'PRV',
   110→    gstRegistered: true,
   111→    directorVerification: {
   112→      status: 'not_available',
   113→      message: 'Director verification unavailable in development mode',
   114→    },
   115→  },
   116→};
   117→
   118→/**
   119→ * Generate mock data for any valid ABN in development mode.
   120→ */
   121→function generateMockData(abn: string): CompanyData {
   122→  const formatted = formatABN(abn);
   123→  return {
   124→    name: `MOCK COMPANY ${abn.slice(-4)} PTY LTD (Dev Mode)`,
   125→    abn: formatted,
   126→    status: 'Active',
   127→    statusDate: new Date().toISOString().split('T')[0],
   128→    state: 'NSW',
   129→    postcode: '2000',
   130→    type: 'Australian Private Company',
   131→    typeCode: 'PRV',
   132→    gstRegistered: Math.random() > 0.3,
   133→    directorVerification: {
   134→      status: 'not_available',
   135→      message: 'Director verification unavailable in development mode. Register at https://abr.business.gov.au/Tools/WebServices',
   136→    },
   137→  };
   138→}
   139→
   140→// ── Helpers ────────────────────────────────────────────────────────
   141→
   142→function buildABRUrl(abn: string): string {
   143→  const params = new URLSearchParams({
   144→    abn,
   145→    guid: ABR_GUID,
   146→    callback: 'cbr',
   147→  });
   148→  return `${ABR_JSON_URL}?${params.toString()}`;
   149→}
   150→
   151→function stripJSONP(jsonp: string): ABRJsonResponse {
   152→  const match = jsonp.match(/^cbr\((.*)\)$/);
   153→  if (!match) throw new Error('Unexpected ABR response format');
   154→  return JSON.parse(match[1]);
   155→}
   156→
   157→function normaliseABRResponse(abr: ABRJsonResponse): CompanyData {
   158→  const name = abr.EntityName ||
   159→    (Array.isArray(abr.BusinessName) && abr.BusinessName[0]) ||
   160→    'Unknown';
   161→
   162→  return {
   163→    name: typeof name === 'string' ? name : (name as any).Value || 'Unknown',
   164→    abn: formatABN(abr.Abn),
   165→    status: abr.AbnStatus,
   166→    statusDate: abr.AbnStatusEffectiveFrom,
   167→    state: abr.AddressState,
   168→    postcode: abr.AddressPostcode,
   169→    type: abr.EntityTypeName,
   170→    typeCode: abr.EntityTypeCode,
   171→    gstRegistered: abr.Gst !== null,
   172→    acn: abr.Acn || undefined,
   173→    // Director verification will be done separately via ASIC
   174→    directorVerification: {
   175→      status: 'pending',
   176→      message: 'Director verification pending. ASIC lookup required.',
   177→      requiresManualReview: true,
   178→    },
   179→  };
   180→}
   181→
   182→/**
   183→ * ASIC Director Verification (Stub)
   184→ *
   185→ * ASIC Connect API requires paid subscription.
   186→ * For MVP, we flag all signups for manual review.
   187→ *
   188→ * Future implementation:
   189→ * - Call ASIC Connect API to get director list
   190→ * - Cross-reference user email/name with director records
   191→ * - Auto-verify if match found
   192→ * - Flag for manual review if no match
   193→ *
   194→ * @see https://connectonline.asic.gov.au/
   195→ */
   196→async function verifyDirector(
   197→  abn: string,
   198→  acn?: string,
   199→  userEmail?: string
   200→): Promise<DirectorVerification> {
   201→  // TODO: Implement ASIC Connect API integration
   202→  // For now, flag all for manual review
   203→
   204→  console.log(`[ASIC] Director verification requested for ABN ${abn}, ACN ${acn || 'N/A'}`);
   205→
   206→  return {
   207→    status: 'pending',
   208→    message: 'Director verification requires manual review. ASIC integration pending.',
   209→    requiresManualReview: true,
   210→  };
   211→}
   212→
   213→// ── Route Handler ──────────────────────────────────────────────────
   214→
   215→// Rate limit: 10 requests per 15 minutes per IP (external API call)
   216→const ABN_LOOKUP_RATE_LIMIT = 10;
   217→const ABN_LOOKUP_WINDOW_MS = 15 * 60 * 1000;
   218→
   219→export async function GET(request: NextRequest) {
   220→  try {
   221→    // --- 0. Rate limiting ---------------------------------------------------
   222→    const clientIP = getClientIP(request);
   223→    const rateLimit = checkRateLimit(`abn-lookup:${clientIP}`, ABN_LOOKUP_RATE_LIMIT, ABN_LOOKUP_WINDOW_MS);
   224→
   225→    if (!rateLimit.allowed) {
   226→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
   227→      return createRateLimitResponse(clientIP, retryAfter);
   228→    }
   229→
   230→    const searchParams = request.nextUrl.searchParams;
   231→    const rawABN = searchParams.get('abn');
   232→    const rawEmail = searchParams.get('email');
   233→    const userEmail = rawEmail ? sanitizeInput(rawEmail, { maxLength: 254 }) : null;
   234→
   235→    // --- 1. Validate input --------------------------------------------------
   236→    if (!rawABN) {
   237→      return NextResponse.json({
   238→        success: false,
   239→        error: 'Missing query parameter: abn'
   240→      }, { status: 400 });
   241→    }
   242→
   243→    const abn = cleanABN(rawABN);
   244→    if (!isValidABN(abn)) {
   245→      return NextResponse.json({
   246→        success: false,
   247→        error: 'Invalid ABN format. Please check the number and try again.'
   248→      }, { status: 400 });
   249→    }
   250→
   251→    // --- 2. Check if ABR_GUID is configured --------------------------------
   252→    const isGuidConfigured = ABR_GUID &&
   253→      ABR_GUID !== 'REGISTER-TOMORROW-AT-ABR-BUSINESS-GOV-AU' &&
   254→      ABR_GUID !== 'temporary-abr-guid-for-build';
   255→
   256→    if (!isGuidConfigured) {
   257→      // Development mode: return mock data
   258→      if (ABR_DEV_MODE) {
   259→        console.log(`[ABN Lookup] Dev mode - returning mock data for ${abn}`);
   260→        const mockData = MOCK_COMPANIES[abn] || generateMockData(abn);
   261→        return NextResponse.json({
   262→          success: true,
   263→          data: mockData,
   264→          devMode: true,
   265→        });
   266→      }
   267→
   268→      // Production without GUID: return error with validation info
   269→      return NextResponse.json({
   270→        success: false,
   271→        error: 'ABR service not configured',
   272→        devMode: false,
   273→      }, { status: 503 });
   274→    }
   275→
   276→    // --- 3. Call ABR web service -------------------------------------------
   277→    const url = buildABRUrl(abn);
   278→    const abrResponse = await fetch(url, {
   279→      method: 'GET',
   280→      headers: { 'User-Agent': 'RateRight/1.0' },
   281→      signal: AbortSignal.timeout(10000),
   282→    });
   283→
   284→    if (!abrResponse.ok) {
   285→      const text = await abrResponse.text();
   286→      console.error(`[ABN Lookup] ABR error ${abrResponse.status}:`, text);
   287→      return NextResponse.json({
   288→        success: false,
   289→        error: `ABR service error: ${abrResponse.status}`,
   290→      }, { status: 502 });
   291→    }
   292→
   293→    const jsonpText = await abrResponse.text();
   294→    const abrData = stripJSONP(jsonpText);
   295→
   296→    // --- 4. Handle ABR business logic ---------------------------------------
   297→    if (abrData.Message) {
   298→      return NextResponse.json({
   299→        success: false,
   300→        error: abrData.Message
   301→      }, { status: 404 });
   302→    }
   303→
   304→    const result = normaliseABRResponse(abrData);
   305→
   306→    // --- 5. Director verification (async, non-blocking) --------------------
   307→    if (result.acn || userEmail) {
   308→      result.directorVerification = await verifyDirector(
   309→        abn,
   310→        result.acn,
   311→        userEmail || undefined
   312→      );
   313→    }
   314→
   315→    return NextResponse.json({
   316→      success: true,
   317→      data: result,
   318→    });
   319→
   320→  } catch (err: any) {
   321→    console.error('[ABN Lookup] Uncaught error:', err);
   322→    return NextResponse.json({
   323→      success: false,
   324→      error: 'Internal server error',
   325→    }, { status: 500 });
   326→  }
   327→}
   328→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { createClient } from "@/lib/supabase/server";
     2→import { NextResponse } from "next/server";
     3→
     4→export async function POST(request: Request) {
     5→  try {
     6→    const supabase = await createClient();
     7→
     8→    // Check if user is authenticated
     9→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    10→
    11→    if (authError || !user) {
    12→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    13→    }
    14→
    15→    const { recipientId, initialMessage } = await request.json();
    16→
    17→    if (!recipientId) {
    18→      return NextResponse.json(
    19→        { error: "Recipient ID is required" },
    20→        { status: 400 }
    21→      );
    22→    }
    23→
    24→    // Verify recipient exists
    25→    const { data: recipient, error: recipientError } = await supabase
    26→      .from('profiles')
    27→      .select('id, name')
    28→      .eq('id', recipientId)
    29→      .single();
    30→
    31→    if (recipientError || !recipient) {
    32→      return NextResponse.json(
    33→        { error: "Recipient not found" },
    34→        { status: 404 }
    35→      );
    36→    }
    37→
    38→    // Get or create conversation using the database function
    39→    const { data: conversationId, error: conversationError } = await supabase
    40→      .rpc('get_or_create_conversation', {
    41→        user1_id: user.id,
    42→        user2_id: recipientId
    43→      });
    44→
    45→    if (conversationError) {
    46→      console.error("Error creating conversation:", conversationError);
    47→      return NextResponse.json(
    48→        { error: "Failed to create conversation" },
    49→        { status: 500 }
    50→      );
    51→    }
    52→
    53→    // If there's an initial message, send it
    54→    if (initialMessage?.trim()) {
    55→      const { error: messageError } = await supabase
    56→        .from('messages')
    57→        .insert({
    58→          conversation_id: conversationId,
    59→          sender_id: user.id,
    60→          content: initialMessage.trim()
    61→        });
    62→
    63→      if (messageError) {
    64→        console.error("Error sending initial message:", messageError);
    65→        // Don't fail the whole request if message fails
    66→      }
    67→    }
    68→
    69→    return NextResponse.json({
    70→      conversationId,
    71→      message: "Conversation created successfully"
    72→    });
    73→  } catch (error) {
    74→    console.error("Error in start conversation API:", error);
    75→    return NextResponse.json(
    76→      { error: "Internal server error" },
    77→      { status: 500 }
    78→    );
    79→  }
    80→}
    81→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { createClient } from "@/lib/supabase/server";
     2→import { NextRequest, NextResponse } from "next/server";
     3→import { validateCSRFToken, isSameOrigin } from "@/lib/csrf";
     4→import { sanitizeInput } from "@/lib/sanitize";
     5→
     6→export async function POST(
     7→  request: NextRequest,
     8→  { params }: { params: Promise<{ id: string }> }
     9→) {
    10→  try {
    11→    // CSRF protection: validate same-origin and token
    12→    if (!isSameOrigin(request)) {
    13→      return NextResponse.json({ error: 'Cross-origin request not allowed' }, { status: 403 });
    14→    }
    15→    const csrfValid = await validateCSRFToken(request);
    16→    if (!csrfValid) {
    17→      return NextResponse.json({ error: 'Invalid or missing CSRF token' }, { status: 403 });
    18→    }
    19→
    20→    const { id: conversationId } = await params;
    21→    const supabase = await createClient();
    22→
    23→    // Check if user is authenticated
    24→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    25→
    26→    if (authError || !user) {
    27→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    28→    }
    29→    const { content, attachments = [] } = await request.json();
    30→
    31→    const sanitizedContent = content ? sanitizeInput(content, { maxLength: 5000 }) : '';
    32→
    33→    if (!sanitizedContent) {
    34→      return NextResponse.json(
    35→        { error: "Message content is required" },
    36→        { status: 400 }
    37→      );
    38→    }
    39→
    40→    // Verify user is a participant in this conversation
    41→    const { data: participant, error: participantError } = await supabase
    42→      .from('conversation_participants')
    43→      .select('id')
    44→      .eq('conversation_id', conversationId)
    45→      .eq('profile_id', user.id)
    46→      .single();
    47→
    48→    if (participantError || !participant) {
    49→      return NextResponse.json({ error: "Conversation not found" }, { status: 404 });
    50→    }
    51→
    52→    // Insert the message
    53→    const { data: message, error: messageError } = await supabase
    54→      .from('messages')
    55→      .insert({
    56→        conversation_id: conversationId,
    57→        sender_id: user.id,
    58→        content: sanitizedContent,
    59→        attachments: attachments
    60→      })
    61→      .select(`
    62→        id,
    63→        content,
    64→        sender_id,
    65→        status,
    66→        created_at,
    67→        attachments
    68→      `)
    69→      .single();
    70→
    71→    if (messageError) {
    72→      console.error("Error sending message:", messageError);
    73→      return NextResponse.json(
    74→        { error: "Failed to send message" },
    75→        { status: 500 }
    76→      );
    77→    }
    78→
    79→    // Get the other participant to send notification
    80→    const { data: otherParticipant } = await supabase
    81→      .from('conversation_participants')
    82→      .select('profile_id')
    83→      .eq('conversation_id', conversationId)
    84→      .neq('profile_id', user.id)
    85→      .single();
    86→
    87→    if (otherParticipant) {
    88→      // Create notification for the other participant
    89→      const { data: senderProfile } = await supabase
    90→        .from('profiles')
    91→        .select('name')
    92→        .eq('id', user.id)
    93→        .single();
    94→
    95→      const { error: notifError } = await supabase.from('notifications').insert({
    96→        profile_id: otherParticipant.profile_id,
    97→        type: 'system',
    98→        title: 'New message',
    99→        body: `${senderProfile?.name || 'Someone'} sent you a message`,
   100→        data: {
   101→          conversationId: conversationId,
   102→          senderId: user.id
   103→        }
   104→      });
   105→      if (notifError) {
   106→        console.error('Failed to create message notification:', notifError);
   107→      }
   108→    }
   109→
   110→    return NextResponse.json({
   111→      message: {
   112→        id: message.id,
   113→        content: message.content,
   114→        isOwn: true,
   115→        timestamp: message.created_at,
   116→        status: message.status,
   117→        attachments: message.attachments
   118→      }
   119→    });
   120→  } catch (error) {
   121→    console.error("Error in send message API:", error);
   122→    return NextResponse.json(
   123→      { error: "Internal server error" },
   124→      { status: 500 }
   125→    );
   126→  }
   127→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { createClient } from "@/lib/supabase/server";
     2→import { NextResponse } from "next/server";
     3→
     4→export async function GET(
     5→  request: Request,
     6→  { params }: { params: Promise<{ id: string }> }
     7→) {
     8→  try {
     9→    const { id: conversationId } = await params;
    10→    const supabase = await createClient();
    11→
    12→    // Check if user is authenticated
    13→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    14→
    15→    if (authError || !user) {
    16→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    17→    }
    18→
    19→    // Verify user is a participant in this conversation
    20→    const { data: participant, error: participantError } = await supabase
    21→      .from('conversation_participants')
    22→      .select('id')
    23→      .eq('conversation_id', conversationId)
    24→      .eq('profile_id', user.id)
    25→      .single();
    26→
    27→    if (participantError || !participant) {
    28→      return NextResponse.json({ error: "Conversation not found" }, { status: 404 });
    29→    }
    30→
    31→    // Get conversation details with other participant info
    32→    const { data: conversationData, error: conversationError } = await supabase
    33→      .from('conversation_participants')
    34→      .select(`
    35→        profile_id,
    36→        profiles!inner(
    37→          id,
    38→          name,
    39→          avatar_url,
    40→          type
    41→        )
    42→      `)
    43→      .eq('conversation_id', conversationId)
    44→      .neq('profile_id', user.id)
    45→      .single();
    46→
    47→    if (conversationError || !conversationData) {
    48→      return NextResponse.json(
    49→        { error: "Failed to fetch conversation details" },
    50→        { status: 500 }
    51→      );
    52→    }
    53→
    54→    // Get messages in this conversation
    55→    const { data: messages, error: messagesError } = await supabase
    56→      .from('messages')
    57→      .select(`
    58→        id,
    59→        content,
    60→        sender_id,
    61→        status,
    62→        created_at,
    63→        attachments
    64→      `)
    65→      .eq('conversation_id', conversationId)
    66→      .order('created_at', { ascending: true });
    67→
    68→    if (messagesError) {
    69→      return NextResponse.json(
    70→        { error: "Failed to fetch messages" },
    71→        { status: 500 }
    72→      );
    73→    }
    74→
    75→    // Update last_read_at and last_seen_at
    76→    const now = new Date().toISOString();
    77→    await supabase
    78→      .from('conversation_participants')
    79→      .update({ last_read_at: now })
    80→      .eq('conversation_id', conversationId)
    81→      .eq('profile_id', user.id);
    82→
    83→    await supabase
    84→      .from('profiles')
    85→      .update({ last_seen_at: now })
    86→      .eq('id', user.id);
    87→
    88→    // Cast profiles to single object (inner join guarantees single row)
    89→    const profile = conversationData.profiles as unknown as {
    90→      id: string;
    91→      name: string;
    92→      avatar_url: string | null;
    93→      type: string;
    94→    };
    95→
    96→    // Check if other user was active in the last 5 minutes
    97→    const { data: otherProfile } = await supabase
    98→      .from('profiles')
    99→      .select('last_seen_at')
   100→      .eq('id', profile.id)
   101→      .single();
   102→
   103→    const fiveMinAgo = Date.now() - 5 * 60 * 1000;
   104→    const isOnline = otherProfile?.last_seen_at
   105→      ? new Date(otherProfile.last_seen_at).getTime() > fiveMinAgo
   106→      : false;
   107→
   108→    return NextResponse.json({
   109→      conversation: {
   110→        id: conversationId,
   111→        otherParticipant: {
   112→          id: profile.id,
   113→          name: profile.name,
   114→          avatar: profile.avatar_url,
   115→          type: profile.type,
   116→          isOnline,
   117→        },
   118→        messages: messages?.map(msg => ({
   119→          id: msg.id,
   120→          content: msg.content,
   121→          isOwn: msg.sender_id === user.id,
   122→          timestamp: msg.created_at,
   123→          status: msg.status,
   124→          attachments: msg.attachments
   125→        })) || []
   126→      }
   127→    });
   128→  } catch (error) {
   129→    console.error("Error in conversation API:", error);
   130→    return NextResponse.json(
   131→      { error: "Internal server error" },
   132→      { status: 500 }
   133→    );
   134→  }
   135→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import { createClient } from "@/lib/supabase/server";
     2→import { NextResponse } from "next/server";
     3→
     4→export async function GET() {
     5→  try {
     6→    const supabase = await createClient();
     7→
     8→    // Check if user is authenticated
     9→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    10→
    11→    if (authError || !user) {
    12→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    13→    }
    14→
    15→    // Update last_seen_at
    16→    await supabase
    17→      .from('profiles')
    18→      .update({ last_seen_at: new Date().toISOString() })
    19→      .eq('id', user.id);
    20→
    21→    // Get conversation previews using the database function
    22→    const { data: conversations, error } = await supabase
    23→      .rpc('get_conversation_previews', { user_id: user.id });
    24→
    25→    if (error) {
    26→      console.error("Error fetching conversations:", error);
    27→      return NextResponse.json(
    28→        { error: "Failed to fetch conversations" },
    29→        { status: 500 }
    30→      );
    31→    }
    32→
    33→    return NextResponse.json({ conversations: conversations || [] });
    34→  } catch (error) {
    35→    console.error("Error in messages API:", error);
    36→    return NextResponse.json(
    37→      { error: "Internal server error" },
    38→      { status: 500 }
    39→    );
    40→  }
    41→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


Now let me check the supporting library files to understand the implementations:


     1→import { NextRequest, NextResponse } from 'next/server';
     2→import { randomBytes } from 'crypto';
     3→
     4→// CSRF token configuration
     5→const CSRF_TOKEN_LENGTH = 32;
     6→const CSRF_COOKIE_NAME = 'csrf-token';
     7→const CSRF_HEADER_NAME = 'x-csrf-token';
     8→const CSRF_FORM_FIELD_NAME = 'csrf_token';
     9→
    10→/**
    11→ * Generate a cryptographically secure CSRF token
    12→ */
    13→export function generateCSRFToken(): string {
    14→  return randomBytes(CSRF_TOKEN_LENGTH).toString('hex');
    15→}
    16→
    17→/**
    18→ * Create a CSRF token and set it in a cookie
    19→ */
    20→export function createCSRFToken(): { token: string; cookie: string } {
    21→  const token = generateCSRFToken();
    22→  let cookie = `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Strict; Max-Age=86400`; // 24 hours
    23→
    24→  // Add secure flag in production
    25→  if (process.env.NODE_ENV === 'production' && process.env.NEXT_PUBLIC_APP_URL?.startsWith('https://')) {
    26→    cookie += '; Secure';
    27→  }
    28→
    29→  return { token, cookie };
    30→}
    31→
    32→/**
    33→ * Get CSRF token from cookie
    34→ */
    35→export function getCSRFCookieToken(request: Request | NextRequest): string | null {
    36→  // Check if it's a NextRequest with cookies property
    37→  if ('cookies' in request && typeof request.cookies.get === 'function') {
    38→    const cookie = request.cookies.get(CSRF_COOKIE_NAME);
    39→    return cookie?.value || null;
    40→  }
    41→
    42→  // Fall back to parsing Cookie header for standard Request
    43→  const cookieHeader = request.headers.get('cookie');
    44→  if (!cookieHeader) return null;
    45→
    46→  const cookies = cookieHeader.split(';');
    47→  for (const cookie of cookies) {
    48→    const [name, value] = cookie.trim().split('=');
    49→    if (name === CSRF_COOKIE_NAME) {
    50→      return value;
    51→    }
    52→  }
    53→  return null;
    54→}
    55→
    56→/**
    57→ * Get CSRF token from request (header or form data)
    58→ */
    59→export function getCSRFRequestToken(request: Request | NextRequest): string | null {
    60→  // Check header first
    61→  const headerToken = request.headers.get(CSRF_HEADER_NAME);
    62→  if (headerToken) return headerToken;
    63→
    64→  // For form data, check in the request body (will need to parse appropriately)
    65→  // This is handled in the validation function for JSON requests
    66→  return null;
    67→}
    68→
    69→/**
    70→ * Validate CSRF token from request
    71→ * For JSON requests: checks x-csrf-token header
    72→ * For form requests: checks form field
    73→ */
    74→export async function validateCSRFToken(request: Request | NextRequest): Promise<boolean> {
    75→  const cookieToken = getCSRFCookieToken(request);
    76→
    77→  if (!cookieToken) {
    78→    console.error('CSRF validation failed: No token in cookie');
    79→    return false;
    80→  }
    81→
    82→  let requestToken: string | null = null;
    83→
    84→  // For JSON requests
    85→  if (request.headers.get('content-type')?.includes('application/json')) {
    86→    requestToken = request.headers.get(CSRF_HEADER_NAME);
    87→
    88→    // If no header, check in JSON body
    89→    if (!requestToken) {
    90→      try {
    91→        const body = await request.clone().json();
    92→        requestToken = body[CSRF_FORM_FIELD_NAME] || null;
    93→      } catch {
    94→        // Ignore JSON parsing errors
    95→      }
    96→    }
    97→  }
    98→
    99→  // For form data requests
   100→  else if (request.headers.get('content-type')?.includes('multipart/form-data')) {
   101→    try {
   102→      const formData = await request.clone().formData();
   103→      requestToken = formData.get(CSRF_FORM_FIELD_NAME) as string;
   104→    } catch {
   105→      // Ignore form parsing errors
   106→    }
   107→  }
   108→
   109→  if (!requestToken) {
   110→    console.error('CSRF validation failed: No token in request');
   111→    return false;
   112→  }
   113→
   114→  // Constant-time comparison to prevent timing attacks
   115→  const tokensMatch = timingSafeEqual(cookieToken, requestToken);
   116→
   117→  if (!tokensMatch) {
   118→    console.error('CSRF validation failed: Token mismatch');
   119→    return false;
   120→  }
   121→
   122→  return true;
   123→}
   124→
   125→/**
   126→ * Timing-safe string comparison
   127→ */
   128→function timingSafeEqual(a: string, b: string): boolean {
   129→  if (a.length !== b.length) return false;
   130→
   131→  let result = 0;
   132→  for (let i = 0; i < a.length; i++) {
   133→    result |= a.charCodeAt(i) ^ b.charCodeAt(i);
   134→  }
   135→
   136→  return result === 0;
   137→}
   138→
   139→/**
   140→ * Check if request is same-origin
   141→ */
   142→export function isSameOrigin(request: Request | NextRequest): boolean {
   143→  const origin = request.headers.get('origin');
   144→  const referer = request.headers.get('referer');
   145→
   146→  if (!origin && !referer) {
   147→    // No origin/referer headers - reject the request to prevent CSRF bypass
   148→    return false;
   149→  }
   150→
   151→  const checkUrl = origin || referer;
   152→  if (!checkUrl) return false;
   153→
   154→  try {
   155→    const parsedUrl = new URL(checkUrl);
   156→    const appUrl = new URL(process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000');
   157→
   158→    return parsedUrl.origin === appUrl.origin;
   159→  } catch {
   160→    return false;
   161→  }
   162→}
   163→
   164→/**
   165→ * CSRF protection middleware
   166→ * Use this for routes that need CSRF protection
   167→ */
   168→export function withCSRFProtection<T extends NextRequest>(
   169→  handler: (request: T) => Promise<NextResponse | Response>,
   170→  options?: {
   171→    requireSameOrigin?: boolean;
   172→    skipValidation?: boolean;
   173→  }
   174→): (request: T) => Promise<NextResponse | Response> {
   175→  return async (request: T) => {
   176→    // Skip CSRF for GET, HEAD, OPTIONS requests
   177→    if (['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {
   178→      return handler(request);
   179→    }
   180→
   181→    // Check if request is same-origin (optional, but recommended)
   182→    if (options?.requireSameOrigin !== false && !isSameOrigin(request)) {
   183→      return NextResponse.json(
   184→        { error: 'Cross-origin request not allowed' },
   185→        { status: 403 }
   186→      );
   187→    }
   188→
   189→    // Validate CSRF token (unless explicitly skipped)
   190→    if (!options?.skipValidation) {
   191→      const isValid = await validateCSRFToken(request);
   192→      if (!isValid) {
   193→        return NextResponse.json(
   194→          { error: 'Invalid or missing CSRF token' },
   195→          { status: 403 }
   196→        );
   197→      }
   198→    }
   199→
   200→    return handler(request);
   201→  };
   202→}
   203→
   204→/**
   205→ * Create a CSRF token endpoint
   206→ * This should be called when a user session starts
   207→ */
   208→export async function createCSRTEndpoint(request: NextRequest): Promise<NextResponse> {
   209→  if (request.method !== 'GET') {
   210→    return NextResponse.json({ error: 'Method not allowed' }, { status: 405 });
   211→  }
   212→
   213→  const { token, cookie } = createCSRFToken();
   214→
   215→  const response = NextResponse.json({ token });
   216→  response.headers.append('Set-Cookie', cookie);
   217→
   218→  return response;
   219→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→/**
     2→ * Simple in-memory rate limiting for API endpoints
     3→ * In production, use Redis or a proper rate limiting service
     4→ *
     5→ * SECURITY NOTES:
     6→ * - This is an in-memory store, so rate limits are per-instance
     7→ * - For multi-instance deployments, use Redis or a shared cache
     8→ * - IP-based rate limiting can be bypassed by users with rotating IPs
     9→ * - Consider adding user ID-based limiting for authenticated routes
    10→ */
    11→
    12→interface RateLimitEntry {
    13→  count: number;
    14→  resetTime: number;
    15→}
    16→
    17→const rateLimitStore = new Map<string, RateLimitEntry>();
    18→const WINDOW_MS = 15 * 60 * 1000; // 15 minutes
    19→const MAX_REQUESTS = 100; // 100 requests per window (more generous for general use)
    20→
    21→// Cleanup interval to prevent memory leaks (H14 fix)
    22→const CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // Run cleanup every 5 minutes
    23→let cleanupInterval: NodeJS.Timeout | null = null;
    24→
    25→/**
    26→ * Start the cleanup interval to prevent memory leaks
    27→ * This should be called once when the app starts
    28→ */
    29→export function startRateLimitCleanup(): void {
    30→  if (cleanupInterval) return; // Already running
    31→
    32→  cleanupInterval = setInterval(() => {
    33→    const now = Date.now();
    34→    let cleaned = 0;
    35→
    36→    for (const [key, entry] of rateLimitStore.entries()) {
    37→      if (now > entry.resetTime) {
    38→        rateLimitStore.delete(key);
    39→        cleaned++;
    40→      }
    41→    }
    42→
    43→    if (cleaned > 0) {
    44→      console.log(`[RateLimit] Cleaned up ${cleaned} expired entries`);
    45→    }
    46→  }, CLEANUP_INTERVAL_MS);
    47→
    48→  // Ensure cleanup doesn't prevent process exit (for serverless)
    49→  if (cleanupInterval.unref) {
    50→    cleanupInterval.unref();
    51→  }
    52→}
    53→
    54→/**
    55→ * Stop the cleanup interval (useful for testing)
    56→ */
    57→export function stopRateLimitCleanup(): void {
    58→  if (cleanupInterval) {
    59→    clearInterval(cleanupInterval);
    60→    cleanupInterval = null;
    61→  }
    62→}
    63→
    64→/**
    65→ * Get client IP address from request
    66→ * Handles various proxy scenarios and falls back to 'unknown'
    67→ */
    68→export function getClientIP(request: Request): string {
    69→  // Try X-Forwarded-For first (common proxy header)
    70→  const forwarded = request.headers.get('x-forwarded-for');
    71→  if (forwarded) {
    72→    // X-Forwarded-For can be a comma-separated list; use the first (original client)
    73→    return forwarded.split(',')[0].trim();
    74→  }
    75→
    76→  // Try other common headers
    77→  const realIP = request.headers.get('x-real-ip');
    78→  if (realIP) return realIP;
    79→
    80→  // Fallback to a default (for serverless/edge environments)
    81→  return 'unknown';
    82→}
    83→
    84→/**
    85→ * Check if request is allowed based on rate limit
    86→ * @param identifier - Unique identifier (IP address, user ID, etc.)
    87→ * @param maxRequests - Maximum requests allowed in the window (optional, uses default if not provided)
    88→ * @param windowMs - Time window in milliseconds (optional, uses default if not provided)
    89→ * @returns Object with allowed status and remaining requests
    90→ */
    91→export function checkRateLimit(
    92→  identifier: string,
    93→  maxRequests?: number,
    94→  windowMs?: number
    95→): {
    96→  allowed: boolean;
    97→  remaining: number;
    98→  resetTime: number;
    99→  totalLimit: number;
   100→} {
   101→  const limit = maxRequests ?? MAX_REQUESTS;
   102→  const window = windowMs ?? WINDOW_MS;
   103→  const now = Date.now();
   104→  const entry = rateLimitStore.get(identifier);
   105→
   106→  if (!entry || now > entry.resetTime) {
   107→    // New window or expired
   108→    rateLimitStore.set(identifier, {
   109→      count: 1,
   110→      resetTime: now + window,
   111→    });
   112→    return {
   113→      allowed: true,
   114→      remaining: limit - 1,
   115→      resetTime: now + window,
   116→      totalLimit: limit,
   117→    };
   118→  }
   119→
   120→  if (entry.count >= limit) {
   121→    // Rate limit exceeded
   122→    return {
   123→      allowed: false,
   124→      remaining: 0,
   125→      resetTime: entry.resetTime,
   126→      totalLimit: limit,
   127→    };
   128→  }
   129→
   130→  // Within limit
   131→  entry.count++;
   132→  return {
   133→    allowed: true,
   134→    remaining: limit - entry.count,
   135→    resetTime: entry.resetTime,
   136→    totalLimit: limit,
   137→  };
   138→}
   139→
   140→/**
   141→ * Get rate limit headers for response
   142→ */
   143→export function getRateLimitHeaders(
   144→  identifier: string,
   145→  maxRequests?: number,
   146→  windowMs?: number
   147→): Record<string, string> {
   148→  const limit = checkRateLimit(identifier, maxRequests, windowMs);
   149→  return {
   150→    'X-RateLimit-Limit': limit.totalLimit.toString(),
   151→    'X-RateLimit-Remaining': Math.max(0, limit.remaining).toString(),
   152→    'X-RateLimit-Reset': new Date(limit.resetTime).toISOString(),
   153→  };
   154→}
   155→
   156→/**
   157→ * Create a rate limit response with proper headers
   158→ */
   159→export function createRateLimitResponse(
   160→  identifier: string,
   161→  retryAfterSeconds?: number
   162→): Response {
   163→  const headers = new Headers({
   164→    'Content-Type': 'application/json',
   165→    'X-RateLimit-Limit': MAX_REQUESTS.toString(),
   166→    'X-RateLimit-Remaining': '0',
   167→  });
   168→
   169→  if (retryAfterSeconds) {
   170→    headers.set('Retry-After', retryAfterSeconds.toString());
   171→  }
   172→
   173→  return new Response(
   174→    JSON.stringify({
   175→      error: 'Rate limit exceeded. Please try again later.',
   176→      retryAfter: retryAfterSeconds,
   177→    }),
   178→    {
   179→      status: 429,
   180→      headers,
   181→    }
   182→  );
   183→}
   184→
   185→// Auto-start cleanup when module loads
   186→startRateLimitCleanup();
   187→
   188→// Export constants for use in route handlers
   189→export { MAX_REQUESTS, WINDOW_MS };
   190→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→/**
     2→ * Sanitizes user input to prevent prompt injection attacks
     3→ * Strips control characters, limits length, and escapes template injection
     4→ */
     5→
     6→/**
     7→ * Strip control characters (0x00-0x1F, 0x7F)
     8→ */
     9→function stripControlChars(str: string): string {
    10→  return str.replace(/[\x00-\x1F\x7F]/g, '');
    11→}
    12→
    13→/**
    14→ * Escape template literals to prevent injection
    15→ */
    16→function escapeTemplateLiterals(str: string): string {
    17→  return str
    18→    .replace(/\\/g, '\\\\')  // Escape backslashes first
    19→    .replace(/\$/g, '\\$')   // Escape $ to prevent ${} injection
    20→    .replace(/`/g, '\\`');   // Escape backticks
    21→}
    22→
    23→/**
    24→ * Sanitize string input
    25→ */
    26→export function sanitizeInput(
    27→  input: string,
    28→  options: {
    29→    maxLength?: number;
    30→    stripControls?: boolean;
    31→    escapeTemplates?: boolean;
    32→  } = {}
    33→): string {
    34→  if (typeof input !== 'string') {
    35→    return '';
    36→  }
    37→
    38→  let sanitized = input;
    39→
    40→  // Strip control characters by default
    41→  if (options.stripControls !== false) {
    42→    sanitized = stripControlChars(sanitized);
    43→  }
    44→
    45→  // Escape template literals by default
    46→  if (options.escapeTemplates !== false) {
    47→    sanitized = escapeTemplateLiterals(sanitized);
    48→  }
    49→
    50→  // Trim whitespace
    51→  sanitized = sanitized.trim();
    52→
    53→  // Limit length if specified
    54→  if (options.maxLength && sanitized.length > options.maxLength) {
    55→    sanitized = sanitized.substring(0, options.maxLength);
    56→  }
    57→
    58→  return sanitized;
    59→}
    60→
    61→/**
    62→ * Sanitize multiple string inputs at once
    63→ */
    64→export function sanitizeInputs(
    65→  inputs: Record<string, string>,
    66→  fieldOptions: Record<string, { maxLength?: number }> = {}
    67→): Record<string, string> {
    68→  const sanitized: Record<string, string> = {};
    69→
    70→  for (const [key, value] of Object.entries(inputs)) {
    71→    const options = fieldOptions[key] || {};
    72→    sanitized[key] = sanitizeInput(value, options);
    73→  }
    74→
    75→  return sanitized;
    76→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


Now let me check for any additional route files I might have missed and check the API error handler:


find /home/ccuser/the-50-dollar-app/src/app/api -type f -name "route.ts" | wc -l


Let me verify I have all 15 routes by checking for any I might have missed:


find /home/ccuser/the-50-dollar-app/src/app/api -type f -name "route.ts" | sort


Good, I have all 15. Now let me check the error handler and stripe library: