All files / src/lib auto-provision-organization.ts

0% Statements 0/153
100% Branches 1/1
100% Functions 1/1
0% Lines 0/153

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Auto-Provision Organization Service
 *
 * Creates a personal organization for new users during signup.
 * This ensures every user has a billing context from day one.
 *
 * Security considerations (per enterprise standards):
 * - Transaction safety: Uses database transactions for atomicity
 * - Input sanitization: Prevents XSS in organization names
 * - Unique slug generation: Handles collisions with retry logic
 * - Audit logging: Tracks all auto-provisioning events
 * - Rate limiting: Relies on auth rate limits (no additional limits needed)
 *
 * @see https://owasp.org/www-project-web-security-testing-guide/
 */
 
import { logger } from "@snapback/infrastructure";
import { nanoid } from "nanoid";
import { type AuditEventType, trackEvent } from "./audit";
 
// Configuration
const MAX_SLUG_RETRIES = 5;
const SLUG_SUFFIX_LENGTH = 6;
const MAX_ORG_NAME_LENGTH = 100;
const MAX_SLUG_LENGTH = 50;
 
/**
 * User object from Better Auth hook
 */
export interface BetterAuthUser {
	id: string;
	email: string;
	name?: string;
	emailVerified?: boolean;
	[key: string]: unknown;
}
 
/**
 * Result of auto-provisioning
 */
export interface AutoProvisionResult {
	success: boolean;
	organizationId?: string;
	organizationSlug?: string;
	error?: string;
}
 
/**
 * Sanitize organization name to prevent XSS and ensure validity
 * - Strips HTML tags
 * - Limits length
 * - Removes control characters
 */
function sanitizeOrgName(name: string): string {
	return (
		name
			// Remove HTML tags
			.replace(/<[^>]*>/g, "")
			// Remove control characters
			.replace(/[\x00-\x1f\x7f]/g, "")
			// Normalize whitespace
			.replace(/\s+/g, " ")
			.trim()
			// Limit length
			.slice(0, MAX_ORG_NAME_LENGTH)
	);
}
 
/**
 * Generate URL-safe slug from name
 */
function generateSlug(name: string): string {
	return (
		name
			.toLowerCase()
			// Replace special characters with hyphens
			.replace(/[^a-z0-9]+/g, "-")
			// Remove leading/trailing hyphens
			.replace(/^-+|-+$/g, "")
			// Limit length
			.slice(0, MAX_SLUG_LENGTH - SLUG_SUFFIX_LENGTH - 1)
	);
}
 
/**
 * Generate unique slug with collision handling
 */
async function generateUniqueSlug(db: any, combinedSchema: any, baseName: string): Promise<string> {
	const { sql } = await import("drizzle-orm");
	const { organization } = combinedSchema;
	const baseSlug = generateSlug(baseName);
 
	for (let attempt = 0; attempt < MAX_SLUG_RETRIES; attempt++) {
		const slug = attempt === 0 ? baseSlug : `${baseSlug}-${nanoid(SLUG_SUFFIX_LENGTH)}`;
 
		// Check for collision
		const existing = await db
			.select({ id: organization.id })
			.from(organization)
			.where(sql`${organization.slug} = ${slug}`)
			.limit(1);
 
		if (existing.length === 0) {
			return slug;
		}
 
		logger.debug("Slug collision detected, retrying", { slug, attempt });
	}
 
	// Fallback: use completely random slug
	return `org-${nanoid(12)}`;
}
 
/**
 * Extract display name from user object
 */
function getDisplayName(user: BetterAuthUser): string {
	// Priority: name > email username > generic
	if (user.name && user.name.trim()) {
		return sanitizeOrgName(user.name.trim());
	}
 
	const emailParts = user.email.split("@");
	if (emailParts[0]) {
		// Capitalize first letter
		const username = emailParts[0];
		return sanitizeOrgName(username.charAt(0).toUpperCase() + username.slice(1));
	}
 
	return "Personal Workspace";
}
 
/**
 * Auto-provision a personal organization for a new user
 *
 * Called from Better Auth's databaseHooks.user.create.after
 *
 * Security:
 * - Uses transaction for atomicity
 * - Validates user exists before creating org
 * - Creates owner membership in same transaction
 * - Audit logs the operation
 */
export async function autoProvisionOrganization(user: BetterAuthUser): Promise<AutoProvisionResult> {
	const startTime = Date.now();
 
	try {
		// Lazy import to avoid circular dependencies
		const { db, combinedSchema } = await import("@snapback/platform");
		const { sql } = await import("drizzle-orm");
 
		if (!db) {
			logger.error("Database not available for auto-provisioning", { userId: user.id });
			return { success: false, error: "Database not available" };
		}
 
		const { organization, member } = combinedSchema;
 
		// Generate organization details
		const displayName = getDisplayName(user);
		const orgName = `${displayName}'s Workspace`;
		const orgSlug = await generateUniqueSlug(db, combinedSchema, displayName);
		const orgId = nanoid();
 
		// Transaction: Create organization + owner membership atomically
		await db.transaction(async (tx: any) => {
			// 1. Create the organization
			await tx.insert(organization).values({
				id: orgId,
				name: orgName,
				slug: orgSlug,
				createdAt: new Date(),
			});
 
			// 2. Create owner membership
			await tx.insert(member).values({
				id: nanoid(),
				userId: user.id,
				organizationId: orgId,
				role: "owner",
				createdAt: new Date(),
			});
 
			// 3. Set as user's active organization if they have an existing session
			// Note: New signup flow creates user first, then session via session.create.after hook
			// This handles the case where user already has a session (e.g., magic link, OAuth)
			const { session } = combinedSchema;
			try {
				await tx
					.update(session)
					.set({ activeOrganizationId: orgId })
					.where(sql`${session.userId} = ${user.id}`);
			} catch {
				// Session may not exist yet for new signups - that's expected
				// The session.create.after hook will set activeOrganizationId when session is created
			}
		});
 
		const duration = Date.now() - startTime;
 
		// Audit log the successful auto-provisioning
		await trackEvent("org.auto_provisioned" as AuditEventType, {
			userId: user.id,
			orgId,
			organizationName: orgName,
			organizationSlug: orgSlug,
			duration,
			timestamp: new Date().toISOString(),
		});
 
		logger.info("Auto-provisioned organization for new user", {
			userId: user.id,
			organizationId: orgId,
			organizationSlug: orgSlug,
			duration,
		});
 
		return {
			success: true,
			organizationId: orgId,
			organizationSlug: orgSlug,
		};
	} catch (error) {
		const duration = Date.now() - startTime;
 
		// Log error but don't crash auth flow
		logger.error("Failed to auto-provision organization", {
			userId: user.id,
			error: error instanceof Error ? error.message : String(error),
			stack: error instanceof Error ? error.stack : undefined,
			duration,
		});
 
		// Track the failure
		await trackEvent("org.auto_provision_failed" as AuditEventType, {
			userId: user.id,
			errorMessage: error instanceof Error ? error.message : String(error),
			duration,
			timestamp: new Date().toISOString(),
		}).catch(() => {
			// Ignore tracking errors
		});
 
		return {
			success: false,
			error: error instanceof Error ? error.message : "Unknown error",
		};
	}
}
 
/**
 * Check if user already has an organization
 * Used to avoid duplicate provisioning
 */
export async function userHasOrganization(userId: string): Promise<boolean> {
	try {
		const { db, combinedSchema } = await import("@snapback/platform");
		const { sql } = await import("drizzle-orm");
 
		if (!db) {
			return false;
		}
 
		const { member } = combinedSchema;
 
		const memberships = await db
			.select({ id: member.id })
			.from(member)
			.where(sql`${member.userId} = ${userId}`)
			.limit(1);
 
		return memberships.length > 0;
	} catch (error) {
		logger.error("Failed to check user organization membership", {
			userId,
			error: error instanceof Error ? error.message : String(error),
		});
		return false;
	}
}