diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index a1e5c0b..06cbe06 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -83,15 +83,26 @@ For the service account to send as a Workspace user: 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. +3. `GOOGLE_MAIL_FROM` is the address it sends as. It must be a + **user** in the Workspace, one that signs in and has Gmail: not a + group (eg. `webb-admin@`, even mail-enabled), not an alias. The + service account acts as that user, and a group can't be acted as; + Google answers `Client is unauthorized to retrieve access tokens`. + A dedicated user such as `web@` keeps the sent copies out of anyone's + own mailbox. A group is fine as a **recipient** (below): each member + gets the notice. 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. +**Send a test notice**, under that box, emails whatever addresses are in +it (saved or not) straight away and shows the result on the page: +where it was sent from, or Google's reason for refusing. A new +delegation can take a while to start working, so retry it after a few +minutes before changing anything. + ## 4. The service and nginx ```sh @@ -122,13 +133,19 @@ location = /api/requests { ## Checking it +- Mail: Panel → Site settings → Notices → **Send a test notice**. + - 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 shared drive's Requests folder (made on the first upload), 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 +- `Client is unauthorized to retrieve access tokens` (or + `unauthorized_client`) on mail: `GOOGLE_MAIL_FROM` is a group or alias + rather than a user, or the delegation (step 3) is missing, has the + wrong Client ID (the service account's numeric Unique ID), or a scope + other than exactly `https://www.googleapis.com/auth/gmail.send`, or + is too new to have taken effect. `404 File not found` on upload means `GOOGLE_SHARED_DRIVE` isn't the bare id (a whole URL, say) or the service account isn't a member of the shared drive. diff --git a/server/src/notify.js b/server/src/notify.js index f56756a..ac13e0d 100644 --- a/server/src/notify.js +++ b/server/src/notify.js @@ -13,11 +13,15 @@ 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 ?? "") +/* The usable addresses in a list separated by commas, semicolons or + spaces; anything else is left out. */ +export const addresses = (text) => + String(text ?? "") .split(/[\s,;]+/) .filter((address) => EMAIL.test(address)); + +export function recipients(db) { + return addresses(db.prepare(`SELECT notify_emails FROM site_settings WHERE id = 'site'`).get()?.notify_emails); } /* queue: the admin path of the queue it landed in, eg. /admin/requests */ diff --git a/server/src/routes/panel.js b/server/src/routes/panel.js index 4b3a78e..8a2e7c1 100644 --- a/server/src/routes/panel.js +++ b/server/src/routes/panel.js @@ -4,6 +4,7 @@ GET /api/admin/panel/overview PATCH /api/admin/panel/users/:id role, is_active DELETE /api/admin/panel/users/:id/sessions sign out everywhere + POST /api/admin/panel/test-notice { to }: a test email Everything here is superadmin-only, enforced once at the top rather than per route; there's no read here that an ordinary @@ -27,6 +28,8 @@ import { Hono } from "hono"; import { requireAuth, requireRole, ROLES } from "../auth.js"; import { tx } from "../db.js"; import { NO_STORE } from "../shape.js"; +import { mailReady, sendMail } from "../googleService.js"; +import { addresses } from "../notify.js"; const panel = new Hono(); @@ -214,4 +217,42 @@ function userRow(db, id) { .get(id); } +/* ── POST /test-notice ─────────────────────────────────────────── + Site settings → Notices → "Send a test notice": one email to the + addresses in the box (saved or not), now, with Google's own words + if it refuses, so the setup can be checked without the journal. + ───────────────────────────────────────────────────────────── */ + +panel.post("/test-notice", async (c) => { + if (!mailReady()) { + return c.json( + { error: "Mail isn't set up on the server: GOOGLE_SERVICE_ACCOUNT and GOOGLE_MAIL_FROM (docs/google-drive-and-mail.md)." }, + 400, + ); + } + const body = (await c.req.json().catch(() => null)) ?? {}; + const to = addresses(body.to).slice(0, 10); + if (to.length === 0) return c.json({ error: "Enter at least one email address first." }, 422); + + const from = process.env.GOOGLE_MAIL_FROM; + try { + await sendMail({ + to, + subject: "Test notice from the NGU website", + text: [ + "This is a test from Panel → Site settings → Notices.", + "", + `Sent by ${c.get("user").email}, from ${from}.`, + "New content requests and data requests will arrive like this.", + "", + ].join("\n"), + }); + } catch (err) { + console.warn(`test notice by ${c.get("user").email} failed: ${err.message}`); + return c.json({ error: `Google refused it: ${err.message}` }, 502); + } + console.log(`test notice sent by ${c.get("user").email} to ${to.length}`); + return c.json({ sent: to, from }, 200, NO_STORE); +}); + export default panel; diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index bcd2629..467ff03 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -56,6 +56,10 @@ (LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty title, blurb and image through `onPatch`. + `widget: "testNotice"` is a text box of email addresses with a + "Send a test notice" button (TestNoticeInput below), for Site + settings → Notices. + `widget: "image"` is a text box with a preview and upload and library buttons beside it (ImageInput in MediaLibrary.tsx). Its `resolve` option is the media.ts helper for the field's public/ @@ -78,6 +82,7 @@ import { ArrowUp, ArrowDown, CaretRight } from "@phosphor-icons/react"; import { useRef, useState } from "react"; +import { ApiError, post } from "../../lib/api.ts"; import ContentBlocks from "../ContentBlocks.tsx"; import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx"; @@ -311,6 +316,14 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: onChange={onChange} onPatch={onPatch} /> + ) : widget === "testNotice" ? ( + ) : widget === "image" ? ( ); } + +/* Addresses, and a button that emails them a test notice now (the + box as typed, saved or not), showing what Google said. */ +function TestNoticeInput({ + id, + value, + locked, + className, + onChange, +}: { + id: string; + value: string | null | undefined; + locked: boolean; + className: string; + onChange: (value: string) => void; +}) { + const [busy, setBusy] = useState(false); + const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null); + + async function send() { + setBusy(true); + setNote(null); + try { + const { sent, from } = await post("/admin/panel/test-notice", { to: value }); + setNote({ tone: "ok", text: `Sent from ${from} to ${sent.join(", ")}. Check the inbox (and spam).` }); + } catch (err) { + setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." }); + } finally { + setBusy(false); + } + } + + return ( +
+ onChange(e.target.value)} + className={className} + /> + {!locked && ( +
+ + {note && ( + + {note.text} + + )} +
+ )} +
+ ); +} diff --git a/src/lib/adminSchema/siteSettings.ts b/src/lib/adminSchema/siteSettings.ts index 1311384..7d86f1c 100644 --- a/src/lib/adminSchema/siteSettings.ts +++ b/src/lib/adminSchema/siteSettings.ts @@ -128,7 +128,9 @@ export const siteSettings = { { path: "notify_emails", label: "Email new requests to", - help: "Who gets an email for each new content request (the Request form) and data request (the Privacy page), separated by commas, eg. web@nextgenerationofunity.org, board@nextgenerationofunity.org. Needs Gmail set up on the server (docs/google-drive-and-mail.md). Default: none, check Forms instead.", + widget: "testNotice", + full: true, + help: "Who gets an email for each new content request (the Request form) and data request (the Privacy page), separated by commas, eg. web@nextgenerationofunity.org, board@nextgenerationofunity.org. Needs Gmail set up on the server (docs/google-drive-and-mail.md). Send a test notice emails whatever is in the box now, saved or not, and shows Google's answer. Default: none, check Forms instead.", }, ], },