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