The Complete Production SOP: How to Deploy and Run Supabase RLS & Realtime Engine in Autonomous AI Agents
Production SOP to install and run the Supabase RLS & Realtime Engine skill in Codex, Claude Code, Cursor, and Windsurf. Author secure policies deterministically.
Technical Overview & Architectural Context
Autonomous coding agents frequently introduce critical data leak vulnerabilities when drafting Supabase schemas and database migrations. Standard LLM completions often default to enabling Row Level Security (RLS) on Postgres tables while forgetting to write comprehensive policies for UPDATE, DELETE, or SELECT operations, or conversely, writing permissive `true` policies that grant unintended public access across multi-tenant boundaries. Furthermore, agents often overlook the performance implications of unindexed foreign keys in RLS expressions like `auth.uid() = user_id`, triggering sequential scans across production databases. The 'cursor-supabase' skill addresses these domain pitfalls by embedding deterministic operational constraints directly into agent context trees. It enforces strict procedural checkpoints: every table must have explicit RLS enabled, security policies must isolate tenant identifiers using defensive Postgres functions, client-side queries must enforce typed Supabase SDK filters, and realtime broadcast/presence channel permissions must strictly authenticate the initiating session before emitting table mutations.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into your workspace or global agent registry.
Autonomous runtimes such as Claude Code, Cursor, and Codex monitor local directory structures (like `.cursor/rules/`, `.claude/rules/`, or the unified `.agents/skills/` directory) to inject procedural constraints. We mount `cursor-supabase` as a deterministic SKILL.md manifest so the agent dynamically ingests strict RLS and Supabase schema authoring rules whenever database files are modified.
mkdir -p .agents/skills/cursor-supabase .cursor/rules && curl -fsSL https://askills.dev/api/skills/cursor-supabase/raw -o .agents/skills/cursor-supabase/SKILL.md && cp .agents/skills/cursor-supabase/SKILL.md .cursor/rules/supabase.mdc---
name: "cursor-supabase"
description: "Author secure Row Level Security (RLS) policies, Postgres functions, and Supabase client code."
category: "fullstack"
triggers:
- "supabase migration"
- "row level security"
- "rls policy"
- "supabase realtime"
dependencies:
npm:
- "@supabase/supabase-js"
---
# Supabase RLS & Realtime Engine Rules
1. Always generate deterministic migrations inside `supabase/migrations/<timestamp>_<name>.sql`.
2. Every `CREATE TABLE` statement MUST be immediately followed by `ALTER TABLE <table_name> ENABLE ROW LEVEL SECURITY;`.
3. Never author permissive `USING (true)` policies for authenticated roles unless explicitly tasked with a public read catalog.
4. Foreign key references matching `auth.uid()` MUST be indexed with B-tree indexes to prevent RLS-induced full table scans.
5. Verify policy coverage across ALL four operations: SELECT, INSERT, UPDATE, DELETE.Symlink `.agents/skills/cursor-supabase/SKILL.md` directly into `.cursor/rules/` to ensure real-time rule hot-reloading without consuming persistent system prompt tokens across unneeded task cycles.
Avoid committing local temporary rule files into public forks if they contain hardcoded project reference IDs; keep the SKILL.md strictly procedural and generic.
Environment Secrets & Dependency Validation
Install client libraries and configure mock/local Supabase environment variables without leaking credentials.
The skill relies on `@supabase/supabase-js` for deterministic client-side querying and type generation. Agents must verify that dependencies are declared in `package.json` and that secret keys (`SUPABASE_SERVICE_ROLE_KEY`) are kept isolated from client bundles (`NEXT_PUBLIC_SUPABASE_ANON_KEY`).
npm install @supabase/supabase-js && touch .env.example && printf 'NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321\nNEXT_PUBLIC_SUPABASE_ANON_KEY=eyJh...\nSUPABASE_SERVICE_ROLE_KEY=eyJh...' >> .env.exampleimport { createClient } from '@supabase/supabase-js';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'http://127.0.0.1:54321';
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '';
if (!supabaseAnonKey && process.env.NODE_ENV === 'production') {
throw new Error('Missing NEXT_PUBLIC_SUPABASE_ANON_KEY');
}
export const supabase = createClient(supabaseUrl, supabaseAnonKey);Instruct the agent to read `.env.example` rather than `.env.local` to prevent it from exposing production service keys in scratchpads or telemetry logs.
Never allow the agent to use `SUPABASE_SERVICE_ROLE_KEY` inside client-side components; this bypasses RLS completely and exposes your database to privilege escalation.
Intent Matching & Trigger Invocation
Trigger the autonomous agent with high-intent keywords that match the frontmatter triggers to activate RLS enforcement.
Autonomous agents inspect workspace skill triggers before generating database files. Using phrases like 'author rls policy', 'supabase migration', or 'multi-tenant organization rls' triggers the SKILL.md boundary constraints, preventing naive or insecure SQL drafts.
npx supabase test db || echo 'Database runner initialized for agent triggers'Frame prompts using explicit verbs such as 'Author an isolated multi-tenant migration with tenant-level RLS policies' to trigger the security-first code paths.
If the agent drafts an unindexed policy using `auth.jwt() ->> 'org_id'`, it will degrade database performance. Ensure the prompt mandates index creation.
Verification, Linting & Output Quality Gate
Run pgTAP tests and Supabase CLI database linters to validate policy isolation before concluding agent tasks.
The skill mandates self-verification through automated validation gates. The agent must run the Supabase database linter and inspect generated migration files for missing RLS policies or permissive filters before finalizing the pull request or commit.
npx supabase db lint --level error && npx supabase test dbBEGIN;
SELECT plan(3);
-- Test that RLS is enabled
SELECT tests.rls_enabled('public', 'organizations');
SELECT tests.rls_enabled('public', 'documents');
-- Verify unauthenticated user cannot read documents
SET ROLE anon;
SELECT is_empty('SELECT * FROM public.documents', 'Anon cannot view documents');
SELECT * FROM finish();
ROLLBACK;Review `git diff supabase/migrations/` to ensure the agent did not inject `SECURITY DEFINER` into custom Postgres functions without setting an explicit `search_path = public`.
Running migrations without `BEGIN; ... COMMIT;` blocks can leave Postgres in a partially migrated state if a policy error occurs mid-execution.
Real-World Scenario: Authoring Multi-Tenant Document Storage with RLS and Realtime Broadcast
“Generate a new Supabase migration creating an 'organizations' table and a 'documents' table. Ensure strict multi-tenant Row Level Security where users can only read and update documents matching their organization. Include B-tree indexes for foreign keys, enable RLS, and add a realtime broadcast publication for document updates.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent authored an INSERT policy that validates records with a `USING` clause instead of a `WITH CHECK` clause, or the authenticated user JWT lacks the corresponding tenancy claim during insertion.
ALTER POLICY "Users can insert documents for their org" ON documents WITH CHECK (EXISTS (SELECT 1 FROM organization_members om WHERE om.org_id = documents.organization_id AND om.user_id = auth.uid()));Root Cause: The agent enabled RLS via `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` but failed to generate access policies, effectively blocking all reads and writes including for authenticated service users.
npx supabase db lint && printf '\nCREATE POLICY "Allow authenticated users to read documents" ON documents FOR SELECT TO authenticated USING (true);\n' >> supabase/migrations/$(ls supabase/migrations | tail -n 1)Frequently Asked Questions (Supabase RLS & Realtime Engine SOP)
Q:Can I use Supabase RLS & Realtime Engine across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. You can symlink or copy the file into `.cursor/rules/`, `.claude/rules/`, or your Codex workspace configuration for identical deterministic policy enforcement.
Q:How does Supabase RLS & Realtime Engine prevent context window overflow during long agent sessions?
The skill isolates specific database rules and checklist triggers instead of dumping the entire Supabase documentation into system prompts. It only surfaces procedural constraints during migration and client query authoring.
Q:Does this skill require escalated root or container permissions?
No. The skill operates strictly within user workspace sandboxes, carrying an audited security score of 98/100 without requiring Docker daemon escalation or root privileges.
Ready to equip your autonomous agent with Supabase RLS & Realtime Engine?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.