Skip to content

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

TypeScript

Refuse a field save made against an older field list

Claude5be86d88a931
diff --git a/db/migrations/20261119120000_fields_revision.sql b/db/migrations/20261119120000_fields_revision.sql
new file mode 100644
index 0000000..17b1aae
--- /dev/null
+++ b/db/migrations/20261119120000_fields_revision.sql
@@ -0,0 +1,7 @@
+-- How many times a draft's field list has been saved. The field editor sends
+-- the count it last saw with each save, and a save made against an older
+-- count is refused, so a save still on its way from a page the sender has
+-- left cannot overwrite a newer one made after they came back.
+
+alter table public.envelopes
+ add column if not exists fields_revision integer not null default 0;
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsx
index b11013b..5461448 100644
--- a/src/components/envelopes/prepare-live-shell.tsx
+++ b/src/components/envelopes/prepare-live-shell.tsx
@@ -469,6 +469,11 @@ function PrepareLiveShellContent({
const documentPanGestureRef = useRef<DocumentPanGesture | null>(null);
const currentFieldsRef = useRef(fields);
const lastSavedSignatureRef = useRef(serializeFieldRequest(initialFields));
+ // The field list's revision this editor last saw. Each save sends it, so
+ // the server refuses a save made against an older list instead of
+ // letting it overwrite a newer one (a save still on its way from a page
+ // the sender left, landing after one made when they came back).
+ const fieldsRevisionRef = useRef(record.fieldsRevision);
const fieldCounterRef = useRef(initialFields.length);
const persistFieldsRef = useRef<
(nextFields: readonly PrepareField[]) => Promise<PersistFieldsResult>
@@ -589,7 +594,10 @@ function PrepareLiveShellContent({
// After any save still on its way, so this one lands last.
void saveChainRef.current.then(() =>
fetch(`/api/envelopes/${envelopeId}/fields`, {
- body: JSON.stringify(buildFieldRequest(unsaved)),
+ body: JSON.stringify({
+ ...buildFieldRequest(unsaved),
+ expectedRevision: fieldsRevisionRef.current,
+ }),
headers: { "content-type": "application/json" },
keepalive: true,
method: "PUT",
@@ -677,7 +685,10 @@ function PrepareLiveShellContent({
setSaveState("saving");
const response = await fetch(`/api/envelopes/${envelopeId}/fields`, {
- body: JSON.stringify(buildFieldRequest(nextFields)),
+ body: JSON.stringify({
+ ...buildFieldRequest(nextFields),
+ expectedRevision: fieldsRevisionRef.current,
+ }),
headers: {
"content-type": "application/json",
},
@@ -694,6 +705,11 @@ function PrepareLiveShellContent({
};
}
+ // Saved, so the next save is made against this list.
+ if (payload.data) {
+ fieldsRevisionRef.current = payload.data.fieldsRevision;
+ }
+
if (
serializeFieldRequest(currentFieldsRef.current) !== requestedSignature
) {
diff --git a/src/lib/draft-changes.dbtest.ts b/src/lib/draft-changes.dbtest.ts
index 8975d2a..8225848 100644
--- a/src/lib/draft-changes.dbtest.ts
+++ b/src/lib/draft-changes.dbtest.ts
@@ -10,6 +10,8 @@ import type pg from "pg";
import { afterStatement, openTestDatabase } from "./db/test-database.ts";
import {
EnvelopeMutationError,
+ FIELDS_CHANGED_MESSAGE,
+ getPrepareEnvelopeDataForUser,
replaceDraftEnvelopeFields,
replaceDraftEnvelopeSigners,
sendDraftEnvelope,
@@ -428,3 +430,58 @@ test("sending with no email provider is refused as a setup state and leaves the
assert.equal(sent.length, 0);
});
+
+test("a field save made on an older page does not overwrite a newer one", async () => {
+ const draft = await createDraft();
+ // Two field editors opened on the same list: the one the sender is
+ // leaving, and the one they open on coming back.
+ const opened = await getPrepareEnvelopeDataForUser(
+ draft.userId,
+ draft.envelopeId,
+ { database },
+ );
+ const seenRevision = opened?.fieldsRevision;
+
+ assert.equal(typeof seenRevision, "number");
+
+ // The page they came back to saves first.
+ const saved = await replaceDraftEnvelopeFields(
+ draft.userId,
+ draft.envelopeId,
+ {
+ expectedRevision: seenRevision,
+ fields: [field(draft.casey, "signature", 0.7)],
+ },
+ database,
+ );
+
+ assert.equal(saved.fieldsRevision, seenRevision! + 1);
+
+ // The departing page's save lands afterwards, against the older list.
+ await assert.rejects(
+ replaceDraftEnvelopeFields(
+ draft.userId,
+ draft.envelopeId,
+ {
+ expectedRevision: seenRevision,
+ fields: [field(draft.riley, "signature", 0.5)],
+ },
+ database,
+ ),
+ refusedWith(409, new RegExp(FIELDS_CHANGED_MESSAGE.slice(0, 30))),
+ );
+
+ assert.deepEqual(await fieldSignersOf(draft.envelopeId), [draft.casey]);
+
+ // A save that names no revision (a template filling a new draft, say)
+ // still goes through.
+ const unchecked = await replaceDraftEnvelopeFields(
+ draft.userId,
+ draft.envelopeId,
+ { fields: [field(draft.riley, "signature", 0.5)] },
+ database,
+ );
+
+ assert.equal(unchecked.fieldsRevision, seenRevision! + 2);
+ assert.deepEqual(await fieldSignersOf(draft.envelopeId), [draft.riley]);
+});
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 313ddbb..e5d5a45 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -377,6 +377,8 @@ export type DraftSignerStepData = {
export type PrepareEnvelopeData = {
envelopeId: string;
fields: readonly FieldRecord[];
+ /** Sent back with each save, so a save from an older page is refused. */
+ fieldsRevision: number;
pageCount: number;
pages: readonly EnvelopePageRecord[];
pdfUrl: string;
@@ -2306,15 +2308,17 @@ export async function getPrepareEnvelopeDataForUser(
return null;
}
- const [fieldsByEnvelope, pages, signers] = await Promise.all([
+ const [fieldsByEnvelope, pages, signers, fieldsRevision] = await Promise.all([
listFieldsForEnvelopeIds([envelopeId], database),
listEnvelopePagesForEnvelopeId(envelopeId, database),
listSignersForEnvelopeId(envelopeId, database),
+ readFieldsRevision(envelopeId, database),
]);
return {
envelopeId,
fields: fieldsByEnvelope.get(envelopeId) ?? [],
+ fieldsRevision,
pageCount: envelope.pageCount,
pages,
pdfUrl: `/api/envelopes/${encodeURIComponent(envelopeId)}/document`,
@@ -2415,6 +2419,22 @@ async function readDraftParties(envelopeId: string, database: DbExecutor) {
* The lock an UPDATE takes, not FOR UPDATE: the signer rows written next
* need a share of this row for their foreign key.
*/
+/** What a sender is told when their field save was made on an older page. */
+export const FIELDS_CHANGED_MESSAGE =
+ "These fields were changed somewhere else, so this change was not saved. Reload the page to see the latest fields.";
+
+async function readFieldsRevision(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<number> {
+ const result = await database.query<{ fields_revision: number }>(
+ `SELECT fields_revision FROM envelopes WHERE id = $1`,
+ [envelopeId],
+ );
+
+ return result.rows[0]?.fields_revision ?? 0;
+}
+
async function lockDraftEnvelope(
userId: string,
envelopeId: string,
@@ -3697,8 +3717,20 @@ export async function replaceDraftEnvelopeFields(
};
});
- await withTransaction(async (tx) => {
+ const fieldsRevision = await withTransaction(async (tx) => {
await lockDraftEnvelope(userId, envelopeId, tx);
+
+ // Under the draft's lock, so two saves cannot both pass this check: a
+ // save made against an older list (from a page the sender has since
+ // left, say) does not overwrite a newer one.
+ if (
+ parsedInput.expectedRevision !== undefined &&
+ parsedInput.expectedRevision !==
+ (await readFieldsRevision(envelopeId, tx))
+ ) {
+ throw new EnvelopeMutationError(FIELDS_CHANGED_MESSAGE, 409);
+ }
+
await tx.query(
`
DELETE FROM fields
@@ -3757,14 +3789,17 @@ export async function replaceDraftEnvelopeFields(
);
}
- await tx.query(
+ const updated = await tx.query<{ fields_revision: number }>(
`
UPDATE envelopes
- SET updated_at = $1
+ SET updated_at = $1, fields_revision = fields_revision + 1
WHERE id = $2 AND user_id = $3
+ RETURNING fields_revision
`,
[updatedAt, envelopeId, userId],
);
+
+ return updated.rows[0]?.fields_revision ?? 0;
}, database);
return replaceFieldsResponseSchema.parse({
@@ -3773,6 +3808,7 @@ export async function replaceDraftEnvelopeFields(
(await listFieldsForEnvelopeIds([envelopeId], database)).get(
envelopeId,
) ?? [],
+ fieldsRevision,
redirectPath: `/envelopes/${envelopeId}/review`,
updatedAt,
}) as ReplaceDraftFieldsResult;
diff --git a/src/lib/schemas/field.ts b/src/lib/schemas/field.ts
index 6a43cab..b9e93d5 100644
--- a/src/lib/schemas/field.ts
+++ b/src/lib/schemas/field.ts
@@ -158,6 +158,12 @@ export const fieldPlacementListSchema = z
});
export const replaceFieldsSchema = z.object({
+ /**
+ * The field list's revision the editor last saw. When it is given and the
+ * list has been saved since, the save is refused instead of overwriting
+ * the newer list. Left out, the save always goes through.
+ */
+ expectedRevision: z.number().int().min(0).optional(),
fields: fieldPlacementListSchema,
});
@@ -168,6 +174,8 @@ export const replaceFieldsResponseSchema = z.object({
id: idSchema,
}),
),
+ /** The field list's revision after this save. */
+ fieldsRevision: z.number().int().min(0),
redirectPath: z.string().trim().min(1),
updatedAt: unixTimestampSchema,
});