Do a very thorough analysis of ALL API routes and server-side code in /home/ccuser/the-50-dollar-app.

1. Find every API route (app/api/**/route.ts or similar)
2. For each route, read the full file and analyze:
   - HTTP methods supported (GET, POST, PUT, DELETE, PATCH)
   - Authentication/authorization checks
   - Input validation
   - Error handling
   - Database queries
   - Response format
3. Check for server actions (files with "use server" directive)
4. Look for any middleware
5. Check auth flow - how does login/signup/logout work?
6. Look for any broken imports, missing dependencies, or dead code
7. Check for security issues: SQL injection, missing auth checks, exposed secrets, CSRF

Report ALL findings with file paths and line numbers. Flag anything broken, insecure, or incomplete.


I'll conduct a thorough analysis of all API routes and server-side code in the repository. Let me start by exploring the structure.


Bash

find /home/ccuser/the-50-dollar-app -type f -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" | head -50


Let me look at the source structure more carefully:


total 1752
drwxrwxr-x  10 ccuser ccuser    4096 Feb  8 12:04 .
drwxr-x---  20 ccuser ccuser    4096 Feb  8 19:55 ..
-rw-r--r--   1 ccuser ccuser    2190 Feb  8 11:21 .env.local
drwxrwxr-x   8 ccuser ccuser    4096 Feb  8 19:32 .git
-rw-rw-r--   1 ccuser ccuser     496 Feb  8 11:18 .gitignore
drwxrwxr-x   8 ccuser ccuser    4096 Feb  8 19:24 .next
-rw-rw-r--   1 ccuser ccuser    4319 Feb  8 11:18 AI-PROFILE-BUILDER.md
-rw-rw-r--   1 ccuser ccuser    6216 Feb  8 11:18 APPLICATION-CODE-UPDATES-FOR-RLS-FIX.md
-rw-rw-r--   1 ccuser ccuser    5238 Feb  8 11:18 AUDIT-C3-COMPLETION.md
-rw-rw-r--   1 ccuser ccuser    2213 Feb  8 11:18 AUDIT-C4-COMPLETION.md
-rw-rw-r--   1 ccuser ccuser    6276 Feb  8 11:18 AUDIT-C5-COMPLETION.md
-rw-rw-r--   1 ccuser ccuser    5447 Feb  8 11:18 AUDIT-H1-H5-H11-H14-M16-M17-COMPLETION.md
-rw-rw-r--   1 ccuser ccuser    4394 Feb  8 11:18 CLAUDE.md
-rw-rw-r--   1 ccuser ccuser    3115 Feb  8 11:18 CSRF_IMPLEMENTATION.md
-rw-rw-r--   1 ccuser ccuser   13785 Feb  8 11:18 PRODUCT-SPEC.md
-rw-rw-r--   1 ccuser ccuser    2179 Feb  8 11:18 README.md
-rw-rw-r--   1 ccuser ccuser    9184 Feb  8 11:18 SUPABASE-KEY-ROTATION-GUIDE.md
-rw-rw-r--   1 ccuser ccuser    8977 Feb  8 11:18 UX-IMPLEMENTATION-GUIDE.md
-rw-rw-r--   1 ccuser ccuser    3480 Feb  8 11:18 VERCEL-DEPLOYMENT.md
-rw-rw-r--   1 ccuser ccuser     467 Feb  8 11:18 components.json
drwxrwxr-x   2 ccuser ccuser    4096 Feb  8 11:18 docs
-rw-rw-r--   1 ccuser ccuser     465 Feb  8 11:18 eslint.config.mjs
-rw-rw-r--   1 ccuser ccuser     247 Feb  8 11:23 next-env.d.ts
-rw-rw-r--   1 ccuser ccuser    1651 Feb  8 11:18 next.config.ts
drwxr-xr-x 321 ccuser ccuser   12288 Feb  7 20:58 node_modules
-rw-rw-r--   1 ccuser ccuser  305740 Feb  8 11:18 package-lock.json
-rw-rw-r--   1 ccuser ccuser    1080 Feb  8 11:18 package.json
-rw-rw-r--   1 ccuser ccuser      94 Feb  8 11:18 postcss.config.mjs
drwxrwxr-x   2 ccuser ccuser    4096 Feb  8 11:18 public
drwxrwxr-x   2 ccuser ccuser    4096 Feb  8 11:18 scripts
drwxrwxr-x   5 ccuser ccuser    4096 Feb  8 11:18 src
drwxrwxr-x   4 ccuser ccuser    4096 Feb  8 11:18 supabase
-rw-rw-r--   1 ccuser ccuser     753 Feb  8 11:18 tsconfig.json
-rw-rw-r--   1 ccuser ccuser 1289934 Feb  8 19:24 tsconfig.tsbuildinfo
-rw-rw-r--   1 ccuser ccuser     474 Feb  8 11:18 vercel.json


Now let me explore the src directory to find all API routes:


find /home/ccuser/the-50-dollar-app/src -type f \( -name "*.ts" -o -name "*.tsx" \) | sort


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

<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→// 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, experience, location, availability } = 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→
    48→    // Validate experience is a number
    49→    const experienceYears = parseInt(experience, 10);
    50→    if (isNaN(experienceYears) || experienceYears < 0 || experienceYears > 100) {
    51→      return NextResponse.json(
    52→        { error: "Invalid experience value" },
    53→        { status: 400 }
    54→      );
    55→    }
    56→
    57→    const prompt = `You are an expert construction industry recruiter. Based on the following information about a construction worker, generate a professional profile.
    58→
    59→Worker Information:
    60→- Trade: ${sanitizedTrade}
    61→- Years of Experience: ${experienceYears} years
    62→- Location: ${sanitizedLocation}
    63→- Availability: ${sanitizedAvailability}
    64→
    65→Generate a JSON response with:
    66→1. bio: A professional 2-3 sentence bio (50-80 words) highlighting their expertise, experience, and work style
    67→2. skills: An array of 6-10 relevant technical skills for their trade (specific tools, techniques, materials)
    68→3. certifications: An array of 3-5 common/recommended certifications for their trade (actual Australian construction certifications)
    69→
    70→Make it sound professional but approachable. Focus on practical skills and experience.
    71→
    72→Return ONLY valid JSON in this exact format:
    73→{
    74→  "bio": "string",
    75→  "skills": ["skill1", "skill2", ...],
    76→  "certifications": ["cert1", "cert2", ...]
    77→}`;
    78→
    79→    const completion = await openai.chat.completions.create({
    80→      model: "gpt-4o-mini",
    81→      messages: [
    82→        {
    83→          role: "system",
    84→          content: "You are a construction industry expert. Always respond with valid JSON only.",
    85→        },
    86→        {
    87→          role: "user",
    88→          content: prompt,
    89→        },
    90→      ],
    91→      temperature: 0.7,
    92→      response_format: { type: "json_object" },
    93→    });
    94→
    95→    const content = completion.choices[0]?.message?.content;
    96→    if (!content) {
    97→      throw new Error("No response from AI");
    98→    }
    99→
   100→    const generated = JSON.parse(content);
   101→
   102→    return NextResponse.json({
   103→      bio: generated.bio || "",
   104→      skills: generated.skills || [],
   105→      certifications: generated.certifications || [],
   106→    });
   107→  } catch (error) {
   108→    console.error("AI generation error:", error);
   109→
   110→    // Return more specific error messages
   111→    if (error instanceof Error) {
   112→      if (error.message.includes("API key")) {
   113→        return NextResponse.json(
   114→          { error: "AI service configuration error" },
   115→          { status: 503 }
   116→        );
   117→      }
   118→      if (error.message.includes("rate limit") || error.message.includes("429")) {
   119→        return NextResponse.json(
   120→          { error: "AI service is busy. Please try again in a moment." },
   121→          { status: 429 }
   122→        );
   123→      }
   124→    }
   125→
   126→    return NextResponse.json(
   127→      { error: "Failed to generate profile. Please try again." },
   128→      { status: 500 }
   129→    );
   130→  }
   131→}
   132→
   133→// Apply CSRF protection to the handler
   134→export const POST = withCSRFProtection(handler);
   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 { 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→  "trade": "one of the valid trades or null",
    78→  "experience_years": number or null,
    79→  "location": "suburb/area string or null",
    80→  "availability": "one of the valid availability options or null"
    81→}
    82→
    83→Match trades loosely — e.g. "sparky" = "Electrician", "chippie" = "Carpenter", "bricky" = "Bricklayer".
    84→For experience, extract the number of years mentioned.
    85→For location, extract any suburb, city, or area name mentioned.
    86→For availability, match to the closest option.
    87→If a field is not mentioned, set it to null.`,
    88→        },
    89→        {
    90→          role: "user",
    91→          content: sanitizedTranscript,
    92→        },
    93→      ],
    94→      temperature: 0.3,
    95→      response_format: { type: "json_object" },
    96→    });
    97→
    98→    const content = completion.choices[0]?.message?.content;
    99→    if (!content) {
   100→      throw new APIError("No response from AI", 500, ErrorCodes.EXTERNAL_SERVICE_ERROR);
   101→    }
   102→
   103→    const parsed = JSON.parse(content);
   104→
   105→    // Validate trade
   106→    if (parsed.trade && !VALID_TRADES.includes(parsed.trade)) {
   107→      parsed.trade = null;
   108→    }
   109→
   110→    // Validate availability
   111→    if (parsed.availability && !VALID_AVAILABILITY.includes(parsed.availability)) {
   112→      parsed.availability = null;
   113→    }
   114→
   115→    // Validate experience_years
   116→    if (parsed.experience_years !== null && (typeof parsed.experience_years !== "number" || parsed.experience_years < 0)) {
   117→      parsed.experience_years = null;
   118→    }
   119→
   120→    return Response.json(parsed);
   121→  } catch (error) {
   122→    console.error("OpenAI parsing error:", error);
   123→    if (error instanceof APIError) {
   124→      throw error;
   125→    }
   126→    throw new APIError(
   127→      "Failed to parse voice input",
   128→      500,
   129→      ErrorCodes.EXTERNAL_SERVICE_ERROR
   130→    );
   131→  }
   132→}
   133→
   134→export const POST = withErrorHandler(handler);
   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 { 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 { 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>


Let me continue reading the remaining API routes:


     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.
    13→ * Body: { job_id: string }
    14→ *
    15→ * Scoring weights:
    16→ * - Trade match: 40%
    17→ * - Availability: 20%
    18→ * - Experience: 15%
    19→ * - Certifications: 15%
    20→ * - Ratings: 10%
    21→ */
    22→export async function POST(request: NextRequest) {
    23→  try {
    24→    // Rate limiting
    25→    const clientIP = getClientIP(request);
    26→    const rateLimit = checkRateLimit(`match:${clientIP}`, RATE_LIMIT, WINDOW_MS);
    27→    if (!rateLimit.allowed) {
    28→      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
    29→      return createRateLimitResponse(clientIP, retryAfter);
    30→    }
    31→
    32→    // Auth check
    33→    const supabase = await createClient();
    34→    const { data: { user }, error: authError } = await supabase.auth.getUser();
    35→    if (authError || !user) {
    36→      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    37→    }
    38→
    39→    const { job_id } = await request.json();
    40→    if (!job_id) {
    41→      return NextResponse.json({ error: "job_id is required" }, { status: 400 });
    42→    }
    43→
    44→    // Use admin client to bypass RLS for matching operations
    45→    const admin = getSupabaseAdmin();
    46→
    47→    // Get the job details
    48→    const { data: job, error: jobError } = await admin
    49→      .from("jobs")
    50→      .select("*, companies!inner(profile_id)")
    51→      .eq("id", job_id)
    52→      .single();
    53→
    54→    if (jobError || !job) {
    55→      return NextResponse.json({ error: "Job not found" }, { status: 404 });
    56→    }
    57→
    58→    // Verify the requesting user owns this job's company
    59→    if (job.companies.profile_id !== user.id) {
    60→      return NextResponse.json({ error: "Not authorized for this job" }, { status: 403 });
    61→    }
    62→
    63→    if (job.status !== "active") {
    64→      return NextResponse.json({ error: "Job is not active" }, { status: 400 });
    65→    }
    66→
    67→    // Get all workers with completed profiles
    68→    const { data: workers, error: workersError } = await admin
    69→      .from("worker_profiles")
    70→      .select("*, profiles!inner(id, suburb, location, onboarding_completed)")
    71→      .eq("profiles.onboarding_completed", true);
    72→
    73→    if (workersError) {
    74→      console.error("Error fetching workers:", workersError);
    75→      return NextResponse.json({ error: "Failed to fetch workers" }, { status: 500 });
    76→    }
    77→
    78→    if (!workers || workers.length === 0) {
    79→      return NextResponse.json({ matches: [], message: "No workers available" });
    80→    }
    81→
    82→    // Get existing matches for this job to avoid duplicates
    83→    const { data: existingMatches } = await admin
    84→      .from("matches")
    85→      .select("worker_id")
    86→      .eq("job_id", job_id);
    87→
    88→    const existingWorkerIds = new Set((existingMatches || []).map((m: { worker_id: string }) => m.worker_id));
    89→
    90→    // Get ratings for all workers
    91→    const workerIds = workers.map((w: { profiles: { id: string } }) => w.profiles.id);
    92→    const { data: ratings } = await admin
    93→      .from("ratings")
    94→      .select("to_id, score")
    95→      .in("to_id", workerIds);
    96→
    97→    // Calculate average ratings per worker
    98→    const avgRatings: Record<string, { total: number; count: number }> = {};
    99→    if (ratings) {
   100→      for (const r of ratings) {
   101→        if (!avgRatings[r.to_id]) {
   102→          avgRatings[r.to_id] = { total: 0, count: 0 };
   103→        }
   104→        avgRatings[r.to_id].total += r.score;
   105→        avgRatings[r.to_id].count += 1;
   106→      }
   107→    }
   108→
   109→    // Score each worker
   110→    const scoredWorkers: Array<{
   111→      worker_id: string;
   112→      score: number;
   113→      summary: string;
   114→      reasons: string[];
   115→    }> = [];
   116→
   117→    for (const worker of workers) {
   118→      const workerId = worker.profiles.id;
   119→
   120→      // Skip already-matched workers
   121→      if (existingWorkerIds.has(workerId)) continue;
   122→
   123→      let score = 0;
   124→      const reasons: string[] = [];
   125→
   126→      // 1. Trade match (40 points)
   127→      const workerTrades: string[] = worker.trades || [];
   128→      if (workerTrades.includes(job.trade)) {
   129→        score += 40;
   130→        reasons.push(`Trades as ${job.trade}`);
   131→      } else {
   132→        // Partial match for related trades
   133→        const relatedTradeScore = getRelatedTradeScore(job.trade, workerTrades);
   134→        score += relatedTradeScore;
   135→        if (relatedTradeScore > 0) {
   136→          reasons.push("Related trade experience");
   137→        }
   138→      }
   139→
   140→      // 2. Availability match (20 points)
   141→      const availScore = getAvailabilityScore(job, worker.availability);
   142→      score += availScore;
   143→      if (availScore > 0) {
   144→        reasons.push(`Available ${worker.availability}`);
   145→      }
   146→
   147→      // 3. Experience (15 points)
   148→      const expScore = getExperienceScore(worker.experience_years);
   149→      score += expScore;
   150→      if (worker.experience_years) {
   151→        reasons.push(`${worker.experience_years}+ years experience`);
   152→      }
   153→
   154→      // 4. Certifications match (15 points)
   155→      const certScore = getCertificationScore(
   156→        job.certifications_required || [],
   157→        worker.certifications || []
   158→      );
   159→      score += certScore;
   160→      if (certScore > 0) {
   161→        const matched = (job.certifications_required || []).filter(
   162→          (c: string) => (worker.certifications || []).includes(c)
   163→        );
   164→        if (matched.length > 0) {
   165→          reasons.push(`Has ${matched.join(", ")}`);
   166→        }
   167→      }
   168→
   169→      // 5. Location proximity (bonus: up to 10 points)
   170→      const locScore = getLocationScore(job.suburb, worker.profiles.suburb);
   171→      score += locScore;
   172→      if (locScore > 0) {
   173→        reasons.push(`Based in ${worker.profiles.suburb}`);
   174→      }
   175→
   176→      // 6. Ratings (10 points)
   177→      const ratingData = avgRatings[workerId];
   178→      if (ratingData && ratingData.count > 0) {
   179→        const avg = ratingData.total / ratingData.count;
   180→        const ratingScore = Math.round((avg / 5) * 10);
   181→        score += ratingScore;
   182→        if (avg >= 4) {
   183→          reasons.push(`${avg.toFixed(1)} star rating`);
   184→        }
   185→      }
   186→
   187→      // Only include workers with a meaningful match score (>= 20)
   188→      if (score >= 20) {
   189→        const summary = reasons.slice(0, 3).join(". ") + ".";
   190→        scoredWorkers.push({
   191→          worker_id: workerId,
   192→          score: Math.min(score, 100),
   193→          summary,
   194→          reasons,
   195→        });
   196→      }
   197→    }
   198→
   199→    // Sort by score descending
   200→    scoredWorkers.sort((a, b) => b.score - a.score);
   201→
   202→    // Take top 20 matches
   203→    const topMatches = scoredWorkers.slice(0, 20);
   204→
   205→    // Insert matches into the database
   206→    if (topMatches.length > 0) {
   207→      const matchRows = topMatches.map((m) => ({
   208→        job_id,
   209→        worker_id: m.worker_id,
   210→        status: "suggested" as const,
   211→        match_score: m.score,
   212→        ai_summary: m.summary,
   213→        contractor_action: "pending" as const,
   214→        worker_action: "pending" as const,
   215→      }));
   216→
   217→      const { error: insertError } = await admin
   218→        .from("matches")
   219→        .upsert(matchRows, { onConflict: "job_id,worker_id", ignoreDuplicates: true });
   220→
   221→      if (insertError) {
   222→        console.error("Error inserting matches:", insertError);
   223→        return NextResponse.json({ error: "Failed to save matches" }, { status: 500 });
   224→      }
   225→    }
   226→
   227→    return NextResponse.json({
   228→      matches: topMatches,
   229→      total_workers_evaluated: workers.length,
   230→      matches_created: topMatches.length,
   231→    });
   232→  } catch (error) {
   233→    console.error("Match finding error:", error);
   234→    return NextResponse.json(
   235→      { error: "Failed to find matches" },
   236→      { status: 500 }
   237→    );
   238→  }
   239→}
   240→
   241→// --- Scoring helper functions ---
   242→
   243→/**
   244→ * Score related trades (e.g., Formworker and Concreter are related)
   245→ */
   246→function getRelatedTradeScore(jobTrade: string, workerTrades: string[]): number {
   247→  const tradeGroups: Record<string, string[]> = {
   248→    structural: ["Steel Fixer", "Formworker", "Concreter", "Scaffolder"],
   249→    finishing: ["Painter", "Tiler", "Plasterer"],
   250→    services: ["Electrician", "Plumber"],
   251→    heavy: ["Crane Operator", "Excavator Operator"],
   252→    general: ["Labourer", "Carpenter"],
   253→    building: ["Bricklayer", "Roofer", "Welder"],
   254→  };
   255→
   256→  for (const group of Object.values(tradeGroups)) {
   257→    if (group.includes(jobTrade)) {
   258→      for (const wt of workerTrades) {
   259→        if (group.includes(wt)) {
   260→          return 15; // Related trade bonus
   261→        }
   262→      }
   263→    }
   264→  }
   265→
   266→  // Labourers can work on any site
   267→  if (workerTrades.includes("Labourer")) {
   268→    return 10;
   269→  }
   270→
   271→  return 0;
   272→}
   273→
   274→/**
   275→ * Score availability compatibility
   276→ */
   277→function getAvailabilityScore(
   278→  job: { start_date?: string; duration?: string },
   279→  workerAvailability: string | null
   280→): number {
   281→  if (!workerAvailability) return 0;
   282→
   283→  // Flexible workers match everything
   284→  if (workerAvailability === "flexible") return 20;
   285→
   286→  // Full-time workers are the best general match
   287→  if (workerAvailability === "full-time") return 18;
   288→
   289→  // Casual workers are a decent match
   290→  if (workerAvailability === "casual") return 12;
   291→
   292→  // Weekend workers are only good for weekend jobs
   293→  if (workerAvailability === "weekends") return 8;
   294→
   295→  return 0;
   296→}
   297→
   298→/**
   299→ * Score experience level (more is better, with diminishing returns)
   300→ */
   301→function getExperienceScore(years: number | null): number {
   302→  if (years === null || years === undefined) return 0;
   303→
   304→  if (years >= 10) return 15;
   305→  if (years >= 7) return 13;
   306→  if (years >= 4) return 11;
   307→  if (years >= 2) return 8;
   308→  if (years >= 1) return 5;
   309→  return 2; // Less than 1 year still gets some points
   310→}
   311→
   312→/**
   313→ * Score certification overlap
   314→ */
   315→function getCertificationScore(required: string[], workerCerts: string[]): number {
   316→  if (required.length === 0) return 15; // No requirements = full marks
   317→
   318→  const matched = required.filter((c) => workerCerts.includes(c));
   319→  const ratio = matched.length / required.length;
   320→
   321→  return Math.round(ratio * 15);
   322→}
   323→
   324→/**
   325→ * Score location proximity based on suburb matching
   326→ * (Basic string matching for now — will upgrade to geo-distance later)
   327→ */
   328→function getLocationScore(jobSuburb: string | null, workerSuburb: string | null): number {
   329→  if (!jobSuburb || !workerSuburb) return 0;
   330→
   331→  const jobLoc = jobSuburb.toLowerCase().trim();
   332→  const workerLoc = workerSuburb.toLowerCase().trim();
   333→
   334→  // Exact suburb match
   335→  if (jobLoc === workerLoc) return 10;
   336→
   337→  // Partial match (one contains the other)
   338→  if (jobLoc.includes(workerLoc) || workerLoc.includes(jobLoc)) return 7;
   339→
   340→  // Same city/region heuristic (basic - check if they share significant words)
   341→  const jobWords = jobLoc.split(/[\s,]+/).filter((w) => w.length > 3);
   342→  const workerWords = workerLoc.split(/[\s,]+/).filter((w) => w.length > 3);
   343→  const sharedWords = jobWords.filter((w) => workerWords.includes(w));
   344→
   345→  if (sharedWords.length > 0) return 5;
   346→
   347→  return 0;
   348→}
   349→

<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→    // Get conversation previews using the database function
    16→    const { data: conversations, error } = await supabase
    17→      .rpc('get_conversation_previews', { user_id: user.id });
    18→
    19→    if (error) {
    20→      console.error("Error fetching conversations:", error);
    21→      return NextResponse.json(
    22→        { error: "Failed to fetch conversations" },
    23→        { status: 500 }
    24→      );
    25→    }
    26→
    27→    return NextResponse.json({ conversations: conversations || [] });
    28→  } catch (error) {
    29→    console.error("Error in messages API:", error);
    30→    return NextResponse.json(
    31→      { error: "Internal server error" },
    32→      { status: 500 }
    33→    );
    34→  }
    35→}

<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 for the current user
    76→    await supabase
    77→      .from('conversation_participants')
    78→      .update({ last_read_at: new Date().toISOString() })
    79→      .eq('conversation_id', conversationId)
    80→      .eq('profile_id', user.id);
    81→
    82→    // Cast profiles to single object (inner join guarantees single row)
    83→    const profile = conversationData.profiles as unknown as {
    84→      id: string;
    85→      name: string;
    86→      avatar_url: string | null;
    87→      type: string;
    88→    };
    89→
    90→    return NextResponse.json({
    91→      conversation: {
    92→        id: conversationId,
    93→        otherParticipant: {
    94→          id: profile.id,
    95→          name: profile.name,
    96→          avatar: profile.avatar_url,
    97→          type: profile.type,
    98→          isOnline: true // TODO: Implement online status
    99→        },
   100→        messages: messages?.map(msg => ({
   101→          id: msg.id,
   102→          content: msg.content,
   103→          isOwn: msg.sender_id === user.id,
   104→          timestamp: msg.created_at,
   105→          status: msg.status,
   106→          attachments: msg.attachments
   107→        })) || []
   108→      }
   109→    });
   110→  } catch (error) {
   111→    console.error("Error in conversation API:", error);
   112→    return NextResponse.json(
   113→      { error: "Internal server error" },
   114→      { status: 500 }
   115→    );
   116→  }
   117→}

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

<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>


Now let me read the payment and webhook routes:


     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 { 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→    return;
    71→  }
    72→
    73→  try {
    74→    // Update payment status to charged
    75→    const { data: payment, error: paymentError } = await supabase
    76→      .from('payments')
    77→      .update({
    78→        status: 'charged',
    79→      })
    80→      .eq('stripe_payment_id', paymentIntent.id)
    81→      .select('id, match_id, company_id')
    82→      .single();
    83→
    84→    if (paymentError) {
    85→      console.error('Error updating payment status:', paymentError);
    86→      return;
    87→    }
    88→
    89→    if (!payment) {
    90→      console.error('Payment not found for intent:', paymentIntent.id);
    91→      return;
    92→    }
    93→
    94→    // Update match status to hired
    95→    const { error: matchError } = await supabase
    96→      .from('matches')
    97→      .update({
    98→        status: 'hired',
    99→        contractor_action: 'accepted',
   100→        hired_at: new Date().toISOString(),
   101→        fee_charged: true,
   102→      })
   103→      .eq('id', matchId);
   104→
   105→    if (matchError) {
   106→      console.error('Error updating match status:', matchError);
   107→      return;
   108→    }
   109→
   110→    // Create notification for worker
   111→    const { data: match } = await supabase
   112→      .from('matches')
   113→      .select('worker_id, jobs(title)')
   114→      .eq('id', matchId)
   115→      .single();
   116→
   117→    if (match) {
   118→      const jobTitle = (match.jobs as { title?: string }).title || 'a job';
   119→      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→    }
   127→
   128→    console.log('Payment success processed for match:', matchId);
   129→  } catch (error) {
   130→    console.error('Error processing payment success:', error);
   131→  }
   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 { NextResponse } from "next/server";
     2→import { createServerClient } from "@supabase/ssr";
     3→import { cookies } from "next/headers";
     4→
     5→export async function GET(request: Request) {
     6→  const { searchParams, origin } = new URL(request.url);
     7→  const code = searchParams.get("code");
     8→  const next = searchParams.get("next") ?? "/dashboard";
     9→
    10→  if (code) {
    11→    const cookieStore = await cookies();
    12→
    13→    const supabase = createServerClient(
    14→      process.env.NEXT_PUBLIC_SUPABASE_URL!,
    15→      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    16→      {
    17→        cookies: {
    18→          getAll() {
    19→            return cookieStore.getAll();
    20→          },
    21→          setAll(cookiesToSet) {
    22→            try {
    23→              cookiesToSet.forEach(({ name, value, options }) =>
    24→                cookieStore.set(name, value, options)
    25→              );
    26→            } catch {
    27→              // Cookies can only be set in Server Actions or Route Handlers
    28→            }
    29→          },
    30→        },
    31→      }
    32→    );
    33→
    34→    const { error } = await supabase.auth.exchangeCodeForSession(code);
    35→
    36→    if (!error) {
    37→      return NextResponse.redirect(`${origin}${next}`);
    38→    }
    39→  }
    40→
    41→  return NextResponse.redirect(
    42→    `${origin}/auth/login?error=Could+not+authenticate`
    43→  );
    44→}
    45→

<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 critical support files - middleware, CSRF, auth, and error handling:


     1→import { type NextRequest } from "next/server";
     2→import { updateSession } from "@/lib/supabase/middleware";
     3→
     4→export async function middleware(request: NextRequest) {
     5→  return await updateSession(request);
     6→}
     7→
     8→export const config = {
     9→  matcher: [
    10→    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
    11→  ],
    12→};
    13→

<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 { 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=/; HttpOnly; 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→ * Client-side CSRF protection utilities
     3→ */
     4→
     5→const CSRF_HEADER_NAME = 'x-csrf-token';
     6→const CSRF_COOKIE_NAME = 'csrf-token';
     7→
     8→/**
     9→ * Get CSRF token from cookie
    10→ */
    11→export function getCSRFCookie(): string | null {
    12→  if (typeof document === 'undefined') return null;
    13→
    14→  const cookies = document.cookie.split(';');
    15→  for (const cookie of cookies) {
    16→    const [name, value] = cookie.trim().split('=');
    17→    if (name === CSRF_COOKIE_NAME) {
    18→      return value;
    19→    }
    20→  }
    21→  return null;
    22→}
    23→
    24→/**
    25→ * Fetch a new CSRF token from the server
    26→ * This should be called after authentication
    27→ */
    28→export async function fetchCSRFToken(): Promise<string | null> {
    29→  try {
    30→    const response = await fetch('/api/auth/csrf', {
    31→      method: 'GET',
    32→      credentials: 'include', // Include cookies
    33→    });
    34→
    35→    if (!response.ok) {
    36→      console.error('Failed to fetch CSRF token:', response.status);
    37→      return null;
    38→    }
    39→
    40→    const data = await response.json();
    41→    return data.token || null;
    42→  } catch (error) {
    43→    console.error('Error fetching CSRF token:', error);
    44→    return null;
    45→  }
    46→}
    47→
    48→/**
    49→ * Add CSRF token to fetch options
    50→ */
    51→export function withCSRFToken(options: RequestInit = {}): RequestInit {
    52→  const token = getCSRFCookie();
    53→
    54→  if (!token) {
    55→    console.warn('No CSRF token found in cookies');
    56→    return options;
    57→  }
    58→
    59→  return {
    60→    ...options,
    61→    headers: {
    62→      ...options.headers,
    63→      [CSRF_HEADER_NAME]: token,
    64→    },
    65→  };
    66→}
    67→
    68→/**
    69→ * Enhanced fetch with CSRF protection
    70→ */
    71→export async function csrfFetch(input: RequestInfo | URL, options?: RequestInit): Promise<Response> {
    72→  const enhancedOptions = withCSRFToken(options);
    73→  return fetch(input, enhancedOptions);
    74→}
    75→
    76→/**
    77→ * Add CSRF token to form data
    78→ */
    79→export function addCSRFTokenToFormData(formData: FormData): FormData {
    80→  const token = getCSRFCookie();
    81→
    82→  if (token) {
    83→    formData.append('csrf_token', token);
    84→  } else {
    85→    console.warn('No CSRF token found in cookies');
    86→  }
    87→
    88→  return formData;
    89→}
    90→
    91→/**
    92→ * Initialize CSRF token after authentication
    93→ * Call this after successful login/signup
    94→ */
    95→export async function initializeCSRF(): Promise<boolean> {
    96→  const token = await fetchCSRFToken();
    97→  return token !== null;
    98→}

<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>