@polymorphism-tech/morph-spec 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CLAUDE.md +36 -0
  2. package/README.md +2 -2
  3. package/bin/morph-spec.js +3 -0
  4. package/bin/task-manager.js +999 -962
  5. package/claude-plugin.json +1 -1
  6. package/docs/CHEATSHEET.md +1 -1
  7. package/docs/QUICKSTART.md +1 -1
  8. package/framework/agents/ai-agents/vector-search-expert.md +247 -233
  9. package/framework/agents/backend/ms-agent-expert.md +1 -1
  10. package/framework/agents/backend/neon-expert.md +379 -0
  11. package/framework/agents/frontend/gsap-animator.md +131 -0
  12. package/framework/agents/integrations/neon-auth.md +151 -0
  13. package/framework/agents.json +1183 -1085
  14. package/framework/commands/morph-preflight.md +200 -192
  15. package/framework/hooks/claude-code/session-start/inject-morph-context.js +1 -1
  16. package/framework/rules/gsap-standards.md +13 -0
  17. package/framework/rules/neon-auth-standards.md +13 -0
  18. package/framework/rules/neon-standards.md +26 -0
  19. package/framework/skills/level-0-meta/mcp-registry.json +1 -1
  20. package/framework/skills/level-0-meta/morph-agent-teams/SKILL.md +472 -472
  21. package/framework/skills/level-0-meta/morph-frontend-review/SKILL.md +1 -1
  22. package/framework/skills/level-0-meta/morph-init/SKILL.md +12 -12
  23. package/framework/skills/level-0-meta/morph-post-implementation/SKILL.md +5 -5
  24. package/framework/skills/level-0-meta/morph-tool-usage-guide/SKILL.md +5 -5
  25. package/framework/skills/level-0-meta/morph-tool-usage-guide/references/tools-per-phase.md +7 -7
  26. package/framework/skills/level-1-workflows/morph-phase-codebase-analysis/SKILL.md +24 -24
  27. package/framework/skills/level-1-workflows/morph-phase-design/SKILL.md +12 -12
  28. package/framework/skills/level-1-workflows/morph-phase-implement/SKILL.md +9 -9
  29. package/framework/skills/level-1-workflows/morph-phase-plan/SKILL.md +1 -1
  30. package/framework/skills/level-1-workflows/morph-phase-tasks/SKILL.md +1 -1
  31. package/framework/skills/level-1-workflows/morph-phase-tasks/references/task-planning-patterns.md +143 -143
  32. package/framework/skills/level-1-workflows/morph-phase-uiux/SKILL.md +1 -1
  33. package/framework/skills/level-1-workflows/morph-scope-escalation/SKILL.md +1 -1
  34. package/framework/standards/STANDARDS.json +197 -116
  35. package/framework/standards/ai-agents/production.md +1 -0
  36. package/framework/standards/ai-agents/setup.md +3 -2
  37. package/framework/standards/ai-agents/workflows.md +1 -0
  38. package/framework/standards/architecture/vertical-slice/vertical-slice.md +4 -4
  39. package/framework/standards/backend/database/postgresql/database.md +63 -83
  40. package/framework/standards/backend/dotnet/scalar-ui.md +172 -172
  41. package/framework/standards/backend/dotnet/vsa-handler-patterns.md +274 -274
  42. package/framework/standards/backend/integrations/asaas/asaas-api.md +2 -2
  43. package/framework/standards/backend/integrations/neon-auth/neon-auth.md +364 -0
  44. package/framework/standards/frontend/design-system/animations.md +9 -0
  45. package/framework/standards/frontend/gsap/gsap-core.md +463 -0
  46. package/framework/standards/frontend/gsap/gsap-plugins.md +294 -0
  47. package/framework/standards/frontend/gsap/gsap-scrolltrigger.md +318 -0
  48. package/framework/standards/frontend/nextjs/motion-patterns.md +1 -0
  49. package/framework/standards/frontend/nextjs/nextjs-patterns.md +47 -37
  50. package/framework/standards/infrastructure/docker/easypanel-deploy.md +4 -8
  51. package/framework/standards/infrastructure/neon/neon-pgrag.md +239 -0
  52. package/framework/standards/infrastructure/neon/neon-pgvector.md +236 -0
  53. package/framework/standards/infrastructure/neon/neon-semantic-kernel.md +310 -0
  54. package/framework/standards/infrastructure/neon/neon-setup.md +186 -0
  55. package/framework/standards/integration/mcp/mcp-tools.md +32 -34
  56. package/framework/templates/README.md +20 -20
  57. package/framework/templates/REGISTRY.json +54 -101
  58. package/framework/templates/code/dotnet/abstractions/api-endpoint.cs +7 -7
  59. package/framework/templates/code/dotnet/backend/repository.cs +148 -148
  60. package/framework/templates/code/dotnet/contracts/contracts-vsa.cs +2 -2
  61. package/framework/templates/code/dotnet/database/vector-entity.cs +93 -0
  62. package/framework/templates/code/dotnet/feature/endpoint.cs.hbs +1 -1
  63. package/framework/templates/code/sql/{supabase-migration.sql → postgresql-migration.sql} +12 -21
  64. package/framework/templates/code/sql/{supabase-migration.template.sql → postgresql-migration.template.sql} +13 -18
  65. package/framework/templates/code/sql/{rls-policy.sql → postgresql-rls-policy.sql} +6 -9
  66. package/framework/templates/code/typescript/contracts.ts +167 -168
  67. package/framework/templates/context/CONTEXT.md +3 -3
  68. package/framework/templates/docs/proposal.md +6 -6
  69. package/framework/templates/docs/ui-components.md +1 -1
  70. package/framework/templates/feature/decisions.md +122 -121
  71. package/framework/templates/feature/recap.md +145 -145
  72. package/framework/templates/feature/tasks.md +199 -199
  73. package/framework/templates/frontend/nextjs/gsap-scroll-section.tsx.hbs +44 -0
  74. package/framework/templates/infrastructure/docker/docker-compose.template.yml +50 -67
  75. package/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +38 -38
  76. package/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +48 -48
  77. package/framework/templates/infrastructure/docker/easypanel.template.json +46 -54
  78. package/framework/templates/infrastructure/github/README.md +56 -56
  79. package/framework/templates/integrations/neon-auth-config.cs +133 -0
  80. package/framework/templates/integrations/semantic-kernel-neon.cs +125 -0
  81. package/framework/workflows/README.md +1 -1
  82. package/framework/workflows/docs/full-morph.md +69 -69
  83. package/package.json +1 -1
  84. package/src/commands/agents/dispatch-agents.js +19 -15
  85. package/src/commands/state/advance-phase.js +5 -0
  86. package/src/commands/tasks/task.js +3 -0
  87. package/src/core/state/state-manager.js +45 -1
  88. package/src/core/templates/template-registry.js +1 -66
  89. package/src/lib/detectors/index.js +4 -4
  90. package/src/lib/generators/architecture-scanner.js +639 -640
  91. package/src/lib/installers/mcp-installer.js +1 -1
  92. package/src/lib/tasks/task-classifier.js +15 -1
  93. package/src/lib/tasks/test-runner.js +5 -1
  94. package/src/lib/validators/content/content-validator.js +9 -10
  95. package/src/lib/validators/validation-runner.js +7 -5
  96. package/framework/agents/backend/supabase-expert.md +0 -256
  97. package/framework/agents/integrations/clerk-auth.md +0 -109
  98. package/framework/rules/clerk-standards.md +0 -13
  99. package/framework/rules/supabase-standards.md +0 -29
  100. package/framework/standards/backend/integrations/clerk/clerk-auth.md +0 -290
  101. package/framework/standards/infrastructure/supabase/mcp-setup.md +0 -142
  102. package/framework/standards/infrastructure/supabase/supabase-auth.md +0 -176
  103. package/framework/standards/infrastructure/supabase/supabase-custom-jwt.md +0 -206
  104. package/framework/standards/infrastructure/supabase/supabase-pgvector.md +0 -169
  105. package/framework/standards/infrastructure/supabase/supabase-rls.md +0 -184
  106. package/framework/standards/infrastructure/supabase/supabase-storage.md +0 -153
  107. package/framework/templates/integrations/clerk-config.cs +0 -217
@@ -1,206 +0,0 @@
1
- # Supabase Custom JWT Standard
2
-
3
- > **Scope:** dotnet, nextjs
4
- > **Layer:** 2 (on keyword)
5
- > **Keywords:** JWT, custom JWT, JWT signing, token creation, JWT claims, custom claims
6
- > **Load When:** custom JWT patterns detected (e.g., custom claims, manual token creation)
7
-
8
- ## JWT Token Creation
9
-
10
- ### Node.js (jose)
11
-
12
- ```ts
13
- import { SignJWT } from "jose";
14
-
15
- const secret = new TextEncoder().encode(process.env.SUPABASE_JWT_SECRET!);
16
-
17
- export async function createCustomJWT(userId: string, claims: Record<string, unknown>) {
18
- return new SignJWT({
19
- sub: userId,
20
- role: "authenticated",
21
- app_metadata: claims,
22
- aud: "authenticated",
23
- })
24
- .setProtectedHeader({ alg: "HS256", typ: "JWT" })
25
- .setIssuedAt()
26
- .setExpirationTime("1h")
27
- .sign(secret);
28
- }
29
- ```
30
-
31
- ### .NET (System.IdentityModel.Tokens.Jwt)
32
-
33
- ```csharp
34
- using System.IdentityModel.Tokens.Jwt;
35
- using System.Security.Claims;
36
- using Microsoft.IdentityModel.Tokens;
37
-
38
- public static string CreateCustomJWT(string userId, Dictionary<string, string> appMetadata)
39
- {
40
- var key = new SymmetricSecurityKey(
41
- Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SUPABASE_JWT_SECRET")!));
42
-
43
- var claims = new List<Claim>
44
- {
45
- new(JwtRegisteredClaimNames.Sub, userId),
46
- new("role", "authenticated"),
47
- new("aud", "authenticated"),
48
- };
49
-
50
- // Add app_metadata claims
51
- foreach (var (k, v) in appMetadata)
52
- claims.Add(new Claim($"app_metadata.{k}", v));
53
-
54
- var token = new JwtSecurityToken(
55
- claims: claims,
56
- expires: DateTime.UtcNow.AddHours(1),
57
- signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
58
-
59
- return new JwtSecurityTokenHandler().WriteToken(token);
60
- }
61
- ```
62
-
63
- ## Custom Claims Structure
64
-
65
- ### Required Claims
66
-
67
- | Claim | Description | Example |
68
- |-------|-------------|---------|
69
- | `sub` | User ID (UUID) | `"a1b2c3d4-..."` |
70
- | `role` | Supabase role | `"authenticated"` |
71
- | `aud` | Audience | `"authenticated"` |
72
- | `exp` | Expiration (epoch) | `1710000000` |
73
-
74
- ### Recommended App Metadata Claims
75
-
76
- | Claim | Purpose | Used By |
77
- |-------|---------|---------|
78
- | `tenant_id` | Multi-tenant RLS filtering | RLS policies |
79
- | `org_id` | Organization scoping | RLS policies |
80
- | `permissions` | Fine-grained access | Application logic |
81
-
82
- ### Structure
83
-
84
- ```json
85
- {
86
- "sub": "user-uuid",
87
- "role": "authenticated",
88
- "aud": "authenticated",
89
- "iat": 1710000000,
90
- "exp": 1710003600,
91
- "app_metadata": {
92
- "tenant_id": "tenant-uuid",
93
- "org_id": "org-uuid",
94
- "permissions": ["read", "write"]
95
- }
96
- }
97
- ```
98
-
99
- **RLS Integration:** Always include `tenant_id` in `app_metadata` for RLS policies. Access in SQL via:
100
-
101
- ```sql
102
- -- In RLS policy
103
- (auth.jwt() -> 'app_metadata' ->> 'tenant_id')::uuid = tenant_id
104
- ```
105
-
106
- Cross-ref: [supabase-rls.md](supabase-rls.md)
107
-
108
- ## JWT Refresh Patterns
109
-
110
- ### Token Rotation (Recommended)
111
-
112
- 1. Issue short-lived access tokens (1h max)
113
- 2. Use refresh tokens with rotation enabled
114
- 3. Invalidate old refresh token on each rotation
115
- 4. Store refresh tokens server-side only — never expose to client JS
116
-
117
- ### Node.js Refresh Flow
118
-
119
- ```ts
120
- import { createClient } from "@supabase/supabase-js";
121
-
122
- const supabase = createClient(url, anonKey);
123
-
124
- // On auth state change, handle token refresh
125
- supabase.auth.onAuthStateChange((event, session) => {
126
- if (event === "TOKEN_REFRESHED" && session) {
127
- // Update server-side session cookie
128
- updateSessionCookie(session.access_token, session.refresh_token);
129
- }
130
- });
131
- ```
132
-
133
- ### .NET Refresh Flow
134
-
135
- ```csharp
136
- // Validate and refresh on each request via middleware
137
- public async Task InvokeAsync(HttpContext context)
138
- {
139
- var token = context.Request.Headers.Authorization.ToString().Replace("Bearer ", "");
140
-
141
- var handler = new JwtSecurityTokenHandler();
142
- var jwt = handler.ReadJwtToken(token);
143
-
144
- // If token expires within 5 minutes, trigger refresh
145
- if (jwt.ValidTo < DateTime.UtcNow.AddMinutes(5))
146
- {
147
- var newToken = await RefreshTokenAsync(jwt.Subject);
148
- context.Response.Headers.Append("X-New-Token", newToken);
149
- }
150
-
151
- await _next(context);
152
- }
153
- ```
154
-
155
- ## Validation Setup
156
-
157
- ### Environment Variables
158
-
159
- ```env
160
- # Required — never commit to source control
161
- SUPABASE_JWT_SECRET=your-jwt-secret-from-supabase-dashboard
162
- ```
163
-
164
- - **Always** store JWT secret in environment variables or a secrets manager
165
- - **Never** hardcode secrets in source code
166
- - **Use HS256** for shared secrets (default Supabase setup)
167
- - **Use RS256** for asymmetric keys (advanced: separate sign/verify keys)
168
-
169
- ### Validation in .NET
170
-
171
- ```csharp
172
- builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
173
- .AddJwtBearer(options =>
174
- {
175
- options.TokenValidationParameters = new TokenValidationParameters
176
- {
177
- ValidateIssuerSigningKey = true,
178
- IssuerSigningKey = new SymmetricSecurityKey(
179
- Encoding.UTF8.GetBytes(builder.Configuration["Supabase:JwtSecret"]!)),
180
- ValidateIssuer = false,
181
- ValidateAudience = true,
182
- ValidAudience = "authenticated",
183
- ClockSkew = TimeSpan.FromSeconds(30),
184
- };
185
- });
186
- ```
187
-
188
- ### Validation in Node.js
189
-
190
- ```ts
191
- import { jwtVerify } from "jose";
192
-
193
- const secret = new TextEncoder().encode(process.env.SUPABASE_JWT_SECRET!);
194
-
195
- export async function verifyJWT(token: string) {
196
- const { payload } = await jwtVerify(token, secret, {
197
- audience: "authenticated",
198
- });
199
- return payload;
200
- }
201
- ```
202
-
203
- ## Cross-References
204
-
205
- - [Supabase Auth](supabase-auth.md) — authentication flows and client setup
206
- - [Supabase RLS](supabase-rls.md) — row-level security policies using JWT claims
@@ -1,169 +0,0 @@
1
- # Supabase pgvector Standard
2
-
3
- > **Scope:** nextjs-supabase
4
- > **Layer:** 2 (on keyword)
5
- > **Keywords:** supabase, pgvector, embedding, similarity, vector search
6
- > **Load When:** supabase pgvector keywords detected
7
-
8
- Stack: Next.js 15 + Supabase + .NET Backend
9
-
10
- ## Core Rules
11
-
12
- - ALWAYS use HNSW indexes for production (faster queries, no training required)
13
- - ALWAYS match dimensions to embedding model (e.g., 1536 for text-embedding-3-small)
14
- - NEVER store embeddings without an index -- full table scan at query time
15
- - Use `halfvec` for large datasets to halve storage (16-bit vs 32-bit per dimension)
16
- - ALWAYS use RLS on tables containing embeddings
17
-
18
- ## Setup and Table Design
19
-
20
- ```sql
21
- CREATE EXTENSION IF NOT EXISTS vector;
22
-
23
- CREATE TABLE documents (
24
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
25
- user_id UUID NOT NULL REFERENCES auth.users(id),
26
- title TEXT NOT NULL,
27
- content TEXT NOT NULL,
28
- metadata JSONB DEFAULT '{}',
29
- embedding vector(1536),
30
- created_at TIMESTAMPTZ DEFAULT now()
31
- );
32
-
33
- ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
34
- CREATE POLICY "owner_access" ON documents FOR ALL
35
- USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
36
- CREATE INDEX idx_documents_user_id ON documents (user_id);
37
- ```
38
-
39
- ### halfvec Optimization
40
-
41
- | Type | Storage/dim | 1536-dim | Best for |
42
- |------|------------|----------|----------|
43
- | `vector` | 4 bytes | 6 KB | High precision, small datasets |
44
- | `halfvec` | 2 bytes | 3 KB | Large datasets, cost optimization |
45
-
46
- ## Index Types
47
-
48
- ```sql
49
- -- HNSW (recommended)
50
- CREATE INDEX idx_docs_embedding ON documents
51
- USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
52
-
53
- -- IVFFlat (legacy, requires existing data)
54
- CREATE INDEX idx_docs_ivf ON documents
55
- USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
56
- ```
57
-
58
- | Feature | HNSW | IVFFlat |
59
- |---------|------|---------|
60
- | Query speed | Faster | Slower |
61
- | Requires training | No | Yes |
62
- | Recall quality | Higher | Lower |
63
- | Recommended | Yes | Only for very large datasets |
64
-
65
- ## HNSW Parameters
66
-
67
- | Parameter | Default | Tuning |
68
- |-----------|---------|--------|
69
- | `m` | 16 | Higher = better recall, more memory |
70
- | `ef_construction` | 64 | Higher = better index, slower build |
71
- | `ef_search` | 40 | `SET hnsw.ef_search = 100;` per session |
72
-
73
- ## Distance Functions
74
-
75
- | Operator | Function | Index Ops | Use Case |
76
- |----------|----------|-----------|----------|
77
- | `<=>` | Cosine distance | `vector_cosine_ops` | Normalized embeddings (most common) |
78
- | `<->` | L2 (Euclidean) | `vector_l2_ops` | Spatial/positional data |
79
- | `<#>` | Inner product (neg) | `vector_ip_ops` | Pre-normalized, max similarity |
80
-
81
- ## Similarity Search
82
-
83
- ```sql
84
- CREATE OR REPLACE FUNCTION match_documents(
85
- query_embedding vector(1536),
86
- match_threshold float DEFAULT 0.78,
87
- match_count int DEFAULT 10,
88
- p_user_id uuid DEFAULT auth.uid()
89
- ) RETURNS TABLE (id uuid, title text, content text, similarity float)
90
- LANGUAGE sql STABLE AS $$
91
- SELECT d.id, d.title, d.content,
92
- 1 - (d.embedding <=> query_embedding) AS similarity
93
- FROM documents d
94
- WHERE d.user_id = p_user_id
95
- AND 1 - (d.embedding <=> query_embedding) > match_threshold
96
- ORDER BY d.embedding <=> query_embedding
97
- LIMIT match_count;
98
- $$;
99
- ```
100
-
101
- ## Hybrid Search (Vector + Full-Text)
102
-
103
- ```sql
104
- CREATE OR REPLACE FUNCTION hybrid_search(
105
- query_text text, query_embedding vector(1536),
106
- match_count int DEFAULT 10,
107
- text_weight float DEFAULT 0.3, vector_weight float DEFAULT 0.7
108
- ) RETURNS TABLE (id uuid, title text, content text, score float)
109
- LANGUAGE sql STABLE AS $$
110
- WITH vector_results AS (
111
- SELECT id, title, content,
112
- 1 - (embedding <=> query_embedding) AS vector_score
113
- FROM documents WHERE user_id = auth.uid()
114
- ORDER BY embedding <=> query_embedding LIMIT match_count * 2
115
- ),
116
- text_results AS (
117
- SELECT id, title, content,
118
- ts_rank(to_tsvector('english', content), plainto_tsquery('english', query_text)) AS text_score
119
- FROM documents WHERE user_id = auth.uid()
120
- AND to_tsvector('english', content) @@ plainto_tsquery('english', query_text)
121
- LIMIT match_count * 2
122
- )
123
- SELECT COALESCE(v.id, t.id), COALESCE(v.title, t.title), COALESCE(v.content, t.content),
124
- (COALESCE(v.vector_score, 0) * vector_weight + COALESCE(t.text_score, 0) * text_weight)
125
- FROM vector_results v FULL OUTER JOIN text_results t ON v.id = t.id
126
- ORDER BY score DESC LIMIT match_count;
127
- $$;
128
- ```
129
-
130
- ## .NET Integration (Npgsql)
131
-
132
- ```csharp
133
- public sealed class DocumentRepository(AppDbContext db)
134
- {
135
- public async Task StoreEmbeddingAsync(
136
- Guid documentId, float[] embedding, CancellationToken ct = default)
137
- {
138
- await db.Database.ExecuteSqlInterpolatedAsync(
139
- $"UPDATE documents SET embedding = {new Vector(embedding)} WHERE id = {documentId}", ct);
140
- }
141
-
142
- public async Task<List<DocumentMatch>> SearchSimilarAsync(
143
- float[] queryEmbedding, int limit = 10, float threshold = 0.78f,
144
- CancellationToken ct = default)
145
- {
146
- return await db.Database.SqlQuery<DocumentMatch>($"""
147
- SELECT id, title, content,
148
- 1 - (embedding <=> {new Vector(queryEmbedding)}::vector) AS similarity
149
- FROM documents
150
- WHERE 1 - (embedding <=> {new Vector(queryEmbedding)}::vector) > {threshold}
151
- ORDER BY embedding <=> {new Vector(queryEmbedding)}::vector LIMIT {limit}
152
- """).ToListAsync(ct);
153
- }
154
- }
155
-
156
- // EF Core registration
157
- builder.Services.AddDbContext<AppDbContext>(o =>
158
- o.UseNpgsql(connectionString, npg => npg.UseVector()));
159
- ```
160
-
161
- ## Common Mistakes
162
-
163
- | Wrong | Right | Why |
164
- |-------|-------|-----|
165
- | No index on embedding column | HNSW index | Full table scan, extremely slow |
166
- | `ORDER BY similarity DESC` | `ORDER BY embedding <=> query ASC` | Operator returns distance, not similarity |
167
- | Mixing embedding dimensions | Consistent dimensions per column | Dimension mismatch causes runtime errors |
168
- | Full-precision for millions of rows | `halfvec` for large datasets | 2x storage savings, minimal quality loss |
169
- | Missing RLS on embedding tables | RLS with user/tenant policies | Embeddings contain sensitive content context |
@@ -1,184 +0,0 @@
1
- # Supabase Row Level Security Standard
2
-
3
- > **Scope:** nextjs-supabase
4
- > **Layer:** 2 (on keyword)
5
- > **Keywords:** supabase, rls, policy, security, row level security
6
- > **Load When:** supabase rls keywords detected
7
-
8
- Stack: Next.js 15 + Supabase + .NET Backend
9
-
10
- ## Core Rules
11
-
12
- - ALWAYS enable RLS on every table: `ALTER TABLE t ENABLE ROW LEVEL SECURITY`
13
- - NEVER rely solely on application-level filtering — RLS is the security boundary
14
- - `service_role` key bypasses ALL RLS — use only on trusted backend
15
- - ALWAYS create at least one policy after enabling RLS — otherwise no rows are accessible
16
- - ALWAYS add indexes on columns used in RLS policies
17
-
18
- ## Policy Syntax
19
-
20
- ### USING vs WITH CHECK
21
-
22
- | Clause | Applies To | Purpose |
23
- |--------|-----------|---------|
24
- | `USING (expr)` | SELECT, UPDATE, DELETE | Filter which existing rows are visible |
25
- | `WITH CHECK (expr)` | INSERT, UPDATE | Validate new/modified row data |
26
-
27
- ```sql
28
- -- SELECT: only see your own rows
29
- CREATE POLICY "users_select_own" ON documents
30
- FOR SELECT USING (user_id = auth.uid());
31
-
32
- -- INSERT: can only insert rows owned by you
33
- CREATE POLICY "users_insert_own" ON documents
34
- FOR INSERT WITH CHECK (user_id = auth.uid());
35
-
36
- -- UPDATE: can only see AND modify your own rows
37
- CREATE POLICY "users_update_own" ON documents
38
- FOR UPDATE
39
- USING (user_id = auth.uid())
40
- WITH CHECK (user_id = auth.uid());
41
-
42
- -- DELETE: can only delete your own rows
43
- CREATE POLICY "users_delete_own" ON documents
44
- FOR DELETE USING (user_id = auth.uid());
45
- ```
46
-
47
- ## Auth Functions
48
-
49
- | Function | Returns | Use Case |
50
- |----------|---------|----------|
51
- | `auth.uid()` | UUID of authenticated user | Ownership checks |
52
- | `auth.jwt()` | Full JWT claims as JSON | Custom claims, roles, tenant ID |
53
- | `auth.role()` | Current role string | Distinguish anon vs authenticated |
54
-
55
- ```sql
56
- -- Access custom JWT claims
57
- auth.jwt() ->> 'tenant_id'
58
- auth.jwt() -> 'app_metadata' ->> 'role'
59
- ```
60
-
61
- ## Common Patterns
62
-
63
- ### 1. Ownership
64
-
65
- ```sql
66
- ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
67
-
68
- CREATE POLICY "owner_all" ON documents
69
- FOR ALL USING (user_id = auth.uid())
70
- WITH CHECK (user_id = auth.uid());
71
- ```
72
-
73
- ### 2. Tenant Isolation
74
-
75
- ```sql
76
- -- Requires tenant_id in JWT app_metadata
77
- CREATE POLICY "tenant_isolation" ON orders
78
- FOR ALL
79
- USING (tenant_id = (auth.jwt() -> 'app_metadata' ->> 'tenant_id')::uuid)
80
- WITH CHECK (tenant_id = (auth.jwt() -> 'app_metadata' ->> 'tenant_id')::uuid);
81
- ```
82
-
83
- ### 3. Role-Based Access
84
-
85
- ```sql
86
- -- Admins see everything, users see own
87
- CREATE POLICY "admin_full_access" ON documents
88
- FOR ALL USING (
89
- auth.jwt() -> 'app_metadata' ->> 'role' = 'admin'
90
- );
91
-
92
- CREATE POLICY "user_own_access" ON documents
93
- FOR ALL USING (user_id = auth.uid())
94
- WITH CHECK (user_id = auth.uid());
95
- ```
96
-
97
- ### 4. Public Read, Authenticated Write
98
-
99
- ```sql
100
- CREATE POLICY "public_read" ON posts
101
- FOR SELECT USING (published = true);
102
-
103
- CREATE POLICY "auth_write" ON posts
104
- FOR INSERT WITH CHECK (auth.role() = 'authenticated');
105
- ```
106
-
107
- ### 5. Team/Organization Access
108
-
109
- ```sql
110
- CREATE POLICY "team_access" ON projects
111
- FOR SELECT USING (
112
- EXISTS (
113
- SELECT 1 FROM team_members
114
- WHERE team_members.team_id = projects.team_id
115
- AND team_members.user_id = auth.uid()
116
- )
117
- );
118
- ```
119
-
120
- ## Index Recommendations
121
-
122
- Always index columns used in RLS policies for performance:
123
-
124
- ```sql
125
- CREATE INDEX idx_documents_user_id ON documents (user_id);
126
- CREATE INDEX idx_orders_tenant_id ON orders (tenant_id);
127
- CREATE INDEX idx_team_members_lookup ON team_members (team_id, user_id);
128
- ```
129
-
130
- ## Testing RLS Policies
131
-
132
- ### Via SQL (Supabase SQL Editor)
133
-
134
- ```sql
135
- -- Test as a specific user
136
- SET request.jwt.claims = '{"sub": "user-uuid-here", "role": "authenticated",
137
- "app_metadata": {"tenant_id": "tenant-uuid", "role": "admin"}}';
138
- SET role = 'authenticated';
139
-
140
- SELECT * FROM documents; -- should only return rows matching policy
141
-
142
- RESET role;
143
- RESET request.jwt.claims;
144
- ```
145
-
146
- ### Via Client (different auth contexts)
147
-
148
- ```ts
149
- // Test with anon key (unauthenticated)
150
- const anonClient = createClient(url, anonKey);
151
- const { data } = await anonClient.from("documents").select("*");
152
- // Should return empty if no public policy
153
-
154
- // Test with authenticated user
155
- const { data: userData } = await authClient.from("documents").select("*");
156
- // Should return only user's rows
157
- ```
158
-
159
- ## Migration Pattern
160
-
161
- ```sql
162
- -- migration: 001_enable_rls.sql
163
- ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
164
- ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
165
- ALTER TABLE team_members ENABLE ROW LEVEL SECURITY;
166
-
167
- -- Always pair with policies
168
- CREATE POLICY "documents_owner" ON documents
169
- FOR ALL USING (user_id = auth.uid())
170
- WITH CHECK (user_id = auth.uid());
171
- ```
172
-
173
- ## Common Mistakes
174
-
175
- | Wrong | Right | Why |
176
- |-------|-------|-----|
177
- | Enable RLS without policies | Enable RLS + create policies | No policies = no access at all |
178
- | `FOR ALL USING (true)` | Specific conditions per operation | Grants unrestricted access, defeats RLS |
179
- | UPDATE with only USING | UPDATE with USING + WITH CHECK | User could change user_id to another user |
180
- | Complex subqueries in policies | Simple conditions + indexed columns | Subqueries in policies cause N+1 perf issues |
181
- | Using `anon` key as service_role | Separate keys, service_role only on backend | anon key respects RLS (correct), don't confuse |
182
- | RLS on some tables but not others | RLS on ALL tables with user data | Attackers target unprotected tables |
183
- | `auth.uid()` without null check | `auth.uid() IS NOT NULL AND user_id = auth.uid()` | Prevents anon access when policy is permissive |
184
- | Forgetting junction table RLS | RLS on junction tables too | team_members without RLS leaks membership |