Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let an install have more than one administrator
Claudec9818778e3cb
diff --git a/src/app/api/admin/people/[id]/route.ts b/src/app/api/admin/people/[id]/route.tsnew file mode 100644index 0000000..4e25340--- /dev/null+++ b/src/app/api/admin/people/[id]/route.ts@@ -0,0 +1,99 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "@/lib/auth/admin";+import {+ listPeople,+ parsePersonRole,+ PeopleError,+ setPersonRole,+} from "@/lib/people";+import { logRouteError, logSecurityEvent } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";++type PersonRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++const noStore = { "cache-control": "private, no-store" };++// Makes an account an administrator or an ordinary account again.+// Administrators only. Answers with the whole list as it now stands.+export async function PATCH(request: Request, context: PersonRouteContext) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ const { id } = await context.params;+ const ipAddress = getClientIpAddress(request.headers);+ const rateLimitResponse = await applyRateLimit({+ category: "people_role_change",+ key: buildRateLimitKey(["people-role", session.user.id]),+ limit: 30,+ request,+ userId: session.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const body = (await request.json().catch(() => null)) as {+ role?: unknown;+ } | null;+ const role = parsePersonRole(body?.role);++ if (!role) {+ return NextResponse.json(+ { error: "Choose administrator or member." },+ { headers: noStore, status: 400 },+ );+ }++ try {+ const person = await setPersonRole(id, role);++ logSecurityEvent("info", {+ category: "people_role_changed",+ ipAddress,+ message: "An administrator changed an account's role.",+ metadata: { role, targetUserId: person.id },+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { people: await listPeople(), you: session.user.id },+ { headers: noStore },+ );+ } catch (error) {+ if (error instanceof PeopleError) {+ return NextResponse.json(+ { error: error.message },+ { headers: noStore, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "people_role_change_failure",+ ipAddress,+ message: "Unexpected failure while changing an account's role.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "That change could not be saved." },+ { headers: noStore, status: 500 },+ );+ }+}diff --git a/src/app/api/admin/people/route.ts b/src/app/api/admin/people/route.tsnew file mode 100644index 0000000..32f2fb5--- /dev/null+++ b/src/app/api/admin/people/route.ts@@ -0,0 +1,37 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "@/lib/auth/admin";+import { listPeople } from "@/lib/people";+import { logRouteError } from "@/lib/security/logging";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";++// The accounts on this install, for the People list in Settings.+// Administrators only.++export async function GET(request: Request) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ try {+ return NextResponse.json(+ { people: await listPeople(), you: sessionResult.user.id },+ { headers: { "cache-control": "private, no-store" } },+ );+ } catch (error) {+ logRouteError(error, {+ category: "people_list_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while listing accounts.",+ path: getRequestPathname(request),+ userId: sessionResult.user.id,+ });++ return NextResponse.json(+ { error: "The list of people could not be loaded." },+ { status: 500 },+ );+ }+}diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex aabf7ac..12195d5 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -3,6 +3,7 @@import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";import { FieldShell, ShellButton } from "@/components/shared/form-shell";+import { PeoplePanel } from "@/components/settings/people-panel";import { SignerDataPanel } from "@/components/settings/signer-data-panel";import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";import type {@@ -361,6 +362,10 @@ export function OrganizationSettings({<EmailSetupPanel key={emailRevision} />+ {/* The hosted service's accounts are strangers to each other, not+ one organization, so it has no list of them here. */}+ {!values.hosted ? <PeoplePanel /> : null}+<SignerDataPanel /></div></section>diff --git a/src/components/settings/people-panel.tsx b/src/components/settings/people-panel.tsxnew file mode 100644index 0000000..38203d0--- /dev/null+++ b/src/components/settings/people-panel.tsx@@ -0,0 +1,234 @@+"use client";++import { useEffect, useState } from "react";++import type { Person, PersonRole } from "@/lib/people";++// Who has an account on this install, and which of them are administrators.+// Administrators only.++const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";++type PeopleResponse = {+ error?: string;+ people?: Person[];+ you?: string;+} | null;++export function PeoplePanel() {+ const [people, setPeople] = useState<Person[] | null>(null);+ const [you, setYou] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [pendingId, setPendingId] = useState<string | null>(null);+ const [filter, setFilter] = useState("");++ useEffect(() => {+ const controller = new AbortController();++ fetch("/api/admin/people", { signal: controller.signal })+ .then(async (response) => {+ const payload = (await response+ .json()+ .catch(() => null)) as PeopleResponse;++ if (!response.ok || !payload?.people) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ setPeople(payload.people);+ setYou(payload.you ?? null);+ })+ .catch((loadError: unknown) => {+ // Leaving the page cancels the request; that is not a failure.+ if (!(+ loadError instanceof DOMException && loadError.name === "AbortError"+ )) {+ setError(GENERIC_ERROR_MESSAGE);+ }+ });++ return () => controller.abort();+ }, []);++ async function changeRole(person: Person, role: PersonRole) {+ if (pendingId) {+ return;+ }++ setPendingId(person.id);+ setError(null);++ try {+ const response = await fetch(+ `/api/admin/people/${encodeURIComponent(person.id)}`,+ {+ body: JSON.stringify({ role }),+ headers: { "content-type": "application/json" },+ method: "PATCH",+ },+ );+ const payload = (await response+ .json()+ .catch(() => null)) as PeopleResponse;++ if (!response.ok || !payload?.people) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ // Having given up the role, this page is no longer theirs to see.+ if (person.id === you && role === "user") {+ window.location.reload();+ return;+ }++ setPeople(payload.people);+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ } finally {+ setPendingId(null);+ }+ }++ const needle = filter.trim().toLowerCase();+ const shown = (people ?? []).filter(+ (person) =>+ needle.length === 0 ||+ person.name.toLowerCase().includes(needle) ||+ person.email.toLowerCase().includes(needle),+ );+ const administratorCount = (people ?? []).filter(+ (person) => person.role === "admin",+ ).length;++ return (+ <div className="space-y-5 border-t border-(--border) pt-8">+ <div className="space-y-2">+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">+ People+ </h3>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ Everyone with an account here. Administrators can change these+ settings, answer signer data requests and receive the finished+ documents of accounts that are closed. Keep at least two, so that one+ person leaving does not lock everyone out.+ </p>+ </div>++ {error ? (+ <div className="notice notice-danger" role="alert">+ {error}+ </div>+ ) : null}++ {people === null && !error ? (+ <p className="text-sm text-(--secondary)">Loading people...</p>+ ) : null}++ {people && people.length > 8 ? (+ <label className="grid max-w-sm gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Find a person+ </span>+ <input+ className="field-input"+ onChange={(event) => setFilter(event.target.value)}+ placeholder="Name or email"+ type="search"+ value={filter}+ />+ </label>+ ) : null}++ {people ? (+ <ul aria-label="People" className="space-y-3">+ {shown.map((person) => {+ const isAdmin = person.role === "admin";+ const isYou = person.id === you;+ const isLastAdmin = isAdmin && administratorCount === 1;++ return (+ <li+ className="well flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between"+ key={person.id}+ >+ <div className="min-w-0 space-y-1.5">+ <p className="truncate text-[0.9375rem] font-bold text-(--fg)">+ {person.name}+ </p>+ <p className="truncate text-sm text-(--secondary)">+ {person.email}+ </p>+ <div className="flex flex-wrap gap-1.5">+ <span+ className={`pill ${isAdmin ? "pill-accent" : "pill-neutral"}`}+ >+ {isAdmin ? "Administrator" : "Member"}+ </span>+ {isYou ? (+ <span className="pill pill-neutral">You</span>+ ) : null}+ {!person.emailVerified ? (+ <span className="pill pill-warning">+ Email not confirmed+ </span>+ ) : null}+ {person.closing ? (+ <span className="pill pill-warning">Closing</span>+ ) : null}+ </div>+ </div>++ {isAdmin ? (+ <button+ aria-label={`Remove ${person.name} as administrator`}+ className="btn-quiet btn-quiet-danger shrink-0"+ disabled={pendingId !== null || isLastAdmin}+ onClick={() => void changeRole(person, "user")}+ title={+ isLastAdmin+ ? "There has to be at least one administrator."+ : undefined+ }+ type="button"+ >+ {pendingId === person.id+ ? "Saving..."+ : "Remove as administrator"}+ </button>+ ) : (+ <button+ aria-label={`Make ${person.name} an administrator`}+ className="btn-quiet shrink-0"+ disabled={+ pendingId !== null ||+ !person.emailVerified ||+ person.closing+ }+ onClick={() => void changeRole(person, "admin")}+ type="button"+ >+ {pendingId === person.id+ ? "Saving..."+ : "Make administrator"}+ </button>+ )}+ </li>+ );+ })}+ </ul>+ ) : null}++ {people && shown.length === 0 ? (+ <p className="text-sm text-(--secondary)">Nobody matches that.</p>+ ) : null}++ {people && people.length >= 500 ? (+ <p className="text-sm text-(--secondary)">+ Showing the first 500 accounts.+ </p>+ ) : null}+ </div>+ );+}diff --git a/src/lib/people.dbtest.ts b/src/lib/people.dbtest.tsnew file mode 100644index 0000000..9ccbb7c--- /dev/null+++ b/src/lib/people.dbtest.ts@@ -0,0 +1,186 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import { listPeople, PeopleError, setPersonRole } from "./people.ts";++// Administrator roles against a real Postgres: there is always at least+// one, even when two removals arrive at once. Run with `npm run test:db`.++let database: pg.Pool;+const createdUsers: string[] = [];+let administratorsBefore: string[] = [];++before(async () => {+ database = await openTestDatabase();++ // The rule under test is about every administrator in the database, so+ // the ones other tests left behind step aside while this file runs.+ const existing = await database.query<{ id: string }>(+ `update public."user" set role = 'user' where role = 'admin' returning id`,+ );++ administratorsBefore = existing.rows.map((row) => row.id);+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.query(+ `update public."user" set role = 'admin' where id = any($1)`,+ [administratorsBefore],+ );+ await database.end();+});++async function createUser({+ role = "user",+ verified = true,+}: { role?: "admin" | "user"; verified?: boolean } = {}) {+ const id = randomUUID();++ createdUsers.push(id);+ await database.query(+ `+ insert into public."user" (id, name, email, role, "emailVerified")+ values ($1, $2, $3, $4, $5)+ `,+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`, role, verified],+ );++ return id;+}++async function roleOf(userId: string) {+ const result = await database.query<{ role: string }>(+ `select role from public."user" where id = $1`,+ [userId],+ );++ return result.rows[0]?.role ?? null;+}++async function resetRoles() {+ await database.query(+ `update public."user" set role = 'user' where id = any($1)`,+ [createdUsers],+ );+}++function refusedWith(statusCode: number, pattern: RegExp) {+ return (error: unknown) => {+ assert.ok(error instanceof PeopleError);+ assert.equal(error.statusCode, statusCode);+ assert.match(error.message, pattern);+ return true;+ };+}++test("an administrator can be added and removed, but never the last one", async () => {+ await resetRoles();++ const first = await createUser({ role: "admin" });+ const second = await createUser();++ await assert.rejects(+ setPersonRole(first, "user", database),+ refusedWith(409, /at least one administrator/),+ );+ assert.equal(await roleOf(first), "admin");++ assert.equal((await setPersonRole(second, "admin", database)).role, "admin");+ assert.equal((await setPersonRole(first, "user", database)).role, "user");+ assert.equal(await roleOf(first), "user");+ assert.equal(await roleOf(second), "admin");++ // Asking for the role an account already has changes nothing.+ assert.equal((await setPersonRole(second, "admin", database)).role, "admin");++ const listed = await listPeople(database);+ const mine = listed.filter((person) => createdUsers.includes(person.id));++ // Administrators come first.+ assert.equal(mine[0]?.id, second);+ assert.equal(mine[0]?.role, "admin");+});++test("two administrators removing each other at once leaves one", async () => {+ await resetRoles();++ const left = await createUser({ role: "admin" });+ const right = await createUser({ role: "admin" });+ const results = await Promise.allSettled([+ setPersonRole(left, "user", database),+ setPersonRole(right, "user", database),+ ]);++ assert.deepEqual(results.map((result) => result.status).sort(), [+ "fulfilled",+ "rejected",+ ]);+ assert.deepEqual([await roleOf(left), await roleOf(right)].sort(), [+ "admin",+ "user",+ ]);+});++test("an administrator whose account is closing does not count as the one that stays", async () => {+ await resetRoles();++ const staying = await createUser({ role: "admin" });+ const leaving = await createUser({ role: "admin" });++ await database.query(+ `+ insert into account_closure_requests+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)+ values ($1, 1, 2, 3, 1)+ `,+ [leaving],+ );++ await assert.rejects(+ setPersonRole(staying, "user", database),+ refusedWith(409, /at least one administrator/),+ );++ const person = (await listPeople(database)).find(+ (entry) => entry.id === leaving,+ );++ assert.equal(person?.closing, true);+});++test("only a confirmed account that is staying can become an administrator", async () => {+ await resetRoles();+ await createUser({ role: "admin" });++ const unverified = await createUser({ verified: false });+ const closing = await createUser();++ await database.query(+ `+ insert into account_closure_requests+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)+ values ($1, 1, 2, 3, 1)+ `,+ [closing],+ );++ await assert.rejects(+ setPersonRole(unverified, "admin", database),+ refusedWith(409, /not confirmed their email/),+ );+ await assert.rejects(+ setPersonRole(closing, "admin", database),+ refusedWith(409, /being closed/),+ );+ await assert.rejects(+ setPersonRole(randomUUID(), "admin", database),+ refusedWith(404, /no longer exists/),+ );+});diff --git a/src/lib/people.ts b/src/lib/people.tsnew file mode 100644index 0000000..4acf38d--- /dev/null+++ b/src/lib/people.ts@@ -0,0 +1,169 @@+import {+ type DbExecutor,+ type DbPool,+ getDb,+ queryMany,+ queryOne,+ withTransaction,+} from "./db/connection.ts";++// The accounts on this install and who among them is an administrator.+//+// An administrator can make another account an administrator or take that+// role away, their own included. There is always at least one: the last+// administrator cannot be removed, and neither can the last one whose+// account is not on its way to being closed.++/** Serializes role changes, so two removals cannot both leave "one more". */+const ROLE_CHANGE_LOCK_ID = 746108324;+const MAX_LISTED_PEOPLE = 500;++export type PersonRole = "admin" | "user";++export type Person = {+ /** The account has asked to be closed and is waiting out its notice. */+ closing: boolean;+ createdAt: string;+ email: string;+ emailVerified: boolean;+ id: string;+ name: string;+ role: PersonRole;+};++export class PeopleError extends Error {+ readonly statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.name = "PeopleError";+ this.statusCode = statusCode;+ }+}++type PersonRow = {+ closing: boolean;+ createdAt: Date;+ email: string;+ emailVerified: boolean;+ id: string;+ name: string;+ role: string;+};++const PERSON_COLUMNS = `+ u.id,+ u.name,+ u.email,+ u.role,+ u."emailVerified" AS "emailVerified",+ u."createdAt" AS "createdAt",+ EXISTS (+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id+ ) AS closing+`;++function mapPerson(row: PersonRow): Person {+ return {+ closing: row.closing,+ createdAt: row.createdAt.toISOString(),+ email: row.email,+ emailVerified: row.emailVerified,+ id: row.id,+ name: row.name,+ role: row.role === "admin" ? "admin" : "user",+ };+}++/** Every account, administrators first, then by name. */+export async function listPeople(+ database: DbExecutor = getDb(),+): Promise<Person[]> {+ const rows = await queryMany<PersonRow>(+ database,+ `+ SELECT ${PERSON_COLUMNS}+ FROM "user" u+ ORDER BY (u.role = 'admin') DESC, lower(u.name) ASC, u.id ASC+ LIMIT ${MAX_LISTED_PEOPLE}+ `,+ );++ return rows.map(mapPerson);+}++export function parsePersonRole(value: unknown): PersonRole | null {+ return value === "admin" || value === "user" ? value : null;+}++/**+ * Makes an account an administrator, or an ordinary account again.+ * Returns the account as it now is.+ */+export async function setPersonRole(+ targetUserId: string,+ role: PersonRole,+ database: DbPool = getDb(),+): Promise<Person> {+ return withTransaction(async (tx) => {+ await tx.query("SELECT pg_advisory_xact_lock($1)", [ROLE_CHANGE_LOCK_ID]);++ const target = await queryOne<PersonRow>(+ tx,+ `SELECT ${PERSON_COLUMNS} FROM "user" u WHERE u.id = $1 FOR UPDATE OF u`,+ [targetUserId],+ );++ if (!target) {+ throw new PeopleError("That account no longer exists.", 404);+ }++ if (target.role === role) {+ return mapPerson(target);+ }++ if (role === "admin") {+ if (!target.emailVerified) {+ throw new PeopleError(+ "This person has not confirmed their email address yet. They can be made an administrator once they have.",+ 409,+ );+ }++ if (target.closing) {+ throw new PeopleError(+ "This account is being closed, so it cannot become an administrator.",+ 409,+ );+ }+ } else {+ const others = await queryOne<{ count: number }>(+ tx,+ `+ SELECT count(*)::int AS count+ FROM "user" u+ WHERE u.role = 'admin'+ AND u.id <> $1+ AND NOT EXISTS (+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id+ )+ `,+ [targetUserId],+ );++ if ((others?.count ?? 0) === 0) {+ throw new PeopleError(+ "There has to be at least one administrator. Make someone else an administrator first.",+ 409,+ );+ }+ }++ await tx.query(+ `UPDATE "user" SET role = $1, "updatedAt" = now() WHERE id = $2`,+ [role, targetUserId],+ );++ return mapPerson({ ...target, role });+ }, database);+}