Compare commits

..

21 commits

Author SHA1 Message Date
f797e2c509 Merge pull request 'Content display, requests and Google Workspace (v1.9.5 to v1.9.11-content-display)' (#15) from content-display into main 2026-09-30 02:34:52 +01:00
Zaldimmar
1473f4d081 Version v1.9.11-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:02:35 -05:00
Zaldimmar
706abf6a03 Replace the last glyph icons with Phosphor
The editor's insert, duplicate and remove buttons, the image
library's close button and audio tile, the schedule's fold-out caret,
the admin menu's caret, the history timeline's caret and gap marker,
and the QR page's copied tick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:43:48 -05:00
Zaldimmar
5292eda4a6 Version v1.9.10-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:35:46 -05:00
Zaldimmar
b504c24fb0 Keep page files in the shared drive's Media folder, not Blog
The folder isn't only for blog posts. A Blog folder made before this
can be renamed to Media in Drive; its files keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:33:19 -05:00
Zaldimmar
6191322fea Pick up files added to the Blog folder in Drive, and name nginx errors
Opening Tools → Media → Files (or a Choose a file picker) now looks in
the shared drive's Blog folder, at most every 30 seconds, and adds
anything put there in Drive itself: shared as anyone with the link,
previewed, Google Docs, Sheets and Slides included, folders and
shortcuts left out. A file Drive won't share is named in a note and
tried again every ten minutes.

A reply that isn't the API's (nginx's own error page) now says what it
was: a 413 names nginx's upload limit, a 502 the service, a 504 the
timeout, instead of "Server did not return JSON".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:14:40 -05:00
Zaldimmar
5f13273e69 Version v1.9.9-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:43:38 -05:00
Zaldimmar
934598f954 Add a file library in Google Drive for pages to link to
Tools → Media → Files uploads PDF, Office (.docx, .xlsx, .pptx), MP3,
M4A and zip files, up to 50 MB, to the shared drive's Blog folder and
shares each as anyone with the link can view (migration 048). A file's
name and contents must agree.

Content block links get "Choose a file" (paragraph, button and image
links, list and link items, link cards). A link card also takes the
file's name and Drive's picture of its first page, fetched after
upload and saved into the image library; cards to Drive say "Google
Drive". Deleting a file says first what still links to it.

Setup and the nginx block: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:37:15 -05:00
Zaldimmar
36c9226bd9 Version v1.9.8-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:54:33 -05:00
Zaldimmar
80877a4659 Let Google Workspace groups grant admin access
Site settings → Access names a group for each of admin, editor and
viewer (migration 047). Someone in one who signs in with Google gets a
Google-only account with their highest group's role, and the role
follows the groups: at every sign-in, hourly while signed in, and on
Panel → Google groups → Re-sync now. Out of every group, the account
is disabled and signed out until they're back in one.

Group accounts' roles are locked in the Panel; a superadmin's Disable
sticks. Superadmins and admin-cli accounts are never changed. If
Google can't be asked, sign-ins are refused but the hourly check
leaves accounts alone. Panel → Check their groups tests an email.

Lookups use the service account through the Directory API as
GOOGLE_DIRECTORY_AS. Setup: docs/google-sign-in.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:44:04 -05:00
Zaldimmar
d7835dd5d4 Version v1.9.7-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:19:58 -05:00
Zaldimmar
8fd3a9b15b Add a test notice button to Site settings
Panel → Site settings → Notices → Send a test notice emails the
addresses in the box now and shows where it came from, or Google's
reason for refusing, so the Gmail setup can be checked without the
journal. Superadmins only (POST /api/admin/panel/test-notice).

The docs now say the sender must be a Workspace user: a group can't
be acted as through delegation, though it can receive notices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:18:43 -05:00
Zaldimmar
c63478a72a Version v1.9.6-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:59:19 -05:00
Zaldimmar
0f6a796021 Keep Drive files in named folders of one shared drive
GOOGLE_SHARED_DRIVE (the shared drive's bare id) replaces
GOOGLE_DRIVE_FOLDER. driveUpload takes a folder path, found by name in
the shared drive or made the first time, so each use gets its own
folder: "Requests" for the Request form now, others later. The docs
say plainly that the setting is the id only, not the address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:53:40 -05:00
Zaldimmar
e7743829be Version v1.9.5-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:57:35 -05:00
Zaldimmar
dc53af238f Add a Request form, with files in Google Drive and email notices
One form at /request for blog posts, events, and new or updated
chapters, regions (updates only), partners, teams, awards and people.
?type= opens it on one; buttons on the Community sections, blog posts,
Retreats and the front page calendar do. Files (.docx, PDF, JPEG, PNG)
go to a Google Drive folder through a service account.

Requests are feedback rows of type 'content' (migration 046), in a
third Forms queue: files download from Drive, a .docx can become a
draft blog post, and deleting a request deletes its files. New content
and data requests email the addresses in Site settings through Gmail.

Setup: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:54:00 -05:00
Zaldimmar
0e582c236b Move link cards into their own migration
044 had already run with only the table type, so a database that ran
it would never see the edited CHECK, and boot would refuse the cards
type. 044 is back as it was; 045 rebuilds content_blocks to allow
cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:53:58 -05:00
Zaldimmar
4e9b4e3329 Add link card blocks to post bodies
A "cards" content block: each item is a card with a picture, title and
description that links somewhere, like a link shared in a chat. Fetch
preview fills the card from the link. Migration 044 (not deployed yet)
now allows both table and cards.

Also fixes hidden-field clearing when two fields share a path, and adds
table and card blocks to the showcase post.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:40:24 -05:00
Zaldimmar
5dceeb5860 Let a blog post be downloaded as a PDF
Download PDF beside the byline opens the browser's print dialog (Save
as PDF) with a print layout: the site's header, footer and notices
hidden, the contents column dropped, the light palette whatever the
screen shows, and at the bottom the post's link and a QR code of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:34:43 -05:00
Zaldimmar
c03914a210 Move Blog posts from Pages to Data in the admin menu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:33:09 -05:00
Zaldimmar
7f12824c93 Import a Word document as a blog post, and add table blocks
- Table content blocks (migration 044): a grid of text, a row per
  line, cells split by |, the first row the header; cells take the
  same formatting as a paragraph; wide tables scroll on a phone
- Blog posts -> Import from Word: the server reads the .docx (zip and
  XML read without a library, sizes capped) and creates an unpublished
  post through the CRUD engine: title, date, headings, paragraphs,
  lists, tables, bold, italic and links; the editor opens with a note
  of what came over and what didn't (images)
- docs/importing.md, and an nginx block for the upload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:44:20 -05:00
69 changed files with 3863 additions and 172 deletions

View file

@ -34,9 +34,11 @@ 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`.
- Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.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`.
- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`.
## Git workflow
- Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`.

View file

@ -0,0 +1,229 @@
# Google Drive and Gmail
The site keeps files in one Google **shared drive**: the Request form
(`/request`) puts what people send in its "Requests" folder, and files
uploaded in Tools → Media → Files, for pages to link to, go in its
"Media" folder (see "Files for pages" below). New requests can be emailed to whoever is listed in
Panel → Site settings → Notices. Both go through one Google **service
account** (`server/src/googleService.js`). Nothing here is needed for
the rest of the site; until it's set up, the form takes no files and no
mail goes out.
| Setting on the `ngu-api` service | What it is |
| --- | --- |
| `GOOGLE_SERVICE_ACCOUNT` | Path to the service account's key file, eg. `/etc/ngu/google-service-account.json` |
| `GOOGLE_SHARED_DRIVE` | The shared drive's **id only**, eg. `0ACUt32ze-CVGUk9PVA`: never the whole address (see step 2) |
| `GOOGLE_MAIL_FROM` | The Workspace address notices are sent from, eg. `web@nextgenerationofunity.org` |
Files need the first two; mail needs the first and third.
## 1. The service account
1. In Google Cloud Console (the project that holds the Google sign-in
client is fine), enable the **Google Drive API** and the **Gmail
API**.
2. IAM & Admin → Service accounts → Create. Name it eg. `ngu-site`. It
needs no roles on the project.
3. Open it → Keys → Add key → JSON. Copy the file to the VPS, outside
the app and the repo:
```sh
sudo mkdir -p /etc/ngu
sudo mv ngu-site-*.json /etc/ngu/google-service-account.json
sudo chown <ngu-api user>: /etc/ngu/google-service-account.json
sudo chmod 600 /etc/ngu/google-service-account.json
```
Note the account's email (`ngu-site@<project>.iam.gserviceaccount.com`)
and, from its Details page, its **Client ID** (a long number).
## 2. The shared drive
A service account has no Drive storage of its own, so everything goes in
a **shared drive**.
1. In Google Drive, make (or pick) a shared drive, eg. "NGU Website".
2. Shared drive → Manage members → add the service account's email as
**Content manager** (it makes folders and deletes files).
3. Open the shared drive itself (not a folder in it). Its address is
`https://drive.google.com/drive/u/2/folders/0ACUt32ze-CVGUk9PVA`;
the id is only the part after `folders/`, here `0ACUt32ze-CVGUk9PVA`.
A shared drive's id starts with `0A`. Leave out the address, the
`/u/2/` part and anything after a `?`: pasting the whole URL gives
`404 File not found` on every upload.
### Folders in it
The site finds each folder it uses by name, at the top of the shared
drive, and makes it the first time it's needed. Nothing needs making by
hand.
| Folder | Used by | Set in |
| --- | --- | --- |
| `Requests` | Files sent with the Request form | `DRIVE_FOLDER` in `server/src/routes/requests.js` |
| `Media` | Files for pages to link to (Tools → Media → Files) | `FOLDER` in `server/src/routes/files.js` |
A new use calls `driveUpload("<Folder>", name, mime, bytes)` from
`server/src/googleService.js`; a path such as `"Media/2026"` makes each
level. Add it to this table.
Files for pages went in a folder called `Blog` before v1.9.10. If the
shared drive has one, rename it to `Media` in Drive: the files inside
keep working and stay listed, and nothing is made twice.
Folders are matched by name, so renaming or moving one in Drive makes
the site start a new one under the old name (files already stored keep
working: they're found by their own id). People can add their own
folders to the drive; the site ignores them.
Request files are named `Request 12 - original name.docx`, so the number
matches the one in Forms → Content requests. Deleting a request in the
admin deletes its files from Drive too.
## 3. Gmail (domain-wide delegation)
For the service account to send as a Workspace user:
1. Google Admin console → Security → Access and data control → API
controls → **Manage domain wide delegation** → Add new.
2. Client ID: the service account's Client ID from step 1.
OAuth scopes: `https://www.googleapis.com/auth/gmail.send` (and,
for access groups, `https://www.googleapis.com/auth/admin.directory.group.member.readonly`,
comma separated: `docs/google-sign-in.md`)
3. `GOOGLE_MAIL_FROM` is the address it sends as. It must be a
**user** in the Workspace, one that signs in and has Gmail: not a
group (eg. `webb-admin@`, even mail-enabled), not an alias. The
service account acts as that user, and a group can't be acted as;
Google answers `Client is unauthorized to retrieve access tokens`.
A dedicated user such as `web@` keeps the sent copies out of anyone's
own mailbox. A group is fine as a **recipient** (below): each member
gets the notice.
Then in the admin, Panel → Site settings → Notices → "Email new
requests to": one or more addresses, separated by commas. Each new
content request and data request sends one plain-text email with a link
to the queue; replying goes to the person who sent the request.
**Send a test notice**, under that box, emails whatever addresses are in
it (saved or not) straight away and shows the result on the page:
where it was sent from, or Google's reason for refusing. A new
delegation can take a while to start working, so retry it after a few
minutes before changing anything.
## 4. The service and nginx
```sh
sudo systemctl edit ngu-api
```
```ini
[Service]
Environment=GOOGLE_SERVICE_ACCOUNT=/etc/ngu/google-service-account.json
Environment=GOOGLE_SHARED_DRIVE=<shared drive id, eg. 0ACUt32ze-CVGUk9PVA>
Environment=GOOGLE_MAIL_FROM=web@nextgenerationofunity.org
```
nginx caps `/api/` bodies at 64k, so the form needs its own block in
the site's `server` block, beside `/api/admin/import/docx` (`nginx-dev`
has it):
```nginx
location = /api/requests {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 120s;
client_max_body_size 31m;
}
# Tools → Media → Files: one file of up to 50 MB
location = /api/admin/files {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 180s;
client_max_body_size 51m;
}
```
`sudo nginx -t && sudo systemctl reload nginx && sudo systemctl restart ngu-api`.
## Checking it
- Mail: Panel → Site settings → Notices → **Send a test notice**.
- Send a request with a small file at `/request`. The journal shows
`feedback #N (content: new blog, 1 files)`, and with mail on,
`feedback #N: notice sent to 1`.
- The file is in the shared drive's Requests folder (made on the first upload), and downloads from Forms → Content
requests.
- `Client is unauthorized to retrieve access tokens` (or
`unauthorized_client`) on mail: `GOOGLE_MAIL_FROM` is a group or alias
rather than a user, or the delegation (step 3) is missing, has the
wrong Client ID (the service account's numeric Unique ID), or a scope
other than exactly `https://www.googleapis.com/auth/gmail.send`, or
is too new to have taken effect. `404 File not
found` on upload means `GOOGLE_SHARED_DRIVE` isn't the bare id (a
whole URL, say) or the service account isn't a member of the shared
drive.
## What the form takes
Up to 3 files of 10 MB each: Word documents (.docx), PDFs, JPEG and PNG,
checked by their contents rather than their names
(`server/src/routes/requests.js`). A Word document on a request can be
turned into an unpublished blog post from the queue ("Make a blog post
from it"), the same conversion as Blog posts → Import from Word
(`docs/importing.md`).
## Files for pages
Tools → Media → **Files** (editors and up upload, admins and up delete)
puts a file in the shared drive's `Media` folder and shares it as
**anyone with the link can view**, so visitors open it in Drive's viewer
without signing in. Content block links pick from it with **Choose a
file**: paragraph, button and image links, list and link-button items,
and link cards. A link card also takes the file's name as its title and
Drive's picture of the first page as its picture; the card says "Google
Drive" above the title.
- Types: PDF, Word, Excel and PowerPoint (.docx, .xlsx, .pptx), MP3,
M4A and zip, up to 50 MB. The name and the contents must agree (a PDF
named `.mp3` is refused). Older Office formats (.doc, .ppt) aren't
taken: save them in the new format first.
- The first-page picture: Drive draws one for PDFs and Office files a
little after upload. The server asks at once and again over the next
few minutes, and saves it into the image library as an ordinary
upload. Audio and zips get an icon in the admin and no picture.
- **Files put in the Media folder in Drive itself** (dragged in, made
there, moved there) are listed too: opening the Files tab or a
"Choose a file" picker looks in the folder (at most every 30
seconds), adds anything new, shares it the same way and fetches its
preview. Google's own Docs, Sheets and Slides count; folders inside it
and shortcuts don't. A file Drive won't share with anyone who has the
link is named in a red note instead of listed, and tried again every
ten minutes.
- Deleting a file in the admin deletes it from Drive; the delete says
first which records still link to it (those links stop working).
Deleting it in Drive by hand leaves a broken link and a list entry
that can still be deleted.
- **"Too large for the web server (HTTP 413)"** on upload (older builds
said "Server did not return JSON", with nothing in the journal): nginx
refused the file before it reached the API, because the site has no
`location = /api/admin/files` block (above), so the 64k `/api/` limit
applies. `sudo tail /var/log/nginx/error.log` shows "client intended
to send too large body".
**Sharing has to be allowed.** Uploads fail with "Drive wouldn't share
it with anyone who has the link" unless both allow it:
1. Admin console → Apps → Google Workspace → Drive and Docs → Sharing
settings: sharing outside nextgenerationofunity.org is on (at least
for the organizational unit the service account's delegated user is
in, and for shared drives: "Allow people outside ... to access files
in shared drives").
2. The shared drive itself → Shared drive settings: "Allow people who
aren't shared drive members to access files" and sharing outside the
organization are on.
Files the Request form stores are never shared this way; only files
uploaded in Tools → Media → Files are.

View file

@ -6,7 +6,14 @@ off until the service has an OAuth client ID and secret.
## Who gets in
Only accounts that already exist. Create them as before with
Two kinds of account can sign in with Google:
- **Group accounts**, when access groups are set up (below): anyone in
one of the site's Workspace groups. Their account is made at their
first sign-in, and their role follows the group.
- **Accounts made with admin-cli**, as before.
Created with
`admin-cli.js add <email>` (the password it asks for stays as a way in
if Google is ever unavailable). The first time that person signs in with
Google, their Google account is linked to the admin account with the
@ -14,12 +21,79 @@ same email; after that it matches by the link, even if the email later
changes. `admin-cli.js list` shows which accounts are linked.
Refused, with a message on the login page: no admin account for that
email, an email already linked to a different Google account, a
email (and in no access group), an email already linked to a different Google account, a
disabled account, any account outside the Workspace domain (checked by
Google's `hd` claim, not just the email), an unverified email.
Code: `server/src/googleAuth.js` (the Google side) and
`server/src/routes/auth.js` (matching and linking accounts).
Code: `server/src/googleAuth.js` (the Google side),
`server/src/routes/auth.js` (matching and linking accounts) and
`server/src/accessGroups.js` (access groups).
## Access groups
Panel → Site settings → **Access (Google groups)** names a Workspace
group for each of Admin, Editor and Viewer, eg.
`web-admins@nextgenerationofunity.org`. Any of them may be blank.
- **First sign-in:** someone in one of the groups signs in with Google
and gets an account with the highest role their groups give (in both
the editors and viewers groups: editor). No password: Google only.
Groups inside groups count.
- **The role follows the group**, checked at every sign-in, about once
an hour while they're signed in, and whenever a superadmin presses
Panel → Google groups → **Re-sync now**. Moved to another group: the
role changes. Out of every group: the account is disabled and signed
out; put back in one, it's turned on again at the next sign-in or
re-sync.
- **In the Panel**, a group account says "Google group" and its role
can't be changed there (change the membership instead). Disable still
works, and sticks: no group check turns back on an account a
superadmin disabled.
- **Not affected:** superadmins (there's no superadmin group) and
accounts made with admin-cli, which keep the role set in the Panel
whatever groups they're in.
- **If Google can't be asked** (an outage, a setup mistake), a sign-in
is refused ("Couldn't check your Google groups"), but the hourly
check leaves accounts as they are and tries again; nobody is signed
out because Google was down. Password and admin-cli accounts still
get in.
Panel → Google groups → **Check their groups** shows what role an email
would get, changing nothing: the quickest check of the setup.
### Setting it up
Group lookups use the service account from
`docs/google-drive-and-mail.md` (step 1 there), through the Admin SDK
Directory API:
1. Cloud Console, the service account's project → APIs & Services →
Library → enable the **Admin SDK API**.
2. Admin console → Security → Access and data control → API controls →
Manage domain wide delegation → the service account's entry → Edit.
Add the scope (comma separated, beside `gmail.send`):
`https://www.googleapis.com/auth/admin.directory.group.member.readonly`
3. Pick a Workspace **user** who can see the groups' members: a super
admin, or an admin with a role that includes Groups → Read. The
lookups are made as them. Set it on the service:
```ini
Environment=GOOGLE_DIRECTORY_AS=<that user, eg. it-admin@nextgenerationofunity.org>
```
4. Make the groups in Google Admin (or Groups), add people, and put the
addresses in Site settings → Access. Restart `ngu-api` after the
`systemctl edit`.
`GOOGLE_SERVICE_ACCOUNT` and `GOOGLE_DIRECTORY_AS` without any groups
set changes nothing; groups set without them show a warning in the
Panel and Google sign-in works as before.
Errors in the Panel or journal (`grep access`): `groupKey` means a group
address in Site settings isn't a group Google knows; `unauthorized_client`
means the delegation or scope (step 2) is missing, or
`GOOGLE_DIRECTORY_AS` isn't a user; `Not Authorized to access this
resource` means that user can't read the group.
## Setting up the OAuth client

63
docs/importing.md Normal file
View file

@ -0,0 +1,63 @@
# Importing a Word document as a blog post
Admin → Data → Blog posts → **Import from Word** (editors and up). Pick
a `.docx`; the server turns it into a new blog post, **unpublished**, and
opens it in the editor with a note of what came over. Check it, add the
authors and a cover, then tick Published.
## What becomes what
| In the document | In the post |
| --- | --- |
| The Title, or the first Heading 1 | The post's title (the file name if there's neither) |
| A date line right under the title, eg. "Sep 28, 2026 · @Aidan" | The post's date (the rest of that line is dropped) |
| Heading 1 and Heading 2 | Heading blocks |
| Heading 3 and smaller | Subheading blocks |
| Paragraphs | Paragraph blocks |
| A run of bulleted or numbered paragraphs | One List block, one item each |
| Tables | Table blocks: a row per line, cells split by `\|`, the first row the header |
| Bold, italic, links (http, https, mailto) | `**bold**`, `*italic*`, `[text](url)`, in paragraphs, list items and table cells |
A post with three headings or more gets **Show contents** turned on. The
URL ID is the title as a slug, with `-2`, `-3` when it's taken.
Not carried over: images and drawings (the note says how many; add them
as Image blocks), text boxes, footnotes, comments, colours and fonts.
Numbered lists come over as bulleted lists.
The conversion is `server/src/docx.js`; the route is
`server/src/routes/import.js`.
## PDFs
A PDF has no headings, lists or tables inside it, only positioned
text, so it can't be converted the same way. Open it in Word (or Google
Docs) and save it as `.docx` first, or have it converted by hand.
## Table blocks
Any page's content blocks can have one (Content blocks → Type → Table):
```
Platform | Monthly cost | Best for
Zeffy | Free | Fee-free giving
[Breeze](https://www.breezechms.com) | $72 | **Small churches**
```
A literal `|` inside a cell is written `\|`. On a phone a wide table
scrolls sideways in its box.
## nginx
nginx caps `/api/` bodies at 64k, so the upload needs its own block
(in the site's `server` block, beside `/api/admin/media`; `nginx-dev`
has it):
```nginx
location = /api/admin/import/docx {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 60s;
client_max_body_size 11m;
}
```

View file

@ -29,7 +29,7 @@ what a dropdown in the admin editor says.
| ------------------------------------------------------------ | ---------------- | ------------------------------------ |
| A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin |
| The front page's words, photos, bands, stats and paths | the database | Admin → Pages → Front page |
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Pages → Blog posts, and Community blog section |
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Data → Blog posts, and Admin → Pages → Community blog section |
| The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) |
| The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) |
| Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) |
@ -176,7 +176,7 @@ also in `server/src/admin-schema/` 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/shared.ts`). |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule, table | **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 |
@ -273,6 +273,7 @@ The numbers band's "Number Source" dropdown works the same way:
| 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. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. |
| Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints and the name field's question are client-only. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `<RequestLink>` (`src/components/RequestLink.tsx`). |
| 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. |

132
server/src/accessGroups.js Normal file
View file

@ -0,0 +1,132 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN ACCESS BY GOOGLE GROUP
Panel → Site settings → Access names a Workspace group for each of
viewer, editor and admin. Someone in one of them who signs in with
Google gets an account (access_source 'group', no password) with
the highest of those roles; routes/auth.js calls groupRole() and
applyGroupRole() at every Google sign-in.
The role then follows the group:
at sign-in always checked
while signed in startGroupSync() rechecks accounts with a
live session every SYNC_EVERY_MS, once
their last check is STALE_AFTER_MS old
Panel → Re-sync now every group account, straight away
Out of every group: the account is disabled (group_disabled = 1)
and signed out; back in one, the next sign-in or sync turns it on
again. A superadmin's Disable in the Panel sets group_disabled = 0,
which no group check undoes.
Never touched: superadmins and 'manual' accounts (admin-cli, which
may also sign in with Google as before).
If Google can't be asked, a sign-in is refused (it can't be shown
to be allowed), but a background recheck leaves the account as it
is and tries again next time: an outage shouldn't sign everyone out.
Needs GOOGLE_DIRECTORY_AS (googleService.js) and at least one group.
Setup: docs/google-sign-in.md.
═══════════════════════════════════════════════════════════════ */
import { directoryReady, isGroupMember } from "./googleService.js";
const SYNC_EVERY_MS = 10 * 60 * 1000;
const STALE_AFTER_MS = 30 * 60 * 1000;
// Highest first: the first group someone is in gives their role.
const GROUP_ROLES = ["admin", "editor", "viewer"];
/* [[role, group address], ...], highest role first, set ones only. */
export function accessGroups(db) {
const row =
db
.prepare(
`SELECT access_group_viewer, access_group_editor, access_group_admin
FROM site_settings WHERE id = 'site'`,
)
.get() ?? {};
return GROUP_ROLES.map((role) => [role, String(row[`access_group_${role}`] ?? "").trim().toLowerCase()]).filter(
([, group]) => group,
);
}
export const accessEnabled = (db) => directoryReady() && accessGroups(db).length > 0;
/* The role someone's groups give them, or null for none. Throws a
GoogleError when Google can't say. */
export async function groupRole(db, email) {
for (const [role, group] of accessGroups(db)) {
if (await isGroupMember(group, email)) return role;
}
return null;
}
/* Brings a group account in line with `role` (null: in no group).
Returns what changed, as text for the log and the Panel, or null. */
export function applyGroupRole(db, user, role) {
let change = null;
if (!role) {
if (user.is_active === 1) {
db.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ?`).run(user.id);
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
change = "disabled: in no access group";
}
} else if (user.is_active !== 1 || user.role !== role) {
db.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ?`).run(role, user.id);
change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
}
db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id);
if (change) console.log(`access: ${user.email} ${change}`);
return change;
}
/* Rechecks group accounts: all of them (Panel → Re-sync now), or only
those signed in whose last check is stale (the timer). Accounts a
superadmin disabled are left alone. */
export async function syncGroupAccounts(db, { all = false } = {}) {
const users = db
.prepare(
`SELECT u.id, u.email, u.role, u.is_active FROM admin_users u
WHERE u.access_source = 'group' AND u.role <> 'superadmin'
AND (u.is_active = 1 OR u.group_disabled = 1)
${
all
? ""
: `AND u.is_active = 1
AND EXISTS (SELECT 1 FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now'))
AND (u.groups_checked_at IS NULL OR u.groups_checked_at <= datetime('now', ?))`
}`,
)
.all(...(all ? [] : [`-${STALE_AFTER_MS / 1000} seconds`]));
const result = { checked: 0, changes: [], failed: [] };
for (const user of users) {
try {
const change = applyGroupRole(db, user, await groupRole(db, user.email));
result.checked++;
if (change) result.changes.push(`${user.email}: ${change}`);
} catch (err) {
console.warn(`access: couldn't check ${user.email}: ${err.message}`);
result.failed.push(`${user.email}: ${err.message}`);
}
}
return result;
}
export function startGroupSync(db) {
let running = false;
const tick = async () => {
if (running || !accessEnabled(db)) return;
running = true;
try {
await syncGroupAccounts(db);
} catch (err) {
console.error("access sync failed", err);
} finally {
running = false;
}
};
setInterval(tick, SYNC_EVERY_MS).unref();
}

View file

@ -148,6 +148,8 @@ export const blocksChild = (ownerKind) => ({
"button",
"callout",
"schedule",
"table",
"cards",
],
{ required: true },
),

View file

@ -30,6 +30,10 @@ export const siteSettings = {
text("apple_touch_icon"),
enumeration("indexing", ["on", "off"]),
text("privacy_email"),
text("notify_emails"),
text("access_group_viewer"),
text("access_group_editor"),
text("access_group_admin"),
],
children: [

249
server/src/docx.js Normal file
View file

@ -0,0 +1,249 @@
/* ═══════════════════════════════════════════════════════════════
DOCX → CONTENT BLOCKS
Reads a Word document and turns it into a blog post's content
blocks (routes/import.js; Blog posts → Import from Word):
the Title, or the first Heading 1 the post's title
a date line right under it the post's date
Heading 1 and 2 heading blocks
Heading 3 and below subheading blocks
paragraphs paragraph blocks
runs of list paragraphs one list block, one item each
tables table blocks (a row per line,
cells split by |)
bold, italic, links **bold**, *italic*, [text](url)
Images, text boxes, footnotes and comments aren't carried over;
the result counts what was skipped so the editor can say so.
A .docx is a zip of XML. Both are read here with no library: the
zip through Node's own zlib, the XML with a small tokenizer. The
file is someone's upload, so every size is capped and the XML is
walked once, with no pattern that rescans it.
═══════════════════════════════════════════════════════════════ */
import { inflateRawSync } from "node:zlib";
export class DocxError extends Error {
constructor(message) {
super(message);
this.status = 400;
}
}
const MAX_PART_BYTES = 20 * 1024 * 1024; // any one XML part, unpacked
const PARTS = ["word/document.xml", "word/styles.xml", "word/_rels/document.xml.rels"];
/* ── Zip ───────────────────────────────────────────────────────── */
/* The named entries of a zip, unpacked. Reads the central directory
(the index at the end), so it never walks the whole file. */
function unzip(buf, wanted) {
const out = {};
// End of central directory: the last 0x06054b50 in the final 64 KB.
let eocd = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
if (buf.readUInt32LE(i) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd === -1) throw new DocxError("That file isn't a Word document (.docx).");
const count = buf.readUInt16LE(eocd + 10);
let at = buf.readUInt32LE(eocd + 16);
for (let n = 0; n < count && at + 46 <= buf.length; n++) {
if (buf.readUInt32LE(at) !== 0x02014b50) break;
const method = buf.readUInt16LE(at + 10);
const packed = buf.readUInt32LE(at + 20);
const size = buf.readUInt32LE(at + 24);
const nameLen = buf.readUInt16LE(at + 28);
const extraLen = buf.readUInt16LE(at + 30);
const commentLen = buf.readUInt16LE(at + 32);
const local = buf.readUInt32LE(at + 42);
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
at += 46 + nameLen + extraLen + commentLen;
if (!wanted.includes(name)) continue;
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
const data = buf.subarray(dataAt, dataAt + packed);
if (method === 0) out[name] = data.toString("utf8");
else if (method === 8) out[name] = inflateRawSync(data, { maxOutputLength: MAX_PART_BYTES }).toString("utf8");
}
return out;
}
/* ── XML ───────────────────────────────────────────────────────── */
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
const decode = (s) =>
s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos);/gi, (_, e) => {
if (e[0] !== "#") return ENTITY[e.toLowerCase()];
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1));
return String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
});
/* A tree of { name, attrs, children, text }. One pass of one global
regex over the tags, so its cost is the file's length. */
function parseXml(xml) {
const root = { name: "#root", attrs: {}, children: [] };
const stack = [root];
const token = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([^\s>/]+)([^>]*?)(\/?)>|([^<]+)/g;
let m;
while ((m = token.exec(xml))) {
const top = stack[stack.length - 1];
if (m[1] !== undefined) top.children.push({ name: "#text", text: m[1] });
else if (m[6] !== undefined) top.children.push({ name: "#text", text: decode(m[6]) });
else if (m[3]) {
if (m[2]) {
if (stack.length > 1) stack.pop();
} else {
const attrs = {};
for (const a of m[4].matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g)) attrs[a[1]] = decode(a[2]);
const node = { name: m[3], attrs, children: [] };
top.children.push(node);
if (!m[5]) stack.push(node);
}
}
}
return root;
}
const kids = (node, name) => (node?.children ?? []).filter((c) => c.name === name);
const kid = (node, name) => (node?.children ?? []).find((c) => c.name === name);
function* all(node, name) {
for (const c of node?.children ?? []) {
if (c.name === name) yield c;
yield* all(c, name);
}
}
const on = (el) => el && !["0", "false"].includes(el.attrs["w:val"]);
/* ── Text ──────────────────────────────────────────────────────── */
function runText(r) {
let t = "";
for (const c of r.children) {
if (c.name === "w:t") t += c.children.map((x) => x.text ?? "").join("");
else if (c.name === "w:tab") t += " ";
else if (c.name === "w:br" || c.name === "w:cr") t += " ";
}
if (!t.trim()) return t;
const rpr = kid(r, "w:rPr");
const b = on(kid(rpr, "w:b"));
const i = on(kid(rpr, "w:i"));
const lead = t.match(/^\s*/)[0];
const trail = t.match(/\s*$/)[0];
const core = t.trim();
const marked = b && i ? `***${core}***` : b ? `**${core}**` : i ? `*${core}*` : core;
return lead + marked + trail;
}
const SAFE_LINK = /^(https?:|mailto:)/i;
function paragraphText(p, rels, counts) {
let out = "";
for (const c of p.children) {
if (c.name === "w:r") {
if (kid(c, "w:drawing") || kid(c, "w:pict")) counts.images++;
out += runText(c);
} else if (c.name === "w:hyperlink") {
const label = [...all(c, "w:r")].map(runText).join("").trim();
const href = rels[c.attrs["r:id"]];
out += href && SAFE_LINK.test(href) && label ? `[${label.replace(/[[\]]/g, "")}](${href})` : label;
} else if (c.name === "w:ins" || c.name === "w:smartTag" || c.name === "w:sdt") {
out += [...all(c, "w:r")].map(runText).join("");
}
}
// Word splits a phrase into runs; adjacent bold runs meet as "** **".
return out.replace(/\*\*(\s*)\*\*/g, "$1").replace(/\s+/g, " ").trim();
}
/* ── Document ──────────────────────────────────────────────────── */
const DATE_LINE = /^([A-Z][a-z]{2,8}\.? \d{1,2},? \d{4}|\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8} \d{4})\b/;
export function readDocx(buf) {
const parts = unzip(buf, PARTS);
if (!parts["word/document.xml"]) throw new DocxError("That file isn't a Word document (.docx).");
const rels = {};
for (const r of all(parseXml(parts["word/_rels/document.xml.rels"] ?? ""), "Relationship")) {
if (r.attrs.TargetMode === "External" || /^https?:|^mailto:/i.test(r.attrs.Target ?? "")) rels[r.attrs.Id] = r.attrs.Target;
}
const styleName = {};
for (const s of all(parseXml(parts["word/styles.xml"] ?? ""), "w:style")) {
styleName[s.attrs["w:styleId"]] = (kid(s, "w:name")?.attrs["w:val"] ?? s.attrs["w:styleId"]).toLowerCase();
}
const body = kid(kid(parseXml(parts["word/document.xml"]), "w:document"), "w:body");
if (!body) throw new DocxError("That document has no body to import.");
const counts = { images: 0 };
const blocks = [];
let title = null;
let date = null;
let list = null; // the list block being filled
const close = () => {
if (list) blocks.push(list);
list = null;
};
for (const el of body.children) {
if (el.name === "w:tbl") {
close();
const rows = kids(el, "w:tr").map((tr) =>
kids(tr, "w:tc")
.map((tc) =>
kids(tc, "w:p")
.map((p) => paragraphText(p, rels, counts))
.filter(Boolean)
.join(" / ")
.replace(/\|/g, "\\|"),
)
.join(" | "),
);
if (rows.some((r) => r.replace(/[|\s]/g, ""))) blocks.push({ type: "table", text: rows.join("\n") });
continue;
}
if (el.name !== "w:p") continue;
const ppr = kid(el, "w:pPr");
const style = styleName[kid(ppr, "w:pStyle")?.attrs["w:val"]] ?? "";
const text = paragraphText(el, rels, counts);
if (!text) continue;
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
if (!title && (level === 0 || level === 1)) {
close();
title = text.replace(/\*/g, "");
continue;
}
// The line under the title, when it starts with a date ("Sep 28,
// 2026 · @Aidan"), is the post's date, not part of the body.
if (title && !date && blocks.length === 0 && !list) {
const d = DATE_LINE.exec(text.replace(/\*/g, ""));
const parsed = d && new Date(d[1]);
if (parsed && !Number.isNaN(parsed.getTime())) {
date = parsed.toISOString().slice(0, 10);
continue;
}
}
if (level >= 1) {
close();
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
continue;
}
if (kid(ppr, "w:numPr") || /list/.test(style)) {
if (!list) list = { type: "list", items: [] };
list.items.push({ text });
continue;
}
close();
blocks.push({ type: "paragraph", text });
}
close();
return { title, date, blocks, skipped: counts };
}

301
server/src/googleService.js Normal file
View file

@ -0,0 +1,301 @@
/* ═══════════════════════════════════════════════════════════════
GOOGLE SERVICE ACCOUNT: Drive files and Gmail
The server acting as itself (not a person signing in, that's
googleAuth.js). A service account's key signs a short JWT, which
Google swaps for an access token (RS256 with node:crypto, no
library). Three uses:
Drive one shared drive (a service account has no storage of
its own), with a folder per use: "Requests" for files sent
with the Request form, and so on. Each folder is found by
name, or made, the first time it's needed; a path such as
"Media/2026" makes each level.
Gmail new-request notices, sent as a Workspace user through
domain-wide delegation.
Groups who is in the admin access groups (accessGroups.js), read
through the Directory API as a Workspace admin, the same
delegation.
Configured by the service environment:
GOOGLE_SERVICE_ACCOUNT path to the key's .json file (never in
the repo)
GOOGLE_SHARED_DRIVE the shared drive's id: only the last part
of its address, not the whole URL
GOOGLE_MAIL_FROM the Workspace address notices come from
GOOGLE_DIRECTORY_AS a Workspace admin (a user) whose view of
groups is read
Each part is off until its settings are there: without a shared drive
the form offers no uploads, and without a sender no mail goes out.
Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */
import { readFileSync } from "node:fs";
import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
const GROUPS_SCOPE = "https://www.googleapis.com/auth/admin.directory.group.member.readonly";
const DRIVE = "https://www.googleapis.com/drive/v3/files";
const DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
export class GoogleError extends Error {}
let key = null;
function serviceKey() {
const file = process.env.GOOGLE_SERVICE_ACCOUNT;
if (!file) return null;
if (!key) {
const parsed = JSON.parse(readFileSync(file, "utf8"));
if (!parsed.client_email || !parsed.private_key) throw new GoogleError(`${file} is not a service account key.`);
key = parsed;
}
return key;
}
export const driveReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_SHARED_DRIVE);
export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM);
export const directoryReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DIRECTORY_AS);
/* ── Access tokens, kept until a minute before they run out ──── */
const tokens = new Map();
async function accessToken(scope, subject) {
const cacheKey = `${scope} ${subject ?? ""}`;
const cached = tokens.get(cacheKey);
if (cached && cached.until > Date.now()) return cached.token;
const sa = serviceKey();
if (!sa) throw new GoogleError("GOOGLE_SERVICE_ACCOUNT is not set.");
const now = Math.floor(Date.now() / 1000);
const part = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const unsigned = `${part({ alg: "RS256", typ: "JWT" })}.${part({
iss: sa.client_email,
scope,
aud: sa.token_uri ?? "https://oauth2.googleapis.com/token",
iat: now,
exp: now + 3600,
...(subject ? { sub: subject } : {}),
})}`;
const signature = createSign("RSA-SHA256").update(unsigned).sign(sa.private_key, "base64url");
const res = await fetch(sa.token_uri ?? "https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: `${unsigned}.${signature}`,
}),
signal: AbortSignal.timeout(15_000),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.access_token) {
throw new GoogleError(`token refused: ${data.error_description ?? data.error ?? res.status}`);
}
tokens.set(cacheKey, { token: data.access_token, until: Date.now() + (data.expires_in - 60) * 1000 });
return data.access_token;
}
async function call(url, init, scope, subject) {
const res = await fetch(url, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) {
const detail = await res.json().catch(() => null);
throw new GoogleError(`${res.status} ${detail?.error?.message ?? res.statusText}`);
}
return res;
}
/* ── Drive ───────────────────────────────────────────────────── */
const FOLDER = "application/vnd.google-apps.folder";
// Folder path → a promise of its id. A promise, so two uploads at
// once don't both make the folder. A failed lookup is forgotten.
const folders = new Map();
/* The id of a folder in the shared drive, eg. "Requests" or
"Media/2026", made if it isn't there. Found by name, so a folder
renamed in Drive is made again under the old name. */
export function driveFolder(path) {
let pending = folders.get(path);
if (!pending) {
pending = findOrMakeFolder(path);
folders.set(path, pending);
pending.catch(() => folders.delete(path));
}
return pending;
}
async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive;
for (const name of path.split("/").filter(Boolean)) {
const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,
corpora: "drive",
driveId: drive,
includeItemsFromAllDrives: "true",
supportsAllDrives: "true",
fields: "files(id)",
});
const found = (await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json()).files?.[0];
parent = found
? found.id
: (
await (
await call(
`${DRIVE}?supportsAllDrives=true&fields=id`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, mimeType: FOLDER, parents: [parent] }),
},
DRIVE_SCOPE,
)
).json()
).id;
}
return parent;
}
/* One file into a folder of the shared drive (driveFolder). Returns
{ id, webViewLink }: Drive's id, and the page that shows it. */
export async function driveUpload(folder, name, mime, buffer) {
const boundary = `ngu${Date.now().toString(36)}`;
const meta = JSON.stringify({ name, parents: [await driveFolder(folder)] });
const body = Buffer.concat([
Buffer.from(
`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n` +
`--${boundary}\r\nContent-Type: ${mime}\r\n\r\n`,
),
buffer,
Buffer.from(`\r\n--${boundary}--`),
]);
const res = await call(
`${DRIVE_UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id,webViewLink`,
{ method: "POST", headers: { "Content-Type": `multipart/related; boundary=${boundary}` }, body },
DRIVE_SCOPE,
);
return await res.json();
}
/* The files (not folders) directly in a folder of the shared drive:
[{ id, name, mimeType, size, webViewLink }]. size is missing for
Google's own Docs, Sheets and Slides. */
export async function driveList(folder) {
const parent = await driveFolder(folder);
const found = [];
let pageToken = "";
do {
const query = new URLSearchParams({
q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`,
corpora: "drive",
driveId: process.env.GOOGLE_SHARED_DRIVE,
includeItemsFromAllDrives: "true",
supportsAllDrives: "true",
pageSize: "200",
fields: "nextPageToken,files(id,name,mimeType,size,webViewLink)",
...(pageToken ? { pageToken } : {}),
});
const page = await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json();
found.push(...(page.files ?? []));
pageToken = page.nextPageToken ?? "";
} while (pageToken);
return found;
}
/* Anyone with the link can view: for files the public site links to.
Refused when the shared drive (or the Workspace) doesn't allow
sharing outside the organization. */
export async function driveShareWithAnyone(id) {
await call(
`${DRIVE}/${encodeURIComponent(id)}/permissions?supportsAllDrives=true`,
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "anyone", role: "reader" }) },
DRIVE_SCOPE,
);
}
/* Drive's picture of a file's first page (PDFs, Office files), as
image bytes about `edge` pixels on the long side, or null while
Drive hasn't drawn one (it does so a little after upload) or can't. */
export async function driveThumbnail(id, edge = 1280) {
const res = await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&fields=hasThumbnail,thumbnailLink`,
{},
DRIVE_SCOPE,
);
const { hasThumbnail, thumbnailLink } = await res.json();
if (!hasThumbnail || !thumbnailLink) return null;
// The link ends in its size, eg. =s220; ask for a bigger one.
const image = await call(thumbnailLink.replace(/=s\d+$/, `=s${edge}`), {}, DRIVE_SCOPE);
return Buffer.from(await image.arrayBuffer());
}
export async function driveDownload(id) {
const res = await call(`${DRIVE}/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`, {}, DRIVE_SCOPE);
return Buffer.from(await res.arrayBuffer());
}
export async function driveDelete(id) {
await call(`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, { method: "DELETE" }, DRIVE_SCOPE);
}
/* ── Gmail ───────────────────────────────────────────────────── */
// A header value can't be allowed to start a new header.
const oneLine = (value) => String(value ?? "").replace(/[\r\n]+/g, " ").trim();
const encodeWord = (value) => `=?UTF-8?B?${Buffer.from(oneLine(value)).toString("base64")}?=`;
/* Plain text mail from GOOGLE_MAIL_FROM. replyTo lets a reply go
straight to whoever filled in the form. */
export async function sendMail({ to, subject, text, replyTo }) {
const from = process.env.GOOGLE_MAIL_FROM;
const headers = [
`From: ${oneLine(from)}`,
`To: ${to.map(oneLine).join(", ")}`,
...(replyTo ? [`Reply-To: ${oneLine(replyTo)}`] : []),
`Subject: ${encodeWord(subject)}`,
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: base64",
];
const raw = `${headers.join("\r\n")}\r\n\r\n${Buffer.from(text).toString("base64")}`;
await call(
"https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ raw: Buffer.from(raw).toString("base64url") }),
},
GMAIL_SCOPE,
from,
);
}
/* ── Groups ──────────────────────────────────────────────────── */
/* Whether someone is in a group, directly or through a group inside
it (the Directory API's hasMember follows nesting in the domain). */
export async function isGroupMember(group, email) {
const url =
"https://admin.googleapis.com/admin/directory/v1/groups/" +
`${encodeURIComponent(group)}/hasMember/${encodeURIComponent(email)}`;
try {
const res = await call(url, {}, GROUPS_SCOPE, process.env.GOOGLE_DIRECTORY_AS);
return (await res.json()).isMember === true;
} catch (err) {
// An address Google doesn't know ("Invalid Input: memberKey",
// "Resource Not Found: memberKey") is in no group of ours. A group
// it doesn't know (groupKey) is a setup mistake, and throws.
if (/^40[04] .*memberKey/i.test(err.message)) return false;
throw new GoogleError(`${group}: ${err.message}`);
}
}

View file

@ -28,16 +28,20 @@ import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
import auth from "./routes/auth.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js";
import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import files from "./routes/files.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { ENTITIES } from "./admin-schema.js";
const HOST = process.env.HOST ?? "127.0.0.1";
@ -169,6 +173,9 @@ app.route("/api", blog);
// Tighter limit on the write path than anything else gets.
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback);
// Requests carry files: fewer again.
app.use("/api/requests", rateLimit({ windowMs: 10 * 60_000, max: 5 }));
app.route("/api/requests", requests);
app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,
@ -179,6 +186,8 @@ app.route("/api/auth", auth);
app.route("/api/admin", admin);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);
app.route("/api/admin", files);
app.route("/api/admin", clips);
app.route("/api/admin", adminEntities);
@ -207,6 +216,7 @@ app.use(
app.route("/", pages);
startSessionSweeper(db);
startGroupSync(db);
startClipWorker(db);
console.log(`clips ${CLIPS_DIR}`);

View file

@ -0,0 +1,72 @@
-- ═══════════════════════════════════════════════════════════════
-- 044 TABLE BLOCKS
--
-- A content block of type 'table': a grid of text, for comparison
-- charts and the like (a blog post imported from Word, say). The
-- grid is the block's text, one row per line, cells split by "|",
-- the first row the header; cells take the same inline formatting as
-- a paragraph (**bold**, *italic*, [link](url)). ContentBlocks.tsx
-- draws it.
--
-- Only the type's CHECK changes, and SQLite can't alter a CHECK, so
-- the table is rebuilt the way 031, 032 and 034 did it
-- (legacy_alter_table around the rename, then its index and owner
-- trigger again).
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout', 'schedule', 'table')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;

View file

@ -0,0 +1,70 @@
-- ═══════════════════════════════════════════════════════════════
-- 045 LINK CARD BLOCKS
--
-- A content block of type 'cards': link cards, one per item, like a
-- link shared in a chat. The item's text is the title, detail the
-- description, url the link and media the picture (the item columns
-- there already are); Fetch preview in the admin fills them.
-- ContentBlocks.tsx draws it.
--
-- Only the type's CHECK changes, so the table is rebuilt as 044 did
-- (legacy_alter_table around the rename, then its index and owner
-- trigger again).
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout', 'schedule', 'table', 'cards')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;

View file

@ -0,0 +1,39 @@
-- ═══════════════════════════════════════════════════════════════
-- 046 CONTENT REQUESTS
--
-- The Request form (/request): someone asks for a blog post, an
-- event, or a new or updated chapter, region, partner, team, award
-- or person, and can attach files (a .docx to fill in, photos).
-- Requests are feedback rows of type 'content', so they share the
-- admin's triage (Forms → Content requests): status, notes, delete.
--
-- category what it's about (REQUEST_TYPES in
-- src/data/requestTypes.ts)
-- request_action 'new' or 'update'
-- subject the title or name, or which record to update
--
-- The files themselves live in Google Drive (googleService.js);
-- feedback_files keeps Drive's id for each, and goes with its row.
--
-- site_settings.notify_emails: who gets an email for each new
-- content or data request (Panel → Site settings), comma separated.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE feedback ADD COLUMN category TEXT
CHECK (category IN ('blog', 'event', 'chapter', 'region', 'partner', 'team', 'award', 'person'));
ALTER TABLE feedback ADD COLUMN request_action TEXT
CHECK (request_action IN ('new', 'update'));
ALTER TABLE feedback ADD COLUMN subject TEXT;
CREATE TABLE feedback_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
feedback_id INTEGER NOT NULL REFERENCES feedback (id) ON DELETE CASCADE,
drive_id TEXT NOT NULL,
name TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL
) STRICT;
CREATE INDEX feedback_files_owner_idx ON feedback_files (feedback_id);
ALTER TABLE site_settings ADD COLUMN notify_emails TEXT;

View file

@ -0,0 +1,29 @@
-- ═══════════════════════════════════════════════════════════════
-- 047 ACCESS BY GOOGLE GROUP
--
-- Admin access from Google Workspace groups (accessGroups.js).
-- Panel → Site settings → Access names a group for each of viewer,
-- editor and admin. Someone in one of them who signs in with Google
-- gets an account with the highest of those roles, and keeps it only
-- while they're in the group. Superadmins and admin-cli accounts are
-- never touched.
--
-- admin_users.access_source 'manual' (admin-cli, the Panel) or
-- 'group' (made by a group sign-in;
-- Google only, role follows the group)
-- admin_users.group_disabled 1 when a group check turned it off
-- (back in a group turns it on again);
-- a superadmin's Disable sets 0, and
-- that one sticks
-- admin_users.groups_checked_at the last group check, UTC
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE admin_users ADD COLUMN access_source TEXT NOT NULL DEFAULT 'manual'
CHECK (access_source IN ('manual', 'group'));
ALTER TABLE admin_users ADD COLUMN group_disabled INTEGER NOT NULL DEFAULT 0
CHECK (group_disabled IN (0, 1));
ALTER TABLE admin_users ADD COLUMN groups_checked_at TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_viewer TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_editor TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_admin TEXT;

View file

@ -0,0 +1,28 @@
-- ═══════════════════════════════════════════════════════════════
-- 048 FILES IN GOOGLE DRIVE
--
-- Files for the public site to link to (a handout, slides, a talk's
-- audio, a brand kit), uploaded from Tools → Media → Files into the
-- shared drive's "Blog" folder (routes/files.js) and shared as
-- "anyone with the link can view". Content blocks link to `url`,
-- Drive's page for the file.
--
-- preview /uploads/... of Drive's picture of the first page, in
-- the media library, once Drive has drawn one (PDFs and
-- Office files); a link card to the file takes it as its
-- picture
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE drive_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
drive_id TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
mime TEXT NOT NULL,
bytes INTEGER NOT NULL CHECK (bytes >= 0),
url TEXT NOT NULL,
preview TEXT,
uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX drive_files_created_idx ON drive_files (created_at DESC);

44
server/src/notify.js Normal file
View file

@ -0,0 +1,44 @@
/* ═══════════════════════════════════════════════════════════════
NEW-REQUEST NOTICES
An email to the people in Panel → Site settings → "Email new
requests to" when a content request (/request) or a data request
(the Privacy page) comes in. Sent after the row is saved and never
waited on: a mail problem is logged, the submission stands.
Off until Gmail is set up (googleService.js) and someone is listed.
═══════════════════════════════════════════════════════════════ */
import { mailReady, sendMail } from "./googleService.js";
import { siteFor } from "./pageMeta.js";
const EMAIL = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
/* The usable addresses in a list separated by commas, semicolons or
spaces; anything else is left out. */
export const addresses = (text) =>
String(text ?? "")
.split(/[\s,;]+/)
.filter((address) => EMAIL.test(address));
export function recipients(db) {
return addresses(db.prepare(`SELECT notify_emails FROM site_settings WHERE id = 'site'`).get()?.notify_emails);
}
/* queue: the admin path of the queue it landed in, eg. /admin/requests */
export function notifyNew(db, { id, subject, lines, replyTo, queue }) {
if (!mailReady()) return;
const to = recipients(db);
if (to.length === 0) return;
let origin = "";
try {
origin = (siteFor(db).url ?? "").replace(/\/$/, "");
} catch {
// No site.json: the notice goes without a link.
}
const text = [...lines, "", origin ? `Open it: ${origin}${queue}` : `In the admin: Forms, ${queue}`, ""].join("\n");
sendMail({ to, subject, text, replyTo: EMAIL.test(replyTo ?? "") ? replyTo : undefined })
.then(() => console.log(`feedback #${id}: notice sent to ${to.length}`))
.catch((err) => console.warn(`feedback #${id}: notice failed: ${err.message}`));
}

View file

@ -43,6 +43,7 @@ import { fileURLToPath } from "node:url";
import { loadBlocks, paragraphs } from "./shape.js";
import { themeCss } from "./theme.js";
import { driveReady } from "./googleService.js";
const here = path.dirname(fileURLToPath(import.meta.url));
@ -112,7 +113,13 @@ export function siteFor(db) {
}
/* What the browser app reads for headings and titles. */
const forBrowser = (site) => ({ title: site.title, pages: site.pages, privacyEmail: site.privacyEmail });
// requestFiles: whether the Request form can take files (Drive set up).
const forBrowser = (site) => ({
title: site.title,
pages: site.pages,
privacyEmail: site.privacyEmail,
requestFiles: driveReady(),
});
/* robots.txt for this database's setting, as the build writes it. */
export function robotsTxt(site) {

View file

@ -11,6 +11,9 @@
import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload } from "../googleService.js";
import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js";
const admin = new Hono();
@ -18,13 +21,39 @@ admin.use("*", requireAuth);
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
// Website feedback, data requests and content requests share the
// table but are three queues in the admin (Forms).
const KIND_WHERE = {
feedback: "feedback_type NOT IN ('privacy', 'content')",
privacy: "feedback_type = 'privacy'",
content: "feedback_type = 'content'",
};
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject`;
/* Each row with its files (content requests), in one query. */
function withFiles(db, rows) {
if (rows.length === 0) return rows;
const files = db
.prepare(
`SELECT id, feedback_id, name, mime, size FROM feedback_files
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
)
.all(...rows.map((r) => r.id));
return rows.map((row) => ({
...row,
files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f),
}));
}
const MAX_LIMIT = 200;
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=feedback website feedback (every type but the two below)
?kind=privacy data requests from the Privacy page
?kind=content content requests from /request, with files
?type=broken feedback_type
?q=retreat substring of the message
?before=41 cursor: rows with a lower id than this
@ -38,10 +67,7 @@ admin.get("/feedback", (c) => {
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;
const kindWhere = KIND_WHERE[kind] ?? null;
if (kindWhere) where.push(kindWhere);
if (STATUSES.includes(status)) {
@ -53,8 +79,8 @@ admin.get("/feedback", (c) => {
params.push(type.slice(0, 40));
}
if (q) {
where.push("message LIKE ?");
params.push(`%${q.slice(0, 100)}%`);
where.push("(message LIKE ? OR subject LIKE ?)");
params.push(`%${q.slice(0, 100)}%`, `%${q.slice(0, 100)}%`);
}
if (before && Number.isInteger(Number(before))) {
where.push("id < ?");
@ -65,8 +91,7 @@ admin.get("/feedback", (c) => {
const rows = db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
`SELECT ${COLUMNS}
FROM feedback
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY id DESC
@ -75,7 +100,7 @@ admin.get("/feedback", (c) => {
.all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take;
const page = hasMore ? rows.slice(0, take) : rows;
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows);
// Status counts cover this queue (kind) but ignore the other
// filters: the tabs show what's waiting, not what's left after a
@ -88,7 +113,8 @@ admin.get("/feedback", (c) => {
}
const newByKind = db
.prepare(
`SELECT SUM(feedback_type <> 'privacy') AS feedback, SUM(feedback_type = 'privacy') AS privacy
`SELECT SUM(${KIND_WHERE.feedback}) AS feedback, SUM(${KIND_WHERE.privacy}) AS privacy,
SUM(${KIND_WHERE.content}) AS content
FROM feedback WHERE status = 'new'`,
)
.get();
@ -97,7 +123,11 @@ admin.get("/feedback", (c) => {
{
feedback: page,
counts,
newByKind: { feedback: newByKind?.feedback ?? 0, privacy: newByKind?.privacy ?? 0 },
newByKind: {
feedback: newByKind?.feedback ?? 0,
privacy: newByKind?.privacy ?? 0,
content: newByKind?.content ?? 0,
},
nextCursor: hasMore ? page[page.length - 1].id : null,
},
200,
@ -155,13 +185,7 @@ function db_update(db, id, sets, params) {
if (changed.changes === 0) return null;
return db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
FROM feedback WHERE id = ?`,
)
.get(id);
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0];
}
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -170,20 +194,78 @@ function db_update(db, id, sets, params) {
the content itself shouldn't stay on disk.
───────────────────────────────────────────────────────────── */
admin.delete("/feedback/:id", requireRole("admin"), (c) => {
admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
const id = Number(c.req.param("id"));
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
const result = c
.get("db")
.prepare("DELETE FROM feedback WHERE id = ?")
.run(id);
const db = c.get("db");
const files = db.prepare(`SELECT drive_id FROM feedback_files WHERE feedback_id = ?`).all(id);
const result = db.prepare("DELETE FROM feedback WHERE id = ?").run(id);
if (result.changes === 0) return c.json({ error: "No such feedback." }, 404);
// The row is gone either way; a file Drive won't delete is logged
// for someone to remove from the folder by hand.
for (const { drive_id } of files) {
try {
await driveDelete(drive_id);
} catch (err) {
console.warn(`feedback #${id}: Drive file ${drive_id} not deleted: ${err.message}`);
}
}
console.log(`feedback #${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
/* ── A content request's files ───────────────────────────────────
GET /feedback/:id/files/:file download, from Drive
POST /feedback/:id/files/:file/blog-post a .docx as a new
unpublished blog post (import.js), editors and up
───────────────────────────────────────────────────────────── */
function fileOf(c) {
return c
.get("db")
.prepare(`SELECT id, drive_id, name, mime FROM feedback_files WHERE id = ? AND feedback_id = ?`)
.get(Number(c.req.param("file")), Number(c.req.param("id")));
}
async function fromDrive(file) {
try {
return await driveDownload(file.drive_id);
} catch (err) {
console.warn(`feedback file ${file.id}: Drive download failed: ${err.message}`);
throw new HttpError(502, "Google Drive didn't send that file. Try again, or find it in the Drive folder.");
}
}
admin.get("/feedback/:id/files/:file", async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
try {
return c.body(await fromDrive(file), 200, {
...NO_STORE,
"Content-Type": file.mime,
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`,
"X-Content-Type-Options": "nosniff",
});
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
throw err;
}
});
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
if (!/\.docx$/i.test(file.name)) return c.json({ error: "Only a Word document (.docx) can become a post." }, 400);
try {
return c.json(importDocx(c.get("db"), await fromDrive(file), file.name, c.get("user").email), 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;
}
});
export default admin;

View file

@ -19,12 +19,14 @@
A failed login still runs a hash. Otherwise the response time
itself says whether the account exists.
Nothing here creates accounts. See admin-cli.js. Google sign-in
only lets in an account that already exists: matched by its
linked Google id, or on first use by its email, which then links
it. A matching email already linked to a different Google
account is refused rather than relinked. googleAuth.js checks
the identity itself.
Accounts come from admin-cli.js, with one exception: with access
groups set up (accessGroups.js), a Google sign-in by someone in
one makes a group account, whose role then follows the group.
Otherwise Google sign-in only lets in an account that already
exists: matched by its linked Google id, or on first use by its
email, which then links it. A matching email already linked to a
different Google account is refused rather than relinked.
googleAuth.js checks the identity itself.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
@ -41,6 +43,7 @@ import {
verifyPassword,
} from "../auth.js";
import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js";
import { accessEnabled, applyGroupRole, groupRole } from "../accessGroups.js";
import { failureLimit } from "../rateLimit.js";
import { NO_STORE } from "../shape.js";
@ -208,24 +211,65 @@ auth.get("/google/callback", async (c) => {
}
const db = c.get("db");
const columns = `id, email, name, role, is_active, google_sub`;
const columns = `id, email, name, role, is_active, google_sub, access_source, group_disabled`;
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
// What the access groups give this person (accessGroups.js), asked
// only when it matters. Unanswerable is a refusal: a sign-in has to
// be shown to be allowed.
const roleFromGroups = async () => {
try {
return { role: await groupRole(db, identity.email) };
} catch (err) {
console.warn(`google login: groups unreadable for ${identity.email}: ${err.message}`);
return { failed: true };
}
};
if (!user) {
const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!byEmail) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
if (byEmail.google_sub) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
// In an access group: the account is made now, Google only.
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (!found.role) {
console.warn(`google login: ${identity.email} is in no access group`);
return backToLogin(c, "not_in_group");
}
const id = db
.prepare(
`INSERT INTO admin_users (email, name, role, google_sub, access_source, groups_checked_at)
VALUES (?, ?, ?, ?, 'group', datetime('now'))`,
)
.run(identity.email, identity.name, found.role, identity.sub).lastInsertRowid;
console.log(`account ${identity.email} made from access group (${found.role})`);
user = byId(id);
} else if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return backToLogin(c, "linked_elsewhere");
} else {
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
}
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
}
// A group account's role follows its groups, checked every time.
// One a superadmin disabled stays disabled whatever its groups say.
if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) {
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
applyGroupRole(db, user, found.role);
if (!found.role) return backToLogin(c, "not_in_group");
user = byId(user.id);
}
if (user.is_active !== 1) return backToLogin(c, "disabled");

View file

@ -16,6 +16,7 @@
import { Hono } from "hono";
import { clientIp, hashIp } from "../auth.js";
import { notifyNew } from "../notify.js";
const feedback = new Hono();
@ -36,14 +37,14 @@ const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other",
/* ── Input cleaning ──────────────────────────────────────────── */
function clean(value, max) {
export function clean(value, max) {
if (typeof value !== "string") return "";
return value.trim().slice(0, max);
}
// Deliberately permissive. Rejecting odd-but-valid addresses loses
// real submissions, and the field is optional anyway.
function looksLikeEmail(value) {
export function looksLikeEmail(value) {
return value === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
@ -108,6 +109,15 @@ feedback.post("/", async (c) => {
// created_at and status come from column defaults.
console.log(`feedback #${result.lastInsertRowid} (${feedbackType})`);
if (feedbackType === "privacy") {
notifyNew(db, {
id: result.lastInsertRowid,
subject: "Data request from the Privacy page",
lines: [`From: ${name ? `${name} <${email}>` : email}`, "", message],
replyTo: email,
queue: "/admin/data-requests",
});
}
return c.body(null, 204);
});

254
server/src/routes/files.js Normal file
View file

@ -0,0 +1,254 @@
/* ═══════════════════════════════════════════════════════════════
FILE ROUTES: mounted under /api/admin
GET /files the files, newest first, ?q=name.
Picks up files put in the folder
in Drive by hand first (pickUp, at
most every SCAN_EVERY_MS)
POST /files upload one (multipart: file)
GET /files/:id/uses which records link to it
DELETE /files/:id out of Drive and the list
Files for the public site to link to, kept in the shared drive's
FOLDER (googleService.js) and shared as "anyone with the link can
view", so a link opens Drive's viewer. Content blocks' link fields
pick from here ("Choose a file"); a link card takes the file's name
and its first-page preview too.
The preview: Drive draws a picture of a PDF's or Office file's
first page a little after upload. It's asked for straight away and
again over the next few minutes (PREVIEW_TRIES), and saved into the
media library as an ordinary upload when it comes.
Files added to the folder in Drive itself (not through here) are
listed too: the next look at the list finds them, shares them the
same way and fetches their previews. Google's own Docs, Sheets and
Slides count; folders and shortcuts don't. One that Drive won't
share is left out and named in the list's `refused`.
The same ladder as media: reading needs a session, uploading
editor, deleting admin. nginx needs a block for POST /files
(docs/google-drive-and-mail.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js";
import { NO_STORE } from "../shape.js";
const files = new Hono();
files.use("*", requireAuth);
const FOLDER = "Media";
const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_LIST = 500;
// Seconds after upload to ask Drive for the preview again.
const PREVIEW_TRIES = [0, 5, 20, 60, 180];
// How often listing the files looks in the Drive folder for new ones.
const SCAN_EVERY_MS = 30_000;
const SKIP_TYPES = new Set(["application/vnd.google-apps.folder", "application/vnd.google-apps.shortcut"]);
/* What a file is: its first bytes and its name have to agree (Office
files are zips, so for them the name is what tells them apart). A
PDF named .mp3 is refused, so a download is always what it says. */
const ZIPPED = {
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
zip: "application/zip",
};
export function kindOf(bytes, name) {
const ext = String(name).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];
const starts = (at, ...sig) => sig.every((b, i) => bytes[at + i] === b);
if (ext === "pdf" && starts(0, 0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
if (starts(0, 0x50, 0x4b, 0x03, 0x04) && ZIPPED[ext]) return ZIPPED[ext];
if (ext === "mp3" && (starts(0, 0x49, 0x44, 0x33) || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0))) return "audio/mpeg";
if (ext === "m4a" && starts(4, 0x66, 0x74, 0x79, 0x70)) return "audio/mp4";
return null;
}
const safeName = (name) =>
String(name ?? "file")
.replace(/[\u0000-\u001f"\\/]+/g, " ")
.trim()
.slice(0, 150) || "file";
const SELECT = `SELECT f.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email
FROM drive_files f LEFT JOIN admin_users u ON u.id = f.uploaded_by`;
const shape = (row) => ({
id: row.id,
name: row.name,
// What a link card calls it: the name without its extension.
title: row.name.replace(/\.[a-z0-9]+$/i, ""),
mime: row.mime,
bytes: row.bytes,
url: row.url,
preview: row.preview,
uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null,
created_at: row.created_at,
});
/* Asks Drive for the first-page picture until it has one or the
tries run out; saved into the media library. Never throws. */
function fetchPreview(db, row, userId) {
let attempt = 0;
const next = async () => {
try {
const image = await driveThumbnail(row.drive_id);
if (image) {
const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId });
db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(`/uploads/${saved.filename}`, row.id);
return;
}
} catch (err) {
console.warn(`files: preview for ${row.name}: ${err.message}`);
}
attempt++;
if (attempt < PREVIEW_TRIES.length) setTimeout(next, (PREVIEW_TRIES[attempt] - PREVIEW_TRIES[attempt - 1]) * 1000).unref();
};
return next();
}
/* Files put in the folder in Drive by hand, added to the list and
shared. A file Drive won't share is tried again after RETRY_MS, not
on every look (a sharing setting fixed in the meantime then takes).
Never throws: the list still shows what's known. */
const RETRY_MS = 10 * 60 * 1000;
let lastScan = 0;
const refused = new Map(); // drive id → { name, at }
async function pickUp(db) {
if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return;
lastScan = Date.now();
let found;
try {
found = await driveList(FOLDER);
} catch (err) {
console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`);
return;
}
const known = new Set(db.prepare(`SELECT drive_id FROM drive_files`).all().map((r) => r.drive_id));
for (const file of found) {
if (known.has(file.id) || SKIP_TYPES.has(file.mimeType)) continue;
if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue;
try {
await driveShareWithAnyone(file.id);
} catch (err) {
console.warn(`files: ${file.name} (added in Drive) not shared: ${err.message}`);
refused.set(file.id, { name: file.name, at: Date.now() });
continue;
}
refused.delete(file.id);
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url) VALUES (?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink).lastInsertRowid;
console.log(`files: ${file.name} picked up from Drive`);
// In the background: a folder of new files shouldn't hold the list.
fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null);
}
}
files.get("/files", async (c) => {
await pickUp(c.get("db"));
const q = (c.req.query("q") ?? "").trim().slice(0, 100);
const rows = c
.get("db")
.prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`)
.all(...(q ? [`%${q}%`] : []));
return c.json({ files: rows.map(shape), ready: driveReady(), refused: [...refused.values()].map((r) => r.name) }, 200, NO_STORE);
});
files.post(
"/files",
requireRole("editor"),
bodyLimit({
maxSize: MAX_FILE_BYTES + 64 * 1024,
onError: (c) => c.json({ error: `Files can be ${MAX_FILE_BYTES / 1024 / 1024} MB at most.` }, 413),
}),
async (c) => {
if (!driveReady()) {
return c.json({ error: "Google Drive isn't set up on the server (docs/google-drive-and-mail.md)." }, 400);
}
const db = c.get("db");
const user = c.get("user");
let body;
try {
body = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = body.file;
if (!(file instanceof File) || file.size === 0) return c.json({ error: "No file was sent." }, 400);
const buffer = Buffer.from(await file.arrayBuffer());
const mime = kindOf(buffer, file.name);
if (!mime) {
return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415);
}
const name = safeName(file.name);
let uploaded;
try {
uploaded = await driveUpload(FOLDER, name, mime, buffer);
} catch (err) {
console.warn(`files: upload of ${name} failed: ${err.message}`);
return c.json({ error: `Google Drive didn't take it: ${err.message}` }, 502);
}
try {
await driveShareWithAnyone(uploaded.id);
} catch (err) {
console.warn(`files: sharing ${name} failed: ${err.message}`);
await driveDelete(uploaded.id).catch(() => {});
return c.json(
{
error:
`Drive wouldn't share it with anyone who has the link (${err.message}). ` +
"The shared drive's settings, or the Workspace's sharing settings, must allow sharing outside the organization.",
},
502,
);
}
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, buffer.length, uploaded.webViewLink, user.id).lastInsertRowid;
const row = db.prepare(`${SELECT} WHERE f.id = ?`).get(id);
console.log(`files: ${name} uploaded by ${user.email}`);
// The first try is waited for; Drive often has the picture already.
await fetchPreview(db, row, user.id);
return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE);
},
);
function findOr404(c) {
const id = Number(c.req.param("id"));
return Number.isInteger(id) ? c.get("db").prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id) : null;
}
files.get("/files/:id/uses", (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
return c.json({ uses: recordsNaming(c.get("db"), [row.url]) }, 200, NO_STORE);
});
files.delete("/files/:id", requireRole("admin"), async (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
try {
await driveDelete(row.drive_id);
} catch (err) {
// Already gone from Drive (deleted by hand): the row goes anyway.
if (!/^404 /.test(err.message)) {
return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
}
c.get("db").prepare(`DELETE FROM drive_files WHERE id = ?`).run(row.id);
console.log(`files: ${row.name} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
export default files;

123
server/src/routes/import.js Normal file
View file

@ -0,0 +1,123 @@
/* ═══════════════════════════════════════════════════════════════
IMPORT ROUTES (mounted under /api/admin)
POST /import/docx a Word document → a new blog post, unpublished
Blog posts → Import from Word. The document becomes a draft post
(docx.js decides what each part becomes), created through the same
CRUD engine as the editor, so it's validated the same way. The
reply says what came over and what didn't (images), and the admin
opens the new post for review before anyone publishes it.
nginx caps /api/ bodies at 64k; this path needs its own block
with a larger client_max_body_size (docs/media-uploads.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { createRow, HttpError } from "../admin-crud.js";
import { ENTITIES } from "../admin-schema.js";
import { DocxError, readDocx } from "../docx.js";
import { NO_STORE } from "../shape.js";
const MAX_DOCX_BYTES = 10 * 1024 * 1024;
const imports = new Hono();
imports.use("*", requireAuth);
const slug = (text) =>
String(text ?? "")
.toLowerCase()
.normalize("NFKD")
.replace(/[^\w\s-]/g, "")
.trim()
.replace(/[\s_]+/g, "-")
.replace(/-+/g, "-")
.slice(0, 64)
.replace(/-$/, "") || "imported-post";
/* A free URL ID: the title's slug, or it with -2, -3... */
function freeId(db, base) {
const taken = (id) => db.prepare(`SELECT 1 FROM blog_posts WHERE id = ?`).get(id);
let id = base;
for (let n = 2; taken(id); n++) id = `${base.slice(0, 60)}-${n}`;
return id;
}
/* A Word document as a new unpublished blog post, through the CRUD
engine. Returns { id, summary }; an unreadable document is a 400
HttpError. Also used by Forms → Content requests, on a file someone
sent with the Request form. */
export function importDocx(db, buffer, fileName, byEmail) {
let doc;
try {
doc = readDocx(buffer);
} catch (err) {
throw new HttpError(400, err instanceof DocxError ? err.message : "That document couldn't be read. Save it again as .docx and retry.");
}
if (doc.blocks.length === 0) throw new HttpError(400, "That document has no text to import.");
const title = doc.title || String(fileName ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const row = createRow(db, ENTITIES.blog_posts, {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
});
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${byEmail}`);
return {
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
};
}
imports.post(
"/import/docx",
requireRole("editor"),
bodyLimit({
maxSize: MAX_DOCX_BYTES + 64 * 1024,
onError: (c) => c.json({ error: "That document is too large (10 MB at most)." }, 413),
}),
async (c) => {
const db = c.get("db");
let body;
try {
body = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = body.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
try {
const result = importDocx(db, Buffer.from(await file.arrayBuffer()), file.name, c.get("user").email);
return c.json(result, 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;
}
},
);
export default imports;

View file

@ -52,7 +52,7 @@ const SCAN_EVERY_MS = 30_000;
let lastScan = 0;
/* Tables that can't hold an image path, or mustn't be searched. */
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]);
const NOT_CONTENT = new Set(["media", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
function shape(row) {
return {
@ -77,7 +77,7 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e
/* Writes the file, then its row; a failed insert takes the file
back out so nothing is left on disk that the library can't see. */
async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) {
export async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) {
const stored = await store(buf, { keepOriginal });
try {
const { lastInsertRowid } = db
@ -203,13 +203,18 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
same place. Read from the live schema rather than a list of image
columns, so a new image field is covered the day it's added. */
function usesOf(db, filename) {
const values = [
...new Set([
`${PUBLIC_PREFIX}${filename}`,
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
filename,
]),
];
return recordsNaming(db, [
`${PUBLIC_PREFIX}${filename}`,
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
filename,
]);
}
/* Which content tables have a TEXT column holding exactly one of
`values`: [{ table, count }]. Also how Tools → Media → Files finds
what links to a file (routes/files.js). */
export function recordsNaming(db, values) {
values = [...new Set(values)];
const tables = db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()

View file

@ -4,6 +4,9 @@
GET /api/admin/panel/overview
PATCH /api/admin/panel/users/:id role, is_active
DELETE /api/admin/panel/users/:id/sessions sign out everywhere
POST /api/admin/panel/test-notice { to }: a test email
POST /api/admin/panel/access-sync recheck every group account
POST /api/admin/panel/access-check { email }: what their groups give
Everything here is superadmin-only, enforced once at the top
rather than per route; there's no read here that an ordinary
@ -27,6 +30,9 @@ import { Hono } from "hono";
import { requireAuth, requireRole, ROLES } from "../auth.js";
import { tx } from "../db.js";
import { NO_STORE } from "../shape.js";
import { directoryReady, mailReady, sendMail } from "../googleService.js";
import { addresses } from "../notify.js";
import { accessEnabled, accessGroups, groupRole, syncGroupAccounts } from "../accessGroups.js";
const panel = new Hono();
@ -54,7 +60,8 @@ panel.get("/overview", (c) => {
const users = db
.prepare(
`SELECT u.id, u.email, u.name, u.role, u.is_active,
u.created_at, u.last_login_at,
u.created_at, u.last_login_at, u.access_source, u.group_disabled,
u.groups_checked_at,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id
AND s.expires_at > datetime('now')) AS sessions
@ -82,6 +89,12 @@ panel.get("/overview", (c) => {
},
content,
users,
// Google groups (accessGroups.js): which are set, and whether the
// server can read them.
access: {
directory: directoryReady(),
groups: Object.fromEntries(accessGroups(db)),
},
},
200,
NO_STORE,
@ -124,10 +137,17 @@ panel.patch("/users/:id", async (c) => {
}
const target = db
.prepare("SELECT id, email, role, is_active FROM admin_users WHERE id = ?")
.prepare("SELECT id, email, role, is_active, access_source FROM admin_users WHERE id = ?")
.get(id);
if (!target) return c.json({ error: "No such account." }, 404);
if (target.access_source === "group" && body.role !== undefined && body.role !== target.role) {
return c.json(
{ error: "This account's role comes from its Google group. Change the group membership instead." },
409,
);
}
const sets = [];
const params = [];
@ -152,6 +172,8 @@ panel.patch("/users/:id", async (c) => {
if (body.is_active !== undefined) {
sets.push("is_active = ?");
params.push(Number(body.is_active) ? 1 : 0);
// A superadmin's choice: no group check undoes it (accessGroups.js).
sets.push("group_disabled = 0");
}
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
@ -205,7 +227,8 @@ function userRow(db, id) {
return db
.prepare(
`SELECT u.id, u.email, u.name, u.role, u.is_active,
u.created_at, u.last_login_at,
u.created_at, u.last_login_at, u.access_source, u.group_disabled,
u.groups_checked_at,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id
AND s.expires_at > datetime('now')) AS sessions
@ -214,4 +237,84 @@ function userRow(db, id) {
.get(id);
}
/* ── POST /test-notice ───────────────────────────────────────────
Site settings → Notices → "Send a test notice": one email to the
addresses in the box (saved or not), now, with Google's own words
if it refuses, so the setup can be checked without the journal.
───────────────────────────────────────────────────────────── */
panel.post("/test-notice", async (c) => {
if (!mailReady()) {
return c.json(
{ error: "Mail isn't set up on the server: GOOGLE_SERVICE_ACCOUNT and GOOGLE_MAIL_FROM (docs/google-drive-and-mail.md)." },
400,
);
}
const body = (await c.req.json().catch(() => null)) ?? {};
const to = addresses(body.to).slice(0, 10);
if (to.length === 0) return c.json({ error: "Enter at least one email address first." }, 422);
const from = process.env.GOOGLE_MAIL_FROM;
try {
await sendMail({
to,
subject: "Test notice from the NGU website",
text: [
"This is a test from Panel → Site settings → Notices.",
"",
`Sent by ${c.get("user").email}, from ${from}.`,
"New content requests and data requests will arrive like this.",
"",
].join("\n"),
});
} catch (err) {
console.warn(`test notice by ${c.get("user").email} failed: ${err.message}`);
return c.json({ error: `Google refused it: ${err.message}` }, 502);
}
console.log(`test notice sent by ${c.get("user").email} to ${to.length}`);
return c.json({ sent: to, from }, 200, NO_STORE);
});
/* ── Access by Google group ──────────────────────────────────────
access-sync every group account against its groups now (the
timer only rechecks signed-in ones, hourly)
access-check what someone's groups would give them, changing
nothing: for checking the setup
───────────────────────────────────────────────────────────── */
const accessOff = (c, db) =>
accessEnabled(db)
? null
: c.json(
{
error: directoryReady()
? "No access groups set: Panel → Site settings → Access."
: "Group lookups aren't set up on the server: GOOGLE_SERVICE_ACCOUNT and GOOGLE_DIRECTORY_AS (docs/google-sign-in.md).",
},
400,
);
panel.post("/access-sync", async (c) => {
const db = c.get("db");
const off = accessOff(c, db);
if (off) return off;
const result = await syncGroupAccounts(db, { all: true });
console.log(`access re-sync by ${c.get("user").email}: ${result.checked} checked, ${result.changes.length} changed, ${result.failed.length} failed`);
return c.json(result, 200, NO_STORE);
});
panel.post("/access-check", async (c) => {
const db = c.get("db");
const off = accessOff(c, db);
if (off) return off;
const body = (await c.req.json().catch(() => null)) ?? {};
const email = String(body.email ?? "").trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return c.json({ error: "Enter an email address." }, 422);
try {
return c.json({ email, role: await groupRole(db, email) }, 200, NO_STORE);
} catch (err) {
return c.json({ error: `Google couldn't say: ${err.message}` }, 502);
}
});
export default panel;

View file

@ -0,0 +1,167 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST ROUTE: POST /api/requests
The Request form (/request): a blog post, an event, or a new or
updated chapter, region, partner, team, award or person, with up
to MAX_FILES attachments. Stored as a feedback row of type
'content' (046_content_requests.sql), files in Google Drive.
The same defences as the feedback route (honeypot, length caps,
a rate limit where it's mounted), plus: files are judged by their
first bytes, not the name or type the browser claims, and nothing
goes to Drive until everything else has passed.
nginx caps /api/ bodies at 64k; this path needs its own block
(docs/google-drive-and-mail.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { clientIp, hashIp } from "../auth.js";
import { clean, looksLikeEmail } from "./feedback.js";
import { driveDelete, driveReady, driveUpload } from "../googleService.js";
import { notifyNew } from "../notify.js";
const requests = new Hono();
// Must match REQUEST_TYPES in src/data/requestTypes.ts and the CHECK
// in 046_content_requests.sql. The actions each category allows.
const CATEGORIES = {
blog: ["new"],
event: ["new", "update"],
chapter: ["new", "update"],
region: ["update"],
partner: ["new", "update"],
team: ["new", "update"],
award: ["new", "update"],
person: ["new", "update"],
};
const LIMITS = { name: 120, email: 254, subject: 200, message: 5000 };
const MIN_MESSAGE = 10;
// Where in the shared drive the files go (googleService.js).
const DRIVE_FOLDER = "Requests";
export const MAX_FILES = 3;
export const MAX_FILE_BYTES = 10 * 1024 * 1024;
/* What a file is, from its first bytes. A zip is only taken as a
Word document when it's named like one. */
const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
function kindOf(bytes, name) {
const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
if (starts(0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
if (starts(0xff, 0xd8, 0xff)) return "image/jpeg";
if (starts(0x89, 0x50, 0x4e, 0x47)) return "image/png";
if (starts(0x50, 0x4b, 0x03, 0x04) && /\.docx$/i.test(name)) return DOCX;
return null;
}
// A file name as Drive and a download header will see it.
const safeName = (name) =>
String(name ?? "file")
.replace(/[\u0000-\u001f"\\/]+/g, " ")
.trim()
.slice(0, 150) || "file";
requests.post(
"/",
bodyLimit({
maxSize: MAX_FILES * MAX_FILE_BYTES + 64 * 1024,
onError: (c) => c.json({ error: `Files can be ${MAX_FILE_BYTES / 1024 / 1024} MB each at most.` }, 413),
}),
async (c) => {
let body;
try {
body = await c.req.parseBody({ all: true });
} catch {
return c.json({ error: "Expected a form." }, 400);
}
const field = (name, max) => clean(Array.isArray(body[name]) ? body[name][0] : body[name], max);
if (field("website", 50) !== "") return c.body(null, 204); // honeypot
const category = field("category", 20);
const action = field("action", 10);
const subject = field("subject", LIMITS.subject);
const message = field("message", LIMITS.message);
const name = field("name", LIMITS.name);
const email = field("email", LIMITS.email);
const files = [body.files ?? []].flat().filter((f) => f instanceof File && f.size > 0);
const errors = {};
if (!CATEGORIES[category]) errors.category = "Choose what this is about.";
else if (!CATEGORIES[category].includes(action)) errors.action = "Choose new or update.";
if (!subject) errors.subject = "Give it a name.";
if (message.length < MIN_MESSAGE) errors.message = "Please write a little more.";
if (!email) errors.email = "We need an email address to follow up.";
else if (!looksLikeEmail(email)) errors.email = "That email doesn't look right.";
const uploads = [];
if (files.length > 0 && !driveReady()) errors.files = "File uploads aren't set up yet. Describe it in the message instead.";
else if (files.length > MAX_FILES) errors.files = `${MAX_FILES} files at most.`;
else {
for (const file of files) {
if (file.size > MAX_FILE_BYTES) {
errors.files = `${file.name} is over ${MAX_FILE_BYTES / 1024 / 1024} MB.`;
break;
}
const buffer = Buffer.from(await file.arrayBuffer());
const mime = kindOf(buffer, file.name);
if (!mime) {
errors.files = `${file.name} isn't a Word document (.docx), PDF, JPEG or PNG.`;
break;
}
uploads.push({ name: safeName(file.name), mime, buffer });
}
}
if (Object.keys(errors).length > 0) return c.json({ error: "Validation failed", fields: errors }, 422);
const db = c.get("db");
const id = Number(
db
.prepare(
`INSERT INTO feedback
(feedback_type, category, request_action, subject, message, name, email, user_agent, ip_hash)
VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(category, action, subject, message, name || null, email, clean(c.req.header("user-agent"), 500) || null, hashIp(clientIp(c)))
.lastInsertRowid,
);
// The row first, so each file in Drive is named for it; if Drive
// fails, the row and whatever did upload go again.
const stored = [];
try {
for (const file of uploads) {
stored.push({ ...file, driveId: (await driveUpload(DRIVE_FOLDER, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id });
}
} catch (err) {
console.warn(`feedback #${id}: Drive upload failed: ${err.message}`);
await Promise.allSettled(stored.map((f) => driveDelete(f.driveId)));
db.prepare(`DELETE FROM feedback WHERE id = ?`).run(id);
return c.json({ error: "Your files couldn't be stored just now. Try again in a moment." }, 502);
}
const addFile = db.prepare(`INSERT INTO feedback_files (feedback_id, drive_id, name, mime, size) VALUES (?, ?, ?, ?, ?)`);
for (const f of stored) addFile.run(id, f.driveId, f.name, f.mime, f.buffer.length);
console.log(`feedback #${id} (content: ${action} ${category}, ${stored.length} files)`);
notifyNew(db, {
id,
subject: `Request: ${action} ${category}: ${subject}`,
lines: [
`${action === "new" ? "New" : "Update"} ${category}: ${subject}`,
`From: ${name ? `${name} <${email}>` : email}`,
...(stored.length ? [`Files: ${stored.map((f) => f.name).join(", ")}`] : []),
"",
message,
],
replyTo: email,
queue: "/admin/requests",
});
return c.body(null, 204);
},
);
export default requests;

View file

@ -132,6 +132,18 @@ const ALL_BLOCKS = [
["subheading", { text: "Video" }],
["video", { href: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", text: "A YouTube video, with its own thumbnail" }],
["video", { href: "https://vimeo.com/76979871", media: IMAGE, text: "A Vimeo video with an uploaded still" }],
["subheading", { text: "Table" }],
["table", { text: [
"Platform | Monthly cost | Best for | Notes",
"[Zeffy](https://www.zeffy.com) | Free | Fee-free giving | **0%** to the church",
"Breeze | $72 | Small churches | Flat price, all features",
"A cell with a bar \\| in it | Blank cells follow | |",
].join("\n") }],
["subheading", { text: "Link cards" }],
["cards", {}, [
{ text: "A card with a picture", detail: "Its description, up to three lines, under the title. The whole card is the link.", url: "/retreats", media: IMAGE },
{ text: "An outside link, text only", detail: "The card shows the site it goes to above the title.", url: "https://example.org" },
]],
];
/* A record page's body: a handful of types, so it reads like a

View file

@ -38,6 +38,10 @@
"title": "Feedback",
"description": "Tell us what's working, what isn't, and what you'd like to see next."
},
"/request": {
"title": "Request",
"description": "Ask for a blog post, an event, or a new or updated chapter, region, partner, team, award or person on the site."
},
"/qr": {
"title": "QR Codes",
"description": "Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colours."

View file

@ -55,6 +55,7 @@ const Leadership = lazyPage(() => import("./pages/Leadership.tsx"))
const Resources = lazyPage(() => import("./pages/Resources.tsx"))
const History = lazyPage(() => import("./pages/History.tsx"))
const Feedback = lazyPage(() => import("./pages/Feedback.tsx"))
const Request = lazyPage(() => import("./pages/Request.tsx"))
const Giving = lazyPage(() => import("./pages/Giving.tsx"))
const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
@ -104,6 +105,7 @@ export default function App() {
<Route path="resources" element={<Resources />} />
<Route path="history" element={<History />} />
<Route path="feedback" element={<Feedback />} />
<Route path="request" element={<Request />} />
<Route path="qr" element={<QrCodes />} />
<Route path="give" element={<Giving />} />
<Route path="privacy" element={<Privacy />} />
@ -129,6 +131,7 @@ export default function App() {
</Route>
<Route path="feedback" element={<AdminFeedback />} />
<Route path="data-requests" element={<AdminFeedback kind="privacy" />} />
<Route path="requests" element={<AdminFeedback kind="content" />} />
<Route path="media" element={<AdminMedia />} />
<Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} />

View file

@ -23,6 +23,9 @@
text, detail, url, location, person, and
a fold-out of description, media, map);
text is an optional intro. ScheduleBlock
table text: a row per line, cells split by |
cards items as link cards: text the title,
detail, url, media the picture
divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
@ -34,12 +37,14 @@
═══════════════════════════════════════════════════════════════ */
import { mediaUrl } from '../lib/media.ts'
import type { ContentBlock } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs } from './InlineText.tsx'
import type { ContentBlock, ContentBlockItem } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs, isExternalUrl } from './InlineText.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import ScheduleBlock from './ScheduleBlock.tsx'
import { accentText, BRAND } from '../lib/color.ts'
import { headingAnchors } from '../lib/contents.ts'
import { SITE_NAME } from '../lib/site.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
const BODY = 'var(--color-muted)'
@ -66,6 +71,56 @@ export default function ContentBlocks({
)
}
/* One link card: the whole card is the link. The site's name above
the title says where it goes (the host for an outside link). */
function LinkCard({ item }: { item: ContentBlockItem }) {
const url = item.url ?? ''
const img = useSmallImage(mediaUrl(item.media))
const where = isExternalUrl(url)
? (() => {
try {
const host = new URL(url).hostname.replace(/^www\./, '')
// A file from Tools → Media → Files (routes/files.js).
return /^(drive|docs)\.google\.com$/.test(host) ? 'Google Drive' : host
} catch {
return url
}
})()
: SITE_NAME
return (
<Anchor
href={url}
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-brand/15 bg-surface shadow-sm transition-shadow hover:shadow-lg"
>
{!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)}
<span className="flex flex-1 flex-col gap-1 p-5">
<span className="text-xs font-semibold text-muted">{where}</span>
<span className="font-display text-lg font-bold leading-snug text-ink group-hover:text-link">{item.text}</span>
{item.detail && <span className="line-clamp-3 text-sm text-body">{item.detail}</span>}
</span>
</Anchor>
)
}
/* A table block's text as rows of cells: one row per line, cells
split by "|" (a literal bar is "\|"), blank lines skipped. A
leading and trailing bar, as in Markdown, is allowed. */
export function tableRows(text: string): string[][] {
return text
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) =>
line
.replace(/^\|/, '')
.replace(/(?<!\\)\|$/, '')
.split(/(?<!\\)\|/)
.map((cell) => cell.replace(/\\\|/g, '|').trim()),
)
}
function Caption({ text }: { text?: string | null }) {
if (!text) return null
return (
@ -165,6 +220,61 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string;
</figure>
)
case 'cards': {
const cards = (block.items ?? []).filter((item) => item.url && item.text)
if (cards.length === 0) return null
return (
<ul className={cards.length === 1 ? 'max-w-xl' : 'grid gap-4 sm:grid-cols-2'}>
{cards.map((item, i) => (
<li key={i}>
<LinkCard item={item} />
</li>
))}
</ul>
)
}
case 'table': {
const rows = tableRows(text)
if (rows.length === 0) return null
const [head, ...body] = rows
const width = Math.max(...rows.map((row) => row.length))
return (
// Wide tables scroll sideways inside their box on a phone
// rather than squeezing every column to a word.
<div className="overflow-x-auto rounded-2xl border border-brand/15">
<table className="min-w-full text-left text-sm leading-snug">
<thead className="bg-tint">
<tr>
{Array.from({ length: width }, (_, i) => (
<th key={i} scope="col" className="min-w-[8rem] px-4 py-3 font-semibold text-ink">
<Inline text={head[i] ?? ''} accent={accent} />
</th>
))}
</tr>
</thead>
<tbody>
{body.map((row, r) => (
<tr key={r} className={r % 2 ? 'bg-tint-soft' : ''}>
{Array.from({ length: width }, (_, i) =>
i === 0 ? (
<th key={i} scope="row" className="min-w-[8rem] px-4 py-3 align-top font-semibold text-ink">
<Inline text={row[i] ?? ''} accent={accent} />
</th>
) : (
<td key={i} className="min-w-[8rem] px-4 py-3 align-top" style={{ color: BODY }}>
<Inline text={row[i] ?? ''} accent={accent} />
</td>
),
)}
</tr>
))}
</tbody>
</table>
</div>
)
}
case 'callout':
if (!text) return null
return (

View file

@ -21,6 +21,7 @@ type TouchLink = { label: string } & (
const Get_In_Touch: TouchLink[] = [
{ label: "Feedback", to: "/feedback"},
{ label: "Request", to: "/request" },
{ label: "Contact Us", to: "/leadership#contact" },
];

View file

@ -175,7 +175,7 @@ export default function Layout() {
{/* ── NAV ─────────────────────────────────────────────── */}
<header
ref={headerRef}
className="fixed top-0 left-0 right-0 z-50 backdrop-blur-md"
className="fixed top-0 left-0 right-0 z-50 backdrop-blur-md print:hidden"
inert={mobileMenuOpen}
>
@ -273,7 +273,7 @@ export default function Layout() {
</header>
{/* Keeps page content clear of the fixed header */}
<div aria-hidden style={{ height: headerHeight }} />
<div aria-hidden className="print:hidden" style={{ height: headerHeight }} />
{/* Page content */}
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
@ -283,7 +283,7 @@ export default function Layout() {
</main>
{/*Site Footer applied to every page*/}
<div inert={mobileMenuOpen}>
<div inert={mobileMenuOpen} className="print:hidden">
<Footer />
<PrivacyNotice />
</div>

View file

@ -74,7 +74,7 @@ export default function PostContents({ entries }: { entries: ContentsEntry[] })
const lit = useLit(entries)
return (
<>
<details className="rounded-2xl border border-brand/20 bg-tint-soft p-4 lg:hidden">
<details className="rounded-2xl border border-brand/20 bg-tint-soft p-4 lg:hidden print:hidden">
<summary className="cursor-pointer font-semibold text-ink">On this page</summary>
<div className="mt-3">
<List entries={entries} lit={lit} />
@ -82,7 +82,7 @@ export default function PostContents({ entries }: { entries: ContentsEntry[] })
</details>
<nav
aria-label="On this page"
className="sticky hidden self-start lg:block"
className="sticky hidden self-start lg:block print:hidden"
style={{ top: 'calc(var(--header-h, 5rem) + 1.5rem)' }}
>
<p className="mb-2 px-3 text-sm font-semibold text-ink">On this page</p>

View file

@ -0,0 +1,18 @@
import { Link } from "react-router-dom";
import { PaperPlaneTilt } from "@phosphor-icons/react";
import { requestLink } from "../data/requestTypes.ts";
/* A button to the Request form, opened on one kind of request
(REQUEST_TYPES). Section manifests place it with `request`. */
export default function RequestLink({ type, label, className = "" }: { type: string; label: string; className?: string }) {
return (
<Link
to={requestLink(type)}
className={`inline-flex items-center gap-2 rounded-full border border-brand/40 px-4 py-2 text-sm font-semibold text-link transition-colors hover:bg-tint print:hidden ${className}`}
>
<PaperPlaneTilt aria-hidden="true" weight="bold" className="h-4 w-4" />
{label}
</Link>
);
}

View file

@ -20,6 +20,7 @@
Tabs follow the ARIA tab pattern: arrow keys move between them.
═══════════════════════════════════════════════════════════════ */
import { CaretDown } from '@phosphor-icons/react'
import { useId, useState, type KeyboardEvent } from 'react'
import { Link } from 'react-router-dom'
@ -133,9 +134,11 @@ function Entry({ entry, accent }: { entry: ContentBlockItem; accent: string }) {
className="h-8 w-8 shrink-0 rounded-full border text-sm transition-colors hover:bg-tint"
style={{ borderColor: `${withAlpha(accent, 33)}`, color: accentText(accent) }}
>
<span aria-hidden="true" className={`inline-block transition-transform ${open ? 'rotate-180' : ''}`}>
▾
</span>
<CaretDown
aria-hidden="true"
weight="bold"
className={`mx-auto h-4 w-4 transition-transform ${open ? 'rotate-180' : ''}`}
/>
</button>
)}
</div>

View file

@ -0,0 +1,303 @@
/* ═══════════════════════════════════════════════════════════════
DRIVE FILES
Files for the site to link to (server/src/routes/files.js), kept in
the shared Google Drive and shared as "anyone with the link can
view". The admin side, in one file:
FileUploadButton upload one or more files
FileList the list both the picker and Tools → Media →
Files draw, each with its first-page preview
or an icon for its type
FilePicker the dialog behind a link field's "Choose a
file" (a field with `files: true`, fields.tsx)
A link field stores the file's Drive link, a plain URL, so nothing
else needs to know where it came from. Files put in the Drive
folder by hand are listed too (the server picks them up).
═══════════════════════════════════════════════════════════════ */
import {
File as FileIcon,
FileAudio,
FileDoc,
FilePdf,
FilePpt,
FileXls,
FileZip,
X,
} from "@phosphor-icons/react";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { ApiError, get, upload } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
import { formatBytes } from "./MediaLibrary.tsx";
export type DriveFile = {
id: number;
name: string;
title: string;
mime: string;
bytes: number;
url: string;
preview: string | null;
uploaded_by: string | null;
created_at: string;
};
const button =
"rounded-full border border-brand px-3 py-1 text-sm font-medium text-link " +
"transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
export const FILE_HELP =
"PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A or zip, up to 50 MB. Stored in the shared Google Drive and viewable by anyone with the link.";
const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip";
/* An icon per kind of file; Google's own Docs, Sheets and Slides
(application/vnd.google-apps.*) count as their Office kin. */
const TYPE_ICONS: [RegExp, typeof FileIcon][] = [
[/pdf$/, FilePdf],
[/wordprocessing|google-apps\.document$/, FileDoc],
[/spreadsheet/, FileXls],
[/presentation/, FilePpt],
[/^audio\//, FileAudio],
[/zip$/, FileZip],
];
function TypeIcon({ mime }: { mime: string }) {
const Icon = TYPE_ICONS.find(([test]) => test.test(mime))?.[1] ?? FileIcon;
return <Icon aria-hidden="true" weight="bold" className="h-8 w-8 text-link" />;
}
/* ── Data ────────────────────────────────────────────────────── */
export function useDriveFiles(query: string) {
const [items, setItems] = useState<DriveFile[] | null>(null);
const [ready, setReady] = useState(true);
// Files in the Drive folder that Drive wouldn't share publicly.
const [refused, setRefused] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => {
const q = query.trim();
setError(null);
get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
.then((data) => {
setItems(data.files);
setReady(data.ready);
setRefused(data.refused ?? []);
})
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
}, [query]);
useEffect(reload, [reload]);
return { items, ready, refused, error, reload, setItems };
}
/* ── Upload ──────────────────────────────────────────────────── */
export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUploaded: (file: DriveFile) => void; label?: string }) {
const inputRef = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
async function send(list: FileList | null) {
if (!list?.length) return;
setError(null);
try {
// One at a time, so a failure names its file.
for (const file of Array.from(list)) {
setBusy(file.name);
const form = new FormData();
form.append("file", file);
try {
onUploaded((await upload("/admin/files", form)).file);
} catch (err) {
const why = err instanceof ApiError ? err.message : "Upload failed.";
setError(list.length > 1 ? `${file.name}: ${why}` : why);
break;
}
}
} finally {
setBusy(null);
if (inputRef.current) inputRef.current.value = "";
}
}
return (
<div>
<button type="button" className={button} disabled={busy !== null} onClick={() => inputRef.current?.click()}>
{busy ? `Uploading ${busy}…` : label}
</button>
<input ref={inputRef} type="file" accept={ACCEPT} multiple className="hidden" onChange={(e) => send(e.target.files)} />
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
</div>
);
}
/* ── List ────────────────────────────────────────────────────── */
export function FileList({
items,
selected,
onPick,
renderActions,
}: {
items: DriveFile[];
selected?: string | null;
onPick?: (file: DriveFile) => void;
renderActions?: (file: DriveFile) => ReactNode;
}) {
if (items.length === 0) return <p className="text-sm text-muted">No files yet.</p>;
return (
<ul className="grid gap-3 sm:grid-cols-2">
{items.map((file) => {
const isSelected = selected === file.url;
const body = (
<span className="flex items-center gap-3">
<span className="flex h-16 w-14 shrink-0 items-center justify-center overflow-hidden rounded-md border border-muted/20 bg-tint">
{file.preview ? (
<img src={file.preview} alt="" loading="lazy" className="h-full w-full object-cover object-top" />
) : (
<TypeIcon mime={file.mime} />
)}
</span>
<span className="min-w-0">
<span className="block truncate text-sm font-medium text-body" title={file.name}>
{file.name}
</span>
<span className="block text-xs text-muted/80">{formatBytes(file.bytes)}</span>
</span>
</span>
);
return (
<li
key={file.id}
className={`rounded-xl border bg-surface p-2 ${isSelected ? "border-brand ring-2 ring-brand/30" : "border-muted/20"}`}
>
{onPick ? (
<button type="button" onClick={() => onPick(file)} className="block w-full text-left" aria-pressed={isSelected}>
{body}
</button>
) : (
body
)}
{renderActions && <div className="mt-2">{renderActions(file)}</div>}
</li>
);
})}
</ul>
);
}
/* ── Picker dialog ───────────────────────────────────────────── */
export function FilePicker({
selected,
onPick,
onClose,
}: {
selected?: string | null;
onPick: (file: DriveFile) => void;
onClose: () => void;
}) {
const { user } = useAuth();
const [query, setQuery] = useState("");
const { items, ready, refused, error, setItems } = useDriveFiles(query);
const dialogRef = useRef<HTMLDialogElement>(null);
useEffect(() => {
dialogRef.current?.showModal();
}, []);
const pick = (file: DriveFile) => {
onPick(file);
dialogRef.current?.close();
};
return (
<dialog
ref={dialogRef}
onClose={onClose}
onClick={(e) => {
if (e.target === dialogRef.current) dialogRef.current?.close();
}}
className="w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40"
>
<div className="flex max-h-[85vh] flex-col">
<div className="flex flex-wrap items-center gap-3 border-b border-brand/15 px-5 py-4">
<h2 className="text-lg font-semibold text-link">Choose a file</h2>
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search by file name"
className="ml-auto w-56 rounded-lg border border-muted/25 px-3 py-1.5 text-sm outline-none focus:border-brand"
/>
<button
type="button"
onClick={() => dialogRef.current?.close()}
aria-label="Close"
className="flex h-8 w-8 items-center justify-center rounded-full text-muted hover:bg-tint"
>
<X aria-hidden="true" weight="bold" className="h-4 w-4" />
</button>
</div>
{roleCanWrite(user) && ready && (
<div className="border-b border-brand/10 px-5 py-3">
<FileUploadButton
label="Upload new"
onUploaded={(file) => {
setItems((current) => [file, ...(current ?? [])]);
pick(file);
}}
/>
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
</div>
)}
<div className="overflow-y-auto px-5 py-4">
{!ready && <p className="mb-3 text-sm text-danger">Google Drive isn't set up on the server, so nothing can be uploaded.</p>}
<RefusedNote names={refused} />
{error ? (
<p className="text-sm text-danger">{error}</p>
) : items === null ? (
<p className="text-sm text-muted">Loading…</p>
) : (
<FileList items={items} selected={selected} onPick={pick} />
)}
</div>
</div>
</dialog>
);
}
/* Files someone put in the Drive folder that Drive wouldn't share
with anyone who has the link, so they aren't listed. */
export function RefusedNote({ names }: { names: string[] }) {
if (names.length === 0) return null;
return (
<p className="mb-3 text-sm text-danger">
In the Drive folder but not listed, because Drive wouldn't share {names.length === 1 ? "it" : "them"} with anyone
who has the link: {names.join(", ")}. Check the sharing settings (docs/google-drive-and-mail.md); they're tried
again every ten minutes.
</p>
);
}
/* "Choose a file" under a link field. */
export function ChooseFileButton({ value, onPick }: { value?: string | null; onPick: (file: DriveFile) => void }) {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" className={button} onClick={() => setOpen(true)}>
Choose a file
</button>
{open && <FilePicker selected={value} onPick={onPick} onClose={() => setOpen(false)} />}
</>
);
}

View file

@ -29,6 +29,7 @@
cached list would lie.
═══════════════════════════════════════════════════════════════ */
import { FileAudio, X } from "@phosphor-icons/react";
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
import { ApiError, get, post, upload } from "../../lib/api.ts";
@ -214,8 +215,8 @@ export function MediaGrid({
// A still of the first frame; metadata only, not the file.
<video src={item.url} preload="metadata" muted className="h-full w-full bg-black object-contain" />
) : item.content_type.startsWith("audio/") ? (
<div className="flex h-full w-full items-center justify-center bg-tint text-3xl" aria-hidden="true">
♪
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
<FileAudio weight="bold" className="h-10 w-10 text-link" />
</div>
) : (
<img
@ -305,9 +306,9 @@ export function MediaPicker({
type="button"
onClick={() => dialogRef.current?.close()}
aria-label="Close"
className="h-8 w-8 rounded-full text-muted hover:bg-tint"
className="flex h-8 w-8 items-center justify-center rounded-full text-muted hover:bg-tint"
>
✕
<X aria-hidden="true" weight="bold" className="h-4 w-4" />
</button>
</div>
@ -438,6 +439,7 @@ export function LinkPreviewInput({
locked,
className,
showButton,
fills = { title: "title", blurb: "blurb", image: "image" },
onChange,
onPatch,
}: {
@ -449,6 +451,9 @@ export function LinkPreviewInput({
showButton: boolean;
onChange: (value: string) => void;
onPatch?: (patch: Record<string, any>) => void;
/** Which of the row's fields the preview fills (a list item's are
* text, detail and media). */
fills?: { title: string; blurb: string; image: string };
}) {
const { user } = useAuth();
const [busy, setBusy] = useState(false);
@ -461,9 +466,9 @@ export function LinkPreviewInput({
try {
const { preview } = await post("/admin/link-preview", { url: value });
const patch: Record<string, any> = {};
if (!row.title && preview.title) patch.title = preview.title;
if (!row.blurb && preview.description) patch.blurb = preview.description;
if (!row.image && preview.image) patch.image = preview.image.url;
if (!row[fills.title] && preview.title) patch[fills.title] = preview.title;
if (!row[fills.blurb] && preview.description) patch[fills.blurb] = preview.description;
if (!row[fills.image] && preview.image) patch[fills.image] = preview.image.url;
onPatch(patch);
const filled = Object.keys(patch).length;

View file

@ -56,6 +56,16 @@
(LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty
title, blurb and image through `onPatch`.
`files: true` on a link field adds "Choose a file" (FilePicker in
DriveFiles.tsx): the field takes the file's Drive link, and with
`previewFills` (a link card) the row's empty title and picture take
the file's name and first-page preview. `filesWhen` limits it to
rows that match, as `when` does for the field.
`widget: "testNotice"` is a text box of email addresses with a
"Send a test notice" button (TestNoticeInput below), for Site
settings → Notices.
`widget: "image"` is a text box with a preview and upload and
library buttons beside it (ImageInput in MediaLibrary.tsx). Its
`resolve` option is the media.ts helper for the field's public/
@ -75,11 +85,13 @@
able to read and copy.
═══════════════════════════════════════════════════════════════ */
import { ArrowUp, ArrowDown, CaretRight } from "@phosphor-icons/react";
import { ArrowUp, ArrowDown, CaretRight, Copy, Plus, X } from "@phosphor-icons/react";
import { useRef, useState } from "react";
import { ApiError, post } from "../../lib/api.ts";
import ContentBlocks from "../ContentBlocks.tsx";
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
import { ChooseFileButton } from "./DriveFiles.tsx";
/* Live previews a collection can name with `preview`. Each gets the
row as the form holds it, which is the API's shape. */
@ -160,9 +172,13 @@ export function fieldShown(field, row, parent?) {
the engine's deliberate clear, so it saves as NULL. */
function withHiddenCleared(spec, row, parent?) {
let next = row;
// Two fields can share a path, each shown for a different kind of
// row (a card's Description and a list item's Detail are both
// `detail`); a value is only hidden when none of them is showing.
const shownPaths = new Set(spec.fields.filter((f) => fieldShown(f, row, parent)).map((f) => f.path));
for (const field of spec.fields) {
const value = next[field.path];
if (!fieldShown(field, next, parent) && value != null && value !== "") {
if (!shownPaths.has(field.path) && value != null && value !== "") {
next = { ...next, [field.path]: "" };
}
}
@ -226,6 +242,17 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
!list.some(([optionId]) => String(optionId) === String(value));
}
// A file from the Drive library into this link field (`files`).
const pickFile = (file) => {
const fills = field.previewFills;
const patch = { [field.path]: file.url };
if (fills && !row?.[fills.title]) patch[fills.title] = file.title;
if (fills && !row?.[fills.image] && file.preview) patch[fills.image] = file.preview;
if (onPatch && !field.path.includes(".")) onPatch(patch);
else onChange(file.url);
};
const showFiles = field.files && !locked && (!field.filesWhen || fieldShown({ when: field.filesWhen }, row));
const common = {
id,
className: `${input} ${error ? inputError : ""}`,
@ -303,9 +330,18 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
locked={locked}
className={locked ? inputLocked : common.className}
showButton={!field.previewWhen || fieldShown({ when: field.previewWhen }, row)}
fills={field.previewFills}
onChange={onChange}
onPatch={onPatch}
/>
) : widget === "testNotice" ? (
<TestNoticeInput
id={id}
value={value}
locked={locked}
className={locked ? inputLocked : common.className}
onChange={onChange}
/>
) : widget === "image" ? (
<ImageInput
id={id}
@ -353,6 +389,11 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
className={locked ? inputLocked : common.className}
/>
)}
{showFiles && (
<div className="mt-2">
<ChooseFileButton value={value} onPick={pickFile} />
</div>
)}
</div>
{error ? (
@ -611,20 +652,20 @@ export function Repeater({
label="Insert a new one below"
onClick={() => insertAt(index + 1, { ...spec.blank })}
>
+
<Plus size={14} weight="bold" aria-hidden="true" />
</IconButton>
<IconButton
label="Duplicate"
onClick={() => insertAt(index + 1, withoutIds(row))}
>
⧉
<Copy size={14} weight="bold" aria-hidden="true" />
</IconButton>
<IconButton
label="Remove"
danger
onClick={() => removeAt(index)}
>
✕
<X size={14} weight="bold" aria-hidden="true" />
</IconButton>
</div>
</div>
@ -692,7 +733,7 @@ function IconButton({ label, onClick, danger = false, disabled = false, children
aria-label={label}
title={label}
className={
"h-7 w-7 rounded-full border text-sm leading-none transition-colors " +
"flex h-7 w-7 items-center justify-center rounded-full border text-sm leading-none transition-colors " +
(disabled
? "cursor-default border-muted/20 text-muted/40"
: danger
@ -704,3 +745,65 @@ function IconButton({ label, onClick, danger = false, disabled = false, children
</button>
);
}
/* Addresses, and a button that emails them a test notice now (the
box as typed, saved or not), showing what Google said. */
function TestNoticeInput({
id,
value,
locked,
className,
onChange,
}: {
id: string;
value: string | null | undefined;
locked: boolean;
className: string;
onChange: (value: string) => void;
}) {
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
async function send() {
setBusy(true);
setNote(null);
try {
const { sent, from } = await post("/admin/panel/test-notice", { to: value });
setNote({ tone: "ok", text: `Sent from ${from} to ${sent.join(", ")}. Check the inbox (and spam).` });
} catch (err) {
setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
} finally {
setBusy(false);
}
}
return (
<div className="space-y-2">
<input
id={id}
type="text"
value={value ?? ""}
readOnly={locked}
onChange={(e) => onChange(e.target.value)}
className={className}
/>
{!locked && (
<div className="flex flex-wrap items-center gap-3">
<button
type="button"
disabled={busy || !value?.trim()}
onClick={send}
className="rounded-full border border-brand px-3 py-1 text-sm font-medium text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"
>
{busy ? "Sending…" : "Send a test notice"}
</button>
{note && (
<span role="status" className={`text-xs ${note.tone === "ok" ? "text-link" : "text-danger"}`}>
{note.text}
</span>
)}
</div>
)}
</div>
);
}

37
src/data/requestTypes.ts Normal file
View file

@ -0,0 +1,37 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST TYPES
What the Request form (/request) can ask for, and whether each can
be new, an update, or both. The ids and actions must match
CATEGORIES in server/src/routes/requests.js (and the CHECK in
046_content_requests.sql); keep them in step.
A link can open the form on one: requestLink("chapter") is
/request?type=chapter. People, teams and awards have no buttons on
the site, but are here to pick.
═══════════════════════════════════════════════════════════════ */
export type RequestAction = "new" | "update";
export const REQUEST_TYPES: {
id: string;
label: string;
hint: string;
actions: RequestAction[];
// What the name field asks, for a new one and for an update.
subject: string;
}[] = [
{ id: "blog", label: "Blog post", hint: "A story or article for the community blog", actions: ["new"], subject: "Its title" },
{ id: "event", label: "Event", hint: "A retreat, gathering or calendar event", actions: ["new", "update"], subject: "The event's name" },
{ id: "chapter", label: "Chapter", hint: "A local NGU chapter", actions: ["new", "update"], subject: "The chapter's name" },
{ id: "region", label: "Region", hint: "Details for a Unity region", actions: ["update"], subject: "Which region" },
{ id: "partner", label: "Partner", hint: "A partner organization", actions: ["new", "update"], subject: "The organization's name" },
{ id: "team", label: "Team", hint: "A team or committee", actions: ["new", "update"], subject: "The team's name" },
{ id: "award", label: "Award", hint: "An award and who received it", actions: ["new", "update"], subject: "The award's name" },
{ id: "person", label: "Person", hint: "Someone's profile", actions: ["new", "update"], subject: "Their name" },
];
export const requestLink = (type: string) => `/request?type=${type}`;
const BY_ID = new Map(REQUEST_TYPES.map((t) => [t.id, t.label]));
export const requestTypeLabel = (id: string) => BY_ID.get(id) ?? id;

View file

@ -149,6 +149,37 @@ h1, h2, h3, h4, h5, h6 {
}
}
/* Printing (a blog post's Download PDF, or any page): the light
palette whatever the screen shows, since paper is white and dark
mode's pale text would barely print; and backgrounds kept, so the
tinted panels and table rows come out as on screen. */
@media print {
:root,
:root[data-theme="dark"] {
--color-ink: #073d4a;
--color-body: #26454c;
--color-muted: #4a6b72;
--color-link: #0f7183;
--color-brand: #138ba0;
--color-surface: #ffffff;
--color-tint: #eef9fb;
--color-tint-soft: #f6fbfc;
--color-danger: #b3261e;
--color-danger-tint: #fdf3f2;
--accent-text-mix: 100%;
color-scheme: light;
print-color-adjust: exact;
}
.logo-plate {
background: none !important;
padding: 0 !important;
}
}
@page {
margin: 1.5cm;
}
/* Church Center's giving modal (Giving.tsx) is a transparent iframe
over the whole page, drawn for light pages. On a dark page the
browser sees the iframe's scheme differ from ours and paints its

View file

@ -23,6 +23,8 @@ export const blogPosts = {
singular: "blog post",
idLabel: "URL ID",
slugFrom: "title",
// Blog posts → Import from Word (server/src/routes/import.js).
importer: { label: "Import from Word", endpoint: "/admin/import/docx", accept: ".docx" },
list: {
columns: [

View file

@ -278,15 +278,20 @@ export const BLOCK_TYPES = [
["image", "Image", "A picture, with alt text and an optional caption and link."],
["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."],
["schedule", "Schedule", "Entries in one tab per day, each folding out for more. The text is an optional intro."],
["table", "Table", "A grid of text, eg. a comparison chart: one row per line, cells split by |, the first row the header."],
["cards", "Link cards", "Cards with a picture, title and description, each a link, like a link shared in a chat. Paste a link and press Fetch preview."],
["divider", "Divider", "A thin line between parts."],
];
/* An item field that only a schedule's entries have. */
export const SCHEDULE_ENTRY = { scope: "parent", path: "type", value: "schedule" };
/* Item fields for a link card, and for every other kind of item. */
export const CARD_ITEM = { scope: "parent", path: "type", value: "cards" };
export const NOT_CARD_ITEM = { scope: "parent", path: "type", value: ["list", "links", "schedule"] };
export const blockTypeLabel = (type) => BLOCK_TYPES.find(([value]) => value === type)?.[1] ?? type;
export const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video", "schedule"];
export const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video", "schedule", "table"];
export const TEXT_HELP = {
paragraph: FORMATTING_HELP,
@ -296,9 +301,12 @@ export const TEXT_HELP = {
image: "Caption shown under the image. Optional.",
video: "Caption shown under the video. Optional.",
schedule: "Optional intro above the tabs. " + FORMATTING_HELP,
table:
"One row per line; cells split by |. The first row is the header. eg. Platform | Price | Best for. " +
"Cells take the same formatting as a paragraph. A | inside a cell is written \|.",
};
export const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption", schedule: "Intro" };
export const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption", schedule: "Intro", table: "Rows" };
export const HREF_HELP = {
paragraph: "Optional. Makes the whole paragraph one link. For a link inside the text, use [text](url).",
@ -354,6 +362,8 @@ export const blocksChild = {
path: "href",
label: "Link",
full: true,
files: true,
filesWhen: { path: "type", value: ["paragraph", "button", "image"] },
when: { path: "type", value: ["paragraph", "button", "image", "video"] },
help: (row) => HREF_HELP[row?.type],
},
@ -380,7 +390,7 @@ export const blocksChild = {
key: "items",
label: "Items",
addLabel: "Add item",
when: { path: "type", value: ["list", "links", "schedule"] },
when: { path: "type", value: ["list", "links", "schedule", "cards"] },
title: (row) => [row.day, row.time, row.text].filter(Boolean).join(" · ") || "New item",
blank: { text: "" },
fields: [
@ -391,7 +401,18 @@ export const blocksChild = {
when: SCHEDULE_ENTRY,
},
{ path: "time", label: "Time", help: "eg. 7:00pm, or 9:00 to 10:30am", when: SCHEDULE_ENTRY },
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title" },
// A card: the link first, so Fetch preview can fill the rest.
{
path: "url",
label: "Link",
widget: "linkPreview",
previewFills: { title: "text", blurb: "detail", image: "media" },
files: true,
full: true,
help: "A page on this site (eg. /retreats), anywhere else, or a file (Choose a file). Fetch preview fills the title, description and picture from a page; a file fills its name and first-page picture.",
when: CARD_ITEM,
},
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title. Cards: the card's title" },
{
path: "location",
label: "Location",
@ -407,8 +428,18 @@ export const blocksChild = {
help: "Who hosts or speaks: shown with their photo, linked to their page",
when: SCHEDULE_ENTRY,
},
{ path: "detail", label: "Detail", help: "A line under the text. Lists: shown after the text" },
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one." },
{ path: "detail", label: "Detail", help: "A line under the text. Lists: shown after the text", when: NOT_CARD_ITEM },
{ path: "detail", label: "Description", widget: "textarea", full: true, when: CARD_ITEM },
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", files: true, when: NOT_CARD_ITEM },
{
path: "media",
label: "Picture",
widget: "image",
resolve: mediaUrl,
full: true,
help: "Optional. Default: none, the card is text only.",
when: CARD_ITEM,
},
{
path: "description",
label: "More",

View file

@ -122,6 +122,39 @@ export const siteSettings = {
},
],
},
{
legend: "Access (Google groups)",
note: "Anyone in one of these Workspace groups can sign in to the admin with Google; their account is made at first sign-in, with the highest role their groups give. Their role follows the groups (checked at sign-in, hourly, and by Panel → Re-sync now); out of every group, the account is disabled. Superadmins and accounts made with admin-cli aren't affected. Needs GOOGLE_DIRECTORY_AS on the server (docs/google-sign-in.md).",
fields: [
{
path: "access_group_admin",
label: "Admins group",
help: "Its members sign in as admins: edit and delete anything. eg. web-admins@nextgenerationofunity.org. Default: none.",
},
{
path: "access_group_editor",
label: "Editors group",
help: "Its members sign in as editors: create and edit, not delete. eg. web-editors@nextgenerationofunity.org. Default: none.",
},
{
path: "access_group_viewer",
label: "Viewers group",
help: "Its members sign in as viewers: read only. eg. web-viewers@nextgenerationofunity.org. Default: none.",
},
],
},
{
legend: "Notices",
fields: [
{
path: "notify_emails",
label: "Email new requests to",
widget: "testNotice",
full: true,
help: "Who gets an email for each new content request (the Request form) and data request (the Privacy page), separated by commas, eg. web@nextgenerationofunity.org, board@nextgenerationofunity.org. Needs Gmail set up on the server (docs/google-drive-and-mail.md). Send a test notice emails whatever is in the box now, saved or not, and shows Google's answer. Default: none, check Forms instead.",
},
],
},
],
children: [

View file

@ -29,6 +29,13 @@ export class ApiError extends Error {
}
}
/* nginx's answers of its own, in words that point at the fix. */
const NOT_THE_API: Record<number, string> = {
413: "Too large for the web server: nginx's upload limit for this address is lower than the file (HTTP 413). The nginx block for it is in the docs.",
502: "The API isn't answering (HTTP 502). Check that the ngu-api service is running.",
504: "The API took too long to answer (HTTP 504). Try again; if it keeps happening, nginx's timeout for this address is too short.",
};
async function request(path, options: RequestInit = {}) {
const response = await fetch(`${BASE}${path}`, {
...options,
@ -39,9 +46,11 @@ async function request(path, options: RequestInit = {}) {
const type = response.headers.get("content-type") ?? "";
if (!type.includes("application/json")) {
// Usually the SPA fallback returning index.html for a URL the
// API doesn't serve. Parsing it would throw something useless.
throw new ApiError("Server did not return JSON.", {
// Not the API's answer: the SPA fallback returning index.html for
// a URL the API doesn't serve, or nginx's own error page when the
// request never reached the API (nothing in its journal then).
// Parsing it would throw something useless; say what it was.
throw new ApiError(NOT_THE_API[response.status] ?? `The server didn't answer as expected (HTTP ${response.status}).`, {
status: response.status,
});
}

View file

@ -1,5 +1,7 @@
import { useState } from "react";
import RequestLink from "../components/RequestLink.tsx";
/* ═══════════════════════════════════════════════════════════════
SECTION MANIFEST
@ -21,6 +23,10 @@ import { useState } from "react";
default: "carousel",
Toggle: EventCardsToggle,
},
request: { // optional button
type: "chapter", // to the Request form
label: "Add or update a chapter",
},
}
Sections fetch their own data. The page never does, which is why
@ -50,20 +56,25 @@ export function useSectionManifest(manifest) {
const setView = (id, value) => setViews(prev => ({ ...prev, [id]: value }));
return manifest.map(entry => {
const { Component, props, views: spec, ...heading } = entry;
const { Component, props, views: spec, request, ...heading } = entry;
const view = views[entry.id];
const Toggle = spec?.Toggle;
return {
...heading,
actions: Toggle ? (
<Toggle
view={view}
setView={value => setView(entry.id, value)}
accent={entry.accent}
options={spec.options}
/>
actions: Toggle || request ? (
<div className="flex flex-wrap items-center gap-3">
{request && <RequestLink type={request.type} label={request.label} />}
{Toggle && (
<Toggle
view={view}
setView={value => setView(entry.id, value)}
accent={entry.accent}
options={spec.options}
/>
)}
</div>
) : undefined,
content: (

View file

@ -24,7 +24,7 @@ import siteConfiguration from '../../site.json'
type PageText = { title: string; description: string }
type SiteText = { title?: string; pages?: Record<string, PageText>; privacyEmail?: string }
type SiteText = { title?: string; pages?: Record<string, PageText>; privacyEmail?: string; requestFiles?: boolean }
/* What the server wrote into the page, if it did. */
const fromServer: SiteText =
@ -38,6 +38,11 @@ export const SITE_ORIGIN: string = siteConfiguration.url
* settings, else site.json). Blank: the Privacy page's form only. */
export const PRIVACY_EMAIL: string = fromServer.privacyEmail ?? siteConfiguration.privacyEmail
/** Whether the Request form takes files (Google Drive is set up on
* the server). Unknown (the Vite dev server) offers them, and the
* server says so if it can't. */
export const REQUEST_FILES: boolean = fromServer.requestFiles ?? true
/** A site path as a full URL on the live site. */
export const siteUrl = (path: string): string => new URL(path, SITE_ORIGIN).href

View file

@ -35,6 +35,8 @@ export type ContentBlock = {
| 'button'
| 'callout'
| 'schedule'
| 'table'
| 'cards'
text?: string | null
media?: string | null
href?: string | null

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.9.4-audit";
export const SITE_VERSION = "NGU-Web.v1.9.11-content-display";

View file

@ -21,6 +21,10 @@ import { postDate, useBlogPost } from "../lib/useBlog.ts"
import { accentText, BRAND } from "../lib/color.ts"
import PostContents from "../components/PostContents.tsx"
import { headingAnchors } from "../lib/contents.ts"
import QrCode from "../components/QrCode.tsx"
import RequestLink from "../components/RequestLink.tsx"
import { siteUrl } from "../lib/site.ts"
import { FilePdf } from "@phosphor-icons/react"
const BODY = "var(--color-muted)"
@ -49,6 +53,7 @@ export default function BlogPost() {
const contents = post.show_contents ? headingAnchors(post.blocks).entries : []
const withContents = contents.length >= 2
const postUrl = siteUrl(`/blog/${post.id}`)
const date = postDate(post.published_on)
const cover = mediaUrl(post.cover_image)
const byline = [
@ -85,7 +90,7 @@ export default function BlogPost() {
<div
className={
withContents
? "mx-auto grid max-w-6xl gap-8 px-6 lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-12"
? "mx-auto grid max-w-6xl gap-8 px-6 lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-12 print:block"
: "contents"
}
>
@ -117,9 +122,17 @@ export default function BlogPost() {
{tag}
</span>
))}
<button
type="button"
onClick={() => window.print()}
className="ml-auto inline-flex items-center gap-1.5 rounded-full border border-link px-3 py-1 font-semibold text-link transition-colors hover:bg-tint print:hidden"
>
<FilePdf size={16} weight="bold" aria-hidden="true" />
Download PDF
</button>
<Link
to={BACK.to}
className="ml-auto hover:underline"
className="hover:underline print:hidden"
style={{ color: accentText(BRAND) }}
>
{BACK.label}
@ -135,6 +148,22 @@ export default function BlogPost() {
)}
<ContentBlocks blocks={post.blocks} accent={BRAND} />
<div className="flex flex-wrap items-center gap-3 border-t border-brand/15 pt-6 text-sm text-muted print:hidden">
Have a story to share?
<RequestLink type="blog" label="Write for the blog" />
</div>
{/* Only on paper (Download PDF): where the post lives online,
as a link and as a code to scan. */}
<footer className="hidden break-inside-avoid items-center gap-6 border-t border-brand/20 pt-6 print:flex">
<QrCode value={postUrl} label={`QR code for ${postUrl}`} className="h-28 w-28 shrink-0" />
<p className="text-sm text-body">
Read this post online at
<br />
<span className="font-semibold text-link">{postUrl}</span>
</p>
</footer>
</article>
</div>
),

View file

@ -34,6 +34,7 @@ const SECTIONS = [
accent: BRAND,
background: "var(--color-tint)",
Component: OrgListMap,
request: { type: "chapter", label: "Add or update a chapter" },
views: { options: ["map", "grid"], default: "map", Toggle: OrgMapToggle },
},
{
@ -44,6 +45,7 @@ const SECTIONS = [
accent: "#4a6b72",
background: "var(--color-surface)",
Component: OrgListVertical,
request: { type: "region", label: "Update a region" },
props: {
kind: "region",
pageLabel: "Region page",
@ -62,6 +64,7 @@ const SECTIONS = [
accent: ACCENTS.mint,
background: "var(--color-tint)",
Component: OrgListCards,
request: { type: "partner", label: "Add or update a partner" },
props: {
kind: "partner",
pageLabel: "Partner page",
@ -81,6 +84,7 @@ export default function CommunityPage() {
accent: BRAND,
background: "var(--color-surface)",
Component: CommunityBlog,
request: { type: "blog", label: "Write for the blog" },
},
...SECTIONS,
]);

View file

@ -13,8 +13,8 @@ const PAGE = sitePage("/privacy");
/* ═══════════════════════════════════════════════════════════════
Privacy policy, cookie notice included.
What it says must stay true of the code: what the feedback form
stores (routes/feedback.js), what the browser keeps (Banner,
What it says must stay true of the code: what the feedback and
request forms store (routes/feedback.js, routes/requests.js), what the browser keeps (Banner,
PrivacyNotice, the theme toggle), which embeds wait for a click
(VideoPlayer, HeroStage, ScheduleBlock), and that nothing about
a minor is shown. Change the date when the wording changes.
@ -24,7 +24,7 @@ const PAGE = sitePage("/privacy");
'privacy', in Admin → Forms → Data requests.
═══════════════════════════════════════════════════════════════ */
const LAST_UPDATED = "September 28, 2026";
const LAST_UPDATED = "September 29, 2026";
const link = "underline underline-offset-2 text-link";
@ -57,7 +57,7 @@ const PARTS: LegalPart[] = [
<strong>Feedback and requests you send.</strong> Your message, the page it's about, and, if you
give them, your name and email. With it we keep your browser's description (its user agent) and
a scrambled form of your IP address that can't be turned back into the address; we use it only to
spot abuse.
spot abuse. Files you attach to a <Link to="/request" className={link}>request</Link> are kept with it.
</>,
<>
<strong>People on the site.</strong> Leaders, speakers and volunteers can appear with a name,
@ -119,9 +119,13 @@ const PARTS: LegalPart[] = [
<>
<strong>Staff sign-in</strong> can use a Google account on our own domain.
</>,
<>
<strong>Files attached to requests</strong> are stored in our Google Workspace (Google Drive), and
our staff may be told of a new request by email through it.
</>,
],
after: [
"This site runs on a server we rent and manage ourselves; your information is stored there, not with an outside website service.",
"This site runs on a server we rent and manage ourselves; your information is stored there, not with an outside website service, apart from request files as above.",
],
},
{

33
src/pages/Request.tsx Normal file
View file

@ -0,0 +1,33 @@
import PageShell from "../components/PageShell.tsx";
import { sitePage } from "../lib/site.ts";
import RequestForm from "./sections/RequestForm.tsx";
import { BRAND } from "../lib/color.ts";
/* Title and intro: site.json, which also gives the search metadata. */
const PAGE = sitePage("/request");
/* ═══════════════════════════════════════════════════════════════
Request page: ask for something to be added to the site or
changed on it. The form (sections/RequestForm) reads ?type= to
start on one kind of request; requestLink() makes those links.
═══════════════════════════════════════════════════════════════ */
const SECTIONS = [
{
id: "request",
title: "Send a request",
blurb:
"Tell us what you'd like on the site, or what should change. Attach a Word document with the details and we'll take it from there.",
accent: BRAND,
background: "var(--color-tint)",
content: (
<div className="mx-auto max-w-3xl px-6">
<RequestForm />
</div>
),
},
];
export default function Request() {
return <PageShell title={PAGE.title} intro={PAGE.description} sections={SECTIONS} />;
}

View file

@ -52,6 +52,7 @@ const SECTIONS = [
Component: EventListCards,
props: { scope: "national", ...RETREATS },
views: { ...CARD_VIEWS, default: "carousel" },
request: { type: "event", label: "Add or update an event" },
},
{
id: "regional",

View file

@ -20,10 +20,11 @@
import { useCallback, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { del, get, patch, ApiError } from "../../lib/api.ts";
import { del, get, patch, post, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts";
import { feedbackTypeLabel } from "../../data/feedbackTypes.ts";
import { requestTypeLabel } from "../../data/requestTypes.ts";
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
@ -46,6 +47,63 @@ function formatDate(value) {
});
}
const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
/* A content request's files: each downloads from Drive through the
server, and a Word document can become a draft blog post
(the same import as Blog posts → Import from Word). */
function RequestFiles({ row, canWrite }) {
const navigate = useNavigate();
const [busy, setBusy] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
async function makePost(file) {
setBusy(file.id);
setError(null);
try {
const result = await post(`/admin/feedback/${row.id}/files/${file.id}/blog-post`, {});
navigate(`/admin/blog_posts/${result.id}`, { state: { imported: result.summary } });
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
setBusy(null);
}
}
return (
<div className="mt-4">
<ul className="space-y-2">
{row.files.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
<a
href={`/api/admin/feedback/${row.id}/files/${file.id}`}
download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
<span className="text-xs text-muted">{sizeOf(file.size)}</span>
{canWrite && /\.docx$/i.test(file.name) && (
<button
type="button"
disabled={busy !== null}
onClick={() => makePost(file)}
className="rounded-full border border-link px-3 py-0.5 text-xs font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60"
>
{busy === file.id ? "Making the post…" : "Make a blog post from it"}
</button>
)}
</li>
))}
</ul>
{error && (
<p role="alert" className="mt-2 text-sm text-danger">
{error}
</p>
)}
</div>
);
}
function locationOf(row) {
if (!row.page_path) return "Not page-specific";
return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path;
@ -93,7 +151,9 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
<article className="rounded-2xl border border-brand/20 bg-surface p-5">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
<span className="font-semibold text-body">
{feedbackTypeLabel(row.feedback_type)}
{row.feedback_type === "content"
? `${row.request_action === "update" ? "Update" : "New"} ${requestTypeLabel(row.category).toLowerCase()}`
: feedbackTypeLabel(row.feedback_type)}
</span>
<span
className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
@ -102,13 +162,15 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
>
{row.status}
</span>
<span className="text-muted">{locationOf(row)}</span>
{row.feedback_type !== "content" && <span className="text-muted">{locationOf(row)}</span>}
<span className="ml-auto text-xs text-muted">
#{row.id} · {formatDate(row.created_at)}
</span>
</div>
<p className="mt-4 whitespace-pre-wrap text-body">{row.message}</p>
{row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>}
<p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p>
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} />}
<p className="mt-4 text-sm text-muted">
{row.name || row.email ? (
@ -117,7 +179,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
{row.name && row.email && " · "}
{row.email && (
<a
href={`mailto:${row.email}?subject=Your%20NGU%20site%20feedback`}
href={`mailto:${row.email}?subject=${encodeURIComponent(row.subject ? `Your request: ${row.subject}` : "Your NGU site feedback")}`}
className="text-link underline underline-offset-2"
>
{row.email}
@ -225,14 +287,20 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
/* ── The page ────────────────────────────────────────────────── */
/* The two queues this page shows: the website feedback form, and
data requests from the Privacy page. Same table, same triage. */
/* The queues this page shows: the website feedback form, content
requests from /request, and data requests from the Privacy page.
Same table, same triage. */
const QUEUES = {
feedback: {
to: "/admin/feedback",
title: "Website feedback",
blurb: "Everything submitted through the site's feedback form.",
},
content: {
to: "/admin/requests",
title: "Content requests",
blurb: "Requests from the site's Request form: blog posts, events, and new or updated organizations, teams, awards and people. Files open from Google Drive.",
},
privacy: {
to: "/admin/data-requests",
title: "Data requests",

View file

@ -20,6 +20,7 @@
The route guard and the API are what actually say no.
═══════════════════════════════════════════════════════════════ */
import { CaretDown } from "@phosphor-icons/react";
import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx";
@ -54,9 +55,7 @@ function GroupMenu({ item, lit, pathname }) {
<NavLink to={target(item)} className={`flex items-center gap-1 ${link}`}>
{item.label}
{children.length > 1 && (
<span aria-hidden="true" className="text-[10px] opacity-60">
▾
</span>
<CaretDown aria-hidden="true" weight="bold" className="h-2.5 w-2.5 opacity-60" />
)}
</NavLink>

View file

@ -33,6 +33,9 @@ const GOOGLE_ERRORS: Record<string, string> = {
unverified: "That Google account's email isn't verified.",
google_unreachable: "Couldn't reach Google. Try again in a moment.",
google_failed: "Google sign-in didn't work. Try again, or use your password.",
not_in_group:
"That Google account isn't in a website access group. Ask a superadmin to add you to one.",
groups_unreachable: "Couldn't check your Google groups just now. Try again in a moment.",
};
const fieldClass =

View file

@ -1,10 +1,13 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN: MEDIA
The uploaded-image library: search it, add to it, copy a file's
path, delete what nothing needs. Image fields in the editors
upload and pick from the same library (MediaLibrary.tsx), so this
page is for housekeeping rather than the way images get in.
Two tabs. Images: the uploaded-image library: search it, add to
it, copy a file's path, delete what nothing needs. Image fields in
the editors upload and pick from the same library
(MediaLibrary.tsx), so this is housekeeping rather than the way
images get in. Files: documents, audio and zips in the shared
Google Drive, for pages to link to (DriveFiles.tsx); link fields'
"Choose a file" picks from them.
Two ranks, as on the server: editors and up upload, admins and
up delete. A delete first asks the server which records still
@ -17,6 +20,13 @@ import { useState } from "react";
import { ApiError, del, get } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx";
import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts";
import {
FILE_HELP,
FileList,
FileUploadButton,
RefusedNote,
useDriveFiles,
} from "../../components/admin/DriveFiles.tsx";
import {
MediaGrid,
UPLOAD_HELP,
@ -27,7 +37,18 @@ import {
type Use = { table: string; count: number };
function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => void }) {
/* `base` is where the item lives: /admin/media or /admin/files. */
function DeleteControl({
item,
base = "/admin/media",
broken = "Those will show no image.",
onDeleted,
}: {
item: { id: number };
base?: string;
broken?: string;
onDeleted: () => void;
}) {
const [uses, setUses] = useState<Use[] | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@ -36,7 +57,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
setBusy(true);
setError(null);
try {
const data = await get(`/admin/media/${item.id}/uses`, { ttl: 0 });
const data = await get(`${base}/${item.id}/uses`, { ttl: 0 });
setUses(data.uses);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't check where it's used.");
@ -49,7 +70,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
setBusy(true);
setError(null);
try {
await del(`/admin/media/${item.id}`);
await del(`${base}/${item.id}`);
onDeleted();
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't delete that.");
@ -78,8 +99,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
{uses.length > 0 ? (
<p>
Still used by{" "}
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those
will show no image.
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. {broken}
</p>
) : (
<p>Nothing uses this file.</p>
@ -102,7 +122,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
);
}
function CopyPath({ url }: { url: string }) {
function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) {
const [copied, setCopied] = useState(false);
return (
<button
@ -115,13 +135,80 @@ function CopyPath({ url }: { url: string }) {
}}
className="text-xs text-link hover:underline"
>
{copied ? "Copied" : "Copy path"}
{copied ? "Copied" : label}
</button>
);
}
function FilesTab() {
const { user } = useAuth();
const [query, setQuery] = useState("");
const { items, ready, refused, error, setItems } = useDriveFiles(query);
return (
<>
<div className="mt-6 flex flex-wrap items-start gap-6">
{roleCanWrite(user) && ready && (
<div className="max-w-md">
<FileUploadButton onUploaded={(file) => setItems((current) => [file, ...(current ?? [])])} />
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
</div>
)}
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search by file name"
className="ml-auto w-64 rounded-lg border border-muted/25 px-3 py-2 text-sm outline-none focus:border-brand"
/>
</div>
{!ready && (
<p className="mt-4 text-sm text-danger">
Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.
</p>
)}
<div className="mt-6">
<RefusedNote names={refused} />
{error ? (
<p className="text-sm text-danger">{error}</p>
) : items === null ? (
<p className="text-sm text-muted">Loading…</p>
) : (
<FileList
items={items}
renderActions={(file) => (
<div className="flex flex-wrap items-start gap-x-3 gap-y-1">
<CopyPath url={file.url} label="Copy link" />
<a href={file.url} target="_blank" rel="noreferrer" className="text-xs text-link hover:underline">
Open in Drive
</a>
{canDelete(user) && (
<div className="w-full">
<DeleteControl
item={file}
base="/admin/files"
broken="Those links will stop working."
onDeleted={() => setItems((current) => (current ?? []).filter((f) => f.id !== file.id))}
/>
</div>
)}
</div>
)}
/>
)}
</div>
</>
);
}
const TABS = [
["images", "Images"],
["files", "Files"],
] as const;
export default function AdminMedia() {
const { user } = useAuth();
const [tab, setTab] = useState<"images" | "files">("images");
const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query);
@ -130,10 +217,34 @@ export default function AdminMedia() {
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-link">Media</h1>
<p className="text-sm text-muted">
Uploaded images. Image fields in every editor pick from here.
{tab === "images"
? "Uploaded images. Image fields in every editor pick from here."
: "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."}
</p>
</div>
<nav aria-label="Media" className="mt-4 flex gap-1 border-b border-brand/15">
{TABS.map(([id, label]) => (
<button
key={id}
type="button"
aria-current={tab === id ? "page" : undefined}
onClick={() => setTab(id)}
className={
"-mb-px border-b-2 px-4 py-2 text-sm font-semibold transition-colors " +
(tab === id ? "border-link text-link" : "border-transparent text-muted hover:text-link")
}
>
{label}
</button>
))}
</nav>
{tab === "files" ? (
<FilesTab />
) : (
<>
<div className="mt-6 flex flex-wrap items-start gap-6">
{roleCanWrite(user) && (
<div className="max-w-md">
@ -188,6 +299,8 @@ export default function AdminMedia() {
/>
)}
</div>
</>
)}
</div>
);
}

View file

@ -6,11 +6,16 @@
assumes neither: it renders whatever the API gives it and shows
whatever the API refuses.
Three blocks, deliberately boring:
Four blocks, deliberately boring:
System what's actually running, for when something is off
Content row counts, the cheapest "is the database there"
Accounts roles, access and live sessions
System what's actually running, for when something is off
Content row counts, the cheapest "is the database there"
Accounts roles, access and live sessions
Google groups check someone's groups, re-sync every group
account (server/src/accessGroups.js)
A group account's role comes from its Google group, so its role
select is locked; Disable still works, and sticks.
The role select is driven by ROLES from lib/roles.ts, so a new
rung on the ladder appears here without this file changing. The
@ -25,7 +30,7 @@
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useState } from "react";
import { del, get, patch } from "../../lib/api.ts";
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { useNavigate } from "react-router-dom";
import { ROLES, ROLE_LABELS, ROLE_NOTES, isSuper } from "../../lib/roles.ts";
@ -73,6 +78,107 @@ function Stat({ label, value }) {
);
}
/* Google groups: what's set, who a group would let in, and a
re-sync of every group account. */
function AccessGroups({ access, onSynced }) {
const [email, setEmail] = useState("");
const [busy, setBusy] = useState<"check" | "sync" | null>(null);
const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
const [changes, setChanges] = useState<string[]>([]);
const groups = Object.entries(access?.groups ?? {});
async function send(kind: "check" | "sync") {
setBusy(kind);
setNote(null);
setChanges([]);
try {
if (kind === "check") {
const { role } = await post("/admin/panel/access-check", { email });
setNote(
role
? { tone: "ok", text: `${email} would sign in as ${ROLE_LABELS[role] ?? role}.` }
: { tone: "error", text: `${email} isn't in any of these groups.` },
);
} else {
const result = await post("/admin/panel/access-sync", {});
setNote({
tone: result.failed.length ? "error" : "ok",
text:
`Checked ${result.checked} group account${result.checked === 1 ? "" : "s"}, ` +
`${result.changes.length} changed` +
(result.failed.length ? `, ${result.failed.length} couldn't be checked.` : "."),
});
setChanges([...result.changes, ...result.failed]);
onSynced();
}
} catch (err) {
setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
} finally {
setBusy(null);
}
}
const button =
"rounded-full border border-brand px-4 py-1.5 text-sm font-medium text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
return (
<Block
title="Google groups"
note="Members of these groups sign in with Google and get the group's role. Set them in Site settings → Access."
>
{!access?.directory && (
<p className="mb-3 text-sm text-danger">
Group lookups aren't set up on the server (GOOGLE_DIRECTORY_AS, docs/google-sign-in.md).
</p>
)}
{groups.length > 0 ? (
<dl className="mb-4 grid gap-x-6 gap-y-1.5 text-sm sm:grid-cols-3">
{groups.map(([role, group]) => (
<div key={role}>
<dt className="font-medium text-ink">{ROLE_LABELS[role] ?? role}</dt>
<dd className="break-all text-muted">{group as string}</dd>
</div>
))}
</dl>
) : (
<p className="mb-4 text-sm text-muted">No groups set: accounts come from admin-cli only.</p>
)}
<div className="flex flex-wrap items-center gap-3">
<label htmlFor="access-check" className="sr-only">
Email to check
</label>
<input
id="access-check"
type="email"
value={email}
placeholder="someone@nextgenerationofunity.org"
onChange={(e) => setEmail(e.target.value)}
className="min-w-0 flex-1 rounded-lg border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25 sm:max-w-sm"
/>
<button type="button" className={button} disabled={busy !== null || !email.trim()} onClick={() => send("check")}>
{busy === "check" ? "Checking…" : "Check their groups"}
</button>
<button type="button" className={button} disabled={busy !== null} onClick={() => send("sync")}>
{busy === "sync" ? "Re-syncing…" : "Re-sync now"}
</button>
</div>
{note && (
<p role="status" className={`mt-3 text-sm ${note.tone === "ok" ? "text-link" : "text-danger"}`}>
{note.text}
</p>
)}
{changes.length > 0 && (
<ul className="mt-2 space-y-1 text-xs text-muted">
{changes.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
)}
</Block>
);
}
export default function AdminPanel() {
const { user: me } = useAuth();
const navigate = useNavigate();
@ -103,6 +209,16 @@ export default function AdminPanel() {
load();
}, [load]);
// After a re-sync: the accounts table again, without the loading
// screen (which would clear the sync's result).
const refresh = async () => {
try {
setData(await get("/admin/panel/overview", { ttl: 0 }));
} catch {
// The table stays as it was; the next load shows any error.
}
};
/* Replace the one row the server returns rather than refetching
the whole overview; the counts didn't change. */
function mergeUser(updated) {
@ -164,7 +280,7 @@ export default function AdminPanel() {
);
}
const { system, content, users } = data;
const { system, content, users, access } = data;
const activeSupers = users.filter(
(u) => isSuper(u) && u.is_active === 1,
).length;
@ -227,6 +343,7 @@ export default function AdminPanel() {
const lastSuper =
isSuper(row) && row.is_active === 1 && activeSupers <= 1;
const locked = isMe || lastSuper;
const fromGroup = row.access_source === "group";
const busy = busyId === row.id;
return (
@ -243,6 +360,12 @@ export default function AdminPanel() {
{row.name && (
<div className="text-xs text-muted/80">{row.email}</div>
)}
{fromGroup && (
<div className="mt-1 text-xs text-muted">
Google group
{row.group_disabled === 1 && ": in no access group"}
</div>
)}
{rowError?.id === row.id && (
<div className="mt-1 text-xs text-danger">
{rowError.message}
@ -253,11 +376,13 @@ export default function AdminPanel() {
<td className="px-4 py-3">
<select
value={row.role}
disabled={locked || busy}
disabled={locked || busy || fromGroup}
onChange={(e) => changeRole(row, e.target.value)}
className="rounded-lg border border-brand/30 bg-surface px-2 py-1 text-sm text-ink disabled:cursor-not-allowed disabled:bg-tint-soft disabled:text-muted/60"
title={
isMe
fromGroup
? "The role comes from this person's Google group."
: isMe
? "You can't change your own role."
: lastSuper
? "The last active superadmin can't be demoted."
@ -323,9 +448,12 @@ export default function AdminPanel() {
</dl>
<p className="mt-4 text-xs text-muted/80">
New accounts are still created with <code>admin-cli.js</code> on the server.
New accounts are created with <code>admin-cli.js</code> on the server, or by signing in
with Google while in one of the groups below.
</p>
</Block>
<AccessGroups access={access} onSynced={refresh} />
</div>
);
}

View file

@ -48,7 +48,7 @@
import { ArrowLeft } from "@phosphor-icons/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { get, post, patch, del, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
@ -367,6 +367,8 @@ export default function EntityEdit() {
{isNew ? `New ${manifest.singular}` : heading}
</h1>
<ImportedNote />
{/* Straight in the page, not wrapped: a sticky element only
travels within its parent, so its parent has to be tall. */}
<SectionJump sections={sections} />
@ -527,3 +529,25 @@ export default function EntityEdit() {
</div>
);
}
/* After Import from Word (EntityList's ImportButton): what came over,
and what's left to do before publishing. Gone on the next visit. */
function ImportedNote() {
const summary = (useLocation().state as any)?.imported;
if (!summary) return null;
const parts = [
`${summary.headings} headings`,
`${summary.paragraphs} paragraphs`,
`${summary.lists} lists`,
`${summary.tables} tables`,
];
return (
<p role="status" className="mt-4 rounded-xl border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
Imported from Word: {parts.join(", ")}.
{summary.skipped?.images
? ` ${summary.skipped.images} image${summary.skipped.images === 1 ? " was" : "s were"} not carried over; add them as Image blocks.`
: ""}{" "}
It's saved unpublished: check it, add the authors and a cover, then tick Published.
</p>
);
}

View file

@ -15,7 +15,7 @@
import { useCallback, useEffect, useState } from "react";
import { Link, Navigate, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { get, ApiError } from "../../lib/api.ts";
import { get, upload, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { ADMIN_ENTITIES } from "../../lib/adminSchema.ts";
import { atLeast } from "../../lib/roles.ts";
@ -93,10 +93,11 @@ export default function EntityList() {
<div>
<div className="flex flex-wrap items-center gap-4">
<h1 className="text-3xl font-bold text-link">{manifest.label}</h1>
{canWrite && manifest.importer && <ImportButton manifest={manifest} />}
{canWrite && (
<Link
to={`/admin/${manifest.key}/new`}
className="ml-auto rounded-full bg-action px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-action-hover"
className={`${manifest.importer ? "" : "ml-auto "}rounded-full bg-action px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-action-hover`}
>
New {manifest.singular}
</Link>
@ -213,3 +214,54 @@ export default function EntityList() {
</div>
);
}
/* A manifest's `importer`: pick a file, the server turns it into a
new record, and its editor opens with a note of what came over
(EntityEdit shows it). Blog posts take Word documents. */
function ImportButton({ manifest }: { manifest: any }) {
const navigate = useNavigate();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function send(file: File) {
setBusy(true);
setError(null);
const form = new FormData();
form.set("file", file);
try {
const result = await upload(manifest.importer.endpoint, form);
navigate(`/admin/${manifest.key}/${result.id}`, { state: { imported: result.summary } });
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
setBusy(false);
}
}
return (
<div className="ml-auto flex items-center gap-3">
{error && (
<span role="alert" className="text-sm text-danger">
{error}
</span>
)}
<label
className={`cursor-pointer rounded-full border border-link px-4 py-2 text-sm font-semibold text-link transition-colors hover:bg-tint ${
busy ? "pointer-events-none opacity-60" : ""
}`}
>
{busy ? "Importing…" : manifest.importer.label}
<input
type="file"
accept={manifest.importer.accept}
className="sr-only"
disabled={busy}
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (file) send(file);
}}
/>
</label>
</div>
);
}

View file

@ -75,6 +75,11 @@ export const DATA_NAV = {
label: "People",
blurb: "Bios, contact details, affiliations and awards received.",
},
{
to: "/admin/blog_posts",
label: "Blog posts",
blurb: "Posts of our own, each at /blog/…, written here or imported from Word.",
},
],
};
@ -95,11 +100,6 @@ export const PAGES_NAV = {
label: "Timeline",
blurb: "What the history page shows, and the order it shows it in.",
},
{
to: "/admin/blog_posts",
label: "Blog posts",
blurb: "Posts of our own, each at /blog/…",
},
{
to: "/admin/community_page",
label: "Community blog section",
@ -118,6 +118,11 @@ export const FORMS_NAV = {
label: "Website feedback",
blurb: "The triage queue for the feedback form.",
},
{
to: "/admin/requests",
label: "Content requests",
blurb: "Requests for blog posts, events, and new or updated organizations, teams, awards and people, with their files.",
},
{
to: "/admin/data-requests",
label: "Data requests",

View file

@ -34,16 +34,16 @@ const WHOLE_PAGE = "";
/* ── Shared field chrome ─────────────────────────────────────── */
const fieldClass =
export const fieldClass =
"w-full rounded-xl border border-muted/50 bg-surface px-4 py-3 text-body " +
"placeholder:text-muted outline-none transition-colors " +
"focus:border-brand focus:ring-2 focus:ring-brand/25";
const errorFieldClass = "border-danger focus:border-danger focus:ring-danger/20";
export const errorFieldClass = "border-danger focus:border-danger focus:ring-danger/20";
const selectClass = `${fieldClass} appearance-none pr-10`;
function OptionalTag() {
export function OptionalTag() {
return (
<span className="ml-2 rounded-full bg-tint px-2 py-0.5 text-xs font-medium text-link">
Optional
@ -51,7 +51,7 @@ function OptionalTag() {
);
}
function FieldError({ id, children }) {
export function FieldError({ id, children }) {
if (!children) return null;
return (
<p id={id} className="mt-2 text-sm text-danger">
@ -82,26 +82,38 @@ function Select({ id, label, value, onChange, children }) {
);
}
/* ── Type picker ─────────────────────────────────────────────── */
/* ── Type picker: a tile per option (the Request form's too) ─── */
function TypePicker({ value, onChange }) {
export function TilePicker({
legend,
blurb,
name,
options,
value,
onChange,
}: {
legend: string;
blurb: string;
name: string;
options: { id: string; label: string; hint: string }[];
value: string | null;
onChange: (id: string) => void;
}) {
return (
<fieldset>
<legend className="text-base font-semibold text-body">
What kind of feedback is this?
</legend>
<legend className="text-base font-semibold text-body">{legend}</legend>
<p className="mt-1 text-sm" style={{ color: MUTED }}>
Pick the closest fit. It helps us route it to the right person.
{blurb}
</p>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{FEEDBACK_TYPES.map((type) => {
{options.map((type) => {
const selected = value === type.id;
return (
<label key={type.id} className="cursor-pointer">
<input
type="radio"
name="feedbackType"
name={name}
value={type.id}
checked={selected}
onChange={() => onChange(type.id)}
@ -317,7 +329,14 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
>
{!fixedType && (
<>
<TypePicker value={type} onChange={setType} />
<TilePicker
legend="What kind of feedback is this?"
blurb="Pick the closest fit. It helps us route it to the right person."
name="feedbackType"
options={FEEDBACK_TYPES}
value={type}
onChange={setType}
/>
<div className="mt-10">
<LocationPicker

View file

@ -432,7 +432,7 @@ export default function QrCodeMaker() {
className="rounded-full border px-4 py-2 text-sm font-semibold transition-colors hover:bg-brand/10"
style={{ borderColor: BRAND, color: accentText(BRAND) }}
>
{copied ? 'Copied ✓' : 'Copy link'}
{copied ? 'Copied' : 'Copy link'}
</button>
</div>
</div>

View file

@ -0,0 +1,336 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST FORM
Posts to /api/requests (server/src/routes/requests.js), as a form
so files can go with it. What can be asked for is REQUEST_TYPES;
?type=chapter in the address picks one to start with, which is how
the site's "Request" buttons open it.
Files go to Google Drive on the server; when Drive isn't set up
(REQUEST_FILES) the file field isn't shown. The limits here match
the server's, so nobody waits on an upload that will be refused.
═══════════════════════════════════════════════════════════════ */
import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import { ApiError, upload } from "../../lib/api.ts";
import { accentText, BRAND } from "../../lib/color.ts";
import { REQUEST_FILES } from "../../lib/site.ts";
import { REQUEST_TYPES, type RequestAction } from "../../data/requestTypes.ts";
import { FieldError, OptionalTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx";
const MUTED = "var(--color-muted)";
const MAX_CHARS = 5000;
const MIN_MESSAGE = 10; // matches the server
const MAX_FILES = 3;
const MAX_FILE_MB = 10;
const ACCEPT = ".docx,.pdf,.jpg,.jpeg,.png";
const ACTION_LABEL: Record<RequestAction, string> = {
new: "Something new",
update: "An update to what's there",
};
const PLACEHOLDER: Record<string, string> = {
blog: "A few lines about the post: what it's about, and anything we should know. Attach the post as a Word document.",
event: "When and where, who it's for, how to register, and who to contact.",
};
export default function RequestForm() {
const [params] = useSearchParams();
const start = REQUEST_TYPES.find((t) => t.id === params.get("type")) ?? null;
const [category, setCategory] = useState<string | null>(start?.id ?? null);
const [action, setAction] = useState<RequestAction | null>(start?.actions.length === 1 ? start.actions[0] : null);
const [subject, setSubject] = useState("");
const [message, setMessage] = useState("");
const [files, setFiles] = useState<File[]>([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [website, setWebsite] = useState(""); // honeypot
const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle");
const [formError, setFormError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const type = REQUEST_TYPES.find((t) => t.id === category);
const sending = status === "sending";
const fileError =
files.length > MAX_FILES
? `${MAX_FILES} files at most.`
: files.find((f) => f.size > MAX_FILE_MB * 1024 * 1024)
? `Files can be ${MAX_FILE_MB} MB each at most.`
: null;
const ready =
Boolean(type && action) &&
subject.trim() !== "" &&
message.trim().length >= MIN_MESSAGE &&
email.trim() !== "" &&
!fileError;
function pick(id: string) {
const next = REQUEST_TYPES.find((t) => t.id === id);
setCategory(id);
// One choice picks itself; otherwise keep what was chosen if it still applies.
setAction((prev) => (next?.actions.length === 1 ? next.actions[0] : prev && next?.actions.includes(prev) ? prev : null));
}
async function handleSubmit(event) {
event.preventDefault();
if (!ready || sending || !category || !action) return;
setStatus("sending");
setFormError(null);
setFieldErrors({});
const form = new FormData();
form.set("category", category);
form.set("action", action);
form.set("subject", subject.trim());
form.set("message", message.trim());
form.set("name", name.trim());
form.set("email", email.trim());
form.set("website", website);
for (const file of files) form.append("files", file);
try {
await upload("/requests", form);
setStatus("sent");
} catch (error) {
setStatus("idle");
if (error instanceof ApiError) {
setFieldErrors(error.fields ?? {});
setFormError(error.fields ? "Have another look at the highlighted fields." : error.message);
} else {
setFormError("Couldn't reach the server. Try again in a moment.");
}
}
}
function reset() {
setSubject("");
setMessage("");
setFiles([]);
setStatus("idle");
setFormError(null);
setFieldErrors({});
}
if (status === "sent") {
return (
<div aria-live="polite" className="rounded-2xl border border-brand/20 bg-surface p-8 sm:p-10">
<h3 className="text-2xl font-bold" style={{ color: accentText(BRAND) }}>
Thanks, we've got it
</h3>
<p className="mt-3 max-w-prose" style={{ color: MUTED }}>
We'll look it over and follow up at {email}, usually within a week.
</p>
<button
type="button"
onClick={reset}
className="mt-6 rounded-full border border-brand px-5 py-2.5 font-semibold text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40"
>
Send another request
</button>
</div>
);
}
return (
<form onSubmit={handleSubmit} noValidate className="rounded-2xl border border-brand/20 bg-surface p-6 sm:p-8">
<TilePicker
legend="What is this about?"
blurb="Pick the closest fit."
name="category"
options={REQUEST_TYPES}
value={category}
onChange={pick}
/>
<FieldError id="request-category-error">{fieldErrors.category}</FieldError>
{type && type.actions.length > 1 && (
<fieldset className="mt-8">
<legend className="text-base font-semibold text-body">New, or an update?</legend>
<div className="mt-3 flex flex-wrap gap-3">
{type.actions.map((a) => (
<label key={a} className="cursor-pointer">
<input
type="radio"
name="action"
value={a}
checked={action === a}
onChange={() => setAction(a)}
className="peer sr-only"
/>
<span
className={
"inline-block rounded-full border px-5 py-2 text-sm font-semibold transition-colors " +
"peer-focus-visible:ring-2 peer-focus-visible:ring-brand/40 " +
(action === a ? "border-brand bg-tint text-link" : "border-muted/30 text-body hover:border-brand/50")
}
>
{ACTION_LABEL[a]}
</span>
</label>
))}
</div>
<FieldError id="request-action-error">{fieldErrors.action}</FieldError>
</fieldset>
)}
{type?.id === "region" && (
<p className="mt-4 text-sm" style={{ color: MUTED }}>
Regions are set by Unity, so this is for updating one that's on the site.
</p>
)}
{type && (
<>
<div className="mt-8">
<label htmlFor="request-subject" className="text-base font-semibold text-body">
{action === "update" && type.actions.length > 1 ? `Which ${type.label.toLowerCase()}?` : type.subject}
</label>
<input
id="request-subject"
type="text"
maxLength={200}
value={subject}
onChange={(e) => setSubject(e.target.value)}
aria-invalid={Boolean(fieldErrors.subject)}
aria-describedby={fieldErrors.subject ? "request-subject-error" : undefined}
className={`mt-3 ${fieldClass} ${fieldErrors.subject ? errorFieldClass : ""}`}
/>
<FieldError id="request-subject-error">{fieldErrors.subject}</FieldError>
</div>
<div className="mt-8">
<label htmlFor="request-message" className="text-base font-semibold text-body">
{action === "update" ? "What should change?" : "Tell us about it"}
</label>
<textarea
id="request-message"
rows={7}
maxLength={MAX_CHARS}
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder={
action === "update"
? "What's there now, and what it should say instead."
: (PLACEHOLDER[type.id] ?? "Everything we'd need to add it: a description, links, and who to contact.")
}
aria-invalid={Boolean(fieldErrors.message)}
aria-describedby={fieldErrors.message ? "request-message-error" : undefined}
className={`mt-3 resize-y ${fieldClass} ${fieldErrors.message ? errorFieldClass : ""}`}
/>
<div className="mt-2 flex items-start justify-between gap-4">
<FieldError id="request-message-error">{fieldErrors.message}</FieldError>
<span className="ml-auto shrink-0 text-xs tabular-nums" style={{ color: MUTED }}>
{message.length} / {MAX_CHARS}
</span>
</div>
</div>
{REQUEST_FILES && (
<div className="mt-8">
<div className="flex flex-wrap items-center">
<label htmlFor="request-files" className="text-base font-semibold text-body">
Files
</label>
<OptionalTag />
</div>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
A Word document (.docx) with the details or the post itself, photos (JPEG or PNG) or a PDF. Up to{" "}
{MAX_FILES}, {MAX_FILE_MB} MB each.
</p>
<input
id="request-files"
type="file"
multiple
accept={ACCEPT}
onChange={(e) => setFiles(Array.from(e.target.files ?? []))}
aria-invalid={Boolean(fileError || fieldErrors.files)}
aria-describedby={fileError || fieldErrors.files ? "request-files-error" : undefined}
className="mt-3 block w-full text-sm text-body file:mr-4 file:rounded-full file:border-0 file:bg-tint file:px-4 file:py-2 file:font-semibold file:text-link hover:file:bg-tint-soft"
/>
<FieldError id="request-files-error">{fileError ?? fieldErrors.files}</FieldError>
</div>
)}
</>
)}
<div className="mt-8 rounded-xl border border-dashed border-muted/30 bg-tint/60 p-5 sm:p-6">
<h3 className="text-base font-semibold text-body">How we reach you</h3>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
We use these only to follow up on this request, and we won't add you to any list.
</p>
<div className="mt-5 grid gap-4 sm:grid-cols-2">
<div>
<label htmlFor="request-name" className="block text-sm font-medium text-body">
Name <span className="font-normal text-muted">(optional)</span>
</label>
<input
id="request-name"
type="text"
autoComplete="name"
value={name}
onChange={(e) => setName(e.target.value)}
className={`mt-2 ${fieldClass}`}
/>
</div>
<div>
<label htmlFor="request-email" className="block text-sm font-medium text-body">
Email <span className="font-normal text-muted">(required)</span>
</label>
<input
id="request-email"
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? "request-email-error" : undefined}
className={`mt-2 ${fieldClass} ${fieldErrors.email ? errorFieldClass : ""}`}
/>
<FieldError id="request-email-error">{fieldErrors.email}</FieldError>
</div>
</div>
</div>
{/* Honeypot, as on the feedback form. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<label htmlFor="request-website">Website</label>
<input
id="request-website"
type="text"
tabIndex={-1}
autoComplete="off"
value={website}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
{formError && (
<p role="alert" className="mt-8 rounded-xl border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
{formError}
</p>
)}
<div className="mt-6 flex flex-wrap items-center gap-4">
<button
type="submit"
disabled={!ready || sending}
className="rounded-full bg-action px-7 py-3 font-semibold text-white transition-colors hover:bg-action-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:bg-muted/25 disabled:text-white/80"
>
{sending ? (files.length ? "Uploading…" : "Sending…") : "Send request"}
</button>
{!ready && !sending && (
<p className="text-sm" style={{ color: MUTED }}>
Choose what it's about, give it a name, write at least a sentence and give an email address to send.
</p>
)}
</div>
</form>
);
}

View file

@ -1,3 +1,4 @@
import { CircleDashed } from '@phosphor-icons/react'
import {
decadeLabel,
withGapYears,
@ -44,7 +45,7 @@ export default function TimelineDecade({
{decade.blurb ? <p className="site-tl__decadeBlurb">{decade.blurb}</p> : null}
{decade.preProgram ? (
<p className="site-tl__gapNote">
<span aria-hidden="true">◌</span>
<CircleDashed aria-hidden="true" weight="bold" className="inline-block align-[-0.125em]" />
Before the program, kept for context, not part of our record
</p>
) : null}

View file

@ -1,3 +1,4 @@
import { CaretDown, CaretUp } from '@phosphor-icons/react'
import { useState } from 'react'
import type { GroupedYear, SortDirection } from '../../../lib/timeline.ts'
import TimelineYear from './TimelineYear.tsx'
@ -48,7 +49,7 @@ export default function TimelineUpcoming({
: `${count} ${count === 1 ? 'thing' : 'things'} still to come`}
</span>
<span className="site-tl__chevron" aria-hidden="true">
{open ? '▾' : '▴'}
{open ? <CaretDown weight="bold" /> : <CaretUp weight="bold" />}
</span>
</button>

View file

@ -9,17 +9,21 @@
═══════════════════════════════════════════════════════════════ */
import EventCalendar from '../EventCalendar.tsx'
import RequestLink from '../../../components/RequestLink.tsx'
type CalendarBandProps = { id: string; title: string; blurb?: string | null }
export default function CalendarBand({ id, title, blurb }: CalendarBandProps) {
return (
<section id={id} className="py-24" style={{ background: 'var(--color-tint-soft)' }}>
<div className="mx-auto mb-10 max-w-6xl px-6">
<h2 className="font-display text-4xl font-extrabold text-ink md:text-5xl">
{title}
</h2>
{blurb && <p className="mt-3 max-w-xl text-lg text-muted">{blurb}</p>}
<div className="mx-auto mb-10 flex max-w-6xl flex-wrap items-end justify-between gap-4 px-6">
<div>
<h2 className="font-display text-4xl font-extrabold text-ink md:text-5xl">
{title}
</h2>
{blurb && <p className="mt-3 max-w-xl text-lg text-muted">{blurb}</p>}
</div>
<RequestLink type="event" label="Add or update an event" />
</div>
<EventCalendar />