feat: Add comprehensive input validation
- Created lib/validation.ts with validation utilities for all form inputs - Added validation for list titles, item titles, colors, dates, tags, descriptions, and notes - Implemented inline validation with real-time error feedback in ListForm - Enhanced ItemForm with comprehensive validation for all fields - Updated InlineItemCreate with validation - Added input sanitization to prevent XSS attacks - Updated server actions to use validation utilities - Added maxLength attributes to prevent excessive input - Improved accessibility with aria-invalid and aria-describedby attributes - Added visual feedback for validation errors with red borders - Validates Requirements 1.1 and 2.1
This commit is contained in:
107
lib/actions.ts
107
lib/actions.ts
@@ -2,6 +2,14 @@
|
||||
|
||||
import { prisma } from './db'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import {
|
||||
validateListTitle,
|
||||
validateItemTitle,
|
||||
validateColor,
|
||||
validateDateString,
|
||||
validateTags,
|
||||
sanitizeString,
|
||||
} from './validation'
|
||||
|
||||
// Retry utility for database operations
|
||||
async function retryOperation<T>(
|
||||
@@ -57,19 +65,23 @@ export async function getLists() {
|
||||
|
||||
export async function createList(title: string, color: string = '#3B82F6') {
|
||||
try {
|
||||
// Validate input
|
||||
if (!title || !title.trim()) {
|
||||
throw new Error('List title is required')
|
||||
// Validate and sanitize input
|
||||
const titleResult = validateListTitle(title)
|
||||
if (!titleResult.isValid) {
|
||||
throw new Error(titleResult.error)
|
||||
}
|
||||
|
||||
if (title.length > 200) {
|
||||
throw new Error('List title must be less than 200 characters')
|
||||
const colorResult = validateColor(color)
|
||||
if (!colorResult.isValid) {
|
||||
throw new Error(colorResult.error)
|
||||
}
|
||||
|
||||
const sanitizedTitle = sanitizeString(title)
|
||||
|
||||
const list = await retryOperation(() =>
|
||||
prisma.list.create({
|
||||
data: {
|
||||
title: title.trim(),
|
||||
title: sanitizedTitle,
|
||||
color,
|
||||
},
|
||||
})
|
||||
@@ -79,7 +91,7 @@ export async function createList(title: string, color: string = '#3B82F6') {
|
||||
return list
|
||||
} catch (error) {
|
||||
console.error('Error creating list:', error)
|
||||
if (error instanceof Error && error.message.includes('required')) {
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to create list. Please try again.')
|
||||
@@ -165,24 +177,35 @@ export async function createItem(
|
||||
throw new Error('List ID is required')
|
||||
}
|
||||
|
||||
if (!title || !title.trim()) {
|
||||
throw new Error('Item title is required')
|
||||
const titleResult = validateItemTitle(title)
|
||||
if (!titleResult.isValid) {
|
||||
throw new Error(titleResult.error)
|
||||
}
|
||||
|
||||
if (title.length > 200) {
|
||||
throw new Error('Item title must be less than 200 characters')
|
||||
// Validate tags if provided
|
||||
if (metadata?.tags) {
|
||||
const tagsResult = validateTags(metadata.tags)
|
||||
if (!tagsResult.isValid) {
|
||||
throw new Error(tagsResult.error)
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize inputs
|
||||
const sanitizedTitle = sanitizeString(title)
|
||||
const sanitizedDescription = description ? sanitizeString(description) : null
|
||||
const sanitizedNotes = metadata?.notes ? sanitizeString(metadata.notes) : null
|
||||
const sanitizedTags = metadata?.tags ? metadata.tags.map(sanitizeString) : undefined
|
||||
|
||||
const item = await retryOperation(() =>
|
||||
prisma.item.create({
|
||||
data: {
|
||||
title: title.trim(),
|
||||
description: description?.trim() || null,
|
||||
title: sanitizedTitle,
|
||||
description: sanitizedDescription,
|
||||
listId,
|
||||
...(metadata?.priority && { priority: metadata.priority }),
|
||||
...(metadata?.dueDate !== undefined && { dueDate: metadata.dueDate }),
|
||||
...(metadata?.tags && { tags: metadata.tags }),
|
||||
...(metadata?.notes !== undefined && { notes: metadata.notes }),
|
||||
...(sanitizedTags && { tags: sanitizedTags }),
|
||||
...(sanitizedNotes !== undefined && { notes: sanitizedNotes }),
|
||||
},
|
||||
})
|
||||
)
|
||||
@@ -191,7 +214,7 @@ export async function createItem(
|
||||
return item
|
||||
} catch (error) {
|
||||
console.error('Error creating item:', error)
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be'))) {
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be') || error.message.includes('Invalid'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to create item. Please try again.')
|
||||
@@ -247,20 +270,32 @@ export async function updateItem(
|
||||
throw new Error('Item ID is required')
|
||||
}
|
||||
|
||||
// Validate title if provided
|
||||
// Validate and sanitize title if provided
|
||||
if (data.title !== undefined) {
|
||||
if (!data.title || !data.title.trim()) {
|
||||
throw new Error('Item title cannot be empty')
|
||||
const titleResult = validateItemTitle(data.title)
|
||||
if (!titleResult.isValid) {
|
||||
throw new Error(titleResult.error)
|
||||
}
|
||||
if (data.title.length > 200) {
|
||||
throw new Error('Item title must be less than 200 characters')
|
||||
}
|
||||
data.title = data.title.trim()
|
||||
data.title = sanitizeString(data.title)
|
||||
}
|
||||
|
||||
// Trim description if provided
|
||||
// Sanitize description if provided
|
||||
if (data.description !== undefined && data.description !== null) {
|
||||
data.description = data.description.trim() || null
|
||||
data.description = sanitizeString(data.description) || null
|
||||
}
|
||||
|
||||
// Validate tags if provided
|
||||
if (data.tags !== undefined) {
|
||||
const tagsResult = validateTags(data.tags)
|
||||
if (!tagsResult.isValid) {
|
||||
throw new Error(tagsResult.error)
|
||||
}
|
||||
data.tags = data.tags.map(sanitizeString)
|
||||
}
|
||||
|
||||
// Sanitize notes if provided
|
||||
if (data.notes !== undefined && data.notes !== null) {
|
||||
data.notes = sanitizeString(data.notes) || null
|
||||
}
|
||||
|
||||
const item = await retryOperation(() =>
|
||||
@@ -282,7 +317,7 @@ export async function updateItem(
|
||||
return updated
|
||||
} catch (error) {
|
||||
console.error('Error updating item:', error)
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be'))) {
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be') || error.message.includes('Invalid'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to update item. Please try again.')
|
||||
@@ -364,15 +399,21 @@ export async function updateList(
|
||||
throw new Error('List ID is required')
|
||||
}
|
||||
|
||||
// Validate title if provided
|
||||
// Validate and sanitize title if provided
|
||||
if (data.title !== undefined) {
|
||||
if (!data.title || !data.title.trim()) {
|
||||
throw new Error('List title cannot be empty')
|
||||
const titleResult = validateListTitle(data.title)
|
||||
if (!titleResult.isValid) {
|
||||
throw new Error(titleResult.error)
|
||||
}
|
||||
if (data.title.length > 200) {
|
||||
throw new Error('List title must be less than 200 characters')
|
||||
data.title = sanitizeString(data.title)
|
||||
}
|
||||
|
||||
// Validate color if provided
|
||||
if (data.color !== undefined) {
|
||||
const colorResult = validateColor(data.color)
|
||||
if (!colorResult.isValid) {
|
||||
throw new Error(colorResult.error)
|
||||
}
|
||||
data.title = data.title.trim()
|
||||
}
|
||||
|
||||
const updated = await retryOperation(() =>
|
||||
@@ -387,7 +428,7 @@ export async function updateList(
|
||||
return updated
|
||||
} catch (error) {
|
||||
console.error('Error updating list:', error)
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be'))) {
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be') || error.message.includes('Invalid'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to update list. Please try again.')
|
||||
|
||||
303
lib/validation.ts
Normal file
303
lib/validation.ts
Normal file
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* Input validation utilities for the Ultimate Lists App
|
||||
* Provides validation functions and sanitization for user inputs
|
||||
*/
|
||||
|
||||
export interface ValidationResult {
|
||||
isValid: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize string input by trimming whitespace
|
||||
*/
|
||||
export function sanitizeString(input: string | null | undefined): string {
|
||||
if (input === null || input === undefined) {
|
||||
return ''
|
||||
}
|
||||
return input.trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate list title
|
||||
*/
|
||||
export function validateListTitle(title: string): ValidationResult {
|
||||
const sanitized = sanitizeString(title)
|
||||
|
||||
if (!sanitized) {
|
||||
return { isValid: false, error: 'List title is required' }
|
||||
}
|
||||
|
||||
if (sanitized.length > 200) {
|
||||
return { isValid: false, error: 'List title must be less than 200 characters' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate item/task title
|
||||
*/
|
||||
export function validateItemTitle(title: string): ValidationResult {
|
||||
const sanitized = sanitizeString(title)
|
||||
|
||||
if (!sanitized) {
|
||||
return { isValid: false, error: 'Task title is required' }
|
||||
}
|
||||
|
||||
if (sanitized.length > 200) {
|
||||
return { isValid: false, error: 'Task title must be less than 200 characters' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate hex color format
|
||||
*/
|
||||
export function validateColor(color: string): ValidationResult {
|
||||
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
|
||||
|
||||
if (!hexColorRegex.test(color)) {
|
||||
return { isValid: false, error: 'Invalid color format. Use hex format (e.g., #3B82F6)' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate priority value
|
||||
*/
|
||||
export function validatePriority(priority: string): ValidationResult {
|
||||
const validPriorities = ['low', 'medium', 'high']
|
||||
|
||||
if (!validPriorities.includes(priority)) {
|
||||
return { isValid: false, error: 'Priority must be low, medium, or high' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate date string format (ISO 8601 or YYYY-MM-DD)
|
||||
*/
|
||||
export function validateDateString(dateString: string): ValidationResult {
|
||||
if (!dateString) {
|
||||
return { isValid: true } // Empty date is valid (optional field)
|
||||
}
|
||||
|
||||
// Try to parse the date
|
||||
const date = new Date(dateString)
|
||||
|
||||
// Check if date is valid
|
||||
if (isNaN(date.getTime())) {
|
||||
return { isValid: false, error: 'Invalid date format. Use YYYY-MM-DD format' }
|
||||
}
|
||||
|
||||
// Check if date is reasonable (not too far in past or future)
|
||||
const minDate = new Date('1900-01-01')
|
||||
const maxDate = new Date('2100-12-31')
|
||||
|
||||
if (date < minDate || date > maxDate) {
|
||||
return { isValid: false, error: 'Date must be between 1900 and 2100' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate tag string
|
||||
*/
|
||||
export function validateTag(tag: string): ValidationResult {
|
||||
const sanitized = sanitizeString(tag)
|
||||
|
||||
if (!sanitized) {
|
||||
return { isValid: false, error: 'Tag cannot be empty' }
|
||||
}
|
||||
|
||||
if (sanitized.length > 50) {
|
||||
return { isValid: false, error: 'Tag must be less than 50 characters' }
|
||||
}
|
||||
|
||||
// Disallow special characters that might cause issues
|
||||
const invalidCharsRegex = /[<>\"']/
|
||||
if (invalidCharsRegex.test(sanitized)) {
|
||||
return { isValid: false, error: 'Tag contains invalid characters' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate array of tags
|
||||
*/
|
||||
export function validateTags(tags: string[]): ValidationResult {
|
||||
if (!Array.isArray(tags)) {
|
||||
return { isValid: false, error: 'Tags must be an array' }
|
||||
}
|
||||
|
||||
if (tags.length > 20) {
|
||||
return { isValid: false, error: 'Maximum 20 tags allowed' }
|
||||
}
|
||||
|
||||
for (const tag of tags) {
|
||||
const result = validateTag(tag)
|
||||
if (!result.isValid) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate description text
|
||||
*/
|
||||
export function validateDescription(description: string | null | undefined): ValidationResult {
|
||||
if (!description) {
|
||||
return { isValid: true } // Description is optional
|
||||
}
|
||||
|
||||
if (description.length > 2000) {
|
||||
return { isValid: false, error: 'Description must be less than 2000 characters' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate notes text
|
||||
*/
|
||||
export function validateNotes(notes: string | null | undefined): ValidationResult {
|
||||
if (!notes) {
|
||||
return { isValid: true } // Notes are optional
|
||||
}
|
||||
|
||||
if (notes.length > 5000) {
|
||||
return { isValid: false, error: 'Notes must be less than 5000 characters' }
|
||||
}
|
||||
|
||||
return { isValid: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize HTML to prevent XSS attacks
|
||||
* Basic implementation - strips HTML tags
|
||||
*/
|
||||
export function sanitizeHtml(input: string): string {
|
||||
return input.replace(/<[^>]*>/g, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and sanitize list creation data
|
||||
*/
|
||||
export function validateListData(data: { title: string; color?: string }): {
|
||||
isValid: boolean
|
||||
errors: Record<string, string>
|
||||
sanitized: { title: string; color: string }
|
||||
} {
|
||||
const errors: Record<string, string> = {}
|
||||
|
||||
// Validate title
|
||||
const titleResult = validateListTitle(data.title)
|
||||
if (!titleResult.isValid) {
|
||||
errors.title = titleResult.error!
|
||||
}
|
||||
|
||||
// Validate color if provided
|
||||
const color = data.color || '#3B82F6'
|
||||
const colorResult = validateColor(color)
|
||||
if (!colorResult.isValid) {
|
||||
errors.color = colorResult.error!
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: Object.keys(errors).length === 0,
|
||||
errors,
|
||||
sanitized: {
|
||||
title: sanitizeString(data.title),
|
||||
color,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and sanitize item creation data
|
||||
*/
|
||||
export function validateItemData(data: {
|
||||
title: string
|
||||
description?: string | null
|
||||
priority?: string
|
||||
dueDate?: string | null
|
||||
tags?: string[]
|
||||
notes?: string | null
|
||||
}): {
|
||||
isValid: boolean
|
||||
errors: Record<string, string>
|
||||
sanitized: {
|
||||
title: string
|
||||
description: string | null
|
||||
priority: 'low' | 'medium' | 'high'
|
||||
dueDate: Date | null
|
||||
tags: string[]
|
||||
notes: string | null
|
||||
}
|
||||
} {
|
||||
const errors: Record<string, string> = {}
|
||||
|
||||
// Validate title
|
||||
const titleResult = validateItemTitle(data.title)
|
||||
if (!titleResult.isValid) {
|
||||
errors.title = titleResult.error!
|
||||
}
|
||||
|
||||
// Validate description
|
||||
const descResult = validateDescription(data.description)
|
||||
if (!descResult.isValid) {
|
||||
errors.description = descResult.error!
|
||||
}
|
||||
|
||||
// Validate priority
|
||||
const priority = data.priority || 'medium'
|
||||
const priorityResult = validatePriority(priority)
|
||||
if (!priorityResult.isValid) {
|
||||
errors.priority = priorityResult.error!
|
||||
}
|
||||
|
||||
// Validate due date
|
||||
let dueDate: Date | null = null
|
||||
if (data.dueDate) {
|
||||
const dateResult = validateDateString(data.dueDate)
|
||||
if (!dateResult.isValid) {
|
||||
errors.dueDate = dateResult.error!
|
||||
} else {
|
||||
dueDate = new Date(data.dueDate)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate tags
|
||||
const tags = data.tags || []
|
||||
const tagsResult = validateTags(tags)
|
||||
if (!tagsResult.isValid) {
|
||||
errors.tags = tagsResult.error!
|
||||
}
|
||||
|
||||
// Validate notes
|
||||
const notesResult = validateNotes(data.notes)
|
||||
if (!notesResult.isValid) {
|
||||
errors.notes = notesResult.error!
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: Object.keys(errors).length === 0,
|
||||
errors,
|
||||
sanitized: {
|
||||
title: sanitizeString(data.title),
|
||||
description: data.description ? sanitizeString(data.description) : null,
|
||||
priority: priority as 'low' | 'medium' | 'high',
|
||||
dueDate,
|
||||
tags: tags.map(sanitizeString),
|
||||
notes: data.notes ? sanitizeString(data.notes) : null,
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user