When loading a conversation (after clicking a conversation), it shouldn't use the…
- User
When loading a conversation (after clicking a conversation), it shouldn't use the
marked.parseon user messages, only on the AI messages. - Assistant
When loading a conversation (after clicking a conversation), it shouldn't use the marked.parse on user messages, only on the AI messages.
You're absolutely correct. Applying marked.parse to user messages can pose security risks, such as Cross-Site Scripting (XSS) attacks, since users could input malicious content that gets rendered as HTML. To mitigate this risk, you should only parse the AI-generated messages (which you can control and sanitize) with marked.parse, and render user messages as plain text to ensure any potentially harmful input is not executed.
Here's how you can modify your code to apply marked.parse only to AI messages:
// Assuming you have a messages array with message objects
messages.forEach((message) => {
if (message.role === 'assistant') {
// Use marked.parse to render AI messages with Markdown
message.content = marked.parse(message.content);
} else if (message.role === 'user') {
// Render user messages as plain text to avoid security risks
message.content = escapeHtml(message.content);
}
});
// Function to escape HTML special characters in user messages
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
Explanation:
For AI Messages (`message.role === 'assistant'):
marked.parse() to convert Markdown content into HTML.For User Messages (`message.role === 'user'):
escapeHtml function to sanitize the input by escaping HTML special characters.Additional Tips:
Always Sanitize Inputs: Even when rendering AI messages, it’s a good practice to sanitize or validate the content if there's a possibility of unexpected input.
Use Trusted Libraries: Consider using libraries like DOMPurify after marked.parse() to sanitize the rendered HTML if necessary.
Consistent Rendering: Ensure that the styling for both user and AI messages remains consistent for a seamless user experience, even if the rendering methods differ.
Security Considerations:
Avoid Rendering User Input as HTML: Rendering user inputs directly as HTML without proper sanitization can lead to security vulnerabilities.
Regular Updates: Keep your dependencies, like marked, up to date to benefit from security patches and improvements.
By making this change, you'll enhance the security of your application while still providing rich content formatting in the AI responses.
If you need further assistance or have questions about implementing this solution, feel free to ask!
Not yet included in a published release.