From a94b34225d37eeedc91ba19bd4786f7683485c0a Mon Sep 17 00:00:00 2001 From: foxster-mp4 Date: Sun, 30 Apr 2023 11:01:55 -0700 Subject: [PATCH] Better HTTP URL validation --- js/main.js | 14 +++++++++----- js/shared.js | 40 ++++++++++++++++++++++++++++------------ 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/js/main.js b/js/main.js index 71cdcdf..bc71208 100644 --- a/js/main.js +++ b/js/main.js @@ -1,9 +1,13 @@ (function () { - // If no source or source is not a URL - if (!urlSearchParams.has('source') || !sourceURL.match(urlRegex)) - window.location.replace("index.html"); - insertAddToAltStoreBanner(); -})() + // If no source + if (!urlSearchParams.has('source')) + search(); + // If source is not a valid HTTP URL + else if (!isValidHTTPURL(sourceURL)) { + alert("Invalid HTTP URL."); + search(); + } else insertAddToAltStoreBanner(); +})(); fetch(sourceURL, { cache: "force-cache" diff --git a/js/shared.js b/js/shared.js index a226e04..a0e90a0 100644 --- a/js/shared.js +++ b/js/shared.js @@ -48,18 +48,6 @@ const appHeaderHTML = app => app ? ` ` : undefined; -function formatString(string) { - if (!string) return undefined; - - // URLs - const urlArray = string.match(urlRegex); - const urlSet = [...new Set(urlArray)]; // Converting to set to remove duplicates - urlSet.forEach(url => string = string.replaceAll(url, `${url}`)); - - // New lines - return string.replaceAll("\n", "
"); -} - function insertAddToAltStoreBanner() { document.getElementById("top")?.insertAdjacentHTML("afterbegin", `
@@ -96,6 +84,30 @@ function insertNavigationBar(title) { setUpBackButton(); } +// https://stackoverflow.com/a/43467144/19227228 +function isValidHTTPURL(string) { + var url; + try { + url = new URL(string); + } catch (error) { + console.error("An error occurred.", error); + return false; + } + return url.protocol == "http:" || url.protocol == "https:"; +} + +function formatString(string) { + if (!string) return undefined; + + // URLs + const urlArray = string.match(urlRegex); + const urlSet = [...new Set(urlArray)]; // Converting to set to remove duplicates + urlSet.forEach(url => string = string.replaceAll(url, `${url}`)); + + // New lines + return string.replaceAll("\n", "
"); +} + function setTintColor(color) { document.querySelector(':root')?.style.setProperty("--accent-color", `#${color}`); } @@ -104,6 +116,10 @@ function setUpBackButton() { document.getElementById("back")?.addEventListener("click", () => history.back(1)); } +function search() { + window.location.replace("search.html"); +} + const $ = selector => selector.startsWith("#") && !selector.includes(".") && !selector.includes(" ") ? document.getElementById(selector.substring(1)) : document.querySelectorAll(selector); \ No newline at end of file