Skip to content

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

TypeScript

List an envelope's audit events in the order they were recorded

njarraraee827ee5bf0
diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.ts
index 835865a..59a4927 100644
--- a/src/lib/services/audit.ts
+++ b/src/lib/services/audit.ts
@@ -72,7 +72,10 @@ export async function listAuditEventsForEnvelope(
created_at AS "createdAt"
FROM audit_events
WHERE envelope_id = $1
- ORDER BY created_at ASC, id ASC
+ -- created_at is in whole seconds and id is random, so the chain's
+ -- sequence decides the order of events from the same second. Rows
+ -- from before the chain have none and come first.
+ ORDER BY sequence ASC NULLS FIRST, created_at ASC, id ASC
`,
[envelopeId],
);
diff --git a/src/lib/signature-evidence.dbtest.ts b/src/lib/signature-evidence.dbtest.ts
index 4dfa70e..49ffd7e 100644
--- a/src/lib/signature-evidence.dbtest.ts
+++ b/src/lib/signature-evidence.dbtest.ts
@@ -9,7 +9,11 @@ import type pg from "pg";
import { openTestDatabase } from "./db/test-database.ts";
import { runRetentionSweep } from "./retention.ts";
-import { recordAuditEvent, verifyAuditChain } from "./services/audit.ts";
+import {
+ listAuditEventsForEnvelope,
+ recordAuditEvent,
+ verifyAuditChain,
+} from "./services/audit.ts";
import type { EmailService } from "./services/email.ts";
import { createStorageService } from "./services/storage.ts";
import { eraseSignerData, exportSignerData } from "./signer-data.ts";
@@ -97,6 +101,32 @@ async function envelopeOwner(envelopeId: string) {
return result.rows[0]?.user_id ?? null;
}
+test("events from the same second are listed in the order they were recorded", async () => {
+ const owner = await createUser();
+ const createdAt = 1_800_000_000;
+ const recorded = ["sent", "viewed", "signed", "completed"] as const;
+
+ // The ids are random, so with enough envelopes an order that leans on
+ // them is sure to come out wrong for some.
+ for (let index = 0; index < 12; index += 1) {
+ const envelopeId = await createEnvelope(owner, "sent", "[email protected]");
+
+ for (const event of recorded) {
+ await recordAuditEvent(
+ { actorType: "system", createdAt, envelopeId, event },
+ database,
+ );
+ }
+
+ const listed = await listAuditEventsForEnvelope(envelopeId, database);
+
+ assert.deepEqual(
+ listed.map((event) => event.event),
+ recorded,
+ );
+ }
+});
+
test("the audit chain verifies, and shows an edited row", async () => {
const owner = await createUser();
const envelopeId = await createEnvelope(owner, "sent", "[email protected]");