Skip to content

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

TypeScript

Schedule admin deletions and keep other members' drafts private

Claudee2d7581a2aec
diff --git a/db/migrations/20261118110000_scheduled_envelope_deletions.sql b/db/migrations/20261118110000_scheduled_envelope_deletions.sql
new file mode 100644
index 0000000..6ac42ee
--- /dev/null
+++ b/db/migrations/20261118110000_scheduled_envelope_deletions.sql
@@ -0,0 +1,22 @@
+-- Finished envelopes an administrator has asked to delete. Nothing goes at
+-- once: the envelope stays as it is for the waiting period, its sender is
+-- emailed a link to download it, and any administrator can cancel. The
+-- daily cleanup deletes it once the wait is over.
+
+create table if not exists public.scheduled_envelope_deletions (
+ envelope_id text primary key references public.envelopes (id) on delete cascade,
+ -- Who asked. No foreign key: the request stands, and the record names
+ -- them, after their account is gone.
+ requested_by_user_id text not null,
+ requested_by_email text not null,
+ requested_at bigint not null,
+ -- Deleted by the first daily cleanup at or after this time.
+ delete_after bigint not null,
+ reason text,
+ -- When the sender was told. Null until the email went out; the daily
+ -- cleanup tries again. Set at once when the sender asked themselves.
+ sender_notified_at bigint
+);
+
+create index if not exists scheduled_envelope_deletions_due_idx
+ on public.scheduled_envelope_deletions (delete_after);
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 4160ce4..487a65a 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. Administrators see every envelope in the install (Documents, "Everyone's"), whoever sent it. They can open and download any of them, and delete a finished one by hand from its page. Sending, voiding, reminders and edits stay with the envelope's sender. An administrator's download of another member's file and every deletion are recorded in the install's audit log (Settings, Organization, "Site audit trail"), deletions with the document's fingerprints, its sender 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.
+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. Administrators see every envelope in the install that has been sent (Documents, "Everyone's"), whoever sent it; a draft stays its sender's own. They can open and download any of them, and ask for a finished one to be deleted from its page. The deletion waits 14 days: its sender is emailed a link to download it, any administrator can cancel until then, and the daily cleanup deletes it after that. A Part 11 record needs a reason. Sending, voiding, reminders and edits stay with the envelope's sender. An administrator's download of another member's file, each deletion request, each cancellation and each deletion are recorded in the install's audit log (Settings, Organization, "Site audit trail"), deletions with the document's fingerprints, its sender 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 dabd563..65476cd 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -1341,7 +1341,7 @@ test("a signer who declines is told the decline was recorded, not that the link
).toBeVisible();
});
- await test.step("an administrator sees another member's envelope and deletes it for good", async () => {
+ await test.step("an administrator sees another member's envelope and schedules its deletion", async () => {
// The envelope becomes a plain member's, as if they had sent it.
const memberId = `member-${runId}`;
const memberEmail = `member+${runId}@example.com`;
@@ -1402,23 +1402,60 @@ test("a signer who declines is told the decline was recorded, not that the link
await page.getByRole("button", { name: "Download certificate" }).click();
expect((await download).suggestedFilename()).toMatch(/\.pdf$/);
- await page.getByRole("button", { name: "Delete envelope" }).click();
+ // Nothing goes at once: the deletion is scheduled, and the sender is
+ // emailed a link to download it.
+ async function scheduleDeletion(reason: string) {
+ await page.getByRole("button", { name: "Delete envelope" }).click();
- const confirm = page.getByRole("dialog", {
- name: "Delete this envelope?",
+ const confirm = page.getByRole("dialog", {
+ name: "Schedule this envelope for deletion?",
+ });
+
+ await confirm.getByLabel("Reason (optional)").fill(reason);
+ await confirm.getByRole("button", { name: "Schedule deletion" }).click();
+ await expect(page.getByText(/Scheduled to be deleted on/)).toBeVisible();
+ await expect(page.getByText(`Reason: ${reason}`)).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "Delete envelope" }),
+ ).toHaveCount(0);
+ }
+
+ await scheduleDeletion("Changed my mind.");
+
+ const notice = await waitForEmail({
+ template: "deletion_notice",
+ to: memberEmail,
});
- await confirm.getByLabel("Reason (optional)").fill("Never agreed.");
- await confirm.getByRole("button", { name: "Delete envelope" }).click();
- await expect(page).toHaveURL(/\/dashboard\?view=all$/);
+ expect(notice.subject).toMatch(/^"Terms to decline" will be deleted on /);
+ expect(notice.text).toContain(`/envelopes/${envelopeId}`);
- await page.goto(`/envelopes/${envelopeId}`);
+ // Any administrator can cancel until then; the sender is told.
+ await page.getByRole("button", { name: "Cancel deletion" }).click();
+ await page
+ .getByRole("dialog", { name: "Cancel this deletion?" })
+ .getByRole("button", { name: "Cancel deletion" })
+ .click();
+ await expect(page.getByText(/Scheduled to be deleted on/)).toHaveCount(0);
+ await expect.poll(async () => {
+ const latest = await waitForEmail({
+ template: "deletion_notice",
+ to: memberEmail,
+ });
+
+ return latest.subject;
+ }).toBe('"Terms to decline" will not be deleted');
+
+ await scheduleDeletion("Never agreed.");
+
+ // The envelope itself stays until the wait is over.
+ await page.reload();
await expect(
- page.getByRole("heading", { name: "This envelope is unavailable" }),
+ page.getByRole("heading", { name: "Terms to decline" }),
).toBeVisible();
- // The download and the deletion stay on record in the install's audit
- // trail, with whose envelope it was.
+ // The download, the request and its cancellation stay on record in the
+ // install's audit trail, with whose envelope it was.
const audit = await page.request.get("/api/admin/audit");
const { events } = (await audit.json()) as {
events: { event: string; metadata: Record<string, unknown> | null }[];
@@ -1433,13 +1470,18 @@ test("a signer who declines is told the decline was recorded, not that the link
ownerEmail: memberEmail,
});
expect(
- events.find((event) => event.event === "envelope_deleted")?.metadata,
+ events.find((event) => event.event === "envelope_deletion_scheduled")
+ ?.metadata,
).toMatchObject({
envelopeId,
ownerEmail: memberEmail,
reason: "Never agreed.",
status: "declined",
});
+ expect(
+ events.find((event) => event.event === "envelope_deletion_cancelled")
+ ?.metadata,
+ ).toMatchObject({ envelopeId, ownerEmail: memberEmail });
});
});
diff --git a/src/app/(app)/dashboard/page.tsx b/src/app/(app)/dashboard/page.tsx
index 3ea7c77..005e201 100644
--- a/src/app/(app)/dashboard/page.tsx
+++ b/src/app/(app)/dashboard/page.tsx
@@ -80,7 +80,7 @@ export default async function DashboardPage({
result = !session
? { envelopes: [], hasMore: false }
: showAll
- ? await listAllEnvelopesForAdmin(filters, database)
+ ? await listAllEnvelopesForAdmin(session.user.id, filters, database)
: await listEnvelopesForUser(session.user.id, filters, database);
// Nothing at all yet, as opposed to nothing that matches or nothing
// on this page.
diff --git a/src/app/(app)/envelopes/[id]/page.tsx b/src/app/(app)/envelopes/[id]/page.tsx
index 1a6b81a..fd8465e 100644
--- a/src/app/(app)/envelopes/[id]/page.tsx
+++ b/src/app/(app)/envelopes/[id]/page.tsx
@@ -1,4 +1,7 @@
-import { EnvelopeDetailShell } from "@/components/envelopes/envelope-detail-shell";
+import {
+ EnvelopeDetailShell,
+ type EnvelopeDeletionNotice,
+} from "@/components/envelopes/envelope-detail-shell";
import { isAdminUser } from "@/lib/auth/admin";
import { getAuthSession } from "@/lib/auth/server";
import { getDb } from "@/lib/db/connection";
@@ -6,8 +9,16 @@ import {
formatEnvelopeOwner,
resolveEnvelopeViewerAccess,
} from "@/lib/envelope-access";
+import { getScheduledEnvelopeDeletion } from "@/lib/envelope-deletion";
import { getEnvelopeDetailDataForUser } from "@/lib/envelopes";
+const deletionDateFormatter = new Intl.DateTimeFormat("en-US", {
+ day: "numeric",
+ month: "long",
+ timeZone: "UTC",
+ year: "numeric",
+});
+
type EnvelopeDetailPageProps = {
params: Promise<{
id: string;
@@ -24,6 +35,7 @@ export default async function EnvelopeDetailPage({
let initialState: "error" | "not-found" | undefined;
let canDeleteFinished = false;
let ownerLabel: string | undefined;
+ let scheduledDeletion: EnvelopeDeletionNotice | undefined;
try {
const session = await getAuthSession();
@@ -43,6 +55,21 @@ export default async function EnvelopeDetailPage({
detailRecord !== null &&
session !== null &&
(await isAdminUser(session.user.id, getDb()));
+
+ const scheduled = detailRecord
+ ? await getScheduledEnvelopeDeletion(id, getDb())
+ : null;
+
+ scheduledDeletion = scheduled
+ ? {
+ deleteOnLabel: deletionDateFormatter.format(
+ new Date(scheduled.deleteAfter * 1000),
+ ),
+ // Why is for administrators; the sender is told who asked.
+ reason: canDeleteFinished ? scheduled.reason : null,
+ requestedByEmail: scheduled.requestedByEmail,
+ }
+ : undefined;
} catch {
initialState = "error";
}
@@ -55,6 +82,7 @@ export default async function EnvelopeDetailPage({
key={id}
ownerLabel={ownerLabel}
record={detailRecord ?? undefined}
+ scheduledDeletion={scheduledDeletion}
/>
);
}
diff --git a/src/app/api/envelopes/[id]/delete/route.ts b/src/app/api/envelopes/[id]/deletion/route.ts
similarity index 52%
rename from src/app/api/envelopes/[id]/delete/route.ts
rename to src/app/api/envelopes/[id]/deletion/route.ts
index d3d1ec8..2c26788 100644
--- a/src/app/api/envelopes/[id]/delete/route.ts
+++ b/src/app/api/envelopes/[id]/deletion/route.ts
@@ -2,7 +2,10 @@ import { NextResponse } from "next/server";
import { requireAdminSession } from "@/lib/auth/admin";
import { getDb } from "@/lib/db/connection";
-import { deleteFinishedEnvelope } from "@/lib/envelope-deletion";
+import {
+ cancelEnvelopeDeletion,
+ scheduleEnvelopeDeletion,
+} from "@/lib/envelope-deletion";
import { EnvelopeMutationError } from "@/lib/envelopes";
import { logRouteError } from "@/lib/security/logging";
import {
@@ -15,11 +18,11 @@ import {
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.
+// A finished envelope's scheduled deletion. POST schedules it, DELETE
+// cancels it; only an administrator may do either. Drafts are deleted with
+// DELETE on the envelope itself.
-type EnvelopeDeleteRouteContext = {
+type EnvelopeDeletionRouteContext = {
params: Promise<{
id: string;
}>;
@@ -27,9 +30,10 @@ type EnvelopeDeleteRouteContext = {
const NO_STORE = { "cache-control": "private, no-store" };
-export async function POST(
+async function handle(
request: Request,
- context: EnvelopeDeleteRouteContext,
+ context: EnvelopeDeletionRouteContext,
+ action: "cancel" | "schedule",
) {
const sessionResult = await requireAdminSession(request);
@@ -54,24 +58,31 @@ export async function POST(
return rateLimitResponse;
}
- const body = (await request.json().catch(() => null)) as {
- reason?: unknown;
- } | null;
+ const actor = { email: session.user.email, userId: session.user.id };
+ const userAgent = getRequestUserAgent(request.headers);
try {
- const result = await deleteFinishedEnvelope(
+ if (action === "cancel") {
+ const result = await cancelEnvelopeDeletion(
+ id,
+ { actor, ipAddress, userAgent },
+ { database: getDb() },
+ );
+
+ return NextResponse.json(result, { headers: NO_STORE, status: 200 });
+ }
+
+ const body = (await request.json().catch(() => null)) as {
+ reason?: unknown;
+ } | null;
+ const result = await scheduleEnvelopeDeletion(
id,
- {
- actor: { email: session.user.email, userId: session.user.id },
- ipAddress,
- reason: body?.reason ?? null,
- userAgent: getRequestUserAgent(request.headers),
- },
+ { actor, ipAddress, reason: body?.reason ?? null, userAgent },
{ database: getDb() },
);
return NextResponse.json(
- { ...result, redirectPath: "/dashboard" },
+ { deleteAfter: result.deleteAfter, envelopeId: id },
{ headers: NO_STORE, status: 200 },
);
} catch (error) {
@@ -85,14 +96,33 @@ export async function POST(
logRouteError(error, {
category: "finished_envelope_delete_failure",
ipAddress,
- message: "Unexpected failure while deleting a finished envelope.",
+ message:
+ action === "cancel"
+ ? "Unexpected failure while cancelling an envelope's deletion."
+ : "Unexpected failure while scheduling an envelope's deletion.",
path: getRequestPathname(request),
userId: session.user.id,
});
return NextResponse.json(
- { error: "Unable to delete this envelope." },
+ {
+ error:
+ action === "cancel"
+ ? "Unable to cancel this deletion."
+ : "Unable to schedule this envelope's deletion.",
+ },
{ headers: NO_STORE, status: 500 },
);
}
}
+
+export function POST(request: Request, context: EnvelopeDeletionRouteContext) {
+ return handle(request, context, "schedule");
+}
+
+export function DELETE(
+ request: Request,
+ context: EnvelopeDeletionRouteContext,
+) {
+ return handle(request, context, "cancel");
+}
diff --git a/src/app/api/internal/retention/route.ts b/src/app/api/internal/retention/route.ts
index bcae3a3..5e843c6 100644
--- a/src/app/api/internal/retention/route.ts
+++ b/src/app/api/internal/retention/route.ts
@@ -38,7 +38,11 @@ async function handle(request: Request) {
if (caller === "authorized") {
return NextResponse.json(
outcome.status === "ran"
- ? { ...outcome.summary, schedule: outcome.schedule }
+ ? {
+ ...outcome.summary,
+ deletions: outcome.deletions,
+ schedule: outcome.schedule,
+ }
: outcome,
{ status: failed ? 500 : 200 },
);
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index 52d1b1e..25944cf 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -36,6 +36,14 @@ import {
} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
+/** A finished envelope an administrator has scheduled to be deleted. */
+export type EnvelopeDeletionNotice = {
+ deleteOnLabel: string;
+ /** Shown to administrators only. */
+ reason: string | null;
+ requestedByEmail: string;
+};
+
type EnvelopeDetailShellProps = {
/** An administrator may delete a finished envelope. */
canDeleteFinished?: boolean;
@@ -48,6 +56,7 @@ type EnvelopeDetailShellProps = {
*/
ownerLabel?: string;
record?: EnvelopeDetailData;
+ scheduledDeletion?: EnvelopeDeletionNotice;
};
type EnvelopeStatus = "draft" | "sent" | "completed" | "declined" | "voided";
@@ -82,6 +91,7 @@ type ModalState =
| "change-reminders"
| "copy-draft"
| "correct-signer"
+ | "cancel-deletion"
| "delete-draft"
| "delete-finished"
| "save-template"
@@ -138,6 +148,7 @@ export function EnvelopeDetailShell({
initialState,
ownerLabel,
record,
+ scheduledDeletion,
}: EnvelopeDetailShellProps) {
const isOwnEnvelope = ownerLabel === undefined;
const [activeModal, setActiveModal] = useState<ModalState>(null);
@@ -148,6 +159,7 @@ export function EnvelopeDetailShell({
const [isCorrectingSigner, setIsCorrectingSigner] = useState(false);
const [isDeletingDraft, setIsDeletingDraft] = useState(false);
const [isDeletingFinished, setIsDeletingFinished] = useState(false);
+ const [isCancellingDeletion, setIsCancellingDeletion] = useState(false);
const [deleteReason, setDeleteReason] = useState("");
const [isSendingReminder, setIsSendingReminder] = useState(false);
const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);
@@ -432,37 +444,61 @@ export function EnvelopeDetailShell({
setIsDeletingFinished(true);
try {
- const response = await fetch(`/api/envelopes/${envelopeId}/delete`, {
+ const response = await fetch(`/api/envelopes/${envelopeId}/deletion`, {
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.");
+ setActionError(
+ payload?.error ?? "Unable to schedule this envelope's deletion.",
+ );
return;
}
- // Back to the list it came from.
- window.location.assign(
- isOwnEnvelope
- ? (payload?.redirectPath ?? "/dashboard")
- : "/dashboard?view=all",
- );
+ // The page shows when it will go, and lets it be cancelled.
+ window.location.reload();
} catch {
// The request may or may not have reached the server.
setActionError(
- "Could not reach the server. Reload the page to see whether the envelope was deleted.",
+ "Could not reach the server. Reload the page to see whether the deletion was scheduled.",
);
} finally {
setIsDeletingFinished(false);
}
}
+ async function handleConfirmCancelDeletion() {
+ setActionError(null);
+ setIsCancellingDeletion(true);
+
+ try {
+ const response = await fetch(`/api/envelopes/${envelopeId}/deletion`, {
+ method: "DELETE",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+
+ if (!response.ok) {
+ setActionError(payload?.error ?? "Unable to cancel this deletion.");
+ return;
+ }
+
+ window.location.reload();
+ } catch {
+ setActionError(
+ "Could not reach the server. Reload the page to see whether the deletion was cancelled.",
+ );
+ } finally {
+ setIsCancellingDeletion(false);
+ }
+ }
+
async function handleConfirmVoidEnvelope() {
setActionError(null);
setIsVoidingEnvelope(true);
@@ -642,7 +678,20 @@ export function EnvelopeDetailShell({
</>
) : null}
+ {canDeleteFinished && scheduledDeletion ? (
+ <ShellButton
+ onClick={() => {
+ setActionError(null);
+ setActiveModal("cancel-deletion");
+ }}
+ variant="secondary"
+ >
+ Cancel deletion
+ </ShellButton>
+ ) : null}
+
{canDeleteFinished &&
+ !scheduledDeletion &&
(activeRecord.status === "completed" ||
activeRecord.status === "declined" ||
activeRecord.status === "voided") ? (
@@ -659,6 +708,27 @@ export function EnvelopeDetailShell({
</div>
</div>
+ {scheduledDeletion ? (
+ <div
+ className="mt-4 rounded-xl border border-(--border) bg-(--danger-soft) px-4 py-3 text-sm leading-6 text-(--fg)"
+ role="status"
+ >
+ <p className="font-semibold">
+ Scheduled to be deleted on {scheduledDeletion.deleteOnLabel}
+ </p>
+ <p className="text-(--secondary)">
+ {canDeleteFinished
+ ? `${scheduledDeletion.requestedByEmail} asked for it. Any administrator can cancel until then.`
+ : `An administrator (${scheduledDeletion.requestedByEmail}) asked for it. Download the signed PDF and the certificate before then if you need to keep them.`}
+ </p>
+ {scheduledDeletion.reason ? (
+ <p className="text-(--secondary)">
+ Reason: {scheduledDeletion.reason}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+
{reminderHelperText ? (
<p className="mt-4 text-sm leading-6 text-(--secondary) lg:text-right">
{reminderHelperText}
@@ -990,17 +1060,21 @@ export function EnvelopeDetailShell({
{activeModal === "delete-finished" ? (
<ConfirmationDialog
confirmDisabled={record.part11 && deleteReason.trim().length === 0}
- confirmLabel="Delete envelope"
+ confirmLabel="Schedule deletion"
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.",
+ "The envelope, its signed PDF, its certificate and its audit trail will be deleted for good in 14 days. Download links already sent to signers will stop working then.",
+ ...(isOwnEnvelope
+ ? []
+ : [
+ "Its sender is emailed now, with a link to download what they need to keep.",
+ ]),
+ "Until then any administrator can cancel. The install's audit log records the request, and the deletion with the document's fingerprints.",
]}
errorMessage={actionError}
onCancel={() => setActiveModal(null)}
onConfirm={handleConfirmDeleteFinished}
processing={isDeletingFinished}
- title="Delete this envelope?"
+ title="Schedule this envelope for deletion?"
>
<label className="grid gap-2 text-sm">
<span className="text-[0.8125rem] font-semibold text-(--secondary)">
@@ -1020,6 +1094,23 @@ export function EnvelopeDetailShell({
</ConfirmationDialog>
) : null}
+ {activeModal === "cancel-deletion" ? (
+ <ConfirmationDialog
+ confirmLabel="Cancel deletion"
+ description={[
+ "The envelope stays as it is and will not be deleted.",
+ ...(isOwnEnvelope
+ ? []
+ : ["If its sender was told it would be deleted, they are told it will not."]),
+ ]}
+ errorMessage={actionError}
+ onCancel={() => setActiveModal(null)}
+ onConfirm={handleConfirmCancelDeletion}
+ processing={isCancellingDeletion}
+ title="Cancel this deletion?"
+ />
+ ) : 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 8a602b3..746cad2 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -25,6 +25,8 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
account_deleted: "Account deleted",
email_domain_changed: "Email domain changed",
envelope_deleted: "Finished envelope deleted",
+ envelope_deletion_cancelled: "Envelope deletion cancelled",
+ envelope_deletion_scheduled: "Envelope deletion scheduled",
envelope_file_downloaded: "Another member's file downloaded",
identity_verification_revoked: "Identity confirmation taken back",
identity_verified: "Identity confirmed",
@@ -107,6 +109,20 @@ function describeEvent(event: SystemAuditEvent): string {
]
.filter(Boolean)
.join(", ");
+ case "envelope_deletion_scheduled":
+ case "envelope_deletion_cancelled":
+ return [
+ typeof metadata.title === "string" ? `"${metadata.title}"` : null,
+ typeof metadata.deleteAfter === "number"
+ ? `${event.event === "envelope_deletion_scheduled" ? "to be deleted" : "was due"} on ${new Date(metadata.deleteAfter * 1000).toISOString().slice(0, 10)}`
+ : null,
+ typeof metadata.reason === "string" ? metadata.reason : null,
+ typeof metadata.ownerEmail === "string"
+ ? `sent by ${metadata.ownerEmail}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
case "envelope_file_downloaded":
return [
typeof metadata.file === "string"
diff --git a/src/lib/envelope-access.dbtest.ts b/src/lib/envelope-access.dbtest.ts
index e6b12b8..cd26aff 100644
--- a/src/lib/envelope-access.dbtest.ts
+++ b/src/lib/envelope-access.dbtest.ts
@@ -8,8 +8,8 @@ import { openTestDatabase } from "./db/test-database.ts";
import { resolveEnvelopeViewerAccess } from "./envelope-access.ts";
import { listAllEnvelopesForAdmin, listEnvelopesForUser } from "./envelopes.ts";
-// Who can see an envelope: its sender, and any administrator. Run with
-// `npm run test:db`.
+// Who can see an envelope: its sender, and any administrator once it has
+// been sent. Run with `npm run test:db`.
let database: pg.Pool;
const createdUsers: string[] = [];
@@ -38,22 +38,28 @@ async function createUser(role: "admin" | "user", name: string) {
return { email, name, userId: id };
}
-async function createEnvelope(userId: string, title: string) {
+async function createEnvelope(
+ userId: string,
+ title: string,
+ status: "draft" | "sent" = "sent",
+) {
const envelopeId = 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
- ) values ($1, $2, $3, 'draft', $4, 'doc.pdf', 4, 1, $5)
+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at
+ ) values ($1, $2, $3, $4, $5, 'doc.pdf', 4, 1, $6, $7)
`,
[
envelopeId,
userId,
title,
+ status,
`users/${userId}/envelopes/${envelopeId}/source.pdf`,
"a".repeat(64),
+ status === "draft" ? null : Math.floor(Date.now() / 1000),
],
);
@@ -112,7 +118,7 @@ test("an administrator's list of every envelope names each sender", async () =>
const firstEnvelope = await createEnvelope(first.userId, "First lease");
const secondEnvelope = await createEnvelope(second.userId, "Second lease");
- const all = await listAllEnvelopesForAdmin({ limit: 100 }, database);
+ const all = await listAllEnvelopesForAdmin(second.userId, { limit: 100 }, database);
const byId = new Map(
all.envelopes.map((envelope) => [envelope.id, envelope]),
);
@@ -172,6 +178,7 @@ test("searching every envelope finds a sender by name or address", async () => {
for (const search of ["quentin quarry", sender.email.slice(0, 12)]) {
const result = await listAllEnvelopesForAdmin(
+ sender.userId,
{ limit: 100, search },
database,
);
@@ -191,3 +198,38 @@ test("searching every envelope finds a sender by name or address", async () => {
assert.deepEqual(own.envelopes, []);
});
+
+test("another member's draft stays theirs: an administrator neither lists nor opens it", async () => {
+ const sender = await createUser("user", "Dana Drafter");
+ const admin = await createUser("admin", "Avery Admin");
+ const draftId = await createEnvelope(sender.userId, "Unsent lease", "draft");
+ const sentId = await createEnvelope(sender.userId, "Sent lease");
+ const ownDraftId = await createEnvelope(admin.userId, "Own draft", "draft");
+
+ assert.equal(
+ await resolveEnvelopeViewerAccess(admin.userId, draftId, database),
+ null,
+ );
+ assert.ok(await resolveEnvelopeViewerAccess(admin.userId, sentId, database));
+ // The sender still sees it.
+ assert.ok(await resolveEnvelopeViewerAccess(sender.userId, draftId, database));
+
+ const all = await listAllEnvelopesForAdmin(
+ admin.userId,
+ { limit: 100, search: "lease" },
+ database,
+ );
+ const ids = all.envelopes.map((envelope) => envelope.id);
+
+ assert.ok(ids.includes(sentId));
+ assert.ok(!ids.includes(draftId));
+
+ // An administrator's own drafts are still in everyone's list.
+ const own = await listAllEnvelopesForAdmin(
+ admin.userId,
+ { limit: 100, search: "own draft" },
+ database,
+ );
+
+ assert.ok(own.envelopes.some((envelope) => envelope.id === ownDraftId));
+});
diff --git a/src/lib/envelope-access.ts b/src/lib/envelope-access.ts
index b5f9f47..1bade26 100644
--- a/src/lib/envelope-access.ts
+++ b/src/lib/envelope-access.ts
@@ -1,9 +1,10 @@
import { type DbExecutor, getDb, queryOne } from "./db/connection.ts";
// Whose envelope a signed-in account is looking at. Its sender sees it, as
-// before; an administrator sees every envelope in the install, to read,
-// download and, once it is finished, delete. Everything else that changes
-// an envelope (sending, voiding, reminders, editing) stays with its sender.
+// before; an administrator sees every envelope in the install that has
+// been sent, to read, download and, once it is finished, delete. A draft
+// stays its sender's own until it is sent. Everything else that changes an
+// envelope (sending, voiding, reminders, editing) stays with its sender.
export type EnvelopeViewerAccess = {
ownerEmail: string;
@@ -17,6 +18,7 @@ type AccessRow = {
ownerEmail: string;
ownerName: string | null;
ownerUserId: string;
+ status: string;
viewerRole: string | null;
};
@@ -37,6 +39,7 @@ export async function resolveEnvelopeViewerAccess(
e.user_id AS "ownerUserId",
owner.email AS "ownerEmail",
owner.name AS "ownerName",
+ e.status,
(SELECT role FROM public."user" WHERE id = $2) AS "viewerRole"
FROM envelopes e
JOIN public."user" owner ON owner.id = e.user_id
@@ -51,7 +54,9 @@ export async function resolveEnvelopeViewerAccess(
const viewerIsOwner = row.ownerUserId === viewerUserId;
- if (!viewerIsOwner && row.viewerRole !== "admin") {
+ // Someone else's envelope only for an administrator, and never their
+ // draft.
+ if (!viewerIsOwner && (row.viewerRole !== "admin" || row.status === "draft")) {
return null;
}
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.ts
index a2fbb1e..fc7bc68 100644
--- a/src/lib/envelope-deletion.dbtest.ts
+++ b/src/lib/envelope-deletion.dbtest.ts
@@ -9,13 +9,24 @@ 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 {
+ cancelEnvelopeDeletion,
+ deleteScheduledEnvelope,
+ ENVELOPE_DELETION_WAIT_DAYS,
+ getScheduledEnvelopeDeletion,
+ runScheduledEnvelopeDeletions,
+ scheduleEnvelopeDeletion,
+} from "./envelope-deletion.ts";
import { EnvelopeMutationError } from "./envelopes.ts";
import {
deletePendingFiles,
queueFileDeletions,
runRetentionSweep,
} from "./retention.ts";
+import type {
+ EmailService,
+ TransactionalEmailMessage,
+} from "./services/email.ts";
import { getRecipientCertificateKey } from "./services/storage-keys.ts";
import {
createStorageService,
@@ -26,8 +37,9 @@ import {
verifySystemAuditChain,
} from "./services/system-audit.ts";
-// An administrator deleting a finished envelope by hand, against a real
-// Postgres. Run with `npm run test:db`.
+// An administrator scheduling a finished envelope's deletion, cancelling
+// it, and the daily cleanup deleting it once the wait is over, against a
+// real Postgres. Run with `npm run test:db`.
const SOURCE_HASH = "a".repeat(64);
const SIGNED_HASH = "b".repeat(64);
@@ -35,6 +47,8 @@ const EVIDENCE_HASH = "c".repeat(64);
const RECIPIENT_EVIDENCE_HASH = "d".repeat(64);
// The install audit trail's lock (services/system-audit.ts).
const SYSTEM_AUDIT_LOCK_ID = 746108325;
+const DAY = 24 * 60 * 60;
+const WAIT = ENVELOPE_DELETION_WAIT_DAYS * DAY;
let database: pg.Pool;
let storageDir: string;
@@ -175,51 +189,124 @@ async function filesExist(keys: readonly string[]) {
);
}
-function deleteAs(
+let sent: TransactionalEmailMessage[] = [];
+
+function createOutbox(fail = false): EmailService {
+ return {
+ async send(message) {
+ if (fail) {
+ throw new Error("Email is down.");
+ }
+
+ sent.push(message);
+ return { accepted: [message.to], rejected: [] };
+ },
+ async sendBatch(messages) {
+ return Promise.all(messages.map((message) => this.send(message)));
+ },
+ };
+}
+
+function emailsTo(address: string) {
+ return sent.filter((message) => message.to === address);
+}
+
+function scheduleAs(
actor: { email: string; userId: string },
envelopeId: string,
- reason?: string,
+ reason?: unknown,
+ { emailService = createOutbox(), now = Math.floor(Date.now() / 1000) } = {},
) {
- return deleteFinishedEnvelope(
+ return scheduleEnvelopeDeletion(
envelopeId,
{ actor, ipAddress: "203.0.113.9", reason, userAgent: "Test browser" },
- { database, storageService },
+ { database, emailService, now },
+ );
+}
+
+function cancelAs(actor: { email: string; userId: string }, envelopeId: string) {
+ return cancelEnvelopeDeletion(
+ envelopeId,
+ { actor, ipAddress: "203.0.113.9", userAgent: "Test browser" },
+ { database, emailService: createOutbox() },
);
}
+function deleteWhenDue(
+ envelopeId: string,
+ now: number,
+ storage: StorageService = storageService,
+) {
+ return deleteScheduledEnvelope(envelopeId, {
+ database,
+ now,
+ storageService: storage,
+ });
+}
+
function rejectsWith(statusCode: number) {
return (error: unknown) =>
error instanceof EnvelopeMutationError && error.statusCode === statusCode;
}
+async function latestEvent() {
+ const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+
+ return event;
+}
+
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 () => {
+ test(`a ${status} envelope is scheduled, waits ${String(ENVELOPE_DELETION_WAIT_DAYS)} days, then goes with its files, all on record`, async () => {
const admin = await createUser("admin");
const envelope = await createEnvelope(admin.userId, { status });
+ const now = Math.floor(Date.now() / 1000);
+
+ const scheduled = await scheduleAs(
+ admin,
+ envelope.envelopeId,
+ "Kept long enough.",
+ { now },
+ );
+ assert.equal(scheduled.deleteAfter, now + WAIT);
+ // Nothing goes yet.
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
assert.ok((await filesExist(envelope.stored)).every(Boolean));
- await deleteAs(admin, envelope.envelopeId, "Kept long enough.");
+ const request = await latestEvent();
+
+ assert.equal(request?.event, "envelope_deletion_scheduled");
+ assert.equal(request?.actorUserId, admin.userId);
+ assert.equal(request?.ipAddress, "203.0.113.9");
+ assert.equal(request?.metadata?.deleteAfter, now + WAIT);
+ assert.equal(request?.metadata?.reason, "Kept long enough.");
+ // A day early, still nothing.
+ assert.equal(await deleteWhenDue(envelope.envelopeId, now + WAIT - DAY), false);
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+
+ assert.equal(await deleteWhenDue(envelope.envelopeId, now + WAIT), true);
assert.equal(await envelopeExists(envelope.envelopeId), false);
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
assert.deepEqual(
await filesExist(envelope.stored),
envelope.stored.map(() => false),
);
assert.deepEqual(await pendingFileDeletions(envelope.envelopeId), []);
- const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+ const event = await latestEvent();
assert.equal(event?.event, "envelope_deleted");
+ // Under the administrator who asked for it.
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,
recipientEvidenceSha256: event?.metadata?.recipientEvidenceSha256,
+ requestedAt: event?.metadata?.requestedAt,
sourcePdfHash: event?.metadata?.sourcePdfHash,
status: event?.metadata?.status,
title: event?.metadata?.title,
@@ -229,6 +316,7 @@ for (const status of ["completed", "declined", "voided"] as const) {
evidenceSha256: EVIDENCE_HASH,
reason: "Kept long enough.",
recipientEvidenceSha256: RECIPIENT_EVIDENCE_HASH,
+ requestedAt: now,
sourcePdfHash: SOURCE_HASH,
status,
title: "Lease",
@@ -238,88 +326,150 @@ for (const status of ["completed", "declined", "voided"] as const) {
});
}
-test("someone who is not an administrator cannot delete a finished envelope", async () => {
+test("someone who is not an administrator cannot schedule a deletion", 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));
+ await assert.rejects(scheduleAs(user, envelope.envelopeId), rejectsWith(403));
- assert.equal(await envelopeExists(envelope.envelopeId), true);
- assert.ok((await filesExist(envelope.stored)).every(Boolean));
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
assert.deepEqual(await listSystemAuditEvents({ limit: 1 }, database), before);
});
-test("an envelope still out for signature, or a draft, is not deleted this way", async () => {
+test("an envelope still out for signature, or a draft, is not scheduled", 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),
+ scheduleAs(admin, envelope.envelopeId),
rejectsWith(409),
);
- assert.equal(await envelopeExists(envelope.envelopeId), true);
- assert.ok((await filesExist(envelope.stored)).every(Boolean));
+ assert.equal(
+ await getScheduledEnvelopeDeletion(envelope.envelopeId, database),
+ null,
+ );
}
});
-test("an administrator deletes another member's finished envelope, and the record names its sender", async () => {
+test("another member's envelope: its sender is emailed, and the records name them", async () => {
+ sent = [];
const owner = await createUser("user");
const admin = await createUser("admin");
const envelope = await createEnvelope(owner.userId, { status: "completed" });
+ const now = Math.floor(Date.now() / 1000);
- await deleteAs(admin, envelope.envelopeId, "Asked to by legal.");
+ await scheduleAs(admin, envelope.envelopeId, "Asked to by legal.", { now });
- assert.equal(await envelopeExists(envelope.envelopeId), false);
- assert.deepEqual(
- await filesExist(envelope.stored),
- envelope.stored.map(() => false),
- );
+ const [notice] = emailsTo(owner.email);
- const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+ assert.equal(notice?.template, "deletion_notice");
+ assert.match(notice?.subject ?? "", /^"Lease" will be deleted on \d{4}-\d{2}-\d{2}$/);
+ assert.match(notice?.textBody ?? "", new RegExp(admin.email.replace(/[.]/g, "\\.")));
+ // The reason is for administrators.
+ assert.doesNotMatch(notice?.textBody ?? "", /legal/);
+
+ const request = await latestEvent();
+
+ assert.equal(request?.targetUserId, owner.userId);
+ assert.equal(request?.metadata?.ownerEmail, owner.email);
+
+ await deleteWhenDue(envelope.envelopeId, now + WAIT);
+
+ const event = await latestEvent();
assert.equal(event?.event, "envelope_deleted");
assert.equal(event?.actorUserId, admin.userId);
assert.equal(event?.metadata?.ownerUserId, owner.userId);
assert.equal(event?.metadata?.ownerEmail, owner.email);
assert.equal(event?.metadata?.reason, "Asked to by legal.");
+ assert.equal(event?.metadata?.senderNotified, true);
+});
+
+test("an administrator's own envelope sends no email", async () => {
+ sent = [];
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status: "completed" });
+
+ await scheduleAs(admin, envelope.envelopeId);
+
+ assert.deepEqual(emailsTo(admin.email), []);
});
-test("someone who is not an administrator cannot find another member's envelope to delete", async () => {
+test("someone who is not an administrator cannot find another member's envelope", async () => {
const owner = await createUser("admin");
const other = await createUser("user");
const envelope = await createEnvelope(owner.userId, { status: "completed" });
- await assert.rejects(deleteAs(other, envelope.envelopeId), rejectsWith(404));
- assert.equal(await envelopeExists(envelope.envelopeId), true);
+ await assert.rejects(scheduleAs(other, envelope.envelopeId), rejectsWith(404));
+ await assert.rejects(cancelAs(other, envelope.envelopeId), rejectsWith(404));
+ await assert.rejects(scheduleAs(owner, randomUUID()), rejectsWith(404));
});
-test("an envelope that does not exist is not found", async () => {
+test("a deletion already scheduled is not scheduled twice", async () => {
const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status: "completed" });
- await assert.rejects(deleteAs(admin, randomUUID()), rejectsWith(404));
+ await scheduleAs(admin, envelope.envelopeId);
+ await assert.rejects(scheduleAs(admin, envelope.envelopeId), rejectsWith(409));
});
-test("a Part 11 record needs a reason before it is deleted", async () => {
+test("any administrator can cancel, the sender is told, and nothing is deleted", async () => {
+ sent = [];
+ const owner = await createUser("user");
+ const admin = await createUser("admin");
+ const otherAdmin = await createUser("admin");
+ const envelope = await createEnvelope(owner.userId, { status: "completed" });
+ const now = Math.floor(Date.now() / 1000);
+
+ await scheduleAs(admin, envelope.envelopeId, "Tidying up.", { now });
+ await cancelAs(otherAdmin, envelope.envelopeId);
+
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
+
+ const event = await latestEvent();
+
+ assert.equal(event?.event, "envelope_deletion_cancelled");
+ assert.equal(event?.actorUserId, otherAdmin.userId);
+ assert.equal(event?.metadata?.requestedByEmail, admin.email);
+ assert.deepEqual(
+ emailsTo(owner.email).map((message) => message.subject),
+ ['"Lease" will be deleted on ' + new Date((now + WAIT) * 1000).toISOString().slice(0, 10), '"Lease" will not be deleted'],
+ );
+
+ // The day it would have gone, it stays.
+ assert.equal(await deleteWhenDue(envelope.envelopeId, now + WAIT), false);
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.ok((await filesExist(envelope.stored)).every(Boolean));
+
+ // Nothing left to cancel; a member cannot cancel at all.
+ await assert.rejects(cancelAs(admin, envelope.envelopeId), rejectsWith(409));
+ await assert.rejects(cancelAs(owner, envelope.envelopeId), rejectsWith(403));
+ await assert.rejects(scheduleAs(owner, envelope.envelopeId), rejectsWith(403));
+});
+
+test("a Part 11 record needs a reason before it is scheduled", async () => {
const admin = await createUser("admin");
const envelope = await createEnvelope(admin.userId, {
part11: true,
status: "completed",
});
+ const now = Math.floor(Date.now() / 1000);
await assert.rejects(
- deleteAs(admin, envelope.envelopeId, " "),
+ scheduleAs(admin, envelope.envelopeId, " "),
rejectsWith(400),
);
- assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
- await deleteAs(admin, envelope.envelopeId, "Retention period over.");
+ await scheduleAs(admin, envelope.envelopeId, "Retention period over.", { now });
+ await deleteWhenDue(envelope.envelopeId, now + WAIT);
assert.equal(await envelopeExists(envelope.envelopeId), false);
- const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+ const event = await latestEvent();
assert.equal(event?.metadata?.part11, true);
assert.equal(event?.metadata?.reason, "Retention period over.");
@@ -329,24 +479,72 @@ 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(scheduleAs(admin, envelope.envelopeId, 42), rejectsWith(400));
await assert.rejects(
- deleteFinishedEnvelope(
- envelope.envelopeId,
- { actor: admin, reason: 42 },
- { database, storageService },
- ),
- rejectsWith(400),
- );
- await assert.rejects(
- deleteAs(admin, envelope.envelopeId, "x".repeat(1001)),
+ scheduleAs(admin, envelope.envelopeId, "x".repeat(1001)),
rejectsWith(400),
);
- assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
+});
+
+test("when the email to the sender fails, the deletion is still scheduled and the daily run sends it", async () => {
+ sent = [];
+ const owner = await createUser("user");
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(owner.userId, { status: "declined" });
+ const now = Math.floor(Date.now() / 1000);
+ const originalConsoleError = console.error;
+
+ console.error = () => {};
+
+ try {
+ await scheduleAs(admin, envelope.envelopeId, undefined, {
+ emailService: createOutbox(true),
+ now,
+ });
+ } finally {
+ console.error = originalConsoleError;
+ }
+
+ assert.ok(await getScheduledEnvelopeDeletion(envelope.envelopeId, database));
+ assert.deepEqual(emailsTo(owner.email), []);
+
+ const summary = await runScheduledEnvelopeDeletions({
+ database,
+ emailService: createOutbox(),
+ now: now + DAY,
+ storageService,
+ });
+
+ assert.ok(summary.noticesSent >= 1);
+ assert.equal(emailsTo(owner.email).length, 1);
+
+ // Told once: the next run does not send it again.
+ await runScheduledEnvelopeDeletions({
+ database,
+ emailService: createOutbox(),
+ now: now + 2 * DAY,
+ storageService,
+ });
+ assert.equal(emailsTo(owner.email).length, 1);
+
+ // And once the wait is over, the run deletes it.
+ const final = await runScheduledEnvelopeDeletions({
+ database,
+ emailService: createOutbox(),
+ now: now + WAIT,
+ storageService,
+ });
+
+ assert.ok(final.deleted >= 1);
+ assert.deepEqual(final.failures, []);
+ assert.equal(await envelopeExists(envelope.envelopeId), false);
});
test("when a file cannot be deleted, the envelope is still deleted and recorded, and the next cleanup deletes the file", async () => {
const admin = await createUser("admin");
const envelope = await createEnvelope(admin.userId, { status: "completed" });
+ const now = Math.floor(Date.now() / 1000);
const failingStorage = {
...storageService,
deleteObject: async () => {
@@ -356,23 +554,21 @@ test("when a file cannot be deleted, the envelope is still deleted and recorded,
const logged: unknown[][] = [];
const originalConsoleError = console.error;
+ await scheduleAs(admin, envelope.envelopeId, undefined, { now });
+
console.error = (...args: unknown[]) => {
logged.push(args);
};
try {
- await deleteFinishedEnvelope(
- envelope.envelopeId,
- { actor: admin },
- { database, storageService: failingStorage },
- );
+ await deleteWhenDue(envelope.envelopeId, now + WAIT, failingStorage);
} finally {
console.error = originalConsoleError;
}
assert.equal(await envelopeExists(envelope.envelopeId), false);
- const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+ const event = await latestEvent();
assert.equal(event?.event, "envelope_deleted");
assert.equal(event?.metadata?.envelopeId, envelope.envelopeId);
@@ -399,12 +595,10 @@ test("when a file cannot be deleted, the envelope is still deleted and recorded,
assert.deepEqual(await pendingFileDeletions(envelope.envelopeId), []);
});
-test("when the deletion fails before it commits, no file is touched", async () => {
+test("a deletion that is not due touches no file", async () => {
const admin = await createUser("admin");
- const envelope = await createEnvelope(admin.userId, {
- part11: true,
- status: "completed",
- });
+ const envelope = await createEnvelope(admin.userId, { status: "completed" });
+ const now = Math.floor(Date.now() / 1000);
let deletes = 0;
const countingStorage = {
...storageService,
@@ -414,14 +608,10 @@ test("when the deletion fails before it commits, no file is touched", async () =
},
} as StorageService;
- await assert.rejects(
- deleteFinishedEnvelope(
- envelope.envelopeId,
- { actor: admin },
- { database, storageService: countingStorage },
- ),
- rejectsWith(400),
- );
+ // Not scheduled at all, then scheduled but not due.
+ assert.equal(await deleteWhenDue(envelope.envelopeId, now + WAIT, countingStorage), false);
+ await scheduleAs(admin, envelope.envelopeId, undefined, { now });
+ assert.equal(await deleteWhenDue(envelope.envelopeId, now, countingStorage), false);
assert.equal(deletes, 0);
assert.equal(await envelopeExists(envelope.envelopeId), true);
assert.ok((await filesExist(envelope.stored)).every(Boolean));
@@ -440,7 +630,7 @@ test("an administrator whose role is being taken away waits for it, and is then
[admin.userId],
);
- const deletion = deleteAs(admin, envelope.envelopeId, "Done.");
+ const scheduling = scheduleAs(admin, envelope.envelopeId, "Done.");
await delay(300);
await demotion.query(
@@ -449,16 +639,15 @@ test("an administrator whose role is being taken away waits for it, and is then
);
await demotion.query("commit");
- await assert.rejects(deletion, rejectsWith(403));
+ await assert.rejects(scheduling, rejectsWith(403));
} finally {
demotion.release();
}
- assert.equal(await envelopeExists(envelope.envelopeId), true);
- assert.ok((await filesExist(envelope.stored)).every(Boolean));
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
});
-test("a deletion running while the administrator's handed-over envelopes move does not deadlock", async () => {
+test("a request running while the administrator's handed-over envelopes move does not deadlock", async () => {
const admin = await createUser("admin");
const keeper = await createUser("admin");
const envelope = await createEnvelope(admin.userId, { status: "completed" });
@@ -480,7 +669,7 @@ test("a deletion running while the administrator's handed-over envelopes move do
SYSTEM_AUDIT_LOCK_ID,
]);
- const deletion = deleteAs(admin, envelope.envelopeId, "Done.");
+ const scheduling = scheduleAs(admin, envelope.envelopeId, "Done.");
await delay(300);
await demotion.query(`update envelopes set user_id = $1 where id = $2`, [
@@ -489,13 +678,28 @@ test("a deletion running while the administrator's handed-over envelopes move do
]);
await demotion.query("commit");
- // It moved while the deletion waited: told to look again.
- await assert.rejects(deletion, rejectsWith(409));
+ // It moved while the request waited: told to look again.
+ await assert.rejects(scheduling, rejectsWith(409));
} finally {
demotion.release();
}
- assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.equal(await getScheduledEnvelopeDeletion(envelope.envelopeId, database), null);
+});
+
+test("a scheduled deletion still runs after the administrator who asked loses the role", async () => {
+ const admin = await createUser("admin");
+ const keeper = await createUser("admin");
+ const envelope = await createEnvelope(keeper.userId, { status: "completed" });
+ const now = Math.floor(Date.now() / 1000);
+
+ await scheduleAs(admin, envelope.envelopeId, "Asked for.", { now });
+ await database.query(`update public."user" set role = 'user' where id = $1`, [
+ admin.userId,
+ ]);
+
+ assert.equal(await deleteWhenDue(envelope.envelopeId, now + WAIT), true);
+ assert.equal(await envelopeExists(envelope.envelopeId), false);
});
test("a file that keeps failing goes to the back of the queue, so the others are still reached", async () => {
diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.ts
index 31a2d37..e25ddf7 100644
--- a/src/lib/envelope-deletion.ts
+++ b/src/lib/envelope-deletion.ts
@@ -1,6 +1,8 @@
import {
+ type DbExecutor,
type DbPool,
getDb,
+ queryMany,
queryOne,
withTransaction,
} from "./db/connection.ts";
@@ -10,23 +12,35 @@ import {
listEnvelopeStorageKeys,
queueFileDeletions,
} from "./retention.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
import {
createStorageService,
type StorageService,
} from "./services/storage.ts";
import { recordSystemAuditEvent } from "./services/system-audit.ts";
+import { resolveAppUrl } from "./utils/env.ts";
-// An administrator may delete any finished envelope by hand, their own or
-// another member's: 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, whose it was, by whom and why stays in the
-// install's audit trail, with the fingerprints the certificate gave, so the
-// deletion itself is on record.
+// An administrator may delete any finished envelope, their own or another
+// member's, but not at once. Asking schedules it: the envelope stays as it
+// is for ENVELOPE_DELETION_WAIT_DAYS, its sender is emailed a link to
+// download it, and any administrator can cancel until then. The daily
+// cleanup then deletes the signed PDF, the certificates, the fields and the
+// envelope's own audit trail, as the retention period does. Asking,
+// cancelling and the deletion itself all stay in the install's audit
+// trail, the last with the fingerprints the certificate gave.
const FINISHED_STATUSES = ["completed", "declined", "voided"] as const;
export const ENVELOPE_DELETION_REASON_MAX_LENGTH = 1000;
+/** How long a scheduled deletion waits, so it can be cancelled. */
+export const ENVELOPE_DELETION_WAIT_DAYS = 14;
+
+const DAY_IN_SECONDS = 24 * 60 * 60;
+
+/** How many due deletions, and sender notices, one daily run handles. */
+const SCHEDULED_DELETIONS_PER_RUN = 100;
+
type FinishedEnvelopeRow = {
evidenceSha256: string | null;
finishedAt: number | null;
@@ -40,13 +54,39 @@ type FinishedEnvelopeRow = {
title: string;
};
-export type FinishedEnvelopeDeletion = {
+type OwnerRow = { email: string; name: string | null; role: string };
+
+type ScheduleRow = {
+ deleteAfter: number;
+ reason: string | null;
+ requestedAt: number;
+ requestedByEmail: string;
+ requestedByUserId: string;
+ senderNotifiedAt: number | null;
+};
+
+export type ScheduledEnvelopeDeletion = {
+ deleteAfter: number;
+ reason: string | null;
+ requestedAt: number;
+ requestedByEmail: string;
+};
+
+export type EnvelopeDeletionRequest = {
actor: { email: string; userId: string };
ipAddress?: string | null;
reason?: unknown;
userAgent?: string | null;
};
+function currentTime(): number {
+ return Math.floor(Date.now() / 1000);
+}
+
+function formatDay(timestamp: number): string {
+ return new Date(timestamp * 1000).toISOString().slice(0, 10);
+}
+
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);
@@ -72,178 +112,617 @@ function parseReason(reason: unknown, part11: boolean): string | null {
}
/**
- * Deletes a completed, declined or voided envelope, the administrator's own
- * or another member's, with its files, and records the deletion in the
- * install's audit trail.
+ * Locks a finished envelope for an administrator, or for the daily cleanup
+ * when `actorUserId` is null, in the one order everything here uses.
+ *
+ * The account rows come before the envelope row: the sender's, then the
+ * administrator's. Taking away a role, and closing an account, hold that
+ * account's row (FOR UPDATE) before they take the audit trail lock and
+ * move its envelopes, so the two wait in turn here instead of each holding
+ * what the other needs. Read under these locks, the administrator's role is
+ * the one in force: a change since the page loaded is honored. The
+ * envelope row comes next, then the install's audit trail lock.
+ */
+async function lockFinishedEnvelope(
+ tx: DbExecutor,
+ envelopeId: string,
+ actorUserId: string | null,
+): Promise<{ envelope: FinishedEnvelopeRow; owner: OwnerRow | null }> {
+ // Whose envelope it is, read first without a lock, so that the sender's
+ // account row can be taken before the envelope row.
+ const located = await queryOne<{ ownerUserId: string }>(
+ tx,
+ `SELECT user_id AS "ownerUserId" FROM envelopes WHERE id = $1`,
+ [envelopeId],
+ );
+
+ if (!located) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ const owner = await queryOne<OwnerRow>(
+ tx,
+ `SELECT email, name, role FROM public."user" WHERE id = $1 FOR SHARE`,
+ [located.ownerUserId],
+ );
+ let actorIsAdmin = true;
+
+ if (actorUserId !== null) {
+ const actorIsOwner = located.ownerUserId === actorUserId;
+ const actorRole = actorIsOwner
+ ? owner
+ : await queryOne<{ role: string }>(
+ tx,
+ `SELECT role FROM public."user" WHERE id = $1 FOR SHARE`,
+ [actorUserId],
+ );
+
+ actorIsAdmin = actorRole?.role === "admin";
+
+ // Someone else's envelope is not there for anyone but an
+ // administrator.
+ if (!actorIsOwner && !actorIsAdmin) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+ }
+
+ const envelope = await queryOne<FinishedEnvelopeRow>(
+ tx,
+ `
+ SELECT
+ id,
+ user_id AS "ownerUserId",
+ title,
+ status,
+ part11,
+ source_pdf_hash AS "sourcePdfHash",
+ signed_pdf_sha256 AS "signedPdfSha256",
+ evidence_sha256 AS "evidenceSha256",
+ recipient_evidence_sha256 AS "recipientEvidenceSha256",
+ COALESCE(completed_at, declined_at, voided_at) AS "finishedAt"
+ FROM envelopes
+ WHERE id = $1
+ FOR UPDATE
+ `,
+ [envelopeId],
+ );
+
+ if (!envelope) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (envelope.ownerUserId !== located.ownerUserId) {
+ // Handed to another administrator in the moment between.
+ throw new EnvelopeMutationError(
+ "This envelope just moved to another account. Reload the page and try again.",
+ 409,
+ );
+ }
+
+ 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,
+ );
+ }
+
+ if (!actorIsAdmin) {
+ throw new EnvelopeMutationError(
+ "Only an administrator can delete a finished envelope.",
+ 403,
+ );
+ }
+
+ return { envelope, owner };
+}
+
+const SCHEDULE_COLUMNS = `
+ requested_by_user_id AS "requestedByUserId",
+ requested_by_email AS "requestedByEmail",
+ requested_at AS "requestedAt",
+ delete_after AS "deleteAfter",
+ reason,
+ sender_notified_at AS "senderNotifiedAt"
+`;
+
+/** The deletion scheduled for an envelope, if there is one. */
+export async function getScheduledEnvelopeDeletion(
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+): Promise<ScheduledEnvelopeDeletion | null> {
+ const row = await queryOne<ScheduleRow>(
+ database,
+ `SELECT ${SCHEDULE_COLUMNS} FROM scheduled_envelope_deletions WHERE envelope_id = $1`,
+ [envelopeId],
+ );
+
+ return row
+ ? {
+ deleteAfter: row.deleteAfter,
+ reason: row.reason,
+ requestedAt: row.requestedAt,
+ requestedByEmail: row.requestedByEmail,
+ }
+ : null;
+}
+
+function envelopeLink(envelopeId: string): string | null {
+ const appUrl = resolveAppUrl();
+
+ return appUrl ? `${appUrl}/envelopes/${envelopeId}` : null;
+}
+
+/** Tells the sender that their envelope will be deleted, and when. */
+async function sendDeletionNotice(
+ {
+ deleteAfter,
+ envelopeId,
+ ownerEmail,
+ ownerName,
+ requestedAt,
+ requestedByEmail,
+ title,
+ }: {
+ deleteAfter: number;
+ envelopeId: string;
+ ownerEmail: string;
+ ownerName: string | null;
+ requestedAt: number;
+ requestedByEmail: string;
+ title: string;
+ },
+ database: DbExecutor,
+ emailService: EmailService,
+): Promise<void> {
+ const link = envelopeLink(envelopeId);
+
+ await emailService.send(
+ {
+ subject: `"${title}" will be deleted on ${formatDay(deleteAfter)}`,
+ template: "deletion_notice",
+ textBody: [
+ `Hello ${ownerName?.trim() || ownerEmail},`,
+ "",
+ `An administrator of your organization (${requestedByEmail}) has scheduled "${title}" and its audit trail to be deleted on or after ${formatDay(deleteAfter)}.`,
+ "",
+ "Download the signed PDF and the certificate before then if you need to keep them. If this is a mistake, ask an administrator: they can cancel it until that day.",
+ ...(link ? ["", link] : []),
+ ].join("\n"),
+ to: ownerEmail,
+ },
+ { idempotencyKey: `deletion-notice/${envelopeId}/${String(requestedAt)}` },
+ );
+
+ await database.query(
+ `
+ UPDATE scheduled_envelope_deletions
+ SET sender_notified_at = $1
+ WHERE envelope_id = $2 AND requested_at = $3
+ `,
+ [currentTime(), envelopeId, requestedAt],
+ );
+}
+
+/**
+ * Schedules a completed, declined or voided envelope, the administrator's
+ * own or another member's, to be deleted once the waiting period is over,
+ * and emails its sender a link to download it.
*/
-export async function deleteFinishedEnvelope(
+export async function scheduleEnvelopeDeletion(
+ envelopeId: string,
+ { actor, ipAddress = null, reason, userAgent = null }: EnvelopeDeletionRequest,
+ {
+ database = getDb(),
+ emailService,
+ now = currentTime(),
+ }: {
+ database?: DbPool;
+ emailService?: EmailService;
+ now?: number;
+ } = {},
+): Promise<ScheduledEnvelopeDeletion> {
+ const deleteAfter = now + ENVELOPE_DELETION_WAIT_DAYS * DAY_IN_SECONDS;
+ const scheduled = await withTransaction(async (tx) => {
+ const { envelope, owner } = await lockFinishedEnvelope(
+ tx,
+ envelopeId,
+ actor.userId,
+ );
+ const deletionReason = parseReason(reason, envelope.part11);
+ const senderIsActor = envelope.ownerUserId === actor.userId;
+ const inserted = await tx.query(
+ `
+ INSERT INTO scheduled_envelope_deletions (
+ envelope_id, requested_by_user_id, requested_by_email,
+ requested_at, delete_after, reason, sender_notified_at
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7)
+ ON CONFLICT (envelope_id) DO NOTHING
+ `,
+ [
+ envelope.id,
+ actor.userId,
+ actor.email,
+ now,
+ deleteAfter,
+ deletionReason,
+ // Nobody to tell when the sender asked themselves.
+ senderIsActor ? now : null,
+ ],
+ );
+
+ if (inserted.rowCount !== 1) {
+ throw new EnvelopeMutationError(
+ "This envelope is already scheduled to be deleted.",
+ 409,
+ );
+ }
+
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "envelope_deletion_scheduled",
+ ipAddress,
+ metadata: {
+ deleteAfter,
+ envelopeId: envelope.id,
+ ownerEmail: owner?.email ?? null,
+ ownerUserId: envelope.ownerUserId,
+ part11: envelope.part11,
+ reason: deletionReason,
+ status: envelope.status,
+ title: envelope.title,
+ },
+ targetUserId: envelope.ownerUserId,
+ userAgent,
+ },
+ tx,
+ );
+
+ return {
+ notice:
+ !senderIsActor && owner
+ ? {
+ deleteAfter,
+ envelopeId: envelope.id,
+ ownerEmail: owner.email,
+ ownerName: owner.name,
+ requestedAt: now,
+ requestedByEmail: actor.email,
+ title: envelope.title,
+ }
+ : null,
+ reason: deletionReason,
+ };
+ }, database);
+
+ // The schedule stands whatever happens to the email; the daily cleanup
+ // tries again until it goes out.
+ if (scheduled.notice) {
+ try {
+ await sendDeletionNotice(
+ scheduled.notice,
+ database,
+ emailService ?? createEmailService(),
+ );
+ } catch (error) {
+ console.error(
+ `Telling the sender about the deletion of envelope ${envelopeId} failed:`,
+ error,
+ );
+ }
+ }
+
+ return {
+ deleteAfter,
+ reason: scheduled.reason,
+ requestedAt: now,
+ requestedByEmail: actor.email,
+ };
+}
+
+/**
+ * Cancels a scheduled deletion. Any administrator may, whoever asked for
+ * it. A sender who was told it would go is told it will not.
+ */
+export async function cancelEnvelopeDeletion(
envelopeId: string,
{
actor,
ipAddress = null,
- reason,
userAgent = null,
- }: FinishedEnvelopeDeletion,
+ }: Omit<EnvelopeDeletionRequest, "reason">,
{
database = getDb(),
- storageService = createStorageService(),
+ emailService,
}: {
database?: DbPool;
- storageService?: StorageService;
+ emailService?: EmailService;
} = {},
-): Promise<{ deletedEnvelopeId: string }> {
- const { deletedEnvelopeId, storageKeys } = await withTransaction(
- async (tx) => {
- // Whose envelope it is, read first without a lock, so that the
- // sender's account row can be taken before the envelope row.
- const located = await queryOne<{ ownerUserId: string }>(
- tx,
- `SELECT user_id AS "ownerUserId" FROM envelopes WHERE id = $1`,
- [envelopeId],
+): Promise<{ envelopeId: string }> {
+ const cancelled = await withTransaction(async (tx) => {
+ const { envelope, owner } = await lockFinishedEnvelope(
+ tx,
+ envelopeId,
+ actor.userId,
+ );
+ const schedule = await queryOne<ScheduleRow>(
+ tx,
+ `
+ DELETE FROM scheduled_envelope_deletions
+ WHERE envelope_id = $1
+ RETURNING ${SCHEDULE_COLUMNS}
+ `,
+ [envelope.id],
+ );
+
+ if (!schedule) {
+ throw new EnvelopeMutationError(
+ "This envelope is not scheduled to be deleted.",
+ 409,
);
+ }
- if (!located) {
- throw new EnvelopeMutationError("Envelope not found.", 404);
- }
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "envelope_deletion_cancelled",
+ ipAddress,
+ metadata: {
+ deleteAfter: schedule.deleteAfter,
+ envelopeId: envelope.id,
+ ownerEmail: owner?.email ?? null,
+ ownerUserId: envelope.ownerUserId,
+ requestedByEmail: schedule.requestedByEmail,
+ title: envelope.title,
+ },
+ targetUserId: envelope.ownerUserId,
+ userAgent,
+ },
+ tx,
+ );
+
+ return {
+ // Only a sender who was told, and is someone else.
+ notify:
+ owner &&
+ envelope.ownerUserId !== actor.userId &&
+ envelope.ownerUserId !== schedule.requestedByUserId &&
+ schedule.senderNotifiedAt !== null
+ ? { email: owner.email, name: owner.name, title: envelope.title }
+ : null,
+ };
+ }, database);
+
+ if (cancelled.notify) {
+ const link = envelopeLink(envelopeId);
- // The account rows before the envelope row: the sender's, then the
- // administrator's. Taking away a role, and closing an account, hold
- // that account's row (FOR UPDATE) before they take the audit trail
- // lock and move its envelopes, so the two wait in turn here instead
- // of each holding what the other needs. Read under these locks, the
- // administrator's role is the one in force: a change since the page
- // loaded is honored.
- const owner = await queryOne<{
- email: string;
- name: string | null;
- role: string;
- }>(
- tx,
- `SELECT email, name, role FROM public."user" WHERE id = $1 FOR SHARE`,
- [located.ownerUserId],
+ try {
+ await (emailService ?? createEmailService()).send({
+ subject: `"${cancelled.notify.title}" will not be deleted`,
+ template: "deletion_notice",
+ textBody: [
+ `Hello ${cancelled.notify.name?.trim() || cancelled.notify.email},`,
+ "",
+ `An administrator of your organization (${actor.email}) has cancelled the deletion of "${cancelled.notify.title}". It stays as it is.`,
+ ...(link ? ["", link] : []),
+ ].join("\n"),
+ to: cancelled.notify.email,
+ });
+ } catch (error) {
+ console.error(
+ `Telling the sender about the cancelled deletion of envelope ${envelopeId} failed:`,
+ error,
);
- const actorIsOwner = located.ownerUserId === actor.userId;
- const actorRole = actorIsOwner
- ? owner
- : await queryOne<{ role: string }>(
- tx,
- `SELECT role FROM public."user" WHERE id = $1 FOR SHARE`,
- [actor.userId],
- );
- const actorIsAdmin = actorRole?.role === "admin";
-
- // Someone else's envelope is not there for anyone but an
- // administrator.
- if (!actorIsOwner && !actorIsAdmin) {
- throw new EnvelopeMutationError("Envelope not found.", 404);
- }
+ }
+ }
- // Then the envelope row, as everything that changes an envelope takes
- // it; the install's audit trail lock comes after.
- const envelope = await queryOne<FinishedEnvelopeRow>(
- tx,
- `
- SELECT
- id,
- user_id AS "ownerUserId",
- title,
- status,
- part11,
- source_pdf_hash AS "sourcePdfHash",
- signed_pdf_sha256 AS "signedPdfSha256",
- evidence_sha256 AS "evidenceSha256",
- recipient_evidence_sha256 AS "recipientEvidenceSha256",
- COALESCE(completed_at, declined_at, voided_at) AS "finishedAt"
- FROM envelopes
- WHERE id = $1
+ return { envelopeId };
+}
+
+/**
+ * Deletes one envelope whose scheduled deletion is due, with its files,
+ * and records the deletion in the install's audit trail under the
+ * administrator who asked for it. False when there was nothing due: it was
+ * cancelled, or is not due yet.
+ */
+export async function deleteScheduledEnvelope(
+ envelopeId: string,
+ {
+ database = getDb(),
+ now = currentTime(),
+ storageService = createStorageService(),
+ }: {
+ database?: DbPool;
+ now?: number;
+ storageService?: StorageService;
+ } = {},
+): Promise<boolean> {
+ const result = await withTransaction(async (tx) => {
+ const { envelope, owner } = await lockFinishedEnvelope(
+ tx,
+ envelopeId,
+ null,
+ );
+ // Cancelled, or not due, by the time it was locked: nothing to do.
+ const schedule = await queryOne<ScheduleRow>(
+ tx,
+ `
+ SELECT ${SCHEDULE_COLUMNS}
+ FROM scheduled_envelope_deletions
+ WHERE envelope_id = $1 AND delete_after <= $2
FOR UPDATE
`,
- [envelopeId],
- );
+ [envelope.id, now],
+ );
- if (!envelope) {
- throw new EnvelopeMutationError("Envelope not found.", 404);
- }
+ if (!schedule) {
+ return null;
+ }
- if (envelope.ownerUserId !== located.ownerUserId) {
- // Handed to another administrator in the moment between.
- throw new EnvelopeMutationError(
- "This envelope just moved to another account. Reload the page and try again.",
- 409,
- );
- }
+ await recordSystemAuditEvent(
+ {
+ actorEmail: schedule.requestedByEmail,
+ actorUserId: schedule.requestedByUserId,
+ event: "envelope_deleted",
+ metadata: {
+ envelopeId: envelope.id,
+ evidenceSha256: envelope.evidenceSha256,
+ finishedAt: envelope.finishedAt,
+ ownerEmail: owner?.email ?? null,
+ ownerUserId: envelope.ownerUserId,
+ part11: envelope.part11,
+ reason: schedule.reason,
+ recipientEvidenceSha256: envelope.recipientEvidenceSha256,
+ requestedAt: schedule.requestedAt,
+ senderNotified: schedule.senderNotifiedAt !== null,
+ signedPdfSha256: envelope.signedPdfSha256,
+ sourcePdfHash: envelope.sourcePdfHash,
+ status: envelope.status,
+ title: envelope.title,
+ },
+ targetUserId: envelope.ownerUserId,
+ },
+ tx,
+ );
- 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,
- );
- }
+ // The row, the record of its deletion and the list of its files commit
+ // together. The files cannot roll back with them, so they go only after
+ // the commit; one that cannot be deleted then stays on the list, and
+ // the daily cleanup tries it again.
+ const storageKeys = await listEnvelopeStorageKeys(envelope.id, tx);
- if (!actorIsAdmin) {
- throw new EnvelopeMutationError(
- "Only an administrator can delete a finished envelope.",
- 403,
- );
- }
+ await queueFileDeletions(envelope.id, storageKeys, now, tx);
+ await tx.query(`DELETE FROM envelopes WHERE id = $1`, [envelope.id]);
+
+ return storageKeys;
+ }, database);
+
+ if (!result) {
+ return false;
+ }
- const deletionReason = parseReason(reason, envelope.part11);
+ for (const key of result) {
+ await deletePendingFile(key, database, storageService);
+ }
+
+ return true;
+}
- await recordSystemAuditEvent(
+export type ScheduledDeletionSummary = {
+ deleted: number;
+ failures: string[];
+ noticeFailures: string[];
+ noticesSent: number;
+};
+
+/**
+ * The daily part: emails any sender not yet told, then deletes the
+ * envelopes whose wait is over.
+ */
+export async function runScheduledEnvelopeDeletions({
+ database = getDb(),
+ emailService,
+ now = currentTime(),
+ storageService = createStorageService(),
+}: {
+ database?: DbPool;
+ emailService?: EmailService;
+ now?: number;
+ storageService?: StorageService;
+} = {}): Promise<ScheduledDeletionSummary> {
+ const summary: ScheduledDeletionSummary = {
+ deleted: 0,
+ failures: [],
+ noticeFailures: [],
+ noticesSent: 0,
+ };
+ const unsent = await queryMany<
+ ScheduleRow & {
+ envelopeId: string;
+ ownerEmail: string;
+ ownerName: string | null;
+ title: string;
+ }
+ >(
+ database,
+ `
+ SELECT
+ s.envelope_id AS "envelopeId",
+ ${SCHEDULE_COLUMNS},
+ e.title,
+ u.email AS "ownerEmail",
+ u.name AS "ownerName"
+ FROM scheduled_envelope_deletions s
+ JOIN envelopes e ON e.id = s.envelope_id
+ JOIN public."user" u ON u.id = e.user_id
+ WHERE s.sender_notified_at IS NULL AND s.delete_after > $1
+ ORDER BY s.requested_at ASC
+ LIMIT ${String(SCHEDULED_DELETIONS_PER_RUN)}
+ `,
+ [now],
+ );
+ let service = emailService;
+
+ for (const row of unsent) {
+ try {
+ await sendDeletionNotice(
{
- actorEmail: actor.email,
- actorUserId: actor.userId,
- event: "envelope_deleted",
- ipAddress,
- metadata: {
- envelopeId: envelope.id,
- evidenceSha256: envelope.evidenceSha256,
- finishedAt: envelope.finishedAt,
- ownerEmail: owner?.email ?? null,
- ownerUserId: envelope.ownerUserId,
- part11: envelope.part11,
- reason: deletionReason,
- recipientEvidenceSha256: envelope.recipientEvidenceSha256,
- signedPdfSha256: envelope.signedPdfSha256,
- sourcePdfHash: envelope.sourcePdfHash,
- status: envelope.status,
- title: envelope.title,
- },
- userAgent,
+ deleteAfter: row.deleteAfter,
+ envelopeId: row.envelopeId,
+ ownerEmail: row.ownerEmail,
+ ownerName: row.ownerName,
+ requestedAt: row.requestedAt,
+ requestedByEmail: row.requestedByEmail,
+ title: row.title,
},
- tx,
+ database,
+ (service ??= createEmailService()),
);
-
- // The row, the record of its deletion and the list of its files
- // commit together. The files cannot roll back with them, so they go
- // only after the commit; one that cannot be deleted then stays on the
- // list, and the daily cleanup tries it again.
- const storageKeys = await listEnvelopeStorageKeys(envelope.id, tx);
-
- await queueFileDeletions(
- envelope.id,
- storageKeys,
- Math.floor(Date.now() / 1000),
- tx,
+ summary.noticesSent += 1;
+ } catch (error) {
+ summary.noticeFailures.push(row.envelopeId);
+ console.error(
+ `Telling the sender about the deletion of envelope ${row.envelopeId} failed:`,
+ error,
);
- const deleted = await tx.query(`DELETE FROM envelopes WHERE id = $1`, [
- envelope.id,
- ]);
-
- if (deleted.rowCount !== 1) {
- throw new EnvelopeMutationError("Envelope not found.", 404);
- }
+ }
+ }
- return { deletedEnvelopeId: envelope.id, storageKeys };
- },
+ const due = await queryMany<{ envelopeId: string }>(
database,
+ `
+ SELECT envelope_id AS "envelopeId"
+ FROM scheduled_envelope_deletions
+ WHERE delete_after <= $1
+ ORDER BY delete_after ASC, envelope_id ASC
+ LIMIT ${String(SCHEDULED_DELETIONS_PER_RUN)}
+ `,
+ [now],
);
- for (const key of storageKeys) {
- await deletePendingFile(key, database, storageService);
+ for (const { envelopeId } of due) {
+ try {
+ if (
+ await deleteScheduledEnvelope(envelopeId, {
+ database,
+ now,
+ storageService,
+ })
+ ) {
+ summary.deleted += 1;
+ }
+ } catch (error) {
+ summary.failures.push(envelopeId);
+ console.error(
+ `The scheduled deletion of envelope ${envelopeId} failed:`,
+ error,
+ );
+ }
}
- return { deletedEnvelopeId };
+ return summary;
}
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index f01b01e..010638a 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -1802,23 +1802,30 @@ export async function listEnvelopesForUser(
/**
* Every envelope in the install, whoever sent it, each with its sender.
- * For an administrator: the caller checks the role.
+ * Other members' drafts are left out: a draft is its sender's own until it
+ * is sent. For an administrator: the caller checks the role.
*/
export async function listAllEnvelopesForAdmin(
+ adminUserId: string,
filters: Partial<EnvelopeListFilters> = {},
database: DbExecutor = getDb(),
): Promise<DashboardEnvelopePage> {
- return listEnvelopes(null, filters, database);
+ return listEnvelopes(null, filters, database, adminUserId);
}
async function listEnvelopes(
ownerUserId: string | null,
filters: Partial<EnvelopeListFilters>,
database: DbExecutor,
+ adminUserId?: string,
): Promise<DashboardEnvelopePage> {
const parsedFilters = envelopeListFiltersSchema.parse(filters);
- const values: unknown[] = ownerUserId === null ? [] : [ownerUserId];
- const clauses = ownerUserId === null ? ["TRUE"] : ["user_id = $1"];
+ const values: unknown[] =
+ ownerUserId === null ? [adminUserId ?? ""] : [ownerUserId];
+ const clauses =
+ ownerUserId === null
+ ? ["(status <> 'draft' OR user_id = $1)"]
+ : ["user_id = $1"];
let nextParamIndex = values.length + 1;
if (parsedFilters.status) {
diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.ts
index 4e5641b..54c219a 100644
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@ -1,6 +1,10 @@
import { createHash, timingSafeEqual } from "node:crypto";
import { getDb, type DbPool } from "./db/connection.ts";
+import {
+ runScheduledEnvelopeDeletions,
+ type ScheduledDeletionSummary,
+} from "./envelope-deletion.ts";
import {
envelopeScheduleFailed,
runEnvelopeSchedule,
@@ -17,8 +21,9 @@ import { isMissingSchemaError } from "./settings.ts";
import { getEnv, type EnvSource } from "./utils/env.ts";
// The daily job. First the cleanup: stale drafts, queued account deletions,
-// expired download links and finished rate limit windows. Then the envelopes
-// that are out for signature: see envelope-schedule.ts.
+// expired download links and finished rate limit windows. Then the
+// deletions administrators scheduled (envelope-deletion.ts), and the
+// envelopes that are out for signature (envelope-schedule.ts).
//
// On Vercel it is called by a cron job (see vercel.json). A click-to-deploy
// install has no secret for that call, because nobody typed one in, so the
@@ -39,6 +44,8 @@ export type RetentionCaller = "anonymous" | "authorized" | "denied";
export type RetentionJobOutcome =
| {
+ /** Null when that part could not run. The cleanup still counts. */
+ deletions: ScheduledDeletionSummary | null;
/** Null when that part could not run. The cleanup still counts. */
schedule: EnvelopeScheduleSummary | null;
status: "ran";
@@ -171,6 +178,20 @@ export async function runRetentionJob({
}
});
+ const deletions = await runScheduledEnvelopeDeletions({
+ database,
+ emailService,
+ storageService,
+ }).catch((error: unknown) => {
+ // A database from before scheduled deletions has none to run.
+ if (!isMissingSchemaError(error)) {
+ console.error("The scheduled envelope deletions failed:", error);
+ return null;
+ }
+
+ return { deleted: 0, failures: [], noticeFailures: [], noticesSent: 0 };
+ });
+
const schedule = await runEnvelopeSchedule({
database,
emailService,
@@ -192,7 +213,7 @@ export async function runRetentionJob({
};
});
- return { schedule, status: "ran", summary };
+ return { deletions, schedule, status: "ran", summary };
} finally {
await lockClient.query("rollback").catch(() => undefined);
lockClient.release();
@@ -213,6 +234,9 @@ export function retentionJobFailed(
): boolean {
return (
retentionSweepFailed(outcome.summary) ||
+ outcome.deletions === null ||
+ outcome.deletions.failures.length > 0 ||
+ outcome.deletions.noticeFailures.length > 0 ||
outcome.schedule === null ||
envelopeScheduleFailed(outcome.schedule)
);
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
index bf668bc..33fa381 100644
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@ -44,6 +44,8 @@ export const systemAuditEventTypes = [
"email_domain_changed",
"envelope_deleted",
"envelope_file_downloaded",
+ "envelope_deletion_scheduled",
+ "envelope_deletion_cancelled",
] as const;
export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index 35a0730..51c2771 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -99,6 +99,7 @@ export const emailTemplateKinds = [
"void_notification",
"password_reset",
"retention_notice",
+ "deletion_notice",
"expiry_notice",
"test_email",
"signing_lock_alert",