Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Refuse to close the last administrator's account
Matthew Jackson8be8bcfae776
diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsxindex 71e4025..4235966 100644--- a/src/app/(app)/settings/page.tsx+++ b/src/app/(app)/settings/page.tsx@@ -2,6 +2,7 @@ import { OrganizationSettings } from "@/components/settings/organization-settingimport { SettingsShell } from "@/components/settings/settings-shell";import { UpdatesPanel } from "@/components/settings/updates-panel";import { isAdminUser } from "@/lib/auth/admin";+import { accountClosureBlock } from "@/lib/account";import { getAuthSession } from "@/lib/auth/server";import { toOrganizationSettingsView } from "@/lib/organization-settings";import {@@ -16,10 +17,14 @@ export default async function SettingsPage() {const session = await getAuthSession();const isAdmin = session ? await isAdminUser(session.user.id) : false;const settings = await getSettings();+ const closureBlockedReason = session+ ? await accountClosureBlock(session.user).catch(() => null)+ : null;return (<div className="space-y-8"><SettingsShell+ closureBlockedReason={closureBlockedReason}initialProfile={{email: session?.user.email ?? "",fullName: session?.user.name ?? "",diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsxindex 26b158f..ffdb66f 100644--- a/src/components/settings/settings-shell.tsx+++ b/src/components/settings/settings-shell.tsx@@ -21,6 +21,8 @@ const CLOSURE_CONFIRMATION_PHRASE = "close my account";const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";type SettingsShellProps = {+ /** Why this account cannot be closed; shown in place of the button. */+ closureBlockedReason?: string | null;initialProfile?: ProfileValues;twoFactor?: { enabled: boolean; required: boolean };};@@ -162,6 +164,7 @@ function isNoOpEmailChangeMessage(message: string) {}export function SettingsShell({+ closureBlockedReason = null,initialProfile = defaultProfileValues,twoFactor = { enabled: false, required: false },}: SettingsShellProps) {@@ -673,14 +676,20 @@ export function SettingsShell({<p className="max-w-2xl text-sm leading-6 text-(--secondary)">{closureCopy}</p>- <ShellButton- className="w-fit border-[rgba(180,35,24,0.35)] text-(--danger) hover:border-(--danger) hover:bg-(--danger-soft) hover:text-(--danger)"- disabled={isBusy}- onClick={openClosureDialog}- variant="secondary"- >- Request account closure- </ShellButton>+ {closureBlockedReason ? (+ <p className="notice notice-warning max-w-2xl" role="status">+ {closureBlockedReason}+ </p>+ ) : (+ <ShellButton+ className="w-fit border-[rgba(180,35,24,0.35)] text-(--danger) hover:border-(--danger) hover:bg-(--danger-soft) hover:text-(--danger)"+ disabled={isBusy}+ onClick={openClosureDialog}+ variant="secondary"+ >+ Request account closure+ </ShellButton>+ )}</div></div></div>diff --git a/src/lib/account-closure.dbtest.ts b/src/lib/account-closure.dbtest.tsnew file mode 100644index 0000000..1c51b80--- /dev/null+++ b/src/lib/account-closure.dbtest.ts@@ -0,0 +1,175 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { after, before, test } from "node:test";++import type pg from "pg";++import {+ AccountMutationError,+ LAST_ADMIN_CLOSURE_MESSAGE,+ accountClosureBlock,+ requestAccountClosure,+} from "./account.ts";+import { openTestDatabase } from "./db/test-database.ts";++// Closing an account from Settings is refused for the last administrator,+// even when two administrators close at once. Run with `npm run test:db`.++const env = { BETTER_AUTH_SECRET: "a".repeat(40), EMAIL_DRIVER: "capture" };+const confirmation = { confirmation: "close my account" };++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 account_closure_requests where user_id = any($1)`,+ [createdUsers],+ );+ 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: "admin" | "user" = "admin") {+ const id = randomUUID();++ createdUsers.push(id);+ await database.query(+ `+ insert into public."user" (id, name, email, role, "emailVerified")+ values ($1, $2, $3, $4, true)+ `,+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`, role],+ );++ return { id };+}++async function resetRoles() {+ await database.query(+ `delete from account_closure_requests where user_id = any($1)`,+ [createdUsers],+ );+ await database.query(+ `update public."user" set role = 'user' where id = any($1)`,+ [createdUsers],+ );+}++async function isQueued(userId: string) {+ const result = await database.query(+ `select 1 from account_closure_requests where user_id = $1`,+ [userId],+ );++ return result.rowCount === 1;+}++function refusedWith(message: string) {+ return (error: unknown) =>+ error instanceof AccountMutationError &&+ error.statusCode === 409 &&+ error.message === message;+}++test("the last administrator cannot close their account", async () => {+ await resetRoles();++ const admin = await createUser();++ assert.equal(+ await accountClosureBlock(admin, database, env),+ LAST_ADMIN_CLOSURE_MESSAGE,+ );+ await assert.rejects(+ requestAccountClosure(admin.id, confirmation, { database, env }),+ refusedWith(LAST_ADMIN_CLOSURE_MESSAGE),+ );+ assert.equal(await isQueued(admin.id), false);+});++test("an administrator can close once another one stays", async () => {+ await resetRoles();++ const admin = await createUser();+ const other = await createUser();++ assert.equal(await accountClosureBlock(admin, database, env), null);++ const result = await requestAccountClosure(admin.id, confirmation, {+ database,+ env,+ });++ assert.equal(result.alreadyQueued, false);+ assert.equal(await isQueued(admin.id), true);++ // The one left is now the last.+ await assert.rejects(+ requestAccountClosure(other.id, confirmation, { database, env }),+ refusedWith(LAST_ADMIN_CLOSURE_MESSAGE),+ );+});++test("someone who is not an administrator can always close", async () => {+ await resetRoles();++ const person = await createUser("user");++ assert.equal(await accountClosureBlock(person, database, env), null);+});++test("the hosted service lets anyone close their account", async () => {+ await resetRoles();++ const admin = await createUser();++ assert.equal(+ await accountClosureBlock(admin, database, { ...env, HOSTED_MODE: "1" }),+ null,+ );+});++test("two administrators closing at once cannot both go", async () => {+ await resetRoles();++ const first = await createUser();+ const second = await createUser();+ const results = await Promise.allSettled([+ requestAccountClosure(first.id, confirmation, { database, env }),+ requestAccountClosure(second.id, confirmation, { database, env }),+ ]);+ const refused = results.filter((result) => result.status === "rejected");++ assert.equal(refused.length, 1);+ assert.ok(+ refused.every(+ (result) =>+ result.status === "rejected" &&+ refusedWith(LAST_ADMIN_CLOSURE_MESSAGE)(result.reason),+ ),+ );+ assert.equal(+ Number(await isQueued(first.id)) + Number(await isQueued(second.id)),+ 1,+ );+});diff --git a/src/lib/account.ts b/src/lib/account.tsindex ee40d6d..f70c694 100644--- a/src/lib/account.ts+++ b/src/lib/account.ts@@ -9,10 +9,13 @@ import {} from "./schemas/auth.ts";import {type DbExecutor,+ type DbPool,getDb,queryMany,queryOne,+ withTransaction,} from "./db/connection.ts";+import { ROLE_CHANGE_LOCK_ID } from "./people.ts";import {ACCOUNT_CLOSURE_EXPORT_WINDOW_DAYS,scheduleAccountClosure,@@ -21,7 +24,7 @@ import { resolvePublicSupportAddress } from "./public-contact.ts";import { createEmailService } from "./services/email.ts";import { recordSystemAuditEvent } from "./services/system-audit.ts";import { getBranding } from "./settings.ts";-import { type EnvSource } from "./utils/env.ts";+import { isHostedMode, type EnvSource } from "./utils/env.ts";type SenderAccountRow = {email: string;@@ -192,6 +195,54 @@ function buildClosureValidationError();}+export const LAST_ADMIN_CLOSURE_MESSAGE =+ "You are the only administrator. Make someone else an administrator first, then close your account.";++/**+ * Why this account may not be closed, or null when it may: the last+ * administrator would leave the install with nobody to run it.+ */+export async function accountClosureBlock(+ user: { id: string },+ database: DbExecutor = getDb(),+ env: EnvSource = process.env,+): Promise<string | null> {+ // The hosted service has no install to keep running.+ if (isHostedMode(env)) {+ return null;+ }++ const row = await queryOne<{ has_other_admin: boolean; role: string }>(+ database,+ `+ SELECT+ role,+ EXISTS (+ SELECT 1+ FROM "user" AS other+ WHERE other.role = 'admin'+ AND other.id <> $1+ AND NOT EXISTS (+ SELECT 1+ FROM account_closure_requests+ WHERE account_closure_requests.user_id = other.id+ )+ ) AS has_other_admin+ FROM "user"+ WHERE id = $1+ `,+ [user.id],+ );++ return row?.role === "admin" && !row.has_other_admin+ ? LAST_ADMIN_CLOSURE_MESSAGE+ : null;+}++function isPool(database: DbExecutor): database is DbPool {+ return "connect" in database && "totalCount" in database;+}+async function formatEnvelopeCounts(userId: string,database: DbExecutor,@@ -217,7 +268,6 @@ async function formatEnvelopeCounts();}-function formatRetentionDeadline(timestamp: number): string {return new Date(timestamp * 1000).toISOString().replace(".000Z", " UTC");}@@ -235,7 +285,22 @@ export async function requestAccountClosure(throw new AccountMutationError("Account not found.", 404);}- const closureSchedule = await scheduleAccountClosure(userId, database);+ // Under the lock role changes take, so two administrators closing their+ // accounts at once cannot both count the other as the one who stays.+ const guardAndSchedule = async (tx: DbExecutor) => {+ await tx.query("SELECT pg_advisory_xact_lock($1)", [ROLE_CHANGE_LOCK_ID]);++ const blocked = await accountClosureBlock(account, tx, env);++ if (blocked) {+ throw new AccountMutationError(blocked, 409);+ }++ return scheduleAccountClosure(userId, tx);+ };+ const closureSchedule = isPool(database)+ ? await withTransaction(guardAndSchedule, database)+ : await guardAndSchedule(database);if (!closureSchedule.alreadyQueued) {await recordSystemAuditEvent(diff --git a/src/lib/people.ts b/src/lib/people.tsindex 36d4708..2d8410a 100644--- a/src/lib/people.ts+++ b/src/lib/people.ts@@ -16,7 +16,7 @@ import { recordSystemAuditEvent } from "./services/system-audit.ts";// 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;+export const ROLE_CHANGE_LOCK_ID = 746108324;const MAX_LISTED_PEOPLE = 500;const MAX_SEARCH_LENGTH = 100;