NGU-Web/server/src/routes/feedback.js
Zaldimmar dc53af238f 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>
2026-09-29 15:54:00 -05:00

125 lines
4.4 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
FEEDBACK ROUTE: the only public write on the site
Everything hostile that will ever reach this service arrives
here, so the defences live here rather than being sprinkled
around:
rate limit applied where this router is mounted (5/min)
honeypot a field real users never see or fill
length caps rejected before anything touches the database
no HTML stored verbatim, escaped at render time
The write is a single INSERT. No transaction: one statement is
already atomic.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { clientIp, hashIp } from "../auth.js";
import { notifyNew } from "../notify.js";
const feedback = new Hono();
const LIMITS = {
name: 120,
email: 254,
message: 5000,
pagePath: 200,
sectionId: 80,
};
const MIN_MESSAGE = 10;
// Must match FEEDBACK_TYPES and DATA_REQUEST in src/data/feedbackTypes.ts.
// Anything else falls back to 'general' rather than being rejected,
// a renamed option shouldn't lose someone's submission.
const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other", "privacy"];
/* ── Input cleaning ──────────────────────────────────────────── */
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.
export function looksLikeEmail(value) {
return value === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
/* ── POST /api/feedback ──────────────────────────────────────── */
feedback.post("/", async (c) => {
let body;
try {
// `?? {}`: a body of JSON null parses fine and has no fields.
body = (await c.req.json()) ?? {};
} catch {
return c.json({ error: "Expected a JSON body." }, 400);
}
// Honeypot. A bot fills every input it finds; a person can't see
// this one. Return success so the bot doesn't learn anything.
if (clean(body.website, 50) !== "") {
return c.body(null, 204);
}
const name = clean(body.name, LIMITS.name);
const email = clean(body.email, LIMITS.email);
const message = clean(body.message, LIMITS.message);
const pagePath = clean(body.pagePath, LIMITS.pagePath);
// The picker holds nav hashes ('#chapters'); the column holds ids.
const sectionId = clean(body.sectionId, LIMITS.sectionId).replace(/^#/, "");
const feedbackType = TYPES.includes(body.feedbackType)
? body.feedbackType
: "general";
const errors = {};
if (message.length < MIN_MESSAGE) errors.message = "Please write a little more.";
if (!looksLikeEmail(email)) errors.email = "That email doesn't look right.";
// A data request (Privacy page) has to be answerable.
else if (feedbackType === "privacy" && !email) {
errors.email = "We need an email address to reply to a data request.";
}
if (Object.keys(errors).length > 0) {
return c.json({ error: "Validation failed", fields: errors }, 422);
}
const db = c.get("db");
const result = db
.prepare(
`INSERT INTO feedback
(feedback_type, message, name, email, page_path, section_id,
user_agent, ip_hash)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
feedbackType,
message,
name || null,
email || null,
pagePath || null,
sectionId || null,
clean(c.req.header("user-agent"), 500) || null,
hashIp(clientIp(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);
});
export default feedback;