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:
parent
0e582c236b
commit
dc53af238f
31 changed files with 1318 additions and 113 deletions
165
server/src/routes/requests.js
Normal file
165
server/src/routes/requests.js
Normal 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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue