Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Pass handed-over records on when an administrator is removed

Claude35b255924e45
diff --git a/README.md b/README.md
index 1ea65ce..7b6739a 100644
--- a/README.md
+++ b/README.md
@@ -195,6 +195,7 @@ Open [http://localhost:3000](http://localhost:3000).
The first time you open a new install it takes you to `/setup`. There you name your organization and create the first account, which becomes the administrator. After that the setup page is gone for good.
- **Who can sign up.** The install starts by letting people with an email address at the administrator's own domain create accounts (or nobody else, if the administrator used a public mailbox such as Gmail). The administrator can change this under Settings, Organization: people at listed domains, nobody, or anyone. People who are only sent a document to sign never need an account.
+- **More administrators.** Settings, Organization lists everyone with an account under People, where an administrator can make someone else an administrator or take that away. There is always at least one. When an account is closed, its finished documents and their audit trails move to the longest-standing administrator, because they are the organization's records. If that person later stops being an administrator, those documents move on to one who stays, and the documents they sent themselves stay with them.
- **Email.** Settings, Organization also shows whether email is working. While no sender address is set, mail goes out from Resend's test address, which only reaches the owner of the Resend account. Enter a sender address at your domain and the page shows the DNS records to add and checks them for you. Mail from that address is not delivered until its domain is verified.
- **`SETUP_TOKEN`.** A new install can be claimed by whoever opens it first. If its URL will be public before you get to it, set `SETUP_TOKEN` to a secret of your own and the setup page will ask for it.
- **An install from before this page existed** has accounts but no administrator. Set `SETUP_TOKEN`, sign in with the account that should be in charge, and open `/setup`. Sign-up stays open, as it was, until that administrator changes it.
diff --git a/db/migrations/20261114150000_handed_over_envelopes.sql b/db/migrations/20261114150000_handed_over_envelopes.sql
new file mode 100644
index 0000000..af9738c
--- /dev/null
+++ b/db/migrations/20261114150000_handed_over_envelopes.sql
@@ -0,0 +1,11 @@
+-- When an account is closed, its finished envelopes are handed to an
+-- administrator, because they are the organization's records and not the
+-- person's who is leaving.
+--
+-- This marks an envelope that was handed over, and when, so that it can be
+-- told apart from the envelopes its keeper sent themselves. Someone who
+-- stops being an administrator keeps their own envelopes, and the marked
+-- ones move on to an administrator who stays.
+
+alter table public.envelopes
+ add column if not exists handed_over_at bigint;
diff --git a/src/components/settings/people-panel.tsx b/src/components/settings/people-panel.tsx
index ff8edc4..0666061 100644
--- a/src/components/settings/people-panel.tsx
+++ b/src/components/settings/people-panel.tsx
@@ -157,8 +157,10 @@ export function PeoplePanel() {
<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.
+ documents of accounts that are closed. When someone stops being an
+ administrator, the documents they received that way move to an
+ administrator who stays. Keep at least two, so that one person leaving
+ does not lock everyone out.
</p>
</div>
diff --git a/src/lib/people.dbtest.ts b/src/lib/people.dbtest.ts
index 4ce56ce..cf19790 100644
--- a/src/lib/people.dbtest.ts
+++ b/src/lib/people.dbtest.ts
@@ -79,6 +79,60 @@ async function resetRoles() {
);
}
+function storage() {
+ return createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
+ });
+}
+
+/** A completed envelope sent by this account. */
+async function createFinishedEnvelope(userId: string) {
+ const id = randomUUID();
+
+ await database.query(
+ `
+ insert into envelopes (
+ id, user_id, title, status, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, source_pdf_hash, completed_at
+ ) values ($1, $2, 'Lease', 'completed', $3, 'lease.pdf', 10, 1, $4, 1)
+ `,
+ [id, userId, `test/${id}.pdf`, "a".repeat(64)],
+ );
+
+ return id;
+}
+
+async function envelopeRow(envelopeId: string) {
+ const result = await database.query<{
+ handed_over_at: number | null;
+ user_id: string;
+ }>(`select user_id, handed_over_at from envelopes where id = $1`, [
+ envelopeId,
+ ]);
+
+ return result.rows[0]!;
+}
+
+/** Asks for the account to be closed, with its notice already over. */
+async function closeAccount(userId: string) {
+ await database.query(
+ `
+ insert into account_closure_requests
+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)
+ values ($1, 1, 1, 1, 1)
+ `,
+ [userId],
+ );
+}
+
+/** Makes this account the one that has been here longest. */
+async function makeLongestStanding(userId: string) {
+ await database.query(
+ `update public."user" set "createdAt" = now() - interval '1 day' where id = $1`,
+ [userId],
+ );
+}
+
/** Waits until this many sessions are held up behind a lock. */
async function waitForLockWaiters(count: number) {
for (let attempt = 0; attempt < 300; attempt += 1) {
@@ -222,29 +276,12 @@ test("a closed account's records do not go to someone whose role is being taken
const removed = await createUser({ role: "admin" });
const staying = await createUser({ role: "admin" });
const leaver = await createUser();
- const envelopeId = randomUUID();
- await database.query(
- `update public."user" set "createdAt" = now() - interval '1 day' where id = $1`,
- [removed],
- );
- await database.query(
- `
- insert into envelopes (
- id, user_id, title, status, source_pdf_key, source_pdf_filename,
- source_pdf_size_bytes, page_count, source_pdf_hash, completed_at
- ) values ($1, $2, 'Lease', 'completed', $3, 'lease.pdf', 10, 1, $4, 1)
- `,
- [envelopeId, leaver, `test/${envelopeId}.pdf`, "a".repeat(64)],
- );
- await database.query(
- `
- insert into account_closure_requests
- (user_id, requested_at, export_expires_at, purge_after_at, updated_at)
- values ($1, 1, 1, 1, 1)
- `,
- [leaver],
- );
+ await makeLongestStanding(removed);
+
+ const envelopeId = await createFinishedEnvelope(leaver);
+
+ await closeAccount(leaver);
const holder = await database.connect();
@@ -256,12 +293,7 @@ test("a closed account's records do not go to someone whose role is being taken
removed,
]);
- const sweep = runRetentionSweep({
- database,
- storageService: createStorageService({
- env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
- }),
- });
+ const sweep = runRetentionSweep({ database, storageService: storage() });
sweep.catch(() => undefined);
// The hand-over waits for the removal instead of going ahead of it.
@@ -274,15 +306,99 @@ test("a closed account's records do not go to someone whose role is being taken
holder.release();
}
- const owner = await database.query<{ user_id: string }>(
- `select user_id from envelopes where id = $1`,
- [envelopeId],
- );
-
- assert.equal(owner.rows[0]?.user_id, staying);
+ assert.equal((await envelopeRow(envelopeId)).user_id, staying);
assert.equal(await roleOf(leaver), null);
});
+test("records handed over from a closed account move on when their keeper stops being an administrator", async () => {
+ await resetRoles();
+
+ const keeper = await createUser({ role: "admin" });
+ const staying = await createUser({ role: "admin" });
+ const leaver = await createUser();
+
+ await makeLongestStanding(keeper);
+
+ const sentByKeeper = await createFinishedEnvelope(keeper);
+ const sentByLeaver = await createFinishedEnvelope(leaver);
+
+ await closeAccount(leaver);
+
+ const summary = await runRetentionSweep({
+ database,
+ storageService: storage(),
+ });
+
+ assert.ok(!summary.accountPurgeFailures.includes(leaver));
+
+ // Handed to the keeper, and marked as handed over. What the keeper sent
+ // is not.
+ const handedOver = await envelopeRow(sentByLeaver);
+
+ assert.equal(handedOver.user_id, keeper);
+ assert.ok(handedOver.handed_over_at);
+ assert.equal((await envelopeRow(sentByKeeper)).handed_over_at, null);
+
+ // The keeper gives the role up. The organization's record goes to the
+ // administrator who stays, and the keeper's own envelope stays theirs.
+ await setPersonRole(keeper, keeper, "user", database);
+
+ assert.deepEqual(await envelopeRow(sentByLeaver), {
+ handed_over_at: handedOver.handed_over_at,
+ user_id: staying,
+ });
+ assert.equal((await envelopeRow(sentByKeeper)).user_id, keeper);
+
+ // Getting the role back does not bring the record back.
+ await setPersonRole(staying, keeper, "admin", database);
+ assert.equal((await envelopeRow(sentByLeaver)).user_id, staying);
+});
+
+test("an administrator who closes their account passes on what they were handed", async () => {
+ await resetRoles();
+
+ const first = await createUser({ role: "admin" });
+ const second = await createUser({ role: "admin" });
+ const leaver = await createUser();
+ const firstRunAt = Math.floor(Date.now() / 1000);
+ const secondRunAt = firstRunAt + 24 * 60 * 60;
+
+ await makeLongestStanding(first);
+
+ const sentByFirst = await createFinishedEnvelope(first);
+ const sentByLeaver = await createFinishedEnvelope(leaver);
+
+ await closeAccount(leaver);
+ await runRetentionSweep({
+ database,
+ now: firstRunAt,
+ storageService: storage(),
+ });
+ assert.deepEqual(await envelopeRow(sentByLeaver), {
+ handed_over_at: firstRunAt,
+ user_id: first,
+ });
+
+ await closeAccount(first);
+ await runRetentionSweep({
+ database,
+ now: secondRunAt,
+ storageService: storage(),
+ });
+
+ // Both are with the second administrator now. The one that was handed
+ // over before keeps the day it first was.
+ assert.equal(await roleOf(first), null);
+ assert.deepEqual(await envelopeRow(sentByLeaver), {
+ handed_over_at: firstRunAt,
+ user_id: second,
+ });
+ assert.deepEqual(await envelopeRow(sentByFirst), {
+ handed_over_at: secondRunAt,
+ user_id: second,
+ });
+});
+
test("an administrator whose account is closing does not count as the one that stays", async () => {
await resetRoles();
diff --git a/src/lib/people.ts b/src/lib/people.ts
index 535cfdb..61fb9ab 100644
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@ -132,6 +132,35 @@ export async function listPeople(
};
}
+/**
+ * The administrator who keeps the organization's records: the one who has
+ * been here longest and whose own account is not on its way to being
+ * closed. `exceptUserId` is the account that is giving the records up.
+ * Returns null when there is no such administrator.
+ */
+export async function findRecordKeeper(
+ exceptUserId: string,
+ database: DbExecutor,
+): Promise<string | null> {
+ const keeper = await queryOne<{ id: string }>(
+ database,
+ `
+ SELECT u.id
+ FROM "user" u
+ WHERE u.id <> $1
+ AND u.role = 'admin'
+ AND NOT EXISTS (
+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id
+ )
+ ORDER BY u."createdAt" ASC, u.id ASC
+ LIMIT 1
+ `,
+ [exceptUserId],
+ );
+
+ return keeper?.id ?? null;
+}
+
export function parsePersonRole(value: unknown): PersonRole | null {
return value === "admin" || value === "user" ? value : null;
}
@@ -146,6 +175,11 @@ export function parsePersonRole(value: unknown): PersonRole | null {
* looked at again here, where no role can change underneath it. Without
* that, a request already under way would let someone who has just been
* removed put themselves back.
+ *
+ * Taking the role away also takes away the finished envelopes the account
+ * was handed from closed accounts. Those were given to an administrator to
+ * keep for the organization, so they go to one who stays. The envelopes
+ * the account sent itself are its own and stay where they are.
*/
export async function setPersonRole(
actingUserId: string,
@@ -180,6 +214,8 @@ export async function setPersonRole(
return mapPerson(target);
}
+ let keeperId: string | null = null;
+
if (role === "admin") {
if (!target.emailVerified) {
throw new PeopleError(
@@ -195,21 +231,10 @@ export async function setPersonRole(
);
}
} 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],
- );
+ // The administrator who stays, and who takes over the records.
+ keeperId = await findRecordKeeper(targetUserId, tx);
- if ((others?.count ?? 0) === 0) {
+ if (!keeperId) {
throw new PeopleError(
"There has to be at least one administrator. Make someone else an administrator first.",
409,
@@ -222,6 +247,26 @@ export async function setPersonRole(
[role, targetUserId],
);
+ if (keeperId) {
+ // The account's row has been held since it was read above. A closed
+ // account's envelopes are handed over only while holding the
+ // keeper's row too, so none can arrive here after this has looked.
+ const moved = await tx.query(
+ `
+ UPDATE envelopes
+ SET user_id = $1
+ WHERE user_id = $2 AND handed_over_at IS NOT NULL
+ `,
+ [keeperId, targetUserId],
+ );
+
+ if ((moved.rowCount ?? 0) > 0) {
+ console.info(
+ `Moved ${moved.rowCount} handed-over envelopes from ${targetUserId}, no longer an administrator, to ${keeperId}.`,
+ );
+ }
+ }
+
return mapPerson({ ...target, role });
}, database);
}
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index c5b9858..0bc37f5 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -5,6 +5,7 @@ import {
queryOne,
withTransaction,
} from "./db/connection.ts";
+import { findRecordKeeper } from "./people.ts";
import {
buildEnvelopeThumbnailKey,
getRecipientCertificateKey,
@@ -347,12 +348,14 @@ const MAX_KEEPER_ATTEMPTS = 5;
* person leaving must not take them along. Finished envelopes move to an
* administrator before the
* account is deleted. Only an administrator may receive them: anyone else
- * would gain documents they were never party to. Returns false when there
- * is no administrator to keep them, which leaves the account for the next
- * run.
+ * would gain documents they were never party to. Each envelope is marked
+ * as handed over, so that it moves on again if its keeper stops being an
+ * administrator. Returns false when there is no administrator to keep
+ * them, which leaves the account for the next run.
*/
async function handOverFinishedEnvelopes(
userId: string,
+ now: number,
database: DbExecutor,
): Promise<boolean> {
for (let attempt = 0; attempt < MAX_KEEPER_ATTEMPTS; attempt += 1) {
@@ -370,23 +373,9 @@ async function handOverFinishedEnvelopes(
return true;
}
- const keeper = await queryOne<{ id: string }>(
- database,
- `
- SELECT u.id
- FROM "user" u
- WHERE u.id <> $1
- AND u.role = 'admin'
- AND NOT EXISTS (
- SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id
- )
- ORDER BY u."createdAt" ASC, u.id ASC
- LIMIT 1
- `,
- [userId],
- );
+ const keeperId = await findRecordKeeper(userId, database);
- if (!keeper) {
+ if (!keeperId) {
return false;
}
@@ -395,10 +384,12 @@ async function handOverFinishedEnvelopes(
// it holds their row: a removal already under way finishes first and is
// seen here, and one that starts now waits until the records have
// moved. Nothing moves to someone who is no longer an administrator.
+ // An envelope that was handed over before keeps the day it first was.
const moved = await database.query(
`
UPDATE envelopes e
- SET user_id = k.id
+ SET user_id = k.id,
+ handed_over_at = COALESCE(e.handed_over_at, $4)
FROM (
SELECT u.id
FROM "user" u
@@ -411,12 +402,12 @@ async function handOverFinishedEnvelopes(
) k
WHERE e.user_id = $2 AND e.status = ANY($3::text[])
`,
- [keeper.id, userId, FINISHED_ENVELOPE_STATUSES],
+ [keeperId, userId, FINISHED_ENVELOPE_STATUSES, now],
);
if ((moved.rowCount ?? 0) > 0) {
console.info(
- `Moved finished envelopes from closed account ${userId} to ${keeper.id}.`,
+ `Moved finished envelopes from closed account ${userId} to ${keeperId}.`,
);
return true;
@@ -509,13 +500,14 @@ async function deleteAccountRows(
async function purgeQueuedAccount(
userId: string,
+ now: number,
database: DbExecutor,
storageService: StorageService,
env: EnvSource = process.env,
): Promise<boolean> {
if (
!isHostedMode(env) &&
- !(await handOverFinishedEnvelopes(userId, database))
+ !(await handOverFinishedEnvelopes(userId, now, database))
) {
throw new AccountPurgeDeferredError(userId);
}
@@ -862,6 +854,7 @@ export async function runRetentionSweep({
try {
const deleted = await purgeQueuedAccount(
closureRequest.userId,
+ now,
database,
storageService,
);