diff --git a/CLAUDE.md b/CLAUDE.md index 04b725c..f9737d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,6 +32,8 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. +- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.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`. ## Git workflow - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. @@ -55,7 +57,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `api.ts` is the shared caching client used by frontend data hooks. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. -- Logos: org logos in `public/org-logos/` (served at `/org-logos/`), event logos in `public/event-logos/`. The `` component hides itself on load error. +- Images: every record image (logos, photos, backgrounds, block images) is an upload. A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. The `` component hides itself on load error. ## Rules and gotchas - **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. diff --git a/docs/google-sign-in.md b/docs/google-sign-in.md new file mode 100644 index 0000000..3d84ead --- /dev/null +++ b/docs/google-sign-in.md @@ -0,0 +1,75 @@ +# Google sign-in + +The admin login offers "Sign in with Google" for +@nextgenerationofunity.org accounts, alongside email and password. It's +off until the service has an OAuth client ID and secret. + +## Who gets in + +Only accounts that already exist. Create them as before 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 +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 +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). + +## Setting up the OAuth client + +In [Google Cloud Console](https://console.cloud.google.com/), signed in +as a Workspace admin for nextgenerationofunity.org: + +1. **Create or pick a project**, eg. "NGU Website". +2. **APIs & Services → OAuth consent screen** (Google Auth Platform → + Branding / Audience): + - User type / audience: **Internal**. Only accounts in the Workspace + can use it, and Google doesn't need to review the app. + - App name: NGU Admin. Support email: yours. + - Scopes: `openid`, `email`, `profile` (nothing else is needed). +3. **APIs & Services → Credentials → Create credentials → OAuth client + ID** (Google Auth Platform → Clients): + - Application type: **Web application**. Name: NGU admin. + - Authorized redirect URIs: + - `https://nextgenerationofunity.org/api/auth/google/callback` + - for local work, also the dev address, eg. + `http://localhost:5174/api/auth/google/callback` + - No JavaScript origins are needed: the browser never talks to Google + directly. +4. Copy the **Client ID** and **Client secret**. + +## Turning it on + +On the server, add them to the `ngu-api` unit (`systemctl edit ngu-api`) +and restart. Never commit the secret or paste it into the repo: + +```ini +[Service] +Environment=GOOGLE_CLIENT_ID= +Environment=GOOGLE_CLIENT_SECRET= +Environment=GOOGLE_REDIRECT_URI=https://nextgenerationofunity.org/api/auth/google/callback +``` + +`GOOGLE_REDIRECT_URI` must match the redirect URI in step 3 exactly. +Without it the API builds it from `site.json`'s `url`, which the API only +finds if `site.json` is deployed with it and `SITE_CONFIG` points at it +(the deploy copies `server/` into `/srv/ngu-api`, and `site.json` lives +at the repo root, so it isn't there by default). If neither is set, +sign-in fails and the log says so. + +Optional: + +| Variable | Default | +| --- | --- | +| `GOOGLE_REDIRECT_URI` | `/api/auth/google/callback`. Set it for local work, eg. `http://localhost:5174/api/auth/google/callback`, and add the same URI in step 3. | +| `GOOGLE_ALLOWED_DOMAIN` | `nextgenerationofunity.org` | + +The login page asks `/api/auth/providers` whether Google is set up, so +the button appears as soon as the service restarts with both values. +Locally, also set `COOKIE_SECURE=false` when working over plain http. diff --git a/docs/media-uploads.md b/docs/media-uploads.md index d548e27..2352a3e 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -23,6 +23,17 @@ in the `media` table (`server/src/migrations/028_media.sql`). Limits and sizes are constants at the top of `server/src/media.js`. +## Files copied in by hand + +A file put straight into the uploads directory (with `scp`, say) shows +up in the library the next time the Media page or an image picker opens: +the server registers any image it finds there without a record, under +the file's own name, kept as it is (not resized). Anything that isn't a +JPEG, PNG, GIF, WebP or SVG is ignored. A record can name such a file by +its bare filename (eg. `fall-retreat-logo.svg`), which resolves to +`/uploads/`, and the delete check counts those uses too. Keep the +files readable by the `ngu-api` user. + ## Local development The API reads `UPLOADS_DIR` (default `./uploads`, so `server/uploads/`, diff --git a/docs/seo.md b/docs/seo.md new file mode 100644 index 0000000..feaa726 --- /dev/null +++ b/docs/seo.md @@ -0,0 +1,128 @@ +# Search and link previews + +Each page's HTML carries its own title, description, preview image, +canonical address and, where it fits, structured data, so a link shared +on Facebook, iMessage, Slack, Discord or X shows that page, and search +engines see the right title before any JavaScript runs. + +The API does this: nginx sends page requests to it, and it fills the +built `index.html` in for that path (`server/src/routes/pages.js`, rules +in `server/src/pageMeta.js`). It also serves `/sitemap.xml`. + +## Where the words come from + +Everything below can also be set in the admin, under **Panel → Site +settings** (superadmins only): the site's name, description, preview +image, favicon and home-screen icon, each static page's title and intro, +and whether search engines may list the site. A setting there wins; a +blank one falls back to `site.json`. The indexing switch is per +database, so the dev server can be off while production is on, from the +same build. + +| What | Where | +| --- | --- | +| Site name, address, default description | `site.json`: `title`, `url`, `description` (blank uses the front page's subhead) | +| Default preview image | `site.json`: `openGraph.image`, eg. `/uploads/` from Admin → Tools → Media. Blank means pages without their own image have none. | +| Static pages (Retreats, Community, History…) | `site.json`: `pages`. The page's heading and intro read the same entry, so they can't drift. A new static page needs an entry. | +| Records (events, organizations, teams, awards, people, posts) | The database: the record's name, then its tagline or first paragraph; its own image (an event's card background, else its logo; a post's cover; a person's photo; an organization's logo). SVGs aren't used as previews. | +| Whether search may list it | `site.json` `robots.index` for the whole site; per record, published and listed is indexed, published but unlisted is `noindex`, anything else is a 404. `/admin` is always `noindex`. | + +Structured data: Organization on the home page, Event on event pages, +BlogPosting on posts. + +`robots.txt` is written by the build (`vite.config.ts`): with indexing +on it allows everything but `/admin` and `/api` and names the sitemap; +with it off it blocks everything. + +## Production setup + +1. The API needs to find two files. Both default to the repo layout + (`site.json` at the root, the build in `dist/`), which isn't how the + server is deployed: the deploy copies `server/` into `/srv/ngu-api`, + so neither file is next to it. Copy `site.json` there with each + deploy (eg. rsync it to `/srv/ngu-api/site.json`) and set both on the + `ngu-api` unit: + + ```ini + [Service] + Environment=SITE_CONFIG=/srv/ngu-api/site.json + Environment=SITE_INDEX=/path/to/the/built/site/index.html + ``` + + `index.html` is reread when it changes, so a frontend deploy doesn't + need an API restart. + +2. In the nginx site, serve files that exist, send everything else to + the API, and fall back to the plain `index.html` if the API is down, + so the site still loads (with default previews) during a restart: + + ```nginx + # Shared by every block that sends a page to the API. + # (Or repeat these lines in each block, as nginx-dev does.) + # proxy_http_version 1.1; + # proxy_set_header Host $host; + # proxy_set_header X-Real-IP $remote_addr; + # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + # proxy_set_header X-Forwarded-Proto $scheme; + + location = /sitemap.xml { + proxy_pass http://127.0.0.1:3001; + } + + # The home page needs its own block: try_files would otherwise find + # the site's folder and serve index.html without asking the API. + location = / { + proxy_pass http://127.0.0.1:3001; + proxy_intercept_errors on; + error_page 500 502 503 504 = @static; + } + + location / { + try_files $uri @page; + } + + location @page { + proxy_pass http://127.0.0.1:3001; + proxy_intercept_errors on; + error_page 500 502 503 504 = @static; + } + + location @static { + try_files /index.html =404; + } + + # From the API, so Site settings' indexing switch applies; the + # build's own robots.txt if the API is down. + location = /robots.txt { + proxy_pass http://127.0.0.1:3001; + proxy_intercept_errors on; + error_page 500 502 503 504 = @file; + } + + location @file { + try_files $uri =404; + } + + # Uploads are bigger than the /api/ block's 64k limit allows. + location = /api/admin/media { + proxy_pass http://127.0.0.1:3001; + client_max_body_size 26m; + proxy_read_timeout 60s; + } + ``` + + Keep the existing `/api/` and `/uploads/` blocks; they're more + specific and still win. Use the port the API listens on. A 404 + from the API (a record that doesn't exist) goes through as it is; + 500 to 504 fall back to the plain page. + + A dev or test server should also send `X-Robots-Tag: noindex, + nofollow` and its own blocking `robots.txt`, since it shares the + production build's settings: see `nginx-dev` in the repo root. + +3. Check it: `curl -s https://nextgenerationofunity.org/events/ | grep og:title` + should show the event's name, and Facebook's Sharing Debugger or + `https://www.opengraph.xyz` will show the preview. + +4. Tell Google: add the site in Google Search Console and submit + `https://nextgenerationofunity.org/sitemap.xml`. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 8c09e41..bd861f7 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -28,12 +28,13 @@ what a dropdown in the admin editor says. | If it's… | It lives in… | Change it by… | | ------------------------------------------------------------ | ---------------- | ------------------------------------ | | A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin | -| The front page's words, photos, bands, stats and paths | the database | Admin → Front page | -| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Blog | +| The front page's words, photos, bands, stats and paths | the database | Admin → Pages → Front page | +| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Pages → Blog posts, and Community blog section | | The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | | The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | | Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | -| Uploaded images | disk + the `media` table | Admin → Media, or any image field. See `docs/media-uploads.md` | +| A static page's title and intro (also its search title and description), the site's name, description, preview image, icons, search indexing | the database, over `site.json` | Admin → Panel → Site settings (superadmins). Blank uses `site.json`, which also holds the site's address and the pages' defaults. See `docs/seo.md` | +| Uploaded images | disk + the `media` table | Admin → Tools → Media, or any image field. See `docs/media-uploads.md` | The rule of thumb from `CLAUDE.md`: data belongs in the database, presentation belongs in code. A dropdown's *values* are data the @@ -175,16 +176,16 @@ also in `admin-schema.js` and a CHECK): | Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` | | Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. | | Content blocks → Shown in (slot) | card, body | **yes** | `paragraphs()` in `server/src/shape.js` (card), `ContentBlocks.tsx` (body) | -| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema.ts`). | +| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema.ts`). | | Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` | | Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` | | Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping | | Front page → Countdown → Only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/routes/home.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. | | Front page → Background | brand, photos | **yes** | `HeroStage.tsx` | -| Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | +| Front page → Feature | none, livestream, video, event | **yes** | `HeroStage.tsx`; the event is picked in `server/src/routes/home.js` | | Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect, featured | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | | Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | -| Front page → Featured cards → Card type (Blog → Community section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | +| Front page → Featured cards → Card type (Community blog section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | | Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` | | Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a | @@ -200,11 +201,11 @@ code): | Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) | | Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name | | Event hosts / event people / team members / timeline people → Person | `people` | people | -| Blog → Community section → Pinned posts → Post | `blog_posts` | blog posts, newest first | +| Community blog section → Pinned posts → Post | `blog_posts` | blog posts, newest first | | Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it | | Affiliations → Team | `teams` | teams, filtered to the chosen organization | | Person awards → Award | `awards` | awards, labelled "Award (Organization)" | -| Person awards → Presented at; Front page → Count down to | `events` | events | +| Person awards → Presented at; Front page → Count down to; Front page → Featured event | `events` | events | | Timeline → Record | `timeline_refs` | all five kinds, filtered by "Points at" | --- @@ -216,7 +217,7 @@ each is changed in a different place: | What you see | Where it's set | | --- | --- | -| **The heading on the page** ("National Retreats", "What's on") | **Admin → Front page → Page sections → Heading.** Blank uses the default below. | +| **The heading on the page** ("National Retreats", "What's on") | **Admin → Pages → Front page → Page sections → Heading.** Blank uses the default below. | | The default heading when that field is blank | `SECTIONS` in `src/pages/Home.tsx`, the `title` of each entry | | **The name in the admin's Section dropdown** ("Events Carousel (National Retreats)") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema.ts` | | The subnav links under the header ("#Retreats", "#Calendar") | `PAGE_SECTIONS["/"]` in `src/navConfig.ts` | @@ -271,7 +272,7 @@ The numbers band's "Number Source" dropdown works the same way: | Section titles, blurbs and colours on Retreats, Community, Leadership, Resources, Feedback, Privacy, Terms | the page file in `src/pages/` | the `SECTIONS` array at the top. A section's `id` must match its subnav `hash`. | | Site-wide announcement banner | `src/data/bannerConfig.ts` | `enabled: false` hides it. Bump `id` when the message changes, so people who dismissed the old one see the new one. | | History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. | -| Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Organizations → a region → Map areas). | +| Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). | | Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. | | Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | | Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | diff --git a/server/src/admin-cli.js b/server/src/admin-cli.js index b294a69..7c907f3 100644 --- a/server/src/admin-cli.js +++ b/server/src/admin-cli.js @@ -209,6 +209,7 @@ function list(db) { const rows = db .prepare( `SELECT u.email, u.name, u.role, u.is_active, u.last_login_at, + u.google_sub IS NOT NULL AS google, (SELECT COUNT(*) FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions FROM admin_users u @@ -228,7 +229,8 @@ function list(db) { const state = r.is_active ? r.role : `${r.role} (disabled)`; const seen = r.last_login_at ?? "never"; console.log( - `${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)`, + `${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)` + + (r.google ? " google linked" : ""), ); } } diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index fafa531..9e85beb 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -179,6 +179,7 @@ const blocksChild = (ownerKind) => ({ "video", "button", "callout", + "schedule", ], { required: true }, ), @@ -198,6 +199,14 @@ const blocksChild = (ownerKind) => ({ text("text", { required: true }), text("detail"), text("url"), + // Schedule entries only (034_schedule_block.sql). + text("day"), + text("time"), + text("location"), + text("person_id"), + text("description"), + text("media"), + text("map"), ], }, ], @@ -710,7 +719,8 @@ const frontPage = { columns: [ enumeration("hero_backdrop", ["brand", "photos"]), - enumeration("hero_feature", ["none", "livestream", "video"]), + enumeration("hero_feature", ["none", "livestream", "video", "event"]), + text("hero_event_id"), text("eyebrow"), text("headline"), text("subhead"), @@ -894,6 +904,47 @@ const communityPage = { ], }; +/* ── Site settings (035_site_settings.sql) ────────────────────── + A singleton of overrides for what site.json says: name, + description, preview image, icons, search indexing, and static + pages' titles and intros. Superadmins only. pageMeta.js merges it + over site.json. */ +const siteSettings = { + key: "site_settings", + table: "site_settings", + idColumn: "id", + idKind: "slug", + singleton: "site", + concurrency: "updated_at", + writeRole: "superadmin", + + list: { + columns: ["id", "site_name", "updated_at"], + filters: [], + search: [], + order: "id", + }, + + columns: [ + text("site_name"), + text("description"), + text("preview_image"), + text("favicon"), + text("apple_touch_icon"), + enumeration("indexing", ["on", "off"]), + ], + + children: [ + { + key: "pages", + table: "site_setting_pages", + owner: { column: "settings_id" }, + order: "sort_order", + columns: [text("path", { required: true }), text("title"), text("description")], + }, + ], +}; + export const ENTITIES = { organizations, events, @@ -904,6 +955,7 @@ export const ENTITIES = { front_page: frontPage, blog_posts: blogPosts, community_page: communityPage, + site_settings: siteSettings, }; /* ── Options for the form's select inputs ────────────────────── */ diff --git a/server/src/auth.js b/server/src/auth.js index 9a8a181..ca7d977 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -31,7 +31,7 @@ const SESSION_DAYS = 30; const REFRESH_WITHIN_DAYS = 7; // Off only for plain-http local work. Production is behind TLS. -const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; +export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex"); @@ -201,6 +201,11 @@ export async function requireAuth(c, next) { export const ROLES = ["viewer", "editor", "admin", "superadmin"]; const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 }; +/* Whether a user is at least this rank. A ladder, never equality. */ +export function hasRole(user, role) { + return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity); +} + export function requireRole(...roles) { const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity)); return async (c, next) => { diff --git a/server/src/googleAuth.js b/server/src/googleAuth.js new file mode 100644 index 0000000..6baaedb --- /dev/null +++ b/server/src/googleAuth.js @@ -0,0 +1,153 @@ +/* ═══════════════════════════════════════════════════════════════ + GOOGLE SIGN-IN + + The OAuth 2.0 authorization-code flow with PKCE, done on the + server, for @nextgenerationofunity.org accounts. The routes are + in routes/auth.js; this is the part that talks to Google and + decides whether an answer is good enough. + + Configured by the service environment: + + GOOGLE_CLIENT_ID from Google Cloud Console + GOOGLE_CLIENT_SECRET the same; never in the repo + GOOGLE_REDIRECT_URI default /api/auth/google/callback; + set it when the server is deployed + without site.json (SITE_CONFIG) + GOOGLE_ALLOWED_DOMAIN default nextgenerationofunity.org + + With no client id or secret it's off: the login page doesn't + offer it and the routes answer 404. Setup: docs/google-sign-in.md. + + ── Why the ID token isn't signature-checked ── + The token comes straight from Google's token endpoint, over TLS, + in answer to a request this server made with its own secret. + Google's documentation says a token received that way can be + trusted without verifying its signature. Everything else is + checked: issuer, audience (our client id), expiry, a verified + email, and the Workspace domain in the `hd` claim, which only + Google sets, not just the email's suffix. + + Nothing here creates an account. A Google login is only let in + if admin-cli has already made one for that email (see auth.js + routes), and is linked to it on first use. + ═══════════════════════════════════════════════════════════════ */ + +import { createHash, randomBytes } from "node:crypto"; + +import { loadSite } from "./pageMeta.js"; + +const AUTHORIZE = "https://accounts.google.com/o/oauth2/v2/auth"; +const TOKEN = "https://oauth2.googleapis.com/token"; +const ISSUERS = new Set(["accounts.google.com", "https://accounts.google.com"]); + +const base64url = (buf) => buf.toString("base64url"); + +export function googleConfig() { + const clientId = process.env.GOOGLE_CLIENT_ID; + const clientSecret = process.env.GOOGLE_CLIENT_SECRET; + if (!clientId || !clientSecret) return null; + + // Whether Google is on depends only on the id and secret. The + // return address can come from site.json, which a deploy of the + // server alone may not have; that's reported where it's needed + // (the sign-in routes), rather than hiding the button. + let redirectUri = process.env.GOOGLE_REDIRECT_URI ?? null; + if (!redirectUri) { + try { + const origin = (loadSite().url ?? "").replace(/\/$/, ""); + if (origin) redirectUri = `${origin}/api/auth/google/callback`; + } catch { + redirectUri = null; + } + } + + return { + clientId, + clientSecret, + redirectUri, + domain: (process.env.GOOGLE_ALLOWED_DOMAIN ?? "nextgenerationofunity.org").toLowerCase(), + }; +} + +/* The first leg: where to send the browser, and the state and PKCE + verifier to keep (in a short-lived cookie) until it comes back. */ +export function startLogin(config) { + const state = base64url(randomBytes(24)); + const verifier = base64url(randomBytes(48)); + const challenge = base64url(createHash("sha256").update(verifier).digest()); + + const url = new URL(AUTHORIZE); + url.search = new URLSearchParams({ + client_id: config.clientId, + redirect_uri: config.redirectUri, + response_type: "code", + scope: "openid email profile", + state, + code_challenge: challenge, + code_challenge_method: "S256", + // Only a hint to Google's account chooser; the hd claim is what's + // actually checked on the way back. + hd: config.domain, + prompt: "select_account", + }); + + return { url: url.toString(), state, verifier }; +} + +export class GoogleLoginError extends Error { + constructor(code, message) { + super(message); + this.code = code; // shown to the login page as ?error= + } +} + +/* The second leg: trade the code for tokens and check the identity. + Returns { sub, email, name } or throws GoogleLoginError. */ +export async function finishLogin(config, code, verifier) { + let res; + try { + res = await fetch(TOKEN, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + code, + client_id: config.clientId, + client_secret: config.clientSecret, + redirect_uri: config.redirectUri, + grant_type: "authorization_code", + code_verifier: verifier, + }), + signal: AbortSignal.timeout(10_000), + }); + } catch { + throw new GoogleLoginError("google_unreachable", "Couldn't reach Google."); + } + + const body = await res.json().catch(() => ({})); + if (!res.ok || !body.id_token) { + console.warn(`google token exchange failed: ${res.status} ${body.error ?? ""}`); + throw new GoogleLoginError("google_failed", "Google didn't accept the sign-in."); + } + + let claims; + try { + claims = JSON.parse(Buffer.from(body.id_token.split(".")[1], "base64url").toString("utf8")); + } catch { + throw new GoogleLoginError("google_failed", "Google's answer couldn't be read."); + } + + const now = Math.floor(Date.now() / 1000); + if (!ISSUERS.has(claims.iss) || claims.aud !== config.clientId || !(claims.exp > now)) { + throw new GoogleLoginError("google_failed", "Google's answer didn't check out."); + } + + const email = String(claims.email ?? "").toLowerCase(); + if (!claims.email_verified || !email) { + throw new GoogleLoginError("unverified", "That Google account's email isn't verified."); + } + if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) { + throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`); + } + + return { sub: String(claims.sub), email, name: claims.name ?? null }; +} diff --git a/server/src/index.js b/server/src/index.js index aa8248f..0c9a45f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -23,6 +23,7 @@ import history from "./routes/history.js"; import home from "./routes/home.js"; import directory from "./routes/directory.js"; import blog from "./routes/blog.js"; +import pages from "./routes/pages.js"; import feedback from "./routes/feedback.js"; import auth from "./routes/auth.js"; import admin from "./routes/admin.js"; @@ -75,6 +76,9 @@ app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); app.route("/api/feedback", feedback); app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 })); +// Looser than a password guess: each Google sign-in is two requests, +// and Google has already checked the person by the second. +app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 })); app.route("/api/admin/panel", panel); app.route("/api/auth", auth); app.route("/api/admin", admin); @@ -102,6 +106,10 @@ app.use( }), ); +// Last: every other GET that isn't /api is a page of the site, sent +// with its metadata filled in (routes/pages.js). +app.route("/", pages); + startSessionSweeper(db); app.notFound((c) => c.json({ error: "Not found" }, 404)); diff --git a/server/src/media.js b/server/src/media.js index c4a5b91..7427770 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -29,10 +29,19 @@ Names are random, so two uploads of "logo.png" can't collide and a filename says nothing about what's in it. + + ── Files copied in by hand ── + A file put straight into UPLOADS_DIR has no media row, so the + library wouldn't know it. registerLooseFiles() gives each image + it finds one, under the file's own name, unprocessed, uploaded by + nobody. The Media routes call it when the library is listed. Only + images are registered (by their bytes, as for an upload); anything + else, dotfiles and the temporary names store() writes through + are left alone. ═══════════════════════════════════════════════════════════════ */ import { randomBytes } from "node:crypto"; -import { mkdir, rename, unlink, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; import sharp from "sharp"; @@ -182,3 +191,82 @@ export async function remove(filename) { if (err.code !== "ENOENT") throw err; } } + +/* ── Files copied in by hand ─────────────────────────────────── */ + +/* What a file already on disk is: the fields a media row needs, or + null when it isn't an image this library takes. */ +async function describe(filename) { + const full = path.join(UPLOADS_DIR, filename); + const info = await stat(full); + if (!info.isFile() || info.size === 0 || info.size > MAX_UPLOAD_BYTES) return null; + + const buf = await readFile(full); + const kind = sniff(buf); + if (!kind) return null; + + let width = null; + let height = null; + if (kind !== "svg") { + try { + const meta = await sharp(buf).metadata(); + width = meta.width ?? null; + height = meta.pageHeight ?? meta.height ?? null; + } catch { + return null; // looks like an image, won't open as one + } + } + + return { + filename, + content_type: TYPES[kind].mime, + bytes: info.size, + width, + height, + processed: 0, + }; +} + +/* Gives every image in UPLOADS_DIR without a media row one. Returns + how many it added. Safe to run often: it only reads the folder + and the table, and inserts nothing twice (filename is UNIQUE). */ +export async function registerLooseFiles(db) { + let names; + try { + names = await readdir(UPLOADS_DIR); + } catch (err) { + if (err.code === "ENOENT") return 0; + throw err; + } + + const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename)); + const insert = db.prepare( + `INSERT OR IGNORE INTO media + (filename, original_name, content_type, bytes, width, height, processed, uploaded_by) + VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`, + ); + + let added = 0; + for (const name of names) { + if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue; + let row; + try { + row = await describe(name); + } catch { + continue; + } + if (!row) continue; + const result = insert.run( + row.filename, + row.filename, + row.content_type, + row.bytes, + row.width, + row.height, + row.processed, + ); + added += result.changes; + } + if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`); + return added; +} diff --git a/server/src/migrations/033_hero_event.sql b/server/src/migrations/033_hero_event.sql new file mode 100644 index 0000000..ae50122 --- /dev/null +++ b/server/src/migrations/033_hero_event.sql @@ -0,0 +1,34 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 033 HERO: A FEATURED EVENT +-- +-- A fourth hero feature, 'event': an event's card beside the +-- headline, over whichever backdrop is chosen. +-- +-- hero_event_id the event to feature. Null means the event the +-- countdown shows (its pin, or the next one that +-- hasn't ended, narrowed by its scope and type), +-- so the hero and the countdown can't disagree. +-- A pinned event that is over, unpublished or +-- deleted falls back the same way; ON DELETE SET +-- NULL does the last one. +-- +-- hero_feature's CHECK gains 'event'. A CHECK can't be altered in +-- place, so the column is replaced the way 025 did it: a new column +-- with the new CHECK, the values copied across, the old one dropped +-- and the new one renamed into its place. Nothing else names the +-- column, so front_page itself needn't be rebuilt. +-- +-- PRAGMA user_version; -- reads 32 before this file +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE front_page ADD COLUMN hero_feature_new TEXT NOT NULL DEFAULT 'none' + CHECK (hero_feature_new IN ('none', 'livestream', 'video', 'event')); + +UPDATE front_page SET hero_feature_new = hero_feature; + +ALTER TABLE front_page DROP COLUMN hero_feature; + +ALTER TABLE front_page RENAME COLUMN hero_feature_new TO hero_feature; + +ALTER TABLE front_page ADD COLUMN hero_event_id TEXT + REFERENCES events (id) ON DELETE SET NULL; diff --git a/server/src/migrations/034_schedule_block.sql b/server/src/migrations/034_schedule_block.sql new file mode 100644 index 0000000..0655c1a --- /dev/null +++ b/server/src/migrations/034_schedule_block.sql @@ -0,0 +1,99 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 034 CONTENT BLOCKS: SCHEDULE +-- +-- A 'schedule' block: the block's items are its entries, grouped +-- into one tab per day. Each entry says when, what and where, and +-- folds out for more. The block's own text is an optional intro. +-- +-- content_block_items gains the entry's fields. A list or link-row +-- block leaves them empty: +-- +-- day the tab it sits under, eg. 'Friday'. Tabs follow +-- the order entries are in; blank means one untitled +-- day, and a schedule of one day draws no tabs +-- time '7:00pm', '9:00 to 10:30am': shown as typed +-- location where it happens, eg. 'Main Hall' +-- person_id who hosts or speaks: a people row, drawn with its +-- photo and linked to its page. ON DELETE SET NULL, +-- and an unpublished person isn't shown +-- description the fold-out text, formatted like a paragraph +-- media a graphic in the fold-out: '/uploads/…' or a URL +-- map a place or address to show on a Google map in the +-- fold-out, eg. 'Camp Hebron, Halifax PA' +-- +-- text is the entry's title, detail a line under it, url a link on +-- the title, as for list items. +-- +-- The type list is a CHECK, so content_blocks is rebuilt the way +-- 031 and 032 did it (legacy_alter_table around the rename, then +-- the index and the owner trigger again). The item columns are +-- plain ADD COLUMNs. +-- +-- PRAGMA user_version; -- reads 33 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE content_blocks_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_kind TEXT NOT NULL + CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')), + owner_id TEXT NOT NULL, + slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')), + sort_order INTEGER NOT NULL DEFAULT 0, + + type TEXT NOT NULL + CHECK (type IN ('heading', 'subheading', 'paragraph', + 'list', 'links', 'quote', 'image', 'divider', + 'video', 'button', 'callout', 'schedule')), + text TEXT, + media TEXT, + href TEXT, + alt TEXT, + cite TEXT +) STRICT; + +INSERT INTO content_blocks_new + (id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite) +SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite + FROM content_blocks; + +PRAGMA legacy_alter_table = ON; +DROP TABLE content_blocks; +ALTER TABLE content_blocks_new RENAME TO content_blocks; +PRAGMA legacy_alter_table = OFF; + +CREATE INDEX content_blocks_owner_idx + ON content_blocks (owner_kind, owner_id, slot, sort_order); + +ALTER TABLE content_block_items ADD COLUMN day TEXT; +ALTER TABLE content_block_items ADD COLUMN time TEXT; +ALTER TABLE content_block_items ADD COLUMN location TEXT; +ALTER TABLE content_block_items ADD COLUMN person_id TEXT + REFERENCES people (id) ON DELETE SET NULL; +ALTER TABLE content_block_items ADD COLUMN description TEXT; +ALTER TABLE content_block_items ADD COLUMN media TEXT; +ALTER TABLE content_block_items ADD COLUMN map TEXT; + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER content_blocks_owner_exists +BEFORE INSERT ON content_blocks +BEGIN + SELECT CASE + WHEN new.owner_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such event') + WHEN new.owner_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such organization') + WHEN new.owner_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such person') + WHEN new.owner_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such team') + WHEN new.owner_kind = 'blog_post' + AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such blog post') + END; +END; diff --git a/server/src/migrations/035_site_settings.sql b/server/src/migrations/035_site_settings.sql new file mode 100644 index 0000000..e2a38c0 --- /dev/null +++ b/server/src/migrations/035_site_settings.sql @@ -0,0 +1,62 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 035 SITE SETTINGS +-- +-- What the site says about itself, editable in the admin (Panel → +-- Site settings, superadmins only) instead of only in site.json. +-- Every column is an override: null means "whatever site.json +-- says", so a fresh database behaves exactly as before and the +-- built index.html (made from site.json) stays a true fallback for +-- when the API is down. +-- +-- site_name the site's name, in every title +-- description the default search description +-- preview_image the default link-preview image +-- favicon the browser-tab icon ('/uploads/…', PNG or SVG) +-- apple_touch_icon the home-screen icon on iPhones (PNG, 180px) +-- indexing 'on' or 'off': whether search engines may list +-- the site. Per database, so the dev server can +-- say off while production says on, from one +-- build. Null follows site.json's robots.index. +-- +-- site_setting_pages overrides a static page's title and intro +-- (site.json's "pages"), one row per page that differs. The path +-- must be one of site.json's pages; the admin only offers those. +-- +-- A singleton like front_page: one row, made here, which the admin +-- edits and can't delete. +-- +-- PRAGMA user_version; -- reads 34 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE site_settings ( + id TEXT PRIMARY KEY CHECK (id = 'site'), + site_name TEXT, + description TEXT, + preview_image TEXT, + favicon TEXT, + apple_touch_icon TEXT, + indexing TEXT CHECK (indexing IN ('on', 'off')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +INSERT INTO site_settings (id) VALUES ('site'); + +CREATE TABLE site_setting_pages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + path TEXT NOT NULL, -- '/retreats' + title TEXT, + description TEXT, + UNIQUE (settings_id, path) +) STRICT; + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER site_settings_touch +AFTER UPDATE ON site_settings +FOR EACH ROW WHEN new.updated_at = old.updated_at +BEGIN + UPDATE site_settings SET updated_at = datetime('now') WHERE id = new.id; +END; diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js new file mode 100644 index 0000000..ae7bd08 --- /dev/null +++ b/server/src/pageMeta.js @@ -0,0 +1,506 @@ +/* ═══════════════════════════════════════════════════════════════ + 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), 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.__NGU_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 + /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"; + +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 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_setting_pages WHERE settings_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, + }, + pages, + }; +} + +/* What the browser app reads for headings and titles. */ +const forBrowser = (site) => ({ title: site.title, pages: site.pages }); + +/* 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; + const flat = String(text) + .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", chapter: "/chapters", 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.card_image, "eventBackground") ?? + 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. + if (!row || (kind && row.kind !== kind)) 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 people 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, + }; +} + +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 people 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 metadata for one request path. */ +export function metaFor(db, rawPath) { + 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); + + if (pathname === "/") { + return { + ...meta, + 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 }; + + const page = site.pages?.[pathname]; + if (page) { + return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description }; + } + + const match = pathname.match(/^\/(events|regions|chapters|partners|organizations|teams|awards|people|blog)\/([^/]+)$/); + 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 "chapters": + return organizationMeta(site, db, id, "chapter", 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); + } + return notFound(meta); +} + +/* ── Into the HTML ─────────────────────────────────────────── */ + +const escapeHtml = (value) => + String(value) + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(//g, ">"); + +/* 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 = [ + /[\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"); + +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)}`, + meta.description && ``, + meta.noindex && ``, + meta.status === 200 && ``, + ``, + ``, + ``, + meta.description && ``, + meta.status === 200 && ``, + meta.image && ``, + ``, + meta.image && ``, + // "`, + site.icons?.apple && ``, + meta.jsonLd && ``, + // Read by src/lib/site.ts before the app's module runs (a plain + // script in the head runs during parsing; modules wait). + ``, + ].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, ``); + } + + return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n `); +} + +/* ── Sitemap ───────────────────────────────────────────────── */ + +export function sitemap(db) { + const site = siteFor(db); + const base = origin(site); + const day = (value) => (value ? String(value).slice(0, 10) : null); + + const entries = [ + { loc: "/" }, + ...Object.keys(site.pages ?? {}).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`) + .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) })), + ]; + + const xml = entries + .map( + (e) => + ` ${escapeHtml(base + e.loc.split("/").map(encodeURIComponent).join("/"))}` + + (e.lastmod ? `${e.lastmod}` : "") + + ``, + ) + .join("\n"); + + return `\n\n${xml}\n\n`; +} diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js index 9b700aa..f50c64b 100644 --- a/server/src/routes/admin-entities.js +++ b/server/src/routes/admin-entities.js @@ -18,7 +18,7 @@ import { Hono } from "hono"; -import { requireAuth, requireRole } from "../auth.js"; +import { hasRole, requireAuth, requireRole } from "../auth.js"; import { ENTITIES, OPTION_QUERIES } from "../admin-schema.js"; import { HttpError, @@ -41,6 +41,17 @@ function entityOr404(c) { return entity; } +/* Saving needs editor, unless the descriptor asks for more + (writeRole): site settings are superadmin-only. requireRole on the + route is the floor; this is the entity's own bar on top. */ +function entityForWrite(c) { + const entity = entityOr404(c); + if (entity.writeRole && !hasRole(c.get("user"), entity.writeRole)) { + throw new HttpError(403, "Not allowed."); + } + return entity; +} + /* Everything the select inputs need, in one request. Small enough that paging it would cost more than it saves. */ entities.get("/options", (c) => { @@ -64,14 +75,14 @@ entities.get("/:entity/:id", (c) => { }); entities.post("/:entity", requireRole("editor"), async (c) => { - const entity = entityOr404(c); + const entity = entityForWrite(c); const row = createRow(c.get("db"), entity, await json(c)); console.log(`${entity.key} ${row[entity.idColumn]} created by ${c.get("user").email}`); return c.json({ row }, 201, NO_STORE); }); entities.patch("/:entity/:id", requireRole("editor"), async (c) => { - const entity = entityOr404(c); + const entity = entityForWrite(c); const id = c.req.param("id"); const row = updateRow(c.get("db"), entity, id, await json(c)); console.log(`${entity.key} ${id} updated by ${c.get("user").email}`); diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index b84eba8..179452a 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -4,6 +4,10 @@ POST /api/auth/login email + password → session cookie POST /api/auth/logout deletes the session row and cookie GET /api/auth/me who am I, or 401 + GET /api/auth/providers which ways in are switched on + GET /api/auth/google off to Google's account chooser + GET /api/auth/google/callback back from it: sign in, or + back to the login page with ?error= Three deliberate choices: @@ -14,18 +18,27 @@ 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. + 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. ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; +import { deleteCookie, getCookie, setCookie } from "hono/cookie"; + import { + SECURE_COOKIE, createSession, destroySession, currentUser, hashPassword, verifyPassword, } from "../auth.js"; +import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js"; const auth = new Hono(); @@ -96,4 +109,111 @@ auth.get("/me", (c) => { return c.json({ user }, 200, NO_STORE); }); + +/* ── Google ──────────────────────────────────────────────────── */ + +// The state and PKCE verifier between the two legs. Scoped to the +// Google routes and gone in ten minutes; Lax so it comes back on +// the redirect from Google, which is a top-level navigation. +const OAUTH_COOKIE = "ngu_oauth"; +const OAUTH_COOKIE_OPTIONS = { + httpOnly: true, + secure: SECURE_COOKIE, + sameSite: "Lax", + path: "/api/auth/google", +}; + +// Where to land afterwards: an admin page, never anywhere else. +const safeNext = (value) => + typeof value === "string" && /^\/admin(\/[\w\-/]*)?$/.test(value) ? value : "/admin/home"; + +const backToLogin = (c, code) => c.redirect(`/admin/login?error=${encodeURIComponent(code)}`, 302); + +auth.get("/providers", (c) => + c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE), +); + +auth.get("/google", (c) => { + const config = googleConfig(); + if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404); + if (!config.redirectUri) { + // Said in the log, where whoever runs the box will look; the + // person at the login page just learns it didn't work. + console.error( + "google login: no return address. Set GOOGLE_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.", + ); + return backToLogin(c, "google_failed"); + } + + const { url, state, verifier } = startLogin(config); + setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), { + ...OAUTH_COOKIE_OPTIONS, + maxAge: 600, + }); + return c.redirect(url, 302); +}); + +auth.get("/google/callback", async (c) => { + const config = googleConfig(); + if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404); + + let saved = null; + try { + saved = JSON.parse(getCookie(c, OAUTH_COOKIE) ?? "null"); + } catch { + saved = null; + } + deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS); + + // Pressing Cancel on Google's screen comes back as ?error=. + if (c.req.query("error")) return backToLogin(c, "cancelled"); + + const code = c.req.query("code"); + if (!saved?.state || !code || c.req.query("state") !== saved.state) { + return backToLogin(c, "expired"); + } + + let identity; + try { + identity = await finishLogin(config, code, saved.verifier); + } catch (err) { + if (err instanceof GoogleLoginError) { + console.warn(`google login refused: ${err.code}`); + return backToLogin(c, err.code); + } + throw err; + } + + const db = c.get("db"); + const columns = `id, email, name, role, is_active, google_sub`; + let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub); + + 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) { + console.warn(`google login: ${identity.email} is linked to another Google account`); + return backToLogin(c, "linked_elsewhere"); + } + // 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; + } + + if (user.is_active !== 1) return backToLogin(c, "disabled"); + + createSession(db, c, user.id); + db.prepare( + `UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`, + ).run(identity.name, user.id); + console.log(`login ${user.email} (google)`); + + return c.redirect(saved.next ?? "/admin/home", 302); +}); + export default auth; diff --git a/server/src/routes/home.js b/server/src/routes/home.js index d09a465..bd5824d 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -34,6 +34,12 @@ means any. They don't apply to a pinned event: the admin chose that one by name. + ── Hero event ── + With the 'event' feature, the hero draws the pinned hero_event_id + if it's still published and not over, else the countdown's event + (above), so the two never disagree. Its action links ride along + for the card's buttons. + ── Featured ── The featured band's cards, record cards filled in from their records (loadFeaturedCards in shape.js, which the Community @@ -42,7 +48,7 @@ import { Hono } from "hono"; -import { asBool, loadFeaturedCards, shapeSeries } from "../shape.js"; +import { asBool, loadFeaturedCards, loadLinks, shapeSeries, splitLinks } from "../shape.js"; const home = new Hono(); @@ -84,6 +90,20 @@ function statValue(db, row) { return sql ? String(db.prepare(sql).get().n) : null; } +/* The countdown's fields plus what the hero's event card also draws: + its tagline, place, card background and buttons. */ +function shapeHeroEvent(db, row) { + if (!row) return null; + const { actions } = splitLinks(loadLinks(db, "event", [row.id]).get(row.id) ?? []); + return { + ...shapeCountdown(row), + tagline: row.tagline, + card_image: row.card_image, + org_logo: row.effective_org_logo, + links: actions, + }; +} + function shapeCountdown(row) { if (!row) return null; return { @@ -179,6 +199,15 @@ home.get("/front-page", (c) => { ) .get(...params); + const heroEvent = + page.hero_feature === "event" + ? (page.hero_event_id + ? db + .prepare(`SELECT * FROM v_events WHERE id = ? AND ${notOver}`) + .get(page.hero_event_id) + : null) ?? next + : null; + return json(c, { front_page: { hero: { @@ -201,6 +230,7 @@ home.get("/front-page", (c) => { video: page.video_url ? { url: page.video_url, title: page.video_title } : null, + event: shapeHeroEvent(db, heroEvent), }, sections, stats, diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 285ee8d..58ee209 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -1,7 +1,11 @@ /* ═══════════════════════════════════════════════════════════════ MEDIA ROUTES: mounted under /api/admin - GET /media the library, newest first, ?q=name + GET /media the library, newest first, ?q=name. + Picks up images copied into the + uploads folder by hand first + (registerLooseFiles, at most every + SCAN_EVERY_MS) POST /media upload one image (multipart: file, keep_original) GET /media/:id/uses which records name this file @@ -23,7 +27,14 @@ import { Hono } from "hono"; import { bodyLimit } from "hono/body-limit"; import { requireAuth, requireRole } from "../auth.js"; -import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js"; +import { + MAX_UPLOAD_BYTES, + MediaError, + PUBLIC_PREFIX, + registerLooseFiles, + remove, + store, +} from "../media.js"; import { fetchImage, previewLink } from "../linkPreview.js"; const media = new Hono(); @@ -34,13 +45,20 @@ const NO_STORE = { "Cache-Control": "no-store" }; const MAX_LIST = 500; +/* How often listing the library looks in the uploads folder for + files copied there by hand. */ +const SCAN_EVERY_MS = 30_000; +let lastScan = 0; + /* Tables that can't hold an image path, or mustn't be searched. */ const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]); function shape(row) { return { id: row.id, - url: `${PUBLIC_PREFIX}${row.filename}`, + // A hand-copied file keeps its own name, which may need escaping + // in a URL (a space, say); uploads' random names never do. + url: `${PUBLIC_PREFIX}${encodeURIComponent(row.filename)}`, original_name: row.original_name, content_type: row.content_type, bytes: row.bytes, @@ -84,7 +102,12 @@ async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) { } } -media.get("/media", (c) => { +media.get("/media", async (c) => { + if (Date.now() - lastScan > SCAN_EVERY_MS) { + lastScan = Date.now(); + await registerLooseFiles(c.get("db")); + } + const q = (c.req.query("q") ?? "").trim().slice(0, 100); const rows = c .get("db") @@ -168,10 +191,20 @@ media.post("/link-preview", requireRole("editor"), async (c) => { ); }); -/* Every TEXT column of every content table, searched for the exact - path. Read from the live schema rather than a list of image +/* Every TEXT column of every content table, searched for any of the + exact values a record can use to name the file: its /uploads/ + path, that path escaped, or (for a file copied in by hand and + typed into a field) its bare name, which media.ts resolves to the + same place. Read from the live schema rather than a list of image columns, so a new image field is covered the day it's added. */ -function usesOf(db, url) { +function usesOf(db, filename) { + const values = [ + ...new Set([ + `${PUBLIC_PREFIX}${filename}`, + `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, + filename, + ]), + ]; const tables = db .prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) .all() @@ -188,10 +221,11 @@ function usesOf(db, url) { if (columns.length === 0) continue; // Names come from the schema, not the request; quoted anyway. - const where = columns.map((col) => `"${col}" = ?`).join(" OR "); + const marks = values.map(() => "?").join(", "); + const where = columns.map((col) => `"${col}" IN (${marks})`).join(" OR "); const { n } = db .prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`) - .get(...columns.map(() => url)); + .get(...columns.flatMap(() => values)); if (n > 0) uses.push({ table, count: n }); } return uses; @@ -208,7 +242,7 @@ function findOr404(c) { media.get("/media/:id/uses", (c) => { const row = findOr404(c); - return c.json({ uses: usesOf(c.get("db"), `${PUBLIC_PREFIX}${row.filename}`) }, 200, NO_STORE); + return c.json({ uses: usesOf(c.get("db"), row.filename) }, 200, NO_STORE); }); media.delete("/media/:id", requireRole("admin"), async (c) => { diff --git a/server/src/routes/pages.js b/server/src/routes/pages.js new file mode 100644 index 0000000..11a9323 --- /dev/null +++ b/server/src/routes/pages.js @@ -0,0 +1,129 @@ +/* ═══════════════════════════════════════════════════════════════ + PAGE ROUTES: the site's HTML, with each page's metadata + + GET /sitemap.xml every public, listed page + GET /robots.txt this database's indexing setting (Site + settings, else site.json), so a dev server + can say no while production says yes + GET /anything the built index.html, its title, description, + preview image, canonical link and structured + data filled in for that path (pageMeta.js) + + In production nginx serves files that exist (the JS, CSS, + uploads) itself and sends everything else here, so a shared link + carries the right preview; see docs/seo.md for the block. The app + in the page then takes over as usual. In development Vite serves + index.html itself and this is never reached. + + SITE_INDEX is the built index.html (default: dist/ at the repo + root). It's reread when the file changes, so a deploy needs no + restart for the page to update. A record that doesn't exist gets + the app's own not-found page with a 404 status, so search engines + drop it. + + If the metadata can't be built (no site.json at SITE_CONFIG, say), + the page is still served, as built, and the cause is logged once: + a preview is never worth a page that won't load. + + Mounted last, after every /api and /uploads route; an unknown + /api path is still the API's JSON 404. + ═══════════════════════════════════════════════════════════════ */ + +import { readFileSync, statSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { Hono } from "hono"; + +import { metaFor, renderPage, robotsTxt, siteFor, sitemap } from "../pageMeta.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +export const SITE_INDEX = path.resolve( + process.env.SITE_INDEX ?? path.join(here, "../../../dist/index.html"), +); + +const CACHE = "public, max-age=60, stale-while-revalidate=300"; + +let cached = { mtime: 0, html: null }; + +function indexHtml() { + const mtime = statSync(SITE_INDEX).mtimeMs; + if (cached.html && cached.mtime === mtime) return cached.html; + cached = { mtime, html: readFileSync(SITE_INDEX, "utf8") }; + return cached.html; +} + +const pages = new Hono(); + +/* Warned once per cause rather than on every request, so a missing + site.json doesn't bury the log. */ +const warned = new Set(); +function warnOnce(key, message) { + if (warned.has(key)) return; + warned.add(key); + console.error(message); +} + +pages.get("/robots.txt", (c) => { + let text; + try { + text = robotsTxt(siteFor(c.get("db"))); + } catch (err) { + warnOnce(`robots:${err.message}`, `pages: can't build robots.txt: ${err.message}`); + return c.text("robots.txt isn't available.", 503); + } + return c.text(text, 200, { "Cache-Control": CACHE }); +}); + +pages.get("/sitemap.xml", (c) => { + let xml; + try { + xml = sitemap(c.get("db")); + } catch (err) { + warnOnce(`sitemap:${err.message}`, `pages: can't build the sitemap: ${err.message}`); + return c.text("The sitemap isn't available.", 503); + } + return c.body(xml, 200, { + "Content-Type": "application/xml; charset=utf-8", + "Cache-Control": CACHE, + }); +}); + +pages.get("*", (c, next) => { + const pathname = c.req.path; + // The API's own paths, and an upload that isn't there, stay plain + // 404s rather than becoming a page. + if (/^\/(api|uploads)(\/|$)/.test(pathname)) return next(); + + let html; + try { + html = indexHtml(); + } catch (err) { + console.error(`pages: can't read ${SITE_INDEX}: ${err.message}`); + return c.text("The site hasn't been built.", 503); + } + + // The metadata is an extra. If it can't be built (site.json + // missing, a query failing), the page goes out as it was built, + // with the site's default tags, rather than not at all. + let meta; + let page; + try { + meta = metaFor(c.get("db"), pathname); + page = renderPage(html, meta); + } catch (err) { + warnOnce( + `meta:${err.message}`, + `pages: serving ${pathname} without its metadata: ${err.message}` + + (err.code === "ENOENT" ? " (set SITE_CONFIG to the deployed site.json)" : ""), + ); + return c.html(html, 200, { "Cache-Control": "no-store" }); + } + + return c.html(page, meta.status, { + "Cache-Control": meta.status === 200 ? CACHE : "no-store", + }); +}); + +export default pages; diff --git a/server/src/seed-showcase.js b/server/src/seed-showcase.js index 616fc47..41bcb3b 100644 --- a/server/src/seed-showcase.js +++ b/server/src/seed-showcase.js @@ -16,7 +16,8 @@ /people/showcase-person person: bio, links, roles past and current, events, awards, private data /events/showcase-event upcoming retreat: hosts, billed - people, links, blocks, background + people, links, blocks, background, + a three-day schedule /events/showcase-series weekly series with times /events/showcase-past-event past event where the award was given /blog/content-block-showcase every content block type @@ -37,7 +38,7 @@ Run without it again to take them back out. Images point at /uploads/showcase.jpg. Upload any photo in - Admin → Media and copy it to that name in the uploads directory, + Admin → Tools → Media and copy it to that name in the uploads directory, or leave it missing to check how each page copes without one. A database under /var/lib/ngu (where the deployed service keeps @@ -81,6 +82,23 @@ const PAST = "showcase-past-event"; /* ── Content ───────────────────────────────────────────────── */ +/* A schedule over three days, using every entry field: a plain + entry, one with a location and person, one folding out with a + description, graphic and map, one linked, and one with no day + (it lands in a tab of its own). */ +const SCHEDULE = [ + "schedule", + { text: "The weekend at a glance. Tap an entry for more." }, + [ + { day: "Friday", time: "4:00pm", text: "Arrivals and check-in", location: "Front desk" }, + { day: "Friday", time: "7:00 to 8:30pm", text: "Opening session", location: "Main Hall", person_id: "showcase-person", detail: "Welcome and worship", description: "The **opening session** sets the theme for the weekend.\n\nBring a notebook.", media: "/uploads/showcase.jpg", map: "Camp Hebron, Halifax PA" }, + { day: "Saturday", time: "9:00am", text: "Workshops", location: "Classrooms", person_id: "showcase-member-2", detail: "Pick one of three", url: "/blog/content-block-showcase" }, + { day: "Saturday", time: "7:00pm", text: "Talent night", location: "Main Hall", person_id: "showcase-member-3", description: "Sign up at the front desk by noon." }, + { day: "Sunday", time: "10:00am", text: "Closing service", location: "Chapel", map: "Main Street, Halifax PA" }, + { time: "Any time", text: "Quiet room open", location: "Library", detail: "An entry with no day" }, + ], +]; + /* Every block type, for the blog showcase. [type, fields, items?] */ const ALL_BLOCKS = [ ["paragraph", { text: "Every content block type, top to bottom, with each of its options. Use it to check the page after changing how blocks draw." }], @@ -109,6 +127,8 @@ const ALL_BLOCKS = [ ["subheading", { text: "Images" }], ["image", { media: IMAGE, alt: "Describe the picture here", text: "An image with a caption and alt text" }], ["image", { media: IMAGE, alt: "The same picture, linked", href: "/history" }], + ["subheading", { text: "Schedule" }], + SCHEDULE, ["subheading", { text: "Video" }], ["video", { href: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", text: "A YouTube video, with its own thumbnail" }], ["video", { href: "https://vimeo.com/76979871", media: IMAGE, text: "A Vimeo video with an uploaded still" }], @@ -354,7 +374,7 @@ tx(db, () => { { kind: "social", platform: "instagram", label: "@showcaseretreat", url: "https://instagram.com/showcaseretreat" }, ]); blocks("event", EVENT, "card", cardText("event")); - blocks("event", EVENT, "body", pageBody("event")); + blocks("event", EVENT, "body", [...pageBody("event"), ["heading", { text: "Schedule" }], SCHEDULE]); insert("events", { id: SERIES, diff --git a/server/src/shape.js b/server/src/shape.js index 5973156..179d71c 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -98,18 +98,39 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { const itemRows = db .prepare( - `SELECT block_id, text, detail, url - FROM content_block_items - WHERE block_id IN (${placeholders(blockIds.length)}) - ORDER BY block_id, sort_order`, + `SELECT i.block_id, i.text, i.detail, i.url, + i.day, i.time, i.location, i.description, i.media, i.map, + p.id AS person_id, p.display_name AS person_name, + p.photo AS person_photo, p.tagline AS person_tagline + FROM content_block_items i + LEFT JOIN people p ON p.id = i.person_id AND p.is_published = 1 + WHERE i.block_id IN (${placeholders(blockIds.length)}) + ORDER BY i.block_id, i.sort_order`, ) .all(...blockIds); + // The schedule fields are null on a list or link-row item; they + // ride along anyway rather than branching on the block's type. + // An unpublished person comes back as no person. for (const row of itemRows) { byId.get(row.block_id)?.items.push({ text: row.text, detail: row.detail, url: row.url, + day: row.day, + time: row.time, + location: row.location, + description: row.description, + media: row.media, + map: row.map, + person: row.person_id + ? { + id: row.person_id, + name: row.person_name, + photo: row.person_photo, + tagline: row.person_tagline, + } + : null, }); } diff --git a/site.json b/site.json index c0eb7d4..786515f 100644 --- a/site.json +++ b/site.json @@ -1,11 +1,57 @@ { "title": "Next Generation of Unity", + "url": "https://nextgenerationofunity.org", "description": "", "robots": { - "index": false + "index": true + }, + "openGraph": { + "image": "" }, "accessibility": { "addBypassLinks": false, "ignoreReducedMotion": false + }, + "pages": { + "/retreats": { + "title": "Retreats", + "description": "Retreats hosted by Next Generation of Unity, our regions, and our partners throughout the year." + }, + "/community": { + "title": "Community", + "description": "Chapters, regions and the people who make up Next Generation of Unity." + }, + "/leadership": { + "title": "Leadership", + "description": "The board, staff, and volunteers who keep Next Generation of Unity running." + }, + "/resources": { + "title": "Resources", + "description": "Teachings, brand assets, and material for chapters and partners." + }, + "/history": { + "title": "History", + "description": "A near-complete timeline of Next Generation of Unity (NGU), and other Unity Young Adult programs." + }, + "/feedback": { + "title": "Feedback", + "description": "Tell us what's working, what isn't, and what you'd like to see next." + }, + "/qr": { + "title": "QR Codes", + "description": "Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colours." + }, + "/give": { + "title": "Giving", + "description": "Support the work of Next Generation of Unity." + }, + "/privacy": { + "title": "Privacy Policy", + "description": "How Next Generation of Unity collects, uses, and protects your information." + }, + "/terms": { + "title": "Terms of Service", + "description": "The terms that apply when you use this site and our programs." + } } } diff --git a/src/assets/Fall Logo.svg b/src/assets/Fall Logo.svg deleted file mode 100644 index 33f133f..0000000 --- a/src/assets/Fall Logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/assets/event-logos/fall-retreat-logo.svg b/src/assets/event-logos/fall-retreat-logo.svg deleted file mode 100644 index 33f133f..0000000 --- a/src/assets/event-logos/fall-retreat-logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/assets/event-logos/ngu-logo-white-bg.svg b/src/assets/event-logos/ngu-logo-white-bg.svg deleted file mode 100644 index 3202fa3..0000000 --- a/src/assets/event-logos/ngu-logo-white-bg.svg +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - Next Generation - of Unity - - - - diff --git a/src/assets/NGU_Logo.svg b/src/assets/logos/NGU_Logo.svg similarity index 100% rename from src/assets/NGU_Logo.svg rename to src/assets/logos/NGU_Logo.svg diff --git a/src/assets/NGU_Logo_WhiteBG.svg b/src/assets/logos/NGU_Logo_WhiteBG.svg similarity index 100% rename from src/assets/NGU_Logo_WhiteBG.svg rename to src/assets/logos/NGU_Logo_WhiteBG.svg diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index d94e4b9..959dcd3 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -19,6 +19,10 @@ image media, alt, text is the caption, href video href is the video, media a still, text the caption; click to play + schedule items as entries in day tabs (day, time, + text, detail, url, location, person, and + a fold-out of description, media, map); + text is an optional intro. ScheduleBlock divider nothing "Formatted" is InlineText.tsx: **bold**, *italic*, [text](url), @@ -33,6 +37,7 @@ import { blockMedia } from '../lib/media.ts' import type { ContentBlock } from '../lib/useContent.ts' import { Anchor, Inline, Paragraphs } from './InlineText.tsx' import VideoPlayer from './VideoPlayer.tsx' +import ScheduleBlock from './ScheduleBlock.tsx' const BODY = '#4a6b72' @@ -196,6 +201,10 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) { ) + case 'schedule': + if (!block.items?.length) return null + return + case 'divider': return
diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index 21974ea..d06455e 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -1,6 +1,6 @@ import { Link } from "react-router-dom"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; -import nguLogo from "../assets/NGU_Logo.svg"; +import nguLogo from "../assets/logos/NGU_Logo.svg"; import PlatformIcon from "./PlatformIcon.tsx"; const Social_Links = [ diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index 6b999a7..d04bf59 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -2,7 +2,7 @@ import { useState, useEffect, useRef } from "react"; import { NavLink, Link, Outlet, useLocation } from "react-router-dom"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; import Banner from "./Banner.jsx"; -import nguLogo from "../assets/NGU_Logo.svg"; +import nguLogo from "../assets/logos/NGU_Logo.svg"; import Footer from "./Footer.tsx"; /* ── Right-side nav actions ──────────────────────────────── */ diff --git a/src/components/PageShell.tsx b/src/components/PageShell.tsx index 496f926..0d2017c 100644 --- a/src/components/PageShell.tsx +++ b/src/components/PageShell.tsx @@ -29,7 +29,9 @@ /> ═══════════════════════════════════════════════════════════════ */ -import type { ReactNode } from "react"; +import { useEffect, type ReactNode } from "react"; + +import { documentTitle } from "../lib/site.ts"; const TEAL = "#138ba0"; @@ -89,6 +91,13 @@ export function Section({ section }: { section: ShellSection }) { } export default function PageShell({ title, intro, sections }: PageShellProps) { + // The tab's title as the visitor moves around. The first load's + // comes from the server (pageMeta.js), which also sets the page's + // description and preview for search and link sharing. + useEffect(() => { + if (typeof title === "string") document.title = documentTitle(title); + }, [title]); + return ( <> {/* Page header */} diff --git a/src/components/QrCode.tsx b/src/components/QrCode.tsx index e5f92d1..8ae64bf 100644 --- a/src/components/QrCode.tsx +++ b/src/components/QrCode.tsx @@ -1,16 +1,25 @@ /* ═══════════════════════════════════════════════════════════════ QR CODE - A QR code as an , sized by its container. With `dove`, the - NGU dove sits on a white badge over the centre; the code switches - to high error correction so the modules under the badge are - recovered when it's scanned (see lib/qr.ts). The badge covers - under 6% of the code, well inside what 'H' repairs, and never - reaches the three corner finder patterns. + A QR code as an , sized by its container. - Everything is drawn in the SVG itself (no CSS, no external - references), so the element serialises to a file that looks the - same outside the page. `ref` reaches the for exactly that. + `centre` puts something on a badge over the middle: the NGU dove, + or an image (an SVG from src/assets/qr, passed as a data: URL). + With anything there, the code switches to high error correction + so the modules under the badge are recovered when it's scanned + (see lib/qr.ts). The badge covers under 6% of the code, well + inside what 'H' repairs, and never reaches the three corner + finder patterns. + + `ink` is the modules and the badge's outline, `paper` the + background and the badge. A code should stay dark on light with + strong contrast to scan reliably; QrCodeMaker warns when it + doesn't, this just draws what it's given. + + Everything is drawn in the SVG itself (no CSS, and an image is + embedded rather than linked), so the element serialises to a + file that looks the same outside the page. `ref` reaches the + for exactly that. ═══════════════════════════════════════════════════════════════ */ import { useMemo, type Ref } from 'react' @@ -23,8 +32,9 @@ import { qrMatrix, qrPath } from '../lib/qr.ts' const MARGIN = 4 /* Dark enough to scan as black; the site's deep teal. */ -const INK = '#04262e' -const TEAL = '#138ba0' +export const QR_INK = '#04262e' +export const QR_PAPER = '#ffffff' +export const QR_DOVE = '#138ba0' /* Badge side as a share of the code's width. */ const BADGE = 0.24 @@ -32,21 +42,28 @@ const BADGE = 0.24 /* DoveMark's own viewBox is 72.87 × 48.57. */ const DOVE_ASPECT = 72.867699 / 48.568241 +export type QrCentre = { kind: 'dove'; color?: string } | { kind: 'image'; src: string } | null + export default function QrCode({ value, - dove = false, + centre = null, + ink = QR_INK, + paper = QR_PAPER, label, ref, className, }: { value: string - dove?: boolean + centre?: QrCentre + ink?: string + paper?: string /** Accessible name for the image, e.g. "QR code for /retreats". */ label: string ref?: Ref className?: string }) { - const matrix = useMemo(() => qrMatrix(value, dove ? 'H' : 'M'), [value, dove]) + const level = centre ? 'H' : 'M' + const matrix = useMemo(() => qrMatrix(value, level), [value, level]) const path = useMemo(() => qrPath(matrix, MARGIN), [matrix]) const total = matrix.size + MARGIN * 2 @@ -54,6 +71,7 @@ export default function QrCode({ const badgeAt = (total - badge) / 2 const doveWidth = badge * 0.78 const doveHeight = doveWidth / DOVE_ASPECT + const imageSize = badge * 0.8 return ( - - + + - {dove && ( + {centre && ( - + {centre.kind === 'dove' ? ( + + ) : ( + + )} )} diff --git a/src/components/ScheduleBlock.tsx b/src/components/ScheduleBlock.tsx new file mode 100644 index 0000000..d15e2d0 --- /dev/null +++ b/src/components/ScheduleBlock.tsx @@ -0,0 +1,270 @@ +/* ═══════════════════════════════════════════════════════════════ + SCHEDULE BLOCK + + The 'schedule' content block (034_schedule_block.sql): entries + in one tab per day, each a row of time, title, place and person, + folding out for the rest. + + Tabs are the entries' `day` values in the order they first + appear, so the admin's order is the page's. An entry with no day + joins an untitled group; a schedule of one day draws no tabs. The + tab whose name starts with today's weekday opens first ("Friday", + "Fri", "Friday, June 6"), so on the day of an event the visitor + lands on today; otherwise the first tab. + + A row folds out when it has anything more to show: a + description, a graphic, a map, or a person (their photo, tagline + and a link to their page). The map is Google's key-free embed of + the place typed in, with a link out to the full map. + + Tabs follow the ARIA tab pattern: arrow keys move between them. + ═══════════════════════════════════════════════════════════════ */ + +import { useId, useState, type KeyboardEvent } from 'react' +import { Link } from 'react-router-dom' + +import { personHref } from '../lib/hrefs.ts' +import { blockMedia, initials, personPhoto } from '../lib/media.ts' +import type { ContentBlockItem } from '../lib/useContent.ts' +import { Anchor, Paragraphs } from './InlineText.tsx' + +const BODY = '#4a6b72' +const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] + +type Day = { name: string; entries: ContentBlockItem[] } + +function groupByDay(items: ContentBlockItem[]): Day[] { + const days: Day[] = [] + for (const item of items) { + const name = item.day?.trim() ?? '' + let day = days.find((d) => d.name === name) + if (!day) { + day = { name, entries: [] } + days.push(day) + } + day.entries.push(item) + } + return days +} + +/* The tab to open with: today's weekday if a tab starts with it (or + its three-letter form), else the first. */ +function todayIndex(days: Day[]): number { + const today = WEEKDAYS[new Date().getDay()] + const found = days.findIndex((day) => { + const name = day.name.toLowerCase() + return name.startsWith(today) || name.startsWith(today.slice(0, 3)) + }) + return found >= 0 ? found : 0 +} + +const mapEmbed = (place: string) => + `https://maps.google.com/maps?q=${encodeURIComponent(place)}&output=embed&maptype=satellite` +const mapLink = (place: string) => + `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(place)}` + +function Avatar({ person, size }: { person: NonNullable; size: string }) { + const [failed, setFailed] = useState(false) + const src = personPhoto(person.photo) + return src && !failed ? ( + setFailed(true)} className={`${size} shrink-0 rounded-full object-cover`} /> + ) : ( + + ) +} + +function Entry({ entry, accent }: { entry: ContentBlockItem; accent: string }) { + const [open, setOpen] = useState(false) + const panelId = useId() + const graphic = blockMedia(entry.media) + const place = entry.map?.trim() + const more = Boolean(entry.description || graphic || place || entry.person) + + const title = entry.url ? ( + + {entry.text} + + ) : ( + entry.text + ) + + return ( +
  • +
    +

    + {entry.time} +

    + +
    +

    {title}

    + {(entry.location || entry.person) && ( +

    + {entry.location && {entry.location}} + {entry.person && ( + + + {entry.person.name} + + )} +

    + )} + {entry.detail && ( +

    + {entry.detail} +

    + )} +
    + + {more && ( + + )} +
    + + {more && open && ( +
    + {entry.person && ( +
    + +
    + + {entry.person.name} + + {entry.person.tagline && ( +

    + {entry.person.tagline} +

    + )} +
    +
    + )} + + {entry.description && ( +
    + +
    + )} + + {graphic && } + + {place && ( +
    +