Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Read the audit trail a certificate seals while the envelope is held
Claude7a6602dd1172
diff --git a/src/lib/certificate-race.dbtest.ts b/src/lib/certificate-race.dbtest.tsindex 0fff310..a85c578 100644--- a/src/lib/certificate-race.dbtest.ts+++ b/src/lib/certificate-race.dbtest.ts@@ -12,7 +12,7 @@ import { afterStatement, openTestDatabase } from "./db/test-database.ts";import { getSenderEnvelopeDownload } from "./downloads.ts";import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";import { EnvelopeMutationError, voidSentEnvelope } from "./envelopes.ts";-import { verifyAuditChain } from "./services/audit.ts";+import { recordAuditEvent, verifyAuditChain } from "./services/audit.ts";import { issueSigningLink } from "./services/signing-links.ts";import { buildEnvelopeCertificateKey } from "./services/storage-keys.ts";import {@@ -590,3 +590,80 @@ test("a decline whose commit fails removes the certificates it stored", async ()assert.equal(row.rows[0]?.status, "sent");assert.deepEqual(await certificatesStored(envelope), [false, false]);});++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, " ");+}++// An event recorded after the envelope was read, and before whatever ends it+// holds the envelope, belongs on the certificate it seals. Each way of+// ending it is held up at a statement it runs once it holds the envelope,+// and the event is recorded then, from another connection.+for (const [name, statement, end] of [+ ["the last signature", "AND status <> 'signed'", signEnvelope],+ [+ "a void",+ "SELECT id, status FROM signers WHERE envelope_id = $1 AND role = 'signer'",+ voidEnvelope,+ ],+ [+ "a decline",+ "WHERE envelope_id = $1 AND role = 'signer' AND id <> $2",+ declineEnvelope,+ ],+] as const) {+ test(`${name} seals the audit events recorded while it was under way`, async () => {+ const envelope = await createSignableEnvelope();+ const lateActor = `late-${randomUUID().slice(0, 8)}@example.test`;+ let recorded = false;+ const pool = afterStatement(+ database,+ (text) => !recorded && text.includes(statement),+ async () => {+ recorded = true;+ await recordAuditEvent(+ {+ actorEmail: lateActor,+ actorType: "signer",+ envelopeId: envelope.envelopeId,+ event: "viewed",+ },+ database,+ );+ },+ );++ await end(envelope, pool);++ assert.equal(recorded, true);++ const certificate = await storageService.getObject(+ buildEnvelopeCertificateKey({ ...envelope, audience: "internal" }),+ );++ assert.match(await extractPdfText(certificate.body), new RegExp(lateActor));+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );+ });+}diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 347487e..0e158c9 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -3887,10 +3887,6 @@ async function voidSentEnvelopeOnce(}): signer,);- const auditEvents = [- ...(await listAuditEventsForEnvelope(envelopeId, database)),- voidedAuditEvent,- ];const storedCertificateKeys: string[] = [];// The seal's key and the install's name, read before the transaction:// sealing inside it then needs no second connection from the pool.@@ -3945,6 +3941,16 @@ async function voidSentEnvelopeOnce(throw new VoidRouteChangedError();}+ // The audit trail the certificates show, read with the envelope and its+ // audit chain held, so an event recorded since the page was opened is+ // on them and none can be added before the void is.+ await lockEnvelopeAuditChain(envelopeId, tx);++ const auditEvents = [+ ...(await listAuditEventsForEnvelope(envelopeId, tx)),+ voidedAuditEvent,+ ];+const certificate = await storeEnvelopeCertificatePdf({auditEvents,diff --git a/src/lib/signer-correction.dbtest.ts b/src/lib/signer-correction.dbtest.tsindex f4c016f..a3d217e 100644--- a/src/lib/signer-correction.dbtest.ts+++ b/src/lib/signer-correction.dbtest.ts@@ -1587,12 +1587,11 @@ async function declineRacingAnotherCorrection(}test("a decline whose certificate missed another signer's correction is refused", async () => {- // The correction lands after the decline has read the audit trail for- // its certificate, and before it takes the envelope lock.- await declineRacingAnotherCorrection(- (text) =>- text.includes("FROM audit_events") &&- text.includes("ORDER BY sequence ASC NULLS FIRST"),+ // The correction lands just before the decline takes the envelope lock.+ // The audit trail for its certificate is read under that lock, so it has+ // the correction; the signers it read before do not, so it starts again.+ await declineRacingAnotherCorrection((text) =>+ text.includes('s.embed_origin AS origin, k.name AS "apiKeyName"'),);});diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex e3bca6e..83788c9 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -58,6 +58,7 @@ import {} from "./part11.ts";import {listAuditEventsForEnvelope,+ lockEnvelopeAuditChain,recordAuditEvent,recordEmailSent,} from "./services/audit.ts";@@ -3021,10 +3022,6 @@ async function submitSigningOnce(context.envelope.id,database,);- const auditEvents = [- ...(await listAuditEventsForEnvelope(context.envelope.id, database)),- signedAuditEvent,- ];const storageIdentity = {envelopeId: context.envelope.id,userId: context.envelope.userId,@@ -3079,6 +3076,17 @@ async function submitSigningOnce(throw new SigningRouteChangedError();}+ // The audit trail the certificate shows, read with the envelope and+ // its audit chain held: an event recorded since the link was opened+ // (a view, an email, a reminder) is on it, and one recorded from+ // now on waits until the envelope is finished.+ await lockEnvelopeAuditChain(context.envelope.id, tx);++ const auditEvents = [+ ...(await listAuditEventsForEnvelope(context.envelope.id, tx)),+ signedAuditEvent,+ ];+// Made while the envelope is locked: the files have fixed keys, and// a second submission at the same time waits, then stops above.finalArtifactsStored = true;@@ -3456,10 +3464,6 @@ async function declineSigningOnce(declinedAt,declineReason,);- const auditEvents = [- ...(await listAuditEventsForEnvelope(context.envelope.id, database)),- declinedAuditEvent,- ];const storedCertificateKeys: string[] = [];// The seal's key and the install's name, read before the transaction:// sealing inside it then needs no second connection from the pool.@@ -3527,6 +3531,16 @@ async function declineSigningOnce(throw new SigningRouteChangedError();}+ // The audit trail the certificates show, read with the envelope and its+ // audit chain held, so an event recorded since the link was opened is+ // on them and none can be added before the decline is.+ await lockEnvelopeAuditChain(context.envelope.id, tx);++ const auditEvents = [+ ...(await listAuditEventsForEnvelope(context.envelope.id, tx)),+ declinedAuditEvent,+ ];+// 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.