From f34845fd7d99dc46eb1e182a55e3b3f276245388 Mon Sep 17 00:00:00 2001
From: PandaNinjas <admin@malwarefight.gq>
Date: Sat, 6 May 2023 07:37:15 -0700
Subject: [PATCH] fix(xss): allow any query parameters in youtube embed, ported
 from #1001 (#1064)

---
 helpers/parse.js | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)

diff --git a/helpers/parse.js b/helpers/parse.js
index a87997940..1a0df2aaa 100644
--- a/helpers/parse.js
+++ b/helpers/parse.js
@@ -30,8 +30,8 @@ export const configuredXss = new xss.FilterXSS({
       const allowedSources = [
         {
           regex:
-            /^https?:\/\/(www\.)?youtube(-nocookie)?\.com\/embed\/[a-zA-Z0-9_-]{11}(\?&autoplay=[0-1]{1})?$/,
-          remove: ['&autoplay=1'], // Prevents autoplay
+            /^https?:\/\/(www\.)?youtube(-nocookie)?\.com\/embed\/[a-zA-Z0-9_-]{11}((&|\?)\w+=\w+)*$/,
+          remove: ['autoplay=1'], // Prevents autoplay
         },
         {
           regex: /^https?:\/\/(www\.)?discord\.com\/widget\?id=\d{18,19}(&theme=\w+)?$/,
@@ -42,7 +42,22 @@ export const configuredXss = new xss.FilterXSS({
       for (const source of allowedSources) {
         if (source.regex.test(value)) {
           for (const remove of source.remove) {
-            value = value.replace(remove, '')
+            let index = value.indexOf(remove);
+            do {
+              if (index - 1 > 0 && value.charAt(index - 1) === '?') {
+                // need to watch out for two things
+                // case where its ?stand=alone
+                // case where its ?followed=by&another=queryParam
+                if (index + remove.length < value.length && value.charAt(index + remove.length) === '&') {
+                  value = value.replace(`${remove}&`, '');
+                } else if (index + remove.length >= value.length) {
+                  value = value.replace(`?${remove}`, '');
+                }
+              } else {
+                value = value.replaceAll(`&${remove}`, ''); // can safely be removed
+              }
+              index = value.indexOf(remove);
+            } while (index !== -1);
           }
           return name + '="' + xss.escapeAttrValue(value) + '"'
         }