Third audit: security and server-side scalability (v1.11.0-audit) #22
18 changed files with 229 additions and 96 deletions
|
|
@ -66,16 +66,24 @@ export async function groupRole(db, email) {
|
||||||
/* Brings a group account in line with `role` (null: in no group).
|
/* 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. */
|
Returns what changed, as text for the log and the Panel, or null. */
|
||||||
export function applyGroupRole(db, user, role) {
|
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;
|
let change = null;
|
||||||
if (!role) {
|
if (!role) {
|
||||||
if (user.is_active === 1) {
|
if (user.is_active === 1) {
|
||||||
db.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ?`).run(user.id);
|
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);
|
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
|
||||||
change = "disabled: in no access group";
|
if (res.changes) change = "disabled: in no access group";
|
||||||
}
|
}
|
||||||
} else if (user.is_active !== 1 || user.role !== role) {
|
} 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);
|
const res = db
|
||||||
change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
|
.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);
|
db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id);
|
||||||
if (change) console.log(`access: ${user.email} ${change}`);
|
if (change) console.log(`access: ${user.email} ${change}`);
|
||||||
|
|
|
||||||
|
|
@ -163,18 +163,23 @@ export function listRows(db, entity, query = {}) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500));
|
const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500));
|
||||||
|
const offset = Math.max(0, Math.floor(Number(query.offset) || 0));
|
||||||
|
const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : "";
|
||||||
|
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${columns.join(", ")}
|
`SELECT ${columns.join(", ")}
|
||||||
FROM ${entity.table}
|
FROM ${entity.table}
|
||||||
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
${whereSql}
|
||||||
ORDER BY ${order}
|
ORDER BY ${order}
|
||||||
LIMIT ?`,
|
LIMIT ? OFFSET ?`,
|
||||||
)
|
)
|
||||||
.all(...params, limit);
|
.all(...params, limit, offset);
|
||||||
|
|
||||||
return { rows, total: rows.length };
|
// Every match, not just this page, so the list can say how many more.
|
||||||
|
const { total } = db.prepare(`SELECT COUNT(*) AS total FROM ${entity.table} ${whereSql}`).get(...params);
|
||||||
|
|
||||||
|
return { rows, total };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readRow(db, entity, rawId) {
|
export function readRow(db, entity, rawId) {
|
||||||
|
|
|
||||||
|
|
@ -63,7 +63,8 @@ function unzip(buf, wanted) {
|
||||||
const local = buf.readUInt32LE(at + 42);
|
const local = buf.readUInt32LE(at + 42);
|
||||||
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
|
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
|
||||||
at += 46 + nameLen + extraLen + commentLen;
|
at += 46 + nameLen + extraLen + commentLen;
|
||||||
if (!wanted.includes(name)) continue;
|
// Each part once: a zip can list the same name thousands of times.
|
||||||
|
if (!wanted.includes(name) || name in out) continue;
|
||||||
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
|
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
|
||||||
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
|
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
|
||||||
const data = buf.subarray(dataAt, dataAt + packed);
|
const data = buf.subarray(dataAt, dataAt + packed);
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@
|
||||||
import { createReadStream, readFileSync } from "node:fs";
|
import { createReadStream, readFileSync } from "node:fs";
|
||||||
import { stat } from "node:fs/promises";
|
import { stat } from "node:fs/promises";
|
||||||
import { Readable } from "node:stream";
|
import { Readable } from "node:stream";
|
||||||
import { createSign } from "node:crypto";
|
import { createSign, randomBytes } from "node:crypto";
|
||||||
|
|
||||||
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
|
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
|
||||||
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
|
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
|
||||||
|
|
@ -183,7 +183,8 @@ async function findOrMakeFolder(path) {
|
||||||
/* One file into a folder of the shared drive (driveFolder). Returns
|
/* One file into a folder of the shared drive (driveFolder). Returns
|
||||||
{ id, webViewLink }: Drive's id, and the page that shows it. */
|
{ id, webViewLink }: Drive's id, and the page that shows it. */
|
||||||
export async function driveUpload(folder, name, mime, buffer) {
|
export async function driveUpload(folder, name, mime, buffer) {
|
||||||
const boundary = `ngu${Date.now().toString(36)}`;
|
// 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 meta = JSON.stringify({ name, parents: [await driveFolder(folder)] });
|
||||||
const body = Buffer.concat([
|
const body = Buffer.concat([
|
||||||
Buffer.from(
|
Buffer.from(
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import { mkdir } from "node:fs/promises";
|
||||||
import { serve } from "@hono/node-server";
|
import { serve } from "@hono/node-server";
|
||||||
import { serveStatic } from "@hono/node-server/serve-static";
|
import { serveStatic } from "@hono/node-server/serve-static";
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
|
import { bodyLimit } from "hono/body-limit";
|
||||||
import { HTTPException } from "hono/http-exception";
|
import { HTTPException } from "hono/http-exception";
|
||||||
import { csrf } from "hono/csrf";
|
import { csrf } from "hono/csrf";
|
||||||
import { logger } from "hono/logger";
|
import { logger } from "hono/logger";
|
||||||
|
|
@ -118,6 +119,12 @@ app.use(
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/* The public JSON writes read their whole body before trimming it,
|
||||||
|
so each is capped well above its longest real body (a 5000
|
||||||
|
character message) and far below nginx's limit. */
|
||||||
|
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
|
||||||
|
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login"]) app.use(path, smallBody);
|
||||||
|
|
||||||
/* What the policy above would have blocked. Browsers post these on
|
/* What the policy above would have blocked. Browsers post these on
|
||||||
their own; a short line per report is plenty to go on. */
|
their own; a short line per report is plenty to go on. */
|
||||||
app.use("/api/csp-report", rateLimit({ windowMs: 60_000, max: 30 }));
|
app.use("/api/csp-report", rateLimit({ windowMs: 60_000, max: 30 }));
|
||||||
|
|
|
||||||
50
server/src/migrations/059_events_view.sql
Normal file
50
server/src/migrations/059_events_view.sql
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
-- ═══════════════════════════════════════════════════════════════
|
||||||
|
-- 059 EVENTS VIEW: FIRST PUBLISHED HOST, READ DIRECTLY
|
||||||
|
--
|
||||||
|
-- v_events took its host (name, logo, color) from the first row of
|
||||||
|
-- v_event_hosts, published or not, so a draft partner hosting a
|
||||||
|
-- published event showed in its page's structured data and preview
|
||||||
|
-- image. It now takes the first published host, as loadHosts does.
|
||||||
|
--
|
||||||
|
-- It also joins event_hosts, organizations and people itself:
|
||||||
|
-- through the v_event_hosts view, SQLite built every host of every
|
||||||
|
-- event for each lookup, even one event's page. Same columns.
|
||||||
|
--
|
||||||
|
-- person_awards gets the index its event_id lookups (an event's
|
||||||
|
-- awards, and the SET NULL when an event is deleted) were missing.
|
||||||
|
-- ═══════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
DROP VIEW v_events;
|
||||||
|
|
||||||
|
CREATE VIEW v_events AS
|
||||||
|
SELECT
|
||||||
|
e.*,
|
||||||
|
CASE WHEN eh.id IS NULL THEN NULL
|
||||||
|
WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
|
||||||
|
AS host_kind,
|
||||||
|
COALESCE(eh.org_id, eh.person_id) AS host_id,
|
||||||
|
COALESCE(o.name, p.display_name) AS host_name,
|
||||||
|
o.kind AS host_org_kind,
|
||||||
|
COALESCE(e.org_logo, o.logo) AS effective_org_logo,
|
||||||
|
COALESCE(e.color, o.color) AS effective_color,
|
||||||
|
COALESCE(
|
||||||
|
e.status,
|
||||||
|
CASE WHEN e.ends_on IS NOT NULL AND e.ends_on < date('now')
|
||||||
|
THEN 'past' ELSE 'upcoming' END
|
||||||
|
) AS effective_status
|
||||||
|
FROM events e
|
||||||
|
LEFT JOIN event_hosts eh
|
||||||
|
ON eh.id = (
|
||||||
|
SELECT x.id
|
||||||
|
FROM event_hosts x
|
||||||
|
LEFT JOIN organizations xo ON xo.id = x.org_id
|
||||||
|
LEFT JOIN people xp ON xp.id = x.person_id
|
||||||
|
WHERE x.event_id = e.id
|
||||||
|
AND COALESCE(xo.is_published, xp.is_published) = 1
|
||||||
|
ORDER BY x.sort_order, x.id
|
||||||
|
LIMIT 1
|
||||||
|
)
|
||||||
|
LEFT JOIN organizations o ON o.id = eh.org_id
|
||||||
|
LEFT JOIN people p ON p.id = eh.person_id;
|
||||||
|
|
||||||
|
CREATE INDEX person_awards_event_idx ON person_awards (event_id);
|
||||||
|
|
@ -262,8 +262,11 @@ auth.get("/google/callback", async (c) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
// A group account's role follows its groups, checked every time.
|
// A group account's role follows its groups, checked every time.
|
||||||
// One a superadmin disabled stays disabled whatever its groups say.
|
// One a superadmin disabled stays disabled whatever its groups say,
|
||||||
if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) {
|
// and with access groups switched off none gets in (it can't be
|
||||||
|
// rechecked, so it would keep its last role for good).
|
||||||
|
if (user.access_source === "group" && user.role !== "superadmin") {
|
||||||
|
if (!accessEnabled(db)) return backToLogin(c, "not_in_group");
|
||||||
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
|
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
|
||||||
const found = await roleFromGroups();
|
const found = await roleFromGroups();
|
||||||
if (found.failed) return backToLogin(c, "groups_unreachable");
|
if (found.failed) return backToLogin(c, "groups_unreachable");
|
||||||
|
|
|
||||||
|
|
@ -442,8 +442,8 @@ function attachAwards(db, orgs) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Events ────────────────────────────────────────────────────
|
/* ── Events ────────────────────────────────────────────────────
|
||||||
Flat, with the event scopes alongside. Retreats.tsx owns the
|
Flat, with the event scopes alongside, narrowed by the query
|
||||||
band titles and colors and filters this list by scope_id.
|
(below). Each band asks for only what it shows.
|
||||||
|
|
||||||
Oldest first, undated last. The carousel shows the list as it
|
Oldest first, undated last. The carousel shows the list as it
|
||||||
comes and opens on the first upcoming event, so past events
|
comes and opens on the first upcoming event, so past events
|
||||||
|
|
@ -461,13 +461,26 @@ content.get("/events", (c) => {
|
||||||
.prepare(`SELECT id, name, sort_order FROM event_scopes ORDER BY sort_order`)
|
.prepare(`SELECT id, name, sort_order FROM event_scopes ORDER BY sort_order`)
|
||||||
.all();
|
.all();
|
||||||
|
|
||||||
|
// Optional filters, each narrowing the list (src/lib/eventData.ts):
|
||||||
|
// ?scope=national ?host=<org or person slug> ?status=upcoming
|
||||||
|
// ?type=class,workshop
|
||||||
|
const where = [`is_published = 1`, `is_listed = 1`];
|
||||||
|
const params = [];
|
||||||
|
const scope = c.req.query("scope");
|
||||||
|
if (scope) where.push(`scope_id = ?`), params.push(scope);
|
||||||
|
const host = c.req.query("host");
|
||||||
|
if (host) {
|
||||||
|
where.push(`EXISTS (SELECT 1 FROM event_hosts h WHERE h.event_id = v_events.id AND (h.org_id = ? OR h.person_id = ?))`);
|
||||||
|
params.push(host, host);
|
||||||
|
}
|
||||||
|
const status = c.req.query("status");
|
||||||
|
if (status) where.push(`effective_status = ?`), params.push(status);
|
||||||
|
const types = (c.req.query("type") ?? "").split(",").filter(Boolean).slice(0, 20);
|
||||||
|
if (types.length) where.push(`event_type IN (${marks(types.length)})`), params.push(...types);
|
||||||
|
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(`SELECT * FROM v_events WHERE ${where.join(" AND ")} ORDER BY ${EVENT_ORDER}`)
|
||||||
`SELECT * FROM v_events
|
.all(...params);
|
||||||
WHERE is_published = 1 AND is_listed = 1
|
|
||||||
ORDER BY ${EVENT_ORDER}`,
|
|
||||||
)
|
|
||||||
.all();
|
|
||||||
|
|
||||||
const ids = rows.map((row) => row.id);
|
const ids = rows.map((row) => row.id);
|
||||||
const links = loadLinks(db, "event", ids);
|
const links = loadLinks(db, "event", ids);
|
||||||
|
|
@ -576,20 +589,17 @@ content.get("/organizations", (c) => {
|
||||||
const ids = rows.map((row) => row.id);
|
const ids = rows.map((row) => row.id);
|
||||||
const links = loadLinks(db, "organization", ids);
|
const links = loadLinks(db, "organization", ids);
|
||||||
const cards = loadBlocks(db, "organization", ids, "card");
|
const cards = loadBlocks(db, "organization", ids, "card");
|
||||||
const bodies = loadBlocks(db, "organization", ids, "body");
|
|
||||||
|
|
||||||
const organizations = rows.map((row) =>
|
// No body blocks or leadership: they grow with every organization
|
||||||
shapeOrganization(
|
// and only a group's own detail panel or page shows them, which
|
||||||
row,
|
// fetch /organizations/:id.
|
||||||
links.get(row.id) ?? [],
|
const organizations = rows.map((row) => {
|
||||||
cards.get(row.id) ?? [],
|
const { blocks, leadership, ...org } = shapeOrganization(row, links.get(row.id) ?? [], cards.get(row.id) ?? [], []);
|
||||||
bodies.get(row.id) ?? [],
|
return org;
|
||||||
),
|
});
|
||||||
);
|
|
||||||
|
|
||||||
attachRegionDetails(db, organizations);
|
attachRegionDetails(db, organizations);
|
||||||
attachGroupDetails(db, organizations);
|
attachGroupDetails(db, organizations);
|
||||||
attachLeadership(db, organizations);
|
|
||||||
|
|
||||||
return json(c, { organizations });
|
return json(c, { organizations });
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -86,9 +86,15 @@ export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER);
|
||||||
Returns what the list shows. Also how the clip tool's Save to Drive
|
Returns what the list shows. Also how the clip tool's Save to Drive
|
||||||
lands (routes/clips.js). */
|
lands (routes/clips.js). */
|
||||||
export async function recordDriveUpload(db, uploaded, { name, mime, bytes, folder, userId }) {
|
export async function recordDriveUpload(db, uploaded, { name, mime, bytes, folder, userId }) {
|
||||||
const id = db
|
// A pick-up may have found it in Drive before this insert: ours wins.
|
||||||
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`)
|
const { id } = db
|
||||||
.run(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId).lastInsertRowid;
|
.prepare(
|
||||||
|
`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (drive_id) DO UPDATE SET name = excluded.name, mime = excluded.mime, bytes = excluded.bytes,
|
||||||
|
url = excluded.url, folder = excluded.folder, uploaded_by = excluded.uploaded_by
|
||||||
|
RETURNING id`,
|
||||||
|
)
|
||||||
|
.get(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId);
|
||||||
await fetchPreview(db, db.prepare(`${SELECT} WHERE f.id = ?`).get(id), userId);
|
await fetchPreview(db, db.prepare(`${SELECT} WHERE f.id = ?`).get(id), userId);
|
||||||
return shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id));
|
return shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id));
|
||||||
}
|
}
|
||||||
|
|
@ -201,9 +207,13 @@ async function pickUp(db, force = false) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
refused.delete(file.id);
|
refused.delete(file.id);
|
||||||
const id = db
|
// OR IGNORE: another pick-up, or an upload between Drive and its
|
||||||
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`)
|
// own insert, may have recorded it meanwhile.
|
||||||
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder).lastInsertRowid;
|
const res = db
|
||||||
|
.prepare(`INSERT OR IGNORE INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`)
|
||||||
|
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder);
|
||||||
|
if (!res.changes) continue;
|
||||||
|
const id = res.lastInsertRowid;
|
||||||
console.log(`files: ${file.name} picked up from Drive`);
|
console.log(`files: ${file.name} picked up from Drive`);
|
||||||
// In the background: a folder of new files shouldn't hold the list.
|
// 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);
|
fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null);
|
||||||
|
|
|
||||||
|
|
@ -26,8 +26,9 @@ import { postsBy } from "./blog.js";
|
||||||
|
|
||||||
const people = new Hono();
|
const people = new Hono();
|
||||||
|
|
||||||
/* How many slugs one request may name. Keeps the URL sane. */
|
/* How many slugs one request may name. Keeps the URL sane (a few
|
||||||
const MAX_IDS = 50;
|
KB) while covering any hand-picked list. */
|
||||||
|
const MAX_IDS = 200;
|
||||||
|
|
||||||
function shapePerson(row) {
|
function shapePerson(row) {
|
||||||
return {
|
return {
|
||||||
|
|
@ -69,9 +70,10 @@ people.get("/teams/:id/people", (c) => {
|
||||||
|
|
||||||
const team = db
|
const team = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT id, org_id, name, tagline, color, logo
|
`SELECT t.id, t.org_id, t.name, t.tagline, t.color, t.logo
|
||||||
FROM teams
|
FROM teams t
|
||||||
WHERE id = ? AND is_published = 1`,
|
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
|
||||||
|
WHERE t.id = ? AND t.is_published = 1`,
|
||||||
)
|
)
|
||||||
.get(id);
|
.get(id);
|
||||||
|
|
||||||
|
|
@ -125,7 +127,7 @@ people.get("/people", (c) => {
|
||||||
o.id AS primary_org_id,
|
o.id AS primary_org_id,
|
||||||
o.name AS primary_org_name
|
o.name AS primary_org_name
|
||||||
FROM people p
|
FROM people p
|
||||||
LEFT JOIN organizations o ON o.id = p.primary_org_id
|
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
|
||||||
WHERE p.id IN (${marks(ids.length)})
|
WHERE p.id IN (${marks(ids.length)})
|
||||||
AND p.is_published = 1`,
|
AND p.is_published = 1`,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -79,15 +79,17 @@ export const TYPE_FOLDERS = {
|
||||||
export const MAX_FILES = 3;
|
export const MAX_FILES = 3;
|
||||||
export const MAX_FILE_BYTES = 10 * 1024 * 1024;
|
export const MAX_FILE_BYTES = 10 * 1024 * 1024;
|
||||||
|
|
||||||
/* What a file is, from its first bytes. A zip is only taken as a
|
/* What a file is, from its first bytes, and only when its name says
|
||||||
Word document when it's named like one. */
|
the same: a PDF named .html is refused, so a download is always
|
||||||
|
what it says. */
|
||||||
const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
||||||
function kindOf(bytes, name) {
|
function kindOf(bytes, name) {
|
||||||
|
const ext = String(name).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];
|
||||||
const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
|
const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
|
||||||
if (starts(0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
|
if (ext === "pdf" && starts(0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
|
||||||
if (starts(0xff, 0xd8, 0xff)) return "image/jpeg";
|
if ((ext === "jpg" || ext === "jpeg") && starts(0xff, 0xd8, 0xff)) return "image/jpeg";
|
||||||
if (starts(0x89, 0x50, 0x4e, 0x47)) return "image/png";
|
if (ext === "png" && starts(0x89, 0x50, 0x4e, 0x47)) return "image/png";
|
||||||
if (starts(0x50, 0x4b, 0x03, 0x04) && /\.docx$/i.test(name)) return DOCX;
|
if (ext === "docx" && starts(0x50, 0x4b, 0x03, 0x04)) return DOCX;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
/* ═══════════════════════════════════════════════════════════════
|
/* ═══════════════════════════════════════════════════════════════
|
||||||
EVENT DATA
|
EVENT DATA
|
||||||
|
|
||||||
One request, filtered per band. The Retreats page has three
|
Events, narrowed by the server. Each filter is part of the path,
|
||||||
bands of events, and all three call this hook, the cache in
|
so the cache in api.ts gives each its own entry and callers
|
||||||
api.ts keys on the path, so they share a single fetch and each
|
asking the same thing share one fetch.
|
||||||
narrows the result to what it shows.
|
|
||||||
|
|
||||||
useEvents({ scope: "national" }) one band
|
useEvents({ scope: "national" }) one band
|
||||||
useEvents({ host: "northwest" }) one host's events
|
useEvents({ host: "northwest" }) one host's events
|
||||||
|
|
@ -24,47 +23,33 @@
|
||||||
No fallback. An empty list on a failed request would read as
|
No fallback. An empty list on a failed request would read as
|
||||||
"nothing scheduled" when the truth is "the server is down", so
|
"nothing scheduled" when the truth is "the server is down", so
|
||||||
the error comes back and each caller says so.
|
the error comes back and each caller says so.
|
||||||
|
|
||||||
Filtering here rather than in the query keeps the endpoint to
|
|
||||||
one cached response. At a few dozen events that's the right
|
|
||||||
trade; if the list ever runs to hundreds, move the filters into
|
|
||||||
the URL and let each become its own cache entry.
|
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
import { useMemo } from "react";
|
|
||||||
|
|
||||||
import { useResource } from "./useResource.ts";
|
import { useResource } from "./useResource.ts";
|
||||||
|
|
||||||
/* One shared empty list, so a memo keyed on `scopes` doesn't
|
/* Shared empty lists, so a memo keyed on them doesn't
|
||||||
restart on every render before the data arrives. */
|
restart on every render before the data arrives. */
|
||||||
const NO_SCOPES: any[] = [];
|
const NO_SCOPES: any[] = [];
|
||||||
|
const NO_EVENTS: any[] = [];
|
||||||
|
|
||||||
export function useEvents({ scope, host, status, type }: any = {}) {
|
/* The path for a filter, as the server reads it (routes/content.js). */
|
||||||
const { data, error, loading } = useResource("/events");
|
export function eventsPath({ scope, host, status, type }: any = {}) {
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
if (scope) query.set("scope", scope);
|
||||||
|
// An organization or a person slug: co-hosting puts one event on
|
||||||
|
// both hosts' lists, which is the point.
|
||||||
|
if (host) query.set("host", host);
|
||||||
|
if (status) query.set("status", status);
|
||||||
|
const types = Array.isArray(type) ? type.join(",") : type;
|
||||||
|
if (types) query.set("type", types);
|
||||||
|
const qs = query.toString();
|
||||||
|
return qs ? `/events?${qs}` : "/events";
|
||||||
|
}
|
||||||
|
|
||||||
const all = data?.events;
|
export function useEvents(filter: any = {}) {
|
||||||
|
const { data, error, loading } = useResource(eventsPath(filter));
|
||||||
|
const events = data?.events ?? NO_EVENTS;
|
||||||
const scopes = data?.scopes ?? NO_SCOPES;
|
const scopes = data?.scopes ?? NO_SCOPES;
|
||||||
|
|
||||||
/* An array prop is a new identity on every render, which would
|
|
||||||
restart the memo each time. Joining it gives the dependency
|
|
||||||
list something stable to compare. */
|
|
||||||
const typeKey = Array.isArray(type) ? type.join(",") : (type ?? "");
|
|
||||||
|
|
||||||
const events = useMemo(() => {
|
|
||||||
let list = all ?? [];
|
|
||||||
if (scope) list = list.filter(e => e.scope_id === scope);
|
|
||||||
// `host` is an organization or a person slug, and an event can
|
|
||||||
// have several of either, co-hosting puts one event on both
|
|
||||||
// hosts' lists, which is the point.
|
|
||||||
if (host) list = list.filter(e => e.hosts?.some(h => h.id === host));
|
|
||||||
if (status) list = list.filter(e => e.status === status);
|
|
||||||
if (typeKey) {
|
|
||||||
const wanted = new Set(typeKey.split(","));
|
|
||||||
list = list.filter(e => wanted.has(e.event_type));
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
}, [all, scope, host, status, typeKey]);
|
|
||||||
|
|
||||||
return { events, scopes, loading, error };
|
return { events, scopes, loading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -254,7 +254,7 @@ export type OrganizationRecord = {
|
||||||
|
|
||||||
/** One row of GET /organizations: the card surface and details,
|
/** One row of GET /organizations: the card surface and details,
|
||||||
* without the sections only the org's own page loads. */
|
* without the sections only the org's own page loads. */
|
||||||
export type OrganizationListItem = Omit<OrganizationRecord, 'teams' | 'awards' | 'events'> & {
|
export type OrganizationListItem = Omit<OrganizationRecord, 'blocks' | 'leadership' | 'teams' | 'awards' | 'events'> & {
|
||||||
sort_order: number
|
sort_order: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -77,12 +77,12 @@ const BANDS: Record<FrontPageSectionKey, (props: BandProps) => ReactNode> = {
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const { data: page, error, reload } = useFrontPage()
|
const { data: page, error, reload } = useFrontPage()
|
||||||
|
|
||||||
// The bands below ask for events and the timeline once the front
|
// The bands below ask for the timeline once the front page has said
|
||||||
// page has said which of them to show. Start both now, alongside it:
|
// which of them to show. Start it now, alongside it: api.ts hands the
|
||||||
// api.ts hands the same request to the bands when they mount, so
|
// same request to the band when it mounts, so the page waits for one
|
||||||
// the page waits for one round trip instead of two.
|
// round trip instead of two. Events aren't fetched ahead: each band
|
||||||
|
// asks the server for only its own, so there's no one list to start.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
get('/events').catch(() => {})
|
|
||||||
get('/history').catch(() => {})
|
get('/history').catch(() => {})
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -208,7 +208,16 @@ function RequestRecord({ row }) {
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams({ limit: "500", ...(type.preset ?? {}) });
|
const params = new URLSearchParams({ limit: "500", ...(type.preset ?? {}) });
|
||||||
const { rows } = await get(`/admin/${type.entity}?${params}`, { ttl: 0 });
|
// The records matching the request's name, however far down the
|
||||||
|
// list they sort, then the first 500 for picking by hand.
|
||||||
|
const search = new URLSearchParams(params);
|
||||||
|
search.set("q", String(row.subject ?? "").trim().slice(0, 100));
|
||||||
|
const [matches, all] = await Promise.all([
|
||||||
|
search.get("q") ? get(`/admin/${type.entity}?${search}`, { ttl: 0 }) : { rows: [] },
|
||||||
|
get(`/admin/${type.entity}?${params}`, { ttl: 0 }),
|
||||||
|
]);
|
||||||
|
const seen = new Set();
|
||||||
|
const rows = [...matches.rows, ...all.rows].filter((r) => !seen.has(r.id) && seen.add(r.id));
|
||||||
const wanted = String(row.subject ?? "").toLowerCase().trim();
|
const wanted = String(row.subject ?? "").toLowerCase().trim();
|
||||||
const name = (r) => String(r[type.heading] ?? r.id);
|
const name = (r) => String(r[type.heading] ?? r.id);
|
||||||
// The closest name first: exact, then containing, then the rest.
|
// The closest name first: exact, then containing, then the rest.
|
||||||
|
|
|
||||||
|
|
@ -109,8 +109,8 @@ export default function AdminNewsletter() {
|
||||||
const cards = frontPage?.featured ?? []
|
const cards = frontPage?.featured ?? []
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
get('/admin/blog_posts?limit=200', { ttl: 0 })
|
get('/admin/blog_posts?is_published=1&is_listed=1&limit=200', { ttl: 0 })
|
||||||
.then((data: { rows: PostRow[] }) => setPosts(data.rows.filter((row) => row.is_published && row.is_listed)))
|
.then((data: { rows: PostRow[] }) => setPosts(data.rows))
|
||||||
.catch(() => setPosts([]))
|
.catch(() => setPosts([]))
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,8 @@ export default function EntityList() {
|
||||||
|
|
||||||
const [params, setParams] = useSearchParams();
|
const [params, setParams] = useSearchParams();
|
||||||
const [rows, setRows] = useState<any[]>([]);
|
const [rows, setRows] = useState<any[]>([]);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [loadingMore, setLoadingMore] = useState(false);
|
||||||
const [options, setOptions] = useState<any>({});
|
const [options, setOptions] = useState<any>({});
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<any>(null);
|
const [error, setError] = useState<any>(null);
|
||||||
|
|
@ -53,6 +55,7 @@ export default function EntityList() {
|
||||||
get("/admin/options", { ttl: 60_000 }),
|
get("/admin/options", { ttl: 60_000 }),
|
||||||
]);
|
]);
|
||||||
setRows(list.rows);
|
setRows(list.rows);
|
||||||
|
setTotal(list.total);
|
||||||
setOptions(opts.options);
|
setOptions(opts.options);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
|
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
|
||||||
|
|
@ -66,6 +69,22 @@ export default function EntityList() {
|
||||||
load();
|
load();
|
||||||
}, [load]);
|
}, [load]);
|
||||||
|
|
||||||
|
// The server sends a page at a time; the next one goes under it.
|
||||||
|
async function loadMore() {
|
||||||
|
setLoadingMore(true);
|
||||||
|
try {
|
||||||
|
const next = new URLSearchParams(params);
|
||||||
|
next.set("offset", String(rows.length));
|
||||||
|
const list = await get(`/admin/${manifest.key}?${next}`, { ttl: 0 });
|
||||||
|
setRows((current) => [...current, ...list.rows]);
|
||||||
|
setTotal(list.total);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
|
||||||
|
} finally {
|
||||||
|
setLoadingMore(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!manifest) {
|
if (!manifest) {
|
||||||
return <p className="text-muted">No such thing to edit.</p>;
|
return <p className="text-muted">No such thing to edit.</p>;
|
||||||
}
|
}
|
||||||
|
|
@ -211,6 +230,22 @@ export default function EntityList() {
|
||||||
)}
|
)}
|
||||||
{loading && <p className="px-4 py-8 text-center text-muted">Loading…</p>}
|
{loading && <p className="px-4 py-8 text-center text-muted">Loading…</p>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!loading && rows.length < total && (
|
||||||
|
<div className="mt-4 flex items-center gap-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={loadMore}
|
||||||
|
disabled={loadingMore}
|
||||||
|
className="btn border border-muted/25 px-4 py-1.5 text-sm text-muted hover:border-brand/50 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{loadingMore ? "Loading…" : "Show more"}
|
||||||
|
</button>
|
||||||
|
<p className="text-sm text-muted">
|
||||||
|
{rows.length} of {total}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { CaretRight, X } from '@phosphor-icons/react';
|
import { CaretRight, X } from '@phosphor-icons/react';
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useCommunity } from "../../lib/useCommunity.ts";
|
import { useCommunity } from "../../lib/useCommunity.ts";
|
||||||
|
import { useOrganization } from "../../lib/useContent.ts";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import ArrowLink from "../../components/ArrowLink.tsx";
|
import ArrowLink from "../../components/ArrowLink.tsx";
|
||||||
import OrgLogo from "../../components/OrgLogo.tsx";
|
import OrgLogo from "../../components/OrgLogo.tsx";
|
||||||
|
|
@ -522,9 +523,13 @@ function GroupCard({ group, color, open, onOpen }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function GroupDetail({ group, region, onClose }) {
|
function GroupDetail({ group, region, onClose }) {
|
||||||
|
// The list leaves out each group's body and leadership; this
|
||||||
|
// panel fetches them for the one group it shows.
|
||||||
|
const { data: full } = useOrganization(group.id);
|
||||||
|
|
||||||
/* "Led by" comes from affiliations rather than a text field, so
|
/* "Led by" comes from affiliations rather than a text field, so
|
||||||
it lists real people and stays empty until they exist. */
|
it lists real people and stays empty until they exist. */
|
||||||
const leads = (group.leadership ?? [])
|
const leads = (full?.leadership ?? [])
|
||||||
.map(person =>
|
.map(person =>
|
||||||
person.title ? `${person.display_name} (${person.title})` : person.display_name
|
person.title ? `${person.display_name} (${person.title})` : person.display_name
|
||||||
)
|
)
|
||||||
|
|
@ -561,7 +566,7 @@ function GroupDetail({ group, region, onClose }) {
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Blocks blocks={group.blocks} color={colorOf(region)} />
|
<Blocks blocks={full?.blocks} color={colorOf(region)} />
|
||||||
|
|
||||||
{rows.length > 0 && (
|
{rows.length > 0 && (
|
||||||
<dl className="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-1 text-sm">
|
<dl className="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-1 text-sm">
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue