/* ═══════════════════════════════════════════════════════════════ REQUEST ROUTE: POST /api/requests The Request form (/request): a blog post, an event, or a new or updated group, 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 defenses 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"], group: ["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 }; // details (049): at most this many keys, each value this long. const MAX_DETAILS = 30; const MAX_DETAIL = 2000; /* The form's details as a JSON object of short strings, or null. Which keys exist is the client's (requestTypes.ts); anything that isn't a plain key with a string value is dropped, as are blanks. */ export function cleanDetails(raw) { let parsed; try { parsed = JSON.parse(raw || "null"); } catch { return null; } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; const out = {}; for (const [key, value] of Object.entries(parsed).slice(0, MAX_DETAILS)) { if (!/^[a-z_]{1,40}$/.test(key) || typeof value !== "string") continue; const text = value.trim().slice(0, MAX_DETAIL); if (text) out[key] = text; } return Object.keys(out).length ? out : null; } const MIN_MESSAGE = 10; // Where in the shared drive the files go (googleService.js): a // folder per type under Requests, eg. Requests/Groups. export const DRIVE_FOLDER = "Requests"; export const TYPE_FOLDERS = { blog: "Blog Posts", event: "Events", group: "Groups", region: "Regions", partner: "Partners", team: "Teams", award: "Awards", person: "People", }; 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 details = cleanDetails(field("details", MAX_DETAILS * (MAX_DETAIL + 60))); 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, details, message, name, email, user_agent, ip_hash) VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .run( category, action, subject, details ? JSON.stringify(details) : null, 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(`${DRIVE_FOLDER}/${TYPE_FOLDERS[category]}`, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id }); } } 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(", ")}`] : []), ...Object.entries(details ?? {}).map(([key, value]) => `${key.replace(/_/g, " ")}: ${value}`), "", message, ], replyTo: email, queue: "/admin/requests", }); return c.body(null, 204); }, ); export default requests;