From 80877a465989e82fe5e2cff7f7d772c1be1da56b Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 17:44:04 -0500 Subject: [PATCH 001/184] Let Google Workspace groups grant admin access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Site settings → Access names a group for each of admin, editor and viewer (migration 047). Someone in one who signs in with Google gets a Google-only account with their highest group's role, and the role follows the groups: at every sign-in, hourly while signed in, and on Panel → Google groups → Re-sync now. Out of every group, the account is disabled and signed out until they're back in one. Group accounts' roles are locked in the Panel; a superadmin's Disable sticks. Superadmins and admin-cli accounts are never changed. If Google can't be asked, sign-ins are refused but the hourly check leaves accounts alone. Panel → Check their groups tests an email. Lookups use the service account through the Directory API as GOOGLE_DIRECTORY_AS. Setup: docs/google-sign-in.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/google-drive-and-mail.md | 4 +- docs/google-sign-in.md | 82 ++++++++++- server/src/accessGroups.js | 132 ++++++++++++++++++ server/src/admin-schema/siteSettings.js | 3 + server/src/googleService.js | 29 +++- server/src/index.js | 2 + server/src/migrations/047_access_groups.sql | 29 ++++ server/src/routes/auth.js | 76 +++++++--- server/src/routes/panel.js | 70 +++++++++- src/lib/adminSchema/siteSettings.ts | 21 +++ src/pages/admin/AdminLogin.tsx | 3 + src/pages/admin/AdminPanel.tsx | 146 ++++++++++++++++++-- 13 files changed, 563 insertions(+), 36 deletions(-) create mode 100644 server/src/accessGroups.js create mode 100644 server/src/migrations/047_access_groups.sql diff --git a/CLAUDE.md b/CLAUDE.md index 4095dfd..c641daa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,7 +38,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - 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 the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `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`. +- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`. ## Git workflow - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index 06cbe06..74492e0 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -82,7 +82,9 @@ 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` + OAuth scopes: `https://www.googleapis.com/auth/gmail.send` (and, + for access groups, `https://www.googleapis.com/auth/admin.directory.group.member.readonly`, + comma separated: `docs/google-sign-in.md`) 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 diff --git a/docs/google-sign-in.md b/docs/google-sign-in.md index 3d84ead..7c5f30a 100644 --- a/docs/google-sign-in.md +++ b/docs/google-sign-in.md @@ -6,7 +6,14 @@ off until the service has an OAuth client ID and secret. ## Who gets in -Only accounts that already exist. Create them as before with +Two kinds of account can sign in with Google: + +- **Group accounts**, when access groups are set up (below): anyone in + one of the site's Workspace groups. Their account is made at their + first sign-in, and their role follows the group. +- **Accounts made with admin-cli**, as before. + +Created with `admin-cli.js add ` (the password it asks for stays as a way in if Google is ever unavailable). The first time that person signs in with Google, their Google account is linked to the admin account with the @@ -14,12 +21,79 @@ same email; after that it matches by the link, even if the email later changes. `admin-cli.js list` shows which accounts are linked. Refused, with a message on the login page: no admin account for that -email, an email already linked to a different Google account, a +email (and in no access group), an email already linked to a different Google account, a disabled account, any account outside the Workspace domain (checked by Google's `hd` claim, not just the email), an unverified email. -Code: `server/src/googleAuth.js` (the Google side) and -`server/src/routes/auth.js` (matching and linking accounts). +Code: `server/src/googleAuth.js` (the Google side), +`server/src/routes/auth.js` (matching and linking accounts) and +`server/src/accessGroups.js` (access groups). + +## Access groups + +Panel → Site settings → **Access (Google groups)** names a Workspace +group for each of Admin, Editor and Viewer, eg. +`web-admins@nextgenerationofunity.org`. Any of them may be blank. + +- **First sign-in:** someone in one of the groups signs in with Google + and gets an account with the highest role their groups give (in both + the editors and viewers groups: editor). No password: Google only. + Groups inside groups count. +- **The role follows the group**, checked at every sign-in, about once + an hour while they're signed in, and whenever a superadmin presses + Panel → Google groups → **Re-sync now**. Moved to another group: the + role changes. Out of every group: the account is disabled and signed + out; put back in one, it's turned on again at the next sign-in or + re-sync. +- **In the Panel**, a group account says "Google group" and its role + can't be changed there (change the membership instead). Disable still + works, and sticks: no group check turns back on an account a + superadmin disabled. +- **Not affected:** superadmins (there's no superadmin group) and + accounts made with admin-cli, which keep the role set in the Panel + whatever groups they're in. +- **If Google can't be asked** (an outage, a setup mistake), a sign-in + is refused ("Couldn't check your Google groups"), but the hourly + check leaves accounts as they are and tries again; nobody is signed + out because Google was down. Password and admin-cli accounts still + get in. + +Panel → Google groups → **Check their groups** shows what role an email +would get, changing nothing: the quickest check of the setup. + +### Setting it up + +Group lookups use the service account from +`docs/google-drive-and-mail.md` (step 1 there), through the Admin SDK +Directory API: + +1. Cloud Console, the service account's project → APIs & Services → + Library → enable the **Admin SDK API**. +2. Admin console → Security → Access and data control → API controls → + Manage domain wide delegation → the service account's entry → Edit. + Add the scope (comma separated, beside `gmail.send`): + `https://www.googleapis.com/auth/admin.directory.group.member.readonly` +3. Pick a Workspace **user** who can see the groups' members: a super + admin, or an admin with a role that includes Groups → Read. The + lookups are made as them. Set it on the service: + + ```ini + Environment=GOOGLE_DIRECTORY_AS= + ``` + +4. Make the groups in Google Admin (or Groups), add people, and put the + addresses in Site settings → Access. Restart `ngu-api` after the + `systemctl edit`. + +`GOOGLE_SERVICE_ACCOUNT` and `GOOGLE_DIRECTORY_AS` without any groups +set changes nothing; groups set without them show a warning in the +Panel and Google sign-in works as before. + +Errors in the Panel or journal (`grep access`): `groupKey` means a group +address in Site settings isn't a group Google knows; `unauthorized_client` +means the delegation or scope (step 2) is missing, or +`GOOGLE_DIRECTORY_AS` isn't a user; `Not Authorized to access this +resource` means that user can't read the group. ## Setting up the OAuth client diff --git a/server/src/accessGroups.js b/server/src/accessGroups.js new file mode 100644 index 0000000..5c636c7 --- /dev/null +++ b/server/src/accessGroups.js @@ -0,0 +1,132 @@ +/* ═══════════════════════════════════════════════════════════════ + ADMIN ACCESS BY GOOGLE GROUP + + Panel → Site settings → Access names a Workspace group for each of + viewer, editor and admin. Someone in one of them who signs in with + Google gets an account (access_source 'group', no password) with + the highest of those roles; routes/auth.js calls groupRole() and + applyGroupRole() at every Google sign-in. + + The role then follows the group: + at sign-in always checked + while signed in startGroupSync() rechecks accounts with a + live session every SYNC_EVERY_MS, once + their last check is STALE_AFTER_MS old + Panel → Re-sync now every group account, straight away + + Out of every group: the account is disabled (group_disabled = 1) + and signed out; back in one, the next sign-in or sync turns it on + again. A superadmin's Disable in the Panel sets group_disabled = 0, + which no group check undoes. + + Never touched: superadmins and 'manual' accounts (admin-cli, which + may also sign in with Google as before). + + If Google can't be asked, a sign-in is refused (it can't be shown + to be allowed), but a background recheck leaves the account as it + is and tries again next time: an outage shouldn't sign everyone out. + + Needs GOOGLE_DIRECTORY_AS (googleService.js) and at least one group. + Setup: docs/google-sign-in.md. + ═══════════════════════════════════════════════════════════════ */ + +import { directoryReady, isGroupMember } from "./googleService.js"; + +const SYNC_EVERY_MS = 10 * 60 * 1000; +const STALE_AFTER_MS = 30 * 60 * 1000; + +// Highest first: the first group someone is in gives their role. +const GROUP_ROLES = ["admin", "editor", "viewer"]; + +/* [[role, group address], ...], highest role first, set ones only. */ +export function accessGroups(db) { + const row = + db + .prepare( + `SELECT access_group_viewer, access_group_editor, access_group_admin + FROM site_settings WHERE id = 'site'`, + ) + .get() ?? {}; + return GROUP_ROLES.map((role) => [role, String(row[`access_group_${role}`] ?? "").trim().toLowerCase()]).filter( + ([, group]) => group, + ); +} + +export const accessEnabled = (db) => directoryReady() && accessGroups(db).length > 0; + +/* The role someone's groups give them, or null for none. Throws a + GoogleError when Google can't say. */ +export async function groupRole(db, email) { + for (const [role, group] of accessGroups(db)) { + if (await isGroupMember(group, email)) return role; + } + return null; +} + +/* Brings a group account in line with `role` (null: in no group). + Returns what changed, as text for the log and the Panel, or null. */ +export function applyGroupRole(db, user, role) { + let change = null; + if (!role) { + if (user.is_active === 1) { + db.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ?`).run(user.id); + db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id); + change = "disabled: in no access group"; + } + } else if (user.is_active !== 1 || user.role !== role) { + db.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ?`).run(role, user.id); + change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`; + } + db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id); + if (change) console.log(`access: ${user.email} ${change}`); + return change; +} + +/* Rechecks group accounts: all of them (Panel → Re-sync now), or only + those signed in whose last check is stale (the timer). Accounts a + superadmin disabled are left alone. */ +export async function syncGroupAccounts(db, { all = false } = {}) { + const users = db + .prepare( + `SELECT u.id, u.email, u.role, u.is_active FROM admin_users u + WHERE u.access_source = 'group' AND u.role <> 'superadmin' + AND (u.is_active = 1 OR u.group_disabled = 1) + ${ + all + ? "" + : `AND u.is_active = 1 + AND EXISTS (SELECT 1 FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now')) + AND (u.groups_checked_at IS NULL OR u.groups_checked_at <= datetime('now', ?))` + }`, + ) + .all(...(all ? [] : [`-${STALE_AFTER_MS / 1000} seconds`])); + + const result = { checked: 0, changes: [], failed: [] }; + for (const user of users) { + try { + const change = applyGroupRole(db, user, await groupRole(db, user.email)); + result.checked++; + if (change) result.changes.push(`${user.email}: ${change}`); + } catch (err) { + console.warn(`access: couldn't check ${user.email}: ${err.message}`); + result.failed.push(`${user.email}: ${err.message}`); + } + } + return result; +} + +export function startGroupSync(db) { + let running = false; + const tick = async () => { + if (running || !accessEnabled(db)) return; + running = true; + try { + await syncGroupAccounts(db); + } catch (err) { + console.error("access sync failed", err); + } finally { + running = false; + } + }; + setInterval(tick, SYNC_EVERY_MS).unref(); +} diff --git a/server/src/admin-schema/siteSettings.js b/server/src/admin-schema/siteSettings.js index 5242e18..2947291 100644 --- a/server/src/admin-schema/siteSettings.js +++ b/server/src/admin-schema/siteSettings.js @@ -31,6 +31,9 @@ export const siteSettings = { enumeration("indexing", ["on", "off"]), text("privacy_email"), text("notify_emails"), + text("access_group_viewer"), + text("access_group_editor"), + text("access_group_admin"), ], children: [ diff --git a/server/src/googleService.js b/server/src/googleService.js index 160b585..9812620 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -4,7 +4,7 @@ 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: + 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 @@ -13,6 +13,9 @@ "Blog/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: @@ -21,6 +24,8 @@ 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. @@ -32,6 +37,7 @@ 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 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"; @@ -51,6 +57,7 @@ function serviceKey() { 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 ──── */ @@ -220,3 +227,23 @@ export async function sendMail({ to, subject, text, replyTo }) { 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}`); + } +} diff --git a/server/src/index.js b/server/src/index.js index a933029..d89b987 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -40,6 +40,7 @@ import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { logSafe, startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; +import { startGroupSync } from "./accessGroups.js"; import { ENTITIES } from "./admin-schema.js"; const HOST = process.env.HOST ?? "127.0.0.1"; @@ -213,6 +214,7 @@ app.use( app.route("/", pages); startSessionSweeper(db); +startGroupSync(db); startClipWorker(db); console.log(`clips ${CLIPS_DIR}`); diff --git a/server/src/migrations/047_access_groups.sql b/server/src/migrations/047_access_groups.sql new file mode 100644 index 0000000..0677d68 --- /dev/null +++ b/server/src/migrations/047_access_groups.sql @@ -0,0 +1,29 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 047 ACCESS BY GOOGLE GROUP +-- +-- Admin access from Google Workspace groups (accessGroups.js). +-- Panel → Site settings → Access names a group for each of viewer, +-- editor and admin. Someone in one of them who signs in with Google +-- gets an account with the highest of those roles, and keeps it only +-- while they're in the group. Superadmins and admin-cli accounts are +-- never touched. +-- +-- admin_users.access_source 'manual' (admin-cli, the Panel) or +-- 'group' (made by a group sign-in; +-- Google only, role follows the group) +-- admin_users.group_disabled 1 when a group check turned it off +-- (back in a group turns it on again); +-- a superadmin's Disable sets 0, and +-- that one sticks +-- admin_users.groups_checked_at the last group check, UTC +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE admin_users ADD COLUMN access_source TEXT NOT NULL DEFAULT 'manual' + CHECK (access_source IN ('manual', 'group')); +ALTER TABLE admin_users ADD COLUMN group_disabled INTEGER NOT NULL DEFAULT 0 + CHECK (group_disabled IN (0, 1)); +ALTER TABLE admin_users ADD COLUMN groups_checked_at TEXT; + +ALTER TABLE site_settings ADD COLUMN access_group_viewer TEXT; +ALTER TABLE site_settings ADD COLUMN access_group_editor TEXT; +ALTER TABLE site_settings ADD COLUMN access_group_admin TEXT; diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index d798f87..e2c3a3a 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -19,12 +19,14 @@ A failed login still runs a hash. Otherwise the response time itself says whether the account exists. - Nothing here creates accounts. See admin-cli.js. Google sign-in - only lets in an account that already exists: matched by its - linked Google id, or on first use by its email, which then links - it. A matching email already linked to a different Google - account is refused rather than relinked. googleAuth.js checks - the identity itself. + Accounts come from admin-cli.js, with one exception: with access + groups set up (accessGroups.js), a Google sign-in by someone in + one makes a group account, whose role then follows the group. + Otherwise Google sign-in only lets in an account that already + exists: matched by its linked Google id, or on first use by its + email, which then links it. A matching email already linked to a + different Google account is refused rather than relinked. + googleAuth.js checks the identity itself. ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; @@ -41,6 +43,7 @@ import { verifyPassword, } from "../auth.js"; import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js"; +import { accessEnabled, applyGroupRole, groupRole } from "../accessGroups.js"; import { failureLimit } from "../rateLimit.js"; import { NO_STORE } from "../shape.js"; @@ -208,24 +211,65 @@ auth.get("/google/callback", async (c) => { } const db = c.get("db"); - const columns = `id, email, name, role, is_active, google_sub`; + const columns = `id, email, name, role, is_active, google_sub, access_source, group_disabled`; + const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id); let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub); + // What the access groups give this person (accessGroups.js), asked + // only when it matters. Unanswerable is a refusal: a sign-in has to + // be shown to be allowed. + const roleFromGroups = async () => { + try { + return { role: await groupRole(db, identity.email) }; + } catch (err) { + console.warn(`google login: groups unreadable for ${identity.email}: ${err.message}`); + return { failed: true }; + } + }; + if (!user) { const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email); if (!byEmail) { - console.warn(`google login: no account for ${identity.email}`); - return backToLogin(c, "no_account"); - } - if (byEmail.google_sub) { + if (!accessEnabled(db)) { + console.warn(`google login: no account for ${identity.email}`); + return backToLogin(c, "no_account"); + } + // In an access group: the account is made now, Google only. + const found = await roleFromGroups(); + if (found.failed) return backToLogin(c, "groups_unreachable"); + if (!found.role) { + console.warn(`google login: ${identity.email} is in no access group`); + return backToLogin(c, "not_in_group"); + } + const id = db + .prepare( + `INSERT INTO admin_users (email, name, role, google_sub, access_source, groups_checked_at) + VALUES (?, ?, ?, ?, 'group', datetime('now'))`, + ) + .run(identity.email, identity.name, found.role, identity.sub).lastInsertRowid; + console.log(`account ${identity.email} made from access group (${found.role})`); + user = byId(id); + } else if (byEmail.google_sub) { console.warn(`google login: ${identity.email} is linked to another Google account`); return backToLogin(c, "linked_elsewhere"); + } else { + // Before linking: a refused sign-in mustn't change the account. + if (byEmail.is_active !== 1) return backToLogin(c, "disabled"); + db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id); + console.log(`google account linked to ${byEmail.email}`); + user = byEmail; } - // Before linking: a refused sign-in mustn't change the account. - if (byEmail.is_active !== 1) return backToLogin(c, "disabled"); - db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id); - console.log(`google account linked to ${byEmail.email}`); - user = byEmail; + } + + // A group account's role follows its groups, checked every time. + // One a superadmin disabled stays disabled whatever its groups say. + if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) { + if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled"); + const found = await roleFromGroups(); + if (found.failed) return backToLogin(c, "groups_unreachable"); + applyGroupRole(db, user, found.role); + if (!found.role) return backToLogin(c, "not_in_group"); + user = byId(user.id); } if (user.is_active !== 1) return backToLogin(c, "disabled"); diff --git a/server/src/routes/panel.js b/server/src/routes/panel.js index 8a2e7c1..0e3e1ac 100644 --- a/server/src/routes/panel.js +++ b/server/src/routes/panel.js @@ -5,6 +5,8 @@ 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 + POST /api/admin/panel/access-sync recheck every group account + POST /api/admin/panel/access-check { email }: what their groups give Everything here is superadmin-only, enforced once at the top rather than per route; there's no read here that an ordinary @@ -28,8 +30,9 @@ 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 { directoryReady, mailReady, sendMail } from "../googleService.js"; import { addresses } from "../notify.js"; +import { accessEnabled, accessGroups, groupRole, syncGroupAccounts } from "../accessGroups.js"; const panel = new Hono(); @@ -57,7 +60,8 @@ panel.get("/overview", (c) => { const users = db .prepare( `SELECT u.id, u.email, u.name, u.role, u.is_active, - u.created_at, u.last_login_at, + u.created_at, u.last_login_at, u.access_source, u.group_disabled, + u.groups_checked_at, (SELECT COUNT(*) FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions @@ -85,6 +89,12 @@ panel.get("/overview", (c) => { }, content, users, + // Google groups (accessGroups.js): which are set, and whether the + // server can read them. + access: { + directory: directoryReady(), + groups: Object.fromEntries(accessGroups(db)), + }, }, 200, NO_STORE, @@ -127,10 +137,17 @@ panel.patch("/users/:id", async (c) => { } const target = db - .prepare("SELECT id, email, role, is_active FROM admin_users WHERE id = ?") + .prepare("SELECT id, email, role, is_active, access_source FROM admin_users WHERE id = ?") .get(id); if (!target) return c.json({ error: "No such account." }, 404); + if (target.access_source === "group" && body.role !== undefined && body.role !== target.role) { + return c.json( + { error: "This account's role comes from its Google group. Change the group membership instead." }, + 409, + ); + } + const sets = []; const params = []; @@ -155,6 +172,8 @@ panel.patch("/users/:id", async (c) => { if (body.is_active !== undefined) { sets.push("is_active = ?"); params.push(Number(body.is_active) ? 1 : 0); + // A superadmin's choice: no group check undoes it (accessGroups.js). + sets.push("group_disabled = 0"); } if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); @@ -208,7 +227,8 @@ function userRow(db, id) { return db .prepare( `SELECT u.id, u.email, u.name, u.role, u.is_active, - u.created_at, u.last_login_at, + u.created_at, u.last_login_at, u.access_source, u.group_disabled, + u.groups_checked_at, (SELECT COUNT(*) FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions @@ -255,4 +275,46 @@ panel.post("/test-notice", async (c) => { return c.json({ sent: to, from }, 200, NO_STORE); }); +/* ── Access by Google group ────────────────────────────────────── + access-sync every group account against its groups now (the + timer only rechecks signed-in ones, hourly) + access-check what someone's groups would give them, changing + nothing: for checking the setup + ───────────────────────────────────────────────────────────── */ + +const accessOff = (c, db) => + accessEnabled(db) + ? null + : c.json( + { + error: directoryReady() + ? "No access groups set: Panel → Site settings → Access." + : "Group lookups aren't set up on the server: GOOGLE_SERVICE_ACCOUNT and GOOGLE_DIRECTORY_AS (docs/google-sign-in.md).", + }, + 400, + ); + +panel.post("/access-sync", async (c) => { + const db = c.get("db"); + const off = accessOff(c, db); + if (off) return off; + const result = await syncGroupAccounts(db, { all: true }); + console.log(`access re-sync by ${c.get("user").email}: ${result.checked} checked, ${result.changes.length} changed, ${result.failed.length} failed`); + return c.json(result, 200, NO_STORE); +}); + +panel.post("/access-check", async (c) => { + const db = c.get("db"); + const off = accessOff(c, db); + if (off) return off; + const body = (await c.req.json().catch(() => null)) ?? {}; + const email = String(body.email ?? "").trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return c.json({ error: "Enter an email address." }, 422); + try { + return c.json({ email, role: await groupRole(db, email) }, 200, NO_STORE); + } catch (err) { + return c.json({ error: `Google couldn't say: ${err.message}` }, 502); + } +}); + export default panel; diff --git a/src/lib/adminSchema/siteSettings.ts b/src/lib/adminSchema/siteSettings.ts index 7d86f1c..ed49905 100644 --- a/src/lib/adminSchema/siteSettings.ts +++ b/src/lib/adminSchema/siteSettings.ts @@ -122,6 +122,27 @@ export const siteSettings = { }, ], }, + { + legend: "Access (Google groups)", + note: "Anyone in one of these Workspace groups can sign in to the admin with Google; their account is made at first sign-in, with the highest role their groups give. Their role follows the groups (checked at sign-in, hourly, and by Panel → Re-sync now); out of every group, the account is disabled. Superadmins and accounts made with admin-cli aren't affected. Needs GOOGLE_DIRECTORY_AS on the server (docs/google-sign-in.md).", + fields: [ + { + path: "access_group_admin", + label: "Admins group", + help: "Its members sign in as admins: edit and delete anything. eg. web-admins@nextgenerationofunity.org. Default: none.", + }, + { + path: "access_group_editor", + label: "Editors group", + help: "Its members sign in as editors: create and edit, not delete. eg. web-editors@nextgenerationofunity.org. Default: none.", + }, + { + path: "access_group_viewer", + label: "Viewers group", + help: "Its members sign in as viewers: read only. eg. web-viewers@nextgenerationofunity.org. Default: none.", + }, + ], + }, { legend: "Notices", fields: [ diff --git a/src/pages/admin/AdminLogin.tsx b/src/pages/admin/AdminLogin.tsx index 63560e7..accbf2c 100644 --- a/src/pages/admin/AdminLogin.tsx +++ b/src/pages/admin/AdminLogin.tsx @@ -33,6 +33,9 @@ const GOOGLE_ERRORS: Record = { unverified: "That Google account's email isn't verified.", google_unreachable: "Couldn't reach Google. Try again in a moment.", google_failed: "Google sign-in didn't work. Try again, or use your password.", + not_in_group: + "That Google account isn't in a website access group. Ask a superadmin to add you to one.", + groups_unreachable: "Couldn't check your Google groups just now. Try again in a moment.", }; const fieldClass = diff --git a/src/pages/admin/AdminPanel.tsx b/src/pages/admin/AdminPanel.tsx index 5ebb543..67a2acd 100644 --- a/src/pages/admin/AdminPanel.tsx +++ b/src/pages/admin/AdminPanel.tsx @@ -6,11 +6,16 @@ assumes neither: it renders whatever the API gives it and shows whatever the API refuses. - Three blocks, deliberately boring: + Four blocks, deliberately boring: - System what's actually running, for when something is off - Content row counts, the cheapest "is the database there" - Accounts roles, access and live sessions + System what's actually running, for when something is off + Content row counts, the cheapest "is the database there" + Accounts roles, access and live sessions + Google groups check someone's groups, re-sync every group + account (server/src/accessGroups.js) + + A group account's role comes from its Google group, so its role + select is locked; Disable still works, and sticks. The role select is driven by ROLES from lib/roles.ts, so a new rung on the ladder appears here without this file changing. The @@ -25,7 +30,7 @@ ═══════════════════════════════════════════════════════════════ */ import { useCallback, useEffect, useState } from "react"; -import { del, get, patch } from "../../lib/api.ts"; +import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { useNavigate } from "react-router-dom"; import { ROLES, ROLE_LABELS, ROLE_NOTES, isSuper } from "../../lib/roles.ts"; @@ -73,6 +78,107 @@ function Stat({ label, value }) { ); } +/* Google groups: what's set, who a group would let in, and a + re-sync of every group account. */ +function AccessGroups({ access, onSynced }) { + const [email, setEmail] = useState(""); + const [busy, setBusy] = useState<"check" | "sync" | null>(null); + const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null); + const [changes, setChanges] = useState([]); + const groups = Object.entries(access?.groups ?? {}); + + async function send(kind: "check" | "sync") { + setBusy(kind); + setNote(null); + setChanges([]); + try { + if (kind === "check") { + const { role } = await post("/admin/panel/access-check", { email }); + setNote( + role + ? { tone: "ok", text: `${email} would sign in as ${ROLE_LABELS[role] ?? role}.` } + : { tone: "error", text: `${email} isn't in any of these groups.` }, + ); + } else { + const result = await post("/admin/panel/access-sync", {}); + setNote({ + tone: result.failed.length ? "error" : "ok", + text: + `Checked ${result.checked} group account${result.checked === 1 ? "" : "s"}, ` + + `${result.changes.length} changed` + + (result.failed.length ? `, ${result.failed.length} couldn't be checked.` : "."), + }); + setChanges([...result.changes, ...result.failed]); + onSynced(); + } + } catch (err) { + setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." }); + } finally { + setBusy(null); + } + } + + const button = + "rounded-full border border-brand px-4 py-1.5 text-sm font-medium text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"; + + return ( + + {!access?.directory && ( +

+ Group lookups aren't set up on the server (GOOGLE_DIRECTORY_AS, docs/google-sign-in.md). +

+ )} + {groups.length > 0 ? ( +
+ {groups.map(([role, group]) => ( +
+
{ROLE_LABELS[role] ?? role}
+
{group as string}
+
+ ))} +
+ ) : ( +

No groups set: accounts come from admin-cli only.

+ )} + +
+ + setEmail(e.target.value)} + className="min-w-0 flex-1 rounded-lg border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25 sm:max-w-sm" + /> + + +
+ {note && ( +

+ {note.text} +

+ )} + {changes.length > 0 && ( +
    + {changes.map((line) => ( +
  • {line}
  • + ))} +
+ )} +
+ ); +} + export default function AdminPanel() { const { user: me } = useAuth(); const navigate = useNavigate(); @@ -103,6 +209,16 @@ export default function AdminPanel() { load(); }, [load]); + // After a re-sync: the accounts table again, without the loading + // screen (which would clear the sync's result). + const refresh = async () => { + try { + setData(await get("/admin/panel/overview", { ttl: 0 })); + } catch { + // The table stays as it was; the next load shows any error. + } + }; + /* Replace the one row the server returns rather than refetching the whole overview; the counts didn't change. */ function mergeUser(updated) { @@ -164,7 +280,7 @@ export default function AdminPanel() { ); } - const { system, content, users } = data; + const { system, content, users, access } = data; const activeSupers = users.filter( (u) => isSuper(u) && u.is_active === 1, ).length; @@ -227,6 +343,7 @@ export default function AdminPanel() { const lastSuper = isSuper(row) && row.is_active === 1 && activeSupers <= 1; const locked = isMe || lastSuper; + const fromGroup = row.access_source === "group"; const busy = busyId === row.id; return ( @@ -243,6 +360,12 @@ export default function AdminPanel() { {row.name && (
{row.email}
)} + {fromGroup && ( +
+ Google group + {row.group_disabled === 1 && ": in no access group"} +
+ )} {rowError?.id === row.id && (
{rowError.message} @@ -253,11 +376,13 @@ export default function AdminPanel() { send(e.target.files)} /> + {error &&

{error}

} +
+ ); +} + +/* ── List ────────────────────────────────────────────────────── */ + +export function FileList({ + items, + selected, + onPick, + renderActions, +}: { + items: DriveFile[]; + selected?: string | null; + onPick?: (file: DriveFile) => void; + renderActions?: (file: DriveFile) => ReactNode; +}) { + if (items.length === 0) return

No files yet.

; + + return ( +
    + {items.map((file) => { + const isSelected = selected === file.url; + const body = ( + + + {file.preview ? ( + + ) : ( + + )} + + + + {file.name} + + {formatBytes(file.bytes)} + + + ); + return ( +
  • + {onPick ? ( + + ) : ( + body + )} + {renderActions &&
    {renderActions(file)}
    } +
  • + ); + })} +
+ ); +} + +/* ── Picker dialog ───────────────────────────────────────────── */ + +export function FilePicker({ + selected, + onPick, + onClose, +}: { + selected?: string | null; + onPick: (file: DriveFile) => void; + onClose: () => void; +}) { + const { user } = useAuth(); + const [query, setQuery] = useState(""); + const { items, ready, error, setItems } = useDriveFiles(query); + const dialogRef = useRef(null); + + useEffect(() => { + dialogRef.current?.showModal(); + }, []); + + const pick = (file: DriveFile) => { + onPick(file); + dialogRef.current?.close(); + }; + + return ( + { + if (e.target === dialogRef.current) dialogRef.current?.close(); + }} + className="w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" + > +
+
+

Choose a file

+ setQuery(e.target.value)} + placeholder="Search by file name" + className="ml-auto w-56 rounded-lg border border-muted/25 px-3 py-1.5 text-sm outline-none focus:border-brand" + /> + +
+ + {roleCanWrite(user) && ready && ( +
+ { + setItems((current) => [file, ...(current ?? [])]); + pick(file); + }} + /> +

{FILE_HELP}

+
+ )} + +
+ {!ready &&

Google Drive isn't set up on the server, so nothing can be uploaded.

} + {error ? ( +

{error}

+ ) : items === null ? ( +

Loading…

+ ) : ( + + )} +
+
+
+ ); +} + +/* "Choose a file" under a link field. */ +export function ChooseFileButton({ value, onPick }: { value?: string | null; onPick: (file: DriveFile) => void }) { + const [open, setOpen] = useState(false); + return ( + <> + + {open && setOpen(false)} />} + + ); +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 467ff03..b6d876c 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -56,6 +56,12 @@ (LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty title, blurb and image through `onPatch`. + `files: true` on a link field adds "Choose a file" (FilePicker in + DriveFiles.tsx): the field takes the file's Drive link, and with + `previewFills` (a link card) the row's empty title and picture take + the file's name and first-page preview. `filesWhen` limits it to + rows that match, as `when` does for the field. + `widget: "testNotice"` is a text box of email addresses with a "Send a test notice" button (TestNoticeInput below), for Site settings → Notices. @@ -85,6 +91,7 @@ import { useRef, useState } from "react"; import { ApiError, post } from "../../lib/api.ts"; import ContentBlocks from "../ContentBlocks.tsx"; import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx"; +import { ChooseFileButton } from "./DriveFiles.tsx"; /* Live previews a collection can name with `preview`. Each gets the row as the form holds it, which is the API's shape. */ @@ -235,6 +242,17 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: !list.some(([optionId]) => String(optionId) === String(value)); } + // A file from the Drive library into this link field (`files`). + const pickFile = (file) => { + const fills = field.previewFills; + const patch = { [field.path]: file.url }; + if (fills && !row?.[fills.title]) patch[fills.title] = file.title; + if (fills && !row?.[fills.image] && file.preview) patch[fills.image] = file.preview; + if (onPatch && !field.path.includes(".")) onPatch(patch); + else onChange(file.url); + }; + const showFiles = field.files && !locked && (!field.filesWhen || fieldShown({ when: field.filesWhen }, row)); + const common = { id, className: `${input} ${error ? inputError : ""}`, @@ -371,6 +389,11 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: className={locked ? inputLocked : common.className} /> )} + {showFiles && ( +
+ +
+ )} {error ? ( diff --git a/src/lib/adminSchema/shared.ts b/src/lib/adminSchema/shared.ts index aa7f22e..d97f2cf 100644 --- a/src/lib/adminSchema/shared.ts +++ b/src/lib/adminSchema/shared.ts @@ -362,6 +362,8 @@ export const blocksChild = { path: "href", label: "Link", full: true, + files: true, + filesWhen: { path: "type", value: ["paragraph", "button", "image"] }, when: { path: "type", value: ["paragraph", "button", "image", "video"] }, help: (row) => HREF_HELP[row?.type], }, @@ -405,8 +407,9 @@ export const blocksChild = { label: "Link", widget: "linkPreview", previewFills: { title: "text", blurb: "detail", image: "media" }, + files: true, full: true, - help: "A page on this site (eg. /retreats) or anywhere else. Fetch preview fills the title, description and picture.", + help: "A page on this site (eg. /retreats), anywhere else, or a file (Choose a file). Fetch preview fills the title, description and picture from a page; a file fills its name and first-page picture.", when: CARD_ITEM, }, { path: "text", label: "Text", required: true, help: "Schedules: the entry's title. Cards: the card's title" }, @@ -427,7 +430,7 @@ export const blocksChild = { }, { path: "detail", label: "Detail", help: "A line under the text. Lists: shown after the text", when: NOT_CARD_ITEM }, { path: "detail", label: "Description", widget: "textarea", full: true, when: CARD_ITEM }, - { path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", when: NOT_CARD_ITEM }, + { path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", files: true, when: NOT_CARD_ITEM }, { path: "media", label: "Picture", diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx index 822d2c1..9b3d573 100644 --- a/src/pages/admin/AdminMedia.tsx +++ b/src/pages/admin/AdminMedia.tsx @@ -1,10 +1,13 @@ /* ═══════════════════════════════════════════════════════════════ ADMIN: MEDIA - The uploaded-image library: search it, add to it, copy a file's - path, delete what nothing needs. Image fields in the editors - upload and pick from the same library (MediaLibrary.tsx), so this - page is for housekeeping rather than the way images get in. + Two tabs. Images: the uploaded-image library: search it, add to + it, copy a file's path, delete what nothing needs. Image fields in + the editors upload and pick from the same library + (MediaLibrary.tsx), so this is housekeeping rather than the way + images get in. Files: documents, audio and zips in the shared + Google Drive, for pages to link to (DriveFiles.tsx); link fields' + "Choose a file" picks from them. Two ranks, as on the server: editors and up upload, admins and up delete. A delete first asks the server which records still @@ -17,6 +20,12 @@ import { useState } from "react"; import { ApiError, del, get } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; +import { + FILE_HELP, + FileList, + FileUploadButton, + useDriveFiles, +} from "../../components/admin/DriveFiles.tsx"; import { MediaGrid, UPLOAD_HELP, @@ -27,7 +36,18 @@ import { type Use = { table: string; count: number }; -function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => void }) { +/* `base` is where the item lives: /admin/media or /admin/files. */ +function DeleteControl({ + item, + base = "/admin/media", + broken = "Those will show no image.", + onDeleted, +}: { + item: { id: number }; + base?: string; + broken?: string; + onDeleted: () => void; +}) { const [uses, setUses] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); @@ -36,7 +56,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => setBusy(true); setError(null); try { - const data = await get(`/admin/media/${item.id}/uses`, { ttl: 0 }); + const data = await get(`${base}/${item.id}/uses`, { ttl: 0 }); setUses(data.uses); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't check where it's used."); @@ -49,7 +69,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => setBusy(true); setError(null); try { - await del(`/admin/media/${item.id}`); + await del(`${base}/${item.id}`); onDeleted(); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't delete that."); @@ -78,8 +98,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => {uses.length > 0 ? (

Still used by{" "} - {uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those - will show no image. + {uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. {broken}

) : (

Nothing uses this file.

@@ -102,7 +121,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => ); } -function CopyPath({ url }: { url: string }) { +function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) { const [copied, setCopied] = useState(false); return ( ); } +function FilesTab() { + const { user } = useAuth(); + const [query, setQuery] = useState(""); + const { items, ready, error, setItems } = useDriveFiles(query); + + return ( + <> +
+ {roleCanWrite(user) && ready && ( +
+ setItems((current) => [file, ...(current ?? [])])} /> +

{FILE_HELP}

+
+ )} + setQuery(e.target.value)} + placeholder="Search by file name" + className="ml-auto w-64 rounded-lg border border-muted/25 px-3 py-2 text-sm outline-none focus:border-brand" + /> +
+ {!ready && ( +

+ Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded. +

+ )} +
+ {error ? ( +

{error}

+ ) : items === null ? ( +

Loading…

+ ) : ( + ( +
+ + + Open in Drive + + {canDelete(user) && ( +
+ setItems((current) => (current ?? []).filter((f) => f.id !== file.id))} + /> +
+ )} +
+ )} + /> + )} +
+ + ); +} + +const TABS = [ + ["images", "Images"], + ["files", "Files"], +] as const; + export default function AdminMedia() { const { user } = useAuth(); + const [tab, setTab] = useState<"images" | "files">("images"); const [query, setQuery] = useState(""); const { items, error, setItems } = useMediaLibrary(query); @@ -130,10 +215,34 @@ export default function AdminMedia() {

Media

- Uploaded images. Image fields in every editor pick from here. + {tab === "images" + ? "Uploaded images. Image fields in every editor pick from here." + : "Files in the shared Google Drive, for pages to link to. Link fields pick from here with Choose a file."}

+ + + {tab === "files" ? ( + + ) : ( + <> +
{roleCanWrite(user) && (
@@ -188,6 +297,8 @@ export default function AdminMedia() { /> )}
+ + )}
); } From 5f13273e696c0ccfd23fc7c01586f612a87513ae Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 18:43:38 -0500 Subject: [PATCH 004/184] Version v1.9.9-content-display Co-Authored-By: Claude Opus 5.5 --- src/lib/version.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/version.ts b/src/lib/version.ts index d24f277..76903a8 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -7,4 +7,4 @@ box or a build banner can read the same value later. ═══════════════════════════════════════════════════════════════ */ -export const SITE_VERSION = "NGU-Web.v1.9.8-content-display"; +export const SITE_VERSION = "NGU-Web.v1.9.9-content-display"; From 6191322feac4f961965cf321624d7f6e49575b80 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 19:14:40 -0500 Subject: [PATCH 005/184] Pick up files added to the Blog folder in Drive, and name nginx errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Opening Tools → Media → Files (or a Choose a file picker) now looks in the shared drive's Blog folder, at most every 30 seconds, and adds anything put there in Drive itself: shared as anyone with the link, previewed, Google Docs, Sheets and Slides included, folders and shortcuts left out. A file Drive won't share is named in a note and tried again every ten minutes. A reply that isn't the API's (nginx's own error page) now says what it was: a 413 names nginx's upload limit, a 502 the service, a 504 the timeout, instead of "Server did not return JSON". Co-Authored-By: Claude Opus 5.5 --- docs/google-drive-and-mail.md | 14 +++++++ server/src/googleService.js | 25 ++++++++++++ server/src/routes/files.js | 59 +++++++++++++++++++++++++++-- src/components/admin/DriveFiles.tsx | 49 ++++++++++++++++-------- src/lib/api.ts | 15 ++++++-- src/pages/admin/AdminMedia.tsx | 6 ++- 6 files changed, 143 insertions(+), 25 deletions(-) diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index f61183b..d2aaadc 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -189,10 +189,24 @@ Drive" above the title. little after upload. The server asks at once and again over the next few minutes, and saves it into the image library as an ordinary upload. Audio and zips get an icon in the admin and no picture. +- **Files put in the Blog folder in Drive itself** (dragged in, made + there, moved there) are listed too: opening the Files tab or a + "Choose a file" picker looks in the folder (at most every 30 + seconds), adds anything new, shares it the same way and fetches its + preview. Google's own Docs, Sheets and Slides count; folders inside it + and shortcuts don't. A file Drive won't share with anyone who has the + link is named in a red note instead of listed, and tried again every + ten minutes. - Deleting a file in the admin deletes it from Drive; the delete says first which records still link to it (those links stop working). Deleting it in Drive by hand leaves a broken link and a list entry that can still be deleted. +- **"Too large for the web server (HTTP 413)"** on upload (older builds + said "Server did not return JSON", with nothing in the journal): nginx + refused the file before it reached the API, because the site has no + `location = /api/admin/files` block (above), so the 64k `/api/` limit + applies. `sudo tail /var/log/nginx/error.log` shows "client intended + to send too large body". **Sharing has to be allowed.** Uploads fail with "Drive wouldn't share it with anyone who has the link" unless both allow it: diff --git a/server/src/googleService.js b/server/src/googleService.js index dc51e17..973076a 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -187,6 +187,31 @@ export async function driveUpload(folder, name, mime, buffer) { return await res.json(); } +/* The files (not folders) directly in a folder of the shared drive: + [{ id, name, mimeType, size, webViewLink }]. size is missing for + Google's own Docs, Sheets and Slides. */ +export async function driveList(folder) { + const parent = await driveFolder(folder); + const found = []; + let pageToken = ""; + do { + const query = new URLSearchParams({ + q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`, + 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; +} + /* 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. */ diff --git a/server/src/routes/files.js b/server/src/routes/files.js index 0521125..9d0f18b 100644 --- a/server/src/routes/files.js +++ b/server/src/routes/files.js @@ -1,7 +1,10 @@ /* ═══════════════════════════════════════════════════════════════ FILE ROUTES: mounted under /api/admin - GET /files the files, newest first, ?q=name + GET /files the files, newest first, ?q=name. + Picks up files put in the folder + in Drive by hand first (pickUp, at + most every SCAN_EVERY_MS) POST /files upload one (multipart: file) GET /files/:id/uses which records link to it DELETE /files/:id out of Drive and the list @@ -17,6 +20,12 @@ again over the next few minutes (PREVIEW_TRIES), and saved into the media library as an ordinary upload when it comes. + Files added to the folder in Drive itself (not through here) are + listed too: the next look at the list finds them, shares them the + same way and fetches their previews. Google's own Docs, Sheets and + Slides count; folders and shortcuts don't. One that Drive won't + share is left out and named in the list's `refused`. + The same ladder as media: reading needs a session, uploading editor, deleting admin. nginx needs a block for POST /files (docs/google-drive-and-mail.md). @@ -26,7 +35,7 @@ import { Hono } from "hono"; import { bodyLimit } from "hono/body-limit"; import { requireAuth, requireRole } from "../auth.js"; -import { driveDelete, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js"; +import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js"; import { addToLibrary, recordsNaming } from "./media.js"; import { NO_STORE } from "../shape.js"; @@ -38,6 +47,9 @@ const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_LIST = 500; // Seconds after upload to ask Drive for the preview again. const PREVIEW_TRIES = [0, 5, 20, 60, 180]; +// How often listing the files looks in the Drive folder for new ones. +const SCAN_EVERY_MS = 30_000; +const SKIP_TYPES = new Set(["application/vnd.google-apps.folder", "application/vnd.google-apps.shortcut"]); /* What a file is: its first bytes and its name have to agree (Office files are zips, so for them the name is what tells them apart). A @@ -101,13 +113,52 @@ function fetchPreview(db, row, userId) { return next(); } -files.get("/files", (c) => { +/* Files put in the folder in Drive by hand, added to the list and + shared. A file Drive won't share is tried again after RETRY_MS, not + on every look (a sharing setting fixed in the meantime then takes). + Never throws: the list still shows what's known. */ +const RETRY_MS = 10 * 60 * 1000; +let lastScan = 0; +const refused = new Map(); // drive id → { name, at } +async function pickUp(db) { + if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return; + lastScan = Date.now(); + let found; + try { + found = await driveList(FOLDER); + } catch (err) { + console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`); + return; + } + const known = new Set(db.prepare(`SELECT drive_id FROM drive_files`).all().map((r) => r.drive_id)); + for (const file of found) { + if (known.has(file.id) || SKIP_TYPES.has(file.mimeType)) continue; + if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue; + try { + await driveShareWithAnyone(file.id); + } catch (err) { + console.warn(`files: ${file.name} (added in Drive) not shared: ${err.message}`); + refused.set(file.id, { name: file.name, at: Date.now() }); + continue; + } + refused.delete(file.id); + const id = db + .prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url) VALUES (?, ?, ?, ?, ?)`) + .run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink).lastInsertRowid; + console.log(`files: ${file.name} picked up from Drive`); + // In the background: a folder of new files shouldn't hold the list. + fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null); + } +} + +files.get("/files", async (c) => { + await pickUp(c.get("db")); const q = (c.req.query("q") ?? "").trim().slice(0, 100); const rows = c .get("db") .prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`) .all(...(q ? [`%${q}%`] : [])); - return c.json({ files: rows.map(shape), ready: driveReady() }, 200, NO_STORE); + return c.json({ files: rows.map(shape), ready: driveReady(), refused: [...refused.values()].map((r) => r.name) }, 200, NO_STORE); }); files.post( diff --git a/src/components/admin/DriveFiles.tsx b/src/components/admin/DriveFiles.tsx index 7c6fd22..c81b163 100644 --- a/src/components/admin/DriveFiles.tsx +++ b/src/components/admin/DriveFiles.tsx @@ -13,7 +13,8 @@ file" (a field with `files: true`, fields.tsx) A link field stores the file's Drive link, a plain URL, so nothing - else needs to know where it came from. + else needs to know where it came from. Files put in the Drive + folder by hand are listed too (the server picks them up). ═══════════════════════════════════════════════════════════════ */ import { @@ -54,20 +55,19 @@ export const FILE_HELP = const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip"; +/* An icon per kind of file; Google's own Docs, Sheets and Slides + (application/vnd.google-apps.*) count as their Office kin. */ +const TYPE_ICONS: [RegExp, typeof FileIcon][] = [ + [/pdf$/, FilePdf], + [/wordprocessing|google-apps\.document$/, FileDoc], + [/spreadsheet/, FileXls], + [/presentation/, FilePpt], + [/^audio\//, FileAudio], + [/zip$/, FileZip], +]; + function TypeIcon({ mime }: { mime: string }) { - const Icon = mime === "application/pdf" - ? FilePdf - : mime.includes("wordprocessing") - ? FileDoc - : mime.includes("spreadsheet") - ? FileXls - : mime.includes("presentation") - ? FilePpt - : mime.startsWith("audio/") - ? FileAudio - : mime === "application/zip" - ? FileZip - : FileIcon; + const Icon = TYPE_ICONS.find(([test]) => test.test(mime))?.[1] ?? FileIcon; return