NGU-Web/server/src/accessGroups.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

140 lines
5.7 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
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) {
// `user` was read before the group lookups were awaited, so each
// write rechecks that a superadmin hasn't disabled or promoted the
// account meanwhile.
const STILL_OURS = `AND role <> 'superadmin' AND (is_active = 1 OR group_disabled = 1)`;
let change = null;
if (!role) {
if (user.is_active === 1) {
const res = db
.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ? ${STILL_OURS}`)
.run(user.id);
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
if (res.changes) change = "disabled: in no access group";
}
} else if (user.is_active !== 1 || user.role !== role) {
const res = db
.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ? ${STILL_OURS}`)
.run(role, user.id);
if (res.changes) 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();
}