Skip to content

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

TypeScript

Let administrators delete finished envelopes

Claude95d577d97324
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 1aef0cf..952c8ed 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -211,7 +211,7 @@ SAML is not supported. Okta, Entra ID and Google all offer OIDC for the same app
## Your responsibilities
-Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.
+Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. An administrator can also delete a finished envelope by hand, from its page; the deletion is recorded in the install's audit log (Settings, Organization, "Site audit trail"), with the document's fingerprints and the reason given. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.
## FDA 21 CFR Part 11
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index 39e8656..220997d 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -1340,6 +1340,36 @@ test("a signer who declines is told the decline was recorded, not that the link
),
).toBeVisible();
});
+
+ await test.step("the administrator deletes the declined envelope for good", async () => {
+ await page.getByRole("button", { name: "Delete envelope" }).click();
+
+ const confirm = page.getByRole("dialog", {
+ name: "Delete this envelope?",
+ });
+
+ await confirm.getByLabel("Reason (optional)").fill("Never agreed.");
+ await confirm.getByRole("button", { name: "Delete envelope" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+
+ await page.goto(`/envelopes/${envelopeId}`);
+ await expect(
+ page.getByRole("heading", { name: "This envelope is unavailable" }),
+ ).toBeVisible();
+
+ // The deletion itself stays on record in the install's audit trail.
+ const audit = await page.request.get("/api/admin/audit");
+ const { events } = (await audit.json()) as {
+ events: { event: string; metadata: Record<string, unknown> | null }[];
+ };
+ const deletion = events.find((event) => event.event === "envelope_deleted");
+
+ expect(deletion?.metadata).toMatchObject({
+ envelopeId,
+ reason: "Never agreed.",
+ status: "declined",
+ });
+ });
});
test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({
diff --git a/src/app/(app)/envelopes/[id]/page.tsx b/src/app/(app)/envelopes/[id]/page.tsx
index 59badee..7d00405 100644
--- a/src/app/(app)/envelopes/[id]/page.tsx
+++ b/src/app/(app)/envelopes/[id]/page.tsx
@@ -1,4 +1,5 @@
import { EnvelopeDetailShell } from "@/components/envelopes/envelope-detail-shell";
+import { isAdminUser } from "@/lib/auth/admin";
import { getAuthSession } from "@/lib/auth/server";
import { getDb } from "@/lib/db/connection";
import { getEnvelopeDetailDataForUser } from "@/lib/envelopes";
@@ -17,6 +18,7 @@ export default async function EnvelopeDetailPage({
let detailRecord: Awaited<ReturnType<typeof getEnvelopeDetailDataForUser>> =
null;
let initialState: "error" | "not-found" | undefined;
+ let canDeleteFinished = false;
try {
const session = await getAuthSession();
@@ -24,12 +26,18 @@ export default async function EnvelopeDetailPage({
? await getEnvelopeDetailDataForUser(session.user.id, id, getDb())
: null;
initialState = detailRecord ? undefined : "not-found";
+ // Only an administrator may delete a finished envelope.
+ canDeleteFinished =
+ detailRecord !== null &&
+ session !== null &&
+ (await isAdminUser(session.user.id, getDb()));
} catch {
initialState = "error";
}
return (
<EnvelopeDetailShell
+ canDeleteFinished={canDeleteFinished}
envelopeId={id}
initialState={initialState}
key={id}
diff --git a/src/app/api/envelopes/[id]/delete/route.ts b/src/app/api/envelopes/[id]/delete/route.ts
new file mode 100644
index 0000000..d3d1ec8
--- /dev/null
+++ b/src/app/api/envelopes/[id]/delete/route.ts
@@ -0,0 +1,98 @@
+import { NextResponse } from "next/server";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import { getDb } from "@/lib/db/connection";
+import { deleteFinishedEnvelope } from "@/lib/envelope-deletion";
+import { EnvelopeMutationError } from "@/lib/envelopes";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+
+// Deletes a finished envelope for good. Drafts are deleted with DELETE on
+// the envelope itself; this is for completed, declined and voided ones, and
+// only an administrator may do it.
+
+type EnvelopeDeleteRouteContext = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+const NO_STORE = { "cache-control": "private, no-store" };
+
+export async function POST(
+ request: Request,
+ context: EnvelopeDeleteRouteContext,
+) {
+ 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: "finished_envelope_delete",
+ key: buildRateLimitKey(["envelope-delete", session.user.id]),
+ limit: 60,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ rateLimitResponse.headers.set("cache-control", "private, no-store");
+ return rateLimitResponse;
+ }
+
+ const body = (await request.json().catch(() => null)) as {
+ reason?: unknown;
+ } | null;
+
+ try {
+ const result = await deleteFinishedEnvelope(
+ id,
+ {
+ actor: { email: session.user.email, userId: session.user.id },
+ ipAddress,
+ reason: body?.reason ?? null,
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ { database: getDb() },
+ );
+
+ return NextResponse.json(
+ { ...result, redirectPath: "/dashboard" },
+ { headers: NO_STORE, status: 200 },
+ );
+ } catch (error) {
+ if (error instanceof EnvelopeMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "finished_envelope_delete_failure",
+ ipAddress,
+ message: "Unexpected failure while deleting a finished envelope.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "Unable to delete this envelope." },
+ { headers: NO_STORE, status: 500 },
+ );
+ }
+}
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index 447e29c..f15d3ed 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -37,6 +37,8 @@ import {
import { getSignerPalette } from "./signer-palette";
type EnvelopeDetailShellProps = {
+ /** An administrator may delete a finished envelope. */
+ canDeleteFinished?: boolean;
envelopeId: string;
initialState?: "error" | "not-found";
record?: EnvelopeDetailData;
@@ -75,6 +77,7 @@ type ModalState =
| "copy-draft"
| "correct-signer"
| "delete-draft"
+ | "delete-finished"
| "save-template"
| "void-envelope"
| null;
@@ -124,6 +127,7 @@ const timelineToneClasses: Record<TimelineTone, string> = {
};
export function EnvelopeDetailShell({
+ canDeleteFinished = false,
envelopeId,
initialState,
record,
@@ -135,6 +139,8 @@ export function EnvelopeDetailShell({
const [isCopyingDraft, setIsCopyingDraft] = useState(false);
const [isCorrectingSigner, setIsCorrectingSigner] = useState(false);
const [isDeletingDraft, setIsDeletingDraft] = useState(false);
+ const [isDeletingFinished, setIsDeletingFinished] = useState(false);
+ const [deleteReason, setDeleteReason] = useState("");
const [isSendingReminder, setIsSendingReminder] = useState(false);
const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);
const [correctingSigner, setCorrectingSigner] =
@@ -413,6 +419,32 @@ export function EnvelopeDetailShell({
}
}
+ async function handleConfirmDeleteFinished() {
+ setActionError(null);
+ setIsDeletingFinished(true);
+
+ try {
+ const response = await fetch(`/api/envelopes/${envelopeId}/delete`, {
+ body: JSON.stringify({ reason: deleteReason }),
+ headers: { "Content-Type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ redirectPath?: string;
+ } | null;
+
+ if (!response.ok) {
+ setActionError(payload?.error ?? "Unable to delete this envelope.");
+ return;
+ }
+
+ window.location.assign(payload?.redirectPath ?? "/dashboard");
+ } finally {
+ setIsDeletingFinished(false);
+ }
+ }
+
async function handleConfirmVoidEnvelope() {
setActionError(null);
setIsVoidingEnvelope(true);
@@ -584,6 +616,21 @@ export function EnvelopeDetailShell({
</ShellButton>
</>
) : null}
+
+ {canDeleteFinished &&
+ (activeRecord.status === "completed" ||
+ activeRecord.status === "declined" ||
+ activeRecord.status === "voided") ? (
+ <ShellButton
+ onClick={() => {
+ setActionError(null);
+ setActiveModal("delete-finished");
+ }}
+ variant="secondary"
+ >
+ Delete envelope
+ </ShellButton>
+ ) : null}
</div>
</div>
@@ -910,6 +957,39 @@ export function EnvelopeDetailShell({
/>
) : null}
+ {activeModal === "delete-finished" ? (
+ <ConfirmationDialog
+ confirmDisabled={record.part11 && deleteReason.trim().length === 0}
+ confirmLabel="Delete envelope"
+ description={[
+ "This permanently deletes the envelope, its signed PDF, its certificate and its audit trail. Download links already sent to signers stop working.",
+ "The install's audit log keeps a record of the deletion, with the document's fingerprints.",
+ "This action cannot be undone.",
+ ]}
+ errorMessage={actionError}
+ onCancel={() => setActiveModal(null)}
+ onConfirm={handleConfirmDeleteFinished}
+ processing={isDeletingFinished}
+ title="Delete this envelope?"
+ >
+ <label className="grid gap-2 text-sm">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ {record.part11 ? "Reason (required)" : "Reason (optional)"}
+ </span>
+ <Textarea
+ disabled={isDeletingFinished}
+ maxLength={1000}
+ onChange={(event) => setDeleteReason(event.target.value)}
+ rows={3}
+ value={deleteReason}
+ />
+ <span className="text-xs leading-5 text-(--tertiary)">
+ Kept in the install&apos;s audit log.
+ </span>
+ </label>
+ </ConfirmationDialog>
+ ) : null}
+
{activeModal === "void-envelope" ? (
<ConfirmationDialog
confirmLabel="Void envelope"
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index eee9784..fbfd93b 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -24,6 +24,7 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
account_closure_requested: "Account closure requested",
account_deleted: "Account deleted",
email_domain_changed: "Email domain changed",
+ envelope_deleted: "Finished envelope deleted",
identity_verification_revoked: "Identity confirmation taken back",
identity_verified: "Identity confirmed",
logo_changed: "Logo changed",
@@ -94,6 +95,14 @@ function describeEvent(event: SystemAuditEvent): string {
return metadata.action === "removed" ? "Removed" : "Replaced";
case "email_domain_changed":
return typeof metadata.domain === "string" ? metadata.domain : "";
+ case "envelope_deleted":
+ return [
+ typeof metadata.title === "string" ? `"${metadata.title}"` : null,
+ typeof metadata.status === "string" ? metadata.status : null,
+ typeof metadata.reason === "string" ? metadata.reason : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
default:
return target ?? "";
}
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.ts
new file mode 100644
index 0000000..7d424bc
--- /dev/null
+++ b/src/lib/envelope-deletion.dbtest.ts
@@ -0,0 +1,318 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import { deleteFinishedEnvelope } from "./envelope-deletion.ts";
+import { EnvelopeMutationError } from "./envelopes.ts";
+import { getRecipientCertificateKey } from "./services/storage-keys.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import {
+ listSystemAuditEvents,
+ verifySystemAuditChain,
+} from "./services/system-audit.ts";
+
+// An administrator deleting a finished envelope by hand, against a real
+// Postgres. Run with `npm run test:db`.
+
+const SOURCE_HASH = "a".repeat(64);
+const SIGNED_HASH = "b".repeat(64);
+const EVIDENCE_HASH = "c".repeat(64);
+
+let database: pg.Pool;
+let storageDir: string;
+let storageService: StorageService;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-deletion-"));
+ Object.assign(process.env, {
+ STORAGE_DRIVER: "local",
+ STORAGE_LOCAL_DIR: storageDir,
+ });
+ storageService = createStorageService();
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+ await rm(storageDir, { force: true, recursive: true });
+});
+
+async function createUser(role: "admin" | "user") {
+ const id = randomUUID();
+ const email = `${id}@example.test`;
+
+ createdUsers.push(id);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Avery Admin', $2, $3)`,
+ [id, email, role],
+ );
+
+ return { email, userId: id };
+}
+
+/** An envelope with its files stored, in the given state. */
+async function createEnvelope(
+ userId: string,
+ {
+ part11 = false,
+ status,
+ }: {
+ part11?: boolean;
+ status: "completed" | "declined" | "draft" | "sent" | "voided";
+ },
+) {
+ const envelopeId = randomUUID();
+ const base = `users/${userId}/envelopes/${envelopeId}`;
+ const keys = {
+ evidence: `${base}/evidence/internal.pdf`,
+ signed: `${base}/signed.pdf`,
+ source: `${base}/source.pdf`,
+ };
+ const finished = status !== "draft" && status !== "sent";
+ const stored = [keys.source];
+
+ if (finished) {
+ stored.push(
+ keys.evidence,
+ getRecipientCertificateKey(keys.evidence),
+ ...(status === "completed" ? [keys.signed] : []),
+ );
+ }
+
+ for (const key of stored) {
+ await storageService.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const now = Math.floor(Date.now() / 1000);
+
+ 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, sent_at,
+ completed_at, declined_at, voided_at, signed_pdf_key, evidence_key,
+ signed_pdf_sha256, evidence_sha256, part11
+ ) values (
+ $1, $2, 'Lease', $3, $4, 'lease.pdf', 4, 1, $14, $5,
+ $6, $7, $8, $9, $10, $11, $12, $13
+ )
+ `,
+ [
+ envelopeId,
+ userId,
+ status,
+ keys.source,
+ status === "draft" ? null : now - 100,
+ status === "completed" ? now : null,
+ status === "declined" ? now : null,
+ status === "voided" ? now : null,
+ status === "completed" ? keys.signed : null,
+ finished ? keys.evidence : null,
+ status === "completed" ? SIGNED_HASH : null,
+ finished ? EVIDENCE_HASH : null,
+ part11,
+ SOURCE_HASH,
+ ],
+ );
+ await database.query(
+ `
+ insert into signers (id, envelope_id, name, email, sign_order, status)
+ values ($1, $2, 'Riley Recipient', '[email protected]', 1, $3)
+ `,
+ [randomUUID(), envelopeId, status === "completed" ? "signed" : "pending"],
+ );
+
+ return { envelopeId, stored };
+}
+
+async function envelopeExists(envelopeId: string) {
+ const result = await database.query(`select 1 from envelopes where id = $1`, [
+ envelopeId,
+ ]);
+
+ return result.rowCount === 1;
+}
+
+async function filesExist(keys: readonly string[]) {
+ return Promise.all(
+ keys.map(async (key) => (await storageService.headObject(key)).exists),
+ );
+}
+
+function deleteAs(
+ actor: { email: string; userId: string },
+ envelopeId: string,
+ reason?: string,
+) {
+ return deleteFinishedEnvelope(
+ envelopeId,
+ { actor, ipAddress: "203.0.113.9", reason, userAgent: "Test browser" },
+ { database, storageService },
+ );
+}
+
+function rejectsWith(statusCode: number) {
+ return (error: unknown) =>
+ error instanceof EnvelopeMutationError && error.statusCode === statusCode;
+}
+
+for (const status of ["completed", "declined", "voided"] as const) {
+ test(`an administrator deletes a ${status} envelope, its files go and the deletion is recorded`, async () => {
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status });
+
+ assert.ok((await filesExist(envelope.stored)).every(Boolean));
+
+ await deleteAs(admin, envelope.envelopeId, "Kept long enough.");
+
+ assert.equal(await envelopeExists(envelope.envelopeId), false);
+ assert.deepEqual(
+ await filesExist(envelope.stored),
+ envelope.stored.map(() => false),
+ );
+
+ const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+
+ assert.equal(event?.event, "envelope_deleted");
+ assert.equal(event?.actorUserId, admin.userId);
+ assert.equal(event?.actorEmail, admin.email);
+ assert.equal(event?.ipAddress, "203.0.113.9");
+ assert.deepEqual(
+ {
+ envelopeId: event?.metadata?.envelopeId,
+ evidenceSha256: event?.metadata?.evidenceSha256,
+ reason: event?.metadata?.reason,
+ sourcePdfHash: event?.metadata?.sourcePdfHash,
+ status: event?.metadata?.status,
+ title: event?.metadata?.title,
+ },
+ {
+ envelopeId: envelope.envelopeId,
+ evidenceSha256: EVIDENCE_HASH,
+ reason: "Kept long enough.",
+ sourcePdfHash: SOURCE_HASH,
+ status,
+ title: "Lease",
+ },
+ );
+ assert.equal((await verifySystemAuditChain(database)).ok, true);
+ });
+}
+
+test("someone who is not an administrator cannot delete a finished envelope", async () => {
+ const user = await createUser("user");
+ const envelope = await createEnvelope(user.userId, { status: "completed" });
+ const before = await listSystemAuditEvents({ limit: 1 }, database);
+
+ await assert.rejects(deleteAs(user, envelope.envelopeId), rejectsWith(403));
+
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.ok((await filesExist(envelope.stored)).every(Boolean));
+ assert.deepEqual(await listSystemAuditEvents({ limit: 1 }, database), before);
+});
+
+test("an envelope still out for signature, or a draft, is not deleted this way", async () => {
+ const admin = await createUser("admin");
+
+ for (const status of ["sent", "draft"] as const) {
+ const envelope = await createEnvelope(admin.userId, { status });
+
+ await assert.rejects(
+ deleteAs(admin, envelope.envelopeId),
+ rejectsWith(409),
+ );
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.ok((await filesExist(envelope.stored)).every(Boolean));
+ }
+});
+
+test("an administrator cannot delete another account's envelope", async () => {
+ const owner = await createUser("admin");
+ const other = await createUser("admin");
+ const envelope = await createEnvelope(owner.userId, { status: "completed" });
+
+ await assert.rejects(deleteAs(other, envelope.envelopeId), rejectsWith(404));
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+});
+
+test("a Part 11 record needs a reason before it is deleted", async () => {
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, {
+ part11: true,
+ status: "completed",
+ });
+
+ await assert.rejects(
+ deleteAs(admin, envelope.envelopeId, " "),
+ rejectsWith(400),
+ );
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+
+ await deleteAs(admin, envelope.envelopeId, "Retention period over.");
+
+ assert.equal(await envelopeExists(envelope.envelopeId), false);
+
+ const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+
+ assert.equal(event?.metadata?.part11, true);
+ assert.equal(event?.metadata?.reason, "Retention period over.");
+});
+
+test("a reason that is not text, or too long, is refused", async () => {
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status: "voided" });
+
+ await assert.rejects(
+ deleteFinishedEnvelope(
+ envelope.envelopeId,
+ { actor: admin, reason: 42 },
+ { database, storageService },
+ ),
+ rejectsWith(400),
+ );
+ await assert.rejects(
+ deleteAs(admin, envelope.envelopeId, "x".repeat(1001)),
+ rejectsWith(400),
+ );
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+});
+
+test("when a file cannot be deleted, nothing is deleted and nothing is recorded", async () => {
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status: "completed" });
+ const before = await listSystemAuditEvents({ limit: 1 }, database);
+ const failingStorage = {
+ ...storageService,
+ deleteObject: async () => {
+ throw new Error("Storage is down.");
+ },
+ } as StorageService;
+
+ await assert.rejects(
+ deleteFinishedEnvelope(
+ envelope.envelopeId,
+ { actor: admin },
+ { database, storageService: failingStorage },
+ ),
+ /Storage is down/,
+ );
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.deepEqual(await listSystemAuditEvents({ limit: 1 }, database), before);
+});
diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.ts
new file mode 100644
index 0000000..177f0d2
--- /dev/null
+++ b/src/lib/envelope-deletion.ts
@@ -0,0 +1,176 @@
+import {
+ type DbPool,
+ getDb,
+ queryOne,
+ withTransaction,
+} from "./db/connection.ts";
+import { EnvelopeMutationError } from "./envelopes.ts";
+import { deleteEnvelopesAndFiles } from "./retention.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import { recordSystemAuditEvent } from "./services/system-audit.ts";
+
+// An administrator may delete a finished envelope of theirs by hand: the
+// signed PDF, the certificates, the fields and the envelope's own audit
+// trail all go, as they do when the retention period deletes it. What was
+// deleted, by whom and why stays in the install's audit trail, with the
+// fingerprints the certificate gave, so the deletion itself is on record.
+
+const FINISHED_STATUSES = ["completed", "declined", "voided"] as const;
+
+export const ENVELOPE_DELETION_REASON_MAX_LENGTH = 1000;
+
+type FinishedEnvelopeRow = {
+ evidenceSha256: string | null;
+ finishedAt: number | null;
+ id: string;
+ part11: boolean;
+ signedPdfSha256: string | null;
+ sourcePdfHash: string;
+ status: string;
+ title: string;
+};
+
+export type FinishedEnvelopeDeletion = {
+ actor: { email: string; userId: string };
+ ipAddress?: string | null;
+ reason?: unknown;
+ userAgent?: string | null;
+};
+
+function parseReason(reason: unknown, part11: boolean): string | null {
+ if (reason !== undefined && reason !== null && typeof reason !== "string") {
+ throw new EnvelopeMutationError("The reason must be text.", 400);
+ }
+
+ const trimmed = typeof reason === "string" ? reason.trim() : "";
+
+ if (trimmed.length > ENVELOPE_DELETION_REASON_MAX_LENGTH) {
+ throw new EnvelopeMutationError(
+ `Keep the reason under ${String(ENVELOPE_DELETION_REASON_MAX_LENGTH)} characters.`,
+ 400,
+ );
+ }
+
+ if (part11 && trimmed.length === 0) {
+ throw new EnvelopeMutationError(
+ "Give a reason for deleting this Part 11 record.",
+ 400,
+ );
+ }
+
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+/**
+ * Deletes a completed, declined or voided envelope the administrator owns,
+ * with its files, and records the deletion in the install's audit trail.
+ */
+export async function deleteFinishedEnvelope(
+ envelopeId: string,
+ {
+ actor,
+ ipAddress = null,
+ reason,
+ userAgent = null,
+ }: FinishedEnvelopeDeletion,
+ {
+ database = getDb(),
+ storageService = createStorageService(),
+ }: {
+ database?: DbPool;
+ storageService?: StorageService;
+ } = {},
+): Promise<{ deletedEnvelopeId: string }> {
+ return withTransaction(async (tx) => {
+ // The envelope row first, as everything that changes an envelope takes
+ // it; the install's audit trail lock comes after.
+ const envelope = await queryOne<FinishedEnvelopeRow>(
+ tx,
+ `
+ SELECT
+ id,
+ title,
+ status,
+ part11,
+ source_pdf_hash AS "sourcePdfHash",
+ signed_pdf_sha256 AS "signedPdfSha256",
+ evidence_sha256 AS "evidenceSha256",
+ COALESCE(completed_at, declined_at, voided_at) AS "finishedAt"
+ FROM envelopes
+ WHERE id = $1 AND user_id = $2
+ FOR UPDATE
+ `,
+ [envelopeId, actor.userId],
+ );
+
+ if (!envelope) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (!(FINISHED_STATUSES as readonly string[]).includes(envelope.status)) {
+ throw new EnvelopeMutationError(
+ envelope.status === "sent"
+ ? "This envelope is still out for signature. Void it first."
+ : "Only finished envelopes can be deleted this way.",
+ 409,
+ );
+ }
+
+ // Asked again here, not only by the route: the role is read from the
+ // database, and a change since the page loaded is honored.
+ const actorRole = await queryOne<{ role: string }>(
+ tx,
+ `SELECT role FROM public."user" WHERE id = $1`,
+ [actor.userId],
+ );
+
+ if (actorRole?.role !== "admin") {
+ throw new EnvelopeMutationError(
+ "Only an administrator can delete a finished envelope.",
+ 403,
+ );
+ }
+
+ const deletionReason = parseReason(reason, envelope.part11);
+
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "envelope_deleted",
+ ipAddress,
+ metadata: {
+ envelopeId: envelope.id,
+ evidenceSha256: envelope.evidenceSha256,
+ finishedAt: envelope.finishedAt,
+ part11: envelope.part11,
+ reason: deletionReason,
+ signedPdfSha256: envelope.signedPdfSha256,
+ sourcePdfHash: envelope.sourcePdfHash,
+ status: envelope.status,
+ title: envelope.title,
+ },
+ userAgent,
+ },
+ tx,
+ );
+
+ // Files first, then the row, all while the row is held: if a file
+ // cannot be deleted, the whole deletion rolls back and can be tried
+ // again.
+ const deleted = await deleteEnvelopesAndFiles(
+ [envelope.id],
+ tx,
+ storageService,
+ );
+
+ if (deleted !== 1) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ return { deletedEnvelopeId: envelope.id };
+ }, database);
+}
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
index b68cbfa..68ca1a1 100644
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@ -42,6 +42,7 @@ export const systemAuditEventTypes = [
"two_factor_requirement_changed",
"logo_changed",
"email_domain_changed",
+ "envelope_deleted",
] as const;
export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];