Skip to content

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

TypeScript

Let the sender open the document while an envelope is out for signature

Claude25e28f7de929
diff --git a/e2e/wizard-view-document.spec.ts b/e2e/wizard-view-document.spec.ts
new file mode 100644
index 0000000..4b34bc0
--- /dev/null
+++ b/e2e/wizard-view-document.spec.ts
@@ -0,0 +1,167 @@
+import { expect, type Page, test } from "@playwright/test";
+import pg from "pg";
+
+import { e2eDatabaseUrl } from "../playwright.config";
+import { signInAsAdministrator } from "./support/admin-session";
+import { writeSamplePdf } from "./support/sample-pdf";
+
+// Runs after signing-flow.spec.ts, which sets up the install and its
+// administrator.
+
+const TITLE = "SAMPLE - Supplier Agreement (view while out)";
+const SIGNER_EMAIL = "[email protected]";
+const OTHER_MEMBER_ID = "e2e-view-document-member";
+const OTHER_MEMBER_EMAIL = "[email protected]";
+
+async function expectTheDocumentAsSent(page: Page, documentUrl: string) {
+ const response = await page.request.get(documentUrl);
+
+ expect(response.status()).toBe(200);
+ expect(response.headers()["content-type"]).toBe("application/pdf");
+ expect(response.headers()["x-content-type-options"]).toBe("nosniff");
+ expect(response.headers()["cache-control"]).toBe("private, no-store");
+ expect((await response.body()).subarray(0, 5).toString("latin1")).toBe(
+ "%PDF-",
+ );
+}
+
+async function countOriginalViews(envelopeId: string): Promise<number> {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+
+ await database.connect();
+
+ try {
+ const result = await database.query<{ count: string }>(
+ `
+ select count(*) as count
+ from public.system_audit_events
+ where event = 'envelope_file_downloaded'
+ and metadata->>'envelopeId' = $1
+ and metadata->>'file' = 'original'
+ `,
+ [envelopeId],
+ );
+
+ return Number(result.rows[0]?.count ?? "0");
+ } finally {
+ await database.end();
+ }
+}
+
+test("a sender opens the document while it is out for signature, and after voiding it", async ({
+ page,
+}, testInfo) => {
+ let envelopeId = "";
+ const documentUrl = () => `/api/envelopes/${envelopeId}/document`;
+
+ await signInAsAdministrator(page);
+
+ await test.step("the sender sends a document", async () => {
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("view.pdf"));
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill(TITLE);
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+ envelopeId = /\/envelopes\/([^/]+)\/signers$/.exec(page.url())?.[1] ?? "";
+
+ await page.getByLabel("Signer 1 name").fill("Valentina View");
+ await page.getByLabel("Signer 1 email").fill(SIGNER_EMAIL);
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/prepare$/);
+ await page.getByRole("button", { exact: true, name: "Signature" }).click();
+
+ const placementTarget = page.getByLabel("Place Signature on page 1");
+ const box = await placementTarget.boundingBox();
+
+ await placementTarget.click({
+ position: { x: box!.width * 0.3, y: box!.height * 0.6 },
+ });
+ await expect(page.getByRole("status")).toHaveText("Saved");
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/review$/);
+ await page.getByRole("button", { name: "Send envelope" }).click();
+
+ const confirmation = page.getByRole("dialog", {
+ name: "Send this envelope?",
+ });
+
+ await confirmation.getByRole("checkbox").check();
+ await confirmation.getByRole("button", { name: "Send now" }).click();
+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));
+ });
+
+ await test.step("while it is out, View document and the thumbnail open it in a new tab", async () => {
+ const viewButton = page.getByRole("link", { name: "View document" });
+
+ await expect(viewButton).toBeVisible();
+ await expect(viewButton).toHaveAttribute("href", documentUrl());
+ await expect(viewButton).toHaveAttribute("target", "_blank");
+ await expect(viewButton).toHaveAttribute("rel", /noopener/);
+
+ const thumbnailLink = page.getByRole("link", {
+ name: `View ${TITLE} (opens in a new tab)`,
+ });
+
+ await expect(thumbnailLink).toBeVisible();
+ await expect(thumbnailLink).toHaveAttribute("href", documentUrl());
+ await expect(thumbnailLink).toHaveAttribute("target", "_blank");
+
+ await expectTheDocumentAsSent(page, documentUrl());
+ // The sender looking at their own document is nothing to record.
+ expect(await countOriginalViews(envelopeId)).toBe(0);
+ });
+
+ await test.step("once voided, it can still be opened", async () => {
+ await page.getByRole("button", { name: "Void envelope" }).click();
+
+ const voidDialog = page.getByRole("dialog", {
+ name: "Void this envelope?",
+ });
+
+ await voidDialog.getByRole("textbox").fill("Wrong supplier name.");
+ await voidDialog.getByRole("button", { name: "Void envelope" }).click();
+ await expect(
+ page.getByText("Voided", { exact: true }).first(),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("link", { name: "View document" }),
+ ).toHaveAttribute("href", documentUrl());
+ await expectTheDocumentAsSent(page, documentUrl());
+ });
+
+ await test.step("an administrator opening another member's document is on record", async () => {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+
+ await database.connect();
+
+ try {
+ await database.query(
+ `
+ insert into public."user" (id, name, email, "emailVerified")
+ values ($1, 'Morgan Member', $2, true)
+ on conflict (id) do nothing
+ `,
+ [OTHER_MEMBER_ID, OTHER_MEMBER_EMAIL],
+ );
+ await database.query(`update envelopes set user_id = $1 where id = $2`, [
+ OTHER_MEMBER_ID,
+ envelopeId,
+ ]);
+ } finally {
+ await database.end();
+ }
+
+ await page.goto(`/envelopes/${envelopeId}`);
+ await expect(page.getByText(/Sent by Morgan Member/)).toBeVisible();
+ await expect(
+ page.getByRole("link", { name: "View document" }),
+ ).toHaveAttribute("href", documentUrl());
+
+ const before = await countOriginalViews(envelopeId);
+
+ await expectTheDocumentAsSent(page, documentUrl());
+ expect(await countOriginalViews(envelopeId)).toBe(before + 1);
+ });
+});
diff --git a/src/app/api/envelopes/[id]/document/route.ts b/src/app/api/envelopes/[id]/document/route.ts
index 2a9059d..514b61b 100644
--- a/src/app/api/envelopes/[id]/document/route.ts
+++ b/src/app/api/envelopes/[id]/document/route.ts
@@ -10,6 +10,7 @@ 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 EnvelopeDocumentRouteContext = {
params: Promise<{
@@ -42,6 +43,27 @@ export async function GET(
id,
{ database: getDb() },
);
+
+ if (access && !access.viewerIsOwner) {
+ // An administrator opening someone else's document is on record in
+ // the install's audit trail, as a download of its files is. 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: "original",
+ ownerEmail: access.ownerEmail,
+ ownerUserId: access.ownerUserId,
+ },
+ targetUserId: access.ownerUserId,
+ userAgent: request.headers.get("user-agent"),
+ });
+ }
+
const responseBody = document.body.slice().buffer as ArrayBuffer;
return new Response(responseBody, {
@@ -53,6 +75,7 @@ export async function GET(
),
"content-length": String(document.contentLength),
"content-type": document.contentType,
+ "x-content-type-options": "nosniff",
},
status: 200,
});
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index ab759a7..b969d71 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -4,6 +4,7 @@ import {
CheckIcon,
ClockIcon,
DownloadIcon,
+ FileTextIcon,
MinusIcon,
PencilIcon,
XIcon,
@@ -246,6 +247,15 @@ export function EnvelopeDetailShell({
reminderIntervalDays === null
? "Automatic reminders are off."
: `Automatic reminders: ${formatReminderInterval(reminderIntervalDays).toLowerCase()}.`;
+ // The document as it was sent, before anyone signed: while it is out for
+ // signature, and once it was declined or voided. A completed envelope
+ // has its signed PDF instead.
+ const documentUrl =
+ activeRecord.status === "sent" ||
+ activeRecord.status === "declined" ||
+ activeRecord.status === "voided"
+ ? `/api/envelopes/${encodeURIComponent(envelopeId)}/document`
+ : null;
const activeSigner =
activeRecord.status === "sent"
? activeRecord.signers.find((signer) => signer.status === "waiting")
@@ -545,12 +555,27 @@ export function EnvelopeDetailShell({
<div className="mt-5 flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
<div className="flex min-w-0 items-center gap-5">
- <span className="hidden h-28 shrink-0 items-center justify-center rounded-2xl bg-(--surface) px-4 py-3 sm:flex">
- <DocumentThumbnail
- envelopeId={envelopeId}
- title={activeRecord.title}
- />
- </span>
+ {documentUrl ? (
+ <a
+ aria-label={`View ${activeRecord.title} (opens in a new tab)`}
+ className="hidden h-28 shrink-0 items-center justify-center rounded-2xl bg-(--surface) px-4 py-3 outline-none transition hover:bg-(--surface-strong) focus-visible:ring-3 focus-visible:ring-ring/50 sm:flex"
+ href={documentUrl}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ <DocumentThumbnail
+ envelopeId={envelopeId}
+ title={activeRecord.title}
+ />
+ </a>
+ ) : (
+ <span className="hidden h-28 shrink-0 items-center justify-center rounded-2xl bg-(--surface) px-4 py-3 sm:flex">
+ <DocumentThumbnail
+ envelopeId={envelopeId}
+ title={activeRecord.title}
+ />
+ </span>
+ )}
<div className="min-w-0 space-y-2.5">
<h1
className={`text-[clamp(1.5rem,3vw,1.875rem)] font-extrabold leading-tight tracking-[-0.03em] wrap-break-word ${
@@ -589,6 +614,17 @@ export function EnvelopeDetailShell({
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap lg:justify-end">
+ {documentUrl ? (
+ <ShellButton href={documentUrl} inNewTab variant="secondary">
+ <FileTextIcon
+ aria-hidden="true"
+ className="size-[1.125rem]"
+ strokeWidth={2.2}
+ />
+ View document
+ </ShellButton>
+ ) : null}
+
{isOwnEnvelope && activeRecord.status === "draft" ? (
<>
<ShellButton
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index 746cad2..46ca5ef 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -142,6 +142,7 @@ function describeEvent(event: SystemAuditEvent): string {
const downloadedFileLabels: Record<string, string> = {
audit_trail: "audit trail",
evidence: "certificate",
+ original: "document as sent",
signed: "signed PDF",
};
diff --git a/src/components/shared/form-shell.tsx b/src/components/shared/form-shell.tsx
index 28e8560..2479161 100644
--- a/src/components/shared/form-shell.tsx
+++ b/src/components/shared/form-shell.tsx
@@ -44,6 +44,11 @@ type ShellButtonProps = {
className?: string;
disabled?: boolean;
href?: string;
+ /**
+ * With `href`: open it in a new tab, as a plain link rather than a page
+ * of this app (a file served by an API route, say).
+ */
+ inNewTab?: boolean;
loading?: boolean;
onClick?: () => void;
type?: "button" | "submit";
@@ -135,6 +140,7 @@ export function ShellButton({
className = "",
disabled = false,
href,
+ inNewTab = false,
loading = false,
onClick,
type = "button",
@@ -157,6 +163,16 @@ export function ShellButton({
</>
);
+ if (href && inNewTab && !disabled && !loading) {
+ return (
+ <Button asChild className={shellButtonClassName} variant={buttonVariant}>
+ <a href={href} rel="noopener noreferrer" target="_blank">
+ {children}
+ </a>
+ </Button>
+ );
+ }
+
if (href && !disabled && !loading) {
return (
<Button asChild className={shellButtonClassName} variant={buttonVariant}>