@@ -64,6 +64,9 @@ export class WordList extends Protection {
6464
6565 if ( event [ 'type' ] === 'm.room.message' ) {
6666 const message = content [ 'formatted_body' ] || content [ 'body' ] || null ;
67+ if ( ! message ) {
68+ return ;
69+ }
6770
6871 // Check conditions first
6972 if ( minsBeforeTrusting > 0 ) {
@@ -84,25 +87,25 @@ export class WordList extends Protection {
8487 return
8588 }
8689 }
87- if ( this . badWords === null ) {
88- // Create a mega-regex from all the tiny baby regexs
89- try {
90- this . badWords = new RegExp (
91- "(" + mjolnir . config . protections . wordlist . words . join ( ")|(" ) + ")" ,
92- "i"
93- ) ;
94- } catch ( ex ) {
95- await mjolnir . managementRoomOutput . logMessage ( LogLevel . ERROR , "WordList" , `Could not produce a regex from the word list:\n${ ex } .` )
90+ if ( ! this . badWords ) {
91+ // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
92+ const escapeRegExp = ( string : string ) => {
93+ return string . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
94+ } ;
95+
96+ // Create a mega-regex from all the tiny words.
97+ const words = mjolnir . config . protections . wordlist . words . filter ( word => word . length !== 0 ) . map ( escapeRegExp ) ;
98+ if ( words . length === 0 ) {
99+ mjolnir . managementRoomOutput . logMessage ( LogLevel . ERROR , "WordList" , `Someone turned on the word list protection without configuring any words. Disabling.` ) ;
100+ this . enabled = false ;
101+ return ;
96102 }
103+ this . badWords = new RegExp ( words . join ( "|" ) , "i" ) ;
97104 }
98105
99- if ( ! message ) {
100- return ;
101- }
102-
103- const matches = message . match ( this . badWords ! ) ;
104- if ( matches ) {
105- const reason = `bad word: ${ matches [ 0 ] } ` ;
106+ const match = this . badWords ! . exec ( message ) ;
107+ if ( match ) {
108+ const reason = `bad word: ${ match [ 0 ] } ` ;
106109 return [ new ConsequenceBan ( reason ) , new ConsequenceRedact ( reason ) ] ;
107110 }
108111 }
0 commit comments