Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Remove a void's or decline's certificates when its commit fails
Claude3a2d2a930a9c
diff --git a/src/lib/certificate-race.dbtest.ts b/src/lib/certificate-race.dbtest.tsindex c44d470..0fff310 100644--- a/src/lib/certificate-race.dbtest.ts+++ b/src/lib/certificate-race.dbtest.ts@@ -505,3 +505,88 @@ test("a void that fails with nothing else ending the envelope removes the certifassert.equal(row.rows[0]?.status, "sent");assert.deepEqual(await certificatesStored(envelope), [false, false]);});++/**+ * The same database, except that the first COMMIT sent through it fails:+ * the transaction is rolled back instead, as when the connection drops+ * before Postgres gets the COMMIT.+ */+function withFailingCommit() {+ let failed = false;++ function bound(object: object, property: string | symbol): unknown {+ const value: unknown = Reflect.get(object, property);++ return typeof value === "function"+ ? (value.bind(object) as unknown)+ : value;+ }++ return new Proxy(database, {+ get(target, property) {+ if (property !== "connect") {+ return bound(target, property);+ }++ return async () => {+ const client = await target.connect();++ return new Proxy(client, {+ get(object, name) {+ if (name !== "query") {+ return bound(object, name);+ }++ const query = bound(object, name) as QueryFunction;+ const failing: QueryFunction = async (text, values) => {+ if (failed || text !== "COMMIT") {+ return query(text, values);+ }++ failed = true;+ await query("ROLLBACK");++ throw new Error("The commit failed.");+ };++ return failing;+ },+ });+ };+ },+ });+}++test("a void whose commit fails removes the certificates it stored", async () => {+ const envelope = await createSignableEnvelope();++ await assert.rejects(+ voidEnvelope(envelope, withFailingCommit()),+ /The commit failed/,+ );++ const row = await database.query<{ status: string }>(+ `select status from envelopes where id = $1`,+ [envelope.envelopeId],+ );++ assert.equal(row.rows[0]?.status, "sent");+ assert.deepEqual(await certificatesStored(envelope), [false, false]);+});++test("a decline whose commit fails removes the certificates it stored", async () => {+ const envelope = await createSignableEnvelope();++ await assert.rejects(+ declineEnvelope(envelope, withFailingCommit()),+ /The commit failed/,+ );++ const row = await database.query<{ status: string }>(+ `select status from envelopes where id = $1`,+ [envelope.envelopeId],+ );++ assert.equal(row.rows[0]?.status, "sent");+ assert.deepEqual(await certificatesStored(envelope), [false, false]);+});diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 180ce57..7fc4332 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -3323,7 +3323,6 @@ export async function voidSentEnvelope(voidedAuditEvent,];const storedCertificateKeys: string[] = [];- let failedAfterLock = false;// The seal's key and the install's name, read before the transaction:// sealing inside it then needs no second connection from the pool.const seal = await loadInstallSealer();@@ -3357,108 +3356,104 @@ export async function voidSentEnvelope();}- try {- const certificate = await storeEnvelopeCertificatePdf(- {- auditEvents,- certificate: canonicalCertificate,- envelope: voidedEnvelope,- signers: voidedSigners,- },- {- seal,- storageService,- },- );- storedCertificateKeys.push(certificate.key);+ const certificate = await storeEnvelopeCertificatePdf(+ {+ auditEvents,+ certificate: canonicalCertificate,+ envelope: voidedEnvelope,+ signers: voidedSigners,+ },+ {+ seal,+ storageService,+ },+ );+ storedCertificateKeys.push(certificate.key);- const recipientCertificate = await storeRecipientEnvelopeCertificatePdf(- {- auditEvents,- certificate: {- bucketName: sourcePdfHead.bucketName,- key: buildEnvelopeCertificateKey({- ...storageIdentity,- audience: "recipient",- }),- },- envelope: voidedEnvelope,- signers: voidedSigners,- },- {- seal,- storageService,+ const recipientCertificate = await storeRecipientEnvelopeCertificatePdf(+ {+ auditEvents,+ certificate: {+ bucketName: sourcePdfHead.bucketName,+ key: buildEnvelopeCertificateKey({+ ...storageIdentity,+ audience: "recipient",+ }),},- );- storedCertificateKeys.push(recipientCertificate.key);-- const updatedEnvelope = await tx.query(- `- UPDATE envelopes- SET- status = 'voided',- evidence_key = $1,- voided_at = $2,- updated_at = $3,- evidence_sha256 = $6,- recipient_evidence_sha256 = $7- WHERE id = $4- AND user_id = $5- AND status = 'sent'- `,- [- certificate.key,- voidedAt,- voidedAt,- envelopeId,- userId,- certificate.sha256,- recipientCertificate.sha256,- ],- );-- if (updatedEnvelope.rowCount !== 1) {- throw new EnvelopeMutationError(- "This envelope can no longer be voided.",- 409,- );- }+ envelope: voidedEnvelope,+ signers: voidedSigners,+ },+ {+ seal,+ storageService,+ },+ );+ storedCertificateKeys.push(recipientCertificate.key);- await tx.query(- `- UPDATE signers- SET- signing_token_hash = NULL,- signing_token_expires_at = NULL,- updated_at = $1- WHERE envelope_id = $2- AND status = 'notified'- `,- [voidedAt, envelopeId],- );+ const updatedEnvelope = await tx.query(+ `+ UPDATE envelopes+ SET+ status = 'voided',+ evidence_key = $1,+ voided_at = $2,+ updated_at = $3,+ evidence_sha256 = $6,+ recipient_evidence_sha256 = $7+ WHERE id = $4+ AND user_id = $5+ AND status = 'sent'+ `,+ [+ certificate.key,+ voidedAt,+ voidedAt,+ envelopeId,+ userId,+ certificate.sha256,+ recipientCertificate.sha256,+ ],+ );- await recordAuditEvent(- {- actorEmail: voidedAuditEvent.actorEmail,- actorType: voidedAuditEvent.actorType,- id: voidedAuditEvent.id,- createdAt: voidedAuditEvent.createdAt,- envelopeId: voidedAuditEvent.envelopeId,- event: voidedAuditEvent.event,- ipAddress: voidedAuditEvent.ipAddress,- metadata: voidedAuditEvent.metadata,- userAgent: voidedAuditEvent.userAgent,- },- tx,+ if (updatedEnvelope.rowCount !== 1) {+ throw new EnvelopeMutationError(+ "This envelope can no longer be voided.",+ 409,);- } catch (error) {- failedAfterLock = true;- throw error;}++ await tx.query(+ `+ UPDATE signers+ SET+ signing_token_hash = NULL,+ signing_token_expires_at = NULL,+ updated_at = $1+ WHERE envelope_id = $2+ AND status = 'notified'+ `,+ [voidedAt, envelopeId],+ );++ await recordAuditEvent(+ {+ actorEmail: voidedAuditEvent.actorEmail,+ actorType: voidedAuditEvent.actorType,+ id: voidedAuditEvent.id,+ createdAt: voidedAuditEvent.createdAt,+ envelopeId: voidedAuditEvent.envelopeId,+ event: voidedAuditEvent.event,+ ipAddress: voidedAuditEvent.ipAddress,+ metadata: voidedAuditEvent.metadata,+ userAgent: voidedAuditEvent.userAgent,+ },+ tx,+ );}, database).catch(async (error: unknown) => {- // Only once the envelope was this call's to end: before that, the files- // under these keys are not ones it stored.- if (failedAfterLock) {+ // Only files this call stored, so only once the envelope was its to end.+ // That includes a failed COMMIT: the cleanup keeps the files if the+ // envelope did end after all.+ if (storedCertificateKeys.length > 0) {await removeUnclaimedEnvelopeCertificates({envelopeId: envelopeId,diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 58dba66..7118ab8 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -3100,7 +3100,6 @@ export async function declineSigningForToken(declinedAuditEvent,];const storedCertificateKeys: string[] = [];- let failedAfterLock = false;// The seal's key and the install's name, read before the transaction:// sealing inside it then needs no second connection from the pool.const seal = await loadInstallSealer();@@ -3145,128 +3144,124 @@ export async function declineSigningForToken();}- try {- // Made while the envelope is locked: the certificates have fixed keys,- // and a void, the last signature or a second decline at the same time- // waits, then stops above without touching the files this one saved.- const certificate = await storeEnvelopeCertificatePdf(- {- auditEvents,- certificate: canonicalCertificate,- envelope: declinedEnvelope,- signers: declinedSigners,- },- {- seal,- storageService,- },- );- storedCertificateKeys.push(certificate.key);+ // Made while the envelope is locked: the certificates have fixed keys,+ // and a void, the last signature or a second decline at the same time+ // waits, then stops above without touching the files this one saved.+ const certificate = await storeEnvelopeCertificatePdf(+ {+ auditEvents,+ certificate: canonicalCertificate,+ envelope: declinedEnvelope,+ signers: declinedSigners,+ },+ {+ seal,+ storageService,+ },+ );+ storedCertificateKeys.push(certificate.key);- const recipientCertificate = await storeRecipientEnvelopeCertificatePdf(- {- auditEvents,- certificate: {- bucketName: sourcePdfHead.bucketName,- key: buildEnvelopeCertificateKey({- ...storageIdentity,- audience: "recipient",- }),- },- envelope: declinedEnvelope,- signers: declinedSigners,- },- {- seal,- storageService,+ const recipientCertificate = await storeRecipientEnvelopeCertificatePdf(+ {+ auditEvents,+ certificate: {+ bucketName: sourcePdfHead.bucketName,+ key: buildEnvelopeCertificateKey({+ ...storageIdentity,+ audience: "recipient",+ }),},- );- storedCertificateKeys.push(recipientCertificate.key);-- const declinedSignerResult = await tx.query(- `- UPDATE signers- SET- status = 'declined',- signing_token_hash = NULL,- signing_token_expires_at = NULL,- declined_at = $1,- decline_reason = $2,- updated_at = $3- WHERE id = $4- AND envelope_id = $5- AND status = 'notified'- AND signing_token_hash = $6- `,- [- declinedAt,- declineReason ?? null,- declinedAt,- currentSignerId,- context.envelope.id,- presentedTokenHash,- ],- );+ envelope: declinedEnvelope,+ signers: declinedSigners,+ },+ {+ seal,+ storageService,+ },+ );+ storedCertificateKeys.push(recipientCertificate.key);- if (declinedSignerResult.rowCount !== 1) {- throw new SigningMutationError(- "This signing link is no longer active.",- 409,- );- }+ const declinedSignerResult = await tx.query(+ `+ UPDATE signers+ SET+ status = 'declined',+ signing_token_hash = NULL,+ signing_token_expires_at = NULL,+ declined_at = $1,+ decline_reason = $2,+ updated_at = $3+ WHERE id = $4+ AND envelope_id = $5+ AND status = 'notified'+ AND signing_token_hash = $6+ `,+ [+ declinedAt,+ declineReason ?? null,+ declinedAt,+ currentSignerId,+ context.envelope.id,+ presentedTokenHash,+ ],+ );- const declinedEnvelopeResult = await tx.query(- `- UPDATE envelopes- SET- status = 'declined',- evidence_key = $1,- declined_at = $2,- updated_at = $3,- evidence_sha256 = $5,- recipient_evidence_sha256 = $6- WHERE id = $4- AND status = 'sent'- `,- [- certificate.key,- declinedAt,- declinedAt,- context.envelope.id,- certificate.sha256,- recipientCertificate.sha256,- ],+ if (declinedSignerResult.rowCount !== 1) {+ throw new SigningMutationError(+ "This signing link is no longer active.",+ 409,);+ }- if (declinedEnvelopeResult.rowCount !== 1) {- throw new SigningMutationError(- "This signing link is no longer active.",- 409,- );- }+ const declinedEnvelopeResult = await tx.query(+ `+ UPDATE envelopes+ SET+ status = 'declined',+ evidence_key = $1,+ declined_at = $2,+ updated_at = $3,+ evidence_sha256 = $5,+ recipient_evidence_sha256 = $6+ WHERE id = $4+ AND status = 'sent'+ `,+ [+ certificate.key,+ declinedAt,+ declinedAt,+ context.envelope.id,+ certificate.sha256,+ recipientCertificate.sha256,+ ],+ );- await recordAuditEvent(- {- actorEmail: declinedAuditEvent.actorEmail,- actorType: declinedAuditEvent.actorType,- id: declinedAuditEvent.id,- createdAt: declinedAuditEvent.createdAt,- envelopeId: declinedAuditEvent.envelopeId,- event: declinedAuditEvent.event,- ipAddress: declinedAuditEvent.ipAddress,- metadata: declinedAuditEvent.metadata,- userAgent: declinedAuditEvent.userAgent,- },- tx,+ if (declinedEnvelopeResult.rowCount !== 1) {+ throw new SigningMutationError(+ "This signing link is no longer active.",+ 409,);- } catch (error) {- failedAfterLock = true;- throw error;}++ await recordAuditEvent(+ {+ actorEmail: declinedAuditEvent.actorEmail,+ actorType: declinedAuditEvent.actorType,+ id: declinedAuditEvent.id,+ createdAt: declinedAuditEvent.createdAt,+ envelopeId: declinedAuditEvent.envelopeId,+ event: declinedAuditEvent.event,+ ipAddress: declinedAuditEvent.ipAddress,+ metadata: declinedAuditEvent.metadata,+ userAgent: declinedAuditEvent.userAgent,+ },+ tx,+ );}, database).catch(async (error: unknown) => {- // Only once the envelope was this call's to end: before that, the files- // under these keys are not ones it stored.- if (failedAfterLock) {+ // Only files this call stored, so only once the envelope was its to end.+ // That includes a failed COMMIT: the cleanup keeps the files if the+ // envelope did end after all.+ if (storedCertificateKeys.length > 0) {await removeUnclaimedEnvelopeCertificates({envelopeId: context.envelope.id,