Skip to content

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

TypeScript

Refuse a decline whose certificate missed a correction; record the corrected recipient's view

Claude0f5b5f74d28e
diff --git a/src/lib/signer-correction.dbtest.ts b/src/lib/signer-correction.dbtest.ts
index 9f7bcb3..804cc84 100644
--- a/src/lib/signer-correction.dbtest.ts
+++ b/src/lib/signer-correction.dbtest.ts
@@ -1493,3 +1493,135 @@ test("a failed reminder does not bring back the link a correction replaced", asy
});
assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
});
+
+test("a decline whose certificate missed another signer's correction is refused", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const declining = await createSigner({ envelopeId });
+ const waiting = await createSigner({
+ envelopeId,
+ signOrder: 2,
+ status: "pending",
+ });
+ const storageDir = await mkdtemp(
+ path.join(tmpdir(), "signudoc-correct-other-decline-"),
+ );
+ const storageService = createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
+ });
+ const sourcePdf = await PDFDocument.create();
+
+ sourcePdf.addPage([612, 792]);
+ await storageService.putObject({
+ body: await sourcePdf.save(),
+ 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(declining.token!);
+
+ 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);
+
+ // The correction lands after the decline has read the audit trail for
+ // its certificate, and before it takes the envelope lock.
+ const pool = afterStatement(
+ database,
+ (text) =>
+ text.includes("FROM audit_events") &&
+ text.includes("ORDER BY sequence ASC NULLS FIRST"),
+ async () => {
+ await correct(userId, envelopeId, waiting.signerId, {
+ email: "[email protected]",
+ });
+ },
+ );
+
+ try {
+ await assert.rejects(
+ declineSigningForToken(
+ declining.token!,
+ { reason: "Changed mind." },
+ { database: pool },
+ ),
+ (error: unknown) => {
+ assert.ok(error instanceof SigningMutationError);
+ assert.equal(error.statusCode, 409);
+ return true;
+ },
+ );
+ assert.equal((await readSigner(declining.signerId)).status, "notified");
+ assert.equal(
+ (await readSigner(waiting.signerId)).email,
+ );
+
+ // Opening the link again and declining now works, with the correction
+ // in the certificate.
+ await declineSigningForToken(
+ declining.token!,
+ { reason: "Changed mind." },
+ { database },
+ );
+ assert.equal((await readSigner(declining.signerId)).status, "declined");
+ } 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("the corrected recipient's first view is recorded", async () => {
+ const { userId } = await createOwner();
+ const envelopeId = await createEnvelope({ userId });
+ const signer = await createSigner({ envelopeId });
+ const { sent, service } = recordingEmailService();
+
+ await getSigningPayloadForToken(signer.token!, { database });
+ await correct(
+ userId,
+ envelopeId,
+ signer.signerId,
+ { email: "[email protected]" },
+ service,
+ );
+
+ const match = sent[0]?.textBody.match(/\/sign\/([A-Za-z0-9_-]+)/);
+ assert.ok(match);
+ await getSigningPayloadForToken(match[1]!, { database });
+ await getSigningPayloadForToken(match[1]!, { database });
+
+ const viewed = await database.query<{ email: string }>(
+ `
+ select metadata->>'signerEmail' as email from audit_events
+ where envelope_id = $1 and event = 'viewed'
+ order by sequence
+ `,
+ [envelopeId],
+ );
+ assert.deepEqual(
+ viewed.rows.map((row) => row.email),
+ [signer.email, "[email protected]"],
+ );
+});
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 1e156e8..8a1e505 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -821,9 +821,12 @@ async function recordViewedEventOnce(
WHERE envelope_id = $1
AND event = 'viewed'
AND metadata->>'signerId' = $2
+ -- A corrected signer keeps the row id, so the first view by the
+ -- person now at that address is recorded too.
+ AND lower(metadata->>'signerEmail') = lower($3)
LIMIT 1
`,
- [context.envelope.id, context.signer.id],
+ [context.envelope.id, context.signer.id, context.signer.email],
);
if (existing) {
@@ -3077,10 +3080,11 @@ export async function declineSigningForToken(
declinedAt,
declineReason,
);
- const auditEvents = [
- ...(await listAuditEventsForEnvelope(context.envelope.id, database)),
- declinedAuditEvent,
- ];
+ const auditEventsBefore = await listAuditEventsForEnvelope(
+ context.envelope.id,
+ database,
+ );
+ const auditEvents = [...auditEventsBefore, declinedAuditEvent];
const storedCertificateKeys: string[] = [];
let certificate: { key: string; sha256: string };
let recipientCertificateSha256: string;
@@ -3136,6 +3140,27 @@ export async function declineSigningForToken(
tokenHash: presentedTokenHash,
});
+ // The certificates above were made before the envelope lock. If the
+ // sender corrected another recipient in that time, they name the old
+ // person and leave the correction out, so they must not be kept.
+ const correctedSince = await tx.query(
+ `
+ SELECT 1 FROM audit_events
+ WHERE envelope_id = $1
+ AND event = 'signer_corrected'
+ AND NOT (id = ANY($2::text[]))
+ LIMIT 1
+ `,
+ [context.envelope.id, auditEventsBefore.map((event) => event.id)],
+ );
+
+ if ((correctedSince.rowCount ?? 0) > 0) {
+ throw new SigningMutationError(
+ "This envelope changed while you were declining. Open your signing link again.",
+ 409,
+ );
+ }
+
const declinedSignerResult = await tx.query(
`
UPDATE signers