Skip to content

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

TypeScript

Fix what the second review of provider signing found

Claudefb11a7b2780a
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 24a318f..6779e66 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -150,7 +150,7 @@ What ends up in the PDF:
- Each signer's signature is a PAdES signature in a revision of its own, holding their filled-in fields. The revisions only add to the file, so every earlier signer's signature stays valid, and a PDF reader lists one signature per signer with the name from their certificate.
- When the last signer has signed, the install adds the certificates and revocation answers (B-LT), and with `SEAL_TIMESTAMP_URL` an archive timestamp too (B-LTA), as for the seal above. If the provider did not timestamp a signature, the install's timestamp server does.
- The signed PDF does not get the install's seal, because the signers' signatures already cover all of it. The certificate of completion is still sealed, and lists each signer's certificate, its issuer, and the provider.
-- The certificate has to be in the name the document was sent to, so a signing link passed to someone else does not let them sign. Case, accents, punctuation, word order and ID numbers in the certificate's name do not count, and a middle name or title on one side only is allowed, but otherwise a certificate in another name is refused and the signer is asked to have the sender correct the name. Enter each signer's name as it is on their ID.
+- The certificate has to be in the name the document was sent to, so a signing link passed to someone else does not let them sign. Case, accents, punctuation (an apostrophe, as in O'Connor, can be left out), word order and ID numbers in the certificate's name do not count, and a middle name or title on one side only is allowed, but otherwise a certificate in another name is refused and the signer is asked to have the sender correct the name. Enter each signer's name as it is on their ID.
- For a qualified signature, the install refuses a certificate that does not say it is qualified and held on a qualified signature device (the EU QC statements). It does not look the issuer up on the EU trusted lists; PDF readers and the EU's own validator do that when the document is checked.
Not available in Part 11 mode, where signers sign with their accounts instead.
@@ -179,7 +179,7 @@ Some data still leaves the EU: Vercel's and Resend's account metadata and logs,
## Daily cleanup
-Once a day the app deletes drafts nobody has touched for 30 days, finishes account deletions that were requested, and clears expired download links, finished rate limit counters, and trips to a signing provider that nobody came back from. The same run sends the automatic reminders that are due and tells a sender when an envelope has passed its signing deadline. The work is done by a request to:
+Once a day the app deletes drafts nobody has touched for 30 days, finishes account deletions that were requested, and clears expired download links, finished rate limit counters, and trips to a signing provider that nobody came back from, with the signer revisions nothing needs any more (a file that could not be deleted is tried again the next day). The same run sends the automatic reminders that are due and tells a sender when an envelope has passed its signing deadline. The work is done by a request to:
```text
/api/internal/retention
diff --git a/src/lib/provider-signing.dbtest.ts b/src/lib/provider-signing.dbtest.ts
index 3a3aa15..ed4af36 100644
--- a/src/lib/provider-signing.dbtest.ts
+++ b/src/lib/provider-signing.dbtest.ts
@@ -38,6 +38,7 @@ import {
type ProviderStandIns,
} from "./services/signing-provider-test-support.ts";
import { issueSigningLink } from "./services/signing-links.ts";
+import { getRecipientCertificateKey } from "./services/storage-keys.ts";
import {
createStorageService,
type StorageService,
@@ -97,6 +98,11 @@ before(async () => {
});
setEnv({
APP_URL: "https://sign.example.test",
+ // Only the eID Easy stand-in: a CSC provider set in the shell would
+ // otherwise be the one these tests use, or find when none is set.
+ CSC_API_URL: undefined,
+ CSC_CLIENT_ID: undefined,
+ CSC_CLIENT_SECRET: undefined,
EIDEASY_API_URL: standIns.eidEasyUrl,
EIDEASY_CLIENT_ID: STAND_IN_CLIENT.id,
EIDEASY_SECRET: STAND_IN_CLIENT.secret,
@@ -779,6 +785,153 @@ test("an ended session keeps no secrets, and the daily cleanup ends abandoned on
);
});
+test("two submissions by the last signer at once finish the envelope once, and keep its files", async () => {
+ const draft = await createDraft();
+
+ await send(draft, "simple");
+ await submitSigningForToken(
+ await linkFor(draft.riley.id),
+ submissionFor(draft.riley),
+ { database, storageService },
+ );
+
+ // Casey presses Finish twice.
+ const caseyToken = await linkFor(draft.casey.id);
+ const results = await Promise.allSettled(
+ [1, 2].map(() =>
+ submitSigningForToken(caseyToken, submissionFor(draft.casey), {
+ database,
+ storageService,
+ }),
+ ),
+ );
+
+ assert.deepEqual(results.map((result) => result.status).sort(), [
+ "fulfilled",
+ "rejected",
+ ]);
+ assert.ok(
+ results.some(
+ (result) =>
+ result.status === "rejected" &&
+ result.reason instanceof SigningMutationError,
+ ),
+ );
+
+ const finished = (
+ await database.query<{
+ evidence_key: string;
+ signed_pdf_key: string;
+ status: string;
+ }>(
+ `select evidence_key, signed_pdf_key, status from envelopes where id = $1`,
+ [draft.envelopeId],
+ )
+ ).rows[0]!;
+
+ assert.equal(finished.status, "completed");
+
+ // The submission that lost deleted none of the files the other saved.
+ for (const key of [
+ finished.signed_pdf_key,
+ finished.evidence_key,
+ getRecipientCertificateKey(finished.evidence_key),
+ ]) {
+ assert.equal(await stored(key), true, key);
+ }
+});
+
+test("a revision the cleanup cannot delete is tried again, and the current one is kept", async () => {
+ const draft = await createDraft();
+
+ await send(draft, "advanced");
+
+ const rileyToken = await linkFor(draft.riley.id);
+ const abandoned = await signAtProvider(rileyToken, draft.riley);
+ const sessionRow = async (id: string) =>
+ (
+ await database.query<{
+ expires_at: string;
+ revision_key: string;
+ state: string;
+ }>(
+ `select expires_at, revision_key, state from provider_signing_sessions where id = $1`,
+ [id],
+ )
+ ).rows[0]!;
+ const abandonedId = abandoned.query.get("state") ?? "";
+ const abandonedBefore = await sessionRow(abandonedId);
+ const expiresAt = Number(abandonedBefore.expires_at);
+ // Storage refuses to delete the abandoned session's revision, once.
+ const failingStorage: StorageService = {
+ ...storageService,
+ deleteObject: async (key) => {
+ if (key === abandonedBefore.revision_key) {
+ throw new Error("Storage is unavailable.");
+ }
+
+ await storageService.deleteObject(key);
+ },
+ };
+
+ await runRetentionSweep({
+ database,
+ now: expiresAt,
+ storageService: failingStorage,
+ });
+
+ // Ended, but the revision and the key that finds it are both kept.
+ assert.equal((await sessionRow(abandonedId)).state, "failed");
+ assert.equal(
+ (await sessionRow(abandonedId)).revision_key,
+ abandonedBefore.revision_key,
+ );
+ assert.equal(await stored(abandonedBefore.revision_key), true);
+
+ await runRetentionSweep({ database, now: expiresAt, storageService });
+
+ assert.equal((await sessionRow(abandonedId)).revision_key, "");
+ assert.equal(await stored(abandonedBefore.revision_key), false);
+
+ // Riley and Casey sign. Riley's revision is deleted once Casey's replaces
+ // it; here that delete is taken to have failed, so the file is back.
+ const riley = await signAtProvider(rileyToken, draft.riley);
+
+ await riley.finish();
+
+ const rileyRevision = await sessionRow(riley.query.get("state") ?? "");
+ const rileyBytes = (
+ await storageService.getObject(rileyRevision.revision_key)
+ ).body;
+ const casey = await signAtProvider(
+ await linkFor(draft.casey.id),
+ draft.casey,
+ );
+
+ await casey.finish();
+ await storageService.putObject({
+ body: rileyBytes,
+ contentType: "application/pdf",
+ key: rileyRevision.revision_key,
+ });
+
+ const caseyRevision = await sessionRow(casey.query.get("state") ?? "");
+
+ await runRetentionSweep({ database, now: expiresAt, storageService });
+
+ // The replaced revision goes, the envelope's current one stays.
+ assert.equal(
+ (await sessionRow(riley.query.get("state") ?? "")).revision_key,
+ "",
+ );
+ assert.equal(await stored(rileyRevision.revision_key), false);
+ assert.equal(
+ (await sessionRow(casey.query.get("state") ?? "")).revision_key,
+ caseyRevision.revision_key,
+ );
+ assert.equal(await stored(caseyRevision.revision_key), true);
+});
+
test("a certificate in someone else's name does not sign for the invited signer", async () => {
const draft = await createDraft();
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index 736d1a4..534b5a9 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -198,6 +198,7 @@ async function listFieldImagesForEnvelopeIds(
SELECT envelope_id, revision_key
FROM provider_signing_sessions
WHERE envelope_id IN (${placeholders})
+ AND revision_key <> ''
`,
envelopeIds,
);
@@ -298,38 +299,92 @@ async function deleteExpiredRecipientDownloadTokens(
/** How long past its expiry a claimed signing session is given up on. */
const CLAIMED_PROVIDER_SESSION_GRACE_SECONDS = 60 * 60;
+/** How many unused revisions one cleanup deletes, at most. */
+const UNUSED_PROVIDER_REVISIONS_PER_SWEEP = 500;
+
/**
* Ends the trips to a signing provider that will not finish: sessions the
* signer never came back to, past their expiry, and sessions a return
* claimed but never finished (it stopped with its function), an hour past
- * their expiry. Their prepared revisions and their secrets (the signing
- * link, the submission and the provider's state) go with them. Neither kind
- * holds the envelope's current revision, which only a completed session
- * sets.
+ * their expiry. Their secrets (the signing link, the submission and the
+ * provider's state) go at once, and their prepared revisions with the
+ * other unused ones below.
*/
async function endAbandonedProviderSessions(
now: number,
database: DbExecutor,
storageService: StorageService,
): Promise<number> {
- const ended = await database.query<{ revisionKey: string }>(
+ const ended = await database.query(
`
UPDATE provider_signing_sessions
SET state = 'failed', secret_data = ''
WHERE (state = 'pending' AND expires_at <= $1)
OR (state = 'signing' AND expires_at <= $2)
- RETURNING revision_key AS "revisionKey"
`,
[now, now - CLAIMED_PROVIDER_SESSION_GRACE_SECONDS],
);
- for (const row of ended.rows) {
- await storageService.deleteObject(row.revisionKey).catch(() => undefined);
- }
+ await deleteUnusedProviderRevisions(database, storageService);
return ended.rowCount ?? 0;
}
+/**
+ * Deletes the signer revisions nothing needs any more: those of sessions
+ * that failed, and those a later signer's revision replaced (it contains
+ * them). Each is deleted when that happens, and again here in case that
+ * delete failed. A session's key is cleared only once its file is gone, so a
+ * delete that fails now is tried again at the next cleanup. The envelope's
+ * current revision is never one of them: only a completed session sets it,
+ * in the same transaction that completes the session.
+ */
+async function deleteUnusedProviderRevisions(
+ database: DbExecutor,
+ storageService: StorageService,
+) {
+ const unused = await queryMany<{ id: string; revisionKey: string }>(
+ database,
+ `
+ SELECT sessions.id, sessions.revision_key AS "revisionKey"
+ FROM provider_signing_sessions sessions
+ JOIN envelopes ON envelopes.id = sessions.envelope_id
+ WHERE sessions.revision_key <> ''
+ AND (
+ sessions.state = 'failed'
+ OR (
+ sessions.state = 'completed'
+ AND envelopes.revision_key IS DISTINCT FROM sessions.revision_key
+ )
+ )
+ ORDER BY sessions.created_at
+ LIMIT $1
+ `,
+ [UNUSED_PROVIDER_REVISIONS_PER_SWEEP],
+ );
+
+ for (const session of unused) {
+ try {
+ await storageService.deleteObject(session.revisionKey);
+ } catch (error) {
+ console.error(
+ `Failed to delete the unused signer revision of session ${session.id}:`,
+ error,
+ );
+ continue;
+ }
+
+ await database.query(
+ `
+ UPDATE provider_signing_sessions
+ SET revision_key = ''
+ WHERE id = $1 AND revision_key = $2
+ `,
+ [session.id, session.revisionKey],
+ );
+ }
+}
+
function getClosureSchedule(requestedAt = getCurrentUnixTimestamp()) {
const exportExpiresAt =
requestedAt + ACCOUNT_CLOSURE_EXPORT_WINDOW_DAYS * DAY_IN_SECONDS;
diff --git a/src/lib/services/pdf-revision.test.ts b/src/lib/services/pdf-revision.test.ts
index e64c893..9001b72 100644
--- a/src/lib/services/pdf-revision.test.ts
+++ b/src/lib/services/pdf-revision.test.ts
@@ -1,6 +1,12 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
-import { createHash, generateKeyPairSync, sign, verify } from "node:crypto";
+import {
+ constants,
+ createHash,
+ generateKeyPairSync,
+ sign,
+ verify,
+} from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -10,6 +16,13 @@ import { promisify } from "node:util";
import { PDFDocument, PDFName, StandardFonts } from "pdf-lib";
import type { FieldRecord } from "../schemas/field.ts";
+import {
+ algorithm,
+ contextTag,
+ der,
+ encode,
+ encodeSmallInteger,
+} from "./der.ts";
import { fillSignature, findSignatures } from "./pdf-incremental.ts";
import {
addLongTermValidation,
@@ -27,9 +40,12 @@ import { buildCadesSignature, requestDocumentTimestamp } from "./pdf-seal.ts";
import { startTestPki, type TestPki } from "./pki-test-support.ts";
import {
addSignatureTimestamp,
+ assembleSignedData,
+ buildSignedAttributes,
certificateHolderNames,
certificateMatchesName,
checkSignerSignature,
+ CMS_OIDS,
ecdsaSignatureAsDer,
SignerSignatureError,
} from "./signer-cms.ts";
@@ -506,6 +522,70 @@ test("a certificate matches the name a signer was sent the document under", asyn
}
assert.equal(certificateMatchesName(national, "Kadri Männik"), false);
+
+ // An apostrophe joins the letters around it, however it is typed.
+ const irish = parseCertificate(
+ pki.issueSigner({ commonName: "Alice O'Connor" }).certificate,
+ );
+
+ for (const name of ["Alice OConnor", "Alice O’Connor", "alice o'connor"]) {
+ assert.equal(certificateMatchesName(irish, name), true, name);
+ }
+
+ assert.equal(certificateMatchesName(irish, "Alice Connor"), false);
+ });
+});
+
+test("an RSA-PSS signature is checked only with a mask it says it uses", async () => {
+ await withPki(async (pki) => {
+ const alice = pki.issueSigner({ commonName: "Alice Example" });
+ const digest = createHash("sha256").update("revision bytes").digest();
+ const signedAttributes = buildSignedAttributes({
+ certificate: alice.certificate,
+ contentDigest: digest,
+ });
+ // SHA-256, MGF1 with SHA-256, a 32-byte salt.
+ const signature = sign("sha256", signedAttributes, {
+ key: alice.privateKeyPem,
+ padding: constants.RSA_PKCS1_PSS_PADDING,
+ saltLength: 32,
+ });
+ const cmsDeclaring = (maskHash: string) =>
+ assembleSignedData({
+ certificates: [alice.certificate, pki.caCertificate],
+ signature,
+ signatureAlgorithm: der.sequence(
+ der.oid(CMS_OIDS.rsaPss),
+ der.sequence(
+ encode(contextTag(0), algorithm(CMS_OIDS.sha256)),
+ encode(
+ contextTag(1),
+ der.sequence(der.oid(CMS_OIDS.mgf1), algorithm(maskHash)),
+ ),
+ encode(contextTag(2), encodeSmallInteger(32)),
+ ),
+ ),
+ signedAttributes,
+ });
+
+ assert.match(
+ checkSignerSignature(cmsDeclaring(CMS_OIDS.sha256), digest, {
+ level: "advanced",
+ }).subject,
+ /Alice Example/,
+ );
+ // The same signature, declaring a mask over SHA-1: not checked as one.
+ assert.throws(
+ () =>
+ checkSignerSignature(cmsDeclaring(CMS_OIDS.sha1), digest, {
+ level: "advanced",
+ }),
+ (error: unknown) =>
+ error instanceof SignerSignatureError &&
+ /RSA-PSS signature uses parameters that cannot be checked/.test(
+ error.message,
+ ),
+ );
});
});
diff --git a/src/lib/services/signer-cms.ts b/src/lib/services/signer-cms.ts
index c5d9981..aefd3c2 100644
--- a/src/lib/services/signer-cms.ts
+++ b/src/lib/services/signer-cms.ts
@@ -41,6 +41,7 @@ export const CMS_OIDS = {
ecdsaSha512: "1.2.840.10045.4.3.4",
ecPublicKey: "1.2.840.10045.2.1",
messageDigest: "1.2.840.113549.1.9.4",
+ mgf1: "1.2.840.113549.1.1.8",
qcCompliance: "0.4.0.1862.1.1",
qcSscd: "0.4.0.1862.1.4",
qcTypeSignature: "0.4.0.1862.1.6.1",
@@ -414,6 +415,59 @@ function findSigner(
return match;
}
+/**
+ * RSASSA-PSS-params (RFC 4055): [0] the hash, [1] the mask generation
+ * function, [2] the salt length and [3] the trailer, each SHA-1, MGF1 with
+ * SHA-1, 20 and 1 when left out. Node checks a PSS signature with MGF1 over
+ * the same hash as the message, so a signature that declares any other mask
+ * is refused rather than checked as something it does not say it is.
+ */
+function readPssParameters(
+ bytes: Buffer,
+ parameters: Tlv | null,
+): { hash: string; saltLength: number } {
+ let hash: string | undefined = "sha1";
+ let maskHash: string | undefined = "sha1";
+ let saltLength = 20;
+ let trailer = 1;
+ const readNumber = (value: Tlv) => {
+ const content = contentBytes(bytes, value);
+
+ return content.length > 0 && content.length <= 6
+ ? content.readUIntBE(0, content.length)
+ : -1;
+ };
+
+ for (const field of parameters ? children(bytes, parameters) : []) {
+ const value = children(bytes, field)[0];
+
+ if (!value) {
+ maskHash = undefined;
+ } else if (field.tag === contextTag(0)) {
+ hash = HASHES[readOid(bytes, children(bytes, value)[0]!)];
+ } else if (field.tag === contextTag(1)) {
+ const [mask, maskParameters] = children(bytes, value);
+
+ maskHash =
+ mask && maskParameters && readOid(bytes, mask) === CMS_OIDS.mgf1
+ ? HASHES[readOid(bytes, children(bytes, maskParameters)[0]!)]
+ : undefined;
+ } else if (field.tag === contextTag(2)) {
+ saltLength = readNumber(value);
+ } else if (field.tag === contextTag(3)) {
+ trailer = readNumber(value);
+ }
+ }
+
+ if (!hash || maskHash !== hash || saltLength < 0 || trailer !== 1) {
+ throw new SignerSignatureError(
+ "The RSA-PSS signature uses parameters that cannot be checked (its mask has to use the same hash as the signature).",
+ );
+ }
+
+ return { hash, saltLength };
+}
+
function verifyValue(info: ParsedSignerInfo, key: KeyObject): boolean {
const { bytes, signatureAlgorithm, signature, signedAttributes } = info;
const digestHash = HASHES[info.digestAlgorithm];
@@ -445,24 +499,10 @@ function verifyValue(info: ParsedSignerInfo, key: KeyObject): boolean {
);
}
case CMS_OIDS.rsaPss: {
- // RSASSA-PSS-params: [0] hash, [1] mask generation, [2] salt length.
- let hash = "sha1";
- let saltLength = 20;
-
- for (const field of signatureAlgorithm.parameters
- ? children(bytes, signatureAlgorithm.parameters)
- : []) {
- if (field.tag === contextTag(0)) {
- hash =
- HASHES[
- readOid(bytes, children(bytes, children(bytes, field)[0]!)[0]!)
- ] ?? "";
- } else if (field.tag === contextTag(2)) {
- const value = contentBytes(bytes, children(bytes, field)[0]!);
-
- saltLength = value.readUIntBE(0, Math.min(6, value.length));
- }
- }
+ const { hash, saltLength } = readPssParameters(
+ bytes,
+ signatureAlgorithm.parameters,
+ );
return verifySignature(
hash,
@@ -666,10 +706,15 @@ export function certificateHolderNames(certificate: Certificate): string[] {
];
}
-/** A name's words, without case, accents, punctuation or numbers. */
+/**
+ * A name's words, without case, accents, punctuation or numbers. An
+ * apostrophe joins the letters around it, so O'Connor and OConnor are the
+ * same word; other punctuation, such as a hyphen, separates words.
+ */
function nameWords(name: string): Set<string> {
return new Set(
name
+ .replace(/['`\u00B4\u2018\u2019\u02BC]/gu, "")
.normalize("NFKD")
.replace(/\p{M}+/gu, "")
.toLocaleLowerCase("en")
diff --git a/src/lib/services/storage-keys.ts b/src/lib/services/storage-keys.ts
index 5b750c4..7e0c917 100644
--- a/src/lib/services/storage-keys.ts
+++ b/src/lib/services/storage-keys.ts
@@ -143,15 +143,21 @@ export function buildEnvelopeCertificateKey(
);
}
+/**
+ * A drawn signature, under a key of its own for each submission: of two
+ * submissions by the same signer at once, the one that fails then deletes
+ * only its own pictures, never the ones the other saved.
+ */
export function buildSignatureImageKey(
input: EnvelopeStorageIdentity & {
fieldId: string;
+ submissionId: string;
},
): string {
return path.posix.join(
buildEnvelopePrefix(input),
"signatures",
- `${input.fieldId}.png`,
+ `${input.fieldId}-${input.submissionId}.png`,
);
}
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 4dd769c..86d4f64 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -1923,6 +1923,8 @@ async function commitProviderRevision(
now: number,
): Promise<string | null> {
// Locked, so the revision read here is the one the update below replaces.
+ // The lock an UPDATE takes, as in lockSentEnvelope: a stronger one would
+ // also stop audit events being added to this envelope meanwhile.
const current = await queryOne<{ revisionKey: string | null }>(
tx,
`
@@ -1930,7 +1932,7 @@ async function commitProviderRevision(
FROM envelopes
WHERE id = $1
AND revision_sha256 IS NOT DISTINCT FROM $2
- FOR UPDATE
+ FOR NO KEY UPDATE
`,
[envelopeId, completion.baseSha256],
);
@@ -1978,6 +1980,35 @@ async function deleteReplacedRevision(
}
}
+/**
+ * Refuses a submission once the signer has signed, read while the envelope
+ * is locked. The last signer's submission makes the envelope's final files,
+ * which have fixed keys, only after this, under that lock. So of two by the
+ * same signer at once (a double click, or two returns from a signing
+ * provider), the second waits and stops here: it never writes over, or
+ * deletes, the files the first one saved.
+ */
+async function assertStillSignersTurn(
+ envelopeId: string,
+ signerId: string,
+ tx: DbExecutor,
+) {
+ const turn = await tx.query(
+ `
+ SELECT 1 FROM signers
+ WHERE id = $1 AND envelope_id = $2 AND status = 'notified'
+ `,
+ [signerId, envelopeId],
+ );
+
+ if (turn.rowCount !== 1) {
+ throw new SigningMutationError(
+ "This signing link is no longer active.",
+ 409,
+ );
+ }
+}
+
type SigningContext = Awaited<ReturnType<typeof resolveSigningContext>>;
/**
@@ -2034,6 +2065,8 @@ function buildSignerSubmission(
relevantSubmissions.set(submission.fieldId, submission);
}
+ // Names this submission's drawn signatures apart from any other's.
+ const submissionId = randomUUID();
const localDateValue = formatLocalSigningDate(
submittedAt,
parsedInput.clientTimezoneOffsetMinutes,
@@ -2079,6 +2112,7 @@ function buildSignerSubmission(
const imageKey = buildSignatureImageKey({
envelopeId: context.envelope.id,
fieldId: field.id,
+ submissionId,
userId: context.envelope.userId,
});
@@ -2521,26 +2555,10 @@ export async function submitSigningForToken(
context.envelope.id,
database,
);
- const finalArtifacts = await finalizeEnvelope(
- {
- auditEvents: [
- ...(await listAuditEventsForEnvelope(context.envelope.id, database)),
- signedAuditEvent,
- ],
- copyRecipients,
- envelope: context.envelope,
- fields: completedFields,
- signers: completedSigners,
- sourcePdf: {
- bucketName: sourcePdfHead.bucketName,
- key: context.envelope.sourcePdfKey,
- },
- },
- {
- signedRevision: providerSignature?.revision.bytes,
- storageService,
- },
- );
+ const auditEvents = [
+ ...(await listAuditEventsForEnvelope(context.envelope.id, database)),
+ signedAuditEvent,
+ ];
const storageIdentity = {
envelopeId: context.envelope.id,
userId: context.envelope.userId,
@@ -2557,9 +2575,36 @@ export async function submitSigningForToken(
}),
];
+ // Set once this submission may have stored the final files.
+ let finalArtifactsStored = false;
+ let finalArtifacts: Awaited<ReturnType<typeof finalizeEnvelope>>;
+
try {
- await withTransaction(async (tx) => {
+ finalArtifacts = await withTransaction(async (tx) => {
await lockSentEnvelope(context.envelope.id, tx);
+ await assertStillSignersTurn(context.envelope.id, currentSignerId, tx);
+
+ // 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;
+
+ const artifacts = await finalizeEnvelope(
+ {
+ auditEvents,
+ copyRecipients,
+ envelope: context.envelope,
+ fields: completedFields,
+ signers: completedSigners,
+ sourcePdf: {
+ bucketName: sourcePdfHead.bucketName,
+ key: context.envelope.sourcePdfKey,
+ },
+ },
+ {
+ signedRevision: providerSignature?.revision.bytes,
+ storageService,
+ },
+ );
if (providerSignature) {
replacedRevisionKey = await commitProviderRevision(
@@ -2645,14 +2690,14 @@ export async function submitSigningForToken(
AND status = 'sent'
`,
[
- finalArtifacts.signedPdf.key,
- finalArtifacts.certificate.key,
- finalArtifacts.generatedAt,
- finalArtifacts.generatedAt,
+ artifacts.signedPdf.key,
+ artifacts.certificate.key,
+ artifacts.generatedAt,
+ artifacts.generatedAt,
context.envelope.id,
- finalArtifacts.signedPdf.sha256,
- finalArtifacts.certificate.sha256,
- finalArtifacts.recipientCertificate.sha256,
+ artifacts.signedPdf.sha256,
+ artifacts.certificate.sha256,
+ artifacts.recipientCertificate.sha256,
],
);
@@ -2682,22 +2727,27 @@ export async function submitSigningForToken(
{
actorEmail: null,
actorType: "system",
- createdAt: finalArtifacts.generatedAt,
+ createdAt: artifacts.generatedAt,
envelopeId: context.envelope.id,
event: "completed",
metadata: null,
},
tx,
);
+
+ return artifacts;
}, database);
signingStatePersisted = true;
await deleteReplacedRevision(replacedRevisionKey, storageService);
} catch (error) {
- await Promise.all(
- storedArtifactKeys.map((key) =>
- storageService.deleteObject(key).catch(() => undefined),
- ),
- );
+ if (finalArtifactsStored) {
+ await Promise.all(
+ storedArtifactKeys.map((key) =>
+ storageService.deleteObject(key).catch(() => undefined),
+ ),
+ );
+ }
+
throw error;
}