diff --git a/CLAUDE.md b/CLAUDE.md index aed2df4..5e5a077 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,6 +37,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`. - Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`. - Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`. +- Request form (`/request`): files go to a Google Drive folder (a shared drive) and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`); off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_DRIVE_FOLDER` / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`. - Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`. ## Git workflow diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md new file mode 100644 index 0000000..702161c --- /dev/null +++ b/docs/google-drive-and-mail.md @@ -0,0 +1,118 @@ +# Google Drive and Gmail (the Request form) + +The Request form (`/request`) keeps the files people send in a Google +Drive folder, and new requests can be emailed to whoever is listed in +Panel → Site settings → Notices. Both go through one Google **service +account** (`server/src/googleService.js`). Nothing here is needed for +the rest of the site; until it's set up, the form takes no files and no +mail goes out. + +| Setting on the `ngu-api` service | What it is | +| --- | --- | +| `GOOGLE_SERVICE_ACCOUNT` | Path to the service account's key file, eg. `/etc/ngu/google-service-account.json` | +| `GOOGLE_DRIVE_FOLDER` | The Drive folder's id (the last part of its URL) | +| `GOOGLE_MAIL_FROM` | The Workspace address notices are sent from, eg. `web@nextgenerationofunity.org` | + +Files need the first two; mail needs the first and third. + +## 1. The service account + +1. In Google Cloud Console (the project that holds the Google sign-in + client is fine), enable the **Google Drive API** and the **Gmail + API**. +2. IAM & Admin → Service accounts → Create. Name it eg. `ngu-site`. It + needs no roles on the project. +3. Open it → Keys → Add key → JSON. Copy the file to the VPS, outside + the app and the repo: + + ```sh + sudo mkdir -p /etc/ngu + sudo mv ngu-site-*.json /etc/ngu/google-service-account.json + sudo chown : /etc/ngu/google-service-account.json + sudo chmod 600 /etc/ngu/google-service-account.json + ``` + + Note the account's email (`ngu-site@.iam.gserviceaccount.com`) + and, from its Details page, its **Client ID** (a long number). + +## 2. The Drive folder + +A service account has no Drive storage of its own, so the folder must +be in a **shared drive**. + +1. In Google Drive, make (or pick) a shared drive, eg. "NGU Website", + and a folder in it, eg. "Requests". +2. Shared drive → Manage members → add the service account's email as + **Content manager**. +3. Open the folder; its id is the end of the address: + `https://drive.google.com/drive/folders/`. + +Files are named `Request 12 - original name.docx`, so the number matches +the one in Forms → Content requests. Deleting a request in the admin +deletes its files from Drive too. + +## 3. Gmail (domain-wide delegation) + +For the service account to send as a Workspace user: + +1. Google Admin console → Security → Access and data control → API + controls → **Manage domain wide delegation** → Add new. +2. Client ID: the service account's Client ID from step 1. + OAuth scopes: `https://www.googleapis.com/auth/gmail.send` +3. `GOOGLE_MAIL_FROM` is the address it sends as. It must be a real + user or group-owned mailbox in the Workspace (not an alias); a + dedicated `web@` account keeps the sent mail out of anyone's inbox. + +Then in the admin, Panel → Site settings → Notices → "Email new +requests to": one or more addresses, separated by commas. Each new +content request and data request sends one plain-text email with a link +to the queue; replying goes to the person who sent the request. + +## 4. The service and nginx + +```sh +sudo systemctl edit ngu-api +``` + +```ini +[Service] +Environment=GOOGLE_SERVICE_ACCOUNT=/etc/ngu/google-service-account.json +Environment=GOOGLE_DRIVE_FOLDER= +Environment=GOOGLE_MAIL_FROM=web@nextgenerationofunity.org +``` + +nginx caps `/api/` bodies at 64k, so the form needs its own block in +the site's `server` block, beside `/api/admin/import/docx` (`nginx-dev` +has it): + +```nginx +location = /api/requests { + proxy_pass http://127.0.0.1:3001; + # the usual proxy_set_header lines + proxy_read_timeout 120s; + client_max_body_size 31m; +} +``` + +`sudo nginx -t && sudo systemctl reload nginx && sudo systemctl restart ngu-api`. + +## Checking it + +- Send a request with a small file at `/request`. The journal shows + `feedback #N (content: new blog, 1 files)`, and with mail on, + `feedback #N: notice sent to 1`. +- The file is in the Drive folder, and downloads from Forms → Content + requests. +- `token refused: unauthorized_client` on mail means the delegation + (step 3) is missing or has the wrong Client ID or scope. `404 File not + found` on upload means the folder id is wrong or the service account + isn't a member of the shared drive. + +## What the form takes + +Up to 3 files of 10 MB each: Word documents (.docx), PDFs, JPEG and PNG, +checked by their contents rather than their names +(`server/src/routes/requests.js`). A Word document on a request can be +turned into an unpublished blog post from the queue ("Make a blog post +from it"), the same conversion as Blog posts → Import from Word +(`docs/importing.md`). diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 91268c3..a7578d0 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -273,6 +273,7 @@ The numbers band's "Number Source" dropdown works the same way: | History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. | | Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). | | Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. | +| Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints and the name field's question are client-only. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `` (`src/components/RequestLink.tsx`). | | The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. | | The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | | A page section's accent colour | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a colour there, not a hex in a page. Each is readable as text on white and the tints. | diff --git a/server/src/admin-schema/siteSettings.js b/server/src/admin-schema/siteSettings.js index 2a7b86a..5242e18 100644 --- a/server/src/admin-schema/siteSettings.js +++ b/server/src/admin-schema/siteSettings.js @@ -30,6 +30,7 @@ export const siteSettings = { text("apple_touch_icon"), enumeration("indexing", ["on", "off"]), text("privacy_email"), + text("notify_emails"), ], children: [ diff --git a/server/src/googleService.js b/server/src/googleService.js new file mode 100644 index 0000000..0321c8e --- /dev/null +++ b/server/src/googleService.js @@ -0,0 +1,166 @@ +/* ═══════════════════════════════════════════════════════════════ + GOOGLE SERVICE ACCOUNT: Drive files and Gmail + + The server acting as itself (not a person signing in, that's + googleAuth.js). A service account's key signs a short JWT, which + Google swaps for an access token (RS256 with node:crypto, no + library). Two uses: + + Drive files sent with the Request form are kept in one folder, + in a shared drive (a service account has no storage of + its own), and read back for the admin. + Gmail new-request notices, sent as a Workspace user through + domain-wide delegation. + + Configured by the service environment: + + GOOGLE_SERVICE_ACCOUNT path to the key's .json file (never in + the repo) + GOOGLE_DRIVE_FOLDER the folder's id, from its URL + GOOGLE_MAIL_FROM the Workspace address notices come from + + Each part is off until its settings are there: without a folder the + form offers no uploads, and without a sender no mail goes out. + Setup: docs/google-drive-and-mail.md. + ═══════════════════════════════════════════════════════════════ */ + +import { readFileSync } from "node:fs"; +import { createSign } from "node:crypto"; + +const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"; +const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"; +const DRIVE = "https://www.googleapis.com/drive/v3/files"; +const DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files"; + +export class GoogleError extends Error {} + +let key = null; +function serviceKey() { + const file = process.env.GOOGLE_SERVICE_ACCOUNT; + if (!file) return null; + if (!key) { + const parsed = JSON.parse(readFileSync(file, "utf8")); + if (!parsed.client_email || !parsed.private_key) throw new GoogleError(`${file} is not a service account key.`); + key = parsed; + } + return key; +} + +export const driveReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DRIVE_FOLDER); +export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM); + +/* ── Access tokens, kept until a minute before they run out ──── */ + +const tokens = new Map(); + +async function accessToken(scope, subject) { + const cacheKey = `${scope} ${subject ?? ""}`; + const cached = tokens.get(cacheKey); + if (cached && cached.until > Date.now()) return cached.token; + + const sa = serviceKey(); + if (!sa) throw new GoogleError("GOOGLE_SERVICE_ACCOUNT is not set."); + const now = Math.floor(Date.now() / 1000); + const part = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url"); + const unsigned = `${part({ alg: "RS256", typ: "JWT" })}.${part({ + iss: sa.client_email, + scope, + aud: sa.token_uri ?? "https://oauth2.googleapis.com/token", + iat: now, + exp: now + 3600, + ...(subject ? { sub: subject } : {}), + })}`; + const signature = createSign("RSA-SHA256").update(unsigned).sign(sa.private_key, "base64url"); + + const res = await fetch(sa.token_uri ?? "https://oauth2.googleapis.com/token", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion: `${unsigned}.${signature}`, + }), + signal: AbortSignal.timeout(15_000), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok || !data.access_token) { + throw new GoogleError(`token refused: ${data.error_description ?? data.error ?? res.status}`); + } + tokens.set(cacheKey, { token: data.access_token, until: Date.now() + (data.expires_in - 60) * 1000 }); + return data.access_token; +} + +async function call(url, init, scope, subject) { + const res = await fetch(url, { + ...init, + headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` }, + signal: AbortSignal.timeout(60_000), + }); + if (!res.ok) { + const detail = await res.json().catch(() => null); + throw new GoogleError(`${res.status} ${detail?.error?.message ?? res.statusText}`); + } + return res; +} + +/* ── Drive ───────────────────────────────────────────────────── */ + +/* One file into the folder. Returns Drive's id for it. */ +export async function driveUpload(name, mime, buffer) { + const boundary = `ngu${Date.now().toString(36)}`; + const meta = JSON.stringify({ name, parents: [process.env.GOOGLE_DRIVE_FOLDER] }); + const body = Buffer.concat([ + Buffer.from( + `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n` + + `--${boundary}\r\nContent-Type: ${mime}\r\n\r\n`, + ), + buffer, + Buffer.from(`\r\n--${boundary}--`), + ]); + const res = await call( + `${DRIVE_UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`, + { method: "POST", headers: { "Content-Type": `multipart/related; boundary=${boundary}` }, body }, + DRIVE_SCOPE, + ); + return (await res.json()).id; +} + +export async function driveDownload(id) { + const res = await call(`${DRIVE}/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`, {}, DRIVE_SCOPE); + return Buffer.from(await res.arrayBuffer()); +} + +export async function driveDelete(id) { + await call(`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, { method: "DELETE" }, DRIVE_SCOPE); +} + +/* ── Gmail ───────────────────────────────────────────────────── */ + +// A header value can't be allowed to start a new header. +const oneLine = (value) => String(value ?? "").replace(/[\r\n]+/g, " ").trim(); +const encodeWord = (value) => `=?UTF-8?B?${Buffer.from(oneLine(value)).toString("base64")}?=`; + +/* Plain text mail from GOOGLE_MAIL_FROM. replyTo lets a reply go + straight to whoever filled in the form. */ +export async function sendMail({ to, subject, text, replyTo }) { + const from = process.env.GOOGLE_MAIL_FROM; + const headers = [ + `From: ${oneLine(from)}`, + `To: ${to.map(oneLine).join(", ")}`, + ...(replyTo ? [`Reply-To: ${oneLine(replyTo)}`] : []), + `Subject: ${encodeWord(subject)}`, + "MIME-Version: 1.0", + "Content-Type: text/plain; charset=UTF-8", + "Content-Transfer-Encoding: base64", + ]; + const raw = `${headers.join("\r\n")}\r\n\r\n${Buffer.from(text).toString("base64")}`; + await call( + "https://gmail.googleapis.com/gmail/v1/users/me/messages/send", + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ raw: Buffer.from(raw).toString("base64url") }), + }, + GMAIL_SCOPE, + from, + ); +} diff --git a/server/src/index.js b/server/src/index.js index f90f249..a933029 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -28,6 +28,7 @@ import directory from "./routes/directory.js"; import blog from "./routes/blog.js"; import pages from "./routes/pages.js"; import feedback from "./routes/feedback.js"; +import requests from "./routes/requests.js"; import auth from "./routes/auth.js"; import admin from "./routes/admin.js"; import panel from "./routes/panel.js"; @@ -170,6 +171,9 @@ app.route("/api", blog); // Tighter limit on the write path than anything else gets. app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); app.route("/api/feedback", feedback); +// Requests carry files: fewer again. +app.use("/api/requests", rateLimit({ windowMs: 10 * 60_000, max: 5 })); +app.route("/api/requests", requests); app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 })); // Looser than a password guess: each Google sign-in is two requests, diff --git a/server/src/migrations/046_content_requests.sql b/server/src/migrations/046_content_requests.sql new file mode 100644 index 0000000..2a22d1e --- /dev/null +++ b/server/src/migrations/046_content_requests.sql @@ -0,0 +1,39 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 046 CONTENT REQUESTS +-- +-- The Request form (/request): someone asks for a blog post, an +-- event, or a new or updated chapter, region, partner, team, award +-- or person, and can attach files (a .docx to fill in, photos). +-- Requests are feedback rows of type 'content', so they share the +-- admin's triage (Forms → Content requests): status, notes, delete. +-- +-- category what it's about (REQUEST_TYPES in +-- src/data/requestTypes.ts) +-- request_action 'new' or 'update' +-- subject the title or name, or which record to update +-- +-- The files themselves live in Google Drive (googleService.js); +-- feedback_files keeps Drive's id for each, and goes with its row. +-- +-- site_settings.notify_emails: who gets an email for each new +-- content or data request (Panel → Site settings), comma separated. +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE feedback ADD COLUMN category TEXT + CHECK (category IN ('blog', 'event', 'chapter', 'region', 'partner', 'team', 'award', 'person')); +ALTER TABLE feedback ADD COLUMN request_action TEXT + CHECK (request_action IN ('new', 'update')); +ALTER TABLE feedback ADD COLUMN subject TEXT; + +CREATE TABLE feedback_files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + feedback_id INTEGER NOT NULL REFERENCES feedback (id) ON DELETE CASCADE, + drive_id TEXT NOT NULL, + name TEXT NOT NULL, + mime TEXT NOT NULL, + size INTEGER NOT NULL +) STRICT; + +CREATE INDEX feedback_files_owner_idx ON feedback_files (feedback_id); + +ALTER TABLE site_settings ADD COLUMN notify_emails TEXT; diff --git a/server/src/notify.js b/server/src/notify.js new file mode 100644 index 0000000..f56756a --- /dev/null +++ b/server/src/notify.js @@ -0,0 +1,40 @@ +/* ═══════════════════════════════════════════════════════════════ + NEW-REQUEST NOTICES + + An email to the people in Panel → Site settings → "Email new + requests to" when a content request (/request) or a data request + (the Privacy page) comes in. Sent after the row is saved and never + waited on: a mail problem is logged, the submission stands. + Off until Gmail is set up (googleService.js) and someone is listed. + ═══════════════════════════════════════════════════════════════ */ + +import { mailReady, sendMail } from "./googleService.js"; +import { siteFor } from "./pageMeta.js"; + +const EMAIL = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/; + +export function recipients(db) { + const row = db.prepare(`SELECT notify_emails FROM site_settings WHERE id = 'site'`).get(); + return String(row?.notify_emails ?? "") + .split(/[\s,;]+/) + .filter((address) => EMAIL.test(address)); +} + +/* queue: the admin path of the queue it landed in, eg. /admin/requests */ +export function notifyNew(db, { id, subject, lines, replyTo, queue }) { + if (!mailReady()) return; + const to = recipients(db); + if (to.length === 0) return; + + let origin = ""; + try { + origin = (siteFor(db).url ?? "").replace(/\/$/, ""); + } catch { + // No site.json: the notice goes without a link. + } + const text = [...lines, "", origin ? `Open it: ${origin}${queue}` : `In the admin: Forms, ${queue}`, ""].join("\n"); + + sendMail({ to, subject, text, replyTo: EMAIL.test(replyTo ?? "") ? replyTo : undefined }) + .then(() => console.log(`feedback #${id}: notice sent to ${to.length}`)) + .catch((err) => console.warn(`feedback #${id}: notice failed: ${err.message}`)); +} diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js index 1461d42..da9b940 100644 --- a/server/src/pageMeta.js +++ b/server/src/pageMeta.js @@ -43,6 +43,7 @@ import { fileURLToPath } from "node:url"; import { loadBlocks, paragraphs } from "./shape.js"; import { themeCss } from "./theme.js"; +import { driveReady } from "./googleService.js"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -112,7 +113,13 @@ export function siteFor(db) { } /* What the browser app reads for headings and titles. */ -const forBrowser = (site) => ({ title: site.title, pages: site.pages, privacyEmail: site.privacyEmail }); +// requestFiles: whether the Request form can take files (Drive set up). +const forBrowser = (site) => ({ + title: site.title, + pages: site.pages, + privacyEmail: site.privacyEmail, + requestFiles: driveReady(), +}); /* robots.txt for this database's setting, as the build writes it. */ export function robotsTxt(site) { diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index e14cd1c..239cf97 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -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; diff --git a/server/src/routes/feedback.js b/server/src/routes/feedback.js index 885394e..536e235 100644 --- a/server/src/routes/feedback.js +++ b/server/src/routes/feedback.js @@ -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); }); diff --git a/server/src/routes/import.js b/server/src/routes/import.js index 118f2c3..d1c591d 100644 --- a/server/src/routes/import.js +++ b/server/src/routes/import.js @@ -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; diff --git a/server/src/routes/requests.js b/server/src/routes/requests.js new file mode 100644 index 0000000..b0936c0 --- /dev/null +++ b/server/src/routes/requests.js @@ -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; diff --git a/site.json b/site.json index 8d330e0..ad90c32 100644 --- a/site.json +++ b/site.json @@ -38,6 +38,10 @@ "title": "Feedback", "description": "Tell us what's working, what isn't, and what you'd like to see next." }, + "/request": { + "title": "Request", + "description": "Ask for a blog post, an event, or a new or updated chapter, region, partner, team, award or person on the site." + }, "/qr": { "title": "QR Codes", "description": "Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colours." diff --git a/src/App.tsx b/src/App.tsx index 2f20f98..fd90856 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -55,6 +55,7 @@ const Leadership = lazyPage(() => import("./pages/Leadership.tsx")) const Resources = lazyPage(() => import("./pages/Resources.tsx")) const History = lazyPage(() => import("./pages/History.tsx")) const Feedback = lazyPage(() => import("./pages/Feedback.tsx")) +const Request = lazyPage(() => import("./pages/Request.tsx")) const Giving = lazyPage(() => import("./pages/Giving.tsx")) const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx")) const Privacy = lazyPage(() => import("./pages/Privacy.tsx")) @@ -104,6 +105,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> @@ -129,6 +131,7 @@ export default function App() { } /> } /> + } /> } /> }> } /> diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index 0c8e37f..2223e55 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -21,6 +21,7 @@ type TouchLink = { label: string } & ( const Get_In_Touch: TouchLink[] = [ { label: "Feedback", to: "/feedback"}, + { label: "Request", to: "/request" }, { label: "Contact Us", to: "/leadership#contact" }, ]; diff --git a/src/components/RequestLink.tsx b/src/components/RequestLink.tsx new file mode 100644 index 0000000..af6b742 --- /dev/null +++ b/src/components/RequestLink.tsx @@ -0,0 +1,18 @@ +import { Link } from "react-router-dom"; +import { PaperPlaneTilt } from "@phosphor-icons/react"; + +import { requestLink } from "../data/requestTypes.ts"; + +/* A button to the Request form, opened on one kind of request + (REQUEST_TYPES). Section manifests place it with `request`. */ +export default function RequestLink({ type, label, className = "" }: { type: string; label: string; className?: string }) { + return ( + +