Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Refuse a bulk-send retry whose saved draft's recipients changed
Matt Van Horn4bfe9c4bb004
diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.tsindex 33c17e5..86e88af 100644--- a/src/lib/bulk-send.dbtest.ts+++ b/src/lib/bulk-send.dbtest.ts@@ -22,6 +22,7 @@ import { MAX_BULK_SEND_ROWS } from "./bulk-send-csv.ts";import { openTestDatabase } from "./db/test-database.ts";import {createDraftEnvelope,+ draftRecipientsChangedMessage,getEnvelopeDetailDataForUser,getPrepareEnvelopeDataForUser,replaceDraftEnvelopeFields,@@ -1259,3 +1260,236 @@ test("a request that loses its claim before sending does not send, and the retryassert.equal(await countSent(userId), 1);assert.equal(await countEnvelopes(userId), 2);});++/** Loses the claim right after the row's draft is saved, as a slow request would. */+async function leaveProcessingDraft(+ userId: string,+ templateId: string,+ body: Record<string, unknown>,+): Promise<string> {+ const slowDatabase = new Proxy(database, {+ get(target, property, receiver) {+ if (property !== "query") {+ return Reflect.get(target, property, receiver);+ }++ return async (text: string, values?: unknown[]) => {+ const result = await target.query(text, values);++ if (+ typeof text === "string" &&+ text.includes("INSERT INTO bulk_send_batch_rows") &&+ values?.[2] === "processing"+ ) {+ await takeOverBatch(userId, body.batchKey);+ }++ return result;+ };+ },+ });++ await assert.rejects(+ bulkSendFromTemplate(userId, templateId, body, {+ database: slowDatabase,+ sender: senderFor(userId),+ storageService,+ }),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.message === bulkSendBatchBusyMessage,+ );++ const stored = await database.query<{ envelopeId: string }>(+ `+ select r.envelope_id as "envelopeId"+ from bulk_send_batch_rows r+ join bulk_send_batches b on b.id = r.batch_id+ where b.user_id = $1 and b.batch_key = $2 and r.status = 'processing'+ `,+ [userId, body.batchKey],+ );++ await database.query(+ `+ update bulk_send_batches+ set claimed_at = extract(epoch from now())::bigint - $3+ where user_id = $1 and batch_key = $2+ `,+ [userId, body.batchKey, BULK_SEND_CLAIM_STALE_SECONDS + 1],+ );++ return stored.rows[0]!.envelopeId;+}++test("a retry does not send a saved draft whose signer was changed", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\n`,+ );+ const envelopeId = await leaveProcessingDraft(userId, template.id, body);+ const prepared = await getPrepareEnvelopeDataForUser(userId, envelopeId, {+ database,+ });+ const otherEmail = `other-${randomUUID()}@example.test`;++ await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ {+ signers: [+ { email: otherEmail, id: prepared!.signers[0]!.id, name: "Other" },+ ],+ },+ database,+ );++ const retry = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.equal(retry.rows[0]?.status, "failed");+ assert.equal(retry.rows[0]?.reason, draftRecipientsChangedMessage);+ assert.equal(retry.rows[0]?.envelopeId, envelopeId);+ assert.equal(await countSent(userId), 0);+ assert.ok(+ !(await capturedInvitations()).some((email) =>+ email.to.includes(otherEmail),+ ),+ );+});++test("a retry does not send a saved two-role draft that lost a signer", async () => {+ const userId = await createUser();+ const template = await createTwoRoleTemplate(userId);+ const tenantEmail = `tenant-${randomUUID()}@example.test`;+ const body = confirmBody(+ twoRoleCsv([+ [+ "Tia Tenant",+ tenantEmail,+ "Lou Landlord",+ `landlord-${randomUUID()}@example.test`,+ "Lease",+ ],+ ]),+ );+ const envelopeId = await leaveProcessingDraft(userId, template.id, body);+ const prepared = await getPrepareEnvelopeDataForUser(userId, envelopeId, {+ database,+ });+ const tenant = prepared!.signers.find((signer) => signer.order === 1)!;++ await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ { signers: [{ email: tenant.email, id: tenant.id, name: tenant.name }] },+ database,+ );++ const retry = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.equal(retry.rows[0]?.status, "failed");+ assert.equal(retry.rows[0]?.reason, draftRecipientsChangedMessage);+ assert.equal(await countSent(userId), 0);+ assert.ok(+ !(await capturedInvitations()).some((email) =>+ email.to.includes(tenantEmail),+ ),+ );+});++test("a draft changed after the row is checked and before it is sent is not sent", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\n`,+ );+ const otherEmail = `other-${randomUUID()}@example.test`;+ let draftSaved = false;+ let edited = false;+ // The sender edits the draft between the row's last claim refresh and+ // the send, after every check in the batch code has run.+ const editingDatabase = new Proxy(database, {+ get(target, property, receiver) {+ if (property !== "query") {+ return Reflect.get(target, property, receiver);+ }++ return async (text: string, values?: unknown[]) => {+ const result = await target.query(text, values);++ if (+ typeof text === "string" &&+ text.includes("INSERT INTO bulk_send_batch_rows") &&+ values?.[2] === "processing"+ ) {+ draftSaved = true;+ } else if (+ draftSaved &&+ !edited &&+ typeof text === "string" &&+ text.includes("SET claimed_at") &&+ !text.includes("INSERT")+ ) {+ edited = true;++ const envelopeId = (+ await target.query<{ envelopeId: string }>(+ `+ select r.envelope_id as "envelopeId"+ from bulk_send_batch_rows r+ join bulk_send_batches b on b.id = r.batch_id+ where b.user_id = $1 and b.batch_key = $2+ `,+ [userId, body.batchKey],+ )+ ).rows[0]!.envelopeId;+ const prepared = await getPrepareEnvelopeDataForUser(+ userId,+ envelopeId,+ { database: target },+ );++ await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ {+ signers: [+ {+ email: otherEmail,+ id: prepared!.signers[0]!.id,+ name: "Other",+ },+ ],+ },+ target,+ );+ }++ return result;+ };+ },+ });++ const result = await bulkSendFromTemplate(userId, template.id, body, {+ database: editingDatabase,+ sender: senderFor(userId),+ storageService,+ });++ assert.ok(edited);+ assert.equal(result.rows[0]?.status, "failed");+ assert.equal(result.rows[0]?.reason, draftRecipientsChangedMessage);+ assert.equal(await countSent(userId), 0);+ assert.ok(+ !(await capturedInvitations()).some((email) =>+ email.to.includes(otherEmail),+ ),+ );+});diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.tsindex affc44f..ce423e6 100644--- a/src/lib/bulk-send.ts+++ b/src/lib/bulk-send.ts@@ -19,6 +19,8 @@ import {} from "./db/connection.ts";import {deleteDraftEnvelope,+ draftRecipientsChangedMessage,+ draftRecipientsMatch,EnvelopeMutationError,getPrepareEnvelopeDataForUser,replaceDraftEnvelopeSigners,@@ -526,6 +528,20 @@ async function sendOneRow(progress.envelopeId = null;} else if (prepared.status !== "draft") {throw new BulkSendError(bulkSendInvitationUnconfirmedMessage, 409);+ } else if (+ // The sender can edit a saved draft before retrying. Only the people+ // on the confirmed row are sent to, so a changed draft is left alone.+ !draftRecipientsMatch(+ {+ copyRecipients: [],+ signers: [...prepared.signers].sort(+ (left, right) => left.order - right.order,+ ),+ },+ { copyRecipients: [], signers: row.signers },+ )+ ) {+ throw new EnvelopeMutationError(draftRecipientsChangedMessage, 409);}}@@ -625,7 +641,10 @@ async function sendOneRow(signatureLevel: "simple",userAgent: sender.userAgent,},- { database },+ {+ database,+ expectedRecipients: { copyRecipients, signers: row.signers },+ },);} catch (error) {if (diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 7fc4332..22a00b0 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -181,10 +181,25 @@ type CorrectSentEnvelopeSignerOptions = {nowUnixTimestamp?: number;};+type ExpectedRecipient = { email: string; name: string };+type SendDraftEnvelopeOptions = {database?: DbPool;+ /**+ * The people the caller confirmed. When given, the draft is sent only if+ * its signers, in signing order, and its copy recipients are exactly+ * these. The check runs on the parties the send holds unchanged until+ * the invitation goes out.+ */+ expectedRecipients?: {+ copyRecipients: readonly ExpectedRecipient[];+ signers: readonly ExpectedRecipient[];+ };};+export const draftRecipientsChangedMessage =+ "This draft's recipients were changed after the list was confirmed, so it was not sent. Check the draft and send it from there.";+type VoidEnvelopeOptions = {database?: DbPool;};@@ -2304,6 +2319,47 @@ async function readDraftParties(envelopeId: string, database: DbExecutor) {return { copyRecipients, fields, signers };}+function recipientKey(recipient: ExpectedRecipient): string {+ return JSON.stringify([+ recipient.email.trim().toLowerCase(),+ recipient.name.trim(),+ ]);+}++/**+ * Whether a draft's parties are exactly the confirmed people: the signers+ * in signing order, and the copy recipients in any order.+ */+export function draftRecipientsMatch(+ parties: {+ copyRecipients: readonly ExpectedRecipient[];+ signers: readonly ExpectedRecipient[];+ },+ expected: {+ copyRecipients: readonly ExpectedRecipient[];+ signers: readonly ExpectedRecipient[];+ },+): boolean {+ const sameInOrder = (+ left: readonly ExpectedRecipient[],+ right: readonly ExpectedRecipient[],+ ) =>+ left.length === right.length &&+ left.every(+ (recipient, index) =>+ recipientKey(recipient) === recipientKey(right[index]!),+ );+ const sorted = (recipients: readonly ExpectedRecipient[]) =>+ [...recipients].sort((left, right) =>+ recipientKey(left).localeCompare(recipientKey(right)),+ );++ return (+ sameInOrder(parties.signers, expected.signers) &&+ sameInOrder(sorted(parties.copyRecipients), sorted(expected.copyRecipients))+ );+}+/*** Takes hold of a draft before its signers or fields are changed, and* refuses when it is no longer a draft. Saving signers, saving fields,@@ -2341,7 +2397,7 @@ export async function sendDraftEnvelope(userId: string,envelopeId: string,input: SendDraftEnvelopeInput,- { database = getDb() }: SendDraftEnvelopeOptions = {},+ { database = getDb(), expectedRecipients }: SendDraftEnvelopeOptions = {},): Promise<SendDraftEnvelopeResult> {const envelope = await getEnvelopeByIdForUser(userId, envelopeId, database);@@ -2356,6 +2412,15 @@ export async function sendDraftEnvelope(const checkedParties = await readDraftParties(envelopeId, database);const { fields, signers } = checkedParties;+ // The transaction below refuses a draft whose parties changed after this+ // read, so the people checked here are the people the invitation reaches.+ if (+ expectedRecipients &&+ !draftRecipientsMatch(checkedParties, expectedRecipients)+ ) {+ throw new EnvelopeMutationError(draftRecipientsChangedMessage, 409);+ }+if (signers.length === 0 || fields.length === 0) {throw new EnvelopeMutationError("Add signers and place fields before sending this envelope.",