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 00000000000..718d6fea483 Binary files /dev/null and b/examples/supa-builder/app/favicon.ico differ diff --git a/examples/supa-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 */} +
+ +