Skip to content

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

TypeScript

Fix the five findings of the automated review

Claudeac318fc5afa2
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index 4eb6070..b992e43 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -373,6 +373,19 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a
await page
.getByRole("textbox", { name: "Choices" })
.fill("Monthly\nYearly");
+
+ // The field editor is on the page twice, for narrow and for wide
+ // windows. The one that was not typed in shows what was saved, so
+ // typing in it after the window changes width cannot undo the choices.
+ await page.setViewportSize({ height: 900, width: 800 });
+ await expect(page.getByRole("textbox", { name: "Choices" })).toHaveValue(
+ "Monthly\nYearly",
+ );
+ await page.setViewportSize({ height: 900, width: 1440 });
+ await expect(page.getByRole("textbox", { name: "Choices" })).toHaveValue(
+ "Monthly\nYearly",
+ );
+
await placeField("Radio button", 0.25, 0.4);
await page
.getByRole("textbox", { name: "What this button means" })
@@ -383,6 +396,11 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a
await page
.getByRole("textbox", { name: "What this button means" })
.fill("No");
+ await page.setViewportSize({ height: 900, width: 800 });
+ await expect(
+ page.getByRole("textbox", { name: "What this button means" }),
+ ).toHaveValue("No");
+ await page.setViewportSize({ height: 900, width: 1440 });
await expect(page.getByRole("button", { name: "Next →" })).toBeEnabled();
await page.getByRole("button", { name: "Next →" }).click();
await expect(page).toHaveURL(/\/review$/);
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsx
index c8cb08d..cc77640 100644
--- a/src/components/envelopes/prepare-live-shell.tsx
+++ b/src/components/envelopes/prepare-live-shell.tsx
@@ -27,9 +27,11 @@ import { type PrepareEnvelopeData } from "@/lib/envelopes";
import {
describeChoiceFieldProblem,
findChoiceFieldProblem,
+ labelTextToShow,
MAX_FIELD_OPTIONS,
MAX_FIELD_OPTION_LENGTH,
MAX_RADIO_GROUP_BUTTONS,
+ optionsTextToShow,
parseOptionLines,
} from "@/lib/field-choices";
import {
@@ -1425,7 +1427,13 @@ function FieldEditor({
);
const optionCount = field.options?.length ?? 0;
// The editor is on the page twice, once for narrow screens and once in
- // the side panel, so its inputs cannot share fixed ids.
+ // the side panel, and only one of the two is typed in. What the other
+ // holds goes stale, so each shows its own text only while that still
+ // stands for the saved value. Otherwise, after the window changes width,
+ // typing would put the stale text back over what was saved.
+ const shownLabel = labelTextToShow(labelDraft, field.label);
+ const shownOptions = optionsTextToShow(optionsDraft, field.options);
+ // For the same reason its inputs cannot share fixed ids.
const editorId = useId();
const optionsId = `${editorId}-options`;
const labelId = `${editorId}-label`;
@@ -1490,7 +1498,7 @@ function FieldEditor({
}}
placeholder={"Yes\nNo\nNot sure"}
spellCheck={false}
- value={optionsDraft}
+ value={shownOptions}
/>
<p
className={`mt-1.5 px-1 text-xs leading-5 ${
@@ -1525,7 +1533,7 @@ function FieldEditor({
onSetLabel(event.target.value.trim() || undefined);
}}
placeholder="Yes"
- value={labelDraft}
+ value={shownLabel}
/>
<p
className={`mt-1.5 px-1 text-xs leading-5 ${
diff --git a/src/lib/automatic-reminders.dbtest.ts b/src/lib/automatic-reminders.dbtest.ts
index 0d4775c..79b842f 100644
--- a/src/lib/automatic-reminders.dbtest.ts
+++ b/src/lib/automatic-reminders.dbtest.ts
@@ -6,7 +6,11 @@ import type pg from "pg";
import { openTestDatabase } from "./db/test-database.ts";
import { runEnvelopeSchedule } from "./envelope-schedule.ts";
-import { changeEnvelopeReminders, EnvelopeMutationError } from "./envelopes.ts";
+import {
+ changeEnvelopeDeadline,
+ changeEnvelopeReminders,
+ EnvelopeMutationError,
+} from "./envelopes.ts";
import { verifyAuditChain } from "./services/audit.ts";
import type {
EmailService,
@@ -131,11 +135,15 @@ async function auditEvents(envelopeId: string) {
return result.rows.map((row) => row.event);
}
-function recordingEmailService(failWith?: Error) {
+function recordingEmailService(
+ failWith?: Error,
+ beforeFailing?: (message: TransactionalEmailMessage) => Promise<void>,
+) {
const sent: TransactionalEmailMessage[] = [];
const service: EmailService = {
async send(message) {
if (failWith) {
+ await beforeFailing?.(message);
throw failWith;
}
@@ -254,6 +262,36 @@ test("a reminder whose email fails leaves the signer's link as it was", async ()
);
});
+test("a deadline moved while a reminder's email fails stays moved", async () => {
+ const due = await createSentEnvelope({ reminderIntervalDays: 1 });
+ let newDeadline: number | undefined;
+ const failing = recordingEmailService(
+ new Error("mail is down"),
+ async (message) => {
+ if (message.to.startsWith(due.signerId)) {
+ newDeadline = (
+ await changeEnvelopeDeadline(
+ due.userId,
+ due.envelopeId,
+ { expiresInDays: 7, senderEmail: "[email protected]" },
+ { database },
+ )
+ ).expiresAt;
+ }
+ },
+ );
+
+ await run(SENT_AT + DAY, failing.service);
+
+ const signer = await readSigner(due.signerId);
+
+ // The link the signer already holds is the one that works, and it lasts
+ // until the new deadline, not until the one it was issued with.
+ assert.ok(newDeadline);
+ assert.equal(signer.signing_token_hash, due.tokenHash);
+ assert.equal(signer.signing_token_expires_at, newDeadline);
+});
+
test("a run that is out of time leaves the rest for the next one", async () => {
const due = await createSentEnvelope({ reminderIntervalDays: 1 });
const { sent, service } = recordingEmailService();
diff --git a/src/lib/envelope-deadline.dbtest.ts b/src/lib/envelope-deadline.dbtest.ts
index 3795c08..95690a7 100644
--- a/src/lib/envelope-deadline.dbtest.ts
+++ b/src/lib/envelope-deadline.dbtest.ts
@@ -5,6 +5,7 @@ import { after, before, test } from "node:test";
import type pg from "pg";
import { openTestDatabase } from "./db/test-database.ts";
+import { formatDeadline } from "./envelope-deadline.ts";
import { runEnvelopeSchedule } from "./envelope-schedule.ts";
import { changeEnvelopeDeadline, EnvelopeMutationError } from "./envelopes.ts";
import { ReminderMutationError, sendManualEnvelopeNudge } from "./reminders.ts";
@@ -14,7 +15,12 @@ import type {
TransactionalEmailMessage,
} from "./services/email.ts";
import { issueSigningLink } from "./services/signing-links.ts";
-import { recordSignerConsent, SigningAccessError } from "./signing.ts";
+import type { StorageService } from "./services/storage.ts";
+import {
+ recordSignerConsent,
+ SigningAccessError,
+ submitSigningForToken,
+} from "./signing.ts";
import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";
// An envelope's deadline against a real Postgres: what a passed deadline
@@ -30,6 +36,8 @@ const createdUsers: string[] = [];
before(async () => {
database = await openTestDatabase();
+ // The invitation email reads the install's name through the shared pool.
+ globalThis.__signudocPgPool = database;
});
after(async () => {
@@ -131,7 +139,10 @@ function consent(token: string) {
);
}
-function recordingEmailService(failWith?: Error) {
+function recordingEmailService(
+ failWith?: Error,
+ whileSending?: (message: TransactionalEmailMessage) => Promise<void>,
+) {
const sent: TransactionalEmailMessage[] = [];
const service: EmailService = {
async send(message) {
@@ -139,6 +150,8 @@ function recordingEmailService(failWith?: Error) {
throw failWith;
}
+ await whileSending?.(message);
+
sent.push(message);
return { accepted: [message.to], messageId: "m-1", rejected: [] };
@@ -353,3 +366,178 @@ test("a notice whose email fails is tried again on the next run", async () => {
);
assert.deepEqual(await auditEvents(envelopeId), ["expired"]);
});
+
+test("nothing is marked as told before the notice has gone out", async () => {
+ const now = unixNow();
+ const { envelopeId, userId } = await createSentEnvelope({
+ expiresAt: now - 60,
+ });
+ const seenWhileSending: (number | null)[] = [];
+ // A run that is cut off here, mid-send, must leave the notice still due.
+ const { sent, service } = recordingEmailService(
+ undefined,
+ async (message) => {
+ if (message.to.startsWith(userId)) {
+ seenWhileSending.push(
+ (await readEnvelope(envelopeId)).expiry_notified_at,
+ );
+ assert.deepEqual(await auditEvents(envelopeId), []);
+ }
+ },
+ );
+
+ await runEnvelopeSchedule({ database, emailService: service, now });
+
+ assert.deepEqual(seenWhileSending, [null]);
+ assert.equal(
+ sent.filter((message) => message.to.startsWith(userId)).length,
+ 1,
+ );
+ assert.equal((await readEnvelope(envelopeId)).expiry_notified_at, now);
+ assert.deepEqual(await auditEvents(envelopeId), ["expired"]);
+});
+
+test("a deadline moved during the run is not told or noted as passed", async () => {
+ const now = unixNow();
+ // Notices go out oldest deadline first, so this one is sent first.
+ const first = await createSentEnvelope({ expiresAt: now - 2 * DAY });
+ const second = await createSentEnvelope({ expiresAt: now - 60 });
+ const moveDeadline = (envelope: typeof first) =>
+ changeEnvelopeDeadline(
+ envelope.userId,
+ envelope.envelopeId,
+ { expiresInDays: 7, senderEmail: "[email protected]" },
+ { database },
+ );
+ const { sent, service } = recordingEmailService(
+ undefined,
+ async (message) => {
+ if (message.to.startsWith(first.userId)) {
+ // While the first notice is on its way, both senders move their
+ // deadlines: one too late to stop the notice, one in time.
+ await moveDeadline(first);
+ await moveDeadline(second);
+ }
+ },
+ );
+
+ await runEnvelopeSchedule({ database, emailService: service, now });
+
+ assert.equal(
+ sent.filter((message) => message.to.startsWith(first.userId)).length,
+ 1,
+ );
+ assert.equal(
+ sent.some((message) => message.to.startsWith(second.userId)),
+ false,
+ );
+
+ // Neither trail says "expired", and each new deadline is still to be told
+ // about if it passes in turn.
+ for (const envelope of [first, second]) {
+ assert.deepEqual(await auditEvents(envelope.envelopeId), [
+ "deadline_changed",
+ ]);
+ assert.equal(
+ (await readEnvelope(envelope.envelopeId)).expiry_notified_at,
+ null,
+ );
+ }
+});
+
+test("a deadline moved while a signer submits reaches the next signer", async () => {
+ const now = unixNow();
+ const { envelopeId, signerId, token, userId } = await createSentEnvelope({
+ expiresAt: now + DAY,
+ });
+ const nextSignerId = randomUUID();
+ const nextSignerEmail = `${nextSignerId}@example.test`;
+ const fieldId = randomUUID();
+
+ await database.query(
+ `update signers set signing_token_expires_at = $1 where id = $2`,
+ [now + DAY, signerId],
+ );
+ await database.query(
+ `
+ insert into signers (id, envelope_id, name, email, sign_order, status)
+ values ($1, $2, 'Casey Second', $3, 2, 'pending')
+ `,
+ [nextSignerId, envelopeId, nextSignerEmail],
+ );
+ await database.query(
+ `
+ insert into fields (
+ id, envelope_id, signer_id, type, page, x, y, width, height
+ ) values ($1, $2, $3, 'signature', 1, 0.1, 0.1, 0.2, 0.1)
+ `,
+ [fieldId, envelopeId, signerId],
+ );
+ await consent(token);
+
+ let newDeadline: number | undefined;
+ const refuse = async (): Promise<never> => {
+ throw new Error("not used");
+ };
+ const storageService: StorageService = {
+ deleteObject: refuse,
+ getObject: refuse,
+ getObjectStream: refuse,
+ headObject: refuse,
+ // Storing the drawn signature comes after the envelope was read and
+ // before the signature is saved: the gap a sender's change can land in.
+ async putObject({ key }) {
+ newDeadline = (
+ await changeEnvelopeDeadline(
+ userId,
+ envelopeId,
+ { expiresInDays: 7, senderEmail: "[email protected]" },
+ { database },
+ )
+ ).expiresAt;
+
+ return { bucketName: "test", key };
+ },
+ };
+ const { sent, service } = recordingEmailService();
+
+ await submitSigningForToken(
+ token,
+ {
+ clientTimezoneOffsetMinutes: 0,
+ fields: [
+ {
+ fieldId,
+ imageDataUrl: "data:image/png;base64,iVBORw0KGgo=",
+ inputMethod: "drawn",
+ type: "signature",
+ },
+ ],
+ },
+ { database, emailService: service, storageService },
+ );
+
+ assert.ok(newDeadline && newDeadline >= now + 7 * DAY);
+
+ const nextSigner = await database.query<{
+ signing_token_expires_at: number | null;
+ status: string;
+ }>(`select status, signing_token_expires_at from signers where id = $1`, [
+ nextSignerId,
+ ]);
+
+ // The next signer's link lasts until the deadline as it is now, not as it
+ // was when the signer before them opened the page.
+ assert.equal(nextSigner.rows[0]?.status, "notified");
+ assert.equal(nextSigner.rows[0]?.signing_token_expires_at, newDeadline);
+
+ const invitation = sent.find((message) => message.to === nextSignerEmail);
+
+ assert.equal(invitation?.template, "signing_invitation");
+ assert.ok(
+ invitation?.textBody.includes(
+ `This request expires on ${formatDeadline(newDeadline)}.`,
+ ),
+ );
+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
+});
diff --git a/src/lib/envelope-deadline.test.ts b/src/lib/envelope-deadline.test.ts
index ce0091a..fa8ec21 100644
--- a/src/lib/envelope-deadline.test.ts
+++ b/src/lib/envelope-deadline.test.ts
@@ -6,6 +6,7 @@ import {
EnvelopeDeadlinePassedError,
formatDeadline,
isEnvelopeExpired,
+ nextSignerLinkExpiresAt,
parseDeadlineDays,
signingLinkLifetimeSeconds,
} from "./envelope-deadline.ts";
@@ -63,6 +64,16 @@ test("a signing link lives until the envelope's deadline", () => {
);
});
+test("the next signer's link ends at the envelope's deadline", () => {
+ assert.equal(nextSignerLinkExpiresAt(NOW + 5 * DAY, NOW), NOW + 5 * DAY);
+ // The deadline passed while the signer before them was submitting.
+ assert.equal(nextSignerLinkExpiresAt(NOW - 5, NOW), NOW + 60);
+ assert.equal(
+ nextSignerLinkExpiresAt(null, NOW),
+ NOW + SIGNING_LINK_TTL_SECONDS,
+ );
+});
+
test("a deadline is written out in full, in UTC", () => {
// 2027-01-15 08:00:00 UTC
assert.equal(
diff --git a/src/lib/envelope-deadline.ts b/src/lib/envelope-deadline.ts
index 4b375fc..89d7e62 100644
--- a/src/lib/envelope-deadline.ts
+++ b/src/lib/envelope-deadline.ts
@@ -75,6 +75,24 @@ export function signingLinkLifetimeSeconds(
return envelopeExpiresAt - issuedAt;
}
+/**
+ * When the link of a signer whose turn starts now should end: at the
+ * envelope's deadline. The signer before them finished inside the deadline
+ * a moment ago, so a minute is kept in hand instead of refusing.
+ *
+ * Give it the deadline as read under the envelope's lock. A sender can move
+ * the deadline while a signer is submitting, and a deadline read earlier
+ * would hand the next signer a link that ends at the old one.
+ */
+export function nextSignerLinkExpiresAt(
+ envelopeExpiresAt: number | null | undefined,
+ turnStartsAt: number,
+): number {
+ return typeof envelopeExpiresAt === "number"
+ ? Math.max(envelopeExpiresAt, turnStartsAt + 60)
+ : turnStartsAt + SIGNING_LINK_TTL_SECONDS;
+}
+
const deadlineFormatter = new Intl.DateTimeFormat("en-US", {
day: "numeric",
hour: "numeric",
diff --git a/src/lib/envelope-schedule.ts b/src/lib/envelope-schedule.ts
index 9904f71..871492c 100644
--- a/src/lib/envelope-schedule.ts
+++ b/src/lib/envelope-schedule.ts
@@ -1,7 +1,12 @@
-import { type DbPool, queryMany, withTransaction } from "./db/connection.ts";
+import {
+ type DbPool,
+ queryMany,
+ queryOne,
+ withTransaction,
+} from "./db/connection.ts";
import { formatDeadline } from "./envelope-deadline.ts";
import { sendAutomaticEnvelopeReminder } from "./reminders.ts";
-import { lockEnvelopeAuditChain, recordAuditEvent } from "./services/audit.ts";
+import { recordAuditEvent } from "./services/audit.ts";
import { createEmailService, type EmailService } from "./services/email.ts";
import { AUTOMATIC_REMINDER_SLACK_SECONDS } from "./services/reminders.ts";
import { resolveAppUrl } from "./utils/env.ts";
@@ -14,10 +19,17 @@ import { resolveAppUrl } from "./utils/env.ts";
// for automatic reminders.
//
// It runs from the same cron call as the cleanup (see retention-job.ts), so
-// an install needs no second schedule. Each envelope is claimed in the
-// database before its email goes out, and the claim is given back if the
-// email fails, so a failed run is retried the next day and a second run
-// never sends twice.
+// an install needs no second schedule, and that call's lock means two runs
+// never work at once.
+//
+// A notice about a passed deadline is sent first and noted afterwards. So a
+// notice that did not go out, because the email failed or because the run
+// was cut off, is simply still due on the next run. The cost is that a run
+// cut off between the two can send the notice a second time; the mail
+// provider drops a repeat that reaches it within its idempotency window.
+//
+// A reminder changes the signer's link, so it is saved first and undone if
+// its email fails (see reminders.ts).
const BATCH_SIZE = 200;
// The job shares one function call with the cleanup, and a mail provider
@@ -83,18 +95,45 @@ async function listExpiredEnvelopesToNotify(
);
}
+/**
+ * True while there is still something to tell: the envelope is out, its
+ * deadline is the one that passed, and the sender has not been told. The
+ * list above can be minutes old by the time an envelope's turn comes, and
+ * the sender may have moved the deadline or voided the envelope since.
+ */
+async function isExpiryNoticeDue(
+ envelope: ExpiredEnvelopeRow,
+ database: DbPool,
+): Promise<boolean> {
+ const due = await queryOne<{ id: string }>(
+ database,
+ `
+ SELECT id
+ FROM envelopes
+ WHERE id = $1
+ AND status = 'sent'
+ AND expires_at = $2
+ AND expiry_notified_at IS NULL
+ `,
+ [envelope.id, envelope.expiresAt],
+ );
+
+ return due !== null;
+}
+
/**
* Marks the envelope as told and notes the passed deadline in its audit
- * trail. False when there is nothing to tell any more: the sender moved the
- * deadline, the envelope was finished or voided, or another run got here.
+ * trail, once the notice has gone out. Nothing is noted when the sender
+ * moved the deadline while the notice was on its way: the new deadline is a
+ * new thing to tell.
*/
-async function claimExpiryNotice(
+async function noteExpiryNoticeSent(
envelope: ExpiredEnvelopeRow,
now: number,
database: DbPool,
-): Promise<boolean> {
- return withTransaction(async (tx) => {
- const claimed = await tx.query(
+): Promise<void> {
+ await withTransaction(async (tx) => {
+ const noted = await tx.query(
`
UPDATE envelopes
SET expiry_notified_at = $1
@@ -106,8 +145,8 @@ async function claimExpiryNotice(
[now, envelope.id, envelope.expiresAt],
);
- if (claimed.rowCount !== 1) {
- return false;
+ if (noted.rowCount !== 1) {
+ return;
}
await recordAuditEvent(
@@ -120,46 +159,6 @@ async function claimExpiryNotice(
},
tx,
);
-
- return true;
- }, database);
-}
-
-/** Gives a claim back after its email failed, so the next run tries again. */
-async function releaseExpiryNotice(
- envelope: ExpiredEnvelopeRow,
- now: number,
- database: DbPool,
-): Promise<void> {
- await withTransaction(async (tx) => {
- await lockEnvelopeAuditChain(envelope.id, tx);
-
- const removed = await tx.query(
- `
- DELETE FROM audit_events
- WHERE envelope_id = $1
- AND event = 'expired'
- AND created_at = $2
- -- Only while it is still the newest link of the audit chain.
- AND sequence = (
- SELECT max(sequence) FROM audit_events WHERE envelope_id = $1
- )
- `,
- [envelope.id, now],
- );
-
- // An event chained after it keeps the note in place, and then the
- // envelope stays marked: the trail must not say "expired" twice.
- if (removed.rowCount === 1) {
- await tx.query(
- `
- UPDATE envelopes
- SET expiry_notified_at = NULL
- WHERE id = $1 AND expiry_notified_at = $2
- `,
- [envelope.id, now],
- );
- }
}, database);
}
@@ -202,26 +201,14 @@ async function sendExpiryNotices({
}
try {
- if (!(await claimExpiryNotice(envelope, now, database))) {
+ if (!(await isExpiryNoticeDue(envelope, database))) {
continue;
}
- try {
- await emailService().send(buildExpiryNotice(envelope), {
- idempotencyKey: `expiry-notice/${envelope.id}/${envelope.expiresAt}`,
- });
- } catch (error) {
- await releaseExpiryNotice(envelope, now, database).catch(
- (releaseError: unknown) => {
- console.error(
- `Failed to give back the expiry notice claim for envelope ${envelope.id}:`,
- releaseError,
- );
- },
- );
-
- throw error;
- }
+ await emailService().send(buildExpiryNotice(envelope), {
+ idempotencyKey: `expiry-notice/${envelope.id}/${envelope.expiresAt}`,
+ });
+ await noteExpiryNoticeSent(envelope, now, database);
summary.expiryNoticesSent += 1;
} catch (error) {
diff --git a/src/lib/field-choices.test.ts b/src/lib/field-choices.test.ts
index 9683029..3daa918 100644
--- a/src/lib/field-choices.test.ts
+++ b/src/lib/field-choices.test.ts
@@ -9,11 +9,38 @@ import {
findChoiceFieldProblem,
isNumberEntry,
judgeRadioGroups,
+ labelTextToShow,
MAX_FIELD_OPTIONS,
NUMBER_ENTRY_MESSAGE,
+ optionsTextToShow,
parseOptionLines,
} from "./field-choices.ts";
+test("an editor box shows what was typed only while it still stands for what is saved", () => {
+ const saved = ["Monthly", "Yearly"];
+
+ // Mid-thought: the empty line and the trailing space are kept.
+ assert.equal(
+ optionsTextToShow("Monthly\nYearly \n", saved),
+ "Monthly\nYearly \n",
+ );
+ // The other copy of the editor: never typed in, or typed in a while ago.
+ assert.equal(optionsTextToShow("", saved), "Monthly\nYearly");
+ assert.equal(
+ optionsTextToShow("Monthly\nYearly", [...saved, "Once"]),
+ "Monthly\nYearly\nOnce",
+ );
+ assert.equal(optionsTextToShow("Yearly\nMonthly", saved), "Monthly\nYearly");
+ assert.equal(optionsTextToShow("Old", null), "");
+ assert.equal(optionsTextToShow(" \n", []), " \n");
+
+ assert.equal(labelTextToShow("Yes ", "Yes"), "Yes ");
+ assert.equal(labelTextToShow("", "Yes"), "Yes");
+ assert.equal(labelTextToShow("Ye", "Yes"), "Yes");
+ assert.equal(labelTextToShow("Old", undefined), "");
+ assert.equal(labelTextToShow(" ", null), " ");
+});
+
test("a number field takes plain and comma-grouped numbers and nothing else", () => {
for (const entry of [
"0",
diff --git a/src/lib/field-choices.ts b/src/lib/field-choices.ts
index 9553be7..e10023a 100644
--- a/src/lib/field-choices.ts
+++ b/src/lib/field-choices.ts
@@ -49,6 +49,40 @@ export function parseOptionLines(text: string): string[] {
return options;
}
+/**
+ * What the editor's box for a dropdown's choices should show: the text as
+ * it was typed there, for as long as that text still gives the saved
+ * choices, and otherwise the saved choices.
+ *
+ * The box keeps what was typed so that a trailing space or an empty line
+ * survives in mid-thought. But the field editor is on the page twice, for
+ * narrow and for wide screens, and only one of the two is typed in. What
+ * the other one holds goes stale, and it must not be what the sender types
+ * on top of after the window changes width.
+ */
+export function optionsTextToShow(
+ typedText: string,
+ savedOptions: readonly string[] | null | undefined,
+): string {
+ const saved = savedOptions ?? [];
+ const typed = parseOptionLines(typedText);
+
+ return typed.length === saved.length &&
+ typed.every((option, index) => option === saved[index])
+ ? typedText
+ : saved.join("\n");
+}
+
+/** The same for the box that holds a radio button's label. */
+export function labelTextToShow(
+ typedText: string,
+ savedLabel: string | null | undefined,
+): string {
+ const saved = savedLabel ?? "";
+
+ return typedText.trim() === saved ? typedText : saved;
+}
+
type ChoiceField = {
groupId?: string | null;
options?: readonly string[] | null;
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index ff620d2..dc521ca 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -131,11 +131,16 @@ export class ReminderMutationError extends Error {
}
}
-/** The envelope, and only for its owner when a user is given. */
+/**
+ * The envelope, and only for its owner when a user is given. With a lock,
+ * inside a transaction, the envelope's row is held until the transaction
+ * ends, so its deadline cannot be moved in between.
+ */
async function getReminderEnvelope(
envelopeId: string,
userId: string | null,
database: DbExecutor,
+ { lock = false }: { lock?: boolean } = {},
): Promise<ReminderEnvelopeRow | null> {
return queryOne<ReminderEnvelopeRow>(
database,
@@ -154,6 +159,7 @@ async function getReminderEnvelope(
JOIN "user" u ON u.id = e.user_id
WHERE e.id = $1
AND ($2::text IS NULL OR e.user_id = $2)
+ ${lock ? "FOR UPDATE OF e" : ""}
`,
[envelopeId, userId],
);
@@ -313,7 +319,12 @@ async function persistReminder(
issuedAt: dispatchedAt,
});
return withTransaction(async (tx) => {
- const persistedEnvelope = await getReminderEnvelope(envelopeId, userId, tx);
+ const persistedEnvelope = await getReminderEnvelope(
+ envelopeId,
+ userId,
+ tx,
+ { lock: true },
+ );
if (!persistedEnvelope) {
throw new ReminderMutationError("This envelope is unavailable.", 404);
@@ -326,7 +337,8 @@ async function persistReminder(
);
}
- // The deadline may have been moved since the link was issued.
+ // The deadline may have been moved since the link was issued. From
+ // here on it cannot be: the envelope's row is locked.
if (persistedEnvelope.expiresAt !== envelope.expiresAt) {
throw new ReminderMutationError(
"This envelope's deadline just changed. Try again.",
@@ -521,7 +533,13 @@ async function deliverReminder(
UPDATE signers
SET
signing_token_hash = $1,
- signing_token_expires_at = $2,
+ -- The old link gets its old end back, unless the sender moved
+ -- the deadline while the email was failing: then the link
+ -- already ends at the new deadline, and keeps it.
+ signing_token_expires_at = CASE
+ WHEN signing_token_expires_at = $8 THEN $2
+ ELSE signing_token_expires_at
+ END,
last_notified_at = $3,
last_nudged_at = $4,
updated_at = $5
@@ -537,6 +555,7 @@ async function deliverReminder(
persisted.previousSigner.updatedAt,
persisted.previousSigner.id,
persisted.envelopeId,
+ persisted.issuedLink.exp,
],
);
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 2fbbaa2..44755a7 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -82,7 +82,10 @@ import {
} from "./types/domain.ts";
import { getEnv } from "./utils/env.ts";
import { escapeHtml } from "./utils/html.ts";
-import { isEnvelopeExpired } from "./envelope-deadline.ts";
+import {
+ isEnvelopeExpired,
+ nextSignerLinkExpiresAt,
+} from "./envelope-deadline.ts";
import { describeEntryProblem, judgeRadioGroups } from "./field-choices.ts";
import {
buildElectronicRecordsDisclosure,
@@ -204,7 +207,9 @@ type ResolvedSigningContext = {
type SubmitSigningOptions = {
database?: DbPool;
+ emailService?: EmailService;
requestMeta?: SigningRequestMeta;
+ storageService?: StorageService;
/** The extra checks this browser has passed for the link (from its cookie). */
verifiedMethods?: readonly SignerCheckMethod[];
};
@@ -1649,7 +1654,9 @@ export async function submitSigningForToken(
input: unknown,
{
database = getDb(),
+ emailService: givenEmailService,
requestMeta = {},
+ storageService: givenStorageService,
verifiedMethods = [],
}: SubmitSigningOptions = {},
): Promise<SigningSubmitResponse> {
@@ -1668,8 +1675,8 @@ export async function submitSigningForToken(
);
}
- const emailService = createEmailService();
- const storageService = createStorageService();
+ const emailService = givenEmailService ?? createEmailService();
+ const storageService = givenStorageService ?? createStorageService();
const currentSignerId = context.signer.id;
if (!currentSignerId) {
@@ -1877,15 +1884,9 @@ export async function submitSigningForToken(
);
}
- nextSignerLink = await issueSigningLink({
- // Until the envelope's deadline. The signer who just finished was
- // inside it a moment ago, so a minute is kept in hand.
- expiresInSeconds:
- typeof context.envelope.expiresAt === "number"
- ? Math.max(60, context.envelope.expiresAt - submittedAt)
- : undefined,
- issuedAt: submittedAt,
- });
+ // Only the link itself. When it ends is settled further down, from
+ // the deadline as it stands once the envelope is locked.
+ nextSignerLink = await issueSigningLink({ issuedAt: submittedAt });
}
for (const upload of drawnSignatureUploads) {
@@ -1923,17 +1924,35 @@ export async function submitSigningForToken(
});
if (nextSigner && nextSignerLink) {
+ // The deadline the next signer is given. The sender can move it while
+ // this signer submits, and moving it only reaches the signer whose
+ // turn it is then. So it is read here, where this update holds the
+ // envelope's row and a change of deadline has to wait its turn.
+ let nextSignerDeadline = context.envelope.expiresAt ?? null;
+
await withTransaction(async (tx) => {
- await tx.query(
+ const lockedEnvelope = await queryOne<{ expiresAt: number | null }>(
+ tx,
`
UPDATE envelopes
SET updated_at = $1
WHERE id = $2
AND status = 'sent'
+ RETURNING expires_at AS "expiresAt"
`,
[submittedAt, context.envelope.id],
);
+ if (!lockedEnvelope) {
+ // Voided or declined since the page was opened.
+ throw new SigningMutationError(
+ "This signing link is no longer active.",
+ 409,
+ );
+ }
+
+ nextSignerDeadline = lockedEnvelope.expiresAt;
+
for (const update of fieldUpdates.values()) {
const result = await tx.query(
`
@@ -2009,7 +2028,7 @@ export async function submitSigningForToken(
`,
[
nextSignerLink.tokenHash,
- nextSignerLink.exp,
+ nextSignerLinkExpiresAt(lockedEnvelope.expiresAt, submittedAt),
submittedAt,
submittedAt,
submittedAt,
@@ -2047,7 +2066,7 @@ export async function submitSigningForToken(
buildSigningInvitationEmail({
branding: await getBranding(),
envelopeTitle: context.envelope.title,
- expiresAt: context.envelope.expiresAt,
+ expiresAt: nextSignerDeadline,
senderName: normalizeSenderName(context.sender),
signerEmail: nextSigner.email,
signerName: nextSigner.name,
diff --git a/src/lib/templates.dbtest.ts b/src/lib/templates.dbtest.ts
index 4e35737..934ee12 100644
--- a/src/lib/templates.dbtest.ts
+++ b/src/lib/templates.dbtest.ts
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { after, before, test } from "node:test";
@@ -30,6 +30,7 @@ import {
deleteTemplate,
getUseTemplateDataForUser,
listTemplatesForUser,
+ MAX_TEMPLATES_PER_USER,
saveEnvelopeAsTemplate,
TemplateError,
} from "./templates.ts";
@@ -537,6 +538,105 @@ test("the database refuses a template without signers", async () => {
await insert('[{"id":"r1","name":"Client"}]');
});
+test("a template whose document cannot be deleted is kept, to be deleted again", async () => {
+ const userId = await createUser();
+ const { envelopeId } = await createPreparedDraft(userId);
+ const template = await saveEnvelopeAsTemplate(
+ userId,
+ envelopeId,
+ { name: "Lease" },
+ { database, storageService },
+ );
+ const key = buildTemplatePdfKey({ templateId: template.id, userId });
+ const storageDown: StorageService = {
+ ...storageService,
+ async deleteObject() {
+ throw new Error("storage is down");
+ },
+ };
+
+ await assert.rejects(
+ deleteTemplate(userId, template.id, {
+ database,
+ storageService: storageDown,
+ }),
+ assertTemplateError(503),
+ );
+
+ // Still listed, so the document is still known and can be asked for again.
+ assert.equal(await fileExists(key), true);
+ assert.deepEqual(
+ (await listTemplatesForUser(userId, database)).map((entry) => entry.id),
+ [template.id],
+ );
+
+ await deleteTemplate(userId, template.id, { database, storageService });
+
+ assert.equal(await fileExists(key), false);
+ assert.deepEqual(await listTemplatesForUser(userId, database), []);
+});
+
+test("saves at the same moment cannot pass the most an account may keep", async () => {
+ const userId = await createUser();
+ const { envelopeId } = await createPreparedDraft(userId);
+
+ // One short of full.
+ await database.query(
+ `
+ insert into templates (
+ id, user_id, name, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, roles, fields, created_at,
+ updated_at
+ )
+ select
+ gen_random_uuid(), $1, 'Filler ' || n, 'test/filler-' || n || '.pdf',
+ 'filler.pdf', 10, 1, '[{"id":"r1","name":"Client"}]'::jsonb,
+ '[]'::jsonb, 1, 1
+ from generate_series(1, $2::int) as n
+ `,
+ [userId, MAX_TEMPLATES_PER_USER - 1],
+ );
+
+ const saves = await Promise.allSettled(
+ ["First", "Second"].map((name) =>
+ saveEnvelopeAsTemplate(
+ userId,
+ envelopeId,
+ { name },
+ { database, storageService },
+ ),
+ ),
+ );
+ const stored = saves.flatMap((save) =>
+ save.status === "fulfilled" ? [save.value] : [],
+ );
+ const refused = saves.flatMap((save) =>
+ save.status === "rejected" ? [save.reason as unknown] : [],
+ );
+
+ assert.equal(stored.length, 1);
+ assert.equal(refused.length, 1);
+ assertTemplateError(409)(refused[0]);
+ assert.equal(
+ (
+ await database.query<{ total: number }>(
+ `select count(*)::int as total from templates where user_id = $1`,
+ [userId],
+ )
+ ).rows[0]?.total,
+ MAX_TEMPLATES_PER_USER,
+ );
+
+ // The save that was refused took its copy of the document back.
+ const keptDocuments = (
+ await readdir(path.join(storageDir, "users", userId, "templates"), {
+ recursive: true,
+ })
+ ).filter((entry) => entry.endsWith("original.pdf"));
+
+ assert.deepEqual(keptDocuments, [path.join(stored[0]!.id, "original.pdf")]);
+});
+
test("closing the account removes its templates and their documents", async () => {
const userId = await createUser();
const { envelopeId } = await createPreparedDraft(userId);
diff --git a/src/lib/templates.ts b/src/lib/templates.ts
index dc932cc..7c2d363 100644
--- a/src/lib/templates.ts
+++ b/src/lib/templates.ts
@@ -6,6 +6,7 @@ import {
getDb,
queryMany,
queryOne,
+ withTransaction,
} from "./db/connection.ts";
import {
createDraftEnvelope,
@@ -58,6 +59,25 @@ type TemplateOptions = {
storageService?: StorageService;
};
+/** Refuses another template for a user who already has the most allowed. */
+async function assertRoomForTemplate(
+ userId: string,
+ database: DbExecutor,
+): Promise<void> {
+ const existing = await queryOne<{ total: number }>(
+ database,
+ `SELECT count(*)::int AS total FROM templates WHERE user_id = $1`,
+ [userId],
+ );
+
+ if ((existing?.total ?? 0) >= MAX_TEMPLATES_PER_USER) {
+ throw new TemplateError(
+ `You have ${String(MAX_TEMPLATES_PER_USER)} templates, which is the most an account can keep. Delete one to save another.`,
+ 409,
+ );
+ }
+}
+
type TemplateRow = {
createdAt: number;
fields: unknown;
@@ -301,18 +321,10 @@ export async function saveEnvelopeAsTemplate(
: [];
}),
);
- const existing = await queryOne<{ total: number }>(
- database,
- `SELECT count(*)::int AS total FROM templates WHERE user_id = $1`,
- [userId],
- );
- if ((existing?.total ?? 0) >= MAX_TEMPLATES_PER_USER) {
- throw new TemplateError(
- `You have ${String(MAX_TEMPLATES_PER_USER)} templates, which is the most an account can keep. Delete one to save another.`,
- 409,
- );
- }
+ // Before the document is copied, so a full account costs no upload. It is
+ // counted again when the template is stored.
+ await assertRoomForTemplate(userId, database);
let document: Awaited<ReturnType<typeof getDraftEnvelopeDocumentForUser>>;
@@ -343,35 +355,44 @@ export async function saveEnvelopeAsTemplate(
});
try {
- await database.query(
- `
- INSERT INTO templates (
- id,
- user_id,
- name,
- source_pdf_key,
- source_pdf_filename,
- source_pdf_size_bytes,
- page_count,
- roles,
- fields,
- created_at,
- updated_at
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $10)
- `,
- [
- templateId,
+ await withTransaction(async (tx) => {
+ // Two saves at the same moment would both pass the count above. Here
+ // the saves of one user take turns, and each counts what the one
+ // before it stored.
+ await tx.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 13))", [
userId,
- parsedInput.name,
- sourcePdfKey,
- document.fileName,
- document.body.length,
- envelope.pageCount,
- JSON.stringify(roles),
- JSON.stringify(fields),
- now,
- ],
- );
+ ]);
+ await assertRoomForTemplate(userId, tx);
+ await tx.query(
+ `
+ INSERT INTO templates (
+ id,
+ user_id,
+ name,
+ source_pdf_key,
+ source_pdf_filename,
+ source_pdf_size_bytes,
+ page_count,
+ roles,
+ fields,
+ created_at,
+ updated_at
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $10)
+ `,
+ [
+ templateId,
+ userId,
+ parsedInput.name,
+ sourcePdfKey,
+ document.fileName,
+ document.body.length,
+ envelope.pageCount,
+ JSON.stringify(roles),
+ JSON.stringify(fields),
+ now,
+ ],
+ );
+ }, database);
} catch (error) {
// Nothing points at the copy, so nothing would ever remove it.
await storageService.deleteObject(sourcePdfKey).catch(() => undefined);
@@ -502,25 +523,41 @@ export async function deleteTemplate(
storageService = createStorageService(),
}: TemplateOptions = {},
): Promise<void> {
- const deleted = await queryOne<{ sourcePdfKey: string }>(
+ const template = await queryOne<{ sourcePdfKey: string }>(
database,
`
- DELETE FROM templates
+ SELECT source_pdf_key AS "sourcePdfKey"
+ FROM templates
WHERE id = $1 AND user_id = $2
- RETURNING source_pdf_key AS "sourcePdfKey"
`,
[templateId, userId],
);
- if (!deleted) {
+ if (!template) {
throw new TemplateError("Template not found.", 404);
}
- // Envelopes made from the template have their own copies of the document.
- await storageService.deleteObject(deleted.sourcePdfKey).catch((error) => {
+ // The document goes first and the template only once it is gone. If
+ // storage fails, the template is still listed, and deleting it again
+ // tries again. The other way round, a failure would leave a document that
+ // nothing points to, which nothing would ever remove. Envelopes made from
+ // the template have their own copies of the document.
+ try {
+ await storageService.deleteObject(template.sourcePdfKey);
+ } catch (error) {
console.error(
`Failed to delete the document of template ${templateId}:`,
error,
);
- });
+
+ throw new TemplateError(
+ "The template's document could not be deleted, so the template was kept. Try again in a moment.",
+ 503,
+ );
+ }
+
+ await database.query(`DELETE FROM templates WHERE id = $1 AND user_id = $2`, [
+ templateId,
+ userId,
+ ]);
}