From b78d05b89fbfe0f13d12f4faeeae3683b34d1774 Mon Sep 17 00:00:00 2001 From: Chris Caruso Date: Sat, 31 Jan 2026 14:42:37 -0600 Subject: [PATCH] feat: implement SupaBuilder - enterprise self-service Supabase project provisioning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit • 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 --- examples/supa-builder/.gitignore | 41 + examples/supa-builder/README.md | 551 ++ examples/supa-builder/TODO.md | 34 + examples/supa-builder/app/actions/projects.ts | 414 + .../supa-builder/app/auth/callback/route.ts | 31 + examples/supa-builder/app/favicon.ico | Bin 0 -> 25931 bytes examples/supa-builder/app/globals.css | 26 + examples/supa-builder/app/layout.tsx | 34 + examples/supa-builder/app/login/page.tsx | 68 + examples/supa-builder/app/page.tsx | 111 + .../supa-builder/app/projects/[id]/page.tsx | 224 + .../supa-builder/app/projects/new/page.tsx | 80 + examples/supa-builder/app/projects/page.tsx | 93 + .../supa-builder/components/LoginButton.tsx | 91 + .../supa-builder/components/ProjectForm.tsx | 192 + .../supa-builder/components/ProjectTable.tsx | 240 + examples/supa-builder/eslint.config.mjs | 18 + examples/supa-builder/lib/supabase/client.ts | 8 + .../supa-builder/lib/supabase/middleware.ts | 36 + examples/supa-builder/lib/supabase/server.ts | 29 + examples/supa-builder/middleware.ts | 19 + examples/supa-builder/next.config.ts | 7 + examples/supa-builder/package-lock.json | 6688 +++++++++++++++++ examples/supa-builder/package.json | 28 + examples/supa-builder/postcss.config.mjs | 7 + examples/supa-builder/public/file.svg | 1 + examples/supa-builder/public/globe.svg | 1 + examples/supa-builder/public/next.svg | 1 + examples/supa-builder/public/vercel.svg | 1 + examples/supa-builder/public/window.svg | 1 + examples/supa-builder/supabase/.gitignore | 8 + examples/supa-builder/supabase/config.toml | 359 + .../supa-builder/supabase/config.toml.backup | 76 + .../supabase/functions/_shared/cors.ts | 18 + .../supabase/functions/_shared/types.ts | 143 + .../functions/create-project/.supabaserc | 3 + .../functions/create-project/deno.json | 5 + .../functions/create-project/index.ts | 391 + .../20260131000001_initial_schema.sql | 277 + .../20260131000002_rls_policies.sql | 233 + .../20260131000003_helper_functions.sql | 321 + .../20260131000004_auto_admin_assignment.sql | 123 + .../20260131000005_fix_rls_recursion.sql | 222 + ...20260131000006_fix_rls_recursion_final.sql | 169 + examples/supa-builder/tsconfig.json | 34 + 45 files changed, 11457 insertions(+) create mode 100644 examples/supa-builder/.gitignore create mode 100644 examples/supa-builder/README.md create mode 100644 examples/supa-builder/TODO.md create mode 100644 examples/supa-builder/app/actions/projects.ts create mode 100644 examples/supa-builder/app/auth/callback/route.ts create mode 100644 examples/supa-builder/app/favicon.ico create mode 100644 examples/supa-builder/app/globals.css create mode 100644 examples/supa-builder/app/layout.tsx create mode 100644 examples/supa-builder/app/login/page.tsx create mode 100644 examples/supa-builder/app/page.tsx create mode 100644 examples/supa-builder/app/projects/[id]/page.tsx create mode 100644 examples/supa-builder/app/projects/new/page.tsx create mode 100644 examples/supa-builder/app/projects/page.tsx create mode 100644 examples/supa-builder/components/LoginButton.tsx create mode 100644 examples/supa-builder/components/ProjectForm.tsx create mode 100644 examples/supa-builder/components/ProjectTable.tsx create mode 100644 examples/supa-builder/eslint.config.mjs create mode 100644 examples/supa-builder/lib/supabase/client.ts create mode 100644 examples/supa-builder/lib/supabase/middleware.ts create mode 100644 examples/supa-builder/lib/supabase/server.ts create mode 100644 examples/supa-builder/middleware.ts create mode 100644 examples/supa-builder/next.config.ts create mode 100644 examples/supa-builder/package-lock.json create mode 100644 examples/supa-builder/package.json create mode 100644 examples/supa-builder/postcss.config.mjs create mode 100644 examples/supa-builder/public/file.svg create mode 100644 examples/supa-builder/public/globe.svg create mode 100644 examples/supa-builder/public/next.svg create mode 100644 examples/supa-builder/public/vercel.svg create mode 100644 examples/supa-builder/public/window.svg create mode 100644 examples/supa-builder/supabase/.gitignore create mode 100644 examples/supa-builder/supabase/config.toml create mode 100644 examples/supa-builder/supabase/config.toml.backup create mode 100644 examples/supa-builder/supabase/functions/_shared/cors.ts create mode 100644 examples/supa-builder/supabase/functions/_shared/types.ts create mode 100644 examples/supa-builder/supabase/functions/create-project/.supabaserc create mode 100644 examples/supa-builder/supabase/functions/create-project/deno.json create mode 100644 examples/supa-builder/supabase/functions/create-project/index.ts create mode 100644 examples/supa-builder/supabase/migrations/20260131000001_initial_schema.sql create mode 100644 examples/supa-builder/supabase/migrations/20260131000002_rls_policies.sql create mode 100644 examples/supa-builder/supabase/migrations/20260131000003_helper_functions.sql create mode 100644 examples/supa-builder/supabase/migrations/20260131000004_auto_admin_assignment.sql create mode 100644 examples/supa-builder/supabase/migrations/20260131000005_fix_rls_recursion.sql create mode 100644 examples/supa-builder/supabase/migrations/20260131000006_fix_rls_recursion_final.sql create mode 100644 examples/supa-builder/tsconfig.json diff --git a/examples/supa-builder/.gitignore b/examples/supa-builder/.gitignore new file mode 100644 index 00000000000..5ef6a520780 --- /dev/null +++ b/examples/supa-builder/.gitignore @@ -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 diff --git a/examples/supa-builder/README.md b/examples/supa-builder/README.md new file mode 100644 index 00000000000..f3c4808e41a --- /dev/null +++ b/examples/supa-builder/README.md @@ -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 +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) diff --git a/examples/supa-builder/TODO.md b/examples/supa-builder/TODO.md new file mode 100644 index 00000000000..1772266010d --- /dev/null +++ b/examples/supa-builder/TODO.md @@ -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 + diff --git a/examples/supa-builder/app/actions/projects.ts b/examples/supa-builder/app/actions/projects.ts new file mode 100644 index 00000000000..a44f8694a20 --- /dev/null +++ b/examples/supa-builder/app/actions/projects.ts @@ -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 { + success: boolean + data?: T + error?: string +} + +// ============================================================================ +// CREATE PROJECT +// ============================================================================ + +export async function createProject( + input: CreateProjectInput +): Promise> { + 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> { + 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> { + 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 { + 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 { + 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 { + 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> { + 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', + } + } +} diff --git a/examples/supa-builder/app/auth/callback/route.ts b/examples/supa-builder/app/auth/callback/route.ts new file mode 100644 index 00000000000..904ba8bedbb --- /dev/null +++ b/examples/supa-builder/app/auth/callback/route.ts @@ -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`) +} diff --git a/examples/supa-builder/app/favicon.ico b/examples/supa-builder/app/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..718d6fea4835ec2d246af9800eddb7ffb276240c GIT binary patch literal 25931 zcmeHv30#a{`}aL_*G&7qml|y<+KVaDM2m#dVr!KsA!#An?kSQM(q<_dDNCpjEux83 zLb9Z^XxbDl(w>%i@8hT6>)&Gu{h#Oeyszu?xtw#Zb1mO{pgX9699l+Qppw7jXaYf~-84xW z)w4x8?=youko|}Vr~(D$UXIbiXABHh`p1?nn8Po~fxRJv}|0e(BPs|G`(TT%kKVJAdg5*Z|x0leQq0 zkdUBvb#>9F()jo|T~kx@OM8$9wzs~t2l;K=woNssA3l6|sx2r3+kdfVW@e^8e*E}v zA1y5{bRi+3Z`uD3{F7LgFJDdvm;nJilkzDku>BwXH(8ItVCXk*-lSJnR?-2UN%hJ){&rlvg`CDTj z)Bzo!3v7Ou#83zEDEFc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builder/app/globals.css b/examples/supa-builder/app/globals.css new file mode 100644 index 00000000000..a2dc41ecee5 --- /dev/null +++ b/examples/supa-builder/app/globals.css @@ -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; +} diff --git a/examples/supa-builder/app/layout.tsx b/examples/supa-builder/app/layout.tsx new file mode 100644 index 00000000000..f7fa87eb875 --- /dev/null +++ b/examples/supa-builder/app/layout.tsx @@ -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 ( + + + {children} + + + ); +} diff --git a/examples/supa-builder/app/login/page.tsx b/examples/supa-builder/app/login/page.tsx new file mode 100644 index 00000000000..f14d90cfdad --- /dev/null +++ b/examples/supa-builder/app/login/page.tsx @@ -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 ( +
+
+ {/* Header */} +
+

+ SupaBuilder +

+

+ Sign in to manage your Supabase projects +

+
+ + {/* Login Card */} +
+

+ Sign In +

+ + {/* SSO Login Buttons */} +
+ + + {/* Add more providers as needed */} + {/* */} + {/* */} +
+ + {/* Info Text */} +
+

Sign in with your organization account

+
+
+ + {/* Footer Info */} +
+

+ First-time users: The first person to sign in from your organization will automatically receive admin privileges. +

+
+
+
+ ) +} diff --git a/examples/supa-builder/app/page.tsx b/examples/supa-builder/app/page.tsx new file mode 100644 index 00000000000..8f3a0cfdce9 --- /dev/null +++ b/examples/supa-builder/app/page.tsx @@ -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 ( +
+
+ {/* Hero Section */} +
+

+ SupaBuilder +

+

+ Enterprise Self-Service Supabase Project Provisioning +

+

+ Empower your team to create and manage Supabase projects with proper governance, + audit trails, and role-based access control. +

+
+ + {/* CTA Button */} +
+ + Sign In to Get Started + +
+ + {/* Features Grid */} +
+
+
🚀
+

Self-Service

+

+ Builders can create projects instantly without waiting for IT approval +

+
+ +
+
🔒
+

Secure by Default

+

+ Role-based access, encrypted credentials, and complete audit trails +

+
+ +
+
⚡
+

Rate Limited

+

+ Built-in protections prevent abuse with 5 projects per hour limit +

+
+
+ + {/* Key Features */} +
+

Key Features

+
    +
  • + ✓ + + SSO Authentication: Seamless sign-in with Google, Azure AD, or any OAuth provider + +
  • +
  • + ✓ + + Role-Based Access: Admins manage all projects, builders manage their own + +
  • +
  • + ✓ + + Automatic Provisioning: Projects created in 1-2 minutes via Management API + +
  • +
  • + ✓ + + Audit Logging: Complete immutable history of all project operations + +
  • +
+
+ + {/* Footer */} +
+

Built with Supabase • Next.js • TypeScript

+
+
+
+ ) +} diff --git a/examples/supa-builder/app/projects/[id]/page.tsx b/examples/supa-builder/app/projects/[id]/page.tsx new file mode 100644 index 00000000000..6462e248301 --- /dev/null +++ b/examples/supa-builder/app/projects/[id]/page.tsx @@ -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 ( + + {status.charAt(0).toUpperCase() + status.slice(1)} + + ) + } + + return ( +
+ {/* Header */} +
+ + ← Back to Projects + +
+
+

{project.project_name}

+

Project Reference: {project.project_ref}

+
+ {getStatusBadge(project.status)} +
+
+ + {/* Project Details Grid */} +
+ {/* Basic Information */} +
+

Basic Information

+
+
+
Organization ID
+
{project.organization_id}
+
+
+
Region
+
{project.region}
+
+
+
Created By
+
{project.creator_email}
+
+
+
Created At
+
+ {new Date(project.created_at).toLocaleString()} +
+
+ {project.purpose && ( +
+
Purpose
+
{project.purpose}
+
+ )} +
+
+ + {/* Credentials */} +
+

API Credentials

+
+
+ + + https://{project.project_ref}.supabase.co + +
+
+ + + {project.anon_key} + +
+ {isAdmin && ( +
+

+ Admin Note: Service role key is encrypted in the database. + Contact system administrator for access. +

+
+ )} +
+
+
+ + {/* Description */} + {project.description && ( +
+

Description

+

{project.description}

+
+ )} + + {/* Quick Links */} + + + {/* Audit Logs */} + {auditLogs && auditLogs.length > 0 && ( +
+

Recent Activity

+
+ {auditLogs.map((log) => ( +
+ + {log.action} + +
+

+ {log.actor_email} +

+

+ {new Date(log.created_at).toLocaleString()} +

+
+
+ ))} +
+
+ )} +
+ ) +} diff --git a/examples/supa-builder/app/projects/new/page.tsx b/examples/supa-builder/app/projects/new/page.tsx new file mode 100644 index 00000000000..c98c4aa72cd --- /dev/null +++ b/examples/supa-builder/app/projects/new/page.tsx @@ -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 ( +
+
+

No organization assigned

+

Please contact an administrator to assign you to an organization.

+
+
+ ) + } + + // Get admin project region from env or default + const adminProjectRegion = process.env.ADMIN_PROJECT_REGION || 'us-east-1' + + return ( +
+ {/* Header */} +
+ + ← Back to Projects + +

Create New Project

+

+ Create a new Supabase Pico project for your organization +

+
+ + {/* Info Box */} +
+

What you need to know

+
    +
  • • Projects are created on the Pico (free) tier
  • +
  • • Project provisioning typically completes in 1-2 minutes
  • +
  • • All projects include PostgreSQL database, Auth, Storage, and Realtime
  • +
  • • Projects will be created in the {adminProjectRegion} region
  • +
+
+ + {/* Form */} + +
+ ) +} diff --git a/examples/supa-builder/app/projects/page.tsx b/examples/supa-builder/app/projects/page.tsx new file mode 100644 index 00000000000..f3da6792118 --- /dev/null +++ b/examples/supa-builder/app/projects/page.tsx @@ -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 ( +
+
+

Error loading projects

+

{result.error}

+
+
+ ) + } + + 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 ( +
+ {/* Header */} +
+
+

Projects

+

+ Manage your Supabase projects + {isAdmin && Admin} +

+
+ + Create Project + +
+ + {/* User Info */} +
+

+ Logged in as: {user.email} +

+
+ + {/* Projects Table */} + + + {/* Footer Info */} +
+

About SupaBuilder

+

+ 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. +

+
+
+ ) +} diff --git a/examples/supa-builder/components/LoginButton.tsx b/examples/supa-builder/components/LoginButton.tsx new file mode 100644 index 00000000000..4a886d6645a --- /dev/null +++ b/examples/supa-builder/components/LoginButton.tsx @@ -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(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 ( +
+ + + {error && ( +

+ {error} +

+ )} +
+ ) +} diff --git a/examples/supa-builder/components/ProjectForm.tsx b/examples/supa-builder/components/ProjectForm.tsx new file mode 100644 index 00000000000..e8f654b65cc --- /dev/null +++ b/examples/supa-builder/components/ProjectForm.tsx @@ -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(null) + const [formData, setFormData] = useState({ + 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 + ) => { + const { name, value } = e.target + setFormData((prev) => ({ ...prev, [name]: value })) + } + + return ( +
+ {/* Error Display */} + {error && ( +
+

Error

+

{error}

+
+ )} + + {/* Project Name */} +
+ + +

+ 3-63 characters, lowercase letters, numbers, and hyphens +

+
+ + {/* Hidden fields - automatically set */} + + + + {/* Purpose */} +
+ + +

+ Optional: What will this project be used for? +

+
+ + {/* Description */} +
+ +