Skip to content

Commit

Permalink
Sanitize the user message before send (#287)
Browse files Browse the repository at this point in the history
* The message sanitizer function

* Sanitize the user message before send

---------

Co-authored-by: Anderson Dourado <[email protected]>
  • Loading branch information
inaciocorrea and andersonba committed Jan 26, 2024
1 parent 108f279 commit 58e9c64
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/core/sanitizers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ export function sanitizeListener(listener: IListener) {
};
}

export function sanitizeMessage(message: string): string {
const parser = new DOMParser();
const doc = parser.parseFromString(message, 'text/html');
return doc.body.textContent || '';
}

export function sanitizeRuleType(
ruleType: IRuleType | IRuleTypeExecutor
): IRuleType {
Expand Down
19 changes: 19 additions & 0 deletions src/ui/__tests__/bot.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -633,4 +633,23 @@ describe('DOM behaviors', () => {
input.dispatchEvent(inputEvent);
expect(input.style.height).toBe(`${scrollHeight}px`);
});

test('should sanitize message before send', async () => {
const rules = loadYaml(`
- message: value
type: String
`);

new YveBotUI(rules, OPTS).start();
const { input, submit, getUserMessages } = getChatElements();

input.value = '<h1>msg';
submit.click();

await sleep();

const message = getUserMessages()[0];
expect(message.innerHTML).toEqual('msg');
});

});
3 changes: 2 additions & 1 deletion src/ui/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isMobile } from 'is-mobile';
import YveBot from '../core';
import { sanitizeMessage } from '../core/sanitizers';
import { Answer, ChatMessageSource, IChatOptions, IRule } from '../types';
import { ChatUI } from './ui';

Expand Down Expand Up @@ -45,7 +46,7 @@ export default class YveBotUI extends YveBot {
this.UI.form.addEventListener('submit', evt => {
evt.preventDefault();
evt.stopPropagation();
const msg = this.UI.input.value.trim();
const msg = sanitizeMessage(this.UI.input.value.trim());

if (msg) {
this.hear(msg);
Expand Down

0 comments on commit 58e9c64

Please sign in to comment.