supabase-rls-policy-generator
Supabase RLS Policy Generator
To generate comprehensive Row-Level Security policies for Supabase databases, follow these steps systematically.
Step 1: Analyze Current Schema
Before generating policies:
- Ask user for the database schema file path or table names
- Read the schema to understand table structures, foreign keys, and relationships
- Identify tables that need RLS protection
- Determine the security model: multi-tenant, role-based, or hybrid
Step 2: Identify Security Requirements
Determine access patterns by asking:
- Is this a multi-tenant application? (tenant_id isolation)
- What roles exist in the system? (admin, user, viewer, etc.)
- Are there public vs private resources?
- Do users need to share resources across accounts?
- Are there hierarchical permissions? (organization > team > user)
Consult references/rls-patterns.md for common security patterns.
Step 3: Generate RLS Policies
For each table requiring protection, generate policies following this structure:
Enable RLS
ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;
Policy Types to Generate
SELECT Policies - Control read access:
- User can view their own records
- User can view records in their tenant
- Role-based viewing (admins see all)
- Public records accessible to all authenticated users
INSERT Policies - Control creation:
- User can create records with their own user_id
- User can create records in their tenant
- Role-based creation restrictions
UPDATE Policies - Control modifications:
- User can update their own records
- Admins can update all records
- Tenant-scoped updates
DELETE Policies - Control deletion:
- User can delete their own records
- Admin-only deletion
- Tenant-scoped deletion
Policy Templates
Use templates from assets/policy-templates.sql:
Basic User Ownership:
CREATE POLICY "Users can view own records"
ON table_name FOR SELECT
USING (auth.uid() = user_id);
Multi-Tenant Isolation:
CREATE POLICY "Tenant isolation"
ON table_name FOR ALL
USING (
tenant_id IN (
SELECT tenant_id FROM user_tenants
WHERE user_id = auth.uid()
)
);
Role-Based Access:
CREATE POLICY "Admins have full access"
ON table_name FOR ALL
USING (
auth.jwt() ->> 'role' = 'admin'
);
JWT Claims:
CREATE POLICY "Organization access"
ON table_name FOR SELECT
USING (
organization_id = (auth.jwt() -> 'app_metadata' ->> 'organization_id')::uuid
);
Step 4: Generate Helper Functions
Create PostgreSQL functions to support complex policies:
-- Function to check user role
CREATE OR REPLACE FUNCTION auth.user_has_role(required_role TEXT)
RETURNS BOOLEAN AS $$
BEGIN
RETURN (auth.jwt() ->> 'role') = required_role;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Function to check tenant membership
CREATE OR REPLACE FUNCTION auth.user_in_tenant(target_tenant_id UUID)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM user_tenants
WHERE user_id = auth.uid()
AND tenant_id = target_tenant_id
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
Step 5: Generate Testing Queries
Create test queries to verify policies work correctly:
-- Test as authenticated user
SET request.jwt.claim.sub = 'user-uuid';
SELECT * FROM table_name; -- Should see only accessible records
-- Test as admin
SET request.jwt.claim.role = 'admin';
SELECT * FROM table_name; -- Should see all records
-- Test as different tenant
SET request.jwt.claim.sub = 'other-user-uuid';
SELECT * FROM table_name; -- Should see different tenant's records
Step 6: Create Migration File
Generate a migration file with proper structure:
-- Migration: Add RLS policies
-- Created: [timestamp]
-- Enable RLS on tables
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE items ENABLE ROW LEVEL SECURITY;
-- Drop existing policies if any
DROP POLICY IF EXISTS "policy_name" ON table_name;
-- Create new policies
[Generated policies here]
-- Create helper functions
[Generated functions here]
-- Grant necessary permissions
GRANT SELECT, INSERT, UPDATE, DELETE ON table_name TO authenticated;
GRANT SELECT ON table_name TO anon; -- If public read needed
Step 7: Document Generated Policies
Create documentation explaining:
- What each policy does
- Which users/roles have what access
- Any special cases or exceptions
- How to test the policies
- Common troubleshooting tips
Use template from assets/policy-documentation-template.md.
Implementation Guidelines
Security Best Practices
- Always enable RLS on tables with user data
- Use auth.uid() for user-owned records
- Use JWT claims for role-based access
- Prefer SECURITY DEFINER functions for complex logic
- Test policies with different user roles
- Use USING clause for read access, WITH CHECK for write validation
Performance Considerations
- Add indexes on columns used in policies (user_id, tenant_id, role)
- Keep policy logic simple for better performance
- Use helper functions for reusable complex logic
- Avoid subqueries in policies when possible
Common Patterns
Consult references/rls-patterns.md for detailed examples of:
- Multi-tenant isolation
- Role-based access control (RBAC)
- Attribute-based access control (ABAC)
- Hierarchical permissions
- Public/private resource splitting
- Shared resource access
Output Format
Generate files in the following structure:
migrations/
[timestamp]_add_rls_policies.sql
docs/
rls-policies.md (documentation)
tests/
rls_tests.sql (test queries)
Verification Checklist
Before completing:
- RLS enabled on all sensitive tables
- Policies cover all operations (SELECT, INSERT, UPDATE, DELETE)
- Policies tested with different user roles
- Indexes added for policy columns
- Helper functions created for complex logic
- Documentation generated
- Test queries provided
- No policies accidentally grant excessive access
Consulting References
Throughout generation:
- Consult
references/rls-patterns.mdfor security patterns - Consult
references/supabase-auth.mdfor auth.uid() and JWT structure - Use templates from
assets/policy-templates.sql
Completion
When finished:
- Display the generated migration file
- Summarize the policies created
- Provide testing instructions
- Offer to generate additional policies or modify existing ones
More from hopeoverture/worldbuilding-app-skills
eslint-prettier-husky-config
This skill should be used when setting up code quality tooling with ESLint v9 flat config, Prettier formatting, Husky git hooks, lint-staged pre-commit checks, and GitHub Actions CI lint workflow. Apply when initializing linting, adding code formatting, configuring pre-commit hooks, setting up quality gates, or establishing lint CI checks for Next.js or React projects.
51testing-next-stack
Scaffolds comprehensive testing setup for Next.js applications including Vitest unit tests, React Testing Library component tests, and Playwright E2E flows with accessibility testing via axe-core. This skill should be used when setting up test infrastructure, generating test files, creating test utilities, adding accessibility checks, or configuring testing frameworks for Next.js projects. Trigger terms include setup testing, scaffold tests, vitest, RTL, playwright, e2e tests, component tests, unit tests, accessibility testing, a11y tests, axe-core, test configuration.
38markdown-editor-integrator
This skill should be used when installing and configuring markdown editor functionality using @uiw/react-md-editor. Applies when adding rich text editing, markdown support, WYSIWYG editors, content editing with preview, or text formatting features. Trigger terms include markdown editor, rich text editor, text editor, add markdown, install markdown editor, markdown component, WYSIWYG, content editor, text formatting, editor preview.
27form-generator-rhf-zod
This skill should be used when generating React forms with React Hook Form, Zod validation, and shadcn/ui components. Applies when creating entity forms, character editors, location forms, data entry forms, or any form requiring client and server validation. Trigger terms include create form, generate form, build form, React Hook Form, RHF, Zod validation, form component, entity form, character form, data entry, form schema.
23supabase-auth-ssr-setup
This skill should be used when configuring Supabase Auth for server-side rendering with Next.js App Router, including secure cookie handling, middleware protection, route guards, authentication utilities, and logout flow. Apply when setting up SSR auth, adding protected routes, implementing middleware authentication, configuring secure sessions, or building login/logout flows with Supabase.
18tailwind-shadcn-ui-setup
This skill should be used when setting up, configuring, or initializing Tailwind CSS (v3 or v4) and shadcn/ui for Next.js 16 App Router projects. Configure dark mode, design tokens, base layout with header/sidebar, accessibility defaults, and generate example components. Includes comprehensive setup automation, theme customization, and production-ready patterns. Use when the user requests "setup Tailwind", "configure shadcn/ui", "add dark mode", "initialize design system", or "setup UI framework" for Next.js projects.
17