Skip to content

Commit

Permalink
Properly sanitizes loaded messages in tgui chat
Browse files Browse the repository at this point in the history
  • Loading branch information
S34NW committed Jan 14, 2024
1 parent 197f32a commit 4c32a70
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 60 deletions.
12 changes: 11 additions & 1 deletion tgui/packages/tgui-panel/chat/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* @license MIT
*/

import DOMPurify from 'dompurify';
import { storage } from 'common/storage';
import {
loadSettings,
Expand All @@ -29,7 +30,9 @@ import { MAX_PERSISTED_MESSAGES, MESSAGE_SAVE_INTERVAL } from './constants';
import { createMessage, serializeMessage } from './model';
import { chatRenderer } from './renderer';
import { selectChat, selectCurrentChatPage } from './selectors';
import { logger } from 'tgui/logging';

// List of blacklisted tags
const FORBID_TAGS = ['a', 'iframe', 'link', 'video'];

const saveChatToStorage = async (store) => {
const state = selectChat(store.getState());
Expand All @@ -55,6 +58,13 @@ const loadChatFromStorage = async (store) => {
return;
}
if (messages) {
for (let message of messages) {
if (message.html) {
message.html = DOMPurify.sanitize(message.html, {
FORBID_TAGS,
});
}
}
const batch = [
...messages,
createMessage({
Expand Down
49 changes: 49 additions & 0 deletions tgui/packages/tgui/sanitize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Uses DOMPurify to purify/sanitise HTML.
*/

import DOMPurify from 'dompurify';

// Default values
let defTag = [
'b',
'br',
'center',
'code',
'div',
'font',
'hr',
'i',
'li',
'menu',
'ol',
'p',
'pre',
'span',
'table',
'td',
'th',
'tr',
'u',
'ul',
];
let defAttr = ['class', 'style'];

/**
* Feed it a string and it should spit out a sanitized version.
*
* @param {string} input
* @param {array} tags
* @param {array} forbidAttr
*/
export const sanitizeText = (input, tags = defTag, forbidAttr = defAttr) => {
// This is VERY important to think first if you NEED
// the tag you put in here. We are pushing all this
// though dangerouslySetInnerHTML and even though
// the default DOMPurify kills javascript, it dosn't
// kill href links or such
return DOMPurify.sanitize(input, {
ALLOWED_TAGS: tags,
FORBID_ATTR: forbidAttr,
});
};
118 changes: 59 additions & 59 deletions tgui/public/tgui-panel.bundle.js

Large diffs are not rendered by default.

0 comments on commit 4c32a70

Please sign in to comment.