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:
parent
fd40907ed6
commit
be7e92417e
18 changed files with 226 additions and 59 deletions
|
|
@ -55,6 +55,18 @@ Both lines are already in every proxied block in `nginx-dev` and in
|
||||||
`routes/auth.js`: five wrong passwords for one address lock it for
|
`routes/auth.js`: five wrong passwords for one address lock it for
|
||||||
the rest of 15 minutes, from anywhere; a correct one clears the
|
the rest of 15 minutes, from anywhere; a correct one clears the
|
||||||
count. Both are in memory and reset when the service restarts.
|
count. Both are in memory and reset when the service restarts.
|
||||||
|
- The per-email lock is a trade-off: anyone who knows an admin's
|
||||||
|
address can keep password sign-in for it locked by guessing wrong
|
||||||
|
five times every 15 minutes. Google sign-in still works for that
|
||||||
|
account, and the lock clears on a restart.
|
||||||
|
- `clientIp` trusts the last `X-Forwarded-For` entry, the one nginx
|
||||||
|
adds. If a CDN or another proxy is ever put in front of nginx, that
|
||||||
|
entry becomes the proxy's address and every visitor shares one
|
||||||
|
rate-limit bucket: set nginx's `real_ip_header` and
|
||||||
|
`set_real_ip_from` for the proxy first.
|
||||||
|
- The Google sign-in state cookie is `__Host-ngu_oauth` (plain
|
||||||
|
`ngu_oauth` over local http), and the page it returns to is checked
|
||||||
|
again when the browser comes back.
|
||||||
|
|
||||||
## From nginx: HSTS
|
## From nginx: HSTS
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,8 @@
|
||||||
admin + delete records
|
admin + delete records
|
||||||
superadmin + accounts, roles and sessions, via /admin/panel
|
superadmin + accounts, roles and sessions, via /admin/panel
|
||||||
|
|
||||||
add takes --role=editor, --name="Full Name". It defaults to
|
add takes --role=admin, --name="Full Name". It defaults to
|
||||||
admin. Press enter at the password prompt and it generates one
|
editor, the least that can change content; raise it on purpose. Press enter at the password prompt and it generates one
|
||||||
and prints it once.
|
and prints it once.
|
||||||
|
|
||||||
The list comes from auth.js rather than being repeated here, so
|
The list comes from auth.js rather than being repeated here, so
|
||||||
|
|
@ -139,7 +139,7 @@ function warnIfLastSuper(db, user) {
|
||||||
async function add(db, email, flags) {
|
async function add(db, email, flags) {
|
||||||
if (findUser(db, email)) fail(`${email} already exists. Use passwd to change it.`);
|
if (findUser(db, email)) fail(`${email} already exists. Use passwd to change it.`);
|
||||||
|
|
||||||
const role = checkRole(flags.role ?? "admin");
|
const role = checkRole(flags.role ?? "editor");
|
||||||
|
|
||||||
const password = await readPassword();
|
const password = await readPassword();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,9 @@ function coerceValue(column, raw, errors, prefix = "") {
|
||||||
}
|
}
|
||||||
case "url": {
|
case "url": {
|
||||||
const value = String(raw).trim();
|
const value = String(raw).trim();
|
||||||
const scheme = URL_SCHEME.exec(value)?.[1].toLowerCase();
|
// The URL parser ignores control characters, spaces and tabs
|
||||||
|
// inside a scheme ("java\tscript:"), so read it the same way.
|
||||||
|
const scheme = URL_SCHEME.exec(value.replace(/[\u0000-\u0020\u007f]/g, ""))?.[1].toLowerCase();
|
||||||
if (scheme && !SAFE_SCHEMES.has(scheme)) {
|
if (scheme && !SAFE_SCHEMES.has(scheme)) {
|
||||||
errors[key] = "Links must start with http://, https://, mailto: or tel:, or be a site path like /retreats.";
|
errors[key] = "Links must start with http://, https://, mailto: or tel:, or be a site path like /retreats.";
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -160,7 +162,7 @@ export function listRows(db, entity, query = {}) {
|
||||||
params.push(...search.map(() => term));
|
params.push(...search.map(() => term));
|
||||||
}
|
}
|
||||||
|
|
||||||
const limit = Math.min(Number(query.limit) || 200, 500);
|
const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500));
|
||||||
|
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(
|
||||||
|
|
|
||||||
|
|
@ -91,6 +91,12 @@ export function verifyPassword(password, stored) {
|
||||||
return timingSafeEqual(candidate, expected);
|
return timingSafeEqual(candidate, expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Text a visitor controls, made safe for one log line: control
|
||||||
|
characters (a newline would start a forged line) become "?", and
|
||||||
|
it's cut short. */
|
||||||
|
export const logSafe = (value, max = 200) =>
|
||||||
|
String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, max);
|
||||||
|
|
||||||
/* ── Hashing helpers ─────────────────────────────────────────── */
|
/* ── Hashing helpers ─────────────────────────────────────────── */
|
||||||
|
|
||||||
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
||||||
|
|
|
||||||
|
|
@ -330,8 +330,17 @@ async function download(db, job) {
|
||||||
if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) });
|
if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) });
|
||||||
const t = line.match(/^TITLE (.+)$/);
|
const t = line.match(/^TITLE (.+)$/);
|
||||||
if (t) title = t[1].slice(0, 300);
|
if (t) title = t[1].slice(0, 300);
|
||||||
|
// Only this job's own output file counts: a video title with
|
||||||
|
// a newline in it could print a "FILE ..." line of its own.
|
||||||
const f = line.match(/^FILE (.+)$/);
|
const f = line.match(/^FILE (.+)$/);
|
||||||
if (f) file = f[1].trim();
|
const candidate = f?.[1].trim();
|
||||||
|
if (
|
||||||
|
candidate &&
|
||||||
|
path.resolve(path.dirname(candidate)) === path.resolve(CLIPS_DIR) &&
|
||||||
|
path.basename(candidate).startsWith(`source-${job.id}.`)
|
||||||
|
) {
|
||||||
|
file = candidate;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@
|
||||||
image on the page.
|
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 CACHE_MS = 30 * 60 * 1000;
|
||||||
const MAX_FEED_BYTES = 3 * 1024 * 1024;
|
const MAX_FEED_BYTES = 3 * 1024 * 1024;
|
||||||
|
|
@ -34,24 +34,32 @@ function unwrap(text) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
|
/* 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) {
|
function inner(xml, tag) {
|
||||||
const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i"));
|
const text = innerOf(xml, tag);
|
||||||
return match ? unwrap(match[1]) : null;
|
return text == null ? null : unwrap(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
function attrOf(xml, tag, name, where = () => true) {
|
function attrOf(xml, tag, name, where = () => true) {
|
||||||
for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) {
|
for (const el of openTags(xml, tag, 50)) {
|
||||||
const el = match[0];
|
|
||||||
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
|
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
|
||||||
if (value && where(el)) return value[2] ?? value[3];
|
if (value && where(el)) return value[2] ?? value[3];
|
||||||
}
|
}
|
||||||
return null;
|
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) {
|
function plain(html) {
|
||||||
if (!html) return null;
|
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 (<p>).
|
||||||
|
const strip = (s) => s.replace(/<[^>]*>/g, " ");
|
||||||
|
const text = decodeEntities(strip(decodeEntities(strip(html.slice(0, PLAIN_SCAN)))));
|
||||||
if (!text) return null;
|
if (!text) return null;
|
||||||
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
|
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
|
||||||
}
|
}
|
||||||
|
|
@ -74,21 +82,34 @@ function isoDate(raw) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function firstImage(html) {
|
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) {
|
function parseFeed(xml, feedUrl) {
|
||||||
const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml);
|
// The root element is near the top; nothing needs the rest for this.
|
||||||
const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? "");
|
const top = xml.slice(0, 8192);
|
||||||
const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? [];
|
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 = [];
|
const items = [];
|
||||||
for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) {
|
for (const block of blocks) {
|
||||||
const link = isAtom
|
const link = isAtom
|
||||||
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
|
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
|
||||||
: inner(block, "link");
|
: inner(block, "link");
|
||||||
const url = safeUrl(link?.trim(), feedUrl);
|
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;
|
if (!url || !title) continue;
|
||||||
|
|
||||||
const body = inner(block, "content:encoded") ?? inner(block, "content");
|
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());
|
return parseFeed(result.body.toString("utf8"), result.url.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readFeed(url) {
|
/* 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);
|
const hit = cache.get(url);
|
||||||
if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed;
|
if (hit?.pending) return hit.pending;
|
||||||
try {
|
const pending = fetchFeed(url)
|
||||||
const feed = await fetchFeed(url);
|
.then((feed) => {
|
||||||
cache.set(url, { at: Date.now(), feed });
|
cache.set(url, { at: Date.now(), feed });
|
||||||
return feed;
|
return feed;
|
||||||
} catch (err) {
|
})
|
||||||
|
.catch((err) => {
|
||||||
console.warn(`feed ${url}: ${err.message}`);
|
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: [] };
|
const stale = hit?.feed ?? { title: null, items: [] };
|
||||||
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
|
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
|
||||||
return 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
|
/* Every listed feed's items, newest first, each tagged with its
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import { mkdir } from "node:fs/promises";
|
||||||
import { serve } from "@hono/node-server";
|
import { serve } from "@hono/node-server";
|
||||||
import { serveStatic } from "@hono/node-server/serve-static";
|
import { serveStatic } from "@hono/node-server/serve-static";
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
|
import { HTTPException } from "hono/http-exception";
|
||||||
import { csrf } from "hono/csrf";
|
import { csrf } from "hono/csrf";
|
||||||
import { logger } from "hono/logger";
|
import { logger } from "hono/logger";
|
||||||
import { secureHeaders } from "hono/secure-headers";
|
import { secureHeaders } from "hono/secure-headers";
|
||||||
|
|
@ -35,7 +36,7 @@ import media from "./routes/media.js";
|
||||||
import clips from "./routes/clips.js";
|
import clips from "./routes/clips.js";
|
||||||
import { CLIPS_DIR, startClipWorker } from "./clips.js";
|
import { CLIPS_DIR, startClipWorker } from "./clips.js";
|
||||||
import { UPLOADS_DIR } from "./media.js";
|
import { UPLOADS_DIR } from "./media.js";
|
||||||
import { startSessionSweeper } from "./auth.js";
|
import { logSafe, startSessionSweeper } from "./auth.js";
|
||||||
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
||||||
import { ENTITIES } from "./admin-schema.js";
|
import { ENTITIES } from "./admin-schema.js";
|
||||||
|
|
||||||
|
|
@ -111,8 +112,9 @@ app.post("/api/csp-report", async (c) => {
|
||||||
const text = (await c.req.text()).slice(0, 4000);
|
const text = (await c.req.text()).slice(0, 4000);
|
||||||
try {
|
try {
|
||||||
const report = JSON.parse(text)["csp-report"] ?? {};
|
const report = JSON.parse(text)["csp-report"] ?? {};
|
||||||
|
const field = (name) => logSafe(report[name] ?? "?", 150);
|
||||||
console.warn(
|
console.warn(
|
||||||
`csp ${report["violated-directive"] ?? "?"} blocked ${report["blocked-uri"] ?? "?"} on ${report["document-uri"] ?? "?"}`,
|
`csp ${field("violated-directive")} blocked ${field("blocked-uri")} on ${field("document-uri")}`,
|
||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
// Not a report; nothing to log.
|
// Not a report; nothing to log.
|
||||||
|
|
@ -203,6 +205,9 @@ console.log(`clips ${CLIPS_DIR}`);
|
||||||
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
||||||
|
|
||||||
app.onError((err, c) => {
|
app.onError((err, c) => {
|
||||||
|
// A deliberate refusal (the CSRF check's 403, say) is an answer,
|
||||||
|
// not a crash: send it as it is and keep it out of the error log.
|
||||||
|
if (err instanceof HTTPException) return err.getResponse();
|
||||||
console.error(err);
|
console.error(err);
|
||||||
// Never leak internals to the browser.
|
// Never leak internals to the browser.
|
||||||
return c.json({ error: "Something went wrong." }, 500);
|
return c.json({ error: "Something went wrong." }, 500);
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,8 @@ import net from "node:net";
|
||||||
import { MAX_UPLOAD_BYTES, MediaError } from "./media.js";
|
import { MAX_UPLOAD_BYTES, MediaError } from "./media.js";
|
||||||
|
|
||||||
const TIMEOUT_MS = 8000;
|
const TIMEOUT_MS = 8000;
|
||||||
|
// The whole request, however steadily the bytes trickle in.
|
||||||
|
const TOTAL_TIMEOUT_MS = 15000;
|
||||||
const MAX_REDIRECTS = 4;
|
const MAX_REDIRECTS = 4;
|
||||||
const MAX_HTML_BYTES = 1024 * 1024;
|
const MAX_HTML_BYTES = 1024 * 1024;
|
||||||
const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
|
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();
|
const BLOCKED = new net.BlockList();
|
||||||
for (const [ip, bits] of [
|
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],
|
["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],
|
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24],
|
||||||
["198.18.0.0", 15], ["224.0.0.0", 3],
|
["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");
|
]) BLOCKED.addSubnet(ip, bits, "ipv4");
|
||||||
for (const [ip, bits] of [
|
for (const [ip, bits] of [
|
||||||
["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16],
|
["::", 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");
|
]) BLOCKED.addSubnet(ip, bits, "ipv6");
|
||||||
|
|
||||||
function ipBlocked(ip) {
|
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.")));
|
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) =>
|
req.on("error", (err) =>
|
||||||
reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")),
|
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: " " };
|
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) {
|
export function decodeEntities(text) {
|
||||||
return text
|
return text
|
||||||
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
|
.replace(/&#x([0-9a-f]{1,6});/gi, (_, hex) => codePoint(parseInt(hex, 16)))
|
||||||
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
|
.replace(/&#(\d{1,7});/g, (_, dec) => codePoint(Number(dec)))
|
||||||
.replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole)
|
.replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole)
|
||||||
.replace(/\s+/g, " ")
|
.replace(/\s+/g, " ")
|
||||||
.trim();
|
.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) {
|
function attr(tag, name) {
|
||||||
const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
|
const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
|
||||||
return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null;
|
return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null;
|
||||||
|
|
@ -185,12 +263,12 @@ function attr(tag, name) {
|
||||||
|
|
||||||
function readMeta(html) {
|
function readMeta(html) {
|
||||||
const meta = {};
|
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 key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase();
|
||||||
const content = attr(tag, "content");
|
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 {
|
return {
|
||||||
title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null,
|
title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null,
|
||||||
description:
|
description:
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,10 @@ export const KEEP_MAX_BYTES = 10 * MB;
|
||||||
|
|
||||||
/* Longest side after processing, in pixels. Wide enough for a
|
/* Longest side after processing, in pixels. Wide enough for a
|
||||||
full-bleed hero on a large screen. */
|
full-bleed hero on a large screen. */
|
||||||
|
// About 60 megapixels (eg. 9000 x 6700): past any camera an editor
|
||||||
|
// uses, and it stops one giant image eating the VPS's memory while
|
||||||
|
// it's decoded. sharp's own default is 268 MP.
|
||||||
|
const MAX_INPUT_PIXELS = 60_000_000;
|
||||||
const MAX_EDGE = 2400;
|
const MAX_EDGE = 2400;
|
||||||
|
|
||||||
const WEBP_QUALITY = 82;
|
const WEBP_QUALITY = 82;
|
||||||
|
|
@ -141,7 +145,7 @@ export async function store(buf, { keepOriginal = false } = {}) {
|
||||||
try {
|
try {
|
||||||
if (convert) {
|
if (convert) {
|
||||||
// animated keeps every frame of a GIF or an animated WebP.
|
// animated keeps every frame of a GIF or an animated WebP.
|
||||||
const { data, info } = await sharp(buf, { animated: true })
|
const { data, info } = await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
|
||||||
.rotate()
|
.rotate()
|
||||||
.resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true })
|
.resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true })
|
||||||
.webp({ quality: WEBP_QUALITY })
|
.webp({ quality: WEBP_QUALITY })
|
||||||
|
|
@ -152,7 +156,7 @@ export async function store(buf, { keepOriginal = false } = {}) {
|
||||||
// An animated image reports the whole strip's height.
|
// An animated image reports the whole strip's height.
|
||||||
height = info.pageHeight ?? info.height;
|
height = info.pageHeight ?? info.height;
|
||||||
} else if (kind !== "svg") {
|
} else if (kind !== "svg") {
|
||||||
const meta = await sharp(buf).metadata();
|
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
|
||||||
width = meta.width ?? null;
|
width = meta.width ?? null;
|
||||||
height = meta.pageHeight ?? meta.height ?? null;
|
height = meta.pageHeight ?? meta.height ?? null;
|
||||||
}
|
}
|
||||||
|
|
@ -209,7 +213,7 @@ async function describe(filename) {
|
||||||
let height = null;
|
let height = null;
|
||||||
if (kind !== "svg") {
|
if (kind !== "svg") {
|
||||||
try {
|
try {
|
||||||
const meta = await sharp(buf).metadata();
|
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
|
||||||
width = meta.width ?? null;
|
width = meta.width ?? null;
|
||||||
height = meta.pageHeight ?? meta.height ?? null;
|
height = meta.pageHeight ?? meta.height ?? null;
|
||||||
} catch {
|
} catch {
|
||||||
|
|
|
||||||
|
|
@ -130,7 +130,10 @@ export function robotsTxt(site) {
|
||||||
cut on a word near DESCRIPTION_CHARS. */
|
cut on a word near DESCRIPTION_CHARS. */
|
||||||
export function plainText(text) {
|
export function plainText(text) {
|
||||||
if (!text) return null;
|
if (!text) return null;
|
||||||
|
// A description is ~160 characters; reading far past that only
|
||||||
|
// gives the patterns below more to rescan on pathological text.
|
||||||
const flat = String(text)
|
const flat = String(text)
|
||||||
|
.slice(0, 2000)
|
||||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
||||||
.replace(/\*\*(.+?)\*\*/g, "$1")
|
.replace(/\*\*(.+?)\*\*/g, "$1")
|
||||||
.replace(/\*(.+?)\*/g, "$1")
|
.replace(/\*(.+?)\*/g, "$1")
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,8 @@ entities.use("*", requireAuth);
|
||||||
const NO_STORE = { "Cache-Control": "no-store" };
|
const NO_STORE = { "Cache-Control": "no-store" };
|
||||||
|
|
||||||
function entityOr404(c) {
|
function entityOr404(c) {
|
||||||
const entity = ENTITIES[c.req.param("entity")];
|
const name = c.req.param("entity");
|
||||||
|
const entity = Object.hasOwn(ENTITIES, name) ? ENTITIES[name] : null;
|
||||||
if (!entity) throw new HttpError(404, "Unknown entity.");
|
if (!entity) throw new HttpError(404, "Unknown entity.");
|
||||||
return entity;
|
return entity;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,7 @@ admin.get("/feedback", (c) => {
|
||||||
params.push(Number(before));
|
params.push(Number(before));
|
||||||
}
|
}
|
||||||
|
|
||||||
const take = Math.min(Number(limit) || 50, MAX_LIMIT);
|
const take = Math.max(1, Math.min(Number(limit) || 50, MAX_LIMIT));
|
||||||
|
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(
|
||||||
|
|
@ -99,7 +99,8 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
|
||||||
|
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = await c.req.json();
|
// `?? {}`: a body of JSON null parses fine and has no fields.
|
||||||
|
body = (await c.req.json()) ?? {};
|
||||||
} catch {
|
} catch {
|
||||||
return c.json({ error: "Expected a JSON body." }, 400);
|
return c.json({ error: "Expected a JSON body." }, 400);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,7 @@ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
SECURE_COOKIE,
|
SECURE_COOKIE,
|
||||||
|
logSafe,
|
||||||
createSession,
|
createSession,
|
||||||
destroySession,
|
destroySession,
|
||||||
currentUser,
|
currentUser,
|
||||||
|
|
@ -58,7 +59,8 @@ const NO_STORE = { "Cache-Control": "no-store" };
|
||||||
auth.post("/login", async (c) => {
|
auth.post("/login", async (c) => {
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = await c.req.json();
|
// `?? {}`: a body of JSON null parses fine and has no fields.
|
||||||
|
body = (await c.req.json()) ?? {};
|
||||||
} catch {
|
} catch {
|
||||||
return c.json({ error: "Expected a JSON body." }, 400);
|
return c.json({ error: "Expected a JSON body." }, 400);
|
||||||
}
|
}
|
||||||
|
|
@ -72,7 +74,7 @@ auth.post("/login", async (c) => {
|
||||||
|
|
||||||
const wait = loginFailures.blockedFor(email);
|
const wait = loginFailures.blockedFor(email);
|
||||||
if (wait) {
|
if (wait) {
|
||||||
console.warn(`login locked for ${email}`);
|
console.warn(`login locked for ${logSafe(email)}`);
|
||||||
return c.json(
|
return c.json(
|
||||||
{ error: "Too many wrong passwords for this account. Try again in a few minutes." },
|
{ error: "Too many wrong passwords for this account. Try again in a few minutes." },
|
||||||
429,
|
429,
|
||||||
|
|
@ -97,7 +99,7 @@ auth.post("/login", async (c) => {
|
||||||
|
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
loginFailures.fail(email);
|
loginFailures.fail(email);
|
||||||
console.warn(`login failed for ${email}`);
|
console.warn(`login failed for ${logSafe(email)}`);
|
||||||
return c.json({ error: "That email and password don't match." }, 401);
|
return c.json({ error: "That email and password don't match." }, 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -134,12 +136,14 @@ auth.get("/me", (c) => {
|
||||||
// The state and PKCE verifier between the two legs. Scoped to the
|
// The state and PKCE verifier between the two legs. Scoped to the
|
||||||
// Google routes and gone in ten minutes; Lax so it comes back on
|
// Google routes and gone in ten minutes; Lax so it comes back on
|
||||||
// the redirect from Google, which is a top-level navigation.
|
// the redirect from Google, which is a top-level navigation.
|
||||||
const OAUTH_COOKIE = "ngu_oauth";
|
// __Host- (Secure, path /, no Domain) when over https, like the
|
||||||
|
// session cookie, so a sibling subdomain can't plant its own state.
|
||||||
|
const OAUTH_COOKIE = SECURE_COOKIE ? "__Host-ngu_oauth" : "ngu_oauth";
|
||||||
const OAUTH_COOKIE_OPTIONS = {
|
const OAUTH_COOKIE_OPTIONS = {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: SECURE_COOKIE,
|
secure: SECURE_COOKIE,
|
||||||
sameSite: "Lax",
|
sameSite: "Lax",
|
||||||
path: "/api/auth/google",
|
path: "/",
|
||||||
};
|
};
|
||||||
|
|
||||||
// Where to land afterwards: an admin page, never anywhere else.
|
// Where to land afterwards: an admin page, never anywhere else.
|
||||||
|
|
@ -232,7 +236,8 @@ auth.get("/google/callback", async (c) => {
|
||||||
).run(identity.name, user.id);
|
).run(identity.name, user.id);
|
||||||
console.log(`login ${user.email} (google)`);
|
console.log(`login ${user.email} (google)`);
|
||||||
|
|
||||||
return c.redirect(saved.next ?? "/admin/home", 302);
|
// Checked again: the cookie came back from the browser.
|
||||||
|
return c.redirect(safeNext(saved.next), 302);
|
||||||
});
|
});
|
||||||
|
|
||||||
export default auth;
|
export default auth;
|
||||||
|
|
|
||||||
|
|
@ -52,7 +52,8 @@ function looksLikeEmail(value) {
|
||||||
feedback.post("/", async (c) => {
|
feedback.post("/", async (c) => {
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = await c.req.json();
|
// `?? {}`: a body of JSON null parses fine and has no fields.
|
||||||
|
body = (await c.req.json()) ?? {};
|
||||||
} catch {
|
} catch {
|
||||||
return c.json({ error: "Expected a JSON body." }, 400);
|
return c.json({ error: "Expected a JSON body." }, 400);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -165,7 +165,7 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
|
||||||
const user = c.get("user");
|
const user = c.get("user");
|
||||||
let url;
|
let url;
|
||||||
try {
|
try {
|
||||||
({ url } = await c.req.json());
|
({ url } = (await c.req.json()) ?? {});
|
||||||
} catch {
|
} catch {
|
||||||
return c.json({ error: "Expected a JSON body." }, 400);
|
return c.json({ error: "Expected a JSON body." }, 400);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@
|
||||||
|
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { requireAuth, requireRole, ROLES } from "../auth.js";
|
import { requireAuth, requireRole, ROLES } from "../auth.js";
|
||||||
|
import { tx } from "../db.js";
|
||||||
|
|
||||||
const panel = new Hono();
|
const panel = new Hono();
|
||||||
|
|
||||||
|
|
@ -116,7 +117,8 @@ panel.patch("/users/:id", async (c) => {
|
||||||
|
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = await c.req.json();
|
// `?? {}`: a body of JSON null parses fine and has no fields.
|
||||||
|
body = (await c.req.json()) ?? {};
|
||||||
} catch {
|
} catch {
|
||||||
return c.json({ error: "Expected a JSON body." }, 400);
|
return c.json({ error: "Expected a JSON body." }, 400);
|
||||||
}
|
}
|
||||||
|
|
@ -154,7 +156,8 @@ panel.patch("/users/:id", async (c) => {
|
||||||
|
|
||||||
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
|
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
|
||||||
|
|
||||||
const tx = db.transaction(() => {
|
// tx(), not db.transaction(): node:sqlite has no transaction().
|
||||||
|
tx(db, () => {
|
||||||
db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run(
|
db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run(
|
||||||
...params,
|
...params,
|
||||||
id,
|
id,
|
||||||
|
|
@ -163,7 +166,6 @@ panel.patch("/users/:id", async (c) => {
|
||||||
// matches the row. Make them sign in again.
|
// matches the row. Make them sign in again.
|
||||||
db.prepare("DELETE FROM sessions WHERE user_id = ?").run(id);
|
db.prepare("DELETE FROM sessions WHERE user_id = ?").run(id);
|
||||||
});
|
});
|
||||||
tx();
|
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
`account ${target.email} updated by ${me.email}: ${JSON.stringify(body)}`,
|
`account ${target.email} updated by ${me.email}: ${JSON.stringify(body)}`,
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ function overrides(db) {
|
||||||
.all();
|
.all();
|
||||||
// Checked again here, not only by the table's CHECK: this goes
|
// Checked again here, not only by the table's CHECK: this goes
|
||||||
// straight into a <style> element.
|
// straight into a <style> element.
|
||||||
return rows.filter((row) => THEME_DEFAULTS[row.token]);
|
return rows.filter((row) => Object.hasOwn(THEME_DEFAULTS, row.token));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* { light: { ink: '#…', … }, dark: { … } }, defaults with overrides. */
|
/* { light: { ink: '#…', … }, dark: { … } }, defaults with overrides. */
|
||||||
|
|
|
||||||
|
|
@ -184,7 +184,7 @@ export function UploadButton({
|
||||||
|
|
||||||
export const UPLOAD_HELP =
|
export const UPLOAD_HELP =
|
||||||
"Photos are shrunk to 2400px and saved as WebP, which also removes their location data. " +
|
"Photos are shrunk to 2400px and saved as WebP, which also removes their location data. " +
|
||||||
"Keep original stores the file exactly as it is (up to 10 MB). SVGs are always kept as they are.";
|
"Keep original stores the file exactly as it is (up to 10 MB), including any location a phone saved in a photo; shrinking removes it. SVGs are always kept as they are.";
|
||||||
|
|
||||||
/* ── Grid ────────────────────────────────────────────────────── */
|
/* ── Grid ────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue