NGU-Web/server/src/feeds.js
Zaldimmar be7e92417e Fix the Panel account bug and harden what the second audit found
- Panel: changing a role or disabling an account always failed
  (db.transaction doesn't exist on node:sqlite); it uses tx() now
- Feeds and link previews are scanned with indexOf, not whole-document
  regexes, so a hostile feed or page can't freeze the server; entity
  decoding can't throw; escaped-HTML descriptions make clean excerpts
- Feed reads share one fetch per feed and serve the stale copy while
  a refresh runs
- Deliberate HTTP errors (the CSRF 403) keep their status instead of
  becoming logged 500s; a JSON null body is handled
- url columns read the scheme the way the URL parser does, so
  control characters can't hide javascript:
- Google sign-in state cookie is __Host- and its return page is
  checked again; more reserved ranges blocked for previews and feeds,
  and a 15 s cap on each whole fetch
- Log lines from visitor text are made single-line and short; list
  limits can't go negative; entity names can't hit object prototypes
- A clip title can't point the clip tool at another file
- Uploads over 60 MP are refused before decoding; the Keep original
  help says a photo's location stays in it
- admin-cli add defaults to the editor role

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:34:26 -05:00

188 lines
7.2 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets
the same public-address checks, timeout and size cap as a link
preview. Results are kept in memory for CACHE_MS. A feed that
fails keeps serving what it last returned, and one that has never
worked contributes nothing: the section shows the pinned posts
and whatever the other feeds have, rather than an error.
Items come back as plain data: title, url, excerpt, image,
published (ISO), source. Only http(s) links and https images are
kept, so a feed can't put a javascript: link or a mixed-content
image on the page.
═══════════════════════════════════════════════════════════════ */
import { decodeEntities, elements, innerOf, openTags, safeGet } from "./linkPreview.js";
const CACHE_MS = 30 * 60 * 1000;
const MAX_FEED_BYTES = 3 * 1024 * 1024;
const MAX_ITEMS_PER_FEED = 20;
const EXCERPT_CHARS = 300;
const cache = new Map(); // url → { at, feed }
/* ── Parsing ───────────────────────────────────────────────── */
function unwrap(text) {
return text.replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1");
}
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
names may carry a namespace prefix (content:encoded). Scanned with
indexOf, not a regex: the feed is someone else's (see "Scanning
markup" in linkPreview.js). */
function inner(xml, tag) {
const text = innerOf(xml, tag);
return text == null ? null : unwrap(text);
}
function attrOf(xml, tag, name, where = () => true) {
for (const el of openTags(xml, tag, 50)) {
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
if (value && where(el)) return value[2] ?? value[3];
}
return null;
}
// Enough of a body or summary to make an excerpt from, so the tag
// strip and entity decoding never see more than this.
const PLAIN_SCAN = 20_000;
function plain(html) {
if (!html) return null;
// Tags stripped both before and after decoding: a description is
// often HTML written as entities (&lt;p&gt;).
const strip = (s) => s.replace(/<[^>]*>/g, " ");
const text = decodeEntities(strip(decodeEntities(strip(html.slice(0, PLAIN_SCAN)))));
if (!text) return null;
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
}
function safeUrl(raw, base, { httpsOnly = false } = {}) {
if (!raw) return null;
try {
const url = new URL(decodeEntities(raw), base);
if (url.protocol === "https:" || (!httpsOnly && url.protocol === "http:")) return url.toString();
} catch {
/* not a URL */
}
return null;
}
function isoDate(raw) {
if (!raw) return null;
const date = new Date(raw.trim());
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
function firstImage(html) {
if (!html) return null;
for (const tag of openTags(html, "img", 20)) {
const src = tag.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1];
if (src) return src;
}
return null;
}
function parseFeed(xml, feedUrl) {
// The root element is near the top; nothing needs the rest for this.
const top = xml.slice(0, 8192);
const root = openTags(top, "feed", 1)[0] ?? "";
const isAtom = /xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(root) && openTags(top, "rss", 1).length === 0;
const tag = isAtom ? "entry" : "item";
// The channel's own title is the one before the first item.
const firstItem = xml.toLowerCase().indexOf(`<${tag}`);
const channelTitle = decodeEntities(
inner(firstItem === -1 ? xml : xml.slice(0, firstItem), "title")?.slice(0, 1000) ?? "",
);
const blocks = elements(xml, tag, MAX_ITEMS_PER_FEED);
const items = [];
for (const block of blocks) {
const link = isAtom
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
: inner(block, "link");
const url = safeUrl(link?.trim(), feedUrl);
const title = decodeEntities(inner(block, "title")?.slice(0, 1000) ?? "");
if (!url || !title) continue;
const body = inner(block, "content:encoded") ?? inner(block, "content");
const summary = inner(block, "description") ?? inner(block, "summary");
const image =
attrOf(block, "enclosure", "url", (el) => /type\s*=\s*["']image\//i.test(el)) ??
attrOf(block, "media:content", "url") ??
attrOf(block, "media:thumbnail", "url") ??
firstImage(body) ??
firstImage(summary);
items.push({
title,
url,
excerpt: plain(summary) ?? plain(body),
image: safeUrl(image, feedUrl, { httpsOnly: true }),
published: isoDate(inner(block, "pubDate") ?? inner(block, "published") ?? inner(block, "updated")),
});
}
return { title: channelTitle || null, items };
}
/* ── Fetching ──────────────────────────────────────────────── */
async function fetchFeed(url) {
const result = await safeGet(url, {
maxBytes: MAX_FEED_BYTES,
accept: "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.1",
});
return parseFeed(result.body.toString("utf8"), result.url.toString());
}
/* One fetch at a time per feed, shared by everyone who asks while it
runs. A failure keeps the last good copy and waits 5 minutes before
trying again, rather than retrying on every request. */
function refresh(url) {
const hit = cache.get(url);
if (hit?.pending) return hit.pending;
const pending = fetchFeed(url)
.then((feed) => {
cache.set(url, { at: Date.now(), feed });
return feed;
})
.catch((err) => {
console.warn(`feed ${url}: ${err.message}`);
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
});
cache.set(url, { ...hit, pending });
return pending;
}
/* A fresh copy as it is; a stale one straight away while a refresh
runs behind it, so no visitor waits on someone else's server once
the feed has been read once. Only the very first read waits. */
async function readFeed(url) {
const hit = cache.get(url);
if (hit?.feed) {
if (Date.now() - hit.at >= CACHE_MS) refresh(url);
return hit.feed;
}
return refresh(url);
}
/* Every listed feed's items, newest first, each tagged with its
source: the row's label, else the feed's own title. */
export async function readFeeds(rows) {
const feeds = await Promise.all(rows.map((row) => readFeed(row.url)));
const items = feeds.flatMap((feed, i) =>
feed.items.map((item) => ({ ...item, source: rows[i].label || feed.title })),
);
return items.sort((a, b) => (b.published ?? "").localeCompare(a.published ?? ""));
}