It looks like there are a few issues in your WebSocket implementation, particularly around authentication and how you're handling incoming data (prompt). Below are the primary problems and how to fix them:
-
Authentication Middleware:
- WebSocket connections don't support the traditional Express middleware chain (i.e.,
next()), so you need to handle authentication within the WebSocket route itself.
-
Accessing req.body:
- WebSockets don't have a
req.body the way HTTP requests do. Instead, data should be received via WebSocket messages after the connection is established.
-
TypeScript Type Assertions:
- Ensure that TypeScript correctly recognizes any custom properties (like
user) added to the req object by your authentication middleware.
-
Error Handling:
- Properly handle asynchronous operations and potential errors to prevent unhandled promise rejections.
Here's the revised code addressing these issues:
import express from 'express';
import expressWs from 'express-ws';
import WebSocket from 'ws';
import { createRoadmapWithStatusUpdates } from '../src/services/roadmap.service/roadmapLongchain.service';
import app from '../src/app';
import { jwtAuth } from '../src/middlewares/auth.middlewares';
// Extend Express's Request interface to include `user`
declare module 'express-serve-static-core' {
interface Request {
user?: {
id: number;
// Include other user properties if needed
};
}
}
// Initialize WebSocket server with the Express app
const wsInstance = expressWs(app);
const wss = wsInstance.getWss();
// WebSocket route for roadmap creation
app.ws('/speck/v1/roadmap/create', async (ws: WebSocket, req: express.Request) => {
try {
// Authenticate the user
await new Promise<void>((resolve, reject) => {
jwtAuth(req, {} as express.Response, (err) => {
if (err) {
ws.send(JSON.stringify({ error: 'Unauthorized' }));
ws.close();
reject(new Error('Unauthorized'));
} else {
resolve();
}
});
});
// Ensure the user is attached to the request
if (!req.user) {
ws.send(JSON.stringify({ error: 'User not found after authentication' }));
ws.close();
return;
}
const userId = req.user.id;
ws.send(JSON.stringify({ progress: 0, message: "Starting roadmap creation..." }));
// Listen for the first message containing the prompt
ws.once('message', async (msg: WebSocket.Data) => {
try {
// Parse the incoming message
const data = typeof msg === 'string' ? JSON.parse(msg) : JSON.parse(msg.toString());
const { prompt } = data;
if (!prompt || typeof prompt !== 'string') {
ws.send(JSON.stringify({ error: 'Invalid or missing "prompt"' }));
ws.close();
return;
}
// Start the roadmap creation process
await createRoadmapWithStatusUpdates(prompt, userId, ws);
ws.send(JSON.stringify({ progress: 100, message: "Roadmap creation complete" }));
ws.close();
} catch (error) {
console.error('Error during roadmap creation:', error);
ws.send(JSON.stringify({ error: 'Roadmap creation failed', details: error.message }));
ws.close();
}
});
// Optional: Handle cases where the client disconnects before sending a message
ws.on('close', () => {
console.log('WebSocket connection closed before receiving prompt.');
});
} catch (error) {
// Authentication failed
console.error('Authentication error:', error);
// If not already handled, ensure the WebSocket is closed
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ error: 'Authentication failed' }));
ws.close();
}
}
});
export default app;
Detailed Breakdown of the Fixes
-
Authentication Handling:
- Before: You tried to pass a
next function to handle the continuation after authentication.
- After: The authentication is handled within a
Promise. If authentication fails, an error message is sent, and the connection is closed. If it succeeds, the process continues.
-
Receiving the prompt:
- Before: The code attempted to access
req.body.prompt, which isn't available in WebSocket connections.
- After: The server listens for the first message from the client, expecting it to contain the
prompt. This message is parsed, and the prompt is extracted for processing.
-
TypeScript Enhancements:
- Extended Express's
Request interface to include the user property. This ensures TypeScript recognizes req.user without type errors.
declare module 'express-serve-static-core' {
interface Request {
user?: {
id: number;
// Add other properties if necessary
};
}
}
-
Error Handling:
- Wrapped asynchronous operations in
try-catch blocks to capture and handle errors gracefully.
- Provided clear error messages to the client for different failure scenarios (e.g., authentication failure, missing prompt, processing errors).
-
WebSocket Event Handling:
- Used
ws.once('message', ...) to ensure that only the first message (which should contain the prompt) is processed. This prevents multiple prompts from being processed in the same connection.
- Added a
close event listener to handle cases where the client disconnects before sending the required prompt.
-
Security Considerations:
- Validated the
prompt to ensure it's present and of the correct type before proceeding with roadmap creation.
- Ensured that all error messages are sanitized and do not expose sensitive server information to the client.
Client-Side Considerations
Ensure that your client adheres to the following protocol when interacting with this WebSocket endpoint:
-
Establish the Connection:
- Connect to
/speck/v1/roadmap/create with the necessary authentication tokens, typically sent via query parameters or headers during the WebSocket handshake.
-
Send the Prompt:
-
Handle Responses:
- Listen for progress updates and final completion messages to update the UI or handle next steps accordingly.
Example Client-Side Implementation
Here's a simple example using JavaScript to interact with the WebSocket server:
const socket = new WebSocket('ws://yourserver.com/speck/v1/roadmap/create?token=YOUR_JWT_TOKEN');
socket.onopen = () => {
console.log('WebSocket connection established');
// Send the prompt after connection is open
const message = {
prompt: "Create a roadmap for integrating AI into our product."
};
socket.send(JSON.stringify(message));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.progress !== undefined) {
console.log(`Progress: ${data.progress}% - ${data.message}`);
}
if (data.error) {
console.error(`Error: ${data.error}`);
}
};
socket.onclose = () => {
console.log('WebSocket connection closed');
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
Final Notes
- Security: Always ensure that sensitive operations over WebSockets are secured, typically using WSS (WebSocket Secure) and proper authentication tokens.
- Scalability: If you plan to handle many concurrent WebSocket connections, ensure that your server infrastructure can scale accordingly.
- Resource Management: Implement proper cleanup and resource management to prevent memory leaks or other issues related to long-lived WebSocket connections.
By implementing these fixes and considerations, your WebSocket server should handle roadmap creation requests more reliably and securely.