NGU-Web/server/src/pageMeta.js
Aidan Dona e4c7e165d1 Profile accounts: invites, any-Google sign-in, claiming People, visibility, Discord
Migration 076 adds a member role below viewer (the site and its own
profile, never the admin: /api/admin now needs viewer), invites, person
claims, a Discord link on accounts and people.hide_* switches. Public reads
of people go through v_people_public, which nulls hidden fields, and the
views that read people are rebuilt over it.

Admins invite an email from Data -> Profile accounts (link shown once,
emailed on request). The invitee sets a password or signs in with any
Google account under that email, asks to claim their People record, and
once approved edits it and chooses what shows at /account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:14:30 -05:00

615 lines
24 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
PAGE METADATA
What a page's HTML should say about it before any JavaScript
runs: title, description, preview image, canonical address,
whether search engines may index it, and structured data. Link
previews (Facebook, iMessage, Slack, Discord, X) never run the
app's JavaScript, so this is the only way a shared event shows
the event rather than the site's defaults.
routes/pages.js puts it into the built index.html for each
request, and serves /sitemap.xml from the same rules.
── Where it comes from ──
/site.json (SITE_CONFIG): the site's name, address, default
description and image, icons, and each static page's title and
description. Laid over it: Panel → Site settings (the
site_settings table, 035) and Pages → Navigation's page titles
(site_nav_pages, 075), where anything set wins and anything
blank falls back to site.json. siteFor(db) does the merge. The
pages read the same merged values (renderPage writes them into
the HTML as window.__SITE__, see src/lib/site.ts), so a
heading and its search title can't drift.
The database: records' names, taglines, first paragraphs and
images. A blank site description falls back to the front page's
subhead.
── Rules ──
published, listed indexed, in the sitemap
published, unlisted noindex: reachable by link, not by search
unpublished, missing 404 and noindex, with the site defaults
a hidden static page 404 and noindex below viewer, out of the
sitemap (siteNav.js)
/admin noindex
Image paths resolve like src/lib/media.ts does: a bare filename
is in the uploads directory, anything starting with / or a scheme
is used as it is.
An SVG isn't used as a preview image (the big sites won't show
one), so it falls back to the site default.
═══════════════════════════════════════════════════════════════ */
import { readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadBlocks, paragraphs } from "./shape.js";
import { themeCss } from "./theme.js";
import { driveReady } from "./googleService.js";
import { hiddenFrom, hiddenPaths, navFor } from "./siteNav.js";
const here = path.dirname(fileURLToPath(import.meta.url));
export const SITE_CONFIG = path.resolve(process.env.SITE_CONFIG ?? path.join(here, "../../site.json"));
const DESCRIPTION_CHARS = 160;
/* Where a bare filename lives: record images are uploads, whatever
kind they are. Mirrors src/lib/media.ts. */
const UPLOADS = "/uploads";
/* ── site.json, reread when it changes ─────────────────────── */
let cached = { mtime: 0, site: null };
export function loadSite() {
const mtime = statSync(SITE_CONFIG).mtimeMs;
if (cached.site && cached.mtime === mtime) return cached.site;
const site = JSON.parse(readFileSync(SITE_CONFIG, "utf8"));
cached = { mtime, site };
return site;
}
const origin = (site) => (site.url ?? "").replace(/\/$/, "");
/* site.json with the admin's Site settings laid over it: a value set
there wins, a blank one falls back. indexing 'on' / 'off' overrides
robots.index for this database only. Page overrides (Pages →
Navigation) apply only to pages site.json knows. */
export function siteFor(db) {
const base = loadSite();
const row = db.prepare(`SELECT * FROM site_settings WHERE id = 'site'`).get() ?? {};
const pages = { ...(base.pages ?? {}) };
const overrides = db
.prepare(`SELECT path, title, description FROM site_nav_pages WHERE nav_id = 'site'`)
.all();
for (const page of overrides) {
const known = pages[page.path];
if (!known) continue;
pages[page.path] = {
title: page.title || known.title,
description: page.description || known.description,
};
}
return {
...base,
title: row.site_name || base.title,
description: row.description || base.description,
openGraph: { ...base.openGraph, image: row.preview_image || base.openGraph?.image },
icons: {
...base.icons,
icon: row.favicon || base.icons?.icon,
apple: row.apple_touch_icon || base.icons?.apple,
},
robots: {
...base.robots,
index: row.indexing ? row.indexing === "on" : base.robots?.index !== false,
},
privacyEmail: row.privacy_email || base.privacyEmail || "",
// The admin's colors (theme.js): only #rrggbb values and fixed
// text, so safe inside <style>.
themeCss: themeCss(db),
pages,
};
}
/* What the browser app reads for headings, titles and its menus.
requestFiles: whether the Request form can take files (Drive set
up). nav: this visitor's links and the hidden pages (siteNav.js). */
const forBrowser = (site, nav) => ({
title: site.title,
pages: site.pages,
privacyEmail: site.privacyEmail,
requestFiles: driveReady(),
nav,
});
/* robots.txt for this database's setting, as the build writes it. */
export function robotsTxt(site) {
if (site.robots?.index === false) return "User-agent: *\nDisallow: /\n";
return (
"User-agent: *\nDisallow: /admin\nDisallow: /api\n" +
(site.url ? `\nSitemap: ${origin(site)}/sitemap.xml\n` : "")
);
}
/* ── Helpers ───────────────────────────────────────────────── */
/* Text as a description: the formatting marks content blocks allow
(**bold**, *italic*, [text](url)) taken out, whitespace folded,
cut on a word near DESCRIPTION_CHARS. */
export function plainText(text) {
if (!text) return null;
// A description is ~160 characters; reading far past that only
// gives the patterns below more to rescan on pathological text.
const flat = String(text)
.slice(0, 2000)
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/\*\*(.+?)\*\*/g, "$1")
.replace(/\*(.+?)\*/g, "$1")
.replace(/\s+/g, " ")
.trim();
if (!flat) return null;
if (flat.length <= DESCRIPTION_CHARS) return flat;
const cut = flat.slice(0, DESCRIPTION_CHARS);
const space = cut.lastIndexOf(" ");
return `${(space > DESCRIPTION_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
}
const first = (...values) => values.find((v) => v != null && String(v).trim() !== "") ?? null;
function imageUrl(site, file, kind) {
if (!file || /\.svg(\?|#|$)/i.test(file)) return null;
// A record's bare filename is an upload; the site's own default
// image (kind null) is a path from the site's root.
const pathOrUrl = /^(https?:|\/)/.test(file) ? file : kind ? `${UPLOADS}/${file}` : `/${file}`;
return /^https?:/.test(pathOrUrl) ? pathOrUrl : `${origin(site)}${pathOrUrl}`;
}
function firstParagraph(db, ownerKind, id, slot) {
return paragraphs(loadBlocks(db, ownerKind, [id], slot).get(id) ?? [])[0] ?? null;
}
/* ── One page ──────────────────────────────────────────────── */
const ORG_ROUTES = { region: "/regions", group: "/groups", partner: "/partners", national: "/organizations" };
function defaults(site, db, pathname) {
const home = db.prepare(`SELECT headline, subhead FROM front_page WHERE id = 'home'`).get();
return {
status: 200,
title: site.title,
description: plainText(first(site.description, home?.subhead)),
image: imageUrl(site, site.openGraph?.image, null),
canonical: `${origin(site)}${pathname === "/" ? "/" : pathname}`,
type: "website",
noindex: false,
jsonLd: null,
site,
};
}
function notFound(meta) {
return { ...meta, status: 404, noindex: true, title: `Page not found | ${meta.title}` };
}
/* Title for a record page: "Name | Site". */
const titled = (site, name) => `${name} | ${site.title}`;
function eventMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM v_events WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
const when = [row.date_label, row.location_label].filter(Boolean).join(" · ");
const image =
imageUrl(site, row.photo, "eventPhoto") ??
imageUrl(site, row.event_logo, "eventLogo") ??
imageUrl(site, row.effective_org_logo, "organization") ??
meta.image;
const description = plainText(first(row.tagline, firstParagraph(db, "event", id, "card"), when, row.theme));
const place = row.is_online
? { "@type": "VirtualLocation", url: meta.canonical }
: {
"@type": "Place",
name: first(row.venue, row.location_label, row.locality),
address: {
"@type": "PostalAddress",
streetAddress: row.address ?? undefined,
addressLocality: row.locality ?? undefined,
addressRegion: row.state_code ?? undefined,
addressCountry: row.country ?? undefined,
},
};
return {
...meta,
title: titled(site, row.title),
description,
image,
noindex: row.is_listed !== 1,
jsonLd: row.starts_on
? {
"@context": "https://schema.org",
"@type": "Event",
name: row.title,
description: description ?? undefined,
startDate: row.starts_on,
endDate: row.ends_on ?? undefined,
eventStatus:
row.effective_status === "cancelled"
? "https://schema.org/EventCancelled"
: "https://schema.org/EventScheduled",
eventAttendanceMode: row.is_online
? "https://schema.org/OnlineEventAttendanceMode"
: "https://schema.org/OfflineEventAttendanceMode",
location: place,
image: image ? [image] : undefined,
organizer: row.host_name ? { "@type": "Organization", name: row.host_name } : undefined,
url: meta.canonical,
}
: null,
};
}
function organizationMeta(site, db, id, kind, meta) {
const row = db.prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1`).get(id);
// /regions/x must be a region: the same slug under the wrong route
// is a page the site doesn't have. A ministry has no page at all
// (063_ministries.sql).
if (!row || (kind && row.kind !== kind) || row.kind === "ministry") return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(first(row.tagline, firstParagraph(db, "organization", id, "card"))),
image: imageUrl(site, row.logo, "organization") ?? meta.image,
canonical: `${origin(site)}${ORG_ROUTES[row.kind] ?? "/organizations"}/${row.id}`,
noindex: row.is_listed !== 1,
};
}
function teamMeta(site, db, id, meta) {
const row = db
.prepare(
`SELECT t.* FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.id = ? AND t.is_published = 1`,
)
.get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(first(row.tagline, firstParagraph(db, "team", id, "card"))),
image: imageUrl(site, row.logo, "team") ?? meta.image,
noindex: row.is_listed !== 1,
};
}
function awardMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM awards WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(row.description),
image: imageUrl(site, row.logo, "award") ?? meta.image,
noindex: row.is_listed !== 1,
};
}
function personMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM v_people_public WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.display_name),
description: plainText(first(row.tagline, row.bio, firstParagraph(db, "person", id, "card"))),
image: imageUrl(site, row.photo, "person") ?? meta.image,
type: "profile",
noindex: row.is_listed !== 1,
};
}
/* A people tag's directory (062_people_tags.sql), /directory/:id. */
function directoryMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM person_tag_types WHERE id = ?`).get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(row.blurb) ?? meta.description,
};
}
function blogMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
const authors = db
.prepare(
`SELECT p.display_name AS name
FROM blog_post_authors a
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id = ? ORDER BY a.sort_order`,
)
.all(id)
.map((a) => a.name);
if (row.guest_author) authors.push(row.guest_author);
const description = plainText(first(row.excerpt, firstParagraph(db, "blog_post", id, "body")));
const image = imageUrl(site, row.cover_image, "blog") ?? meta.image;
return {
...meta,
title: titled(site, row.title),
description,
image,
type: "article",
noindex: row.is_listed !== 1,
jsonLd: {
"@context": "https://schema.org",
"@type": "BlogPosting",
headline: row.title,
description: description ?? undefined,
datePublished: row.published_on ?? undefined,
dateModified: row.updated_at ? row.updated_at.replace(" ", "T") + "Z" : undefined,
author: authors.length ? authors.map((name) => ({ "@type": "Person", name })) : undefined,
image: image ? [image] : undefined,
publisher: { "@type": "Organization", name: site.title, url: `${origin(site)}/` },
mainEntityOfPage: meta.canonical,
},
};
}
/* The profile account pages and their titles (src/pages/SignIn.tsx,
Account.tsx, AccountWelcome.tsx say the same). */
const ACCOUNT_PAGES = { "/sign-in": "Sign in", "/account": "Your profile", "/account/welcome": "Welcome" };
/* The metadata for one request path, for this visitor (the signed-in
user or null, who decides whether a hidden page is there). */
export function metaFor(db, rawPath, user = null) {
const site = siteFor(db);
// Canonical form: no trailing slash (but "/" itself), no query.
const pathname = rawPath.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/";
const meta = { ...defaults(site, db, pathname), nav: navFor(db, user) };
if (pathname === "/") {
// The home page's data, and its first hero photo when the hero is
// a slideshow, requested alongside the app's JavaScript instead of
// after it has run.
const hero = db.prepare(`SELECT hero_backdrop FROM front_page WHERE id = 'home'`).get();
const slide =
hero?.hero_backdrop === "photos"
? db
.prepare(`SELECT media FROM front_page_slides WHERE page_id = 'home' ORDER BY sort_order LIMIT 1`)
.get()
: null;
const slideSrc = slide?.media ? (/^(https?:|\/)/.test(slide.media) ? slide.media : `${UPLOADS}/${slide.media}`) : null;
return {
...meta,
preload: [
{ href: "/api/front-page", as: "fetch" },
...(slideSrc ? [{ href: slideSrc, as: "image" }] : []),
],
jsonLd: {
"@context": "https://schema.org",
"@type": "Organization",
name: site.title,
url: `${origin(site)}/`,
logo: meta.image ?? undefined,
},
};
}
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
// A profile account's pages (076): there for anyone, about no one
// in particular, so never indexed or in the sitemap.
if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
const page = site.pages?.[pathname];
if (page && hiddenFrom(db, user, pathname)) return notFound(meta);
if (page) {
return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description };
}
// An event's schedule presentation (SchedulePresent.tsx): the
// event's own title and preview, kept out of search, pointing
// search engines at the event page.
const present = pathname.match(/^\/events\/([^/]+)\/present$/);
if (present) {
let id;
try {
id = decodeURIComponent(present[1]);
} catch {
return notFound(meta);
}
const event = eventMeta(site, db, id, { ...meta, canonical: `${origin(site)}/events/${present[1]}` });
return event.status === 200 ? { ...event, noindex: true, jsonLd: null } : event;
}
const match = pathname.match(/^\/(events|regions|groups|partners|organizations|teams|awards|people|blog|directory)\/([^/]+)$/);
if (!match) return notFound(meta);
const [, base, rawId] = match;
let id;
try {
id = decodeURIComponent(rawId);
} catch {
return notFound(meta);
}
switch (base) {
case "events":
return eventMeta(site, db, id, meta);
case "regions":
return organizationMeta(site, db, id, "region", meta);
case "groups":
return organizationMeta(site, db, id, "group", meta);
case "partners":
return organizationMeta(site, db, id, "partner", meta);
case "organizations":
return organizationMeta(site, db, id, null, meta);
case "teams":
return teamMeta(site, db, id, meta);
case "awards":
return awardMeta(site, db, id, meta);
case "people":
return personMeta(site, db, id, meta);
case "blog":
return blogMeta(site, db, id, meta);
case "directory":
return directoryMeta(site, db, id, meta);
}
return notFound(meta);
}
/* ── Into the HTML ─────────────────────────────────────────── */
const escapeHtml = (value) =>
String(value)
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
/* The tags the build put in (vite.config.ts's site plugin) that this
replaces, so a page never says two different things. */
const REPLACED = [
/<title>[\s\S]*?<\/title>\s*/i,
/<meta\s+(?:name|property)="(?:description|robots|og:[^"]+|twitter:[^"]+)"[^>]*>\s*/gi,
/<link\s+rel="canonical"[^>]*>\s*/gi,
/<script\s+type="application\/ld\+json"[^>]*>[\s\S]*?<\/script>\s*/gi,
/<link\s+rel="(?:icon|apple-touch-icon)"[^>]*>\s*/gi,
];
/* A value for a <script>: JSON with "<" escaped, so nothing in it
can end the element early. */
const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
/* Plausible, self-hosted and reached through nginx at /pa/ (the
Privacy page describes it). Each deployment counts under its own
address, site.json's url, so dev and live stay apart. Its script
follows the app's page changes itself. */
const PLAUSIBLE = { script: "/pa/js/script.js", api: "/pa/api/event" };
function analyticsTag(site) {
let domain;
try {
domain = new URL(site.url).hostname;
} catch {
return null; // no url, nothing to count under
}
return `<script defer data-domain="${escapeHtml(domain)}" data-api="${PLAUSIBLE.api}" src="${PLAUSIBLE.script}"></script>`;
}
export function renderPage(html, meta) {
const site = meta.site;
let out = html;
for (const pattern of REPLACED) out = out.replace(pattern, "");
const tags = [
`<title>${escapeHtml(meta.title)}</title>`,
meta.description && `<meta name="description" content="${escapeHtml(meta.description)}">`,
meta.noindex && `<meta name="robots" content="noindex">`,
meta.status === 200 && `<link rel="canonical" href="${escapeHtml(meta.canonical)}">`,
`<meta property="og:site_name" content="${escapeHtml(site.title)}">`,
`<meta property="og:type" content="${meta.type}">`,
`<meta property="og:title" content="${escapeHtml(meta.title)}">`,
meta.description && `<meta property="og:description" content="${escapeHtml(meta.description)}">`,
meta.status === 200 && `<meta property="og:url" content="${escapeHtml(meta.canonical)}">`,
meta.image && `<meta property="og:image" content="${escapeHtml(meta.image)}">`,
`<meta name="twitter:card" content="${meta.image ? "summary_large_image" : "summary"}">`,
meta.image && `<meta name="twitter:image" content="${escapeHtml(meta.image)}">`,
// "</" can't appear inside the script, or the browser would
// end the element there.
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
...(meta.preload ?? []).map((p) =>
p.as === "fetch"
? `<link rel="preload" href="${escapeHtml(p.href)}" as="fetch" crossorigin>`
: `<link rel="preload" href="${escapeHtml(p.href)}" as="image" fetchpriority="high">`,
),
// Read by src/lib/site.ts before the app's module runs (a plain
// script in the head runs during parsing; modules wait).
`<script>window.__SITE__ = ${scriptJson(forBrowser(site, meta.nav))}</script>`,
site.themeCss && `<style id="site-colors">${site.themeCss}</style>`,
analyticsTag(site),
].filter(Boolean);
// A blocked site (Site settings indexing off, or site.json's
// robots.index false) stays blocked on every page, whatever the
// record says.
if (site.robots?.index === false && !meta.noindex) {
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
}
// A function, so a $& or $` in record text isn't read as a pattern.
return out.replace(/<\/head>/i, () => ` ${tags.join("\n ")}\n </head>`);
}
/* ── Sitemap ───────────────────────────────────────────────── */
export function sitemap(db) {
const site = siteFor(db);
const base = origin(site);
const day = (value) => (value ? String(value).slice(0, 10) : null);
const hidden = hiddenPaths(db);
const entries = [
{ loc: "/" },
...Object.keys(site.pages ?? {})
.filter((loc) => !hidden.has(loc))
.map((loc) => ({ loc })),
...db
.prepare(`SELECT id, updated_at FROM events WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/events/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(
`SELECT id, kind, updated_at FROM organizations
WHERE is_published = 1 AND is_listed = 1 AND kind <> 'ministry'`,
)
.all()
.map((r) => ({ loc: `${ORG_ROUTES[r.kind] ?? "/organizations"}/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(
`SELECT t.id, t.updated_at FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.is_published = 1 AND t.is_listed = 1`,
)
.all()
.map((r) => ({ loc: `/teams/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(`SELECT id FROM awards WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/awards/${r.id}` })),
...db
.prepare(`SELECT id, updated_at FROM people WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/people/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(`SELECT id, updated_at FROM blog_posts WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/blog/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(`SELECT id FROM person_tag_types`)
.all()
.map((r) => ({ loc: `/directory/${r.id}` })),
];
const xml = entries
.map(
(e) =>
` <url><loc>${escapeHtml(base + e.loc.split("/").map(encodeURIComponent).join("/"))}</loc>` +
(e.lastmod ? `<lastmod>${e.lastmod}</lastmod>` : "") +
`</url>`,
)
.join("\n");
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${xml}\n</urlset>\n`;
}