feat: implement SupaBuilder - enterprise self-service Supabase project provisioning

• Database schema with RLS policies for admin/builder roles
• Edge function for creating Pico projects via Management API
• SSO authentication with Google OAuth support
• Auto-assignment of admin role to first user per organization
• Next.js UI with project creation, listing, and detail views
• Rate limiting (configurable), audit logging, and encrypted credentials
• Server actions for project management operations

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Chris CarusoandClaude Sonnet 4.5 committed 2026-01-31 14:42:37 -06:00
1 parent 18345e5c59
commit b78d05b89f
45 files changed
+11457

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+551
View File
@@ -0,0 +1,551 @@
# SupaBuilder
**Enterprise Self-Service Supabase Project Provisioning Platform**
SupaBuilder is a secure, scalable platform that enables enterprise teams to self-provision Supabase Pico (free tier) projects through a web interface. Built for organizations that need controlled project creation with proper governance, audit trails, and role-based access control.
## Features
- **Self-Service Project Creation**: Non-technical builders (PMs, designers, engineers) can create Supabase projects via a simple web form
- **Role-Based Access Control**: Admin and builder roles with appropriate permissions
- **Rate Limiting**: Built-in protection (5 projects/hour per user)
- **Audit Logging**: Immutable audit trail for all project operations
- **Security First**: Encrypted credentials, RLS policies, secure PAT storage
- **Enterprise Ready**: Organization-based isolation, soft delete, extensible architecture
## Architecture
```
User (Builder/Admin)
↓
Next.js App (SSR + Client Components)
↓
Server Actions → Edge Function (create-project)
↓
Management API → Creates Pico Project
↓
Store in Admin DB (projects table)
```
### Key Components
1. **Database Layer**: PostgreSQL with RLS policies, encryption functions, audit logs
2. **Edge Functions**: Deno-based serverless functions that interact with Management API
3. **Next.js Frontend**: Server and client components for UI
4. **Management API**: Official Supabase API for programmatic project creation
## Prerequisites
Before setting up SupaBuilder, ensure you have:
1. **Supabase Account** with access to:
- Management API (organization owner/admin)
- Personal Access Token (PAT) generation capability
2. **Development Tools**:
- Node.js 18+ and npm
- Supabase CLI (`npm install -g supabase`)
- Git
3. **Access Requirements**:
- Organization ID from your Supabase organization
- Ability to create a new Supabase project (for the admin dashboard)
## Setup Guide
### Step 1: Create Admin Supabase Project
1. Go to [Supabase Dashboard](https://supabase.com/dashboard)
2. Create a new project (this will host SupaBuilder itself)
3. Wait for provisioning to complete
4. Note your project URL and anon key from Settings > API
### Step 2: Generate Management API Token
1. Go to [Account Tokens](https://supabase.com/dashboard/account/tokens)
2. Click "Generate New Token"
3. Give it a descriptive name (e.g., "SupaBuilder Management API")
4. Select appropriate scopes (project creation, read)
5. **Save this token securely** - you'll need it for edge function secrets
### Step 3: Clone and Install
```bash
# Clone the repository
git clone https://github.com/supabase/examples.git
cd examples/supa-builder
# Install dependencies
npm install
# Copy environment file
cp .env.local.example .env.local
```
### Step 4: Configure Environment Variables
Edit `.env.local`:
```bash
# Admin Supabase Project (where SupaBuilder runs)
NEXT_PUBLIC_SUPABASE_URL=https://your-admin-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
# These will be set as edge function secrets (see Step 6)
MANAGEMENT_ACCESS_TOKEN=sbp_your_management_token
ENCRYPTION_KEY=$(openssl rand -base64 32) # Generate a secure key
```
### Step 5: Link to Supabase Project
```bash
# Login to Supabase CLI
supabase login
# Link to your admin project
supabase link --project-ref your-project-ref
```
### Step 6: Run Database Migrations
```bash
# Push migrations to your database
supabase db push
# This will create:
# - projects table
# - user_roles table
# - project_audit_logs table
# - rate_limits table
# - RLS policies
# - Helper functions
# - Auto-admin assignment trigger (first user becomes admin)
```
### Step 7: Set Edge Function Secrets
```bash
# Set all secrets from .env.local file
supabase secrets set --env-file .env.local
# Verify secrets were set correctly
supabase secrets list
```
Note: The CLI will automatically filter and only set non-`NEXT_PUBLIC_*` variables as secrets.
### Step 8: Deploy Edge Functions
```bash
# Deploy the create-project function
supabase functions deploy create-project
# Verify deployment
supabase functions list
```
### Step 9: Configure SSO Authentication
SupaBuilder uses SSO (Single Sign-On) for authentication. The first user to sign in will automatically be assigned the admin role.
#### Configure an SSO Provider
**For Production:**
1. Go to your Supabase Dashboard: Authentication > Providers
2. Enable your preferred provider (Google, Azure AD, Okta, etc.)
**Example: Google OAuth (Production)**
```
1. Navigate to: Authentication > Providers > Google
2. Enable Google provider
3. Add your Google OAuth credentials:
- Client ID: [from Google Cloud Console]
- Client Secret: [from Google Cloud Console]
4. Set authorized redirect URL:
https://[your-project-ref].supabase.co/auth/v1/callback
```
**For Local Development:**
If you want to test Google OAuth locally with `supabase start`:
1. Create OAuth credentials in [Google Cloud Console](https://console.cloud.google.com/apis/credentials)
2. Add authorized redirect URI: `http://127.0.0.1:54321/auth/v1/callback`
3. Add to `.env.local`:
```bash
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
```
4. The `supabase/config.toml` is already configured to use these variables
5. Start local Supabase: `supabase start`
6. Your Next.js app will use the local Supabase instance
Note: Local development will use `http://127.0.0.1:54321` for the Supabase URL instead of your production URL.
#### Organization ID Mapping
The system automatically extracts the organization ID from SSO claims. Configure your SSO provider to include one of these claims:
- `organization_id` (preferred)
- `org_id`
- Or set a default in the migration file
**For Google Workspace:**
- The `hd` (hosted domain) claim is automatically available
- You can map this to organization_id in your app
**For Azure AD / Okta:**
- Configure custom claims in your IdP to include `organization_id`
#### First User Setup
1. Deploy the application (Step 10)
2. Navigate to your app URL
3. Click "Sign in with [Provider]"
4. The first user will automatically receive admin role
5. Subsequent users will receive builder role by default
#### Promote Additional Admins
After signing in as an admin, you can promote other users via SQL:
```sql
SELECT public.promote_to_admin('user@example.com', 'your_org_id');
```
Or build an admin UI that calls this function via your Next.js app.
### Step 10: Deploy Next.js Application
#### Option A: Deploy to Vercel
```bash
# Install Vercel CLI
npm install -g vercel
# Deploy
vercel
# Set environment variables in Vercel dashboard
# NEXT_PUBLIC_SUPABASE_URL
# NEXT_PUBLIC_SUPABASE_ANON_KEY
```
#### Option B: Self-Host
```bash
# Build for production
npm run build
# Start production server
npm start
```
### Step 11: Test the Application
1. Navigate to your deployed URL
2. Sign up / Log in with your admin account
3. Go to `/projects` to see the dashboard
4. Click "Create Project" to test project creation
5. Verify the project appears in both:
- SupaBuilder dashboard
- Supabase Management Console
## Usage
### For Builders (Non-Admin Users)
1. **Create a Project**:
- Navigate to `/projects/new`
- Fill out the form:
- Project name (3-63 characters)
- Organization ID
- Region
- Optional: Purpose and description
- Click "Create Project"
- Wait for provisioning (1-2 minutes)
2. **View Your Projects**:
- Go to `/projects` to see all your projects
- Click on a project to view details and credentials
3. **Access Credentials**:
- Project detail page shows:
- Supabase URL
- Anon key
- Quick links to dashboard
### For Admins
Admins have all builder permissions plus:
1. **View All Organization Projects**: See projects created by all users in your org
2. **Pause Projects**: Temporarily disable a project
3. **Resume Projects**: Reactivate a paused project
4. **Delete Projects**: Soft delete (preserves audit trail)
5. **View Audit Logs**: See complete history of project operations
6. **Manage User Roles**: Assign admin/builder roles to users
### Rate Limits
- **5 projects per hour** per user
- Resets on a rolling 60-minute window
- Exceeded limit returns 429 error with clear message
## Security Checklist
Before going to production, verify:
- [ ] Management API PAT is stored only in edge function secrets (never in code)
- [ ] Encryption key is generated securely (32+ characters)
- [ ] Database RLS policies are enabled on all tables
- [ ] Admin users are properly assigned in `user_roles` table
- [ ] Edge function has `verify_jwt: true` in config
- [ ] `.env.local` is in `.gitignore` (never commit secrets)
- [ ] Service role keys are encrypted in database
- [ ] CORS headers are configured appropriately
- [ ] Rate limiting is enabled and configured
- [ ] Audit logging is working for all operations
## Database Schema
### Core Tables
#### `projects`
Stores all child Supabase projects with encrypted credentials.
```sql
- id (uuid, PK)
- project_ref (text, unique) - Supabase project reference
- project_name (text)
- organization_id (text)
- anon_key (text)
- service_role_key_encrypted (text) - Encrypted with pgcrypto
- region (text)
- status (enum: provisioning, active, paused, failed, deleted)
- creator_id (uuid) - References auth.users
- creator_email (text)
- created_at, updated_at, deleted_at
```
#### `user_roles`
Manages admin vs builder role assignments.
```sql
- id (uuid, PK)
- user_id (uuid) - References auth.users
- organization_id (text)
- role (enum: admin, builder)
- assigned_by (uuid)
- assigned_at (timestamptz)
```
#### `project_audit_logs`
Immutable audit trail (no update/delete allowed).
```sql
- id (uuid, PK)
- project_id (uuid) - References projects
- action (enum: create, pause, resume, delete, update)
- actor_id (uuid)
- actor_email (text)
- organization_id (text)
- metadata (jsonb)
- created_at (timestamptz)
```
#### `rate_limits`
Simple DB-based rate limiting.
```sql
- id (uuid, PK)
- user_id (uuid)
- organization_id (text)
- action (text)
- created_at (timestamptz)
```
## API Reference
### Edge Function: `create-project`
**Endpoint**: `POST /functions/v1/create-project`
**Headers**:
```
Authorization: Bearer <user-jwt-token>
Content-Type: application/json
```
**Request Body**:
```json
{
"project_name": "my-project",
"organization_id": "org_abc123",
"region": "us-east-1",
"purpose": "Development",
"description": "Optional description"
}
```
**Success Response** (201):
```json
{
"success": true,
"project_id": "uuid",
"project_ref": "abcdefgh",
"anon_key": "eyJhbGc...",
"message": "Project created successfully"
}
```
**Error Response** (400/429/500):
```json
{
"success": false,
"error": "Error message here"
}
```
### Server Actions
All located in `app/actions/projects.ts`:
- `createProject(input)` - Create new project
- `getProjects()` - Get all user's projects (respects RLS)
- `getProject(id)` - Get single project details
- `pauseProject(id)` - Admin only: pause project
- `resumeProject(id)` - Admin only: resume project
- `deleteProject(id)` - Admin only: soft delete
- `getUserRole(orgId)` - Get user's role in organization
## Troubleshooting
### Edge Function Returns 401 Unauthorized
**Cause**: JWT verification failed or missing auth header
**Solution**:
- Verify user is logged in
- Check `Authorization` header is being sent
- Ensure edge function has `verify_jwt: true`
### Edge Function Returns 500 - Management API Error
**Cause**: Invalid PAT or insufficient permissions
**Solution**:
```bash
# Check secrets are set
supabase secrets list
# Verify PAT has correct scopes
# Regenerate if needed from dashboard
```
### Projects Not Showing in Dashboard
**Cause**: RLS policies blocking access
**Solution**:
```sql
-- Check user role
SELECT * FROM public.user_roles WHERE user_id = 'YOUR_UUID';
-- Verify RLS is enabled
SELECT tablename, rowsecurity FROM pg_tables WHERE schemaname = 'public';
-- Test RLS policy
SELECT * FROM public.projects; -- Run as authenticated user
```
### Rate Limit Not Working
**Cause**: Rate limit function not being called
**Solution**:
- Check edge function calls `check_rate_limit` before creating project
- Verify `rate_limits` table has entries
- Check time window calculation (60 minutes rolling)
### Encryption/Decryption Errors
**Cause**: Missing or incorrect encryption key
**Solution**:
```bash
# Generate new key
openssl rand -base64 32
# Set as secret
supabase secrets set ENCRYPTION_KEY=your_new_key
# Redeploy edge function
supabase functions deploy create-project
```
## Extension Points for v2
SupaBuilder is designed to be extended. Future enhancements could include:
### 1. PII Scanning Hook
Add a hook in edge function to scan project names/descriptions for PII before creation.
### 2. RLS Policy Enforcement
Automatically apply RLS policies to child projects based on templates.
### 3. Compliance Scanning
Create `compliance_scans` table to track and enforce security requirements.
### 4. Webhook Notifications
Integrate with ServiceNow or other ITSM tools via webhooks.
### 5. Project Templates
Pre-configured database schemas and auth settings for common use cases.
### 6. Usage Tracking
Monitor API usage, storage, and database size for child projects.
### 7. Backup Configuration
Automatically configure PITR and backups for child projects.
### 8. Bulk Operations
Admin interface for bulk project operations (pause all, delete old projects, etc.).
## Contributing
This is an example project demonstrating Supabase Management API integration. Contributions are welcome!
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test thoroughly
5. Submit a pull request
## License
MIT License - see LICENSE file for details
## Support
For issues specific to SupaBuilder:
- Open an issue on GitHub
- Check existing issues and discussions
For Supabase platform issues:
- [Supabase Documentation](https://supabase.com/docs)
- [Supabase Discord](https://discord.supabase.com)
- [Supabase Support](https://supabase.com/support)
## Additional Resources
- [Supabase Management API Docs](https://supabase.com/docs/reference/api)
- [Supabase Edge Functions](https://supabase.com/docs/guides/functions)
- [Row Level Security Guide](https://supabase.com/docs/guides/auth/row-level-security)
- [Next.js Documentation](https://nextjs.org/docs)
---
Built with ❤️ using [Supabase](https://supabase.com)
+34
View File
@@ -0,0 +1,34 @@
# SupaBuilder TODO
## Pending Items
- [ ] Update README for better setup
- Simplify installation steps
- Add troubleshooting section
- Include screenshots/GIFs
- Document organization slug setup more clearly
- [ ] Squash migrations
- Combine all 6 migration files into a single initial migration
- Test against fresh database
- Update migration numbering
- [ ] Update UI
- Improve overall design and polish
- Better loading states
- Enhanced error messages
- Consistent styling across all pages
- [ ] Show waiting page until form is successfully submitted and project is created
- Display progress indicator during project creation
- Show estimated time (1-2 minutes)
- Poll for project status updates
- Handle timeout scenarios
- Redirect to project detail page on success
- [ ] Return project ref and anon key
- Display project credentials immediately after creation
- Add copy-to-clipboard functionality
- Show project URL
- Provide quick-start code snippets
@@ -0,0 +1,414 @@
'use server'
/**
* SupaBuilder Server Actions
*
* Server-side actions for project management that bridge Next.js and
* Supabase edge functions.
*/
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
// ============================================================================
// TYPES
// ============================================================================
export interface CreateProjectInput {
project_name: string
organization_id: string
region: string
purpose?: string
description?: string
}
export interface Project {
id: string
project_ref: string
project_name: string
organization_id: string
anon_key: string
region: string
status: 'provisioning' | 'active' | 'paused' | 'failed' | 'deleted'
purpose?: string
description?: string
creator_id: string
creator_email: string
created_at: string
updated_at: string
}
export interface ActionResult<T = unknown> {
success: boolean
data?: T
error?: string
}
// ============================================================================
// CREATE PROJECT
// ============================================================================
export async function createProject(
input: CreateProjectInput
): Promise<ActionResult<{ project_id: string; project_ref: string; anon_key: string }>> {
try {
const supabase = await createClient()
// Get current session
const {
data: { session },
error: sessionError,
} = await supabase.auth.getSession()
if (sessionError || !session) {
return {
success: false,
error: 'You must be logged in to create a project',
}
}
// Call edge function to create project
const functionUrl = process.env.NEXT_PUBLIC_SUPABASE_URL + '/functions/v1/create-project'
const response = await fetch(functionUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${session.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(input),
})
const result = await response.json()
if (!response.ok || !result.success) {
return {
success: false,
error: result.error || 'Failed to create project',
}
}
// Revalidate projects page
revalidatePath('/projects')
return {
success: true,
data: {
project_id: result.project_id,
project_ref: result.project_ref,
anon_key: result.anon_key,
},
}
} catch (error) {
console.error('Error creating project:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
// ============================================================================
// GET PROJECTS
// ============================================================================
export async function getProjects(): Promise<ActionResult<Project[]>> {
try {
const supabase = await createClient()
// Check authentication
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return {
success: false,
error: 'You must be logged in to view projects',
}
}
// Fetch projects (RLS policies will filter based on user role)
const { data: projects, error } = await supabase
.from('projects')
.select('*')
.is('deleted_at', null)
.order('created_at', { ascending: false })
if (error) {
return {
success: false,
error: error.message,
}
}
return {
success: true,
data: projects as Project[],
}
} catch (error) {
console.error('Error fetching projects:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
// ============================================================================
// GET SINGLE PROJECT
// ============================================================================
export async function getProject(projectId: string): Promise<ActionResult<Project>> {
try {
const supabase = await createClient()
// Check authentication
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return {
success: false,
error: 'You must be logged in to view this project',
}
}
// Fetch project (RLS will enforce access control)
const { data: project, error } = await supabase
.from('projects')
.select('*')
.eq('id', projectId)
.is('deleted_at', null)
.single()
if (error) {
return {
success: false,
error: error.message,
}
}
if (!project) {
return {
success: false,
error: 'Project not found',
}
}
return {
success: true,
data: project as Project,
}
} catch (error) {
console.error('Error fetching project:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
// ============================================================================
// PAUSE PROJECT (Admin only)
// ============================================================================
export async function pauseProject(projectId: string): Promise<ActionResult> {
try {
const supabase = await createClient()
// Get current user
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return {
success: false,
error: 'You must be logged in to pause projects',
}
}
// Update project status using helper function
const { error } = await supabase.rpc('update_project_status', {
p_project_id: projectId,
p_new_status: 'paused',
p_actor_id: user.id,
p_actor_email: user.email!,
})
if (error) {
return {
success: false,
error: error.message,
}
}
// Revalidate projects pages
revalidatePath('/projects')
revalidatePath(`/projects/${projectId}`)
return {
success: true,
}
} catch (error) {
console.error('Error pausing project:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
// ============================================================================
// RESUME PROJECT (Admin only)
// ============================================================================
export async function resumeProject(projectId: string): Promise<ActionResult> {
try {
const supabase = await createClient()
// Get current user
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return {
success: false,
error: 'You must be logged in to resume projects',
}
}
// Update project status using helper function
const { error } = await supabase.rpc('update_project_status', {
p_project_id: projectId,
p_new_status: 'active',
p_actor_id: user.id,
p_actor_email: user.email!,
})
if (error) {
return {
success: false,
error: error.message,
}
}
// Revalidate projects pages
revalidatePath('/projects')
revalidatePath(`/projects/${projectId}`)
return {
success: true,
}
} catch (error) {
console.error('Error resuming project:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
// ============================================================================
// DELETE PROJECT (Admin only, soft delete)
// ============================================================================
export async function deleteProject(projectId: string): Promise<ActionResult> {
try {
const supabase = await createClient()
// Get current user
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return {
success: false,
error: 'You must be logged in to delete projects',
}
}
// Soft delete using helper function
const { error } = await supabase.rpc('soft_delete_project', {
p_project_id: projectId,
p_actor_id: user.id,
p_actor_email: user.email!,
})
if (error) {
return {
success: false,
error: error.message,
}
}
// Revalidate projects page
revalidatePath('/projects')
return {
success: true,
}
} catch (error) {
console.error('Error deleting project:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
// ============================================================================
// GET USER ROLE
// ============================================================================
export async function getUserRole(organizationId: string): Promise<ActionResult<string>> {
try {
const supabase = await createClient()
// Get current user
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
return {
success: false,
error: 'You must be logged in',
}
}
// Get user role
const { data: role, error } = await supabase.rpc('get_user_role', {
p_user_id: user.id,
p_organization_id: organizationId,
})
if (error) {
return {
success: false,
error: error.message,
}
}
return {
success: true,
data: role || 'builder',
}
} catch (error) {
console.error('Error getting user role:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
}
}
}
@@ -0,0 +1,31 @@
/**
* Auth Callback Route
*
* Handles the OAuth callback after successful authentication.
* Exchanges the code for a session and redirects to the projects page.
*/
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
export async function GET(request: Request) {
const requestUrl = new URL(request.url)
const code = requestUrl.searchParams.get('code')
const origin = requestUrl.origin
if (code) {
const supabase = await createClient()
// Exchange the code for a session
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (error) {
console.error('Auth callback error:', error)
// Redirect to login with error
return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(error.message)}`)
}
}
// URL to redirect to after sign in process completes
return NextResponse.redirect(`${origin}/projects`)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+26
View File
@@ -0,0 +1,26 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
+34
View File
@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}
+68
View File
@@ -0,0 +1,68 @@
/**
* Login Page
*
* Handles SSO authentication via Supabase Auth.
* Supports Google OAuth and other configured providers.
*/
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import LoginButton from '@/components/LoginButton'
export default async function LoginPage() {
const supabase = await createClient()
// Check if user is already authenticated
const {
data: { user },
} = await supabase.auth.getUser()
// If already logged in, redirect to projects
if (user) {
redirect('/projects')
}
return (
<div className="flex min-h-screen flex-col items-center justify-center p-8 bg-gradient-to-b from-gray-50 to-white">
<div className="w-full max-w-md space-y-8">
{/* Header */}
<div className="text-center">
<h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-2">
SupaBuilder
</h1>
<p className="text-gray-600">
Sign in to manage your Supabase projects
</p>
</div>
{/* Login Card */}
<div className="bg-white border border-gray-200 rounded-lg shadow-lg p-8">
<h2 className="text-2xl font-semibold mb-6 text-center">
Sign In
</h2>
{/* SSO Login Buttons */}
<div className="space-y-4">
<LoginButton provider="google" />
{/* Add more providers as needed */}
{/* <LoginButton provider="azure" /> */}
{/* <LoginButton provider="github" /> */}
</div>
{/* Info Text */}
<div className="mt-6 text-center text-sm text-gray-500">
<p>Sign in with your organization account</p>
</div>
</div>
{/* Footer Info */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<p className="text-sm text-blue-800 text-center">
<strong>First-time users:</strong> The first person to sign in from your organization will automatically receive admin privileges.
</p>
</div>
</div>
</div>
)
}
+111
View File
@@ -0,0 +1,111 @@
import { redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
export default async function Home() {
const supabase = await createClient()
// Check if user is authenticated
const {
data: { user },
} = await supabase.auth.getUser()
// If logged in, redirect to projects dashboard
if (user) {
redirect('/projects')
}
// Show landing page for non-authenticated users
return (
<div className="flex min-h-screen flex-col items-center justify-center p-8 bg-gradient-to-b from-gray-50 to-white">
<main className="flex flex-col items-center gap-8 max-w-4xl text-center">
{/* Hero Section */}
<div className="space-y-4">
<h1 className="text-5xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
SupaBuilder
</h1>
<p className="text-2xl text-gray-600">
Enterprise Self-Service Supabase Project Provisioning
</p>
<p className="text-lg text-gray-500 max-w-2xl">
Empower your team to create and manage Supabase projects with proper governance,
audit trails, and role-based access control.
</p>
</div>
{/* CTA Button */}
<div className="flex gap-4 mt-8">
<Link
href="/login"
className="px-8 py-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold text-lg shadow-lg hover:shadow-xl transition-all"
>
Sign In to Get Started
</Link>
</div>
{/* Features Grid */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 w-full mt-12">
<div className="p-6 border border-gray-200 rounded-lg bg-white">
<div className="text-3xl mb-3">🚀</div>
<h3 className="font-semibold text-lg mb-2">Self-Service</h3>
<p className="text-sm text-gray-600">
Builders can create projects instantly without waiting for IT approval
</p>
</div>
<div className="p-6 border border-gray-200 rounded-lg bg-white">
<div className="text-3xl mb-3">🔒</div>
<h3 className="font-semibold text-lg mb-2">Secure by Default</h3>
<p className="text-sm text-gray-600">
Role-based access, encrypted credentials, and complete audit trails
</p>
</div>
<div className="p-6 border border-gray-200 rounded-lg bg-white">
<div className="text-3xl mb-3">⚡</div>
<h3 className="font-semibold text-lg mb-2">Rate Limited</h3>
<p className="text-sm text-gray-600">
Built-in protections prevent abuse with 5 projects per hour limit
</p>
</div>
</div>
{/* Key Features */}
<div className="w-full max-w-2xl mt-8 p-8 border border-gray-200 rounded-lg bg-white text-left">
<h2 className="text-2xl font-semibold mb-4 text-center">Key Features</h2>
<ul className="space-y-3">
<li className="flex items-start gap-3">
<span className="text-green-600 font-bold mt-1">✓</span>
<span className="text-gray-700">
<strong>SSO Authentication:</strong> Seamless sign-in with Google, Azure AD, or any OAuth provider
</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-600 font-bold mt-1">✓</span>
<span className="text-gray-700">
<strong>Role-Based Access:</strong> Admins manage all projects, builders manage their own
</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-600 font-bold mt-1">✓</span>
<span className="text-gray-700">
<strong>Automatic Provisioning:</strong> Projects created in 1-2 minutes via Management API
</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-600 font-bold mt-1">✓</span>
<span className="text-gray-700">
<strong>Audit Logging:</strong> Complete immutable history of all project operations
</span>
</li>
</ul>
</div>
{/* Footer */}
<div className="mt-12 text-sm text-gray-500">
<p>Built with Supabase • Next.js • TypeScript</p>
</div>
</main>
</div>
)
}
@@ -0,0 +1,224 @@
/**
* Project Detail Page
*
* Server component that displays detailed information about a single project.
*/
import Link from 'next/link'
import { redirect, notFound } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { getProject } from '@/app/actions/projects'
interface ProjectDetailPageProps {
params: Promise<{
id: string
}>
}
export default async function ProjectDetailPage({ params }: ProjectDetailPageProps) {
const { id } = await params
const supabase = await createClient()
// Check authentication
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
redirect('/login')
}
// Fetch project
const result = await getProject(id)
if (!result.success) {
notFound()
}
const project = result.data!
// Check if user is admin
const { data: role } = await supabase.rpc('get_user_role', {
p_user_id: user.id,
p_organization_id: project.organization_id,
})
const isAdmin = role === 'admin'
// Get audit logs (if admin or creator)
const { data: auditLogs } = await supabase
.from('project_audit_logs')
.select('*')
.eq('project_id', project.id)
.order('created_at', { ascending: false })
.limit(10)
const getStatusBadge = (status: typeof project.status) => {
const styles = {
provisioning: 'bg-yellow-100 text-yellow-800 border-yellow-200',
active: 'bg-green-100 text-green-800 border-green-200',
paused: 'bg-gray-100 text-gray-800 border-gray-200',
failed: 'bg-red-100 text-red-800 border-red-200',
deleted: 'bg-red-100 text-red-800 border-red-200',
}
return (
<span
className={`px-3 py-1 rounded-full text-sm font-medium border ${
styles[status] || styles.active
}`}
>
{status.charAt(0).toUpperCase() + status.slice(1)}
</span>
)
}
return (
<div className="container mx-auto px-4 py-8 max-w-6xl">
{/* Header */}
<div className="mb-8">
<Link
href="/projects"
className="text-blue-600 hover:text-blue-800 text-sm mb-4 inline-block"
>
← Back to Projects
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold mb-2">{project.project_name}</h1>
<p className="text-gray-600">Project Reference: {project.project_ref}</p>
</div>
{getStatusBadge(project.status)}
</div>
</div>
{/* Project Details Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
{/* Basic Information */}
<div className="bg-white border border-gray-200 rounded-lg p-6">
<h2 className="text-lg font-semibold mb-4">Basic Information</h2>
<dl className="space-y-3">
<div>
<dt className="text-sm font-medium text-gray-500">Organization ID</dt>
<dd className="text-sm text-gray-900">{project.organization_id}</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">Region</dt>
<dd className="text-sm text-gray-900">{project.region}</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">Created By</dt>
<dd className="text-sm text-gray-900">{project.creator_email}</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">Created At</dt>
<dd className="text-sm text-gray-900">
{new Date(project.created_at).toLocaleString()}
</dd>
</div>
{project.purpose && (
<div>
<dt className="text-sm font-medium text-gray-500">Purpose</dt>
<dd className="text-sm text-gray-900">{project.purpose}</dd>
</div>
)}
</dl>
</div>
{/* Credentials */}
<div className="bg-white border border-gray-200 rounded-lg p-6">
<h2 className="text-lg font-semibold mb-4">API Credentials</h2>
<div className="space-y-4">
<div>
<label className="text-sm font-medium text-gray-500 block mb-1">
Supabase URL
</label>
<code className="block text-xs bg-gray-100 px-3 py-2 rounded border border-gray-200 break-all">
https://{project.project_ref}.supabase.co
</code>
</div>
<div>
<label className="text-sm font-medium text-gray-500 block mb-1">
Anon Key
</label>
<code className="block text-xs bg-gray-100 px-3 py-2 rounded border border-gray-200 break-all">
{project.anon_key}
</code>
</div>
{isAdmin && (
<div className="bg-yellow-50 border border-yellow-200 rounded p-3 mt-4">
<p className="text-xs text-yellow-800">
<strong>Admin Note:</strong> Service role key is encrypted in the database.
Contact system administrator for access.
</p>
</div>
)}
</div>
</div>
</div>
{/* Description */}
{project.description && (
<div className="bg-white border border-gray-200 rounded-lg p-6 mb-8">
<h2 className="text-lg font-semibold mb-4">Description</h2>
<p className="text-sm text-gray-700 whitespace-pre-wrap">{project.description}</p>
</div>
)}
{/* Quick Links */}
<div className="bg-white border border-gray-200 rounded-lg p-6 mb-8">
<h2 className="text-lg font-semibold mb-4">Quick Links</h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<a
href={`https://supabase.com/dashboard/project/${project.project_ref}`}
target="_blank"
rel="noopener noreferrer"
className="text-center px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50"
>
<span className="text-sm font-medium text-blue-600">Dashboard →</span>
</a>
<a
href={`https://supabase.com/dashboard/project/${project.project_ref}/editor`}
target="_blank"
rel="noopener noreferrer"
className="text-center px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50"
>
<span className="text-sm font-medium text-blue-600">Table Editor →</span>
</a>
<a
href={`https://supabase.com/dashboard/project/${project.project_ref}/auth/users`}
target="_blank"
rel="noopener noreferrer"
className="text-center px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50"
>
<span className="text-sm font-medium text-blue-600">Auth Users →</span>
</a>
</div>
</div>
{/* Audit Logs */}
{auditLogs && auditLogs.length > 0 && (
<div className="bg-white border border-gray-200 rounded-lg p-6">
<h2 className="text-lg font-semibold mb-4">Recent Activity</h2>
<div className="space-y-3">
{auditLogs.map((log) => (
<div key={log.id} className="flex items-start gap-3 text-sm border-b border-gray-100 pb-3 last:border-0">
<span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs font-medium">
{log.action}
</span>
<div className="flex-1">
<p className="text-gray-900">
{log.actor_email}
</p>
<p className="text-xs text-gray-500">
{new Date(log.created_at).toLocaleString()}
</p>
</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,80 @@
/**
* Create New Project Page
*
* Server component that displays the project creation form.
*/
import { redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import ProjectForm from '@/components/ProjectForm'
export default async function NewProjectPage() {
const supabase = await createClient()
// Check authentication
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
redirect('/login')
}
// Get user's organization from user_roles
const { data: userRole } = await supabase
.from('user_roles')
.select('organization_id, role')
.eq('user_id', user.id)
.single()
if (!userRole) {
return (
<div className="container mx-auto px-4 py-8">
<div className="bg-red-50 border border-red-200 text-red-800 rounded-lg p-4">
<p className="font-medium">No organization assigned</p>
<p className="text-sm">Please contact an administrator to assign you to an organization.</p>
</div>
</div>
)
}
// Get admin project region from env or default
const adminProjectRegion = process.env.ADMIN_PROJECT_REGION || 'us-east-1'
return (
<div className="container mx-auto px-4 py-8 max-w-4xl">
{/* Header */}
<div className="mb-8">
<Link
href="/projects"
className="text-blue-600 hover:text-blue-800 text-sm mb-4 inline-block"
>
← Back to Projects
</Link>
<h1 className="text-3xl font-bold mb-2">Create New Project</h1>
<p className="text-gray-600">
Create a new Supabase Pico project for your organization
</p>
</div>
{/* Info Box */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
<h3 className="font-medium text-blue-900 mb-2">What you need to know</h3>
<ul className="text-sm text-blue-800 space-y-1">
<li>• Projects are created on the Pico (free) tier</li>
<li>• Project provisioning typically completes in 1-2 minutes</li>
<li>• All projects include PostgreSQL database, Auth, Storage, and Realtime</li>
<li>• Projects will be created in the {adminProjectRegion} region</li>
</ul>
</div>
{/* Form */}
<ProjectForm
defaultOrganizationId={userRole.organization_id}
defaultRegion={adminProjectRegion}
/>
</div>
)
}
@@ -0,0 +1,93 @@
/**
* Projects List Page
*
* Server component that displays all projects for the authenticated user.
* Shows different views based on user role (admin vs builder).
*/
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { getProjects } from '@/app/actions/projects'
import ProjectTable from '@/components/ProjectTable'
export default async function ProjectsPage() {
const supabase = await createClient()
// Check authentication
const {
data: { user },
error: authError,
} = await supabase.auth.getUser()
if (authError || !user) {
redirect('/login')
}
// Fetch projects (respects RLS)
const result = await getProjects()
if (!result.success) {
return (
<div className="container mx-auto px-4 py-8">
<div className="bg-red-50 border border-red-200 text-red-800 rounded-lg p-4">
<p className="font-medium">Error loading projects</p>
<p className="text-sm">{result.error}</p>
</div>
</div>
)
}
const projects = result.data || []
// Check if user is admin (simple check - look at first project's org)
// In production, you might want to fetch this separately
let isAdmin = false
if (projects.length > 0) {
const { data: role } = await supabase.rpc('get_user_role', {
p_user_id: user.id,
p_organization_id: projects[0].organization_id,
})
isAdmin = role === 'admin'
}
return (
<div className="container mx-auto px-4 py-8 max-w-7xl">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold mb-2">Projects</h1>
<p className="text-gray-600">
Manage your Supabase projects
{isAdmin && <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded">Admin</span>}
</p>
</div>
<Link
href="/projects/new"
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium"
>
Create Project
</Link>
</div>
{/* User Info */}
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4 mb-6">
<p className="text-sm text-gray-700">
Logged in as: <strong>{user.email}</strong>
</p>
</div>
{/* Projects Table */}
<ProjectTable projects={projects} isAdmin={isAdmin} />
{/* Footer Info */}
<div className="mt-8 bg-blue-50 border border-blue-200 rounded-lg p-4">
<h3 className="font-medium text-blue-900 mb-2">About SupaBuilder</h3>
<p className="text-sm text-blue-800">
SupaBuilder is an enterprise self-service platform for provisioning Supabase Pico projects.
All projects are automatically created with the free (Pico) tier and can be managed through this interface.
</p>
</div>
</div>
)
}
@@ -0,0 +1,91 @@
'use client'
/**
* LoginButton Component
*
* Client component that handles OAuth login flow for various providers.
*/
import { createClient } from '@/lib/supabase/client'
import { useState } from 'react'
type Provider = 'google' | 'azure' | 'github' | 'gitlab'
interface LoginButtonProps {
provider: Provider
}
const providerConfig = {
google: {
name: 'Google',
icon: '🔐',
color: 'bg-white hover:bg-gray-50 text-gray-900 border border-gray-300',
},
azure: {
name: 'Azure AD',
icon: '🔷',
color: 'bg-blue-600 hover:bg-blue-700 text-white',
},
github: {
name: 'GitHub',
icon: '⚫',
color: 'bg-gray-800 hover:bg-gray-900 text-white',
},
gitlab: {
name: 'GitLab',
icon: '🦊',
color: 'bg-orange-600 hover:bg-orange-700 text-white',
},
}
export default function LoginButton({ provider }: LoginButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const config = providerConfig[provider]
const handleLogin = async () => {
setIsLoading(true)
setError(null)
try {
const supabase = createClient()
const { error } = await supabase.auth.signInWithOAuth({
provider: provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
})
if (error) {
throw error
}
// OAuth flow initiated, user will be redirected
} catch (err) {
console.error('Login error:', err)
setError(err instanceof Error ? err.message : 'Failed to sign in')
setIsLoading(false)
}
}
return (
<div>
<button
onClick={handleLogin}
disabled={isLoading}
className={`w-full px-6 py-3 rounded-lg font-medium transition-all shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-3 ${config.color}`}
>
<span className="text-xl">{config.icon}</span>
{isLoading ? `Signing in...` : `Continue with ${config.name}`}
</button>
{error && (
<p className="mt-2 text-sm text-red-600">
{error}
</p>
)}
</div>
)
}
@@ -0,0 +1,192 @@
'use client'
/**
* ProjectForm Component
*
* Client component for creating new Supabase projects.
* Handles form validation, submission, and loading states.
*/
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { createProject, type CreateProjectInput } from '@/app/actions/projects'
const REGIONS = [
{ value: 'us-east-1', label: 'US East (N. Virginia)' },
{ value: 'us-west-1', label: 'US West (N. California)' },
{ value: 'us-west-2', label: 'US West (Oregon)' },
{ value: 'eu-west-1', label: 'EU West (Ireland)' },
{ value: 'eu-west-2', label: 'EU West (London)' },
{ value: 'eu-central-1', label: 'EU Central (Frankfurt)' },
{ value: 'ap-southeast-1', label: 'Asia Pacific (Singapore)' },
{ value: 'ap-southeast-2', label: 'Asia Pacific (Sydney)' },
{ value: 'ap-northeast-1', label: 'Asia Pacific (Tokyo)' },
{ value: 'sa-east-1', label: 'South America (São Paulo)' },
]
interface ProjectFormProps {
defaultOrganizationId?: string
defaultRegion?: string
}
export default function ProjectForm({ defaultOrganizationId, defaultRegion }: ProjectFormProps) {
const router = useRouter()
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const [formData, setFormData] = useState<CreateProjectInput>({
project_name: '',
organization_id: defaultOrganizationId || '',
region: defaultRegion || 'us-east-1',
purpose: '',
description: '',
})
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError(null)
setIsSubmitting(true)
try {
// Client-side validation
if (formData.project_name.length < 3) {
setError('Project name must be at least 3 characters')
setIsSubmitting(false)
return
}
if (!formData.organization_id) {
setError('Organization ID is required')
setIsSubmitting(false)
return
}
// Call server action
const result = await createProject(formData)
if (!result.success) {
setError(result.error || 'Failed to create project')
setIsSubmitting(false)
return
}
// Success - redirect to projects list
router.push('/projects')
} catch (err) {
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
setIsSubmitting(false)
}
}
const handleInputChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
) => {
const { name, value } = e.target
setFormData((prev) => ({ ...prev, [name]: value }))
}
return (
<form onSubmit={handleSubmit} className="space-y-6 max-w-2xl">
{/* Error Display */}
{error && (
<div className="bg-red-50 border border-red-200 text-red-800 rounded-lg p-4">
<p className="font-medium">Error</p>
<p className="text-sm">{error}</p>
</div>
)}
{/* Project Name */}
<div>
<label htmlFor="project_name" className="block text-sm font-medium mb-2">
Project Name *
</label>
<input
type="text"
id="project_name"
name="project_name"
value={formData.project_name}
onChange={handleInputChange}
required
minLength={3}
maxLength={63}
placeholder="my-awesome-project"
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
disabled={isSubmitting}
/>
<p className="text-xs text-gray-500 mt-1">
3-63 characters, lowercase letters, numbers, and hyphens
</p>
</div>
{/* Hidden fields - automatically set */}
<input type="hidden" name="organization_id" value={formData.organization_id} />
<input type="hidden" name="region" value={formData.region} />
{/* Purpose */}
<div>
<label htmlFor="purpose" className="block text-sm font-medium mb-2">
Purpose
</label>
<input
type="text"
id="purpose"
name="purpose"
value={formData.purpose}
onChange={handleInputChange}
placeholder="Development, Staging, Production, etc."
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
disabled={isSubmitting}
/>
<p className="text-xs text-gray-500 mt-1">
Optional: What will this project be used for?
</p>
</div>
{/* Description */}
<div>
<label htmlFor="description" className="block text-sm font-medium mb-2">
Description
</label>
<textarea
id="description"
name="description"
value={formData.description}
onChange={handleInputChange}
rows={4}
placeholder="Describe your project..."
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
disabled={isSubmitting}
/>
<p className="text-xs text-gray-500 mt-1">
Optional: Additional details about this project
</p>
</div>
{/* Submit Button */}
<div className="flex gap-4">
<button
type="submit"
disabled={isSubmitting}
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium"
>
{isSubmitting ? 'Creating Project...' : 'Create Project'}
</button>
<button
type="button"
onClick={() => router.back()}
disabled={isSubmitting}
className="px-6 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 disabled:bg-gray-100 disabled:cursor-not-allowed font-medium"
>
Cancel
</button>
</div>
{/* Info */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<p className="text-sm text-blue-800">
Projects are provisioned as Pico (free) tier.
</p>
</div>
</form>
)
}
@@ -0,0 +1,240 @@
'use client'
/**
* ProjectTable Component
*
* Displays a table of projects with admin actions (pause, resume, delete).
* Includes loading states and error handling.
*/
import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import {
pauseProject,
resumeProject,
deleteProject,
type Project,
} from '@/app/actions/projects'
interface ProjectTableProps {
projects: Project[]
isAdmin: boolean
}
export default function ProjectTable({ projects, isAdmin }: ProjectTableProps) {
const router = useRouter()
const [loadingAction, setLoadingAction] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const handlePause = async (projectId: string) => {
if (!confirm('Are you sure you want to pause this project?')) {
return
}
setLoadingAction(projectId)
setError(null)
const result = await pauseProject(projectId)
if (!result.success) {
setError(result.error || 'Failed to pause project')
} else {
router.refresh()
}
setLoadingAction(null)
}
const handleResume = async (projectId: string) => {
setLoadingAction(projectId)
setError(null)
const result = await resumeProject(projectId)
if (!result.success) {
setError(result.error || 'Failed to resume project')
} else {
router.refresh()
}
setLoadingAction(null)
}
const handleDelete = async (projectId: string) => {
if (!confirm('Are you sure you want to delete this project? This action cannot be undone.')) {
return
}
setLoadingAction(projectId)
setError(null)
const result = await deleteProject(projectId)
if (!result.success) {
setError(result.error || 'Failed to delete project')
} else {
router.refresh()
}
setLoadingAction(null)
}
const getStatusBadge = (status: Project['status']) => {
const styles = {
provisioning: 'bg-yellow-100 text-yellow-800 border-yellow-200',
active: 'bg-green-100 text-green-800 border-green-200',
paused: 'bg-gray-100 text-gray-800 border-gray-200',
failed: 'bg-red-100 text-red-800 border-red-200',
deleted: 'bg-red-100 text-red-800 border-red-200',
}
return (
<span
className={`px-2 py-1 rounded-full text-xs font-medium border ${
styles[status] || styles.active
}`}
>
{status.charAt(0).toUpperCase() + status.slice(1)}
</span>
)
}
if (projects.length === 0) {
return (
<div className="text-center py-12 bg-gray-50 rounded-lg border border-gray-200">
<p className="text-gray-500 mb-4">No projects found</p>
<Link
href="/projects/new"
className="inline-block px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium"
>
Create Your First Project
</Link>
</div>
)
}
return (
<div className="space-y-4">
{/* Error Display */}
{error && (
<div className="bg-red-50 border border-red-200 text-red-800 rounded-lg p-4">
<p className="font-medium">Error</p>
<p className="text-sm">{error}</p>
</div>
)}
{/* Table */}
<div className="overflow-x-auto border border-gray-200 rounded-lg">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Project Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Reference
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Region
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Creator
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Created
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{projects.map((project) => (
<tr key={project.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap">
<Link
href={`/projects/${project.id}`}
className="text-blue-600 hover:text-blue-800 font-medium"
>
{project.project_name}
</Link>
{project.purpose && (
<p className="text-xs text-gray-500 mt-1">{project.purpose}</p>
)}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<code className="text-xs bg-gray-100 px-2 py-1 rounded">
{project.project_ref}
</code>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
{project.region}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{getStatusBadge(project.status)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
{project.creator_email}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{new Date(project.created_at).toLocaleDateString()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
<Link
href={`/projects/${project.id}`}
className="text-blue-600 hover:text-blue-800"
>
View
</Link>
{isAdmin && (
<>
{project.status === 'active' && (
<button
onClick={() => handlePause(project.id)}
disabled={loadingAction === project.id}
className="text-yellow-600 hover:text-yellow-800 disabled:text-gray-400"
>
{loadingAction === project.id ? 'Loading...' : 'Pause'}
</button>
)}
{project.status === 'paused' && (
<button
onClick={() => handleResume(project.id)}
disabled={loadingAction === project.id}
className="text-green-600 hover:text-green-800 disabled:text-gray-400"
>
{loadingAction === project.id ? 'Loading...' : 'Resume'}
</button>
)}
<button
onClick={() => handleDelete(project.id)}
disabled={loadingAction === project.id}
className="text-red-600 hover:text-red-800 disabled:text-gray-400"
>
{loadingAction === project.id ? 'Loading...' : 'Delete'}
</button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Legend */}
<div className="text-xs text-gray-500 mt-4">
<p>
<strong>Note:</strong> {isAdmin ? 'As an admin, you can pause, resume, and delete projects.' : 'Contact an admin to pause, resume, or delete projects.'}
</p>
</div>
</div>
)
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;
@@ -0,0 +1,8 @@
import { createBrowserClient } from '@supabase/ssr'
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
}
@@ -0,0 +1,36 @@
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
request,
})
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({
request,
})
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options)
)
},
},
}
)
// Refresh session if expired
const {
data: { user },
} = await supabase.auth.getUser()
return supabaseResponse
}
@@ -0,0 +1,29 @@
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function createClient() {
const cookieStore = await cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch {
// The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
// user sessions.
}
},
},
}
)
}
+19
View File
@@ -0,0 +1,19 @@
import { updateSession } from '@/lib/supabase/middleware'
import { type NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
return await updateSession(request)
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "supa-builder",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@supabase/ssr": "^0.8.0",
"@supabase/supabase-js": "^2.93.3",
"next": "16.1.6",
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"tailwindcss": "^4",
"typescript": "^5"
}
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+1
View File
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

@@ -0,0 +1,8 @@
# Supabase
.branches
.temp
# dotenvx
.env.keys
.env.local
.env.*.local
+359
View File
@@ -0,0 +1,359 @@
# For detailed configuration reference documentation, visit:
# https://supabase.com/docs/guides/local-development/cli/config
# A string used to distinguish different Supabase projects on the same host. Defaults to the
# working directory name when running `supabase init`.
project_id = "supa-builder"
[api]
enabled = true
# Port to use for the API URL.
port = 54321
# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
# endpoints. `public` and `graphql_public` schemas are included by default.
schemas = ["public", "graphql_public"]
# Extra schemas to add to the search_path of every request.
extra_search_path = ["public", "extensions"]
# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
# for accidental or malicious requests.
max_rows = 1000
[api.tls]
# Enable HTTPS endpoints locally using a self-signed certificate.
enabled = false
# Paths to self-signed certificate pair.
# cert_path = "../certs/my-cert.pem"
# key_path = "../certs/my-key.pem"
[db]
# Port to use for the local database URL.
port = 54322
# Port used by db diff command to initialize the shadow database.
shadow_port = 54320
# The database major version to use. This has to be the same as your remote database's. Run `SHOW
# server_version;` on the remote database to check.
major_version = 17
[db.pooler]
enabled = false
# Port to use for the local connection pooler.
port = 54329
# Specifies when a server connection can be reused by other clients.
# Configure one of the supported pooler modes: `transaction`, `session`.
pool_mode = "transaction"
# How many server connections to allow per user/database pair.
default_pool_size = 20
# Maximum number of client connections allowed.
max_client_conn = 100
# [db.vault]
# secret_key = "env(SECRET_VALUE)"
[db.migrations]
# If disabled, migrations will be skipped during a db push or reset.
enabled = true
# Specifies an ordered list of schema files that describe your database.
# Supports glob patterns relative to supabase directory: "./schemas/*.sql"
schema_paths = []
[db.seed]
# If enabled, seeds the database after migrations during a db reset.
enabled = true
# Specifies an ordered list of seed files to load during db reset.
# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
sql_paths = ["./seed.sql"]
[db.network_restrictions]
# Enable management of network restrictions.
enabled = false
# List of IPv4 CIDR blocks allowed to connect to the database.
# Defaults to allow all IPv4 connections. Set empty array to block all IPs.
allowed_cidrs = ["0.0.0.0/0"]
# List of IPv6 CIDR blocks allowed to connect to the database.
# Defaults to allow all IPv6 connections. Set empty array to block all IPs.
allowed_cidrs_v6 = ["::/0"]
[realtime]
enabled = true
# Bind realtime via either IPv4 or IPv6. (default: IPv4)
# ip_version = "IPv6"
# The maximum length in bytes of HTTP request headers. (default: 4096)
# max_header_length = 4096
[studio]
enabled = true
# Port to use for Supabase Studio.
port = 54323
# External URL of the API server that frontend connects to.
api_url = "http://127.0.0.1"
# OpenAI API Key to use for Supabase AI in the Supabase Studio.
openai_api_key = "env(OPENAI_API_KEY)"
# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
# are monitored, and you can view the emails that would have been sent from the web interface.
[inbucket]
enabled = true
# Port to use for the email testing server web interface.
port = 54324
# Uncomment to expose additional ports for testing user applications that send emails.
# smtp_port = 54325
# pop3_port = 54326
# admin_email = "admin@email.com"
# sender_name = "Admin"
[storage]
enabled = true
# The maximum file size allowed (e.g. "5MB", "500KB").
file_size_limit = "50MiB"
# Image transformation API is available to Supabase Pro plan.
# [storage.image_transformation]
# enabled = true
# Uncomment to configure local storage buckets
# [storage.buckets.images]
# public = false
# file_size_limit = "50MiB"
# allowed_mime_types = ["image/png", "image/jpeg"]
# objects_path = "./images"
[auth]
enabled = true
# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
# in emails.
site_url = "http://127.0.0.1:3000"
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
additional_redirect_urls = ["https://127.0.0.1:3000"]
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
jwt_expiry = 3600
# Path to JWT signing key. DO NOT commit your signing keys file to git.
# signing_keys_path = "./signing_keys.json"
# If disabled, the refresh token will never expire.
enable_refresh_token_rotation = true
# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
# Requires enable_refresh_token_rotation = true.
refresh_token_reuse_interval = 10
# Allow/disallow new user signups to your project.
enable_signup = true
# Allow/disallow anonymous sign-ins to your project.
enable_anonymous_sign_ins = false
# Allow/disallow testing manual linking of accounts
enable_manual_linking = false
# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.
minimum_password_length = 6
# Passwords that do not meet the following requirements will be rejected as weak. Supported values
# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols`
password_requirements = ""
[auth.rate_limit]
# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled.
email_sent = 2
# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled.
sms_sent = 30
# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true.
anonymous_users = 30
# Number of sessions that can be refreshed in a 5 minute interval per IP address.
token_refresh = 150
# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users).
sign_in_sign_ups = 30
# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address.
token_verifications = 30
# Number of Web3 logins that can be made in a 5 minute interval per IP address.
web3 = 30
# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`.
# [auth.captcha]
# enabled = true
# provider = "hcaptcha"
# secret = ""
[auth.email]
# Allow/disallow new user signups via email to your project.
enable_signup = true
# If enabled, a user will be required to confirm any email change on both the old, and new email
# addresses. If disabled, only the new email is required to confirm.
double_confirm_changes = true
# If enabled, users need to confirm their email address before signing in.
enable_confirmations = false
# If enabled, users will need to reauthenticate or have logged in recently to change their password.
secure_password_change = false
# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
max_frequency = "1s"
# Number of characters used in the email OTP.
otp_length = 6
# Number of seconds before the email OTP expires (defaults to 1 hour).
otp_expiry = 3600
# Use a production-ready SMTP server
# [auth.email.smtp]
# enabled = true
# host = "smtp.sendgrid.net"
# port = 587
# user = "apikey"
# pass = "env(SENDGRID_API_KEY)"
# admin_email = "admin@email.com"
# sender_name = "Admin"
# Uncomment to customize email template
# [auth.email.template.invite]
# subject = "You have been invited"
# content_path = "./supabase/templates/invite.html"
[auth.sms]
# Allow/disallow new user signups via SMS to your project.
enable_signup = false
# If enabled, users need to confirm their phone number before signing in.
enable_confirmations = false
# Template for sending OTP to users
template = "Your code is {{ .Code }}"
# Controls the minimum amount of time that must pass before sending another sms otp.
max_frequency = "5s"
# Use pre-defined map of phone number to OTP for testing.
# [auth.sms.test_otp]
# 4152127777 = "123456"
# Configure logged in session timeouts.
# [auth.sessions]
# Force log out after the specified duration.
# timebox = "24h"
# Force log out if the user has been inactive longer than the specified duration.
# inactivity_timeout = "8h"
# This hook runs before a new user is created and allows developers to reject the request based on the incoming user object.
# [auth.hook.before_user_created]
# enabled = true
# uri = "pg-functions://postgres/auth/before-user-created-hook"
# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used.
# [auth.hook.custom_access_token]
# enabled = true
# uri = "pg-functions://<database>/<schema>/<hook_name>"
# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`.
[auth.sms.twilio]
enabled = false
account_sid = ""
message_service_sid = ""
# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead:
auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)"
# Multi-factor-authentication is available to Supabase Pro plan.
[auth.mfa]
# Control how many MFA factors can be enrolled at once per user.
max_enrolled_factors = 10
# Control MFA via App Authenticator (TOTP)
[auth.mfa.totp]
enroll_enabled = false
verify_enabled = false
# Configure MFA via Phone Messaging
[auth.mfa.phone]
enroll_enabled = false
verify_enabled = false
otp_length = 6
template = "Your code is {{ .Code }}"
max_frequency = "5s"
# Configure MFA via WebAuthn
# [auth.mfa.web_authn]
# enroll_enabled = true
# verify_enabled = true
# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`,
# `twitter`, `slack`, `spotify`, `workos`, `zoom`.
# Google OAuth Configuration
[auth.external.google]
enabled = true
client_id = "env(GOOGLE_CLIENT_ID)"
# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
secret = "env(GOOGLE_CLIENT_SECRET)"
# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
skip_nonce_check = false
[auth.external.apple]
enabled = false
client_id = ""
# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
# Overrides the default auth redirectUrl.
redirect_uri = ""
# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
# or any other third-party OIDC providers.
url = ""
# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
skip_nonce_check = false
# If enabled, it will allow the user to successfully authenticate when the provider does not return an email address.
email_optional = false
# Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS, EIP-4361) standard.
# You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting.
[auth.web3.solana]
enabled = false
# Use Firebase Auth as a third-party provider alongside Supabase Auth.
[auth.third_party.firebase]
enabled = false
# project_id = "my-firebase-project"
# Use Auth0 as a third-party provider alongside Supabase Auth.
[auth.third_party.auth0]
enabled = false
# tenant = "my-auth0-tenant"
# tenant_region = "us"
# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth.
[auth.third_party.aws_cognito]
enabled = false
# user_pool_id = "my-user-pool-id"
# user_pool_region = "us-east-1"
# Use Clerk as a third-party provider alongside Supabase Auth.
[auth.third_party.clerk]
enabled = false
# Obtain from https://clerk.com/setup/supabase
# domain = "example.clerk.accounts.dev"
# OAuth server configuration
[auth.oauth_server]
# Enable OAuth server functionality
enabled = false
# Path for OAuth consent flow UI
authorization_url_path = "/oauth/consent"
# Allow dynamic client registration
allow_dynamic_registration = false
[edge_runtime]
enabled = true
# Supported request policies: `oneshot`, `per_worker`.
# `per_worker` (default) — enables hot reload during local development.
# `oneshot` — fallback mode if hot reload causes issues (e.g. in large repos or with symlinks).
policy = "per_worker"
# Port to attach the Chrome inspector for debugging edge functions.
inspector_port = 8083
# The Deno major version to use.
deno_version = 2
# [edge_runtime.secrets]
# secret_key = "env(SECRET_VALUE)"
[analytics]
enabled = true
port = 54327
# Configure one of the supported backends: `postgres`, `bigquery`.
backend = "postgres"
# Experimental features may be deprecated any time
[experimental]
# Configures Postgres storage engine to use OrioleDB (S3)
orioledb_version = ""
# Configures S3 bucket URL, eg. <bucket_name>.s3-<region>.amazonaws.com
s3_host = "env(S3_HOST)"
# Configures S3 bucket region, eg. us-east-1
s3_region = "env(S3_REGION)"
# Configures AWS_ACCESS_KEY_ID for S3 bucket
s3_access_key = "env(S3_ACCESS_KEY)"
# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
s3_secret_key = "env(S3_SECRET_KEY)"
@@ -0,0 +1,76 @@
# SupaBuilder Supabase Configuration
# This file configures the local Supabase development environment
[project]
# A unique identifier for your project
project_id = "supabuilder"
[api]
# Port to use for the API URL
port = 54321
# Schemas to expose in your API. Tables, views and stored procedures in these schemas will be API endpoints.
schemas = ["public", "storage", "graphql_public"]
# Extra schemas to add to the search_path of every request.
extra_search_path = ["public", "extensions"]
# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size.
max_rows = 1000
[db]
# Port to use for the local database URL
port = 54322
# The database major version to use
major_version = 15
[studio]
# Port to use for Supabase Studio
port = 54323
[inbucket]
# Port to use for the email testing server (inbucket)
port = 54324
[storage]
# The maximum file size allowed (e.g. "5MB", "500KB")
file_size_limit = "50MiB"
[auth]
# The base URL of your website
site_url = "http://localhost:3000"
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication
additional_redirect_urls = ["https://localhost:3000"]
# How long tokens are valid for (in seconds)
jwt_expiry = 3600
# Allow/disallow new user signups to your project
enable_signup = true
[auth.email]
# Allow/disallow new user signups via email to your project
enable_signup = true
# If enabled, a user will be required to confirm any email change via email
double_confirm_changes = true
# If enabled, users need to confirm their email address before signing in
enable_confirmations = false
# ============================================================================
# EDGE FUNCTIONS CONFIGURATION
# ============================================================================
[functions.create-project]
# Verify JWT for this function
verify_jwt = true
# ============================================================================
# LOCAL DEVELOPMENT
# ============================================================================
[local]
# Port for local PostgreSQL database
port = 54322
# ============================================================================
# EXTENSIONS
# ============================================================================
[extensions]
# Enable pgcrypto for encryption functions
enabled = ["pgcrypto", "uuid-ossp"]
@@ -0,0 +1,18 @@
/**
* CORS utilities for Supabase Edge Functions
*/
export const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
/**
* Handle CORS preflight requests
*/
export function handleCors(req: Request): Response | null {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders })
}
return null
}
@@ -0,0 +1,143 @@
/**
* Shared TypeScript types for Supabase Edge Functions
*/
// ============================================================================
// REQUEST/RESPONSE TYPES
// ============================================================================
export interface CreateProjectRequest {
project_name: string
organization_id: string
region: string
purpose?: string
description?: string
}
export interface CreateProjectResponse {
success: boolean
project_id?: string
project_ref?: string
anon_key?: string
error?: string
message?: string
}
export interface ErrorResponse {
success: false
error: string
message?: string
}
// ============================================================================
// DATABASE TYPES
// ============================================================================
export interface Project {
id: string
project_ref: string
project_name: string
organization_id: string
anon_key: string
service_role_key_encrypted: string
region: string
status: 'provisioning' | 'active' | 'paused' | 'failed' | 'deleted'
purpose?: string
description?: string
creator_id: string
creator_email: string
created_at: string
updated_at: string
deleted_at?: string
management_api_response?: Record<string, unknown>
}
export interface UserRole {
id: string
user_id: string
organization_id: string
role: 'admin' | 'builder'
assigned_by?: string
assigned_at: string
}
export interface AuditLog {
id: string
project_id: string
action: 'create' | 'pause' | 'resume' | 'delete' | 'update'
actor_id: string
actor_email: string
organization_id: string
metadata?: Record<string, unknown>
created_at: string
}
// ============================================================================
// MANAGEMENT API TYPES
// ============================================================================
export interface ManagementAPICreateProjectRequest {
name: string
organization_id: string
plan: 'free' | 'pro' | 'team' | 'enterprise'
region: string
db_pass?: string
}
export interface ManagementAPIProjectResponse {
id: string
organization_id: string
name: string
region: string
created_at: string
database: {
host: string
version: string
}
status: string
}
// ============================================================================
// VALIDATION HELPERS
// ============================================================================
export function validateCreateProjectRequest(
data: unknown
): data is CreateProjectRequest {
if (typeof data !== 'object' || data === null) {
return false
}
const req = data as CreateProjectRequest
return (
typeof req.project_name === 'string' &&
req.project_name.length >= 3 &&
req.project_name.length <= 63 &&
typeof req.organization_id === 'string' &&
req.organization_id.length > 0 &&
typeof req.region === 'string' &&
req.region.length > 0 &&
(req.purpose === undefined || typeof req.purpose === 'string') &&
(req.description === undefined || typeof req.description === 'string')
)
}
export const VALID_REGIONS = [
'us-east-1',
'us-west-1',
'us-west-2',
'eu-west-1',
'eu-west-2',
'eu-central-1',
'ap-southeast-1',
'ap-southeast-2',
'ap-northeast-1',
'sa-east-1',
] as const
export type ValidRegion = typeof VALID_REGIONS[number]
export function isValidRegion(region: string): region is ValidRegion {
return VALID_REGIONS.includes(region as ValidRegion)
}
@@ -0,0 +1,3 @@
{
"verify_jwt": false
}
@@ -0,0 +1,5 @@
{
"imports": {
"@supabase/supabase-js": "npm:@supabase/supabase-js@^2.93.3"
}
}
@@ -0,0 +1,391 @@
/**
* SupaBuilder - Create Project Edge Function
*
* This edge function orchestrates the creation of new Supabase Pico projects
* via the Management API. It handles rate limiting, validation, encryption,
* and audit logging.
*
* Flow:
* 1. Verify JWT from Authorization header
* 2. Parse & validate request
* 3. Check rate limit (5 projects/hour)
* 4. Create provisional project record
* 5. Call Management API to create Pico project
* 6. Encrypt and store service_role_key
* 7. Update project record with credentials
* 8. Create audit log entry
* 9. Return project details
*/
import { createClient } from 'npm:@supabase/supabase-js@^2.93.3'
import { corsHeaders, handleCors } from '../_shared/cors.ts'
import {
type CreateProjectRequest,
type CreateProjectResponse,
type ErrorResponse,
validateCreateProjectRequest,
isValidRegion,
} from '../_shared/types.ts'
Deno.serve(async (req: Request): Promise<Response> => {
// Handle CORS preflight
const corsResponse = handleCors(req)
if (corsResponse) return corsResponse
try {
// =========================================================================
// 1. VERIFY JWT AND GET USER INFO
// =========================================================================
const authHeader = req.headers.get('Authorization')
if (!authHeader) {
return jsonError('Missing Authorization header', 401)
}
const jwt = authHeader.replace('Bearer ', '')
// Create Supabase client for database operations
const supabaseUrl = Deno.env.get('SUPABASE_URL')!
const supabaseAnonKey = Deno.env.get('SUPABASE_ANON_KEY')!
const supabase = createClient(supabaseUrl, supabaseAnonKey)
// Verify JWT and get user - pass the JWT explicitly
const {
data: { user },
error: authError,
} = await supabase.auth.getUser(jwt)
if (authError || !user) {
console.error('Auth error:', authError)
return jsonError('Unauthorized', 401)
}
console.log('User authenticated:', user.email)
// Now create a client with the user's JWT for database operations
const supabaseWithAuth = createClient(supabaseUrl, supabaseAnonKey, {
global: {
headers: { Authorization: authHeader },
},
})
// =========================================================================
// 2. PARSE AND VALIDATE REQUEST
// =========================================================================
let requestData: CreateProjectRequest
try {
requestData = await req.json()
} catch {
return jsonError('Invalid JSON in request body', 400)
}
if (!validateCreateProjectRequest(requestData)) {
return jsonError(
'Invalid request: project_name (3-63 chars), organization_id, and region are required',
400
)
}
if (!isValidRegion(requestData.region)) {
return jsonError(
`Invalid region. Must be one of: us-east-1, us-west-1, us-west-2, eu-west-1, eu-west-2, eu-central-1, ap-southeast-1, ap-southeast-2, ap-northeast-1, sa-east-1`,
400
)
}
const { project_name, organization_id, region, purpose, description } =
requestData
// =========================================================================
// 3. CHECK RATE LIMIT (if enabled)
// =========================================================================
const rateLimitingEnabled = Deno.env.get('ENABLE_RATE_LIMITING') !== 'false'
if (rateLimitingEnabled) {
const { data: rateLimitOk, error: rateLimitError } = await supabaseWithAuth.rpc(
'check_rate_limit',
{
p_user_id: user.id,
p_organization_id: organization_id,
p_action: 'create_project',
p_max_requests: 5,
p_window_minutes: 60,
}
)
if (rateLimitError) {
console.error('Rate limit check error:', rateLimitError)
return jsonError('Error checking rate limit', 500)
}
if (!rateLimitOk) {
return jsonError(
'Rate limit exceeded: Maximum 5 projects per hour',
429
)
}
// Record rate limit event
await supabaseWithAuth.rpc('record_rate_limit', {
p_user_id: user.id,
p_organization_id: organization_id,
p_action: 'create_project',
})
} else {
console.log('Rate limiting disabled')
}
// =========================================================================
// 4. CREATE PROVISIONAL PROJECT RECORD
// =========================================================================
const { data: provisionalProject, error: insertError } = await supabaseWithAuth
.from('projects')
.insert({
project_name,
organization_id,
region,
purpose,
description,
creator_id: user.id,
creator_email: user.email!,
status: 'provisioning',
// Temporary values, will be updated after API call
project_ref: 'pending',
anon_key: 'pending',
service_role_key_encrypted: 'pending',
})
.select('id')
.single()
if (insertError || !provisionalProject) {
console.error('Error creating provisional project:', insertError)
return jsonError('Failed to create project record', 500)
}
const projectId = provisionalProject.id
try {
// =========================================================================
// 5. CALL MANAGEMENT API
// =========================================================================
const managementAccessToken = Deno.env.get('MANAGEMENT_ACCESS_TOKEN')
if (!managementAccessToken) {
throw new Error('MANAGEMENT_ACCESS_TOKEN not configured')
}
const supabaseOrgSlug = Deno.env.get('ORGANIZATION_SLUG')
if (!supabaseOrgSlug) {
throw new Error('ORGANIZATION_SLUG not configured')
}
console.log(`Creating project via Management API: ${project_name}`)
// Map region to smart group
const regionMap: Record<string, string> = {
'us-east-1': 'americas',
'us-west-1': 'americas',
'us-west-2': 'americas',
'sa-east-1': 'americas',
'eu-west-1': 'europe',
'eu-west-2': 'europe',
'eu-central-1': 'europe',
'ap-southeast-1': 'asia-pacific',
'ap-southeast-2': 'asia-pacific',
'ap-northeast-1': 'asia-pacific',
}
const smartGroupCode = regionMap[region] || 'americas'
// Generate a secure database password
const dbPassword = crypto.randomUUID() + crypto.randomUUID().replace(/-/g, '')
// Create Pico project using direct API call
const createResponse = await fetch('https://api.supabase.com/v1/projects', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${managementAccessToken}`,
},
body: JSON.stringify({
name: project_name,
organization_slug: supabaseOrgSlug,
db_pass: dbPassword,
region_selection: {
type: 'smartGroup',
code: smartGroupCode,
},
desired_instance_size: 'micro', // Pico instance that pause for inactivity.
}),
})
if (!createResponse.ok) {
const errorText = await createResponse.text()
throw new Error(`Management API error (${createResponse.status}): ${errorText}`)
}
const newProject = await createResponse.json()
if (!newProject || !newProject.id) {
throw new Error('Management API returned invalid response')
}
console.log(`Project created: ${newProject.id}`)
const projectRef = newProject.id
// Wait for project to be ready and fetch API keys
// The project needs time to provision before keys are available
console.log('Waiting for project to provision...')
await new Promise(resolve => setTimeout(resolve, 5000)) // Wait 5 seconds
// Fetch project API keys
const keysResponse = await fetch(
`https://api.supabase.com/v1/projects/${projectRef}/api-keys`,
{
headers: {
'Authorization': `Bearer ${managementAccessToken}`,
},
}
)
if (!keysResponse.ok) {
throw new Error(`Failed to fetch API keys: ${keysResponse.status}`)
}
const keysData = await keysResponse.json()
// Extract anon and service_role keys
const anonKey = keysData.find((k: any) => k.name === 'anon')?.api_key
const serviceRoleKey = keysData.find((k: any) => k.name === 'service_role')?.api_key
if (!anonKey || !serviceRoleKey) {
throw new Error('Failed to retrieve API keys from Management API')
}
console.log('API keys retrieved successfully')
// =========================================================================
// 6. ENCRYPT SERVICE ROLE KEY
// =========================================================================
const encryptionKey = Deno.env.get('ENCRYPTION_KEY')
if (!encryptionKey) {
throw new Error('ENCRYPTION_KEY not configured')
}
const { data: encryptedKey, error: encryptError } = await supabaseWithAuth.rpc(
'encrypt_service_role_key',
{
p_service_role_key: serviceRoleKey,
p_encryption_key: encryptionKey,
}
)
if (encryptError || !encryptedKey) {
throw new Error(`Failed to encrypt service_role_key: ${encryptError?.message}`)
}
// =========================================================================
// 7. UPDATE PROJECT RECORD WITH CREDENTIALS
// =========================================================================
const { error: updateError } = await supabaseWithAuth
.from('projects')
.update({
project_ref: projectRef,
anon_key: anonKey,
service_role_key_encrypted: encryptedKey,
status: 'active',
management_api_response: newProject,
})
.eq('id', projectId)
if (updateError) {
throw new Error(`Failed to update project: ${updateError.message}`)
}
// =========================================================================
// 8. CREATE AUDIT LOG
// =========================================================================
await supabaseWithAuth.rpc('create_audit_log', {
p_project_id: projectId,
p_action: 'create',
p_actor_id: user.id,
p_actor_email: user.email!,
p_organization_id: organization_id,
p_metadata: {
project_name,
region,
project_ref: projectRef,
},
})
// =========================================================================
// 9. RETURN SUCCESS RESPONSE
// =========================================================================
const response: CreateProjectResponse = {
success: true,
project_id: projectId,
project_ref: projectRef,
anon_key: anonKey,
message: 'Project created successfully',
}
return jsonResponse(response, 201)
} catch (error) {
// If Management API call fails, update project status to 'failed'
await supabaseWithAuth
.from('projects')
.update({
status: 'failed',
management_api_response: {
error: error instanceof Error ? error.message : String(error),
},
})
.eq('id', projectId)
console.error('Error creating project:', error)
return jsonError(
`Failed to create project: ${error instanceof Error ? error.message : String(error)}`,
500
)
}
} catch (error) {
console.error('Unexpected error:', error)
return jsonError(
`Unexpected error: ${error instanceof Error ? error.message : String(error)}`,
500
)
}
})
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
function jsonResponse(data: CreateProjectResponse, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
})
}
function jsonError(message: string, status = 400): Response {
const error: ErrorResponse = {
success: false,
error: message,
}
return new Response(JSON.stringify(error), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
})
}
@@ -0,0 +1,277 @@
-- SupaBuilder Initial Schema
-- Core tables for enterprise project provisioning platform
-- Enable required extensions
create extension if not exists "pgcrypto";
-- ============================================================================
-- PROJECTS TABLE
-- Tracks all child Supabase projects created through SupaBuilder
-- ============================================================================
create table public.projects (
id uuid primary key default gen_random_uuid(),
-- Project identification
project_ref text unique not null, -- Supabase project reference (e.g., "abcdefghijklmnop")
project_name text not null,
organization_id text not null, -- Enterprise org identifier
-- Credentials (encrypted)
anon_key text not null,
service_role_key_encrypted text not null, -- Encrypted with pgcrypto
-- Project configuration
region text not null, -- AWS region (e.g., "us-east-1")
status text not null default 'provisioning' check (status in ('provisioning', 'active', 'paused', 'failed', 'deleted')),
-- Metadata
purpose text, -- Why this project was created
description text,
-- Ownership and tracking
creator_id uuid not null, -- User who created the project (references auth.users)
creator_email text not null,
-- Timestamps
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
deleted_at timestamptz, -- Soft delete
-- Management API metadata
management_api_response jsonb, -- Store full API response for debugging
-- Indexes for common queries
constraint projects_org_name_unique unique (organization_id, project_name, deleted_at)
);
-- Indexes for performance
create index idx_projects_organization on public.projects(organization_id) where deleted_at is null;
create index idx_projects_creator on public.projects(creator_id) where deleted_at is null;
create index idx_projects_status on public.projects(status) where deleted_at is null;
create index idx_projects_created_at on public.projects(created_at desc);
-- Comment
comment on table public.projects is 'Child Supabase projects created through SupaBuilder';
-- ============================================================================
-- USER ROLES TABLE
-- Manages admin vs builder role assignments per organization
-- ============================================================================
create table public.user_roles (
id uuid primary key default gen_random_uuid(),
user_id uuid not null, -- references auth.users(id)
organization_id text not null,
role text not null check (role in ('admin', 'builder')),
-- Metadata
assigned_by uuid, -- Admin who assigned this role
assigned_at timestamptz not null default now(),
-- Ensure one role per user per org
constraint user_roles_unique unique (user_id, organization_id)
);
-- Indexes
create index idx_user_roles_user on public.user_roles(user_id);
create index idx_user_roles_org on public.user_roles(organization_id);
comment on table public.user_roles is 'Role assignments for users within organizations';
-- ============================================================================
-- PROJECT AUDIT LOGS TABLE
-- Immutable audit trail of all project operations
-- ============================================================================
create table public.project_audit_logs (
id uuid primary key default gen_random_uuid(),
project_id uuid not null references public.projects(id) on delete cascade,
-- Action details
action text not null check (action in ('create', 'pause', 'resume', 'delete', 'update')),
actor_id uuid not null, -- User who performed the action
actor_email text not null,
-- Context
organization_id text not null,
metadata jsonb, -- Additional context (e.g., what was changed)
-- Timestamp (immutable)
created_at timestamptz not null default now()
);
-- Indexes for audit queries
create index idx_audit_project on public.project_audit_logs(project_id, created_at desc);
create index idx_audit_actor on public.project_audit_logs(actor_id, created_at desc);
create index idx_audit_org on public.project_audit_logs(organization_id, created_at desc);
create index idx_audit_action on public.project_audit_logs(action);
comment on table public.project_audit_logs is 'Immutable audit trail for all project operations';
-- ============================================================================
-- RATE LIMITS TABLE
-- Simple DB-based rate limiting (5 projects/hour per user)
-- ============================================================================
create table public.rate_limits (
id uuid primary key default gen_random_uuid(),
user_id uuid not null,
organization_id text not null,
action text not null, -- e.g., 'create_project'
created_at timestamptz not null default now(),
-- Index for quick lookups
constraint rate_limits_idx unique (user_id, organization_id, action, created_at)
);
-- Index for time-based queries
create index idx_rate_limits_user_action on public.rate_limits(user_id, action, created_at desc);
comment on table public.rate_limits is 'Rate limiting tracking for user actions';
-- ============================================================================
-- ENCRYPTION FUNCTIONS
-- Encrypt/decrypt service_role_key using pgcrypto
-- ============================================================================
-- Encryption function
-- Uses AES-256 encryption with a key from environment/secrets
create or replace function public.encrypt_service_role_key(
p_service_role_key text,
p_encryption_key text
)
returns text
language plpgsql
security definer
as $$
begin
return encode(
pgp_sym_encrypt(
p_service_role_key,
p_encryption_key,
'cipher-algo=aes256'
),
'base64'
);
end;
$$;
-- Decryption function (admin only)
create or replace function public.decrypt_service_role_key(
p_encrypted_key text,
p_encryption_key text
)
returns text
language plpgsql
security definer
as $$
begin
return pgp_sym_decrypt(
decode(p_encrypted_key, 'base64'),
p_encryption_key,
'cipher-algo=aes256'
);
end;
$$;
comment on function public.encrypt_service_role_key is 'Encrypt service_role_key using AES-256';
comment on function public.decrypt_service_role_key is 'Decrypt service_role_key (admin only)';
-- ============================================================================
-- TRIGGERS
-- Auto-update timestamps
-- ============================================================================
-- Function to update updated_at timestamp
create or replace function public.handle_updated_at()
returns trigger
language plpgsql
as $$
begin
new.updated_at = now();
return new;
end;
$$;
-- Apply trigger to projects table
create trigger set_updated_at
before update on public.projects
for each row
execute function public.handle_updated_at();
-- ============================================================================
-- HELPER FUNCTIONS
-- ============================================================================
-- Function to get user's role in an organization
create or replace function public.get_user_role(
p_user_id uuid,
p_organization_id text
)
returns text
language plpgsql
security definer
stable
as $$
declare
v_role text;
begin
select role into v_role
from public.user_roles
where user_id = p_user_id
and organization_id = p_organization_id;
return coalesce(v_role, 'builder'); -- Default to builder if no role assigned
end;
$$;
comment on function public.get_user_role is 'Get user role within an organization';
-- Function to check if user is admin
create or replace function public.is_admin(
p_user_id uuid,
p_organization_id text
)
returns boolean
language plpgsql
security definer
stable
as $$
begin
return exists (
select 1
from public.user_roles
where user_id = p_user_id
and organization_id = p_organization_id
and role = 'admin'
);
end;
$$;
comment on function public.is_admin is 'Check if user has admin role in organization';
-- ============================================================================
-- GRANTS
-- Enable RLS and grant basic permissions
-- ============================================================================
-- Enable RLS on all tables
alter table public.projects enable row level security;
alter table public.user_roles enable row level security;
alter table public.project_audit_logs enable row level security;
alter table public.rate_limits enable row level security;
-- Grant usage on schema
grant usage on schema public to authenticated;
grant usage on schema public to anon;
-- Grant permissions on tables (RLS policies will control actual access)
grant select, insert, update on public.projects to authenticated;
grant select on public.user_roles to authenticated;
grant select, insert on public.project_audit_logs to authenticated;
grant select, insert on public.rate_limits to authenticated;
-- Grant execute on functions
grant execute on function public.get_user_role to authenticated;
grant execute on function public.is_admin to authenticated;
@@ -0,0 +1,233 @@
-- SupaBuilder RLS Policies
-- Row Level Security policies for admin vs builder access control
-- ============================================================================
-- PROJECTS TABLE POLICIES
-- Admins see all org projects, builders see only their own
-- ============================================================================
-- Policy: Admins can see all projects in their organization
create policy "Admins can view all organization projects"
on public.projects
for select
to authenticated
using (
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = projects.organization_id
and user_roles.role = 'admin'
)
and deleted_at is null
);
-- Policy: Builders can only see projects they created
create policy "Builders can view their own projects"
on public.projects
for select
to authenticated
using (
creator_id = auth.uid()
and deleted_at is null
);
-- Policy: All authenticated users can create projects (rate limited by function)
create policy "Authenticated users can create projects"
on public.projects
for insert
to authenticated
with check (
creator_id = auth.uid()
);
-- Policy: Admins can update any project in their organization
create policy "Admins can update organization projects"
on public.projects
for update
to authenticated
using (
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = projects.organization_id
and user_roles.role = 'admin'
)
)
with check (
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = projects.organization_id
and user_roles.role = 'admin'
)
);
-- Policy: Builders can update their own projects (limited fields)
create policy "Builders can update their own projects"
on public.projects
for update
to authenticated
using (creator_id = auth.uid())
with check (creator_id = auth.uid());
-- ============================================================================
-- USER ROLES TABLE POLICIES
-- Only admins can modify roles, everyone can view their own role
-- ============================================================================
-- Policy: Users can view their own roles
create policy "Users can view their own roles"
on public.user_roles
for select
to authenticated
using (user_id = auth.uid());
-- Policy: Admins can view all roles in their organization
create policy "Admins can view organization roles"
on public.user_roles
for select
to authenticated
using (
exists (
select 1
from public.user_roles as ur
where ur.user_id = auth.uid()
and ur.organization_id = user_roles.organization_id
and ur.role = 'admin'
)
);
-- Policy: Admins can assign roles in their organization
create policy "Admins can assign roles"
on public.user_roles
for insert
to authenticated
with check (
exists (
select 1
from public.user_roles as ur
where ur.user_id = auth.uid()
and ur.organization_id = user_roles.organization_id
and ur.role = 'admin'
)
);
-- Policy: Admins can update roles in their organization
create policy "Admins can update roles"
on public.user_roles
for update
to authenticated
using (
exists (
select 1
from public.user_roles as ur
where ur.user_id = auth.uid()
and ur.organization_id = user_roles.organization_id
and ur.role = 'admin'
)
);
-- Policy: Admins can delete roles in their organization (except their own)
create policy "Admins can delete roles"
on public.user_roles
for delete
to authenticated
using (
user_id != auth.uid() -- Can't delete own role
and exists (
select 1
from public.user_roles as ur
where ur.user_id = auth.uid()
and ur.organization_id = user_roles.organization_id
and ur.role = 'admin'
)
);
-- ============================================================================
-- PROJECT AUDIT LOGS POLICIES
-- Admins can view all org logs, builders can view their project logs
-- ============================================================================
-- Policy: Admins can view all audit logs in their organization
create policy "Admins can view organization audit logs"
on public.project_audit_logs
for select
to authenticated
using (
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = project_audit_logs.organization_id
and user_roles.role = 'admin'
)
);
-- Policy: Builders can view audit logs for their projects
create policy "Builders can view their project audit logs"
on public.project_audit_logs
for select
to authenticated
using (
exists (
select 1
from public.projects
where projects.id = project_audit_logs.project_id
and projects.creator_id = auth.uid()
)
);
-- Policy: All authenticated users can insert audit logs (for their own actions)
create policy "Users can create audit logs"
on public.project_audit_logs
for insert
to authenticated
with check (actor_id = auth.uid());
-- ============================================================================
-- RATE LIMITS TABLE POLICIES
-- Users can view their own rate limits
-- ============================================================================
-- Policy: Users can view their own rate limits
create policy "Users can view their own rate limits"
on public.rate_limits
for select
to authenticated
using (user_id = auth.uid());
-- Policy: Users can insert their own rate limit records
create policy "Users can create rate limit records"
on public.rate_limits
for insert
to authenticated
with check (user_id = auth.uid());
-- Policy: Admins can view all rate limits in their organization
create policy "Admins can view organization rate limits"
on public.rate_limits
for select
to authenticated
using (
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = rate_limits.organization_id
and user_roles.role = 'admin'
)
);
-- ============================================================================
-- SECURITY NOTES
-- ============================================================================
-- 1. Service role keys are encrypted in the database
-- 2. Decryption function should only be called server-side with proper auth
-- 3. Builders cannot see other builders' projects
-- 4. Admins have full visibility within their organization
-- 5. Audit logs are immutable (no update/delete policies)
-- 6. Rate limits prevent abuse even before RLS checks
@@ -0,0 +1,321 @@
-- SupaBuilder Helper Functions
-- Rate limiting and utility functions
-- ============================================================================
-- RATE LIMITING FUNCTION
-- Checks if user has exceeded rate limit (5 projects/hour)
-- ============================================================================
create or replace function public.check_rate_limit(
p_user_id uuid,
p_organization_id text,
p_action text,
p_max_requests integer default 5,
p_window_minutes integer default 60
)
returns boolean
language plpgsql
security definer
as $$
declare
v_count integer;
v_window_start timestamptz;
begin
-- Calculate time window start
v_window_start := now() - (p_window_minutes || ' minutes')::interval;
-- Count requests in the time window
select count(*)
into v_count
from public.rate_limits
where user_id = p_user_id
and organization_id = p_organization_id
and action = p_action
and created_at > v_window_start;
-- Return true if under limit, false if exceeded
return v_count < p_max_requests;
end;
$$;
comment on function public.check_rate_limit is 'Check if user is within rate limit for an action';
-- ============================================================================
-- RATE LIMIT RECORDING FUNCTION
-- Records a rate limit event
-- ============================================================================
create or replace function public.record_rate_limit(
p_user_id uuid,
p_organization_id text,
p_action text
)
returns uuid
language plpgsql
security definer
as $$
declare
v_id uuid;
begin
insert into public.rate_limits (user_id, organization_id, action)
values (p_user_id, p_organization_id, p_action)
returning id into v_id;
return v_id;
end;
$$;
comment on function public.record_rate_limit is 'Record a rate limit event';
-- ============================================================================
-- AUDIT LOG HELPER FUNCTION
-- Creates an audit log entry
-- ============================================================================
create or replace function public.create_audit_log(
p_project_id uuid,
p_action text,
p_actor_id uuid,
p_actor_email text,
p_organization_id text,
p_metadata jsonb default null
)
returns uuid
language plpgsql
security definer
as $$
declare
v_id uuid;
begin
insert into public.project_audit_logs (
project_id,
action,
actor_id,
actor_email,
organization_id,
metadata
)
values (
p_project_id,
p_action,
p_actor_id,
p_actor_email,
p_organization_id,
p_metadata
)
returning id into v_id;
return v_id;
end;
$$;
comment on function public.create_audit_log is 'Create an audit log entry';
-- ============================================================================
-- PROJECT STATUS UPDATE FUNCTION
-- Updates project status with validation and audit logging
-- ============================================================================
create or replace function public.update_project_status(
p_project_id uuid,
p_new_status text,
p_actor_id uuid,
p_actor_email text
)
returns boolean
language plpgsql
security definer
as $$
declare
v_old_status text;
v_organization_id text;
begin
-- Validate status
if p_new_status not in ('provisioning', 'active', 'paused', 'failed', 'deleted') then
raise exception 'Invalid status: %', p_new_status;
end if;
-- Get current status and org
select status, organization_id
into v_old_status, v_organization_id
from public.projects
where id = p_project_id;
if not found then
raise exception 'Project not found: %', p_project_id;
end if;
-- Update status
update public.projects
set status = p_new_status
where id = p_project_id;
-- Create audit log
perform public.create_audit_log(
p_project_id,
'update',
p_actor_id,
p_actor_email,
v_organization_id,
jsonb_build_object(
'field', 'status',
'old_value', v_old_status,
'new_value', p_new_status
)
);
return true;
end;
$$;
comment on function public.update_project_status is 'Update project status with audit logging';
-- ============================================================================
-- SOFT DELETE FUNCTION
-- Soft deletes a project (sets deleted_at timestamp)
-- ============================================================================
create or replace function public.soft_delete_project(
p_project_id uuid,
p_actor_id uuid,
p_actor_email text
)
returns boolean
language plpgsql
security definer
as $$
declare
v_organization_id text;
begin
-- Get organization ID
select organization_id
into v_organization_id
from public.projects
where id = p_project_id;
if not found then
raise exception 'Project not found: %', p_project_id;
end if;
-- Soft delete (set deleted_at and status)
update public.projects
set
deleted_at = now(),
status = 'deleted'
where id = p_project_id
and deleted_at is null;
-- Create audit log
perform public.create_audit_log(
p_project_id,
'delete',
p_actor_id,
p_actor_email,
v_organization_id,
jsonb_build_object('soft_delete', true)
);
return true;
end;
$$;
comment on function public.soft_delete_project is 'Soft delete a project with audit logging';
-- ============================================================================
-- CLEANUP OLD RATE LIMITS
-- Function to clean up old rate limit records (run periodically)
-- ============================================================================
create or replace function public.cleanup_old_rate_limits(
p_retention_hours integer default 168 -- 7 days default
)
returns integer
language plpgsql
security definer
as $$
declare
v_deleted integer;
begin
delete from public.rate_limits
where created_at < now() - (p_retention_hours || ' hours')::interval;
get diagnostics v_deleted = row_count;
return v_deleted;
end;
$$;
comment on function public.cleanup_old_rate_limits is 'Clean up old rate limit records (7+ days)';
-- ============================================================================
-- GET USER PROJECTS COUNT
-- Returns count of active projects for a user
-- ============================================================================
create or replace function public.get_user_projects_count(
p_user_id uuid,
p_organization_id text
)
returns integer
language plpgsql
security definer
stable
as $$
declare
v_count integer;
begin
select count(*)
into v_count
from public.projects
where creator_id = p_user_id
and organization_id = p_organization_id
and deleted_at is null
and status in ('active', 'provisioning', 'paused');
return v_count;
end;
$$;
comment on function public.get_user_projects_count is 'Get count of active projects for a user';
-- ============================================================================
-- GET ORGANIZATION PROJECTS COUNT
-- Returns count of all projects in an organization
-- ============================================================================
create or replace function public.get_org_projects_count(
p_organization_id text
)
returns integer
language plpgsql
security definer
stable
as $$
declare
v_count integer;
begin
select count(*)
into v_count
from public.projects
where organization_id = p_organization_id
and deleted_at is null
and status in ('active', 'provisioning', 'paused');
return v_count;
end;
$$;
comment on function public.get_org_projects_count is 'Get count of all projects in an organization';
-- ============================================================================
-- GRANT EXECUTE PERMISSIONS
-- ============================================================================
grant execute on function public.check_rate_limit to authenticated;
grant execute on function public.record_rate_limit to authenticated;
grant execute on function public.create_audit_log to authenticated;
grant execute on function public.update_project_status to authenticated;
grant execute on function public.soft_delete_project to authenticated;
grant execute on function public.cleanup_old_rate_limits to authenticated;
grant execute on function public.get_user_projects_count to authenticated;
grant execute on function public.get_org_projects_count to authenticated;
@@ -0,0 +1,123 @@
-- Auto-assign admin role to first user per organization
-- This trigger runs after a new user signs in via SSO
-- ============================================================================
-- AUTO ADMIN ASSIGNMENT FUNCTION
-- Automatically assigns admin role to first user in an organization
-- ============================================================================
create or replace function public.auto_assign_first_admin()
returns trigger
language plpgsql
security definer
as $$
declare
v_org_id text;
v_user_count integer;
begin
-- Extract organization from user metadata (set via SSO claims)
-- Adjust this based on your SSO configuration
--
-- For Google Workspace: use 'hd' (hosted domain)
-- For Azure AD/Okta: use custom claim 'organization_id'
-- For development: use 'default_org'
v_org_id := coalesce(
new.raw_user_meta_data->>'organization_id',
new.raw_user_meta_data->>'org_id',
new.raw_user_meta_data->>'hd', -- Google Workspace hosted domain
new.raw_app_meta_data->>'organization_id',
'default_org' -- Fallback for development/testing
);
-- Count existing users in this organization
select count(*)
into v_user_count
from public.user_roles
where organization_id = v_org_id;
-- If this is the first user, make them admin
if v_user_count = 0 then
insert into public.user_roles (user_id, organization_id, role)
values (new.id, v_org_id, 'admin')
on conflict (user_id, organization_id) do nothing;
raise notice 'Auto-assigned admin role to user % in organization %', new.email, v_org_id;
else
-- Subsequent users get builder role by default
insert into public.user_roles (user_id, organization_id, role)
values (new.id, v_org_id, 'builder')
on conflict (user_id, organization_id) do nothing;
raise notice 'Auto-assigned builder role to user % in organization %', new.email, v_org_id;
end if;
return new;
end;
$$;
-- ============================================================================
-- TRIGGER ON AUTH.USERS
-- Fires when a new user is created (after SSO sign-in)
-- ============================================================================
create trigger on_auth_user_created
after insert on auth.users
for each row
execute function public.auto_assign_first_admin();
comment on function public.auto_assign_first_admin is 'Automatically assign admin role to first user per organization, builder to others';
-- ============================================================================
-- MANUAL ADMIN ASSIGNMENT FUNCTION (for additional admins)
-- Admins can use this to promote other users
-- ============================================================================
create or replace function public.promote_to_admin(
p_user_email text,
p_organization_id text
)
returns boolean
language plpgsql
security definer
as $$
declare
v_user_id uuid;
v_caller_is_admin boolean;
begin
-- Check if caller is admin
select exists(
select 1
from public.user_roles
where user_id = auth.uid()
and organization_id = p_organization_id
and role = 'admin'
) into v_caller_is_admin;
if not v_caller_is_admin then
raise exception 'Only admins can promote users';
end if;
-- Get user ID from email
select id into v_user_id
from auth.users
where email = p_user_email;
if v_user_id is null then
raise exception 'User not found: %', p_user_email;
end if;
-- Update role to admin
update public.user_roles
set role = 'admin',
assigned_by = auth.uid(),
assigned_at = now()
where user_id = v_user_id
and organization_id = p_organization_id;
return true;
end;
$$;
grant execute on function public.promote_to_admin to authenticated;
comment on function public.promote_to_admin is 'Allow admins to promote other users to admin role';
@@ -0,0 +1,222 @@
-- Fix RLS infinite recursion in user_roles table
-- The issue: policies were querying user_roles to check permissions on user_roles
-- ============================================================================
-- DROP EXISTING PROBLEMATIC POLICIES
-- ============================================================================
drop policy if exists "Admins can view organization roles" on public.user_roles;
drop policy if exists "Admins can assign roles" on public.user_roles;
drop policy if exists "Admins can update roles" on public.user_roles;
drop policy if exists "Admins can delete roles" on public.user_roles;
-- ============================================================================
-- SIMPLIFIED USER_ROLES POLICIES (NO RECURSION)
-- ============================================================================
-- Policy: Users can view their own role (simple, no recursion)
-- This policy already exists and is fine
-- create policy "Users can view their own roles"
-- on public.user_roles
-- for select
-- to authenticated
-- using (user_id = auth.uid());
-- Policy: Users can view all roles in their org (simplified)
-- We'll allow users to see all roles in orgs they belong to
create policy "Users can view roles in their organizations"
on public.user_roles
for select
to authenticated
using (
organization_id in (
select organization_id
from public.user_roles
where user_id = auth.uid()
)
);
-- Policy: Allow inserts (validation handled by helper functions/triggers)
create policy "Allow role assignments"
on public.user_roles
for insert
to authenticated
with check (true); -- Will be validated by application logic
-- Policy: Allow updates (validation handled by helper functions)
create policy "Allow role updates"
on public.user_roles
for update
to authenticated
using (true)
with check (true); -- Will be validated by application logic
-- Policy: Allow deletes (validation handled by helper functions)
create policy "Allow role deletions"
on public.user_roles
for delete
to authenticated
using (user_id != auth.uid()); -- Can't delete own role
-- ============================================================================
-- UPDATE HELPER FUNCTIONS TO HANDLE PERMISSIONS
-- ============================================================================
-- These functions run as SECURITY DEFINER and bypass RLS
-- They should handle the actual permission checks
-- Update the promote_to_admin function to check permissions properly
create or replace function public.promote_to_admin(
p_user_email text,
p_organization_id text
)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
v_user_id uuid;
v_caller_role text;
begin
-- Get caller's role (this function bypasses RLS)
select role into v_caller_role
from public.user_roles
where user_id = auth.uid()
and organization_id = p_organization_id;
-- Check if caller is admin
if v_caller_role != 'admin' then
raise exception 'Only admins can promote users';
end if;
-- Get user ID from email
select id into v_user_id
from auth.users
where email = p_user_email;
if v_user_id is null then
raise exception 'User not found: %', p_user_email;
end if;
-- Update role to admin
update public.user_roles
set role = 'admin',
assigned_by = auth.uid(),
assigned_at = now()
where user_id = v_user_id
and organization_id = p_organization_id;
return true;
end;
$$;
-- ============================================================================
-- UPDATE PROJECTS POLICIES TO USE SECURITY DEFINER FUNCTIONS
-- ============================================================================
-- Drop and recreate admin-related policies for projects table
drop policy if exists "Admins can view all organization projects" on public.projects;
drop policy if exists "Admins can update organization projects" on public.projects;
-- Simplified admin view policy
create policy "Admins can view all organization projects"
on public.projects
for select
to authenticated
using (
deleted_at is null
and (
creator_id = auth.uid() -- Own projects
or
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = projects.organization_id
and user_roles.role = 'admin'
)
)
);
-- Simplified admin update policy
create policy "Admins can update organization projects"
on public.projects
for update
to authenticated
using (
creator_id = auth.uid() -- Own projects
or
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = projects.organization_id
and user_roles.role = 'admin'
)
)
with check (
creator_id = auth.uid() -- Own projects
or
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = projects.organization_id
and user_roles.role = 'admin'
)
);
-- ============================================================================
-- UPDATE AUDIT LOGS POLICIES
-- ============================================================================
drop policy if exists "Admins can view organization audit logs" on public.project_audit_logs;
create policy "Admins can view organization audit logs"
on public.project_audit_logs
for select
to authenticated
using (
actor_id = auth.uid() -- Own actions
or
exists (
select 1
from public.projects
where projects.id = project_audit_logs.project_id
and projects.creator_id = auth.uid()
)
or
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = project_audit_logs.organization_id
and user_roles.role = 'admin'
)
);
-- ============================================================================
-- UPDATE RATE LIMITS POLICIES
-- ============================================================================
drop policy if exists "Admins can view organization rate limits" on public.rate_limits;
create policy "Admins can view organization rate limits"
on public.rate_limits
for select
to authenticated
using (
user_id = auth.uid() -- Own rate limits
or
exists (
select 1
from public.user_roles
where user_roles.user_id = auth.uid()
and user_roles.organization_id = rate_limits.organization_id
and user_roles.role = 'admin'
)
);
comment on policy "Users can view roles in their organizations" on public.user_roles is 'Allow users to view all roles in organizations they belong to';
@@ -0,0 +1,169 @@
-- Final fix for RLS infinite recursion
-- Solution: Make user_roles completely open for SELECT (no recursion)
-- Access control happens at the projects level, not at viewing roles
-- ============================================================================
-- DROP ALL EXISTING user_roles POLICIES
-- ============================================================================
drop policy if exists "Users can view their own roles" on public.user_roles;
drop policy if exists "Users can view roles in their organizations" on public.user_roles;
drop policy if exists "Allow role assignments" on public.user_roles;
drop policy if exists "Allow role updates" on public.user_roles;
drop policy if exists "Allow role deletions" on public.user_roles;
-- ============================================================================
-- SIMPLE NON-RECURSIVE POLICIES FOR user_roles
-- ============================================================================
-- Policy: All authenticated users can view all roles
-- This is safe because viewing roles doesn't grant access to projects
-- Project access is controlled by separate RLS policies on the projects table
create policy "Authenticated users can view all roles"
on public.user_roles
for select
to authenticated
using (true);
-- Policy: Prevent inserts via RLS (use helper functions instead)
-- This ensures role assignment goes through proper validation
create policy "No direct role inserts"
on public.user_roles
for insert
to authenticated
with check (false);
-- Policy: Prevent updates via RLS (use helper functions instead)
create policy "No direct role updates"
on public.user_roles
for update
to authenticated
using (false);
-- Policy: Prevent deletes via RLS (use helper functions instead)
create policy "No direct role deletes"
on public.user_roles
for delete
to authenticated
using (false);
-- ============================================================================
-- HELPER FUNCTION FOR ROLE ASSIGNMENT (bypasses RLS)
-- ============================================================================
-- Function to assign initial role (used by trigger)
create or replace function public.assign_user_role(
p_user_id uuid,
p_organization_id text,
p_role text
)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
begin
insert into public.user_roles (user_id, organization_id, role)
values (p_user_id, p_organization_id, p_role)
on conflict (user_id, organization_id) do nothing;
return true;
end;
$$;
grant execute on function public.assign_user_role to authenticated;
comment on function public.assign_user_role is 'Assign role to user (bypasses RLS)';
-- ============================================================================
-- UPDATE AUTO-ADMIN ASSIGNMENT TRIGGER TO USE NEW FUNCTION
-- ============================================================================
create or replace function public.auto_assign_first_admin()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
declare
v_org_id text;
v_user_count integer;
begin
-- Extract organization from user metadata
v_org_id := coalesce(
new.raw_user_meta_data->>'organization_id',
new.raw_user_meta_data->>'org_id',
new.raw_user_meta_data->>'hd', -- Google Workspace hosted domain
new.raw_app_meta_data->>'organization_id',
'default_org' -- Fallback for development/testing
);
-- Count existing users in this organization
select count(*)
into v_user_count
from public.user_roles
where organization_id = v_org_id;
-- Assign role based on whether this is first user
if v_user_count = 0 then
perform public.assign_user_role(new.id, v_org_id, 'admin');
raise notice 'Auto-assigned admin role to user % in organization %', new.email, v_org_id;
else
perform public.assign_user_role(new.id, v_org_id, 'builder');
raise notice 'Auto-assigned builder role to user % in organization %', new.email, v_org_id;
end if;
return new;
end;
$$;
-- ============================================================================
-- UPDATE promote_to_admin FUNCTION
-- ============================================================================
create or replace function public.promote_to_admin(
p_user_email text,
p_organization_id text
)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
v_user_id uuid;
v_caller_role text;
begin
-- Get caller's role (this function bypasses RLS)
select role into v_caller_role
from public.user_roles
where user_id = auth.uid()
and organization_id = p_organization_id;
-- Check if caller is admin
if v_caller_role != 'admin' then
raise exception 'Only admins can promote users';
end if;
-- Get user ID from email
select id into v_user_id
from auth.users
where email = p_user_email;
if v_user_id is null then
raise exception 'User not found: %', p_user_email;
end if;
-- Update role to admin (bypasses RLS because security definer)
update public.user_roles
set role = 'admin',
assigned_by = auth.uid(),
assigned_at = now()
where user_id = v_user_id
and organization_id = p_organization_id;
return true;
end;
$$;
comment on policy "Authenticated users can view all roles" on public.user_roles is 'Allow viewing roles - access control happens at projects level';
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}