From d6e1af0e7dedb34dcd9932105ee4f2ddbe98e221 Mon Sep 17 00:00:00 2001 From: Reto Brunner Date: Fri, 24 Jun 2022 10:55:33 +0200 Subject: [PATCH] Fix regex escape for prefix patterns Our regex escape function escapes proper regexes, however it isn't meant to be shoved into a char class via string interpolation. We need to also escape '-' if we do so. --- .../js/helpers/ircmessageparser/findChannels.ts | 11 +++++++++-- .../js/helpers/ircmessageparser/findChannels.ts | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/client/js/helpers/ircmessageparser/findChannels.ts b/client/js/helpers/ircmessageparser/findChannels.ts index 69296b41..f55ea586 100644 --- a/client/js/helpers/ircmessageparser/findChannels.ts +++ b/client/js/helpers/ircmessageparser/findChannels.ts @@ -8,6 +8,13 @@ export type ChannelPart = Part & { channel: string; }; +// escapes a regex in a way that's compatible to shove it in +// a regex char set (meaning it also escapes -) +function escapeRegExpCharSet(raw: string): string { + const escaped: string = escapeRegExp(raw); + return escaped.replace("-", "\\-"); +} + // Given an array of channel prefixes (such as "#" and "&") and an array of user // modes (such as "@" and "+"), this function extracts channels and nicks from a // text. @@ -18,8 +25,8 @@ function findChannels(text: string, channelPrefixes: string[], userModes: string // For example, a voiced user in #thelounge will have a /whois response of: // > foo is on the following channels: +#thelounge // We need to explicitly ignore user modes to parse such channels correctly. - const userModePattern = userModes.map(escapeRegExp).join(""); - const channelPrefixPattern = channelPrefixes.map(escapeRegExp).join(""); + const userModePattern = userModes.map(escapeRegExpCharSet).join(""); + const channelPrefixPattern = channelPrefixes.map(escapeRegExpCharSet).join(""); const channelPattern = `(?:^|\\s)[${userModePattern}]*([${channelPrefixPattern}][^ \u0007]+)`; const channelRegExp = new RegExp(channelPattern, "g"); diff --git a/test/client/js/helpers/ircmessageparser/findChannels.ts b/test/client/js/helpers/ircmessageparser/findChannels.ts index 7fed830b..bb45d828 100644 --- a/test/client/js/helpers/ircmessageparser/findChannels.ts +++ b/test/client/js/helpers/ircmessageparser/findChannels.ts @@ -122,6 +122,21 @@ describe("findChannels", () => { expect(actual).to.deep.equal(expected); }); + it("should work with - in usermodes", () => { + const input = "-#a some -text"; + const expected = [ + { + channel: "#a", + start: 1, + end: 3, + }, + ]; + + const actual = findChannels(input, ["#"], ["#", "+", "-"]); + + expect(actual).to.deep.equal(expected); + }); + it("should handle multiple channelPrefix correctly", () => { const input = "##test"; const expected = [