Skip to content

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

TypeScript

Merge the updated endpoints branch (main 0.5.2) into the webhooks branch

Claude2bbdf2a91fef
diff --cc CHANGELOG.md
index 935a6db,c152eb2..0b2a77f
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -22,19 -22,235 +22,244 @@@ release says when it does
delete; list and read envelopes and their audit trail; download the signed
PDF and the certificate; start an envelope from a template; upload PDFs
over 4 MB straight to Blob. `GET /api/v1/openapi.json` describes it all.
-
-This changes the database: the new `api_keys` and `api_idempotency` tables
-and three new columns are added by the migrations that run on deploy.
+- Webhooks: an administrator can add endpoints under Settings,
+ Organization, Webhooks, to be told when an envelope is sent, viewed,
+ signed, completed, declined, voided or expires. Deliveries are signed the
+ Standard Webhooks way, written in the same transaction as the change they
+ report, and retried for about two and a half days. Settings shows a
+ delivery log with "Send again", a test button and secret rotation;
+ `GET /api/v1/webhook-deliveries` lets an app catch up. A new daily cron
+ job, `/api/internal/webhooks`, sends retries that are due.
+
+This changes the database: the new `api_keys`, `api_idempotency`,
+`webhook_endpoints` and `webhook_deliveries` tables and three new columns
+are added by the migrations that run on deploy.
+ ## [0.5.2] - 2026-11-19
+
+ Twenty-four bug fixes. Seventeen fix reported issues (sixteen from @coygeek,
+ one from @seanGSISG), and ten came as pull requests from five outside
+ contributors. This release adds one database column: see the end of this
+ entry.
+
+ ### Signing
+
+ - Opening an old invitation after the envelope was signed, completed,
+ declined or voided says what happened to it, instead of asking the signer
+ to request a new link the sender cannot send (#110, PR #178).
+ - Reloading the signing page before Finish asks first, instead of throwing
+ away the signature and answers without warning (#99, PR #169).
+ - A long Text answer no longer widens the signing page past the window
+ (#103, PR #177).
+ - Closing the signature dialog, including with Escape, returns focus to the
+ field instead of the top of the page (#105, PR #181).
+ - "Resend code" says when the code was not sent, instead of confirming an
+ email during the wait between codes (#113, PR #172).
+ - A signer name that is a lone emoji, or uses scripts with combining marks,
+ gives whole-character avatar initials instead of a broken one that could
+ stop the page from loading (#115, PR #173).
+
+ ### Sending
+
+ - Going Back from Add signers returns to the same draft, instead of a blank
+ upload where a second upload made a second draft (#94, PR #166).
+ - A field placed just before pressing Back on Place fields is saved
+ (#102, PR #165).
+ - On a phone, the Field tools sheet stays on screen with Done visible, and
+ Escape closes it (#111, PR #180).
+ - A long unbroken title in the review and send dialogs wraps, so "Send now"
+ stays on screen (#104, PR #168).
+ - On wide screens the envelope page's action buttons wrap instead of covering
+ a long title (#131, PR #132 by @seanGSISG, carried in PR #170).
+ - A new sender on an install without email is told so at sign-up, instead of
+ being told to check their inbox (#95, PR #167).
+ - Uploading a cut-off or damaged logo is refused, instead of replacing the
+ working logo with a broken one (#91, PR #124 by @HimanshuMahto, carried in
+ PR #171).
+
+ ### Audit trail and certificates
+
+ - Password resets, role changes and account closure requests record the IP
+ address and user agent in the site audit trail (#98, PR #164).
+ - The daily job's scheduled account deletion is logged as the system's, not as
+ a user action (#109, PR #176).
+ - The certificate says a locally captured email was captured, not accepted by
+ a mail provider (#106, PR #175).
+
+ ### Administrators and settings
+
+ - The last administrator cannot close their own account (PR #153 by
+ @MattJackson).
+ - Saving settings can no longer be undone by an older cached copy
+ (PR #152 by @MattJackson).
+ - A cancelled deletion's email always arrives before the notice of a deletion
+ scheduled again (PR #160 by @RayFernando1337).
+ - A scheduled deletion whose files could not be removed is reported as a
+ failure (PR #162 by @RayFernando1337).
+ - Switching between Mine and Everyone's on the dashboard clears the old search
+ (PR #161 by @RayFernando1337).
+
+ ### Hosting
+
+ - The functions that draw PDFs ship only the files they need instead of a
+ copy of the whole project, and CI checks this after each build (#108,
+ PR #119 by @UsamaKhan, carried in PR #174).
+ - An empty `STORAGE_LOCAL_DIR` uses the default `.data/storage` folder instead
+ of the working directory (PR #151 by @MattJackson).
+ - A backup or restore whose copy fails lets go of its download
+ (PR #150 by @MattJackson).
+
+ The seven outside PRs #150-#153 and #160-#162 were merged through PR #179.
+
+ Thank you to everyone who helped with this release. @coygeek filed sixteen of
+ these reports, each with the cause and a clear way to reproduce it, which is a
+ huge gift to the project. @MattJackson sent four careful fixes for the edges of
+ backups, storage, settings and account closure. @RayFernando1337 sent three
+ fixes for scheduled deletion and the dashboard. @UsamaKhan made the PDF
+ functions much smaller, @HimanshuMahto made logo uploads safe against damaged
+ files, and @seanGSISG both reported the covered title and sent the fix.
+
+ This release changes the database (`20261119090000_spent_signing_links.sql`,
+ one new column on signers that lets an old link say what happened). On Vercel
+ the production build applies it. On other hosts, run `npm run db:migrate` as on
+ every deploy.
+
+ ## [0.5.1] - 2026-11-19
+
+ Six bug fixes, all reported by @coygeek. There are no database changes and no
+ new settings.
+
+ ### Fixes
+
+ - A completed envelope whose title has an emoji near the 120th character can
+ be downloaded again. Its signed PDF and certificate returned a server error,
+ because the file name was cut in the middle of the emoji (#89, PR #142).
+ The email sender's name and the seal certificate's names are now cut at
+ whole characters too, so an emoji in an organization name cannot break the
+ seal or the From line (PR #148).
+ - A long answer in a Text, Number or Dropdown field wraps onto as many lines
+ as it needs inside its box on the signed PDF, at the largest size that fits,
+ instead of running past the box and off the page. While typing, the signer
+ sees a "box is full" warning with how many characters fit, and Finish stays
+ off until the answer is shortened. Answers accepted before this release are
+ still drawn whole (#90, PR #146).
+ - With local disk storage, PDFs between 10 and 20 MB upload instead of failing
+ with a misleading title error. An upload over the limit gets the usual size
+ message (#92, PR #147).
+ - The certificate lists audit events in the order they were recorded, so
+ events from the same second no longer swap places, for example "completed"
+ above the last "signed". Existing certificates still verify (#97, PR #143).
+ - The last signer can finish, and a signer can decline, when the install's
+ email setup has been removed. The envelope used to stay incomplete with a
+ server error (#96, PR #145).
+ - Voiding an envelope emails the signers who already signed, telling them the
+ document will not be completed. Signers still waiting for their turn were
+ never invited and still get nothing. The void dialog says who will be told
+ (#93, PR #144).
+
+ Thanks to @coygeek for six clear, careful reports, each with the cause and a
+ way to reproduce it, which made every one of these fixes straightforward.
+
+ ## [0.5.0] - 2026-11-18
+
+ Administrators can now see every member's envelopes and delete finished ones
+ after a 14-day notice, plus six outside bug fixes and a security update. This
+ release changes the database: see the end of this entry.
+
+ ### Administrators
+
+ - An "Everyone's" view on the dashboard lists every member's sent and
+ finished envelopes, with the sender on each card. Administrators can open
+ them and download their files, and a download of another member's file is
+ recorded in the site audit trail. Drafts stay private to their sender.
+ - The dashboard is split into pages of 48, and its search box searches the
+ whole list on the server, including the sender's name and email in
+ "Everyone's".
+ - "Delete envelope" on a completed, declined or voided envelope schedules it
+ for deletion 14 days later. The sender gets an email naming who asked, and
+ any administrator can cancel within the 14 days, in which case the sender
+ is told it will not be deleted. Nothing is deleted before the sender has
+ been emailed. In Part 11 mode a reason is required. The request, a
+ cancellation and the deletion itself are all in the site audit trail, with
+ the record's hashes kept after the files are gone.
+ - A deleted envelope's files are queued and retried by the daily job until
+ they are gone, so a storage hiccup cannot leave orphaned files behind.
+ - The retention sweep does not delete an envelope with a deletion scheduled,
+ so the retention period cannot cut the 14-day notice short.
+
+ ### Fixes
+
+ - Fields placed on rotated pages (typical of landscape scans), and on pages
+ whose crop box differs from the page size, are stamped where they were
+ placed in the signed PDF instead of shifted or sideways. This includes
+ envelopes uploaded before this release (#69, PR #116).
+ - A void or decline that races another void, decline or the last signature
+ no longer deletes the winner's certificate (#68).
+ - After switching signature tabs, the Draw tab shows the drawing that will
+ be applied, instead of an empty canvas (#70).
+ - A client that sends an empty User-Agent header can sign, verify, consent
+ and decline, instead of getting an error (#71).
+ - Exporting the audit trail of an envelope whose title has a dash, curly
+ quote or non-Latin characters works, instead of failing with a server
+ error (#72).
+ - An envelope's timeline lists events in the order they were recorded, so
+ "completed" no longer shows before "signed" (#73).
+
+ ### Security
+
+ - node-forge updated to 1.4.3, which fixes four moderate advisories (#80).
+
+ Thanks to @njarrar for the six fixes, and to @jasonhaggart for the node-forge
+ update.
+
+ This release changes the database (`20261118100000_pending_file_deletions.sql`,
+ `20261118110000_scheduled_envelope_deletions.sql`). On Vercel the production
+ build applies them. On other hosts, run `npm run db:migrate` as on every
+ deploy.
+
+ ## [0.4.0] - 2026-11-17
+
+ A name field, and fixes for nine reported bugs. This release changes the
+ database: see the end of this entry.
+
+ ### Envelopes
+
+ - A name field. Place it where the signer's printed name belongs, and it is
+ filled in with the name the sender gave that signer when they sign, the
+ way a date field is filled in with the day. It is always required, and the
+ signer does not type it. Contributed by @sumnerboy12 (#49, PR #50).
+
+ ### Fixes
+
+ - The certificate's "sent" and reminder rows name the sender, not the first
+ signer next to the sender's email address (#52).
+ - Sending or reminding when email is not set up says so, instead of failing
+ with a generic server error. A manual reminder no longer retires the
+ signer's link before finding there is no email to send it with (#53).
+ - A password-locked PDF is named as locked on upload, instead of being
+ reported as a file that could not be rendered (#54).
+ - After a signer declines, the page says the decline was recorded, instead
+ of "This link has expired" (#55).
+ - Setup refuses a password over 128 characters instead of silently cutting
+ it short, which made the next sign-in fail (#56).
+ - Sign-in and sign-up say a password is too long, instead of "too short" or
+ "something went wrong" (#57).
+ - Typed signatures in the script font keep every letter when the text is
+ copied or searched, and no longer show gaps inside names where the font
+ joins letters (#58, #59).
+
+ ### Documentation
+
+ - The agent deploy guide checks Vercel's rule that the free Hobby plan is
+ for non-commercial use before choosing free plans for a company (#47).
+
+ Thanks to @coygeek for the detailed bug reports, and to @sumnerboy12 for the
+ name field.
+
+ This release changes the database (`20261118090000_name_field.sql`). On
+ Vercel the production build applies it. On other hosts, run
+ `npm run db:migrate` as on every deploy.
+
## [0.3.0] - 2026-11-16
Sign-in security and audit features for organizations that need them, and
diff --cc e2e/signing-flow.spec.ts
index d900264,cfad5de..54289af
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@@ -4,11 -4,8 +4,12 @@@ import pg from "pg"
import { e2eDatabaseUrl, e2eSetupToken } from "../playwright.config";
import { extractLink, extractLinks, waitForEmail } from "./support/outbox";
import { totpCode } from "./support/totp";
- import { writeSamplePdf } from "./support/sample-pdf";
+ import { writeLargePdf, writeSamplePdf } from "./support/sample-pdf";
+ import { startSignInWindowAfresh } from "./support/sign-in-limit";
+import {
+ hasValidSignature,
+ startWebhookReceiver,
+} from "./support/webhook-receiver";
const PASSWORD = "correct horse battery staple 42";
// The ampersand is on purpose: the name goes into HTML emails and page titles.
@@@ -1220,7 -1217,475 +1221,475 @@@ test("a signer signs with a qualified s
});
});
+ test("a signer who declines is told the decline was recorded, not that the link expired", async ({
+ browser,
+ page,
+ }, testInfo) => {
+ const runId = String(Date.now());
+ const signerEmail = `decliner+${runId}@example.com`;
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ const admin = await database.query<{ email: string }>(
+ `select email from public."user" where role = 'admin' limit 1`,
+ );
+
+ adminEmail = admin.rows[0]?.email ?? "";
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ let envelopeId = "";
+
+ await test.step("the sender sends a document to one signer", async () => {
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("terms.pdf"));
+
+ await page.goto("/login");
+ await page.getByLabel("Email").fill(adminEmail);
+ await page.getByLabel("Password").fill(PASSWORD);
+ await page.getByRole("button", { name: "Log in" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill("Terms to decline");
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+ envelopeId = /\/envelopes\/([^/]+)\/signers$/.exec(page.url())?.[1] ?? "";
+
+ await page.getByLabel("Signer 1 name").fill("Dana Decliner");
+ await page.getByLabel("Signer 1 email").fill(signerEmail);
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/prepare$/);
+
+ await page.getByRole("button", { exact: true, name: "Signature" }).click();
+
+ const placementTarget = page.getByLabel("Place Signature on page 1");
+ const box = await placementTarget.boundingBox();
+
+ await placementTarget.click({
+ position: { x: box!.width * 0.3, y: box!.height * 0.6 },
+ });
+ await expect(page.getByRole("status")).toHaveText("Saved");
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/review$/);
+ await page.getByRole("button", { name: "Send envelope" }).click();
+
+ const confirmation = page.getByRole("dialog", {
+ name: "Send this envelope?",
+ });
+
+ await confirmation.getByRole("checkbox").check();
+ await confirmation.getByRole("button", { name: "Send now" }).click();
+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));
+ });
+
+ await test.step("the signer declines and sees that it was recorded", async () => {
+ const invitation = await waitForEmail({
+ template: "signing_invitation",
+ to: signerEmail,
+ });
+ const signerContext = await browser.newContext({
+ viewport: { height: 900, width: 1440 },
+ });
+ const signerPage = await signerContext.newPage();
+
+ await signerPage.goto(extractLink(invitation.text, "/sign/"));
+
+ const consent = signerPage.getByRole("dialog", { name: "Before you sign" });
+
+ await consent
+ .getByRole("checkbox", {
+ name: "I agree to use electronic records and signatures",
+ })
+ .check();
+ await consent.getByRole("button", { name: "Agree and continue" }).click();
+ await signerPage
+ .getByRole("button", { exact: true, name: "Decline" })
+ .click();
+
+ const decline = signerPage.getByRole("dialog", {
+ name: "Decline to sign?",
+ });
+
+ await decline
+ .getByLabel("Reason (optional)")
+ .fill("Terms in section 2 are not what we agreed.");
+ await decline.getByRole("button", { name: "Decline to sign" }).click();
+
+ const declined = signerPage.getByRole("heading", {
+ name: "You declined to sign",
+ });
+
+ await expect(declined).toBeVisible();
+ // Focus moves to the outcome, so a screen reader reads it out.
+ await expect(declined).toBeFocused();
+ await expect(signerPage.getByText("This link has expired")).toHaveCount(0);
+ await expect(
+ signerPage.getByText(/Request a new signing link/),
+ ).toHaveCount(0);
+ await signerContext.close();
+ });
+
+ await test.step("the sender sees the decline and its reason", async () => {
+ await waitForEmail({ template: "decline_notification", to: adminEmail });
+ await page.goto(`/envelopes/${envelopeId}`);
+ await expect(
+ page.getByText(
+ "Decline reason: Terms in section 2 are not what we agreed.",
+ ),
+ ).toBeVisible();
+ });
+
+ await test.step("an administrator sees another member's envelope and schedules its deletion", async () => {
+ // The envelope becomes a plain member's, as if they had sent it.
+ const memberId = `member-${runId}`;
+ const memberEmail = `member+${runId}@example.com`;
+ const db = new pg.Client({ connectionString: e2eDatabaseUrl });
+
+ await db.connect();
+
+ try {
+ await db.query(
+ `insert into public."user" (id, name, email, role, "emailVerified") values ($1, 'Mira Member', $2, 'user', true)`,
+ [memberId, memberEmail],
+ );
+ await db.query(`update envelopes set user_id = $1 where id = $2`, [
+ memberId,
+ envelopeId,
+ ]);
+ } finally {
+ await db.end();
+ }
+
+ const senderLabel = `Mira Member (${memberEmail})`;
+
+ // Gone from the administrator's own list, there in everyone's.
+ await page.goto("/dashboard");
+ await expect(
+ page.getByRole("heading", { name: "Terms to decline" }),
+ ).toHaveCount(0);
+ await page.getByRole("link", { name: "Everyone's" }).click();
+ await expect(page).toHaveURL(/\/dashboard\?view=all$/);
+ await expect(
+ page.getByRole("heading", { level: 1, name: "All envelopes" }),
+ ).toBeVisible();
+
+ const card = page.getByRole("link").filter({ hasText: "Terms to decline" });
+
+ await expect(card).toContainText(senderLabel);
+
+ // Enter searches every envelope, the sender's address included.
+ const search = page.getByRole("searchbox", {
+ name: "Search by title or email...",
+ });
+
+ await search.fill(memberEmail);
+ await search.press("Enter");
+ await expect(page).toHaveURL(/\/dashboard\?view=all&q=/);
+ await expect(card).toBeVisible();
+
+ // Switching views drops the search, in the box too.
+ await page.getByRole("link", { name: "Mine" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+ await expect(search).toHaveValue("");
+ await page.getByRole("link", { name: "Everyone's" }).click();
+ await expect(page).toHaveURL(/\/dashboard\?view=all$/);
+ await expect(search).toHaveValue("");
+ await card.click();
+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));
+ await expect(page.getByText(`Sent by ${senderLabel}`)).toBeVisible();
+ // What changes the envelope stays with its sender.
+ await expect(
+ page.getByRole("button", { name: "Copy to new draft" }),
+ ).toHaveCount(0);
+
+ // A copy of someone else's certificate is on record.
+ const download = page.waitForEvent("download");
+
+ await page.getByRole("button", { name: "Download certificate" }).click();
+ expect((await download).suggestedFilename()).toMatch(/\.pdf$/);
+
+ // Nothing goes at once: the deletion is scheduled, and the sender is
+ // emailed a link to download it.
+ async function scheduleDeletion(reason: string) {
+ await page.getByRole("button", { name: "Delete envelope" }).click();
+
+ const confirm = page.getByRole("dialog", {
+ name: "Schedule this envelope for deletion?",
+ });
+
+ await confirm.getByLabel("Reason (optional)").fill(reason);
+ await confirm.getByRole("button", { name: "Schedule deletion" }).click();
+ await expect(page.getByText(/Scheduled to be deleted on/)).toBeVisible();
+ await expect(page.getByText(`Reason: ${reason}`)).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "Delete envelope" }),
+ ).toHaveCount(0);
+ }
+
+ await scheduleDeletion("Changed my mind.");
+
+ const notice = await waitForEmail({
+ template: "deletion_notice",
+ to: memberEmail,
+ });
+
+ expect(notice.subject).toMatch(/^"Terms to decline" will be deleted on /);
+ expect(notice.text).toContain(`/envelopes/${envelopeId}`);
+
+ // Any administrator can cancel until then; the sender is told.
+ await page.getByRole("button", { name: "Cancel deletion" }).click();
+ await page
+ .getByRole("dialog", { name: "Cancel this deletion?" })
+ .getByRole("button", { name: "Cancel deletion" })
+ .click();
+ await expect(page.getByText(/Scheduled to be deleted on/)).toHaveCount(0);
+ await expect
+ .poll(async () => {
+ const latest = await waitForEmail({
+ template: "deletion_notice",
+ to: memberEmail,
+ });
+
+ return latest.subject;
+ })
+ .toBe('"Terms to decline" will not be deleted');
+
+ await scheduleDeletion("Never agreed.");
+
+ // The envelope itself stays until the wait is over.
+ await page.reload();
+ await expect(
+ page.getByRole("heading", { name: "Terms to decline" }),
+ ).toBeVisible();
+
+ // The download, the request and its cancellation stay on record in the
+ // install's audit trail, with whose envelope it was.
+ const audit = await page.request.get("/api/admin/audit");
+ const { events } = (await audit.json()) as {
+ events: { event: string; metadata: Record<string, unknown> | null }[];
+ };
+
+ expect(
+ events.find((event) => event.event === "envelope_file_downloaded")
+ ?.metadata,
+ ).toMatchObject({
+ envelopeId,
+ file: "evidence",
+ ownerEmail: memberEmail,
+ });
+ expect(
+ events.find((event) => event.event === "envelope_deletion_scheduled")
+ ?.metadata,
+ ).toMatchObject({
+ envelopeId,
+ ownerEmail: memberEmail,
+ reason: "Never agreed.",
+ status: "declined",
+ });
+ expect(
+ events.find((event) => event.event === "envelope_deletion_cancelled")
+ ?.metadata,
+ ).toMatchObject({ envelopeId, ownerEmail: memberEmail });
+ });
+ });
+
+ test("a long Text answer keeps the signing page within the window", async ({
+ browser,
+ page,
+ }, testInfo) => {
+ const runId = String(Date.now());
+ const signerEmail = `long-answer+${runId}@example.com`;
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ const admin = await database.query<{ email: string }>(
+ `select email from public."user" where role = 'admin' limit 1`,
+ );
+
+ adminEmail = admin.rows[0]?.email ?? "";
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ await test.step("the sender sends a signature and a Text field", async () => {
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("form.pdf"));
+
+ await page.goto("/login");
+ await page.getByLabel("Email").fill(adminEmail);
+ await page.getByLabel("Password").fill(PASSWORD);
+ await page.getByRole("button", { name: "Log in" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill("Form with a long answer");
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+
+ await page.getByLabel("Signer 1 name").fill("Lee Longanswer");
+ await page.getByLabel("Signer 1 email").fill(signerEmail);
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/prepare$/);
+
+ const placeField = async (tool: string, x: number, y: number) => {
+ await page.getByRole("button", { exact: true, name: tool }).click();
+
+ const target = page.getByLabel(`Place ${tool} on page 1`);
+ const box = await target.boundingBox();
+
+ expect(box).not.toBeNull();
+ await target.click({
+ position: { x: box!.width * x, y: box!.height * y },
+ });
+ };
+
+ await placeField("Signature", 0.3, 0.7);
+ await expect(page.getByRole("status")).toHaveText("Saved");
+ await placeField("Text", 0.3, 0.4);
+ await expect(page.getByRole("status")).toHaveText("Saved");
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/review$/);
+ await page.getByRole("button", { name: "Send envelope" }).click();
+
+ const confirmation = page.getByRole("dialog", {
+ name: "Send this envelope?",
+ });
+
+ await confirmation.getByRole("checkbox").check();
+ await confirmation.getByRole("button", { name: "Send now" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+$/);
+ });
+
+ await test.step("typing a long unbroken answer does not widen the page", async () => {
+ const invitation = await waitForEmail({
+ template: "signing_invitation",
+ to: signerEmail,
+ });
+ // Narrower than the two-column layout, as in the report.
+ const signerContext = await browser.newContext({
+ viewport: { height: 900, width: 1200 },
+ });
+ const signerPage = await signerContext.newPage();
+
+ await signerPage.goto(extractLink(invitation.text, "/sign/"));
+
+ const consent = signerPage.getByRole("dialog", { name: "Before you sign" });
+
+ await consent
+ .getByRole("checkbox", {
+ name: "I agree to use electronic records and signatures",
+ })
+ .check();
+ await consent.getByRole("button", { name: "Agree and continue" }).click();
+ await expect(consent).toBeHidden();
+
+ const pdfPage = signerPage.getByRole("img", {
+ name: "Rendered PDF page 1",
+ });
+
+ await expect(pdfPage).toBeVisible();
+
+ const answer = signerPage.getByLabel("Enter text", { exact: true });
+ const measure = () =>
+ signerPage.evaluate(() => document.documentElement.scrollWidth);
+
+ await answer.fill("Short");
+ await expect(signerPage.getByText("Short", { exact: true })).toBeVisible();
+
+ const shortWidth = (await pdfPage.boundingBox())?.width ?? 0;
+
+ expect(await measure()).toBeLessThanOrEqual(1200);
+
+ const longAnswer = "W".repeat(230);
+
+ await answer.fill(longAnswer);
+ await expect(
+ signerPage.getByText(longAnswer, { exact: true }),
+ ).toBeAttached();
+ expect(await measure()).toBeLessThanOrEqual(1200);
+ expect((await pdfPage.boundingBox())?.width).toBeCloseTo(shortWidth, 0);
+ // The whole answer is still there to edit.
+ await expect(answer).toHaveValue(longAnswer);
+
+ await answer.fill("Short again");
+ expect(await measure()).toBeLessThanOrEqual(1200);
+
+ await signerContext.close();
+ });
+ });
+
+ test("with local disk storage a PDF just under 20 MB uploads, and a larger request is refused", async ({
+ page,
+ }, testInfo) => {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ const admin = await database.query<{ email: string }>(
+ `select email from public."user" where role = 'admin' limit 1`,
+ );
+
+ adminEmail = admin.rows[0]?.email ?? "";
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ await page.goto("/login");
+ await page.getByLabel("Email").fill(adminEmail);
+ await page.getByLabel("Password").fill(PASSWORD);
+ await page.getByRole("button", { name: "Log in" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+
+ await test.step("a 19 MB PDF, over Next.js's 10 MB default, makes a draft", async () => {
+ const pdfPath = await writeLargePdf(
+ testInfo.outputPath("large.pdf"),
+ 19 * 1024 * 1024,
+ );
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill("Large agreement");
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+ });
+
+ await test.step("a request over the limit gets the size message", async () => {
+ const response = await page.request.post("/api/envelopes", {
+ headers: { origin: new URL(page.url()).origin },
+ multipart: {
+ file: {
+ buffer: Buffer.alloc(22 * 1024 * 1024),
+ mimeType: "application/pdf",
+ name: "too-large.pdf",
+ },
+ title: "Too large",
+ },
+ });
+
+ expect(response.status()).toBe(413);
+ expect(await response.json()).toEqual({
+ error: "This file exceeds the 20 MB limit.",
+ });
+ });
+ });
+
-test("an administrator makes an API key, an app sends and downloads an envelope with it, and revoking it stops it", async ({
+test("an administrator makes an API key and a webhook, an app sends and downloads an envelope and hears each step, and revoking the key stops it", async ({
baseURL,
browser,
page,
diff --cc src/components/settings/security-panel.tsx
index b8f0e80,69efdcc..98ccd32
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@@ -110,20 -111,42 +114,56 @@@ function describeEvent(event: SystemAud
]
.filter(Boolean)
.join(", ");
+ case "webhook_endpoint_created":
+ case "webhook_endpoint_changed":
+ case "webhook_endpoint_deleted":
+ return [
+ typeof metadata.url === "string" ? metadata.url : null,
+ metadata.secretRotated === true ? "new signing secret" : null,
+ metadata.enabled === false
+ ? "turned off"
+ : metadata.enabled === true
+ ? "turned on"
+ : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
+ case "envelope_deleted":
+ return [
+ typeof metadata.title === "string" ? `"${metadata.title}"` : null,
+ typeof metadata.status === "string" ? metadata.status : null,
+ typeof metadata.reason === "string" ? metadata.reason : null,
+ typeof metadata.ownerEmail === "string"
+ ? `sent by ${metadata.ownerEmail}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
+ case "envelope_deletion_scheduled":
+ case "envelope_deletion_cancelled":
+ return [
+ typeof metadata.title === "string" ? `"${metadata.title}"` : null,
+ typeof metadata.deleteAfter === "number"
+ ? `${event.event === "envelope_deletion_scheduled" ? "to be deleted" : "was due"} on ${new Date(metadata.deleteAfter * 1000).toISOString().slice(0, 10)}`
+ : null,
+ typeof metadata.reason === "string" ? metadata.reason : null,
+ typeof metadata.ownerEmail === "string"
+ ? `sent by ${metadata.ownerEmail}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
+ case "envelope_file_downloaded":
+ return [
+ typeof metadata.file === "string"
+ ? (downloadedFileLabels[metadata.file] ?? metadata.file)
+ : null,
+ typeof metadata.ownerEmail === "string"
+ ? `sent by ${metadata.ownerEmail}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
default:
return target ?? "";
}
diff --cc src/lib/retention-job.ts
index ed414e5,63a1d80..d8b1e6d
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@@ -2,7 -2,10 +2,11 @@@ import { createHash, timingSafeEqual }
import { deleteExpiredIdempotencyKeys } from "./api/idempotency.ts";
import { getDb, type DbPool } from "./db/connection.ts";
+import { deleteOldWebhookDeliveries } from "./webhooks/log.ts";
+ import {
+ runScheduledEnvelopeDeletions,
+ type ScheduledDeletionSummary,
+ } from "./envelope-deletion.ts";
import {
envelopeScheduleFailed,
runEnvelopeSchedule,
@@@ -180,12 -186,20 +187,26 @@@ export async function runRetentionJob(
}
});
+ await deleteOldWebhookDeliveries(database).catch((error: unknown) => {
+ if (!isMissingSchemaError(error)) {
+ console.error("Clearing old webhook deliveries failed:", error);
+ }
+ });
+
+ const deletions = await runScheduledEnvelopeDeletions({
+ database,
+ emailService,
+ storageService,
+ }).catch((error: unknown) => {
+ // A database from before scheduled deletions has none to run.
+ if (!isMissingSchemaError(error)) {
+ console.error("The scheduled envelope deletions failed:", error);
+ return null;
+ }
+
+ return { deleted: 0, failures: [], noticeFailures: [], noticesSent: 0 };
+ });
+
const schedule = await runEnvelopeSchedule({
database,
emailService,
diff --cc src/lib/services/system-audit.ts
index 542ee96,40886ea..00a8190
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@@ -44,9 -44,10 +44,13 @@@ export const systemAuditEventTypes =
"email_domain_changed",
"api_key_created",
"api_key_revoked",
+ "webhook_endpoint_created",
+ "webhook_endpoint_changed",
+ "webhook_endpoint_deleted",
+ "envelope_deleted",
+ "envelope_file_downloaded",
+ "envelope_deletion_scheduled",
+ "envelope_deletion_cancelled",
] as const;
export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];