Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Keep old signing links, emails and consent out of a corrected signer
Matt Van Horna002e63e7be9
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 11d7d60..f18c9af 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -2499,9 +2499,151 @@ type PersistedSignerCorrection = {signerEmail: string;signerId: string;signerName: string;+ signerOrder: number;userId: string;};+/**+ * Puts a notified signer back as they were when sending their new+ * invitation failed. Another correction of the same person can land while+ * that 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. If a later audit event is already+ * chained, the original event stays and a second event records the+ * reversal so the trail matches the row.+ */+async function revertFailedSignerCorrection(+ persisted: PersistedSignerCorrection,+ context: CorrectSentEnvelopeSignerContext,+ 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 lockEnvelopeAuditChain(persisted.envelopeId, tx);++ const deleted = 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],+ );++ if (deleted.rowCount === 1) {+ await tx.query(+ `+ UPDATE envelopes+ SET updated_at = $1+ WHERE id = $2+ `,+ [persisted.envelopeUpdatedAt, persisted.envelopeId],+ );+ return;+ }++ const reversedAt = Math.floor(Date.now() / 1000);++ await recordAuditEvent(+ {+ actorEmail: context.senderEmail,+ actorType: "sender",+ createdAt: reversedAt,+ envelopeId: persisted.envelopeId,+ event: "signer_corrected",+ ipAddress: context.ipAddress ?? null,+ metadata: {+ previousEmail: persisted.signerEmail,+ previousName: persisted.signerName,+ signerEmail: persisted.previous.email,+ signerId: persisted.signerId,+ signerName: persisted.previous.name,+ signerOrder: persisted.signerOrder,+ },+ userAgent: context.userAgent ?? null,+ },+ tx,+ );+ await tx.query(+ `+ UPDATE envelopes+ SET updated_at = $1+ WHERE id = $2+ `,+ [reversedAt, persisted.envelopeId],+ );+ }, 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@@ -2653,6 +2795,7 @@ export async function correctSentEnvelopeSigner(signerEmail: signer.email,signerId,signerName: signer.name,+ signerOrder: signer.signOrder,userId,} satisfies PersistedSignerCorrection;}@@ -2797,6 +2940,7 @@ export async function correctSentEnvelopeSigner(signerEmail: nextEmail,signerId,signerName: nextName,+ signerOrder: signer.signOrder,userId,} satisfies PersistedSignerCorrection;}, database);@@ -2811,10 +2955,11 @@ export async function correctSentEnvelopeSigner(});}- const mailer = emailService ?? createEmailService();let invitationMessageId: string | undefined;try {+ const mailer = emailService ?? createEmailService();+invitationMessageId = (await mailer.send(buildSigningInvitationEmail({@@ -2829,72 +2974,14 @@ export async function correctSentEnvelopeSigner()).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,- );- });+ await revertFailedSignerCorrection(persisted, context, database).catch(+ (rollbackError) => {+ console.error(+ `Failed to roll back a signer correction for envelope ${persisted.envelopeId} after email delivery failure:`,+ rollbackError,+ );+ },+ );throw error;}diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.tsindex fc2f2dc..69be673 100644--- a/src/lib/services/audit.ts+++ b/src/lib/services/audit.ts@@ -54,6 +54,14 @@ export function describeSignerCorrectedEvent(return `Signer name corrected from ${previousName} to ${name}`;}+ // Recipient certificates strip addresses. Name-only wording still holds;+ // an email-only change has to be named without the addresses themselves.+ if (!previousEmail && !email && previousName && name) {+ return previousName === name+ ? "Signer email was corrected"+ : `Signer name corrected from ${previousName} to ${name}`;+ }+return `Signer corrected from ${formatSignerPerson(previousName, previousEmail)} to ${formatSignerPerson(name, email)}`;}@@ -115,7 +123,7 @@ export async function listAuditEventsForEnvelope(created_at AS "createdAt"FROM audit_eventsWHERE envelope_id = $1- ORDER BY created_at ASC, id ASC+ ORDER BY sequence ASC NULLS FIRST, created_at ASC, id ASC`,[envelopeId],);diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.tsindex 12ba2af..0e3c10b 100644--- a/src/lib/services/pdf-finalize.test.ts+++ b/src/lib/services/pdf-finalize.test.ts@@ -264,6 +264,110 @@ test("the certificate names the people who were sent a copy", async () => {assert.ok(!(await extractText(without)).includes("Copy recipients"));});+test("recipient certificates omit a correction's previous email", async () => {+ const fixture = await makeFixture();+ const previousEmail = "[email protected]";+ const auditEvents: AuditEventRecord[] = [+ {+ actorEmail: "[email protected]",+ actorType: "sender",+ createdAt: 1_800_000_000 - 50,+ envelopeId: fixture.envelope.id,+ event: "signer_corrected",+ id: "event-correction",+ metadata: {+ previousEmail,+ previousName: SIGNER_NAME,+ signerEmail: "[email protected]",+ signerId: "signer-1",+ signerName: SIGNER_NAME,+ },+ },+ ...fixture.auditEvents,+ ];+ const render = (redactForRecipients: boolean) =>+ renderEnvelopeCertificatePdf(+ {+ auditEvents,+ envelope: fixture.envelope,+ redactForRecipients,+ signers: fixture.signers,+ },+ { seal: saveUnsealed },+ ).then(async (bytes) => (await extractText(bytes)).replace(/\s+/g, " "));+ const full = await render(false);+ const redacted = await render(true);++ assert.ok(full.includes(previousEmail));+ assert.ok(full.includes("Signer email corrected from"));+ assert.ok(!redacted.includes(previousEmail));+ assert.ok(redacted.includes("Signer email was corrected"));+});++test("the certificate credits consent recorded after a signer correction", async () => {+ const fixture = await makeFixture();+ const auditEvents: AuditEventRecord[] = [+ {+ actorEmail: "[email protected]",+ actorType: "signer",+ createdAt: 1_799_999_000,+ envelopeId: fixture.envelope.id,+ event: "consented",+ id: "event-old-consent",+ metadata: {+ disclosureVersion: "old-version",+ signerId: "signer-1",+ signerName: SIGNER_NAME,+ },+ },+ {+ actorEmail: "[email protected]",+ actorType: "sender",+ createdAt: 1_799_999_010,+ envelopeId: fixture.envelope.id,+ event: "signer_corrected",+ id: "event-correction",+ metadata: {+ previousEmail: "[email protected]",+ previousName: SIGNER_NAME,+ signerEmail: "[email protected]",+ signerId: "signer-1",+ signerName: SIGNER_NAME,+ },+ },+ {+ actorEmail: "[email protected]",+ actorType: "signer",+ createdAt: 1_800_000_050,+ envelopeId: fixture.envelope.id,+ event: "consented",+ id: "event-new-consent",+ metadata: {+ disclosureVersion: "new-version",+ signerId: "signer-1",+ signerName: SIGNER_NAME,+ },+ },+ ...fixture.auditEvents,+ ];+ const text = (+ await extractText(+ await renderEnvelopeCertificatePdf(+ {+ auditEvents,+ envelope: fixture.envelope,+ signers: fixture.signers,+ },+ { seal: saveUnsealed },+ ),+ )+ ).replace(/\s+/g, " ");+ const signersSection = text.split("Audit events")[0] ?? "";++ assert.ok(signersSection.includes("disclosure new-version"));+ assert.ok(!signersSection.includes("disclosure old-version"));+});+test("numbers and dropdown choices are stamped as text, radio buttons as rings", async () => {const fixture = await makeFixture();const base = {diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 2b779ae..0df5ba4 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -132,6 +132,8 @@ function redactAuditEventMetadataForRecipients(delete nextMetadata.signerEmail;// Who an email went to is another party's address.delete nextMetadata.recipient;+ // A correction's previous address is the same kind of third-party email.+ delete nextMetadata.previousEmail;return Object.keys(nextMetadata).length > 0 ? nextMetadata : null;}@@ -890,7 +892,18 @@ function describeSignerEvidence();const details: string[] = [];const signed = forSigner.find((event) => event.event === "signed");- const consented = forSigner.find((event) => event.event === "consented");+ // 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 correction counts as this recipient's.+ const latestCorrectionIndex = forSigner.reduce(+ (found, event, index) =>+ event.event === "signer_corrected" ? index : found,+ -1,+ );+ const consented = forSigner.find(+ (event, index) =>+ event.event === "consented" && index > latestCorrectionIndex,+ );const checks = ["possession of the emailed signing link",...readStringArray(signed?.metadata?.authMethods).map(diff --git a/src/lib/signer-correction.dbtest.ts b/src/lib/signer-correction.dbtest.tsindex a59733f..60759e1 100644--- a/src/lib/signer-correction.dbtest.ts+++ b/src/lib/signer-correction.dbtest.ts@@ -1,26 +1,51 @@import assert from "node:assert/strict";import { 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 { ZodError } from "zod";+import { PDFDocument } from "pdf-lib";import type pg from "pg";import { exportEnvelopeAuditCsv } from "./audit-export.ts";-import { openTestDatabase } from "./db/test-database.ts";+import { afterStatement, openTestDatabase } from "./db/test-database.ts";+import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";import {correctSentEnvelopeSigner,EnvelopeMutationError,getEnvelopeDetailDataForUser,} from "./envelopes.ts";-import { duplicateSignerEmailMessage } from "./schemas/signer.ts";-import { verifyAuditChain } from "./services/audit.ts";+import type { EnvelopeRecord } from "./schemas/envelope.ts";+import {+ duplicateSignerEmailMessage,+ type SignerRecord,+} from "./schemas/signer.ts";+import {+ listAuditEventsForEnvelope,+ recordAuditEvent,+ verifyAuditChain,+} from "./services/audit.ts";import type {EmailService,TransactionalEmailMessage,} from "./services/email.ts";import { hashOpaqueToken } from "./services/opaque-tokens.ts";+import { renderEnvelopeCertificatePdf } from "./services/pdf-finalize.ts";import { issueSigningLink } from "./services/signing-links.ts";-import { getSigningPayloadForToken, SigningAccessError } from "./signing.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import {+ declineSigningForToken,+ getSigningPayloadForToken,+ recordSignerConsent,+ SigningAccessError,+ SigningMutationError,+ submitSigningForToken,+} 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`.@@ -245,6 +270,182 @@ function correct();}+const DRAWN_SIGNATURE =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";++function stubStorage(putObject?: StorageService["putObject"]): StorageService {+ const refuse = async (): Promise<never> => {+ throw new Error("not used");+ };++ return {+ deleteObject: async () => undefined,+ getObject: refuse,+ getObjectStream: refuse,+ headObject: refuse,+ putObject: putObject ?? (async ({ key }) => ({ bucketName: "test", key })),+ };+}++async function addSignatureField(envelopeId: string, signerId: string) {+ const 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, 0.1, 0.2, 0.1)+ `,+ [fieldId, envelopeId, signerId],+ );++ return fieldId;+}++function consent(token: string) {+ return recordSignerConsent(+ token,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database },+ );+}++function submitDrawn(+ token: string,+ fieldId: string,+ {+ emailService = recordingEmailService().service,+ storageService = stubStorage(),+ }: {+ emailService?: EmailService;+ storageService?: StorageService;+ } = {},+) {+ return submitSigningForToken(+ token,+ {+ clientTimezoneOffsetMinutes: 0,+ fields: [+ {+ fieldId,+ imageDataUrl: DRAWN_SIGNATURE,+ inputMethod: "drawn",+ type: "signature",+ },+ ],+ },+ { database, emailService, storageService },+ );+}++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 renderCorrectionCertificates(envelopeId: string) {+ const envelopeRow = await database.query<{+ created_at: number;+ source_pdf_filename: string;+ source_pdf_hash: string;+ source_pdf_key: string;+ source_pdf_size_bytes: number;+ title: string;+ updated_at: number;+ user_id: string;+ }>(+ `+ select created_at, source_pdf_filename, source_pdf_hash, source_pdf_key,+ source_pdf_size_bytes, title, updated_at, user_id+ from envelopes+ where id = $1+ `,+ [envelopeId],+ );+ const row = envelopeRow.rows[0]!;+ const now = unixNow();+ const envelope: EnvelopeRecord = {+ completedAt: now,+ createdAt: row.created_at,+ declinedAt: null,+ evidenceKey: null,+ id: envelopeId,+ pageCount: 1,+ sentAt: now - 60,+ signedPdfKey: null,+ sourcePdfFilename: row.source_pdf_filename,+ sourcePdfHash: row.source_pdf_hash,+ sourcePdfKey: row.source_pdf_key,+ sourcePdfSizeBytes: row.source_pdf_size_bytes,+ status: "completed",+ title: row.title,+ updatedAt: row.updated_at,+ userId: row.user_id,+ voidedAt: null,+ };+ const signerRows = await database.query<{+ created_at: number;+ email: string;+ id: string;+ name: string;+ sign_order: number;+ signed_at: number | null;+ status: SignerRecord["status"];+ updated_at: number;+ }>(+ `+ select created_at, email, id, name, sign_order, signed_at, status, updated_at+ from signers+ where envelope_id = $1 and role = 'signer'+ order by sign_order+ `,+ [envelopeId],+ );+ const signers: SignerRecord[] = signerRows.rows.map((signer) => ({+ createdAt: signer.created_at,+ email: signer.email,+ id: signer.id,+ name: signer.name,+ signedAt: signer.signed_at,+ signOrder: signer.sign_order,+ status: signer.status === "notified" ? "signed" : signer.status,+ updatedAt: signer.updated_at,+ }));+ const auditEvents = await listAuditEventsForEnvelope(envelopeId, database);+ const seal = (pdfDocument: PDFDocument) => pdfDocument.save();+ const full = await renderEnvelopeCertificatePdf(+ { auditEvents, envelope, signers },+ { seal },+ );+ const redacted = await renderEnvelopeCertificatePdf(+ { auditEvents, envelope, redactForRecipients: true, signers },+ { seal },+ );++ return {+ full: await extractPdfText(full),+ redacted: await extractPdfText(redacted),+ };+}+test("correcting a notified signer rotates the link and emails the new address", async () => {const { userId } = await createOwner();const envelopeId = await createEnvelope({ userId });@@ -598,3 +799,435 @@ test("a failed invitation leaves the old name, email and link in place", async (assert.equal(stored.signing_token_hash, signer.tokenHash);assert.deepEqual(await auditEvents(envelopeId), []);});++test("recipient certificates omit a correction's previous email", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const previousEmail = `previous.${randomUUID()}@hide.test`;+ const signer = await createSigner({+ email: previousEmail,+ envelopeId,+ });+ const { service } = recordingEmailService();++ await correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ service,+ );++ const { full, redacted } = await renderCorrectionCertificates(envelopeId);++ assert.ok(full.includes(previousEmail));+ assert.ok(full.includes("Signer email corrected from"));+ assert.ok(!redacted.includes(previousEmail));+ assert.ok(redacted.includes("Signer email was corrected"));+});++test("the certificate credits consent recorded after a signer correction", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const oldConsentAt = unixNow() - 3_600;+ const signer = await createSigner({+ envelopeId,+ extra: { consentedAt: oldConsentAt },+ });++ await recordAuditEvent(+ {+ actorEmail: signer.email,+ actorType: "signer",+ createdAt: oldConsentAt,+ envelopeId,+ event: "consented",+ metadata: {+ disclosureVersion: "old-version",+ signerId: signer.signerId,+ signerName: "Riley Recipient",+ },+ },+ database,+ );++ const { sent, service } = recordingEmailService();++ await correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ service,+ );++ const match = sent[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,+ );+ assert.ok(!compactSigners.includes("disclosureold-version"));+});++test("an in-flight submit on the old link cannot finish after a correction", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const first = await createSigner({ envelopeId });+ await createSigner({+ envelopeId,+ name: "Casey Second",+ signOrder: 2,+ status: "pending",+ });+ const fieldId = await addSignatureField(envelopeId, first.signerId);+ await consent(first.token!);+ const { service } = recordingEmailService();+ const storageService = stubStorage(async ({ key }) => {+ await correct(+ userId,+ envelopeId,+ first.signerId,+ { email: "[email protected]" },+ service,+ );++ return { bucketName: "test", key };+ });++ await assert.rejects(+ submitDrawn(first.token!, fieldId, { storageService }),+ (error: unknown) => {+ assert.ok(error instanceof SigningMutationError);+ assert.equal(error.statusCode, 409);+ return true;+ },+ );++ const stored = await readSigner(first.signerId);+ assert.equal(stored.status, "notified");+ assert.equal(stored.email, "[email protected]");+ assert.notEqual(stored.signing_token_hash, first.tokenHash);+});++test("an in-flight consent on the old link cannot finish after a correction", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const signer = await createSigner({ envelopeId });+ const { service } = recordingEmailService();+ const pool = afterStatement(+ database,+ (text) => text.includes('access_code_hash AS "accessCodeHash"'),+ async () => {+ await correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ service,+ );+ },+ );++ await assert.rejects(+ recordSignerConsent(+ signer.token!,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database: pool },+ ),+ (error: unknown) => {+ assert.ok(error instanceof SigningMutationError);+ assert.equal(error.statusCode, 409);+ return true;+ },+ );++ assert.equal((await readSigner(signer.signerId)).consented_at, null);+});++test("an in-flight decline on the old link cannot finish after a correction", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const signer = await createSigner({ envelopeId });+ const storageDir = await mkdtemp(+ path.join(tmpdir(), "signudoc-correct-decline-"),+ );+ const storageService = createStorageService({+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },+ });+ const sourcePdf = await PDFDocument.create();++ sourcePdf.addPage([612, 792]);++ const sourcePdfBytes = await sourcePdf.save();++ await storageService.putObject({+ body: sourcePdfBytes,+ contentType: "application/pdf",+ key: `test/${envelopeId}.pdf`,+ });+ await database.query(+ `+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)+ values ($1, $2, 1, 612, 792)+ `,+ [randomUUID(), envelopeId],+ );+ await consent(signer.token!);++ const { service } = recordingEmailService();+ const settings = {+ EMAIL_CAPTURE_DIR: path.join(storageDir, "outbox"),+ EMAIL_DRIVER: "capture",+ STORAGE_DRIVER: "local",+ STORAGE_LOCAL_DIR: storageDir,+ };+ const settingsBefore = Object.keys(settings).map(+ (name) => [name, process.env[name]] as const,+ );++ Object.assign(process.env, settings);++ const pool = afterStatement(+ database,+ (text) => text.includes('access_code_hash AS "accessCodeHash"'),+ async () => {+ await correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ service,+ );+ },+ );++ try {+ await assert.rejects(+ declineSigningForToken(+ signer.token!,+ { reason: "Changed mind." },+ {+ database: pool,+ },+ ),+ (error: unknown) => {+ assert.ok(error instanceof SigningMutationError);+ assert.equal(error.statusCode, 409);+ return true;+ },+ );+ assert.equal((await readSigner(signer.signerId)).status, "notified");+ } finally {+ for (const [name, value] of settingsBefore) {+ if (value === undefined) {+ delete process.env[name];+ } else {+ process.env[name] = value;+ }+ }++ await rm(storageDir, { force: true, recursive: true });+ }+});++test("activating the next signer emails the address stored under the lock", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const first = await createSigner({ envelopeId });+ const pending = await createSigner({+ email: "[email protected]",+ envelopeId,+ name: "Casey Second",+ signOrder: 2,+ status: "pending",+ });+ const fieldId = await addSignatureField(envelopeId, first.signerId);+ await consent(first.token!);+ const { sent, service } = recordingEmailService();+ const storageService = stubStorage(async ({ key }) => {+ await correct(+ userId,+ envelopeId,+ pending.signerId,+ { email: "[email protected]" },+ service,+ );++ return { bucketName: "test", key };+ });++ await submitDrawn(first.token!, fieldId, {+ emailService: service,+ storageService,+ });++ const invitation = sent.find(+ (message) => message.template === "signing_invitation",+ );++ assert.equal(invitation?.to, "[email protected]");+ assert.equal(+ (await readSigner(pending.signerId)).email,+ "[email protected]",+ );+ assert.equal((await readSigner(pending.signerId)).status, "notified");+ assert.ok(!sent.some((message) => message.to === "[email protected]"));+});++test("a failed invitation does not undo a later correction of the same signer", async () => {+ const { userId } = await createOwner();+ 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");+ },+ };++ await assert.rejects(+ correct(+ userId,+ envelopeId,+ signer.signerId,+ { email: "[email protected]" },+ serviceA,+ ),+ { message: "mailbox down" },+ );++ const stored = await readSigner(signer.signerId);+ assert.equal(stored.email, "[email protected]");+ assert.notEqual(stored.signing_token_hash, signer.tokenHash);+ assert.equal(sentB.length, 1);+ assert.equal(sentB[0]?.to, "[email protected]");+ await assert.rejects(getSigningPayloadForToken(signer.token!, { database }), {+ name: "SigningAccessError",+ });+ assert.deepEqual(await auditEvents(envelopeId), [+ "signer_corrected",+ "signer_corrected",+ "email_sent",+ ]);+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);+});++test("a failed invitation records a reversal when a later event blocks deleting it", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const signer = await createSigner({ envelopeId });+ const service: EmailService = {+ async send() {+ await recordAuditEvent(+ {+ actorEmail: "[email protected]",+ actorType: "signer",+ envelopeId,+ event: "viewed",+ metadata: { signerId: signer.signerId },+ },+ database,+ );+ throw new Error("mailbox down");+ },+ async sendBatch() {+ throw new Error("not used");+ },+ };++ 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), [+ "signer_corrected",+ "viewed",+ "signer_corrected",+ ]);+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);++ const csv = await exportEnvelopeAuditCsv(userId, envelopeId, database);+ assert.match(+ csv.body,+ /Signer email corrected from .* to riley\.fixed@example\.test/,+ );+ assert.match(+ csv.body,+ /Signer email corrected from riley\.fixed@example\.test to /,+ );+});++test("a missing email configuration rolls the correction back", async () => {+ const { userId } = await createOwner();+ const envelopeId = await createEnvelope({ userId });+ const signer = await createSigner({ envelopeId });+ const previous = {+ EMAIL_DRIVER: process.env.EMAIL_DRIVER,+ RESEND_API_KEY: process.env.RESEND_API_KEY,+ };++ process.env.EMAIL_DRIVER = "resend";+ delete process.env.RESEND_API_KEY;++ try {+ await assert.rejects(+ correct(userId, envelopeId, signer.signerId, {+ email: "[email protected]",+ }),+ (error: unknown) => {+ assert.ok(error instanceof Error);+ assert.match(error.message, /RESEND_API_KEY/);+ return true;+ },+ );+ } finally {+ if (previous.EMAIL_DRIVER === undefined) {+ delete process.env.EMAIL_DRIVER;+ } else {+ process.env.EMAIL_DRIVER = previous.EMAIL_DRIVER;+ }++ if (previous.RESEND_API_KEY === undefined) {+ delete process.env.RESEND_API_KEY;+ } else {+ process.env.RESEND_API_KEY = previous.RESEND_API_KEY;+ }+ }++ 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.tsindex 4a47245..839efaa 100644--- a/src/lib/signer-correction.test.ts+++ b/src/lib/signer-correction.test.ts@@ -67,4 +67,18 @@ test("a signer_corrected event is described in plain words", () => {}),"Signer corrected from Rily <[email protected]> to Riley Recipient <[email protected]>",);+ assert.equal(+ describeSignerCorrectedEvent({+ previousName: "Riley Recipient",+ signerName: "Riley Recipient",+ }),+ "Signer email was corrected",+ );+ assert.equal(+ describeSignerCorrectedEvent({+ previousName: "Rily",+ signerName: "Riley Recipient",+ }),+ "Signer name corrected from Rily to Riley Recipient",+ );});diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex f2f2f54..1e156e8 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -767,6 +767,46 @@ async function lockSentEnvelope(}}+/**+ * Confirms this request still holds the waiting signer's current link+ * before any of their rows are written. The token is read once when the+ * page is opened; a correction can replace the hash in the meantime and+ * leave status as notified, which the later UPDATE used to treat as enough.+ */+async function lockSignerForPresentedToken(+ tx: DbExecutor,+ {+ envelopeId,+ signerId,+ tokenHash,+ }: {+ envelopeId: string;+ signerId: string;+ tokenHash: string;+ },+): Promise<void> {+ const locked = await queryOne<{ id: string }>(+ tx,+ `+ SELECT id+ FROM signers+ WHERE id = $1+ AND envelope_id = $2+ AND status = 'notified'+ AND signing_token_hash = $3+ FOR NO KEY UPDATE+ `,+ [signerId, envelopeId, tokenHash],+ );++ if (!locked) {+ throw new SigningMutationError(+ "This signing link is no longer active.",+ 409,+ );+ }+}+async function recordViewedEventOnce(context: Pick<ResolvedSigningContext, "envelope" | "signer">,meta: SigningRequestMeta,@@ -1307,6 +1347,7 @@ export async function sendSignerEmailCode(const branding = await getBranding();// Claim the resend window and save the code in one statement, so two// tabs cannot both send, leaving one emailed code already replaced.+ const presentedTokenHash = hashOpaqueToken(token);const claimed = await database.query(`UPDATE signers@@ -1316,6 +1357,7 @@ export async function sendSignerEmailCode(email_code_attempts = 0,email_code_sent_at = $3WHERE id = $4+ AND signing_token_hash = $6AND (email_code_hash IS NULLOR email_code_sent_at IS NULL@@ -1328,10 +1370,28 @@ export async function sendSignerEmailCode(now,context.signer.id,now - EMAIL_CODE_RESEND_SECONDS,+ presentedTokenHash,],);if (claimed.rowCount !== 1) {+ const stillThisLink = await queryOne<{ id: string }>(+ database,+ `+ SELECT id+ FROM signers+ WHERE id = $1 AND signing_token_hash = $2+ `,+ [context.signer.id, presentedTokenHash],+ );++ if (!stillThisLink) {+ throw new SigningMutationError(+ "This signing link is no longer active.",+ 409,+ );+ }+const current = await getSignerCheckState(context.signer.id!, database);return {@@ -1489,12 +1549,13 @@ export async function verifySignerCheck(UPDATE signersSET email_code_attempts = email_code_attempts + 1WHERE id = $1+ AND signing_token_hash = $4AND email_code_hash IS NOT NULLAND email_code_expires_at >= $2AND email_code_attempts < $3RETURNING email_code_hash AS hash, email_code_attempts AS attempts`,- [context.signer.id, now, EMAIL_CODE_MAX_ATTEMPTS],+ [context.signer.id, now, EMAIL_CODE_MAX_ATTEMPTS, hashOpaqueToken(token)],);const current = attempt.rows[0];@@ -1579,18 +1640,44 @@ export async function recordSignerConsent(}const consentedAt = Math.floor(Date.now() / 1000);+ const presentedTokenHash = hashOpaqueToken(token);await withTransaction(async (tx) => {const updated = await tx.query(`UPDATE signersSET consented_at = $1- WHERE id = $2 AND consented_at IS NULL+ WHERE id = $2+ AND consented_at IS NULL+ AND status = 'notified'+ AND signing_token_hash = $3`,- [consentedAt, context.signer.id],+ [consentedAt, context.signer.id, presentedTokenHash],);if (updated.rowCount !== 1) {+ const current = await queryOne<{+ consentedAt: number | null;+ signingTokenHash: string | null;+ }>(+ tx,+ `+ SELECT+ consented_at AS "consentedAt",+ signing_token_hash AS "signingTokenHash"+ FROM signers+ WHERE id = $1+ `,+ [context.signer.id],+ );++ if (!current || current.signingTokenHash !== presentedTokenHash) {+ throw new SigningMutationError(+ "This signing link is no longer active.",+ 409,+ );+ }+return;}@@ -2277,6 +2364,7 @@ export async function submitSigningForToken(drawnSignatureUploads,fieldUpdates,} = buildSignerSubmission(context, parsedInput, submittedAt);+ const presentedTokenHash = hashOpaqueToken(token);let signingStatePersisted = false;@@ -2289,6 +2377,9 @@ export async function submitSigningForToken(? context.signers[currentSignerIndex + 1]: undefined;let nextSignerLink: IssuedSigningLink | undefined;+ let nextSignerDelivery:+ { email: string; id: string; name: string } | undefined;+ const nextSignerId = nextSigner?.id;if (nextSigner) {if (nextSigner.status !== "pending") {@@ -2298,7 +2389,7 @@ export async function submitSigningForToken();}- if (!nextSigner.id) {+ if (!nextSignerId) {throw new SigningMutationError("Envelope routing is out of sync for the next signer.",500,@@ -2347,6 +2438,13 @@ export async function submitSigningForToken(});if (nextSigner && nextSignerLink) {+ if (!nextSignerId) {+ throw new SigningMutationError(+ "Envelope routing is out of sync for the next signer.",+ 500,+ );+ }+// The deadline the next signer is given. The sender can move it while// this signer submits, and moving it only reaches the signer whose// turn it is then. So it is read here, where this update holds the@@ -2385,6 +2483,12 @@ export async function submitSigningForToken();}+ await lockSignerForPresentedToken(tx, {+ envelopeId: context.envelope.id,+ signerId: currentSignerId,+ tokenHash: presentedTokenHash,+ });+for (const update of fieldUpdates.values()) {const result = await tx.query(`@@ -2433,8 +2537,15 @@ export async function submitSigningForToken(WHERE id = $3AND envelope_id = $4AND status = 'notified'+ AND signing_token_hash = $5`,- [submittedAt, submittedAt, currentSignerId, context.envelope.id],+ [+ submittedAt,+ submittedAt,+ currentSignerId,+ context.envelope.id,+ presentedTokenHash,+ ],);if (signedSignerResult.rowCount !== 1) {@@ -2444,7 +2555,11 @@ export async function submitSigningForToken();}- const nextSignerResult = await tx.query(+ const activatedNextSigner = await queryOne<{+ email: string;+ name: string;+ }>(+ tx,`UPDATE signersSET@@ -2457,6 +2572,7 @@ export async function submitSigningForToken(WHERE id = $6AND envelope_id = $7AND status = 'pending'+ RETURNING name, email`,[nextSignerLink.tokenHash,@@ -2464,18 +2580,24 @@ export async function submitSigningForToken(routedAt,routedAt,routedAt,- nextSigner.id,+ nextSignerId,context.envelope.id,],);- if (nextSignerResult.rowCount !== 1) {+ if (!activatedNextSigner) {throw new SigningMutationError("Unable to activate the next signer for this envelope.",500,);}+ nextSignerDelivery = {+ email: activatedNextSigner.email,+ id: nextSignerId,+ name: activatedNextSigner.name,+ };+await recordAuditEvent({actorEmail: signedAuditEvent.actorEmail,@@ -2494,6 +2616,13 @@ export async function submitSigningForToken(signingStatePersisted = true;await deleteReplacedRevision(replacedRevisionKey, storageService);+ if (!nextSignerDelivery) {+ throw new SigningMutationError(+ "Unable to activate the next signer for this envelope.",+ 500,+ );+ }+try {const delivery = await emailService.send(buildSigningInvitationEmail({@@ -2501,8 +2630,8 @@ export async function submitSigningForToken(envelopeTitle: context.envelope.title,expiresAt: nextSignerDeadline,senderName: normalizeSenderName(context.sender),- signerEmail: nextSigner.email,- signerName: nextSigner.name,+ signerEmail: nextSignerDelivery.email,+ signerName: nextSignerDelivery.name,signingUrl: nextSignerLink.url,}),);@@ -2511,15 +2640,15 @@ export async function submitSigningForToken({envelopeId: context.envelope.id,messageId: delivery.messageId,- recipient: nextSigner.email,- signerId: nextSigner.id,+ recipient: nextSignerDelivery.email,+ signerId: nextSignerDelivery.id,template: "signing_invitation",},database,);} catch (error) {console.error(- `Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSigner.email}:`,+ `Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSignerDelivery.email}:`,error,);}@@ -2587,6 +2716,11 @@ export async function submitSigningForToken(finalArtifacts = await withTransaction(async (tx) => {await lockSentEnvelope(context.envelope.id, tx);await assertStillSignersTurn(context.envelope.id, currentSignerId, tx);+ await lockSignerForPresentedToken(tx, {+ envelopeId: context.envelope.id,+ signerId: currentSignerId,+ tokenHash: presentedTokenHash,+ });// Made while the envelope is locked: the files have fixed keys, and// a second submission at the same time waits, then stops above.@@ -2668,8 +2802,15 @@ export async function submitSigningForToken(WHERE id = $3AND envelope_id = $4AND status = 'notified'+ AND signing_token_hash = $5`,- [submittedAt, submittedAt, currentSignerId, context.envelope.id],+ [+ submittedAt,+ submittedAt,+ currentSignerId,+ context.envelope.id,+ presentedTokenHash,+ ],);if (signedSignerResult.rowCount !== 1) {@@ -2883,6 +3024,7 @@ export async function declineSigningForToken(const emailService = createEmailService();const storageService = createStorageService();const currentSignerId = context.signer.id;+ const presentedTokenHash = hashOpaqueToken(token);if (!currentSignerId) {throw new SigningMutationError(@@ -2988,6 +3130,11 @@ export async function declineSigningForToken(try {await withTransaction(async (tx) => {await lockSentEnvelope(context.envelope.id, tx);+ await lockSignerForPresentedToken(tx, {+ envelopeId: context.envelope.id,+ signerId: currentSignerId,+ tokenHash: presentedTokenHash,+ });const declinedSignerResult = await tx.query(`@@ -3002,6 +3149,7 @@ export async function declineSigningForToken(WHERE id = $4AND envelope_id = $5AND status = 'notified'+ AND signing_token_hash = $6`,[declinedAt,@@ -3009,6 +3157,7 @@ export async function declineSigningForToken(declinedAt,currentSignerId,context.envelope.id,+ presentedTokenHash,],);