NGU-Web/server/src/routes/files.js
Zaldimmar f99010252f 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>
2026-10-01 18:29:26 -05:00

409 lines
17 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
FILE ROUTES: mounted under /api/admin
GET /files the files, newest first, ?q=name.
Picks up files put in the folder
in Drive by hand first (pickUp, at
most every SCAN_EVERY_MS)
POST /files upload one (multipart: file, folder)
PATCH /files/:id { folder }: move it to another folder
GET /files/:id/uses which records link to it
DELETE /files/:id into Drive's trash, out of the list
POST /files/folders { path }: make a folder
PATCH /files/folders { path, name }: rename one
DELETE /files/folders?path= delete an empty one
Folders: under FOLDER, at most MAX_DEPTH deep, named by a path
relative to it ('' is FOLDER itself, 'Slides/2026' below it). The
list's `folders` are every one Drive has there, so one made in
Drive by hand shows up too.
Files for the public site to link to, kept in the shared drive's
FOLDER (googleService.js) and shared as "anyone with the link can
view", so a link opens Drive's viewer. Content blocks' link fields
pick from here ("Choose a file"); a link card takes the file's name
and its first-page preview too.
The preview: Drive draws a picture of a PDF's or Office file's
first page a little after upload. It's asked for straight away and
again over the next few minutes (PREVIEW_TRIES), and saved into the
media library as an ordinary upload when it comes.
Files added to the folder in Drive itself (not through here) are
listed too: the next look at the list finds them, shares them the
same way and fetches their previews. Google's own Docs, Sheets and
Slides count; folders and shortcuts don't. One that Drive won't
share is left out and named in the list's `refused`.
The same ladder as media: reading needs a session, uploading
editor, deleting admin. nginx needs a block for POST /files
(docs/google-drive-and-mail.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import {
driveDelete,
driveFolder,
driveFolderEmpty,
driveMove,
driveReady,
driveRename,
driveShareWithAnyone,
driveThumbnail,
driveTree,
driveUpload,
forgetFolders,
} from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js";
import { publicPath } from "../media.js";
import { NO_STORE } from "../shape.js";
const files = new Hono();
files.use("*", requireAuth);
export const FOLDER = "Media";
const MAX_DEPTH = 3;
/* A folder path as given, cleaned: '' for FOLDER itself, or up to
MAX_DEPTH names of 1 to 60 characters, none of them "." or "..",
joined by "/". null when it can't be one. */
export function cleanFolder(value) {
const parts = String(value ?? "")
.split("/")
.map((part) => part.replace(/[\u0000-\u001f\\]+/g, " ").trim())
.filter(Boolean);
if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null;
return parts.join("/");
}
export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER);
/* A file just uploaded to Drive (and shared) into the list: its row,
and the first try at its preview (more follow on their own).
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 }) {
// 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));
}
const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_LIST = 500;
// Seconds after upload to ask Drive for the preview again.
const PREVIEW_TRIES = [0, 5, 20, 60, 180];
// How often listing the files looks in the Drive folder for new ones.
const SCAN_EVERY_MS = 30_000;
const SKIP_TYPES = new Set(["application/vnd.google-apps.folder", "application/vnd.google-apps.shortcut"]);
/* What a file is: its first bytes and its name have to agree (Office
files are zips, so for them the name is what tells them apart). A
PDF named .mp3 is refused, so a download is always what it says. */
const ZIPPED = {
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
zip: "application/zip",
};
export function kindOf(bytes, name) {
const ext = String(name).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];
const starts = (at, ...sig) => sig.every((b, i) => bytes[at + i] === b);
if (ext === "pdf" && starts(0, 0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
if (starts(0, 0x50, 0x4b, 0x03, 0x04) && ZIPPED[ext]) return ZIPPED[ext];
if (ext === "mp3" && (starts(0, 0x49, 0x44, 0x33) || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0))) return "audio/mpeg";
if (ext === "m4a" && starts(4, 0x66, 0x74, 0x79, 0x70)) return "audio/mp4";
return null;
}
const safeName = (name) =>
String(name ?? "file")
.replace(/[\u0000-\u001f"\\/]+/g, " ")
.trim()
.slice(0, 150) || "file";
const SELECT = `SELECT f.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email
FROM drive_files f LEFT JOIN admin_users u ON u.id = f.uploaded_by`;
const shape = (row) => ({
id: row.id,
name: row.name,
// What a link card calls it: the name without its extension.
title: row.name.replace(/\.[a-z0-9]+$/i, ""),
mime: row.mime,
bytes: row.bytes,
url: row.url,
preview: row.preview,
folder: row.folder,
uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null,
created_at: row.created_at,
});
/* Asks Drive for the first-page picture until it has one or the
tries run out; saved into the media library. Never throws. */
function fetchPreview(db, row, userId) {
let attempt = 0;
const next = async () => {
try {
const image = await driveThumbnail(row.drive_id);
if (image) {
const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId, folder: "thumbnails" });
db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(publicPath(saved.filename), row.id);
return;
}
} catch (err) {
console.warn(`files: preview for ${row.name}: ${err.message}`);
}
attempt++;
if (attempt < PREVIEW_TRIES.length) setTimeout(next, (PREVIEW_TRIES[attempt] - PREVIEW_TRIES[attempt - 1]) * 1000).unref();
};
return next();
}
/* Files put in the folder in Drive by hand, added to the list and
shared. A file Drive won't share is tried again after RETRY_MS, not
on every look (a sharing setting fixed in the meantime then takes).
Never throws: the list still shows what's known. */
const RETRY_MS = 10 * 60 * 1000;
let lastScan = 0;
let folderPaths = [];
const refused = new Map(); // drive id → { name, at }
async function pickUp(db, force = false) {
if (!driveReady() || (!force && Date.now() - lastScan < SCAN_EVERY_MS)) return;
lastScan = Date.now();
let tree;
try {
tree = await driveTree(FOLDER, MAX_DEPTH);
} catch (err) {
console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`);
return;
}
folderPaths = tree.folders.map((f) => f.path).filter(Boolean).sort((a, b) => a.localeCompare(b));
const known = new Map(db.prepare(`SELECT drive_id, folder FROM drive_files`).all().map((r) => [r.drive_id, r.folder]));
for (const file of tree.files) {
// Moved in Drive by hand: follow it.
if (known.has(file.id)) {
if (known.get(file.id) !== file.folder) {
db.prepare(`UPDATE drive_files SET folder = ? WHERE drive_id = ?`).run(file.folder, file.id);
}
continue;
}
if (SKIP_TYPES.has(file.mimeType)) continue;
if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue;
try {
await driveShareWithAnyone(file.id);
} catch (err) {
console.warn(`files: ${file.name} (added in Drive) not shared: ${err.message}`);
refused.set(file.id, { name: file.name, at: Date.now() });
continue;
}
refused.delete(file.id);
// 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);
}
}
files.get("/files", async (c) => {
await pickUp(c.get("db"));
const q = (c.req.query("q") ?? "").trim().slice(0, 100);
const rows = c
.get("db")
.prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`)
.all(...(q ? [`%${q}%`] : []));
// Every folder Drive has, and any a file names that the last look
// didn't reach (made since, or Drive unreachable).
const folders = [...new Set([...folderPaths, ...rows.map((r) => r.folder).filter(Boolean)])].sort((a, b) =>
a.localeCompare(b),
);
return c.json(
{ files: rows.map(shape), folders, ready: driveReady(), refused: [...refused.values()].map((r) => r.name) },
200,
NO_STORE,
);
});
files.post(
"/files",
requireRole("editor"),
bodyLimit({
maxSize: MAX_FILE_BYTES + 64 * 1024,
onError: (c) => c.json({ error: `Files can be ${MAX_FILE_BYTES / 1024 / 1024} MB at most.` }, 413),
}),
async (c) => {
if (!driveReady()) {
return c.json({ error: "Google Drive isn't set up on the server (docs/google-drive-and-mail.md)." }, 400);
}
const db = c.get("db");
const user = c.get("user");
let body;
try {
body = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = body.file;
if (!(file instanceof File) || file.size === 0) return c.json({ error: "No file was sent." }, 400);
const buffer = Buffer.from(await file.arrayBuffer());
const mime = kindOf(buffer, file.name);
if (!mime) {
return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415);
}
const name = safeName(file.name);
const folder = cleanFolder(body.folder);
if (folder === null) return c.json({ error: "That isn't a folder name." }, 422);
let uploaded;
try {
uploaded = await driveUpload(inDrive(folder), name, mime, buffer);
} catch (err) {
console.warn(`files: upload of ${name} failed: ${err.message}`);
return c.json({ error: `Google Drive didn't take it: ${err.message}` }, 502);
}
try {
await driveShareWithAnyone(uploaded.id);
} catch (err) {
console.warn(`files: sharing ${name} failed: ${err.message}`);
await driveDelete(uploaded.id).catch(() => {});
return c.json(
{
error:
`Drive wouldn't share it with anyone who has the link (${err.message}). ` +
"The shared drive's settings, or the Workspace's sharing settings, must allow sharing outside the organization.",
},
502,
);
}
console.log(`files: ${name} uploaded by ${user.email}`);
// The first preview try is waited for; Drive often has it already.
const saved = await recordDriveUpload(db, uploaded, { name, mime, bytes: buffer.length, folder, userId: user.id });
return c.json({ file: saved }, 201, NO_STORE);
},
);
function findOr404(c) {
const id = Number(c.req.param("id"));
return Number.isInteger(id) ? c.get("db").prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id) : null;
}
/* ── Folders ────────────────────────────────────────────────── */
const pathOf = async (c, from = "json") => {
const body = from === "json" ? ((await c.req.json().catch(() => null)) ?? {}) : { path: c.req.query("path") };
return { body, path: cleanFolder(body.path) };
};
files.post("/files/folders", requireRole("editor"), async (c) => {
const { path } = await pathOf(c);
if (!path) return c.json({ error: "Give the folder a name." }, 422);
try {
await driveFolder(inDrive(path));
} catch (err) {
return c.json({ error: `Google Drive didn't make it: ${err.message}` }, 502);
}
await pickUp(c.get("db"), true);
console.log(`files: folder ${path} made by ${c.get("user").email}`);
return c.json({ path }, 201, NO_STORE);
});
files.patch("/files/folders", requireRole("editor"), async (c) => {
const { body, path } = await pathOf(c);
const name = cleanFolder(body.name);
if (!path) return c.json({ error: "Which folder?" }, 422);
if (!name || name.includes("/")) return c.json({ error: "Give it a new name (no slashes)." }, 422);
const renamed = [...path.split("/").slice(0, -1), name].join("/");
const db = c.get("db");
try {
await driveRename(await driveFolder(inDrive(path)), name);
} catch (err) {
return c.json({ error: `Google Drive didn't rename it: ${err.message}` }, 502);
}
forgetFolders(inDrive(path));
// The folder and everything under it.
db.prepare(
`UPDATE drive_files SET folder = ? || substr(folder, ?) WHERE folder = ? OR folder LIKE ? ESCAPE '\\'`,
).run(renamed, path.length + 1, path, `${path.replace(/[\\%_]/g, "\\$&")}/%`);
await pickUp(db, true);
console.log(`files: folder ${path} renamed to ${renamed} by ${c.get("user").email}`);
return c.json({ path: renamed }, 200, NO_STORE);
});
files.delete("/files/folders", requireRole("admin"), async (c) => {
const { path } = await pathOf(c, "query");
if (!path) return c.json({ error: "Which folder?" }, 422);
const db = c.get("db");
let id;
try {
id = await driveFolder(inDrive(path));
if (!(await driveFolderEmpty(id))) {
return c.json({ error: "That folder isn't empty: move or delete what's in it first." }, 409);
}
await driveDelete(id);
} catch (err) {
return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
forgetFolders(inDrive(path));
await pickUp(db, true);
console.log(`files: folder ${path} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
files.patch("/files/:id", requireRole("editor"), async (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
const body = (await c.req.json().catch(() => null)) ?? {};
const folder = cleanFolder(body.folder);
if (folder === null) return c.json({ error: "That isn't a folder name." }, 422);
if (folder !== row.folder) {
try {
await driveMove(row.drive_id, await driveFolder(inDrive(row.folder)), await driveFolder(inDrive(folder)));
} catch (err) {
return c.json({ error: `Google Drive didn't move it: ${err.message}` }, 502);
}
c.get("db").prepare(`UPDATE drive_files SET folder = ? WHERE id = ?`).run(folder, row.id);
console.log(`files: ${row.name} moved to ${folder || FOLDER} by ${c.get("user").email}`);
}
return c.json({ file: shape(c.get("db").prepare(`${SELECT} WHERE f.id = ?`).get(row.id)) }, 200, NO_STORE);
});
files.get("/files/:id/uses", (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
return c.json({ uses: recordsNaming(c.get("db"), [row.url]) }, 200, NO_STORE);
});
files.delete("/files/:id", requireRole("admin"), async (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
try {
await driveDelete(row.drive_id);
} catch (err) {
// Already gone from Drive (deleted by hand): the row goes anyway.
if (!/^404 /.test(err.message)) {
return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
}
c.get("db").prepare(`DELETE FROM drive_files WHERE id = ?`).run(row.id);
console.log(`files: ${row.name} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
export default files;