Skip to content

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

TypeScript

Add copy recipients, who get the finished document without signing

Claude0641185f42c0
diff --git a/db/migrations/20261114110000_copy_recipients.sql b/db/migrations/20261114110000_copy_recipients.sql
new file mode 100644
index 0000000..3993a35
--- /dev/null
+++ b/db/migrations/20261114110000_copy_recipients.sql
@@ -0,0 +1,25 @@
+-- People who receive a copy of the finished document without signing it.
+--
+-- They live in the signers table, marked by role, so that everything keyed
+-- to a recipient already covers them: download links, the signer data
+-- request tools and the retention period. A copy recipient is never part
+-- of the signing order: it stays 'pending' and never holds a signing link.
+
+alter table public.signers
+ add column if not exists role text not null default 'signer';
+
+alter table public.signers
+ drop constraint if exists signers_role_check;
+
+alter table public.signers
+ add constraint signers_role_check check (role in ('signer', 'cc'));
+
+alter table public.signers
+ drop constraint if exists signers_copy_recipient_never_signs;
+
+alter table public.signers
+ add constraint signers_copy_recipient_never_signs
+ check (
+ role = 'signer'
+ or (status = 'pending' and signing_token_hash is null)
+ );
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index 605d345..146a207 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -601,6 +601,31 @@ export function EnvelopeDetailShell({
);
})}
</ol>
+
+ {record.copyRecipients && record.copyRecipients.length > 0 ? (
+ <div className="mt-6">
+ <h3 className="text-[0.9375rem] font-extrabold text-(--fg)">
+ Receives a copy
+ </h3>
+ <p className="mt-1 text-sm leading-6 text-(--secondary)">
+ {activeRecord.status === "completed"
+ ? "Sent the finished document and its certificate."
+ : "Gets the finished document once everyone has signed."}
+ </p>
+ <ul className="mt-3 space-y-2">
+ {record.copyRecipients.map((recipient) => (
+ <li className="well px-4 py-3" key={recipient.id}>
+ <p className="truncate text-[0.9375rem] font-bold text-(--fg)">
+ {recipient.name}
+ </p>
+ <p className="truncate text-sm text-(--secondary)">
+ {recipient.email}
+ </p>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
</article>
<article className="panel p-5 sm:p-7">
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index ea7c04a..5518f00 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -37,6 +37,7 @@ type ReviewShellProps = {
};
type ReviewRecordView = {
+ copyRecipients: readonly { email: string; id: string; name: string }[];
filename: string;
pageCount: number;
signers: readonly ReviewSigner[];
@@ -204,6 +205,7 @@ export function ReviewShell({
}
const activeRecord: ReviewRecordView = {
+ copyRecipients: record.copyRecipients ?? [],
filename: record.filename,
pageCount: record.pageCount,
signers: record.signers.map((signer) => ({ ...signer })),
@@ -330,6 +332,21 @@ export function ReviewShell({
})}
</ol>
+ {activeRecord.copyRecipients.length > 0 ? (
+ <div className="well mt-3 p-4">
+ <p className="text-[0.9375rem] font-bold text-(--fg)">
+ Copies when everyone has signed
+ </p>
+ <ul className="mt-2 space-y-1 text-sm leading-6 text-(--secondary)">
+ {activeRecord.copyRecipients.map((recipient) => (
+ <li className="truncate" key={recipient.id}>
+ {recipient.name} · {recipient.email}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+
<p className="notice notice-accent mt-4 font-medium">
After you send, Signer 1 will receive an email with a link to
sign. Each signer is notified in order after the previous signer
diff --git a/src/components/envelopes/signers-shell.tsx b/src/components/envelopes/signers-shell.tsx
index 7156305..25f5dca 100644
--- a/src/components/envelopes/signers-shell.tsx
+++ b/src/components/envelopes/signers-shell.tsx
@@ -12,10 +12,14 @@ import { StatusPanel } from "@/components/shared/status-panel";
import { StepIndicator } from "@/components/shared/step-indicator";
import type { DraftSignerStepData } from "@/lib/envelopes";
import {
+ duplicateCopyRecipientEmailMessage,
duplicateSignerEmailMessage,
type ReplaceSignersResponse,
} from "@/lib/schemas/signer";
-import { MAX_SIGNERS_PER_ENVELOPE } from "@/lib/types/domain";
+import {
+ MAX_COPY_RECIPIENTS_PER_ENVELOPE,
+ MAX_SIGNERS_PER_ENVELOPE,
+} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
const envelopeSteps = ["Upload", "Signers", "Place fields", "Review"];
@@ -53,7 +57,17 @@ type SignerErrors = {
name?: string;
};
+/** Someone who gets the finished document without signing it. */
+type ShellCopyRecipient = {
+ email: string;
+ localId: string;
+ name: string;
+ recipientId?: string;
+ touched: Record<SignerField, boolean>;
+};
+
type InitialModel = {
+ copyRecipients: ShellCopyRecipient[];
showAllErrors: boolean;
signers: ShellSigner[];
};
@@ -97,11 +111,53 @@ function buildInitialModel(record?: DraftSignerStepData): InitialModel {
) ?? [];
return {
+ copyRecipients: (record?.copyRecipients ?? []).map((recipient) => ({
+ email: recipient.email,
+ localId: recipient.id,
+ name: recipient.name,
+ recipientId: recipient.id,
+ touched: { email: true, name: true },
+ })),
showAllErrors: false,
signers: signers.length > 0 ? signers : [createSigner("signer-1")],
};
}
+function buildCopyRecipientErrors(
+ copyRecipients: readonly ShellCopyRecipient[],
+ signers: readonly ShellSigner[],
+) {
+ const errorsByLocalId: Record<string, SignerErrors> = {};
+ const taken = new Set(
+ signers
+ .map((signer) => signer.email.trim().toLowerCase())
+ .filter((email) => email.length > 0),
+ );
+
+ for (const recipient of copyRecipients) {
+ const errors: SignerErrors = {};
+ const normalizedEmail = recipient.email.trim().toLowerCase();
+
+ if (recipient.name.trim().length === 0) {
+ errors.name = "Name is required";
+ }
+
+ if (
+ normalizedEmail.length === 0 ||
+ !validEmailPattern.test(normalizedEmail)
+ ) {
+ errors.email = "Enter a valid email address";
+ } else if (taken.has(normalizedEmail)) {
+ errors.email = duplicateCopyRecipientEmailMessage;
+ }
+
+ taken.add(normalizedEmail);
+ errorsByLocalId[recipient.localId] = errors;
+ }
+
+ return errorsByLocalId;
+}
+
function buildSignerErrors(signers: readonly ShellSigner[]) {
const errorsBySignerId: Record<string, SignerErrors> = {};
const emailCounts = signers.reduce<Record<string, number>>(
@@ -180,8 +236,16 @@ function reorderSigners(
return nextSigners;
}
-function buildSignerRequest(signers: readonly ShellSigner[]) {
+function buildSignerRequest(
+ signers: readonly ShellSigner[],
+ copyRecipients: readonly ShellCopyRecipient[],
+) {
return {
+ copyRecipients: copyRecipients.map((recipient) => ({
+ email: recipient.email,
+ id: recipient.recipientId,
+ name: recipient.name,
+ })),
signers: signers.map((signer, index) => ({
accessCode:
signer.accessCode.trim().length > 0
@@ -456,6 +520,105 @@ function SignerCard({
);
}
+function CopyRecipientCard({
+ disabled = false,
+ emailError,
+ index,
+ nameError,
+ onBlur,
+ onChange,
+ onRemove,
+ recipient,
+}: {
+ disabled?: boolean;
+ emailError?: string;
+ index: number;
+ nameError?: string;
+ onBlur: (field: SignerField) => void;
+ onChange: (field: SignerField, value: string) => void;
+ onRemove: () => void;
+ recipient: ShellCopyRecipient;
+}) {
+ const position = index + 1;
+
+ return (
+ <li className="well p-4 sm:p-5">
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-3">
+ <span className="pill pill-neutral">Copy {position}</span>
+ <button
+ aria-label={`Remove copy recipient ${position}`}
+ className="btn-quiet btn-quiet-danger"
+ disabled={disabled}
+ onClick={onRemove}
+ type="button"
+ >
+ Remove
+ </button>
+ </div>
+
+ <div className="grid gap-x-4 gap-y-1 md:grid-cols-2">
+ <label className="grid auto-rows-min gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Name
+ </span>
+ <input
+ aria-invalid={nameError ? true : undefined}
+ aria-label={`Copy recipient ${position} name`}
+ className="field-input"
+ disabled={disabled}
+ onBlur={() => onBlur("name")}
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ onChange("name", event.target.value)
+ }
+ placeholder="Alex Jones"
+ type="text"
+ value={recipient.name}
+ />
+ <span
+ aria-live="polite"
+ className={`min-h-4 text-xs font-semibold text-(--danger) ${
+ nameError ? "" : "invisible"
+ }`}
+ role={nameError ? "alert" : undefined}
+ >
+ {nameError ?? " "}
+ </span>
+ </label>
+
+ <label className="grid auto-rows-min gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Email
+ </span>
+ <input
+ aria-invalid={emailError ? true : undefined}
+ aria-label={`Copy recipient ${position} email`}
+ className="field-input"
+ disabled={disabled}
+ onBlur={() => onBlur("email")}
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ onChange("email", event.target.value)
+ }
+ placeholder="[email protected]"
+ type="email"
+ value={recipient.email}
+ />
+ <span
+ aria-live="polite"
+ className={`min-h-4 text-xs font-semibold text-(--danger) ${
+ emailError ? "" : "invisible"
+ }`}
+ role={emailError ? "alert" : undefined}
+ >
+ {emailError ?? " "}
+ </span>
+ </label>
+ </div>
+ </div>
+ </li>
+ );
+}
+
export function SignersShell({
envelopeId,
initialState,
@@ -463,6 +626,12 @@ export function SignersShell({
}: SignersShellProps) {
const initialModel = buildInitialModel(record);
const [signers, setSigners] = useState(initialModel.signers);
+ const [copyRecipients, setCopyRecipients] = useState(
+ initialModel.copyRecipients,
+ );
+ const nextCopyRecipientNumberRef = useRef(
+ initialModel.copyRecipients.length + 1,
+ );
const [showAllErrors, setShowAllErrors] = useState(
initialModel.showAllErrors,
);
@@ -471,11 +640,21 @@ export function SignersShell({
const nextSignerNumberRef = useRef(initialModel.signers.length + 1);
const errorsBySignerId = buildSignerErrors(signers);
+ const errorsByCopyRecipientId = buildCopyRecipientErrors(
+ copyRecipients,
+ signers,
+ );
const canAddSigner = signers.length < MAX_SIGNERS_PER_ENVELOPE;
+ const canAddCopyRecipient =
+ copyRecipients.length < MAX_COPY_RECIPIENTS_PER_ENVELOPE;
const canContinue =
signers.length > 0 &&
signers.every(
(signer) => !hasSignerErrors(errorsBySignerId[signer.localId] ?? {}),
+ ) &&
+ copyRecipients.every(
+ (recipient) =>
+ !hasSignerErrors(errorsByCopyRecipientId[recipient.localId] ?? {}),
);
function clearSubmitError() {
@@ -529,6 +708,59 @@ export function SignersShell({
);
}
+ function handleAddCopyRecipient() {
+ if (!canAddCopyRecipient || isSubmitting) {
+ return;
+ }
+
+ clearSubmitError();
+ const number = nextCopyRecipientNumberRef.current;
+ nextCopyRecipientNumberRef.current += 1;
+ setCopyRecipients((current) => [
+ ...current,
+ {
+ email: "",
+ localId: `copy-${number}`,
+ name: "",
+ touched: { email: false, name: false },
+ },
+ ]);
+ }
+
+ function handleCopyRecipientChange(
+ localId: string,
+ patch: Partial<Pick<ShellCopyRecipient, "email" | "name">>,
+ ) {
+ clearSubmitError();
+ setShowAllErrors(false);
+ setCopyRecipients((current) =>
+ current.map((recipient) =>
+ recipient.localId === localId ? { ...recipient, ...patch } : recipient,
+ ),
+ );
+ }
+
+ function handleCopyRecipientBlur(localId: string, field: SignerField) {
+ setCopyRecipients((current) =>
+ current.map((recipient) =>
+ recipient.localId === localId
+ ? { ...recipient, touched: { ...recipient.touched, [field]: true } }
+ : recipient,
+ ),
+ );
+ }
+
+ function handleRemoveCopyRecipient(localId: string) {
+ if (isSubmitting) {
+ return;
+ }
+
+ clearSubmitError();
+ setCopyRecipients((current) =>
+ current.filter((recipient) => recipient.localId !== localId),
+ );
+ }
+
function handleAddSigner() {
if (!canAddSigner || isSubmitting) {
return;
@@ -582,7 +814,7 @@ export function SignersShell({
try {
const response = await fetch(`/api/envelopes/${envelopeId}/signers`, {
- body: JSON.stringify(buildSignerRequest(signers)),
+ body: JSON.stringify(buildSignerRequest(signers, copyRecipients)),
headers: {
"content-type": "application/json",
},
@@ -710,6 +942,76 @@ export function SignersShell({
) : null}
</div>
+ <div className="space-y-3 pt-3">
+ <div className="space-y-1">
+ <h2 className="text-lg font-extrabold text-(--fg)">
+ Send a copy to{" "}
+ <span className="text-sm font-normal text-(--secondary)">
+ (optional)
+ </span>
+ </h2>
+ <p className="text-sm leading-6 text-(--secondary)">
+ These people do not sign. They receive the finished document and
+ its certificate once everyone has signed.
+ </p>
+ </div>
+
+ {copyRecipients.length > 0 ? (
+ <ol className="space-y-3">
+ {copyRecipients.map((recipient, index) => {
+ const errors =
+ errorsByCopyRecipientId[recipient.localId] ?? {};
+
+ return (
+ <CopyRecipientCard
+ disabled={isSubmitting}
+ emailError={
+ showAllErrors || recipient.touched.email
+ ? errors.email
+ : undefined
+ }
+ index={index}
+ key={recipient.localId}
+ nameError={
+ showAllErrors || recipient.touched.name
+ ? errors.name
+ : undefined
+ }
+ onBlur={(field) =>
+ handleCopyRecipientBlur(recipient.localId, field)
+ }
+ onChange={(field, value) =>
+ handleCopyRecipientChange(recipient.localId, {
+ [field]: value,
+ })
+ }
+ onRemove={() =>
+ handleRemoveCopyRecipient(recipient.localId)
+ }
+ recipient={recipient}
+ />
+ );
+ })}
+ </ol>
+ ) : null}
+
+ <div className="flex flex-wrap items-center gap-3">
+ <button
+ className="btn-quiet min-h-11 px-4.5"
+ disabled={!canAddCopyRecipient || isSubmitting}
+ onClick={handleAddCopyRecipient}
+ type="button"
+ >
+ + Add a copy recipient
+ </button>
+ {!canAddCopyRecipient ? (
+ <p className="text-[0.8125rem] font-semibold text-(--tertiary)">
+ Maximum reached
+ </p>
+ ) : null}
+ </div>
+ </div>
+
<div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-end">
<ShellButton href="/envelopes/new" variant="secondary">
← Back
diff --git a/src/lib/copy-recipients.dbtest.ts b/src/lib/copy-recipients.dbtest.ts
new file mode 100644
index 0000000..a538141
--- /dev/null
+++ b/src/lib/copy-recipients.dbtest.ts
@@ -0,0 +1,290 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+import { ZodError } from "zod";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import {
+ EnvelopeMutationError,
+ getDraftSignerStepDataForUser,
+ getEnvelopeDetailDataForUser,
+ getReviewEnvelopeDataForUser,
+ listCopyRecipientsForEnvelopeId,
+ replaceDraftEnvelopeSigners,
+} from "./envelopes.ts";
+import { exportSignerData } from "./signer-data.ts";
+
+// Copy recipients against a real Postgres: they are stored beside the
+// signers, and nothing that walks the signing order may see them.
+// 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 createDraft() {
+ const userId = randomUUID();
+ const envelopeId = randomUUID();
+
+ createdUsers.push(userId);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,
+ [userId, `${userId}@example.test`],
+ );
+ 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, 'Lease', 'draft', $3, 'lease.pdf', 10, 1, $4)
+ `,
+ [envelopeId, userId, `test/${envelopeId}.pdf`, "a".repeat(64)],
+ );
+
+ return { envelopeId, userId };
+}
+
+const riley = { email: "[email protected]", name: "Riley Recipient" };
+const casey = { email: "[email protected]", name: "Casey Second" };
+const zofia = { email: "[email protected]", name: "Zofia Copy" };
+const omar = { email: "[email protected]", name: "Omar Copy" };
+
+async function storedRows(envelopeId: string) {
+ const result = await database.query<{
+ email: string;
+ role: string;
+ sign_order: number;
+ status: string;
+ }>(
+ `
+ select email, role, sign_order, status from signers
+ where envelope_id = $1 order by sign_order
+ `,
+ [envelopeId],
+ );
+
+ return result.rows;
+}
+
+test("copy recipients are saved beside the signers and stay out of the signing order", async () => {
+ const { envelopeId, userId } = await createDraft();
+ const saved = await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [zofia, omar], signers: [riley, casey] },
+ database,
+ );
+
+ assert.deepEqual(
+ saved.signers.map((signer) => [signer.email, signer.signOrder]),
+ [
+ [riley.email, 1],
+ [casey.email, 2],
+ ],
+ );
+ assert.deepEqual(
+ saved.copyRecipients.map((recipient) => recipient.email),
+ [zofia.email, omar.email],
+ );
+ assert.deepEqual(
+ (await storedRows(envelopeId)).map((row) => [row.email, row.role]),
+ [
+ [riley.email, "signer"],
+ [casey.email, "signer"],
+ [zofia.email, "cc"],
+ [omar.email, "cc"],
+ ],
+ );
+
+ // Every screen that lists signers lists the two signers only.
+ const step = await getDraftSignerStepDataForUser(
+ userId,
+ envelopeId,
+ database,
+ );
+ const review = await getReviewEnvelopeDataForUser(
+ userId,
+ envelopeId,
+ database,
+ );
+ const detail = await getEnvelopeDetailDataForUser(
+ userId,
+ envelopeId,
+ database,
+ );
+
+ for (const view of [step, review, detail]) {
+ assert.deepEqual(
+ view?.signers.map((signer) => signer.email),
+ [riley.email, casey.email],
+ );
+ assert.deepEqual(
+ view?.copyRecipients.map((recipient) => recipient.email),
+ [zofia.email, omar.email],
+ );
+ }
+});
+
+test("saving the signers again keeps, replaces or removes the copy recipients", async () => {
+ const { envelopeId, userId } = await createDraft();
+ const first = await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [zofia], signers: [riley] },
+ database,
+ );
+ const zofiaId = first.copyRecipients[0]!.id;
+
+ // A request that does not mention copies leaves them alone, even when
+ // the signers are reordered around them.
+ await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { signers: [casey, { ...riley, id: first.signers[0]!.id }] },
+ database,
+ );
+ assert.deepEqual(
+ await listCopyRecipientsForEnvelopeId(envelopeId, database),
+ [{ ...zofia, id: zofiaId }],
+ );
+
+ // Naming them keeps the ones that carry their id and replaces the rest.
+ const replaced = await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ {
+ copyRecipients: [omar, { ...zofia, id: zofiaId, name: "Zofia Renamed" }],
+ signers: [riley],
+ },
+ database,
+ );
+
+ assert.deepEqual(
+ replaced.copyRecipients.map((recipient) => [
+ recipient.name,
+ recipient.id === zofiaId,
+ ]),
+ [
+ ["Omar Copy", false],
+ ["Zofia Renamed", true],
+ ],
+ );
+
+ await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [], signers: [riley] },
+ database,
+ );
+ assert.deepEqual(
+ (await storedRows(envelopeId)).map((row) => row.email),
+ [riley.email],
+ );
+});
+
+test("one address cannot be both a signer and a copy recipient", async () => {
+ const { envelopeId, userId } = await createDraft();
+
+ await assert.rejects(
+ replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ {
+ copyRecipients: [{ ...riley, email: "[email protected]" }],
+ signers: [riley],
+ },
+ database,
+ ),
+ ZodError,
+ );
+ await assert.rejects(
+ replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [zofia, zofia], signers: [riley] },
+ database,
+ ),
+ ZodError,
+ );
+
+ await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [zofia], signers: [riley] },
+ database,
+ );
+
+ // Signers only, and one of them is already down for a copy.
+ await assert.rejects(
+ replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { signers: [riley, zofia] },
+ database,
+ ),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError && error.statusCode === 400,
+ );
+ assert.deepEqual(
+ (await storedRows(envelopeId)).map((row) => [row.email, row.role]),
+ [
+ [riley.email, "signer"],
+ [zofia.email, "cc"],
+ ],
+ );
+});
+
+test("the database refuses to put a copy recipient into the signing order", async () => {
+ const { envelopeId, userId } = await createDraft();
+
+ await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [zofia], signers: [riley] },
+ database,
+ );
+
+ await assert.rejects(
+ database.query(
+ `update signers set status = 'notified' where envelope_id = $1 and role = 'cc'`,
+ [envelopeId],
+ ),
+ /signers_copy_recipient_never_signs/,
+ );
+ await assert.rejects(
+ database.query(
+ `update signers set signing_token_hash = $2 where envelope_id = $1 and role = 'cc'`,
+ [envelopeId, "b".repeat(64)],
+ ),
+ /signers_copy_recipient_never_signs/,
+ );
+});
+
+test("a data request for an address finds the envelopes it was copied on", async () => {
+ const { envelopeId, userId } = await createDraft();
+ const email = `${randomUUID()}@example.test`;
+
+ await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [{ email, name: "Copied Person" }], signers: [riley] },
+ database,
+ );
+
+ const exported = await exportSignerData(email, database);
+
+ assert.equal(exported.envelopes.length, 1);
+ assert.equal(exported.envelopes[0]?.role, "cc");
+});
diff --git a/src/lib/downloads.ts b/src/lib/downloads.ts
index ebaf97f..d0dfe74 100644
--- a/src/lib/downloads.ts
+++ b/src/lib/downloads.ts
@@ -341,6 +341,7 @@ async function listSignersForEnvelope(
updated_at AS "updatedAt"
FROM signers
WHERE envelope_id = $1
+ AND role = 'signer'
ORDER BY sign_order ASC, id ASC
`,
[envelopeId],
@@ -349,6 +350,24 @@ async function listSignersForEnvelope(
return rows.map(mapSignerRow);
}
+/** The people who were to get a copy without signing. */
+async function listCopyRecipientsForEnvelope(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<{ email: string; name: string }[]> {
+ return queryMany<{ email: string; name: string }>(
+ database,
+ `
+ SELECT name, email
+ FROM signers
+ WHERE envelope_id = $1
+ AND role = 'cc'
+ ORDER BY sign_order ASC, id ASC
+ `,
+ [envelopeId],
+ );
+}
+
async function storeRecipientDownloadToken(
{
envelopeId,
@@ -644,12 +663,16 @@ async function buildCertificateDownload(
throw new DownloadAccessError("This file is no longer available.", 404);
}
- const [auditEvents, signers] = await Promise.all([
+ const [auditEvents, signers, copyRecipients] = await Promise.all([
listAuditEventsForEnvelope(envelope.id, database),
listSignersForEnvelope(envelope.id, database),
+ listCopyRecipientsForEnvelope(envelope.id, database),
]);
const body = await renderEnvelopeCertificatePdf({
auditEvents,
+ // Only a finished envelope sends copies. A declined or voided one
+ // never did, so its certificate does not name anyone as having one.
+ copyRecipients: envelope.status === "completed" ? copyRecipients : [],
envelope,
redactForRecipients,
signedPdfSha256: envelope.signedPdfSha256,
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index e69fe68..063c53e 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -42,9 +42,11 @@ import {
type ReplaceFieldsResponse,
} from "./schemas/field.ts";
import {
+ duplicateCopyRecipientEmailMessage,
replaceSignersResponseSchema,
replaceSignersSchema,
signerRecordSchema,
+ type CopyRecipientRecord,
type ReplaceSignersResponse,
type SignerRecord,
} from "./schemas/signer.ts";
@@ -253,6 +255,7 @@ export type ReviewSignerSummary = {
export type ReviewEnvelopeData = {
canSend: boolean;
+ copyRecipients: readonly CopyRecipientRecord[];
disabledReason: string | null;
envelopeId: string;
filename: string;
@@ -275,6 +278,7 @@ export type DraftSignerStepSigner = {
};
export type DraftSignerStepData = {
+ copyRecipients: readonly CopyRecipientRecord[];
envelopeId: string;
signers: readonly DraftSignerStepSigner[];
status: EnvelopeRecord["status"];
@@ -321,6 +325,8 @@ export type EnvelopeDetailDeadline = {
};
export type EnvelopeDetailData = {
+ /** People who get a copy of the finished document without signing. */
+ copyRecipients: readonly CopyRecipientRecord[];
createdAtLabel: string;
/** Set while the envelope is out for signature. */
deadline: EnvelopeDetailDeadline | null;
@@ -341,6 +347,12 @@ export type DraftEnvelopeDocument = {
fileName: string;
};
+/**
+ * Copy recipients are stored after every signer. Signers use 1 to 10, and a
+ * rewrite of the signer list parks rows 1000 higher for a moment.
+ */
+const COPY_RECIPIENT_SIGN_ORDER_BASE = 500;
+
export class EnvelopeMutationError extends Error {
readonly statusCode: number;
@@ -731,6 +743,7 @@ async function listSignersForEnvelopeIds(
updated_at AS "updatedAt"
FROM signers
WHERE envelope_id IN (${placeholders})
+ AND role = 'signer'
ORDER BY envelope_id ASC, sign_order ASC, id ASC
`,
envelopeIds,
@@ -763,6 +776,57 @@ async function listSignersForEnvelopeId(
);
}
+/**
+ * The people who get a copy of the finished document without signing. They
+ * are rows of the signers table with role 'cc', which every other query
+ * here leaves out.
+ */
+export async function listCopyRecipientsForEnvelopeIds(
+ envelopeIds: readonly string[],
+ database: DbExecutor,
+): Promise<Map<string, CopyRecipientRecord[]>> {
+ const recipientsByEnvelope = new Map<string, CopyRecipientRecord[]>();
+
+ if (envelopeIds.length === 0) {
+ return recipientsByEnvelope;
+ }
+
+ const rows = await queryMany<CopyRecipientRecord & { envelopeId: string }>(
+ database,
+ `
+ SELECT id, envelope_id AS "envelopeId", name, email
+ FROM signers
+ WHERE envelope_id IN (${buildInClausePlaceholders(envelopeIds.length)})
+ AND role = 'cc'
+ ORDER BY envelope_id ASC, sign_order ASC, id ASC
+ `,
+ envelopeIds,
+ );
+
+ for (const { envelopeId, ...recipient } of rows) {
+ const existing = recipientsByEnvelope.get(envelopeId);
+
+ if (existing) {
+ existing.push(recipient);
+ } else {
+ recipientsByEnvelope.set(envelopeId, [recipient]);
+ }
+ }
+
+ return recipientsByEnvelope;
+}
+
+export async function listCopyRecipientsForEnvelopeId(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<CopyRecipientRecord[]> {
+ return (
+ (await listCopyRecipientsForEnvelopeIds([envelopeId], database)).get(
+ envelopeId,
+ ) ?? []
+ );
+}
+
async function listSignerCheckSettings(
envelopeId: string,
database: DbExecutor,
@@ -1197,10 +1261,12 @@ export async function listEnvelopesForUser(
const envelopes = rows.map(mapEnvelopeRow);
const envelopeIds = envelopes.map((envelope) => envelope.id);
- const [signersByEnvelope, fieldsByEnvelope] = await Promise.all([
- listSignersForEnvelopeIds(envelopeIds, database),
- listFieldsForEnvelopeIds(envelopeIds, database),
- ]);
+ const [signersByEnvelope, fieldsByEnvelope, copyRecipientsByEnvelope] =
+ await Promise.all([
+ listSignersForEnvelopeIds(envelopeIds, database),
+ listFieldsForEnvelopeIds(envelopeIds, database),
+ listCopyRecipientsForEnvelopeIds(envelopeIds, database),
+ ]);
return envelopes.map((envelope) => {
const signers = signersByEnvelope.get(envelope.id) ?? [];
@@ -1211,7 +1277,11 @@ export async function listEnvelopesForUser(
createdAtLabel: formatShortDate(envelope.createdAt),
expired: isEnvelopeExpired(envelope, Math.floor(Date.now() / 1000)),
id: envelope.id,
- searchableEmails: signers.map((signer) => signer.email),
+ // The search on the server matches copy recipients too.
+ searchableEmails: [
+ ...signers,
+ ...(copyRecipientsByEnvelope.get(envelope.id) ?? []),
+ ].map((recipient) => recipient.email),
status: envelope.status,
statusLabel: buildDashboardStatusLabel(envelope, signers),
title: envelope.title,
@@ -1230,11 +1300,13 @@ export async function getEnvelopeDetailDataForUser(
return null;
}
- const [signersByEnvelope, fieldsByEnvelope, auditEvents] = await Promise.all([
- listSignersForEnvelopeIds([envelopeId], database),
- listFieldsForEnvelopeIds([envelopeId], database),
- listAuditEventsForEnvelope(envelopeId, database),
- ]);
+ const [signersByEnvelope, fieldsByEnvelope, auditEvents, copyRecipients] =
+ await Promise.all([
+ listSignersForEnvelopeIds([envelopeId], database),
+ listFieldsForEnvelopeIds([envelopeId], database),
+ listAuditEventsForEnvelope(envelopeId, database),
+ listCopyRecipientsForEnvelopeId(envelopeId, database),
+ ]);
const signers = signersByEnvelope.get(envelopeId) ?? [];
const fields = fieldsByEnvelope.get(envelopeId) ?? [];
const fieldCountsBySigner = fields.reduce<Map<string, number>>(
@@ -1307,6 +1379,7 @@ export async function getEnvelopeDetailDataForUser(
}
return {
+ copyRecipients,
createdAtLabel: formatLongDate(envelope.createdAt),
deadline:
envelope.status === "sent"
@@ -1345,6 +1418,7 @@ export async function getDraftSignerStepDataForUser(
const checks = await listSignerCheckSettings(envelopeId, database);
return {
+ copyRecipients: await listCopyRecipientsForEnvelopeId(envelopeId, database),
envelopeId,
signers: (await listSignersForEnvelopeId(envelopeId, database)).map(
(signer) => ({
@@ -1541,10 +1615,12 @@ export async function getReviewEnvelopeDataForUser(
return null;
}
- const [signersByEnvelope, fieldsByEnvelope] = await Promise.all([
- listSignersForEnvelopeIds([envelopeId], database),
- listFieldsForEnvelopeIds([envelopeId], database),
- ]);
+ const [signersByEnvelope, fieldsByEnvelope, copyRecipients] =
+ await Promise.all([
+ listSignersForEnvelopeIds([envelopeId], database),
+ listFieldsForEnvelopeIds([envelopeId], database),
+ listCopyRecipientsForEnvelopeId(envelopeId, database),
+ ]);
const signers = signersByEnvelope.get(envelopeId) ?? [];
const fields = fieldsByEnvelope.get(envelopeId) ?? [];
const fieldsBySigner = buildFieldsBySigner(fields);
@@ -1556,6 +1632,7 @@ export async function getReviewEnvelopeDataForUser(
return {
canSend: !isEmpty && !missingSignatureSigner,
+ copyRecipients,
disabledReason: missingSignatureSigner
? `Every signer must have at least one Signature field before sending. ${missingSignatureSigner.name} is missing one.`
: null,
@@ -2425,6 +2502,41 @@ export async function replaceDraftEnvelopeSigners(
}
const existingSigners = await listSignersForEnvelopeId(envelopeId, database);
+ const existingCopyRecipients = await listCopyRecipientsForEnvelopeId(
+ envelopeId,
+ database,
+ );
+ const existingCopyRecipientIds = new Set(
+ existingCopyRecipients.map((recipient) => recipient.id),
+ );
+ // Left out of the request means "leave them as they are".
+ const nextCopyRecipients = (
+ parsedInput.copyRecipients ?? existingCopyRecipients
+ ).map((recipient, index) => ({
+ email: recipient.email,
+ id:
+ recipient.id && existingCopyRecipientIds.has(recipient.id)
+ ? recipient.id
+ : randomUUID(),
+ name: recipient.name,
+ // After every signer, and clear of the numbers the rewrite below
+ // parks rows on.
+ signOrder: COPY_RECIPIENT_SIGN_ORDER_BASE + index + 1,
+ }));
+ const signerEmails = new Set(
+ parsedInput.signers.map((signer) => signer.email.toLowerCase()),
+ );
+
+ // Checked by the schema when both lists arrive together. This covers a
+ // request that names only signers, one of whom is already a copy recipient.
+ if (
+ nextCopyRecipients.some((recipient) =>
+ signerEmails.has(recipient.email.toLowerCase()),
+ )
+ ) {
+ throw new EnvelopeMutationError(duplicateCopyRecipientEmailMessage, 400);
+ }
+
const existingSignerIds = new Set(existingSigners.map((signer) => signer.id));
const usedSignerIds = new Set<string>();
const updatedAt = Math.floor(Date.now() / 1000);
@@ -2455,6 +2567,13 @@ export async function replaceDraftEnvelopeSigners(
});
await withTransaction(async (tx) => {
+ // Copy recipients hold nothing but a name and an address while the
+ // envelope is a draft, so they are simply written again below.
+ await tx.query(
+ `DELETE FROM signers WHERE envelope_id = $1 AND role = 'cc'`,
+ [envelopeId],
+ );
+
if (existingSigners.length > 0) {
await tx.query(
`
@@ -2545,6 +2664,25 @@ export async function replaceDraftEnvelopeSigners(
[envelopeId, ...nextSigners.map((signer) => signer.id)],
);
+ for (const recipient of nextCopyRecipients) {
+ await tx.query(
+ `
+ INSERT INTO signers (
+ id, envelope_id, name, email, sign_order, status, role,
+ created_at, updated_at
+ ) VALUES ($1, $2, $3, $4, $5, 'pending', 'cc', $6, $6)
+ `,
+ [
+ recipient.id,
+ envelopeId,
+ recipient.name,
+ recipient.email,
+ recipient.signOrder,
+ updatedAt,
+ ],
+ );
+ }
+
await tx.query(
`
UPDATE envelopes
@@ -2558,6 +2696,11 @@ export async function replaceDraftEnvelopeSigners(
const checks = await listSignerCheckSettings(envelopeId, database);
return replaceSignersResponseSchema.parse({
+ copyRecipients: nextCopyRecipients.map(({ email, id, name }) => ({
+ email,
+ id,
+ name,
+ })),
envelopeId,
redirectPath: `/envelopes/${envelopeId}/prepare`,
signers: (await listSignersForEnvelopeId(envelopeId, database)).map(
diff --git a/src/lib/schemas/signer.ts b/src/lib/schemas/signer.ts
index 8c99ca3..7978ae8 100644
--- a/src/lib/schemas/signer.ts
+++ b/src/lib/schemas/signer.ts
@@ -1,6 +1,10 @@
import { z } from "zod";
-import { MAX_SIGNERS_PER_ENVELOPE, signerStatuses } from "../types/domain.ts";
+import {
+ MAX_COPY_RECIPIENTS_PER_ENVELOPE,
+ MAX_SIGNERS_PER_ENVELOPE,
+ signerStatuses,
+} from "../types/domain.ts";
import {
emailSchema,
idSchema,
@@ -12,6 +16,15 @@ import {
export const signerStatusSchema = z.enum(signerStatuses);
export const duplicateSignerEmailMessage =
"Each signer must have a unique email address.";
+export const duplicateCopyRecipientEmailMessage =
+ "This address is already a signer or a copy recipient.";
+
+/** Someone who receives the finished document without signing it. */
+export const copyRecipientSchema = z.object({
+ id: idSchema.optional(),
+ name: nameSchema,
+ email: emailSchema,
+});
export const draftSignerSchema = z.object({
id: idSchema.optional(),
@@ -62,11 +75,39 @@ export const signerListSchema = z
}
});
-export const replaceSignersSchema = z.object({
- signers: signerListSchema,
-});
+export const replaceSignersSchema = z
+ .object({
+ // Left out keeps the copy recipients already saved.
+ copyRecipients: z
+ .array(copyRecipientSchema)
+ .max(MAX_COPY_RECIPIENTS_PER_ENVELOPE)
+ .optional(),
+ signers: signerListSchema,
+ })
+ .superRefine((value, ctx) => {
+ const emails = new Set(
+ value.signers.map((signer) => signer.email.toLowerCase()),
+ );
+
+ for (const [index, recipient] of (value.copyRecipients ?? []).entries()) {
+ const normalizedEmail = recipient.email.toLowerCase();
+
+ if (emails.has(normalizedEmail)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: duplicateCopyRecipientEmailMessage,
+ path: ["copyRecipients", index, "email"],
+ });
+ }
+
+ emails.add(normalizedEmail);
+ }
+ });
export const replaceSignersResponseSchema = z.object({
+ copyRecipients: z.array(
+ z.object({ email: emailSchema, id: idSchema, name: nameSchema }),
+ ),
envelopeId: idSchema,
redirectPath: z.string().trim().min(1),
signers: z.array(
@@ -100,6 +141,9 @@ export const declineEnvelopeSchema = z.object({
reason: optionalTrimmedString(1000),
});
+export type CopyRecipient = z.infer<typeof copyRecipientSchema>;
+/** A copy recipient as stored: it always has an id. */
+export type CopyRecipientRecord = { email: string; id: string; name: string };
export type DraftSigner = z.infer<typeof draftSignerSchema>;
export type ReplaceSignersInput = z.infer<typeof replaceSignersSchema>;
export type ReplaceSignersResponse = z.infer<
diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.ts
index 30a14ac..d92560f 100644
--- a/src/lib/services/pdf-finalize.test.ts
+++ b/src/lib/services/pdf-finalize.test.ts
@@ -222,3 +222,44 @@ test("the certificate prints names, titles and browser strings as they are", asy
assert.ok(reloaded.getTitle()?.includes("業務委託契約書"));
});
+
+test("the certificate names the people who were sent a copy", async () => {
+ const fixture = await makeFixture();
+ const copyRecipients = [
+ { email: "[email protected]", name: "Zofia Wiśniewska" },
+ ];
+ const render = (redactForRecipients: boolean) =>
+ renderEnvelopeCertificatePdf(
+ {
+ auditEvents: fixture.auditEvents,
+ copyRecipients,
+ envelope: fixture.envelope,
+ redactForRecipients,
+ signers: fixture.signers,
+ },
+ { seal: saveUnsealed },
+ ).then(async (bytes) => (await extractText(bytes)).replace(/\s+/g, " "));
+ const full = await render(false);
+
+ assert.ok(full.includes("Copy recipients"));
+ assert.ok(full.includes("They did not sign it."));
+ assert.ok(full.includes("Zofia Wiśniewska <[email protected]>"));
+
+ // The signers' own copy leaves addresses out, as it does for signers.
+ const redacted = await render(true);
+
+ assert.ok(redacted.includes("Zofia Wiśniewska"));
+ assert.ok(!redacted.includes("[email protected]"));
+
+ // No section at all when nobody was sent a copy.
+ const without = await renderEnvelopeCertificatePdf(
+ {
+ auditEvents: fixture.auditEvents,
+ envelope: fixture.envelope,
+ signers: fixture.signers,
+ },
+ { seal: saveUnsealed },
+ );
+
+ assert.ok(!(await extractText(without)).includes("Copy recipients"));
+});
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index 3e76477..8ce4341 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -501,6 +501,7 @@ function buildAuditLines(input: {
auditEvents: AuditEventRecord[];
auditFingerprint?: string | null;
completedAt: number;
+ copyRecipients?: readonly CertificateCopyRecipient[];
envelope: EnvelopeRecord;
fonts: {
bold: TextFace;
@@ -627,6 +628,28 @@ function buildAuditLines(input: {
}
}
+ if (input.copyRecipients && input.copyRecipients.length > 0) {
+ pushParagraph("Copy recipients", input.fonts.bold, sectionFontSize, {
+ gapAfter: 4,
+ gapBefore: 10,
+ });
+ pushParagraph(
+ "Sent a copy of the finished document. They did not sign it.",
+ input.fonts.regular,
+ bodyFontSize,
+ );
+
+ for (const recipient of input.copyRecipients) {
+ pushParagraph(
+ input.redactForRecipients
+ ? recipient.name
+ : `${recipient.name} <${recipient.email}>`,
+ input.fonts.regular,
+ bodyFontSize,
+ );
+ }
+ }
+
pushParagraph("Audit events", input.fonts.bold, sectionFontSize, {
gapAfter: 4,
gapBefore: 10,
@@ -821,6 +844,7 @@ function appendAuditTrailPages(input: {
auditEvents: AuditEventRecord[];
auditFingerprint?: string | null;
completedAt: number;
+ copyRecipients?: readonly CertificateCopyRecipient[];
envelope: EnvelopeRecord;
fonts: {
bold: TextFace;
@@ -847,6 +871,7 @@ function appendAuditTrailPages(input: {
auditEvents: input.auditEvents,
auditFingerprint: input.auditFingerprint,
completedAt: input.completedAt,
+ copyRecipients: input.copyRecipients,
envelope: input.envelope,
fonts: input.fonts,
maxWidth,
@@ -880,8 +905,12 @@ function appendAuditTrailPages(input: {
}
}
+/** Someone sent a copy of the finished document who did not sign it. */
+export type CertificateCopyRecipient = { email: string; name: string };
+
type CertificateInput = {
auditEvents: AuditEventRecord[];
+ copyRecipients?: readonly CertificateCopyRecipient[];
envelope: EnvelopeRecord;
redactForRecipients?: boolean;
/** The finished signed PDF's SHA-256, printed when there is one. */
@@ -960,7 +989,12 @@ export async function renderEnvelopeCertificatePdf(
const pdfDocument = await PDFDocument.create();
const faces = await embedTextFaces(
pdfDocument,
- [input.envelope, input.signers, input.auditEvents],
+ [
+ input.envelope,
+ input.signers,
+ input.auditEvents,
+ input.copyRecipients ?? [],
+ ],
{ bold: true, certificate: true },
);
const terminalTimestamp = resolveTerminalTimestamp(
@@ -976,6 +1010,7 @@ export async function renderEnvelopeCertificatePdf(
stripCompletedAuditEvents(input.auditEvents),
),
completedAt: terminalTimestamp,
+ copyRecipients: input.copyRecipients,
envelope: input.envelope,
fonts: faces,
pdfDocument,
@@ -1002,6 +1037,7 @@ export async function renderFinalizedEnvelopePdf(
input: {
auditEvents: AuditEventRecord[];
completedAt: number;
+ copyRecipients?: readonly CertificateCopyRecipient[];
envelope: EnvelopeRecord;
fields: FieldRecord[];
includeAuditTrail?: boolean;
@@ -1035,7 +1071,12 @@ export async function renderFinalizedEnvelopePdf(
[
stampedFields.map((field) => field.value),
input.includeAuditTrail
- ? [input.envelope, input.signers, input.auditEvents]
+ ? [
+ input.envelope,
+ input.signers,
+ input.auditEvents,
+ input.copyRecipients ?? [],
+ ]
: [],
],
{
@@ -1079,6 +1120,7 @@ export async function renderFinalizedEnvelopePdf(
appendAuditTrailPages({
auditEvents: stripCompletedAuditEvents(input.auditEvents),
completedAt: input.completedAt,
+ copyRecipients: input.copyRecipients,
envelope: input.envelope,
fonts: faces,
pdfDocument,
@@ -1092,6 +1134,7 @@ export async function renderFinalizedEnvelopePdf(
export async function finalizeEnvelope(
input: {
auditEvents: AuditEventRecord[];
+ copyRecipients?: readonly CertificateCopyRecipient[];
envelope: EnvelopeRecord;
fields: FieldRecord[];
signers: SignerRecord[];
@@ -1113,6 +1156,7 @@ export async function finalizeEnvelope(
{
auditEvents: input.auditEvents,
completedAt: generatedAt,
+ copyRecipients: input.copyRecipients,
envelope: input.envelope,
fields: input.fields,
signers: input.signers,
@@ -1155,6 +1199,7 @@ export async function finalizeEnvelope(
audience: "internal",
}),
},
+ copyRecipients: input.copyRecipients,
envelope: completedEnvelope,
signedPdfSha256,
signers: input.signers,
@@ -1174,6 +1219,7 @@ export async function finalizeEnvelope(
audience: "recipient",
}),
},
+ copyRecipients: input.copyRecipients,
envelope: completedEnvelope,
signedPdfSha256,
signers: input.signers,
diff --git a/src/lib/signer-data.ts b/src/lib/signer-data.ts
index d4a85c0..b01b848 100644
--- a/src/lib/signer-data.ts
+++ b/src/lib/signer-data.ts
@@ -37,6 +37,8 @@ type SignerEnvelopeRow = {
signerId: string;
signerName: string;
signerStatus: string;
+ /** "signer", or "cc" for someone who only received a copy. */
+ role: string;
};
function parseEmail(email: unknown): string {
@@ -61,6 +63,7 @@ async function listSignerEnvelopes(
s.name AS "signerName",
s.email AS "signerEmail",
s.status AS "signerStatus",
+ s.role AS "role",
s.signed_at AS "signedAt",
s.declined_at AS "declinedAt",
s.decline_reason AS "declineReason",
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 5a662a5..aaa7d7a 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -37,7 +37,11 @@ import {
type SigningSubmitResponse,
type SigningUnavailableResponse,
} from "./schemas/signing.ts";
-import { declineEnvelopeSchema, signerRecordSchema } from "./schemas/signer.ts";
+import {
+ declineEnvelopeSchema,
+ signerRecordSchema,
+ type CopyRecipientRecord,
+} from "./schemas/signer.ts";
import { getBranding } from "./settings.ts";
import {
listAuditEventsForEnvelope,
@@ -373,6 +377,8 @@ function buildDeclineNotificationEmail(input: {
function buildCompletionSignerEmail(input: {
attached: boolean;
branding: Branding;
+ /** True for someone who gets a copy without having signed. */
+ copyOnly?: boolean;
evidenceDownloadUrl: string;
envelopeId: string;
envelopeTitle: string;
@@ -386,6 +392,9 @@ function buildCompletionSignerEmail(input: {
`Hi ${input.signerName},`,
"",
`"${input.envelopeTitle}" from ${input.senderName} has been fully signed in ${input.branding.productName}.`,
+ ...(input.copyOnly
+ ? [`${input.senderName} asked for you to receive a copy.`]
+ : []),
input.attached
? "The completed document and its certificate are attached. Keep them: they are your copy of the agreement."
: "The completed document and its certificate are ready.",
@@ -397,6 +406,9 @@ function buildCompletionSignerEmail(input: {
const htmlBody = [
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
`<p>&ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; from ${escapeHtml(input.senderName)} has been fully signed in ${escapeHtml(input.branding.productName)}.</p>`,
+ input.copyOnly
+ ? `<p>${escapeHtml(input.senderName)} asked for you to receive a copy.</p>`
+ : "",
input.attached
? "<p>The completed document and its certificate are attached. Keep them: they are your copy of the agreement.</p>"
: "<p>The completed document and its certificate are ready.</p>",
@@ -516,6 +528,26 @@ async function listSignerRows(
updated_at AS "updatedAt"
FROM signers
WHERE envelope_id = $1
+ -- Copy recipients are not part of the signing order.
+ AND role = 'signer'
+ ORDER BY sign_order ASC, id ASC
+ `,
+ [envelopeId],
+ );
+}
+
+/** The people who get the finished document without signing it. */
+async function listCopyRecipientRows(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<CopyRecipientRecord[]> {
+ return queryMany<CopyRecipientRecord>(
+ database,
+ `
+ SELECT id, name, email
+ FROM signers
+ WHERE envelope_id = $1
+ AND role = 'cc'
ORDER BY sign_order ASC, id ASC
`,
[envelopeId],
@@ -895,6 +927,7 @@ async function sendCompletionEmails(input: {
recipientCertificate: Uint8Array;
signedPdf: Uint8Array;
};
+ copyRecipients: readonly CopyRecipientRecord[];
database?: DbExecutor;
emailService: EmailService;
envelopeId: string;
@@ -921,8 +954,17 @@ async function sendCompletionEmails(input: {
const senderName = normalizeSenderName(input.sender);
const issuedAt = Math.floor(Date.now() / 1000);
const branding = await getBranding();
+ // Signers first, then the people who only get a copy: the place in this
+ // list is part of each message's idempotency key.
+ const recipients = [
+ ...input.signers.map((signer) => ({ ...signer, copyOnly: false })),
+ ...input.copyRecipients.map((recipient) => ({
+ ...recipient,
+ copyOnly: true,
+ })),
+ ];
const signerMessages = await Promise.all(
- input.signers.map(async (signer) => {
+ recipients.map(async (signer) => {
if (!signer.id) {
throw new SigningMutationError(
"Completed signer records must include an id.",
@@ -961,6 +1003,7 @@ async function sendCompletionEmails(input: {
...buildCompletionSignerEmail({
attached: attach,
branding,
+ copyOnly: signer.copyOnly,
envelopeId: input.envelopeId,
envelopeTitle: input.envelopeTitle,
evidenceDownloadUrl: redactedEvidenceLink.url,
@@ -1992,12 +2035,17 @@ export async function submitSigningForToken(
);
}
+ const copyRecipients = await listCopyRecipientRows(
+ context.envelope.id,
+ database,
+ );
const finalArtifacts = await finalizeEnvelope(
{
auditEvents: [
...(await listAuditEventsForEnvelope(context.envelope.id, database)),
signedAuditEvent,
],
+ copyRecipients,
envelope: context.envelope,
fields: completedFields,
signers: completedSigners,
@@ -2164,6 +2212,7 @@ export async function submitSigningForToken(
recipientCertificate: finalArtifacts.recipientCertificate.body,
signedPdf: finalArtifacts.signedPdf.body,
},
+ copyRecipients,
database,
emailService,
envelopeId: context.envelope.id,
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index 29ef732..77cdb94 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -1,4 +1,6 @@
export const MAX_SIGNERS_PER_ENVELOPE = 10;
+/** People who get a copy of the finished document without signing. */
+export const MAX_COPY_RECIPIENTS_PER_ENVELOPE = 10;
export const MAX_UPLOAD_SIZE_BYTES = 20 * 1024 * 1024;
export const SIGNING_LINK_TTL_SECONDS = 7 * 24 * 60 * 60;
export const RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS = 7 * 24 * 60 * 60;
diff --git a/src/lib/verify.ts b/src/lib/verify.ts
index 3cec41f..564d109 100644
--- a/src/lib/verify.ts
+++ b/src/lib/verify.ts
@@ -57,7 +57,7 @@ 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) AS "signerCount"
+ (SELECT count(*)::int FROM signers s WHERE s.envelope_id = e.id AND s.role = 'signer') AS "signerCount"
FROM envelopes e
WHERE e.signed_pdf_sha256 = $1
OR e.evidence_sha256 = $1