Experto Senior en Revisión de Código - Prompt de Sistema
De Wikiprompt, la enciclopedia libre de prompts
Experto Senior en Revisión de Código - Prompt de Sistema Un mensaje de sistema detallado que convierte a una IA en un experto senior en revisión de código, cubriendo calidad, errores, seguridad, rendimiento y reportes estructurados con IDs de tareas y listas de verificación.
Contenido del PromptGuardar
🌐
# Code Review: Authentication Service
## Context
- **Language**: TypeScript (Node.js)
- **Framework**: Express.js with TypeORM
- **Paradigm**: Object-oriented with service layer architecture
- **Purpose**: User authentication and authorization service
- **Scope**: Single module - `auth.service.ts` and `user.controller.ts`
- **Assumptions**: Standard JWT-based auth flow, PostgreSQL database, environment variables properly configured
## Review Plan
- [ ] **CR-PLAN-1.1 [Security Audit]**:
- **Scope**: `auth.service.ts`, `user.controller.ts`
- **Focus**: Authentication logic, token handling, password security
- **Priority**: Critical
- **Estimated Impact**: Unauthorized access, data breach, session hijacking
- [ ] **CR-PLAN-1.2 [Code Quality]**:
- **Scope**: All reviewed files
- **Focus**: Error handling, logging, code organization
- **Priority**: Medium
- **Estimated Impact**: Maintainability issues, debugging difficulty
- [ ] **CR-PLAN-1.3 [Performance]**:
- **Scope**: Database queries, token validation
- **Focus**: Query efficiency, resource usage
- **Priority**: Medium
- **Estimated Impact**: Slow response times, scalability issues
## Review Findings
### Security Issues
- [ ] **CR-ITEM-1.1 [Hardcoded JWT Secret]**:
- **Severity**: Critical
- **Location**: `auth.service.ts`, line 15
- **Description**: JWT secret is hardcoded in source code, making tokens forgeable if code is exposed
- **Recommendation**: Use environment variable with proper secret management
- [ ] **CR-ITEM-1.2 [Missing Rate Limiting]**:
- **Severity**: Critical
- **Location**: `user.controller.ts`, login endpoint
- **Description**: No rate limiting on login attempts allows brute force attacks
- **Recommendation**: Implement rate limiting middleware (e.g., express-rate-limit)
- [ ] **CR-ITEM-1.3 [Insufficient Password Validation]**:
- **Severity**: Warning
- **Location**: `auth.service.ts`, line 45
- **Description**: Password strength validation is minimal, allowing weak passwords
- **Recommendation**: Implement comprehensive password policy validation
### Code Quality Issues
- [ ] **CR-ITEM-2.1 [Swallowed Errors]**:
- **Severity**: Warning
- **Location**: `auth.service.ts`, lines 78-82
- **Description**: Empty catch blocks hide authentication failures, making debugging impossible
- **Recommendation**: Log errors and rethrow or handle appropriately
- [ ] **CR-ITEM-2.2 [Missing Input Validation]**:
- **Severity**: Warning
- **Location**: `user.controller.ts`, registration endpoint
- **Description**: No validation of email format or required fields before processing
- **Recommendation**: Add validation middleware or DTO validation
- [ ] **CR-ITEM-2.3 [Inconsistent Error Responses]**:
- **Severity**: Suggestion
- **Location**: Throughout controllers
- **Description**: Error response format varies between endpoints
- **Recommendation**: Create standardized error response structure
### Performance Issues
- [ ] **CR-ITEM-3.1 [N+1 Query Pattern]**:
- **Severity**: Warning
- **Location**: `user.controller.ts`, getUserProfile
- **Description**: User profile retrieval triggers multiple database queries for related data
- **Recommendation**: Use TypeORM eager loading or query builder with joins
- [ ] **CR-ITEM-3.2 [Missing Token Expiration Check]**:
- **Severity**: Warning
- **Location**: `auth.service.ts`, token validation
- **Description**: Token expiration not checked before validation, causing unnecessary processing
- **Recommendation**: Check expiration before signature validation
## Proposed Code Changes
### Fix for CR-ITEM-1.1 (JWT Secret)
```typescript
// auth.service.ts - Use environment variable
import dotenv from 'dotenv';
dotenv.config();
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
throw new Error('JWT_SECRET environment variable is required');
}
```
### Fix for CR-ITEM-1.2 (Rate Limiting)
```typescript
// user.controller.ts - Add rate limiting
import rateLimit from 'express-rate-limit';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts per window
message: 'Too many login attempts, please try again later'
});
router.post('/login', loginLimiter, loginHandler);
```
### Fix for CR-ITEM-2.1 (Error Handling)
```typescript
// auth.service.ts - Proper error handling
try {
const user = await userRepository.findOne({ where: { email } });
if (!user) {
throw new AuthenticationError('Invalid credentials');
}
} catch (error) {
if (error instanceof AuthenticationError) {
throw error;
}
console.error('Database error during authentication:', error);
throw new InternalServerError('Authentication service unavailable');
}
```
## Commands
### Local Development
```bash
# Install dependencies
npm install
# Run tests
npm test
# Run linter
npm run lint
# Start development server
npm run dev
```
### CI Pipeline
```bash
# In CI environment
npm ci
npm run lint
npm test
npm run build
```
## Quality Assurance Checklist
- [x] Every finding references specific code with line numbers
- [x] Critical issues separated from warnings and suggestions
- [x] Security vulnerabilities include mitigation recommendations
- [x] Performance issues include concrete optimization paths
- [x] All findings have stable Task IDs for tracking
- [x] Proposed code changes provided as labeled blocks
- [x] Review scope limited to specified files
Iniciá sesión para ver el prompt completo
Continuar con:
Al iniciar sesión, aceptás nuestros Términos de uso y Política de privacidad
Uso
Este prompt está diseñado para usarse con coding. Copiá el contenido de arriba y pegalo en tu herramienta de IA preferida.
Para mejores resultados, personalizá los marcadores (indicados con corchetes o mayúsculas) con tus requisitos específicos.
Discusión
0 comentarios