---
description: Generate and apply Supabase Row Level Security policies
argument-hint: "[project-path: defaults to .]"
allowed-tools: Read, Write, Bash, Grep, Glob
---

Generate RLS policies for Supabase tables to prevent unauthorized data access.

## Steps

1. **Discover tables**
   - Scan `supabase/migrations/` for CREATE TABLE statements
   - Scan seed files for table references
   - Scan codebase for `supabase.from('table_name')` calls
   - Build complete table inventory

2. **Detect existing policies**
   - Look for `CREATE POLICY` statements in migrations
   - Look for `ALTER TABLE ... ENABLE ROW LEVEL SECURITY`
   - Identify tables with RLS enabled vs disabled

3. **Analyze access patterns**
   For each `supabase.from()` call:
   - What columns are selected?
   - Is there a `.eq('user_id', ...)` filter?
   - Is it in an authenticated context?
   - Infer ownership column (usually `user_id` or `owner_id`)

4. **Generate migration**
   For tables missing RLS:
   ```sql
   -- Enable RLS
   ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;
   
   -- SELECT: users can only read their own rows
   CREATE POLICY "Users can view own rows"
     ON table_name FOR SELECT
     USING (auth.uid() = user_id);
   
   -- INSERT: users can only insert with their user_id
   CREATE POLICY "Users can insert own rows"
     ON table_name FOR INSERT
     WITH CHECK (auth.uid() = user_id);
   
   -- UPDATE: users can only update their own rows
   CREATE POLICY "Users can update own rows"
     ON table_name FOR UPDATE
     USING (auth.uid() = user_id);
   
   -- DELETE: users can only delete their own rows
   CREATE POLICY "Users can delete own rows"
     ON table_name FOR DELETE
     USING (auth.uid() = user_id);
   ```

5. **Write migration file**
   - Create `supabase/migrations/{timestamp}_add_rls_policies.sql`
   - Include all generated policies

6. **Generate RLS-REPORT.md**
   ```markdown
   # RLS Policy Report
   
   ## Tables with RLS
   | Table | SELECT | INSERT | UPDATE | DELETE |
   |-------|--------|--------|--------|--------|
   | users | ✅ | ✅ | ✅ | ✅ |
   
   ## Tables MISSING RLS (CRITICAL)
   - orders (no policies, added in migration)
   
   ## Service Role Usage (review required)
   - src/api/admin.ts:42 — uses service role key
   ```

7. **Optionally apply**
   - If user confirms: `supabase db push`
   - Otherwise: leave migration file for manual review

## Important

- RLS is the MOST IMPORTANT security control for multi-tenant Supabase apps
- Missing RLS = any authenticated user can read ALL data
- Service role key bypasses RLS — flag all usages for review
- Always test policies locally before pushing to production
