Skip to content

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

TypeScript

Keep a failed signer correction out of the audit trail

Matt Van Horneb8e562088bc
diff --git a/db/migrations/20261116090000_signer_corrected.sql b/db/migrations/20261116100000_signer_corrected.sql
similarity index 100%
rename from db/migrations/20261116090000_signer_corrected.sql
rename to db/migrations/20261116100000_signer_corrected.sql
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index f18c9af..800eb4a 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -2476,7 +2476,7 @@ const SENT_ENVELOPE_SIGNER_CORRECTION_MESSAGE =
"Only an envelope that is out for signature can have a signer corrected.";
type PersistedSignerCorrection = {
- auditEventId: string;
+ correctedAt: number;
envelopeExpiresAt: number | null;
envelopeId: string;
envelopeTitle: string;
@@ -2505,16 +2505,15 @@ type PersistedSignerCorrection = {
/**
* 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.
+ * 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,
- context: CorrectSentEnvelopeSignerContext,
database: DbPool,
): Promise<void> {
const issuedLink = persisted.issuedLink;
@@ -2585,61 +2584,18 @@ async function revertFailedSignerCorrection(
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
+ AND updated_at = $3
`,
- [reversedAt, persisted.envelopeId],
+ [
+ persisted.envelopeUpdatedAt,
+ persisted.envelopeId,
+ persisted.correctedAt,
+ ],
);
}, database);
}
@@ -2772,7 +2728,7 @@ export async function correctSentEnvelopeSigner(
nextEmail.toLowerCase() === signer.email.toLowerCase()
) {
return {
- auditEventId: "",
+ correctedAt: nowUnixTimestamp,
envelopeExpiresAt: envelope.expiresAt,
envelopeId,
envelopeTitle: envelope.title,
@@ -2895,29 +2851,34 @@ export async function correctSentEnvelopeSigner(
[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,
+ // 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) {
+ 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,
},
- userAgent: context.userAgent ?? null,
- },
- tx,
- );
+ tx,
+ );
+ }
return {
- auditEventId: auditEvent.id,
+ correctedAt: nowUnixTimestamp,
envelopeExpiresAt: envelope.expiresAt,
envelopeId,
envelopeTitle: envelope.title,
@@ -2974,7 +2935,7 @@ export async function correctSentEnvelopeSigner(
)
).messageId;
} catch (error) {
- await revertFailedSignerCorrection(persisted, context, database).catch(
+ await revertFailedSignerCorrection(persisted, database).catch(
(rollbackError) => {
console.error(
`Failed to roll back a signer correction for envelope ${persisted.envelopeId} after email delivery failure:`,
@@ -2986,6 +2947,26 @@ export async function correctSentEnvelopeSigner(
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,
diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.ts
index 0e3c10b..74fcf2d 100644
--- a/src/lib/services/pdf-finalize.test.ts
+++ b/src/lib/services/pdf-finalize.test.ts
@@ -368,6 +368,72 @@ test("the certificate credits consent recorded after a signer correction", async
assert.ok(!signersSection.includes("disclosure old-version"));
});
+test("the certificate keeps restored consent after a reversed 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-kept-consent",
+ metadata: {
+ disclosureVersion: "kept-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: "sender",
+ createdAt: 1_799_999_020,
+ envelopeId: fixture.envelope.id,
+ event: "signer_corrected",
+ id: "event-reversal",
+ metadata: {
+ previousEmail: "[email protected]",
+ previousName: SIGNER_NAME,
+ reverted: true,
+ signerEmail: "[email protected]",
+ 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 kept-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.ts
index 0df5ba4..3617d40 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -881,6 +881,41 @@ function describeProviderSignatureEvidence(
return details;
}
+function isRevertedSignerCorrection(event: AuditEventRecord): boolean {
+ return (
+ event.event === "signer_corrected" && event.metadata?.reverted === true
+ );
+}
+
+/**
+ * Index at which this signer's current identity begins. A correction that
+ * was later reversed restores the previous identity, so earlier consent
+ * still counts.
+ */
+function currentSignerIdentityStart(
+ events: readonly AuditEventRecord[],
+): number {
+ const starts = [0];
+
+ for (let index = 0; index < events.length; index += 1) {
+ const event = events[index];
+
+ if (event?.event !== "signer_corrected") {
+ continue;
+ }
+
+ if (isRevertedSignerCorrection(event)) {
+ if (starts.length > 1) {
+ starts.pop();
+ }
+ } else {
+ starts.push(index + 1);
+ }
+ }
+
+ return starts[starts.length - 1] ?? 0;
+}
+
/** What the record shows about how one signer was identified and agreed. */
function describeSignerEvidence(
signer: SignerRecord,
@@ -894,16 +929,21 @@ function describeSignerEvidence(
const signed = forSigner.find((event) => event.event === "signed");
// 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,
- );
+ // recorded after the latest standing correction counts as this
+ // recipient's. A reversal restores the earlier identity, including that
+ // earlier agreement.
+ const identityStart = currentSignerIdentityStart(forSigner);
+ let consented: AuditEventRecord | undefined;
+
+ for (let index = forSigner.length - 1; index >= identityStart; index -= 1) {
+ const event = forSigner[index];
+
+ if (event?.event === "consented") {
+ consented = event;
+ break;
+ }
+ }
+
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.ts
index 60759e1..7d36e25 100644
--- a/src/lib/signer-correction.dbtest.ts
+++ b/src/lib/signer-correction.dbtest.ts
@@ -1127,14 +1127,19 @@ test("a failed invitation does not undo a later correction of the same signer",
name: "SigningAccessError",
});
assert.deepEqual(await auditEvents(envelopeId), [
- "signer_corrected",
"signer_corrected",
"email_sent",
]);
assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
+ const csv = await exportEnvelopeAuditCsv(userId, envelopeId, database);
+ 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/,
+ );
});
-test("a failed invitation records a reversal when a later event blocks deleting it", async () => {
+test("a failed invitation leaves no correction in the audit trail when a later event is recorded", async () => {
const { userId } = await createOwner();
const envelopeId = await createEnvelope({ userId });
const signer = await createSigner({ envelopeId });
@@ -1142,7 +1147,7 @@ test("a failed invitation records a reversal when a later event blocks deleting
async send() {
await recordAuditEvent(
{
- actorEmail: "[email protected]",
+ actorEmail: signer.email,
actorType: "signer",
envelopeId,
event: "viewed",
@@ -1171,28 +1176,92 @@ test("a failed invitation records a reversal when a later event blocks deleting
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.deepEqual(await auditEvents(envelopeId), ["viewed"]);
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.doesNotMatch(csv.body, /Signer corrected/);
+ assert.doesNotMatch(csv.body, /riley\.fixed@example\.test/);
+});
+
+test("a failed invitation restores consent and keeps it on the certificate", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const consentedAt = unixNow() - 60;
+ const signer = await createSigner({
+ envelopeId,
+ extra: { consentedAt },
+ });
+
+ await recordAuditEvent(
+ {
+ actorEmail: signer.email,
+ actorType: "signer",
+ createdAt: consentedAt,
+ envelopeId,
+ event: "consented",
+ metadata: {
+ disclosureVersion: "kept-version",
+ signerId: signer.signerId,
+ signerName: "Riley Recipient",
+ },
+ },
+ database,
);
- assert.match(
- csv.body,
- /Signer email corrected from riley\.fixed@example\.test to /,
+
+ 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.consented_at, consentedAt);
+ assert.deepEqual(await auditEvents(envelopeId), ["consented", "viewed"]);
+
+ const { full } = await renderCorrectionCertificates(envelopeId);
+ const signersSection = (full.split("Audit events")[0] ?? "").replace(
+ /\s+/g,
+ " ",
+ );
+ const compactSigners = signersSection.replaceAll(" ", "");
+
+ assert.ok(compactSigners.includes("disclosurekept-version"), signersSection);
});
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 consentedAt = unixNow() - 10;
+ const signer = await createSigner({
+ envelopeId,
+ extra: { consentedAt },
+ });
const previous = {
EMAIL_DRIVER: process.env.EMAIL_DRIVER,
RESEND_API_KEY: process.env.RESEND_API_KEY,
@@ -1229,5 +1298,6 @@ test("a missing email configuration rolls the correction back", async () => {
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, consentedAt);
assert.deepEqual(await auditEvents(envelopeId), []);
});