Skip to content

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

TypeScript

Tidy the edges of teams and approvers

Claudef0466cd61b13
diff --git a/e2e/signing-with-approvers.spec.ts b/e2e/signing-with-approvers.spec.ts
new file mode 100644
index 0000000..4e2b33b
--- /dev/null
+++ b/e2e/signing-with-approvers.spec.ts
@@ -0,0 +1,151 @@
+import { expect, test } from "@playwright/test";
+
+import { signInAsAdministrator } from "./support/admin-session";
+import { extractLink, waitForEmail } from "./support/outbox";
+import { writeSamplePdf } from "./support/sample-pdf";
+
+// Runs after signing-flow.spec.ts, which sets up the install and its
+// administrator. A signer signs, then an approver approves and that
+// finishes the envelope.
+
+const SIGNER = { email: "[email protected]", name: "Sam Signer" };
+const APPROVER = { email: "[email protected]", name: "Alex Approver" };
+
+test("an approver approves after the signer, and that finishes the envelope", async ({
+ browser,
+ page,
+}, testInfo) => {
+ await test.step("the sender adds a signer and an approver", async () => {
+ await signInAsAdministrator(page);
+
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("approval.pdf"));
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill("Needs an approval");
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+
+ await page.getByLabel("Signer 1 name").fill(SIGNER.name);
+ await page.getByLabel("Signer 1 email").fill(SIGNER.email);
+ await page.getByRole("button", { name: "+ Add another signer" }).click();
+ await page.getByLabel("Signer 2 name").fill(APPROVER.name);
+ await page.getByLabel("Signer 2 email").fill(APPROVER.email);
+ await page.getByLabel("Signer 2 role").selectOption("approver");
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/prepare$/);
+
+ // Only the signer gets fields; the approver is not offered.
+ await expect(
+ page.getByRole("button", { name: /Alex Approver \d+ fields? placed/ }),
+ ).toHaveCount(0);
+ await page
+ .getByRole("button", { name: /Sam Signer \d+ fields? placed/ })
+ .click();
+ 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.3 },
+ });
+ 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 expect(confirmation).toContainText(
+ "will be sent to 1 signer and 1 approver.",
+ );
+ await expect(confirmation).toContainText(
+ "The first person (Sam Signer) will be notified immediately.",
+ );
+ await confirmation.getByRole("checkbox").check();
+ await confirmation.getByRole("button", { name: "Send now" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+$/);
+ });
+
+ await test.step("the signer signs", async () => {
+ const invitation = await waitForEmail({
+ template: "signing_invitation",
+ to: SIGNER.email,
+ });
+ const context = await browser.newContext({
+ viewport: { height: 900, width: 1440 },
+ });
+ const signerPage = await context.newPage();
+
+ await signerPage.goto(extractLink(invitation.text, "/sign/"));
+
+ const consent = signerPage.getByRole("dialog", { name: "Before you sign" });
+
+ await consent
+ .getByRole("checkbox", {
+ name: "I agree to use electronic records and signatures",
+ })
+ .check();
+ await consent.getByRole("button", { name: "Agree and continue" }).click();
+ await expect(consent).toBeHidden();
+ await signerPage
+ .getByRole("button", { exact: true, name: "Signature" })
+ .click();
+ await signerPage
+ .getByRole("dialog", { name: "Add your signature" })
+ .getByRole("button", { name: "Apply signature" })
+ .click();
+ await signerPage.getByRole("button", { name: "Finish" }).click();
+ await signerPage
+ .getByRole("dialog", { name: "Finish signing?" })
+ .getByRole("button", { name: "Finish signing" })
+ .click();
+ await expect(signerPage).toHaveURL(/\/sign\/[^/]+\/done/);
+ await context.close();
+ });
+
+ await test.step("the approver approves, which completes it", async () => {
+ const invitation = await waitForEmail({
+ template: "signing_invitation",
+ to: APPROVER.email,
+ });
+ const context = await browser.newContext({
+ viewport: { height: 900, width: 1440 },
+ });
+ const approverPage = await context.newPage();
+
+ await approverPage.goto(extractLink(invitation.text, "/sign/"));
+
+ const consent = approverPage.getByRole("dialog", {
+ name: "Before you approve",
+ });
+
+ await consent
+ .getByRole("checkbox", {
+ name: "I agree to use electronic records and signatures",
+ })
+ .check();
+ await consent.getByRole("button", { name: "Agree and continue" }).click();
+ await expect(consent).toBeHidden();
+ await approverPage
+ .getByRole("button", { exact: true, name: "Approve" })
+ .click();
+ await approverPage
+ .getByRole("dialog", { name: "Approve this document?" })
+ .getByRole("button", { exact: true, name: "Approve" })
+ .click();
+ await expect(approverPage).toHaveURL(/\/sign\/[^/]+\/done/);
+ await expect(
+ approverPage.getByText("Your approval has been recorded"),
+ ).toBeVisible();
+ await context.close();
+
+ await waitForEmail({
+ template: "completion_notification",
+ to: APPROVER.email,
+ });
+ });
+});
diff --git a/src/app/api/signing/[token]/approve/route.ts b/src/app/api/signing/[token]/approve/route.ts
index df28159..26eacde 100644
--- a/src/app/api/signing/[token]/approve/route.ts
+++ b/src/app/api/signing/[token]/approve/route.ts
@@ -21,6 +21,7 @@ import {
getClientIpAddress,
getRequestUserAgent,
} from "@/lib/security/request";
+import { readLimitedBody } from "@/lib/utils/limited-body";
// An approver approves the document. Rejecting goes through the decline
// route, which records a rejection for an approver (signing.ts). The same
@@ -34,6 +35,26 @@ type ApproveRouteContext = {
const NO_STORE = { "cache-control": "private, no-store" };
+/** An approval is one small number; nothing needs more than this. */
+const MAX_APPROVAL_BODY_BYTES = 4 * 1024;
+
+/** The JSON body, or null when it is too large or not JSON. */
+async function readApprovalBody(request: Request): Promise<unknown> {
+ const body = await readLimitedBody(request, MAX_APPROVAL_BODY_BYTES).catch(
+ () => null,
+ );
+
+ if (!body) {
+ return null;
+ }
+
+ try {
+ return JSON.parse(new TextDecoder().decode(body)) as unknown;
+ } catch {
+ return null;
+ }
+}
+
export async function POST(request: Request, context: ApproveRouteContext) {
const { token } = await context.params;
const rateLimitResponse = await applyPublicLinkRateLimit({
@@ -52,7 +73,7 @@ export async function POST(request: Request, context: ApproveRouteContext) {
return rateLimitResponse;
}
- const body = (await request.json().catch(() => null)) as unknown;
+ const body = await readApprovalBody(request);
try {
const payload = await approveSigningForToken(token, body, {
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index d2558cd..34c2016 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -537,7 +537,14 @@ export function ReviewShell({
)
: null
}
- signerCount={activeRecord.signers.length}
+ approverCount={
+ activeRecord.signers.filter((signer) => signer.role === "approver")
+ .length
+ }
+ signerCount={
+ activeRecord.signers.filter((signer) => signer.role !== "approver")
+ .length
+ }
title={activeRecord.title}
/>
) : null}
@@ -546,6 +553,8 @@ export function ReviewShell({
}
type SendConfirmationDialogProps = {
+ /** Approvers in the signing order, who approve or reject. */
+ approverCount: number;
deadlineDays: number;
errorMessage: string | null;
firstSignerName: string;
@@ -556,11 +565,25 @@ type SendConfirmationDialogProps = {
onConfirm: () => void;
/** Set when signers sign through the install's signing provider. */
signatureType: string | null;
+ /** Signers in the signing order, not counting approvers. */
signerCount: number;
title: string;
};
+/** "1 signer", "2 signers and 1 approver" and so on. */
+function describeSigningOrderPeople(
+ signerCount: number,
+ approverCount: number,
+): string {
+ const signers = `${signerCount} ${signerCount === 1 ? "signer" : "signers"}`;
+
+ return approverCount > 0
+ ? `${signers} and ${approverCount} ${approverCount === 1 ? "approver" : "approvers"}`
+ : signers;
+}
+
function SendConfirmationDialog({
+ approverCount,
deadlineDays,
errorMessage,
firstSignerName,
@@ -573,6 +596,8 @@ function SendConfirmationDialog({
title,
}: SendConfirmationDialogProps) {
const [isPermittedUseConfirmed, setIsPermittedUseConfirmed] = useState(false);
+ const peopleCount = signerCount + approverCount;
+ const firstLabel = approverCount > 0 ? "person" : "signer";
return (
<Dialog
@@ -590,13 +615,13 @@ function SendConfirmationDialog({
<DialogDescription asChild>
<div className="space-y-3 text-sm leading-6 text-(--secondary)">
<p>
- &quot;{title}&quot; will be sent to {signerCount}{" "}
- {signerCount === 1 ? "signer" : "signers"}.{" "}
- {signerCount === 1
+ &quot;{title}&quot; will be sent to{" "}
+ {describeSigningOrderPeople(signerCount, approverCount)}.{" "}
+ {peopleCount === 1
? `${firstSignerName} will be notified immediately.`
: firstStepSize > 1
- ? `${firstSignerName} will be notified immediately, to sign at the same time.`
- : `The first signer (${firstSignerName}) will be notified immediately.`}{" "}
+ ? `${firstSignerName} will be notified immediately, ${approverCount > 0 ? "to act" : "to sign"} at the same time.`
+ : `The first ${firstLabel} (${firstSignerName}) will be notified immediately.`}{" "}
The request expires in {deadlineDays} days.
</p>
{signatureType ? (
diff --git a/src/components/settings/teams-panel.tsx b/src/components/settings/teams-panel.tsx
index 62e77cc..0807a09 100644
--- a/src/components/settings/teams-panel.tsx
+++ b/src/components/settings/teams-panel.tsx
@@ -19,6 +19,9 @@ export function TeamsPanel() {
const [pending, setPending] = useState(false);
const [newName, setNewName] = useState("");
const [memberEmails, setMemberEmails] = useState<Record<string, string>>({});
+ // Until the first list arrives, no change is sent: its answer could land
+ // before the list and then be overwritten by it, hiding the change.
+ const loading = teams === null && error === null;
useEffect(() => {
const controller = new AbortController();
@@ -53,7 +56,7 @@ export function TeamsPanel() {
method: "DELETE" | "PATCH" | "POST",
body?: unknown,
): Promise<boolean> {
- if (pending) {
+ if (pending || loading) {
return false;
}
@@ -172,7 +175,7 @@ export function TeamsPanel() {
</span>
<input
className="field-input"
- disabled={pending}
+ disabled={pending || loading}
maxLength={80}
onChange={(event) => setNewName(event.target.value)}
placeholder="Sales"
@@ -181,7 +184,7 @@ export function TeamsPanel() {
/>
</label>
<ShellButton
- disabled={pending || newName.trim().length === 0}
+ disabled={pending || loading || newName.trim().length === 0}
type="submit"
>
Add team
diff --git a/src/components/verify/verify-form.tsx b/src/components/verify/verify-form.tsx
index 324651d..179e3cb 100644
--- a/src/components/verify/verify-form.tsx
+++ b/src/components/verify/verify-form.tsx
@@ -9,6 +9,7 @@ type VerifyAnswer =
fileKind: "signed-document" | "certificate";
finishedAt: number | null;
match: true;
+ approverCount?: number;
signerCount: number;
status: "completed" | "declined" | "voided";
title: string;
@@ -123,8 +124,11 @@ export function VerifyForm() {
? ` on ${dateFormatter.format(new Date(answer.finishedAt * 1000))} UTC`
: ""}{" "}
with {answer.signerCount} signer
- {answer.signerCount === 1 ? "" : "s"}. Envelope ID{" "}
- {answer.envelopeId}.
+ {answer.signerCount === 1 ? "" : "s"}
+ {answer.approverCount
+ ? ` and ${answer.approverCount} approver${answer.approverCount === 1 ? "" : "s"}`
+ : ""}
+ . Envelope ID {answer.envelopeId}.
</p>
</div>
) : null}
diff --git a/src/lib/verify.ts b/src/lib/verify.ts
index 564d109..95363ff 100644
--- a/src/lib/verify.ts
+++ b/src/lib/verify.ts
@@ -22,12 +22,15 @@ export type VerifyResult =
fileKind: "signed-document" | "certificate";
finishedAt: number | null;
match: true;
+ /** People who approved or rejected instead of signing. */
+ approverCount: number;
signerCount: number;
status: "completed" | "declined" | "voided";
title: string;
};
type VerifyRow = {
+ approverCount: number;
completedAt: number | null;
declinedAt: number | null;
envelopeId: string;
@@ -57,7 +60,8 @@ export async function verifyDocumentHash(
e.signed_pdf_sha256 AS "signedPdfSha256",
e.evidence_sha256 AS "evidenceSha256",
e.recipient_evidence_sha256 AS "recipientEvidenceSha256",
- (SELECT count(*)::int FROM signers s WHERE s.envelope_id = e.id AND s.role = 'signer') AS "signerCount"
+ (SELECT count(*)::int FROM signers s WHERE s.envelope_id = e.id AND s.role = 'signer') AS "signerCount",
+ (SELECT count(*)::int FROM signers s WHERE s.envelope_id = e.id AND s.role = 'approver') AS "approverCount"
FROM envelopes e
WHERE e.signed_pdf_sha256 = $1
OR e.evidence_sha256 = $1
@@ -72,6 +76,7 @@ export async function verifyDocumentHash(
}
return {
+ approverCount: row.approverCount,
envelopeId: row.envelopeId,
fileKind:
row.signedPdfSha256 === sha256 ? "signed-document" : "certificate",