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

@ -34,6 +34,8 @@ import net from "node:net";
import { MAX_UPLOAD_BYTES, MediaError } from "./media.js";
const TIMEOUT_MS = 8000;
// The whole request, however steadily the bytes trickle in.
const TOTAL_TIMEOUT_MS = 15000;
const MAX_REDIRECTS = 4;
const MAX_HTML_BYTES = 1024 * 1024;
const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
@ -48,12 +50,13 @@ const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
const BLOCKED = new net.BlockList();
for (const [ip, bits] of [
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16],
["198.18.0.0", 15], ["224.0.0.0", 3],
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24],
["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24],
["224.0.0.0", 3],
]) BLOCKED.addSubnet(ip, bits, "ipv4");
for (const [ip, bits] of [
["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16],
["fc00::", 7], ["fe80::", 10], ["ff00::", 8],
["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8], ["2001:db8::", 32],
]) BLOCKED.addSubnet(ip, bits, "ipv6");
function ipBlocked(ip) {
@ -146,6 +149,14 @@ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) {
},
);
req.on("timeout", () => req.destroy(new MediaError(504, "The site took too long to answer.")));
// `timeout` above only fires when the socket goes quiet; a server
// sending a byte every few seconds would hold the request open
// for hours. This caps the whole exchange.
const deadline = setTimeout(
() => req.destroy(new MediaError(504, "The site took too long to answer.")),
TOTAL_TIMEOUT_MS,
);
req.on("close", () => clearTimeout(deadline));
req.on("error", (err) =>
reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")),
);
@ -169,15 +180,82 @@ export async function safeGet(raw, options) {
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
// A code point past U+10FFFF would make fromCodePoint throw.
const codePoint = (n) => String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
export function decodeEntities(text) {
return text
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
.replace(/&#x([0-9a-f]{1,6});/gi, (_, hex) => codePoint(parseInt(hex, 16)))
.replace(/&#(\d{1,7});/g, (_, dec) => codePoint(Number(dec)))
.replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole)
.replace(/\s+/g, " ")
.trim();
}
/* ── Scanning markup ───────────────────────────────────────────
Pages and feeds come from other people's servers, so nothing here
runs a regex over the whole document: a pattern like
/<meta[^>]*>/ restarts at every "<meta" and turns a few hundred KB
of unclosed tags into seconds of blocked event loop. These walk
the text once with indexOf; the regexes left only ever see one tag
or one short run of text.
───────────────────────────────────────────────────────────── */
const TAG_END = new Set([">", "/", " ", "\t", "\n", "\r"]);
/* Where the next <tag (followed by a space, / or >) starts, or -1. */
function tagStart(lower, name, from) {
for (let i = from; ; ) {
const at = lower.indexOf(name, i);
if (at === -1 || TAG_END.has(lower[at + name.length] ?? "")) return at;
i = at + name.length;
}
}
/* Each opening <tag ...> in text, up to `limit` of them. */
export function openTags(text, tag, limit = 200) {
const lower = text.toLowerCase();
const name = `<${tag.toLowerCase()}`;
const out = [];
for (let i = 0; out.length < limit; ) {
const start = tagStart(lower, name, i);
if (start === -1) break;
const end = lower.indexOf(">", start);
if (end === -1) break;
out.push(text.slice(start, end + 1));
i = end + 1;
}
return out;
}
/* Each whole <tag ...>…</tag> in text, up to `limit` of them. */
export function elements(text, tag, limit) {
const lower = text.toLowerCase();
const name = `<${tag.toLowerCase()}`;
const close = `</${tag.toLowerCase()}>`;
const out = [];
for (let i = 0; out.length < limit; ) {
const start = tagStart(lower, name, i);
if (start === -1) break;
const end = lower.indexOf(close, start);
if (end === -1) break;
out.push(text.slice(start, end + close.length));
i = end + close.length;
}
return out;
}
/* What's between the first <tag ...> and its </tag>, or null. */
export function innerOf(text, tag) {
const lower = text.toLowerCase();
const start = tagStart(lower, `<${tag.toLowerCase()}`, 0);
if (start === -1) return null;
const open = lower.indexOf(">", start);
if (open === -1) return null;
const end = lower.indexOf(`</${tag.toLowerCase()}>`, open);
return end === -1 ? null : text.slice(open + 1, end);
}
function attr(tag, name) {
const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null;
@ -185,12 +263,12 @@ function attr(tag, name) {
function readMeta(html) {
const meta = {};
for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) {
for (const tag of openTags(html, "meta")) {
const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase();
const content = attr(tag, "content");
if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content);
if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content.slice(0, 2000));
}
const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1];
const title = innerOf(html, "title")?.slice(0, 1000);
return {
title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null,
description: