NGU-Web/server/src/googleService.js
Zaldimmar f99010252f Third audit: security fixes and server-side scalability
Security:
- docx unzip reads each part once (a repeated entry was a zip bomb)
- request files must be named for their type (no PDF named .html)
- team roster hidden when its organization is unpublished
- /people?ids= hides draft organizations, takes 200 ids
- v_events takes the first published host and reads event_hosts
  directly (migration 059, plus an index on person_awards.event_id)
- group accounts refused while access groups are off; group sync
  can't undo a superadmin's disable
- 64 KB body limit on login, feedback and csp-report
- Drive pick-up races no longer 500; random upload boundary

Scalability:
- /events filters by scope, host, status and type on the server;
  Home no longer prefetches every event
- /organizations leaves out bodies and leadership; the map's group
  panel fetches its own
- admin lists page with Show more and a real count
- content request record search and the newsletter's post list
  ask the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:29:26 -05:00

404 lines
16 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
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). Three uses:
Drive one shared drive (a service account has no storage of
its own), with a folder per use: "Requests" for files sent
with the Request form, and so on. Each folder is found by
name, or made, the first time it's needed; a path such as
"Media/2026" makes each level.
Gmail new-request notices, sent as a Workspace user through
domain-wide delegation.
Groups who is in the admin access groups (accessGroups.js), read
through the Directory API as a Workspace admin, the same
delegation.
Configured by the service environment:
GOOGLE_SERVICE_ACCOUNT path to the key's .json file (never in
the repo)
GOOGLE_SHARED_DRIVE the shared drive's id: only the last part
of its address, not the whole URL
GOOGLE_MAIL_FROM the Workspace address notices come from
GOOGLE_DIRECTORY_AS a Workspace admin (a user) whose view of
groups is read
Each part is off until its settings are there: without a shared drive
the form offers no uploads, and without a sender no mail goes out.
Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */
import { createReadStream, readFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { createSign, randomBytes } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
const GROUPS_SCOPE = "https://www.googleapis.com/auth/admin.directory.group.member.readonly";
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_SHARED_DRIVE);
export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM);
export const directoryReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DIRECTORY_AS);
/* ── 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, timeoutMs = 60_000) {
const res = await fetch(url, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
const detail = await res.json().catch(() => null);
throw new GoogleError(`${res.status} ${detail?.error?.message ?? res.statusText}`);
}
return res;
}
/* ── Drive ───────────────────────────────────────────────────── */
const FOLDER = "application/vnd.google-apps.folder";
// Folder path → a promise of its id. A promise, so two uploads at
// once don't both make the folder. A failed lookup is forgotten.
const folders = new Map();
/* The id of a folder in the shared drive, eg. "Requests" or
"Media/2026", made if it isn't there. Found by name, so a folder
renamed in Drive is made again under the old name. */
export function driveFolder(path) {
path = path.split("/").filter(Boolean).join("/");
let pending = folders.get(path);
if (!pending) {
pending = findOrMakeFolder(path);
folders.set(path, pending);
pending.catch(() => folders.delete(path));
}
return pending;
}
/* After a folder is renamed or deleted: its path, and the paths
under it, are looked up afresh next time. */
export function forgetFolders(path) {
for (const key of folders.keys()) if (key === path || key.startsWith(`${path}/`)) folders.delete(key);
}
async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive;
const walked = [];
for (const name of path.split("/").filter(Boolean)) {
// Each level on the way is known too: "Requests" once
// "Requests/Groups" has been found.
if (walked.length && !folders.has(walked.join("/"))) folders.set(walked.join("/"), Promise.resolve(parent));
walked.push(name);
const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,
corpora: "drive",
driveId: drive,
includeItemsFromAllDrives: "true",
supportsAllDrives: "true",
fields: "files(id)",
});
const found = (await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json()).files?.[0];
parent = found
? found.id
: (
await (
await call(
`${DRIVE}?supportsAllDrives=true&fields=id`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, mimeType: FOLDER, parents: [parent] }),
},
DRIVE_SCOPE,
)
).json()
).id;
}
return parent;
}
/* One file into a folder of the shared drive (driveFolder). Returns
{ id, webViewLink }: Drive's id, and the page that shows it. */
export async function driveUpload(folder, name, mime, buffer) {
// Random, so no file can carry it by chance or design.
const boundary = `ngu${randomBytes(16).toString("hex")}`;
const meta = JSON.stringify({ name, parents: [await driveFolder(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,webViewLink`,
{ method: "POST", headers: { "Content-Type": `multipart/related; boundary=${boundary}` }, body },
DRIVE_SCOPE,
);
return await res.json();
}
/* Everything directly in a folder: [{ id, name, mimeType, size,
webViewLink }]. size is missing for Google's own Docs, Sheets and
Slides. */
async function driveChildren(parent) {
const found = [];
let pageToken = "";
do {
const query = new URLSearchParams({
q: `'${parent}' in parents and trashed = false`,
corpora: "drive",
driveId: process.env.GOOGLE_SHARED_DRIVE,
includeItemsFromAllDrives: "true",
supportsAllDrives: "true",
pageSize: "200",
fields: "nextPageToken,files(id,name,mimeType,size,webViewLink)",
...(pageToken ? { pageToken } : {}),
});
const page = await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json();
found.push(...(page.files ?? []));
pageToken = page.nextPageToken ?? "";
} while (pageToken);
return found;
}
/* A folder and the folders under it, down to `depth` levels: the
folders' paths (relative to it, "" for itself) and ids, and every
file with the path of the folder it's in. */
export async function driveTree(path, depth = 3) {
const folderList = [{ path: "", id: await driveFolder(path) }];
const files = [];
for (let i = 0; i < folderList.length; i++) {
const here = folderList[i];
for (const item of await driveChildren(here.id)) {
if (item.mimeType === FOLDER) {
const sub = here.path ? `${here.path}/${item.name}` : item.name;
if (sub.split("/").length <= depth) {
folderList.push({ path: sub, id: item.id });
// Known now: no lookup needed to upload into it.
const full = `${path}/${sub}`;
if (!folders.has(full)) folders.set(full, Promise.resolve(item.id));
}
} else {
files.push({ ...item, folder: here.path });
}
}
}
return { folders: folderList, files };
}
/* Whether a folder has anything in it (files or folders). */
export async function driveFolderEmpty(id) {
return (await driveChildren(id)).length === 0;
}
/* A file or folder from one folder into another. */
export async function driveMove(id, fromParent, toParent) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&addParents=${encodeURIComponent(toParent)}&removeParents=${encodeURIComponent(fromParent)}`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}" },
DRIVE_SCOPE,
);
}
export async function driveRename(id, name) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) },
DRIVE_SCOPE,
);
}
/* A file on disk into a folder of the shared drive, streamed through
a resumable upload rather than read into memory (a video clip can
be large). Returns { id, webViewLink }, as driveUpload does. */
export async function driveUploadFile(folder, name, mime, filePath) {
const { size } = await stat(filePath);
const start = await call(
`${DRIVE_UPLOAD}?uploadType=resumable&supportsAllDrives=true&fields=id,webViewLink`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": mime,
"X-Upload-Content-Length": String(size),
},
body: JSON.stringify({ name, parents: [await driveFolder(folder)] }),
},
DRIVE_SCOPE,
);
const session = start.headers.get("location");
if (!session) throw new GoogleError("Drive didn't start the upload.");
const res = await call(
session,
{
method: "PUT",
headers: { "Content-Type": mime, "Content-Length": String(size) },
body: Readable.toWeb(createReadStream(filePath)),
duplex: "half",
},
DRIVE_SCOPE,
undefined,
30 * 60_000,
);
return await res.json();
}
/* Anyone with the link can view: for files the public site links to.
Refused when the shared drive (or the Workspace) doesn't allow
sharing outside the organization. */
export async function driveShareWithAnyone(id) {
await call(
`${DRIVE}/${encodeURIComponent(id)}/permissions?supportsAllDrives=true`,
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "anyone", role: "reader" }) },
DRIVE_SCOPE,
);
}
/* Drive's picture of a file's first page (PDFs, Office files), as
image bytes about `edge` pixels on the long side, or null while
Drive hasn't drawn one (it does so a little after upload) or can't. */
export async function driveThumbnail(id, edge = 1280) {
const res = await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&fields=hasThumbnail,thumbnailLink`,
{},
DRIVE_SCOPE,
);
const { hasThumbnail, thumbnailLink } = await res.json();
if (!hasThumbnail || !thumbnailLink) return null;
// The link ends in its size, eg. =s220; ask for a bigger one.
const image = await call(thumbnailLink.replace(/=s\d+$/, `=s${edge}`), {}, DRIVE_SCOPE);
return Buffer.from(await image.arrayBuffer());
}
export async function driveDownload(id) {
const res = await call(`${DRIVE}/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`, {}, DRIVE_SCOPE);
return Buffer.from(await res.arrayBuffer());
}
/* Into Drive's trash (a shared drive keeps it 30 days), not deleted
outright: a shared drive's Content manager, the service account's
role, may trash but not permanently delete. */
export async function driveDelete(id) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ trashed: true }) },
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,
);
}
/* ── Groups ──────────────────────────────────────────────────── */
/* Whether someone is in a group, directly or through a group inside
it (the Directory API's hasMember follows nesting in the domain). */
export async function isGroupMember(group, email) {
const url =
"https://admin.googleapis.com/admin/directory/v1/groups/" +
`${encodeURIComponent(group)}/hasMember/${encodeURIComponent(email)}`;
try {
const res = await call(url, {}, GROUPS_SCOPE, process.env.GOOGLE_DIRECTORY_AS);
return (await res.json()).isMember === true;
} catch (err) {
// An address Google doesn't know ("Invalid Input: memberKey",
// "Resource Not Found: memberKey") is in no group of ours. A group
// it doesn't know (groupKey) is a setup mistake, and throws.
if (/^40[04] .*memberKey/i.test(err.message)) return false;
throw new GoogleError(`${group}: ${err.message}`);
}
}