|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { member, organization } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { and, eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { z } from 'zod' |
| 7 | +import { AuditAction, AuditResourceType, recordAudit } from '@/lib/audit/log' |
| 8 | +import { getSession } from '@/lib/auth' |
| 9 | +import { isEnterpriseOrgAdminOrOwner } from '@/lib/billing/core/subscription' |
| 10 | +import type { OrganizationWhitelabelSettings } from '@/lib/branding/types' |
| 11 | + |
| 12 | +const logger = createLogger('WhitelabelAPI') |
| 13 | + |
| 14 | +const HEX_COLOR_REGEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i |
| 15 | + |
| 16 | +const updateWhitelabelSchema = z.object({ |
| 17 | + brandName: z.string().trim().max(64, 'Brand name must be 64 characters or fewer').optional(), |
| 18 | + logoUrl: z.string().url('Logo URL must be a valid URL').nullable().optional(), |
| 19 | + primaryColor: z |
| 20 | + .string() |
| 21 | + .regex(HEX_COLOR_REGEX, 'Primary color must be a valid hex color (e.g. #701ffc)') |
| 22 | + .nullable() |
| 23 | + .optional(), |
| 24 | + primaryHoverColor: z |
| 25 | + .string() |
| 26 | + .regex(HEX_COLOR_REGEX, 'Primary hover color must be a valid hex color') |
| 27 | + .nullable() |
| 28 | + .optional(), |
| 29 | + accentColor: z |
| 30 | + .string() |
| 31 | + .regex(HEX_COLOR_REGEX, 'Accent color must be a valid hex color') |
| 32 | + .nullable() |
| 33 | + .optional(), |
| 34 | + accentHoverColor: z |
| 35 | + .string() |
| 36 | + .regex(HEX_COLOR_REGEX, 'Accent hover color must be a valid hex color') |
| 37 | + .nullable() |
| 38 | + .optional(), |
| 39 | + supportEmail: z |
| 40 | + .string() |
| 41 | + .email('Support email must be a valid email address') |
| 42 | + .nullable() |
| 43 | + .optional(), |
| 44 | + documentationUrl: z.string().url('Documentation URL must be a valid URL').nullable().optional(), |
| 45 | + termsUrl: z.string().url('Terms URL must be a valid URL').nullable().optional(), |
| 46 | + privacyUrl: z.string().url('Privacy URL must be a valid URL').nullable().optional(), |
| 47 | + hidePoweredBySim: z.boolean().optional(), |
| 48 | +}) |
| 49 | + |
| 50 | +/** |
| 51 | + * GET /api/organizations/[id]/whitelabel |
| 52 | + * Returns the organization's whitelabel settings. |
| 53 | + * Accessible by any member of the organization. |
| 54 | + */ |
| 55 | +export async function GET(_request: NextRequest, { params }: { params: Promise<{ id: string }> }) { |
| 56 | + try { |
| 57 | + const session = await getSession() |
| 58 | + |
| 59 | + if (!session?.user?.id) { |
| 60 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 61 | + } |
| 62 | + |
| 63 | + const { id: organizationId } = await params |
| 64 | + |
| 65 | + const [memberEntry] = await db |
| 66 | + .select({ id: member.id }) |
| 67 | + .from(member) |
| 68 | + .where(and(eq(member.organizationId, organizationId), eq(member.userId, session.user.id))) |
| 69 | + .limit(1) |
| 70 | + |
| 71 | + if (!memberEntry) { |
| 72 | + return NextResponse.json( |
| 73 | + { error: 'Forbidden - Not a member of this organization' }, |
| 74 | + { status: 403 } |
| 75 | + ) |
| 76 | + } |
| 77 | + |
| 78 | + const [org] = await db |
| 79 | + .select({ whitelabelSettings: organization.whitelabelSettings }) |
| 80 | + .from(organization) |
| 81 | + .where(eq(organization.id, organizationId)) |
| 82 | + .limit(1) |
| 83 | + |
| 84 | + if (!org) { |
| 85 | + return NextResponse.json({ error: 'Organization not found' }, { status: 404 }) |
| 86 | + } |
| 87 | + |
| 88 | + return NextResponse.json({ |
| 89 | + success: true, |
| 90 | + data: (org.whitelabelSettings ?? {}) as OrganizationWhitelabelSettings, |
| 91 | + }) |
| 92 | + } catch (error) { |
| 93 | + logger.error('Failed to get whitelabel settings', { error }) |
| 94 | + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +/** |
| 99 | + * PUT /api/organizations/[id]/whitelabel |
| 100 | + * Updates the organization's whitelabel settings. |
| 101 | + * Requires enterprise plan and owner/admin role. |
| 102 | + */ |
| 103 | +export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { |
| 104 | + try { |
| 105 | + const session = await getSession() |
| 106 | + |
| 107 | + if (!session?.user?.id) { |
| 108 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 109 | + } |
| 110 | + |
| 111 | + const { id: organizationId } = await params |
| 112 | + |
| 113 | + const body = await request.json() |
| 114 | + const parsed = updateWhitelabelSchema.safeParse(body) |
| 115 | + |
| 116 | + if (!parsed.success) { |
| 117 | + return NextResponse.json( |
| 118 | + { error: parsed.error.errors[0]?.message ?? 'Invalid request body' }, |
| 119 | + { status: 400 } |
| 120 | + ) |
| 121 | + } |
| 122 | + |
| 123 | + const [memberEntry] = await db |
| 124 | + .select({ role: member.role }) |
| 125 | + .from(member) |
| 126 | + .where(and(eq(member.organizationId, organizationId), eq(member.userId, session.user.id))) |
| 127 | + .limit(1) |
| 128 | + |
| 129 | + if (!memberEntry) { |
| 130 | + return NextResponse.json( |
| 131 | + { error: 'Forbidden - Not a member of this organization' }, |
| 132 | + { status: 403 } |
| 133 | + ) |
| 134 | + } |
| 135 | + |
| 136 | + if (memberEntry.role !== 'owner' && memberEntry.role !== 'admin') { |
| 137 | + return NextResponse.json( |
| 138 | + { error: 'Forbidden - Only organization owners and admins can update whitelabel settings' }, |
| 139 | + { status: 403 } |
| 140 | + ) |
| 141 | + } |
| 142 | + |
| 143 | + const hasAccess = await isEnterpriseOrgAdminOrOwner(session.user.id) |
| 144 | + |
| 145 | + if (!hasAccess) { |
| 146 | + return NextResponse.json( |
| 147 | + { error: 'Whitelabeling is available on Enterprise plans only' }, |
| 148 | + { status: 403 } |
| 149 | + ) |
| 150 | + } |
| 151 | + |
| 152 | + const [currentOrg] = await db |
| 153 | + .select({ name: organization.name, whitelabelSettings: organization.whitelabelSettings }) |
| 154 | + .from(organization) |
| 155 | + .where(eq(organization.id, organizationId)) |
| 156 | + .limit(1) |
| 157 | + |
| 158 | + if (!currentOrg) { |
| 159 | + return NextResponse.json({ error: 'Organization not found' }, { status: 404 }) |
| 160 | + } |
| 161 | + |
| 162 | + const current: OrganizationWhitelabelSettings = currentOrg.whitelabelSettings ?? {} |
| 163 | + const incoming = parsed.data |
| 164 | + |
| 165 | + const merged: OrganizationWhitelabelSettings = { ...current } |
| 166 | + |
| 167 | + for (const key of Object.keys(incoming) as Array<keyof typeof incoming>) { |
| 168 | + const value = incoming[key] |
| 169 | + if (value === null) { |
| 170 | + delete merged[key as keyof OrganizationWhitelabelSettings] |
| 171 | + } else if (value !== undefined) { |
| 172 | + ;(merged as Record<string, unknown>)[key] = value |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + const [updated] = await db |
| 177 | + .update(organization) |
| 178 | + .set({ whitelabelSettings: merged, updatedAt: new Date() }) |
| 179 | + .where(eq(organization.id, organizationId)) |
| 180 | + .returning({ whitelabelSettings: organization.whitelabelSettings }) |
| 181 | + |
| 182 | + recordAudit({ |
| 183 | + workspaceId: null, |
| 184 | + actorId: session.user.id, |
| 185 | + action: AuditAction.ORGANIZATION_UPDATED, |
| 186 | + resourceType: AuditResourceType.ORGANIZATION, |
| 187 | + resourceId: organizationId, |
| 188 | + actorName: session.user.name ?? undefined, |
| 189 | + actorEmail: session.user.email ?? undefined, |
| 190 | + resourceName: currentOrg.name, |
| 191 | + description: 'Updated organization whitelabel settings', |
| 192 | + metadata: { changes: Object.keys(incoming) }, |
| 193 | + request, |
| 194 | + }) |
| 195 | + |
| 196 | + return NextResponse.json({ |
| 197 | + success: true, |
| 198 | + data: (updated.whitelabelSettings ?? {}) as OrganizationWhitelabelSettings, |
| 199 | + }) |
| 200 | + } catch (error) { |
| 201 | + logger.error('Failed to update whitelabel settings', { error }) |
| 202 | + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
| 203 | + } |
| 204 | +} |
0 commit comments