Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Serialize signer corrections through the invitation send
Matt Van Horn765528020a44
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 800eb4a..3a23567 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -2475,136 +2475,19 @@ 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 = {- correctedAt: number;- 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;- signerOrder: number;- userId: string;-};--/**- * Puts a notified signer back as they were when sending their new- * invitation failed. The correction is not written to the audit trail- * until that send succeeds, so restoring the row is enough. Another- * correction of the same person can land while the send is in flight;- * restoring then would revive the first link and drop the second. The- * row is only written if it still holds this correction's address and- * token.- */-async function revertFailedSignerCorrection(- persisted: PersistedSignerCorrection,- database: DbPool,-): Promise<void> {- const issuedLink = persisted.issuedLink;-- if (!issuedLink) {- return;- }-- await withTransaction(async (tx) => {- const envelope = await queryOne<{ id: string }>(- tx,- `- SELECT id- FROM envelopes- WHERE id = $1 AND user_id = $2 AND status = 'sent'- FOR NO KEY UPDATE- `,- [persisted.envelopeId, persisted.userId],- );-- if (!envelope) {- return;- }-- const restored = 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'- AND name = $14- AND email = $15- AND signing_token_hash = $16- `,- [- 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,- persisted.signerName,- persisted.signerEmail,- issuedLink.tokenHash,- ],- );-- if (restored.rowCount !== 1) {- return;- }-- await tx.query(- `- UPDATE envelopes- SET updated_at = $1- WHERE id = $2- AND updated_at = $3- `,- [- persisted.envelopeUpdatedAt,- persisted.envelopeId,- persisted.correctedAt,- ],- );- }, database);-}-/*** 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.+ *+ * The envelope and signer rows stay locked until that invitation is sent+ * or refused, so another correction of the same person waits. A failed+ * send rolls the whole transaction back: the last committed identity+ * returns, the original link still works when nothing succeeded, and no+ * signer_corrected event is left behind. The audit event is written in+ * this same transaction after a successful send, so overlapping+ * corrections cannot appear out of order.*/export async function correctSentEnvelopeSigner(userId: string,@@ -2619,7 +2502,8 @@ export async function correctSentEnvelopeSigner(}: CorrectSentEnvelopeSignerOptions = {},): Promise<CorrectSentSignerResult> {const parsedInput = correctSentSignerSchema.parse(input);- const persisted = await withTransaction(async (tx) => {++ return withTransaction(async (tx) => {const envelope = await queryOne<{expiresAt: number | null;part11: boolean;@@ -2727,33 +2611,13 @@ export async function correctSentEnvelopeSigner(nextName === signer.name &&nextEmail.toLowerCase() === signer.email.toLowerCase()) {- return {- correctedAt: nowUnixTimestamp,- envelopeExpiresAt: envelope.expiresAt,+ return correctSentSignerResponseSchema.parse({+ email: signer.email,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,+ invitationSent: false,+ name: signer.name,signerId,- signerName: signer.name,- signerOrder: signer.signOrder,- userId,- } satisfies PersistedSignerCorrection;+ });}const duplicate = await queryOne<{ id: string; role: string }>(@@ -2851,10 +2715,22 @@ export async function correctSentEnvelopeSigner([nowUnixTimestamp, envelopeId],);- // A notified signer still needs a new invitation. Do not record the- // correction until that send succeeds; a failed send must not leave a- // signer_corrected event in the trail.- if (!invitationNeeded) {+ if (invitationNeeded && issuedLink) {+ const mailer = emailService ?? createEmailService();+ const invitationMessageId = (+ await mailer.send(+ buildSigningInvitationEmail({+ branding: await getBranding(),+ envelopeTitle: envelope.title,+ expiresAt: envelope.expiresAt,+ senderName: context.senderName,+ signerEmail: nextEmail,+ signerName: nextName,+ signingUrl: issuedLink.url,+ }),+ )+ ).messageId;+await recordAuditEvent({actorEmail: context.senderEmail,@@ -2875,116 +2751,55 @@ export async function correctSentEnvelopeSigner(},tx,);+ await recordEmailSent(+ {+ envelopeId,+ messageId: invitationMessageId,+ recipient: nextEmail,+ signerId,+ template: "signing_invitation",+ },+ tx,+ );++ return correctSentSignerResponseSchema.parse({+ email: nextEmail,+ envelopeId,+ invitationSent: true,+ name: nextName,+ signerId,+ });}- return {- correctedAt: nowUnixTimestamp,- 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,+ 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,},- signerEmail: nextEmail,- signerId,- signerName: nextName,- signerOrder: signer.signOrder,- userId,- } satisfies PersistedSignerCorrection;- }, database);+ tx,+ );- if (!persisted.invitationNeeded || !persisted.issuedLink) {return correctSentSignerResponseSchema.parse({- email: persisted.signerEmail,- envelopeId: persisted.envelopeId,+ email: nextEmail,+ envelopeId,invitationSent: false,- name: persisted.signerName,- signerId: persisted.signerId,+ name: nextName,+ signerId,});- }-- let invitationMessageId: string | undefined;-- try {- const mailer = emailService ?? createEmailService();-- 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 revertFailedSignerCorrection(persisted, database).catch(- (rollbackError) => {- console.error(- `Failed to roll back a signer correction for envelope ${persisted.envelopeId} after email delivery failure:`,- rollbackError,- );- },- );-- throw error;- }-- await recordAuditEvent(- {- actorEmail: context.senderEmail,- actorType: "sender",- createdAt: Math.floor(Date.now() / 1000),- envelopeId: persisted.envelopeId,- event: "signer_corrected",- ipAddress: context.ipAddress ?? null,- metadata: {- previousEmail: persisted.previous.email,- previousName: persisted.previous.name,- signerEmail: persisted.signerEmail,- signerId: persisted.signerId,- signerName: persisted.signerName,- signerOrder: persisted.signerOrder,- },- userAgent: context.userAgent ?? null,- },- database,- );- 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,- });+ }, database);}/**diff --git a/src/lib/signer-correction.dbtest.ts b/src/lib/signer-correction.dbtest.tsindex 7d36e25..bd1525b 100644--- a/src/lib/signer-correction.dbtest.ts+++ b/src/lib/signer-correction.dbtest.ts@@ -93,6 +93,15 @@ function recordingEmailService(failWith?: Error) {return { sent, service };}+function deferred<T = void>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });++ return { promise, resolve };+}+async function createOwner() {const userId = randomUUID();const email = `${userId}@example.test`;@@ -1091,23 +1100,11 @@ test("a failed invitation does not undo a later correction of the same signer",const envelopeId = await createEnvelope({ userId });const signer = await createSigner({ envelopeId });const { sent: sentB, service: serviceB } = recordingEmailService();- const serviceA: EmailService = {- async send() {- await correct(- userId,- envelopeId,- signer.signerId,- { email: "[email protected]" },- serviceB,- );- throw new Error("mailbox down");- },- async sendBatch() {- throw new Error("not used");- },- };+ const { service: serviceA } = recordingEmailService(+ new Error("mailbox down"),+ );- await assert.rejects(+ const outcomes = await Promise.allSettled([correct(userId,envelopeId,@@ -1115,7 +1112,22 @@ test("a failed invitation does not undo a later correction of the same signer",{ email: "[email protected]" },serviceA,),- { message: "mailbox down" },+ correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ serviceB,+ ),+ ]);++ assert.equal(+ outcomes.filter((outcome) => outcome.status === "fulfilled").length,+ 1,+ );+ assert.equal(+ outcomes.filter((outcome) => outcome.status === "rejected").length,+ 1,);const stored = await readSigner(signer.signerId);@@ -1135,7 +1147,139 @@ test("a failed invitation does not undo a later correction of the same signer",assert.equal((csv.body.match(/Signer corrected/g) ?? []).length, 1);assert.match(csv.body,- /Signer email corrected from first@example\.test to second@example\.test/,+ new RegExp(+ `Signer email corrected from ${signer.email.replaceAll(".", "\\.")} to second@example\\.test`,+ ),+ );+});++test("two overlapping failed invitations restore the original signer and link", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const signer = await createSigner({+ envelopeId,+ extra: { consentedAt: unixNow() - 20 },+ });+ const originalConsentedAt = (await readSigner(signer.signerId)).consented_at;+ const { service: serviceA } = recordingEmailService(+ new Error("mailbox down"),+ );+ const { service: serviceB } = recordingEmailService(+ new Error("mailbox down"),+ );++ const outcomes = await Promise.allSettled([+ correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ serviceA,+ ),+ correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ serviceB,+ ),+ ]);++ assert.equal(+ outcomes.filter((outcome) => outcome.status === "rejected").length,+ 2,+ );++ const stored = await readSigner(signer.signerId);+ assert.equal(stored.email, signer.email);+ assert.equal(stored.signing_token_hash, signer.tokenHash);+ assert.equal(stored.consented_at, originalConsentedAt);+ assert.deepEqual(await auditEvents(envelopeId), []);+ await getSigningPayloadForToken(signer.token!, { database });+});++test("overlapping successful corrections record audit events in save order", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const signer = await createSigner({ envelopeId });+ const firstStarted = deferred();+ const firstMayFinish = deferred();+ const sentFirst: TransactionalEmailMessage[] = [];+ const { sent: sentSecond, service: serviceSecond } = recordingEmailService();+ const serviceFirst: EmailService = {+ async send(message) {+ firstStarted.resolve();+ await firstMayFinish.promise;+ sentFirst.push(message);++ return { accepted: [message.to], messageId: "m-first", rejected: [] };+ },+ async sendBatch() {+ throw new Error("not used");+ },+ };++ const firstCorrection = correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ serviceFirst,+ );+ await firstStarted.promise;++ const secondCorrection = correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ serviceSecond,+ );++ await new Promise((resolve) => setTimeout(resolve, 50));+ assert.equal(sentSecond.length, 0);+ assert.equal((await readSigner(signer.signerId)).email, signer.email);++ firstMayFinish.resolve();+ await Promise.all([firstCorrection, secondCorrection]);++ const stored = await readSigner(signer.signerId);+ assert.equal(stored.email, "[email protected]");+ assert.equal(sentFirst.length, 1);+ assert.equal(sentSecond.length, 1);+ assert.deepEqual(await auditEvents(envelopeId), [+ "signer_corrected",+ "email_sent",+ "signer_corrected",+ "email_sent",+ ]);++ const recorded = await listAuditEventsForEnvelope(envelopeId, database);+ const corrections = recorded.filter(+ (event) => event.event === "signer_corrected",+ );+ assert.equal(corrections[0]?.metadata?.signerEmail, "[email protected]");+ assert.equal(corrections[0]?.metadata?.previousEmail, signer.email);+ assert.equal(corrections[1]?.metadata?.signerEmail, "[email protected]");+ assert.equal(corrections[1]?.metadata?.previousEmail, "[email protected]");+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);++ const match = sentSecond[0]?.textBody.match(/\/sign\/([A-Za-z0-9_-]+)/);+ assert.ok(match?.[1]);+ await consent(match[1]!);++ const { full } = await renderCorrectionCertificates(envelopeId);+ const signersSection = (full.split("Audit events")[0] ?? "").replace(+ /\s+/g,+ " ",+ );+ const compactSigners = signersSection.replaceAll(" ", "");++ assert.ok(+ compactSigners.includes(+ `disclosure${ELECTRONIC_RECORDS_DISCLOSURE_VERSION}`,+ ),+ signersSection,);});