Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let administrators see every envelope and delete any finished one
Claudec281c0a54e20
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 952c8ed..4160ce4 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. 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.+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.## FDA 21 CFR Part 11diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 220997d..4e3165e 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -1341,7 +1341,57 @@ 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 test.step("an administrator sees another member's envelope and deletes it for good", async () => {+ // The envelope becomes a plain member's, as if they had sent it.+ const memberId = `member-${runId}`;+ const memberEmail = `member+${runId}@example.com`;+ const db = new pg.Client({ connectionString: e2eDatabaseUrl });++ await db.connect();++ try {+ await db.query(+ `insert into public."user" (id, name, email, role, "emailVerified") values ($1, 'Mira Member', $2, 'user', true)`,+ [memberId, memberEmail],+ );+ await db.query(`update envelopes set user_id = $1 where id = $2`, [+ memberId,+ envelopeId,+ ]);+ } finally {+ await db.end();+ }++ const senderLabel = `Mira Member (${memberEmail})`;++ // Gone from the administrator's own list, there in everyone's.+ await page.goto("/dashboard");+ await expect(+ page.getByRole("heading", { name: "Terms to decline" }),+ ).toHaveCount(0);+ await page.getByRole("link", { name: "Everyone's" }).click();+ await expect(page).toHaveURL(/\/dashboard\?view=all$/);+ await expect(+ page.getByRole("heading", { level: 1, name: "All envelopes" }),+ ).toBeVisible();++ const card = page.getByRole("link").filter({ hasText: "Terms to decline" });++ await expect(card).toContainText(senderLabel);+ await card.click();+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));+ await expect(page.getByText(`Sent by ${senderLabel}`)).toBeVisible();+ // What changes the envelope stays with its sender.+ await expect(+ page.getByRole("button", { name: "Copy to new draft" }),+ ).toHaveCount(0);++ // A copy of someone else's certificate is on record.+ const download = page.waitForEvent("download");++ await page.getByRole("button", { name: "Download certificate" }).click();+ expect((await download).suggestedFilename()).toMatch(/\.pdf$/);+await page.getByRole("button", { name: "Delete envelope" }).click();const confirm = page.getByRole("dialog", {@@ -1350,22 +1400,33 @@ test("a signer who declines is told the decline was recorded, not that the linkawait confirm.getByLabel("Reason (optional)").fill("Never agreed.");await confirm.getByRole("button", { name: "Delete envelope" }).click();- await expect(page).toHaveURL(/\/dashboard$/);+ await expect(page).toHaveURL(/\/dashboard\?view=all$/);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.+ // The download and the deletion 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 }[];};- const deletion = events.find((event) => event.event === "envelope_deleted");- expect(deletion?.metadata).toMatchObject({+ expect(+ events.find((event) => event.event === "envelope_file_downloaded")+ ?.metadata,+ ).toMatchObject({+ envelopeId,+ file: "evidence",+ ownerEmail: memberEmail,+ });+ expect(+ events.find((event) => event.event === "envelope_deleted")?.metadata,+ ).toMatchObject({envelopeId,+ ownerEmail: memberEmail,reason: "Never agreed.",status: "declined",});diff --git a/src/app/(app)/dashboard/page.tsx b/src/app/(app)/dashboard/page.tsxindex 34dfa11..df73f55 100644--- a/src/app/(app)/dashboard/page.tsx+++ b/src/app/(app)/dashboard/page.tsx@@ -1,22 +1,47 @@import { DashboardShell } from "@/components/dashboard/dashboard-shell";+import { isAdminUser } from "@/lib/auth/admin";import { getAuthSession } from "@/lib/auth/server";import { getDb } from "@/lib/db/connection";-import { listEnvelopesForUser } from "@/lib/envelopes";+import {+ listAllEnvelopesForAdmin,+ listEnvelopesForUser,+} from "@/lib/envelopes";-export default async function DashboardPage() {+type DashboardPageProps = {+ searchParams: Promise<Record<string, string | string[] | undefined>>;+};++export default async function DashboardPage({+ searchParams,+}: DashboardPageProps) {const session = await getAuthSession();const database = getDb();+ const { view } = await searchParams;let envelopes: Awaited<ReturnType<typeof listEnvelopesForUser>> | undefined;let initialState: "default" | "empty" | "error" = "error";+ let isAdmin = false;try {- envelopes = session- ? await listEnvelopesForUser(session.user.id, {}, database)- : [];+ isAdmin = session ? await isAdminUser(session.user.id, database) : false;+ // An administrator can see every envelope in the install, not only+ // their own.+ const showAll = isAdmin && view === "all";++ envelopes = !session+ ? []+ : showAll+ ? await listAllEnvelopesForAdmin({}, database)+ : await listEnvelopesForUser(session.user.id, {}, database);initialState = envelopes.length === 0 ? "empty" : "default";} catch {initialState = "error";}- return <DashboardShell envelopes={envelopes} initialState={initialState} />;+ return (+ <DashboardShell+ envelopes={envelopes}+ initialState={initialState}+ view={isAdmin ? (view === "all" ? "all" : "mine") : undefined}+ />+ );}diff --git a/src/app/(app)/envelopes/[id]/page.tsx b/src/app/(app)/envelopes/[id]/page.tsxindex 7d00405..1a6b81a 100644--- a/src/app/(app)/envelopes/[id]/page.tsx+++ b/src/app/(app)/envelopes/[id]/page.tsx@@ -2,6 +2,10 @@ import { EnvelopeDetailShell } from "@/components/envelopes/envelope-detail-shelimport { isAdminUser } from "@/lib/auth/admin";import { getAuthSession } from "@/lib/auth/server";import { getDb } from "@/lib/db/connection";+import {+ formatEnvelopeOwner,+ resolveEnvelopeViewerAccess,+} from "@/lib/envelope-access";import { getEnvelopeDetailDataForUser } from "@/lib/envelopes";type EnvelopeDetailPageProps = {@@ -19,13 +23,21 @@ export default async function EnvelopeDetailPage({null;let initialState: "error" | "not-found" | undefined;let canDeleteFinished = false;+ let ownerLabel: string | undefined;try {const session = await getAuthSession();- detailRecord = session- ? await getEnvelopeDetailDataForUser(session.user.id, id, getDb())+ // Its sender's, or, for an administrator, anyone's.+ const access = session+ ? await resolveEnvelopeViewerAccess(session.user.id, id, getDb())+ : null;++ detailRecord = access+ ? await getEnvelopeDetailDataForUser(access.ownerUserId, id, getDb()): null;initialState = detailRecord ? undefined : "not-found";+ ownerLabel =+ access && !access.viewerIsOwner ? formatEnvelopeOwner(access) : undefined;// Only an administrator may delete a finished envelope.canDeleteFinished =detailRecord !== null &&@@ -41,6 +53,7 @@ export default async function EnvelopeDetailPage({envelopeId={id}initialState={initialState}key={id}+ ownerLabel={ownerLabel}record={detailRecord ?? undefined}/>);diff --git a/src/app/api/envelopes/[id]/audit/route.ts b/src/app/api/envelopes/[id]/audit/route.tsindex f5d1994..914f2cf 100644--- a/src/app/api/envelopes/[id]/audit/route.ts+++ b/src/app/api/envelopes/[id]/audit/route.ts@@ -2,9 +2,11 @@ import { NextResponse } from "next/server";import { AuditExportError, exportEnvelopeAuditCsv } from "@/lib/audit-export";import { requireVerifiedSenderSession } from "@/lib/auth/route-session";+import { resolveEnvelopeViewerAccess } from "@/lib/envelope-access";import { logRouteError } from "@/lib/security/logging";import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";import { buildContentDisposition } from "@/lib/services/storage";+import { recordSystemAuditEvent } from "@/lib/services/system-audit";type EnvelopeAuditRouteContext = {params: Promise<{@@ -12,7 +14,8 @@ type EnvelopeAuditRouteContext = {}>;};-// The envelope's audit trail as a CSV file, for its sender.+// The envelope's audit trail as a CSV file, for its sender, or for an+// administrator, who sees every envelope.export async function GET(request: Request,context: EnvelopeAuditRouteContext,@@ -26,7 +29,31 @@ export async function GET(const { id } = await context.params;try {- const file = await exportEnvelopeAuditCsv(sessionResult.user.id, id);+ // Its sender's, or any envelope for an administrator.+ const access = await resolveEnvelopeViewerAccess(sessionResult.user.id, id);+ const file = await exportEnvelopeAuditCsv(+ access?.ownerUserId ?? sessionResult.user.id,+ id,+ );++ if (access && !access.viewerIsOwner) {+ // An administrator taking a copy of someone else's records is on+ // record in the install's audit trail. No record, no file.+ await recordSystemAuditEvent({+ actorEmail: sessionResult.user.email,+ actorUserId: sessionResult.user.id,+ event: "envelope_file_downloaded",+ ipAddress: getClientIpAddress(request.headers),+ metadata: {+ envelopeId: id,+ file: "audit_trail",+ ownerEmail: access.ownerEmail,+ ownerUserId: access.ownerUserId,+ },+ targetUserId: access.ownerUserId,+ userAgent: request.headers.get("user-agent"),+ });+ }return new Response(file.body, {headers: {diff --git a/src/app/api/envelopes/[id]/document/route.ts b/src/app/api/envelopes/[id]/document/route.tsindex 33e0303..2a9059d 100644--- a/src/app/api/envelopes/[id]/document/route.ts+++ b/src/app/api/envelopes/[id]/document/route.ts@@ -6,6 +6,7 @@ import {EnvelopeDocumentAccessError,getDraftEnvelopeDocumentForUser,} from "@/lib/envelopes";+import { resolveEnvelopeViewerAccess } from "@/lib/envelope-access";import { logRouteError } from "@/lib/security/logging";import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";import { buildContentDisposition } from "@/lib/services/storage";@@ -30,9 +31,17 @@ export async function GET(const { id } = await context.params;try {- const document = await getDraftEnvelopeDocumentForUser(session.user.id, id, {- database: getDb(),- });+ // Its sender's, or any envelope for an administrator.+ const access = await resolveEnvelopeViewerAccess(+ session.user.id,+ id,+ getDb(),+ );+ const document = await getDraftEnvelopeDocumentForUser(+ access?.ownerUserId ?? session.user.id,+ id,+ { database: getDb() },+ );const responseBody = document.body.slice().buffer as ArrayBuffer;return new Response(responseBody, {diff --git a/src/app/api/envelopes/[id]/download/route.ts b/src/app/api/envelopes/[id]/download/route.tsindex 5a52b6a..6b8d7c1 100644--- a/src/app/api/envelopes/[id]/download/route.ts+++ b/src/app/api/envelopes/[id]/download/route.ts@@ -9,8 +9,10 @@ import {getSenderEnvelopeDownload,} from "@/lib/downloads";import { downloadRequestSchema } from "@/lib/schemas/envelope";+import { resolveEnvelopeViewerAccess } from "@/lib/envelope-access";import { logRouteError } from "@/lib/security/logging";import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { recordSystemAuditEvent } from "@/lib/services/system-audit";type EnvelopeDownloadRouteContext = {params: Promise<{@@ -41,15 +43,40 @@ export async function GET(const { type } = downloadRequestSchema.parse({type: getDownloadType(request),});- const download = await getSenderEnvelopeDownload(+ // Its sender's, or any envelope for an administrator.+ const access = await resolveEnvelopeViewerAccess(session.user.id,id,+ getDb(),+ );+ const download = await getSenderEnvelopeDownload(+ access?.ownerUserId ?? session.user.id,+ id,type,{database: getDb(),},);+ if (access && !access.viewerIsOwner) {+ // An administrator taking a copy of someone else's document is on+ // record in the install's audit trail. No record, no file.+ await recordSystemAuditEvent({+ actorEmail: session.user.email,+ actorUserId: session.user.id,+ event: "envelope_file_downloaded",+ ipAddress: getClientIpAddress(request.headers),+ metadata: {+ envelopeId: id,+ file: type,+ ownerEmail: access.ownerEmail,+ ownerUserId: access.ownerUserId,+ },+ targetUserId: access.ownerUserId,+ userAgent: request.headers.get("user-agent"),+ });+ }+return await createDownloadResponse(download);} catch (error) {if (error instanceof ZodError) {diff --git a/src/app/api/envelopes/[id]/nudge/route.ts b/src/app/api/envelopes/[id]/nudge/route.tsindex a11a97b..d735adb 100644--- a/src/app/api/envelopes/[id]/nudge/route.ts+++ b/src/app/api/envelopes/[id]/nudge/route.ts@@ -7,7 +7,10 @@ import {sendManualEnvelopeNudge,} from "@/lib/reminders";import { logRouteError } from "@/lib/security/logging";-import { applyRateLimit, buildRateLimitKey } from "@/lib/security/route-controls";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";import {getClientIpAddress,getRequestPathname,diff --git a/src/app/api/envelopes/[id]/thumbnail/route.ts b/src/app/api/envelopes/[id]/thumbnail/route.tsindex b78e21f..a648a24 100644--- a/src/app/api/envelopes/[id]/thumbnail/route.ts+++ b/src/app/api/envelopes/[id]/thumbnail/route.ts@@ -7,6 +7,7 @@ import {getEnvelopeThumbnailForUser,saveEnvelopeThumbnailForUser,} from "@/lib/envelopes";+import { resolveEnvelopeViewerAccess } from "@/lib/envelope-access";import { logRouteError } from "@/lib/security/logging";import {applyRateLimit,@@ -37,8 +38,9 @@ const privateNoStore = { "cache-control": "private, no-store" };// plan allows before it stops serving files.const privateRevalidate = { "cache-control": "private, no-cache" };-// The picture of a document's first page that the dashboard shows. Only the-// account that owns the envelope can read or write it.+// The picture of a document's first page that the dashboard shows. The+// account that owns the envelope can read and write it; an administrator,+// who sees every envelope, can read it.export async function GET(request: Request,context: EnvelopeThumbnailRouteContext,@@ -53,10 +55,21 @@ export async function GET(const { id } = await context.params;try {- const thumbnail = await getEnvelopeThumbnailForUser(session.user.id, id, {- database: getDb(),- ifNoneMatch: request.headers.get("if-none-match"),- });+ // Its sender's, or any envelope for an administrator. Saving a picture+ // (POST) stays with the sender.+ const access = await resolveEnvelopeViewerAccess(+ session.user.id,+ id,+ getDb(),+ );+ const thumbnail = await getEnvelopeThumbnailForUser(+ access?.ownerUserId ?? session.user.id,+ id,+ {+ database: getDb(),+ ifNoneMatch: request.headers.get("if-none-match"),+ },+ );if (thumbnail.isNotModified) {return new Response(null, {diff --git a/src/components/dashboard/dashboard-documents-surface.tsx b/src/components/dashboard/dashboard-documents-surface.tsxindex fde95a5..b73c8d9 100644--- a/src/components/dashboard/dashboard-documents-surface.tsx+++ b/src/components/dashboard/dashboard-documents-surface.tsx@@ -13,6 +13,9 @@ import { PageHeader } from "@/components/shared/page-header";export type DashboardShellState = "default" | "empty" | "error";+/** An administrator's dashboard: their own envelopes, or everyone's. */+export type DashboardView = "all" | "mine";+export type DashboardFilter ="All" | "Draft" | "Sent" | "Completed" | "Declined" | "Voided";@@ -59,6 +62,8 @@ const statusPillClasses: Record<EnvelopeStatus, string> = {type DashboardDocumentsHeaderProps = {interactive?: boolean;+ /** Shown to administrators only. */+ view?: DashboardView;};type DashboardDocumentsPanelProps = {@@ -91,6 +96,7 @@ type ErrorBannerProps = {export function DashboardDocumentsHeader({interactive = true,+ view,}: DashboardDocumentsHeaderProps) {const label = (<>@@ -104,17 +110,43 @@ export function DashboardDocumentsHeader({);return (- <PageHeader- action={- interactive ? (- <ShellButton href="/envelopes/new">{label}</ShellButton>- ) : (- <StaticShellButton>{label}</StaticShellButton>- )- }- description={documentsDescription}- title="Documents"- />+ <>+ <PageHeader+ action={+ interactive ? (+ <ShellButton href="/envelopes/new">{label}</ShellButton>+ ) : (+ <StaticShellButton>{label}</StaticShellButton>+ )+ }+ description={+ view === "all"+ ? "Every envelope in your organization, whoever sent it."+ : documentsDescription+ }+ title={view === "all" ? "All envelopes" : "Documents"}+ />+ {view && interactive ? (+ <nav aria-label="Whose envelopes" className="segmented self-start">+ <Link+ aria-current={view === "mine" ? "page" : undefined}+ className="segmented-item"+ data-active={view === "mine"}+ href="/dashboard"+ >+ Mine+ </Link>+ <Link+ aria-current={view === "all" ? "page" : undefined}+ className="segmented-item"+ data-active={view === "all"}+ href="/dashboard?view=all"+ >+ Everyone's+ </Link>+ </nav>+ ) : null}+ </>);}@@ -266,6 +298,12 @@ function EnvelopeCard({>{envelope.title}</span>+ {envelope.senderLabel ? (+ <span className="block truncate text-[0.8125rem] text-(--secondary)">+ <span className="sr-only">Sent by </span>+ {envelope.senderLabel}+ </span>+ ) : null}<span className="block truncate text-[0.8125rem] text-(--tertiary)">{envelope.contextLine}</span>diff --git a/src/components/dashboard/dashboard-shell.tsx b/src/components/dashboard/dashboard-shell.tsxindex 3ecaf9f..3a3bcfe 100644--- a/src/components/dashboard/dashboard-shell.tsx+++ b/src/components/dashboard/dashboard-shell.tsx@@ -10,6 +10,7 @@ import {dashboardStatusFilterMap,type DashboardFilter,type DashboardShellState,+ type DashboardView,} from "@/components/dashboard/dashboard-documents-surface";import { DocumentThumbnail } from "@/components/shared/document-thumbnail";import { ShellButton } from "@/components/shared/form-shell";@@ -17,11 +18,14 @@ import { ShellButton } from "@/components/shared/form-shell";type DashboardShellProps = {envelopes?: readonly DashboardEnvelopeListItem[];initialState?: DashboardShellState;+ /** For an administrator: their own envelopes, or everyone's. */+ view?: DashboardView;};export function DashboardShell({envelopes: providedEnvelopes,initialState = "default",+ view,}: DashboardShellProps) {const [searchValue, setSearchValue] = useState("");const [selectedFilter, setSelectedFilter] = useState<DashboardFilter>("All");@@ -66,10 +70,14 @@ export function DashboardShell({return (<div className="space-y-5">- <DashboardDocumentsHeader />+ <DashboardDocumentsHeader view={view} />{initialState === "empty" ? (- <EmptyDashboardState />+ view === "all" ? (+ <EmptyInstallState />+ ) : (+ <EmptyDashboardState />+ )) : (<DashboardDocumentsPanelenvelopes={envelopes}@@ -87,6 +95,23 @@ export function DashboardShell({);}+function EmptyInstallState() {+ return (+ <section+ className="panel px-6 py-14 text-center sm:py-20"+ data-animate="enter"+ data-animate-delay="1"+ >+ <h2 className="text-2xl font-extrabold tracking-[-0.03em] text-(--fg)">+ No envelopes yet+ </h2>+ <p className="mt-2 text-[0.9375rem] leading-6 text-(--secondary)">+ Nobody in your organization has started an envelope.+ </p>+ </section>+ );+}+function EmptyDashboardState() {return (<sectiondiff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex 806e6b1..52d1b1e 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -41,6 +41,12 @@ type EnvelopeDetailShellProps = {canDeleteFinished?: boolean;envelopeId: string;initialState?: "error" | "not-found";+ /**+ * Who sent it, when an administrator is looking at another member's+ * envelope. They can read it, download its files and delete it once it+ * is finished; the rest stays with its sender.+ */+ ownerLabel?: string;record?: EnvelopeDetailData;};@@ -130,8 +136,10 @@ export function EnvelopeDetailShell({canDeleteFinished = false,envelopeId,initialState,+ ownerLabel,record,}: EnvelopeDetailShellProps) {+ const isOwnEnvelope = ownerLabel === undefined;const [activeModal, setActiveModal] = useState<ModalState>(null);const [actionError, setActionError] = useState<string | null>(null);const [isChangingDeadline, setIsChangingDeadline] = useState(false);@@ -439,7 +447,12 @@ export function EnvelopeDetailShell({return;}- window.location.assign(payload?.redirectPath ?? "/dashboard");+ // Back to the list it came from.+ window.location.assign(+ isOwnEnvelope+ ? (payload?.redirectPath ?? "/dashboard")+ : "/dashboard?view=all",+ );} catch {// The request may or may not have reached the server.setActionError(@@ -489,9 +502,9 @@ export function EnvelopeDetailShell({<section className="panel p-5 sm:p-8" data-animate="enter"><LinkclassName="inline-flex items-center text-sm font-semibold text-(--secondary) transition hover:text-(--accent-ink)"- href="/dashboard"+ href={isOwnEnvelope ? "/dashboard" : "/dashboard?view=all"}>- ← Documents+ {isOwnEnvelope ? "← Documents" : "← All envelopes"}</Link><div className="mt-5 flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">@@ -525,6 +538,11 @@ export function EnvelopeDetailShell({<p className="text-sm text-(--secondary)">Created {activeRecord.createdAtLabel}</p>+ {ownerLabel ? (+ <p className="text-sm text-(--secondary)">+ Sent by {ownerLabel}+ </p>+ ) : null}{record.signatureTypeLabel ? (<span className="pill pill-neutral">{record.signatureTypeLabel}@@ -535,7 +553,7 @@ export function EnvelopeDetailShell({</div><div className="flex shrink-0 flex-col gap-3 sm:flex-row sm:flex-wrap lg:justify-end">- {activeRecord.status === "draft" ? (+ {isOwnEnvelope && activeRecord.status === "draft" ? (<><ShellButtononClick={() => setActiveModal("delete-draft")}@@ -549,7 +567,7 @@ export function EnvelopeDetailShell({</>) : null}- {activeRecord.status === "sent" ? (+ {isOwnEnvelope && activeRecord.status === "sent" ? (<><ShellButtononClick={() => setActiveModal("void-envelope")}@@ -598,15 +616,17 @@ export function EnvelopeDetailShell({{activeRecord.status !== "draft" ? (<>- <ShellButton- onClick={() => {- setActionError(null);- setActiveModal("copy-draft");- }}- variant="secondary"- >- Copy to new draft- </ShellButton>+ {isOwnEnvelope ? (+ <ShellButton+ onClick={() => {+ setActionError(null);+ setActiveModal("copy-draft");+ }}+ variant="secondary"+ >+ Copy to new draft+ </ShellButton>+ ) : null}<ShellButtononClick={() =>// A file download from an API route, not a page navigation.@@ -658,16 +678,18 @@ export function EnvelopeDetailShell({>{deadlineText}</p>- <button- className="btn-quiet shrink-0"- onClick={() => {- setActionError(null);- setActiveModal("change-deadline");- }}- type="button"- >- {isExpired ? "Set a new deadline" : "Change deadline"}- </button>+ {isOwnEnvelope ? (+ <button+ className="btn-quiet shrink-0"+ onClick={() => {+ setActionError(null);+ setActiveModal("change-deadline");+ }}+ type="button"+ >+ {isExpired ? "Set a new deadline" : "Change deadline"}+ </button>+ ) : null}</div>) : null}@@ -676,16 +698,18 @@ export function EnvelopeDetailShell({<p className="text-sm leading-6 text-(--secondary)">{remindersText}</p>- <button- className="btn-quiet shrink-0"- onClick={() => {- setActionError(null);- setActiveModal("change-reminders");- }}- type="button"- >- Change reminders- </button>+ {isOwnEnvelope ? (+ <button+ className="btn-quiet shrink-0"+ onClick={() => {+ setActionError(null);+ setActiveModal("change-reminders");+ }}+ type="button"+ >+ Change reminders+ </button>+ ) : null}</div>) : null}@@ -704,7 +728,7 @@ export function EnvelopeDetailShell({View templates</Link></div>- ) : activeRecord.signers.length > 0 ? (+ ) : isOwnEnvelope && activeRecord.signers.length > 0 ? (<divclassName={`well flex flex-col gap-3 px-5 py-3.5 sm:flex-row sm:items-center sm:justify-between ${deadlineText || deadline ? "mt-3" : "mt-5"@@ -796,7 +820,8 @@ export function EnvelopeDetailShell({{signer.statusDateLabel}</p>) : null}- {activeRecord.status === "sent" &&+ {isOwnEnvelope &&+ activeRecord.status === "sent" &&!record.part11 &&(signer.status === "waiting" ||signer.status === "pending") ? (diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsxindex fbfd93b..8a602b3 100644--- a/src/components/settings/security-panel.tsx+++ b/src/components/settings/security-panel.tsx@@ -25,6 +25,7 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {account_deleted: "Account deleted",email_domain_changed: "Email domain changed",envelope_deleted: "Finished envelope deleted",+ envelope_file_downloaded: "Another member's file downloaded",identity_verification_revoked: "Identity confirmation taken back",identity_verified: "Identity confirmed",logo_changed: "Logo changed",@@ -100,6 +101,20 @@ function describeEvent(event: SystemAuditEvent): string {typeof metadata.title === "string" ? `"${metadata.title}"` : null,typeof metadata.status === "string" ? metadata.status : 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"+ ? (downloadedFileLabels[metadata.file] ?? metadata.file)+ : null,+ typeof metadata.ownerEmail === "string"+ ? `sent by ${metadata.ownerEmail}`+ : null,].filter(Boolean).join(", ");@@ -108,6 +123,12 @@ function describeEvent(event: SystemAuditEvent): string {}}+const downloadedFileLabels: Record<string, string> = {+ audit_trail: "audit trail",+ evidence: "certificate",+ signed: "signed PDF",+};+function describeMinutes(minutes: number): string {return minutes < 60? `${String(minutes)} minutes`diff --git a/src/lib/envelope-access.dbtest.ts b/src/lib/envelope-access.dbtest.tsnew file mode 100644index 0000000..9bfe8a4--- /dev/null+++ b/src/lib/envelope-access.dbtest.ts@@ -0,0 +1,133 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import { 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`.++let database: pg.Pool;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+});++async function createUser(role: "admin" | "user", name: string) {+ const id = randomUUID();+ const email = `${id}@example.test`;++ createdUsers.push(id);+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, $2, $3, $4)`,+ [id, name, email, role],+ );++ return { email, name, userId: id };+}++async function createEnvelope(userId: string, title: string) {+ 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)+ `,+ [+ envelopeId,+ userId,+ title,+ `users/${userId}/envelopes/${envelopeId}/source.pdf`,+ "a".repeat(64),+ ],+ );++ return envelopeId;+}++test("the sender sees their own envelope", async () => {+ const sender = await createUser("user", "Sam Sender");+ const envelopeId = await createEnvelope(sender.userId, "Lease");++ assert.deepEqual(+ await resolveEnvelopeViewerAccess(sender.userId, envelopeId, database),+ {+ ownerEmail: sender.email,+ ownerName: "Sam Sender",+ ownerUserId: sender.userId,+ viewerIsOwner: true,+ },+ );+});++test("an administrator sees another member's envelope, and whose it is", async () => {+ const sender = await createUser("user", "Sam Sender");+ const admin = await createUser("admin", "Avery Admin");+ const envelopeId = await createEnvelope(sender.userId, "Lease");++ assert.deepEqual(+ await resolveEnvelopeViewerAccess(admin.userId, envelopeId, database),+ {+ ownerEmail: sender.email,+ ownerName: "Sam Sender",+ ownerUserId: sender.userId,+ viewerIsOwner: false,+ },+ );+});++test("another member who is not an administrator does not see it", async () => {+ const sender = await createUser("admin", "Sam Sender");+ const other = await createUser("user", "Olive Other");+ const envelopeId = await createEnvelope(sender.userId, "Lease");++ assert.equal(+ await resolveEnvelopeViewerAccess(other.userId, envelopeId, database),+ null,+ );+ assert.equal(+ await resolveEnvelopeViewerAccess(other.userId, randomUUID(), database),+ null,+ );+});++test("an administrator's list of every envelope names each sender", async () => {+ const first = await createUser("user", "Sam Sender");+ const second = await createUser("admin", "");+ const firstEnvelope = await createEnvelope(first.userId, "First lease");+ const secondEnvelope = await createEnvelope(second.userId, "Second lease");++ const all = await listAllEnvelopesForAdmin({ limit: 100 }, database);+ const byId = new Map(all.map((envelope) => [envelope.id, envelope]));++ assert.equal(+ byId.get(firstEnvelope)?.senderLabel,+ `Sam Sender (${first.email})`,+ );+ // No name: the address alone.+ assert.equal(byId.get(secondEnvelope)?.senderLabel, second.email);++ // A sender's own list stays theirs, without the sender on each card.+ const own = await listEnvelopesForUser(first.userId, {}, database);++ assert.deepEqual(+ own.map((envelope) => envelope.id),+ [firstEnvelope],+ );+ assert.equal(own[0]?.senderLabel, undefined);+});diff --git a/src/lib/envelope-access.ts b/src/lib/envelope-access.tsnew file mode 100644index 0000000..b5f9f47--- /dev/null+++ b/src/lib/envelope-access.ts@@ -0,0 +1,73 @@+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.++export type EnvelopeViewerAccess = {+ ownerEmail: string;+ ownerName: string | null;+ ownerUserId: string;+ /** False when an administrator is looking at someone else's envelope. */+ viewerIsOwner: boolean;+};++type AccessRow = {+ ownerEmail: string;+ ownerName: string | null;+ ownerUserId: string;+ viewerRole: string | null;+};++/**+ * The envelope's sender, when `viewerUserId` may see it: as its sender, or+ * as an administrator. Null when the envelope does not exist or is not+ * theirs to see, which callers report as "not found".+ */+export async function resolveEnvelopeViewerAccess(+ viewerUserId: string,+ envelopeId: string,+ database: DbExecutor = getDb(),+): Promise<EnvelopeViewerAccess | null> {+ const row = await queryOne<AccessRow>(+ database,+ `+ SELECT+ e.user_id AS "ownerUserId",+ owner.email AS "ownerEmail",+ owner.name AS "ownerName",+ (SELECT role FROM public."user" WHERE id = $2) AS "viewerRole"+ FROM envelopes e+ JOIN public."user" owner ON owner.id = e.user_id+ WHERE e.id = $1+ `,+ [envelopeId, viewerUserId],+ );++ if (!row) {+ return null;+ }++ const viewerIsOwner = row.ownerUserId === viewerUserId;++ if (!viewerIsOwner && row.viewerRole !== "admin") {+ return null;+ }++ return {+ ownerEmail: row.ownerEmail,+ ownerName: row.ownerName,+ ownerUserId: row.ownerUserId,+ viewerIsOwner,+ };+}++/** How an administrator sees who sent an envelope. */+export function formatEnvelopeOwner(+ access: Pick<EnvelopeViewerAccess, "ownerEmail" | "ownerName">,+): string {+ const name = access.ownerName?.trim();++ return name ? `${name} (${access.ownerEmail})` : access.ownerEmail;+}diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.tsindex 58da01b..a2fbb1e 100644--- a/src/lib/envelope-deletion.dbtest.ts+++ b/src/lib/envelope-deletion.dbtest.ts@@ -265,15 +265,43 @@ test("an envelope still out for signature, or a draft, is not deleted this way",}});-test("an administrator cannot delete another account's envelope", async () => {+test("an administrator deletes another member's finished envelope, and the record names its sender", async () => {+ const owner = await createUser("user");+ const admin = await createUser("admin");+ const envelope = await createEnvelope(owner.userId, { status: "completed" });++ await deleteAs(admin, envelope.envelopeId, "Asked to by legal.");++ 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?.metadata?.ownerUserId, owner.userId);+ assert.equal(event?.metadata?.ownerEmail, owner.email);+ assert.equal(event?.metadata?.reason, "Asked to by legal.");+});++test("someone who is not an administrator cannot find another member's envelope to delete", async () => {const owner = await createUser("admin");- const other = 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);});+test("an envelope that does not exist is not found", async () => {+ const admin = await createUser("admin");++ await assert.rejects(deleteAs(admin, randomUUID()), rejectsWith(404));+});+test("a Part 11 record needs a reason before it is deleted", async () => {const admin = await createUser("admin");const envelope = await createEnvelope(admin.userId, {@@ -461,8 +489,8 @@ test("a deletion running while the administrator's handed-over envelopes move do]);await demotion.query("commit");- // The envelope is no longer the deleting account's to delete.- await assert.rejects(deletion, rejectsWith(404));+ // It moved while the deletion waited: told to look again.+ await assert.rejects(deletion, rejectsWith(409));} finally {demotion.release();}diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.tsindex ded8d12..31a2d37 100644--- a/src/lib/envelope-deletion.ts+++ b/src/lib/envelope-deletion.ts@@ -16,11 +16,12 @@ import {} 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.+// 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.const FINISHED_STATUSES = ["completed", "declined", "voided"] as const;@@ -30,6 +31,7 @@ type FinishedEnvelopeRow = {evidenceSha256: string | null;finishedAt: number | null;id: string;+ ownerUserId: string;part11: boolean;recipientEvidenceSha256: string | null;signedPdfSha256: string | null;@@ -70,8 +72,9 @@ function parseReason(reason: unknown, part11: boolean): string | null {}/**- * Deletes a completed, declined or voided envelope the administrator owns,- * with its files, and records the deletion in the install's audit trail.+ * 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.*/export async function deleteFinishedEnvelope(envelopeId: string,@@ -91,18 +94,50 @@ export async function deleteFinishedEnvelope(): Promise<{ deletedEnvelopeId: string }> {const { deletedEnvelopeId, storageKeys } = await withTransaction(async (tx) => {- // The administrator's own account row before the envelope row. Taking- // away the role holds that row (FOR UPDATE) before it takes the audit- // trail lock and moves the account's handed-over envelopes, so the- // two wait for each other here instead of each holding what the- // other needs. Read under this lock, the role is the one in force:- // a change since the page loaded is honored.- const actorRole = await queryOne<{ role: string }>(+ // 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 role FROM public."user" WHERE id = $1 FOR SHARE`,- [actor.userId],+ `SELECT user_id AS "ownerUserId" FROM envelopes WHERE id = $1`,+ [envelopeId],);+ if (!located) {+ throw new EnvelopeMutationError("Envelope not found.", 404);+ }++ // 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],+ );+ 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>(@@ -110,6 +145,7 @@ export async function deleteFinishedEnvelope(`SELECTid,+ user_id AS "ownerUserId",title,status,part11,@@ -119,16 +155,24 @@ export async function deleteFinishedEnvelope(recipient_evidence_sha256 AS "recipientEvidenceSha256",COALESCE(completed_at, declined_at, voided_at) AS "finishedAt"FROM envelopes- WHERE id = $1 AND user_id = $2+ WHERE id = $1FOR UPDATE`,- [envelopeId, actor.userId],+ [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"@@ -138,7 +182,7 @@ export async function deleteFinishedEnvelope();}- if (actorRole?.role !== "admin") {+ if (!actorIsAdmin) {throw new EnvelopeMutationError("Only an administrator can delete a finished envelope.",403,@@ -157,6 +201,8 @@ export async function deleteFinishedEnvelope(envelopeId: envelope.id,evidenceSha256: envelope.evidenceSha256,finishedAt: envelope.finishedAt,+ ownerEmail: owner?.email ?? null,+ ownerUserId: envelope.ownerUserId,part11: envelope.part11,reason: deletionReason,recipientEvidenceSha256: envelope.recipientEvidenceSha256,diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 7fc4332..381c602 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -125,6 +125,7 @@ import {getManualNudgeAvailableAt,isManualNudgeAvailable,} from "./services/reminders.ts";+import { formatEnvelopeOwner } from "./envelope-access.ts";import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";import { hashAccessCode } from "./signer-checks.ts";import { escapeHtml } from "./utils/html.ts";@@ -306,6 +307,8 @@ export type DashboardEnvelopeListItem = {expired?: boolean;id: string;searchableEmails: readonly string[];+ /** Who sent it, in an administrator's list of every envelope. */+ senderLabel?: string;status: EnvelopeRecord["status"];/** What the status pill says: the status, or how far signing has got. */statusLabel: string;@@ -1786,11 +1789,30 @@ export async function listEnvelopesForUser(userId: string,filters: Partial<EnvelopeListFilters> = {},database: DbExecutor = getDb(),+): Promise<DashboardEnvelopeListItem[]> {+ return listEnvelopes(userId, filters, database);+}++/**+ * Every envelope in the install, whoever sent it, each with its sender.+ * For an administrator: the caller checks the role.+ */+export async function listAllEnvelopesForAdmin(+ filters: Partial<EnvelopeListFilters> = {},+ database: DbExecutor = getDb(),+): Promise<DashboardEnvelopeListItem[]> {+ return listEnvelopes(null, filters, database);+}++async function listEnvelopes(+ ownerUserId: string | null,+ filters: Partial<EnvelopeListFilters>,+ database: DbExecutor,): Promise<DashboardEnvelopeListItem[]> {const parsedFilters = envelopeListFiltersSchema.parse(filters);- const values: unknown[] = [userId];- const clauses = ["user_id = $1"];- let nextParamIndex = 2;+ const values: unknown[] = ownerUserId === null ? [] : [ownerUserId];+ const clauses = ownerUserId === null ? ["TRUE"] : ["user_id = $1"];+ let nextParamIndex = values.length + 1;if (parsedFilters.status) {clauses.push(`status = $${String(nextParamIndex)}`);@@ -1863,12 +1885,30 @@ export async function listEnvelopesForUser(listFieldsForEnvelopeIds(envelopeIds, database),listCopyRecipientsForEnvelopeIds(envelopeIds, database),]);+ const sendersById =+ ownerUserId === null+ ? await listSendersById(+ envelopes.map((envelope) => envelope.userId),+ database,+ )+ : null;return envelopes.map((envelope) => {const signers = signersByEnvelope.get(envelope.id) ?? [];const fields = fieldsByEnvelope.get(envelope.id) ?? [];+ const sender = sendersById?.get(envelope.userId);return {+ ...(sendersById+ ? {+ senderLabel: sender+ ? formatEnvelopeOwner({+ ownerEmail: sender.email,+ ownerName: sender.name,+ })+ : "Unknown sender",+ }+ : {}),contextLine: buildDashboardContextLine(envelope, signers, fields),createdAtLabel: formatShortDate(envelope.createdAt),expired: isEnvelopeExpired(envelope, Math.floor(Date.now() / 1000)),@@ -1885,6 +1925,27 @@ export async function listEnvelopesForUser(});}+type SenderRow = { email: string; id: string; name: string | null };++async function listSendersById(+ userIds: readonly string[],+ database: DbExecutor,+): Promise<Map<string, SenderRow>> {+ const uniqueIds = [...new Set(userIds)];++ if (uniqueIds.length === 0) {+ return new Map();+ }++ const rows = await queryMany<SenderRow>(+ database,+ `SELECT id, name, email FROM public."user" WHERE id = ANY($1::text[])`,+ [uniqueIds],+ );++ return new Map(rows.map((row) => [row.id, row]));+}+export async function getEnvelopeDetailDataForUser(userId: string,envelopeId: string,diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.tsindex 68ca1a1..bf668bc 100644--- a/src/lib/services/system-audit.ts+++ b/src/lib/services/system-audit.ts@@ -43,6 +43,7 @@ export const systemAuditEventTypes = ["logo_changed","email_domain_changed","envelope_deleted",+ "envelope_file_downloaded",] as const;export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];