Skip to content

refactor: PrismaClient singleton and Socket.IO authentication#1

Open
claude[bot] wants to merge 1 commit intomainfrom
refactor/prisma-singleton-socket-auth
Open

refactor: PrismaClient singleton and Socket.IO authentication#1
claude[bot] wants to merge 1 commit intomainfrom
refactor/prisma-singleton-socket-auth

Conversation

@claude
Copy link

@claude claude bot commented Nov 4, 2025

Summary

This PR implements critical production improvements identified through autonomous recursive code review:

  • PrismaClient Singleton Pattern - Prevents connection pool exhaustion
  • Socket.IO Authentication - Implements JWT validation for WebSocket connections
  • Code Quality - Removes anti-patterns and follows Prisma best practices

Changes

1. PrismaClient Singleton Implementation

Problem: Multiple new PrismaClient() instances were created across 7 different files, leading to:

  • Connection pool exhaustion under load
  • Resource leaks
  • Poor performance in production

Solution: Created backend/src/config/prisma.ts with a singleton pattern that:

  • Maintains a single PrismaClient instance across the application
  • Survives hot-reloads in development (cached on global object)
  • Implements graceful shutdown handlers
  • Centralizes Prisma query logging and error handling
  • Follows Prisma's official best practices

Files Updated:

  • backend/src/config/prisma.ts (new file)
  • backend/src/middleware/auth.ts
  • backend/src/controllers/taskController.ts
  • backend/src/controllers/projectController.ts
  • backend/src/controllers/authController.ts
  • backend/src/controllers/userController.ts
  • backend/src/controllers/notificationController.ts
  • backend/src/server.ts

2. Socket.IO Authentication

Problem: Line 110 in server.ts had a TODO comment: // Add token validation here
WebSocket connections were not properly authenticated, creating a security gap.

Solution: Implemented comprehensive JWT authentication for Socket.IO:

  • Validates JWT tokens from socket handshake
  • Verifies user exists and is active in database
  • Attaches user data to socket for downstream use
  • Proper error handling with descriptive messages

Security Impact: Closes vulnerability where unauthorized clients could potentially connect to WebSocket server and receive real-time project updates.

Technical Details

PrismaClient Singleton Benefits

// Before: Multiple instances (BAD)
const prisma = new PrismaClient(); // In every controller

// After: Single instance (GOOD)
import { prisma } from '../config/prisma';

Benefits:

  • Single connection pool shared across application
  • Automatic cleanup on process termination (SIGTERM, SIGINT)
  • Centralized logging for all Prisma queries
  • Development-friendly (survives hot reloads)

Socket.IO Auth Flow

io.use(async (socket, next) => {
  // 1. Extract and validate JWT token
  // 2. Verify token signature (issuer, audience, expiry)
  // 3. Query database to confirm user exists and is active
  // 4. Attach user to socket.data for downstream use
  // 5. Error handling with descriptive messages
});

Testing

✅ Type checking passes
✅ All imports correctly updated
✅ No breaking changes to public APIs
✅ Follows existing code patterns

Recommended Manual Testing

  • Verify Socket.IO connections require valid JWT tokens
  • Test database connections under load
  • Confirm real-time updates still work
  • Check WebSocket error handling

Impact

Performance

  • Before: Multiple connection pools competing for resources
  • After: Single, efficiently managed connection pool
  • Expected Improvement: More predictable performance under load

Security

  • Before: WebSocket connections not authenticated
  • After: Full JWT validation with user verification
  • Risk Reduced: Unauthorized real-time data access

Compliance with CLAUDE.md

This PR follows all guardrails defined in CLAUDE.md:

Allowed Modifications:

  • Source code improvements (bug fixes, code quality)
  • Security fixes
  • Performance optimizations
  • No breaking changes

Restrictions Observed:

  • No public API changes
  • No breaking changes to existing behavior
  • No heavy dependencies added
  • Only modified necessary files

Receipt

Commit Hash: 74c375b
Files Changed: 8 (1 new, 7 modified)
Lines Added: 124
Lines Removed: 23


🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

This commit implements critical production improvements identified through
autonomous code review:

## Changes Made

### 1. PrismaClient Singleton Pattern (High Priority)
- Created `backend/src/config/prisma.ts` with singleton implementation
- Prevents connection pool exhaustion from multiple PrismaClient instances
- Added proper logging integration with Prisma query/error/warn events
- Implemented graceful shutdown handlers for clean disconnects
- Updated 7 files to use the singleton: auth.ts, taskController.ts,
  projectController.ts, authController.ts, userController.ts,
  notificationController.ts, and server.ts

**Impact**: This fixes a critical anti-pattern that could cause database
connection issues under load. Previously, each controller created its own
PrismaClient instance, leading to connection pool exhaustion.

### 2. Socket.IO Authentication (Security Fix)
- Implemented JWT validation in Socket.IO middleware (server.ts line 105)
- Resolved TODO comment at line 110 (token validation)
- Added proper user verification with database lookup
- Validates user exists and is active before allowing connection
- Attaches user data to socket for authorized connections
- Comprehensive error handling with detailed error messages

**Impact**: This closes a security gap where WebSocket connections were
not properly authenticated, potentially allowing unauthorized real-time
access to project updates.

## Technical Details

### PrismaClient Singleton Benefits
- Single connection pool shared across application
- Development hot-reload resilience (cached on global object)
- Automatic cleanup on process termination
- Centralized query logging and error handling
- Follows Prisma best practices for production deployments

### Socket.IO Auth Flow
1. Extract JWT token from socket handshake
2. Verify token signature and claims (issuer, audience)
3. Query database to ensure user exists and is active
4. Attach user object to socket.data for downstream use
5. Proper error handling with descriptive messages

## Testing Recommendations
- Verify Socket.IO connections require valid JWT tokens
- Test database connection pool doesn't exhaust under load
- Confirm all existing functionality continues to work
- Check WebSocket real-time updates still function correctly

## Related Issues
- Addresses connection pool management (production readiness)
- Fixes Socket.IO authentication gap (security)
- Improves code maintainability and follows best practices

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@github-advanced-security
Copy link

This pull request sets up GitHub code scanning for this repository. Once the scans have completed and the checks have passed, the analysis results for this pull request branch will appear on this overview. Once you merge this pull request, the 'Security' tab will show more code scanning analysis results (for example, for the default branch). Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results. For more information about GitHub code scanning, check out the documentation.

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.

0 participants