Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Merge the updated API keys branch (main 0.5.2) into the endpoints branch
Claude864c2535da3d
diff --cc CHANGELOG.mdindex bfdca00,65e2eb7..c152eb2--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -16,16 -16,235 +16,241 @@@ release says when it doesbe read-only, can expire, and stop working when revoked or when theiradministrator stops being one. `GET /api/v1/me` checks a key works. See[docs/api.md](docs/api.md).--This changes the database: the new `api_keys` table is added by the-migration that runs on deploy.+- API endpoints under `/api/v1`: create an envelope from a PDF with its+ signers, copy recipients and fields, and send it, in one call (all or+ nothing, safe to retry with an `Idempotency-Key`); send, void, remind and+ 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.+ ## [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-16Sign-in security and audit features for organizations that need them, anddiff --cc docs/api.mdindex 4e76fb7,0af11a5..6906261--- a/docs/api.md+++ b/docs/api.md@@@ -88,152 -89,9 +90,153 @@@ stands- `RateLimit-Remaining`: requests left in it.- `RateLimit-Reset`: seconds until the window starts again.-The limits the web app has on creating and sending envelopes apply to keys-too. An address that sends 30 bad keys in 10 minutes gets 429 for any more-bad keys until the 10 minutes are up. Good keys from it keep working.+On top of that, each key may create 60 envelopes in 10 minutes and send 100+in an hour, counting creates and template calls that also send. Your email+provider's own limits usually bite first: Resend's free plan sends 100- emails a day. An address that sends 30 bad keys in 10 minutes is turned- away until the 10 minutes are up.++emails a day. An address that sends 30 bad keys in 10 minutes gets 429 for++any more bad keys until the 10 minutes are up. Good keys from it keep++working.++## A first envelope in one call++Upload the PDF, name the signers, place the fields, and send, all at once.+`data` is the envelope as JSON:++```sh+curl https://sign.example.com/api/v1/envelopes \+ -H "Authorization: Bearer sdk_…" \+ -H "Idempotency-Key: order-1042" \+ -F [email protected] \+ -F 'data={+ "title": "Service agreement",+ "signers": [+ { "ref": "client", "name": "Casey Client", "email": "[email protected]" }+ ],+ "fields": [+ { "signer": "client", "type": "signature", "page": 1,+ "x": 0.1, "y": 0.8, "width": 0.3, "height": 0.05 },+ { "signer": "client", "type": "date", "page": 1,+ "x": 0.5, "y": 0.8, "width": 0.2, "height": 0.03 }+ ],+ "metadata": { "invoice": "INV-1042" },+ "send": { "expiresInDays": 14, "permittedUseConfirmed": true }+ }'+```++The answer is the envelope (see [The envelope](#the-envelope)), with status+`sent`, and the first signer has their invitation email. Leave out `send` to+make a draft and send it later with `POST /api/v1/envelopes/{id}/send`.++Things to know:++- **Signers** sign in the order given. Each has a `ref`, your own name for+ them (letters, digits, `.`, `_`, `:` and `-`), which fields use to say whose+ they are and which comes back with the signer. Up to 10 signers, and up to+ 10 `copyRecipients` (`name`, `email`) who get the finished document.+ `accessCode` and `requireEmailCode: true` add the same extra checks the web+ app offers.+- **Fields** are placed on a page by fractions of its width and height from+ its top left corner: `"x": 0.1, "y": 0.8` is 10% in from the left and 80%+ down. Types: `signature`, `initials`, `date`, `text`, `checkbox`, `number`,+ `dropdown` (with `options`), `radio` (buttons with one `groupId` are one+ question). `required` is true unless set to false. Every signer needs at+ least one `signature` field.+- **Sending** needs `"permittedUseConfirmed": true`: your app confirms, as the+ web app's send button asks a person to, that the envelope is an ordinary+ business agreement and not one of the kinds of document that the law does+ not let be signed electronically (see `/electronic-signatures` on your+ install). `expiresInDays` (1 to 365) and `reminderIntervalDays` (1 to 30)+ are as in the web app, and `signatureLevel` is `advanced` or `qualified` on+ installs with a signing provider.+- **All or nothing.** If anything about the request is wrong, a field off+ its page or a signer without a signature field, nothing is kept: no+ half-made draft is left behind.+- **`metadata`** is up to 2 KB of JSON of your own, returned with the+ envelope, for matching it to your records.+- **`Idempotency-Key`** makes a retry safe. A request with a key SignuDoc has+ seen in the last 24 hours gets the first answer again (with the header+ `Idempotent-Replayed: true`) instead of making a second envelope. The same+ key with a different request is refused with 422. If the install fails+ after the envelope was made, a retry with the same key gets that envelope+ rather than a second one. Use one key per thing you mean to send, such as+ the invoice number.++### PDFs over 4 MB++On Vercel a request to the app can carry at most 4.5 MB, so a bigger PDF (up+to 20 MB) goes straight to storage first:++```sh+curl -X POST https://sign.example.com/api/v1/uploads -H "Authorization: Bearer sdk_…"+# {"uploadId": "…", "url": "https://…", "method": "PUT",+# "headers": {"content-type": "application/pdf"}, "expiresAt": "…"}++curl -X PUT "<url>" -H "content-type: application/pdf" --data-binary @big.pdf+```++Then create the envelope with JSON instead of a form, naming the upload:++```sh+curl https://sign.example.com/api/v1/envelopes \+ -H "Authorization: Bearer sdk_…" -H "content-type: application/json" \+ -d '{ "uploadId": "…", "filename": "big.pdf", "title": "…", "signers": […], "fields": […] }'+```++The upload URL works for 10 minutes, and an upload that is never used is+deleted after a day. Installs that keep files on their own disk (not on+Vercel) do not need this and answer 404: send any size in the form.++## The envelope++Every endpoint that returns an envelope returns the same object:++```json+{+ "object": "envelope",+ "id": "8c1d…",+ "title": "Service agreement",+ "status": "sent",+ "expired": false,+ "createdAt": "2026-11-17T09:00:00.000Z",+ "sentAt": "2026-11-17T09:00:01.000Z",+ "completedAt": null,+ "declinedAt": null,+ "voidedAt": null,+ "expiresAt": "2026-12-01T09:00:01.000Z",+ "pageCount": 2,+ "signatureLevel": "simple",+ "metadata": { "invoice": "INV-1042" },+ "signers": [+ {+ "id": "51ab…",+ "ref": "client",+ "name": "Casey Client",+ "email": "[email protected]",+ "order": 1,+ "status": "notified",+ "viewedAt": null,+ "signedAt": null,+ "declinedAt": null,+ "declineReason": null+ }+ ],+ "copyRecipients": [],+ "files": { "signed": null, "certificate": null }+}+```++- `status` is `draft`, `sent`, `completed`, `declined` or `voided`. A sent+ envelope past its deadline has `expired: true` until it is voided or the+ deadline moves.+- A signer's `status` is `pending` (not their turn yet), `notified` (their+ turn, invited), `signed` or `declined`. `viewedAt` is when they first+ opened it.+- `files` gives the paths to download once there is something to download:+ the signed PDF once the envelope is completed, and the certificate of+ completion once it is completed, declined or voided.++To know when something happens without asking again and again, use+webhooks (coming in the next release).## Endpointsdiff --cc e2e/signing-flow.spec.tsindex a73fc38,6c92e83..4d7191f--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@@ -1216,9 -1216,476 +1216,477 @@@ 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, the API accepts it, and revoking it stops it", async ({+test("an administrator makes an API key, an app sends and downloads an envelope with it, and revoking it stops it", async ({baseURL,+ browser,page,playwright,}) => {diff --cc src/lib/retention-job.tsindex a3c4805,54c219a..63a1d80--- a/src/lib/retention-job.ts+++ b/src/lib/retention-job.ts@@@ -1,7 -1,10 +1,11 @@@import { createHash, timingSafeEqual } from "node:crypto";+import { deleteExpiredIdempotencyKeys } from "./api/idempotency.ts";import { getDb, type DbPool } from "./db/connection.ts";+ import {+ runScheduledEnvelopeDeletions,+ type ScheduledDeletionSummary,+ } from "./envelope-deletion.ts";import {envelopeScheduleFailed,runEnvelopeSchedule,@@@ -172,13 -178,20 +179,27 @@@ export async function runRetentionJob(}});+ await deleteExpiredIdempotencyKeys(database).catch((error: unknown) => {+ // A database from before the API has no table to clear.+ if (!isMissingSchemaError(error)) {+ console.error("Clearing old API idempotency keys 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,