Third audit: security fixes and server-side scalability

Security:
- docx unzip reads each part once (a repeated entry was a zip bomb)
- request files must be named for their type (no PDF named .html)
- team roster hidden when its organization is unpublished
- /people?ids= hides draft organizations, takes 200 ids
- v_events takes the first published host and reads event_hosts
  directly (migration 059, plus an index on person_awards.event_id)
- group accounts refused while access groups are off; group sync
  can't undo a superadmin's disable
- 64 KB body limit on login, feedback and csp-report
- Drive pick-up races no longer 500; random upload boundary

Scalability:
- /events filters by scope, host, status and type on the server;
  Home no longer prefetches every event
- /organizations leaves out bodies and leadership; the map's group
  panel fetches its own
- admin lists page with Show more and a real count
- content request record search and the newsletter's post list
  ask the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-10-01 18:29:26 -05:00
parent 0bb4b8685f
commit f99010252f
18 changed files with 229 additions and 96 deletions

View file

@ -66,16 +66,24 @@ export async function groupRole(db, email) {
/* Brings a group account in line with `role` (null: in no group).
Returns what changed, as text for the log and the Panel, or null. */
export function applyGroupRole(db, user, role) {
// `user` was read before the group lookups were awaited, so each
// write rechecks that a superadmin hasn't disabled or promoted the
// account meanwhile.
const STILL_OURS = `AND role <> 'superadmin' AND (is_active = 1 OR group_disabled = 1)`;
let change = null;
if (!role) {
if (user.is_active === 1) {
db.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ?`).run(user.id);
const res = db
.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ? ${STILL_OURS}`)
.run(user.id);
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
change = "disabled: in no access group";
if (res.changes) change = "disabled: in no access group";
}
} else if (user.is_active !== 1 || user.role !== role) {
db.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ?`).run(role, user.id);
change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
const res = db
.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ? ${STILL_OURS}`)
.run(role, user.id);
if (res.changes) change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
}
db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id);
if (change) console.log(`access: ${user.email} ${change}`);

View file

@ -163,18 +163,23 @@ export function listRows(db, entity, query = {}) {
}
const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500));
const offset = Math.max(0, Math.floor(Number(query.offset) || 0));
const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : "";
const rows = db
.prepare(
`SELECT ${columns.join(", ")}
FROM ${entity.table}
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
${whereSql}
ORDER BY ${order}
LIMIT ?`,
LIMIT ? OFFSET ?`,
)
.all(...params, limit);
.all(...params, limit, offset);
return { rows, total: rows.length };
// Every match, not just this page, so the list can say how many more.
const { total } = db.prepare(`SELECT COUNT(*) AS total FROM ${entity.table} ${whereSql}`).get(...params);
return { rows, total };
}
export function readRow(db, entity, rawId) {

View file

@ -63,7 +63,8 @@ function unzip(buf, wanted) {
const local = buf.readUInt32LE(at + 42);
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
at += 46 + nameLen + extraLen + commentLen;
if (!wanted.includes(name)) continue;
// Each part once: a zip can list the same name thousands of times.
if (!wanted.includes(name) || name in out) continue;
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
const data = buf.subarray(dataAt, dataAt + packed);

View file

@ -35,7 +35,7 @@
import { createReadStream, readFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { createSign } from "node:crypto";
import { createSign, randomBytes } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
@ -183,7 +183,8 @@ async function findOrMakeFolder(path) {
/* One file into a folder of the shared drive (driveFolder). Returns
{ id, webViewLink }: Drive's id, and the page that shows it. */
export async function driveUpload(folder, name, mime, buffer) {
const boundary = `ngu${Date.now().toString(36)}`;
// Random, so no file can carry it by chance or design.
const boundary = `ngu${randomBytes(16).toString("hex")}`;
const meta = JSON.stringify({ name, parents: [await driveFolder(folder)] });
const body = Buffer.concat([
Buffer.from(

View file

@ -13,6 +13,7 @@ import { mkdir } from "node:fs/promises";
import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { HTTPException } from "hono/http-exception";
import { csrf } from "hono/csrf";
import { logger } from "hono/logger";
@ -118,6 +119,12 @@ app.use(
}),
);
/* The public JSON writes read their whole body before trimming it,
so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */
app.use("/api/csp-report", rateLimit({ windowMs: 60_000, max: 30 }));

View file

@ -0,0 +1,50 @@
-- ═══════════════════════════════════════════════════════════════
-- 059 EVENTS VIEW: FIRST PUBLISHED HOST, READ DIRECTLY
--
-- v_events took its host (name, logo, color) from the first row of
-- v_event_hosts, published or not, so a draft partner hosting a
-- published event showed in its page's structured data and preview
-- image. It now takes the first published host, as loadHosts does.
--
-- It also joins event_hosts, organizations and people itself:
-- through the v_event_hosts view, SQLite built every host of every
-- event for each lookup, even one event's page. Same columns.
--
-- person_awards gets the index its event_id lookups (an event's
-- awards, and the SET NULL when an event is deleted) were missing.
-- ═══════════════════════════════════════════════════════════════
DROP VIEW v_events;
CREATE VIEW v_events AS
SELECT
e.*,
CASE WHEN eh.id IS NULL THEN NULL
WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
AS host_kind,
COALESCE(eh.org_id, eh.person_id) AS host_id,
COALESCE(o.name, p.display_name) AS host_name,
o.kind AS host_org_kind,
COALESCE(e.org_logo, o.logo) AS effective_org_logo,
COALESCE(e.color, o.color) AS effective_color,
COALESCE(
e.status,
CASE WHEN e.ends_on IS NOT NULL AND e.ends_on < date('now')
THEN 'past' ELSE 'upcoming' END
) AS effective_status
FROM events e
LEFT JOIN event_hosts eh
ON eh.id = (
SELECT x.id
FROM event_hosts x
LEFT JOIN organizations xo ON xo.id = x.org_id
LEFT JOIN people xp ON xp.id = x.person_id
WHERE x.event_id = e.id
AND COALESCE(xo.is_published, xp.is_published) = 1
ORDER BY x.sort_order, x.id
LIMIT 1
)
LEFT JOIN organizations o ON o.id = eh.org_id
LEFT JOIN people p ON p.id = eh.person_id;
CREATE INDEX person_awards_event_idx ON person_awards (event_id);

View file

@ -262,8 +262,11 @@ auth.get("/google/callback", async (c) => {
}
// A group account's role follows its groups, checked every time.
// One a superadmin disabled stays disabled whatever its groups say.
if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) {
// One a superadmin disabled stays disabled whatever its groups say,
// and with access groups switched off none gets in (it can't be
// rechecked, so it would keep its last role for good).
if (user.access_source === "group" && user.role !== "superadmin") {
if (!accessEnabled(db)) return backToLogin(c, "not_in_group");
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");

View file

@ -442,8 +442,8 @@ function attachAwards(db, orgs) {
}
/* ── Events ────────────────────────────────────────────────────
Flat, with the event scopes alongside. Retreats.tsx owns the
band titles and colors and filters this list by scope_id.
Flat, with the event scopes alongside, narrowed by the query
(below). Each band asks for only what it shows.
Oldest first, undated last. The carousel shows the list as it
comes and opens on the first upcoming event, so past events
@ -461,13 +461,26 @@ content.get("/events", (c) => {
.prepare(`SELECT id, name, sort_order FROM event_scopes ORDER BY sort_order`)
.all();
// Optional filters, each narrowing the list (src/lib/eventData.ts):
// ?scope=national ?host=<org or person slug> ?status=upcoming
// ?type=class,workshop
const where = [`is_published = 1`, `is_listed = 1`];
const params = [];
const scope = c.req.query("scope");
if (scope) where.push(`scope_id = ?`), params.push(scope);
const host = c.req.query("host");
if (host) {
where.push(`EXISTS (SELECT 1 FROM event_hosts h WHERE h.event_id = v_events.id AND (h.org_id = ? OR h.person_id = ?))`);
params.push(host, host);
}
const status = c.req.query("status");
if (status) where.push(`effective_status = ?`), params.push(status);
const types = (c.req.query("type") ?? "").split(",").filter(Boolean).slice(0, 20);
if (types.length) where.push(`event_type IN (${marks(types.length)})`), params.push(...types);
const rows = db
.prepare(
`SELECT * FROM v_events
WHERE is_published = 1 AND is_listed = 1
ORDER BY ${EVENT_ORDER}`,
)
.all();
.prepare(`SELECT * FROM v_events WHERE ${where.join(" AND ")} ORDER BY ${EVENT_ORDER}`)
.all(...params);
const ids = rows.map((row) => row.id);
const links = loadLinks(db, "event", ids);
@ -576,20 +589,17 @@ content.get("/organizations", (c) => {
const ids = rows.map((row) => row.id);
const links = loadLinks(db, "organization", ids);
const cards = loadBlocks(db, "organization", ids, "card");
const bodies = loadBlocks(db, "organization", ids, "body");
const organizations = rows.map((row) =>
shapeOrganization(
row,
links.get(row.id) ?? [],
cards.get(row.id) ?? [],
bodies.get(row.id) ?? [],
),
);
// No body blocks or leadership: they grow with every organization
// and only a group's own detail panel or page shows them, which
// fetch /organizations/:id.
const organizations = rows.map((row) => {
const { blocks, leadership, ...org } = shapeOrganization(row, links.get(row.id) ?? [], cards.get(row.id) ?? [], []);
return org;
});
attachRegionDetails(db, organizations);
attachGroupDetails(db, organizations);
attachLeadership(db, organizations);
return json(c, { organizations });
});

View file

@ -86,9 +86,15 @@ export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER);
Returns what the list shows. Also how the clip tool's Save to Drive
lands (routes/clips.js). */
export async function recordDriveUpload(db, uploaded, { name, mime, bytes, folder, userId }) {
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId).lastInsertRowid;
// A pick-up may have found it in Drive before this insert: ours wins.
const { id } = db
.prepare(
`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (drive_id) DO UPDATE SET name = excluded.name, mime = excluded.mime, bytes = excluded.bytes,
url = excluded.url, folder = excluded.folder, uploaded_by = excluded.uploaded_by
RETURNING id`,
)
.get(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId);
await fetchPreview(db, db.prepare(`${SELECT} WHERE f.id = ?`).get(id), userId);
return shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id));
}
@ -201,9 +207,13 @@ async function pickUp(db, force = false) {
continue;
}
refused.delete(file.id);
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder).lastInsertRowid;
// OR IGNORE: another pick-up, or an upload between Drive and its
// own insert, may have recorded it meanwhile.
const res = db
.prepare(`INSERT OR IGNORE INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder);
if (!res.changes) continue;
const id = res.lastInsertRowid;
console.log(`files: ${file.name} picked up from Drive`);
// In the background: a folder of new files shouldn't hold the list.
fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null);

View file

@ -26,8 +26,9 @@ import { postsBy } from "./blog.js";
const people = new Hono();
/* How many slugs one request may name. Keeps the URL sane. */
const MAX_IDS = 50;
/* How many slugs one request may name. Keeps the URL sane (a few
KB) while covering any hand-picked list. */
const MAX_IDS = 200;
function shapePerson(row) {
return {
@ -69,9 +70,10 @@ people.get("/teams/:id/people", (c) => {
const team = db
.prepare(
`SELECT id, org_id, name, tagline, color, logo
FROM teams
WHERE id = ? AND is_published = 1`,
`SELECT t.id, t.org_id, t.name, t.tagline, t.color, t.logo
FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.id = ? AND t.is_published = 1`,
)
.get(id);
@ -125,7 +127,7 @@ people.get("/people", (c) => {
o.id AS primary_org_id,
o.name AS primary_org_name
FROM people p
LEFT JOIN organizations o ON o.id = p.primary_org_id
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id IN (${marks(ids.length)})
AND p.is_published = 1`,
)

View file

@ -79,15 +79,17 @@ export const TYPE_FOLDERS = {
export const MAX_FILES = 3;
export const MAX_FILE_BYTES = 10 * 1024 * 1024;
/* What a file is, from its first bytes. A zip is only taken as a
Word document when it's named like one. */
/* What a file is, from its first bytes, and only when its name says
the same: a PDF named .html is refused, so a download is always
what it says. */
const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
function kindOf(bytes, name) {
const ext = String(name).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];
const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
if (starts(0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
if (starts(0xff, 0xd8, 0xff)) return "image/jpeg";
if (starts(0x89, 0x50, 0x4e, 0x47)) return "image/png";
if (starts(0x50, 0x4b, 0x03, 0x04) && /\.docx$/i.test(name)) return DOCX;
if (ext === "pdf" && starts(0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
if ((ext === "jpg" || ext === "jpeg") && starts(0xff, 0xd8, 0xff)) return "image/jpeg";
if (ext === "png" && starts(0x89, 0x50, 0x4e, 0x47)) return "image/png";
if (ext === "docx" && starts(0x50, 0x4b, 0x03, 0x04)) return DOCX;
return null;
}