NGU-Web/server/src/routes/feedback.js
Zaldimmar 2ad65cdc15 Write the site in US English
color, center, canceled, labeled, recognize and the rest, in UI
text, help text, comments, docs and names (ColorInput, QrCenter).
Migration 053 renames the two Site settings color CHECKs, whose
names are the messages the admin shows. Kept: events.status's
stored value 'cancelled' (shown as canceled), aria-labelledby,
schema.org's EventCancelled, and old migrations as they ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:24:11 -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 defenses 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 ('#groups'); 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;