Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let signers in a step sign at the same time
Matthew Jackson2e1ec5cdcdcc
diff --git a/.env.example b/.env.exampleindex 6f543bf..77dcd8e 100644--- a/.env.example+++ b/.env.example@@ -92,6 +92,9 @@ EMAIL_DRIVER=capture# PDF is sealed without a timestamp.# SEAL_TIMESTAMP_URL=+# The most signers one envelope can have, from 1 to 100. 25 when unset.+# MAX_SIGNERS_PER_ENVELOPE=+# Signatures in the signers' own names (eIDAS advanced or qualified), through# a signing provider outside Vercel. Unset, signers make simple electronic# signatures. See "Signatures in the signers' own names" indiff --git a/README.md b/README.mdindex fd3433f..eb1e29c 100644--- a/README.md+++ b/README.md@@ -40,7 +40,7 @@### Prepare a document in minutes-Upload a PDF, add up to 10 signers in the order they sign, and add people who only receive the finished copy. Then place fields where they belong: signature, initials, date, name, text, number, checkbox, dropdown and radio buttons, each required or optional and each tied to one signer.+Upload a PDF, add up to 25 signers in the order they sign, or have some of them sign at the same time, and add people who only receive the finished copy. Then place fields where they belong: signature, initials, date, name, text, number, checkbox, dropdown and radio buttons, each required or optional and each tied to one signer.@@ -122,7 +122,7 @@ DocuSign does more, and charges for it per user. SignuDoc does the everyday sign| | SignuDoc | DocuSign eSignature || -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- || **Signing without an account** | ✅ | ✅ |-| **Signing order** | ✅ in order, up to 10 signers | ✅ in order, at the same time, or mixed |+| **Signing order** | ✅ in order, at the same time, or mixed, up to 25 signers | ✅ in order, at the same time, or mixed || **People who only get a copy** | ✅ | ✅ and more roles: approvers, editors, in-person signers || **Field types** | ✅ signature, initials, date, name, text, number, checkbox, dropdown, radio, each required or optional | ✅ more types; dropdown, radio and signer attachments need Business Pro || **Templates** | ✅ | ✅ from Personal, shared from Standard |@@ -140,7 +140,6 @@ DocuSign does more, and charges for it per user. SignuDoc does the everyday sign| | SignuDoc | DocuSign eSignature || ------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------- || **More than one document per envelope, and Word files** | — PDF only, one per envelope | ✅ |-| **Signing at the same time** | — in order only | ✅ || **Bulk send, web forms, payments** | — | ✅ on Business Pro || **API and webhooks** | — not yet | ✅ API plans from $50 a month || **Integrations** | — | ✅ 1,000+, including Salesforce, Microsoft and Google |diff --git a/db/migrations/20261119090000_signing_steps.sql b/db/migrations/20261119090000_signing_steps.sqlnew file mode 100644index 0000000..e6491aa--- /dev/null+++ b/db/migrations/20261119090000_signing_steps.sql@@ -0,0 +1,57 @@+-- Signing at the same time: signers who share a step of the signing order+-- are invited together and sign in any order among themselves. The next+-- step starts once every signer of the step before has signed.+--+-- * signers.signing_step: the step a signer belongs to, counted from 1.+-- sign_order stays what it was, the signer's place in the list, so it is+-- still unique on an envelope and every list keeps its order. Copy+-- recipients are in no step.+-- * Existing signers get the step of their place in the list, which is how+-- they were signing already: one after the other.+-- * idx_signers_single_notified allowed one waiting signer per envelope.+-- Every signer of the current step now waits at once, so it goes. What+-- kept two transactions from both moving the order on, the envelope's row+-- being locked first, still does.+-- * templates_roles_check: a template keeps up to as many roles as an+-- envelope can have signers at most (MAX_SIGNERS_CEILING in+-- src/lib/types/domain.ts).+--+-- A copy of the app from before this migration still runs on this+-- database, but signs a document whose signers share a step one after the+-- other, and only invites the first of them when it is sent.++alter table public.signers+ add column if not exists signing_step integer;++alter table public.signers+ drop constraint if exists signers_signing_step_check;++alter table public.signers+ add constraint signers_signing_step_check+ check (signing_step is null or signing_step > 0);++alter table public.signers+ drop constraint if exists signers_copy_recipient_has_no_step;++alter table public.signers+ add constraint signers_copy_recipient_has_no_step+ check (role = 'signer' or signing_step is null);++update public.signers+set signing_step = sign_order+where role = 'signer'+ and signing_step is null;++drop index if exists public.idx_signers_single_notified;++alter table public.templates+ drop constraint if exists templates_roles_check;++alter table public.templates+ add constraint templates_roles_check check (+ case+ when jsonb_typeof(roles) = 'array'+ then jsonb_array_length(roles) between 1 and 100+ else false+ end+ );diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex fb77ff2..1ffbacb 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -139,6 +139,7 @@ A deployment made with the button needs no environment variables. These are ther| `RESEND_REGION` | Where Resend sends from when the app adds your domain, for example `eu-west-1`. See [Running in the EU](#running-in-the-eu). || `SEAL_P12_BASE64`, `SEAL_P12_PASSWORD` | Seal finished PDFs with a certificate from a certificate authority instead of the install's own. See [Signed PDFs and the seal](#signed-pdfs-and-the-seal). || `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal, and long-term validation. See [Long-term validation](#long-term-validation). |+| `MAX_SIGNERS_PER_ENVELOPE` | The most signers one envelope can have, from 1 to 100. 25 when unset. See [Signing order](signing-order.md). || `EIDEASY_CLIENT_ID`, `EIDEASY_SECRET` | Let senders ask for advanced or qualified signatures in the signers' own names, through eID Easy. See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). || `CSC_API_URL`, `CSC_CLIENT_ID`, `CSC_CLIENT_SECRET` | The same through a trust service provider's remote signing service (CSC API v2). See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). || `BACKUP_BLOB_READ_WRITE_TOKEN`, `BACKUP_KEEP_DAYS` | A daily backup of the database and files to a second Blob store. See [Backup and restore](backup-and-restore.md). |diff --git a/docs/signing-order.md b/docs/signing-order.mdnew file mode 100644index 0000000..0715db0--- /dev/null+++ b/docs/signing-order.md@@ -0,0 +1,63 @@+# Signing order++The signing order is a list of steps. Each signer is in one step.++- Signers in **the same step sign at the same time.** They are all invited when the step starts, each with a link of their own, and sign in any order among themselves.+- **The next step starts once every signer of the step before has signed.** Its signers are invited then.+- A list where every signer has a step of their own is the plain one-after-the-other order, which is what every envelope sent before steps existed has.+- A list where every signer is in one step is "any order": everyone is invited when it is sent, and the envelope is finished when the last of them signs, whoever that is.+- **Copy recipients** are not in any step. They get the finished document once everyone has signed, as before.++On the signers page, each signer after the first has **Sign at the same time as Signer N**. Ticked, they join the step of the signer above them. So a salesperson can send a contract to the customer and their manager at the same time, and to the company's signatory once both have signed:++| Signer | Sign at the same time as the signer above | Step |+| --------------- | ----------------------------------------- | ---- |+| Customer | | 1 |+| Sales manager | ticked | 1 |+| Company officer | | 2 |++Ticking it for every signer puts them all in step 1. Removing or moving a signer leaves everyone else in their step. A signer moved past the edge of their step gets one of their own, or joins the step they land in the middle of.++A template keeps each role's step, so roles that signed at the same time still do when the template is used. A template saved before steps existed signs one role after the other.++## What happens along the way++- **Invitations.** Sending invites everyone in the first step. If the first invitation cannot be sent, nothing is sent and the envelope stays a draft. Once one has gone out, the envelope is out for signature; a later one that fails is logged, and a reminder sends that signer a new link.+- **What a signer sees.** A signer sees what the signers of earlier steps filled in. What someone in their own step has filled in is not shown: it was not on the page when their turn began. The finished document has everyone's.+- **Reminders.** The sender's **Send reminder** reminds every signer whose turn it is, each with a new link, leaving out anyone reminded in the last 24 hours. Automatic reminders reach each waiting signer on their own schedule.+- **Deadline.** One deadline for the whole envelope, as before. Changing it moves the links of everyone whose turn it is. The notice that an envelope expired names everyone it was waiting on.+- **Decline.** One signer declining ends the envelope for everyone, including the others in the same step, as before.+- **Void.** Voiding tells everyone whose turn it was.+- **Correcting a signer** works on each waiting signer separately: the corrected person gets a new invitation and the old link stops working.+- **Certificate and audit trail.** The certificate numbers each signer by their step. When some share a step it says that signers with the same number were asked to sign at the same time. The envelope's audit trail records the step of each signature and decline, and the "sent" event names everyone invited at once.++## When two signers submit at the same moment++Every signature takes hold of the envelope's row in the database before it changes anything, and so does every decline, void, reminder and change of deadline. Two signers of one step who submit at the same moment therefore take turns:++- the first one's signature is saved;+- the second one then sees, with the envelope held, whether anyone is still to sign. If someone is, it saves its signature and invites the next step if this one is now done. If nobody is, it starts again as the last signature, and makes the final signed PDF, the certificates and the "completed" event, once.++A decline or a void that finds a signer of the step signed in the meantime starts again too, so its certificate shows that signature. `src/lib/parallel-signing.dbtest.ts` runs these races against a real Postgres.++## Where signing at the same time is not offered++- **Part 11 mode.** Part 11 envelopes are signed one signer after another. The Part 11 validation (requirement SYS-08 and OQ-06) is written for that order, and a different sequence would need your OQ to be run again before use. The signers page does not offer the choice in Part 11 mode, and a send that has signers sharing a step is refused.+- **Advanced and qualified signatures** (eID Easy or a CSC provider). Each such signature is added to the PDF on top of the one before it, so two cannot be made at once. The review page and the send refuse it; choose SignuDoc signatures, or give each signer their own step.++## How many signers++An envelope can have up to 25 signers. Set `MAX_SIGNERS_PER_ENVELOPE` (1 to 100) to change that. The old limit of ten was not tied to anything technical: the certificate runs onto as many pages as it needs. Templates follow the same limit when they are used.++## Upgrading and rolling back++The migration `20261119090000_signing_steps.sql` adds `signers.signing_step` and gives every existing signer the step of their place in the list, so existing envelopes keep signing one after the other. It drops the index that allowed only one waiting signer per envelope. `sign_order` stays the signer's place in the list and stays unique.++An older version of the app still runs on the migrated database, but it signs an envelope whose signers share a step one after the other, and invites only the first of them when it is sent. Roll back past this migration only with no such envelopes out for signature.++## For developers++- `src/lib/signing-steps.ts`: steps, renumbering, and who is invited next.+- `src/lib/signing.ts`: `submitSigningForToken` and `declineSigningForToken`, and the restart when the route changed (`SigningRouteChangedError`).+- `src/lib/signer-limit.ts`: the install's limit on signers.+- Tests: `signing-steps.test.ts` and `parallel-signing.dbtest.ts`.diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex eb13138..a2ae8e5 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -75,6 +75,8 @@ type EnvelopeDetailSigner = {order: number;status: SignerStatus;statusDateLabel?: string;+ /** Signers who share a step sign at the same time. */+ step?: number;tint?: string;};@@ -250,6 +252,10 @@ export function EnvelopeDetailShell({activeRecord.status === "sent"? activeRecord.signers.find((signer) => signer.status === "waiting"): null;+ const stepOf = (signer: EnvelopeDetailSigner) => signer.step ?? signer.order;+ const signsAtTheSameTime =+ new Set(activeRecord.signers.map(stepOf)).size <+ activeRecord.signers.length;function handleDownload(fileType: DownloadFileType) {// This starts a file download from an API route, not a page navigation.@@ -860,7 +866,7 @@ export function EnvelopeDetailShell({color: palette.color,}}>- {signer.order}+ {signsAtTheSameTime ? stepOf(signer) : signer.order}</span><div className="min-w-0 flex-1">diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsxindex ace0de3..f514fca 100644--- a/src/components/envelopes/review-shell.tsx+++ b/src/components/envelopes/review-shell.tsx@@ -63,6 +63,8 @@ type ReviewSigner = {id: string;name: string;order: number;+ /** Signers who share a step sign at the same time. */+ step?: number;tint?: string;};@@ -236,9 +238,22 @@ export function ReviewShell({sizeLabel: record.sizeLabel,title: record.title,};- const canSend = Boolean(record.canSend);const disabledReason = record.disabledReason ?? null;const firstSigner = activeRecord.signers[0];+ const stepOf = (signer: ReviewSigner) => signer.step ?? signer.order;+ const firstStep = firstSigner ? stepOf(firstSigner) : 1;+ // Everyone in the first step is invited when the envelope is sent.+ const firstStepNames = activeRecord.signers+ .filter((signer) => stepOf(signer) === firstStep)+ .map((signer) => signer.name);+ const signsAtTheSameTime =+ new Set(activeRecord.signers.map(stepOf)).size <+ activeRecord.signers.length;+ // A signature in a signer's own name goes on top of the one before it, so+ // those signers cannot sign at the same time.+ const providerLevelBlocked =+ signsAtTheSameTime && signatureLevel !== "simple";+ const canSend = Boolean(record.canSend) && !providerLevelBlocked;return (<div className="space-y-5">@@ -311,7 +326,7 @@ export function ReviewShell({color: palette.color,}}>- {signer.order}+ {signsAtTheSameTime ? stepOf(signer) : signer.order}</span><div className="min-w-0 flex-1">@@ -372,9 +387,9 @@ export function ReviewShell({) : 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- completes.+ {signsAtTheSameTime+ ? "After you send, everyone numbered 1 receives an email with a link to sign. Signers with the same number sign at the same time, and the next number is invited once they have all signed."+ : "After you send, Signer 1 will receive an email with a link to sign. Each signer is notified in order after the previous signer completes."}</p><div className="well mt-4 p-4">@@ -461,6 +476,13 @@ export function ReviewShell({? "Signers sign here, and the finished PDF is sealed by this install.": `Each signer proves who they are at ${record.signingProvider.name} and signs with a certificate in their own name. ${signatureLevel === "qualified" ? "A qualified signature needs a qualified certificate, which not every signer has. " : ""}Which type a document needs is a legal question; this is not legal advice.`}</p>+ {providerLevelBlocked ? (+ <p className="notice notice-danger mt-3" role="alert">+ These signatures are added one after another, so signers+ cannot sign at the same time. Give each signer their own+ step, or choose SignuDoc signatures.+ </p>+ ) : null}</div>) : null}</article>@@ -489,7 +511,12 @@ export function ReviewShell({<SendConfirmationDialogdeadlineDays={deadlineDays}errorMessage={sendPhase === "error" ? sendError : null}- firstSignerName={firstSigner?.name ?? "Signer 1"}+ firstSignerName={+ firstStepNames.length > 1+ ? `${firstStepNames.slice(0, -1).join(", ")} and ${firstStepNames[firstStepNames.length - 1]}`+ : (firstSigner?.name ?? "Signer 1")+ }+ firstStepSize={firstStepNames.length}isSending={sendPhase === "sending"}onCancel={closeConfirmation}onConfirm={handleConfirmSend}@@ -513,6 +540,8 @@ type SendConfirmationDialogProps = {deadlineDays: number;errorMessage: string | null;firstSignerName: string;+ /** How many signers are invited at once when it is sent. */+ firstStepSize: number;isSending: boolean;onCancel: () => void;onConfirm: () => void;@@ -526,6 +555,7 @@ function SendConfirmationDialog({deadlineDays,errorMessage,firstSignerName,+ firstStepSize,isSending,onCancel,onConfirm,@@ -555,7 +585,9 @@ function SendConfirmationDialog({{signerCount === 1 ? "signer" : "signers"}.{" "}{signerCount === 1? `${firstSignerName} will be notified immediately.`- : `The first signer (${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.`}{" "}The request expires in {deadlineDays} days.</p>{signatureType ? (diff --git a/src/components/envelopes/signers-shell.tsx b/src/components/envelopes/signers-shell.tsxindex 7ae4789..8c5f9e2 100644--- a/src/components/envelopes/signers-shell.tsx+++ b/src/components/envelopes/signers-shell.tsx@@ -17,9 +17,10 @@ import {type ReplaceSignersResponse,} from "@/lib/schemas/signer";import { SIGNATURE_MEANING_DETAILS } from "@/lib/signature-meanings";+import { moveListedSigner, removeListedSigner } from "@/lib/signing-steps";import {+ DEFAULT_MAX_SIGNERS_PER_ENVELOPE,MAX_COPY_RECIPIENTS_PER_ENVELOPE,- MAX_SIGNERS_PER_ENVELOPE,signatureMeanings,type SignatureMeaning,} from "@/lib/types/domain";@@ -56,6 +57,11 @@ type ShellSigner = SignerChecks & {name: string;signerId?: string;touched: Record<SignerField, boolean>;+ /**+ * Signs at the same time as the signer above, in the same step of the+ * signing order. Ignored for the first signer, and in Part 11 mode.+ */+ withPrevious: boolean;};type SignerErrors = {@@ -100,9 +106,36 @@ function createSigner(email: overrides?.touched?.email ?? false,name: overrides?.touched?.name ?? false,},+ withPrevious: overrides?.withPrevious ?? false,};}+/**+ * Each signer's step of the signing order, from the list and its "at the+ * same time as the signer above" choices. In Part 11 mode every signer has+ * a step of their own.+ */+function computeSigningSteps(+ signers: readonly Pick<ShellSigner, "withPrevious">[],+ part11Mode: boolean,+): number[] {+ const steps: number[] = [];++ for (const [index, signer] of signers.entries()) {+ const previous = steps[index - 1];++ steps.push(+ previous === undefined+ ? 1+ : signer.withPrevious && !part11Mode+ ? previous+ : previous + 1,+ );+ }++ return steps;+}+type SignerCheckChoice = "access_code" | "email_code" | "none";// One check per signer. The server still honours both at once (the signer@@ -137,21 +170,21 @@ function signerCheckChoice(}function buildInitialModel(record?: DraftSignerStepData): InitialModel {- const signers =- record?.signers- .slice()- .sort((left, right) => left.order - right.order)- .map((signer) =>- createSigner(signer.id, {- email: signer.email,- hasAccessCode: signer.hasAccessCode,- name: signer.name,- requireEmailCode: signer.requireEmailCode,- signatureMeaning: signer.signatureMeaning ?? null,- signerId: signer.id,- touched: { email: true, name: true },- }),- ) ?? [];+ const sorted =+ record?.signers.slice().sort((left, right) => left.order - right.order) ??+ [];+ const signers = sorted.map((signer, index) =>+ createSigner(signer.id, {+ email: signer.email,+ hasAccessCode: signer.hasAccessCode,+ name: signer.name,+ requireEmailCode: signer.requireEmailCode,+ signatureMeaning: signer.signatureMeaning ?? null,+ signerId: signer.id,+ touched: { email: true, name: true },+ withPrevious: index > 0 && sorted[index - 1]?.step === signer.step,+ }),+ );return {copyRecipients: (record?.copyRecipients ?? []).map((recipient) => ({@@ -265,27 +298,16 @@ function reorderSigners((signer) => signer.localId === signerLocalId,);- if (signerIndex === -1) {- return signers;- }-- const targetIndex =- direction === "earlier" ? signerIndex - 1 : signerIndex + 1;-- if (targetIndex < 0 || targetIndex >= signers.length) {- return signers;- }-- const nextSigners = [...signers];- const [movedSigner] = nextSigners.splice(signerIndex, 1);- nextSigners.splice(targetIndex, 0, movedSigner);- return nextSigners;+ return moveListedSigner(signers, signerIndex, direction);}function buildSignerRequest(signers: readonly ShellSigner[],copyRecipients: readonly ShellCopyRecipient[],+ part11Mode: boolean,) {+ const steps = computeSigningSteps(signers, part11Mode);+return {copyRecipients: copyRecipients.map((recipient) => ({email: recipient.email,@@ -306,6 +328,7 @@ function buildSignerRequest(requireEmailCode: signer.requireEmailCode,signatureMeaning: signer.signatureMeaning,signOrder: index + 1,+ signingStep: steps[index],})),};}@@ -348,12 +371,26 @@ function SignerCard({onChecksChange,onMove,onRemove,+ onTogetherChange,accessCodeError,part11Mode = false,+ previousStepLabel,+ showStep,signer,+ step,+ stepSize,}: {accessCodeError?: string;part11Mode?: boolean;+ /** Who signs in the step before this signer's, as "Signer 2". */+ previousStepLabel: string | null;+ /** Some signers share a step, so every card says which step it is in. */+ showStep: boolean;+ /** This signer's step of the signing order. */+ step: number;+ /** How many signers are in that step. */+ stepSize: number;+ onTogetherChange: (together: boolean) => void;onChecksChange: (patch: Partial<SignerChecks>) => void;canMoveEarlier: boolean;canMoveLater: boolean;@@ -385,10 +422,21 @@ function SignerCard({};const palette = getSignerPalette(index);const order = index + 1;- const routeLabel =- order === 1- ? "Receives the invitation immediately after send."- : `Receives the document after Signer ${order - 1} finishes.`;+ const together = index > 0 && signer.withPrevious && !part11Mode;+ const previous = previousStepLabel ?? `Signer ${String(order - 1)}`;+ const finishes = previous.includes(" and ") ? "finish" : "finishes";+ let routeLabel: string;++ if (step === 1) {+ routeLabel =+ stepSize > 1+ ? "Receives the invitation immediately after send, and signs at the same time as the others in step 1."+ : "Receives the invitation immediately after send.";+ } else if (together) {+ routeLabel = `Signs at the same time as Signer ${String(order - 1)}, once ${previous} ${finishes}.`;+ } else {+ routeLabel = `Receives the document after ${previous} ${finishes}.`;+ }return (<li className="well p-4 sm:p-5">@@ -408,10 +456,25 @@ function SignerCard({style={{ backgroundColor: palette.color }}/>Signer {order}+ {showStep ? ` · Step ${String(step)}` : ""}</span><p className="text-[0.8125rem] leading-5 text-(--secondary)">{routeLabel}</p>+ {index > 0 && !part11Mode ? (+ <label className="flex items-center gap-2 text-[0.8125rem] font-semibold text-(--secondary)">+ <input+ checked={signer.withPrevious}+ className="size-4 shrink-0 cursor-pointer accent-(--accent)"+ disabled={disabled}+ onChange={(event: ChangeEvent<HTMLInputElement>) =>+ onTogetherChange(event.target.checked)+ }+ type="checkbox"+ />+ Sign at the same time as Signer {order - 1}+ </label>+ ) : null}</div><div className="flex flex-wrap items-center gap-2">@@ -744,7 +807,26 @@ export function SignersShell({copyRecipients,signers,);- const canAddSigner = signers.length < MAX_SIGNERS_PER_ENVELOPE;+ const maxSigners = record?.maxSigners ?? DEFAULT_MAX_SIGNERS_PER_ENVELOPE;+ const part11Mode = record?.part11Mode ?? false;+ const canAddSigner = signers.length < maxSigners;+ const signingSteps = computeSigningSteps(signers, part11Mode);+ const hasSharedStep = new Set(signingSteps).size < signingSteps.length;++ /** "Signer 2", or "Signers 2 and 3", for the signers of one step. */+ function describeStep(step: number): string | null {+ const places = signingSteps.flatMap((entry, index) =>+ entry === step ? [String(index + 1)] : [],+ );++ if (places.length === 0) {+ return null;+ }++ return places.length === 1+ ? `Signer ${places[0]}`+ : `Signers ${places.slice(0, -1).join(", ")} and ${places[places.length - 1]}`;+ }const canAddCopyRecipient =copyRecipients.length < MAX_COPY_RECIPIENTS_PER_ENVELOPE;const canContinue =@@ -794,6 +876,20 @@ export function SignersShell({);}+ function handleSignerTogetherChange(+ signerLocalId: string,+ together: boolean,+ ) {+ clearSubmitError();+ setSigners((currentSigners) =>+ currentSigners.map((signer) =>+ signer.localId === signerLocalId+ ? { ...signer, withPrevious: together }+ : signer,+ ),+ );+ }+function handleSignerBlur(signerLocalId: string, field: SignerField) {setSigners((currentSigners) =>currentSigners.map((signer) =>@@ -886,7 +982,12 @@ export function SignersShell({setSigners((currentSigners) =>currentSigners.length === 1? currentSigners- : currentSigners.filter((signer) => signer.localId !== signerLocalId),+ : removeListedSigner(+ currentSigners,+ currentSigners.findIndex(+ (signer) => signer.localId === signerLocalId,+ ),+ ),);}@@ -916,7 +1017,9 @@ export function SignersShell({try {const response = await fetch(`/api/envelopes/${envelopeId}/signers`, {- body: JSON.stringify(buildSignerRequest(signers, copyRecipients)),+ body: JSON.stringify(+ buildSignerRequest(signers, copyRecipients, part11Mode),+ ),headers: {"content-type": "application/json",},@@ -978,7 +1081,10 @@ export function SignersShell({Signers will receive the document in this order.</h2><p className="text-sm leading-6 text-(--secondary)">- Up to 10 signers per document.+ Up to {maxSigners} signers per document.{" "}+ {part11Mode+ ? "In Part 11 mode each signer signs after the one before."+ : "Signers who sign at the same time are invited together, and the next signer is invited once they have all signed."}</p></div>@@ -1022,8 +1128,21 @@ export function SignersShell({handleMoveSigner(signer.localId, direction)}onRemove={() => handleRemoveSigner(signer.localId)}- part11Mode={record?.part11Mode ?? false}+ onTogetherChange={(together) =>+ handleSignerTogetherChange(signer.localId, together)+ }+ part11Mode={part11Mode}+ previousStepLabel={describeStep(+ (signingSteps[index] ?? 1) - 1,+ )}+ showStep={hasSharedStep}signer={signer}+ step={signingSteps[index] ?? index + 1}+ stepSize={+ signingSteps.filter(+ (step) => step === (signingSteps[index] ?? index + 1),+ ).length+ }/>);})}diff --git a/src/components/landing/landing-shell.tsx b/src/components/landing/landing-shell.tsxindex 5e027f9..2c0d1c8 100644--- a/src/components/landing/landing-shell.tsx+++ b/src/components/landing/landing-shell.tsx@@ -68,7 +68,7 @@ const comparisonRows: readonly ComparisonRow[] = [},{feature: "Signers per document",- signudoc: "Up to 10",+ signudoc: "Up to 25",perSeat: "Varies by plan",},{ feature: "Reminders", signudoc: true, perSeat: "Higher plans only" },@@ -332,7 +332,7 @@ export function LandingShell() {</div><p className="mt-7 text-sm text-white/75">- Free • no signer account required • up to 10 signers per+ Free • no signer account required • up to 25 signers perdocument</p></div>diff --git a/src/components/templates/use-template-shell.tsx b/src/components/templates/use-template-shell.tsxindex f40617a..6742402 100644--- a/src/components/templates/use-template-shell.tsx+++ b/src/components/templates/use-template-shell.tsx@@ -210,8 +210,16 @@ export function UseTemplateShell({className="size-2 rounded-full"style={{ backgroundColor: palette.color }}/>- {index + 1}. {role.name}+ {role.step ?? index + 1}. {role.name}</span>+ {index > 0 &&+ role.step !== undefined &&+ template.roles[index - 1]?.step === role.step ? (+ <p className="mt-2 text-[0.8125rem] leading-5 text-(--secondary)">+ Signs at the same time as{" "}+ {template.roles[index - 1]?.name}.+ </p>+ ) : null}<div className="mt-3 grid gap-x-4 gap-y-3 md:grid-cols-2"><label className="grid auto-rows-min gap-1.5">diff --git a/src/lib/downloads.ts b/src/lib/downloads.tsindex 3050bcc..4d17cd2 100644--- a/src/lib/downloads.ts+++ b/src/lib/downloads.ts@@ -76,6 +76,7 @@ type SignerRow = {name: string;signedAt: number | null;signOrder: number;+ signingStep?: number | null;signingTokenExpiresAt: number | null;signingTokenHash: string | null;status: SignerRecord["status"];@@ -155,6 +156,7 @@ function mapSignerRow(row: SignerRow): SignerRecord {lastNudgedAt: row.lastNudgedAt,name: row.name,signOrder: row.signOrder,+ signingStep: row.signingStep ?? null,signedAt: row.signedAt,signingTokenExpiresAt: row.signingTokenExpiresAt,signingTokenHash: row.signingTokenHash,@@ -300,6 +302,7 @@ async function getSignerForEnvelope(name,email,sign_order AS "signOrder",+ signing_step AS "signingStep",status,signing_token_hash AS "signingTokenHash",signing_token_expires_at AS "signingTokenExpiresAt",diff --git a/src/lib/envelope-schedule.ts b/src/lib/envelope-schedule.tsindex 871492c..02f327e 100644--- a/src/lib/envelope-schedule.ts+++ b/src/lib/envelope-schedule.ts@@ -59,8 +59,8 @@ type ExpiredEnvelopeRow = {id: string;ownerEmail: string;ownerName: string | null;- signerEmail: string | null;- signerName: string | null;+ /** "Name (email)" of each signer it was waiting on, or null. */+ waitingOn: string | null;title: string;};@@ -77,13 +77,19 @@ async function listExpiredEnvelopesToNotify(e.expires_at AS "expiresAt",u.email AS "ownerEmail",u.name AS "ownerName",- s.name AS "signerName",- s.email AS "signerEmail"+ -- Everyone it was waiting on, in signing order: one signer, or a+ -- whole step of signers who sign at the same time.+ (+ SELECT string_agg(+ s.name || ' (' || s.email || ')',+ ', ' ORDER BY s.sign_order, s.id+ )+ FROM signers s+ WHERE s.envelope_id = e.id+ AND s.status = 'notified'+ ) AS "waitingOn"FROM envelopes eJOIN "user" u ON u.id = e.user_id- LEFT JOIN signers s- ON s.envelope_id = e.id- AND s.status = 'notified'WHERE e.status = 'sent'AND e.expires_at IS NOT NULLAND e.expires_at <= $1@@ -165,10 +171,9 @@ async function noteExpiryNoticeSent(function buildExpiryNotice(envelope: ExpiredEnvelopeRow) {const appUrl = resolveAppUrl();const link = appUrl ? `${appUrl}/envelopes/${envelope.id}` : null;- const waitingOn =- envelope.signerName && envelope.signerEmail- ? ` It was still waiting on ${envelope.signerName} (${envelope.signerEmail}).`- : "";+ const waitingOn = envelope.waitingOn+ ? ` It was still waiting on ${envelope.waitingOn}.`+ : "";return {subject: `"${envelope.title}" expired before everyone signed`,@@ -223,14 +228,16 @@ async function sendExpiryNotices({* reminder interval. Expired ones are left out: their link is dead, and the* sender has been told.*/-async function listEnvelopesDueForReminder(+async function listSignersDueForReminder(now: number,database: DbPool,-): Promise<string[]> {- const rows = await queryMany<{ id: string }>(+): Promise<{ envelopeId: string; signerId: string }[]> {+ // One row for each waiting signer who is due: signers of a step that+ // signs at the same time are each reminded on their own schedule.+ return queryMany<{ envelopeId: string; signerId: string }>(database,`- SELECT e.id+ SELECT e.id AS "envelopeId", s.id AS "signerId"FROM envelopes eJOIN signers sON s.envelope_id = e.id@@ -251,13 +258,12 @@ async function listEnvelopesDueForReminder(COALESCE(s.last_notified_at, 0),COALESCE(s.last_nudged_at, 0)) ASC,- e.id ASC+ e.id ASC,+ s.id ASCLIMIT ${BATCH_SIZE}`,[now, AUTOMATIC_REMINDER_SLACK_SECONDS],);-- return rows.map((row) => row.id);}async function sendAutomaticReminders({@@ -267,7 +273,10 @@ async function sendAutomaticReminders({outOfTime,summary,}: ScheduleRun): Promise<void> {- for (const envelopeId of await listEnvelopesDueForReminder(now, database)) {+ for (const { envelopeId, signerId } of await listSignersDueForReminder(+ now,+ database,+ )) {if (outOfTime()) {summary.stoppedEarly = true;return;@@ -278,6 +287,7 @@ async function sendAutomaticReminders({database,emailService: emailService(),nowUnixTimestamp: now,+ signerId,});if (sent) {diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 75520b8..d905dc0 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -128,6 +128,18 @@ import {import { formatEnvelopeOwner } from "./envelope-access.ts";import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";import { hashAccessCode } from "./signer-checks.ts";+import {+ describeSignerLimit,+ getMaxSignersPerEnvelope,+} from "./signer-limit.ts";+import {+ firstStepSigners,+ hasSharedSigningStep,+ joinNames,+ normalizeSigningSteps,+ signingStepOf,+ SigningStepError,+} from "./signing-steps.ts";import { escapeHtml } from "./utils/html.ts";type CreateDraftEnvelopeOptions = {@@ -228,6 +240,7 @@ type SignerRow = {signatureMeaning: SignatureMeaning | null;signedAt: number | null;signOrder: number;+ signingStep: number | null;signingTokenExpiresAt: number | null;signingTokenHash: string | null;status: SignerRecord["status"];@@ -332,6 +345,8 @@ export type ReviewSignerSummary = {id: string;name: string;order: number;+ /** The step of the signing order; signers who share one sign together. */+ step: number;};export type ReviewEnvelopeData = {@@ -363,11 +378,15 @@ export type DraftSignerStepSigner = {requireEmailCode?: boolean;/** Set on the signers step only. */signatureMeaning?: SignatureMeaning | null;+ /** The step of the signing order; signers who share one sign together. */+ step: number;};export type DraftSignerStepData = {copyRecipients: readonly CopyRecipientRecord[];envelopeId: string;+ /** The most signers this install allows on one envelope. */+ maxSigners: number;/** Part 11 mode is on, so each signer needs a meaning and an account. */part11Mode?: boolean;signers: readonly DraftSignerStepSigner[];@@ -393,6 +412,8 @@ export type EnvelopeDetailSignerView = {order: number;status: "declined" | "pending" | "signed" | "waiting";statusDateLabel?: string;+ /** The step of the signing order; signers who share one sign together. */+ step: number;};export type EnvelopeDetailTimelineItem = {@@ -445,8 +466,9 @@ export type DraftEnvelopeDocument = {};/**- * 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.+ * Copy recipients are stored after every signer. Signers use 1 up to+ * MAX_SIGNERS_CEILING (100), and a rewrite of the signer list parks rows+ * 1000 higher for a moment.*/const COPY_RECIPIENT_SIGN_ORDER_BASE = 500;@@ -943,9 +965,10 @@ export async function copyEnvelopeToDraft(updated_at,access_code_hash,require_email_code,- signature_meaning+ signature_meaning,+ signing_step) VALUES (- $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10, $11)`,[@@ -959,6 +982,7 @@ export async function copyEnvelopeToDraft(null,checks.get(signer.id)?.requireEmailCode ?? false,null,+ signingStepOf(signer),],);}@@ -1200,6 +1224,7 @@ async function listSignersForEnvelopeIds(name,email,sign_order AS "signOrder",+ signing_step AS "signingStep",status,signing_token_hash AS "signingTokenHash",signing_token_expires_at AS "signingTokenExpiresAt",@@ -1433,15 +1458,23 @@ function buildDashboardContextLine(}if (envelope.status === "sent") {- const currentSigner =- signers.find((signer) => signer.status === "notified") ??- signers.find((signer) => signer.status === "pending");+ // Everyone whose turn it is: one signer, or all of a step that signs+ // at the same time.+ const waiting = signers.filter((signer) => signer.status === "notified");+ const currentSigners =+ waiting.length > 0+ ? waiting+ : signers.filter((signer) => signer.status === "pending").slice(0, 1);+ const waitingOn =+ currentSigners.length > 0+ ? currentSigners.map((signer) => signer.email).join(", ")+ : "—";if (isEnvelopeExpired(envelope, Math.floor(Date.now() / 1000))) {- return `Expired ${formatShortDate(envelope.expiresAt!)} · was waiting on: ${currentSigner?.email ?? "—"}`;+ return `Expired ${formatShortDate(envelope.expiresAt!)} · was waiting on: ${waitingOn}`;}- return `Waiting on: ${currentSigner?.email ?? "—"}`;+ return `Waiting on: ${waitingOn}`;}if (envelope.status === "declined") {@@ -1673,8 +1706,23 @@ function buildTimelineDescription(event: AuditEventRecord): string {return "Copied from an earlier envelope";case "created":return "Envelope created";- case "sent":- return `Sent to ${targetLabel}`;+ case "sent": {+ // A first step of several signers names them all.+ const stepSigners = Array.isArray(event.metadata?.stepSigners)+ ? event.metadata.stepSigners.flatMap((entry: unknown) =>+ typeof entry === "object" &&+ entry !== null &&+ "signerName" in entry &&+ typeof entry.signerName === "string"+ ? [entry.signerName]+ : [],+ )+ : [];++ return stepSigners.length > 1+ ? `Sent to ${joinNames(stepSigners)} to sign at the same time`+ : `Sent to ${targetLabel}`;+ }case "viewed":return `Viewed by ${targetLabel}`;case "signed":@@ -2021,8 +2069,24 @@ export async function getEnvelopeDetailDataForUser(tone: TIMELINE_TONE_MAP[event.event],}));- const signerViews = signers.map((signer, index) => {- const previousSignerName = index > 0 ? signers[index - 1]?.name : undefined;+ const signerViews = signers.map((signer) => {+ const step = signingStepOf(signer);+ // Whoever signs in the step just before this signer's.+ const previousStep = signers+ .map(signingStepOf)+ .filter((other) => other < step)+ .reduce<number | null>(+ (latest, other) => (latest === null || other > latest ? other : latest),+ null,+ );+ const previousSignerName =+ previousStep === null+ ? undefined+ : joinNames(+ signers+ .filter((other) => signingStepOf(other) === previousStep)+ .map((other) => other.name),+ );const signerStatus: EnvelopeDetailSignerView["status"] =signer.status === "notified" ? "waiting" : signer.status;@@ -2042,26 +2106,38 @@ export async function getEnvelopeDetailDataForUser(signer,previousSignerName,),+ step,};});- const currentSigner = signers.find((signer) => signer.status === "notified");+ // Everyone whose turn it is. A reminder goes to each of them whose last+ // one is far enough back (reminders.ts), so the button works while any of+ // them can have one.+ const waitingSigners = signers.filter(+ (signer) => signer.status === "notified",+ );let manualReminder: EnvelopeDetailManualReminderState | null = null;const nowUnixTimestamp = Math.floor(Date.now() / 1000);const expired = isEnvelopeExpired(envelope, nowUnixTimestamp);- if (envelope.status === "sent" && currentSigner && expired) {+ if (envelope.status === "sent" && waitingSigners.length > 0 && expired) {// A reminder would carry a link that no longer works.manualReminder = { canSend: false, nextAvailableAtLabel: null };- } else if (envelope.status === "sent" && currentSigner) {- const nextAvailableAt =- typeof currentSigner.lastNudgedAt === "number"- ? getManualNudgeAvailableAt(currentSigner.lastNudgedAt)- : null;- const canSend = isManualNudgeAvailable(- currentSigner.lastNudgedAt,- nowUnixTimestamp,+ } else if (envelope.status === "sent" && waitingSigners.length > 0) {+ const canSend = waitingSigners.some((signer) =>+ isManualNudgeAvailable(signer.lastNudgedAt, nowUnixTimestamp),);+ const nextAvailableAt = waitingSigners+ .map((signer) =>+ typeof signer.lastNudgedAt === "number"+ ? getManualNudgeAvailableAt(signer.lastNudgedAt)+ : null,+ )+ .reduce<number | null>(+ (earliest, at) =>+ at !== null && (earliest === null || at < earliest) ? at : earliest,+ null,+ );manualReminder = {canSend,@@ -2116,6 +2192,7 @@ export async function getDraftSignerStepDataForUser(return {copyRecipients: await listCopyRecipientsForEnvelopeId(envelopeId, database),envelopeId,+ maxSigners: getMaxSignersPerEnvelope(),part11Mode: (await readStoredSettings(database))?.part11Mode ?? false,signers: (await listSignersForEnvelopeId(envelopeId, database)).map((signer) => ({@@ -2126,6 +2203,7 @@ export async function getDraftSignerStepDataForUser(order: signer.signOrder,requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,+ step: signingStepOf(signer),}),),status: envelope.status,@@ -2323,6 +2401,7 @@ export async function getPrepareEnvelopeDataForUser(id: signer.id,name: signer.name,order: signer.signOrder,+ step: signingStepOf(signer),})),status: envelope.status,title: envelope.title,@@ -2383,6 +2462,7 @@ export async function getReviewEnvelopeDataForUser(id: signer.id,name: signer.name,order: signer.signOrder,+ step: signingStepOf(signer),})),sizeLabel: formatFileSize(envelope.sourcePdfSizeBytes),status: envelope.status,@@ -2498,6 +2578,32 @@ export async function sendDraftEnvelope(// provider. Part 11 envelopes are signed with the signers' accounts, and// the two are not combined.const signatureLevel = input.signatureLevel ?? "simple";++ // Signing at the same time is for SignuDoc's own simple signatures.+ //+ // * Part 11 mode keeps one signer after another. Its validation+ // (docs/part11, SYS-08 and OQ-06) is written for that order, and a+ // changed sequence would need the install's OQ run again before use.+ // * A signature in the signer's own name is added to the PDF on top of+ // the one before it, so two cannot be made at once: the second would+ // be refused once the first was saved, after the signer had already+ // been through the provider.+ if (hasSharedSigningStep(signers)) {+ if (part11) {+ throw new EnvelopeMutationError(+ "Part 11 mode signs one signer after another. Give each signer their own step in the signing order.",+ 400,+ );+ }++ if (signatureLevel !== "simple") {+ throw new EnvelopeMutationError(+ "Advanced and qualified signatures are added one after another. Give each signer their own step, or send with simple signatures.",+ 400,+ );+ }+ }+const signingProvider =signatureLevel === "simple" ? null : configuredSigningProvider();@@ -2548,7 +2654,9 @@ export async function sendDraftEnvelope(}}- const firstSigner = signers[0];+ // Everyone in the first step of the signing order is invited now.+ const firstSigners = firstStepSigners(signers);+ const firstSigner = firstSigners[0];if (!firstSigner) {throw new EnvelopeMutationError(@@ -2571,10 +2679,17 @@ export async function sendDraftEnvelope(const sentAt = Math.floor(Date.now() / 1000);const sentAuditAt = Math.max(sentAt, envelope.createdAt + 1);const expiresAt = deadlineFromDays(sentAt, input.expiresInDays);- const issuedLink = await issueSigningLink({- expiresInSeconds: expiresAt - sentAt,- issuedAt: sentAt,- });+ const issuedLinks = new Map<string, IssuedSigningLink>();++ for (const signer of firstSigners) {+ issuedLinks.set(+ signer.id,+ await issueSigningLink({+ expiresInSeconds: expiresAt - sentAt,+ issuedAt: sentAt,+ }),+ );+ }try {await withTransaction(async (tx) => {@@ -2682,35 +2797,38 @@ export async function sendDraftEnvelope(}}- const updatedSigner = await tx.query(- `- UPDATE signers- SET- status = 'notified',- signing_token_hash = $1,- signing_token_expires_at = $2,- turn_started_at = $3,- last_notified_at = $4,- updated_at = $5- WHERE id = $6- AND envelope_id = $7- `,- [- issuedLink.tokenHash,- issuedLink.exp,- sentAt,- sentAt,- sentAt,- firstSigner.id,- envelopeId,- ],- );-- if (updatedSigner.rowCount !== 1) {- throw new EnvelopeMutationError(- "Unable to activate the first signer for this envelope.",- 500,+ for (const signer of firstSigners) {+ const issuedLink = issuedLinks.get(signer.id)!;+ const updatedSigner = await tx.query(+ `+ UPDATE signers+ SET+ status = 'notified',+ signing_token_hash = $1,+ signing_token_expires_at = $2,+ turn_started_at = $3,+ last_notified_at = $4,+ updated_at = $5+ WHERE id = $6+ AND envelope_id = $7+ `,+ [+ issuedLink.tokenHash,+ issuedLink.exp,+ sentAt,+ sentAt,+ sentAt,+ signer.id,+ envelopeId,+ ],);++ if (updatedSigner.rowCount !== 1) {+ throw new EnvelopeMutationError(+ "Unable to activate the first signer for this envelope.",+ 500,+ );+ }}await recordAuditEvent(@@ -2737,6 +2855,16 @@ export async function sendDraftEnvelope(signerEmail: firstSigner.email,signerId: firstSigner.id,signerName: firstSigner.name,+ // Everyone invited, when the first step has more than one.+ ...(firstSigners.length > 1+ ? {+ stepSigners: firstSigners.map((signer) => ({+ signerEmail: signer.email,+ signerId: signer.id,+ signerName: signer.name,+ })),+ }+ : {}),},userAgent: input.userAgent ?? null,},@@ -2747,22 +2875,32 @@ export async function sendDraftEnvelope(throw error;}- let invitationMessageId: string | undefined;+ // The first invitation decides whether the envelope went out. If it+ // fails, nothing has been delivered, and the envelope goes back to being+ // a draft. Once one has been accepted the envelope is out: a later one+ // that fails is logged, and the sender's reminder (or the automatic one)+ // sends that signer a new link.+ const invitationMessageIds = new Map<string, string | undefined>();+ let branding: Branding;try {- invitationMessageId = (- await emailService.send(- buildSigningInvitationEmail({- branding: await getBranding(),- envelopeTitle: envelope.title,- expiresAt,- senderName: input.senderName,- signerEmail: firstSigner.email,- signerName: firstSigner.name,- signingUrl: issuedLink.url,- }),- )- ).messageId;+ branding = await getBranding();+ invitationMessageIds.set(+ firstSigner.id,+ (+ await emailService.send(+ buildSigningInvitationEmail({+ branding,+ envelopeTitle: envelope.title,+ expiresAt,+ senderName: input.senderName,+ signerEmail: firstSigner.email,+ signerName: firstSigner.name,+ signingUrl: issuedLinks.get(firstSigner.id)!.url,+ }),+ )+ ).messageId,+ );} catch (error) {await withTransaction(async (tx) => {await tx.query(@@ -2831,26 +2969,74 @@ export async function sendDraftEnvelope(throw error;}- await recordEmailSent(- {- envelopeId,- messageId: invitationMessageId,- recipient: firstSigner.email,- signerId: firstSigner.id,- template: "signing_invitation",- },- database,- );+ for (const signer of firstSigners.slice(1)) {+ try {+ invitationMessageIds.set(+ signer.id,+ (+ await emailService.send(+ buildSigningInvitationEmail({+ branding,+ envelopeTitle: envelope.title,+ expiresAt,+ senderName: input.senderName,+ signerEmail: signer.email,+ signerName: signer.name,+ signingUrl: issuedLinks.get(signer.id)!.url,+ }),+ )+ ).messageId,+ );+ } catch (error) {+ console.error(+ `Failed to send the invitation for envelope ${envelopeId} to ${signer.email}:`,+ error,+ );+ }+ }++ for (const signer of firstSigners) {+ if (!invitationMessageIds.has(signer.id)) {+ continue;+ }++ await recordEmailSent(+ {+ envelopeId,+ messageId: invitationMessageIds.get(signer.id),+ recipient: signer.email,+ signerId: signer.id,+ template: "signing_invitation",+ },+ database,+ );+ }return sendEnvelopeResponseSchema.parse({envelopeId,expiresAt,- notifiedSignerName: firstSigner.name,+ // Only those whose invitation went out.+ notifiedSignerName: describeNotifiedSigners(+ firstSigners+ .filter((signer) => invitationMessageIds.has(signer.id))+ .map((signer) => signer.name),+ ),redirectPath: `/envelopes/${envelopeId}`,sentAt,});}+/** Who was invited, short enough for the message the sender sees. */+function describeNotifiedSigners(names: readonly string[]): string {+ const all = joinNames(names);++ if (all.length <= 160 || names.length < 2) {+ return all.slice(0, 160);+ }++ return `${names[0]!.slice(0, 120)} and ${String(names.length - 1)} others`;+}+type ChangeEnvelopeDeadlineInput = {expiresInDays: number;ipAddress?: string | null;@@ -3324,7 +3510,39 @@ export async function changeEnvelopeReminders(});}+/** A signer signed between the void's first read and its lock. */+class VoidRouteChangedError extends Error {+ constructor() {+ super("A signer signed while the envelope was being voided.");+ this.name = "VoidRouteChangedError";+ }+}+export async function voidSentEnvelope(+ userId: string,+ envelopeId: string,+ input: VoidEnvelopeInput,+ options: VoidEnvelopeOptions = {},+): Promise<VoidEnvelopeResult> {+ for (let attempt = 1; ; attempt += 1) {+ try {+ return await voidSentEnvelopeOnce(userId, envelopeId, input, options);+ } catch (error) {+ if (!(error instanceof VoidRouteChangedError)) {+ throw error;+ }++ if (attempt >= 5) {+ throw new EnvelopeMutationError(+ "Signers were signing while you voided this envelope. Try again.",+ 409,+ );+ }+ }+ }+}++async function voidSentEnvelopeOnce(userId: string,envelopeId: string,input: VoidEnvelopeInput,@@ -3462,6 +3680,26 @@ export async function voidSentEnvelope();}+ // The certificates show the signers as they were read before the lock.+ // A signer who signed in between (one of several signing at the same+ // time, say) would be shown as still waiting, without their signature+ // in the audit trail shown. Then the void starts again from what is+ // there now.+ const statusesNow = await tx.query<{ id: string; status: string }>(+ `SELECT id, status FROM signers WHERE envelope_id = $1 AND role = 'signer'`,+ [envelopeId],+ );++ if (+ statusesNow.rows.length !== signers.length ||+ statusesNow.rows.some(+ (row) =>+ signers.find((signer) => signer.id === row.id)?.status !== row.status,+ )+ ) {+ throw new VoidRouteChangedError();+ }+const certificate = await storeEnvelopeCertificatePdf({auditEvents,@@ -3840,6 +4078,27 @@ export async function replaceDraftEnvelopeSigners(throw new EnvelopeMutationError(duplicateCopyRecipientEmailMessage, 400);}+ const maxSigners = getMaxSignersPerEnvelope();++ if (parsedInput.signers.length > maxSigners) {+ throw new EnvelopeMutationError(describeSignerLimit(maxSigners), 400);+ }++ // Each signer's step of the signing order, in the order of the list.+ let signingSteps: number[];++ try {+ signingSteps = normalizeSigningSteps(+ parsedInput.signers.map((signer) => signer.signingStep),+ );+ } catch (error) {+ if (error instanceof SigningStepError) {+ throw new EnvelopeMutationError(error.message, 400);+ }++ throw error;+ }+const existingSignerIds = new Set(existingSigners.map((signer) => signer.id));const usedSignerIds = new Set<string>();const updatedAt = Math.floor(Date.now() / 1000);@@ -3867,6 +4126,7 @@ export async function replaceDraftEnvelopeSigners(requireEmailCode: signer.requireEmailCode,signatureMeaning: signer.signatureMeaning,signOrder: index + 1,+ signingStep: signingSteps[index]!,};});@@ -3906,7 +4166,8 @@ export async function replaceDraftEnvelopeSigners(updated_at = $4,access_code_hash = CASE WHEN $7::boolean THEN $8 ELSE access_code_hash END,require_email_code = COALESCE($9, require_email_code),- signature_meaning = CASE WHEN $10::boolean THEN $11 ELSE signature_meaning END+ signature_meaning = CASE WHEN $10::boolean THEN $11 ELSE signature_meaning END,+ signing_step = $12WHERE id = $5 AND envelope_id = $6`,[@@ -3921,6 +4182,7 @@ export async function replaceDraftEnvelopeSigners(signer.requireEmailCode ?? null,signer.signatureMeaning !== undefined,signer.signatureMeaning ?? null,+ signer.signingStep,],);} else {@@ -3945,9 +4207,10 @@ export async function replaceDraftEnvelopeSigners(updated_at,access_code_hash,require_email_code,- signature_meaning+ signature_meaning,+ signing_step) VALUES (- $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10, $11)`,[@@ -3961,6 +4224,7 @@ export async function replaceDraftEnvelopeSigners(signer.accessCodeHash ?? null,signer.requireEmailCode ?? false,signer.signatureMeaning ?? null,+ signer.signingStep,],);}@@ -4023,6 +4287,7 @@ export async function replaceDraftEnvelopeSigners(requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,signOrder: signer.signOrder,+ signingStep: signingStepOf(signer),}),),updatedAt,diff --git a/src/lib/parallel-signing.dbtest.ts b/src/lib/parallel-signing.dbtest.tsnew file mode 100644index 0000000..a4f6b8c--- /dev/null+++ b/src/lib/parallel-signing.dbtest.ts@@ -0,0 +1,766 @@+import assert from "node:assert/strict";+import { createHash, randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { createRequire, syncBuiltinESMExports } from "node:module";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";++import { PDFDocument } from "pdf-lib";+import type pg from "pg";++import { afterStatement, openTestDatabase } from "./db/test-database.ts";+import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";+import {+ EnvelopeMutationError,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+ sendDraftEnvelope,+} from "./envelopes.ts";+import { sendAutomaticEnvelopeReminder } from "./reminders.ts";+import { verifyAuditChain } from "./services/audit.ts";+import { issueSigningLink } from "./services/signing-links.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import { saveSettings } from "./settings.ts";+import {+ declineSigningForToken,+ recordSignerConsent,+ submitSigningForToken,+} from "./signing.ts";++// Signing at the same time, against a real Postgres: signers who share a+// step of the signing order are invited together, the next step waits for+// all of them, and two of them submitting at the same moment still move+// the order on, or finish the envelope, exactly once. Run with+// `npm run test:db`.++process.env.APP_URL ??= "https://sign.example.test";++const DAY = 24 * 60 * 60;++// A PNG of one transparent pixel, standing in for a drawn signature.+const DRAWN_SIGNATURE =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";++let database: pg.Pool;+let workDir: string;+let storageService: StorageService;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+ globalThis.__signudocPgPool = database;+ workDir = await mkdtemp(path.join(tmpdir(), "signudoc-parallel-"));+ Object.assign(process.env, {+ EMAIL_CAPTURE_DIR: path.join(workDir, "outbox"),+ EMAIL_DRIVER: "capture",+ STORAGE_DRIVER: "local",+ STORAGE_LOCAL_DIR: workDir,+ });+ storageService = createStorageService();+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+ await rm(workDir, { force: true, recursive: true });+});++type Party = {+ fieldId: string;+ id: string;+ name: string;+ token: string | null;+};++/**+ * An envelope out for signature whose signers are in the given steps, in+ * list order: [1, 1, 2] is two signers at the same time, then a third. The+ * first step's signers are waiting with a link each and have agreed to+ * electronic records; the rest are pending.+ */+async function createSteppedEnvelope(steps: readonly number[]) {+ const userId = randomUUID();+ const envelopeId = randomUUID();+ const now = Math.floor(Date.now() / 1000);+ const sourcePdf = await PDFDocument.create();++ sourcePdf.addPage([612, 792]);++ const sourcePdfBytes = await sourcePdf.save();+ const sourcePdfKey = `test/${envelopeId}.pdf`;++ await storageService.putObject({+ body: sourcePdfBytes,+ contentType: "application/pdf",+ key: sourcePdfKey,+ });++ 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, sent_at, expires_at,+ reminder_interval_days+ ) values ($1, $2, 'Contract', 'sent', $3, 'contract.pdf', $4, 1, $5, $6, $7, 1)+ `,+ [+ envelopeId,+ userId,+ sourcePdfKey,+ sourcePdfBytes.length,+ createHash("sha256").update(sourcePdfBytes).digest("hex"),+ now,+ now + 30 * DAY,+ ],+ );+ await database.query(+ `+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)+ values ($1, $2, 1, 612, 792)+ `,+ [randomUUID(), envelopeId],+ );++ const parties: Party[] = [];++ for (const [index, step] of steps.entries()) {+ const id = randomUUID();+ const fieldId = randomUUID();+ const waiting = step === steps[0];+ const link = waiting+ ? await issueSigningLink({ expiresInSeconds: DAY, issuedAt: now })+ : null;+ const name = `Signer ${String(index + 1)}`;++ await database.query(+ `+ insert into signers (+ id, envelope_id, name, email, sign_order, signing_step, status,+ signing_token_hash, signing_token_expires_at, turn_started_at,+ last_notified_at+ ) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10)+ `,+ [+ id,+ envelopeId,+ name,+ `${id}@example.test`,+ index + 1,+ step,+ waiting ? "notified" : "pending",+ link?.tokenHash ?? null,+ link?.exp ?? null,+ waiting ? now - 2 * DAY : null,+ ],+ );+ await database.query(+ `+ insert into fields (+ id, envelope_id, signer_id, type, page, x, y, width, height+ ) values ($1, $2, $3, 'signature', 1, 0.1, $4, 0.2, 0.05)+ `,+ [fieldId, envelopeId, id, 0.1 + index * 0.06],+ );++ if (link) {+ await recordSignerConsent(+ link.token,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database },+ );+ }++ parties.push({ fieldId, id, name, token: link?.token ?? null });+ }++ return { envelopeId, parties, sourcePdfKey, userId };+}++/**+ * Gives a signer whose turn has come a link this test knows, the way the+ * invitation's link would be opened, and has them agree to electronic+ * records.+ */+async function takeOverLink(party: Party) {+ const now = Math.floor(Date.now() / 1000);+ const link = await issueSigningLink({ expiresInSeconds: DAY, issuedAt: now });+ const updated = await database.query(+ `+ update signers+ set signing_token_hash = $1, signing_token_expires_at = $2+ where id = $3 and status = 'notified'+ `,+ [link.tokenHash, link.exp, party.id],+ );++ assert.equal(updated.rowCount, 1, `${party.name} is not waiting`);+ await recordSignerConsent(+ link.token,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database },+ );+ party.token = link.token;+}++function sign(party: Party, pool: pg.Pool = database) {+ assert.ok(party.token, `${party.name} has no link`);++ return submitSigningForToken(+ party.token,+ {+ clientTimezoneOffsetMinutes: 0,+ fields: [+ {+ fieldId: party.fieldId,+ imageDataUrl: DRAWN_SIGNATURE,+ inputMethod: "drawn",+ type: "signature",+ },+ ],+ },+ { database: pool },+ );+}++async function statusesOf(envelopeId: string) {+ const result = await database.query<{ status: string }>(+ `+ select status from signers+ where envelope_id = $1 and role = 'signer'+ order by sign_order+ `,+ [envelopeId],+ );++ return result.rows.map((row) => row.status);+}++async function envelopeStatusOf(envelopeId: string) {+ const result = await database.query<{ status: string }>(+ `select status from envelopes where id = $1`,+ [envelopeId],+ );++ return result.rows[0]?.status;+}++async function countEvents(envelopeId: string, event: string) {+ const result = await database.query<{ count: number }>(+ `+ select count(*)::int as count from audit_events+ where envelope_id = $1 and event = $2+ `,+ [envelopeId, event],+ );++ return result.rows[0]?.count ?? 0;+}++async function invitationsTo(envelopeId: string, signerId: string) {+ const result = await database.query<{ count: number }>(+ `+ select count(*)::int as count from audit_events+ where envelope_id = $1+ and event = 'email_sent'+ and metadata->>'template' = 'signing_invitation'+ and metadata->>'signerId' = $2+ `,+ [envelopeId, signerId],+ );++ return result.rows[0]?.count ?? 0;+}++/** Resolves once another session is held up behind a lock, or `isOver()`. */+async function waitForLockWaiter(isOver: () => boolean) {+ for (let attempt = 0; attempt < 300; attempt += 1) {+ if (isOver()) {+ return;+ }++ const waiting = await database.query(+ `+ select 1+ from pg_stat_activity+ where datname = current_database() and wait_event_type = 'Lock'+ limit 1+ `,+ );++ if (waiting.rowCount) {+ return;+ }++ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ throw new Error("Nothing came to wait for the envelope.");+}++/**+ * The same database, except that `start()` gets under way right after the+ * one using it has written its signer's `status = 'signed'`, and before it+ * commits: what `start()` began read the envelope while the first signature+ * was not yet saved, and has to wait for the envelope's row.+ */+function withRivalAfterSignature(start: () => Promise<unknown>) {+ const started: { rival?: Promise<unknown> } = {};+ const pool = afterStatement(+ database,+ (text) => !started.rival && text.includes("status = 'signed'"),+ async () => {+ let over = false;+ const rival = start();++ rival.then(+ () => {+ over = true;+ },+ () => {+ over = true;+ },+ );+ started.rival = rival;+ await waitForLockWaiter(() => over);+ },+ );++ return { pool, started };+}++test("signers of one step are invited together, and the next step waits for all of them", async () => {+ const envelope = await createSteppedEnvelope([1, 1, 2]);+ const [first, second, third] = envelope.parties as [Party, Party, Party];++ await sign(first);++ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "notified",+ "pending",+ ]);+ assert.equal(await invitationsTo(envelope.envelopeId, third.id), 0);++ await sign(second);++ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "signed",+ "notified",+ ]);+ assert.equal(await invitationsTo(envelope.envelopeId, third.id), 1);+ assert.equal(await envelopeStatusOf(envelope.envelopeId), "sent");++ await takeOverLink(third);+ await sign(third);++ assert.equal(await envelopeStatusOf(envelope.envelopeId), "completed");+ assert.equal(await countEvents(envelope.envelopeId, "signed"), 3);+ assert.equal(await countEvents(envelope.envelopeId, "completed"), 1);+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );+});++test("a step's signers start the next step together when it has several", async () => {+ const envelope = await createSteppedEnvelope([1, 2, 2]);+ const [first, second, third] = envelope.parties as [Party, Party, Party];++ await sign(first);++ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "notified",+ "notified",+ ]);+ assert.equal(await invitationsTo(envelope.envelopeId, second.id), 1);+ assert.equal(await invitationsTo(envelope.envelopeId, third.id), 1);+});++test("two signers of the last step who submit at the same moment finish the envelope once", async () => {+ const envelope = await createSteppedEnvelope([1, 1]);+ const [first, second] = envelope.parties as [Party, Party];+ // The second signer reads the envelope while the first signature is+ // written but not saved, so takes it for one that is not the last, and+ // only learns otherwise once it holds the envelope.+ const { pool, started } = withRivalAfterSignature(() => sign(second));++ await sign(first, pool);++ assert.ok(started.rival, "the first signature was never written");+ await started.rival;++ assert.deepEqual(await statusesOf(envelope.envelopeId), ["signed", "signed"]);+ assert.equal(await envelopeStatusOf(envelope.envelopeId), "completed");+ assert.equal(await countEvents(envelope.envelopeId, "signed"), 2);+ assert.equal(await countEvents(envelope.envelopeId, "completed"), 1);+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );++ const row = await database.query<{+ signed_pdf_key: string | null;+ signed_pdf_sha256: string | null;+ }>(`select signed_pdf_key, signed_pdf_sha256 from envelopes where id = $1`, [+ envelope.envelopeId,+ ]);+ const stored = row.rows[0]!;++ assert.ok(stored.signed_pdf_key);+ assert.equal(+ createHash("sha256")+ .update((await storageService.getObject(stored.signed_pdf_key)).body)+ .digest("hex"),+ stored.signed_pdf_sha256,+ );+});++test("two signers of a middle step who submit at the same moment invite the next step once", async () => {+ const envelope = await createSteppedEnvelope([1, 1, 2]);+ const [first, second, third] = envelope.parties as [Party, Party, Party];+ const { pool, started } = withRivalAfterSignature(() => sign(second));++ await sign(first, pool);++ assert.ok(started.rival, "the first signature was never written");+ await started.rival;++ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "signed",+ "notified",+ ]);+ assert.equal(await envelopeStatusOf(envelope.envelopeId), "sent");+ assert.equal(await invitationsTo(envelope.envelopeId, third.id), 1);+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );+});++test("a decline while another signer of the step signs starts again from that signature", async () => {+ const envelope = await createSteppedEnvelope([1, 1, 2]);+ const [first, second] = envelope.parties as [Party, Party, Party];+ const { pool, started } = withRivalAfterSignature(() =>+ declineSigningForToken(+ second.token!,+ { reason: "Not this one." },+ {+ database,+ },+ ),+ );++ await sign(first, pool);++ assert.ok(started.rival, "the signature was never written");+ await started.rival;++ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "declined",+ "pending",+ ]);+ assert.equal(await envelopeStatusOf(envelope.envelopeId), "declined");++ // The signature that came first is in the trail before the decline.+ const events = await database.query<{ event: string }>(+ `+ select event from audit_events+ where envelope_id = $1 and event in ('signed', 'declined')+ order by sequence+ `,+ [envelope.envelopeId],+ );++ assert.deepEqual(+ events.rows.map((row) => row.event),+ ["signed", "declined"],+ );+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );+});++test("an automatic reminder reaches every waiting signer of the step", async () => {+ const envelope = await createSteppedEnvelope([1, 1, 2]);++ assert.equal(+ await sendAutomaticEnvelopeReminder(envelope.envelopeId, { database }),+ true,+ );+ assert.equal(await countEvents(envelope.envelopeId, "reminded_auto"), 2);+});++/** A draft with three signers, each with a signature field. */+async function createDraft(steps: readonly number[] | null) {+ const userId = randomUUID();+ const envelopeId = randomUUID();+ const sourcePdf = await PDFDocument.create();++ sourcePdf.addPage([612, 792]);++ const sourcePdfBytes = await sourcePdf.save();+ const sourcePdfKey = `test/${envelopeId}.pdf`;++ await storageService.putObject({+ body: sourcePdfBytes,+ contentType: "application/pdf",+ key: sourcePdfKey,+ });+ 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, 'Contract', 'draft', $3, 'contract.pdf', $4, 1, $5)+ `,+ [+ envelopeId,+ userId,+ sourcePdfKey,+ sourcePdfBytes.length,+ createHash("sha256").update(sourcePdfBytes).digest("hex"),+ ],+ );+ await database.query(+ `+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)+ values ($1, $2, 1, 612, 792)+ `,+ [randomUUID(), envelopeId],+ );++ const saved = await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ {+ signers: ["Ann", "Bob", "Cy"].map((name, index) => ({+ email: `${name.toLowerCase()}-${randomUUID()}@example.test`,+ name,+ ...(steps ? { signingStep: steps[index] } : {}),+ })),+ },+ database,+ );++ await replaceDraftEnvelopeFields(+ userId,+ envelopeId,+ {+ fields: saved.signers.map((signer, index) => ({+ height: 0.05,+ page: 1,+ required: true,+ signerId: signer.id,+ type: "signature",+ width: 0.2,+ x: 0.1,+ y: 0.1 + index * 0.1,+ })),+ },+ database,+ );++ return { envelopeId, saved, userId };+}++test("saved steps are renumbered, and a list without steps signs in order", async () => {+ const stepped = await createDraft([5, 5, 9]);++ assert.deepEqual(+ stepped.saved.signers.map((signer) => [+ signer.signOrder,+ signer.signingStep,+ ]),+ [+ [1, 1],+ [2, 1],+ [3, 2],+ ],+ );++ const plain = await createDraft(null);++ assert.deepEqual(+ plain.saved.signers.map((signer) => [signer.signOrder, signer.signingStep]),+ [+ [1, 1],+ [2, 2],+ [3, 3],+ ],+ );++ await assert.rejects(+ replaceDraftEnvelopeSigners(+ stepped.userId,+ stepped.envelopeId,+ {+ signers: [+ { email: "[email protected]", name: "A", signingStep: 2 },+ { email: "[email protected]", name: "B", signingStep: 1 },+ ],+ },+ database,+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError && error.statusCode === 400,+ );+});++test("sending invites everyone in the first step", async () => {+ const draft = await createDraft([1, 1, 2]);+ const sent = await sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ );++ assert.match(sent.notifiedSignerName, /Ann and Bob/);+ assert.deepEqual(await statusesOf(draft.envelopeId), [+ "notified",+ "notified",+ "pending",+ ]);++ for (const signer of draft.saved.signers.slice(0, 2)) {+ assert.equal(await invitationsTo(draft.envelopeId, signer.id), 1);+ }++ const tokens = await database.query<{ hash: string | null }>(+ `+ select signing_token_hash as hash from signers+ where envelope_id = $1 and status = 'notified'+ `,+ [draft.envelopeId],+ );++ assert.equal(new Set(tokens.rows.map((row) => row.hash)).size, 2);+});++test("advanced or qualified signatures are not sent to signers at the same time", async () => {+ const draft = await createDraft([1, 1, 2]);++ await assert.rejects(+ sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ {+ senderEmail: "[email protected]",+ senderName: "Sam Sender",+ signatureLevel: "advanced",+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 400 &&+ /one after another/.test(error.message),+ );+ assert.equal(await envelopeStatusOf(draft.envelopeId), "draft");+});++test("when a later first-step invitation fails, the sender is not told that person was invited", async () => {+ const draft = await createDraft([1, 1, 2]);+ const bob = draft.saved.signers[1]!;+ // The capture email driver writes each message to a file; making that+ // write fail for Bob's invitation alone stands in for a failed send.+ const require = createRequire(import.meta.url);+ const fsPromises = require("node:fs/promises") as {+ writeFile: (...args: unknown[]) => Promise<unknown>;+ };+ const realWriteFile = fsPromises.writeFile;++ fsPromises.writeFile = (...args: unknown[]) =>+ String(args[1]).includes(bob.email)+ ? Promise.reject(new Error("mail refused"))+ : realWriteFile(...args);+ syncBuiltinESMExports();++ const originalError = console.error;++ console.error = () => undefined;++ try {+ const sent = await sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ );++ assert.match(sent.notifiedSignerName, /Ann/);+ assert.doesNotMatch(sent.notifiedSignerName, /Bob/);+ } finally {+ console.error = originalError;+ fsPromises.writeFile = realWriteFile;+ syncBuiltinESMExports();+ }+});++test("qualified signatures are not sent to signers at the same time either", async () => {+ const draft = await createDraft([1, 1, 2]);++ await assert.rejects(+ sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ {+ senderEmail: "[email protected]",+ senderName: "Sam Sender",+ signatureLevel: "qualified",+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 400 &&+ /one after another/.test(error.message),+ );+ assert.equal(await envelopeStatusOf(draft.envelopeId), "draft");+});++test("Part 11 envelopes are not sent to signers at the same time", async () => {+ const draft = await createDraft([1, 1, 2]);++ await saveSettings({ part11Mode: true }, database);++ try {+ await assert.rejects(+ sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 400 &&+ /Part 11 mode signs one signer after another/.test(error.message),+ );+ } finally {+ await saveSettings({ part11Mode: false }, database);+ }++ assert.equal(await envelopeStatusOf(draft.envelopeId), "draft");+});diff --git a/src/lib/reminders.ts b/src/lib/reminders.tsindex ae0e660..c76037c 100644--- a/src/lib/reminders.ts+++ b/src/lib/reminders.ts@@ -8,6 +8,7 @@ import {type DbExecutor,type DbPool,getDb,+ queryMany,queryOne,withTransaction,} from "./db/connection.ts";@@ -176,9 +177,35 @@ async function getReminderEnvelope();}+/**+ * Everyone whose turn it is: one signer, or every signer of a step that+ * signs at the same time. Each is reminded on their own, with their own+ * link and their own wait between reminders.+ */+async function listWaitingSignerIds(+ envelopeId: string,+ database: DbExecutor,+): Promise<string[]> {+ const rows = await queryMany<{ id: string }>(+ database,+ `+ SELECT id+ FROM signers+ WHERE envelope_id = $1+ AND status = 'notified'+ ORDER BY sign_order ASC, id ASC+ `,+ [envelopeId],+ );++ return rows.map((row) => row.id);+}++/** The waiting signer, or the first of them when none is named. */async function getCurrentSignerForEnvelope(envelopeId: string,database: DbExecutor,+ signerId: string | null = null,): Promise<ReminderSignerRow | null> {return queryOne<ReminderSignerRow>(database,@@ -198,10 +225,11 @@ async function getCurrentSignerForEnvelope(FROM signersWHERE envelope_id = $1AND status = 'notified'+ AND ($2::text IS NULL OR id = $2)ORDER BY sign_order ASC, id ASCLIMIT 1`,- [envelopeId],+ [envelopeId, signerId],);}@@ -290,6 +318,7 @@ async function persistReminder(request: ReminderRequest,dispatchedAt: number,database: DbPool,+ signerId: string | null = null,): Promise<PersistedReminder> {const userId = request.kind === "manual" ? request.userId : null;const envelope = await getReminderEnvelope(envelopeId, userId, database);@@ -305,7 +334,11 @@ async function persistReminder();}- const signer = await getCurrentSignerForEnvelope(envelopeId, database);+ const signer = await getCurrentSignerForEnvelope(+ envelopeId,+ database,+ signerId,+ );if (!signer) {throw new ReminderMutationError(@@ -357,7 +390,13 @@ async function persistReminder();}- const persistedSigner = await getCurrentSignerForEnvelope(envelopeId, tx);+ // The same signer as the one read above: the first waiting one may be+ // another by now, if this one signed meanwhile.+ const persistedSigner = await getCurrentSignerForEnvelope(+ envelopeId,+ tx,+ signer.id,+ );if (!persistedSigner) {throw new ReminderMutationError(@@ -637,22 +676,79 @@ export async function sendManualEnvelopeNudge(throw error;}- const persisted = await persistReminder(- envelopeId,- { ...input, kind: "manual", userId },- nowUnixTimestamp,- database,- );+ // Every signer whose turn it is and whose last reminder is far enough+ // back. With nobody waiting, or an envelope that is not this sender's,+ // the one attempt with no signer named says why.+ const waitingSignerIds = await listWaitingSignerIds(envelopeId, database);+ const targets: (string | null)[] =+ waitingSignerIds.length > 0 ? waitingSignerIds : [null];+ const reminded: PersistedReminder[] = [];+ let refusal: ReminderMutationError | null = null;+ let deliveryError: unknown = null;++ for (const signerId of targets) {+ let persisted: PersistedReminder;++ try {+ persisted = await persistReminder(+ envelopeId,+ { ...input, kind: "manual", userId },+ nowUnixTimestamp,+ database,+ signerId,+ );+ } catch (error) {+ if (!(error instanceof ReminderMutationError)) {+ throw error;+ }- await deliverReminder(persisted, "manual", database, service);+ // Kept to explain why nothing was sent. Of two waits, the shorter.+ if (+ refusal === null ||+ (error.nextAvailableAt !== null &&+ (refusal.nextAvailableAt === null ||+ error.nextAvailableAt < refusal.nextAvailableAt))+ ) {+ refusal = error;+ }++ continue;+ }++ try {+ await deliverReminder(persisted, "manual", database, service);+ reminded.push(persisted);+ } catch (error) {+ // Put back as it was by deliverReminder. The others still go.+ deliveryError ??= error;+ }+ }++ const first = reminded[0];++ if (!first) {+ throw (+ deliveryError ??+ refusal ??+ new ReminderMutationError(+ "This envelope is no longer waiting on a signer.",+ 409,+ )+ );+ }++ const names = reminded.map((entry) => entry.signerName);return manualNudgeResponseSchema.parse({- envelopeId: persisted.envelopeId,- nextAvailableAt: persisted.nextAvailableAt,- nextAvailableAtLabel: formatReminderAvailableAt(persisted.nextAvailableAt),+ envelopeId: first.envelopeId,+ nextAvailableAt: first.nextAvailableAt,+ nextAvailableAtLabel: formatReminderAvailableAt(first.nextAvailableAt),sentAt: nowUnixTimestamp,- signerId: persisted.signerId,- signerName: persisted.signerName,+ signerId: first.signerId,+ signerName:+ names.length === 1+ ? first.signerName+ : `${first.signerName.slice(0, 120)} and ${String(names.length - 1)} more`,});}@@ -670,31 +766,45 @@ export async function sendAutomaticEnvelopeReminder(database = getDb(),emailService,nowUnixTimestamp = Math.floor(Date.now() / 1000),- }: SendReminderOptions = {},+ signerId,+ }: SendReminderOptions & {+ /** One waiting signer. Left out: each waiting signer who is due. */+ signerId?: string;+ } = {},): Promise<boolean> {- let persisted: PersistedReminder;+ const targets = signerId+ ? [signerId]+ : await listWaitingSignerIds(envelopeId, database);+ let sent = false;- try {- persisted = await persistReminder(- envelopeId,- { kind: "automatic" },- nowUnixTimestamp,+ for (const target of targets) {+ let persisted: PersistedReminder;++ try {+ persisted = await persistReminder(+ envelopeId,+ { kind: "automatic" },+ nowUnixTimestamp,+ database,+ target,+ );+ } catch (error) {+ if (error instanceof ReminderMutationError) {+ continue;+ }++ throw error;+ }++ await deliverReminder(+ persisted,+ "automatic",database,+ emailService ?? createEmailService(),);- } catch (error) {- if (error instanceof ReminderMutationError) {- return false;- }- throw error;+ sent = true;}- await deliverReminder(- persisted,- "automatic",- database,- emailService ?? createEmailService(),- );-- return true;+ return sent;}diff --git a/src/lib/schemas/signer.ts b/src/lib/schemas/signer.tsindex 6443da1..8e6bb3a 100644--- a/src/lib/schemas/signer.ts+++ b/src/lib/schemas/signer.ts@@ -2,7 +2,7 @@ import { z } from "zod";import {MAX_COPY_RECIPIENTS_PER_ENVELOPE,- MAX_SIGNERS_PER_ENVELOPE,+ MAX_SIGNERS_CEILING,signatureMeanings,signerStatuses,} from "../types/domain.ts";@@ -33,6 +33,16 @@ export const draftSignerSchema = z.object({name: nameSchema,email: emailSchema,signOrder: z.number().int().positive().optional(),+ // The step of the signing order this signer is in. Signers who share a+ // step sign at the same time; see signing-steps.ts. Left out for every+ // signer, they sign one after the other in the order of the list.+ signingStep: z+ .number()+ .int()+ .positive()+ .max(MAX_SIGNERS_CEILING)+ .nullable()+ .optional(),// Extra checks before signing. accessCode: a string sets it, null removes// it, and leaving it out keeps the code already saved.accessCode: z.string().trim().min(4).max(64).nullable().optional(),@@ -45,7 +55,9 @@ export const draftSignerSchema = z.object({export const signerListSchema = z.array(draftSignerSchema).min(1)- .max(MAX_SIGNERS_PER_ENVELOPE)+ // The install's own limit, which can be lower, is checked when the list+ // is saved (signer-limit.ts).+ .max(MAX_SIGNERS_CEILING).superRefine((signers, ctx) => {const emails = new Set<string>();const signOrders = new Set<number>();@@ -123,6 +135,7 @@ export const replaceSignersResponseSchema = z.object({requireEmailCode: z.boolean(),signatureMeaning: z.enum(signatureMeanings).nullable(),signOrder: z.number().int().positive(),+ signingStep: z.number().int().positive(),}),),updatedAt: unixTimestampSchema,diff --git a/src/lib/schemas/template.test.ts b/src/lib/schemas/template.test.tsindex 41f6b8c..5a6837e 100644--- a/src/lib/schemas/template.test.ts+++ b/src/lib/schemas/template.test.ts@@ -7,6 +7,7 @@ import {templateRolesSchema,useTemplateSchema,} from "./template.ts";+import { MAX_SIGNERS_CEILING } from "../types/domain.ts";test("a template needs a name, and its signers need different names", () => {assert.deepEqual(saveTemplateSchema.parse({ name: " Lease " }), {@@ -40,7 +41,7 @@ test("a template needs a name, and its signers need different names", () => {assert.equal(templateRolesSchema.safeParse([]).success, false);assert.equal(templateRolesSchema.safeParse(- Array.from({ length: 11 }, (_, index) => ({+ Array.from({ length: MAX_SIGNERS_CEILING + 1 }, (_, index) => ({id: String(index),name: `Signer ${String(index)}`,})),@@ -49,6 +50,18 @@ test("a template needs a name, and its signers need different names", () => {);});+test("a template can have as many roles as the ceiling allows", () => {+ assert.equal(+ templateRolesSchema.safeParse(+ Array.from({ length: MAX_SIGNERS_CEILING }, (_, index) => ({+ id: String(index),+ name: `Signer ${String(index)}`,+ })),+ ).success,+ true,+ );+});+test("using a template takes a title and one person for each signer", () => {const parsed = useTemplateSchema.parse({// Anything else about a signer is set on the draft afterwards.diff --git a/src/lib/schemas/template.ts b/src/lib/schemas/template.tsindex 8198d91..a66b632 100644--- a/src/lib/schemas/template.ts+++ b/src/lib/schemas/template.ts@@ -1,6 +1,6 @@import { z } from "zod";-import { MAX_SIGNERS_PER_ENVELOPE } from "../types/domain.ts";+import { MAX_SIGNERS_CEILING } from "../types/domain.ts";import {emailSchema,envelopeTitleSchema,@@ -23,13 +23,17 @@ export const duplicateRoleNameMessage =export const templateRoleSchema = z.object({id: idSchema,name: templateRoleNameSchema,+ // The step of the signing order the role is in; roles that share one+ // sign at the same time. Templates saved before steps existed have none,+ // and their roles sign one after the other.+ step: z.number().int().positive().max(MAX_SIGNERS_CEILING).optional(),});/** A template's roles, in the order their people will sign. */export const templateRolesSchema = z.array(templateRoleSchema).min(1)- .max(MAX_SIGNERS_PER_ENVELOPE)+ .max(MAX_SIGNERS_CEILING).superRefine((roles, ctx) => {const ids = new Set<string>();const names = new Set<string>();@@ -66,7 +70,7 @@ export const saveTemplateSchema = z.object({roleNames: z.array(templateRoleNameSchema).min(1)- .max(MAX_SIGNERS_PER_ENVELOPE)+ .max(MAX_SIGNERS_CEILING).optional(),});@@ -75,7 +79,7 @@ export const useTemplateSchema = z.object({signers: z.array(z.object({ email: emailSchema, name: nameSchema })).min(1)- .max(MAX_SIGNERS_PER_ENVELOPE)+ .max(MAX_SIGNERS_CEILING).superRefine((signers, ctx) => {const emails = new Set<string>();diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 4960dd5..5926c5a 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -10,6 +10,7 @@ import {import type { FieldRecord } from "../schemas/field.ts";import type { SignerRecord } from "../schemas/signer.ts";import { buildSignatureManifestation } from "../signature-meanings.ts";+import { hasSharedSigningStep, signingStepOf } from "../signing-steps.ts";import { describeSignerCorrectedEvent } from "./audit.ts";import { canonicalJson } from "../utils/canonical-json.ts";import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";@@ -1068,11 +1069,24 @@ function buildAuditLines(input: {gapAfter: 4,});+ // Each signer is numbered by their step of the signing order. With every+ // signer in a step of their own that is their place in the list; signers+ // who share a number were asked to sign at the same time, and the line+ // below says so.+ if (hasSharedSigningStep(input.signers)) {+ pushParagraph(+ "Signers with the same number were asked to sign at the same time. Each number started once everyone with the number before it had signed.",+ input.fonts.regular,+ bodyFontSize,+ );+ }+for (const signer of input.signers) {const actionLabel = getSignerCertificateActionLabel(input.envelope, signer);+ const step = signingStepOf(signer);const signerLabel = input.redactForRecipients- ? `${signer.signOrder}. ${signer.name} | ${actionLabel}`- : `${signer.signOrder}. ${signer.name} <${signer.email}> | ${actionLabel}`;+ ? `${step}. ${signer.name} | ${actionLabel}`+ : `${step}. ${signer.name} <${signer.email}> | ${actionLabel}`;pushParagraph(signerLabel, input.fonts.regular, bodyFontSize);diff --git a/src/lib/signer-limit.ts b/src/lib/signer-limit.tsnew file mode 100644index 0000000..f8fa1bd--- /dev/null+++ b/src/lib/signer-limit.ts@@ -0,0 +1,28 @@+import {+ DEFAULT_MAX_SIGNERS_PER_ENVELOPE,+ MAX_SIGNERS_CEILING,+} from "./types/domain.ts";+import { type EnvSource, readEnv } from "./utils/env.ts";++// How many signers one envelope may have on this install, up to+// MAX_SIGNERS_CEILING (the certificate runs onto as many pages as it+// needs). A value that is not a whole number in range is ignored, and the+// default applies, rather than stopping the app.++export function getMaxSignersPerEnvelope(env: EnvSource = process.env): number {+ const configured = readEnv(env, "MAX_SIGNERS_PER_ENVELOPE");++ if (!configured || !/^\d+$/.test(configured)) {+ return DEFAULT_MAX_SIGNERS_PER_ENVELOPE;+ }++ const value = Number(configured);++ return value >= 1 && value <= MAX_SIGNERS_CEILING+ ? value+ : DEFAULT_MAX_SIGNERS_PER_ENVELOPE;+}++export function describeSignerLimit(limit: number): string {+ return `An envelope can have at most ${String(limit)} ${limit === 1 ? "signer" : "signers"}.`;+}diff --git a/src/lib/signing-steps.test.ts b/src/lib/signing-steps.test.tsnew file mode 100644index 0000000..9baf5b6--- /dev/null+++ b/src/lib/signing-steps.test.ts@@ -0,0 +1,223 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import { getMaxSignersPerEnvelope } from "./signer-limit.ts";+import {+ firstStepSigners,+ hasSharedSigningStep,+ isEarlierStep,+ joinNames,+ moveListedSigner,+ normalizeSigningSteps,+ removeListedSigner,+ routeAfterSignatures,+ signingStepOf,+ SigningStepError,+} from "./signing-steps.ts";+import {+ DEFAULT_MAX_SIGNERS_PER_ENVELOPE,+ MAX_SIGNERS_CEILING,+} from "./types/domain.ts";++test("with no steps given, signers sign one after the other", () => {+ assert.deepEqual(+ normalizeSigningSteps([undefined, undefined, undefined]),+ [1, 2, 3],+ );+});++test("given steps are renumbered without gaps", () => {+ assert.deepEqual(normalizeSigningSteps([1, 1, 4, 4, 7]), [1, 1, 2, 2, 3]);+ assert.deepEqual(normalizeSigningSteps([3, 3]), [1, 1]);+});++test("steps cannot go down the list, start below 1, or be given for only some", () => {+ assert.throws(() => normalizeSigningSteps([2, 1]), SigningStepError);+ assert.throws(() => normalizeSigningSteps([0, 1]), SigningStepError);+ assert.throws(() => normalizeSigningSteps([1, undefined]), SigningStepError);+ assert.throws(() => normalizeSigningSteps([1.5]), SigningStepError);+});++test("a signer without a stored step is in the step of its place", () => {+ assert.equal(signingStepOf({ signOrder: 3 }), 3);+ assert.equal(signingStepOf({ signOrder: 3, signingStep: null }), 3);+ assert.equal(signingStepOf({ signOrder: 3, signingStep: 1 }), 1);+});++test("shared steps are found", () => {+ assert.equal(+ hasSharedSigningStep([+ { signOrder: 1, signingStep: 1 },+ { signOrder: 2, signingStep: 2 },+ ]),+ false,+ );+ assert.equal(+ hasSharedSigningStep([+ { signOrder: 1, signingStep: 1 },+ { signOrder: 2, signingStep: 1 },+ ]),+ true,+ );+});++test("the first step is everyone who shares the lowest step", () => {+ const signers = [+ { id: "c", signOrder: 3, signingStep: 2 },+ { id: "b", signOrder: 2, signingStep: 1 },+ { id: "a", signOrder: 1, signingStep: 1 },+ ];++ assert.deepEqual(+ firstStepSigners(signers).map((signer) => signer.id),+ ["a", "b"],+ );+});++test("the next step starts only when nobody in the current one is waiting", () => {+ const route = (statuses: string[]) =>+ routeAfterSignatures([+ { id: "a", signOrder: 1, signingStep: 1, status: statuses[0] },+ { id: "b", signOrder: 2, signingStep: 1, status: statuses[1] },+ { id: "c", signOrder: 3, signingStep: 2, status: statuses[2] },+ { id: "d", signOrder: 4, signingStep: 2, status: statuses[3] },+ { id: "e", signOrder: 5, signingStep: 3, status: statuses[4] },+ ] as Parameters<typeof routeAfterSignatures>[0]);+ const ids = (signers: { id?: string }[]) =>+ signers.map((signer) => signer.id);++ let next = route(["signed", "notified", "pending", "pending", "pending"]);+ assert.deepEqual(ids(next.waiting), ["b"]);+ assert.deepEqual(ids(next.next), []);++ next = route(["signed", "signed", "pending", "pending", "pending"]);+ assert.deepEqual(ids(next.waiting), []);+ assert.deepEqual(ids(next.next), ["c", "d"]);++ next = route(["signed", "signed", "signed", "signed", "signed"]);+ assert.deepEqual(ids(next.waiting), []);+ assert.deepEqual(ids(next.next), []);+});++test("earlier steps are told apart from the same step", () => {+ assert.equal(+ isEarlierStep(+ { signOrder: 1, signingStep: 1 },+ { signOrder: 2, signingStep: 1 },+ ),+ false,+ );+ assert.equal(+ isEarlierStep(+ { signOrder: 1, signingStep: 1 },+ { signOrder: 3, signingStep: 2 },+ ),+ true,+ );+});++test("names are joined for a sentence", () => {+ assert.equal(joinNames([]), "");+ assert.equal(joinNames(["Alex"]), "Alex");+ assert.equal(joinNames(["Alex", "Sam"]), "Alex and Sam");+ assert.equal(joinNames(["Alex", "Sam", "Kim"]), "Alex, Sam and Kim");+});++test("the signer limit comes from the environment, within bounds", () => {+ assert.equal(getMaxSignersPerEnvelope({}), DEFAULT_MAX_SIGNERS_PER_ENVELOPE);+ assert.equal(+ getMaxSignersPerEnvelope({ MAX_SIGNERS_PER_ENVELOPE: "40" }),+ 40,+ );+ assert.equal(+ getMaxSignersPerEnvelope({+ MAX_SIGNERS_PER_ENVELOPE: String(MAX_SIGNERS_CEILING + 1),+ }),+ DEFAULT_MAX_SIGNERS_PER_ENVELOPE,+ );+ assert.equal(+ getMaxSignersPerEnvelope({ MAX_SIGNERS_PER_ENVELOPE: "0" }),+ DEFAULT_MAX_SIGNERS_PER_ENVELOPE,+ );+ assert.equal(+ getMaxSignersPerEnvelope({ MAX_SIGNERS_PER_ENVELOPE: "ten" }),+ DEFAULT_MAX_SIGNERS_PER_ENVELOPE,+ );+});++/** A list on the signers page, from each signer's step: "A1 B2 C2". */+function listed(spec: string) {+ const entries = spec.split(" ").map((entry) => ({+ name: entry[0]!,+ step: Number(entry.slice(1)),+ }));++ return entries.map(({ name, step }, index) => ({+ name,+ withPrevious: index > 0 && entries[index - 1]!.step === step,+ }));+}++/** The same list written back as "A1 B2 C2", steps numbered from 1. */+function described(+ signers: readonly { name: string; withPrevious: boolean }[],+) {+ let step = 0;++ return signers+ .map((signer, index) => {+ step += index > 0 && signer.withPrevious ? 0 : 1;+ return `${signer.name}${String(step)}`;+ })+ .join(" ");+}++test("removing a signer leaves everyone else in their step", () => {+ // B started step 2; C, who signs with B, does not move up to A's step.+ assert.equal(described(removeListedSigner(listed("A1 B2 C2"), 1)), "A1 C2");+ assert.equal(+ described(removeListedSigner(listed("A1 B2 C2 D2"), 1)),+ "A1 C2 D2",+ );+ assert.equal(described(removeListedSigner(listed("A1 B1 C2"), 0)), "B1 C2");+ assert.equal(described(removeListedSigner(listed("A1 B2 C3"), 1)), "A1 C2");+ assert.equal(+ described(removeListedSigner(listed("A1 B1 C2 D2"), 3)),+ "A1 B1 C2",+ );+});++test("moving a signer leaves everyone else in their step", () => {+ // Changing places within a step keeps both in it.+ assert.equal(+ described(moveListedSigner(listed("A1 B2 C2"), 2, "earlier")),+ "A1 C2 B2",+ );+ assert.equal(+ described(moveListedSigner(listed("A1 B1 C2"), 0, "later")),+ "B1 A1 C2",+ );+ // Out of a step: a step of their own, and the one left behind keeps theirs.+ assert.equal(+ described(moveListedSigner(listed("A1 B2 C2"), 1, "earlier")),+ "B1 A2 C3",+ );+ assert.equal(+ described(moveListedSigner(listed("A1 B1 C2"), 1, "later")),+ "A1 C2 B3",+ );+ assert.equal(+ described(moveListedSigner(listed("A1 B2 C3"), 2, "earlier")),+ "A1 C2 B3",+ );+ // Into the middle of a step: they join it, which stays together.+ assert.equal(+ described(moveListedSigner(listed("A1 B2 C2 D3"), 3, "earlier")),+ "A1 B2 D2 C2",+ );+ // Past either end: nothing moves.+ const list = listed("A1 B2");++ assert.equal(moveListedSigner(list, 0, "earlier"), list);+ assert.equal(moveListedSigner(list, 1, "later"), list);+});diff --git a/src/lib/signing-steps.ts b/src/lib/signing-steps.tsnew file mode 100644index 0000000..a6b12c8--- /dev/null+++ b/src/lib/signing-steps.ts@@ -0,0 +1,260 @@+import type { SignerStatus } from "./types/domain.ts";++// The signing order is a list of steps. Each signer is in one step, and the+// signers who share a step sign at the same time: they are all invited when+// the step starts, in any order among themselves. The next step starts+// once every signer of the step before has signed. A list where every+// signer has a step of their own is the plain one-after-the-other order.+//+// sign_order is a signer's place in the list and stays unique; the step is+// signers.signing_step. A row without one (written before steps existed,+// or by hand) is in the step of its place in the list.++export type SteppedSigner = {+ /** The place in the list, from 1. Optional only because drafts' types are. */+ signOrder?: number;+ signingStep?: number | null;+};++export type SteppedSignerWithStatus = SteppedSigner & {+ id?: string;+ status: SignerStatus;+};++export class SigningStepError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "SigningStepError";+ }+}++export function signingStepOf(signer: SteppedSigner): number {+ return typeof signer.signingStep === "number" && signer.signingStep > 0+ ? signer.signingStep+ : (signer.signOrder ?? 0);+}++/**+ * The steps to store for a list of signers, given in the list's order. With+ * no steps given, each signer gets their own, one after the other. Given+ * steps must not go down the list, and are renumbered 1, 2, 3 without gaps,+ * so "1, 1, 4" is stored as "1, 1, 2".+ */+export function normalizeSigningSteps(+ requested: readonly (number | null | undefined)[],+): number[] {+ const given = requested.filter(+ (step): step is number => typeof step === "number",+ );++ if (given.length === 0) {+ return requested.map((_, index) => index + 1);+ }++ if (given.length !== requested.length) {+ throw new SigningStepError(+ "Give every signer a step in the signing order, or none of them.",+ );+ }++ const steps: number[] = [];+ let previous: number | null = null;+ let current = 0;++ for (const step of given) {+ if (!Number.isInteger(step) || step < 1) {+ throw new SigningStepError("Steps in the signing order start at 1.");+ }++ if (previous !== null && step < previous) {+ throw new SigningStepError(+ "List the signers in signing order: a later step cannot come before an earlier one.",+ );+ }++ if (step !== previous) {+ current += 1;+ previous = step;+ }++ steps.push(current);+ }++ return steps;+}++/** True when at least two signers sign at the same time. */+export function hasSharedSigningStep(+ signers: readonly SteppedSigner[],+): boolean {+ const seen = new Set<number>();++ for (const signer of signers) {+ const step = signingStepOf(signer);++ if (seen.has(step)) {+ return true;+ }++ seen.add(step);+ }++ return false;+}++/** The signers of the first step, in list order. */+export function firstStepSigners<T extends SteppedSigner>(+ signers: readonly T[],+): T[] {+ if (signers.length === 0) {+ return [];+ }++ const first = Math.min(...signers.map(signingStepOf));++ return sortByPlace(+ signers.filter((signer) => signingStepOf(signer) === first),+ );+}++/**+ * What happens to the order once the signers marked signed have signed:+ * who is still waiting in the current step, and, when nobody is, who is+ * invited next. Nobody waiting and nobody next means everyone has signed.+ */+export function routeAfterSignatures<T extends SteppedSignerWithStatus>(+ signers: readonly T[],+): { next: T[]; waiting: T[] } {+ const waiting = sortByPlace(+ signers.filter((signer) => signer.status === "notified"),+ );++ if (waiting.length > 0) {+ return { next: [], waiting };+ }++ const pending = signers.filter((signer) => signer.status === "pending");++ return { next: firstStepSigners(pending), waiting: [] };+}++function sortByPlace<T extends SteppedSigner>(signers: readonly T[]): T[] {+ return [...signers].sort(+ (left, right) => (left.signOrder ?? 0) - (right.signOrder ?? 0),+ );+}++/**+ * Every signer whose step comes before this one's. Their fields are already+ * filled in when this signer's turn starts. Signers of the same step may or+ * may not have signed yet.+ */+export function isEarlierStep(+ signer: SteppedSigner,+ than: SteppedSigner,+): boolean {+ return signingStepOf(signer) < signingStepOf(than);+}++/** "Alex", "Alex and Sam", "Alex, Sam and Kim". */+export function joinNames(names: readonly string[]): string {+ if (names.length <= 1) {+ return names[0] ?? "";+ }++ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;+}++/**+ * On the signers page each signer after the first either signs at the same+ * time as the one above (`withPrevious`) or starts the next step.+ */+export type ListedSigner = { withPrevious: boolean };++/** Each listed signer's step, from 1. */+function listedSteps(signers: readonly ListedSigner[]): number[] {+ const steps: number[] = [];++ for (const [index, signer] of signers.entries()) {+ const previous = steps[index - 1];++ steps.push(+ previous === undefined+ ? 1+ : signer.withPrevious+ ? previous+ : previous + 1,+ );+ }++ return steps;+}++/** The signers, each with the step given for them in `steps`. */+function inSteps<T extends ListedSigner>(+ signers: readonly T[],+ steps: readonly number[],+): T[] {+ return signers.map((signer, index) => {+ const withPrevious = index > 0 && steps[index] === steps[index - 1];++ return signer.withPrevious === withPrevious+ ? signer+ : { ...signer, withPrevious };+ });+}++/**+ * The list without the signer at `index`. Everyone else stays in their+ * step: the signer after one who started a step does not join the step+ * before.+ */+export function removeListedSigner<T extends ListedSigner>(+ signers: readonly T[],+ index: number,+): T[] {+ const keep = (_: unknown, at: number) => at !== index;++ return inSteps(signers.filter(keep), listedSteps(signers).filter(keep));+}++/**+ * The list with the signer at `index` moved one place earlier or later.+ * Everyone else stays in their step. The moved signer stays in theirs when+ * changing places with someone of the same step, joins a step they land in+ * the middle of, and otherwise has a step of their own.+ */+export function moveListedSigner<T extends ListedSigner>(+ signers: T[],+ index: number,+ direction: "earlier" | "later",+): T[] {+ const target = direction === "earlier" ? index - 1 : index + 1;++ if (index < 0 || target < 0 || target >= signers.length) {+ return signers;+ }++ const steps = listedSteps(signers);+ const step = steps[index]!;+ const moved = [...signers];+ const movedSteps = [...steps];+ const [signer] = moved.splice(index, 1);++ movedSteps.splice(index, 1);++ const before = movedSteps[target - 1];+ const after = movedSteps[target];+ // 0 is no step's number, so it is a step of their own.+ const newStep =+ steps[target] === step+ ? step+ : before !== undefined && before === after+ ? before+ : 0;++ moved.splice(target, 0, signer!);+ movedSteps.splice(target, 0, newStep);++ return inSteps(moved, movedSteps);+}diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex f950d5e..0c4e6e1 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -74,10 +74,7 @@ import {storeRecipientEnvelopeCertificatePdf,} from "./services/pdf-finalize.ts";import { buildSigningInvitationEmail } from "./services/signing-invitation-email.ts";-import {- issueSigningLink,- type IssuedSigningLink,-} from "./services/signing-links.ts";+import { issueSigningLink } from "./services/signing-links.ts";import { signingProviderById } from "./services/signing-providers.ts";import {buildEnvelopeCertificateKey,@@ -118,6 +115,11 @@ import {type SignerCheckMethod,type SignerCheckState,} from "./signer-checks.ts";+import {+ isEarlierStep,+ routeAfterSignatures,+ signingStepOf,+} from "./signing-steps.ts";export type SigningRequestMeta = {ipAddress?: string | null;@@ -170,6 +172,7 @@ type SigningSignerRow = {lastNudgedAt: number | null;name: string;signOrder: number;+ signingStep: number | null;signatureMeaning:"approval" | "authorship" | "responsibility" | "review" | null;signedAt: number | null;@@ -592,6 +595,7 @@ async function listSignerRows(name,email,sign_order AS "signOrder",+ signing_step AS "signingStep",status,signing_token_hash AS "signingTokenHash",signing_token_expires_at AS "signingTokenExpiresAt",@@ -646,6 +650,7 @@ async function getSignerRowBySigningTokenHash(name,email,sign_order AS "signOrder",+ signing_step AS "signingStep",status,signing_token_hash AS "signingTokenHash",signing_token_expires_at AS "signingTokenExpiresAt",@@ -1021,6 +1026,7 @@ function buildSignedAuditEvent(input: {signerId: input.signer.id,signerName: input.signer.name,signerOrder: input.signer.signOrder,+ signingStep: signingStepOf(input.signer),authMethods: [...input.authMethods],signatureMethods: [...input.signatureMethods],timezoneOffsetMinutes: input.timezoneOffsetMinutes,@@ -1054,6 +1060,7 @@ function buildDeclinedAuditEvent(input: {signerId: input.signer.id,signerName: input.signer.name,signerOrder: input.signer.signOrder,+ signingStep: signingStepOf(input.signer),},userAgent: input.requestMeta.userAgent ?? null,};@@ -1861,10 +1868,9 @@ export async function getSigningPayloadForToken(const signerNamesById = new Map(context.signers.map((signer) => [signer.id, signer.name] as const),);- const signerOrdersById = new Map(- context.signers.map((signer) => [signer.id, signer.signOrder] as const),+ const signersById = new Map(+ context.signers.map((signer) => [signer.id, signer] as const),);- const currentSignerOrder = context.signer.signOrder ?? 0;const currentSignerFields = context.fields.filter((field) => field.signerId === context.signer.id)@@ -1887,11 +1893,14 @@ export async function getSigningPayloadForToken(const visibleFields = await Promise.all(context.fields.filter((field) => {- const signerOrder = signerOrdersById.get(field.signerId);+ const fieldSigner = signersById.get(field.signerId);+ // What the signers of earlier steps entered. Someone signing at the+ // same time may have signed already, but what they entered is not+ // shown: it was not on the page when this signer's turn began.return (- typeof signerOrder === "number" &&- signerOrder < currentSignerOrder &&+ fieldSigner !== undefined &&+ isEarlierStep(fieldSigner, context.signer) &&typeof field.submittedAt === "number");})@@ -2394,7 +2403,55 @@ function buildSignerSubmission(};}+/**+ * Raised inside a signature's or a decline's transaction when the rows it+ * holds locked show that the signing order moved on after the submission+ * was prepared: another signer of the same step signed at the same moment.+ * The transaction rolls back and the whole submission starts again from+ * what the database now says.+ */+class SigningRouteChangedError extends Error {+ constructor() {+ super("Another signer of this step signed at the same moment.");+ this.name = "SigningRouteChangedError";+ }+}++/**+ * Enough for every signer of a step submitting at the same moment: each+ * attempt that loses waits for one that wins, and there are no more than+ * MAX_SIGNERS_CEILING signers.+ */+const MAX_ROUTE_ATTEMPTS = 5;++async function retryWhileRouteChanges<T>(attempt: () => Promise<T>) {+ for (let tries = 1; ; tries += 1) {+ try {+ return await attempt();+ } catch (error) {+ if (!(error instanceof SigningRouteChangedError)) {+ throw error;+ }++ if (tries >= MAX_ROUTE_ATTEMPTS) {+ throw new SigningMutationError(+ "Other signers were signing at the same moment. Try again.",+ 409,+ );+ }+ }+ }+}+export async function submitSigningForToken(+ token: string,+ input: unknown,+ options: SubmitSigningOptions = {},+): Promise<SigningSubmitResponse> {+ return retryWhileRouteChanges(() => submitSigningOnce(token, input, options));+}++async function submitSigningOnce(token: string,input: unknown,{@@ -2467,37 +2524,25 @@ export async function submitSigningForToken(let signingStatePersisted = false;try {- const currentSignerIndex = context.signers.findIndex(- (signer) => signer.id === context.signer.id,+ // Whether this is the last signature, as far as can be told before the+ // envelope is locked. Everyone else has signed: this submission makes+ // the final files. Anyone else still to sign, in this step or a later+ // one: it records the signature and moves the order on if this step is+ // done. Signers of the same step can submit at the same moment, so the+ // second of them may find, once it holds the envelope, that the first+ // has signed meanwhile and it is the last after all. It then starts+ // again (SigningRouteChangedError), and is the last signature this time.+ const isLastSignature = context.signers.every(+ (signer) => signer.id === currentSignerId || signer.status === "signed",);- const nextSigner =- currentSignerIndex >= 0- ? context.signers[currentSignerIndex + 1]- : undefined;- let nextSignerLink: IssuedSigningLink | undefined;- let nextSignerDelivery:- { email: string; id: string; name: string } | undefined;- const nextSignerId = nextSigner?.id;-- if (nextSigner) {- if (nextSigner.status !== "pending") {- throw new SigningMutationError(- "Envelope routing is out of sync for the next signer.",- 409,- );- }-- if (!nextSignerId) {- throw new SigningMutationError(- "Envelope routing is out of sync for the next signer.",- 500,- );- }-- // Only the link itself. When it ends is settled further down, from- // the deadline as it stands once the envelope is locked.- nextSignerLink = await issueSigningLink({ issuedAt: routedAt });- }+ // Each signer of the next step gets a link of their own. When it ends+ // is settled once the envelope is locked, from the deadline then.+ let nextSignerDeliveries: {+ email: string;+ id: string;+ name: string;+ url: string;+ }[] = [];for (const upload of drawnSignatureUploads) {await storageService.putObject({@@ -2535,14 +2580,7 @@ export async function submitSigningForToken(timezoneOffsetMinutes: parsedInput.clientTimezoneOffsetMinutes,});- if (nextSigner && nextSignerLink) {- if (!nextSignerId) {- throw new SigningMutationError(- "Envelope routing is out of sync for the next signer.",- 500,- );- }-+ if (!isLastSignature) {// The deadline the next signer is given. The sender can move it while// this signer submits, and moving it only reaches the signer whose// turn it is then. So it is read here, where this update holds the@@ -2653,48 +2691,73 @@ export async function submitSigningForToken();}- const activatedNextSigner = await queryOne<{- email: string;- name: string;- }>(- tx,- `- UPDATE signers- SET- status = 'notified',- signing_token_hash = $1,- signing_token_expires_at = $2,- turn_started_at = $3,- last_notified_at = $4,- updated_at = $5- WHERE id = $6- AND envelope_id = $7- AND status = 'pending'- RETURNING name, email- `,- [- nextSignerLink.tokenHash,- nextSignerLinkExpiresAt(lockedEnvelope.expiresAt, routedAt),- routedAt,- routedAt,- routedAt,- nextSignerId,- context.envelope.id,- ],+ // Who is still to sign, read with this signature in place and while+ // the envelope's row is held. Every other signature, decline and+ // void takes that row first, so nothing here can change until this+ // transaction ends, and of two signers of one step who submit at+ // the same moment exactly one finds the step finished.+ const route = routeAfterSignatures(+ (await listSignerRows(context.envelope.id, tx)).map(mapSignerRow),);- if (!activatedNextSigner) {- throw new SigningMutationError(- "Unable to activate the next signer for this envelope.",- 500,+ if (route.waiting.length === 0 && route.next.length === 0) {+ // Everyone else signed while this was being prepared: this is the+ // last signature, and the envelope's final files have to be made.+ throw new SigningRouteChangedError();+ }++ const deliveries: typeof nextSignerDeliveries = [];++ for (const nextSigner of route.next) {+ // Each signer of the next step gets a link of their own.+ const link = await issueSigningLink({ issuedAt: routedAt });+ const activatedNextSigner = await queryOne<{+ email: string;+ name: string;+ }>(+ tx,+ `+ UPDATE signers+ SET+ status = 'notified',+ signing_token_hash = $1,+ signing_token_expires_at = $2,+ turn_started_at = $3,+ last_notified_at = $4,+ updated_at = $5+ WHERE id = $6+ AND envelope_id = $7+ AND role = 'signer'+ AND status = 'pending'+ RETURNING name, email+ `,+ [+ link.tokenHash,+ nextSignerLinkExpiresAt(lockedEnvelope.expiresAt, routedAt),+ routedAt,+ routedAt,+ routedAt,+ nextSigner.id,+ context.envelope.id,+ ],);++ if (!activatedNextSigner || !nextSigner.id) {+ throw new SigningMutationError(+ "Unable to activate the next signer for this envelope.",+ 500,+ );+ }++ deliveries.push({+ email: activatedNextSigner.email,+ id: nextSigner.id,+ name: activatedNextSigner.name,+ url: link.url,+ });}- nextSignerDelivery = {- email: activatedNextSigner.email,- id: nextSignerId,- name: activatedNextSigner.name,- };+ nextSignerDeliveries = deliveries;await recordAuditEvent({@@ -2714,41 +2777,37 @@ export async function submitSigningForToken(signingStatePersisted = true;await deleteReplacedRevision(replacedRevisionKey, storageService);- if (!nextSignerDelivery) {- throw new SigningMutationError(- "Unable to activate the next signer for this envelope.",- 500,- );- }-- try {- const delivery = await emailService.send(- buildSigningInvitationEmail({- branding: await getBranding(),- envelopeTitle: context.envelope.title,- expiresAt: nextSignerDeadline,- senderName: normalizeSenderName(context.sender),- signerEmail: nextSignerDelivery.email,- signerName: nextSignerDelivery.name,- signingUrl: nextSignerLink.url,- }),- );+ // Nobody to invite while others in this step are still signing.+ for (const nextSignerDelivery of nextSignerDeliveries) {+ try {+ const delivery = await emailService.send(+ buildSigningInvitationEmail({+ branding: await getBranding(),+ envelopeTitle: context.envelope.title,+ expiresAt: nextSignerDeadline,+ senderName: normalizeSenderName(context.sender),+ signerEmail: nextSignerDelivery.email,+ signerName: nextSignerDelivery.name,+ signingUrl: nextSignerDelivery.url,+ }),+ );- await recordEmailSent(- {- envelopeId: context.envelope.id,- messageId: delivery.messageId,- recipient: nextSignerDelivery.email,- signerId: nextSignerDelivery.id,- template: "signing_invitation",- },- database,- );- } catch (error) {- console.error(- `Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSignerDelivery.email}:`,- error,- );+ await recordEmailSent(+ {+ envelopeId: context.envelope.id,+ messageId: delivery.messageId,+ recipient: nextSignerDelivery.email,+ signerId: nextSignerDelivery.id,+ template: "signing_invitation",+ },+ database,+ );+ } catch (error) {+ console.error(+ `Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSignerDelivery.email}:`,+ error,+ );+ }}return signingSubmitResponseSchema.parse({@@ -2820,6 +2879,27 @@ export async function submitSigningForToken(tokenHash: presentedTokenHash,});+ // The final files are made from the signers, fields and audit trail+ // read before the lock, which hold everyone else's signature: a+ // signature cannot be taken back. Checked again here all the same,+ // so the envelope is never finished while anyone is still to sign.+ const stillToSign = await queryOne<{ id: string }>(+ tx,+ `+ SELECT id FROM signers+ WHERE envelope_id = $1+ AND role = 'signer'+ AND id <> $2+ AND status <> 'signed'+ LIMIT 1+ `,+ [context.envelope.id, currentSignerId],+ );++ if (stillToSign) {+ throw new SigningRouteChangedError();+ }+// Made while the envelope is locked: the files have fixed keys, and// a second submission at the same time waits, then stops above.finalArtifactsStored = true;@@ -3110,6 +3190,16 @@ export async function prepareSignerSubmission(}export async function declineSigningForToken(+ token: string,+ input: unknown,+ options: SubmitSigningOptions = {},+): Promise<SigningDeclineResponse> {+ return retryWhileRouteChanges(() =>+ declineSigningOnce(token, input, options),+ );+}++async function declineSigningOnce(token: string,input: unknown,{@@ -3227,6 +3317,28 @@ export async function declineSigningForToken();}+ // The same for where everyone else stands. A signer of the same step+ // who signed a moment ago would otherwise be shown on the certificates+ // as still waiting, without their signature in the audit trail they+ // show. Started again, the decline reads them as they are now.+ const statusesNow = await tx.query<{ id: string; status: string }>(+ `+ SELECT id, status FROM signers+ WHERE envelope_id = $1 AND role = 'signer' AND id <> $2+ `,+ [context.envelope.id, currentSignerId],+ );++ if (+ statusesNow.rows.some(+ (row) =>+ context.signers.find((signer) => signer.id === row.id)?.status !==+ row.status,+ )+ ) {+ throw new SigningRouteChangedError();+ }+// Made while the envelope is locked: the certificates have fixed keys,// and a void, the last signature or a second decline at the same time// waits, then stops above without touching the files this one saved.diff --git a/src/lib/templates.ts b/src/lib/templates.tsindex 7c2d363..c37cfe1 100644--- a/src/lib/templates.ts+++ b/src/lib/templates.ts@@ -26,6 +26,7 @@ import {type TemplateRole,} from "./schemas/template.ts";import { buildTemplatePdfKey } from "./services/storage-keys.ts";+import { normalizeSigningSteps } from "./signing-steps.ts";import {createStorageService,StorageObjectNotFoundError,@@ -290,8 +291,15 @@ export async function saveEnvelopeAsTemplate();}+ // Each role keeps its signer's step, so roles that signed at the same+ // time still do when the template is used.+ const steps = normalizeSigningSteps(signers.map((signer) => signer.step));const roles = templateRolesSchema.parse(- roleNames.map((name) => ({ id: randomUUID(), name })),+ roleNames.map((name, index) => ({+ id: randomUUID(),+ name,+ step: steps[index],+ })),);const roleIdBySignerId = new Map(signers.map((signer, index) => [signer.id, roles[index]!.id] as const),@@ -470,10 +478,20 @@ export async function createDraftFromTemplate(const envelopeId = draft.envelope.id;try {+ const roleSteps = roles.data.every((role) => role.step !== undefined)+ ? roles.data.map((role) => role.step)+ : null;const saved = await replaceDraftEnvelopeSigners(userId,envelopeId,- { signers: parsedInput.signers },+ {+ // The roles' steps, when the template has them. One saved before+ // steps existed has none, and its people sign one after the other.+ signers: parsedInput.signers.map((signer, index) => ({+ ...signer,+ ...(roleSteps ? { signingStep: roleSteps[index] } : {}),+ })),+ },database,);const signerIdByOrder = new Map(diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.tsindex be652d9..1403641 100644--- a/src/lib/types/domain.ts+++ b/src/lib/types/domain.ts@@ -1,4 +1,12 @@-export const MAX_SIGNERS_PER_ENVELOPE = 10;+/**+ * The most signers an install can allow on one envelope. The number an+ * install allows is set with MAX_SIGNERS_PER_ENVELOPE, up to this, and is+ * DEFAULT_MAX_SIGNERS_PER_ENVELOPE when it is not set (see signer-limit.ts).+ * Copy recipients are stored after the signers, from 501 on, so this has to+ * stay well under that.+ */+export const MAX_SIGNERS_CEILING = 100;+export const DEFAULT_MAX_SIGNERS_PER_ENVELOPE = 25;/** 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;