# Whitelabel Branding & Domains System This document describes the comprehensive whitelabel system that allows organizations to customize their Black Canyon Tickets platform with their own branding and serve it on custom domains. ## Overview The whitelabel system provides: 1. **Host-based Organization Resolution** - Automatically detects organization from the current domain 2. **Dynamic Theming** - Per-organization color themes applied at runtime without FOUC 3. **Custom Domain Management** - Admin UI for adding and verifying custom domains 4. **Branding Management** - Upload logos and customize color schemes with live preview 5. **DNS Verification** - Secure domain ownership verification via TXT records ## Architecture ### Backend (Firebase Functions) #### Domain Resolution API - **Endpoint**: `GET /api/domains/resolve?host=tickets.acme.com` - **Purpose**: Resolves organization data from hostname - **Returns**: Organization ID, branding data, and domain list - **Fallback**: Supports subdomain pattern (e.g., `acme.bct.dev`) #### Domain Verification APIs - **Request Verification**: `POST /api/domains/request-verification` - Generates DNS TXT record token - Updates organization domain list - Returns DNS configuration instructions - **Verify Domain**: `POST /api/domains/verify` - Checks DNS TXT record for verification token - Updates domain status to verified - Enables domain for live use #### Firestore Schema ```typescript // Collection: organizations/{orgId} interface Organization { id: string; name: string; slug: string; branding: { logoUrl?: string; faviconUrl?: string; theme: { accent: string; // e.g., '#F0C457' bgCanvas: string; // e.g., '#2B2D2F' bgSurface: string; // e.g., '#34373A' textPrimary: string; // e.g., '#F1F3F5' textSecondary: string; // e.g., '#C9D0D4' } }; domains: Array<{ host: string; // e.g., 'tickets.acme.com' verified: boolean; createdAt: string; verifiedAt?: string; verificationToken?: string; // DNS TXT record value }>; } ``` ### Frontend Architecture #### Organization Bootstrap System - **Early Resolution**: Runs before React mounts to prevent FOUC - **Theme Application**: Applies CSS custom properties immediately - **Logo/Favicon**: Updates page branding elements - **Store Integration**: Bridges bootstrap data to React state #### Theme System - **CSS Variables**: All colors mapped to custom properties - **Tailwind Integration**: Utilities consume CSS variables - **Live Preview**: Real-time theme changes during admin editing - **Accessibility**: Validates contrast ratios (WCAG AA) #### State Management - **Zustand Store**: Reactive organization data management - **Context Provider**: React integration and effect handling - **Subscriptions**: Automatic theme updates on organization changes ## File Structure ``` src/ ├── stores/ │ └── organizationStore.ts # Zustand store for org data ├── theme/ │ ├── orgTheme.ts # Theme application utilities │ └── orgBootstrap.ts # Early resolution system ├── contexts/ │ └── OrganizationContext.tsx # React provider integration ├── features/org/ │ ├── BrandingSettings.tsx # Logo/theme management UI │ └── DomainSettings.tsx # Custom domain management UI └── tests/ └── whitelabel.spec.ts # Comprehensive test suite functions/src/ └── domains.ts # Cloud Functions for domain APIs ``` ## Usage Guide ### For Organizations #### Setting Up Branding 1. Navigate to Organization → Branding in the user menu 2. Upload your organization logo (PNG, JPG, SVG up to 2MB) 3. Customize theme colors using color pickers 4. Enable "Live Preview" to see changes in real-time 5. Save changes to apply across all sessions #### Adding Custom Domains 1. Navigate to Organization → Domains in the user menu 2. Click "Add Custom Domain" and enter your domain (e.g., `tickets.acme.com`) 3. Follow DNS configuration instructions: - Add TXT record: `_bct-verification.tickets.acme.com` - Set value to the provided verification token - Wait for DNS propagation (up to 24 hours) 4. Click "Check Verification" to validate DNS setup 5. Once verified, your domain is ready for live use ### For Developers #### Theme Development ```typescript import { applyOrgTheme, generateThemeCSS } from '../theme/orgTheme'; // Apply theme programmatically applyOrgTheme({ accent: '#FF6B35', bgCanvas: '#1A1B1E', bgSurface: '#2A2B2E', textPrimary: '#FFFFFF', textSecondary: '#B0B0B0', }); // Generate CSS for external use const css = generateThemeCSS(theme); ``` #### Organization Data Access ```typescript import { useCurrentOrganization } from '../contexts/OrganizationContext'; import { useOrganizationStore } from '../stores/organizationStore'; // In React components const { organization, isLoading, error } = useCurrentOrganization(); // Direct store access const currentOrg = useOrganizationStore(state => state.currentOrg); ``` #### Custom Domain Testing ```typescript // Mock domain resolution in tests await page.route('**/resolveDomain*', async route => { await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ orgId: 'test-org', name: 'Test Organization', branding: { theme: { /* colors */ } }, domains: [] }) }); }); ``` ## Configuration ### Environment Variables #### Development ```bash # Local Firebase Functions FUNCTIONS_BASE_URL=http://localhost:5001/bct-whitelabel-0825/us-central1 # Enable development mode (mocks DNS verification) NODE_ENV=development FUNCTIONS_EMULATOR=true ``` #### Production ```bash # Production Firebase Functions FUNCTIONS_BASE_URL=https://us-central1-bct-whitelabel-0825.cloudfunctions.net # Real DNS verification NODE_ENV=production ``` ### CSS Variables Mapping The theme system maps organization colors to these CSS custom properties: ```css :root { --color-accent-500: /* theme.accent */ --color-bg-canvas: /* theme.bgCanvas */ --color-bg-surface: /* theme.bgSurface */ --color-text-primary: /* theme.textPrimary */ --color-text-secondary: /* theme.textSecondary */ } ``` All Tailwind utilities (e.g., `bg-accent-500`, `text-primary`) automatically use these variables. ## Testing ### Running Tests ```bash # Run whitelabel-specific tests npm run test -- whitelabel.spec.ts # Run with UI for debugging npm run test:ui -- whitelabel.spec.ts # Run in headed mode to see browser npm run test:headed -- whitelabel.spec.ts ``` ### Test Coverage - **Domain Resolution**: Host-based organization lookup - **Theme Application**: CSS variable injection and FOUC prevention - **Branding UI**: Logo upload, color editing, live preview - **Domain Management**: Add/verify/delete custom domains - **Error Handling**: Graceful fallbacks for missing organizations - **Accessibility**: Color contrast validation ### Mock Data Tests use realistic mock organizations and domain data. See `tests/whitelabel.spec.ts` for examples. ## Security Considerations ### Domain Verification - **DNS TXT Records**: Prevents unauthorized domain claiming - **Token Generation**: Cryptographically secure verification tokens - **Rate Limiting**: Built into Firebase Functions - **Validation**: Strict domain format checking ### Asset Upload - **File Types**: Restricted to images only (PNG, JPG, SVG) - **Size Limits**: 2MB maximum file size - **Storage**: Firebase Storage with security rules - **Sanitization**: Image processing to prevent malicious uploads ### Theme Injection - **XSS Prevention**: Color values validated as hex codes only - **CSS Injection**: No arbitrary CSS allowed, only predefined variables - **Contrast Validation**: Ensures accessibility compliance ## Performance ### Bootstrap Optimization - **Early Execution**: Runs before React hydration - **Caching**: Organization data cached in localStorage - **Minimal Dependencies**: Lightweight bootstrap script - **Error Resilience**: Continues with defaults if resolution fails ### Theme Application - **CSS Variables**: More efficient than class switching - **No Re-renders**: Theme changes don't trigger React re-renders - **Bundle Size**: Design tokens reduce CSS payload - **Memory Usage**: Minimal runtime footprint ## Troubleshooting ### Domain Verification Issues 1. **DNS Propagation**: Can take up to 24 hours globally 2. **Record Format**: Ensure TXT record name includes subdomain 3. **Value Accuracy**: Copy verification token exactly as provided 4. **TTL Settings**: Use 300 seconds for faster propagation during setup ### Theme Not Applying 1. **Organization Resolution**: Check browser console for resolution errors 2. **CSS Variables**: Inspect element to verify variables are set 3. **Cache Issues**: Clear localStorage and refresh page 4. **API Connectivity**: Verify Functions endpoints are accessible ### Logo Display Issues 1. **File Format**: Use PNG, JPG, or SVG only 2. **CORS Policy**: Ensure image URLs allow cross-origin requests 3. **Size Optimization**: Large images may slow page load 4. **Fallback Handling**: App continues without logo if load fails ## Future Enhancements ### Planned Features - **Favicon Customization**: Dynamic favicon updates - **Email Templates**: Per-organization email branding - **Font Selection**: Custom typography options - **Advanced Themes**: Gradient and pattern support - **White-label Mobile**: Native app theming - **Analytics Integration**: Usage tracking per organization ### API Improvements - **Real DNS Resolution**: Replace mock DNS with actual lookups - **CDN Integration**: Optimize asset delivery - **Webhook Support**: Real-time domain status updates - **Bulk Operations**: Mass domain import/export - **API Keys**: Third-party integration authentication --- ## Quick Start Checklist For new organizations wanting to set up whitelabel branding: - [ ] Upload organization logo in Branding Settings - [ ] Customize theme colors to match brand - [ ] Test live preview functionality - [ ] Add custom domain in Domain Settings - [ ] Configure DNS TXT record with provided token - [ ] Verify domain ownership - [ ] Test live site on custom domain - [ ] Update any hardcoded URLs in marketing materials For developers integrating whitelabel features: - [ ] Review organization store and context usage - [ ] Understand theme CSS variable system - [ ] Test with multiple mock organizations - [ ] Implement proper error boundaries - [ ] Add accessibility validation for custom themes - [ ] Write tests for new organization-specific features