From e7c99a788ef952d594a94105afc16b6e4da8cd8b Mon Sep 17 00:00:00 2001 From: blake Date: Mon, 26 Oct 2026 14:00:29 -0500 Subject: [PATCH] feat: let a signed-in administrator add and remove other administrators --- README.md | 12 +- public/css/app.css | 29 ++++- src/admin-http.tsx | 91 +++++++++++++++ src/admin-pages.tsx | 101 ++++++++++++++++- src/admins.ts | 133 ++++++++++++++++++++++ tests/admins.test.ts | 259 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 618 insertions(+), 7 deletions(-) create mode 100644 src/admins.ts create mode 100644 tests/admins.test.ts diff --git a/README.md b/README.md index d6cc1e8..2e913c6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This program is distributed in the hope that it will be useful, but WITHOUT ANY You should have received a copy of the GNU General Public License along with this program. If not, see . -**This is not ready for a public launch, and it is not ready for real volunteer records.** Phase 1A has public browsing, individual signup, cancellation, queued email, and coordinator sign-in for events, one-off shifts, rosters, and cancellation. A coordinator can add a walk-in, mark attendance, and move a signup from a shift roster. A volunteer can switch shifts from their private link. An active weekly template fills shifts for the next eight weeks. A coordinator can add, change, or end a weekly template, and can remove a cancelled person, a finished empty shift, an ended template, or an event that is off the public list and already empty. A confirmed signup can receive a reminder 48 hours before the shift and again 2 hours before, and can turn reminders off without cancelling. A coordinator can download a roster for one shift, one event, or a local date range. A coordinator can import a contact list, download it, use a saved contact when adding a walk-in, and add a saved contact to an open shift. A coordinator can set the two reminder times, the reply-to address, how many months to keep a signup, and the wording on the privacy page. After 1:00 AM Central Time, signups older than that many months lose their name and contact details in this app. After 2:30 AM Central Time, the app saves a database backup on this computer. A container can run that same app on this computer, on port 3020, without opening it to the network. This is not a public launch. Around 1:00 AM in each event's time zone, the app adds any missing weekly shifts for the next eight weeks, once that local day. Development prints mail in the server log. It does not send real email. +**This is not ready for a public launch, and it is not ready for real volunteer records.** Phase 1A has public browsing, individual signup, cancellation, queued email, and coordinator sign-in for events, one-off shifts, rosters, and cancellation. A coordinator can add a walk-in, mark attendance, and move a signup from a shift roster. A volunteer can switch shifts from their private link. An active weekly template fills shifts for the next eight weeks. A coordinator can add, change, or end a weekly template, and can remove a cancelled person, a finished empty shift, an ended template, or an event that is off the public list and already empty. A confirmed signup can receive a reminder 48 hours before the shift and again 2 hours before, and can turn reminders off without cancelling. A coordinator can download a roster for one shift, one event, or a local date range. A coordinator can import a contact list, download it, use a saved contact when adding a walk-in, and add a saved contact to an open shift. A coordinator can set the two reminder times, the reply-to address, how many months to keep a signup, and the wording on the privacy page. A signed-in administrator can add another administrator. Removing someone takes away their sign-in access. The last administrator cannot be removed. After 1:00 AM Central Time, signups older than that many months lose their name and contact details in this app. After 2:30 AM Central Time, the app saves a database backup on this computer. A container can run that same app on this computer, on port 3020, without opening it to the network. This is not a public launch. Around 1:00 AM in each event's time zone, the app adds any missing weekly shifts for the next eight weeks, once that local day. Development prints mail in the server log. It does not send real email. ## Current step @@ -77,7 +77,7 @@ An open shift has a signup form. It asks for one person. Another person can use With `MAIL_DRIVER=console`, the development server tries to send queued mail every 30 seconds and prints each accepted message in its terminal. That is not delivery to a real inbox. `sent` means the driver accepted the message. A lost result is marked uncertain and is not sent again. SMTP2GO is the mail provider. Set `MAIL_DRIVER=smtp2go` and `SMTP2GO_API_KEY` to send through it. Postmark and SES remain available. -Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password. +Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. More administrators are added from **Administrators** after someone is signed in. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password. After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling keeps the roster. It does not delete the shift or the signup. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued. @@ -107,6 +107,8 @@ A reminder is queued at each saved time before a confirmed signup, while the shi **Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration. +**Administrators**, on the coordinator page, lists who can sign in. **Add an administrator** saves a name and email. It does not send email. That person requests a sign-in link at `/login`. Saving an address that was removed earlier gives that person access again and updates the name. **Remove** takes away access, signs that person out, and stops unused sign-in links. It does not send email. The last administrator cannot be removed. Any administrator can add or remove the others, including themselves when someone else still has access. + Around 1:00 AM in an event's time zone, the app adds any missing shifts from that event's active weekly templates. It does this once for that local date. If 1:00 happens twice when the clocks change, the second hour does not add them again. If 1:00 does not exist that day, the fill runs once the local clock is past 1:00. A restart later that day still fills the date if it was missed. A date that already has a shift, including a cancelled one, stays as it is. Starting the app, and **Add weekly shifts**, still fill the schedule as well. After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift, the signup status, and attendance stay, so the count remains. Legacy guardian columns, when present, are cleared too. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk. The contact list is separate. Clearing an old signup does not remove that person from the contact list. @@ -140,7 +142,7 @@ Development may use the console driver and the always-pass Turnstile test keys i `DATA_DIR` defaults to `/data`. Local development uses `./data`. The database file is `app.db` inside that directory. -`BOOTSTRAP_ADMIN_EMAIL` is the address used to create the first administrator, and only when no coordinator exists yet. The app does not overwrite an existing account. Password login is not built. `password_hash` stays empty. +`BOOTSTRAP_ADMIN_EMAIL` is the address used to create the first administrator, and only when no coordinator exists yet. The app does not overwrite an existing account. Later administrators are added from the Administrators page. Password login is not built. `password_hash` stays empty. ## Time @@ -272,9 +274,9 @@ In the container, run the built copy. It uses the container's configuration and docker compose exec hope-volunteer node dist/recover-coordinator.js old@example.invalid --replace new@example.invalid ``` -There is one administrator. The address set in `BOOTSTRAP_ADMIN_EMAIL` at the first production start becomes that account. Changing `.env` later does not change it. Use `--replace` to move the account to another address. Before the pantry's mailbox becomes the sign-in address, turn on 2-Step Verification for it: anyone who can read that inbox can sign in. +The address set in `BOOTSTRAP_ADMIN_EMAIL` at the first production start becomes the first administrator. Changing `.env` later does not add or replace anyone. More administrators are added from **Administrators** after sign-in. Use `--replace` to move one account to another address. Before a mailbox becomes a sign-in address, turn on 2-Step Verification for it: anyone who can read that inbox can sign in. -The command prints the coordinator id, not the address. It does not deactivate anyone. Deactivating coordinators in the browser is not built. Do not delete the last administrator without another one ready. The person then requests a new sign-in link at `/login`. +The command prints the coordinator id, not the address. It does not deactivate anyone. Removing access in the browser is on the Administrators page. That page cannot remove the last administrator. Do not delete the last administrator from the database without another one ready. The person then requests a new sign-in link at `/login`. ## What is still unverified diff --git a/public/css/app.css b/public/css/app.css index 821496c..3fc4947 100644 --- a/public/css/app.css +++ b/public/css/app.css @@ -2293,13 +2293,40 @@ button.btn-quiet::before { margin: 0.35rem 0 0; } +.admin-list { + list-style: none; + margin: 1rem 0 0; + padding: 0; +} + +.admin-row { + display: grid; + grid-template-columns: minmax(10rem, 1.2fr) minmax(12rem, 1.6fr) auto; + gap: 0.35rem 1rem; + align-items: baseline; + padding: 0.75rem 0; + border-top: 1px solid var(--hope-border-2); +} + +.admin-row p { + margin: 0; + overflow-wrap: anywhere; +} + +.admin-you { + margin-left: 0.45rem; + font-size: 0.85rem; + font-weight: 650; +} + #add-shift { border-radius: 1.25rem; padding-right: 2.5rem; } @media (max-width: 42em) { - .contact-row { + .contact-row, + .admin-row { grid-template-columns: 1fr; } } diff --git a/src/admin-http.tsx b/src/admin-http.tsx index 60a1e49..9d239dd 100644 --- a/src/admin-http.tsx +++ b/src/admin-http.tsx @@ -60,15 +60,18 @@ import { templateEndPrompt, templateRemovalPrompt, type ConfirmPrompt, + adminRemovalPrompt, contactRemovalPrompt, ContactPage, ContactsPage, + AdminsPage, SettingsPage, ShiftEditor, ShiftRoster, TemplateEditor, type WalkInState, } from './admin-pages.js'; +import { addAdmin, deactivateAdmin, listAdmins, readAdminRemoval, type AdminErrors, type AdminForm } from './admins.js'; import { writeAudit } from './auth/audit.js'; import { consumeLoginLink, issueLoginProof, loginLinkOpen, loginProofMatches, requestMagicLink } from './auth/login.js'; import { csrfMatches, readSession, revokeSession, sessionClearCookie, sessionSetCookie, type CoordinatorSession } from './auth/session.js'; @@ -141,6 +144,10 @@ export function registerAdmin(app: Hono, services: AdminServices): void { app.get(appPath(config, '/admin'), (c) => showHome(c, services)); app.get(appPath(config, '/admin/settings'), (c) => showSettings(c, services)); app.post(appPath(config, '/admin/settings'), (c) => submitSettings(c, services)); + app.get(appPath(config, '/admin/admins'), (c) => showAdmins(c, services)); + app.post(appPath(config, '/admin/admins'), (c) => submitNewAdmin(c, services)); + app.get(appPath(config, '/admin/admins/:id/remove'), (c) => showRemoveAdmin(c, services)); + app.post(appPath(config, '/admin/admins/:id/remove'), (c) => submitRemoveAdmin(c, services)); app.post(appPath(config, '/admin/export'), (c) => submitExportRange(c, services)); app.get(appPath(config, '/admin/contacts'), (c) => showContacts(c, services)); app.post(appPath(config, '/admin/contacts/new'), (c) => submitNewContact(c, services)); @@ -631,6 +638,87 @@ async function submitSettings(c: Context, services: AdminServices): Promise, + { account: session, status: state?.status ?? 200 }, + ); +} + +async function submitNewAdmin(c: Context, services: AdminServices): Promise { + const session = await postedSession(c, services); + if (session instanceof Response) return session; + const values = { name: textField(session.body, 'name'), email: textField(session.body, 'email') }; + try { + const saved = addAdmin(services.db, session.coordinatorId, values, services.now()); + if (!saved.ok) return showAdmins(c, services, { values, errors: saved.errors, status: 400 }); + const notice = saved.status === 'restored' ? 'admin-restored' : 'admin-added'; + return c.redirect(appPath(services.config, `/admin/admins?notice=${notice}`), 303); + } catch (err) { + return saveFailed(c, services, session, err); + } +} + +function showRemoveAdmin(c: Context, services: AdminServices, error?: string, status: 200 | 400 | 403 = 200) { + const session = requireSession(c, services); + if (session instanceof Response) return session; + const removal = readAdminRemoval(services.db, idFrom(c)); + if (!removal) return missing(c, services); + const prompt = adminRemovalPrompt({ + name: removal.admin.name, + email: removal.admin.email, + self: removal.admin.id === session.coordinatorId, + last: removal.last, + }); + return showAdmins(c, services, { + status, + confirm: { + ...prompt, + body: error && error !== prompt.body ? error : prompt.body, + submit: error ? undefined : prompt.submit, + error: error && error !== prompt.body ? error : undefined, + action: appPath(services.config, `/admin/admins/${removal.admin.id}/remove`), + }, + }); +} + +async function submitRemoveAdmin(c: Context, services: AdminServices): Promise { + const session = await postedSession(c, services); + if (session instanceof Response) return session; + const id = idFrom(c); + try { + const removed = deactivateAdmin(services.db, session.coordinatorId, id, services.now()); + if (!removed.ok) { + if (removed.reason === 'missing') return missing(c, services); + return showRemoveAdmin(c, services, 'Add another administrator before removing this one.', 400); + } + if (id === session.coordinatorId) { + c.header('Set-Cookie', sessionClearCookie(services.config)); + return c.redirect(appPath(services.config, '/login'), 303); + } + return c.redirect(appPath(services.config, '/admin/admins?notice=admin-removed'), 303); + } catch (err) { + return saveFailed(c, services, session, err); + } +} + function settingsFormFromBody(body: Record): SettingsForm { return { reminderFar: textField(body, 'reminder_far'), @@ -1520,6 +1608,9 @@ function knownNotice(value: string | undefined): string | undefined { value === 'template-removed' || value === 'event-removed' || value === 'settings-saved' || + value === 'admin-added' || + value === 'admin-restored' || + value === 'admin-removed' || value === 'contact-removed' || value === 'contact-saved' || value === 'contact-updated' || diff --git a/src/admin-pages.tsx b/src/admin-pages.tsx index 5a771f6..88025f8 100644 --- a/src/admin-pages.tsx +++ b/src/admin-pages.tsx @@ -16,6 +16,7 @@ import { import type { SignupErrors, SignupValues } from './signup-form.js'; import { addLocalDays, formatInstantInZone, todayInZone } from './time.js'; import { ShiftTargetOptions } from './shift-options.js'; +import type { AdminAccount, AdminErrors, AdminForm } from './admins.js'; import { assetHref } from './static-assets.js'; import { appPath } from './url.js'; @@ -140,6 +141,27 @@ export function contactRemovalPrompt(contact: { name: string; email: string }): }; } +export function adminRemovalPrompt(admin: { name: string; email: string; self: boolean; last: boolean }): Omit { + const title = admin.self ? 'Remove your access' : `Remove ${admin.name}`; + if (admin.last) { + return { title, detail: admin.email, body: 'Add another administrator before removing this one.' }; + } + if (admin.self) { + return { + title, + detail: admin.email, + body: 'This signs you out. Your sign-in links stop working. Someone else who still has access can add you again. It does not send email.', + submit: 'Remove your access', + }; + } + return { + title, + detail: admin.email, + body: 'This removes their access. Their sign-in links stop working. It does not send email.', + submit: 'Remove this administrator', + }; +} + export function templateRemovalPrompt( template: { role: string; weekday: number; active: boolean }, error?: string, @@ -226,6 +248,7 @@ export function AdminHome(props: { @@ -356,6 +379,78 @@ export function SettingsPage(props: { ); } +export function AdminsPage(props: { + config: AppConfig; + csrf: string; + currentId: number; + admins: AdminAccount[]; + notice?: string; + form?: { values: AdminForm; errors: AdminErrors }; + confirm?: ConfirmPrompt; +}) { + const form = props.form ?? { values: { name: '', email: '' }, errors: {} }; + const only = props.admins.length === 1; + return ( + <> + +

Administrators

+ +

+ These people can sign in and manage the pantry. Adding someone does not send email. They request a sign-in link on the coordinator sign-in page. Removing someone signs them out and stops unused sign-in links. The last administrator stays until another one is added. Saving an address you removed earlier gives that person access again. +

+