All files / src/lib/security validation.ts

71.11% Statements 197/277
100% Branches 0/0
0% Functions 0/10
71.11% Lines 197/277

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 2781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x           1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x                                     1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x                       1x 1x  
/**
 * Security Validation Library
 *
 * Provides input validation and sanitization utilities
 * to prevent XSS, SQL injection, and other attacks.
 */
 
import { z } from 'zod';
 
// ============================================================================
// Sanitization Functions
// ============================================================================
 
/**
 * Simple HTML entity encoding for server-side sanitization
 * This is a lightweight alternative to DOMPurify for server-side use
 */
function escapeHtml(str: string): string {
  const htmlEntities: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;',
    '/': '&#x2F;',
  };
  return str.replace(/[&<>"'/]/g, (char) => htmlEntities[char] || char);
}
 
/**
 * Strip all HTML tags from a string (server-safe)
 */
function stripHtmlTags(str: string): string {
  // Remove HTML tags, keeping text content
  return str
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') // Remove script tags and content
    .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '') // Remove style tags and content
    .replace(/<[^>]+>/g, '') // Remove all other HTML tags
    .replace(/&nbsp;/g, ' ') // Replace nbsp with space
    .replace(/\s+/g, ' ') // Normalize whitespace
    .trim();
}
 
/**
 * Sanitize HTML content - allows limited safe tags
 * On server-side, strips all tags for safety
 * For rich HTML editing, use client-side DOMPurify
 */
export function sanitizeHtml(dirty: string): string {
  // For server-side, we strip HTML for security
  // Rich text editing should be done client-side with proper DOMPurify
  return escapeHtml(stripHtmlTags(dirty));
}
 
/**
 * Sanitize plain text - removes all HTML
 */
export function sanitizeText(dirty: string): string {
  return stripHtmlTags(dirty);
}
 
/**
 * Remove potentially dangerous characters from search queries
 */
export function sanitizeSearchQuery(query: string): string {
  return query.replace(/[<>'"`;\\]/g, '').trim();
}
 
/**
 * Escape string for SQL LIKE queries (prevents injection via wildcards)
 */
export function escapeLikePattern(value: string): string {
  return value.replace(/[%_\\]/g, '\\$&');
}
 
// ============================================================================
// Common Validation Schemas
// ============================================================================
 
export const schemas = {
  // Identity
  email: z
    .string()
    .email('Invalid email address')
    .max(255, 'Email too long')
    .transform((s) => s.toLowerCase().trim()),
 
  password: z
    .string()
    .min(8, 'Password must be at least 8 characters')
    .max(128, 'Password too long')
    .regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
    .regex(/[a-z]/, 'Password must contain at least one lowercase letter')
    .regex(/[0-9]/, 'Password must contain at least one number')
    .regex(/[^A-Za-z0-9]/, 'Password must contain at least one special character'),
 
  username: z
    .string()
    .min(3, 'Username must be at least 3 characters')
    .max(30, 'Username too long')
    .regex(
      /^[a-zA-Z0-9_-]+$/,
      'Username can only contain letters, numbers, underscores, and hyphens'
    ),
 
  // Contact
  phone: z
    .string()
    .regex(/^\+?[1-9]\d{1,14}$/, 'Invalid phone number format')
    .optional(),
 
  // Identifiers
  uuid: z.string().uuid('Invalid ID format'),
 
  cuid: z.string().regex(/^c[a-z0-9]{24}$/, 'Invalid ID format'),
 
  slug: z
    .string()
    .min(1)
    .max(100)
    .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Invalid slug format'),
 
  // URLs
  url: z.string().url('Invalid URL').max(2048, 'URL too long'),
 
  // Commerce
  price: z
    .number()
    .min(0, 'Price cannot be negative')
    .max(1000000, 'Price too high')
    .multipleOf(0.01, 'Price must have at most 2 decimal places'),
 
  quantity: z
    .number()
    .int('Quantity must be a whole number')
    .min(0, 'Quantity cannot be negative')
    .max(10000, 'Quantity too high'),
 
  rating: z
    .number()
    .min(1, 'Rating must be at least 1')
    .max(5, 'Rating cannot exceed 5'),
 
  // Text fields with sanitization
  name: z
    .string()
    .min(1, 'Name is required')
    .max(100, 'Name too long')
    .transform(sanitizeText),
 
  description: z
    .string()
    .max(5000, 'Description too long')
    .transform(sanitizeText),
 
  richText: z
    .string()
    .max(50000, 'Content too long')
    .transform(sanitizeHtml),
 
  // Search
  searchQuery: z
    .string()
    .max(200, 'Search query too long')
    .transform(sanitizeSearchQuery),
 
  // Pagination
  page: z.coerce
    .number()
    .int()
    .min(0)
    .max(10000)
    .default(0),
 
  limit: z.coerce
    .number()
    .int()
    .min(1)
    .max(100)
    .default(20),
 
  // Sort
  sortOrder: z.enum(['asc', 'desc']).default('desc'),
 
  // Date/Time
  date: z.coerce.date(),
 
  dateString: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Invalid date format (YYYY-MM-DD)'),
 
  // Address
  address: z.object({
    street: z.string().min(1).max(200).transform(sanitizeText),
    city: z.string().min(1).max(100).transform(sanitizeText),
    state: z.string().min(1).max(100).transform(sanitizeText),
    postalCode: z.string().min(1).max(20).transform(sanitizeText),
    country: z.string().min(2).max(2), // ISO country code
  }),
 
  // Security tokens
  csrfToken: z.string().min(32).max(256),
 
  otpCode: z.string().regex(/^\d{6}$/, 'Invalid OTP code'),
 
  backupCode: z.string().regex(/^[A-F0-9]{8}$/, 'Invalid backup code'),
};
 
// ============================================================================
// Validation Helpers
// ============================================================================
 
/**
 * Validate request body against a schema
 */
export async function validateBody<T extends z.ZodType>(
  request: Request,
  schema: T
): Promise<z.infer<T>> {
  const body = await request.json();
  return schema.parse(body);
}
 
/**
 * Validate query parameters against a schema
 */
export function validateQuery<T extends z.ZodType>(
  searchParams: URLSearchParams,
  schema: T
): z.infer<T> {
  const params: Record<string, string | string[]> = {};
  searchParams.forEach((value, key) => {
    if (params[key]) {
      if (Array.isArray(params[key])) {
        (params[key] as string[]).push(value);
      } else {
        params[key] = [params[key] as string, value];
      }
    } else {
      params[key] = value;
    }
  });
  return schema.parse(params);
}
 
/**
 * Safely validate and return result with error details
 */
export function safeValidate<T extends z.ZodType>(
  schema: T,
  data: unknown
): { success: true; data: z.infer<T> } | { success: false; errors: z.ZodIssue[] } {
  const result = schema.safeParse(data);
  if (result.success) {
    return { success: true, data: result.data };
  }
  return { success: false, errors: result.error.issues };
}
 
// ============================================================================
// Request Schema Builder
// ============================================================================
 
/**
 * Create a schema for API route handlers
 */
export function createRequestSchema<
  TBody extends z.ZodType | undefined = undefined,
  TQuery extends z.ZodType | undefined = undefined,
  TParams extends z.ZodType | undefined = undefined
>(options: {
  body?: TBody;
  query?: TQuery;
  params?: TParams;
}) {
  return options;
}
 
export type RequestSchema = ReturnType<typeof createRequestSchema>;