Add a Request form, with files in Google Drive and email notices

One form at /request for blog posts, events, and new or updated
chapters, regions (updates only), partners, teams, awards and people.
?type= opens it on one; buttons on the Community sections, blog posts,
Retreats and the front page calendar do. Files (.docx, PDF, JPEG, PNG)
go to a Google Drive folder through a service account.

Requests are feedback rows of type 'content' (migration 046), in a
third Forms queue: files download from Drive, a .docx can become a
draft blog post, and deleting a request deletes its files. New content
and data requests email the addresses in Site settings through Gmail.

Setup: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 15:54:00 -05:00
parent 0e582c236b
commit dc53af238f
31 changed files with 1318 additions and 113 deletions

View file

@ -11,6 +11,9 @@
import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload } from "../googleService.js";
import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js";
const admin = new Hono();
@ -18,13 +21,39 @@ admin.use("*", requireAuth);
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
// Website feedback, data requests and content requests share the
// table but are three queues in the admin (Forms).
const KIND_WHERE = {
feedback: "feedback_type NOT IN ('privacy', 'content')",
privacy: "feedback_type = 'privacy'",
content: "feedback_type = 'content'",
};
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject`;
/* Each row with its files (content requests), in one query. */
function withFiles(db, rows) {
if (rows.length === 0) return rows;
const files = db
.prepare(
`SELECT id, feedback_id, name, mime, size FROM feedback_files
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
)
.all(...rows.map((r) => r.id));
return rows.map((row) => ({
...row,
files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f),
}));
}
const MAX_LIMIT = 200;
const NOTE_LIMIT = 2000;
/* ── GET /api/admin/feedback ─────────────────────────────────────
?status=new one of STATUSES, or omitted for all
?kind=feedback website feedback (every type but 'privacy')
?kind=feedback website feedback (every type but the two below)
?kind=privacy data requests from the Privacy page
?kind=content content requests from /request, with files
?type=broken feedback_type
?q=retreat substring of the message
?before=41 cursor: rows with a lower id than this
@ -38,10 +67,7 @@ admin.get("/feedback", (c) => {
const where = [];
const params = [];
// Data requests and website feedback share the table but are two
// queues in the admin (Forms → Website feedback, Data requests).
const kindWhere =
kind === "privacy" ? "feedback_type = 'privacy'" : kind === "feedback" ? "feedback_type <> 'privacy'" : null;
const kindWhere = KIND_WHERE[kind] ?? null;
if (kindWhere) where.push(kindWhere);
if (STATUSES.includes(status)) {
@ -53,8 +79,8 @@ admin.get("/feedback", (c) => {
params.push(type.slice(0, 40));
}
if (q) {
where.push("message LIKE ?");
params.push(`%${q.slice(0, 100)}%`);
where.push("(message LIKE ? OR subject LIKE ?)");
params.push(`%${q.slice(0, 100)}%`, `%${q.slice(0, 100)}%`);
}
if (before && Number.isInteger(Number(before))) {
where.push("id < ?");
@ -65,8 +91,7 @@ admin.get("/feedback", (c) => {
const rows = db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
`SELECT ${COLUMNS}
FROM feedback
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY id DESC
@ -75,7 +100,7 @@ admin.get("/feedback", (c) => {
.all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take;
const page = hasMore ? rows.slice(0, take) : rows;
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows);
// Status counts cover this queue (kind) but ignore the other
// filters: the tabs show what's waiting, not what's left after a
@ -88,7 +113,8 @@ admin.get("/feedback", (c) => {
}
const newByKind = db
.prepare(
`SELECT SUM(feedback_type <> 'privacy') AS feedback, SUM(feedback_type = 'privacy') AS privacy
`SELECT SUM(${KIND_WHERE.feedback}) AS feedback, SUM(${KIND_WHERE.privacy}) AS privacy,
SUM(${KIND_WHERE.content}) AS content
FROM feedback WHERE status = 'new'`,
)
.get();
@ -97,7 +123,11 @@ admin.get("/feedback", (c) => {
{
feedback: page,
counts,
newByKind: { feedback: newByKind?.feedback ?? 0, privacy: newByKind?.privacy ?? 0 },
newByKind: {
feedback: newByKind?.feedback ?? 0,
privacy: newByKind?.privacy ?? 0,
content: newByKind?.content ?? 0,
},
nextCursor: hasMore ? page[page.length - 1].id : null,
},
200,
@ -155,13 +185,7 @@ function db_update(db, id, sets, params) {
if (changed.changes === 0) return null;
return db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
FROM feedback WHERE id = ?`,
)
.get(id);
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0];
}
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -170,20 +194,78 @@ function db_update(db, id, sets, params) {
the content itself shouldn't stay on disk.
───────────────────────────────────────────────────────────── */
admin.delete("/feedback/:id", requireRole("admin"), (c) => {
admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
const id = Number(c.req.param("id"));
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
const result = c
.get("db")
.prepare("DELETE FROM feedback WHERE id = ?")
.run(id);
const db = c.get("db");
const files = db.prepare(`SELECT drive_id FROM feedback_files WHERE feedback_id = ?`).all(id);
const result = db.prepare("DELETE FROM feedback WHERE id = ?").run(id);
if (result.changes === 0) return c.json({ error: "No such feedback." }, 404);
// The row is gone either way; a file Drive won't delete is logged
// for someone to remove from the folder by hand.
for (const { drive_id } of files) {
try {
await driveDelete(drive_id);
} catch (err) {
console.warn(`feedback #${id}: Drive file ${drive_id} not deleted: ${err.message}`);
}
}
console.log(`feedback #${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
/* ── A content request's files ───────────────────────────────────
GET /feedback/:id/files/:file download, from Drive
POST /feedback/:id/files/:file/blog-post a .docx as a new
unpublished blog post (import.js), editors and up
───────────────────────────────────────────────────────────── */
function fileOf(c) {
return c
.get("db")
.prepare(`SELECT id, drive_id, name, mime FROM feedback_files WHERE id = ? AND feedback_id = ?`)
.get(Number(c.req.param("file")), Number(c.req.param("id")));
}
async function fromDrive(file) {
try {
return await driveDownload(file.drive_id);
} catch (err) {
console.warn(`feedback file ${file.id}: Drive download failed: ${err.message}`);
throw new HttpError(502, "Google Drive didn't send that file. Try again, or find it in the Drive folder.");
}
}
admin.get("/feedback/:id/files/:file", async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
try {
return c.body(await fromDrive(file), 200, {
...NO_STORE,
"Content-Type": file.mime,
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`,
"X-Content-Type-Options": "nosniff",
});
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
throw err;
}
});
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
if (!/\.docx$/i.test(file.name)) return c.json({ error: "Only a Word document (.docx) can become a post." }, 400);
try {
return c.json(importDocx(c.get("db"), await fromDrive(file), file.name, c.get("user").email), 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;
}
});
export default admin;

View file

@ -16,6 +16,7 @@
import { Hono } from "hono";
import { clientIp, hashIp } from "../auth.js";
import { notifyNew } from "../notify.js";
const feedback = new Hono();
@ -36,14 +37,14 @@ const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other",
/* ── Input cleaning ──────────────────────────────────────────── */
function clean(value, max) {
export function clean(value, max) {
if (typeof value !== "string") return "";
return value.trim().slice(0, max);
}
// Deliberately permissive. Rejecting odd-but-valid addresses loses
// real submissions, and the field is optional anyway.
function looksLikeEmail(value) {
export function looksLikeEmail(value) {
return value === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
@ -108,6 +109,15 @@ feedback.post("/", async (c) => {
// created_at and status come from column defaults.
console.log(`feedback #${result.lastInsertRowid} (${feedbackType})`);
if (feedbackType === "privacy") {
notifyNew(db, {
id: result.lastInsertRowid,
subject: "Data request from the Privacy page",
lines: [`From: ${name ? `${name} <${email}>` : email}`, "", message],
replyTo: email,
queue: "/admin/data-requests",
});
}
return c.body(null, 204);
});

View file

@ -46,6 +46,52 @@ function freeId(db, base) {
return id;
}
/* A Word document as a new unpublished blog post, through the CRUD
engine. Returns { id, summary }; an unreadable document is a 400
HttpError. Also used by Forms → Content requests, on a file someone
sent with the Request form. */
export function importDocx(db, buffer, fileName, byEmail) {
let doc;
try {
doc = readDocx(buffer);
} catch (err) {
throw new HttpError(400, err instanceof DocxError ? err.message : "That document couldn't be read. Save it again as .docx and retry.");
}
if (doc.blocks.length === 0) throw new HttpError(400, "That document has no text to import.");
const title = doc.title || String(fileName ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const row = createRow(db, ENTITIES.blog_posts, {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
});
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${byEmail}`);
return {
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
};
}
imports.post(
"/import/docx",
requireRole("editor"),
@ -64,53 +110,9 @@ imports.post(
const file = body.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
let doc;
try {
doc = readDocx(Buffer.from(await file.arrayBuffer()));
} catch (err) {
if (err instanceof DocxError) return c.json({ error: err.message }, 400);
return c.json({ error: "That document couldn't be read. Save it again as .docx and retry." }, 400);
}
if (doc.blocks.length === 0) return c.json({ error: "That document has no text to import." }, 400);
const title = doc.title || String(file.name ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const payload = {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
};
try {
const row = createRow(db, ENTITIES.blog_posts, payload);
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${c.get("user").email}`);
return c.json(
{
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
},
201,
NO_STORE,
);
const result = importDocx(db, Buffer.from(await file.arrayBuffer()), file.name, c.get("user").email);
return c.json(result, 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;

View file

@ -0,0 +1,165 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST ROUTE: POST /api/requests
The Request form (/request): a blog post, an event, or a new or
updated chapter, region, partner, team, award or person, with up
to MAX_FILES attachments. Stored as a feedback row of type
'content' (046_content_requests.sql), files in Google Drive.
The same defences as the feedback route (honeypot, length caps,
a rate limit where it's mounted), plus: files are judged by their
first bytes, not the name or type the browser claims, and nothing
goes to Drive until everything else has passed.
nginx caps /api/ bodies at 64k; this path needs its own block
(docs/google-drive-and-mail.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { clientIp, hashIp } from "../auth.js";
import { clean, looksLikeEmail } from "./feedback.js";
import { driveDelete, driveReady, driveUpload } from "../googleService.js";
import { notifyNew } from "../notify.js";
const requests = new Hono();
// Must match REQUEST_TYPES in src/data/requestTypes.ts and the CHECK
// in 046_content_requests.sql. The actions each category allows.
const CATEGORIES = {
blog: ["new"],
event: ["new", "update"],
chapter: ["new", "update"],
region: ["update"],
partner: ["new", "update"],
team: ["new", "update"],
award: ["new", "update"],
person: ["new", "update"],
};
const LIMITS = { name: 120, email: 254, subject: 200, message: 5000 };
const MIN_MESSAGE = 10;
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. */
const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
function kindOf(bytes, name) {
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;
return null;
}
// A file name as Drive and a download header will see it.
const safeName = (name) =>
String(name ?? "file")
.replace(/[\u0000-\u001f"\\/]+/g, " ")
.trim()
.slice(0, 150) || "file";
requests.post(
"/",
bodyLimit({
maxSize: MAX_FILES * MAX_FILE_BYTES + 64 * 1024,
onError: (c) => c.json({ error: `Files can be ${MAX_FILE_BYTES / 1024 / 1024} MB each at most.` }, 413),
}),
async (c) => {
let body;
try {
body = await c.req.parseBody({ all: true });
} catch {
return c.json({ error: "Expected a form." }, 400);
}
const field = (name, max) => clean(Array.isArray(body[name]) ? body[name][0] : body[name], max);
if (field("website", 50) !== "") return c.body(null, 204); // honeypot
const category = field("category", 20);
const action = field("action", 10);
const subject = field("subject", LIMITS.subject);
const message = field("message", LIMITS.message);
const name = field("name", LIMITS.name);
const email = field("email", LIMITS.email);
const files = [body.files ?? []].flat().filter((f) => f instanceof File && f.size > 0);
const errors = {};
if (!CATEGORIES[category]) errors.category = "Choose what this is about.";
else if (!CATEGORIES[category].includes(action)) errors.action = "Choose new or update.";
if (!subject) errors.subject = "Give it a name.";
if (message.length < MIN_MESSAGE) errors.message = "Please write a little more.";
if (!email) errors.email = "We need an email address to follow up.";
else if (!looksLikeEmail(email)) errors.email = "That email doesn't look right.";
const uploads = [];
if (files.length > 0 && !driveReady()) errors.files = "File uploads aren't set up yet. Describe it in the message instead.";
else if (files.length > MAX_FILES) errors.files = `${MAX_FILES} files at most.`;
else {
for (const file of files) {
if (file.size > MAX_FILE_BYTES) {
errors.files = `${file.name} is over ${MAX_FILE_BYTES / 1024 / 1024} MB.`;
break;
}
const buffer = Buffer.from(await file.arrayBuffer());
const mime = kindOf(buffer, file.name);
if (!mime) {
errors.files = `${file.name} isn't a Word document (.docx), PDF, JPEG or PNG.`;
break;
}
uploads.push({ name: safeName(file.name), mime, buffer });
}
}
if (Object.keys(errors).length > 0) return c.json({ error: "Validation failed", fields: errors }, 422);
const db = c.get("db");
const id = Number(
db
.prepare(
`INSERT INTO feedback
(feedback_type, category, request_action, subject, message, name, email, user_agent, ip_hash)
VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(category, action, subject, message, name || null, email, clean(c.req.header("user-agent"), 500) || null, hashIp(clientIp(c)))
.lastInsertRowid,
);
// The row first, so each file in Drive is named for it; if Drive
// fails, the row and whatever did upload go again.
const stored = [];
try {
for (const file of uploads) {
stored.push({ ...file, driveId: await driveUpload(`Request ${id} - ${file.name}`, file.mime, file.buffer) });
}
} catch (err) {
console.warn(`feedback #${id}: Drive upload failed: ${err.message}`);
await Promise.allSettled(stored.map((f) => driveDelete(f.driveId)));
db.prepare(`DELETE FROM feedback WHERE id = ?`).run(id);
return c.json({ error: "Your files couldn't be stored just now. Try again in a moment." }, 502);
}
const addFile = db.prepare(`INSERT INTO feedback_files (feedback_id, drive_id, name, mime, size) VALUES (?, ?, ?, ?, ?)`);
for (const f of stored) addFile.run(id, f.driveId, f.name, f.mime, f.buffer.length);
console.log(`feedback #${id} (content: ${action} ${category}, ${stored.length} files)`);
notifyNew(db, {
id,
subject: `Request: ${action} ${category}: ${subject}`,
lines: [
`${action === "new" ? "New" : "Update"} ${category}: ${subject}`,
`From: ${name ? `${name} <${email}>` : email}`,
...(stored.length ? [`Files: ${stored.map((f) => f.name).join(", ")}`] : []),
"",
message,
],
replyTo: email,
queue: "/admin/requests",
});
return c.body(null, 204);
},
);
export default requests;