feat: let a signed-in administrator add and remove other administrators
This commit is contained in:
1 parent
58da832bac
commit
e7c99a788e
6 files changed
+618
-7
No files matched your search
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
**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
|
||||
|
||||
|
||||
+28
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Resp
|
||||
return c.redirect(appPath(services.config, '/admin/settings?notice=settings-saved'), 303);
|
||||
}
|
||||
|
||||
function showAdmins(
|
||||
c: Context,
|
||||
services: AdminServices,
|
||||
state?: { values?: AdminForm; errors?: AdminErrors; status?: 200 | 400 | 403; confirm?: ConfirmPrompt },
|
||||
) {
|
||||
const session = requireSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
return html(
|
||||
c,
|
||||
services,
|
||||
'Administrators · Hope Volunteer',
|
||||
<AdminsPage
|
||||
config={services.config}
|
||||
csrf={session.csrf}
|
||||
currentId={session.coordinatorId}
|
||||
admins={listAdmins(services.db)}
|
||||
notice={state?.status === 400 ? undefined : knownNotice(c.req.query('notice'))}
|
||||
form={state?.values ? { values: state.values, errors: state.errors ?? {} } : undefined}
|
||||
confirm={state?.confirm}
|
||||
/>,
|
||||
{ account: session, status: state?.status ?? 200 },
|
||||
);
|
||||
}
|
||||
|
||||
async function submitNewAdmin(c: Context, services: AdminServices): Promise<Response> {
|
||||
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<Response> {
|
||||
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<string, unknown>): 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' ||
|
||||
|
||||
+100
-1
@@ -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<ConfirmPrompt, 'action'> {
|
||||
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: {
|
||||
<nav class="desk-links" aria-label="Coordinator">
|
||||
<a href={appPath(props.config, '/admin/contacts')}>Contacts</a>
|
||||
<a href={appPath(props.config, '/admin/settings')}>Settings</a>
|
||||
<a href={appPath(props.config, '/admin/admins')}>Administrators</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
@@ -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 (
|
||||
<>
|
||||
<Crumb items={[{ href: appPath(props.config, '/admin'), label: 'Coordinator' }, { label: 'Administrators' }]} />
|
||||
<h1>Administrators</h1>
|
||||
<Notice notice={props.notice} />
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<form method="post" action={appPath(props.config, '/admin/admins')} class="signup-form">
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<h2>Add an administrator</h2>
|
||||
<WalkInField id="admin-name" label="Name" name="name" type="text" value={form.values.name} error={form.errors.name} required />
|
||||
<WalkInField
|
||||
id="admin-email"
|
||||
label="Email"
|
||||
name="email"
|
||||
type="email"
|
||||
value={form.values.email}
|
||||
error={form.errors.email}
|
||||
hint="This is the address they use to request a sign-in link."
|
||||
required
|
||||
/>
|
||||
<button type="submit">Add this administrator</button>
|
||||
</form>
|
||||
<section class="desk-events" aria-labelledby="admins-heading">
|
||||
<h2 id="admins-heading">{props.admins.length === 1 ? '1 administrator' : `${props.admins.length} administrators`}</h2>
|
||||
{only ? <p class="panel-note">This is the only administrator. Add another one before removing anyone.</p> : null}
|
||||
{props.admins.length === 0 ? <p class="empty">No administrators yet.</p> : null}
|
||||
{props.admins.length > 0 ? (
|
||||
<ul class="admin-list">
|
||||
{props.admins.map((person) => {
|
||||
const self = person.id === props.currentId;
|
||||
return (
|
||||
<li class="admin-row" key={person.id}>
|
||||
<p>
|
||||
<strong>{person.name}</strong>
|
||||
{self ? <span class="admin-you">You</span> : null}
|
||||
</p>
|
||||
<p>{person.email}</p>
|
||||
{only ? null : (
|
||||
<p>
|
||||
<ConfirmAnchor
|
||||
href={appPath(props.config, `/admin/admins/${person.id}/remove`)}
|
||||
label={self ? 'Remove your access' : `Remove ${person.name}`}
|
||||
prompt={adminRemovalPrompt({ name: person.name, email: person.email, self, last: false })}
|
||||
>
|
||||
Remove
|
||||
</ConfirmAnchor>
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : null}
|
||||
</section>
|
||||
<ConfirmDialog config={props.config} csrf={props.csrf} prompt={props.confirm} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function contactListHref(config: AppConfig, query: string, shown: number): string {
|
||||
const params = new URLSearchParams();
|
||||
if (query) params.set('q', query);
|
||||
@@ -1009,11 +1104,12 @@ function monthBounds(today: string, offset: number): { from: string; to: string
|
||||
return { from: start.toString(), to: end.toString() };
|
||||
}
|
||||
|
||||
function ConfirmAnchor(props: { href: string; class?: string; prompt: Omit<ConfirmPrompt, 'action'>; children: string }) {
|
||||
function ConfirmAnchor(props: { href: string; class?: string; label?: string; prompt: Omit<ConfirmPrompt, 'action'>; children: string }) {
|
||||
return (
|
||||
<a
|
||||
class={props.class}
|
||||
href={props.href}
|
||||
aria-label={props.label}
|
||||
data-confirm=""
|
||||
data-confirm-action={props.href}
|
||||
data-confirm-title={props.prompt.title}
|
||||
@@ -1805,6 +1901,9 @@ const NOTICES: Record<string, string> = {
|
||||
'template-removed': 'That weekly template is removed. Shifts already on the schedule stay, and they are no longer tied to the weekly pattern.',
|
||||
'event-removed': 'That event is removed.',
|
||||
'settings-saved': 'Settings saved.',
|
||||
'admin-added': 'That person can sign in. Ask them to request a sign-in link. This did not send email.',
|
||||
'admin-restored': 'That person can sign in again.',
|
||||
'admin-removed': 'That person can no longer sign in.',
|
||||
'contact-removed': 'That person is removed from the contact list.',
|
||||
'contact-saved': 'That contact is saved.',
|
||||
'contact-updated': 'That contact is updated.',
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from './auth/audit.js';
|
||||
import { EmailAddressError, normalizeEmail } from './email.js';
|
||||
import { isUniqueConstraint } from './sqlite-error.js';
|
||||
|
||||
const MAX_NAME = 80;
|
||||
const MAX_EMAIL = 254;
|
||||
const CONTROL = /[\u0000-\u001F\u007F]/;
|
||||
|
||||
export type AdminAccount = {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
export type AdminForm = {
|
||||
name: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
export type AdminErrors = Partial<Record<'name' | 'email', string>>;
|
||||
|
||||
type AdminRow = { id: number; name: string; email: string; active: number };
|
||||
|
||||
export function listAdmins(db: Database.Database): AdminAccount[] {
|
||||
return db
|
||||
.prepare(
|
||||
`SELECT id AS id, name AS name, email AS email
|
||||
FROM coordinators
|
||||
WHERE active = 1 AND role = 'admin'
|
||||
ORDER BY name COLLATE NOCASE, email, id`,
|
||||
)
|
||||
.all() as AdminAccount[];
|
||||
}
|
||||
|
||||
export function addAdmin(
|
||||
db: Database.Database,
|
||||
actorId: number,
|
||||
values: AdminForm,
|
||||
now: string,
|
||||
): { ok: true; id: number; status: 'added' | 'restored' } | { ok: false; errors: AdminErrors } {
|
||||
const parsed = parseAdminForm(values);
|
||||
if (!parsed.ok) return parsed;
|
||||
try {
|
||||
return db.transaction(() => {
|
||||
const existing = db
|
||||
.prepare('SELECT id AS id, active AS active FROM coordinators WHERE email = ?')
|
||||
.get(parsed.email) as { id: number; active: number } | undefined;
|
||||
if (existing?.active === 1) return { ok: false as const, errors: { email: 'That address already has access.' } };
|
||||
if (existing) {
|
||||
db.prepare(`UPDATE coordinators SET name = ?, role = 'admin', active = 1 WHERE id = ?`).run(parsed.name, existing.id);
|
||||
writeAudit(db, actorId, 'admins.restore', { coordinatorId: existing.id }, now);
|
||||
return { ok: true as const, id: existing.id, status: 'restored' as const };
|
||||
}
|
||||
const inserted = db
|
||||
.prepare(
|
||||
`INSERT INTO coordinators (email, name, role, password_hash, active, created_at)
|
||||
VALUES (?, ?, 'admin', NULL, 1, ?)`,
|
||||
)
|
||||
.run(parsed.email, parsed.name, now);
|
||||
const id = Number(inserted.lastInsertRowid);
|
||||
writeAudit(db, actorId, 'admins.add', { coordinatorId: id }, now);
|
||||
return { ok: true as const, id, status: 'added' as const };
|
||||
}).immediate();
|
||||
} catch (err) {
|
||||
if (isUniqueConstraint(err)) return { ok: false, errors: { email: 'That address already has access.' } };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function readAdminRemoval(db: Database.Database, id: number): { admin: AdminAccount; last: boolean } | null {
|
||||
const admin = activeAdmin(db, id);
|
||||
if (!admin) return null;
|
||||
return { admin: { id: admin.id, name: admin.name, email: admin.email }, last: activeAdminCount(db) <= 1 };
|
||||
}
|
||||
|
||||
export function deactivateAdmin(
|
||||
db: Database.Database,
|
||||
actorId: number,
|
||||
id: number,
|
||||
now: string,
|
||||
): { ok: true } | { ok: false; reason: 'missing' | 'last' } {
|
||||
return db.transaction(() => {
|
||||
const admin = activeAdmin(db, id);
|
||||
if (!admin) return { ok: false as const, reason: 'missing' as const };
|
||||
if (activeAdminCount(db) <= 1) return { ok: false as const, reason: 'last' as const };
|
||||
db.prepare('UPDATE coordinators SET active = 0 WHERE id = ?').run(id);
|
||||
db.prepare('DELETE FROM sessions WHERE coordinator_id = ?').run(id);
|
||||
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(now, id);
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?`,
|
||||
).run('An administrator removed this sign-in link.', admin.email);
|
||||
writeAudit(db, actorId, 'admins.remove', { coordinatorId: id }, now);
|
||||
return { ok: true as const };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
function activeAdmin(db: Database.Database, id: number): AdminRow | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id AS id, name AS name, email AS email, active AS active
|
||||
FROM coordinators
|
||||
WHERE id = ? AND active = 1 AND role = 'admin'`,
|
||||
)
|
||||
.get(id) as AdminRow | undefined;
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
function activeAdminCount(db: Database.Database): number {
|
||||
const row = db.prepare(`SELECT COUNT(*) AS n FROM coordinators WHERE active = 1 AND role = 'admin'`).get() as { n: number };
|
||||
return row.n;
|
||||
}
|
||||
|
||||
function parseAdminForm(values: AdminForm): { ok: true; name: string; email: string } | { ok: false; errors: AdminErrors } {
|
||||
const errors: AdminErrors = {};
|
||||
const nameRaw = values.name.normalize('NFC').trim();
|
||||
if (!nameRaw) errors.name = 'Enter a name.';
|
||||
else if (CONTROL.test(values.name)) errors.name = 'Enter a name without line breaks.';
|
||||
else if (nameRaw.length > MAX_NAME) errors.name = `Use ${MAX_NAME} characters or fewer.`;
|
||||
|
||||
let email = '';
|
||||
try {
|
||||
email = normalizeEmail(values.email);
|
||||
if (email.length > MAX_EMAIL || CONTROL.test(values.email)) errors.email = 'Enter an email address.';
|
||||
} catch (err) {
|
||||
if (!(err instanceof EmailAddressError)) throw err;
|
||||
errors.email = 'Enter an email address.';
|
||||
}
|
||||
if (errors.name || errors.email) return { ok: false, errors };
|
||||
return { ok: true, name: nameRaw, email };
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { bootstrapAdmin } from '../src/auth/bootstrap.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import { openAppDatabase } from '../src/db.js';
|
||||
import { devEnv } from './env.js';
|
||||
|
||||
const NOW = '2026-10-14T18:00:00.000Z';
|
||||
const ORIGIN = 'http://127.0.0.1:3000';
|
||||
const dirs: string[] = [];
|
||||
const databases: { close: () => void }[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const database of databases.splice(0)) database.close();
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('administrators', () => {
|
||||
it('asks a signed-out visitor to sign in', async () => {
|
||||
const { app } = await buildApp();
|
||||
const page = await app.request('/admin/admins');
|
||||
expect(page.status).toBe(303);
|
||||
expect(page.headers.get('location')).toBe('/login');
|
||||
const posted = await app.request('/admin/admins', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ name: 'Ada Lovelace', email: 'ada@example.invalid' }),
|
||||
});
|
||||
expect(posted.status).toBe(303);
|
||||
expect(posted.headers.get('location')).toBe('/login');
|
||||
});
|
||||
|
||||
it('lists the first administrator and adds another who can sign in', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db, 'coordinator@example.invalid');
|
||||
const home = await app.request('/admin', { headers: { cookie } });
|
||||
expect(await home.text()).toContain('href="/admin/admins"');
|
||||
|
||||
const first = await app.request('/admin/admins', { headers: { cookie } });
|
||||
const firstHtml = await first.text();
|
||||
expect(first.status).toBe(200);
|
||||
expect(firstHtml).toContain('Administrator');
|
||||
expect(firstHtml).toContain('coordinator@example.invalid');
|
||||
expect(firstHtml).toContain('>You</span>');
|
||||
expect(firstHtml).toContain('This is the only administrator.');
|
||||
expect(firstHtml).not.toContain('Remove this administrator');
|
||||
|
||||
const rejected = await postAdmin(app, cookie, { name: '', email: 'not-an-email' });
|
||||
expect(rejected.status).toBe(400);
|
||||
const rejectedHtml = await rejected.text();
|
||||
expect(rejectedHtml).toContain('Enter a name.');
|
||||
expect(rejectedHtml).toContain('Enter an email address.');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM coordinators`)).toBe(1);
|
||||
|
||||
const broken = await postAdmin(app, cookie, { name: 'Ada\nLovelace', email: 'ada@example.invalid' });
|
||||
expect(broken.status).toBe(400);
|
||||
expect(await broken.text()).toContain('Enter a name without line breaks.');
|
||||
|
||||
const stale = await app.request('/admin/admins', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf: 'wrong', name: 'Ada Lovelace', email: 'ada@example.invalid' }),
|
||||
});
|
||||
expect(stale.status).toBe(403);
|
||||
|
||||
const saved = await postAdmin(app, cookie, { name: 'Ada <script> "Lovelace"', email: 'Ada@Example.invalid' });
|
||||
expect(saved.status).toBe(303);
|
||||
expect(saved.headers.get('location')).toBe('/admin/admins?notice=admin-added');
|
||||
const page = await app.request('/admin/admins?notice=admin-added', { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(html).toContain('That person can sign in.');
|
||||
expect(html).toContain('Ada <script>');
|
||||
expect(html).not.toContain('Ada <script>');
|
||||
expect(html).toContain('ada@example.invalid');
|
||||
expect(html).toContain('Remove this administrator');
|
||||
expect(html).toContain('Remove your access');
|
||||
expect(html.indexOf('ada@example.invalid')).toBeLessThan(html.indexOf('coordinator@example.invalid'));
|
||||
|
||||
const duplicate = await postAdmin(app, cookie, { name: 'Another Ada', email: 'ADA@example.invalid' });
|
||||
expect(duplicate.status).toBe(400);
|
||||
expect(await duplicate.text()).toContain('That address already has access.');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM coordinators`)).toBe(2);
|
||||
expect(db.prepare(`SELECT name, role, active, password_hash FROM coordinators WHERE email = 'ada@example.invalid'`).get()).toEqual({
|
||||
name: 'Ada <script> "Lovelace"',
|
||||
role: 'admin',
|
||||
active: 1,
|
||||
password_hash: null,
|
||||
});
|
||||
|
||||
const ada = await signIn(app, db, 'ada@example.invalid');
|
||||
const adaHome = await app.request('/admin', { headers: { cookie: ada } });
|
||||
expect(await adaHome.text()).toContain('Signed in as <strong>Ada <script> "Lovelace"</strong>');
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
});
|
||||
|
||||
it('removes access, keeps the last administrator, and can give the same address access again', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db, 'coordinator@example.invalid');
|
||||
const blocked = await app.request('/admin/admins/1/remove', { headers: { cookie } });
|
||||
expect(blocked.status).toBe(200);
|
||||
expect(await blocked.text()).toContain('Add another administrator before removing this one.');
|
||||
const stillThere = await postRemove(app, cookie, 1);
|
||||
expect(stillThere.status).toBe(400);
|
||||
expect(await stillThere.text()).toContain('Add another administrator before removing this one.');
|
||||
expect(db.prepare('SELECT active FROM coordinators WHERE id = 1').get()).toEqual({ active: 1 });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(1);
|
||||
|
||||
await postAdmin(app, cookie, { name: 'Ada Lovelace', email: 'ada@example.invalid' });
|
||||
await postLogin(app, 'ada@example.invalid');
|
||||
const token = magicToken(db, 'ada@example.invalid');
|
||||
const adaId = (db.prepare(`SELECT id AS id FROM coordinators WHERE email = 'ada@example.invalid'`).get() as { id: number }).id;
|
||||
const removed = await postRemove(app, cookie, adaId);
|
||||
expect(removed.status).toBe(303);
|
||||
expect(removed.headers.get('location')).toBe('/admin/admins?notice=admin-removed');
|
||||
const after = await app.request('/admin/admins?notice=admin-removed', { headers: { cookie } });
|
||||
const afterHtml = await after.text();
|
||||
expect(afterHtml).toContain('That person can no longer sign in.');
|
||||
expect(afterHtml).not.toContain('ada@example.invalid');
|
||||
expect((await app.request(`/login/link/${token}`)).status).toBe(404);
|
||||
expect(db.prepare(`SELECT status FROM outbox WHERE to_email = 'ada@example.invalid'`).get()).toEqual({ status: 'cancelled' });
|
||||
await postLogin(app, 'ada@example.invalid');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'ada@example.invalid' AND status = 'pending'`)).toBe(0);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(1);
|
||||
|
||||
const missing = await app.request('/admin/admins/99/remove', { headers: { cookie } });
|
||||
expect(missing.status).toBe(404);
|
||||
|
||||
const restored = await postAdmin(app, cookie, { name: 'Ada Restored', email: 'ada@example.invalid' });
|
||||
expect(restored.status).toBe(303);
|
||||
expect(restored.headers.get('location')).toBe('/admin/admins?notice=admin-restored');
|
||||
const again = await app.request('/admin/admins?notice=admin-restored', { headers: { cookie } });
|
||||
const againHtml = await again.text();
|
||||
expect(againHtml).toContain('That person can sign in again.');
|
||||
expect(againHtml).toContain('Ada Restored');
|
||||
expect(againHtml).toContain('ada@example.invalid');
|
||||
const ada = await signIn(app, db, 'ada@example.invalid');
|
||||
expect(await (await app.request('/admin', { headers: { cookie: ada } })).text()).toContain('Signed in as <strong>Ada Restored</strong>');
|
||||
expect(auditJson(db)).not.toContain('@');
|
||||
});
|
||||
|
||||
it('signs you out when you remove your own access and leaves the other administrator signed in', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const keeper = await signIn(app, db, 'coordinator@example.invalid');
|
||||
await postAdmin(app, keeper, { name: 'Bea Example', email: 'bea@example.invalid' });
|
||||
const bea = await signIn(app, db, 'bea@example.invalid');
|
||||
const beaId = (db.prepare(`SELECT id AS id FROM coordinators WHERE email = 'bea@example.invalid'`).get() as { id: number }).id;
|
||||
const removed = await postRemove(app, bea, beaId);
|
||||
expect(removed.status).toBe(303);
|
||||
expect(removed.headers.get('location')).toBe('/login');
|
||||
expect(removed.headers.get('set-cookie')).toContain('Max-Age=0');
|
||||
expect((await app.request('/admin', { headers: { cookie: bea } })).status).toBe(303);
|
||||
expect((await app.request('/admin', { headers: { cookie: keeper } })).status).toBe(200);
|
||||
const home = await app.request('/admin', { headers: { cookie: keeper } });
|
||||
expect(await home.text()).toContain('Signed in as <strong>Administrator</strong>');
|
||||
expect(db.prepare(`SELECT active FROM coordinators WHERE email = 'bea@example.invalid'`).get()).toEqual({ active: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
async function buildApp() {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'hope-admins-'));
|
||||
dirs.push(root);
|
||||
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
|
||||
const db = await openAppDatabase(config);
|
||||
databases.push(db);
|
||||
bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
|
||||
const app = createApp(config, db, {
|
||||
now: NOW,
|
||||
clientIp: () => '203.0.113.10',
|
||||
verifyTurnstile: async () => ({ ok: true }),
|
||||
});
|
||||
return { app, db };
|
||||
}
|
||||
|
||||
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof buildApp>>['db'], email: string) {
|
||||
await postLogin(app, email);
|
||||
const token = magicToken(db, email);
|
||||
const page = await app.request(`/login/link/${token}`);
|
||||
const signedIn = await postLink(app, token, field(await page.text(), 'proof'));
|
||||
return cookieHeader(signedIn);
|
||||
}
|
||||
|
||||
function postLogin(app: Awaited<ReturnType<typeof buildApp>>['app'], email: string) {
|
||||
return app.request('/login', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ email, company_website: '', 'cf-turnstile-response': 'token' }),
|
||||
});
|
||||
}
|
||||
|
||||
function postLink(app: Awaited<ReturnType<typeof buildApp>>['app'], token: string, proof: string) {
|
||||
return app.request(`/login/link/${token}`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ proof }),
|
||||
});
|
||||
}
|
||||
|
||||
async function postAdmin(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
fields: { name: string; email: string },
|
||||
) {
|
||||
const current = await app.request('/admin/admins', { headers: { cookie } });
|
||||
const csrf = field(await current.text(), 'csrf');
|
||||
return app.request('/admin/admins', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf, ...fields }),
|
||||
});
|
||||
}
|
||||
|
||||
async function postRemove(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, id: number) {
|
||||
const current = await app.request('/admin/admins', { headers: { cookie } });
|
||||
const csrf = field(await current.text(), 'csrf');
|
||||
return app.request(`/admin/admins/${id}/remove`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf }),
|
||||
});
|
||||
}
|
||||
|
||||
function magicToken(db: Awaited<ReturnType<typeof buildApp>>['db'], email: string): string {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT body_text AS body_text
|
||||
FROM outbox
|
||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?
|
||||
ORDER BY id DESC
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(email) as { body_text: string } | undefined;
|
||||
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(row?.body_text ?? '')?.[1];
|
||||
if (!token) throw new Error('The sign-in link was not queued.');
|
||||
return token;
|
||||
}
|
||||
|
||||
function cookieHeader(response: Response): string {
|
||||
const match = /hope_session=([^;]+)/.exec(response.headers.get('set-cookie') ?? '');
|
||||
if (!match?.[1]) throw new Error('The session cookie was not set.');
|
||||
return `hope_session=${match[1]}`;
|
||||
}
|
||||
|
||||
function field(html: string, name: string): string {
|
||||
const tag = new RegExp(`<input\\b[^>]*\\bname="${name}"[^>]*>`).exec(html)?.[0] ?? '';
|
||||
return /value="([^"]*)"/.exec(tag)?.[1] ?? '';
|
||||
}
|
||||
|
||||
function count(db: Awaited<ReturnType<typeof buildApp>>['db'], sql: string): number {
|
||||
return Number((db.prepare(sql).get() as { n: number }).n);
|
||||
}
|
||||
|
||||
function auditJson(db: Awaited<ReturnType<typeof buildApp>>['db']): string {
|
||||
return (db.prepare('SELECT detail_json AS detail_json FROM audit').all() as Array<{ detail_json: string }>)
|
||||
.map((row) => row.detail_json)
|
||||
.join('\n');
|
||||
}
|
||||
Reference in new issue
Block a user