Skip to content

Commit

Permalink
auto-detect url and e-mails in chat
Browse files Browse the repository at this point in the history
  • Loading branch information
vytdev committed Jun 18, 2024
1 parent 40ca882 commit a31170c
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/catalyst/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,59 @@ export function toRomanNumeral(num: number): string {

return '';
}

/**
* escape regular expression in strings
* @param string the string
* @returns {string}
*/
export function escapeRegExp(str: string): string {
// thx: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

/**
* a regex for validating urls. useful for whether filtering urls on chats, or just
* highlighting them automatically. e-mails can match by this regex too! it is good for
* general purpose, but it is not fully compliant to rfc 3986 (i just need this regex
* for the game)
*
* explanation:
*
* scheme
* (?:[\w\d-]+:\/\/)?
*
* username
* (?:[\w\d+_\.~-]+@)?
*
* host (dns and ipv4 part)
* (?:(?:[\w\d_-]+\.)+[\w\d_-]+|
*
* host (ipv6 part)
* \[[0-9a-fA-F:]+\])
*
* port
* (?::\d+)?
*
* start of path
* (?:\/
*
* dirs
* (?:[^\s\/$.?#]+\/)*
*
* file
* [^\s\/$.?#]*
*
* query (?a=b&c=d)
* (?:\?(?:[^\s\/$.?#=]+\=[^\s\/$.?#=]+)+(?:&[^\s\/$.?#=]+=[^\s\/$.?#=]+)*)?
*
* fragment
* (?:#[^\s\/$.?#]*)?
*
* end of path
* )?
*
* @author me (vytdev)
*/
export const urlRegex = /(?:[\w\d-]+:\/\/)?(?:[\w\d+_\.~-]+@)?(?:(?:[\w\d_-]+\.)+[\w\d_-]+|\[[0-9a-fA-F:]+\])(?::\d+)?(?:\/(?:[^\s\/$.?#]+\/)*[^\s\/$.?#]*(?:\?(?:[^\s\/$.?#=]+\=[^\s\/$.?#=]+)+(?:&[^\s\/$.?#=]+=[^\s\/$.?#=]+)*)?(?:#[^\s\/$.?#]*)?)?/gi;

9 changes: 9 additions & 0 deletions src/server/chats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
formatNumber,
message,
broadcast,
urlRegex
} from "../catalyst/index.js";
import { getClientById } from "./client.js";
import { isPlayerAdmin } from "./utils.js";
Expand Down Expand Up @@ -68,6 +69,14 @@ events.on("beforeChatSend", ev => {
msg = msg.replace(new RegExp(`\\[\\${config.commandPrefix}([^\\]]+)\\]`, "g"),
(_, cmd) => "§b[§e" + config.commandPrefix + cmd + "§b]§r");

// highlight urls
msg = msg.replace(urlRegex, "§3$&§r");

// warns the player if the message contains url or possibly e-mail addresses
if (urlRegex.test(msg))
plr.msg('§ewarning: we detected an e-mail address or a url in your message\n' +
'please ensure the message does not contain any of your private information!');

// the message is empty
if (!msg.length) return;

Expand Down

0 comments on commit a31170c

Please sign in to comment.