Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add approvers to the signing order
Matthew Jackson0d82d49c75c3
diff --git a/db/migrations/20261121110000_approvers.sql b/db/migrations/20261121110000_approvers.sqlnew file mode 100644index 0000000..61e111c--- /dev/null+++ b/db/migrations/20261121110000_approvers.sql@@ -0,0 +1,101 @@+-- Approvers.+--+-- * signers.role 'approver': someone in the signing order who reviews the+-- document and approves or rejects it. An approver has no fields, places+-- no signature, and is not stamped into the signed PDF. They take part in+-- the steps of the signing order like a signer: the next step starts once+-- every signer and approver of the step before is done.+--+-- An approval is stored as the row's turn being done, status 'signed',+-- with signed_at the time of the approval, so that every query that moves+-- the order on, counts who is still to act or locks a turn treats an+-- approver exactly as a signer. A rejection is stored as 'declined', the+-- same as a decline, and ends the envelope. What people are shown, the+-- audit trail and the certificate tell the two apart by role and by the+-- events below.+--+-- * audit_events: 'approved' and 'rejected' for an approver's decision.+--+-- A copy of the app from before this migration still runs on this database+-- as long as no approver has been added: it reads signers by role 'signer'+-- and would leave an approver out of the signing order. Roll back past this+-- migration only with no approvers on envelopes out for signature.++alter table public.signers+ drop constraint if exists signers_role_check;++alter table public.signers+ add constraint signers_role_check+ check (role in ('signer', 'approver', 'cc'));++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 in ('signer', 'approver') or signing_step is null);++alter table public.signers+ drop constraint if exists signers_copy_recipient_never_signs;++alter table public.signers+ add constraint signers_copy_recipient_never_signs+ check (+ role in ('signer', 'approver')+ or (status = 'pending' and signing_token_hash is null)+ );++-- An approver places no fields. Checked when fields are saved and when the+-- envelope is sent; this keeps a row written by hand from slipping through.+create or replace function public.signudoc_fields_not_for_approvers()+returns trigger+language plpgsql+as $$+begin+ if exists (+ select 1 from public.signers s+ where s.id = new.signer_id+ and s.envelope_id = new.envelope_id+ and s.role = 'approver'+ ) then+ raise exception 'An approver has no fields.'+ using errcode = 'check_violation';+ end if;++ return new;+end;+$$;++drop trigger if exists fields_not_for_approvers on public.fields;++create trigger fields_not_for_approvers+ before insert or update of signer_id on public.fields+ for each row execute function public.signudoc_fields_not_for_approvers();++alter table public.audit_events+ drop constraint if exists audit_events_event_check;++alter table public.audit_events+ add constraint audit_events_event_check+ check (event in (+ 'created',+ 'sent',+ 'viewed',+ 'consented',+ 'verified',+ 'verification_failed',+ 'signed',+ 'declined',+ 'reminded_manual',+ 'email_sent',+ 'completed',+ 'voided',+ 'deadline_changed',+ 'expired',+ 'reminded_auto',+ 'reauthentication_failed',+ 'copied',+ 'signer_corrected',+ 'approved',+ 'rejected'+ ));diff --git a/docs/api.md b/docs/api.mdindex a046e37..66b8b4e 100644--- a/docs/api.md+++ b/docs/api.md@@ -236,6 +236,7 @@ Every endpoint that returns an envelope returns the same object:"email": "[email protected]","order": 1,"step": 1,+ "role": "signer","status": "notified","viewedAt": null,"signedAt": null,@@ -254,7 +255,10 @@ Every endpoint that returns an envelope returns the same object:- A signer's `status` is `pending` (not their turn yet), `notified` (theirturn, invited), `signed` or `declined`. `step` is their step of the signingorder: signers who share one sign at the same time. `viewedAt` is when they- first opened it.+ first opened it. `role` is `signer`, or `approver` for someone who reviews+ the document and approves or rejects it instead of signing (see+ [Signing order](signing-order.md)): an approval shows as `signed` and a+ rejection as `declined`.- `delivery` is `email` (signers are invited by email) or `embedded` (yourapp shows the signing page, see [Embedded signing](#embedded-signing)).- `files` gives the paths to download once there is something to download:@@ -309,9 +313,9 @@ can ignore the ones that are not its own. An install can have 10 endpoints.| -------------------- | -------------------------------------------------------------------------------------------- || `envelope.sent` | The envelope was sent. `data.signer` is the first signer, now invited. || `signer.viewed` | A signer opened it for the first time. |-| `signer.signed` | A signer signed. `data.signer` is who. |+| `signer.signed` | A signer signed, or an approver approved. `data.signer` is who. || `envelope.completed` | Everyone signed. The signed PDF and the certificate are ready to download when this arrives. |-| `envelope.declined` | A signer declined. `data.reason` is the reason they gave, if any. |+| `envelope.declined` | A signer declined, or an approver rejected. `data.reason` is the reason they gave, if any. || `envelope.voided` | The sender voided it. `data.reason` is why, if given. || `envelope.expired` | Its deadline passed before everyone signed. |@@ -528,8 +532,8 @@ window.addEventListener("message", (event) => {if (event.origin !== "https://sign.example.com") return;switch (event.data.type) {- case "signudoc:signed": // { envelopeId, signerId }- case "signudoc:declined": // { envelopeId, signerId }+ case "signudoc:signed": // { envelopeId, signerId }, also for an approval+ case "signudoc:declined": // { envelopeId, signerId }, also for a rejectioncase "signudoc:error": // { state }: "expired", "already-signed", "completed", "voided", …}});diff --git a/docs/signing-order.md b/docs/signing-order.mdindex 0715db0..6a235e7 100644--- a/docs/signing-order.md+++ b/docs/signing-order.md@@ -1,4 +1,4 @@-# Signing order+# Signing order and approversThe signing order is a list of steps. Each signer is in one step.@@ -45,6 +45,41 @@ A decline or a void that finds a signer of the step signed in the meantime start- **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.+## Approvers++Anyone in the signing order can be an **approver** instead of a signer. On the signers page, each person has **Signs the document** or **Approves or rejects it (no fields)**.++- An approver **reviews the document and approves or rejects it**. They have no fields, place no signature, and nothing of theirs is stamped on the signed PDF. They see what the steps before them filled in, as a signer does.+- Approvers are **in the steps like signers**. The next step starts once every signer and approver of the step before is done. So a salesperson can have their manager approve first, and the customer sign once the manager has:++| Person | Role | Step |+| --------------- | -------- | ---- |+| Sales manager | Approver | 1 |+| Customer | Signer | 2 |+| Company officer | Signer | 3 |++- **Reject** works like decline: it ends the envelope for everyone, with the reason the approver gives, and the sender is emailed "was rejected by".+- An approver goes through the same checks as a signer: the access code or emailed code the sender asked for, and the agreement to use electronic records.+- An envelope needs at least one signer. Approvers cannot have fields: placing fields offers only the signers, and saving a field for an approver is refused (by the app and by the database).+- **Templates** keep whether each role signs or approves.++### What happens along the way++- **Invitations and reminders** ask an approver to "review and approve or reject", not to sign.+- **Deadlines, reminders, void and correcting a person** work for approvers exactly as for signers.+- **Audit trail.** An approval is recorded as **approved** and a rejection as **rejected**, never as signed or declined, with the approver's step and the checks they passed. The envelope's timeline says "Approved by" and "Rejected by".+- **Certificate.** The list is headed "Signers and approvers", each approver is marked **Approver** with "Approved at" or "Rejected at", and a separate **Approvals** section lists "Approved by" (or "Rejected by", with the reason) for each approver. A line says approvers placed no signature.+- **At the same moment.** An approval takes hold of the envelope's row exactly as a signature does, so an approver and a signer of one step who finish at the same moment move the order on, or finish the envelope, once. `src/lib/approvers.dbtest.ts` runs these races.++### Where approvers are not offered++- **Part 11 mode.** An approval is an electronic signature under 21 CFR Part 11 (11.50 lists approval as a meaning), with the account, password and printed manifestation that go with one. Part 11 mode therefore has no approvers: add the person as a signer with the meaning Approval. The signers page does not offer the choice, a send with approvers is refused, and an approval on a Part 11 envelope is refused too.+- **Advanced and qualified signatures.** The finished document is the last signer's own signed revision, and an approval makes none. Send with SignuDoc signatures, or make the approver a signer.++### Upgrading++The migration `20261121110000_approvers.sql` allows the role `approver` and the events `approved` and `rejected`. An approval is stored as the person's turn being done (`signers.status = 'signed'`, with `signed_at` the time of the approval) and a rejection as `declined`, so everything that moves the order on, counts who is still to act or locks a turn treats an approver exactly as a signer; the role and the events tell them apart. An older version of the app reads only role `signer` and would leave approvers out of the signing order, so roll back past this migration only with no approvers on envelopes out for signature.+## How many signersAn 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.@@ -58,6 +93,6 @@ An older version of the app still runs on the migrated database, but it signs an## 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/signing.ts`: `submitSigningForToken`, `approveSigningForToken` (the same path, with no fields and an "approved" event) and `declineSigningForToken` (a "rejected" event for an approver), 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`.+- Tests: `signing-steps.test.ts`, `parallel-signing.dbtest.ts` and `approvers.dbtest.ts`.diff --git a/src/app/api/signing/[token]/approve/route.ts b/src/app/api/signing/[token]/approve/route.tsnew file mode 100644index 0000000..df28159--- /dev/null+++ b/src/app/api/signing/[token]/approve/route.ts@@ -0,0 +1,106 @@+import { NextResponse } from "next/server";+import { ZodError } from "zod";++import { getDb } from "@/lib/db/connection";+import {+ verificationRequiredResponse,+ verifiedMethodsForRequest,+} from "@/lib/signing-route";+import {+ approveSigningForToken,+ SigningAccessError,+ SigningMutationError,+ SigningVerificationRequiredError,+} from "@/lib/signing";+import { logRouteError } from "@/lib/security/logging";+import {+ applyPublicLinkRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import {+ getClientIpAddress,+ getRequestUserAgent,+} from "@/lib/security/request";++// An approver approves the document. Rejecting goes through the decline+// route, which records a rejection for an approver (signing.ts). The same+// checks, consent and limits apply as to a signature.++type ApproveRouteContext = {+ params: Promise<{+ token: string;+ }>;+};++const NO_STORE = { "cache-control": "private, no-store" };++export async function POST(request: Request, context: ApproveRouteContext) {+ const { token } = await context.params;+ const rateLimitResponse = await applyPublicLinkRateLimit({+ category: "signing_submit",+ key: buildRateLimitKey([+ "signing-submit",+ token,+ getClientIpAddress(request.headers) ?? "unknown",+ ]),+ limit: 10,+ request,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const body = (await request.json().catch(() => null)) as unknown;++ try {+ const payload = await approveSigningForToken(token, body, {+ database: getDb(),+ requestMeta: {+ ipAddress: getClientIpAddress(request.headers),+ userAgent: getRequestUserAgent(request.headers),+ },+ verifiedMethods: verifiedMethodsForRequest(token, request),+ });++ return NextResponse.json(payload, { headers: NO_STORE, status: 200 });+ } catch (error) {+ if (error instanceof ZodError) {+ return NextResponse.json(+ { error: error.issues[0]?.message ?? "Invalid approval." },+ { headers: NO_STORE, status: 400 },+ );+ }++ if (error instanceof SigningVerificationRequiredError) {+ return verificationRequiredResponse(error);+ }++ if (error instanceof SigningAccessError) {+ return NextResponse.json(+ { error: error.message, state: error.state },+ { headers: NO_STORE, status: error.statusCode },+ );+ }++ if (error instanceof SigningMutationError) {+ return NextResponse.json(+ { error: error.message },+ { headers: NO_STORE, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "signing_submit_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while approving a document.",+ path: request.url,+ });++ return NextResponse.json(+ { error: "Unable to record the approval." },+ { headers: NO_STORE, status: 500 },+ );+ }+}diff --git a/src/app/embed/sign/[token]/done/page.tsx b/src/app/embed/sign/[token]/done/page.tsxindex ecaf93b..d869e22 100644--- a/src/app/embed/sign/[token]/done/page.tsx+++ b/src/app/embed/sign/[token]/done/page.tsx@@ -4,7 +4,10 @@ import { SigningDoneShell } from "@/components/signing/signing-done-shell";// told already (signudoc:signed); this is what the signer sees meanwhile.type EmbedSignDonePageProps = {- searchParams?: Promise<{ title?: string | string[] }>;+ searchParams?: Promise<{+ approved?: string | string[];+ title?: string | string[];+ }>;};export default async function EmbedSignDonePage({@@ -15,5 +18,11 @@ export default async function EmbedSignDonePage({? resolved.title[0]: resolved?.title;- return <SigningDoneShell embedded envelopeTitle={envelopeTitle} />;+ return (+ <SigningDoneShell+ approved={resolved?.approved === "1"}+ embedded+ envelopeTitle={envelopeTitle}+ />+ );}diff --git a/src/app/sign/[token]/done/page.tsx b/src/app/sign/[token]/done/page.tsxindex 2455f5f..301ea84 100644--- a/src/app/sign/[token]/done/page.tsx+++ b/src/app/sign/[token]/done/page.tsx@@ -2,6 +2,7 @@ import { SigningDoneShell } from "@/components/signing/signing-done-shell";type SignDonePageProps = {searchParams?: Promise<{+ approved?: string | string[];title?: string | string[];}>;};@@ -14,5 +15,10 @@ export default async function SignDonePage({? resolvedSearchParams.title[0]: resolvedSearchParams?.title;- return <SigningDoneShell envelopeTitle={envelopeTitle} />;+ return (+ <SigningDoneShell+ approved={resolvedSearchParams?.approved === "1"}+ envelopeTitle={envelopeTitle}+ />+ );}diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex a93938e..66bd6cf 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -74,6 +74,8 @@ type EnvelopeDetailSigner = {metaLabel: string;name: string;order: number;+ /** An approver's "signed" is shown as approved, "declined" as rejected. */+ role?: "approver" | "signer";status: SignerStatus;statusDateLabel?: string;/** Signers who share a step sign at the same time. */@@ -925,7 +927,13 @@ export function EnvelopeDetailShell({className="size-3.5"strokeWidth={2.6}/>- {signerStatusLabelMap[signer.status]}+ {signer.role === "approver" &&+ signer.status === "signed"+ ? "Approved"+ : signer.role === "approver" &&+ signer.status === "declined"+ ? "Rejected"+ : signerStatusLabelMap[signer.status]}</span>{signer.statusDateLabel ? (<p className="text-xs text-(--tertiary)">@@ -1080,7 +1088,11 @@ export function EnvelopeDetailShell({}}signers={[...activeRecord.signers].sort((left, right) => left.order - right.order)- .map((signer) => ({ id: signer.id, name: signer.name }))}+ .map((signer) => ({+ id: signer.id,+ name: signer.name,+ role: signer.role,+ }))}/>) : null}diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsxindex 040cdb1..1c4096b 100644--- a/src/components/envelopes/prepare-live-shell.tsx+++ b/src/components/envelopes/prepare-live-shell.tsx@@ -268,16 +268,19 @@ const autosaveDelayMs = 450;function buildLiveSigners(signers: PrepareEnvelopeData["signers"],): PrepareShellSigner[] {- return signers- .slice()- .sort((left, right) => left.order - right.order)- .map((signer, index) => ({- ...getSignerPalette(index),- email: signer.email,- id: signer.id,- name: signer.name,- order: signer.order,- }));+ return (+ signers+ // Approvers approve or reject the document and have no fields.+ .filter((signer) => signer.role !== "approver")+ .sort((left, right) => left.order - right.order)+ .map((signer, index) => ({+ ...getSignerPalette(index),+ email: signer.email,+ id: signer.id,+ name: signer.name,+ order: signer.order,+ }))+ );}function buildLiveFields(@@ -397,9 +400,46 @@ export function PrepareLiveShell({return <PrepareLiveShellError envelopeId={envelopeId} />;}+ if (buildLiveSigners(record.signers).length === 0) {+ return <PrepareLiveShellNoSigners envelopeId={envelopeId} />;+ }+return <PrepareLiveShellContent envelopeId={envelopeId} record={record} />;}+// Every recipient is an approver, who has no fields: there is nobody to+// prepare the document for until a signer is added.+function PrepareLiveShellNoSigners({ envelopeId }: { envelopeId: string }) {+ return (+ <CanvasShell+ backHref={`/envelopes/${envelopeId}/signers`}+ backLabel="Back"+ nextDisabled+ nextLabel="Next →"+ stepLabel="Step 3 of 4"+ title='"Document"'+ >+ <div className="flex min-h-[calc(100vh-73px)] items-center justify-center p-4 sm:p-6 lg:p-8">+ <section className="panel w-full max-w-[520px] p-8 text-center sm:p-10">+ <h1 className="text-2xl font-extrabold tracking-[-0.03em] text-(--fg)">+ Add a signer first+ </h1>+ <p className="mt-2 text-sm leading-6 text-(--secondary)">+ This document has only approvers, and approvers have no fields to+ place.+ </p>+ <a+ className="mt-7 inline-block text-sm font-semibold text-(--accent)"+ href={`/envelopes/${envelopeId}/signers`}+ >+ Back to recipients+ </a>+ </section>+ </div>+ </CanvasShell>+ );+}+function PrepareLiveShellError({ envelopeId }: { envelopeId: string }) {return (<CanvasShelldiff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsxindex f514fca..d2558cd 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;+ /** An approver approves or rejects, with no fields. */+ role?: "approver" | "signer";/** Signers who share a step sign at the same time. */step?: number;tint?: string;@@ -352,18 +354,25 @@ export function ReviewShell({style={{ backgroundColor: palette.color }}/>Signer {signer.order}+ {signer.role === "approver" ? " · Approver" : ""}</span></div>- <p- className={`mt-2 text-sm leading-6 ${- signer.fieldSummaries.includes("Signature")- ? "text-(--tertiary)"- : "font-semibold text-(--danger)"- }`}- >- {formatSignerFieldSummary(signer.fieldSummaries)}- </p>+ {signer.role === "approver" ? (+ <p className="mt-2 text-sm leading-6 text-(--tertiary)">+ Approves or rejects the document. No fields.+ </p>+ ) : (+ <p+ className={`mt-2 text-sm leading-6 ${+ signer.fieldSummaries.includes("Signature")+ ? "text-(--tertiary)"+ : "font-semibold text-(--danger)"+ }`}+ >+ {formatSignerFieldSummary(signer.fieldSummaries)}+ </p>+ )}</div></div></li>diff --git a/src/components/envelopes/signers-shell.tsx b/src/components/envelopes/signers-shell.tsxindex 8ba0bde..289a328 100644--- a/src/components/envelopes/signers-shell.tsx+++ b/src/components/envelopes/signers-shell.tsx@@ -55,6 +55,8 @@ type ShellSigner = SignerChecks & {email: string;localId: string;name: string;+ /** An approver approves or rejects, with no fields of their own. */+ role: "approver" | "signer";signerId?: string;touched: Record<SignerField, boolean>;/**@@ -100,6 +102,7 @@ function createSigner(requireEmailCode: overrides?.requireEmailCode ?? false,wantsAccessCode: overrides?.hasAccessCode ?? false,name: overrides?.name ?? "",+ role: overrides?.role ?? "signer",signatureMeaning: overrides?.signatureMeaning ?? null,signerId: overrides?.signerId,touched: {@@ -179,6 +182,7 @@ function buildInitialModel(record?: DraftSignerStepData): InitialModel {hasAccessCode: signer.hasAccessCode,name: signer.name,requireEmailCode: signer.requireEmailCode,+ role: signer.role,signatureMeaning: signer.signatureMeaning ?? null,signerId: signer.id,touched: { email: true, name: true },@@ -326,6 +330,8 @@ function buildSignerRequest(id: signer.signerId,name: signer.name,requireEmailCode: signer.requireEmailCode,+ // Part 11 mode has no approvers (envelopes.ts).+ role: part11Mode ? "signer" : signer.role,signatureMeaning: signer.signatureMeaning,signOrder: index + 1,signingStep: steps[index],@@ -371,6 +377,7 @@ function SignerCard({onChecksChange,onMove,onRemove,+ onRoleChange,onTogetherChange,accessCodeError,part11Mode = false,@@ -391,6 +398,7 @@ function SignerCard({/** How many signers are in that step. */stepSize: number;onTogetherChange: (together: boolean) => void;+ onRoleChange: (role: ShellSigner["role"]) => void;onChecksChange: (patch: Partial<SignerChecks>) => void;canMoveEarlier: boolean;canMoveLater: boolean;@@ -456,11 +464,32 @@ function SignerCard({style={{ backgroundColor: palette.color }}/>Signer {order}+ {signer.role === "approver" && !part11Mode ? " · Approver" : ""}{showStep ? ` · Step ${String(step)}` : ""}</span><p className="text-[0.8125rem] leading-5 text-(--secondary)">{routeLabel}</p>+ {!part11Mode ? (+ <label className="flex items-center gap-2 text-[0.8125rem] font-semibold text-(--secondary)">+ <select+ aria-label={`Signer ${order} role`}+ className="field-input min-h-9 py-1"+ disabled={disabled}+ onChange={(event: ChangeEvent<HTMLSelectElement>) =>+ onRoleChange(+ event.target.value === "approver" ? "approver" : "signer",+ )+ }+ value={signer.role}+ >+ <option value="signer">Signs the document</option>+ <option value="approver">+ Approves or rejects it (no fields)+ </option>+ </select>+ </label>+ ) : null}{index > 0 && !part11Mode ? (<label className="flex items-center gap-2 text-[0.8125rem] font-semibold text-(--secondary)"><input@@ -866,7 +895,7 @@ export function SignersShell({function handleSignerChecksChange(signerLocalId: string,- patch: Partial<SignerChecks>,+ patch: Partial<SignerChecks & Pick<ShellSigner, "role">>,) {clearSubmitError();setSigners((currentSigners) =>@@ -1128,6 +1157,9 @@ export function SignersShell({handleMoveSigner(signer.localId, direction)}onRemove={() => handleRemoveSigner(signer.localId)}+ onRoleChange={(role) =>+ handleSignerChecksChange(signer.localId, { role })+ }onTogetherChange={(together) =>handleSignerTogetherChange(signer.localId, together)}diff --git a/src/components/signing/signing-done-shell.tsx b/src/components/signing/signing-done-shell.tsxindex 9b9b13e..86116e9 100644--- a/src/components/signing/signing-done-shell.tsx+++ b/src/components/signing/signing-done-shell.tsx@@ -4,12 +4,15 @@ import { PublicLegalFooter } from "@/components/layout/public-legal-links";const fallbackEnvelopeTitle = "this document";type SigningDoneShellProps = {+ /** An approver approved, rather than a signer signing. */+ approved?: boolean;/** Shown inside another app's page, which carries on from here. */embedded?: boolean;envelopeTitle?: string | null;};export function SigningDoneShell({+ approved = false,embedded = false,envelopeTitle,}: SigningDoneShellProps) {@@ -55,7 +58,7 @@ export function SigningDoneShell({You're all done.</h1><p className="mx-auto mt-4 max-w-[480px] text-base leading-7 text-(--secondary)">- Your signature has been recorded for{" "}+ Your {approved ? "approval" : "signature"} has been recorded for{" "}<span className="font-bold text-(--fg)">"{resolvedEnvelopeTitle}"</span>diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsxindex e593b0d..dad6ad4 100644--- a/src/components/signing/signing-live-shell.tsx+++ b/src/components/signing/signing-live-shell.tsx@@ -94,6 +94,12 @@ export const declinedConfirmation = {"Your decline has been recorded. No further action is needed, and this link no longer opens the document.",title: "You declined to sign",};+/** What an approver sees once their rejection is recorded. */+export const rejectedConfirmation = {+ description:+ "Your rejection has been recorded and the sender has been told. No further action is needed, and this link no longer opens the document.",+ title: "You rejected this document",+};const compactFieldHeightThreshold = 0.045;const compactFieldWidthThreshold = 0.12;@@ -519,6 +525,9 @@ export function SigningLiveShell({// Signed with a certificate in the signer's own name: Finish goes to the// signing provider, which signs, then sends the signer back.const providerSignature = record.providerSignature ?? null;+ // An approver reviews the document and approves or rejects it. They have+ // no fields, and Finish and Decline become Approve and Reject.+ const isApprover = record.signer.role === "approver";const isReauthReady =part11 === null ||(isMeaningConfirmed &&@@ -803,20 +812,28 @@ export function SigningLiveShell({try {const response = await fetch(- providerSignature?.startUrl ?? record.submitUrl,+ isApprover && record.approveUrl+ ? record.approveUrl+ : (providerSignature?.startUrl ?? record.submitUrl),{- body: JSON.stringify({- ...buildSigningSubmissionPayload(record, enteredValues),- ...(part11+ body: JSON.stringify(+ isApprover? {- reauthentication: {- email: reauthEmail,- meaningConfirmed: true,- password: reauthPassword,- },+ clientTimezoneOffsetMinutes: new Date().getTimezoneOffset(),}- : {}),- }),+ : {+ ...buildSigningSubmissionPayload(record, enteredValues),+ ...(part11+ ? {+ reauthentication: {+ email: reauthEmail,+ meaningConfirmed: true,+ password: reauthPassword,+ },+ }+ : {}),+ },+ ),headers: {"content-type": "application/json",},@@ -843,7 +860,7 @@ export function SigningLiveShell({return;}- if (providerSignature) {+ if (providerSignature && !isApprover) {if (!payload?.redirectUrl) {setSubmitError(defaultSubmitErrorMessage);setIsSubmitting(false);@@ -989,11 +1006,15 @@ export function SigningLiveShell({}if (hasDeclined) {+ const confirmation = isApprover+ ? rejectedConfirmation+ : declinedConfirmation;+return (<SigningStateScreen- description={declinedConfirmation.description}+ description={confirmation.description}focusHeading- title={declinedConfirmation.title}+ title={confirmation.title}/>);}@@ -1031,13 +1052,20 @@ export function SigningLiveShell({}}variant="secondary">- Decline+ {isApprover ? "Reject" : "Decline"}</ShellButton></div></div></header><main className="mx-auto flex w-full max-w-[1320px] flex-1 flex-col gap-5 px-4 pb-8 pt-1 sm:px-6">+ {isApprover ? (+ <div className="notice notice-accent" role="status">+ {record.senderName} asks you to review “{record.envelopeTitle}+ ” and approve or reject it. You have nothing to fill in, and+ nothing of yours is added to the document.+ </div>+ ) : null}{signatureProblem && providerSignature ? (<div className="notice notice-danger" role="alert">{describeProviderProblem(@@ -1226,7 +1254,9 @@ export function SigningLiveShell({<aside className="min-w-0 space-y-4 xl:sticky xl:top-[5.25rem] xl:self-start"><section className="panel rounded-[1.25rem] p-5">- <p className="section-eyebrow">Current signer</p>+ <p className="section-eyebrow">+ {isApprover ? "Approver" : "Current signer"}+ </p><div className="mt-3 flex items-center gap-3"><span className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-(--accent-soft) text-[0.9375rem] font-bold text-(--accent-ink)">{getSignerInitials(record.signer.name)}@@ -1241,7 +1271,7 @@ export function SigningLiveShell({</div></div>- <div className="well mt-5 p-4">+ <div className="well mt-5 p-4" hidden={isApprover}><p className="section-eyebrow">Ready to finish</p><p className="mt-1.5 text-[0.9375rem] font-bold text-(--fg)">{remainingFields === 0@@ -1294,12 +1324,15 @@ export function SigningLiveShell({setIsFinishDialogOpen(true);}}>- Finish+ {isApprover ? "Approve" : "Finish"}</ShellButton></div></section>- <section className="panel rounded-[1.25rem] p-5">+ <section+ className="panel rounded-[1.25rem] p-5"+ hidden={isApprover}+ ><div className="flex items-center justify-between gap-3"><p className="section-eyebrow">Assigned fields</p><span className="pill pill-neutral">@@ -1378,8 +1411,12 @@ export function SigningLiveShell({{isFinishDialogOpen ? (<DialogFrame- description={`You are signing "${record.envelopeTitle}" from ${record.senderName}.`}- title="Finish signing?"+ description={+ isApprover+ ? `You are approving "${record.envelopeTitle}" from ${record.senderName}.`+ : `You are signing "${record.envelopeTitle}" from ${record.senderName}.`+ }+ title={isApprover ? "Approve this document?" : "Finish signing?"}onClose={() => {if (isSubmitting) {return;@@ -1389,7 +1426,13 @@ export function SigningLiveShell({setSubmitError(null);}}>- {providerSignature ? (+ {isApprover ? (+ <p className="text-sm leading-6 text-(--secondary)">+ By clicking Approve, you confirm that you reviewed this document+ and approve it. Your approval is recorded in its audit trail and+ certificate. You place no signature on the document.+ </p>+ ) : providerSignature ? (<div className="grid gap-3 text-sm leading-6 text-(--secondary)"><p>This document asks for{" "}@@ -1482,13 +1525,17 @@ export function SigningLiveShell({loading={isSubmitting}onClick={handleFinishSigning}>- {providerSignature+ {isApprover? isSubmitting- ? "Preparing..."- : `Continue to ${providerSignature.providerName}`- : isSubmitting- ? "Finishing..."- : "Finish signing"}+ ? "Approving..."+ : "Approve"+ : providerSignature+ ? isSubmitting+ ? "Preparing..."+ : `Continue to ${providerSignature.providerName}`+ : isSubmitting+ ? "Finishing..."+ : "Finish signing"}</ShellButton></div></DialogFrame>@@ -1496,9 +1543,9 @@ export function SigningLiveShell({{consentedAt === null && !isDeclineDialogOpen ? (<DialogFrame- description={`${record.senderName} sent you "${record.envelopeTitle}" to sign electronically.`}+ description={`${record.senderName} sent you "${record.envelopeTitle}" to ${isApprover ? "review and approve" : "sign"} electronically.`}onClose={() => undefined}- title="Before you sign"+ title={isApprover ? "Before you approve" : "Before you sign"}><div className="well max-h-[45vh] space-y-4 overflow-y-auto px-4 py-4 text-sm leading-6 text-(--secondary) sm:px-5">{record.disclosure.sections.map((section, index) => (@@ -1544,7 +1591,7 @@ export function SigningLiveShell({}}variant="secondary">- Decline+ {isApprover ? "Reject" : "Decline"}</ShellButton><ShellButtondisabled={!isConsentChecked}@@ -1559,8 +1606,8 @@ export function SigningLiveShell({{isDeclineDialogOpen ? (<DialogFrame- description={`The sender (${record.senderName}) will be notified that you declined. This cannot be undone.`}- title="Decline to sign?"+ description={`The sender (${record.senderName}) will be notified that you ${isApprover ? "rejected it" : "declined"}. This ends the envelope for everyone and cannot be undone.`}+ title={isApprover ? "Reject this document?" : "Decline to sign?"}onClose={() => {if (isDeclining) {return;@@ -1605,7 +1652,13 @@ export function SigningLiveShell({onClick={handleDeclineSigning}variant="danger">- {isDeclining ? "Declining..." : "Decline to sign"}+ {isApprover+ ? isDeclining+ ? "Rejecting..."+ : "Reject"+ : isDeclining+ ? "Declining..."+ : "Decline to sign"}</ShellButton></div></DialogFrame>diff --git a/src/components/signing/signing-shell.tsx b/src/components/signing/signing-shell.tsxindex c038d24..5073bf5 100644--- a/src/components/signing/signing-shell.tsx+++ b/src/components/signing/signing-shell.tsx@@ -43,8 +43,9 @@ const tokenStateCopy: Record<description: "Request a new signing link from the sender.",},"already-signed": {- title: "You've already signed",- description: "You already completed your signature for this document.",+ title: "You've already finished",+ description:+ "You already signed or approved this document. No further action is needed.",},completed: {title: "This envelope has been completed",@@ -59,7 +60,7 @@ const tokenStateCopy: Record<declined: {title: "This envelope has been declined",description:- "A signer declined this document. No further action is needed.",+ "A signer declined, or an approver rejected, this document. No further action is needed.",},};diff --git a/src/components/templates/save-template-dialog.tsx b/src/components/templates/save-template-dialog.tsxindex f38fd60..0edb0fd 100644--- a/src/components/templates/save-template-dialog.tsx+++ b/src/components/templates/save-template-dialog.tsx@@ -19,7 +19,11 @@ type SaveTemplateDialogProps = {onCancel: () => void;onSaved: (templateName: string) => void;/** In signing order. The names only say whose place is being named. */- signers: readonly { id: string; name: string }[];+ signers: readonly {+ id: string;+ name: string;+ role?: "approver" | "signer";+ }[];};const genericError = "Something went wrong. Please try again.";@@ -162,6 +166,11 @@ export function SaveTemplateDialog({type="text"value={roleNames[index] ?? ""}/>+ {signer.role === "approver" ? (+ <span className="text-xs text-(--tertiary)">+ Approves or rejects, with no fields.+ </span>+ ) : null}</label>))}{hasRepeatedRoleName ? (diff --git a/src/components/templates/use-template-shell.tsx b/src/components/templates/use-template-shell.tsxindex 6742402..472cd9e 100644--- a/src/components/templates/use-template-shell.tsx+++ b/src/components/templates/use-template-shell.tsx@@ -220,6 +220,11 @@ export function UseTemplateShell({{template.roles[index - 1]?.name}.</p>) : null}+ {role.kind === "approver" ? (+ <p className="mt-2 text-[0.8125rem] leading-5 text-(--secondary)">+ Approves or rejects the document, with no fields.+ </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/api/envelope-view.ts b/src/lib/api/envelope-view.tsindex 4c16e0f..82886cb 100644--- a/src/lib/api/envelope-view.ts+++ b/src/lib/api/envelope-view.ts@@ -8,7 +8,11 @@ import {type DbPool,} from "../db/connection.ts";import { signingStepOf } from "../signing-steps.ts";-import type { EnvelopeStatus, SignerStatus } from "../types/domain.ts";+import type {+ EnvelopeStatus,+ RecipientRole,+ SignerStatus,+} from "../types/domain.ts";// How the public API shows an envelope: one shape, ApiEnvelope, returned by// every endpoint and carried by webhooks. Only reads here, so the webhook@@ -26,6 +30,11 @@ export type ApiSigner = {name: string;order: number;ref: string | null;+ /**+ * "approver" for someone who approves or rejects instead of signing. An+ * approval shows as `signed`, a rejection as `declined`.+ */+ role: RecipientRole;signedAt: string | null;status: SignerStatus;/** Signers who share a step sign at the same time. */@@ -87,7 +96,7 @@ type SignerRow = {envelopeId: string;id: string;name: string;- role: "cc" | "signer";+ role: "cc" | RecipientRole;signedAt: number | null;signingStep: number | null;signOrder: number;@@ -202,7 +211,7 @@ export function toApiEnvelope(sentAt: isoTime(row.sentAt),signatureLevel: row.signatureLevel ?? "simple",signers: signers- .filter((signer) => signer.role === "signer")+ .filter((signer) => signer.role !== "cc").map((signer) => ({declinedAt: isoTime(signer.declinedAt),declineReason: signer.declineReason,@@ -211,6 +220,7 @@ export function toApiEnvelope(name: signer.name,order: signer.signOrder,ref: signer.apiRef,+ role: signer.role === "approver" ? "approver" : "signer",signedAt: isoTime(signer.signedAt),status: signer.status,step: signingStepOf(signer),diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.tsindex ae75418..ae8df6a 100644--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@ -315,6 +315,12 @@ export function buildOpenApiDocument(name: { type: "string" },order: { type: "integer" },ref: { type: ["string", "null"] },+ role: {+ description:+ "approver: reviews the document and approves or rejects it instead of signing. An approval is signed, a rejection declined.",+ enum: ["signer", "approver"],+ type: "string",+ },signedAt: isoTime,status: {description:diff --git a/src/lib/approvers.dbtest.ts b/src/lib/approvers.dbtest.tsnew file mode 100644index 0000000..bf80680--- /dev/null+++ b/src/lib/approvers.dbtest.ts@@ -0,0 +1,863 @@+import assert from "node:assert/strict";+import { createHash, randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+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,+ getReviewEnvelopeDataForUser,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+ sendDraftEnvelope,+} from "./envelopes.ts";+import { verifyAuditChain } from "./services/audit.ts";+import { issueSigningLink } from "./services/signing-links.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import {+ approveSigningForToken,+ declineSigningForToken,+ getSigningPayloadForToken,+ recordSignerConsent,+ SigningMutationError,+ submitSigningForToken,+} from "./signing.ts";++// Approvers, against a real Postgres: an approver takes part in the steps+// of the signing order like a signer, approves without fields, is recorded+// as "approved" and never as "signed", and a rejection ends the envelope+// like a decline. An approver and a signer of one step who finish at the+// same moment move the order on, or finish the envelope, exactly once,+// under the same locking as two signers (parallel-signing.dbtest.ts).+// Run with `npm run test:db`.++process.env.APP_URL ??= "https://sign.example.test";++const DAY = 24 * 60 * 60;+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-approvers-"));+ 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 | null;+ id: string;+ name: string;+ role: "approver" | "signer";+ token: string | null;+};++async function storeSourcePdf(envelopeId: string) {+ const sourcePdf = await PDFDocument.create();++ sourcePdf.addPage([612, 792]);++ const bytes = await sourcePdf.save();+ const key = `test/${envelopeId}.pdf`;++ await storageService.putObject({+ body: bytes,+ contentType: "application/pdf",+ key,+ });++ return {+ bytes,+ hash: createHash("sha256").update(bytes).digest("hex"),+ key,+ };+}++async function createSender() {+ const userId = randomUUID();++ createdUsers.push(userId);+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,+ [userId, `${userId}@example.test`],+ );++ return userId;+}++/**+ * An envelope out for signature with these people in these steps, in list+ * order. Approvers have no fields. The first step is waiting, with a link+ * each, and has agreed to electronic records.+ */+async function createEnvelope(+ people: ReadonlyArray<{ role: "approver" | "signer"; step: number }>,+) {+ const userId = await createSender();+ const envelopeId = randomUUID();+ const now = Math.floor(Date.now() / 1000);+ const source = await storeSourcePdf(envelopeId);++ 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+ ) values ($1, $2, 'Contract', 'sent', $3, 'contract.pdf', $4, 1, $5, $6, $7)+ `,+ [+ envelopeId,+ userId,+ source.key,+ source.bytes.length,+ source.hash,+ 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[] = [];+ const firstStep = Math.min(...people.map((person) => person.step));++ for (const [index, person] of people.entries()) {+ const id = randomUUID();+ const waiting = person.step === firstStep;+ const link = waiting+ ? await issueSigningLink({ expiresInSeconds: DAY, issuedAt: now })+ : null;+ const name = `${person.role === "approver" ? "Approver" : "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, role+ ) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10, $11)+ `,+ [+ id,+ envelopeId,+ name,+ `${id}@example.test`,+ index + 1,+ person.step,+ waiting ? "notified" : "pending",+ link?.tokenHash ?? null,+ link?.exp ?? null,+ waiting ? now : null,+ person.role,+ ],+ );++ let fieldId: string | null = null;++ if (person.role === "signer") {+ fieldId = randomUUID();+ 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,+ role: person.role,+ token: link?.token ?? null,+ });+ }++ return { envelopeId, parties, userId };+}++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;+}++/** Signs, or approves, as the party's role says. */+function act(party: Party, pool: pg.Pool = database) {+ assert.ok(party.token, `${party.name} has no link`);++ if (party.role === "approver") {+ return approveSigningForToken(+ party.token,+ { clientTimezoneOffsetMinutes: 0 },+ { database: pool },+ );+ }++ 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 in ('signer', 'approver')+ order by sign_order+ `,+ [envelopeId],+ );++ return result.rows.map((row) => row.status);+}++async function envelopeOf(envelopeId: string) {+ const result = await database.query<{+ evidence_key: string | null;+ status: string;+ }>(`select status, evidence_key from envelopes where id = $1`, [envelopeId]);++ return result.rows[0]!;+}++async function eventsOf(envelopeId: string, event: string) {+ const result = await database.query<{+ metadata: Record<string, unknown> | null;+ }>(+ `+ select metadata from audit_events+ where envelope_id = $1 and event = $2+ order by sequence+ `,+ [envelopeId, event],+ );++ return result.rows.map((row) => row.metadata ?? {});+}++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;+}++async function extractPdfText(pdfBytes: Uint8Array): Promise<string> {+ const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");+ const document = await pdfjs.getDocument({+ data: new Uint8Array(pdfBytes),+ useSystemFonts: false,+ verbosity: 0,+ }).promise;+ const parts: string[] = [];++ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber += 1) {+ const page = await document.getPage(pageNumber);+ const content = await page.getTextContent();++ parts.push(+ content.items.map((item: { str?: string }) => item.str ?? "").join(" "),+ );+ }++ await document.destroy();++ return parts.join("\n").replace(/\s+/g, " ");+}++async function storedCertificateText(envelopeId: string) {+ const { evidence_key: key } = await envelopeOf(envelopeId);++ assert.ok(key, "no certificate was stored");++ return extractPdfText((await storageService.getObject(key)).body);+}++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 turn as done (`status = 'signed'`), and+ * before it commits.+ */+function withRivalAfterTurn(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("the manager approves in step 1, then the customer is invited and signs", async () => {+ const envelope = await createEnvelope([+ { role: "approver", step: 1 },+ { role: "signer", step: 2 },+ ]);+ const [manager, customer] = envelope.parties as [Party, Party];++ // The customer has not been invited while the approval is outstanding.+ assert.equal(await invitationsTo(envelope.envelopeId, customer.id), 0);++ const payload = await getSigningPayloadForToken(manager.token!, {+ database,+ });++ assert.equal(payload.signer.role, "approver");+ assert.equal(payload.currentSignerFields.length, 0);+ assert.ok(payload.approveUrl?.endsWith("/approve"));++ const approved = await act(manager);++ assert.match(approved.redirectPath, /approved=1/);+ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "notified",+ ]);+ assert.equal(await invitationsTo(envelope.envelopeId, customer.id), 1);++ const approvals = await eventsOf(envelope.envelopeId, "approved");++ assert.equal(approvals.length, 1);+ assert.equal(approvals[0]?.role, "approver");+ assert.equal(approvals[0]?.signerId, manager.id);+ // An approval is never recorded as a signature.+ assert.equal((await eventsOf(envelope.envelopeId, "signed")).length, 0);++ await takeOverLink(customer);+ await act(customer);++ assert.equal((await envelopeOf(envelope.envelopeId)).status, "completed");+ assert.equal((await eventsOf(envelope.envelopeId, "signed")).length, 1);+ assert.equal((await eventsOf(envelope.envelopeId, "completed")).length, 1);+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );++ const certificate = await storedCertificateText(envelope.envelopeId);++ assert.match(certificate, /Signers and approvers/);+ assert.match(certificate, /Approved by Approver 1/);+ assert.match(certificate, /Approver \| Approved at/);+ assert.match(certificate, /Signer 2 .*\| Signed at/);+});++test("an approval can be the last turn, and finishes the envelope", async () => {+ const envelope = await createEnvelope([+ { role: "signer", step: 1 },+ { role: "approver", step: 2 },+ ]);+ const [customer, approver] = envelope.parties as [Party, Party];++ await act(customer);+ await takeOverLink(approver);+ await act(approver);++ assert.equal((await envelopeOf(envelope.envelopeId)).status, "completed");+ assert.equal((await eventsOf(envelope.envelopeId, "approved")).length, 1);+ assert.equal((await eventsOf(envelope.envelopeId, "completed")).length, 1);+});++test("a rejection ends the envelope like a decline, with its reason, recorded as rejected", async () => {+ const envelope = await createEnvelope([+ { role: "approver", step: 1 },+ { role: "signer", step: 2 },+ ]);+ const [manager, customer] = envelope.parties as [Party, Party];++ await declineSigningForToken(+ manager.token!,+ { reason: "Price is wrong." },+ { database },+ );++ assert.equal((await envelopeOf(envelope.envelopeId)).status, "declined");+ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "declined",+ "pending",+ ]);+ assert.equal(await invitationsTo(envelope.envelopeId, customer.id), 0);++ const rejections = await eventsOf(envelope.envelopeId, "rejected");++ assert.equal(rejections.length, 1);+ assert.equal(rejections[0]?.reason, "Price is wrong.");+ assert.equal((await eventsOf(envelope.envelopeId, "declined")).length, 0);++ const certificate = await storedCertificateText(envelope.envelopeId);++ assert.match(certificate, /Rejected by Approver 1 .*Price is wrong\./);+});++test("an approver's link cannot sign, and a signer's link cannot approve", async () => {+ const envelope = await createEnvelope([+ { role: "approver", step: 1 },+ { role: "signer", step: 1 },+ ]);+ const [approver, signer] = envelope.parties as [Party, Party];++ await assert.rejects(+ submitSigningForToken(+ approver.token!,+ { clientTimezoneOffsetMinutes: 0, fields: [] },+ { database },+ ),+ (error: unknown) =>+ error instanceof SigningMutationError && error.statusCode === 409,+ );+ await assert.rejects(+ approveSigningForToken(+ signer.token!,+ { clientTimezoneOffsetMinutes: 0 },+ { database },+ ),+ (error: unknown) =>+ error instanceof SigningMutationError && error.statusCode === 409,+ );+ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "notified",+ "notified",+ ]);+});++test("an approval is refused on a Part 11 envelope, whatever happened at sending", async () => {+ const envelope = await createEnvelope([+ { role: "approver", step: 1 },+ { role: "signer", step: 2 },+ ]);++ await database.query(`update envelopes set part11 = true where id = $1`, [+ envelope.envelopeId,+ ]);++ await assert.rejects(+ act(envelope.parties[0]!),+ (error: unknown) =>+ error instanceof SigningMutationError && error.statusCode === 409,+ );+ assert.equal((await eventsOf(envelope.envelopeId, "approved")).length, 0);+});++test("an approver and a signer of one step finishing together invite the next step once", async () => {+ const envelope = await createEnvelope([+ { role: "approver", step: 1 },+ { role: "signer", step: 1 },+ { role: "signer", step: 2 },+ ]);+ const [approver, signer, next] = envelope.parties as [Party, Party, Party];+ const { pool, started } = withRivalAfterTurn(() => act(signer));++ await act(approver, pool);++ assert.ok(started.rival, "the approval was never written");+ await started.rival;++ assert.deepEqual(await statusesOf(envelope.envelopeId), [+ "signed",+ "signed",+ "notified",+ ]);+ assert.equal(await invitationsTo(envelope.envelopeId, next.id), 1);+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );+});++test("an approver and a signer of the last step finishing together complete it once", async () => {+ const envelope = await createEnvelope([+ { role: "signer", step: 1 },+ { role: "approver", step: 1 },+ ]);+ const [signer, approver] = envelope.parties as [Party, Party];+ const { pool, started } = withRivalAfterTurn(() => act(approver));++ await act(signer, pool);++ assert.ok(started.rival, "the signature was never written");+ await started.rival;++ assert.equal((await envelopeOf(envelope.envelopeId)).status, "completed");+ assert.equal((await eventsOf(envelope.envelopeId, "completed")).length, 1);+ assert.equal((await eventsOf(envelope.envelopeId, "approved")).length, 1);+ assert.equal((await eventsOf(envelope.envelopeId, "signed")).length, 1);+});++test("a rejection while a signer of the step signs starts again from that signature", async () => {+ const envelope = await createEnvelope([+ { role: "signer", step: 1 },+ { role: "approver", step: 1 },+ { role: "signer", step: 2 },+ ]);+ const [signer, approver] = envelope.parties as [Party, Party, Party];+ const { pool, started } = withRivalAfterTurn(() =>+ declineSigningForToken(approver.token!, { reason: "No." }, { database }),+ );++ await act(signer, 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 envelopeOf(envelope.envelopeId)).status, "declined");++ // The certificate shows the signature that came first.+ const certificate = await storedCertificateText(envelope.envelopeId);++ assert.match(certificate, /Signer 1 .*\| Signed at/);+ assert.match(certificate, /Rejected by Approver 2/);+});++async function createDraft() {+ const userId = await createSender();+ const envelopeId = randomUUID();+ const source = await storeSourcePdf(envelopeId);++ 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, source.key, source.bytes.length, source.hash],+ );+ 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: [+ {+ email: `boss-${randomUUID()}@example.test`,+ name: "Bea Boss",+ role: "approver",+ signingStep: 1,+ },+ {+ email: `client-${randomUUID()}@example.test`,+ name: "Cal Client",+ role: "signer",+ signingStep: 2,+ },+ ],+ },+ database,+ );+ const [approver, customer] = saved.signers as [+ (typeof saved.signers)[number],+ (typeof saved.signers)[number],+ ];++ return { approver, customer, envelopeId, userId };+}++function signatureField(signerId: string) {+ return {+ height: 0.05,+ page: 1,+ required: true,+ signerId,+ type: "signature" as const,+ width: 0.2,+ x: 0.1,+ y: 0.1,+ };+}++test("an approver is saved with the role, and can have no fields", async () => {+ const draft = await createDraft();++ assert.equal(draft.approver.role, "approver");+ assert.equal(draft.customer.role, "signer");++ await assert.rejects(+ replaceDraftEnvelopeFields(+ draft.userId,+ draft.envelopeId,+ { fields: [signatureField(draft.approver.id)] },+ database,+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError && error.statusCode === 400,+ );++ // And the database refuses one written another way.+ await assert.rejects(+ database.query(+ `+ insert into fields (id, envelope_id, signer_id, type, page, x, y, width, height)+ values ($1, $2, $3, 'signature', 1, 0.1, 0.1, 0.2, 0.05)+ `,+ [randomUUID(), draft.envelopeId, draft.approver.id],+ ),+ );+});++test("sending invites the approver first, with an invitation to approve", async () => {+ const draft = await createDraft();++ await replaceDraftEnvelopeFields(+ draft.userId,+ draft.envelopeId,+ { fields: [signatureField(draft.customer.id)] },+ database,+ );+ await sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ );++ assert.deepEqual(await statusesOf(draft.envelopeId), ["notified", "pending"]);+ assert.equal(await invitationsTo(draft.envelopeId, draft.approver.id), 1);+ assert.equal(await invitationsTo(draft.envelopeId, draft.customer.id), 0);+});++test("an envelope of approvers only, or with approvers in Part 11 mode or with a signing provider, is not sent", async () => {+ const onlyApprovers = await createDraft();++ await replaceDraftEnvelopeSigners(+ onlyApprovers.userId,+ onlyApprovers.envelopeId,+ {+ signers: [+ {+ email: onlyApprovers.approver.email,+ id: onlyApprovers.approver.id,+ name: "Bea Boss",+ role: "approver",+ },+ ],+ },+ database,+ );+ await assert.rejects(+ sendDraftEnvelope(+ onlyApprovers.userId,+ onlyApprovers.envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ /place fields/.test(error.message),+ );++ // The sender is told why on the review page, which is where the rule+ // about someone having to sign is the explanation they see.+ const review = await getReviewEnvelopeDataForUser(+ onlyApprovers.userId,+ onlyApprovers.envelopeId,+ database,+ );++ assert.equal(review?.canSend, false);+ assert.match(review?.disabledReason ?? "", /Add at least one signer/);++ const provider = await createDraft();++ await replaceDraftEnvelopeFields(+ provider.userId,+ provider.envelopeId,+ { fields: [signatureField(provider.customer.id)] },+ database,+ );+ await assert.rejects(+ sendDraftEnvelope(+ provider.userId,+ provider.envelopeId,+ {+ senderEmail: "[email protected]",+ senderName: "Sam Sender",+ signatureLevel: "advanced",+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ /Approvers work with SignuDoc signatures only/.test(error.message),+ );++ const part11 = await createDraft();++ await replaceDraftEnvelopeFields(+ part11.userId,+ part11.envelopeId,+ { fields: [signatureField(part11.customer.id)] },+ database,+ );++ const before = await database.query<{ part11_mode: boolean }>(+ `select part11_mode from app_settings where id`,+ );+ const now = Math.floor(Date.now() / 1000);++ if (before.rowCount === 0) {+ await database.query(+ `insert into app_settings (id, part11_mode, created_at, updated_at) values (true, true, $1, $1)`,+ [now],+ );+ } else {+ await database.query(`update app_settings set part11_mode = true where id`);+ }++ try {+ await assert.rejects(+ sendDraftEnvelope(+ part11.userId,+ part11.envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ /Part 11 mode has no approvers/.test(error.message),+ );+ } finally {+ if (before.rowCount === 0) {+ await database.query(`delete from app_settings where id`);+ } else {+ await database.query(+ `update app_settings set part11_mode = $1 where id`,+ [before.rows[0]!.part11_mode],+ );+ }+ }++ for (const draft of [onlyApprovers, provider, part11]) {+ assert.equal((await envelopeOf(draft.envelopeId)).status, "draft");+ }+});diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.tsindex 1f17c72..66fca8b 100644--- a/src/lib/bulk-send.ts+++ b/src/lib/bulk-send.ts@@ -689,6 +689,8 @@ async function sendOneRow(id: signer.id,name: signer.name,requireEmailCode,+ // An approver in the template stays one.+ role: signer.role,signatureMeaning,// Signers who share a step keep signing at the same time.signingStep: signer.step,diff --git a/src/lib/certificate-race.dbtest.ts b/src/lib/certificate-race.dbtest.tsindex a85c578..0a465af 100644--- a/src/lib/certificate-race.dbtest.ts+++ b/src/lib/certificate-race.dbtest.ts@@ -622,12 +622,12 @@ for (const [name, statement, end] of [["the last signature", "AND status <> 'signed'", signEnvelope],["a void",- "SELECT id, status FROM signers WHERE envelope_id = $1 AND role = 'signer'",+ "SELECT id, status FROM signers WHERE envelope_id = $1 AND role IN ('signer', 'approver')",voidEnvelope,],["a decline",- "WHERE envelope_id = $1 AND role = 'signer' AND id <> $2",+ "WHERE envelope_id = $1 AND role IN ('signer', 'approver') AND id <> $2",declineEnvelope,],] as const) {diff --git a/src/lib/downloads.ts b/src/lib/downloads.tsindex 4d17cd2..4c17891 100644--- a/src/lib/downloads.ts+++ b/src/lib/downloads.ts@@ -74,6 +74,8 @@ type SignerRow = {lastNotifiedAt: number | null;lastNudgedAt: number | null;name: string;+ /** Read only where the certificate is made again. */+ role?: string;signedAt: number | null;signOrder: number;signingStep?: number | null;@@ -155,6 +157,7 @@ function mapSignerRow(row: SignerRow): SignerRecord {lastNotifiedAt: row.lastNotifiedAt,lastNudgedAt: row.lastNudgedAt,name: row.name,+ role: row.role === "approver" ? "approver" : undefined,signOrder: row.signOrder,signingStep: row.signingStep ?? null,signedAt: row.signedAt,@@ -346,11 +349,13 @@ async function listSignersForEnvelope(signed_at AS "signedAt",declined_at AS "declinedAt",decline_reason AS "declineReason",+ role,created_at AS "createdAt",updated_at AS "updatedAt"FROM signersWHERE envelope_id = $1- AND role = 'signer'+ -- The signing order: signers and approvers, never copy recipients.+ AND role IN ('signer', 'approver')ORDER BY sign_order ASC, id ASC`,[envelopeId],diff --git a/src/lib/embedding.ts b/src/lib/embedding.tsindex 330e375..dcb1c69 100644--- a/src/lib/embedding.ts+++ b/src/lib/embedding.ts@@ -313,7 +313,7 @@ export async function issueEmbedLink(tx,`SELECT status FROM signers- WHERE id = $1 AND envelope_id = $2 AND role = 'signer'+ WHERE id = $1 AND envelope_id = $2 AND role IN ('signer', 'approver')FOR UPDATE`,[input.signerId, input.envelopeId],diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 4a5242c..c1300ca 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -71,7 +71,7 @@ import {signatureMeaningLabel,} from "./part11.ts";import { getBranding, readStoredSettings } from "./settings.ts";-import { type SignatureMeaning } from "./types/domain.ts";+import { type RecipientRole, type SignatureMeaning } from "./types/domain.ts";import { importPdfDocument } from "./services/document-import.ts";import {describeSignerCorrectedEvent,@@ -262,6 +262,7 @@ type SignerRow = {lastNotifiedAt: number | null;lastNudgedAt: number | null;name: string;+ role: RecipientRole;signatureMeaning: SignatureMeaning | null;signedAt: number | null;signOrder: number;@@ -370,6 +371,8 @@ export type ReviewSignerSummary = {id: string;name: string;order: number;+ /** A signer, or an approver who has no fields. */+ role: RecipientRole;/** The step of the signing order; signers who share one sign together. */step: number;};@@ -401,6 +404,8 @@ export type DraftSignerStepSigner = {name: string;order: number;requireEmailCode?: boolean;+ /** A signer, or an approver who has no fields. */+ role: RecipientRole;/** Set on the signers step only. */signatureMeaning?: SignatureMeaning | null;/** The step of the signing order; signers who share one sign together. */@@ -437,6 +442,8 @@ export type EnvelopeDetailSignerView = {metaLabel: string;name: string;order: number;+ /** An approver's "signed" is an approval and "declined" a rejection. */+ role: RecipientRole;status: "declined" | "pending" | "signed" | "waiting";statusDateLabel?: string;/** The step of the signing order; signers who share one sign together. */@@ -579,7 +586,9 @@ const TIMELINE_TONE_MAP: Record<AuditEventRecord["event"],EnvelopeDetailTimelineItem["tone"]> = {+ approved: "success",completed: "success",+ rejected: "danger",consented: "neutral",copied: "accent",created: "accent",@@ -993,9 +1002,10 @@ export async function copyEnvelopeToDraft(access_code_hash,require_email_code,signature_meaning,- signing_step+ signing_step,+ role) VALUES (- $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10, $11+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10, $11, $12)`,[@@ -1010,6 +1020,8 @@ export async function copyEnvelopeToDraft(checks.get(signer.id)?.requireEmailCode ?? false,null,signingStepOf(signer),+ // An approver stays an approver in the copy.+ signer.role ?? "signer",],);}@@ -1250,6 +1262,7 @@ async function listSignersForEnvelopeIds(envelope_id AS "envelopeId",name,email,+ role,sign_order AS "signOrder",signing_step AS "signingStep",status,@@ -1266,7 +1279,8 @@ async function listSignersForEnvelopeIds(updated_at AS "updatedAt"FROM signersWHERE envelope_id IN (${placeholders})- AND role = 'signer'+ -- Everyone in the signing order: signers and approvers.+ AND role IN ('signer', 'approver')ORDER BY envelope_id ASC, sign_order ASC, id ASC`,envelopeIds,@@ -1508,7 +1522,7 @@ function buildDashboardContextLine(const declinedSigner = signers.find((signer) => signer.status === "declined",);- return `Declined by: ${declinedSigner?.email ?? "—"}`;+ return `${declinedSigner?.role === "approver" ? "Rejected" : "Declined"} by: ${declinedSigner?.email ?? "—"}`;}if (envelope.status === "voided") {@@ -1540,7 +1554,10 @@ function buildDashboardStatusLabel((signer) => signer.status === "signed",).length;- return `${String(signedCount)} of ${String(signers.length)} signed`;+ // An approval is a turn done, not a signature.+ return `${String(signedCount)} of ${String(signers.length)} ${+ signers.some((signer) => signer.role === "approver") ? "done" : "signed"+ }`;}return dashboardStatusLabels[envelope.status];@@ -1642,12 +1659,55 @@ function getMissingSignatureSigner(): PersistedSignerRecord | undefined {return signers.find((signer) =>+ signer.role !== "approver" &&!(fieldsBySigner.get(signer.id) ?? []).some((field) => field.type === "signature",),);}+/**+ * Approvers are not offered in Part 11 mode. An approval there would be an+ * electronic signature under 21 CFR 11 (11.50 lists approval as a meaning),+ * with the account, password and manifestation that go with one, and the+ * Part 11 validation (docs/part11) covers signers only.+ */+const PART11_APPROVER_MESSAGE =+ "Part 11 mode has no approvers. Make each approver a signer with the meaning Approval, so they sign with their account and password.";++/**+ * What stops the signing order from going out, about signers and+ * approvers, in words for the sender: someone has to sign, every signer+ * needs a Signature field, and an approver has no fields at all.+ */+function describeSigningOrderProblem(+ signers: readonly PersistedSignerRecord[],+ fieldsBySigner: ReadonlyMap<string, readonly FieldRecord[]>,+): string | null {+ if (!signers.some((signer) => signer.role !== "approver")) {+ return "Add at least one signer. Approvers approve or reject, so someone else has to sign.";+ }++ const approverWithFields = signers.find(+ (signer) =>+ signer.role === "approver" &&+ (fieldsBySigner.get(signer.id) ?? []).length > 0,+ );++ if (approverWithFields) {+ return `${approverWithFields.name} is an approver, and approvers have no fields. Remove their fields, or make them a signer.`;+ }++ const missingSignatureSigner = getMissingSignatureSigner(+ signers,+ fieldsBySigner,+ );++ return missingSignatureSigner+ ? `Every signer must have at least one Signature field before sending. ${missingSignatureSigner.name} is missing one.`+ : null;+}+function buildVoidNotificationEmail(input: {branding: Branding;envelopeId: string;@@ -1799,6 +1859,12 @@ function buildTimelineDescription(event: AuditEventRecord): string {return declineReason? `Declined by ${targetLabel} — ${declineReason}`: `Declined by ${targetLabel}`;+ case "approved":+ return `Approved by ${targetLabel}`;+ case "rejected":+ return declineReason+ ? `Rejected by ${targetLabel} — ${declineReason}`+ : `Rejected by ${targetLabel}`;case "reminded_manual":return `Manual reminder sent to ${targetLabel}`;case "reminded_auto":@@ -1839,12 +1905,14 @@ function buildDetailSignerStatusLabel(signer: PersistedSignerRecord,previousSignerName?: string,): string | undefined {+ const approver = signer.role === "approver";+if (signer.status === "signed" && signer.signedAt) {- return `Signed ${formatShortDate(signer.signedAt)}`;+ return `${approver ? "Approved" : "Signed"} ${formatShortDate(signer.signedAt)}`;}if (signer.status === "declined" && signer.declinedAt) {- return `Declined ${formatShortDate(signer.declinedAt)}`;+ return `${approver ? "Rejected" : "Declined"} ${formatShortDate(signer.declinedAt)}`;}if (signer.status === "notified") {@@ -1872,12 +1940,37 @@ function buildDetailSignerMetaLabel(signer: PersistedSignerRecord,assignedFieldCount: number,): string {+ const approver = signer.role === "approver";+if (envelope.status === "voided" && signer.status === "notified") {- return "Last notified signer before void";+ return approver+ ? "Last notified approver before void"+ : "Last notified signer before void";}if (signer.status === "declined" && signer.declineReason) {- return `Decline reason: ${signer.declineReason}`;+ return `${approver ? "Rejection" : "Decline"} reason: ${signer.declineReason}`;+ }++ // An approver has no fields to count.+ if (approver) {+ if (envelope.status === "declined" && signer.status === "pending") {+ return "Skipped after decline";+ }++ if (envelope.status === "voided" && signer.status === "pending") {+ return "Not reached before void";+ }++ if (signer.status === "signed") {+ return "Approved";+ }++ if (signer.status === "declined") {+ return "Rejected";+ }++ return signer.status === "notified" ? "Current approver" : "Approver";}if (envelope.status === "declined" && signer.status === "pending") {@@ -2161,6 +2254,7 @@ export async function getEnvelopeDetailDataForUser(),name: signer.name,order: signer.signOrder,+ role: signer.role ?? "signer",status: signerStatus,statusDateLabel: buildDetailSignerStatusLabel(envelope,@@ -2263,6 +2357,7 @@ export async function getDraftSignerStepDataForUser(name: signer.name,order: signer.signOrder,requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,+ role: signer.role ?? "signer",signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,step: signingStepOf(signer),}),@@ -2468,6 +2563,7 @@ export async function getPrepareEnvelopeDataForUser(id: signer.id,name: signer.name,order: signer.signOrder,+ role: signer.role ?? "signer",step: signingStepOf(signer),})),status: envelope.status,@@ -2495,24 +2591,28 @@ export async function getReviewEnvelopeDataForUser(const signers = signersByEnvelope.get(envelopeId) ?? [];const fields = fieldsByEnvelope.get(envelopeId) ?? [];const fieldsBySigner = buildFieldsBySigner(fields);- const missingSignatureSigner = getMissingSignatureSigner(- signers,- fieldsBySigner,- );+ const signingOrderProblem =+ signers.length > 0+ ? describeSigningOrderProblem(signers, fieldsBySigner)+ : null;const isEmpty = signers.length === 0 || fields.length === 0;const choiceProblem = describeChoiceProblem(signers, fields);const provider = configuredSigningProvider();- const part11Mode = provider- ? ((await readStoredSettings(database))?.part11Mode ?? false)- : false;+ const part11Mode = (await readStoredSettings(database))?.part11Mode ?? false;+ const hasApprovers = signers.some((signer) => signer.role === "approver");+ const approverProblem =+ hasApprovers && part11Mode ? PART11_APPROVER_MESSAGE : null;+ const disabledReason =+ signingOrderProblem ?? choiceProblem ?? approverProblem;return {- canSend: !isEmpty && !missingSignatureSigner && !choiceProblem,- signingProvider: provider && !part11Mode ? { name: provider.name } : null,+ canSend: !isEmpty && !disabledReason,+ // Approvers approve on SignuDoc's own page, so a signing provider is+ // not offered alongside them (see sendDraftEnvelope).+ signingProvider:+ provider && !part11Mode && !hasApprovers ? { name: provider.name } : null,copyRecipients,- disabledReason: missingSignatureSigner- ? `Every signer must have at least one Signature field before sending. ${missingSignatureSigner.name} is missing one.`- : choiceProblem,+ disabledReason,envelopeId,filename: envelope.sourcePdfFilename,isEmpty,@@ -2529,6 +2629,7 @@ export async function getReviewEnvelopeDataForUser(id: signer.id,name: signer.name,order: signer.signOrder,+ role: signer.role ?? "signer",step: signingStepOf(signer),})),sizeLabel: formatFileSize(envelope.sourcePdfSizeBytes),@@ -2685,16 +2786,13 @@ export async function sendDraftEnvelope();}- const missingSignatureSigner = getMissingSignatureSigner(+ const signingOrderProblem = describeSigningOrderProblem(signers,buildFieldsBySigner(fields),);- if (missingSignatureSigner) {- throw new EnvelopeMutationError(- `Every signer must have at least one Signature field before sending. ${missingSignatureSigner.name} is missing one.`,- 400,- );+ if (signingOrderProblem) {+ throw new EnvelopeMutationError(signingOrderProblem, 400);}const choiceProblem = describeChoiceProblem(signers, fields);@@ -2721,6 +2819,23 @@ 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";+ const hasApprovers = signers.some((signer) => signer.role === "approver");++ // Approvers are SignuDoc's own. In Part 11 mode an approval would be an+ // electronic signature with everything Part 11 asks of one, so the+ // approver signs instead (see PART11_APPROVER_MESSAGE). With signatures+ // through a signing provider, the finished document is the last+ // signer's own signed revision, and an approval makes none.+ if (hasApprovers && part11) {+ throw new EnvelopeMutationError(PART11_APPROVER_MESSAGE, 400);+ }++ if (hasApprovers && signatureLevel !== "simple") {+ throw new EnvelopeMutationError(+ "Approvers work with SignuDoc signatures only. Send with simple signatures, or make the approvers signers.",+ 400,+ );+ }// Signing at the same time is for SignuDoc's own simple signatures.//@@ -3141,6 +3256,7 @@ export async function sendDraftEnvelope(branding,envelopeTitle: envelope.title,expiresAt,+ role: firstSigner.role,senderName: input.senderName,signerEmail: firstSigner.email,signerName: firstSigner.name,@@ -3245,6 +3361,7 @@ export async function sendDraftEnvelope(branding,envelopeTitle: envelope.title,expiresAt,+ role: signer.role,senderName: input.senderName,signerEmail: signer.email,signerName: signer.name,@@ -3546,7 +3663,7 @@ export async function correctSentEnvelopeSigner([signerId, envelopeId],);- if (!signer || signer.role !== "signer") {+ if (!signer || (signer.role !== "signer" && signer.role !== "approver")) {throw new EnvelopeMutationError("Envelope not found.", 404);}@@ -3689,6 +3806,7 @@ export async function correctSentEnvelopeSigner(branding,envelopeTitle: envelope.title,expiresAt: envelope.expiresAt,+ role: signer.role === "approver" ? "approver" : "signer",senderName: context.senderName,signerEmail: nextEmail,signerName: nextName,@@ -3980,7 +4098,7 @@ async function voidSentEnvelopeOnce(// 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'`,+ `SELECT id, status FROM signers WHERE envelope_id = $1 AND role IN ('signer', 'approver')`,[envelopeId],);@@ -4191,6 +4309,11 @@ export async function replaceDraftEnvelopeFields(listFieldsForEnvelopeIds([envelopeId], database),]);const signerIds = new Set(signers.map((signer) => signer.id));+ const approverIds = new Set(+ signers+ .filter((signer) => signer.role === "approver")+ .map((signer) => signer.id),+ );const pageNumbers = new Set(pages.map((page) => page.pageNumber));const existingFields = existingFieldsByEnvelope.get(envelopeId) ?? [];const existingFieldMetadata = new Map(@@ -4208,6 +4331,13 @@ export async function replaceDraftEnvelopeFields();}+ if (approverIds.has(parsedField.signerId)) {+ throw new EnvelopeMutationError(+ "Approvers approve or reject the document and have no fields. Give the field to a signer.",+ 400,+ );+ }+if (!pageNumbers.has(parsedField.page)) {throw new EnvelopeMutationError("Each field must be placed on an existing page in this document.",@@ -4445,6 +4575,7 @@ export async function replaceDraftEnvelopeSigners(id: persistedSignerId,name: signer.name,requireEmailCode: signer.requireEmailCode,+ role: signer.role ?? "signer",signatureMeaning: signer.signatureMeaning,signOrder: index + 1,signingStep: signingSteps[index]!,@@ -4488,7 +4619,8 @@ export async function replaceDraftEnvelopeSigners(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,- signing_step = $12+ signing_step = $12,+ role = $13WHERE id = $5 AND envelope_id = $6`,[@@ -4504,8 +4636,17 @@ export async function replaceDraftEnvelopeSigners(signer.signatureMeaning !== undefined,signer.signatureMeaning ?? null,signer.signingStep,+ signer.role,],);++ // Someone who becomes an approver has no fields any more.+ if (signer.role === "approver") {+ await tx.query(+ `DELETE FROM fields WHERE envelope_id = $1 AND signer_id = $2`,+ [envelopeId, signer.id],+ );+ }} else {await tx.query(`@@ -4529,9 +4670,10 @@ export async function replaceDraftEnvelopeSigners(access_code_hash,require_email_code,signature_meaning,- signing_step+ signing_step,+ role) VALUES (- $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10, $11+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10, $11, $12)`,[@@ -4546,6 +4688,7 @@ export async function replaceDraftEnvelopeSigners(signer.requireEmailCode ?? false,signer.signatureMeaning ?? null,signer.signingStep,+ signer.role,],);}@@ -4606,6 +4749,7 @@ export async function replaceDraftEnvelopeSigners(id: signer.id,name: signer.name,requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,+ role: signer.role ?? "signer",signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,signOrder: signer.signOrder,signingStep: signingStepOf(signer),diff --git a/src/lib/reminders.ts b/src/lib/reminders.tsindex 64c1cdb..14962b3 100644--- a/src/lib/reminders.ts+++ b/src/lib/reminders.ts@@ -29,7 +29,10 @@ import {isEmailNotConnectedError,type EmailService,} from "./services/email.ts";-import { buildDeadlineLine } from "./services/signing-invitation-email.ts";+import {+ buildDeadlineLine,+ describeRequestedAction,+} from "./services/signing-invitation-email.ts";import { isEmbeddedEnvelope } from "./embedding.ts";import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";import {@@ -63,6 +66,7 @@ type ReminderSignerRow = {lastNotifiedAt: number | null;lastNudgedAt: number | null;name: string;+ role: string;signOrder: number;signingTokenExpiresAt: number | null;signingTokenHash: string | null;@@ -105,6 +109,8 @@ type PersistedReminder = {signerEmail: string;signerId: string;signerName: string;+ /** An approver is reminded to approve, not to sign. */+ signerRole: "approver" | "signer";senderName: string;userId: string;};@@ -218,6 +224,7 @@ async function getCurrentSignerForEnvelope(envelope_id AS "envelopeId",name,email,+ role,sign_order AS "signOrder",status,signing_token_hash AS "signingTokenHash",@@ -245,34 +252,36 @@ function buildReminderEmail(input: {senderName: string;signerEmail: string;signerName: string;+ signerRole?: "approver" | "signer";signingUrl: string;}) {const automatic = input.kind === "automatic";+ const action = describeRequestedAction(input.signerRole);const subject = automatic- ? `Reminder: ${input.senderName} is waiting for your signature on "${input.envelopeTitle}"`- : `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}"`;+ ? `Reminder: ${input.senderName} is waiting for your ${action.noun} on "${input.envelopeTitle}"`+ : `${input.senderName} sent you a reminder to ${action.verb} "${input.envelopeTitle}"`;const introLine = automatic- ? `${input.senderName} is still waiting for your signature on "${input.envelopeTitle}", sent through ${input.branding.productName}.`- : `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}" through ${input.branding.productName}.`;+ ? `${input.senderName} is still waiting for your ${action.noun} on "${input.envelopeTitle}", sent through ${input.branding.productName}.`+ : `${input.senderName} sent you a reminder to ${action.verb} "${input.envelopeTitle}" through ${input.branding.productName}.`;const deadlineLine = buildDeadlineLine(input.expiresAt);const textBody = [`Hi ${input.signerName},`,"",introLine,"",- "Review and sign the document here:",+ `${action.linkText} here:`,input.signingUrl,...(deadlineLine ? ["", deadlineLine] : []),"",- `You do not need a ${input.branding.productName} account to sign.`,+ `You do not need a ${input.branding.productName} account to ${action.accountLine}.`,"If you receive a newer invitation or reminder link, use the newest one.",].join("\n");const htmlBody = [`<p>Hi ${escapeHtml(input.signerName)},</p>`,`<p>${escapeHtml(introLine)}</p>`,- `<p><a href="${escapeHtml(input.signingUrl)}">Review and sign the document</a></p>`,+ `<p><a href="${escapeHtml(input.signingUrl)}">${escapeHtml(action.linkText)}</a></p>`,deadlineLine ? `<p>${escapeHtml(deadlineLine)}</p>` : "",- `<p>You do not need a ${escapeHtml(input.branding.productName)} account to sign.</p>`,+ `<p>You do not need a ${escapeHtml(input.branding.productName)} account to ${action.accountLine}.</p>`,"<p>If you receive a newer invitation or reminder link, use the newest one.</p>",].join("");const legalFooter = withUserEmailLegalFooter(@@ -540,6 +549,7 @@ async function persistReminder(signerEmail: persistedSigner.email,signerId: persistedSigner.id,signerName: persistedSigner.name,+ signerRole: persistedSigner.role === "approver" ? "approver" : "signer",userId: persistedEnvelope.userId,};}, database);@@ -570,6 +580,7 @@ async function deliverReminder(senderName: persisted.senderName,signerEmail: persisted.signerEmail,signerName: persisted.signerName,+ signerRole: persisted.signerRole,signingUrl: persisted.issuedLink.url,}),)diff --git a/src/lib/schemas/signer.ts b/src/lib/schemas/signer.tsindex 8e6bb3a..fe4decd 100644--- a/src/lib/schemas/signer.ts+++ b/src/lib/schemas/signer.ts@@ -3,6 +3,7 @@ import { z } from "zod";import {MAX_COPY_RECIPIENTS_PER_ENVELOPE,MAX_SIGNERS_CEILING,+ recipientRoles,signatureMeanings,signerStatuses,} from "../types/domain.ts";@@ -15,6 +16,7 @@ import {} from "./common.ts";export const signerStatusSchema = z.enum(signerStatuses);+export const recipientRoleSchema = z.enum(recipientRoles);export const duplicateSignerEmailMessage ="Each signer must have a unique email address.";export const duplicateCopyRecipientEmailMessage =@@ -33,6 +35,9 @@ export const draftSignerSchema = z.object({name: nameSchema,email: emailSchema,signOrder: z.number().int().positive().optional(),+ // A signer, or an approver who reviews the document and approves or+ // rejects it without fields of their own. Left out means a signer.+ role: recipientRoleSchema.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.@@ -133,6 +138,7 @@ export const replaceSignersResponseSchema = z.object({hasAccessCode: z.boolean(),name: nameSchema,requireEmailCode: z.boolean(),+ role: recipientRoleSchema,signatureMeaning: z.enum(signatureMeanings).nullable(),signOrder: z.number().int().positive(),signingStep: z.number().int().positive(),diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.tsindex 7a0e063..95e71ec 100644--- a/src/lib/schemas/signing.ts+++ b/src/lib/schemas/signing.ts@@ -107,7 +107,11 @@ export const signingPayloadSchema = z.object({id: idSchema,name: nameSchema,order: z.number().int().positive(),+ // An approver approves or rejects; there are no fields to fill in.+ role: z.enum(["signer", "approver"]).optional(),}),+ /** Where an approver's approval is sent. */+ approveUrl: z.string().trim().min(1).optional(),state: z.literal("ready"),submitUrl: z.string().trim().min(1),visibleFields: z.array(signingVisibleFieldSchema),@@ -164,6 +168,11 @@ export const signerConsentRequestSchema = z.object({disclosureVersion: z.string().trim().min(1).max(40),});+/** An approver's approval. There is nothing else to send. */+export const approvalSubmissionSchema = z.object({+ clientTimezoneOffsetMinutes: z.number().int().min(-840).max(840),+});+export type SigningVerificationState = {emailCodeSentAt: number | null;envelopeTitle: string;diff --git a/src/lib/schemas/template.ts b/src/lib/schemas/template.tsindex f266f63..062bbb0 100644--- a/src/lib/schemas/template.ts+++ b/src/lib/schemas/template.ts@@ -1,6 +1,10 @@import { z } from "zod";-import { MAX_SIGNERS_CEILING, signatureMeanings } from "../types/domain.ts";+import {+ MAX_SIGNERS_CEILING,+ recipientRoles,+ signatureMeanings,+} from "../types/domain.ts";import {emailSchema,envelopeTitleSchema,@@ -27,6 +31,9 @@ export const templateRoleSchema = z.object({// 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(),+ // Whether the person in this role signs or only approves. Templates+ // saved before approvers existed have none, and every role signs.+ kind: z.enum(recipientRoles).optional(),});/** A template's roles, in the order their people will sign. */diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 52d6fe2..d16d880 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -1067,9 +1067,26 @@ function buildAuditLines(input: {},);- pushParagraph("Signers", input.fonts.bold, sectionFontSize, {- gapAfter: 4,- });+ const approvers = input.signers.filter(+ (signer) => signer.role === "approver",+ );++ pushParagraph(+ approvers.length > 0 ? "Signers and approvers" : "Signers",+ input.fonts.bold,+ sectionFontSize,+ {+ gapAfter: 4,+ },+ );++ if (approvers.length > 0) {+ pushParagraph(+ "Approvers reviewed the document and approved or rejected it. They placed no signature and nothing of theirs is stamped on the document.",+ input.fonts.regular,+ bodyFontSize,+ );+ }// 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@@ -1086,9 +1103,10 @@ function buildAuditLines(input: {for (const signer of input.signers) {const actionLabel = getSignerCertificateActionLabel(input.envelope, signer);const step = signingStepOf(signer);+ const roleLabel = signer.role === "approver" ? " | Approver" : "";const signerLabel = input.redactForRecipients- ? `${step}. ${signer.name} | ${actionLabel}`- : `${step}. ${signer.name} <${signer.email}> | ${actionLabel}`;+ ? `${step}. ${signer.name}${roleLabel} | ${actionLabel}`+ : `${step}. ${signer.name} <${signer.email}>${roleLabel} | ${actionLabel}`;pushParagraph(signerLabel, input.fonts.regular, bodyFontSize);@@ -1101,6 +1119,34 @@ function buildAuditLines(input: {}}+ // Approvals on their own, so they are never read as signatures.+ const decided = approvers.filter(+ (signer) => signer.status === "signed" || signer.status === "declined",+ );++ if (decided.length > 0) {+ pushParagraph("Approvals", input.fonts.bold, sectionFontSize, {+ gapAfter: 4,+ gapBefore: 10,+ });++ for (const approver of decided) {+ const who = input.redactForRecipients+ ? approver.name+ : `${approver.name} <${approver.email}>`;++ pushParagraph(+ approver.status === "signed"+ ? `Approved by ${who} at ${formatAuditTimestamp(approver.signedAt)}`+ : `Rejected by ${who} at ${formatAuditTimestamp(approver.declinedAt)}${+ approver.declineReason ? `: ${approver.declineReason}` : ""+ }`,+ input.fonts.regular,+ bodyFontSize,+ );+ }+ }+if (input.copyRecipients && input.copyRecipients.length > 0) {pushParagraph("Copy recipients", input.fonts.bold, sectionFontSize, {gapAfter: 4,@@ -1295,7 +1341,16 @@ function describeSignerEvidence((event) => event.metadata?.signerId === signer.id,);const details: string[] = [];- const signed = forSigner.find((event) => event.event === "signed");+ const approver = signer.role === "approver";+ // The signature, or an approver's approval.+ const signed = forSigner.find(+ (event) => event.event === (approver ? "approved" : "signed"),+ );+ // A decline or a rejection, which also say which checks the person had+ // passed.+ const ended = forSigner.find(+ (event) => event.event === "declined" || event.event === "rejected",+ );// A correction clears the row's consent. The first consented event for// this signer id can still be the previous person's, so only agreement// recorded after the latest standing correction counts as this@@ -1313,11 +1368,14 @@ function describeSignerEvidence(}}- // A signer who declined in another app has no signed event; the- // declined event carries the same record of where it happened.+ // A signer who declined, or an approver who rejected, in another app has+ // no signed event; the declined or rejected event carries the same record+ // of where it happened.const declined =signed === undefined && signer.status === "declined"- ? forSigner.findLast((event) => event.event === "declined")+ ? forSigner.findLast(+ (event) => event.event === "declined" || event.event === "rejected",+ ): undefined;const embeddedSource = signed ?? declined;const embedded =@@ -1329,7 +1387,7 @@ function describeSignerEvidence(embedded? describeEmbeddedDelivery(embedded): "possession of the emailed signing link",- ...readStringArray(signed?.metadata?.authMethods).map(+ ...readStringArray((signed ?? ended)?.metadata?.authMethods).map((method) => AUTHENTICATION_LABELS[method] ?? method,),];@@ -1378,7 +1436,9 @@ function describeSignerEvidence(details.push(...describeProviderSignatureEvidence(signed, redacted));if (!redacted && signed?.ipAddress) {- details.push(`Signed from IP ${signed.ipAddress}`);+ details.push(+ `${approver ? "Approved" : "Signed"} from IP ${signed.ipAddress}`,+ );}return details;@@ -1460,21 +1520,25 @@ function getSignerCertificateActionLabel(envelope: EnvelopeRecord,signer: SignerRecord,): string {+ // An approver's turn done is an approval, and their decline a rejection.+ const approver = signer.role === "approver";+ const awaiting = approver ? "Awaiting approval" : "Awaiting signature";+switch (signer.status) {case "signed":- return `Signed at ${formatAuditTimestamp(signer.signedAt)}`;+ return `${approver ? "Approved" : "Signed"} at ${formatAuditTimestamp(signer.signedAt)}`;case "declined":- return `Declined at ${formatAuditTimestamp(signer.declinedAt)}`;+ return `${approver ? "Rejected" : "Declined"} at ${formatAuditTimestamp(signer.declinedAt)}`;case "notified":if (envelope.status === "voided") {- return "Awaiting signature when envelope was voided";+ return `${awaiting} when envelope was voided`;}if (envelope.status === "declined") {- return "Awaiting signature when envelope was declined";+ return `${awaiting} when envelope was declined`;}- return "Awaiting signature";+ return awaiting;case "pending":return "Not reached";default: {diff --git a/src/lib/services/signing-invitation-email.ts b/src/lib/services/signing-invitation-email.tsindex b57f220..3e7c933 100644--- a/src/lib/services/signing-invitation-email.ts+++ b/src/lib/services/signing-invitation-email.ts@@ -9,6 +9,8 @@ type SigningInvitationEmailInput = {envelopeTitle: string;/** The envelope's deadline, when it has one. */expiresAt?: number | null;+ /** An approver is asked to approve, not to sign. A signer by default. */+ role?: "approver" | "signer";senderName: string;signerEmail: string;signerName: string;@@ -24,30 +26,50 @@ export function buildDeadlineLine(: null;}+/** What the person is asked to do, in the invitation and the reminders. */+export function describeRequestedAction(+ role: "approver" | "signer" = "signer",+) {+ return role === "approver"+ ? {+ accountLine: "approve",+ linkText: "Review and approve or reject the document",+ noun: "approval",+ verb: "approve",+ }+ : {+ accountLine: "sign",+ linkText: "Review and sign the document",+ noun: "signature",+ verb: "sign",+ };+}+export function buildSigningInvitationEmail(input: SigningInvitationEmailInput,): TransactionalEmailMessage {const { productName } = input.branding;- const subject = `${input.senderName} requested your signature on "${input.envelopeTitle}"`;+ const action = describeRequestedAction(input.role);+ const subject = `${input.senderName} requested your ${action.noun} on "${input.envelopeTitle}"`;const deadlineLine = buildDeadlineLine(input.expiresAt);const textBody = [`Hi ${input.signerName},`,"",`${input.senderName} sent you "${input.envelopeTitle}" through ${productName}.`,"",- "Review and sign the document here:",+ `${action.linkText} here:`,input.signingUrl,...(deadlineLine ? ["", deadlineLine] : []),"",- `You do not need a ${productName} account to sign.`,+ `You do not need a ${productName} account to ${action.accountLine}.`,"If you receive a newer invitation or reminder link, use the newest one.",].join("\n");const htmlBody = [`<p>Hi ${escapeHtml(input.signerName)},</p>`,`<p>${escapeHtml(input.senderName)} sent you “${escapeHtml(input.envelopeTitle)}” through ${escapeHtml(productName)}.</p>`,- `<p><a href="${escapeHtml(input.signingUrl)}">Review and sign the document</a></p>`,+ `<p><a href="${escapeHtml(input.signingUrl)}">${escapeHtml(action.linkText)}</a></p>`,deadlineLine ? `<p>${escapeHtml(deadlineLine)}</p>` : "",- `<p>You do not need a ${escapeHtml(productName)} account to sign.</p>`,+ `<p>You do not need a ${escapeHtml(productName)} account to ${action.accountLine}.</p>`,"<p>If you receive a newer invitation or reminder link, use the newest one.</p>",].join("");const legalFooter = withUserEmailLegalFooter(diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex e8961bb..5ffd749 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -28,6 +28,7 @@ import {type SigningSubmission,} from "./schemas/field.ts";import {+ approvalSubmissionSchema,signerCheckRequestSchema,signerConsentRequestSchema,signingFieldFitRequestSchema,@@ -180,6 +181,7 @@ type SigningSignerRow = {lastNotifiedAt: number | null;lastNudgedAt: number | null;name: string;+ role: "approver" | "signer";signOrder: number;signingStep: number | null;signatureMeaning:@@ -307,6 +309,11 @@ export class SigningAccessError extends Error {}}+/** An approver reviews and approves or rejects; they sign nothing. */+function isApprover(signer: { role?: string | null }): boolean {+ return signer.role === "approver";+}+function getSigningUnavailableMessage(state: SigningUnavailableResponse["state"],): string {@@ -337,6 +344,10 @@ function getSigningConsentUrl(token: string): string {return `/api/signing/${encodeURIComponent(token)}/consent`;}+function getSigningApproveUrl(token: string): string {+ return `/api/signing/${encodeURIComponent(token)}/approve`;+}+function getSigningFieldFitUrl(token: string): string {return `/api/signing/${encodeURIComponent(token)}/fit`;}@@ -348,11 +359,16 @@ function getSigningDeclineUrl(token: string): string {function getSigningDoneRedirectPath(token: string,envelopeTitle: string,+ approved = false,): string {const searchParams = new URLSearchParams();searchParams.set("title", envelopeTitle);+ if (approved) {+ searchParams.set("approved", "1");+ }+return `/sign/${encodeURIComponent(token)}/done?${searchParams.toString()}`;}@@ -415,20 +431,23 @@ function buildDeclineNotificationEmail(input: {declineReason?: string;envelopeId: string;envelopeTitle: string;+ /** An approver rejected it, rather than a signer declining. */+ rejected?: boolean;senderEmail: string;senderName: string;signerEmail: string;signerName: string;}) {const envelopeUrl = getEnvelopeUrl(input.envelopeId);- const subject = `"${input.envelopeTitle}" was declined by ${input.signerName}`;+ const verb = input.rejected ? "rejected" : "declined";+ const subject = `"${input.envelopeTitle}" was ${verb} by ${input.signerName}`;const reasonLine = input.declineReason?.trim()? `Reason provided: ${input.declineReason.trim()}`: null;const textBody = [`Hi ${input.senderName},`,"",- `${input.signerName} (${input.signerEmail}) declined "${input.envelopeTitle}" in ${input.branding.productName}.`,+ `${input.signerName} (${input.signerEmail}) ${verb} "${input.envelopeTitle}" in ${input.branding.productName}.`,...(reasonLine ? ["", reasonLine] : []),"","Review the envelope:",@@ -436,7 +455,7 @@ function buildDeclineNotificationEmail(input: {].join("\n");const htmlBody = [`<p>Hi ${escapeHtml(input.senderName)},</p>`,- `<p>${escapeHtml(input.signerName)} (${escapeHtml(input.signerEmail)}) declined “${escapeHtml(input.envelopeTitle)}” in ${escapeHtml(input.branding.productName)}.</p>`,+ `<p>${escapeHtml(input.signerName)} (${escapeHtml(input.signerEmail)}) ${verb} “${escapeHtml(input.envelopeTitle)}” in ${escapeHtml(input.branding.productName)}.</p>`,reasonLine? `<p><strong>Reason provided:</strong> ${escapeHtml(input.declineReason!.trim())}</p>`: "",@@ -606,6 +625,7 @@ async function listSignerRows(envelope_id AS "envelopeId",name,email,+ role,sign_order AS "signOrder",signing_step AS "signingStep",status,@@ -623,8 +643,9 @@ async function listSignerRows(updated_at AS "updatedAt"FROM signersWHERE envelope_id = $1- -- Copy recipients are not part of the signing order.- AND role = 'signer'+ -- Copy recipients are not part of the signing order. Approvers+ -- are, and move it on exactly as signers do.+ AND role IN ('signer', 'approver')ORDER BY sign_order ASC, id ASC`,[envelopeId],@@ -1044,12 +1065,16 @@ function buildSignedAuditEvent(input: {submittedAt: number;timezoneOffsetMinutes: number;}): AuditEventRecord {+ // An approver's decision is its own event, never "signed": the audit+ // trail and the certificate must not show an approval as a signature.+ const approval = isApprover(input.signer);+return {actorEmail: input.signer.email,actorType: "signer",createdAt: input.submittedAt,envelopeId: input.envelopeId,- event: "signed",+ event: approval ? "approved" : "signed",id: randomUUID(),ipAddress: input.requestMeta.ipAddress ?? null,metadata: {@@ -1058,6 +1083,7 @@ function buildSignedAuditEvent(input: {signerName: input.signer.name,signerOrder: input.signer.signOrder,signingStep: signingStepOf(input.signer),+ ...(approval ? { role: "approver" } : {}),authMethods: [...input.authMethods],signatureMethods: [...input.signatureMethods],timezoneOffsetMinutes: input.timezoneOffsetMinutes,@@ -1072,6 +1098,8 @@ function buildSignedAuditEvent(input: {}function buildDeclinedAuditEvent(input: {+ /** The checks the person passed before declining or rejecting. */+ authMethods: readonly string[];declinedAt: number;embedded?: { apiKeyName: string | null; origin: string | null } | null;envelopeId: string;@@ -1084,7 +1112,8 @@ function buildDeclinedAuditEvent(input: {actorType: "signer",createdAt: input.declinedAt,envelopeId: input.envelopeId,- event: "declined",+ // An approver rejects; the envelope ends the same way as a decline.+ event: isApprover(input.signer) ? "rejected" : "declined",id: randomUUID(),ipAddress: input.requestMeta.ipAddress ?? null,metadata: {@@ -1095,6 +1124,8 @@ function buildDeclinedAuditEvent(input: {signerOrder: input.signer.signOrder,signingStep: signingStepOf(input.signer),...(input.embedded ? { embedded: input.embedded } : {}),+ ...(isApprover(input.signer) ? { role: "approver" } : {}),+ authMethods: [...input.authMethods],},userAgent: input.requestMeta.userAgent ?? null,};@@ -2005,7 +2036,10 @@ async function resolveSigningContext(}if (signer.status === "signed") {- throw new SigningAccessError("already-signed");+ throw new SigningAccessError(+ "already-signed",+ isApprover(signer) ? "You've already approved this document." : undefined,+ );}if (typeof signer.signOrder !== "number") {@@ -2171,7 +2205,11 @@ export async function getSigningPayloadForToken(id: context.signer.id,name: context.signer.name,order: context.signer.signOrder,+ role: isApprover(context.signer) ? "approver" : "signer",},+ ...(isApprover(context.signer)+ ? { approveUrl: getSigningApproveUrl(token) }+ : {}),state: "ready",submitUrl: getSigningSubmitUrl(token),visibleFields,@@ -2414,6 +2452,28 @@ function buildSignerSubmission(field.signerId === currentSignerId && typeof field.id === "string",);+ // An approver has no fields: saving fields and sending both refuse one+ // that does, and so does the database. Should one turn up all the same,+ // nothing is approved, rather than leaving their fields empty.+ if (isApprover(context.signer)) {+ if (currentSignerFields.length > 0) {+ throw new SigningMutationError(+ "This document has fields for an approver. Ask the sender to send it again.",+ 409,+ );+ }++ return {+ currentSignerFields,+ currentSignerId,+ drawnSignatureUploads: [] as Array<{+ body: Uint8Array;+ imageKey: string;+ }>,+ fieldUpdates: new Map<string, FieldPersistenceUpdate>(),+ };+ }+if (currentSignerFields.length === 0) {throw new SigningMutationError("No signable fields are assigned to this signer.",@@ -2646,7 +2706,27 @@ export async function submitSigningForToken(input: unknown,options: SubmitSigningOptions = {},): Promise<SigningSubmitResponse> {- return retryWhileRouteChanges(() => submitSigningOnce(token, input, options));+ return retryWhileRouteChanges(() =>+ submitSigningOnce(token, input, options, { approval: false }),+ );+}++/**+ * An approver approves. Everything a signature goes through applies, from+ * the checks and the consent to the locking and the restart when the route+ * changed underneath it, so of a signer and an approver of one step who+ * finish at the same moment exactly one moves the order on, as with two+ * signers. Only what is recorded differs: no fields, and an "approved"+ * event instead of "signed".+ */+export async function approveSigningForToken(+ token: string,+ input: unknown,+ options: Omit<SubmitSigningOptions, "providerSignature"> = {},+): Promise<SigningSubmitResponse> {+ return retryWhileRouteChanges(() =>+ submitSigningOnce(token, input, options, { approval: true }),+ );}async function submitSigningOnce(@@ -2661,8 +2741,14 @@ async function submitSigningOnce(verifiedMethods = [],verifyPassword,}: SubmitSigningOptions = {},+ { approval }: { approval: boolean },): Promise<SigningSubmitResponse> {- const parsedInput = signingSubmissionSchema.parse(input);+ const parsedInput: SigningSubmission = approval+ ? {+ ...approvalSubmissionSchema.parse(input),+ fields: [],+ }+ : signingSubmissionSchema.parse(input);const context = await resolveSigningContext(token, { database });// Signed inside another app: no email to the next signer, and the// evidence says where.@@ -2670,12 +2756,38 @@ async function submitSigningOnce(? await readEmbedEvidence(context.envelope.id, context.signer.id, database): null;const doneRedirectPath = embedded?.origin- ? `/embed/sign/${encodeURIComponent(token)}/done?${new URLSearchParams({ origin: embedded.origin, title: context.envelope.title }).toString()}`- : getSigningDoneRedirectPath(token, context.envelope.title);+ ? `/embed/sign/${encodeURIComponent(token)}/done?${new URLSearchParams({ origin: embedded.origin, title: context.envelope.title, ...(approval ? { approved: "1" } : {}) }).toString()}`+ : getSigningDoneRedirectPath(token, context.envelope.title, approval);++ if (approval !== isApprover(context.signer)) {+ throw new SigningMutationError(+ approval+ ? "This link is for signing, not approving."+ : "This link is for approving. Approve or reject the document from the page.",+ 409,+ );+ }++ // Approvers are refused at sending on Part 11 envelopes and on envelopes+ // signed through a signing provider (envelopes.ts). Checked again here so+ // an approval can never stand where one of those signatures belongs.+ if (+ approval &&+ (context.envelope.part11 ||+ (context.envelope.signatureLevel ?? "simple") !== "simple" ||+ providerSignature)+ ) {+ throw new SigningMutationError(+ "This document cannot be approved here. Ask the sender to send it again.",+ 409,+ );+ }// A document sent for advanced or qualified signatures is signed by each// signer's provider, never by a plain submit, and the other way round.- if ((context.envelope.signatureLevel ?? "simple") === "simple") {+ if (approval) {+ // Nothing to check: no provider is involved in an approval.+ } else if ((context.envelope.signatureLevel ?? "simple") === "simple") {if (providerSignature) {throw new SigningMutationError("This document is not signed through a signing provider.",@@ -2747,6 +2859,7 @@ async function submitSigningOnce(email: string;id: string;name: string;+ role: "approver" | "signer";url: string;}[] = [];@@ -2922,6 +3035,7 @@ async function submitSigningOnce(const activatedNextSigner = await queryOne<{email: string;name: string;+ role: "approver" | "signer";}>(tx,`@@ -2935,9 +3049,9 @@ async function submitSigningOnce(updated_at = $5WHERE id = $6AND envelope_id = $7- AND role = 'signer'+ AND role IN ('signer', 'approver')AND status = 'pending'- RETURNING name, email+ RETURNING name, email, role`,[link.tokenHash,@@ -2961,6 +3075,7 @@ async function submitSigningOnce(email: activatedNextSigner.email,id: nextSigner.id,name: activatedNextSigner.name,+ role: activatedNextSigner.role,url: link.url,});}@@ -2997,6 +3112,7 @@ async function submitSigningOnce(branding: await getBranding(),envelopeTitle: context.envelope.title,expiresAt: nextSignerDeadline,+ role: nextSignerDelivery.role,senderName: normalizeSenderName(context.sender),signerEmail: nextSignerDelivery.email,signerName: nextSignerDelivery.name,@@ -3096,7 +3212,7 @@ async function submitSigningOnce(`SELECT id FROM signersWHERE envelope_id = $1- AND role = 'signer'+ AND role IN ('signer', 'approver')AND id <> $2AND status <> 'signed'LIMIT 1@@ -3367,7 +3483,10 @@ export async function prepareSignerSubmission(const parsedInput = signingSubmissionSchema.parse(input);const context = await resolveSigningContext(token, { database });- if ((context.envelope.signatureLevel ?? "simple") === "simple") {+ if (+ (context.envelope.signatureLevel ?? "simple") === "simple" ||+ isApprover(context.signer)+ ) {throw new SigningMutationError("This document is not signed through a signing provider.",409,@@ -3431,7 +3550,11 @@ async function declineSigningOnce(const parsedInput = declineEnvelopeSchema.parse(input);const context = await resolveSigningContext(token, { database });- await assertSignerChecksPassed(context, verifiedMethods, database);+ const signerChecks = await assertSignerChecksPassed(+ context,+ verifiedMethods,+ database,+ );const emailService = createLazyEmailService();const storageService = createStorageService();const currentSignerId = context.signer.id;@@ -3465,6 +3588,7 @@ async function declineSigningOnce(database,);const declinedAuditEvent = buildDeclinedAuditEvent({+ authMethods: signerChecks.passed,declinedAt,embedded,envelopeId: context.envelope.id,@@ -3548,7 +3672,7 @@ async function declineSigningOnce(const statusesNow = await tx.query<{ id: string; status: string }>(`SELECT id, status FROM signers- WHERE envelope_id = $1 AND role = 'signer' AND id <> $2+ WHERE envelope_id = $1 AND role IN ('signer', 'approver') AND id <> $2`,[context.envelope.id, currentSignerId],);@@ -3712,6 +3836,7 @@ async function declineSigningOnce(declineReason,envelopeId: context.envelope.id,envelopeTitle: context.envelope.title,+ rejected: isApprover(context.signer),senderEmail: context.sender.email,senderName: normalizeSenderName(context.sender),signerEmail: context.signer.email,diff --git a/src/lib/templates.ts b/src/lib/templates.tsindex d6c3e7b..9fbea2f 100644--- a/src/lib/templates.ts+++ b/src/lib/templates.ts@@ -374,11 +374,13 @@ 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.+ // time still do when the template is used, and whether they sign or+ // approve.const steps = normalizeSigningSteps(signers.map((signer) => signer.step));const roles = templateRolesSchema.parse(roleNames.map((name, index) => ({id: randomUUID(),+ kind: signers[index]?.role ?? "signer",name,step: steps[index],})),@@ -571,6 +573,7 @@ export async function createDraftFromTemplate(// steps existed has none, and its people sign one after the other.signers: parsedInput.signers.map((signer, index) => ({...signer,+ role: roles.data[index]?.kind ?? "signer",...(roleSteps ? { signingStep: roleSteps[index] } : {}),})),},diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.tsindex 670a859..ba1984d 100644--- a/src/lib/types/domain.ts+++ b/src/lib/types/domain.ts@@ -85,8 +85,18 @@ export const auditEventTypes = ["reauthentication_failed","copied","signer_corrected",+ "approved",+ "rejected",] as const;+/**+ * What a person in the signing order does. A signer fills in and signs+ * their fields; an approver reviews the document and approves or rejects+ * it, with no fields of their own. Copy recipients are kept apart (role+ * 'cc') and are never in the signing order.+ */+export const recipientRoles = ["signer", "approver"] as const;+/*** What a signature means, for Part 11 envelopes (21 CFR 11.50(a)(3)). The* sender picks one for each signer, and it is printed beside the signature.@@ -125,6 +135,7 @@ export const emailTemplateKinds = [export type EnvelopeStatus = (typeof envelopeStatuses)[number];export type SignerStatus = (typeof signerStatuses)[number];+export type RecipientRole = (typeof recipientRoles)[number];export type FieldType = (typeof fieldTypes)[number];export type FieldInputMethod = (typeof fieldInputMethods)[number];export type AuditEventType = (typeof auditEventTypes)[number];diff --git a/src/lib/webhooks/events.ts b/src/lib/webhooks/events.tsindex 6155257..066b4f8 100644--- a/src/lib/webhooks/events.ts+++ b/src/lib/webhooks/events.ts@@ -19,10 +19,15 @@ export type WebhookEventType = (typeof webhookEventTypes)[number];/** Sent only by the "Send test" button, never by an envelope. */export const WEBHOOK_TEST_EVENT = "webhook.test";+// An approver's approval is reported as their signature and a rejection as+// a decline, which is how each moves the envelope on or ends it. The signer+// in the payload has role "approver".const fromAuditEvent: Partial<Record<AuditEventType, WebhookEventType>> = {+ approved: "signer.signed",completed: "envelope.completed",declined: "envelope.declined",expired: "envelope.expired",+ rejected: "envelope.declined",sent: "envelope.sent",signed: "signer.signed",viewed: "signer.viewed",diff --git a/src/lib/webhooks/webhooks.test.ts b/src/lib/webhooks/webhooks.test.tsindex ef84033..fab1e43 100644--- a/src/lib/webhooks/webhooks.test.ts+++ b/src/lib/webhooks/webhooks.test.ts@@ -22,6 +22,9 @@ test("audit events map to webhook events, and others to none", () => {assert.equal(webhookEventForAuditEvent("sent"), "envelope.sent");assert.equal(webhookEventForAuditEvent("viewed"), "signer.viewed");assert.equal(webhookEventForAuditEvent("completed"), "envelope.completed");+ // An approver's approval and rejection.+ assert.equal(webhookEventForAuditEvent("approved"), "signer.signed");+ assert.equal(webhookEventForAuditEvent("rejected"), "envelope.declined");assert.equal(webhookEventForAuditEvent("email_sent"), null);assert.equal(webhookEventForAuditEvent("consented"), null);});