diff --git a/.gitignore b/.gitignore index 383815b..a8ec6a0 100644 --- a/.gitignore +++ b/.gitignore @@ -13,15 +13,22 @@ build/ # local databases *.db *.db-journal +*.db-wal +*.db-shm # editor and OS files .vscode/* !.vscode/extensions.json .DS_Store Thumbs.db +nginx-dev # plain txt files -.txt +*.txt + # uploaded media (local dev) server/uploads/ server/clips/ + +# skills +graphify-out/ \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index bcbe152..c6a1596 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,17 +8,17 @@ Website for NGU (Next Generation of Unity), a Unity movement organization with r ## Stack - Frontend: React, TypeScript, Tailwind CSS, React Router, Vite (in `src/`) -- Backend: Hono on Node.js, SQLite (WAL mode, STRICT tables) via better-sqlite3 / node:sqlite (in `server/`) +- Backend: Hono on Node.js, SQLite (WAL mode, STRICT tables) via node:sqlite (in `server/`) - Package manager: pnpm only (never npm or yarn) ## Commands Frontend (repo root): - `pnpm dev` / `pnpm build` / `pnpm preview`: Vite - `pnpm format`: oxfmt -- `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script) +- `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script). `noImplicitAny` is off on purpose: turning it on shows about 480 errors (untyped props and params, mostly in OrgList-Map, admin fields, EntityEdit, EventList-Cards). Decided 2026-09-29 not to fix them; don't turn it on or start typing files for it unless asked. New code should still type its props. - There is no test suite. -Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: +Backend (`server/`, Node >= 22.13). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created @@ -34,6 +34,8 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - 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`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. +- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`. +- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`. - 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 @@ -54,24 +56,28 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu ## Project layout - All pages use `PageShell.tsx` as the wrapper unless explicitly noted otherwise. - Pages live in `src/pages/`; section-level components go in `src/pages/sections/`. -- `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite. +- `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite, through hooks in `src/lib/`. - `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. -- 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. +- 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/`. Logo images hide themselves on load error (`onError`). ## 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. - **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere. - **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names. - **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface. +- **Colours are tokens, not hex.** Admins can override any token (Panel → Site settings → Colours). The defaults are `server/src/themeDefaults.js` plus the same values as CSS in `src/index.css`; the build fails if they differ (`themeDefaultsCheck` in `vite.config.ts`), and migration 041's CHECK lists the token names. Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's colour). Data colours (accents, event and region colours) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`. +- **Icons are Phosphor** (`@phosphor-icons/react`), weight `bold` (or `fill` for play/star). No hand-drawn `` icons and no Unicode glyphs as icons (× › ▶ →). Brand marks are the exception: `DoveMark`, `PlatformIcon`, the Google logo, the chapter map. +- **Accents come from `src/lib/color.ts`:** `BRAND` (the teal, via the button token so the admin palette reaches it) and `ACCENTS` (deep, green, mint). Not a new hex in a page. - **No em-dashes** (U+2014) anywhere: UI text, help text, comments, docs, commit messages. Use a colon, comma or parentheses. An empty table cell shows `-`. - **Admin editor text:** blank select options read `Default: …` (what blank means), examples in help text start with `eg.`, and record ids are called "URL ID". Cut-off preview text uses `preview()` from `src/lib/text.ts`, which ends it with an ellipsis. See `docs/updating-data-in-code.md`. ## Admin CRUD engine -Descriptor-driven: `server/admin-crud.js` and `admin-schema.js` (server) and `adminSchema.ts` (client) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code. +Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema/` (server, one file per entity, registered in `admin-schema.js`) and `src/lib/adminSchema/` (client, one file per entity, registered in `adminSchema.ts`) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code. - Child collections are deleted and reinserted wholesale. Unsafe for entities referenced by foreign keys elsewhere. - `reindex: false` prevents cross-entity sort order collisions. +- `check: (db, id) => void` runs after a save has written everything, inside its transaction; throwing an `HttpError` refuses the save (Site settings uses it for the colour contrast check, `server/src/theme.js`). - The `OMIT` sentinel distinguishes unsent fields from deliberate clears. - `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree. - `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift. @@ -83,4 +89,14 @@ Descriptor-driven: `server/admin-crud.js` and `admin-schema.js` (server) and `ad - The runner turns foreign keys off around every migration (it can't be done inside the file's transaction) and runs `PRAGMA foreign_key_check` before committing, so a table rebuild needs no `PRAGMA foreign_keys` of its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename in `PRAGMA legacy_alter_table = ON` ... `OFF`, then recreate the rebuilt table's own indexes and triggers. ## Integrations -- Church Center (ngu.churchcenteronline.com): Planning Center embeds for giving and the calendar. \ No newline at end of file +- Church Center (ngu.churchcenteronline.com): Planning Center embeds for giving. + +## graphify + +This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships. + +Rules: +- For codebase questions, first run `graphify query ""` when graphify-out/graph.json exists. Use `graphify path "" ""` for relationships and `graphify explain ""` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. +- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing. +- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context. +- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost). diff --git a/README.md b/README.md index 5a78d25..655d467 100644 --- a/README.md +++ b/README.md @@ -1 +1,8 @@ -Test line added by Claude Code. +# NGU-Web + +Website for NGU (Next Generation of Unity): a public site and a role-based admin panel. + +- Frontend: React, TypeScript, Tailwind, Vite (`src/`). `pnpm dev`, `pnpm build`. +- API: Hono on Node 22.13+, SQLite (`server/`). `DB_PATH=./dev.db pnpm dev`. +- Accounts are made with `server/src/admin-cli.js`. +- Deployment and setup notes are in `docs/`; working notes for contributors are in `CLAUDE.md`. diff --git a/docs/media-uploads.md b/docs/media-uploads.md index 2352a3e..86cc907 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -72,6 +72,9 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies add_header X-Content-Type-Options nosniff; # An uploaded SVG opened on its own can't run script. add_header Content-Security-Policy "default-src 'none'; style-src 'unsafe-inline'; sandbox"; + # add_header here replaces the server-level HSTS; say it again + # (docs/security-headers.md). + add_header Strict-Transport-Security "max-age=31536000" always; } ``` diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..5744786 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,71 @@ +# Performance + +What keeps the site fast, and what nginx has to do for it. + +## nginx + +In the site's `server` block (both are in `nginx-dev`): + +```nginx +gzip on; +gzip_vary on; +gzip_proxied any; +gzip_comp_level 5; +gzip_min_length 1024; +gzip_types text/css application/javascript text/javascript application/json + image/svg+xml application/xml application/rss+xml text/plain; + +listen 443 ssl http2; +listen [::]:443 ssl http2; +``` + +Ubuntu's `nginx.conf` turns gzip on for `text/html` only, so without +`gzip_types` the JS, CSS, JSON and SVG go out full size (the main JS is +about 314 kB, about 98 kB gzipped). Check with +`curl -sI -H 'Accept-Encoding: gzip' https:///assets/.js | grep -i content-encoding`. +`http2` on the `listen` line works on every nginx; 1.25.1 and later +also take a separate `http2 on;`. + +## Caching + +- `/assets/` (hashed build files): a year, `immutable` (nginx). +- `/uploads/`: 30 days, `immutable` (nginx). Filenames are random and + never reused. +- Page HTML: `no-cache` (the API, `routes/pages.js`). The page names the + build's hashed assets, so a cached old page after a deploy would ask + for files that are gone. +- Public API reads: 60 s, plus 5 minutes stale while revalidating + (`CACHE` in `server/src/shape.js`). +- RSS feeds: read at most every 30 minutes; a visitor never waits for + one after the first read (`server/src/feeds.js`). + +## The bundle + +Only the home page is in the main bundle. Every other page, and the +whole admin, loads when first visited (`src/App.tsx`). A tab still +running an old build that asks for a page removed by a deploy reloads +once to pick up the new one. + +The home page asks for events and the timeline alongside its own data +(`src/pages/Home.tsx`), and the server tells the browser to fetch +`/api/front-page` and the first hero photo while the JS downloads +(`preload` in `server/src/pageMeta.js`). + +## Images + +Every raster upload gets a copy at most 640 px on its longer side, +`-640.webp`, beside it in the uploads folder +(`server/src/media.js`). Logos, avatars and card pictures load that copy +(`useSmallImage` in `src/lib/useSmallImage.ts`) and fall back to the +full file if it's missing. The server makes any missing copies in the +background when it starts, so older uploads and files copied in by hand +get one too; deleting an upload deletes its copy. + +## Server + +- Password checks run off the event loop (`verifyPassword`, async + scrypt), so a login doesn't stall other requests. +- Only `/api/admin/*` is logged per request; nginx's access log has the + rest. +- ffmpeg encodes run at `nice 19` on Linux, so a clip doesn't slow the + site down. diff --git a/docs/security-headers.md b/docs/security-headers.md new file mode 100644 index 0000000..9c72ce6 --- /dev/null +++ b/docs/security-headers.md @@ -0,0 +1,99 @@ +# Security headers + +Who sends what, and what nginx has to do for it. + +## From the API + +Every response the API sends (pages, `/api`, the sitemap, robots.txt) +carries Hono's `secureHeaders()` (`server/src/index.js`): + +- `X-Frame-Options: SAMEORIGIN`: the site can't be framed by another site. +- `X-Content-Type-Options: nosniff` +- `Referrer-Policy: strict-origin-when-cross-origin`: kept to the origin, + because YouTube embeds refuse to play without a referrer. +- `Cross-Origin-Opener-Policy` and `Cross-Origin-Resource-Policy: same-origin` +- no HSTS (nginx sends it, below) +- `Content-Security-Policy-Report-Only`: blocks nothing yet. Browsers + post what it would have blocked to `/api/csp-report`, which logs one + line per report (`journalctl -u ngu-api | grep csp`). The allowed + embed hosts are `EMBEDS` in `server/src/index.js`. After a while of + real use with nothing unexpected in the log, rename + `contentSecurityPolicyReportOnly` to `contentSecurityPolicy` there to + enforce it. A new embed host (a new video site, say) has to be added + to `EMBEDS` first. + +The API also refuses a form-style write (`text/plain`, form or +multipart body) sent from another site, including a sibling subdomain +(`hono/csrf`). Browsers mark their own requests +`Sec-Fetch-Site: same-origin`; for older ones it compares `Origin` with +the `Host` header, so **nginx must pass `Host`**: + +```nginx +proxy_set_header Host $host; +``` + +Rate limits and stored IP hashes use the **last** `X-Forwarded-For` +entry, the one nginx adds from the connection, so each block that +proxies to the API needs: + +```nginx +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +``` + +Both lines are already in every proxied block in `nginx-dev` and in +`docs/seo.md`. + +## Sign-in + +- The session cookie is `__Host-site_session`: the browser only + accepts it Secure, on path `/`, with no Domain, so another + subdomain can't set or overwrite it. With `COOKIE_SECURE=false` + (plain-http local work) it's `site_session`, since the prefix needs + Secure. +- Logins are limited per IP where `/api/auth/login` is mounted (10 + per 15 minutes, `server/src/index.js`) and per email in + `routes/auth.js`: five wrong passwords for one address lock it for + the rest of 15 minutes, from anywhere; a correct one clears the + count. Both are in memory and reset when the service restarts. +- The per-email lock is a trade-off: anyone who knows an admin's + address can keep password sign-in for it locked by guessing wrong + five times every 15 minutes. Google sign-in still works for that + account, and the lock clears on a restart. +- `clientIp` trusts the last `X-Forwarded-For` entry, the one nginx + adds. If a CDN or another proxy is ever put in front of nginx, that + entry becomes the proxy's address and every visitor shares one + rate-limit bucket: set nginx's `real_ip_header` and + `set_real_ip_from` for the proxy first. +- The Google sign-in state cookie is `__Host-site_oauth` (plain + `site_oauth` over local http), and the page it returns to is checked + again when the browser comes back. + +## From nginx: HSTS + +nginx terminates TLS and serves files from disk (`/assets/`, +`/uploads/`, `index.html` when the API is down), so it sends HSTS for +everything: + +```nginx +# In the server block (the 443 one). +add_header Strict-Transport-Security "max-age=31536000" always; +``` + +`add_header` in a `location` replaces the server-level ones, so every +block with an `add_header` of its own repeats that line (and, on the +dev site, the `X-Robots-Tag` one). In `nginx-dev` that's `@file`, +`/uploads/`, `/assets/`, `@static` and `= /index.html`. Blocks with no +`add_header` (the proxied ones) inherit it. + +No `includeSubDomains`: each subdomain (eg. dev) sends its own. Only +add it, or `preload`, once every subdomain is on HTTPS for good; both +are hard to undo. + +Check it: + +```sh +curl -sI https://nextgenerationofunity.org/ | grep -i strict +curl -sI https://nextgenerationofunity.org/assets/ | grep -i strict +``` + +Each should print the header once. diff --git a/docs/seo.md b/docs/seo.md index feaa726..cb2652f 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -90,6 +90,8 @@ with it off it blocks everything. location @static { try_files /index.html =404; } + # (A block that adds headers of its own, eg. Cache-Control, must + # repeat the server-level HSTS line: docs/security-headers.md.) # From the API, so Site settings' indexing switch applies; the # build's own robots.txt if the API is down. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index bd861f7..715cb90 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -33,7 +33,7 @@ what a dropdown in the admin editor says. | 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) | -| 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` | +| A static page's title and intro (also its search title and description), the site's name, description, preview image, icons, search indexing, privacy contact email | 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, @@ -49,8 +49,8 @@ each entity: | File | What it holds | | ----------------------------- | ----------------------------------------------------- | -| `src/lib/adminSchema.ts` | The **form**: field labels, help text, dropdown labels, list columns and filters | -| `server/src/admin-schema.js` | What the server **accepts**: columns, types, the allowed values of each `enumeration(...)` | +| `src/lib/adminSchema/` (one file per entity, `shared.ts` for common fields; `src/lib/adminSchema.ts` lists them) | The **form**: field labels, help text, dropdown labels, list columns and filters | +| `server/src/admin-schema/` (one file per entity, `columns.js` for shared helpers; `server/src/admin-schema.js` lists them) | What the server **accepts**: columns, types, the allowed values of each `enumeration(...)` | And the database itself holds the final word: most fixed lists are a `CHECK (... IN (...))` constraint on the column (read them in @@ -76,7 +76,7 @@ organization name in the label, as the `awards` query does. > are changed with a migration: `UPDATE event_scopes SET name = '…' WHERE id = '…';` **2. A fixed list in code (`options`).** The choices are written in -`src/lib/adminSchema.ts`. Each option is one of two shapes: +the entity's file in `src/lib/adminSchema/`. Each option is one of two shapes: ```ts options: ["speaker", "leader", "host"] // shows: speaker, leader, host @@ -90,7 +90,7 @@ relabelling cheap. ### Renaming what a dropdown shows If the stored value stays the same and you only want the dropdown to -read differently, **only `src/lib/adminSchema.ts` changes**. No +read differently, **only the file in `src/lib/adminSchema/` changes**. No migration, no server change, and every existing row keeps working. Find the field (search for its column name) and give the option a @@ -145,9 +145,9 @@ together, in one branch: **Renaming** a value also needs an `UPDATE` in the same migration so existing rows move to the new value. **Removing** one needs you to decide what existing rows become first. -2. **`server/src/admin-schema.js`**: the `enumeration("column", [...])` +2. **`server/src/admin-schema/.js`**: the `enumeration("column", [...])` list for that column. -3. **`src/lib/adminSchema.ts`**: the `options` on the form field, and on +3. **`src/lib/adminSchema/.ts`**: the `options` on the form field, and on the list filter if there is one. 4. **Anywhere the public site renders or relies on the value**, listed in the table below (for example `EVENT_TYPES` for event types, or the @@ -160,12 +160,12 @@ wrong rather than working around it. ### Every dropdown in the editor -**Fixed lists** (`options`: labels in `src/lib/adminSchema.ts`, values -also in `admin-schema.js` and a CHECK): +**Fixed lists** (`options`: labels in `src/lib/adminSchema/`, values +also in `server/src/admin-schema/` and a CHECK): | Entity → field | Stored values | Labelled? | Also used on the public site by | | --- | --- | --- | --- | -| Organizations → Kind (+ list filter) | national, region, chapter, partner | no, shows values | `ORG_KIND_LABEL` in `src/lib/hrefs.ts`, and the route each kind uses | +| Organizations → Kind (+ list filter) | national, region, chapter, partner | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses) and `orgListHref` there (its back link) | | Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it | | Organizations → Region areas → Edge | top, bottom | no | the chapter map (`OrgList-Map.tsx`) | | Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) | @@ -176,7 +176,7 @@ 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, 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`). | +| 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/shared.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 | @@ -206,7 +206,6 @@ code): | 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; Front page → Featured event | `events` | events | -| Timeline → Record | `timeline_refs` | all five kinds, filtered by "Points at" | --- @@ -219,7 +218,7 @@ each is changed in a different place: | --- | --- | | **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 name in the admin's Section dropdown** ("Events Carousel (National Retreats)") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema/frontPage.ts` | | The subnav links under the header ("#Retreats", "#Calendar") | `PAGE_SECTIONS["/"]` in `src/navConfig.ts` | To rename a band **for visitors**, use the admin. To rename how it @@ -243,7 +242,7 @@ change the band's `id`. **Adding a new kind of band** (not just renaming one) is a feature, not a relabel: it needs a component, an entry in `SECTIONS` in `Home.tsx`, the key added to `FRONT_PAGE_SECTIONS`, to the -`enumeration("section", …)` in `server/src/admin-schema.js`, to the +`enumeration("section", …)` in `server/src/admin-schema/frontPage.js`, to the `FrontPageSectionKey` type in `src/lib/useFrontPage.ts`, and to the CHECK on `front_page_sections.section` via a migration. @@ -253,13 +252,13 @@ CHECK on `front_page_sections.section` via a migration. The numbers band's "Number Source" dropdown works the same way: -- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema.ts`. +- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema/frontPage.ts`. - **Change what a count counts:** its query in `STAT_QUERIES` in `server/src/routes/home.js`. Keep it counting exactly what the matching public page shows (published rows), or the number and the page will disagree. - **Add a source:** the CHECK on `front_page_stats.source` (migration), - the `enumeration("source", …)` in `server/src/admin-schema.js`, + the `enumeration("source", …)` in `server/src/admin-schema/frontPage.js`, `STAT_SOURCES`, and a query in `STAT_QUERIES`. --- @@ -273,10 +272,14 @@ The numbers band's "Number Source" dropdown works the same way: | 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 → 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. | +| 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. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. | +| The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. | +| The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | +| A page section's accent colour | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a colour there, not a hex in a page. Each is readable as text on white and the tints. | +| Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. | | 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` | | -| Organization kind labels ("Region", "Chapter") | `ORG_KIND_LABEL` in `src/lib/hrefs.ts` | | +| Organization kind labels ("Region", "Chapter") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin); `orgListHref` in `src/lib/hrefs.ts` (the public back link, "All regions") | | | Admin account roles | `src/lib/roles.ts` (labels, notes) and `ROLES` in `server/src/auth.js` | Adding a role is also a CHECK change on `admin_users.role`. | | Admin navigation | `src/pages/admin/adminNav.ts` | | | The live site's address (used by QR codes) | `SITE_ORIGIN` in `src/lib/site.ts` | | diff --git a/index.html b/index.html index 2eedec2..6c16a39 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,28 @@ <!-- site:title --> - + + + + + diff --git a/package.json b/package.json index b1ca7fd..14690f3 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "dependencies": { "@fontsource/montserrat": "^5.3.0", "@fontsource/poppins": "^5.3.0", + "@phosphor-icons/react": "^2.1.10", "qrcode": "^1.5.4", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 70bbb7b..2266481 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@fontsource/poppins': specifier: ^5.3.0 version: 5.3.0 + '@phosphor-icons/react': + specifier: ^2.1.10 + version: 2.1.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0) qrcode: specifier: ^1.5.4 version: 1.5.4 @@ -129,6 +132,13 @@ packages: cpu: [x64] os: [win32] + '@phosphor-icons/react@2.1.10': + resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==} + engines: {node: '>=10'} + peerDependencies: + react: '>= 16.8' + react-dom: '>= 16.8' + '@rolldown/binding-android-arm-eabi@1.2.9': resolution: {integrity: sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -823,6 +833,11 @@ snapshots: '@oxfmt/win32-x64@0.2.0': optional: true + '@phosphor-icons/react@2.1.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + dependencies: + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + '@rolldown/binding-android-arm-eabi@1.2.9': optional: true diff --git a/server/package.json b/server/package.json index 9f206bf..886bbb6 100644 --- a/server/package.json +++ b/server/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "engines": { - "node": ">=22" + "node": ">=22.13" }, "scripts": { "dev": "node --watch src/index.js", diff --git a/server/src/admin-cli.js b/server/src/admin-cli.js index 7c907f3..8bbae19 100644 --- a/server/src/admin-cli.js +++ b/server/src/admin-cli.js @@ -21,14 +21,14 @@ admin + delete records superadmin + accounts, roles and sessions, via /admin/panel - add takes --role=editor, --name="Full Name". It defaults to - admin. Press enter at the password prompt and it generates one + add takes --role=admin, --name="Full Name". It defaults to + editor, the least that can change content; raise it on purpose. Press enter at the password prompt and it generates one and prints it once. The list comes from auth.js rather than being repeated here, so the CLI can't drift from what requireRole will actually accept. - This is also how the first superadmin is made — there's no + This is also how the first superadmin is made, there's no bootstrap path in the web interface, on purpose: node src/admin-cli.js role you@ngu.org superadmin @@ -82,7 +82,7 @@ async function readPassword() { if (first === "") { const generated = randomBytes(12).toString("base64url"); console.log(`\nGenerated password: ${generated}`); - console.log("Copy it now — it isn't stored anywhere readable.\n"); + console.log("Copy it now, it isn't stored anywhere readable.\n"); return generated; } @@ -116,7 +116,7 @@ function checkRole(role) { return role; } -/* Printed, never enforced — see the note at the top of the file. +/* Printed, never enforced, see the note at the top of the file. Worth saying out loud, because the person doing it is usually tidying up accounts rather than thinking about lockouts. */ function warnIfLastSuper(db, user) { @@ -139,7 +139,7 @@ function warnIfLastSuper(db, user) { async function add(db, email, flags) { if (findUser(db, email)) fail(`${email} already exists. Use passwd to change it.`); - const role = checkRole(flags.role ?? "admin"); + const role = checkRole(flags.role ?? "editor"); const password = await readPassword(); @@ -183,7 +183,7 @@ function setRole(db, email, role) { db.prepare("UPDATE admin_users SET role = ? WHERE id = ?").run(role, user.id); // The session they're holding was issued against the old role. - // Every check reads the row fresh, so it isn't a security hole — + // Every check reads the row fresh, so it isn't a security hole, // but their open tab would keep drawing buttons that now 403. destroyAllSessionsFor(db, user.id); diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index 6fa3164..f82a0b4 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -35,6 +35,11 @@ export class HttpError extends Error { const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/; const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; const CLOCK_TIME = /^([01]\d|2[0-3]):[0-5]\d$/; +// A url column may hold a full link, a site path, an anchor, a bare +// domain or a filename, but a scheme other than these is refused +// (javascript:, data:), whatever the page does with it later. +const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i; +const SAFE_SCHEMES = new Set(["http", "https", "mailto", "tel"]); /* Not a value the caller can ever send, so it can mean "leave this column out of the statement" without colliding with real data. */ @@ -106,6 +111,17 @@ function coerceValue(column, raw, errors, prefix = "") { if (!CLOCK_TIME.test(value)) errors[key] = "Use HH:MM, 24-hour."; return CLOCK_TIME.test(value) ? value : null; } + case "url": { + const value = String(raw).trim(); + // The URL parser ignores control characters, spaces and tabs + // inside a scheme ("java\tscript:"), so read it the same way. + const scheme = URL_SCHEME.exec(value.replace(/[\u0000-\u0020\u007f]/g, ""))?.[1].toLowerCase(); + if (scheme && !SAFE_SCHEMES.has(scheme)) { + errors[key] = "Links must start with http://, https://, mailto: or tel:, or be a site path like /retreats."; + return null; + } + return value === "" ? null : value; + } default: { const value = String(raw).trim(); return value === "" ? null : value; @@ -146,7 +162,7 @@ export function listRows(db, entity, query = {}) { params.push(...search.map(() => term)); } - const limit = Math.min(Number(query.limit) || 200, 500); + const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500)); const rows = db .prepare( @@ -304,7 +320,7 @@ export function createRow(db, entity, payload) { ) .run(...Object.values(values)) : db.prepare(`INSERT INTO ${entity.table} DEFAULT VALUES`).run(); - // better-sqlite3 and node:sqlite disagree about BigInt here. + // node:sqlite may hand back a BigInt here. newId = Number(result.lastInsertRowid); } else { const names = [entity.idColumn, ...Object.keys(values)]; @@ -316,6 +332,7 @@ export function createRow(db, entity, payload) { writeExtensions(db, entity, newId, payload, values); writeChildren(db, entity, newId, payload, values); + entity.check?.(db, newId); }), ); @@ -365,6 +382,9 @@ export function updateRow(db, entity, rawId, payload) { writeExtensions(db, entity, id, payload, merged); writeChildren(db, entity, id, payload, merged); + // The descriptor's own rule over the saved result, children + // included. Throwing rolls the whole save back. + entity.check?.(db, id); }), ); diff --git a/server/src/admin-schema-sync.js b/server/src/admin-schema-sync.js index 6487d0c..5c671d0 100644 --- a/server/src/admin-schema-sync.js +++ b/server/src/admin-schema-sync.js @@ -18,10 +18,19 @@ ever set it, so every insert through the admin will fail. The first is a silent repair. The other two are deployment bugs, - so with { strict: true } they stop the service starting rather + so they stop the service starting rather than waiting to surface one row at a time. ═══════════════════════════════════════════════════════════════ */ +/* The values a CHECK (column IN (...)) on the table allows, read from + its CREATE TABLE, or null when there's no such CHECK. */ +function checkValues(db, table, column) { + const sql = db.prepare(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`).get(table)?.sql ?? ""; + const match = new RegExp(`\\b${column}"?\\s+IN\\s*\\(([^)]*)\\)`, "i").exec(sql); + if (!match) return null; + return new Set([...match[1].matchAll(/'((?:[^']|'')*)'/g)].map((m) => m[1].replace(/''/g, "'"))); +} + function tableMeta(db, table) { const rows = db.prepare(`PRAGMA table_info(${table})`).all(); if (!rows.length) return null; @@ -84,7 +93,7 @@ function collectGroups(entity) { return groups; } -export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) { +export function syncDescriptorsWithSchema(db, entities) { const list = Array.isArray(entities) ? entities.map((e) => [e.name ?? e.table, e]) : Object.entries(entities); const inferred = []; @@ -114,6 +123,19 @@ export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) inferred.push(`${name}: ${group.table}.${column.name}`); } if (info.notNullable) column.notNullable = true; + + // A dropdown value the table's CHECK refuses would only fail + // when someone saves it; say so at boot instead. + if (column.type === "enum") { + const allowed = checkValues(db, group.table, column.name); + const refused = allowed ? column.values.filter((value) => !allowed.has(value)) : []; + if (refused.length) { + problems.push( + `${name}: ${group.table}.${column.name} offers ${refused.join(", ")}, ` + + `which the table's CHECK doesn't allow.`, + ); + } + } } for (const [columnName, info] of meta) { @@ -136,8 +158,7 @@ export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) if (problems.length) { const report = `[admin-schema] descriptor does not match the database:\n ${problems.join("\n ")}`; - if (strict) throw new Error(report); - console.error(report); + throw new Error(report); } return { inferred, problems }; diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 9e85beb..7c62f6b 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -1,6 +1,10 @@ /* ═══════════════════════════════════════════════════════════════ ADMIN ENTITY DESCRIPTORS + One object per editable entity, one file each in admin-schema/ + (the shared column helpers and child collections are in + admin-schema/columns.js); this file lists them. + One object per editable entity. Everything the CRUD handlers do (validation, SQL, nesting) is read from here, so adding a table later is a descriptor rather than another set of @@ -15,6 +19,9 @@ children ordered collections, replaced wholesale on save singleton the one id this entity ever has; the engine refuses create and delete (see front_page) + check (db, id) => void, run after a save has written + everything, inside its transaction: throw an + HttpError to refuse it (site settings' colours) Replacing children wholesale is only safe because nothing has a foreign key INTO these tables. That is the dividing line, and @@ -35,915 +42,15 @@ what the other side owns rather than blanking it. ═══════════════════════════════════════════════════════════════ */ -/* ── Column helpers ──────────────────────────────────────────── */ - -const text = (name, opts = {}) => ({ name, type: "text", ...opts }); -const int = (name, opts = {}) => ({ name, type: "int", ...opts }); -const real = (name, opts = {}) => ({ name, type: "real", ...opts }); -const bool = (name, opts = {}) => ({ name, type: "bool", ...opts }); -const date = (name, opts = {}) => ({ name, type: "date", ...opts }); -const time = (name, opts = {}) => ({ name, type: "time", ...opts }); -const enumeration = (name, values, opts = {}) => ({ - name, - type: "enum", - values, - ...opts, -}); - -/* Place columns shared by organizations and events, in schema order. */ -const placeColumns = [ - text("venue"), - text("address"), - text("locality"), - text("state_code"), - text("country"), - text("location_label"), - real("latitude"), - real("longitude"), - bool("is_online"), -]; - -/* The affiliation's own fields, minus whichever end owns the row. - Both editors write the same shape so neither loses the other's - values on save. */ -const affiliationRole = [ - text("title"), - enumeration("role", ["lead", "board", "staff", "volunteer", "member"], { - required: true, - }), - bool("is_owner"), - date("started_on"), - date("ended_on"), - bool("is_public"), -]; - -/* The editable half of a timeline entry, shared by the standalone - editor and by the in_timeline extension on events and organizations. - - occurred_on is text, not date. "2012" and "2025-07" are legitimate - values (a backfilled entry often knows the year and nothing more), - and the date coercion would reject both. `precision` is what says how - much of it to believe. */ -const timelineFields = [ - text("occurred_on"), - enumeration("precision", ["year", "month", "day"]), - text("title"), - text("blurb"), - text("meta"), - text("link_url"), - bool("is_featured"), - bool("is_published"), - int("sort_order"), -]; - -/* The extension that the in_timeline checkbox drives. Ticked, the row - is upserted; unticked, writeExtensions deletes it. Both happen in the - parent's transaction, so the flag and the row cannot disagree. - - The conflict target is the UNIQUE (ref_kind, ref_id) constraint - on timeline_entries, which is also what stops a second save creating a - duplicate instead of updating the first. */ -const timelineExtension = (refKind) => ({ - key: "timeline", - table: "timeline_entries", - owner: { column: "ref_id", kindColumn: "ref_kind", kindValue: refKind }, - conflict: ["ref_kind", "ref_id"], - when: { column: "in_timeline", value: 1 }, - columns: [ - // Fixed for this end: an event's entry is always an event entry. - // Declared as a default rather than a form field so the column is - // written without asking. - enumeration( - "kind", - ["milestone", "event", "organization", "award", "people"], - { default: refKind === "organization" ? "organization" : refKind }, - ), - ...timelineFields, - ], -}); - -/* Featured cards (030_featured_cards.sql): polymorphic like links, - so the Community blog can own a set too. */ -const featuredCardsChild = (ownerKind) => ({ - key: "featured_cards", - table: "featured_cards", - owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, - order: "sort_order", - columns: [ - enumeration("kind", ["record", "link", "video"], { required: true }), - enumeration("ref_kind", ["event", "organization", "person", "team", "award"]), - text("ref_id"), - text("url"), - text("eyebrow"), - text("title"), - text("blurb"), - text("image"), - ], -}); - -/* The two polymorphic collections, parameterised by owner_kind. */ -const linksChild = (ownerKind) => ({ - key: "links", - table: "links", - owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, - order: "sort_order", - columns: [ - enumeration("kind", ["action", "social", "website", "email"], { - required: true, - }), - text("platform"), - text("label", { required: true }), - text("url", { required: true }), - bool("is_primary"), - ], -}); - -const blocksChild = (ownerKind) => ({ - key: "content_blocks", - table: "content_blocks", - owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, - order: "sort_order", - columns: [ - enumeration("slot", ["card", "body"], { required: true }), - enumeration( - "type", - [ - "heading", - "subheading", - "paragraph", - "list", - "links", - "quote", - "image", - "divider", - "video", - "button", - "callout", - "schedule", - ], - { required: true }, - ), - text("text"), - text("media"), - text("href"), - text("alt"), - text("cite"), - ], - children: [ - { - key: "items", - table: "content_block_items", - owner: { column: "block_id" }, - order: "sort_order", - columns: [ - 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"), - ], - }, - ], -}); - -/* Hosts. One row is one host, ordered, each either an organization - or a person. The CHECK on event_hosts rejects both and the blank - filter drops neither, so the only bad row that reaches SQLite is - one with both selects filled, and that comes back keyed to the - row like any other field error. - - Not parameterised the way links and blocks are: this table is - events-only, and the owner column says so. - - sort_order isn't declared. The engine writes it from the row's - position because `order` is "sort_order", which is what makes - the first row the one v_events takes the logo and colour from. */ -const hostsChild = { - key: "event_hosts", - table: "event_hosts", - owner: { column: "event_id" }, - order: "sort_order", - columns: [text("org_id"), text("person_id")], -}; - -/* ── Organizations ───────────────────────────────────────────── */ - -const organizations = { - key: "organizations", - table: "organizations", - idColumn: "id", - idKind: "slug", - concurrency: "updated_at", - - list: { - columns: [ - "id", - "kind", - "name", - "short_name", - "locality", - "state_code", - "is_published", - "is_listed", - "sort_order", - "updated_at", - ], - filters: ["kind", "is_published", "is_listed"], - search: ["name", "id", "locality"], - order: "kind, sort_order, name", - }, - - columns: [ - enumeration("kind", ["national", "region", "chapter", "partner"], { - required: true, - }), - text("name", { required: true }), - text("short_name"), - text("tagline"), - text("color"), - text("logo"), - ...placeColumns, - bool("is_published"), - bool("is_listed"), - int("sort_order"), - bool("in_timeline"), - ], - - extensions: [ - timelineExtension("organization"), - { - key: "region", - table: "regions", - idColumn: "id", - when: { column: "kind", value: "region" }, - columns: [ - enumeration("scope", ["domestic", "international", "virtual"], { - required: true, - }), - text("map_note"), - ], - }, - { - key: "chapter", - table: "chapters", - idColumn: "id", - when: { column: "kind", value: "chapter" }, - columns: [text("region_id"), text("meets"), text("started")], - }, - ], - - children: [ - linksChild("organization"), - blocksChild("organization"), - { - key: "region_areas", - table: "region_areas", - owner: { column: "region_id" }, - when: { column: "kind", value: "region" }, - order: "area_code", - columns: [ - text("area_code", { required: true }), - real("share"), - enumeration("edge", ["top", "bottom"]), - text("note"), - ], - }, - ], -}; - -/* ── Events ──────────────────────────────────────────────────── */ - -/* Column suffixes for the series weekday flags, Sunday first to - match Date#getDay. */ -const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; - -const events = { - key: "events", - table: "events", - idColumn: "id", - idKind: "slug", - concurrency: "updated_at", - - list: { - columns: [ - "id", - "title", - "scope_id", - "event_type", - "date_label", - "starts_on", - "status", - "is_published", - "is_listed", - "updated_at", - ], - // No host filter: hosts are rows in another table now, and the - // engine's filters are columns on this one. The events a host - // owns are on that host's own page. - filters: ["scope_id", "event_type", "status", "is_published", "is_listed"], - search: ["title", "id", "theme"], - order: "starts_on IS NULL, starts_on DESC, title", - }, - - columns: [ - text("scope_id", { required: true }), - - // What kind of gathering, as against scope_id's whose gathering - // it is. Declared required even though the column has a - // DEFAULT: every select renders a blank first option, so without - // it a new event files itself as a retreat while nobody is - // looking. An existing row always loads with its value set, so - // this only ever asks on create. - enumeration( - "event_type", - ["retreat", "class", "workshop", "meeting", "other"], - { required: true }, - ), - - text("title", { required: true }), - text("theme"), - text("tagline"), - date("starts_on"), - date("ends_on"), - text("date_label"), - enumeration("status", ["upcoming", "past", "cancelled"]), - ...placeColumns, - text("org_logo"), - text("event_logo"), - text("color"), - text("gradient"), - text("card_image"), - bool("is_published"), - bool("is_listed"), - bool("in_timeline"), - - // A repeating schedule. Columns rather than a side table: the - // schedule is always exactly one per event, and the public view - // is SELECT e.*, so it reaches the site with no join. Ignored - // while is_series is 0. The events table in the schema says - // what each means. - bool("is_series"), - enumeration("series_frequency", ["weekly", "monthly_date", "monthly_weekday"]), - int("series_interval"), - ...SERIES_WEEKDAYS.map((day) => bool(`series_${day}`)), - time("series_start_time"), - time("series_end_time"), - int("series_count"), - ], - - extensions: [timelineExtension("event")], - - children: [ - hostsChild, - linksChild("event"), - blocksChild("event"), - { - key: "event_people", - table: "event_people", - owner: { column: "event_id" }, - order: "sort_order", - columns: [ - text("person_id", { required: true }), - enumeration( - "role", - [ - "speaker", - "leader", - "facilitator", - "host", - "musician", - "volunteer", - "attendee", - ], - { required: true }, - ), - text("title"), - bool("is_public"), - ], - }, - ], -}; - -/* ── People ──────────────────────────────────────────────────── */ - -const people = { - key: "people", - table: "people", - idColumn: "id", - idKind: "slug", - concurrency: "updated_at", - - list: { - columns: [ - "id", - "display_name", - "sort_name", - "tagline", - "locality", - "is_published", - "is_listed", - "updated_at", - ], - filters: ["is_published", "is_listed"], - search: ["display_name", "sort_name", "id"], - order: "sort_name, display_name", - }, - - columns: [ - text("display_name", { required: true }), - text("sort_name"), - text("pronouns"), - text("tagline"), - text("photo"), - text("bio"), - text("primary_org_id"), - text("public_email"), - text("public_phone"), - text("locality"), - text("state_code"), - text("country"), - text("location_label"), - bool("is_published"), - bool("is_listed"), - ], - - extensions: [ - { - key: "private", - table: "person_private", - idColumn: "person_id", - touch: true, // has its own updated_at with no trigger behind it - columns: [ - date("birth_date"), - text("private_email"), - text("private_phone"), - text("address"), - text("notes"), - ], - }, - ], - - children: [ - linksChild("person"), - blocksChild("person"), - { - key: "affiliations", - table: "affiliations", - owner: { column: "person_id" }, - - // sort_order is where this person sits on that team, so it - // belongs to the team's editor. reindex: false stops this - // form renumbering by row position; declaring the column - // keeps the team's value intact across a save here. - reindex: false, - order: "org_id, team_id, sort_order", - - columns: [ - text("org_id", { required: true }), - text("team_id"), - ...affiliationRole, - int("sort_order"), - ], - }, - { - key: "person_awards", - table: "person_awards", - owner: { column: "person_id" }, - order: "awarded_on", - columns: [ - text("award_id", { required: true }), - text("event_id"), - date("awarded_on"), - text("citation"), - bool("is_public"), - ], - }, - ], -}; - -/* ── Teams ───────────────────────────────────────────────────── */ - -// A team belongs to exactly one organization, and affiliations -// point at the pair (team_id, org_id) rather than the team alone. -// Two consequences the form has to live with: -// -// · org_id cannot be changed once anyone is filed under the -// team. The composite foreign key has no ON UPDATE CASCADE, so -// SQLite aborts the UPDATE. That surfaces as a constraint -// error, which is the correct answer: reassign the members -// first. -// -// · deleting a team with members fails the same way, rather than -// quietly detaching them. Emptying the members list first is -// now something the form can do. -const teams = { - key: "teams", - table: "teams", - idColumn: "id", - idKind: "slug", - concurrency: "updated_at", - - list: { - columns: ["id", "org_id", "name", "tagline", "is_published", "is_listed", "sort_order", "updated_at"], - filters: ["org_id", "is_published", "is_listed"], - search: ["name", "id", "tagline"], - order: "org_id, sort_order, name", - }, - - columns: [ - text("org_id", { required: true }), - text("name", { required: true }), - text("tagline"), - text("color"), - text("logo"), - bool("is_published"), - bool("is_listed"), - int("sort_order"), - ], - - children: [ - // 'team' is already a valid owner_kind in both polymorphic - // tables, and teams_cleanup drops the rows on delete, so a team - // page comes free. - linksChild("team"), - blocksChild("team"), - { - key: "members", - table: "affiliations", - - // org_id is inherited from the team rather than asked for: - // the composite foreign key (team_id, org_id) means a member - // of this team can only belong to this team's organization, - // so a second dropdown could only ever be wrong. - owner: { column: "team_id", inherit: { org_id: "org_id" } }, - - // Row position is the order they appear on the public site. - // This is the only editor that writes it. - order: "sort_order", - - columns: [text("person_id", { required: true }), ...affiliationRole], - }, - ], -}; - -/* ── Awards ──────────────────────────────────────────────────── */ - -// org_id is who gives the award. Nullable, because -// an award can predate any decision about which organization owns -// it, and because person_awards rows must survive the awarding -// org being deleted. -// -// No children: 'award' is not in the owner_kind CHECK on -// content_blocks or links. If awards ever need a page of their -// own, that CHECK is a table rebuild, so decide before adding one -// rather than after. -const awards = { - key: "awards", - table: "awards", - idColumn: "id", - idKind: "slug", - - list: { - columns: ["id", "org_id", "name", "description", "is_published", "is_listed", "sort_order"], - filters: ["org_id", "is_published", "is_listed"], - search: ["name", "id", "description"], - order: "org_id, sort_order, name", - }, - - columns: [ - text("org_id"), - text("name", { required: true }), - text("description"), - text("logo"), - bool("is_published"), - bool("is_listed"), - int("sort_order"), - ], -}; - -/* ── Timeline ────────────────────────────────────────────────── */ - -// The history page's spine, and the only entity whose id the table -// assigns. There is nothing to slug: an entry referencing an event has -// no name of its own, and one gets created every time somebody ticks a -// checkbox. idKind "auto" is what lets createRow skip the id entirely. -// -// ref_kind and ref_id are writable here and only here. The extension on -// events and organizations owns those two columns for rows it created, -// which is why they aren't in timelineFields. -// -// Deleting an entry takes its people with it (ON DELETE CASCADE) and -// nothing points at an entry, so the delete-and-reinsert child engine -// is safe on this one. -const timeline = { - key: "timeline", - table: "timeline_entries", - idColumn: "id", - idKind: "auto", - concurrency: "updated_at", - - list: { - columns: [ - "id", - "kind", - "ref_kind", - "ref_id", - "occurred_on", - "title", - "is_featured", - "is_published", - "updated_at", - ], - filters: ["kind", "ref_kind", "is_featured", "is_published"], - search: ["title", "blurb", "meta", "ref_id"], - // Undated entries sort last rather than first, so a missing date - // reads as something to fix instead of something to scroll past. - order: "occurred_on IS NULL, occurred_on DESC, sort_order", - }, - - columns: [ - enumeration( - "kind", - ["milestone", "event", "organization", "award", "people"], - { required: true }, - ), - enumeration("ref_kind", ["event", "organization", "award", "person", "team"]), - text("ref_id"), - ...timelineFields, - ], - - children: [ - { - key: "people", - table: "timeline_entry_people", - owner: { column: "entry_id" }, - order: "sort_order", - columns: [text("person_id", { required: true }), text("note")], - }, - ], -}; - -/* ── Front page ────────────────────────────────────────────────── - - A singleton: one row, id 'home', seeded by the schema and never - created by the admin. `singleton` tells the engine to refuse create - and delete, and the CHECK on front_page.id is what makes a second - row impossible even without it. - - Every collection here is owned by page_id and replaced wholesale. - That is safe for the same reason it is for links and blocks - (nothing has a foreign key into these tables), and paths carry - their actions as a nested collection, the shape content blocks - and their items already use. */ - -const frontPage = { - key: "front_page", - table: "front_page", - idColumn: "id", - idKind: "slug", - singleton: "home", - concurrency: "updated_at", - - list: { - columns: ["id", "headline", "hero_backdrop", "hero_feature", "updated_at"], - filters: [], - search: [], - order: "id", - }, - - columns: [ - enumeration("hero_backdrop", ["brand", "photos"]), - enumeration("hero_feature", ["none", "livestream", "video", "event"]), - text("hero_event_id"), - text("eyebrow"), - text("headline"), - text("subhead"), - text("primary_label"), - text("primary_url"), - text("secondary_label"), - text("secondary_url"), - int("slide_seconds"), - text("livestream_url"), - text("livestream_title"), - text("video_url"), - text("video_title"), - text("countdown_event_id"), - text("countdown_scope_id"), - enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]), - ], - - children: [ - { - key: "slides", - table: "front_page_slides", - owner: { column: "page_id" }, - order: "sort_order", - columns: [ - text("media", { required: true }), - text("alt"), - text("caption"), - text("link_url"), - ], - }, - { - key: "sections", - table: "front_page_sections", - owner: { column: "page_id" }, - order: "sort_order", - columns: [ - enumeration( - "section", - ["countdown", "retreats", "calendar", "stats", "timeline", "connect", "featured"], - { required: true }, - ), - text("title"), - text("blurb"), - bool("is_hidden"), - ], - }, - { - key: "stats", - table: "front_page_stats", - owner: { column: "page_id" }, - order: "sort_order", - columns: [ - text("label", { required: true }), - enumeration("source", [ - "manual", - "years_since", - "regions", - "chapters", - "partners", - "events_held", - "retreats_held", - "people", - "awards_given", - ]), - text("value"), - text("suffix"), - text("note"), - ], - }, - featuredCardsChild("front_page"), - { - key: "paths", - table: "front_page_paths", - owner: { column: "page_id" }, - order: "sort_order", - columns: [text("label", { required: true }), text("icon"), text("blurb")], - children: [ - { - key: "actions", - table: "front_page_path_actions", - owner: { column: "path_id" }, - order: "sort_order", - columns: [ - text("label", { required: true }), - text("description"), - text("url", { required: true }), - ], - }, - ], - }, - ], -}; - -/* ── Blog (031_blog.sql) ───────────────────────────────────────── - - Posts of our own, with a content-block body and people as - authors, and the Community page's blog section, a singleton like - the front page. The section's community posts are featured cards - owned by 'community_page'. ─────────────────────────────────── */ - -const blogPosts = { - key: "blog_posts", - table: "blog_posts", - idColumn: "id", - idKind: "slug", - concurrency: "updated_at", - - list: { - columns: ["id", "title", "published_on", "tags", "is_published", "is_listed", "updated_at"], - filters: ["is_published", "is_listed"], - search: ["title", "id", "tags"], - order: "published_on IS NULL, published_on DESC, title", - }, - - columns: [ - text("title", { required: true }), - text("excerpt"), - text("cover_image"), - date("published_on"), - text("tags"), - text("guest_author"), - text("guest_photo"), - bool("is_published"), - bool("is_listed"), - ], - - children: [ - { - key: "authors", - table: "blog_post_authors", - owner: { column: "post_id" }, - order: "sort_order", - columns: [text("person_id", { required: true })], - }, - blocksChild("blog_post"), - ], -}; - -const communityPage = { - key: "community_page", - table: "community_page", - idColumn: "id", - idKind: "slug", - singleton: "community", - concurrency: "updated_at", - - list: { - columns: ["id", "blog_title", "updated_at"], - filters: [], - search: [], - order: "id", - }, - - columns: [ - text("blog_title"), - text("blog_blurb"), - text("internal_title"), - int("internal_slots"), - text("external_title"), - int("external_slots"), - text("external_url"), - text("external_label"), - ], - - children: [ - { - key: "pinned_posts", - table: "community_page_pinned_posts", - owner: { column: "page_id" }, - order: "sort_order", - columns: [text("post_id", { required: true })], - }, - featuredCardsChild("community_page"), - { - key: "feeds", - table: "community_page_feeds", - owner: { column: "page_id" }, - order: "sort_order", - columns: [text("url", { required: true }), text("label")], - }, - ], -}; - -/* ── 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")], - }, - ], -}; +import { organizations } from "./admin-schema/organizations.js"; +import { events } from "./admin-schema/events.js"; +import { people } from "./admin-schema/people.js"; +import { teams } from "./admin-schema/teams.js"; +import { awards } from "./admin-schema/awards.js"; +import { timeline } from "./admin-schema/timeline.js"; +import { frontPage } from "./admin-schema/frontPage.js"; +import { blogPosts, communityPage } from "./admin-schema/blog.js"; +import { siteSettings } from "./admin-schema/siteSettings.js"; export const ENTITIES = { organizations, diff --git a/server/src/admin-schema/awards.js b/server/src/admin-schema/awards.js new file mode 100644 index 0000000..1643124 --- /dev/null +++ b/server/src/admin-schema/awards.js @@ -0,0 +1,36 @@ +import { text, int, bool } from "./columns.js"; + +/* ── Awards ──────────────────────────────────────────────────── */ + +// org_id is who gives the award. Nullable, because +// an award can predate any decision about which organization owns +// it, and because person_awards rows must survive the awarding +// org being deleted. +// +// No children: 'award' is not in the owner_kind CHECK on +// content_blocks or links. If awards ever need a page of their +// own, that CHECK is a table rebuild, so decide before adding one +// rather than after. +export const awards = { + key: "awards", + table: "awards", + idColumn: "id", + idKind: "slug", + + list: { + columns: ["id", "org_id", "name", "description", "is_published", "is_listed", "sort_order"], + filters: ["org_id", "is_published", "is_listed"], + search: ["name", "id", "description"], + order: "org_id, sort_order, name", + }, + + columns: [ + text("org_id"), + text("name", { required: true }), + text("description"), + text("logo"), + bool("is_published"), + bool("is_listed"), + int("sort_order"), + ], +}; diff --git a/server/src/admin-schema/blog.js b/server/src/admin-schema/blog.js new file mode 100644 index 0000000..55f3da2 --- /dev/null +++ b/server/src/admin-schema/blog.js @@ -0,0 +1,93 @@ +import { text, url, int, bool, date, featuredCardsChild, blocksChild } from "./columns.js"; + +/* ── Blog (031_blog.sql) ───────────────────────────────────────── + + Posts of our own, with a content-block body and people as + authors, and the Community page's blog section, a singleton like + the front page. The section's community posts are featured cards + owned by 'community_page'. ─────────────────────────────────── */ + +export const blogPosts = { + key: "blog_posts", + table: "blog_posts", + idColumn: "id", + idKind: "slug", + concurrency: "updated_at", + + list: { + columns: ["id", "title", "published_on", "tags", "is_published", "is_listed", "updated_at"], + filters: ["is_published", "is_listed"], + search: ["title", "id", "tags"], + order: "published_on IS NULL, published_on DESC, title", + }, + + columns: [ + text("title", { required: true }), + text("excerpt"), + text("cover_image"), + text("cover_alt"), + bool("show_contents"), + date("published_on"), + text("tags"), + text("guest_author"), + text("guest_photo"), + bool("is_published"), + bool("is_listed"), + ], + + children: [ + { + key: "authors", + table: "blog_post_authors", + owner: { column: "post_id" }, + order: "sort_order", + columns: [text("person_id", { required: true })], + }, + blocksChild("blog_post"), + ], +}; + +export const communityPage = { + key: "community_page", + table: "community_page", + idColumn: "id", + idKind: "slug", + singleton: "community", + concurrency: "updated_at", + + list: { + columns: ["id", "blog_title", "updated_at"], + filters: [], + search: [], + order: "id", + }, + + columns: [ + text("blog_title"), + text("blog_blurb"), + text("internal_title"), + int("internal_slots"), + text("external_title"), + int("external_slots"), + url("external_url"), + text("external_label"), + ], + + children: [ + { + key: "pinned_posts", + table: "community_page_pinned_posts", + owner: { column: "page_id" }, + order: "sort_order", + columns: [text("post_id", { required: true })], + }, + featuredCardsChild("community_page"), + { + key: "feeds", + table: "community_page_feeds", + owner: { column: "page_id" }, + order: "sort_order", + columns: [url("url", { required: true }), text("label")], + }, + ], +}; diff --git a/server/src/admin-schema/columns.js b/server/src/admin-schema/columns.js new file mode 100644 index 0000000..311dd4c --- /dev/null +++ b/server/src/admin-schema/columns.js @@ -0,0 +1,202 @@ +/* Column helpers, and the field sets and child collections several + entities share. The descriptor anatomy is in ../admin-schema.js. */ + +/* ── Column helpers ──────────────────────────────────────────── */ + +export const text = (name, opts = {}) => ({ name, type: "text", ...opts }); +// Text that is a link: refuses javascript:, data: and other schemes. +export const url = (name, opts = {}) => ({ name, type: "url", ...opts }); +export const int = (name, opts = {}) => ({ name, type: "int", ...opts }); +export const real = (name, opts = {}) => ({ name, type: "real", ...opts }); +export const bool = (name, opts = {}) => ({ name, type: "bool", ...opts }); +export const date = (name, opts = {}) => ({ name, type: "date", ...opts }); +export const time = (name, opts = {}) => ({ name, type: "time", ...opts }); +export const enumeration = (name, values, opts = {}) => ({ + name, + type: "enum", + values, + ...opts, +}); + +/* Place columns shared by organizations and events, in schema order. */ +export const placeColumns = [ + text("venue"), + text("address"), + text("locality"), + text("state_code"), + text("country"), + text("location_label"), + real("latitude"), + real("longitude"), + bool("is_online"), +]; + +/* The affiliation's own fields, minus whichever end owns the row. + Both editors write the same shape so neither loses the other's + values on save. */ +export const affiliationRole = [ + text("title"), + enumeration("role", ["lead", "board", "staff", "volunteer", "member"], { + required: true, + }), + bool("is_owner"), + date("started_on"), + date("ended_on"), + bool("is_public"), +]; + +/* The editable half of a timeline entry, shared by the standalone + editor and by the in_timeline extension on events and organizations. + + occurred_on is text, not date. "2012" and "2025-07" are legitimate + values (a backfilled entry often knows the year and nothing more), + and the date coercion would reject both. `precision` is what says how + much of it to believe. */ +export const timelineFields = [ + text("occurred_on"), + enumeration("precision", ["year", "month", "day"]), + text("title"), + text("blurb"), + text("meta"), + url("link_url"), + bool("is_featured"), + bool("is_published"), + int("sort_order"), +]; + +/* The extension that the in_timeline checkbox drives. Ticked, the row + is upserted; unticked, writeExtensions deletes it. Both happen in the + parent's transaction, so the flag and the row cannot disagree. + + The conflict target is the UNIQUE (ref_kind, ref_id) constraint + on timeline_entries, which is also what stops a second save creating a + duplicate instead of updating the first. */ +export const timelineExtension = (refKind) => ({ + key: "timeline", + table: "timeline_entries", + owner: { column: "ref_id", kindColumn: "ref_kind", kindValue: refKind }, + conflict: ["ref_kind", "ref_id"], + when: { column: "in_timeline", value: 1 }, + columns: [ + // Fixed for this end: an event's entry is always an event entry. + // Declared as a default rather than a form field so the column is + // written without asking. + enumeration( + "kind", + ["milestone", "event", "organization", "award", "people"], + { default: refKind === "organization" ? "organization" : refKind }, + ), + ...timelineFields, + ], +}); + +/* Featured cards (030_featured_cards.sql): polymorphic like links, + so the Community blog can own a set too. */ +export const featuredCardsChild = (ownerKind) => ({ + key: "featured_cards", + table: "featured_cards", + owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, + order: "sort_order", + columns: [ + enumeration("kind", ["record", "link", "video"], { required: true }), + enumeration("ref_kind", ["event", "organization", "person", "team", "award"]), + text("ref_id"), + url("url"), + text("eyebrow"), + text("title"), + text("blurb"), + text("image"), + ], +}); + +/* The two polymorphic collections, parameterised by owner_kind. */ +export const linksChild = (ownerKind) => ({ + key: "links", + table: "links", + owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, + order: "sort_order", + columns: [ + enumeration("kind", ["action", "social", "website", "email"], { + required: true, + }), + text("platform"), + text("label", { required: true }), + url("url", { required: true }), + bool("is_primary"), + ], +}); + +export const blocksChild = (ownerKind) => ({ + key: "content_blocks", + table: "content_blocks", + owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, + order: "sort_order", + columns: [ + enumeration("slot", ["card", "body"], { required: true }), + enumeration( + "type", + [ + "heading", + "subheading", + "paragraph", + "list", + "links", + "quote", + "image", + "divider", + "video", + "button", + "callout", + "schedule", + ], + { required: true }, + ), + text("text"), + text("media"), + url("href"), + text("alt"), + text("cite"), + ], + children: [ + { + key: "items", + table: "content_block_items", + owner: { column: "block_id" }, + order: "sort_order", + columns: [ + text("text", { required: true }), + text("detail"), + url("url"), + // Schedule entries only (034_schedule_block.sql). + text("day"), + text("time"), + text("location"), + text("person_id"), + text("description"), + text("media"), + text("media_alt"), + text("map"), + ], + }, + ], +}); + +/* Hosts. One row is one host, ordered, each either an organization + or a person. The CHECK on event_hosts rejects both and the blank + filter drops neither, so the only bad row that reaches SQLite is + one with both selects filled, and that comes back keyed to the + row like any other field error. + + Not parameterised the way links and blocks are: this table is + events-only, and the owner column says so. + + sort_order isn't declared. The engine writes it from the row's + position because `order` is "sort_order", which is what makes + the first row the one v_events takes the logo and colour from. */ +export const hostsChild = { + key: "event_hosts", + table: "event_hosts", + owner: { column: "event_id" }, + order: "sort_order", + columns: [text("org_id"), text("person_id")], +}; diff --git a/server/src/admin-schema/events.js b/server/src/admin-schema/events.js new file mode 100644 index 0000000..6274dfb --- /dev/null +++ b/server/src/admin-schema/events.js @@ -0,0 +1,113 @@ +import { text, int, bool, date, time, enumeration, placeColumns, timelineExtension, linksChild, blocksChild, hostsChild } from "./columns.js"; + +/* ── Events ──────────────────────────────────────────────────── */ + +/* Column suffixes for the series weekday flags, Sunday first to + match Date#getDay. */ +const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; + +export const events = { + key: "events", + table: "events", + idColumn: "id", + idKind: "slug", + concurrency: "updated_at", + + list: { + columns: [ + "id", + "title", + "scope_id", + "event_type", + "date_label", + "starts_on", + "status", + "is_published", + "is_listed", + "updated_at", + ], + // No host filter: hosts are rows in another table now, and the + // engine's filters are columns on this one. The events a host + // owns are on that host's own page. + filters: ["scope_id", "event_type", "status", "is_published", "is_listed"], + search: ["title", "id", "theme"], + order: "starts_on IS NULL, starts_on DESC, title", + }, + + columns: [ + text("scope_id", { required: true }), + + // What kind of gathering, as against scope_id's whose gathering + // it is. Declared required even though the column has a + // DEFAULT: every select renders a blank first option, so without + // it a new event files itself as a retreat while nobody is + // looking. An existing row always loads with its value set, so + // this only ever asks on create. + enumeration( + "event_type", + ["retreat", "class", "workshop", "meeting", "other"], + { required: true }, + ), + + text("title", { required: true }), + text("theme"), + text("tagline"), + date("starts_on"), + date("ends_on"), + text("date_label"), + enumeration("status", ["upcoming", "past", "cancelled"]), + ...placeColumns, + text("org_logo"), + text("event_logo"), + text("color"), + text("card_image"), + bool("is_published"), + bool("is_listed"), + bool("in_timeline"), + + // A repeating schedule. Columns rather than a side table: the + // schedule is always exactly one per event, and the public view + // is SELECT e.*, so it reaches the site with no join. Ignored + // while is_series is 0. The events table in the schema says + // what each means. + bool("is_series"), + enumeration("series_frequency", ["weekly", "monthly_date", "monthly_weekday"]), + int("series_interval"), + ...SERIES_WEEKDAYS.map((day) => bool(`series_${day}`)), + time("series_start_time"), + time("series_end_time"), + int("series_count"), + ], + + extensions: [timelineExtension("event")], + + children: [ + hostsChild, + linksChild("event"), + blocksChild("event"), + { + key: "event_people", + table: "event_people", + owner: { column: "event_id" }, + order: "sort_order", + columns: [ + text("person_id", { required: true }), + enumeration( + "role", + [ + "speaker", + "leader", + "facilitator", + "host", + "musician", + "volunteer", + "attendee", + ], + { required: true }, + ), + text("title"), + bool("is_public"), + ], + }, + ], +}; diff --git a/server/src/admin-schema/frontPage.js b/server/src/admin-schema/frontPage.js new file mode 100644 index 0000000..6fe3bcd --- /dev/null +++ b/server/src/admin-schema/frontPage.js @@ -0,0 +1,126 @@ +import { text, url, int, bool, enumeration, featuredCardsChild } from "./columns.js"; + +/* ── Front page ────────────────────────────────────────────────── + + A singleton: one row, id 'home', seeded by the schema and never + created by the admin. `singleton` tells the engine to refuse create + and delete, and the CHECK on front_page.id is what makes a second + row impossible even without it. + + Every collection here is owned by page_id and replaced wholesale. + That is safe for the same reason it is for links and blocks + (nothing has a foreign key into these tables), and paths carry + their actions as a nested collection, the shape content blocks + and their items already use. */ + +export const frontPage = { + key: "front_page", + table: "front_page", + idColumn: "id", + idKind: "slug", + singleton: "home", + concurrency: "updated_at", + + list: { + columns: ["id", "headline", "hero_backdrop", "hero_feature", "updated_at"], + filters: [], + search: [], + order: "id", + }, + + columns: [ + enumeration("hero_backdrop", ["brand", "photos"]), + enumeration("hero_feature", ["none", "livestream", "video", "event"]), + text("hero_event_id"), + text("eyebrow"), + text("headline"), + text("subhead"), + text("primary_label"), + url("primary_url"), + text("secondary_label"), + url("secondary_url"), + int("slide_seconds"), + url("livestream_url"), + text("livestream_title"), + url("video_url"), + text("video_title"), + text("countdown_event_id"), + text("countdown_scope_id"), + enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]), + ], + + children: [ + { + key: "slides", + table: "front_page_slides", + owner: { column: "page_id" }, + order: "sort_order", + columns: [ + text("media", { required: true }), + text("alt"), + text("caption"), + url("link_url"), + ], + }, + { + key: "sections", + table: "front_page_sections", + owner: { column: "page_id" }, + order: "sort_order", + columns: [ + enumeration( + "section", + ["countdown", "retreats", "calendar", "stats", "timeline", "connect", "featured"], + { required: true }, + ), + text("title"), + text("blurb"), + bool("is_hidden"), + ], + }, + { + key: "stats", + table: "front_page_stats", + owner: { column: "page_id" }, + order: "sort_order", + columns: [ + text("label", { required: true }), + enumeration("source", [ + "manual", + "years_since", + "regions", + "chapters", + "partners", + "events_held", + "retreats_held", + "people", + "awards_given", + ]), + text("value"), + text("suffix"), + text("note"), + ], + }, + featuredCardsChild("front_page"), + { + key: "paths", + table: "front_page_paths", + owner: { column: "page_id" }, + order: "sort_order", + columns: [text("label", { required: true }), text("icon"), text("blurb")], + children: [ + { + key: "actions", + table: "front_page_path_actions", + owner: { column: "path_id" }, + order: "sort_order", + columns: [ + text("label", { required: true }), + text("description"), + url("url", { required: true }), + ], + }, + ], + }, + ], +}; diff --git a/server/src/admin-schema/organizations.js b/server/src/admin-schema/organizations.js new file mode 100644 index 0000000..a4059fc --- /dev/null +++ b/server/src/admin-schema/organizations.js @@ -0,0 +1,86 @@ +import { text, int, real, bool, enumeration, placeColumns, timelineExtension, linksChild, blocksChild } from "./columns.js"; + +/* ── Organizations ───────────────────────────────────────────── */ + +export const organizations = { + key: "organizations", + table: "organizations", + idColumn: "id", + idKind: "slug", + concurrency: "updated_at", + + list: { + columns: [ + "id", + "kind", + "name", + "short_name", + "locality", + "state_code", + "is_published", + "is_listed", + "sort_order", + "updated_at", + ], + filters: ["kind", "is_published", "is_listed"], + search: ["name", "id", "locality"], + order: "kind, sort_order, name", + }, + + columns: [ + enumeration("kind", ["national", "region", "chapter", "partner"], { + required: true, + }), + text("name", { required: true }), + text("short_name"), + text("tagline"), + text("color"), + text("logo"), + ...placeColumns, + bool("is_published"), + bool("is_listed"), + int("sort_order"), + bool("in_timeline"), + ], + + extensions: [ + timelineExtension("organization"), + { + key: "region", + table: "regions", + idColumn: "id", + when: { column: "kind", value: "region" }, + columns: [ + enumeration("scope", ["domestic", "international", "virtual"], { + required: true, + }), + text("map_note"), + ], + }, + { + key: "chapter", + table: "chapters", + idColumn: "id", + when: { column: "kind", value: "chapter" }, + columns: [text("region_id"), text("meets"), text("started")], + }, + ], + + children: [ + linksChild("organization"), + blocksChild("organization"), + { + key: "region_areas", + table: "region_areas", + owner: { column: "region_id" }, + when: { column: "kind", value: "region" }, + order: "area_code", + columns: [ + text("area_code", { required: true }), + real("share"), + enumeration("edge", ["top", "bottom"]), + text("note"), + ], + }, + ], +}; diff --git a/server/src/admin-schema/people.js b/server/src/admin-schema/people.js new file mode 100644 index 0000000..32cb15e --- /dev/null +++ b/server/src/admin-schema/people.js @@ -0,0 +1,99 @@ +import { text, int, bool, date, affiliationRole, linksChild, blocksChild } from "./columns.js"; + +/* ── People ──────────────────────────────────────────────────── */ + +export const people = { + key: "people", + table: "people", + idColumn: "id", + idKind: "slug", + concurrency: "updated_at", + + list: { + columns: [ + "id", + "display_name", + "sort_name", + "tagline", + "locality", + "is_published", + "is_listed", + "updated_at", + ], + filters: ["is_published", "is_listed"], + search: ["display_name", "sort_name", "id"], + order: "sort_name, display_name", + }, + + columns: [ + text("display_name", { required: true }), + text("sort_name"), + text("pronouns"), + text("tagline"), + text("photo"), + text("bio"), + text("primary_org_id"), + text("public_email"), + text("public_phone"), + text("locality"), + text("state_code"), + text("country"), + text("location_label"), + bool("is_published"), + bool("is_listed"), + ], + + extensions: [ + { + key: "private", + table: "person_private", + idColumn: "person_id", + readRole: "editor", // viewers don't see birth dates, addresses, phones + touch: true, // has its own updated_at with no trigger behind it + columns: [ + date("birth_date"), + text("private_email"), + text("private_phone"), + text("address"), + text("notes"), + ], + }, + ], + + children: [ + linksChild("person"), + blocksChild("person"), + { + key: "affiliations", + table: "affiliations", + owner: { column: "person_id" }, + + // sort_order is where this person sits on that team, so it + // belongs to the team's editor. reindex: false stops this + // form renumbering by row position; declaring the column + // keeps the team's value intact across a save here. + reindex: false, + order: "org_id, team_id, sort_order", + + columns: [ + text("org_id", { required: true }), + text("team_id"), + ...affiliationRole, + int("sort_order"), + ], + }, + { + key: "person_awards", + table: "person_awards", + owner: { column: "person_id" }, + order: "awarded_on", + columns: [ + text("award_id", { required: true }), + text("event_id"), + date("awarded_on"), + text("citation"), + bool("is_public"), + ], + }, + ], +}; diff --git a/server/src/admin-schema/siteSettings.js b/server/src/admin-schema/siteSettings.js new file mode 100644 index 0000000..2a7b86a --- /dev/null +++ b/server/src/admin-schema/siteSettings.js @@ -0,0 +1,58 @@ +import { THEME_TOKENS, checkTheme } from "../theme.js"; +import { text, enumeration } from "./columns.js"; + +/* ── 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. */ +export 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"]), + text("privacy_email"), + ], + + children: [ + { + key: "pages", + table: "site_setting_pages", + owner: { column: "settings_id" }, + order: "sort_order", + columns: [text("path", { required: true }), text("title"), text("description")], + }, + { + key: "colors", + table: "site_setting_colors", + owner: { column: "settings_id" }, + order: "sort_order", + columns: [ + enumeration("token", THEME_TOKENS, { required: true }), + text("light"), + text("dark"), + ], + }, + ], + + // Refuses a palette that would make text hard to read (theme.js). + check: checkTheme, +}; diff --git a/server/src/admin-schema/teams.js b/server/src/admin-schema/teams.js new file mode 100644 index 0000000..5e7ee4b --- /dev/null +++ b/server/src/admin-schema/teams.js @@ -0,0 +1,66 @@ +import { text, int, bool, affiliationRole, linksChild, blocksChild } from "./columns.js"; + +/* ── Teams ───────────────────────────────────────────────────── */ + +// A team belongs to exactly one organization, and affiliations +// point at the pair (team_id, org_id) rather than the team alone. +// Two consequences the form has to live with: +// +// · org_id cannot be changed once anyone is filed under the +// team. The composite foreign key has no ON UPDATE CASCADE, so +// SQLite aborts the UPDATE. That surfaces as a constraint +// error, which is the correct answer: reassign the members +// first. +// +// · deleting a team with members fails the same way, rather than +// quietly detaching them. Emptying the members list first is +// now something the form can do. +export const teams = { + key: "teams", + table: "teams", + idColumn: "id", + idKind: "slug", + concurrency: "updated_at", + + list: { + columns: ["id", "org_id", "name", "tagline", "is_published", "is_listed", "sort_order", "updated_at"], + filters: ["org_id", "is_published", "is_listed"], + search: ["name", "id", "tagline"], + order: "org_id, sort_order, name", + }, + + columns: [ + text("org_id", { required: true }), + text("name", { required: true }), + text("tagline"), + text("color"), + text("logo"), + bool("is_published"), + bool("is_listed"), + int("sort_order"), + ], + + children: [ + // 'team' is already a valid owner_kind in both polymorphic + // tables, and teams_cleanup drops the rows on delete, so a team + // page comes free. + linksChild("team"), + blocksChild("team"), + { + key: "members", + table: "affiliations", + + // org_id is inherited from the team rather than asked for: + // the composite foreign key (team_id, org_id) means a member + // of this team can only belong to this team's organization, + // so a second dropdown could only ever be wrong. + owner: { column: "team_id", inherit: { org_id: "org_id" } }, + + // Row position is the order they appear on the public site. + // This is the only editor that writes it. + order: "sort_order", + + columns: [text("person_id", { required: true }), ...affiliationRole], + }, + ], +}; diff --git a/server/src/admin-schema/timeline.js b/server/src/admin-schema/timeline.js new file mode 100644 index 0000000..9ee80e1 --- /dev/null +++ b/server/src/admin-schema/timeline.js @@ -0,0 +1,63 @@ +import { text, date, time, enumeration, timelineFields } from "./columns.js"; + +/* ── Timeline ────────────────────────────────────────────────── */ + +// The history page's spine, and the only entity whose id the table +// assigns. There is nothing to slug: an entry referencing an event has +// no name of its own, and one gets created every time somebody ticks a +// checkbox. idKind "auto" is what lets createRow skip the id entirely. +// +// ref_kind and ref_id are writable here and only here. The extension on +// events and organizations owns those two columns for rows it created, +// which is why they aren't in timelineFields. +// +// Deleting an entry takes its people with it (ON DELETE CASCADE) and +// nothing points at an entry, so the delete-and-reinsert child engine +// is safe on this one. +export const timeline = { + key: "timeline", + table: "timeline_entries", + idColumn: "id", + idKind: "auto", + concurrency: "updated_at", + + list: { + columns: [ + "id", + "kind", + "ref_kind", + "ref_id", + "occurred_on", + "title", + "is_featured", + "is_published", + "updated_at", + ], + filters: ["kind", "ref_kind", "is_featured", "is_published"], + search: ["title", "blurb", "meta", "ref_id"], + // Undated entries sort last rather than first, so a missing date + // reads as something to fix instead of something to scroll past. + order: "occurred_on IS NULL, occurred_on DESC, sort_order", + }, + + columns: [ + enumeration( + "kind", + ["milestone", "event", "organization", "award", "people"], + { required: true }, + ), + enumeration("ref_kind", ["event", "organization", "award", "person", "team"]), + text("ref_id"), + ...timelineFields, + ], + + children: [ + { + key: "people", + table: "timeline_entry_people", + owner: { column: "entry_id" }, + order: "sort_order", + columns: [text("person_id", { required: true }), text("note")], + }, + ], +}; diff --git a/server/src/auth.js b/server/src/auth.js index ca7d977..f8972e6 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -18,21 +18,29 @@ import { createHash, randomBytes, + scrypt, scryptSync, timingSafeEqual, } from "node:crypto"; +import { promisify } from "node:util"; import { getCookie, setCookie, deleteCookie } from "hono/cookie"; -export const COOKIE_NAME = "ngu_session"; - const SESSION_DAYS = 30; // Re-issue the expiry when a session is used with less than this // left, so an active person is never signed out mid-task. const REFRESH_WITHIN_DAYS = 7; +// However active, a session ends this long after sign-in. +const MAX_SESSION_DAYS = 90; // Off only for plain-http local work. Production is behind TLS. export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; +// __Host- makes the browser refuse the cookie unless it's Secure, on +// path /, with no Domain, so a sibling subdomain can't plant or +// overwrite it. Plain http (local work, COOKIE_SECURE=false) can't +// use the prefix, so it keeps the plain name. +export const COOKIE_NAME = SECURE_COOKIE ? "__Host-site_session" : "site_session"; + const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex"); /* ── Passwords ───────────────────────────────────────────────── @@ -62,7 +70,11 @@ export function hashPassword(password) { ].join("$"); } -export function verifyPassword(password, stored) { +/* Async: a login's hash runs on libuv's thread pool, so the ~100 ms it + takes doesn't stall every other request while it runs. */ +const scryptAsync = promisify(scrypt); + +export async function verifyPassword(password, stored) { if (typeof stored !== "string") return false; const [scheme, N, r, p, saltHex, keyHex] = stored.split("$"); @@ -70,7 +82,7 @@ export function verifyPassword(password, stored) { let candidate; try { - candidate = scryptSync( + candidate = await scryptAsync( password.normalize("NFKC"), Buffer.from(saltHex, "hex"), Buffer.from(keyHex, "hex").length, @@ -85,6 +97,12 @@ export function verifyPassword(password, stored) { return timingSafeEqual(candidate, expected); } +/* Text a visitor controls, made safe for one log line: control + characters (a newline would start a forged line) become "?", and + it's cut short. */ +export const logSafe = (value, max = 200) => + String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, max); + /* ── Hashing helpers ─────────────────────────────────────────── */ const sha256 = (value) => createHash("sha256").update(value).digest("hex"); @@ -95,9 +113,11 @@ export function hashIp(ip) { } export function clientIp(c) { - // Trustworthy only because this service binds to 127.0.0.1 and - // nginx is the only thing that can reach it. - return c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? null; + // The last X-Forwarded-For entry is the one nginx (or Vite in dev) + // added from the connection itself; anything before it is whatever + // the client sent. Trustworthy only because this service binds to + // 127.0.0.1 and nginx is the only thing that can reach it. + return c.req.header("x-forwarded-for")?.split(",").at(-1).trim() || null; } /* ── Sessions ────────────────────────────────────────────────── */ @@ -160,9 +180,10 @@ export function currentUser(db, c) { JOIN admin_users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.expires_at > datetime('now') + AND s.created_at > datetime('now', ?) AND u.is_active = 1`, ) - .get(tokenHash); + .get(tokenHash, `-${MAX_SESSION_DAYS} days`); if (!row) return null; diff --git a/server/src/clips.js b/server/src/clips.js index fc0a228..28f05e3 100644 --- a/server/src/clips.js +++ b/server/src/clips.js @@ -150,11 +150,16 @@ export function checkClip(input, source) { /* Runs a tool, calling onLine for each line of its output, and resolves with the tail of stderr, or rejects with it. */ -function run(command, args, { onLine } = {}) { +function run(command, args, { onLine, background = false } = {}) { return new Promise((resolve, reject) => { let child; + // An encode takes every core it can get; at the lowest priority it + // still does, but the API and its pages come first. Linux only + // (the VPS); elsewhere it runs as it is. + const [cmd, argv] = + background && process.platform === "linux" ? ["nice", ["-n", "19", command, ...args]] : [command, args]; try { - child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + child = spawn(cmd, argv, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); } catch (err) { reject(err); return; @@ -291,8 +296,9 @@ async function download(db, job) { await run( YTDLP, [ + // Our options only: no yt-dlp.conf on the box changes them. + "--ignore-config", ...cookies.args, - job.source_url, // YouTube needs a JavaScript runtime to list formats; the one // running this server will do. "--js-runtimes", @@ -319,6 +325,9 @@ async function download(db, job) { ...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []), "-o", template, + // Last, after --, so the link can never be read as an option. + "--", + job.source_url, ], { onLine: (line) => { @@ -326,8 +335,17 @@ async function download(db, job) { if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) }); const t = line.match(/^TITLE (.+)$/); if (t) title = t[1].slice(0, 300); + // Only this job's own output file counts: a video title with + // a newline in it could print a "FILE ..." line of its own. const f = line.match(/^FILE (.+)$/); - if (f) file = f[1].trim(); + const candidate = f?.[1].trim(); + if ( + candidate && + path.resolve(path.dirname(candidate)) === path.resolve(CLIPS_DIR) && + path.basename(candidate).startsWith(`source-${job.id}.`) + ) { + file = candidate; + } }, }, ); @@ -412,6 +430,7 @@ async function cut(db, job) { args.push("-progress", "pipe:1", "-nostats", filePath(name)); await run(FFMPEG, args, { + background: true, onLine: (line) => { const us = line.match(/^out_time_us=(\d+)/); if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) }); diff --git a/server/src/db.js b/server/src/db.js index d5c926c..e7c5f3d 100644 --- a/server/src/db.js +++ b/server/src/db.js @@ -2,15 +2,12 @@ DATABASE One SQLite file, opened once at boot and held for the life of - the process. Node's own sqlite module is used when it's there - (Node 24+), better-sqlite3 otherwise. Their APIs overlap enough - that everything below works against either, as long as you: + the process, through Node's own node:sqlite (Node 22.13+). + House rules: • use positional ? parameters, never named ones • pass 0/1 for booleans, never true/false - • use tx() rather than db.transaction() - - Those three rules are the whole compatibility story. + • use tx(): node:sqlite has no db.transaction() ═══════════════════════════════════════════════════════════════ */ import { readdirSync, readFileSync } from "node:fs"; @@ -20,18 +17,6 @@ import { fileURLToPath } from "node:url"; const HERE = dirname(fileURLToPath(import.meta.url)); const MIGRATIONS_DIR = join(HERE, "migrations"); -/* ── Driver selection ──────────────────────────────────────── */ - -async function loadDriver() { - try { - const { DatabaseSync } = await import("node:sqlite"); - return { Driver: DatabaseSync, name: "node:sqlite" }; - } catch { - const { default: BetterSqlite3 } = await import("better-sqlite3"); - return { Driver: BetterSqlite3, name: "better-sqlite3" }; - } -} - /* ── Open ────────────────────────────────────────────────────── WAL readers never block the writer, which matters the moment a feedback POST lands mid page-load @@ -42,15 +27,15 @@ async function loadDriver() { ───────────────────────────────────────────────────────────── */ export async function openDatabase(path) { - const { Driver, name } = await loadDriver(); - const db = new Driver(path); + const { DatabaseSync } = await import("node:sqlite"); + const db = new DatabaseSync(path); db.exec("PRAGMA journal_mode = WAL"); db.exec("PRAGMA foreign_keys = ON"); db.exec("PRAGMA synchronous = NORMAL"); db.exec("PRAGMA busy_timeout = 5000"); - db.driverName = name; + db.driverName = "node:sqlite"; return db; } diff --git a/server/src/feeds.js b/server/src/feeds.js index d5b2fb5..43f826a 100644 --- a/server/src/feeds.js +++ b/server/src/feeds.js @@ -18,7 +18,7 @@ image on the page. ═══════════════════════════════════════════════════════════════ */ -import { decodeEntities, safeGet } from "./linkPreview.js"; +import { decodeEntities, elements, innerOf, openTags, safeGet } from "./linkPreview.js"; const CACHE_MS = 30 * 60 * 1000; const MAX_FEED_BYTES = 3 * 1024 * 1024; @@ -34,24 +34,32 @@ function unwrap(text) { } /* The text inside the first …, CDATA unwrapped. Tag - names may carry a namespace prefix (content:encoded). */ + names may carry a namespace prefix (content:encoded). Scanned with + indexOf, not a regex: the feed is someone else's (see "Scanning + markup" in linkPreview.js). */ function inner(xml, tag) { - const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)`, "i")); - return match ? unwrap(match[1]) : null; + const text = innerOf(xml, tag); + return text == null ? null : unwrap(text); } function attrOf(xml, tag, name, where = () => true) { - for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) { - const el = match[0]; + for (const el of openTags(xml, tag, 50)) { const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i")); if (value && where(el)) return value[2] ?? value[3]; } return null; } +// Enough of a body or summary to make an excerpt from, so the tag +// strip and entity decoding never see more than this. +const PLAIN_SCAN = 20_000; + function plain(html) { if (!html) return null; - const text = decodeEntities(html.replace(/<[^>]+>/g, " ")); + // Tags stripped both before and after decoding: a description is + // often HTML written as entities (<p>). + const strip = (s) => s.replace(/<[^>]*>/g, " "); + const text = decodeEntities(strip(decodeEntities(strip(html.slice(0, PLAIN_SCAN))))); if (!text) return null; return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text; } @@ -74,21 +82,34 @@ function isoDate(raw) { } function firstImage(html) { - return html?.match(/]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null; + if (!html) return null; + for (const tag of openTags(html, "img", 20)) { + const src = tag.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1]; + if (src) return src; + } + return null; } function parseFeed(xml, feedUrl) { - const isAtom = /]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !//gi : //gi) ?? []; + // The root element is near the top; nothing needs the rest for this. + const top = xml.slice(0, 8192); + const root = openTags(top, "feed", 1)[0] ?? ""; + const isAtom = /xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(root) && openTags(top, "rss", 1).length === 0; + const tag = isAtom ? "entry" : "item"; + // The channel's own title is the one before the first item. + const firstItem = xml.toLowerCase().indexOf(`<${tag}`); + const channelTitle = decodeEntities( + inner(firstItem === -1 ? xml : xml.slice(0, firstItem), "title")?.slice(0, 1000) ?? "", + ); + const blocks = elements(xml, tag, MAX_ITEMS_PER_FEED); const items = []; - for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) { + for (const block of blocks) { const link = isAtom ? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el)) : inner(block, "link"); const url = safeUrl(link?.trim(), feedUrl); - const title = decodeEntities(inner(block, "title") ?? ""); + const title = decodeEntities(inner(block, "title")?.slice(0, 1000) ?? ""); if (!url || !title) continue; const body = inner(block, "content:encoded") ?? inner(block, "content"); @@ -123,20 +144,37 @@ async function fetchFeed(url) { return parseFeed(result.body.toString("utf8"), result.url.toString()); } +/* One fetch at a time per feed, shared by everyone who asks while it + runs. A failure keeps the last good copy and waits 5 minutes before + trying again, rather than retrying on every request. */ +function refresh(url) { + const hit = cache.get(url); + if (hit?.pending) return hit.pending; + const pending = fetchFeed(url) + .then((feed) => { + cache.set(url, { at: Date.now(), feed }); + return feed; + }) + .catch((err) => { + console.warn(`feed ${url}: ${err.message}`); + const stale = hit?.feed ?? { title: null, items: [] }; + cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale }); + return stale; + }); + cache.set(url, { ...hit, pending }); + return pending; +} + +/* A fresh copy as it is; a stale one straight away while a refresh + runs behind it, so no visitor waits on someone else's server once + the feed has been read once. Only the very first read waits. */ async function readFeed(url) { const hit = cache.get(url); - if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed; - try { - const feed = await fetchFeed(url); - cache.set(url, { at: Date.now(), feed }); - return feed; - } catch (err) { - console.warn(`feed ${url}: ${err.message}`); - // Serve the last good copy, and don't retry on every request. - const stale = hit?.feed ?? { title: null, items: [] }; - cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale }); - return stale; + if (hit?.feed) { + if (Date.now() - hit.at >= CACHE_MS) refresh(url); + return hit.feed; } + return refresh(url); } /* Every listed feed's items, newest first, each tagged with its diff --git a/server/src/index.js b/server/src/index.js index 30218c8..ed18f4f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -3,7 +3,7 @@ Binds to localhost only. nginx is the only thing that talks to it, which is what lets the routes trust X-Forwarded-For and skip - CORS entirely — in production the API and the site share an + CORS entirely, in production the API and the site share an origin, and in development Vite proxies /api so they share one there too. ═══════════════════════════════════════════════════════════════ */ @@ -13,7 +13,10 @@ import { mkdir } from "node:fs/promises"; import { serve } from "@hono/node-server"; import { serveStatic } from "@hono/node-server/serve-static"; import { Hono } from "hono"; +import { HTTPException } from "hono/http-exception"; +import { csrf } from "hono/csrf"; import { logger } from "hono/logger"; +import { secureHeaders } from "hono/secure-headers"; import { openDatabase, migrate } from "./db.js"; import { rateLimit } from "./rateLimit.js"; @@ -32,8 +35,8 @@ import adminEntities from "./routes/admin-entities.js"; import media from "./routes/media.js"; import clips from "./routes/clips.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js"; -import { UPLOADS_DIR } from "./media.js"; -import { startSessionSweeper } from "./auth.js"; +import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; +import { logSafe, startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { ENTITIES } from "./admin-schema.js"; @@ -50,12 +53,102 @@ syncDescriptorsWithSchema(db, ENTITIES); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); await mkdir(UPLOADS_DIR, { recursive: true }); console.log(`uploads ${UPLOADS_DIR}`); +// In the background: pages fall back to the full file until it's done. +writeMissingThumbs() + .then((made) => made && console.log(`uploads: made ${made} small copies`)) + .catch((err) => console.warn(`uploads: small copies failed: ${err.message}`)); /* ── App ─────────────────────────────────────────────────────── */ const app = new Hono(); -app.use("*", logger()); +// One log line per admin request, for the record of who did what. +// Public traffic is left to nginx's access log: logging every request +// here too would double the lines and, under a spike, cost the event +// loop a synchronous write each. +app.use("/api/admin/*", logger()); + +/* Headers for every response. Referrer kept to the origin (YouTube + embeds refuse to play without one). No HSTS here: nginx sends it on + everything, including the files it serves from disk + (docs/security-headers.md). + + The Content-Security-Policy is Report-Only for now: nothing is + blocked, and each thing it would have blocked is logged by + /api/csp-report (journalctl -u ngu-api). Once a while of real use + logs nothing unexpected, switch contentSecurityPolicyReportOnly to + contentSecurityPolicy. 'unsafe-inline' scripts cover the page's + window.__SITE__ and the theme script in index.html. */ +const EMBEDS = [ + "https://www.youtube-nocookie.com", + "https://www.youtube.com", + "https://www.facebook.com", + "https://player.vimeo.com", + "https://www.google.com", + "https://maps.google.com", + "https://*.churchcenter.com", + "https://*.churchcenteronline.com", +]; + +app.use( + "*", + secureHeaders({ + referrerPolicy: "strict-origin-when-cross-origin", + strictTransportSecurity: false, + contentSecurityPolicyReportOnly: { + defaultSrc: ["'self'"], + scriptSrc: ["'self'", "'unsafe-inline'", "https://js.churchcenter.com"], + styleSrc: ["'self'", "'unsafe-inline'"], + imgSrc: ["'self'", "data:", "https:"], + mediaSrc: ["'self'"], + fontSrc: ["'self'"], + connectSrc: ["'self'"], + frameSrc: EMBEDS, + frameAncestors: ["'self'"], + baseUri: ["'self'"], + formAction: ["'self'"], + objectSrc: ["'none'"], + reportUri: "/api/csp-report", + }, + }), +); + +/* What the policy above would have blocked. Browsers post these on + their own; a short line per report is plenty to go on. */ +app.use("/api/csp-report", rateLimit({ windowMs: 60_000, max: 30 })); +app.post("/api/csp-report", async (c) => { + const text = (await c.req.text()).slice(0, 4000); + try { + const report = JSON.parse(text)["csp-report"] ?? {}; + const field = (name) => logSafe(report[name] ?? "?", 150); + console.warn( + `csp ${field("violated-directive")} blocked ${field("blocked-uri")} on ${field("document-uri")}`, + ); + } catch { + // Not a report; nothing to log. + } + return c.body(null, 204); +}); + +/* Refuse a form-style write (text/plain, form or multipart body) + that another site sent, including a sibling subdomain, which + SameSite=Lax cookies don't stop. Browsers mark their own requests + Sec-Fetch-Site: same-origin; older ones fall back to Origin, judged + by host because nginx speaks plain http to this service. JSON + bodies can't be sent cross-origin without a CORS preflight, which + this API never answers. */ +app.use( + "/api/*", + csrf({ + origin: (origin, c) => { + try { + return new URL(origin).host === c.req.header("host"); + } catch { + return false; + } + }, + }), +); app.use("*", async (c, next) => { c.set("db", db); @@ -120,6 +213,9 @@ console.log(`clips ${CLIPS_DIR}`); app.notFound((c) => c.json({ error: "Not found" }, 404)); app.onError((err, c) => { + // A deliberate refusal (the CSRF check's 403, say) is an answer, + // not a crash: send it as it is and keep it out of the error log. + if (err instanceof HTTPException) return err.getResponse(); console.error(err); // Never leak internals to the browser. return c.json({ error: "Something went wrong." }, 500); @@ -139,7 +235,7 @@ const server = serve({ fetch: app.fetch, hostname: HOST, port: PORT }, (info) => for (const signal of ["SIGTERM", "SIGINT"]) { process.on(signal, () => { - console.log(`${signal} — shutting down`); + console.log(`${signal}, shutting down`); server.close(() => { try { db.close(); diff --git a/server/src/linkPreview.js b/server/src/linkPreview.js index 64e0f65..6b554da 100644 --- a/server/src/linkPreview.js +++ b/server/src/linkPreview.js @@ -34,41 +34,33 @@ import net from "node:net"; import { MAX_UPLOAD_BYTES, MediaError } from "./media.js"; const TIMEOUT_MS = 8000; +// The whole request, however steadily the bytes trickle in. +const TOTAL_TIMEOUT_MS = 15000; const MAX_REDIRECTS = 4; const MAX_HTML_BYTES = 1024 * 1024; const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)"; /* ── Address checks ────────────────────────────────────────── */ -function ipv4Blocked(ip) { - const [a, b] = ip.split(".").map(Number); - return ( - a === 0 || - a === 10 || - a === 127 || - (a === 100 && b >= 64 && b <= 127) || - (a === 169 && b === 254) || - (a === 172 && b >= 16 && b <= 31) || - (a === 192 && b === 168) || - (a === 192 && b === 0) || - (a === 198 && (b === 18 || b === 19)) || - a >= 224 - ); -} +/* Private, loopback, link-local, shared, benchmark, multicast and + reserved ranges. BlockList also judges an IPv4-mapped IPv6 address + (::ffff:7f00:1, however it's written) by the IPv4 inside it. The + IPv6 ranges that embed an IPv4 some other way (NAT64, 6to4, the + old compatible form) are refused outright. */ +const BLOCKED = new net.BlockList(); +for (const [ip, bits] of [ + ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], + ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], + ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24], + ["224.0.0.0", 3], +]) BLOCKED.addSubnet(ip, bits, "ipv4"); +for (const [ip, bits] of [ + ["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16], + ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8], ["2001:db8::", 32], +]) BLOCKED.addSubnet(ip, bits, "ipv6"); function ipBlocked(ip) { - if (net.isIPv4(ip)) return ipv4Blocked(ip); - const lower = ip.toLowerCase(); - // An IPv4 address written as IPv6 is judged as the IPv4 it is. - const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); - if (mapped) return ipv4Blocked(mapped[1]); - return ( - lower === "::" || - lower === "::1" || - /^f[cd]/.test(lower) || // fc00::/7 unique local - /^fe[89ab]/.test(lower) || // fe80::/10 link-local - /^ff/.test(lower) // multicast - ); + return BLOCKED.check(ip, net.isIPv4(ip) ? "ipv4" : "ipv6"); } async function vet(raw) { @@ -157,6 +149,14 @@ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) { }, ); req.on("timeout", () => req.destroy(new MediaError(504, "The site took too long to answer."))); + // `timeout` above only fires when the socket goes quiet; a server + // sending a byte every few seconds would hold the request open + // for hours. This caps the whole exchange. + const deadline = setTimeout( + () => req.destroy(new MediaError(504, "The site took too long to answer.")), + TOTAL_TIMEOUT_MS, + ); + req.on("close", () => clearTimeout(deadline)); req.on("error", (err) => reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")), ); @@ -180,15 +180,82 @@ export async function safeGet(raw, options) { const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }; +// A code point past U+10FFFF would make fromCodePoint throw. +const codePoint = (n) => String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd); + export function decodeEntities(text) { return text - .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16))) - .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))) + .replace(/&#x([0-9a-f]{1,6});/gi, (_, hex) => codePoint(parseInt(hex, 16))) + .replace(/&#(\d{1,7});/g, (_, dec) => codePoint(Number(dec))) .replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole) .replace(/\s+/g, " ") .trim(); } +/* ── Scanning markup ─────────────────────────────────────────── + Pages and feeds come from other people's servers, so nothing here + runs a regex over the whole document: a pattern like + /]*>/ restarts at every "", "/", " ", "\t", "\n", "\r"]); + +/* Where the next ) starts, or -1. */ +function tagStart(lower, name, from) { + for (let i = from; ; ) { + const at = lower.indexOf(name, i); + if (at === -1 || TAG_END.has(lower[at + name.length] ?? "")) return at; + i = at + name.length; + } +} + +/* Each opening in text, up to `limit` of them. */ +export function openTags(text, tag, limit = 200) { + const lower = text.toLowerCase(); + const name = `<${tag.toLowerCase()}`; + const out = []; + for (let i = 0; out.length < limit; ) { + const start = tagStart(lower, name, i); + if (start === -1) break; + const end = lower.indexOf(">", start); + if (end === -1) break; + out.push(text.slice(start, end + 1)); + i = end + 1; + } + return out; +} + +/* Each whole … in text, up to `limit` of them. */ +export function elements(text, tag, limit) { + const lower = text.toLowerCase(); + const name = `<${tag.toLowerCase()}`; + const close = ``; + const out = []; + for (let i = 0; out.length < limit; ) { + const start = tagStart(lower, name, i); + if (start === -1) break; + const end = lower.indexOf(close, start); + if (end === -1) break; + out.push(text.slice(start, end + close.length)); + i = end + close.length; + } + return out; +} + +/* What's between the first and its , or null. */ +export function innerOf(text, tag) { + const lower = text.toLowerCase(); + const start = tagStart(lower, `<${tag.toLowerCase()}`, 0); + if (start === -1) return null; + const open = lower.indexOf(">", start); + if (open === -1) return null; + const end = lower.indexOf(``, open); + return end === -1 ? null : text.slice(open + 1, end); +} + function attr(tag, name) { const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i")); return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null; @@ -196,12 +263,12 @@ function attr(tag, name) { function readMeta(html) { const meta = {}; - for (const tag of html.match(/]*>/gi) ?? []) { + for (const tag of openTags(html, "meta")) { const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase(); const content = attr(tag, "content"); - if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content); + if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content.slice(0, 2000)); } - const title = html.match(/]*>([\s\S]*?)<\/title>/i)?.[1]; + const title = innerOf(html, "title")?.slice(0, 1000); return { title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null, description: diff --git a/server/src/media.js b/server/src/media.js index 7427770..d7580f2 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -63,6 +63,10 @@ export const KEEP_MAX_BYTES = 10 * MB; /* Longest side after processing, in pixels. Wide enough for a full-bleed hero on a large screen. */ +// About 60 megapixels (eg. 9000 x 6700): past any camera an editor +// uses, and it stops one giant image eating the VPS's memory while +// it's decoded. sharp's own default is 268 MP. +const MAX_INPUT_PIXELS = 60_000_000; const MAX_EDGE = 2400; const WEBP_QUALITY = 82; @@ -141,7 +145,7 @@ export async function store(buf, { keepOriginal = false } = {}) { try { if (convert) { // animated keeps every frame of a GIF or an animated WebP. - const { data, info } = await sharp(buf, { animated: true }) + const { data, info } = await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS }) .rotate() .resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true }) .webp({ quality: WEBP_QUALITY }) @@ -152,7 +156,7 @@ export async function store(buf, { keepOriginal = false } = {}) { // An animated image reports the whole strip's height. height = info.pageHeight ?? info.height; } else if (kind !== "svg") { - const meta = await sharp(buf).metadata(); + const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; height = meta.pageHeight ?? meta.height ?? null; } @@ -168,6 +172,7 @@ export async function store(buf, { keepOriginal = false } = {}) { const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`); await writeFile(tmp, out); await rename(tmp, path.join(UPLOADS_DIR, filename)); + if (kind !== "svg") await writeThumb(filename, out); return { filename, @@ -179,16 +184,72 @@ export async function store(buf, { keepOriginal = false } = {}) { }; } -/* Deletes one stored file. A file that's already gone is not an - error: the row is what's being removed. */ +/* ── Small copies ────────────────────────────────────────────── + Beside every raster upload, -640.webp: the same image at most + 640px on its longer side. Photos and logos shown small (avatars, + cards, marks) load it instead of the full file; the page falls back + to the full file if it's missing (src/lib/media.ts, mediaThumb). + Made when a file is uploaded, and at boot for any upload that + doesn't have one yet (files from before this, or copied in by hand). + ───────────────────────────────────────────────────────────── */ + +export const THUMB_EDGE = 640; +const THUMB = /-640\.webp$/; + +export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.webp`; + +async function writeThumb(filename, buf) { + const name = thumbName(filename); + const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`); + try { + await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS }) + .rotate() + .resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true }) + .webp({ quality: WEBP_QUALITY }) + .toFile(tmp); + await rename(tmp, path.join(UPLOADS_DIR, name)); + } catch (err) { + // The full file is what matters; without a copy the page uses it. + await unlink(tmp).catch(() => {}); + console.warn(`media: no small copy of ${filename}: ${err.message}`); + } +} + +/* Makes the small copy for every raster upload that lacks one. + Returns how many it made. */ +export async function writeMissingThumbs() { + let names; + try { + names = await readdir(UPLOADS_DIR); + } catch (err) { + if (err.code === "ENOENT") return 0; + throw err; + } + const present = new Set(names); + let made = 0; + for (const name of names) { + if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue; + if (present.has(thumbName(name))) continue; + const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null); + if (!buf || !sniff(buf) || sniff(buf) === "svg") continue; + await writeThumb(name, buf); + made += 1; + } + return made; +} + +/* Deletes one stored file and its small copy. A file that's already + gone is not an error: the row is what's being removed. */ export async function remove(filename) { // filename comes from our own table, but it's joined onto a // directory, so refuse anything that isn't a bare name. if (path.basename(filename) !== filename) return; - try { - await unlink(path.join(UPLOADS_DIR, filename)); - } catch (err) { - if (err.code !== "ENOENT") throw err; + for (const name of [filename, thumbName(filename)]) { + try { + await unlink(path.join(UPLOADS_DIR, name)); + } catch (err) { + if (err.code !== "ENOENT") throw err; + } } } @@ -209,7 +270,7 @@ async function describe(filename) { let height = null; if (kind !== "svg") { try { - const meta = await sharp(buf).metadata(); + const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; height = meta.pageHeight ?? meta.height ?? null; } catch { @@ -248,7 +309,7 @@ export async function registerLooseFiles(db) { let added = 0; for (const name of names) { - if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue; + if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue; let row; try { row = await describe(name); diff --git a/server/src/migrations/023_schema.sql b/server/src/migrations/023_schema.sql index 71e0565..56dbee4 100644 --- a/server/src/migrations/023_schema.sql +++ b/server/src/migrations/023_schema.sql @@ -180,7 +180,7 @@ CREATE TABLE event_scopes ( -- an every-other-week series is "on", which day -- of the month a monthly one keeps, and the -- weekday used when none is ticked --- ends_on when set, the last day it can meet — which +-- ends_on when set, the last day it can meet, which -- also keeps effective_status right -- series_count when set, stops it after that many meetings, -- whichever comes first @@ -297,7 +297,7 @@ CREATE UNIQUE INDEX event_hosts_person_uniq -- -- Public by design. Everything in this table can appear on a card, -- and is_published = 0 is the only thing between a row and the open --- web — hence the default of 0, unlike organizations. Anything that +-- web, hence the default of 0, unlike organizations. Anything that -- must never be served lives in person_private, so a careless -- SELECT * can't leak it. Bios and pages go in content_blocks, -- socials in links. People sort by sort_name; there is no @@ -306,7 +306,7 @@ CREATE UNIQUE INDEX event_hosts_person_uniq CREATE TABLE people ( id TEXT PRIMARY KEY, -- slug: 'jane-doe' display_name TEXT NOT NULL, -- 'Jane Doe' - sort_name TEXT, -- 'Doe, Jane' — list ordering + sort_name TEXT, -- 'Doe, Jane', list ordering pronouns TEXT, -- 'she/her' tagline TEXT, -- fallback when no title applies photo TEXT, -- filename in public/people/ @@ -346,7 +346,7 @@ CREATE TABLE person_private ( -- A team belongs to exactly one organization: NGU national has a -- Board and a Leadership Team, a region or chapter can have its own. -- UNIQUE (id, org_id) looks redundant against the primary key, and --- is — except that it gives affiliations a composite foreign key to +-- is, except that it gives affiliations a composite foreign key to -- point at, which stops someone filing a person under a team -- belonging to a different organization. CREATE TABLE teams ( @@ -548,7 +548,7 @@ CREATE TABLE timeline_entries ( -- Null inherits from the referenced row: an event's starts_on. A -- hand-authored entry has to supply its own, which the descriptor - -- can't require conditionally — the read layer reports an entry + -- can't require conditionally, the read layer reports an entry -- with neither rather than the table refusing it. occurred_on TEXT, @@ -604,9 +604,9 @@ CREATE INDEX timeline_entry_people_person_idx -- FRONT PAGE -- ═══════════════════════════════════════════════════════════════ -- --- The home page's editable half. One row in front_page — the CHECK +-- The home page's editable half. One row in front_page, the CHECK -- on id makes a second one impossible, and the admin engine treats --- it as a singleton — and ordered collections hanging off it, each +-- it as a singleton, and ordered collections hanging off it, each -- replaced wholesale on save. Nothing has a foreign key into them, -- which is what makes that safe. -- @@ -759,7 +759,7 @@ CREATE TABLE admin_users ( -- password at all. A row with both can use either route in. password_hash TEXT, - -- Google's stable subject id. Nullable, unique when present — + -- Google's stable subject id. Nullable, unique when present, -- SQLite allows any number of NULLs in a unique index. google_sub TEXT UNIQUE, @@ -935,7 +935,7 @@ SELECT tm.name AS team_name, -- Whether the referenced record is itself visible. An entry must not - -- outlive the thing it points at being unpublished — a draft event + -- outlive the thing it points at being unpublished, a draft event -- would otherwise leak its title and date onto a public page. Null -- for a standalone milestone, which answers to nothing but its own -- is_published. @@ -964,7 +964,7 @@ LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.re -- ═══════════════════════════════════════════════════════════════ -- -- What a new database needs before anyone signs in: the scopes an --- event can be filed under, and the front page as it ships — every +-- event can be filed under, and the front page as it ships, every -- section, the stats that need no typing, and the Church Center -- forms sorted into paths. Everything else comes in through the -- admin. diff --git a/server/src/migrations/037_leadership_published_orgs.sql b/server/src/migrations/037_leadership_published_orgs.sql new file mode 100644 index 0000000..cd3a3cf --- /dev/null +++ b/server/src/migrations/037_leadership_published_orgs.sql @@ -0,0 +1,39 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 037 LEADERSHIP VIEW: PUBLISHED HOME ORGS ONLY +-- +-- v_org_leadership named a person's primary organization even when +-- that organization was unpublished, so a draft org's name could +-- show on a public leadership list. It now joins published ones +-- only; an unpublished one reads as no primary org. +-- ═══════════════════════════════════════════════════════════════ + +DROP VIEW v_org_leadership; + +CREATE VIEW v_org_leadership AS +SELECT + a.org_id, + a.team_id, + t.name AS team_name, + t.sort_order AS team_sort_order, + a.person_id, + a.title, + a.role, + a.is_owner, + a.sort_order, + p.display_name, + p.sort_name, + p.pronouns, + p.tagline, + p.photo, + p.public_email, + p.location_label, + p.bio, + o.id AS primary_org_id, + o.name AS primary_org_name +FROM affiliations a +JOIN people p ON p.id = a.person_id AND p.is_published = 1 +LEFT JOIN teams t ON t.id = a.team_id +LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1 +WHERE a.is_public = 1 + AND a.ended_on IS NULL +ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name; diff --git a/server/src/migrations/038_image_alt_text.sql b/server/src/migrations/038_image_alt_text.sql new file mode 100644 index 0000000..cff6a0d --- /dev/null +++ b/server/src/migrations/038_image_alt_text.sql @@ -0,0 +1,13 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 038 ALT TEXT FOR BLOG COVERS AND SCHEDULE GRAPHICS +-- +-- Both images can carry information (a flyer, a site map, a cover +-- photo that sets the scene), so each gets its own description for +-- screen readers. Blank means decorative: the image is skipped. +-- +-- blog_posts.cover_alt the cover image's description +-- content_block_items.media_alt a schedule entry graphic's +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE blog_posts ADD COLUMN cover_alt TEXT; +ALTER TABLE content_block_items ADD COLUMN media_alt TEXT; diff --git a/server/src/migrations/039_privacy_contact.sql b/server/src/migrations/039_privacy_contact.sql new file mode 100644 index 0000000..4e37428 --- /dev/null +++ b/server/src/migrations/039_privacy_contact.sql @@ -0,0 +1,11 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 039 PRIVACY CONTACT +-- +-- The address the Privacy page gives for privacy questions and data +-- requests (Panel → Site settings). Null falls back to site.json's +-- privacyEmail; blank in both, the page points to its request form +-- only. Data requests themselves are feedback rows of type +-- 'privacy' (routes/feedback.js), triaged in Admin → Feedback. +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE site_settings ADD COLUMN privacy_email TEXT; diff --git a/server/src/migrations/040_drop_event_gradient.sql b/server/src/migrations/040_drop_event_gradient.sql new file mode 100644 index 0000000..3282ab1 --- /dev/null +++ b/server/src/migrations/040_drop_event_gradient.sql @@ -0,0 +1,12 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 040 NO MORE CARD GRADIENTS +-- +-- An event card is its photo (card_image) under a light veil, or a +-- plain card, always with the event's colour as its border. The +-- gradient layer went over the photo and hid it, and gradients are +-- leaving the design, so the column goes. Any gradient saved on an +-- event is dropped with it; the card falls back to its photo or the +-- plain surface. +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE events DROP COLUMN gradient; diff --git a/server/src/migrations/041_site_colors.sql b/server/src/migrations/041_site_colors.sql new file mode 100644 index 0000000..30cc48f --- /dev/null +++ b/server/src/migrations/041_site_colors.sql @@ -0,0 +1,28 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 041 SITE COLOURS +-- +-- The admin's palette (Panel → Site settings → Colours): one row per +-- colour token that differs from the site's own (src/index.css), with +-- a light and a dark value. Blank keeps that mode's default. The +-- server writes them into every page (server/src/theme.js) and +-- refuses a save that would make text hard to read. +-- +-- token one of the tokens in THEME_DEFAULTS (theme.js), which +-- the admin's dropdown offers +-- light '#rrggbb', or null for the default +-- dark '#rrggbb', or null for the default +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE site_setting_colors ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + token TEXT NOT NULL CHECK (token IN ( + 'ink', 'body', 'muted', 'link', 'brand', 'action', 'action-hover', + 'surface', 'tint', 'tint-soft', 'danger', 'danger-tint')), + light TEXT CONSTRAINT "A colour must be written #rrggbb, eg. #0f7183." + CHECK (light IS NULL OR (length(light) = 7 AND light GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')), + dark TEXT CONSTRAINT "A dark colour must be written #rrggbb, eg. #5ccbdc." + CHECK (dark IS NULL OR (length(dark) = 7 AND dark GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')), + UNIQUE (settings_id, token) +) STRICT; diff --git a/server/src/migrations/042_person_awards_index.sql b/server/src/migrations/042_person_awards_index.sql new file mode 100644 index 0000000..2c8b10d --- /dev/null +++ b/server/src/migrations/042_person_awards_index.sql @@ -0,0 +1,10 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 042 AWARD RECIPIENTS BY AWARD +-- +-- person_awards is read by award (an award's page lists its +-- recipients, an organization counts them), but its only index +-- starts with person_id, so those reads scan the table. Tiny today; +-- this keeps it from mattering later. +-- ═══════════════════════════════════════════════════════════════ + +CREATE INDEX person_awards_award_idx ON person_awards (award_id); diff --git a/server/src/migrations/043_blog_contents.sql b/server/src/migrations/043_blog_contents.sql new file mode 100644 index 0000000..2064521 --- /dev/null +++ b/server/src/migrations/043_blog_contents.sql @@ -0,0 +1,10 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 043 A POST'S TABLE OF CONTENTS +-- +-- Blog posts → "Show contents": list the post's headings beside it +-- (a fold-out on phones), the one being read lit. Off unless an +-- editor turns it on, since a short post doesn't need one. +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE blog_posts ADD COLUMN show_contents INTEGER NOT NULL DEFAULT 0 + CHECK (show_contents IN (0, 1)); diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js index ae7bd08..1461d42 100644 --- a/server/src/pageMeta.js +++ b/server/src/pageMeta.js @@ -18,7 +18,7 @@ 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 + the HTML as window.__SITE__, see src/lib/site.ts), so a heading and its search title can't drift. The database: records' names, taglines, first paragraphs and images. A blank site description falls back to the front page's @@ -42,6 +42,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { loadBlocks, paragraphs } from "./shape.js"; +import { themeCss } from "./theme.js"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -102,12 +103,16 @@ export function siteFor(db) { ...base.robots, index: row.indexing ? row.indexing === "on" : base.robots?.index !== false, }, + privacyEmail: row.privacy_email || base.privacyEmail || "", + // The admin's colours (theme.js): only #rrggbb values and fixed + // text, so safe inside `, ].filter(Boolean); // A blocked site (Site settings indexing off, or site.json's @@ -450,7 +479,8 @@ export function renderPage(html, meta) { tags.splice(2, 0, ``); } - return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n `); + // A function, so a $& or $` in record text isn't read as a pattern. + return out.replace(/<\/head>/i, () => ` ${tags.join("\n ")}\n `); } /* ── Sitemap ───────────────────────────────────────────────── */ diff --git a/server/src/rateLimit.js b/server/src/rateLimit.js index 5b35773..6d677f6 100644 --- a/server/src/rateLimit.js +++ b/server/src/rateLimit.js @@ -5,11 +5,13 @@ the service restarts and it doesn't survive a second instance, both of which are fine for one systemd unit on one box. - The client IP comes from X-Forwarded-For, which nginx sets. That - header is only trustworthy because nothing but nginx can reach - this port — it binds to 127.0.0.1. Don't expose the port. + The client IP comes from clientIp() in auth.js (the entry nginx + adds to X-Forwarded-For). That is only trustworthy because + nothing but nginx can reach this port, it binds to 127.0.0.1. Don't expose the port. ═══════════════════════════════════════════════════════════════ */ +import { clientIp } from "./auth.js"; + export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { const hits = new Map(); // ip → { count, resetAt } @@ -22,8 +24,7 @@ export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { }, windowMs).unref(); return async (c, next) => { - const ip = - c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? "unknown"; + const ip = clientIp(c) ?? "unknown"; const now = Date.now(); let entry = hits.get(ip); @@ -47,3 +48,45 @@ export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { await next(); }; } + +/* ── Failures per key ────────────────────────────────────────── + For login: count only failed attempts per account, so guessing + one person's password from many addresses still stops, and their + own successful sign-in clears it. Unknown emails are counted the + same way, so the limit says nothing about which accounts exist. + ponytail: in-memory like the IP limit (resets on restart, one + instance); a spray of random emails is swept each window. + ───────────────────────────────────────────────────────────── */ + +export function failureLimit({ windowMs = 15 * 60_000, max = 5 } = {}) { + const failures = new Map(); // key → { count, resetAt } + + setInterval(() => { + const now = Date.now(); + for (const [key, entry] of failures) { + if (entry.resetAt <= now) failures.delete(key); + } + }, windowMs).unref(); + + const live = (key) => { + const entry = failures.get(key); + if (entry && entry.resetAt <= Date.now()) failures.delete(key); + return failures.get(key); + }; + + return { + /** Seconds until the key may try again, or 0. */ + blockedFor(key) { + const entry = live(key); + return entry && entry.count >= max ? Math.ceil((entry.resetAt - Date.now()) / 1000) : 0; + }, + fail(key) { + const entry = live(key) ?? { count: 0, resetAt: Date.now() + windowMs }; + entry.count += 1; + failures.set(key, entry); + }, + clear(key) { + failures.delete(key); + }, + }; +} diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js index f50c64b..f8dec83 100644 --- a/server/src/routes/admin-entities.js +++ b/server/src/routes/admin-entities.js @@ -28,15 +28,16 @@ import { updateRow, deleteRow, } from "../admin-crud.js"; +import { NO_STORE } from "../shape.js"; const entities = new Hono(); entities.use("*", requireAuth); -const NO_STORE = { "Cache-Control": "no-store" }; function entityOr404(c) { - const entity = ENTITIES[c.req.param("entity")]; + const name = c.req.param("entity"); + const entity = Object.hasOwn(ENTITIES, name) ? ENTITIES[name] : null; if (!entity) throw new HttpError(404, "Unknown entity."); return entity; } @@ -52,6 +53,16 @@ function entityForWrite(c) { return entity; } +/* An extension can ask for more than a sign-in to be read + (readRole): a person's private details need editor. Blanked on + every row sent back, so a write's reply can't leak it either. */ +function visible(c, entity, row) { + for (const ext of entity.extensions ?? []) { + if (ext.readRole && !hasRole(c.get("user"), ext.readRole)) row[ext.key] = null; + } + return row; +} + /* Everything the select inputs need, in one request. Small enough that paging it would cost more than it saves. */ entities.get("/options", (c) => { @@ -71,12 +82,12 @@ entities.get("/:entity", (c) => { entities.get("/:entity/:id", (c) => { const entity = entityOr404(c); - return c.json({ row: readRow(c.get("db"), entity, c.req.param("id")) }, 200, NO_STORE); + return c.json({ row: visible(c, entity, readRow(c.get("db"), entity, c.req.param("id"))) }, 200, NO_STORE); }); entities.post("/:entity", requireRole("editor"), async (c) => { const entity = entityForWrite(c); - const row = createRow(c.get("db"), entity, await json(c)); + const row = visible(c, entity, 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); }); @@ -84,7 +95,7 @@ entities.post("/:entity", requireRole("editor"), async (c) => { entities.patch("/:entity/:id", requireRole("editor"), async (c) => { const entity = entityForWrite(c); const id = c.req.param("id"); - const row = updateRow(c.get("db"), entity, id, await json(c)); + const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c))); console.log(`${entity.key} ${id} updated by ${c.get("user").email}`); return c.json({ row }, 200, NO_STORE); }); diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 1479050..e14cd1c 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -10,12 +10,12 @@ import { Hono } from "hono"; import { requireAuth, requireRole } from "../auth.js"; +import { NO_STORE } from "../shape.js"; const admin = new Hono(); admin.use("*", requireAuth); -const NO_STORE = { "Cache-Control": "no-store" }; const STATUSES = ["new", "read", "actioned", "archived", "spam"]; const MAX_LIMIT = 200; @@ -23,6 +23,8 @@ const NOTE_LIMIT = 2000; /* ── GET /api/admin/feedback ───────────────────────────────────── ?status=new one of STATUSES, or omitted for all + ?kind=feedback website feedback (every type but 'privacy') + ?kind=privacy data requests from the Privacy page ?type=broken feedback_type ?q=retreat substring of the message ?before=41 cursor: rows with a lower id than this @@ -31,11 +33,17 @@ const NOTE_LIMIT = 2000; admin.get("/feedback", (c) => { const db = c.get("db"); - const { status, type, q, before, limit } = c.req.query(); + const { status, type, kind, q, before, limit } = c.req.query(); const where = []; const params = []; + // Data requests and website feedback share the table but are two + // queues in the admin (Forms → Website feedback, Data requests). + const kindWhere = + kind === "privacy" ? "feedback_type = 'privacy'" : kind === "feedback" ? "feedback_type <> 'privacy'" : null; + if (kindWhere) where.push(kindWhere); + if (STATUSES.includes(status)) { where.push("status = ?"); params.push(status); @@ -53,7 +61,7 @@ admin.get("/feedback", (c) => { params.push(Number(before)); } - const take = Math.min(Number(limit) || 50, MAX_LIMIT); + const take = Math.max(1, Math.min(Number(limit) || 50, MAX_LIMIT)); const rows = db .prepare( @@ -69,19 +77,27 @@ admin.get("/feedback", (c) => { const hasMore = rows.length > take; const page = hasMore ? rows.slice(0, take) : rows; - // Counts are unfiltered on purpose: the tabs should show what's - // waiting overall, not what's left after the current filter. + // Status counts cover this queue (kind) but ignore the other + // filters: the tabs show what's waiting, not what's left after a + // search. newByKind is what's new in each queue, for the queue tabs. const counts = Object.fromEntries(STATUSES.map((s) => [s, 0])); for (const row of db - .prepare("SELECT status, COUNT(*) AS n FROM feedback GROUP BY status") + .prepare(`SELECT status, COUNT(*) AS n FROM feedback ${kindWhere ? `WHERE ${kindWhere}` : ""} GROUP BY status`) .all()) { counts[row.status] = row.n; } + const newByKind = db + .prepare( + `SELECT SUM(feedback_type <> 'privacy') AS feedback, SUM(feedback_type = 'privacy') AS privacy + FROM feedback WHERE status = 'new'`, + ) + .get(); return c.json( { feedback: page, counts, + newByKind: { feedback: newByKind?.feedback ?? 0, privacy: newByKind?.privacy ?? 0 }, nextCursor: hasMore ? page[page.length - 1].id : null, }, 200, @@ -99,7 +115,8 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 179452a..d798f87 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -11,8 +11,9 @@ Three deliberate choices: - Login is rate limited where it's mounted, and answers wrong - password and unknown account identically. Telling an attacker + Login is rate limited where it's mounted (per IP) and here (per + email, failures only), and answers wrong password and unknown + account identically. Telling an attacker which addresses exist is free reconnaissance. A failed login still runs a hash. Otherwise the response time @@ -32,6 +33,7 @@ import { deleteCookie, getCookie, setCookie } from "hono/cookie"; import { SECURE_COOKIE, + logSafe, createSession, destroySession, currentUser, @@ -39,6 +41,13 @@ import { verifyPassword, } from "../auth.js"; import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js"; +import { failureLimit } from "../rateLimit.js"; +import { NO_STORE } from "../shape.js"; + +// On top of the per-IP limit where /login is mounted: five wrong +// passwords for one email in 15 minutes locks that email for the +// rest of the window, from anywhere. +const loginFailures = failureLimit({ windowMs: 15 * 60_000, max: 5 }); const auth = new Hono(); @@ -46,12 +55,12 @@ const auth = new Hono(); // so both paths cost the same. Computed once at import. const DUMMY_HASH = hashPassword("this password is never correct"); -const NO_STORE = { "Cache-Control": "no-store" }; auth.post("/login", async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } @@ -63,6 +72,16 @@ auth.post("/login", async (c) => { return c.json({ error: "Email and password are required." }, 400); } + const wait = loginFailures.blockedFor(email); + if (wait) { + console.warn(`login locked for ${logSafe(email)}`); + return c.json( + { error: "Too many wrong passwords for this account. Try again in a few minutes." }, + 429, + { "Retry-After": String(wait) }, + ); + } + const db = c.get("db"); const user = db @@ -75,14 +94,16 @@ auth.post("/login", async (c) => { const ok = user && user.is_active === 1 - ? verifyPassword(password, user.password_hash) - : (verifyPassword(password, DUMMY_HASH), false); + ? await verifyPassword(password, user.password_hash) + : (await verifyPassword(password, DUMMY_HASH), false); if (!ok) { - console.warn(`login failed for ${email}`); + loginFailures.fail(email); + console.warn(`login failed for ${logSafe(email)}`); return c.json({ error: "That email and password don't match." }, 401); } + loginFailures.clear(email); createSession(db, c, user.id); db.prepare("UPDATE admin_users SET last_login_at = datetime('now') WHERE id = ?").run( @@ -115,12 +136,14 @@ auth.get("/me", (c) => { // 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"; +// __Host- (Secure, path /, no Domain) when over https, like the +// session cookie, so a sibling subdomain can't plant its own state. +const OAUTH_COOKIE = SECURE_COOKIE ? "__Host-site_oauth" : "site_oauth"; const OAUTH_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, sameSite: "Lax", - path: "/api/auth/google", + path: "/", }; // Where to land afterwards: an admin page, never anywhere else. @@ -213,7 +236,8 @@ auth.get("/google/callback", async (c) => { ).run(identity.name, user.id); console.log(`login ${user.email} (google)`); - return c.redirect(saved.next ?? "/admin/home", 302); + // Checked again: the cookie came back from the browser. + return c.redirect(safeNext(saved.next), 302); }); export default auth; diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js index 835de5f..9407477 100644 --- a/server/src/routes/blog.js +++ b/server/src/routes/blog.js @@ -24,17 +24,11 @@ import { Hono } from "hono"; -import { asBool, loadBlocks, loadFeaturedCards, paragraphs } from "../shape.js"; +import { asBool, json, loadBlocks, loadFeaturedCards, marks, paragraphs } from "../shape.js"; import { readFeeds } from "../feeds.js"; const blog = new Hono(); -const CACHE = "public, max-age=60, stale-while-revalidate=300"; - -const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); - -const marks = (n) => Array(n).fill("?").join(","); - const PAGE_ID = "community"; const splitTags = (tags) => @@ -104,6 +98,8 @@ blog.get("/blog/:id", (c) => { title: row.title, excerpt: row.excerpt, cover_image: row.cover_image, + cover_alt: row.cover_alt, + show_contents: row.show_contents === 1, published_on: row.published_on, tags: splitTags(row.tags), authors, diff --git a/server/src/routes/clips.js b/server/src/routes/clips.js index d96adbb..70586ad 100644 --- a/server/src/routes/clips.js +++ b/server/src/routes/clips.js @@ -39,13 +39,13 @@ import { saveToLibrary, toolVersions, } from "../clips.js"; +import { NO_STORE } from "../shape.js"; const clips = new Hono(); clips.use("/clips", requireAuth, requireRole("admin")); clips.use("/clips/*", requireAuth, requireRole("admin")); -const NO_STORE = { "Cache-Control": "no-store" }; const RECENT = 50; diff --git a/server/src/routes/content.js b/server/src/routes/content.js index 1e56055..b65cc0f 100644 --- a/server/src/routes/content.js +++ b/server/src/routes/content.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - CONTENT ROUTES — read-only, mounted under /api + CONTENT ROUTES: read-only, mounted under /api GET /events list + the event scopes GET /events/:id one event, full body, people @@ -12,7 +12,7 @@ Organizations are one table, so they're one endpoint. A region and a chapter differ by a handful of fields, which arrive under - `details` rather than as separate routes — that's what lets a + `details` rather than as separate routes, that's what lets a list component be written once and pointed at any kind. The lists leave out unlisted records (is_listed = 0); the @@ -32,7 +32,7 @@ every event. An event's hosts are a list, in billing order, and each one is - either an organization or a person — `kind` says which, and + either an organization or a person, `kind` says which, and `org_kind` is there for the three organization routes. The first is the one the colour and logo fell back to, which is why order is data and not a display choice. @@ -54,8 +54,11 @@ import { Hono } from "hono"; import { asBool, + json, loadBlocks, loadLinks, + loadOwned, + marks, paragraphs, shapeSeries, splitLinks, @@ -66,14 +69,9 @@ const content = new Hono(); // Content changes weekly at most, and a stale minute costs nobody // anything. stale-while-revalidate keeps the page instant while the // refresh happens behind it. -const CACHE = "public, max-age=60, stale-while-revalidate=300"; - -const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); const ORG_KINDS = ["national", "region", "chapter", "partner"]; -const marks = (n) => Array(n).fill("?").join(","); - /* ── Loaders ───────────────────────────────────────────────── */ /* Hosts for a batch of events, keyed by event id, in the order @@ -83,7 +81,7 @@ const marks = (n) => Array(n).fill("?").join(","); Unpublished hosts are dropped here rather than in the view: the admin reads the same view and needs to see them. An event whose only host is unpublished comes back with an empty list, which is - the right answer — there is nobody to name and nowhere to link. */ + the right answer, there is nobody to name and nowhere to link. */ function loadHosts(db, ids) { const byEvent = new Map(); if (ids.length === 0) return byEvent; @@ -147,7 +145,6 @@ function shapeEvent(row, links, cardBlocks, hosts = []) { org_logo: row.effective_org_logo, event_logo: row.event_logo, color: row.effective_color, - gradient: row.gradient, card_image: row.card_image, hosts: hosts.map(shapeHost), @@ -230,8 +227,8 @@ function shapeTeam(row, links, cardBlocks) { }; } -/* awards.org_id is nullable — an award can predate any decision - about which organization owns it — so `org` genuinely can be +/* awards.org_id is nullable, an award can predate any decision + about which organization owns it, so `org` genuinely can be null, and is also null when the awarding org is unpublished. */ function shapeAward(row) { return { @@ -372,7 +369,7 @@ function attachLeadership(db, orgs) { /* Every team this organization has, including ones with nobody currently filed under them. `leadership` already carries team_id - and team_name, so the page can group people without this — but + and team_name, so the page can group people without this, but grouping alone would make an empty team invisible rather than listed, which is the wrong answer for a team that exists. */ function attachTeams(db, orgs) { @@ -485,7 +482,6 @@ content.get("/events", (c) => { return json(c, { scopes, events }); }); - /* One event, for its own page. */ content.get("/events/:id", (c) => { const db = c.get("db"); @@ -497,9 +493,7 @@ content.get("/events/:id", (c) => { if (!row) return c.json({ error: "No such event" }, 404); - const links = loadLinks(db, "event", [id]).get(id) ?? []; - const cards = loadBlocks(db, "event", [id], "card").get(id) ?? []; - const body = loadBlocks(db, "event", [id], "body").get(id) ?? []; + const { links, cards, body } = loadOwned(db, "event", id); const hosts = loadHosts(db, [id]).get(id) ?? []; const people = db @@ -542,7 +536,6 @@ content.get("/events/:id", (c) => { }); }); - /* ── Organizations ───────────────────────────────────────────── GET /organizations every published, listed org GET /organizations?kind=region one kind @@ -597,7 +590,6 @@ content.get("/organizations", (c) => { return json(c, { organizations }); }); - /* One organization's page: region, chapter, partner or NGU. */ content.get("/organizations/:id", (c) => { const db = c.get("db"); @@ -609,9 +601,7 @@ content.get("/organizations/:id", (c) => { if (!row) return c.json({ error: "No such organization" }, 404); - const links = loadLinks(db, "organization", [id]).get(id) ?? []; - const cards = loadBlocks(db, "organization", [id], "card").get(id) ?? []; - const body = loadBlocks(db, "organization", [id], "body").get(id) ?? []; + const { links, cards, body } = loadOwned(db, "organization", id); const organization = shapeOrganization(row, links, cards, body); const one = [organization]; @@ -641,7 +631,6 @@ content.get("/organizations/:id", (c) => { return json(c, { organization }); }); - /* ── Teams ───────────────────────────────────────────────────── GET /teams every published, listed team GET /teams?org=mid-atlantic one organization's teams @@ -677,7 +666,6 @@ content.get("/teams", (c) => { }); }); - content.get("/teams/:id", (c) => { const db = c.get("db"); const id = c.req.param("id"); @@ -693,14 +681,11 @@ content.get("/teams/:id", (c) => { if (!row) return c.json({ error: "No such team" }, 404); - const links = loadLinks(db, "team", [id]).get(id) ?? []; - const cards = loadBlocks(db, "team", [id], "card").get(id) ?? []; - const body = loadBlocks(db, "team", [id], "body").get(id) ?? []; + const { links, cards, body } = loadOwned(db, "team", id); return json(c, { team: { ...shapeTeam(row, links, cards), blocks: body } }); }); - /* ── Awards ──────────────────────────────────────────────────── GET /awards every award GET /awards?org=ngu awards a given organization gives @@ -739,7 +724,6 @@ content.get("/awards", (c) => { }); }); - content.get("/awards/:id", (c) => { const db = c.get("db"); const id = c.req.param("id"); diff --git a/server/src/routes/directory.js b/server/src/routes/directory.js index 538393b..0e63a3c 100644 --- a/server/src/routes/directory.js +++ b/server/src/routes/directory.js @@ -28,11 +28,10 @@ ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; +import { CACHE } from "../shape.js"; const directory = new Hono(); -const CACHE = "public, max-age=60, stale-while-revalidate=300"; - directory.get("/directory", (c) => { const db = c.get("db"); const all = (sql) => db.prepare(sql).all(); diff --git a/server/src/routes/feedback.js b/server/src/routes/feedback.js index 6a09822..885394e 100644 --- a/server/src/routes/feedback.js +++ b/server/src/routes/feedback.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - FEEDBACK ROUTE — the only public write on the site + FEEDBACK ROUTE: the only public write on the site Everything hostile that will ever reach this service arrives here, so the defences live here rather than being sprinkled @@ -10,13 +10,12 @@ length caps rejected before anything touches the database no HTML stored verbatim, escaped at render time - The write is a single INSERT with positional parameters, so it - works on node:sqlite and better-sqlite3 alike. No transaction: - one statement is already atomic. + The write is a single INSERT. No transaction: one statement is + already atomic. ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; -import { createHash, randomBytes } from "node:crypto"; +import { clientIp, hashIp } from "../auth.js"; const feedback = new Hono(); @@ -30,29 +29,10 @@ const LIMITS = { const MIN_MESSAGE = 10; -// Must match FEEDBACK_TYPES in src/pages/sections/FeedbackForm.jsx. -// Anything else falls back to 'general' rather than being rejected — +// Must match FEEDBACK_TYPES and DATA_REQUEST in src/data/feedbackTypes.ts. +// Anything else falls back to 'general' rather than being rejected, // a renamed option shouldn't lose someone's submission. -const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other"]; - -/* ── IP hashing ──────────────────────────────────────────────── - Stored so repeat abuse from one source is visible during - triage, hashed so the table never holds an address. Without - IP_SALT the salt is regenerated each boot, which makes hashes - incomparable across restarts — fine for dev, set it in - /etc/ngu/api.env for production. - ───────────────────────────────────────────────────────────── */ - -const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex"); - -if (!process.env.IP_SALT) { - console.warn("IP_SALT unset — feedback ip_hash values reset on restart"); -} - -function hashIp(ip) { - if (!ip) return null; - return createHash("sha256").update(`${IP_SALT}:${ip}`).digest("hex").slice(0, 32); -} +const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other", "privacy"]; /* ── Input cleaning ──────────────────────────────────────────── */ @@ -72,7 +52,8 @@ function looksLikeEmail(value) { feedback.post("/", async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } @@ -96,6 +77,10 @@ feedback.post("/", async (c) => { const errors = {}; if (message.length < MIN_MESSAGE) errors.message = "Please write a little more."; if (!looksLikeEmail(email)) errors.email = "That email doesn't look right."; + // A data request (Privacy page) has to be answerable. + else if (feedbackType === "privacy" && !email) { + errors.email = "We need an email address to reply to a data request."; + } if (Object.keys(errors).length > 0) { return c.json({ error: "Validation failed", fields: errors }, 422); @@ -118,7 +103,7 @@ feedback.post("/", async (c) => { pagePath || null, sectionId || null, clean(c.req.header("user-agent"), 500) || null, - hashIp(c.req.header("x-forwarded-for")?.split(",")[0].trim()), + hashIp(clientIp(c)), ); // created_at and status come from column defaults. diff --git a/server/src/routes/history.js b/server/src/routes/history.js index e7beca1..b32fe83 100644 --- a/server/src/routes/history.js +++ b/server/src/routes/history.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - HISTORY ROUTE — read-only, mounted under /api + HISTORY ROUTE: read-only, mounted under /api GET /history every published timeline entry @@ -17,7 +17,7 @@ queries doesn't grow with the number of entries. · precision that outruns the date. An entry can hold '2012' with - precision 'day' — the admin doesn't stop you. Trusting that + precision 'day', the admin doesn't stop you. Trusting that pair would put the entry in a month node built from a month that isn't there, so precision is capped at what the string actually carries. @@ -31,15 +31,10 @@ ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; +import { json, marks } from "../shape.js"; const history = new Hono(); -const CACHE = "public, max-age=60, stale-while-revalidate=300"; - -const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); - -const marks = (n) => Array(n).fill("?").join(","); - /* 'YYYY' → year, 'YYYY-MM' → month, 'YYYY-MM-DD' → day. */ function precisionOfString(date) { const parts = String(date).split("-"); @@ -115,7 +110,7 @@ history.get("/history", (c) => { ) .all(); - // How many entries exist but can't be placed. Worth knowing about — + // How many entries exist but can't be placed. Worth knowing about, // an entry nobody gave a date to is invisible, and silence is how it // stays that way. const undated = db @@ -153,7 +148,7 @@ function loadRosters(db, rows) { const teamIds = [...new Set(teamEntries.map((row) => row.ref_id))]; // v_org_leadership already decides who counts as current and - // public — affiliation still open, marked public, person + // public, affiliation still open, marked public, person // published. Restating those conditions here is how they drift. const members = db .prepare( diff --git a/server/src/routes/home.js b/server/src/routes/home.js index bd5824d..f503c71 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -48,14 +48,10 @@ import { Hono } from "hono"; -import { asBool, loadFeaturedCards, loadLinks, shapeSeries, splitLinks } from "../shape.js"; +import { asBool, json, loadFeaturedCards, loadLinks, shapeSeries, splitLinks } from "../shape.js"; const home = new Hono(); -const CACHE = "public, max-age=60, stale-while-revalidate=300"; - -const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); - const PAGE_ID = "home"; const STAT_QUERIES = { diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 42d5d1a..23a76b3 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -37,12 +37,12 @@ import { store, } from "../media.js"; import { fetchImage, previewLink } from "../linkPreview.js"; +import { NO_STORE } from "../shape.js"; const media = new Hono(); media.use("*", requireAuth); -const NO_STORE = { "Cache-Control": "no-store" }; const MAX_LIST = 500; @@ -165,7 +165,7 @@ media.post("/link-preview", requireRole("editor"), async (c) => { const user = c.get("user"); let url; try { - ({ url } = await c.req.json()); + ({ url } = (await c.req.json()) ?? {}); } catch { return c.json({ error: "Expected a JSON body." }, 400); } diff --git a/server/src/routes/pages.js b/server/src/routes/pages.js index 11a9323..7a03596 100644 --- a/server/src/routes/pages.js +++ b/server/src/routes/pages.js @@ -36,6 +36,7 @@ import { fileURLToPath } from "node:url"; import { Hono } from "hono"; import { metaFor, renderPage, robotsTxt, siteFor, sitemap } from "../pageMeta.js"; +import { CACHE, NO_STORE } from "../shape.js"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -43,8 +44,6 @@ 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() { @@ -118,11 +117,15 @@ pages.get("*", (c, next) => { `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(html, 200, NO_STORE); } + // no-cache: a browser may keep the page but asks again each time. + // HTML names the build's hashed /assets files, and after a deploy + // those are gone, so a cached old page would load nothing. Pages + // are rebuilt in well under a millisecond. return c.html(page, meta.status, { - "Cache-Control": meta.status === 200 ? CACHE : "no-store", + "Cache-Control": meta.status === 200 ? "no-cache" : "no-store", }); }); diff --git a/server/src/routes/panel.js b/server/src/routes/panel.js index 8aefbce..4b3a78e 100644 --- a/server/src/routes/panel.js +++ b/server/src/routes/panel.js @@ -25,13 +25,14 @@ import { Hono } from "hono"; import { requireAuth, requireRole, ROLES } from "../auth.js"; +import { tx } from "../db.js"; +import { NO_STORE } from "../shape.js"; const panel = new Hono(); panel.use("*", requireAuth); panel.use("*", requireRole("superadmin")); -const NO_STORE = { "Cache-Control": "no-store" }; /* The counts on the overview. Table name is a literal from this list, never anything off the wire. */ @@ -116,7 +117,8 @@ panel.patch("/users/:id", async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } @@ -154,7 +156,8 @@ panel.patch("/users/:id", async (c) => { if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); - const tx = db.transaction(() => { + // tx(), not db.transaction(): node:sqlite has no transaction(). + tx(db, () => { db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run( ...params, id, @@ -163,7 +166,6 @@ panel.patch("/users/:id", async (c) => { // matches the row. Make them sign in again. db.prepare("DELETE FROM sessions WHERE user_id = ?").run(id); }); - tx(); console.log( `account ${target.email} updated by ${me.email}: ${JSON.stringify(body)}`, diff --git a/server/src/routes/people.js b/server/src/routes/people.js index 8d094e9..8200c24 100644 --- a/server/src/routes/people.js +++ b/server/src/routes/people.js @@ -1,12 +1,12 @@ /* ═══════════════════════════════════════════════════════════════ - PEOPLE ROUTES — read-only, mounted under /api + PEOPLE ROUTES: read-only, mounted under /api GET /teams/:id/people current public members of a team GET /people?ids=a,b,c named people, any order GET /people/:id one person's page The team route reads v_org_leadership, which already decides who - counts as current and public — affiliation still open, marked + counts as current and public, affiliation still open, marked public, person published. Restating those conditions here is how they drift apart. @@ -21,16 +21,10 @@ import { Hono } from "hono"; -import { asBool, loadBlocks, loadLinks, paragraphs, splitLinks } from "../shape.js"; +import { asBool, json, loadOwned, marks, paragraphs, splitLinks } from "../shape.js"; const people = new Hono(); -const CACHE = "public, max-age=60, stale-while-revalidate=300"; - -const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); - -const marks = (n) => Array(n).fill("?").join(","); - /* How many slugs one request may name. Keeps the URL sane. */ const MAX_IDS = 50; @@ -55,7 +49,7 @@ function shapePerson(row) { } /* people.bio is one run of prose with blank lines between - paragraphs — unrelated to shape.js's paragraphs(), which turns + paragraphs, unrelated to shape.js's paragraphs(), which turns content_block rows into text. */ function splitParagraphs(text) { if (!text) return null; @@ -144,7 +138,7 @@ people.get("/people", (c) => { the same visibility rules its own page applies: a role needs a public affiliation and a published organization, an event must be published, an award must be published and the citation - public. A hidden team drops its name rather than the role — + public. A hidden team drops its name rather than the role, the seat is still real, it just has no page to link to. Roles are current and past. v_org_leadership only knows @@ -181,9 +175,7 @@ people.get("/people/:id", (c) => { if (!row) return c.json({ error: "No such person" }, 404); - const links = loadLinks(db, "person", [id]).get(id) ?? []; - const cards = loadBlocks(db, "person", [id], "card").get(id) ?? []; - const body = loadBlocks(db, "person", [id], "body").get(id) ?? []; + const { links, cards, body } = loadOwned(db, "person", id); const { actions, socials, website, instagram } = splitLinks(links); // Current first, then most recently ended. Within each, the same diff --git a/server/src/seed-showcase.js b/server/src/seed-showcase.js index 41bcb3b..5e61cf3 100644 --- a/server/src/seed-showcase.js +++ b/server/src/seed-showcase.js @@ -352,7 +352,6 @@ tx(db, () => { org_logo: IMAGE, event_logo: IMAGE, color: "#d62976", - gradient: "linear-gradient(160deg, rgba(214,41,118,0.10), rgba(19,139,160,0.10))", card_image: IMAGE, is_published: 1, is_listed: LISTED, @@ -463,6 +462,7 @@ tx(db, () => { cover_image: IMAGE, published_on: db.prepare(`SELECT date('now') AS d`).get().d, tags: "Test, Showcase", + show_contents: 1, guest_author: "A Guest Author", guest_photo: IMAGE, is_published: 1, diff --git a/server/src/shape.js b/server/src/shape.js index 179d71c..5ea0259 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -3,7 +3,7 @@ Blocks and links are polymorphic: any organization, event, person or team can own them. Every list endpoint therefore needs the - same move — fetch the parent rows, then fetch all their children + same move, fetch the parent rows, then fetch all their children in one query each and stitch. The alternative is a query per row, which at a dozen events is @@ -99,7 +99,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { const itemRows = db .prepare( `SELECT i.block_id, i.text, i.detail, i.url, - i.day, i.time, i.location, i.description, i.media, i.map, + i.day, i.time, i.location, i.description, i.media, i.media_alt, 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 @@ -122,6 +122,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { location: row.location, description: row.description, media: row.media, + media_alt: row.media_alt, map: row.map, person: row.person_id ? { @@ -139,7 +140,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { /* ── Card description ────────────────────────────────────────── The card slot is paragraphs by convention, so it collapses to - an array of strings — desc_a and desc_b become description[0] + an array of strings, desc_a and desc_b become description[0] and description[1]. A non-paragraph block in the card slot is ignored here; put it in the body slot instead. ───────────────────────────────────────────────────────────── */ @@ -172,7 +173,7 @@ export function splitLinks(links = []) { collapse from seven flags to a list of the ticked ones, Sunday first; an empty list means "starts_on's weekday", which the client resolves since it already holds starts_on. Occurrences - are not sent — they are derived, and the client derives them + are not sent, they are derived, and the client derives them against its own today. Shared by /events and /front-page. ───────────────────────────────────────────────────────────── */ const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; @@ -300,3 +301,24 @@ export function loadFeaturedCards(db, ownerKind, ownerId) { } export { asBool }; + +/* One record's links, card blocks and body blocks: what every detail + page sends beside the record itself. */ +export function loadOwned(db, ownerKind, id) { + return { + links: loadLinks(db, ownerKind, [id]).get(id) ?? [], + cards: loadBlocks(db, ownerKind, [id], "card").get(id) ?? [], + body: loadBlocks(db, ownerKind, [id], "body").get(id) ?? [], + }; +} + +/* Public reads may be cached a minute, and served a little stale + while a fresh copy is fetched. json() sends a body with it. */ +export const CACHE = "public, max-age=60, stale-while-revalidate=300"; +export const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); + +// Admin reads and anything personal: never kept by a browser or proxy. +export const NO_STORE = { "Cache-Control": "no-store" }; + +// "?,?,?" for an IN (...) list of n values. +export const marks = (n) => Array(n).fill("?").join(","); diff --git a/server/src/theme.js b/server/src/theme.js new file mode 100644 index 0000000..bccc7ee --- /dev/null +++ b/server/src/theme.js @@ -0,0 +1,122 @@ +/* ═══════════════════════════════════════════════════════════════ + THEME + + The admin's palette (Panel → Site settings → Colours, table + site_setting_colors) over the site's own colour tokens. + + The defaults are THEME_DEFAULTS (themeDefaults.js), which the + build checks against src/index.css. A blank override keeps the + default. + + themeCss() is written into every page's (pageMeta.js). + It goes into the same cascade layers as index.css (theme for + light, base for dark), after it, so an override replaces exactly + the value it names: a light-only change leaves dark mode alone. + + checkTheme() runs when Site settings is saved (the descriptor's + `check`, inside the save's transaction), and refuses a palette in + which any text would fall under WCAG AA (4.5:1) in either mode, so + an admin can't make the site unreadable. + ═══════════════════════════════════════════════════════════════ */ + +import { HttpError } from "./admin-crud.js"; +import { THEME_DEFAULTS } from "./themeDefaults.js"; + +export { THEME_DEFAULTS }; + +export const THEME_TOKENS = Object.keys(THEME_DEFAULTS); + +const HEX = /^#[0-9a-f]{6}$/i; +const MODES = ["light", "dark"]; + +function overrides(db) { + const rows = db + .prepare(`SELECT token, light, dark FROM site_setting_colors WHERE settings_id = 'site'`) + .all(); + // Checked again here, not only by the table's CHECK: this goes + // straight into a