Search the codebase at /home/ccuser/the-50-dollar-app for all existing RLS policy definitions. Look in:
1. SQL migration files
2. Any schema setup files
3. Any file containing "CREATE POLICY"

I need to understand the exact patterns used for each table's existing SELECT/INSERT/UPDATE policies — specifically the naming convention and the qual (WHERE clause) used for each table. Report back all findings organized by table name.


I'll search the codebase for all RLS policy definitions. Let me start by finding SQL migration files and any files with RLS policy definitions.


Found 5 files
supabase/schema.sql
supabase/test-rls-policies.sql
supabase/add-messaging.sql
supabase/fix-critical-rls-insert-policies.sql
supabase/fix-rls-policies-migration.sql


Now let me read all these SQL files to extract the RLS policies:


     1→-- RateRight v2 Database Schema
     2→-- Run this in the Supabase SQL Editor
     3→
     4→-- ============================================
     5→-- ENUMS
     6→-- ============================================
     7→
     8→CREATE TYPE user_type AS ENUM ('worker', 'contractor');
     9→CREATE TYPE availability_type AS ENUM ('full-time', 'casual', 'weekends', 'flexible');
    10→CREATE TYPE rate_type AS ENUM ('hourly', 'daily');
    11→CREATE TYPE job_status AS ENUM ('draft', 'active', 'filled', 'closed');
    12→CREATE TYPE match_status AS ENUM ('suggested', 'applied', 'accepted', 'rejected', 'hired');
    13→CREATE TYPE action_status AS ENUM ('pending', 'accepted', 'rejected');
    14→CREATE TYPE payment_status AS ENUM ('pending', 'charged', 'refunded');
    15→CREATE TYPE notification_type AS ENUM ('match', 'hire_request', 'hire_confirmed', 'rating', 'job_posted', 'system');
    16→
    17→-- ============================================
    18→-- HELPER FUNCTION: auto-update updated_at
    19→-- ============================================
    20→
    21→CREATE OR REPLACE FUNCTION update_updated_at()
    22→RETURNS trigger AS $$
    23→BEGIN
    24→  NEW.updated_at = now();
    25→  RETURN NEW;
    26→END;
    27→$$ LANGUAGE plpgsql;
    28→
    29→-- ============================================
    30→-- TABLES
    31→-- ============================================
    32→
    33→-- Profiles (extends Supabase Auth)
    34→CREATE TABLE profiles (
    35→  id uuid PRIMARY KEY REFERENCES auth.users ON DELETE CASCADE,
    36→  type user_type NOT NULL,
    37→  name text,
    38→  phone text,
    39→  email text,
    40→  avatar_url text,
    41→  location point,
    42→  suburb text,
    43→  verified boolean DEFAULT false,
    44→  onboarding_completed boolean DEFAULT false,
    45→  created_at timestamptz DEFAULT now(),
    46→  updated_at timestamptz DEFAULT now(),
    47→  ai_generated boolean DEFAULT false
    48→);
    49→
    50→CREATE TRIGGER profiles_updated_at
    51→  BEFORE UPDATE ON profiles
    52→  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
    53→
    54→-- Companies (contractor-specific)
    55→CREATE TABLE companies (
    56→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    57→  profile_id uuid NOT NULL UNIQUE REFERENCES profiles ON DELETE CASCADE,
    58→  name text NOT NULL,
    59→  abn text,
    60→  address text,
    61→  industry text,
    62→  size text,
    63→  website text,
    64→  logo_url text,
    65→  ai_research jsonb,
    66→  created_at timestamptz DEFAULT now(),
    67→  updated_at timestamptz DEFAULT now()
    68→);
    69→
    70→CREATE TRIGGER companies_updated_at
    71→  BEFORE UPDATE ON companies
    72→  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
    73→
    74→-- Worker profiles (worker-specific)
    75→CREATE TABLE worker_profiles (
    76→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    77→  profile_id uuid NOT NULL UNIQUE REFERENCES profiles ON DELETE CASCADE,
    78→  trades text[] DEFAULT '{}',
    79→  experience_years integer,
    80→  certifications text[] DEFAULT '{}',
    81→  white_card_number text,
    82→  white_card_verified boolean DEFAULT false,
    83→  availability availability_type,
    84→  languages text[] DEFAULT '{}',
    85→  bio text,
    86→  voice_note_url text,
    87→  ai_extracted jsonb,
    88→  created_at timestamptz DEFAULT now(),
    89→  updated_at timestamptz DEFAULT now()
    90→);
    91→
    92→CREATE TRIGGER worker_profiles_updated_at
    93→  BEFORE UPDATE ON worker_profiles
    94→  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
    95→
    96→-- Jobs
    97→CREATE TABLE jobs (
    98→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    99→  company_id uuid NOT NULL REFERENCES companies ON DELETE CASCADE,
   100→  title text NOT NULL,
   101→  description text,
   102→  trade text NOT NULL,
   103→  location point,
   104→  suburb text,
   105→  site_address text,
   106→  rate_min decimal,
   107→  rate_max decimal,
   108→  rate_type rate_type DEFAULT 'hourly',
   109→  start_date date,
   110→  duration text,
   111→  workers_needed integer DEFAULT 1,
   112→  certifications_required text[] DEFAULT '{}',
   113→  status job_status DEFAULT 'draft',
   114→  ai_generated boolean DEFAULT false,
   115→  created_at timestamptz DEFAULT now(),
   116→  updated_at timestamptz DEFAULT now()
   117→);
   118→
   119→CREATE TRIGGER jobs_updated_at
   120→  BEFORE UPDATE ON jobs
   121→  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
   122→
   123→-- Matches
   124→CREATE TABLE matches (
   125→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
   126→  job_id uuid NOT NULL REFERENCES jobs ON DELETE CASCADE,
   127→  worker_id uuid NOT NULL REFERENCES profiles ON DELETE CASCADE,
   128→  status match_status DEFAULT 'suggested',
   129→  match_score decimal,
   130→  ai_summary text,
   131→  contractor_action action_status DEFAULT 'pending',
   132→  worker_action action_status DEFAULT 'pending',
   133→  hired_at timestamptz,
   134→  fee_charged boolean DEFAULT false,
   135→  created_at timestamptz DEFAULT now(),
   136→  updated_at timestamptz DEFAULT now(),
   137→  UNIQUE (job_id, worker_id)
   138→);
   139→
   140→CREATE TRIGGER matches_updated_at
   141→  BEFORE UPDATE ON matches
   142→  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
   143→
   144→-- Ratings
   145→CREATE TABLE ratings (
   146→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
   147→  match_id uuid NOT NULL REFERENCES matches ON DELETE CASCADE,
   148→  from_id uuid NOT NULL REFERENCES profiles ON DELETE CASCADE,
   149→  to_id uuid NOT NULL REFERENCES profiles ON DELETE CASCADE,
   150→  score integer NOT NULL CHECK (score BETWEEN 1 AND 5),
   151→  comment text,
   152→  created_at timestamptz DEFAULT now(),
   153→  UNIQUE (match_id, from_id)
   154→);
   155→
   156→-- Payments
   157→CREATE TABLE payments (
   158→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
   159→  match_id uuid NOT NULL REFERENCES matches ON DELETE CASCADE,
   160→  company_id uuid NOT NULL REFERENCES companies ON DELETE CASCADE,
   161→  amount decimal DEFAULT 50.00,
   162→  status payment_status DEFAULT 'pending',
   163→  stripe_payment_id text,
   164→  created_at timestamptz DEFAULT now()
   165→);
   166→
   167→-- Notifications
   168→CREATE TABLE notifications (
   169→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
   170→  profile_id uuid NOT NULL REFERENCES profiles ON DELETE CASCADE,
   171→  type notification_type NOT NULL,
   172→  title text NOT NULL,
   173→  body text,
   174→  data jsonb,
   175→  read boolean DEFAULT false,
   176→  created_at timestamptz DEFAULT now()
   177→);
   178→
   179→-- ============================================
   180→-- INDEXES
   181→-- ============================================
   182→
   183→CREATE INDEX idx_profiles_type ON profiles (type);
   184→CREATE INDEX idx_profiles_suburb ON profiles (suburb);
   185→
   186→CREATE INDEX idx_companies_profile_id ON companies (profile_id);
   187→CREATE INDEX idx_companies_abn ON companies (abn);
   188→
   189→CREATE INDEX idx_worker_profiles_profile_id ON worker_profiles (profile_id);
   190→CREATE INDEX idx_worker_profiles_trades ON worker_profiles USING gin (trades);
   191→CREATE INDEX idx_worker_profiles_availability ON worker_profiles (availability);
   192→CREATE INDEX idx_worker_profiles_certifications ON worker_profiles USING gin (certifications);
   193→
   194→CREATE INDEX idx_jobs_company_id ON jobs (company_id);
   195→CREATE INDEX idx_jobs_status ON jobs (status);
   196→CREATE INDEX idx_jobs_trade ON jobs (trade);
   197→CREATE INDEX idx_jobs_created_at ON jobs (created_at DESC);
   198→CREATE INDEX idx_jobs_suburb ON jobs (suburb);
   199→
   200→CREATE INDEX idx_matches_job_id ON matches (job_id);
   201→CREATE INDEX idx_matches_worker_id ON matches (worker_id);
   202→CREATE INDEX idx_matches_status ON matches (status);
   203→
   204→CREATE INDEX idx_ratings_to_id ON ratings (to_id);
   205→CREATE INDEX idx_ratings_from_id ON ratings (from_id);
   206→
   207→CREATE INDEX idx_payments_match_id ON payments (match_id);
   208→CREATE INDEX idx_payments_company_id ON payments (company_id);
   209→
   210→CREATE INDEX idx_notifications_profile_id ON notifications (profile_id);
   211→CREATE INDEX idx_notifications_read ON notifications (profile_id, read);
   212→
   213→-- ============================================
   214→-- ROW LEVEL SECURITY
   215→-- ============================================
   216→
   217→ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
   218→ALTER TABLE companies ENABLE ROW LEVEL SECURITY;
   219→ALTER TABLE worker_profiles ENABLE ROW LEVEL SECURITY;
   220→ALTER TABLE jobs ENABLE ROW LEVEL SECURITY;
   221→ALTER TABLE matches ENABLE ROW LEVEL SECURITY;
   222→ALTER TABLE ratings ENABLE ROW LEVEL SECURITY;
   223→ALTER TABLE payments ENABLE ROW LEVEL SECURITY;
   224→ALTER TABLE notifications ENABLE ROW LEVEL SECURITY;
   225→
   226→-- Profiles: users can read all profiles, update their own
   227→CREATE POLICY "Public profiles are viewable by everyone"
   228→  ON profiles FOR SELECT
   229→  USING (true);
   230→
   231→CREATE POLICY "Users can update their own profile"
   232→  ON profiles FOR UPDATE
   233→  USING (auth.uid() = id);
   234→
   235→CREATE POLICY "Users can insert their own profile"
   236→  ON profiles FOR INSERT
   237→  WITH CHECK (auth.uid() = id);
   238→
   239→-- Companies: viewable by everyone, editable by owner
   240→CREATE POLICY "Companies are viewable by everyone"
   241→  ON companies FOR SELECT
   242→  USING (true);
   243→
   244→CREATE POLICY "Contractors can insert their own company"
   245→  ON companies FOR INSERT
   246→  WITH CHECK (profile_id = auth.uid());
   247→
   248→CREATE POLICY "Contractors can update their own company"
   249→  ON companies FOR UPDATE
   250→  USING (profile_id = auth.uid());
   251→
   252→-- Worker profiles: viewable by everyone, editable by owner
   253→CREATE POLICY "Worker profiles are viewable by everyone"
   254→  ON worker_profiles FOR SELECT
   255→  USING (true);
   256→
   257→CREATE POLICY "Workers can insert their own profile"
   258→  ON worker_profiles FOR INSERT
   259→  WITH CHECK (profile_id = auth.uid());
   260→
   261→CREATE POLICY "Workers can update their own profile"
   262→  ON worker_profiles FOR UPDATE
   263→  USING (profile_id = auth.uid());
   264→
   265→-- Jobs: viewable by everyone, editable by company owner
   266→CREATE POLICY "Jobs are viewable by everyone"
   267→  ON jobs FOR SELECT
   268→  USING (true);
   269→
   270→CREATE POLICY "Contractors can insert jobs for their company"
   271→  ON jobs FOR INSERT
   272→  WITH CHECK (
   273→    company_id IN (
   274→      SELECT id FROM companies WHERE profile_id = auth.uid()
   275→    )
   276→  );
   277→
   278→CREATE POLICY "Contractors can update their own jobs"
   279→  ON jobs FOR UPDATE
   280→  USING (
   281→    company_id IN (
   282→      SELECT id FROM companies WHERE profile_id = auth.uid()
   283→    )
   284→  );
   285→
   286→-- Matches: viewable by involved parties
   287→CREATE POLICY "Users can view their own matches"
   288→  ON matches FOR SELECT
   289→  USING (
   290→    worker_id = auth.uid() OR
   291→    job_id IN (
   292→      SELECT j.id FROM jobs j
   293→      JOIN companies c ON j.company_id = c.id
   294→      WHERE c.profile_id = auth.uid()
   295→    )
   296→  );
   297→
   298→CREATE POLICY "System can insert matches"
   299→  ON matches FOR INSERT
   300→  WITH CHECK (true);
   301→
   302→CREATE POLICY "Involved parties can update matches"
   303→  ON matches FOR UPDATE
   304→  USING (
   305→    worker_id = auth.uid() OR
   306→    job_id IN (
   307→      SELECT j.id FROM jobs j
   308→      JOIN companies c ON j.company_id = c.id
   309→      WHERE c.profile_id = auth.uid()
   310→    )
   311→  );
   312→
   313→-- Ratings: viewable by everyone, insertable by match participants
   314→CREATE POLICY "Ratings are viewable by everyone"
   315→  ON ratings FOR SELECT
   316→  USING (true);
   317→
   318→CREATE POLICY "Match participants can insert ratings"
   319→  ON ratings FOR INSERT
   320→  WITH CHECK (from_id = auth.uid());
   321→
   322→-- Payments: viewable by company owner
   323→CREATE POLICY "Company owners can view their payments"
   324→  ON payments FOR SELECT
   325→  USING (
   326→    company_id IN (
   327→      SELECT id FROM companies WHERE profile_id = auth.uid()
   328→    )
   329→  );
   330→
   331→CREATE POLICY "System can insert payments"
   332→  ON payments FOR INSERT
   333→  WITH CHECK (true);
   334→
   335→-- Notifications: users can only see their own
   336→CREATE POLICY "Users can view their own notifications"
   337→  ON notifications FOR SELECT
   338→  USING (profile_id = auth.uid());
   339→
   340→CREATE POLICY "System can insert notifications"
   341→  ON notifications FOR INSERT
   342→  WITH CHECK (true);
   343→
   344→CREATE POLICY "Users can update their own notifications"
   345→  ON notifications FOR UPDATE
   346→  USING (profile_id = auth.uid());
   347→
   348→-- ============================================
   349→-- FUNCTIONS
   350→-- ============================================
   351→
   352→-- Auto-create profile on signup
   353→-- Fixed: Now handles invalid/missing user_type gracefully (defaults to 'worker')
   354→CREATE OR REPLACE FUNCTION public.handle_new_user()
   355→RETURNS trigger AS $$
   356→DECLARE
   357→    v_user_type text;
   358→    v_valid_type user_type;
   359→BEGIN
   360→    -- Get the user_type from metadata
   361→    v_user_type := NEW.raw_user_meta_data->>'type';
   362→
   363→    -- Validate the user_type before casting (defaults to 'worker' if invalid)
   364→    CASE v_user_type
   365→        WHEN 'worker' THEN
   366→            v_valid_type := 'worker'::user_type;
   367→        WHEN 'contractor' THEN
   368→            v_valid_type := 'contractor'::user_type;
   369→        ELSE
   370→            v_valid_type := 'worker'::user_type;
   371→    END CASE;
   372→
   373→    INSERT INTO public.profiles (id, email, type)
   374→    VALUES (
   375→        NEW.id,
   376→        NEW.email,
   377→        v_valid_type
   378→    );
   379→
   380→    RETURN NEW;
   381→EXCEPTION
   382→    WHEN OTHERS THEN
   383→        RAISE WARNING 'handle_new_user() failed for user %: %', NEW.id, SQLERRM;
   384→        RAISE;
   385→END;
   386→$$ LANGUAGE plpgsql SECURITY DEFINER;
   387→
   388→CREATE OR REPLACE TRIGGER on_auth_user_created
   389→  AFTER INSERT ON auth.users
   390→  FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
   391→
   392→-- Average rating helper
   393→CREATE OR REPLACE FUNCTION public.get_average_rating(user_id uuid)
   394→RETURNS decimal AS $$
   395→  SELECT COALESCE(AVG(score)::decimal, 0)
   396→  FROM ratings
   397→  WHERE to_id = user_id;
   398→$$ LANGUAGE sql STABLE;
   399→
   400→-- Rating count helper
   401→CREATE OR REPLACE FUNCTION public.get_rating_count(user_id uuid)
   402→RETURNS integer AS $$
   403→  SELECT COUNT(*)::integer
   404→  FROM ratings
   405→  WHERE to_id = user_id;
   406→$$ LANGUAGE sql STABLE;
   407→

<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→-- Migration: Add ABN uniqueness constraint to companies table
     2→-- Created: 2026-02-08
     3→-- Description: Ensures ABN values are unique across all companies
     4→--
     5→-- IMPORTANT: This migration requires manual intervention if duplicates exist.
     6→-- The migration will FAIL if duplicate ABN values exist in the database.
     7→--
     8→-- BEFORE RUNNING:
     9→-- 1. Execute the verification queries to check for duplicates
    10→-- 2. If duplicates exist, resolve them (nullify or update manually)
    11→-- 3. Then run this migration
    12→--
    13→-- AFTER RUNNING:
    14→-- 1. Verify the constraint is working with the post-migration queries
    15→
    16→-- ============================================
    17→-- VERIFICATION QUERIES (Run these before migration)
    18→-- ============================================
    19→
    20→-- Check for existing duplicate ABN values
    21→-- If duplicates exist, resolve them before running this migration
    22→/*
    23→SELECT abn, COUNT(*) as duplicate_count, array_agg(id) as company_ids
    24→FROM companies
    25→WHERE abn IS NOT NULL
    26→GROUP BY abn
    27→HAVING COUNT(*) > 1;
    28→*/
    29→
    30→-- Check total companies with ABN values
    31→/*
    32→SELECT COUNT(*) as total_companies_with_abn
    33→FROM companies
    34→WHERE abn IS NOT NULL;
    35→*/
    36→
    37→-- ============================================
    38→-- UP MIGRATION
    39→-- ============================================
    40→
    41→-- Step 1: Handle existing duplicate ABN values
    42→-- Option A: Nullify duplicate ABNs (safer than deletion)
    43→-- This preserves all companies but removes ABN from duplicates
    44→/*
    45→UPDATE companies
    46→SET abn = NULL, updated_at = now()
    47→WHERE id IN (
    48→  SELECT id FROM (
    49→    SELECT id, ROW_NUMBER() OVER (PARTITION BY abn ORDER BY updated_at DESC) as rn
    50→    FROM companies
    51→    WHERE abn IS NOT NULL
    52→  ) ranked
    53→  WHERE rn > 1
    54→);
    55→*/
    56→
    57→-- Option B: Manually review and handle duplicates
    58→-- Use the verification query above to identify duplicates
    59→-- Then manually update them through the app or direct SQL
    60→
    61→-- Step 2: Add unique constraint to ABN column
    62→-- This will fail if duplicates exist - ensure Step 1 is completed first
    63→ALTER TABLE companies
    64→ADD CONSTRAINT companies_abn_unique UNIQUE (abn);
    65→
    66→-- Step 3: Create index on ABN for better query performance
    67→-- This index already exists in the schema but we'll ensure it exists
    68→CREATE INDEX IF NOT EXISTS idx_companies_abn ON companies (abn);
    69→
    70→-- ============================================
    71→-- DOWN MIGRATION
    72→-- ============================================
    73→
    74→-- To rollback this migration, run the following:
    75→
    76→-- Remove the unique constraint
    77→-- ALTER TABLE companies
    78→-- DROP CONSTRAINT IF EXISTS companies_abn_unique;
    79→
    80→-- Note: The index idx_companies_abn is kept for performance even after rollback
    81→-- To also remove the index (not recommended):
    82→-- DROP INDEX IF EXISTS idx_companies_abn;
    83→
    84→-- ============================================
    85→-- POST-MIGRATION VERIFICATION
    86→-- ============================================
    87→
    88→-- Verify the constraint is working (should return 0)
    89→/*
    90→SELECT COUNT(*) as constraint_violations
    91→FROM (
    92→  SELECT abn, COUNT(*) as count
    93→  FROM companies
    94→  WHERE abn IS NOT NULL
    95→  GROUP BY abn
    96→  HAVING COUNT(*) > 1
    97→) as duplicates;
    98→*/
    99→
   100→-- Test inserting a duplicate ABN (should fail)
   101→/*
   102→-- This should fail with unique constraint violation
   103→INSERT INTO companies (profile_id, name, abn)
   104→VALUES ('test-profile-id', 'Test Company', '12345678901');
   105→*/
   106→
   107→-- List all unique ABNs
   108→/*
   109→SELECT DISTINCT abn
   110→FROM companies
   111→WHERE abn IS NOT NULL
   112→ORDER BY abn;
   113→*/

<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→-- Migration: Add unique constraint on companies.abn
     2→-- Created: 2026-02-09
     3→
     4→-- Step 1: Check for existing duplicate ABNs
     5→-- This query will show all companies that have duplicate ABN values
     6→-- (excluding NULL and empty string ABNs)
     7→SELECT
     8→    abn,
     9→    COUNT(*) as duplicate_count,
    10→    array_agg(
    11→        json_build_object(
    12→            'id', id,
    13→            'name', name,
    14→            'email', email
    15→        )
    16→    ) as companies
    17→FROM companies
    18→WHERE abn IS NOT NULL
    19→  AND abn != ''
    20→GROUP BY abn
    21→HAVING COUNT(*) > 1
    22→ORDER BY duplicate_count DESC, abn;
    23→
    24→-- Step 2: Migration to add UNIQUE constraint
    25→-- Note: This migration uses a partial unique index to exclude NULL and empty ABNs
    26→BEGIN;
    27→
    28→-- Create a partial unique index on ABN
    29→-- This allows multiple NULL values and multiple empty strings, but enforces uniqueness on actual ABN values
    30→CREATE UNIQUE INDEX companies_abn_unique
    31→ON companies (abn)
    32→WHERE abn IS NOT NULL AND abn != '';
    33→
    34→-- Add a comment to document the constraint
    35→COMMENT ON INDEX companies_abn_unique IS 'Ensures ABN values are unique across companies, excluding NULL and empty values';
    36→
    37→COMMIT;
    38→
    39→-- Notes on handling duplicates:
    40→-- If the duplicate check query returns results, you'll need to resolve these before running the migration.
    41→-- Options for resolving duplicates:
    42→-- 1. Update duplicate ABNs to NULL or empty string for companies that don't need an ABN
    43→-- 2. Update ABNs to correct unique values where data entry errors occurred
    44→-- 3. Merge duplicate company records if they represent the same business
    45→-- 4. Add a suffix to make ABNs unique temporarily (e.g., '12345678901_OLD')
    46→--
    47→-- Example resolution queries:
    48→-- UPDATE companies SET abn = NULL WHERE id = <duplicate_id>;
    49→-- UPDATE companies SET abn = <correct_abn> WHERE id = <company_id>;

<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→-- FIX CRITICAL RLS POLICIES - Audit Item C5
     3→-- ============================================
     4→-- Fix: matches + payments allow ANY user to insert (WITH CHECK true)
     5→-- Date: 2026-02-07
     6→-- ============================================
     7→
     8→-- ============================================
     9→-- 1. DROP PROBLEMATIC POLICIES
    10→-- ============================================
    11→
    12→-- Drop the overly permissive INSERT policies
    13→DROP POLICY IF EXISTS "System can insert matches" ON matches;
    14→DROP POLICY IF EXISTS "System can insert payments" ON payments;
    15→
    16→-- ============================================
    17→-- 2. CREATE SECURE INSERT POLICIES FOR MATCHES
    18→-- ============================================
    19→
    20→-- Option A: Only system/service role can insert matches
    21→-- This is the most secure option - matches should only be created by:
    22→-- 1. System algorithms suggesting matches
    23→-- 2. Workers applying for jobs (but this should go through an API endpoint)
    24→-- 3. Contractors inviting workers (but this should go through an API endpoint)
    25→
    26→-- For now, we'll create a policy that allows:
    27→-- 1. Workers to apply for jobs (insert matches where they are the worker)
    28→-- 2. Contractors to invite workers to their jobs
    29→-- 3. System/service role (using service key, not JWT)
    30→
    31→CREATE POLICY "Workers can apply for jobs"
    32→  ON matches FOR INSERT
    33→  WITH CHECK (
    34→    -- Worker applying for a job
    35→    (worker_id = auth.uid() AND status = 'applied')
    36→    OR
    37→    -- Contractor inviting a worker to their job
    38→    (
    39→      job_id IN (
    40→        SELECT j.id FROM jobs j
    41→        JOIN companies c ON j.company_id = c.id
    42→        WHERE c.profile_id = auth.uid()
    43→      )
    44→      AND status = 'suggested'
    45→    )
    46→    OR
    47→    -- System/service role (using service key)
    48→    (auth.jwt() ->> 'role' = 'service_role')
    49→  );
    50→
    51→-- ============================================
    52→-- 3. CREATE SECURE INSERT POLICIES FOR PAYMENTS
    53→-- ============================================
    54→
    55→-- Payments should ONLY be created by:
    56→-- 1. System when a match is hired (status changes to 'hired')
    57→-- 2. System/service role (using service key)
    58→
    59→CREATE POLICY "System can insert payments for hired matches"
    60→  ON payments FOR INSERT
    61→  WITH CHECK (
    62→    -- Only system/service role can insert payments
    63→    (auth.jwt() ->> 'role' = 'service_role')
    64→    AND
    65→    -- Payment must be for a hired match
    66→    match_id IN (
    67→      SELECT id FROM matches WHERE status = 'hired'
    68→    )
    69→    AND
    70→    -- Payment company must match the job's company
    71→    company_id IN (
    72→      SELECT j.company_id FROM matches m
    73→      JOIN jobs j ON m.job_id = j.id
    74→      WHERE m.id = match_id
    75→    )
    76→  );
    77→
    78→-- ============================================
    79→-- 4. ADDITIONAL SECURITY MEASURES
    80→-- ============================================
    81→
    82→-- Add a trigger to ensure payments are only created for hired matches
    83→CREATE OR REPLACE FUNCTION validate_payment_match()
    84→RETURNS trigger AS $$
    85→BEGIN
    86→  -- Check if the match is actually hired
    87→  IF NOT EXISTS (
    88→    SELECT 1 FROM matches
    89→    WHERE id = NEW.match_id AND status = 'hired'
    90→  ) THEN
    91→    RAISE EXCEPTION 'Payments can only be created for hired matches';
    92→  END IF;
    93→
    94→  -- Check if the company_id matches the job's company
    95→  IF NOT EXISTS (
    96→    SELECT 1 FROM matches m
    97→    JOIN jobs j ON m.job_id = j.id
    98→    WHERE m.id = NEW.match_id AND j.company_id = NEW.company_id
    99→  ) THEN
   100→    RAISE EXCEPTION 'Payment company must match the job company';
   101→  END IF;
   102→
   103→  RETURN NEW;
   104→END;
   105→$$ LANGUAGE plpgsql;
   106→
   107→DROP TRIGGER IF EXISTS validate_payment_match_trigger ON payments;
   108→CREATE TRIGGER validate_payment_match_trigger
   109→  BEFORE INSERT ON payments
   110→  FOR EACH ROW EXECUTE FUNCTION validate_payment_match();
   111→
   112→-- ============================================
   113→-- 5. UPDATE EXISTING POLICIES FOR CONSISTENCY
   114→-- ============================================
   115→
   116→-- Update matches UPDATE policy to be more restrictive
   117→DROP POLICY IF EXISTS "Involved parties can update matches" ON matches;
   118→
   119→CREATE POLICY "Involved parties can update match status"
   120→  ON matches FOR UPDATE
   121→  USING (
   122→    -- Worker can update their own application status
   123→    (worker_id = auth.uid() AND OLD.status IN ('suggested', 'applied'))
   124→    OR
   125→    -- Contractor can update matches for their jobs
   126→    (
   127→      job_id IN (
   128→        SELECT j.id FROM jobs j
   129→        JOIN companies c ON j.company_id = c.id
   130→        WHERE c.profile_id = auth.uid()
   131→      )
   132→      AND OLD.status IN ('suggested', 'applied')
   133→    )
   134→    OR
   135→    -- System can update any match
   136→    (auth.jwt() ->> 'role' = 'service_role')
   137→  )
   138→  WITH CHECK (
   139→    -- Ensure status transitions are valid
   140→    (
   141→      -- Worker can only accept/reject suggestions
   142→      (worker_id = auth.uid() AND NEW.status IN ('accepted', 'rejected'))
   143→      OR
   144→      -- Contractor can only accept/reject applications
   145→      (
   146→        job_id IN (
   147→          SELECT j.id FROM jobs j
   148→          JOIN companies c ON j.company_id = c.id
   149→          WHERE c.profile_id = auth.uid()
   150→        )
   151→        AND NEW.status IN ('accepted', 'rejected')
   152→      )
   153→      OR
   154→      -- System can set to hired (after payment)
   155→      (NEW.status = 'hired' AND auth.jwt() ->> 'role' = 'service_role')
   156→      OR
   157→      -- Status stays the same (other fields updated)
   158→      (NEW.status = OLD.status)
   159→    )
   160→  );
   161→
   162→-- ============================================
   163→-- 6. VERIFICATION QUERIES
   164→-- ============================================
   165→
   166→-- Check current policies
   167→SELECT
   168→  schemaname,
   169→  tablename,
   170→  policyname,
   171→  permissive,
   172→  roles,
   173→  cmd,
   174→  qual,
   175→  with_check
   176→FROM pg_policies
   177→WHERE tablename IN ('matches', 'payments')
   178→ORDER BY tablename, policyname;
   179→
   180→-- Test data integrity
   181→SELECT
   182→  'Matches with invalid status transitions' as check_name,
   183→  COUNT(*) as issues
   184→FROM matches
   185→WHERE status NOT IN ('suggested', 'applied', 'accepted', 'rejected', 'hired')
   186→UNION ALL
   187→SELECT
   188→  'Payments for non-hired matches' as check_name,
   189→  COUNT(*) as issues
   190→FROM payments p
   191→LEFT JOIN matches m ON p.match_id = m.id
   192→WHERE m.status != 'hired' OR m.id IS NULL;

<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→-- CRITICAL FIX: RLS INSERT POLICIES FOR MATCHES + PAYMENTS
     3→-- Audit Item C5: Fix RLS INSERT policies — matches + payments allow ANY user to insert (WITH CHECK true)
     4→-- ============================================
     5→-- Date: 2026-02-07
     6→-- Priority: CRITICAL
     7→-- ============================================
     8→
     9→-- ============================================
    10→-- PROBLEM ANALYSIS
    11→-- ============================================
    12→-- Current issue: Both matches and payments tables have INSERT policies with WITH CHECK (true)
    13→-- This means ANY authenticated user can insert records into these tables
    14→--
    15→-- Security impact:
    16→-- 1. Users could insert fake matches between any job and worker
    17→-- 2. Users could insert fake payment records
    18→-- 3. Financial fraud, data corruption, system abuse
    19→--
    20→-- Correct behavior:
    21→-- 1. matches INSERT: Only workers (applying) or contractors (inviting) for their own jobs
    22→-- 2. payments INSERT: Only system/service role when match is hired
    23→-- ============================================
    24→
    25→-- ============================================
    26→-- 1. FIX MATCHES TABLE INSERT POLICY
    27→-- ============================================
    28→
    29→-- Drop the dangerous policy
    30→DROP POLICY IF EXISTS "System can insert matches" ON matches;
    31→
    32→-- Create secure INSERT policy for matches
    33→-- Allows:
    34→-- 1. Workers to apply for jobs (worker_id must be their own ID)
    35→-- 2. Contractors to suggest matches for their own jobs
    36→-- 3. Service role (system) for automated matching
    37→CREATE POLICY "Secure matches insert"
    38→  ON matches FOR INSERT
    39→  WITH CHECK (
    40→    -- Worker applying for a job
    41→    (worker_id = auth.uid() AND status = 'applied')
    42→    OR
    43→    -- Contractor suggesting a worker for their job
    44→    (
    45→      job_id IN (
    46→        SELECT j.id FROM jobs j
    47→        JOIN companies c ON j.company_id = c.id
    48→        WHERE c.profile_id = auth.uid()
    49→      )
    50→      AND status = 'suggested'
    51→    )
    52→    OR
    53→    -- System/service role (for automated matching)
    54→    (auth.jwt() ->> 'role' = 'service_role')
    55→  );
    56→
    57→-- ============================================
    58→-- 2. FIX PAYMENTS TABLE INSERT POLICY
    59→-- ============================================
    60→
    61→-- Drop the dangerous policy
    62→DROP POLICY IF EXISTS "System can insert payments" ON payments;
    63→
    64→-- Create secure INSERT policy for payments
    65→-- Only system/service role can insert payments, and only for hired matches
    66→CREATE POLICY "Secure payments insert"
    67→  ON payments FOR INSERT
    68→  WITH CHECK (
    69→    -- Must be service role
    70→    (auth.jwt() ->> 'role' = 'service_role')
    71→    AND
    72→    -- Payment must be for a hired match
    73→    EXISTS (
    74→      SELECT 1 FROM matches
    75→      WHERE id = match_id AND status = 'hired'
    76→    )
    77→    AND
    78→    -- Payment company must own the job
    79→    EXISTS (
    80→      SELECT 1 FROM matches m
    81→      JOIN jobs j ON m.job_id = j.id
    82→      WHERE m.id = match_id AND j.company_id = company_id
    83→    )
    84→  );
    85→
    86→-- ============================================
    87→-- 3. ADD DATA VALIDATION TRIGGER FOR PAYMENTS
    88→-- ============================================
    89→
    90→-- Ensure payments are only created for valid hired matches
    91→CREATE OR REPLACE FUNCTION validate_payment_creation()
    92→RETURNS trigger AS $$
    93→BEGIN
    94→  -- Verify match is hired
    95→  IF NOT EXISTS (
    96→    SELECT 1 FROM matches
    97→    WHERE id = NEW.match_id AND status = 'hired'
    98→  ) THEN
    99→    RAISE EXCEPTION 'Payments can only be created for hired matches (match status must be "hired")';
   100→  END IF;
   101→
   102→  -- Verify company owns the job
   103→  IF NOT EXISTS (
   104→    SELECT 1 FROM matches m
   105→    JOIN jobs j ON m.job_id = j.id
   106→    WHERE m.id = NEW.match_id AND j.company_id = NEW.company_id
   107→  ) THEN
   108→    RAISE EXCEPTION 'Payment company must own the job associated with the match';
   109→  END IF;
   110→
   111→  RETURN NEW;
   112→END;
   113→$$ LANGUAGE plpgsql;
   114→
   115→-- Drop existing trigger if any
   116→DROP TRIGGER IF EXISTS validate_payment_creation_trigger ON payments;
   117→
   118→-- Create trigger
   119→CREATE TRIGGER validate_payment_creation_trigger
   120→  BEFORE INSERT ON payments
   121→  FOR EACH ROW EXECUTE FUNCTION validate_payment_creation();
   122→
   123→-- ============================================
   124→-- 4. UPDATE APPLICATION LOGIC RECOMMENDATIONS
   125→-- ============================================
   126→
   127→-- Note for developers: Application code should now:
   128→-- 1. Use service role key for server-side operations
   129→-- 2. Handle match creation through proper workflows:
   130→--    - Worker apply: Frontend calls API, API validates worker owns worker_id
   131→--    - Contractor invite: Frontend calls API, API validates contractor owns job
   132→--    - System matching: Background job uses service role
   133→-- 3. Payment creation: Only through server-side after Stripe success
   134→
   135→-- ============================================
   136→-- 5. VERIFICATION QUERIES (RUN AFTER MIGRATION)
   137→-- ============================================
   138→
   139→/*
   140→-- Check the new policies
   141→SELECT
   142→  tablename,
   143→  policyname,
   144→  cmd,
   145→  qual,
   146→  with_check
   147→FROM pg_policies
   148→WHERE tablename IN ('matches', 'payments')
   149→ORDER BY tablename, policyname;
   150→
   151→-- Test: Try to insert a match as a regular user (should fail without proper conditions)
   152→-- INSERT INTO matches (job_id, worker_id, status)
   153→-- VALUES ('some-job-id', 'some-worker-id', 'suggested');
   154→
   155→-- Test: Try to insert a payment as a regular user (should always fail)
   156→-- INSERT INTO payments (match_id, company_id, amount)
   157→-- VALUES ('some-match-id', 'some-company-id', 50.00);
   158→*/
   159→
   160→-- ============================================
   161→-- 6. ROLLBACK SCRIPT (IN CASE OF ISSUES)
   162→-- ============================================
   163→/*
   164→-- Rollback to original (insecure) policies:
   165→DROP POLICY IF EXISTS "Secure matches insert" ON matches;
   166→DROP POLICY IF EXISTS "Secure payments insert" ON payments;
   167→DROP TRIGGER IF EXISTS validate_payment_creation_trigger ON payments;
   168→DROP FUNCTION IF EXISTS validate_payment_creation;
   169→
   170→-- Recreate original policies (INSECURE - FOR EMERGENCY ONLY):
   171→CREATE POLICY "System can insert matches"
   172→  ON matches FOR INSERT
   173→  WITH CHECK (true);
   174→
   175→CREATE POLICY "System can insert payments"
   176→  ON payments FOR INSERT
   177→  WITH CHECK (true);
   178→*/
   179→

<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→-- Messaging system for RateRight v2
     2→-- Creates tables for conversations and messages
     3→
     4→-- Conversations table to group messages between users
     5→CREATE TABLE conversations (
     6→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
     7→  created_at timestamptz DEFAULT now(),
     8→  updated_at timestamptz DEFAULT now()
     9→);
    10→
    11→-- Conversation participants
    12→CREATE TABLE conversation_participants (
    13→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    14→  conversation_id uuid NOT NULL REFERENCES conversations ON DELETE CASCADE,
    15→  profile_id uuid NOT NULL REFERENCES profiles ON DELETE CASCADE,
    16→  last_read_at timestamptz,
    17→  created_at timestamptz DEFAULT now(),
    18→  UNIQUE (conversation_id, profile_id)
    19→);
    20→
    21→-- Messages table
    22→CREATE TABLE messages (
    23→  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    24→  conversation_id uuid NOT NULL REFERENCES conversations ON DELETE CASCADE,
    25→  sender_id uuid NOT NULL REFERENCES profiles ON DELETE CASCADE,
    26→  content text NOT NULL,
    27→  attachments jsonb DEFAULT '[]',
    28→  status text DEFAULT 'sent' CHECK (status IN ('sent', 'delivered', 'read')),
    29→  created_at timestamptz DEFAULT now(),
    30→  updated_at timestamptz DEFAULT now()
    31→);
    32→
    33→-- Indexes for performance
    34→CREATE INDEX idx_conversation_participants_conversation_id ON conversation_participants (conversation_id);
    35→CREATE INDEX idx_conversation_participants_profile_id ON conversation_participants (profile_id);
    36→CREATE INDEX idx_messages_conversation_id ON messages (conversation_id);
    37→CREATE INDEX idx_messages_sender_id ON messages (sender_id);
    38→CREATE INDEX idx_messages_created_at ON messages (created_at DESC);
    39→
    40→-- Row Level Security
    41→ALTER TABLE conversations ENABLE ROW LEVEL SECURITY;
    42→ALTER TABLE conversation_participants ENABLE ROW LEVEL SECURITY;
    43→ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
    44→
    45→-- Conversations: participants can view their conversations
    46→CREATE POLICY "Users can view their own conversations"
    47→  ON conversations FOR SELECT
    48→  USING (
    49→    id IN (
    50→      SELECT conversation_id FROM conversation_participants
    51→      WHERE profile_id = auth.uid()
    52→    )
    53→  );
    54→
    55→-- Conversation participants: participants can view participants of their conversations
    56→CREATE POLICY "Users can view participants of their conversations"
    57→  ON conversation_participants FOR SELECT
    58→  USING (
    59→    conversation_id IN (
    60→      SELECT conversation_id FROM conversation_participants
    61→      WHERE profile_id = auth.uid()
    62→    )
    63→  );
    64→
    65→CREATE POLICY "Users can insert conversation participants"
    66→  ON conversation_participants FOR INSERT
    67→  WITH CHECK (profile_id = auth.uid());
    68→
    69→CREATE POLICY "Users can update their own participant record"
    70→  ON conversation_participants FOR UPDATE
    71→  USING (profile_id = auth.uid());
    72→
    73→-- Messages: participants can view messages in their conversations
    74→CREATE POLICY "Users can view messages in their conversations"
    75→  ON messages FOR SELECT
    76→  USING (
    77→    conversation_id IN (
    78→      SELECT conversation_id FROM conversation_participants
    79→      WHERE profile_id = auth.uid()
    80→    )
    81→  );
    82→
    83→CREATE POLICY "Users can send messages in their conversations"
    84→  ON messages FOR INSERT
    85→  WITH CHECK (
    86→    sender_id = auth.uid() AND
    87→    conversation_id IN (
    88→      SELECT conversation_id FROM conversation_participants
    89→      WHERE profile_id = auth.uid()
    90→    )
    91→  );
    92→
    93→CREATE POLICY "Users can update their own messages"
    94→  ON messages FOR UPDATE
    95→  USING (sender_id = auth.uid());
    96→
    97→-- Update updated_at trigger for messages
    98→CREATE TRIGGER messages_updated_at
    99→  BEFORE UPDATE ON messages
   100→  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
   101→
   102→-- Function to get conversation preview data
   103→CREATE OR REPLACE FUNCTION get_conversation_previews(user_id uuid)
   104→RETURNS TABLE (
   105→  conversation_id uuid,
   106→  other_participant_name text,
   107→  other_participant_avatar text,
   108→  last_message text,
   109→  last_message_time timestamptz,
   110→  unread_count bigint,
   111→  other_participant_is_online boolean
   112→) AS $$
   113→BEGIN
   114→  RETURN QUERY
   115→  SELECT
   116→    c.id as conversation_id,
   117→    p.name as other_participant_name,
   118→    p.avatar_url as other_participant_avatar,
   119→    last_msg.content as last_message,
   120→    last_msg.created_at as last_message_time,
   121→    COALESCE(unread.unread_count, 0) as unread_count,
   122→    true as other_participant_is_online -- TODO: Implement online status
   123→  FROM conversations c
   124→  INNER JOIN conversation_participants cp ON c.id = cp.conversation_id
   125→  INNER JOIN conversation_participants other_cp ON c.id = other_cp.conversation_id
   126→  INNER JOIN profiles p ON other_cp.profile_id = p.id
   127→  LEFT JOIN LATERAL (
   128→    SELECT content, created_at
   129→    FROM messages
   130→    WHERE conversation_id = c.id
   131→    ORDER BY created_at DESC
   132→    LIMIT 1
   133→  ) last_msg ON true
   134→  LEFT JOIN LATERAL (
   135→    SELECT COUNT(*) as unread_count
   136→    FROM messages
   137→    WHERE conversation_id = c.id
   138→      AND sender_id != user_id
   139→      AND created_at > cp.last_read_at
   140→  ) unread ON true
   141→  WHERE cp.profile_id = user_id
   142→    AND other_cp.profile_id != user_id
   143→  ORDER BY last_msg.created_at DESC NULLS LAST;
   144→END;
   145→$$ LANGUAGE plpgsql STABLE;
   146→
   147→-- Function to create or get existing conversation between two users
   148→CREATE OR REPLACE FUNCTION get_or_create_conversation(user1_id uuid, user2_id uuid)
   149→RETURNS uuid AS $$
   150→DECLARE
   151→  conversation_uuid uuid;
   152→BEGIN
   153→  -- Check if conversation already exists
   154→  SELECT c.id INTO conversation_uuid
   155→  FROM conversations c
   156→  INNER JOIN conversation_participants cp1 ON c.id = cp1.conversation_id
   157→  INNER JOIN conversation_participants cp2 ON c.id = cp2.conversation_id
   158→  WHERE cp1.profile_id = user1_id
   159→    AND cp2.profile_id = user2_id
   160→  LIMIT 1;
   161→
   162→  -- If conversation doesn't exist, create it
   163→  IF conversation_uuid IS NULL THEN
   164→    INSERT INTO conversations DEFAULT VALUES
   165→    RETURNING id INTO conversation_uuid;
   166→
   167→    INSERT INTO conversation_participants (conversation_id, profile_id)
   168→    VALUES (conversation_uuid, user1_id), (conversation_uuid, user2_id);
   169→  END IF;
   170→
   171→  RETURN conversation_uuid;
   172→END;
   173→$$ LANGUAGE plpgsql;

<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→-- TEST CURRENT RLS POLICIES
     3→-- ============================================
     4→-- Run this in Supabase SQL Editor to check current policies
     5→-- ============================================
     6→
     7→-- 1. Check all policies on matches and payments tables
     8→SELECT
     9→  schemaname,
    10→  tablename,
    11→  policyname,
    12→  permissive,
    13→  roles,
    14→  cmd,
    15→  qual,
    16→  with_check
    17→FROM pg_policies
    18→WHERE tablename IN ('matches', 'payments')
    19→ORDER BY tablename, policyname;
    20→
    21→-- 2. Check if RLS is enabled
    22→SELECT
    23→  schemaname,
    24→  tablename,
    25→  rowsecurity
    26→FROM pg_tables
    27→WHERE tablename IN ('matches', 'payments');
    28→
    29→-- 3. Test data (sample queries to understand current state)
    30→SELECT COUNT(*) as total_matches FROM matches;
    31→SELECT COUNT(*) as total_payments FROM payments;
    32→
    33→SELECT
    34→  status,
    35→  COUNT(*) as count
    36→FROM matches
    37→GROUP BY status
    38→ORDER BY count DESC;
    39→
    40→SELECT
    41→  status,
    42→  COUNT(*) as count
    43→FROM payments
    44→GROUP BY status
    45→ORDER BY count DESC;
    46→
    47→-- 4. Check recent activity
    48→SELECT
    49→  'matches' as table_name,
    50→  COUNT(*) as last_24h_count
    51→FROM matches
    52→WHERE created_at > NOW() - INTERVAL '24 hours'
    53→UNION ALL
    54→SELECT
    55→  'payments' as table_name,
    56→  COUNT(*) as last_24h_count
    57→FROM payments
    58→WHERE created_at > NOW() - INTERVAL '24 hours';
    59→
    60→-- 5. Check for potential abuse (multiple inserts from same user)
    61→SELECT
    62→  worker_id,
    63→  COUNT(*) as match_count,
    64→  MIN(created_at) as first_match,
    65→  MAX(created_at) as last_match
    66→FROM matches
    67→GROUP BY worker_id
    68→HAVING COUNT(*) > 10
    69→ORDER BY match_count DESC
    70→LIMIT 10;
    71→
    72→-- 6. Check payments without hired matches (potential fraud)
    73→SELECT
    74→  p.id as payment_id,
    75→  p.match_id,
    76→  p.amount,
    77→  p.status as payment_status,
    78→  p.created_at as payment_created,
    79→  m.status as match_status,
    80→  m.hired_at
    81→FROM payments p
    82→LEFT JOIN matches m ON p.match_id = m.id
    83→WHERE m.status != 'hired' OR m.id IS NULL
    84→ORDER BY p.created_at DESC;
    85→
    86→-- ============================================
    87→-- SIMPLE FIX FOR IMMEDIATE DEPLOYMENT
    88→-- ============================================
    89→-- If the application is breaking, use this minimal fix
    90→-- instead of the full secure policies
    91→
    92→/*
    93→-- Minimal fix: Allow contractors to insert payments for their matches
    94→DROP POLICY IF EXISTS "System can insert payments" ON payments;
    95→
    96→CREATE POLICY "Contractors can insert payments for their hired matches"
    97→  ON payments FOR INSERT
    98→  WITH CHECK (
    99→    -- Contractor owns the company
   100→    company_id IN (
   101→      SELECT id FROM companies WHERE profile_id = auth.uid()
   102→    )
   103→    AND
   104→    -- Match is hired
   105→    EXISTS (
   106→      SELECT 1 FROM matches
   107→      WHERE id = match_id AND status = 'hired'
   108→    )
   109→    AND
   110→    -- Match belongs to contractor's job
   111→    EXISTS (
   112→      SELECT 1 FROM matches m
   113→      JOIN jobs j ON m.job_id = j.id
   114→      WHERE m.id = match_id AND j.company_id = company_id
   115→    )
   116→  );
   117→
   118→-- Keep the original matches policy (workers can apply)
   119→-- This should already work with: worker_id = auth.uid() AND status = 'applied'
   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>


Perfect! I have found all the RLS policy definitions. Let me compile a comprehensive report organized by table name with the exact naming conventions and WHERE clauses used.

## RLS Policy Definitions Report

Based on my analysis of the codebase, here are all existing RLS policies organized by table:

### **profiles**
| Policy Name | Type | Qualifier (WHERE/WITH CHECK) |
|---|---|---|
| Public profiles are viewable by everyone | SELECT | `true` |
| Users can update their own profile | UPDATE | `auth.uid() = id` |
| Users can insert their own profile | INSERT | `auth.uid() = id` |

### **companies**
| Policy Name | Type | Qualifier |
|---|---|---|
| Companies are viewable by everyone | SELECT | `true` |
| Contractors can insert their own company | INSERT | `profile_id = auth.uid()` |
| Contractors can update their own company | UPDATE | `profile_id = auth.uid()` |

### **worker_profiles**
| Policy Name | Type | Qualifier |
|---|---|---|
| Worker profiles are viewable by everyone | SELECT | `true` |
| Workers can insert their own profile | INSERT | `profile_id = auth.uid()` |
| Workers can update their own profile | UPDATE | `profile_id = auth.uid()` |

### **jobs**
| Policy Name | Type | Qualifier |
|---|---|---|
| Jobs are viewable by everyone | SELECT | `true` |
| Contractors can insert jobs for their company | INSERT | `company_id IN (SELECT id FROM companies WHERE profile_id = auth.uid())` |
| Contractors can update their own jobs | UPDATE | `company_id IN (SELECT id FROM companies WHERE profile_id = auth.uid())` |

### **matches**
| Policy Name | Type | Qualifier |
|---|---|---|
| Users can view their own matches | SELECT | `worker_id = auth.uid() OR job_id IN (SELECT j.id FROM jobs j JOIN companies c ON j.company_id = c.id WHERE c.profile_id = auth.uid())` |
| Secure matches insert | INSERT | `(worker_id = auth.uid() AND status = 'applied') OR (job_id IN (SELECT j.id FROM jobs j JOIN companies c ON j.company_id = c.id WHERE c.profile_id = auth.uid()) AND status = 'suggested') OR (auth.jwt() ->> 'role' = 'service_role')` |
| Involved parties can update match status | UPDATE | Complex multi-condition policy with status transition validation (see file for full details) |

### **ratings**
| Policy Name | Type | Qualifier |
|---|---|---|
| Ratings are viewable by everyone | SELECT | `true` |
| Match participants can insert ratings | INSERT | `from_id = auth.uid()` |

### **payments**
| Policy Name | Type | Qualifier |
|---|---|---|
| Company owners can view their payments | SELECT | `company_id IN (SELECT id FROM companies WHERE profile_id = auth.uid())` |
| Secure payments insert | INSERT | `(auth.jwt() ->> 'role' = 'service_role') AND EXISTS (SELECT 1 FROM matches WHERE id = match_id AND status = 'hired') AND EXISTS (SELECT 1 FROM matches m JOIN jobs j ON m.job_id = j.id WHERE m.id = match_id AND j.company_id = company_id)` |

### **notifications**
| Policy Name | Type | Qualifier |
|---|---|---|
| Users can view their own notifications | SELECT | `profile_id = auth.uid()` |
| System can insert notifications | INSERT | `true` |
| Users can update their own notifications | UPDATE | `profile_id = auth.uid()` |

### **conversations** (New - added in add-messaging.sql)
| Policy Name | Type | Qualifier |
|---|---|---|
| Users can view their own conversations | SELECT | `id IN (SELECT conversation_id FROM conversation_participants WHERE profile_id = auth.uid())` |

### **conversation_participants** (New - added in add-messaging.sql)
| Policy Name | Type | Qualifier |
|---|---|---|
| Users can view participants of their conversations | SELECT | `conversation_id IN (SELECT conversation_id FROM conversation_participants WHERE profile_id = auth.uid())` |
| Users can insert conversation participants | INSERT | `profile_id = auth.uid()` |
| Users can update their own participant record | UPDATE | `profile_id = auth.uid()` |

### **messages** (New - added in add-messaging.sql)
| Policy Name | Type | Qualifier |
|---|---|---|
| Users can view messages in their conversations | SELECT | `conversation_id IN (SELECT conversation_id FROM conversation_participants WHERE profile_id = auth.uid())` |
| Users can send messages in their conversations | INSERT | `sender_id = auth.uid() AND conversation_id IN (SELECT conversation_id FROM conversation_participants WHERE profile_id = auth.uid())` |
| Users can update their own messages | UPDATE | `sender_id = auth.uid()` |

---

## Key Patterns Identified

**Naming Convention:**
- Public read access: `"[Table name] are/is viewable by everyone"`
- User-owned operations: `"Users can [ACTION] their own [resource]"`
- Owner-specific operations: `"[Owner type] can [ACTION] their [resource]"`
- System operations: `"System can [ACTION]"` or `"Secure [table] [action]"`

**Common WHERE Clause Patterns:**
1. **`true`** - Public/unrestricted access (used for SELECT only, never INSERT/UPDATE)
2. **`auth.uid() = column_id`** - Self-referential (user owns the record)
3. **`column_id = auth.uid()`** - Self-referential (reverse)
4. **`column_id IN (SELECT...)` with JOIN** - Owner verification through related tables
5. **`auth.jwt() ->> 'role' = 'service_role'`** - Service role detection for system operations
6. **Complex AND/OR conditions** - Multiple conditions combined for strict INSERT validation (matches, payments)

**Source Files:**
- `/home/ccuser/the-50-dollar-app/supabase/schema.sql` - Main schema with original policies
- `/home/ccuser/the-50-dollar-app/supabase/fix-critical-rls-insert-policies.sql` - Security fixes for matches/payments
- `/home/ccuser/the-50-dollar-app/supabase/add-messaging.sql` - Messaging system policies