diff --git a/package-lock.json b/package-lock.json index da15b4af..5c85c222 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,7 +38,6 @@ "react": "^19.3.1", "react-best-gradient-color-picker": "^3.0.14", "react-dom": "^19.3.1", - "rss-parser": "^3.13.0", "semver": "^7.7.1", "sortablejs": "^1.15.7", "svelte": "^5.57.3", @@ -9986,25 +9985,6 @@ "dev": true, "license": "MIT" }, - "node_modules/rss-parser": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/rss-parser/-/rss-parser-3.13.0.tgz", - "integrity": "sha512-7jWUBV5yGN3rqMMj7CZufl/291QAhvrrGpDNE4k/02ZchL0npisiYYqULF71jCEKoIiHvK/Q2e6IkDwPziT7+w==", - "license": "MIT", - "dependencies": { - "entities": "^2.0.3", - "xml2js": "^0.5.0" - } - }, - "node_modules/rss-parser/node_modules/entities": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "license": "BSD-2-Clause", - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/runed": { "version": "0.37.1", "resolved": "https://registry.npmjs.org/runed/-/runed-0.37.1.tgz", @@ -10076,15 +10056,6 @@ "@parcel/watcher": "^2.4.1" } }, - "node_modules/sax": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", - "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=11.0.0" - } - }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -11460,28 +11431,6 @@ "node": ">=18" } }, - "node_modules/xml2js": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", - "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", - "license": "MIT", - "dependencies": { - "sax": ">=0.6.0", - "xmlbuilder": "~11.0.0" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/xmlbuilder": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", - "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", - "license": "MIT", - "engines": { - "node": ">=4.0" - } - }, "node_modules/xmlchars": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", diff --git a/package.json b/package.json index 0cfdd417..1f350745 100644 --- a/package.json +++ b/package.json @@ -100,7 +100,6 @@ "react": "^19.3.1", "react-best-gradient-color-picker": "^3.0.14", "react-dom": "^19.3.1", - "rss-parser": "^3.13.0", "semver": "^7.7.1", "sortablejs": "^1.15.7", "svelte": "^5.57.3", diff --git a/src/background.ts b/src/background.ts index 15e389f3..93fe310a 100644 --- a/src/background.ts +++ b/src/background.ts @@ -569,7 +569,7 @@ const MESSAGE_HANDLERS: Record = { sendResponse({ error: "Unauthorized sender" }); return false; } - fetchNews(req.source ?? "australia", sendResponse); + void fetchNews(req.source).then((news) => sendResponse({ news })); return true; }, fetchThemes: handleFetchThemes, diff --git a/src/background/news.ts b/src/background/news.ts index e82ac3e6..f5c7a71d 100644 --- a/src/background/news.ts +++ b/src/background/news.ts @@ -1,37 +1,18 @@ -import Parser from "rss-parser"; +import type { NewsFeed, NewsPayload } from "@/seqta/utils/newsFeed"; +const NEWS_API_KEY = "17c0da766ba347c89d094449504e3080"; const MAX_RATE_LIMIT_RETRIES = 3; - -const fetchAustraliaNews = async ( - url: string, - sendResponse: any, - rateLimitRetryCount = 0, -) => { - fetch(url) - .then((result) => result.json()) - .then((response) => { - if (response.code == "rateLimited" && rateLimitRetryCount < MAX_RATE_LIMIT_RETRIES) { - fetchAustraliaNews(`${url}%00`, sendResponse, rateLimitRetryCount + 1); - } else { - sendResponse({ news: response }); - } - }) - .catch((error) => { - console.error("[BetterSEQTA+] Failed to fetch Australia news", error); - sendResponse({ news: { articles: [] } }); - }); -}; +const REQUEST_TIMEOUT_MS = 10_000; +const DAY_MS = 86_400_000; const rssFeedsByCountry: Record = { usa: [ "https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml", - "https://www.huffpost.com/section/front-page/feed", - "https://www.npr.org/rss/rss.php", + "https://feeds.npr.org/1001/rss.xml", ], taiwan: [ "https://news.ltn.com.tw/rss/all.xml", "https://www.taipeitimes.com/xml/index.rss", - "https://international.thenewslens.com/rss", ], hong_kong: [ "https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml", @@ -41,87 +22,71 @@ const rssFeedsByCountry: Record = { "https://critica.com.pa/rss.xml", "https://www.panamaamerica.com.pa/rss.xml", "https://noticiassin.com/feed/", - "https://elcapitalfinanciero.com/feed/", ], canada: [ "https://www.cbc.ca/cmlink/rss-topstories", "https://calgaryherald.com/feed", "https://ottawacitizen.com/feed", - "https://www.montrealgazette.com/feed", ], singapore: [ "https://www.straitstimes.com/news/singapore/rss.xml", "https://www.channelnewsasia.com/rssfeeds/8395986", ], uk: [ - "http://feeds.bbci.co.uk/news/rss.xml", + "https://feeds.bbci.co.uk/news/rss.xml", "https://www.theguardian.com/uk/rss", ], japan: [ - "https://www3.nhk.or.jp/nhkworld/en/news/feeds/", + "https://www3.nhk.or.jp/rss/news/cat0.xml", "https://news.livedoor.com/topics/rss/int.xml", ], netherlands: ["https://www.dutchnews.nl/feed/", "https://www.nrc.nl/rss/"], }; -export async function fetchNews(source: string | undefined, sendResponse: any) { - const normalizedSource = typeof source === "string" && source.trim() - ? source.trim() - : "australia"; +async function fetchAustraliaNews(): Promise { + const from = new Date(Date.now() - 5 * DAY_MS).toISOString().slice(0, 10); + let url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=${NEWS_API_KEY}`; - if (normalizedSource === "australia") { - const date = new Date(); - date.setDate(date.getDate() - 5); - - const from = - date.getFullYear() + - "-" + - String(date.getMonth() + 1).padStart(2, "0") + - "-" + - String(date.getDate()).padStart(2, "0"); - - const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`; - fetchAustraliaNews(url, sendResponse); - - return; - } - - const parser = new Parser(); - let feeds: string[]; - - if (rssFeedsByCountry[normalizedSource.toLowerCase()]) { - feeds = rssFeedsByCountry[normalizedSource.toLowerCase()]; - } else if (normalizedSource.startsWith("http")) { - feeds = [normalizedSource]; - } else { - console.warn("[BetterSEQTA+] Invalid news source, falling back to Australia", normalizedSource); - return fetchNews("australia", sendResponse); - } - - const articlesPromises = feeds.map(async (feedUrl) => { - try { - const response = await fetch(feedUrl); - if (!response.ok) { - console.error(`Failed to fetch RSS feed: ${feedUrl} (${response.status})`); - return []; - } - const feedString = await response.text(); - const feed = await parser.parseString(feedString); - - return feed.items.map((item) => ({ - title: item.title || "", - description: item.contentSnippet || "", - url: item.link || "", - urlToImage: null, - })); - } catch (error) { - console.error(`Failed to fetch RSS feed: ${feedUrl}`, error); - return []; + try { + for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) { + const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); + const data = await response.json(); + if (data.code !== "rateLimited") return { articles: data.articles ?? [] }; + url += "%00"; } - }); + } catch (error) { + console.error("[BetterSEQTA+] Failed to fetch Australia news", error); + } + return { articles: [] }; +} + +async function fetchFeed(url: string): Promise { + const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return { url: response.url || url, xml: await response.text() }; +} + +function feedsForSource(source: string): string[] | null { + const preset = rssFeedsByCountry[source.toLowerCase()]; + if (preset) return preset; + return /^https?:\/\//i.test(source) ? [source] : null; +} + +export async function fetchNews(source?: string): Promise { + const normalizedSource = source?.trim() || "australia"; + if (normalizedSource === "australia") return fetchAustraliaNews(); - const articlesArray = await Promise.all(articlesPromises); - const articles = articlesArray.flat(); + const feedUrls = feedsForSource(normalizedSource); + if (!feedUrls) { + console.warn("[BetterSEQTA+] Invalid news source, falling back to Australia", normalizedSource); + return fetchAustraliaNews(); + } - sendResponse({ news: { articles } }); + const results = await Promise.allSettled(feedUrls.map(fetchFeed)); + const feeds = results.flatMap((result, i) => { + if (result.status === "fulfilled") return [result.value]; + console.error(`[BetterSEQTA+] Failed to fetch RSS feed: ${feedUrls[i]}`, result.reason); + return []; + }); + return { feeds }; } diff --git a/src/manifests/safari.ts b/src/manifests/safari.ts index b5669dad..9d702f55 100644 --- a/src/manifests/safari.ts +++ b/src/manifests/safari.ts @@ -1,19 +1,23 @@ import { createManifest } from "../../lib/createManifest.ts"; +import type { Manifest } from "../../lib/types.ts"; import baseManifest from "./manifest.json" with { type: "json" }; import pkg from "../../package.json" with { type: "json" }; -const updatedSafariManifest = { - ...baseManifest, - version: pkg.version, - description: pkg.description, - browser_specific_settings: { - safari: { - strict_min_version: "15.4", - strict_max_version: "*", - }, - // ^^^ https://developer.apple.com/documentation/safariservices/safari_web_extensions/optimizing_your_web_extension_for_safari#3743239 - // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings#safari_properties +type BrowserSpecificSettings = Extract["browser_specific_settings"]; + +const safariSettings = { + safari: { + strict_min_version: "17.4", + strict_max_version: "*", }, }; -export const safari = createManifest(updatedSafariManifest, "safari"); +export const safari = createManifest( + { + ...baseManifest, + version: pkg.version, + description: pkg.description, + browser_specific_settings: safariSettings as unknown as BrowserSpecificSettings, + }, + "safari", +); diff --git a/src/seqta/utils/SendNewsPage.ts b/src/seqta/utils/SendNewsPage.ts index 973e37bf..1261a307 100644 --- a/src/seqta/utils/SendNewsPage.ts +++ b/src/seqta/utils/SendNewsPage.ts @@ -7,6 +7,7 @@ import LogoLightOutline from "@/resources/icons/betterseqta-light-outline.png"; import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl"; import { animate, stagger } from "motion"; import { verboseInfo } from "@/utils/verboseLog"; +import { toNewsArticles, type NewsPayload } from "@/seqta/utils/newsFeed"; import { applyPageFeatureGateEarly, injectPageFeatureBanner, @@ -67,12 +68,12 @@ export async function SendNewsPage() { const response = (await browser.runtime.sendMessage({ type: "sendNews", source: settingsState.newsSource, - })) as any; + })) as { news?: NewsPayload } | undefined; const newscontainer = document.querySelector("#news-container"); document.getElementById("newsloading")?.remove(); - const articles = response?.news?.articles; - if (!Array.isArray(articles) || articles.length === 0) { + const articles = toNewsArticles(response?.news); + if (articles.length === 0) { const emptyState = document.createElement("div"); emptyState.classList.add("day-empty"); const img = document.createElement("img"); @@ -86,7 +87,7 @@ export async function SendNewsPage() { const fragment = document.createDocumentFragment(); - articles.forEach((article: any) => { + for (const article of articles) { const newsarticle = document.createElement("a"); newsarticle.classList.add("NewsArticle"); newsarticle.href = article.url; @@ -95,14 +96,14 @@ export async function SendNewsPage() { const articleimage = document.createElement("div"); articleimage.classList.add("articleimage"); - if (article.urlToImage == "null" || article.urlToImage == null) { + if (article.imageUrl) { + articleimage.style.backgroundImage = `url(${JSON.stringify(article.imageUrl)})`; + } else { articleimage.style.cssText = ` background-image: url(${resolveExtensionAssetUrl(LogoLightOutline)}); width: 20%; margin: 0 7.5%; `; - } else { - articleimage.style.backgroundImage = `url(${article.urlToImage})`; } const articletext = document.createElement("div"); @@ -114,19 +115,16 @@ export async function SendNewsPage() { title.target = "_blank"; const description = document.createElement("p"); - const articleDescription = typeof article.description === "string" - ? article.description - : "No description available."; - + const articleDescription = article.description || "No description available."; description.textContent = articleDescription.length > 400 - ? articleDescription.substring(0, 400) + "..." + ? `${articleDescription.slice(0, 400)}…` : articleDescription; articletext.append(title, description); newsarticle.append(articleimage, articletext); fragment.append(newsarticle); - }); + } newscontainer?.append(fragment); diff --git a/src/seqta/utils/newsFeed.test.ts b/src/seqta/utils/newsFeed.test.ts new file mode 100644 index 00000000..26303c34 --- /dev/null +++ b/src/seqta/utils/newsFeed.test.ts @@ -0,0 +1,107 @@ +/** + * @jest-environment jsdom + */ +import { describe, expect, it } from "@jest/globals"; +import { parseFeed, toNewsArticles } from "./newsFeed"; + +const rss2 = ` + + + Example + + Budget & tax + https://example.com/budget + The budget passed.

]]>
+ +
+ + Relative + /relative + Plain text + + + + Bad link + javascript:alert(1) + +
+
`; + +const atom = ` + + + Rain <em>today</em> + + + <img src="https://example.org/rain.jpg">Heavy rain expected. + +`; + +const rdf = ` + + + RDF item + https://example.net/rdf + From RSS 1.0 + +`; + +describe("parseFeed", () => { + it("parses RSS 2.0 items with media images and stripped HTML", () => { + const articles = parseFeed(rss2, "https://example.com/feed.xml"); + expect(articles).toEqual([ + { + title: "Budget & tax", + description: "The budget passed.", + url: "https://example.com/budget", + imageUrl: "https://example.com/budget.jpg", + }, + { + title: "Relative", + description: "Plain text", + url: "https://example.com/relative", + imageUrl: "https://example.com/photo.png", + }, + ]); + }); + + it("parses Atom entries using the alternate link and inline images", () => { + expect(parseFeed(atom)).toEqual([ + { + title: "Rain today", + description: "Heavy rain expected.", + url: "https://example.org/rain", + imageUrl: "https://example.org/rain.jpg", + }, + ]); + }); + + it("parses RSS 1.0 (RDF) items", () => { + expect(parseFeed(rdf)[0]).toMatchObject({ title: "RDF item", url: "https://example.net/rdf" }); + }); + + it("returns nothing for invalid XML", () => { + expect(parseFeed("")).toEqual([]); + }); +}); + +describe("toNewsArticles", () => { + it("normalises NewsAPI articles and drops unsafe links and images", () => { + expect( + toNewsArticles({ + articles: [ + { title: "Good", description: null, url: "https://abc.net.au/a", urlToImage: "https://abc.net.au/a.jpg" }, + { title: "Bad", url: "javascript:alert(1)" }, + { title: "No image", url: "https://abc.net.au/b", urlToImage: "data:image/png;base64,AAAA" }, + ], + }), + ).toEqual([ + { title: "Good", description: "", url: "https://abc.net.au/a", imageUrl: "https://abc.net.au/a.jpg" }, + { title: "No image", description: "", url: "https://abc.net.au/b", imageUrl: null }, + ]); + }); + + it("returns an empty list without a payload", () => { + expect(toNewsArticles(undefined)).toEqual([]); + }); +}); diff --git a/src/seqta/utils/newsFeed.ts b/src/seqta/utils/newsFeed.ts new file mode 100644 index 00000000..208f3f66 --- /dev/null +++ b/src/seqta/utils/newsFeed.ts @@ -0,0 +1,103 @@ +export type NewsApiArticle = { + title?: string | null; + description?: string | null; + url?: string | null; + urlToImage?: string | null; +}; + +export type NewsFeed = { url: string; xml: string }; + +export type NewsPayload = { articles: NewsApiArticle[] } | { feeds: NewsFeed[] }; + +export type NewsArticle = { + title: string; + description: string; + url: string; + imageUrl: string | null; +}; + +function safeHttpUrl(value: string | null | undefined, base?: string): string | null { + if (!value?.trim()) return null; + try { + const url = new URL(value.trim(), base); + return url.protocol === "https:" || url.protocol === "http:" ? url.href : null; + } catch { + return null; + } +} + +function htmlToText(html: string): string { + const doc = new DOMParser().parseFromString(html, "text/html"); + return (doc.body.textContent ?? "").replace(/\s+/g, " ").trim(); +} + +function firstImageInHtml(html: string): string | null { + return new DOMParser().parseFromString(html, "text/html").querySelector("img")?.getAttribute("src") ?? null; +} + +function children(el: Element, name: string): Element[] { + return [...el.children].filter((child) => child.localName === name); +} + +function childText(el: Element, ...names: string[]): string { + for (const name of names) { + const text = children(el, name)[0]?.textContent?.trim(); + if (text) return text; + } + return ""; +} + +function itemLink(item: Element): string { + const links = children(item, "link"); + const alternate = links.find((link) => (link.getAttribute("rel") ?? "alternate") === "alternate"); + return alternate?.getAttribute("href") || alternate?.textContent?.trim() || childText(item, "guid", "id"); +} + +function itemImage(item: Element, descriptionHtml: string): string | null { + const media = [...item.getElementsByTagNameNS("*", "thumbnail"), ...item.getElementsByTagNameNS("*", "content")] + .filter((el) => el.namespaceURI?.includes("mrss")) + .find((el) => el.getAttribute("url") && (!el.getAttribute("medium") || el.getAttribute("medium") === "image")); + if (media) return media.getAttribute("url"); + + const enclosure = children(item, "enclosure").find((el) => el.getAttribute("type")?.startsWith("image/")); + if (enclosure) return enclosure.getAttribute("url"); + + return descriptionHtml ? firstImageInHtml(descriptionHtml) : null; +} + +export function parseFeed(xml: string, feedUrl?: string): NewsArticle[] { + const doc = new DOMParser().parseFromString(xml, "application/xml"); + if (doc.querySelector("parsererror")) return []; + + return [...doc.querySelectorAll("item, entry")].flatMap((item) => { + const url = safeHttpUrl(itemLink(item), feedUrl); + if (!url) return []; + const descriptionHtml = childText(item, "description", "summary", "encoded", "content"); + return [ + { + title: htmlToText(childText(item, "title")), + description: htmlToText(descriptionHtml), + url, + imageUrl: safeHttpUrl(itemImage(item, descriptionHtml), url), + }, + ]; + }); +} + +export function toNewsArticles(payload: NewsPayload | undefined): NewsArticle[] { + if (!payload) return []; + if ("feeds" in payload) return payload.feeds.flatMap((feed) => parseFeed(feed.xml, feed.url)); + + return payload.articles.flatMap((article) => { + const url = safeHttpUrl(article.url); + if (!url) return []; + return [ + { + title: article.title ?? "", + description: article.description ?? "", + url, + imageUrl: safeHttpUrl(article.urlToImage), + }, + ]; + }); +}