Compare commits

..

2 commits

Author SHA1 Message Date
Zaldimmar
d7835dd5d4 Version v1.9.7-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:19:58 -05:00
Zaldimmar
8fd3a9b15b Add a test notice button to Site settings
Panel → Site settings → Notices → Send a test notice emails the
addresses in the box now and shows where it came from, or Google's
reason for refusing, so the Gmail setup can be checked without the
journal. Superadmins only (POST /api/admin/panel/test-notice).

The docs now say the sender must be a Workspace user: a group can't
be acted as through delegation, though it can receive notices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:18:43 -05:00
6 changed files with 149 additions and 10 deletions

View file

@ -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.

View file

@ -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 */

View file

@ -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;

View file

@ -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" ? (
<TestNoticeInput
id={id}
value={value}
locked={locked}
className={locked ? inputLocked : common.className}
onChange={onChange}
/>
) : widget === "image" ? (
<ImageInput
id={id}
@ -709,3 +722,65 @@ function IconButton({ label, onClick, danger = false, disabled = false, children
</button>
);
}
/* 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 (
<div className="space-y-2">
<input
id={id}
type="text"
value={value ?? ""}
readOnly={locked}
onChange={(e) => onChange(e.target.value)}
className={className}
/>
{!locked && (
<div className="flex flex-wrap items-center gap-3">
<button
type="button"
disabled={busy || !value?.trim()}
onClick={send}
className="rounded-full border border-brand px-3 py-1 text-sm font-medium text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"
>
{busy ? "Sending…" : "Send a test notice"}
</button>
{note && (
<span role="status" className={`text-xs ${note.tone === "ok" ? "text-link" : "text-danger"}`}>
{note.text}
</span>
)}
</div>
)}
</div>
);
}

View file

@ -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.",
},
],
},

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.9.6-content-display";
export const SITE_VERSION = "NGU-Web.v1.9.7-content-display";