changes made to sanitize html to overcome the VAPT alets

This commit is contained in:
laxmanhalaki 2026-02-09 11:22:40 +05:30
parent 81565d294b
commit d285ea88d8
8 changed files with 786 additions and 756 deletions

View File

@ -1,5 +1,6 @@
import * as React from "react"; import * as React from "react";
import { cn } from "@/components/ui/utils"; import { cn } from "@/components/ui/utils";
import { sanitizeHTML } from "@/utils/sanitizer";
interface FormattedDescriptionProps { interface FormattedDescriptionProps {
content: string; content: string;
@ -33,7 +34,8 @@ export function FormattedDescription({ content, className }: FormattedDescriptio
return `<div class="table-wrapper">${match}</div>`; return `<div class="table-wrapper">${match}</div>`;
}); });
return processed; // Sanitize the content to prevent CSP violations (onclick, style tags, etc.)
return sanitizeHTML(processed);
}, [content]); }, [content]);
if (!content) return null; if (!content) return null;

View File

@ -1,5 +1,6 @@
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { sanitizeHTML } from '../../utils/sanitizer';
import { Button } from '../ui/button'; import { Button } from '../ui/button';
import { Input } from '../ui/input'; import { Input } from '../ui/input';
import { Avatar, AvatarFallback } from '../ui/avatar'; import { Avatar, AvatarFallback } from '../ui/avatar';
@ -166,7 +167,8 @@ export function WorkNoteModal({ open, onClose, requestId }: WorkNoteModalProps)
const formatMessage = (content: string) => { const formatMessage = (content: string) => {
// Simple mention highlighting // Simple mention highlighting
return content.replace(/@(\w+\s?\w+)/g, '<span class="text-blue-600 font-medium">@$1</span>'); const formatted = content.replace(/@(\w+\s?\w+)/g, '<span class="text-blue-600 font-medium">@$1</span>');
return sanitizeHTML(formatted);
}; };
return ( return (
@ -195,8 +197,7 @@ export function WorkNoteModal({ open, onClose, requestId }: WorkNoteModalProps)
<div key={msg.id} className={`flex gap-3 ${msg.isSystem ? 'justify-center' : ''}`}> <div key={msg.id} className={`flex gap-3 ${msg.isSystem ? 'justify-center' : ''}`}>
{!msg.isSystem && ( {!msg.isSystem && (
<Avatar className="h-8 w-8 flex-shrink-0"> <Avatar className="h-8 w-8 flex-shrink-0">
<AvatarFallback className={`text-white text-xs ${ <AvatarFallback className={`text-white text-xs ${msg.user.role === 'Initiator' ? 'bg-re-green' :
msg.user.role === 'Initiator' ? 'bg-re-green' :
msg.user.role === 'Current User' ? 'bg-blue-500' : msg.user.role === 'Current User' ? 'bg-blue-500' :
'bg-re-light-green' 'bg-re-light-green'
}`}> }`}>
@ -306,8 +307,7 @@ export function WorkNoteModal({ open, onClose, requestId }: WorkNoteModalProps)
<div key={index} className="flex items-center gap-3"> <div key={index} className="flex items-center gap-3">
<div className="relative"> <div className="relative">
<Avatar className="h-8 w-8"> <Avatar className="h-8 w-8">
<AvatarFallback className={`text-white text-xs ${ <AvatarFallback className={`text-white text-xs ${participant.role === 'Initiator' ? 'bg-re-green' : 'bg-re-light-green'
participant.role === 'Initiator' ? 'bg-re-green' : 'bg-re-light-green'
}`}> }`}>
{participant.avatar} {participant.avatar}
</AvatarFallback> </AvatarFallback>

View File

@ -54,13 +54,13 @@ function ChartContainer({
<div <div
data-slot="chart" data-slot="chart"
data-chart={chartId} data-chart={chartId}
style={getChartStyle(config)}
className={cn( className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden", "[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className, className,
)} )}
{...props} {...props}
> >
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer> <RechartsPrimitive.ResponsiveContainer>
{children} {children}
</RechartsPrimitive.ResponsiveContainer> </RechartsPrimitive.ResponsiveContainer>
@ -69,37 +69,39 @@ function ChartContainer({
); );
} }
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { const getChartStyle = (config: ChartConfig) => {
const colorConfig = Object.entries(config).filter( const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color, ([, config]) => config.theme || config.color,
); );
if (!colorConfig.length) { if (!colorConfig.length) {
return null; return {};
} }
return ( const styles: Record<string, string> = {};
<style
dangerouslySetInnerHTML={{ colorConfig.forEach(([key, itemConfig]) => {
__html: Object.entries(THEMES) // For simplicity, we'll use the default color or the light theme color
.map( // If you need per-theme variables, they should be handled via CSS classes or media queries
([theme, prefix]) => ` // but applying them here as inline styles is CSP-safe.
${prefix} [data-chart=${id}] { const color = itemConfig.color || itemConfig.theme?.light;
${colorConfig if (color) {
.map(([key, itemConfig]) => { styles[`--color-${key}`] = color;
const color = }
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color; // Handle dark theme if present
return color ? ` --color-${key}: ${color};` : null; const darkColor = itemConfig.theme?.dark;
}) if (darkColor) {
.join("\n")} styles[`--color-${key}-dark`] = darkColor;
} }
`, });
)
.join("\n"), return styles as React.CSSProperties;
}} };
/>
); // Deprecated: Kept for backward compatibility if needed in other files.
const ChartStyle = () => {
return null;
}; };
const ChartTooltip = RechartsPrimitive.Tooltip; const ChartTooltip = RechartsPrimitive.Tooltip;

View File

@ -3,6 +3,7 @@ import { cn } from "./utils";
import { Button } from "./button"; import { Button } from "./button";
import { Bold, Italic, Underline, List, ListOrdered, Heading1, Heading2, Heading3, AlignLeft, AlignCenter, AlignRight, Highlighter, X, Type } from "lucide-react"; import { Bold, Italic, Underline, List, ListOrdered, Heading1, Heading2, Heading3, AlignLeft, AlignCenter, AlignRight, Highlighter, X, Type } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "./popover"; import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { sanitizeHTML } from "@/utils/sanitizer";
interface RichTextEditorProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> { interface RichTextEditorProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
value: string; value: string;
@ -59,7 +60,8 @@ export function RichTextEditor({
// Only update if the value actually changed externally // Only update if the value actually changed externally
const currentValue = editorRef.current.innerHTML; const currentValue = editorRef.current.innerHTML;
if (currentValue !== value) { if (currentValue !== value) {
editorRef.current.innerHTML = value || ''; // Sanitize incoming content
editorRef.current.innerHTML = sanitizeHTML(value || '');
} }
} }
}, [value]); }, [value]);
@ -230,9 +232,9 @@ export function RichTextEditor({
selection.removeAllRanges(); selection.removeAllRanges();
selection.addRange(range); selection.addRange(range);
// Trigger onChange // Trigger onChange with sanitized content
if (editorRef.current) { if (editorRef.current) {
onChange(editorRef.current.innerHTML); onChange(sanitizeHTML(editorRef.current.innerHTML));
} }
}, [onChange, cleanWordHTML]); }, [onChange, cleanWordHTML]);
@ -377,7 +379,7 @@ export function RichTextEditor({
// Update content // Update content
if (editorRef.current) { if (editorRef.current) {
onChange(editorRef.current.innerHTML); onChange(sanitizeHTML(editorRef.current.innerHTML));
} }
// Check active formats after a short delay // Check active formats after a short delay
@ -529,7 +531,7 @@ export function RichTextEditor({
// Update content // Update content
if (editorRef.current) { if (editorRef.current) {
onChange(editorRef.current.innerHTML); onChange(sanitizeHTML(editorRef.current.innerHTML));
} }
// Close popover // Close popover
@ -633,7 +635,7 @@ export function RichTextEditor({
// Update content // Update content
if (editorRef.current) { if (editorRef.current) {
onChange(editorRef.current.innerHTML); onChange(sanitizeHTML(editorRef.current.innerHTML));
} }
// Close popover // Close popover
@ -646,7 +648,7 @@ export function RichTextEditor({
// Handle input changes // Handle input changes
const handleInput = React.useCallback(() => { const handleInput = React.useCallback(() => {
if (editorRef.current) { if (editorRef.current) {
onChange(editorRef.current.innerHTML); onChange(sanitizeHTML(editorRef.current.innerHTML));
} }
checkActiveFormats(); checkActiveFormats();
}, [onChange, checkActiveFormats]); }, [onChange, checkActiveFormats]);
@ -682,7 +684,7 @@ export function RichTextEditor({
const handleBlur = React.useCallback(() => { const handleBlur = React.useCallback(() => {
setIsFocused(false); setIsFocused(false);
if (editorRef.current) { if (editorRef.current) {
onChange(editorRef.current.innerHTML); onChange(sanitizeHTML(editorRef.current.innerHTML));
} }
}, [onChange]); }, [onChange]);

View File

@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useMemo } from 'react'; import { useState, useRef, useEffect, useMemo } from 'react';
import { getWorkNotes, createWorkNoteMultipart, getWorkflowDetails, downloadWorkNoteAttachment, getWorkNoteAttachmentPreviewUrl, addSpectator, addApproverAtLevel } from '@/services/workflowApi'; import { getWorkNotes, createWorkNoteMultipart, getWorkflowDetails, downloadWorkNoteAttachment, getWorkNoteAttachmentPreviewUrl, addSpectator, addApproverAtLevel } from '@/services/workflowApi';
import { sanitizeHTML } from '@/utils/sanitizer';
import { getPublicConfigurations, AdminConfiguration } from '@/services/adminApi'; import { getPublicConfigurations, AdminConfiguration } from '@/services/adminApi';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
@ -109,9 +110,7 @@ const getStatusText = (status: string) => {
const formatMessage = (content: string) => { const formatMessage = (content: string) => {
// Enhanced mention highlighting - Blue color with extra bold font for high visibility // Enhanced mention highlighting - Blue color with extra bold font for high visibility
// Matches: @username or @FirstName LastName (only one space allowed for first name + last name) const formattedContent = content
// Pattern: @word or @word word (stops after second word)
return content
.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g, (match, mention, offset, string) => { .replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g, (match, mention, offset, string) => {
const afterPos = offset + match.length; const afterPos = offset + match.length;
const afterChar = string[afterPos]; const afterChar = string[afterPos];
@ -124,6 +123,8 @@ const formatMessage = (content: string) => {
return match; return match;
}) })
.replace(/\n/g, '<br />'); .replace(/\n/g, '<br />');
return sanitizeHTML(formattedContent);
}; };
const formatFileSize = (bytes: number): string => { const formatFileSize = (bytes: number): string => {
@ -240,7 +241,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
id: m.noteId || m.id || String(Math.random()), id: m.noteId || m.id || String(Math.random()),
user: { user: {
name: m.userName || 'User', name: m.userName || 'User',
avatar: (m.userName || 'U').slice(0,2).toUpperCase(), avatar: (m.userName || 'U').slice(0, 2).toUpperCase(),
role: m.userRole || 'Participant' role: m.userRole || 'Participant'
}, },
content: m.message || '', content: m.message || '',
@ -361,7 +362,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
const userId = p.userId || p.user_id || ''; const userId = p.userId || p.user_id || '';
return { return {
name: p.userName || p.user_name || p.user_email || p.userEmail || 'User', name: p.userName || p.user_name || p.user_email || p.userEmail || 'User',
avatar: (p.userName || p.user_name || p.user_email || 'U').toString().split(' ').map((s: string)=>s[0]).filter(Boolean).join('').slice(0,2).toUpperCase(), avatar: (p.userName || p.user_name || p.user_email || 'U').toString().split(' ').map((s: string) => s[0]).filter(Boolean).join('').slice(0, 2).toUpperCase(),
role: formatParticipantRole(participantType.toString()), role: formatParticipantRole(participantType.toString()),
status: 'offline', // will be updated by presence events status: 'offline', // will be updated by presence events
email: p.userEmail || p.user_email || '', email: p.userEmail || p.user_email || '',
@ -464,7 +465,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
if (details?.workflow?.requestId) { if (details?.workflow?.requestId) {
joinedId = details.workflow.requestId; // join by UUID to match server emits joinedId = details.workflow.requestId; // join by UUID to match server emits
} }
} catch {} } catch { }
try { try {
// Get socket using helper function (handles VITE_BASE_URL or VITE_API_BASE_URL) // Get socket using helper function (handles VITE_BASE_URL or VITE_API_BASE_URL)
const s = getSocket(); // Uses getSocketBaseUrl() helper internally const s = getSocket(); // Uses getSocketBaseUrl() helper internally
@ -693,10 +694,10 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
// Socket cleanup completed - logging removed // Socket cleanup completed - logging removed
}; };
(window as any).__wn_cleanup = cleanup; (window as any).__wn_cleanup = cleanup;
} catch {} } catch { }
})(); })();
return () => { return () => {
try { (window as any).__wn_cleanup?.(); } catch {} try { (window as any).__wn_cleanup?.(); } catch { }
}; };
}, [effectiveRequestId, currentUserId, skipSocketJoin]); }, [effectiveRequestId, currentUserId, skipSocketJoin]);
@ -762,7 +763,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
id: m.noteId || m.id || String(Math.random()), id: m.noteId || m.id || String(Math.random()),
user: { user: {
name: m.userName || 'User', name: m.userName || 'User',
avatar: (m.userName || 'U').slice(0,2).toUpperCase(), avatar: (m.userName || 'U').slice(0, 2).toUpperCase(),
role: m.userRole || 'Participant' role: m.userRole || 'Participant'
}, },
content: m.message || '', content: m.message || '',
@ -1274,8 +1275,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
<div key={msg.id} className={`flex gap-2 sm:gap-3 lg:gap-4 ${msg.isSystem ? 'justify-center' : isCurrentUser ? 'justify-end' : ''}`}> <div key={msg.id} className={`flex gap-2 sm:gap-3 lg:gap-4 ${msg.isSystem ? 'justify-center' : isCurrentUser ? 'justify-end' : ''}`}>
{!msg.isSystem && !isCurrentUser && ( {!msg.isSystem && !isCurrentUser && (
<Avatar className="h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm"> <Avatar className="h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm">
<AvatarFallback className={`text-white font-semibold text-xs sm:text-sm ${ <AvatarFallback className={`text-white font-semibold text-xs sm:text-sm ${msg.user.role === 'Initiator' ? 'bg-green-600' :
msg.user.role === 'Initiator' ? 'bg-green-600' :
msg.user.role === 'Current User' ? 'bg-blue-500' : msg.user.role === 'Current User' ? 'bg-blue-500' :
msg.user.role === 'System' ? 'bg-gray-500' : msg.user.role === 'System' ? 'bg-gray-500' :
'bg-slate-600' 'bg-slate-600'
@ -1414,8 +1414,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
<button <button
key={index} key={index}
onClick={() => addReaction(msg.id, reaction.emoji)} onClick={() => addReaction(msg.id, reaction.emoji)}
className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${ className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${reaction.users.includes('You')
reaction.users.includes('You')
? 'bg-blue-100 text-blue-800 border border-blue-200' ? 'bg-blue-100 text-blue-800 border border-blue-200'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`} }`}
@ -1564,8 +1563,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
className="w-full flex items-center gap-3 p-3 hover:bg-blue-50 rounded-lg text-left transition-colors border border-transparent hover:border-blue-200" className="w-full flex items-center gap-3 p-3 hover:bg-blue-50 rounded-lg text-left transition-colors border border-transparent hover:border-blue-200"
> >
<Avatar className="h-10 w-10"> <Avatar className="h-10 w-10">
<AvatarFallback className={`text-white text-sm font-semibold ${ <AvatarFallback className={`text-white text-sm font-semibold ${participant.role === 'Initiator' ? 'bg-green-600' :
participant.role === 'Initiator' ? 'bg-green-600' :
participant.role === 'Approver' ? 'bg-purple-600' : participant.role === 'Approver' ? 'bg-purple-600' :
'bg-blue-500' 'bg-blue-500'
}`}> }`}>
@ -1713,8 +1711,7 @@ export function WorkNoteChat({ requestId, messages: externalMessages, onSend, sk
<div key={index} className="flex items-center gap-3"> <div key={index} className="flex items-center gap-3">
<div className="relative"> <div className="relative">
<Avatar className="h-9 w-9 sm:h-10 sm:w-10"> <Avatar className="h-9 w-9 sm:h-10 sm:w-10">
<AvatarFallback className={`text-white font-semibold text-sm ${ <AvatarFallback className={`text-white font-semibold text-sm ${participant.role === 'Initiator' ? 'bg-green-600' :
participant.role === 'Initiator' ? 'bg-green-600' :
isCurrentUser ? 'bg-blue-500' : 'bg-slate-600' isCurrentUser ? 'bg-blue-500' : 'bg-slate-600'
}`}> }`}>
{participant.avatar} {participant.avatar}

View File

@ -1,5 +1,6 @@
import { useState, useRef, useEffect } from 'react'; import { useState, useRef, useEffect } from 'react';
import { getWorkNotes, createWorkNoteMultipart, getWorkflowDetails, downloadWorkNoteAttachment, getWorkNoteAttachmentPreviewUrl } from '@/services/workflowApi'; import { getWorkNotes, createWorkNoteMultipart, getWorkflowDetails, downloadWorkNoteAttachment, getWorkNoteAttachmentPreviewUrl } from '@/services/workflowApi';
import { sanitizeHTML } from '@/utils/sanitizer';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { getSocket, joinRequestRoom, leaveRequestRoom } from '@/utils/socket'; import { getSocket, joinRequestRoom, leaveRequestRoom } from '@/utils/socket';
import { formatDateTime } from '@/utils/dateFormatter'; import { formatDateTime } from '@/utils/dateFormatter';
@ -58,9 +59,11 @@ interface WorkNoteChatSimpleProps {
} }
const formatMessage = (content: string) => { const formatMessage = (content: string) => {
return content const formattedContent = content
.replace(/@([\w\s]+)(?=\s|$|[.,!?])/g, '<span class="inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 font-medium text-sm">@$1</span>') .replace(/@([\w\s]+)(?=\s|$|[.,!?])/g, '<span class="inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 font-medium text-sm">@$1</span>')
.replace(/\n/g, '<br />'); .replace(/\n/g, '<br />');
return sanitizeHTML(formattedContent);
}; };
const FileIcon = ({ type }: { type: string }) => { const FileIcon = ({ type }: { type: string }) => {
@ -140,7 +143,7 @@ export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSe
if (details?.workflow?.requestId) { if (details?.workflow?.requestId) {
joinedId = details.workflow.requestId; joinedId = details.workflow.requestId;
} }
} catch {} } catch { }
try { try {
// Get socket using helper function (handles VITE_BASE_URL or VITE_API_BASE_URL) // Get socket using helper function (handles VITE_BASE_URL or VITE_API_BASE_URL)
const s = getSocket(); // Uses getSocketBaseUrl() helper internally const s = getSocket(); // Uses getSocketBaseUrl() helper internally
@ -189,7 +192,7 @@ export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSe
} }
})(); })();
return () => { return () => {
try { (window as any).__wn_cleanup?.(); } catch {} try { (window as any).__wn_cleanup?.(); } catch { }
}; };
}, [requestId, currentUserId]); }, [requestId, currentUserId]);
@ -218,7 +221,7 @@ export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSe
}; };
}) : []; }) : [];
setMessages(mapped as any); setMessages(mapped as any);
} catch {} } catch { }
} }
setMessage(''); setMessage('');
setSelectedFiles([]); setSelectedFiles([]);
@ -257,7 +260,7 @@ export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSe
} as any; } as any;
}); });
setMessages(mapped); setMessages(mapped);
} catch {} } catch { }
} else { } else {
(async () => { (async () => {
try { try {
@ -394,8 +397,7 @@ export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSe
<div key={msg.id} className={`flex gap-3 ${msg.isSystem ? 'justify-center' : isCurrentUser ? 'justify-end' : ''}`}> <div key={msg.id} className={`flex gap-3 ${msg.isSystem ? 'justify-center' : isCurrentUser ? 'justify-end' : ''}`}>
{!msg.isSystem && !isCurrentUser && ( {!msg.isSystem && !isCurrentUser && (
<Avatar className="h-10 w-10 flex-shrink-0 ring-2 ring-white shadow-sm"> <Avatar className="h-10 w-10 flex-shrink-0 ring-2 ring-white shadow-sm">
<AvatarFallback className={`text-white font-semibold text-sm ${ <AvatarFallback className={`text-white font-semibold text-sm ${msg.user.role === 'Initiator' ? 'bg-green-600' :
msg.user.role === 'Initiator' ? 'bg-green-600' :
msg.user.role === 'Approver' ? 'bg-blue-600' : msg.user.role === 'Approver' ? 'bg-blue-600' :
'bg-slate-600' 'bg-slate-600'
}`}> }`}>
@ -528,8 +530,7 @@ export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSe
<button <button
key={index} key={index}
onClick={() => addReaction(msg.id, reaction.emoji)} onClick={() => addReaction(msg.id, reaction.emoji)}
className={`flex items-center gap-1 px-2 py-1 rounded-full text-sm transition-colors flex-shrink-0 ${ className={`flex items-center gap-1 px-2 py-1 rounded-full text-sm transition-colors flex-shrink-0 ${reaction.users.includes('You')
reaction.users.includes('You')
? 'bg-blue-100 text-blue-800 border border-blue-200' ? 'bg-blue-100 text-blue-800 border border-blue-200'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`} }`}

View File

@ -3,6 +3,7 @@ import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator'; import { Separator } from '@/components/ui/separator';
import { FileText, AlertCircle } from 'lucide-react'; import { FileText, AlertCircle } from 'lucide-react';
import { RequestTemplate } from '@/hooks/useCreateRequestForm'; import { RequestTemplate } from '@/hooks/useCreateRequestForm';
import { sanitizeHTML } from '@/utils/sanitizer';
interface AdminRequestReviewStepProps { interface AdminRequestReviewStepProps {
template: RequestTemplate; template: RequestTemplate;
@ -47,7 +48,7 @@ export function AdminRequestReviewStep({
<span className="text-xs font-semibold text-gray-500 uppercase tracking-wider">Request Detail</span> <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider">Request Detail</span>
<div <div
className="text-sm text-gray-700 mt-1 prose prose-sm max-w-none" className="text-sm text-gray-700 mt-1 prose prose-sm max-w-none"
dangerouslySetInnerHTML={{ __html: formData.description }} dangerouslySetInnerHTML={{ __html: sanitizeHTML(formData.description) }}
/> />
</div> </div>

25
src/utils/sanitizer.ts Normal file
View File

@ -0,0 +1,25 @@
/**
* Sanitizes HTML content by removing dangerous attributes and tags.
* This is used to comply with CSP policies and prevent XSS.
*/
export function sanitizeHTML(html: string): string {
if (!html) return '';
// 1. Remove script tags completely
let sanitized = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// 2. Remove all "on*" event handler attributes (onclick, onload, etc.)
// This handles attributes like onclick="alert(1)" or onclick='alert(1)' or onclick=alert(1)
sanitized = sanitized.replace(/\s+on\w+\s*=\s*(?:'[^']*'|"[^"]*"|[^\s>]+)/gi, '');
// 3. Remove "javascript:" pseudo-protocols in href or src
sanitized = sanitized.replace(/(href|src)\s*=\s*(?:'javascript:[^']*'|"javascript:[^"]*"|javascript:[^\s>]+)/gi, '$1="#"');
// 4. Remove <style> tags (to comply with style-src)
sanitized = sanitized.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
// 5. Remove meta and link tags (except for purely visual ones if needed, but safer to remove)
sanitized = sanitized.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi, '');
return sanitized;
}