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>
This commit is contained in:
Zaldimmar 2026-09-29 02:34:26 -05:00
parent fd40907ed6
commit be7e92417e
18 changed files with 226 additions and 59 deletions

View file

@ -18,7 +18,7 @@
image on the page.
═══════════════════════════════════════════════════════════════ */
import { decodeEntities, safeGet } from "./linkPreview.js";
import { decodeEntities, elements, innerOf, openTags, safeGet } from "./linkPreview.js";
const CACHE_MS = 30 * 60 * 1000;
const MAX_FEED_BYTES = 3 * 1024 * 1024;
@ -34,24 +34,32 @@ function unwrap(text) {
}
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
names may carry a namespace prefix (content:encoded). */
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 match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i"));
return match ? unwrap(match[1]) : null;
const text = innerOf(xml, tag);
return text == null ? null : unwrap(text);
}
function attrOf(xml, tag, name, where = () => true) {
for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) {
const el = match[0];
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;
const text = decodeEntities(html.replace(/<[^>]+>/g, " "));
// 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;
}
@ -74,21 +82,34 @@ function isoDate(raw) {
}
function firstImage(html) {
return html?.match(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null;
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) {
const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml);
const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? "");
const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? [];
// 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.slice(0, MAX_ITEMS_PER_FEED)) {
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") ?? "");
const title = decodeEntities(inner(block, "title")?.slice(0, 1000) ?? "");
if (!url || !title) continue;
const body = inner(block, "content:encoded") ?? inner(block, "content");
@ -123,20 +144,37 @@ async function fetchFeed(url) {
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 && Date.now() - hit.at < CACHE_MS) return hit.feed;
try {
const feed = await fetchFeed(url);
cache.set(url, { at: Date.now(), feed });
return feed;
} catch (err) {
console.warn(`feed ${url}: ${err.message}`);
// Serve the last good copy, and don't retry on every request.
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
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