Skip to content

Refactor: Security + Performance optimisation - #31

Merged
sabique-islam merged 8 commits into
mainfrom
security-performance
Aug 29, 2025
Merged

sabique-islam merged 8 commits into
mainfrom
security-performance

Conversation

@Priyans00

Copy link
Copy Markdown
Owner

Security Enhancements

API Route Security

Rate Limiting: Implemented per-endpoint rate limiting (10-100 requests/hour)
Input Validation: UUID validation, data type checking, length constraints
Authentication & Authorization: User verification and access control
XSS Prevention: Input sanitization and HTML tag removal
CSRF Protection: Anti-CSRF tokens and secure headers

Middleware Security

Security Headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options
Attack Prevention: SQL injection, XSS, clickjacking protection
IP-based Rate Limiting: Prevents brute force attacks
Request Size Limits: Prevents DoS attacks

Performance Optimizations

Caching Implementation

API Response Caching: 2-5 minute TTL for frequently accessed data
Client-side Caching: Profile data, item listings, chat messages
Database Query Optimization: Batch queries, reduced N+1 problems

Component Optimization

React Performance: useMemo, useCallback, optimized re-renders
Debounced Search: 300ms delay to reduce API calls
Lazy Loading: Optimized image loading and skeleton states

@vercel

vercel Bot commented Aug 29, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
pesxchange Ready Ready Preview Comment Aug 29, 2025 9:27am

@github-actions

Copy link
Copy Markdown

PR Summary

Here's a summary of the pull request:

  • Enhanced API Security:
    • Authentication & Authorization: Implemented user authentication and strict authorization checks (user.id !== userId) for critical API routes (active-chats).
    • Input Validation: Added robust input validation, including UUID format checks for user IDs and specific SRN format validation for authentication endpoints.
    • Rate Limiting: Introduced per-endpoint rate limiting for general API calls and IP-based/username-based rate limiting for authentication attempts to prevent brute-force attacks.
    • Input Sanitization: Implemented input sanitization to remove potentially malicious characters (e.g., <, >) and truncate inputs, enhancing XSS prevention.
    • General Security Practices: The PR description also outlines plans for CSRF protection, secure headers (CSP, HSTS, etc.), SQL injection, and clickjacking prevention.
  • Significant Performance Optimizations:
    • API Response Caching: Implemented in-memory caching for frequently accessed data (e.g., active chats) with a 5-minute TTL to reduce database load and improve response times.
    • Database Query Optimization: Refactored database queries to reduce N+1 problems, perform batch fetches (e.g., for user profiles), and optimize conversation retrieval with ordering and limits.
    • Broader Performance Improvements: The PR description also highlights client-side caching, React component optimizations (useMemo, useCallback), debounced search, and lazy loading for images and components.

@Priyans00
Priyans00 requested a review from Copilot August 29, 2025 03:22

This comment was marked as outdated.

@github-actions

Copy link
Copy Markdown

PR Summary

This pull request focuses on significant Security Enhancements and Performance Optimizations.

Key Changes:

  • Security Enhancements:

    • API Route Security:
      • Implemented user authentication and authorization checks for the active-chats API, ensuring only authorized users can fetch their chat data.
      • Introduced robust input validation, including UUID format checks for user IDs in active-chats and SRN format validation for usernames in pesu authentication.
      • Added basic input sanitization to pesu authentication to prevent common injection attacks.
      • Integrated IP-based and username-based rate limiting for the pesu authentication endpoint to prevent brute-force attacks.
      • Improved error handling with specific HTTP status codes (400, 401, 403, 429, 500) across API routes.
    • Middleware & General Security (from description): Indicates broader implementation of security headers (CSP, HSTS), XSS prevention (HTML tag removal), CSRF protection, SQL injection, clickjacking protection, and request size limits across the application.
  • Performance Optimizations:

    • API Response Caching: Implemented server-side caching with a 5-minute TTL for the active-chats API, reducing database load for frequently accessed data.
    • Database Query Optimization:
      • Refactored active-chats queries to fetch only necessary data, use LIMIT for conversations, and batch fetch user profiles, significantly reducing N+1 problems.
      • Optimized conversation processing logic for better efficiency.
    • Client-side & Component Optimization (from description): Mentions broader efforts including client-side caching for various data, React performance optimizations (useMemo, useCallback), debounced search functionality, and lazy loading for images and components.

This comment was marked as outdated.

@Priyans00
Priyans00 requested a review from Copilot August 29, 2025 04:19
@github-actions

Copy link
Copy Markdown

PR Summary

This pull request introduces significant security enhancements and performance optimizations, primarily focusing on the active-chats and auth/pesu API routes.

Security Enhancements:

  • Authentication & Authorization:
    • The active-chats API now verifies user authentication (401 Unauthorized) and ensures users can only request their own chats (403 Forbidden).
  • Input Validation:
    • active-chats validates userId as a UUID.
    • auth/pesu validates username against an SRN regex pattern and checks for missing credentials.
  • Input Sanitization & XSS Prevention:
    • auth/pesu sanitizes username and password inputs by trimming, removing HTML tags, and enforcing length constraints.
  • Rate Limiting:
    • Implemented for the auth/pesu endpoint, limiting authentication attempts per IP/username combination (5 attempts per 15 minutes) to prevent brute-force attacks.

Performance Optimizations:

  • API Response Caching:
    • The active-chats API now caches responses in-memory for 5 minutes, reducing database load for frequently accessed chat lists.
  • Database Query Optimization:
    • The active-chats query was refactored to retrieve all necessary message data in a single query with a limit (200 messages).
    • It now efficiently processes unique conversations and fetches associated user profiles in a batch, eliminating N+1 problems.
    • Results are sorted by the latest message time.

This comment was marked as outdated.

@github-actions

Copy link
Copy Markdown

PR Summary

Based on the description and code diff, this pull request introduces significant security enhancements and performance optimizations:

Security Enhancements:

  • Authentication & Authorization: Implemented user authentication and authorization checks (e.g., ensuring userId matches the authenticated user) in the active-chats API.
  • Input Validation: Added UUID validation for userId in active-chats and enhanced SRN validation for usernames in auth/pesu.
  • Input Sanitization: Introduced input sanitization (removing HTML tags like < and >) for username/password in auth/pesu to prevent XSS.
  • Rate Limiting: Implemented an IP and username-based rate limiting mechanism for authentication attempts in auth/pesu to prevent brute-force attacks.
  • Data Type/Length Constraints: Implicitly handled via substring(0, 100) in sanitization and specific regex for UUID/SRN validation.

Performance Optimizations:

  • API Response Caching: Implemented server-side caching (chatCache with a 5-minute TTL) for active-chats responses to reduce redundant database calls for frequently accessed data.
  • Database Query Optimization: Refactored the active-chats query to:
    • Fetch conversations more efficiently with order and limit.
    • Process unique conversation partners in memory using a Map to avoid N+1 problems.
    • Batch fetch user profile details (user_profiles) for the identified conversation partners.
    • Combines and sorts the final results based on the last message time.

@github-actions

Copy link
Copy Markdown

PR Summary

This pull request introduces significant security enhancements and performance optimizations across the application, with specific implementations visible in the active-chats and auth/pesu API routes.

Security Enhancements:

  • Authentication & Authorization: The active-chats API now explicitly authenticates users and performs an authorization check to ensure a user can only request their own active chats.
  • Input Validation:
    • active-chats: Implements UUID validation for the userId parameter.
    • auth/pesu: Adds robust SRN (Student Registration Number) format validation for the username.
  • Input Sanitization: The auth/pesu endpoint now sanitizes username and password inputs by trimming, removing HTML tags (<, >), and enforcing length constraints to prevent XSS.
  • Rate Limiting:
    • auth/pesu: Implements an IP and username-based rate limiting mechanism, allowing a maximum of 5 authentication attempts within a 15-minute window to prevent brute-force attacks.

Performance Optimizations:

  • API Response Caching: The active-chats API now features an in-memory cache with a 5-minute Time-To-Live (TTL) for frequently accessed user chat lists, reducing database load.
  • Database Query Optimization: The active-chats endpoint's database query has been optimized to:
    • Fetch messages efficiently, ordering by created_at and applying a limit.
    • Process conversations to identify unique partners and their latest message/timestamp.
    • Perform batch fetching of user profiles, reducing N+1 query problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR implements comprehensive security enhancements and performance optimizations across the application. The changes add rate limiting, input validation, XSS protection, CSRF prevention, caching mechanisms, and React component optimizations to improve both security posture and performance.

  • Added security headers, rate limiting, and input sanitization across API routes
  • Implemented client-side caching for profile data, messages, and items with TTL
  • Enhanced React components with useMemo, useCallback, and debounced search

Reviewed Changes

Copilot reviewed 15 out of 16 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
package.json Added DOMPurify packages for XSS protection
next.config.ts Added comprehensive security headers including CSP
middleware.ts Enhanced with rate limiting and security validation
lib/utils.ts Added input sanitization and validation utilities
lib/rateLimiter.ts Created centralized rate limiting utility
components/pesu-profile.tsx Added caching, validation, and performance optimizations
components/chat.tsx Implemented message caching and optimized real-time updates
app/sell/sell-form-contents.tsx Enhanced input validation and XSS protection
app/item-listing/item-listing-contents.tsx Added caching, debounced search, and error handling
app/api/profile/pesu-update/route.ts Added authentication, authorization, and input validation
app/api/profile/pesu-stats/route.ts Implemented caching and optimized database queries
app/api/messages/route.ts Added comprehensive security and validation
app/api/items/route.ts Enhanced with caching and query optimization
app/api/auth/pesu/route.ts Added rate limiting and input validation
app/api/active-chats/route.ts Implemented caching and improved performance
Comments suppressed due to low confidence (1)

app/sell/sell-form-contents.tsx:193

  • The validateStep function is recreated on every render which could impact performance. Consider wrapping it with useCallback to memoize the function and prevent unnecessary re-renders of child components that depend on it.
  const validateStep = (step: number): boolean => {
    const newErrors: Record<string, string> = {};

    if (step === 1) {
      if (validationResults.images) {
        newErrors.images = validationResults.images;
      }
    } else if (step === 2) {
      if (validationResults.title) newErrors.title = validationResults.title;
      if (validationResults.description) newErrors.description = validationResults.description;
    } else if (step === 3) {
      if (validationResults.price) newErrors.price = validationResults.price;
      if (validationResults.year) newErrors.year = validationResults.year;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread middleware.ts
Comment on lines +12 to +15
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
response.headers.set('X-XSS-Protection', '1; mode=block');

Copilot AI Aug 29, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security headers are duplicated in the addSecurityHeaders function. Lines 6-9 and 12-15 set the same headers. Remove the duplicate header assignments to avoid redundancy.

Suggested change
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
response.headers.set('X-XSS-Protection', '1; mode=block');

Copilot uses AI. Check for mistakes.
Comment thread app/api/items/route.ts Outdated
if (sanitizedSearch) {
// Use full-text search on both title and description fields using safer syntax
query = query.or(
`title.textSearch.websearch.${sanitizedSearch},description.textSearch.websearch.${sanitizedSearch}`

Copilot AI Aug 29, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The textSearch.websearch syntax is incorrect for PostgreSQL full-text search in Supabase. This should use the proper PostgREST syntax for text search, such as title.fts.websearch.${sanitizedSearch} or title.textSearch(english).${sanitizedSearch} depending on your database configuration.

Suggested change
`title.textSearch.websearch.${sanitizedSearch},description.textSearch.websearch.${sanitizedSearch}`
`title.fts.websearch.${sanitizedSearch},description.fts.websearch.${sanitizedSearch}`

Copilot uses AI. Check for mistakes.
Comment thread app/api/messages/route.ts Outdated
}

function validateUUID(uuid: string): boolean {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

Copilot AI Aug 29, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This UUID regex is too restrictive as it only validates UUID v4. The pattern requires '4' in the version field and '[89ab]' in the variant field, but Supabase may use different UUID versions. Use a more generic UUID pattern: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

Copilot uses AI. Check for mistakes.
Comment thread app/api/active-chats/route.ts Outdated
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

function validateUUID(uuid: string): boolean {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

Copilot AI Aug 29, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This UUID regex is too restrictive as it only validates UUID v4. The pattern requires '4' in the version field and '[89ab]' in the variant field, but Supabase may use different UUID versions. Use a more generic UUID pattern: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

Copilot uses AI. Check for mistakes.
@github-actions

Copy link
Copy Markdown

PR Summary

🚀 Security & Performance Enhancements

This pull request introduces significant security upgrades and performance optimizations across the application, with specific implementations visible in the chat and authentication API routes.

Key Changes:

  • Enhanced API Route Security:
    • Authentication & Authorization: Implemented user authentication and access control (401 Unauthorized, 403 Forbidden) for API endpoints, specifically in active-chats.
    • Input Validation: Added robust validation for user IDs (supporting UUID and SRN formats) and SRN in the authentication process, including data type and length constraints.
    • XSS Prevention: Introduced input sanitization (trimming, HTML tag removal, truncation) for sensitive fields like username and password.
    • Rate Limiting: Implemented per-endpoint rate limiting for login attempts (auth/pesu) based on IP address, preventing brute-force attacks.
  • Performance Optimizations:
    • API Response Caching: Integrated server-side caching (5-minute TTL) for frequently accessed data, as seen in the active-chats endpoint.
    • Database Query Optimization: Refactored database queries to reduce N+1 problems, perform batch fetches (e.g., for user profiles), and retrieve only necessary data, significantly improving response times for chat listings.
    • Efficient Conversation Processing: Optimized logic for gathering unique conversations and their latest messages, reducing processing overhead.
  • Improved Error Handling: Provided more specific and informative error messages with appropriate HTTP status codes (e.g., 400 Bad Request, 500 Internal Server Error) for various failure scenarios.

@github-actions

Copy link
Copy Markdown

PR Summary

This pull request introduces significant security enhancements and performance optimizations across the application.

Security Enhancements:

  • Authentication & Authorization: Implemented robust user authentication (supabase.auth.getUser()) and authorization checks for API routes, such as /api/active-chats, returning 401 for unauthorized and 403 for forbidden access.
  • Input Validation & Sanitization: Added strict input validation for user IDs (supporting UUID and SRN formats) and SRN usernames (/api/auth/pesu), rejecting invalid formats with a 400 status. Basic input sanitization (sanitizeInput) is applied to prevent XSS.
  • Rate Limiting: Introduced per-endpoint rate limiting for authentication attempts (/api/auth/pesu), allowing a maximum of 5 attempts within a 15-minute window per identifier/IP to mitigate brute-force attacks.
  • Security Headers: Ensured security headers are set, with X-Content-Type-Options: nosniff specifically added to the authentication route.

Performance Optimizations:

  • API Response Caching: Implemented server-side caching for frequently accessed data, specifically active chats, with a 5-minute time-to-live (TTL) to reduce database load and improve response times.
  • Database Query Optimization: Refactored database queries for active chats to be more efficient. This includes selecting necessary fields, ordering results, applying limits, and batch-fetching user profiles, reducing N+1 query problems.
  • Efficient Data Processing: Optimized the logic for processing conversation data to efficiently identify unique chat partners and retrieve their latest messages, improving the speed of generating the active chats list.

@github-actions

Copy link
Copy Markdown

PR Summary

This pull request introduces significant security enhancements and performance optimizations across the application, with specific implementations visible in the /api/active-chats and /api/auth/pesu routes.

Key Changes:

  • API Route Security (active-chats and auth/pesu):
    • Authentication & Authorization: Implemented user authentication and strict authorization checks for fetching active chats, ensuring only the authenticated user can access their data.
    • Input Validation: Added robust validation for userId (supporting UUID and SRN formats) and SRN (for username) to prevent malformed requests.
    • Rate Limiting: Introduced per-identifier/IP-based rate limiting for authentication attempts (5 attempts per 15 minutes) to mitigate brute-force attacks.
    • Input Sanitization: Basic sanitization (trimming, HTML tag removal, length constraints) is applied to username and password inputs in the authentication route, and chat messages are truncated.
  • Performance Optimizations (active-chats):
    • API Response Caching: Implemented an in-memory cache for active chat lists with a 5-minute TTL, reducing database load for frequently accessed data.
    • Database Query Optimization: Refactored the active chats query to efficiently retrieve conversation partners and their last messages, using ordering and limiting, and batch-fetching user profiles to reduce N+1 problems.
  • Broader Security & Performance (as per PR description):
    • The PR description indicates broader security enhancements like CSRF protection, comprehensive XSS prevention, SQL injection prevention, and various security headers (CSP, HSTS) are being implemented, likely at a middleware level.
    • Further performance improvements include client-side caching, React component optimizations (useMemo, useCallback), debounced search, and lazy loading for images.

@sabique-islam
sabique-islam merged commit f92ea1c into main Aug 29, 2025
3 checks passed
@SavvyHex
SavvyHex deleted the security-performance branch September 4, 2025 12:02

This branch was successfully deployed

1 active deployment
Preview — 8126f8c2 Deployed Aug 29, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants