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>
This commit is contained in:
Zaldimmar 2026-09-29 15:54:00 -05:00
parent 0e582c236b
commit dc53af238f
31 changed files with 1318 additions and 113 deletions

166
server/src/googleService.js Normal file
View file

@ -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,
);
}