Skip to content

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

TypeScript

Let a sender correct a signer's email after sending

Matt Van Horn5bcc9ac46749
diff --git a/db/migrations/20261116090000_signer_corrected.sql b/db/migrations/20261116090000_signer_corrected.sql
new file mode 100644
index 0000000..1648008
--- /dev/null
+++ b/db/migrations/20261116090000_signer_corrected.sql
@@ -0,0 +1,27 @@
+-- Sender correction of a waiting signer's name or email after send.
+-- A new audit event kind records the old and new values in the hash chain.
+
+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',
+ 'signer_corrected'
+ ));
diff --git a/src/app/api/envelopes/[id]/signers/[signerId]/route.ts b/src/app/api/envelopes/[id]/signers/[signerId]/route.ts
new file mode 100644
index 0000000..5bb40f8
--- /dev/null
+++ b/src/app/api/envelopes/[id]/signers/[signerId]/route.ts
@@ -0,0 +1,110 @@
+import { NextResponse } from "next/server";
+import { ZodError } from "zod";
+
+import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
+import { getDb } from "@/lib/db/connection";
+import {
+ correctSentEnvelopeSigner,
+ EnvelopeMutationError,
+} from "@/lib/envelopes";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+
+type EnvelopeSignerCorrectionRouteContext = {
+ params: Promise<{
+ id: string;
+ signerId: string;
+ }>;
+};
+
+const noStore = { "cache-control": "private, no-store" };
+
+// Fixes the name and/or email of a signer who has not signed or declined
+// on an envelope that is out for signature.
+export async function PATCH(
+ request: Request,
+ context: EnvelopeSignerCorrectionRouteContext,
+) {
+ const sessionResult = await requireVerifiedSenderSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const { id, signerId } = await context.params;
+ const ipAddress = getClientIpAddress(request.headers);
+ const rateLimitResponse = await applyRateLimit({
+ category: "sent_envelope_signer_correct",
+ key: buildRateLimitKey(["envelope-signer-correct", session.user.id, id]),
+ limit: 20,
+ request,
+ userId: session.user.id,
+ windowMs: 60 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ rateLimitResponse.headers.set("cache-control", "private, no-store");
+ return rateLimitResponse;
+ }
+
+ const body = (await request.json().catch(() => null)) as unknown;
+
+ try {
+ const result = await correctSentEnvelopeSigner(
+ session.user.id,
+ id,
+ signerId,
+ body,
+ {
+ ipAddress,
+ senderEmail: session.user.email,
+ senderName:
+ typeof session.user.name === "string" && session.user.name.trim()
+ ? session.user.name
+ : session.user.email,
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ { database: getDb() },
+ );
+
+ return NextResponse.json(result, { headers: noStore, status: 200 });
+ } catch (error) {
+ if (error instanceof ZodError) {
+ const issue = error.issues[0];
+
+ return NextResponse.json(
+ { error: issue?.message ?? "Invalid signer correction." },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ if (error instanceof EnvelopeMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "sent_envelope_signer_correct_failure",
+ ipAddress,
+ message: "Unexpected failure while correcting a signer.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "Unable to correct this signer." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index fd0be9a..bc57feb 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -5,6 +5,7 @@ import {
ClockIcon,
DownloadIcon,
MinusIcon,
+ PencilIcon,
XIcon,
type LucideIcon,
} from "lucide-react";
@@ -71,6 +72,7 @@ type EnvelopeDetailRecord = {
type ModalState =
| "change-deadline"
| "change-reminders"
+ | "correct-signer"
| "delete-draft"
| "save-template"
| "void-envelope"
@@ -129,9 +131,12 @@ export function EnvelopeDetailShell({
const [actionError, setActionError] = useState<string | null>(null);
const [isChangingDeadline, setIsChangingDeadline] = useState(false);
const [isChangingReminders, setIsChangingReminders] = useState(false);
+ const [isCorrectingSigner, setIsCorrectingSigner] = useState(false);
const [isDeletingDraft, setIsDeletingDraft] = useState(false);
const [isSendingReminder, setIsSendingReminder] = useState(false);
const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);
+ const [correctingSigner, setCorrectingSigner] =
+ useState<EnvelopeDetailSigner | null>(null);
const [voidReason, setVoidReason] = useState("");
const [savedTemplateName, setSavedTemplateName] = useState<string | null>(
null,
@@ -285,6 +290,43 @@ export function EnvelopeDetailShell({
}
}
+ async function handleConfirmCorrectSigner(next: {
+ email: string;
+ name: string;
+ }) {
+ if (!correctingSigner) {
+ return;
+ }
+
+ setActionError(null);
+ setIsCorrectingSigner(true);
+
+ try {
+ const response = await fetch(
+ `/api/envelopes/${encodeURIComponent(envelopeId)}/signers/${encodeURIComponent(correctingSigner.id)}`,
+ {
+ body: JSON.stringify(next),
+ headers: { "content-type": "application/json" },
+ method: "PATCH",
+ },
+ );
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+
+ if (response.ok) {
+ window.location.reload();
+ return;
+ }
+
+ setActionError(payload?.error ?? "Unable to correct this signer.");
+ } catch {
+ setActionError("Unable to correct this signer.");
+ } finally {
+ setIsCorrectingSigner(false);
+ }
+ }
+
async function handleConfirmChangeReminders(intervalDays: number | null) {
setActionError(null);
setIsChangingReminders(true);
@@ -656,6 +698,27 @@ export function EnvelopeDetailShell({
{signer.statusDateLabel}
</p>
) : null}
+ {activeRecord.status === "sent" &&
+ !record.part11 &&
+ (signer.status === "waiting" ||
+ signer.status === "pending") ? (
+ <button
+ className="btn-quiet inline-flex items-center gap-1.5"
+ onClick={() => {
+ setActionError(null);
+ setCorrectingSigner(signer);
+ setActiveModal("correct-signer");
+ }}
+ type="button"
+ >
+ <PencilIcon
+ aria-hidden="true"
+ className="size-3.5"
+ strokeWidth={2.4}
+ />
+ Change
+ </button>
+ ) : null}
</div>
</div>
@@ -748,6 +811,20 @@ export function EnvelopeDetailShell({
/>
) : null}
+ {activeModal === "correct-signer" && correctingSigner ? (
+ <CorrectSignerDialog
+ email={correctingSigner.email}
+ errorMessage={actionError}
+ name={correctingSigner.name}
+ onCancel={() => {
+ setActiveModal(null);
+ setCorrectingSigner(null);
+ }}
+ onConfirm={handleConfirmCorrectSigner}
+ processing={isCorrectingSigner}
+ />
+ ) : null}
+
{activeModal === "save-template" ? (
<SaveTemplateDialog
envelopeId={envelopeId}
@@ -1004,6 +1081,103 @@ function RemindersDialog({
);
}
+type CorrectSignerDialogProps = {
+ email: string;
+ errorMessage?: string | null;
+ name: string;
+ onCancel: () => void;
+ onConfirm: (next: { email: string; name: string }) => void | Promise<void>;
+ processing?: boolean;
+};
+
+function CorrectSignerDialog({
+ email,
+ errorMessage,
+ name,
+ onCancel,
+ onConfirm,
+ processing = false,
+}: CorrectSignerDialogProps) {
+ const [nextName, setNextName] = useState(name);
+ const [nextEmail, setNextEmail] = useState(email);
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !processing) {
+ onCancel();
+ }
+ }}
+ >
+ <DialogContent className="max-w-md sm:p-8" showCloseButton={false}>
+ <div className="space-y-4">
+ <DialogHeader className="space-y-3">
+ <DialogTitle>Correct this signer</DialogTitle>
+ <DialogDescription asChild>
+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">
+ <p>
+ The signing link already sent to this person will stop
+ working. If it is their turn, a new invitation goes to the
+ corrected address.
+ </p>
+ </div>
+ </DialogDescription>
+ </DialogHeader>
+
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Name
+ </span>
+ <input
+ autoFocus
+ className="field-input"
+ disabled={processing}
+ onChange={(event) => setNextName(event.target.value)}
+ value={nextName}
+ />
+ </label>
+
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Email
+ </span>
+ <input
+ className="field-input"
+ disabled={processing}
+ onChange={(event) => setNextEmail(event.target.value)}
+ type="email"
+ value={nextEmail}
+ />
+ </label>
+
+ {errorMessage ? (
+ <div className="notice notice-danger" role="alert">
+ <p>{errorMessage}</p>
+ </div>
+ ) : null}
+
+ <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-end">
+ <ShellButton
+ disabled={processing}
+ onClick={onCancel}
+ variant="secondary"
+ >
+ Cancel
+ </ShellButton>
+ <ShellButton
+ loading={processing}
+ onClick={() => onConfirm({ email: nextEmail, name: nextName })}
+ >
+ {processing ? "Saving..." : "Save"}
+ </ShellButton>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
type ConfirmationDialogProps = {
children?: ReactNode;
confirmDisabled?: boolean;
diff --git a/src/lib/audit-export.ts b/src/lib/audit-export.ts
index 070e9bb..ac874fb 100644
--- a/src/lib/audit-export.ts
+++ b/src/lib/audit-export.ts
@@ -4,7 +4,10 @@ import {
queryMany,
queryOne,
} from "./db/connection.ts";
-import { verifyAuditChain } from "./services/audit.ts";
+import {
+ describeSignerCorrectedEvent,
+ verifyAuditChain,
+} from "./services/audit.ts";
import {
listSystemAuditEventsBetween,
verifySystemAuditChain,
@@ -138,12 +141,14 @@ export async function exportEnvelopeAuditCsv(
...rows.map((row) => [
row.sequence,
isoTime(row.createdAt),
- row.event,
+ row.event === "signer_corrected" ? "Signer corrected" : row.event,
row.actorType,
row.actorEmail,
row.ipAddress,
row.userAgent,
- row.metadata,
+ row.event === "signer_corrected"
+ ? describeSignerCorrectedEvent(row.metadata)
+ : row.metadata,
row.id,
row.prevHash,
row.rowHash,
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 6295201..11d7d60 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -13,6 +13,7 @@ import {
deadlineFromDays,
formatDeadline,
isEnvelopeExpired,
+ signingLinkLifetimeSeconds,
} from "./envelope-deadline.ts";
import {
countAnswerableFields,
@@ -47,11 +48,15 @@ import {
type ReplaceFieldsResponse,
} from "./schemas/field.ts";
import {
+ correctSentSignerResponseSchema,
+ correctSentSignerSchema,
duplicateCopyRecipientEmailMessage,
+ duplicateSignerEmailMessage,
replaceSignersResponseSchema,
replaceSignersSchema,
signerRecordSchema,
type CopyRecipientRecord,
+ type CorrectSentSignerResponse,
type ReplaceSignersResponse,
type SignerRecord,
} from "./schemas/signer.ts";
@@ -65,19 +70,23 @@ import { getBranding, readStoredSettings } from "./settings.ts";
import { type SignatureMeaning } from "./types/domain.ts";
import { importPdfDocument } from "./services/document-import.ts";
import {
+ describeSignerCorrectedEvent,
listAuditEventsForEnvelope,
lockEnvelopeAuditChain,
recordAuditEvent,
recordEmailSent,
} from "./services/audit.ts";
-import { createEmailService } from "./services/email.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
import { buildSigningInvitationEmail } from "./services/signing-invitation-email.ts";
import {
storeEnvelopeCertificatePdf,
storeRecipientEnvelopeCertificatePdf,
} from "./services/pdf-finalize.ts";
-import { issueSigningLink } from "./services/signing-links.ts";
+import {
+ issueSigningLink,
+ type IssuedSigningLink,
+} from "./services/signing-links.ts";
import {
buildEnvelopeCertificateKey,
buildEnvelopeOriginalPdfKey,
@@ -148,6 +157,19 @@ type VoidEnvelopeInput = {
userAgent?: string | null;
};
+type CorrectSentEnvelopeSignerContext = {
+ ipAddress?: string | null;
+ senderEmail: string;
+ senderName: string;
+ userAgent?: string | null;
+};
+
+type CorrectSentEnvelopeSignerOptions = {
+ database?: DbPool;
+ emailService?: EmailService;
+ nowUnixTimestamp?: number;
+};
+
type SendDraftEnvelopeOptions = {
database?: DbPool;
};
@@ -442,6 +464,7 @@ export type ReplaceDraftSignersResult = ReplaceSignersResponse;
export type ReplaceDraftFieldsResult = ReplaceFieldsResponse;
export type SendDraftEnvelopeResult = SendEnvelopeResponse;
export type VoidEnvelopeResult = VoidEnvelopeResponse;
+export type CorrectSentSignerResult = CorrectSentSignerResponse;
const FIELD_TYPE_SUMMARY_LABELS: Record<
FieldRecord["type"],
@@ -481,6 +504,7 @@ const TIMELINE_TONE_MAP: Record<
expired: "danger",
reauthentication_failed: "danger",
reminded_auto: "neutral",
+ signer_corrected: "neutral",
reminded_manual: "neutral",
sent: "neutral",
signed: "success",
@@ -1315,6 +1339,8 @@ function buildTimelineDescription(event: AuditEventRecord): string {
: "Deadline changed";
case "expired":
return "Deadline passed before everyone signed";
+ case "signer_corrected":
+ return describeSignerCorrectedEvent(event.metadata);
default:
return event.event;
}
@@ -2446,6 +2472,453 @@ export async function changeEnvelopeDeadline(
});
}
+const SENT_ENVELOPE_SIGNER_CORRECTION_MESSAGE =
+ "Only an envelope that is out for signature can have a signer corrected.";
+
+type PersistedSignerCorrection = {
+ auditEventId: string;
+ envelopeExpiresAt: number | null;
+ envelopeId: string;
+ envelopeTitle: string;
+ envelopeUpdatedAt: number;
+ invitationNeeded: boolean;
+ issuedLink: IssuedSigningLink | null;
+ previous: {
+ consentedAt: number | null;
+ email: string;
+ emailCodeAttempts: number;
+ emailCodeExpiresAt: number | null;
+ emailCodeHash: string | null;
+ emailCodeSentAt: number | null;
+ lastNotifiedAt: number | null;
+ name: string;
+ signingTokenExpiresAt: number | null;
+ signingTokenHash: string | null;
+ updatedAt: number;
+ };
+ signerEmail: string;
+ signerId: string;
+ signerName: string;
+ userId: string;
+};
+
+/**
+ * Fixes the name and/or email of a signer who has not signed or declined on
+ * an envelope that is out for signature. The signing link they already have
+ * stops working. If it is their turn, a new invitation goes to the
+ * corrected address.
+ */
+export async function correctSentEnvelopeSigner(
+ userId: string,
+ envelopeId: string,
+ signerId: string,
+ input: unknown,
+ context: CorrectSentEnvelopeSignerContext,
+ {
+ database = getDb(),
+ emailService,
+ nowUnixTimestamp = Math.floor(Date.now() / 1000),
+ }: CorrectSentEnvelopeSignerOptions = {},
+): Promise<CorrectSentSignerResult> {
+ const parsedInput = correctSentSignerSchema.parse(input);
+ const persisted = await withTransaction(async (tx) => {
+ const envelope = await queryOne<{
+ expiresAt: number | null;
+ part11: boolean;
+ status: EnvelopeRecord["status"];
+ title: string;
+ updatedAt: number;
+ userId: string;
+ }>(
+ tx,
+ `
+ SELECT
+ expires_at AS "expiresAt",
+ part11,
+ status,
+ title,
+ updated_at AS "updatedAt",
+ user_id AS "userId"
+ FROM envelopes
+ WHERE id = $1 AND user_id = $2
+ FOR NO KEY UPDATE
+ `,
+ [envelopeId, userId],
+ );
+
+ if (!envelope) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (envelope.status !== "sent") {
+ throw new EnvelopeMutationError(
+ SENT_ENVELOPE_SIGNER_CORRECTION_MESSAGE,
+ 409,
+ );
+ }
+
+ if (envelope.part11) {
+ throw new EnvelopeMutationError(
+ "This envelope was sent in Part 11 mode. The signer's identity is bound to their account and cannot be corrected.",
+ 409,
+ );
+ }
+
+ const signer = await queryOne<{
+ consentedAt: number | null;
+ email: string;
+ emailCodeAttempts: number;
+ emailCodeExpiresAt: number | null;
+ emailCodeHash: string | null;
+ emailCodeSentAt: number | null;
+ lastNotifiedAt: number | null;
+ name: string;
+ role: string;
+ signOrder: number;
+ signingTokenExpiresAt: number | null;
+ signingTokenHash: string | null;
+ status: SignerRecord["status"];
+ updatedAt: number;
+ }>(
+ tx,
+ `
+ SELECT
+ consented_at AS "consentedAt",
+ email,
+ email_code_attempts AS "emailCodeAttempts",
+ email_code_expires_at AS "emailCodeExpiresAt",
+ email_code_hash AS "emailCodeHash",
+ email_code_sent_at AS "emailCodeSentAt",
+ last_notified_at AS "lastNotifiedAt",
+ name,
+ role,
+ sign_order AS "signOrder",
+ signing_token_expires_at AS "signingTokenExpiresAt",
+ signing_token_hash AS "signingTokenHash",
+ status,
+ updated_at AS "updatedAt"
+ FROM signers
+ WHERE id = $1 AND envelope_id = $2
+ FOR NO KEY UPDATE
+ `,
+ [signerId, envelopeId],
+ );
+
+ if (!signer || signer.role !== "signer") {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (signer.status === "signed") {
+ throw new EnvelopeMutationError(
+ "This person has already signed and cannot be corrected.",
+ 409,
+ );
+ }
+
+ if (signer.status === "declined") {
+ throw new EnvelopeMutationError(
+ "This person has already declined and cannot be corrected.",
+ 409,
+ );
+ }
+
+ const nextName = parsedInput.name ?? signer.name;
+ const nextEmail = parsedInput.email ?? signer.email;
+
+ if (
+ nextName === signer.name &&
+ nextEmail.toLowerCase() === signer.email.toLowerCase()
+ ) {
+ return {
+ auditEventId: "",
+ envelopeExpiresAt: envelope.expiresAt,
+ envelopeId,
+ envelopeTitle: envelope.title,
+ envelopeUpdatedAt: envelope.updatedAt,
+ invitationNeeded: false,
+ issuedLink: null,
+ previous: {
+ consentedAt: signer.consentedAt,
+ email: signer.email,
+ emailCodeAttempts: signer.emailCodeAttempts,
+ emailCodeExpiresAt: signer.emailCodeExpiresAt,
+ emailCodeHash: signer.emailCodeHash,
+ emailCodeSentAt: signer.emailCodeSentAt,
+ lastNotifiedAt: signer.lastNotifiedAt,
+ name: signer.name,
+ signingTokenExpiresAt: signer.signingTokenExpiresAt,
+ signingTokenHash: signer.signingTokenHash,
+ updatedAt: signer.updatedAt,
+ },
+ signerEmail: signer.email,
+ signerId,
+ signerName: signer.name,
+ userId,
+ } satisfies PersistedSignerCorrection;
+ }
+
+ const duplicate = await queryOne<{ id: string; role: string }>(
+ tx,
+ `
+ SELECT id, role
+ FROM signers
+ WHERE envelope_id = $1
+ AND lower(email) = $2
+ AND id <> $3
+ `,
+ [envelopeId, nextEmail.toLowerCase(), signerId],
+ );
+
+ if (duplicate) {
+ throw new EnvelopeMutationError(
+ duplicate.role === "cc"
+ ? duplicateCopyRecipientEmailMessage
+ : duplicateSignerEmailMessage,
+ 400,
+ );
+ }
+
+ let issuedLink: IssuedSigningLink | null = null;
+ let tokenHash: string | null = null;
+ let tokenExpiresAt: number | null = null;
+ let lastNotifiedAt = signer.lastNotifiedAt;
+ const invitationNeeded = signer.status === "notified";
+
+ if (invitationNeeded) {
+ const remainingSeconds =
+ typeof envelope.expiresAt === "number" &&
+ envelope.expiresAt > nowUnixTimestamp
+ ? envelope.expiresAt - nowUnixTimestamp
+ : typeof envelope.expiresAt === "number"
+ ? 1
+ : signingLinkLifetimeSeconds(envelope.expiresAt, nowUnixTimestamp);
+
+ issuedLink = await issueSigningLink({
+ expiresInSeconds: remainingSeconds,
+ issuedAt: nowUnixTimestamp,
+ });
+ tokenHash = issuedLink.tokenHash;
+ tokenExpiresAt =
+ typeof envelope.expiresAt === "number"
+ ? envelope.expiresAt
+ : issuedLink.exp;
+ lastNotifiedAt = nowUnixTimestamp;
+ }
+
+ const updatedSigner = await tx.query(
+ `
+ UPDATE signers
+ SET
+ name = $1,
+ email = $2,
+ signing_token_hash = $3,
+ signing_token_expires_at = $4,
+ last_notified_at = $5,
+ consented_at = NULL,
+ email_code_hash = NULL,
+ email_code_expires_at = NULL,
+ email_code_attempts = 0,
+ email_code_sent_at = NULL,
+ updated_at = $6
+ WHERE id = $7
+ AND envelope_id = $8
+ AND status IN ('pending', 'notified')
+ `,
+ [
+ nextName,
+ nextEmail,
+ tokenHash,
+ tokenExpiresAt,
+ lastNotifiedAt,
+ nowUnixTimestamp,
+ signerId,
+ envelopeId,
+ ],
+ );
+
+ if (updatedSigner.rowCount !== 1) {
+ throw new EnvelopeMutationError(
+ "This person has already signed or declined and cannot be corrected.",
+ 409,
+ );
+ }
+
+ await tx.query(
+ `
+ UPDATE envelopes
+ SET updated_at = $1
+ WHERE id = $2
+ `,
+ [nowUnixTimestamp, envelopeId],
+ );
+
+ const auditEvent = await recordAuditEvent(
+ {
+ actorEmail: context.senderEmail,
+ actorType: "sender",
+ createdAt: nowUnixTimestamp,
+ envelopeId,
+ event: "signer_corrected",
+ ipAddress: context.ipAddress ?? null,
+ metadata: {
+ previousEmail: signer.email,
+ previousName: signer.name,
+ signerEmail: nextEmail,
+ signerId,
+ signerName: nextName,
+ signerOrder: signer.signOrder,
+ },
+ userAgent: context.userAgent ?? null,
+ },
+ tx,
+ );
+
+ return {
+ auditEventId: auditEvent.id,
+ envelopeExpiresAt: envelope.expiresAt,
+ envelopeId,
+ envelopeTitle: envelope.title,
+ envelopeUpdatedAt: envelope.updatedAt,
+ invitationNeeded,
+ issuedLink,
+ previous: {
+ consentedAt: signer.consentedAt,
+ email: signer.email,
+ emailCodeAttempts: signer.emailCodeAttempts,
+ emailCodeExpiresAt: signer.emailCodeExpiresAt,
+ emailCodeHash: signer.emailCodeHash,
+ emailCodeSentAt: signer.emailCodeSentAt,
+ lastNotifiedAt: signer.lastNotifiedAt,
+ name: signer.name,
+ signingTokenExpiresAt: signer.signingTokenExpiresAt,
+ signingTokenHash: signer.signingTokenHash,
+ updatedAt: signer.updatedAt,
+ },
+ signerEmail: nextEmail,
+ signerId,
+ signerName: nextName,
+ userId,
+ } satisfies PersistedSignerCorrection;
+ }, database);
+
+ if (!persisted.invitationNeeded || !persisted.issuedLink) {
+ return correctSentSignerResponseSchema.parse({
+ email: persisted.signerEmail,
+ envelopeId: persisted.envelopeId,
+ invitationSent: false,
+ name: persisted.signerName,
+ signerId: persisted.signerId,
+ });
+ }
+
+ const mailer = emailService ?? createEmailService();
+ let invitationMessageId: string | undefined;
+
+ try {
+ invitationMessageId = (
+ await mailer.send(
+ buildSigningInvitationEmail({
+ branding: await getBranding(),
+ envelopeTitle: persisted.envelopeTitle,
+ expiresAt: persisted.envelopeExpiresAt,
+ senderName: context.senderName,
+ signerEmail: persisted.signerEmail,
+ signerName: persisted.signerName,
+ signingUrl: persisted.issuedLink.url,
+ }),
+ )
+ ).messageId;
+ } catch (error) {
+ await withTransaction(async (tx) => {
+ await tx.query(
+ `
+ UPDATE envelopes
+ SET updated_at = $1
+ WHERE id = $2
+ AND user_id = $3
+ AND status = 'sent'
+ `,
+ [persisted.envelopeUpdatedAt, persisted.envelopeId, persisted.userId],
+ );
+
+ await tx.query(
+ `
+ UPDATE signers
+ SET
+ name = $1,
+ email = $2,
+ signing_token_hash = $3,
+ signing_token_expires_at = $4,
+ last_notified_at = $5,
+ consented_at = $6,
+ email_code_hash = $7,
+ email_code_expires_at = $8,
+ email_code_attempts = $9,
+ email_code_sent_at = $10,
+ updated_at = $11
+ WHERE id = $12
+ AND envelope_id = $13
+ AND status = 'notified'
+ `,
+ [
+ persisted.previous.name,
+ persisted.previous.email,
+ persisted.previous.signingTokenHash,
+ persisted.previous.signingTokenExpiresAt,
+ persisted.previous.lastNotifiedAt,
+ persisted.previous.consentedAt,
+ persisted.previous.emailCodeHash,
+ persisted.previous.emailCodeExpiresAt,
+ persisted.previous.emailCodeAttempts,
+ persisted.previous.emailCodeSentAt,
+ persisted.previous.updatedAt,
+ persisted.signerId,
+ persisted.envelopeId,
+ ],
+ );
+
+ await lockEnvelopeAuditChain(persisted.envelopeId, tx);
+ await tx.query(
+ `
+ DELETE FROM audit_events
+ WHERE envelope_id = $1
+ AND id = $2
+ AND sequence = (
+ SELECT max(sequence) FROM audit_events WHERE envelope_id = $1
+ )
+ `,
+ [persisted.envelopeId, persisted.auditEventId],
+ );
+ }, database).catch((rollbackError) => {
+ console.error(
+ `Failed to roll back a signer correction for envelope ${persisted.envelopeId} after email delivery failure:`,
+ rollbackError,
+ );
+ });
+
+ throw error;
+ }
+
+ await recordEmailSent(
+ {
+ envelopeId: persisted.envelopeId,
+ messageId: invitationMessageId,
+ recipient: persisted.signerEmail,
+ signerId: persisted.signerId,
+ template: "signing_invitation",
+ },
+ database,
+ );
+
+ return correctSentSignerResponseSchema.parse({
+ email: persisted.signerEmail,
+ envelopeId: persisted.envelopeId,
+ invitationSent: true,
+ name: persisted.signerName,
+ signerId: persisted.signerId,
+ });
+}
+
/**
* Turns automatic reminders on, off, or to another interval for an envelope
* that is out for signature. The interval counts from the last time the
diff --git a/src/lib/schemas/signer.ts b/src/lib/schemas/signer.ts
index 861642d..6443da1 100644
--- a/src/lib/schemas/signer.ts
+++ b/src/lib/schemas/signer.ts
@@ -146,6 +146,32 @@ export const declineEnvelopeSchema = z.object({
reason: optionalTrimmedString(1000),
});
+export const missingCorrectedSignerFieldsMessage =
+ "Provide a name, an email address, or both.";
+
+/** Name and/or email for a signer who has not signed or declined. */
+export const correctSentSignerSchema = z
+ .object({
+ email: emailSchema.optional(),
+ name: nameSchema.optional(),
+ })
+ .superRefine((value, ctx) => {
+ if (value.email === undefined && value.name === undefined) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: missingCorrectedSignerFieldsMessage,
+ });
+ }
+ });
+
+export const correctSentSignerResponseSchema = z.object({
+ email: emailSchema,
+ envelopeId: idSchema,
+ invitationSent: z.boolean(),
+ name: nameSchema,
+ signerId: idSchema,
+});
+
export type CopyRecipient = z.infer<typeof copyRecipientSchema>;
/** A copy recipient as stored: it always has an id. */
export type CopyRecipientRecord = { email: string; id: string; name: string };
@@ -156,3 +182,7 @@ export type ReplaceSignersResponse = z.infer<
>;
export type SignerRecord = z.infer<typeof signerRecordSchema>;
export type DeclineEnvelopeInput = z.infer<typeof declineEnvelopeSchema>;
+export type CorrectSentSignerInput = z.infer<typeof correctSentSignerSchema>;
+export type CorrectSentSignerResponse = z.infer<
+ typeof correctSentSignerResponseSchema
+>;
diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.ts
index 835865a..fc2f2dc 100644
--- a/src/lib/services/audit.ts
+++ b/src/lib/services/audit.ts
@@ -14,6 +14,49 @@ import { canonicalJson } from "../utils/canonical-json.ts";
export type AuditEventMetadata = Record<string, unknown> | null;
+function readMetadataString(
+ metadata: Record<string, unknown> | null | undefined,
+ key: string,
+): string | null {
+ const value = metadata?.[key];
+
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
+}
+
+function formatSignerPerson(name: string | null, email: string | null): string {
+ if (name && email) {
+ return `${name} <${email}>`;
+ }
+
+ return name ?? email ?? "signer";
+}
+
+/** Plain words for a signer_corrected audit event, from its stored metadata. */
+export function describeSignerCorrectedEvent(
+ metadata: Record<string, unknown> | null | undefined,
+): string {
+ const previousName = readMetadataString(metadata, "previousName");
+ const previousEmail = readMetadataString(metadata, "previousEmail");
+ const name = readMetadataString(metadata, "signerName");
+ const email = readMetadataString(metadata, "signerEmail");
+ const sameName =
+ previousName !== null && name !== null && previousName === name;
+ const sameEmail =
+ previousEmail !== null &&
+ email !== null &&
+ previousEmail.toLowerCase() === email.toLowerCase();
+
+ if (sameName && previousEmail && email) {
+ return `Signer email corrected from ${previousEmail} to ${email}`;
+ }
+
+ if (sameEmail && previousName && name) {
+ return `Signer name corrected from ${previousName} to ${name}`;
+ }
+
+ return `Signer corrected from ${formatSignerPerson(previousName, previousEmail)} to ${formatSignerPerson(name, email)}`;
+}
+
export type RecordAuditEventInput = {
/** Given when the event was already shown on a certificate under this id. */
id?: string;
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index 275b7d6..2b779ae 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -10,6 +10,7 @@ import {
import type { FieldRecord } from "../schemas/field.ts";
import type { SignerRecord } from "../schemas/signer.ts";
import { buildSignatureManifestation } from "../signature-meanings.ts";
+import { describeSignerCorrectedEvent } from "./audit.ts";
import { canonicalJson } from "../utils/canonical-json.ts";
import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";
import { embedTextFaces, type TextFace } from "./pdf-fonts.ts";
@@ -775,8 +776,11 @@ function buildAuditLines(input: {
const actorLabel =
signerName && actor !== signerName ? `${signerName} <${actor}>` : actor;
+ const eventLabel =
+ event.event === "signer_corrected" ? "Signer corrected" : event.event;
+
pushParagraph(
- `${formatAuditTimestamp(event.createdAt)} | ${event.event} | ${actorLabel}`,
+ `${formatAuditTimestamp(event.createdAt)} | ${eventLabel} | ${actorLabel}`,
input.fonts.regular,
bodyFontSize,
);
@@ -989,6 +993,10 @@ function describeEventEvidence(event: AuditEventRecord): string[] {
);
}
+ if (event.event === "signer_corrected") {
+ details.push(describeSignerCorrectedEvent(metadata));
+ }
+
if (event.event === "verified" && typeof metadata.method === "string") {
details.push(
`passed: ${AUTHENTICATION_LABELS[metadata.method] ?? metadata.method}`,
diff --git a/src/lib/signer-correction.dbtest.ts b/src/lib/signer-correction.dbtest.ts
new file mode 100644
index 0000000..a59733f
--- /dev/null
+++ b/src/lib/signer-correction.dbtest.ts
@@ -0,0 +1,600 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { after, before, test } from "node:test";
+import { ZodError } from "zod";
+
+import type pg from "pg";
+
+import { exportEnvelopeAuditCsv } from "./audit-export.ts";
+import { openTestDatabase } from "./db/test-database.ts";
+import {
+ correctSentEnvelopeSigner,
+ EnvelopeMutationError,
+ getEnvelopeDetailDataForUser,
+} from "./envelopes.ts";
+import { duplicateSignerEmailMessage } from "./schemas/signer.ts";
+import { verifyAuditChain } from "./services/audit.ts";
+import type {
+ EmailService,
+ TransactionalEmailMessage,
+} from "./services/email.ts";
+import { hashOpaqueToken } from "./services/opaque-tokens.ts";
+import { issueSigningLink } from "./services/signing-links.ts";
+import { getSigningPayloadForToken, SigningAccessError } from "./signing.ts";
+
+// Correcting a waiting signer's name or email on a sent envelope, against
+// a real Postgres. Run with `npm run test:db`.
+
+process.env.APP_URL ??= "https://sign.example.test";
+
+const DAY = 24 * 60 * 60;
+
+let database: pg.Pool;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ globalThis.__signudocPgPool = database;
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+});
+
+function unixNow() {
+ return Math.floor(Date.now() / 1000);
+}
+
+function recordingEmailService(failWith?: Error) {
+ const sent: TransactionalEmailMessage[] = [];
+ const service: EmailService = {
+ async send(message) {
+ if (failWith) {
+ throw failWith;
+ }
+
+ sent.push(message);
+
+ return { accepted: [message.to], messageId: "m-1", rejected: [] };
+ },
+ async sendBatch() {
+ throw new Error("not used");
+ },
+ };
+
+ return { sent, service };
+}
+
+async function createOwner() {
+ const userId = randomUUID();
+ const email = `${userId}@example.test`;
+
+ createdUsers.push(userId);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,
+ [userId, email],
+ );
+
+ return { email, userId };
+}
+
+async function createEnvelope({
+ expiresAt = unixNow() + 30 * DAY,
+ part11 = false,
+ status = "sent",
+ userId,
+}: {
+ expiresAt?: number | null;
+ part11?: boolean;
+ status?: "completed" | "declined" | "draft" | "sent" | "voided";
+ userId: string;
+}) {
+ const envelopeId = randomUUID();
+ const sentAt = status === "draft" ? null : unixNow() - 60;
+
+ 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, part11, completed_at, declined_at, voided_at
+ ) values (
+ $1, $2, 'Lease', $3, $4, 'lease.pdf', 10, 1, $5, $6, $7, $8,
+ $9, $10, $11
+ )
+ `,
+ [
+ envelopeId,
+ userId,
+ status,
+ `test/${envelopeId}.pdf`,
+ "a".repeat(64),
+ sentAt,
+ status === "draft" ? null : expiresAt,
+ part11,
+ status === "completed" ? unixNow() : null,
+ status === "declined" ? unixNow() : null,
+ status === "voided" ? unixNow() : null,
+ ],
+ );
+
+ return envelopeId;
+}
+
+async function createSigner({
+ email,
+ envelopeId,
+ extra,
+ name = "Riley Recipient",
+ signOrder = 1,
+ status = "notified",
+}: {
+ email?: string;
+ envelopeId: string;
+ extra?: {
+ consentedAt?: number | null;
+ emailCodeAttempts?: number;
+ emailCodeExpiresAt?: number | null;
+ emailCodeHash?: string | null;
+ emailCodeSentAt?: number | null;
+ };
+ name?: string;
+ signOrder?: number;
+ status?: "declined" | "notified" | "pending" | "signed";
+}) {
+ const signerId = randomUUID();
+ const link =
+ status === "notified"
+ ? await issueSigningLink({ expiresInSeconds: 30 * DAY })
+ : null;
+
+ await database.query(
+ `
+ insert into signers (
+ id, envelope_id, name, email, sign_order, status,
+ signing_token_hash, signing_token_expires_at, last_notified_at,
+ signed_at, declined_at, email_code_hash, email_code_expires_at,
+ email_code_attempts, email_code_sent_at, consented_at
+ ) values (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16
+ )
+ `,
+ [
+ signerId,
+ envelopeId,
+ name,
+ email ?? `${signerId}@example.test`,
+ signOrder,
+ status,
+ link?.tokenHash ?? null,
+ link?.exp ?? null,
+ status === "notified" ? unixNow() : null,
+ status === "signed" ? unixNow() : null,
+ status === "declined" ? unixNow() : null,
+ extra?.emailCodeHash ?? null,
+ extra?.emailCodeExpiresAt ?? null,
+ extra?.emailCodeAttempts ?? 0,
+ extra?.emailCodeSentAt ?? null,
+ extra?.consentedAt ?? null,
+ ],
+ );
+
+ return {
+ email: email ?? `${signerId}@example.test`,
+ signerId,
+ token: link?.token ?? null,
+ tokenHash: link?.tokenHash ?? null,
+ };
+}
+
+async function readSigner(signerId: string) {
+ const result = await database.query<{
+ consented_at: number | null;
+ email: string;
+ email_code_attempts: number;
+ email_code_hash: string | null;
+ email_code_sent_at: number | null;
+ name: string;
+ signing_token_hash: string | null;
+ status: string;
+ }>(
+ `
+ select
+ consented_at, email, email_code_attempts, email_code_hash,
+ email_code_sent_at, name, signing_token_hash, status
+ from signers
+ where id = $1
+ `,
+ [signerId],
+ );
+
+ return result.rows[0]!;
+}
+
+async function auditEvents(envelopeId: string) {
+ const result = await database.query<{ event: string }>(
+ `select event from audit_events where envelope_id = $1 order by sequence`,
+ [envelopeId],
+ );
+
+ return result.rows.map((row) => row.event);
+}
+
+function correct(
+ userId: string,
+ envelopeId: string,
+ signerId: string,
+ body: unknown,
+ emailService?: EmailService,
+) {
+ return correctSentEnvelopeSigner(
+ userId,
+ envelopeId,
+ signerId,
+ body,
+ {
+ ipAddress: "203.0.113.8",
+ senderEmail: "[email protected]",
+ senderName: "Sam Sender",
+ userAgent: "test",
+ },
+ { database, emailService },
+ );
+}
+
+test("correcting a notified signer rotates the link and emails the new address", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const signer = await createSigner({
+ envelopeId,
+ extra: {
+ consentedAt: unixNow() - 10,
+ emailCodeAttempts: 2,
+ emailCodeExpiresAt: unixNow() + 600,
+ emailCodeHash: "a".repeat(64),
+ emailCodeSentAt: unixNow() - 30,
+ },
+ });
+ const { sent, service } = recordingEmailService();
+ const oldToken = signer.token!;
+
+ const result = await correct(
+ userId,
+ envelopeId,
+ signer.signerId,
+ { email: "[email protected]", name: "Riley Recipient" },
+ service,
+ );
+
+ assert.equal(result.invitationSent, true);
+ assert.equal(result.email, "[email protected]");
+ const stored = await readSigner(signer.signerId);
+ assert.equal(stored.email, "[email protected]");
+ assert.notEqual(stored.signing_token_hash, signer.tokenHash);
+ assert.equal(stored.consented_at, null);
+ assert.equal(stored.email_code_hash, null);
+ assert.equal(stored.email_code_attempts, 0);
+ assert.equal(stored.email_code_sent_at, null);
+
+ await assert.rejects(getSigningPayloadForToken(oldToken, { database }), {
+ message: "This link has expired.",
+ name: "SigningAccessError",
+ });
+ await assert.rejects(
+ getSigningPayloadForToken(oldToken, { database }),
+ (error: unknown) => {
+ assert.ok(error instanceof SigningAccessError);
+ assert.equal(error.state, "expired");
+ return true;
+ },
+ );
+
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0]?.to, "[email protected]");
+ assert.equal(sent[0]?.template, "signing_invitation");
+ const match = sent[0]?.textBody.match(/\/sign\/([A-Za-z0-9_-]+)/);
+ assert.ok(match?.[1]);
+ assert.equal(stored.signing_token_hash, hashOpaqueToken(match[1]!));
+
+ assert.deepEqual(await auditEvents(envelopeId), [
+ "signer_corrected",
+ "email_sent",
+ ]);
+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
+
+ const detail = await getEnvelopeDetailDataForUser(
+ userId,
+ envelopeId,
+ database,
+ );
+ assert.ok(
+ detail?.timeline.some((item) =>
+ item.description.includes(
+ "Signer email corrected from " +
+ `${signer.email} to [email protected]`,
+ ),
+ ),
+ );
+
+ const csv = await exportEnvelopeAuditCsv(userId, envelopeId, database);
+ assert.match(csv.body, /Signer corrected/);
+ assert.match(
+ csv.body,
+ /Signer email corrected from .* to riley\.fixed@example\.test/,
+ );
+});
+
+test("correcting a pending signer records the change and sends no invitation", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ await createSigner({ envelopeId, signOrder: 1, status: "notified" });
+ const pending = await createSigner({
+ envelopeId,
+ name: "Casey Second",
+ signOrder: 2,
+ status: "pending",
+ });
+ const { sent, service } = recordingEmailService();
+
+ const result = await correct(
+ userId,
+ envelopeId,
+ pending.signerId,
+ { email: "[email protected]" },
+ service,
+ );
+
+ assert.equal(result.invitationSent, false);
+ assert.equal(sent.length, 0);
+ assert.equal(
+ (await readSigner(pending.signerId)).email,
+ );
+ assert.deepEqual(await auditEvents(envelopeId), ["signer_corrected"]);
+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
+});
+
+test("the same name and email is a no-op: the link stays and nothing is audited", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const signer = await createSigner({
+ email: "[email protected]",
+ envelopeId,
+ name: "Riley Recipient",
+ });
+ const { sent, service } = recordingEmailService();
+
+ const result = await correct(
+ userId,
+ envelopeId,
+ signer.signerId,
+ { email: "[email protected]", name: "Riley Recipient" },
+ service,
+ );
+
+ assert.equal(result.invitationSent, false);
+ assert.equal(result.email, "[email protected]");
+ assert.equal(
+ (await readSigner(signer.signerId)).signing_token_hash,
+ signer.tokenHash,
+ );
+ assert.equal(sent.length, 0);
+ assert.deepEqual(await auditEvents(envelopeId), []);
+ const stillLinked = await database.query<{ id: string }>(
+ `select id from signers where signing_token_hash = $1`,
+ [hashOpaqueToken(signer.token!)],
+ );
+ assert.equal(stillLinked.rows[0]?.id, signer.signerId);
+});
+
+test("a passed deadline can still have a signer corrected", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({
+ expiresAt: unixNow() - 60,
+ userId,
+ });
+ const signer = await createSigner({ envelopeId });
+ const { sent, service } = recordingEmailService();
+
+ const result = await correct(
+ userId,
+ envelopeId,
+ signer.signerId,
+ { name: "Riley Fixed" },
+ service,
+ );
+
+ assert.equal(result.invitationSent, true);
+ assert.equal(sent.length, 1);
+ assert.notEqual(
+ (await readSigner(signer.signerId)).signing_token_hash,
+ signer.tokenHash,
+ );
+ await assert.rejects(getSigningPayloadForToken(signer.token!, { database }), {
+ name: "SigningAccessError",
+ });
+});
+
+test("another signer's email is refused", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const first = await createSigner({
+ email: "[email protected]",
+ envelopeId,
+ });
+ const second = await createSigner({
+ email: "[email protected]",
+ envelopeId,
+ name: "Casey Second",
+ signOrder: 2,
+ status: "pending",
+ });
+
+ await assert.rejects(
+ correct(userId, envelopeId, second.signerId, {
+ email: "[email protected]",
+ }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 400);
+ assert.equal(error.message, duplicateSignerEmailMessage);
+ return true;
+ },
+ );
+ assert.equal((await readSigner(first.signerId)).email, "[email protected]");
+});
+
+test("a signed or declined signer cannot be corrected", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const signed = await createSigner({
+ envelopeId,
+ status: "signed",
+ });
+ const declined = await createSigner({
+ envelopeId,
+ name: "Casey Second",
+ signOrder: 2,
+ status: "declined",
+ });
+
+ await assert.rejects(
+ correct(userId, envelopeId, signed.signerId, { name: "Nope" }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 409);
+ assert.match(error.message, /already signed/);
+ return true;
+ },
+ );
+ await assert.rejects(
+ correct(userId, envelopeId, declined.signerId, { name: "Nope" }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 409);
+ assert.match(error.message, /already declined/);
+ return true;
+ },
+ );
+});
+
+test("a copy recipient cannot be corrected here", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ await createSigner({ envelopeId });
+ const copyId = randomUUID();
+ await database.query(
+ `
+ insert into signers (
+ id, envelope_id, name, email, sign_order, status, role
+ ) values ($1, $2, 'Zofia Copy', '[email protected]', 501, 'pending', 'cc')
+ `,
+ [copyId, envelopeId],
+ );
+
+ await assert.rejects(
+ correct(userId, envelopeId, copyId, { email: "[email protected]" }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 404);
+ return true;
+ },
+ );
+});
+
+test("draft, completed, declined and voided envelopes are refused", async () => {
+ const { userId } = await createOwner();
+
+ for (const status of ["draft", "completed", "declined", "voided"] as const) {
+ const envelopeId = await createEnvelope({ status, userId });
+ const signer = await createSigner({
+ envelopeId,
+ status: status === "draft" ? "pending" : "notified",
+ });
+
+ await assert.rejects(
+ correct(userId, envelopeId, signer.signerId, { name: "Nope" }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 409);
+ assert.match(error.message, /out for signature/);
+ return true;
+ },
+ );
+ }
+});
+
+test("a Part 11 envelope cannot have a signer corrected", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ part11: true, userId });
+ const signer = await createSigner({ envelopeId });
+
+ await assert.rejects(
+ correct(userId, envelopeId, signer.signerId, {
+ email: "[email protected]",
+ }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 409);
+ assert.match(error.message, /Part 11/);
+ return true;
+ },
+ );
+});
+
+test("another user cannot correct a signer", async () => {
+ const owner = await createOwner();
+ const other = await createOwner();
+ const envelopeId = await createEnvelope({ userId: owner.userId });
+ const signer = await createSigner({ envelopeId });
+
+ await assert.rejects(
+ correct(other.userId, envelopeId, signer.signerId, { name: "Nope" }),
+ (error: unknown) => {
+ assert.ok(error instanceof EnvelopeMutationError);
+ assert.equal(error.statusCode, 404);
+ return true;
+ },
+ );
+});
+
+test("an empty or invalid correction is refused by the schema", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const signer = await createSigner({ envelopeId });
+
+ await assert.rejects(
+ correct(userId, envelopeId, signer.signerId, {}),
+ ZodError,
+ );
+ await assert.rejects(
+ correct(userId, envelopeId, signer.signerId, { email: "not-an-email" }),
+ ZodError,
+ );
+});
+
+test("a failed invitation leaves the old name, email and link in place", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const signer = await createSigner({ envelopeId });
+ const { service } = recordingEmailService(new Error("mailbox down"));
+
+ await assert.rejects(
+ correct(
+ userId,
+ envelopeId,
+ signer.signerId,
+ { email: "[email protected]" },
+ service,
+ ),
+ { message: "mailbox down" },
+ );
+
+ const stored = await readSigner(signer.signerId);
+ assert.equal(stored.email, signer.email);
+ assert.equal(stored.signing_token_hash, signer.tokenHash);
+ assert.deepEqual(await auditEvents(envelopeId), []);
+});
diff --git a/src/lib/signer-correction.test.ts b/src/lib/signer-correction.test.ts
new file mode 100644
index 0000000..4a47245
--- /dev/null
+++ b/src/lib/signer-correction.test.ts
@@ -0,0 +1,70 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { ZodError } from "zod";
+
+import { describeSignerCorrectedEvent } from "./services/audit.ts";
+import {
+ correctSentSignerSchema,
+ missingCorrectedSignerFieldsMessage,
+} from "./schemas/signer.ts";
+
+test("a signer correction needs a name, an email address, or both", () => {
+ assert.deepEqual(correctSentSignerSchema.parse({ name: "Riley Recipient" }), {
+ name: "Riley Recipient",
+ });
+ assert.deepEqual(
+ correctSentSignerSchema.parse({ email: "[email protected]" }),
+ { email: "[email protected]" },
+ );
+ assert.deepEqual(
+ correctSentSignerSchema.parse({
+ email: "[email protected]",
+ name: "Riley Recipient",
+ }),
+ { email: "[email protected]", name: "Riley Recipient" },
+ );
+
+ try {
+ correctSentSignerSchema.parse({});
+ assert.fail("expected an empty correction to be refused");
+ } catch (error) {
+ assert.ok(error instanceof ZodError);
+ assert.equal(error.issues[0]?.message, missingCorrectedSignerFieldsMessage);
+ }
+
+ assert.throws(
+ () => correctSentSignerSchema.parse({ email: "not-an-email" }),
+ ZodError,
+ );
+ assert.throws(() => correctSentSignerSchema.parse({ name: " " }), ZodError);
+});
+
+test("a signer_corrected event is described in plain words", () => {
+ assert.equal(
+ describeSignerCorrectedEvent({
+ previousEmail: "[email protected]",
+ previousName: "Riley Recipient",
+ signerEmail: "[email protected]",
+ signerName: "Riley Recipient",
+ }),
+ "Signer email corrected from [email protected] to [email protected]",
+ );
+ assert.equal(
+ describeSignerCorrectedEvent({
+ previousEmail: "[email protected]",
+ previousName: "Rily",
+ signerEmail: "[email protected]",
+ signerName: "Riley Recipient",
+ }),
+ "Signer name corrected from Rily to Riley Recipient",
+ );
+ assert.equal(
+ describeSignerCorrectedEvent({
+ previousEmail: "[email protected]",
+ previousName: "Rily",
+ signerEmail: "[email protected]",
+ signerName: "Riley Recipient",
+ }),
+ "Signer corrected from Rily <[email protected]> to Riley Recipient <[email protected]>",
+ );
+});
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index b801d81..40a6131 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -64,6 +64,7 @@ export const auditEventTypes = [
"expired",
"reminded_auto",
"reauthentication_failed",
+ "signer_corrected",
] as const;
/**