Skip to content

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

TypeScript

Merge main (0.5.2) into the API keys branch

Claude0857c785165e
diff --cc CHANGELOG.md
index f6d4cec,043f3b7..65e2eb7
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -8,18 -8,188 +8,200 @@@ release says when it does
## [Unreleased]
+### API
+
+- API keys: an administrator can make keys under Settings, Organization, API
+ keys, for another app to use the SignuDoc API. A key is shown once, only
+ its hash is stored, and it acts as the administrator who made it. Keys can
+ be read-only, can expire, and stop working when revoked or when their
+ administrator 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.
+
+ ## [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
diff --cc e2e/signing-flow.spec.ts
index da9c090,3ac1d0d..6c92e83
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@@ -1340,93 -1340,350 +1340,435 @@@ test("a signer who declines is told th
),
).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 ({
+ baseURL,
+ page,
+ playwright,
+}) => {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ adminEmail =
+ (
+ await database.query<{ email: string }>(
+ `select email from public."user" where role = 'admin' order by "createdAt" limit 1`,
+ )
+ ).rows[0]?.email ?? "";
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ // A separate client, with no session cookie: only the key gets it in.
+ const api = await playwright.request.newContext({ baseURL });
+ let key = "";
+
+ await test.step("the key is made in Settings and shown once", async () => {
+ 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("/settings");
+ await page.getByPlaceholder("For example: Billing app").fill("Billing app");
+ await page.getByRole("button", { name: "Create key" }).click();
+
+ key =
+ (await page.getByTestId("new-api-key").locator("code").textContent()) ??
+ "";
+ expect(key).toMatch(/^sdk_[A-Za-z0-9_-]{43}$/);
+ await page.getByRole("button", { name: "Done" }).click();
+ await expect(page.getByTestId("new-api-key")).toHaveCount(0);
+ await expect(
+ page.getByRole("list", { name: "API keys" }).getByText(key.slice(0, 12)),
+ ).toBeVisible();
+ });
+
+ await test.step("the API answers to the key and to nothing else", async () => {
+ const me = await api.get("/api/v1/me", {
+ headers: { authorization: `Bearer ${key}` },
+ });
+
+ expect(me.status()).toBe(200);
+ expect(me.headers()["ratelimit-limit"]).toBe("600");
+ expect(await me.json()).toMatchObject({
+ key: { name: "Billing app", scope: "write" },
+ user: { email: adminEmail },
+ });
+
+ const anonymous = await api.get("/api/v1/me");
+
+ expect(anonymous.status()).toBe(401);
+ expect(await anonymous.json()).toMatchObject({
+ error: { code: "unauthorized" },
+ });
+ });
+
+ await test.step("a revoked key is refused at once", async () => {
+ await page.getByRole("button", { name: "Revoke Billing app" }).click();
+ await page.getByRole("button", { name: "Revoke", exact: true }).click();
+ await expect(
+ page.getByRole("list", { name: "API keys" }).getByText("Revoked"),
+ ).toBeVisible();
+
+ const refused = await api.get("/api/v1/me", {
+ headers: { authorization: `Bearer ${key}` },
+ });
+
+ expect(refused.status()).toBe(401);
+ });
+
+ await api.dispose();
+});
+
test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({
browser,
page,
diff --cc src/components/settings/security-panel.tsx
index 3e73080,746cad2..69efdcc
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@@ -23,9 -23,11 +23,13 @@@ type AuditResponse =
const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
account_closure_requested: "Account closure requested",
account_deleted: "Account deleted",
+ api_key_created: "API key created",
+ api_key_revoked: "API key revoked",
email_domain_changed: "Email domain changed",
+ envelope_deleted: "Finished envelope deleted",
+ envelope_deletion_cancelled: "Envelope deletion cancelled",
+ envelope_deletion_scheduled: "Envelope deletion scheduled",
+ envelope_file_downloaded: "Another member's file downloaded",
identity_verification_revoked: "Identity confirmation taken back",
identity_verified: "Identity confirmed",
logo_changed: "Logo changed",
@@@ -96,17 -98,42 +100,53 @@@ function describeEvent(event: SystemAud
return metadata.action === "removed" ? "Removed" : "Replaced";
case "email_domain_changed":
return typeof metadata.domain === "string" ? metadata.domain : "";
+ case "api_key_created":
+ case "api_key_revoked":
+ return [
+ typeof metadata.name === "string" ? metadata.name : null,
+ typeof metadata.prefix === "string" ? `${metadata.prefix}…` : null,
+ metadata.reason === "role_removed"
+ ? "owner is no longer an administrator"
+ : 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/account-purge.dbtest.ts
index e9af412,93fa11b..bee7f4c
--- a/src/lib/account-purge.dbtest.ts
+++ b/src/lib/account-purge.dbtest.ts
@@@ -285,53 -283,44 +285,95 @@@ test("with no administrator to take it
}
});
+test("deleting a closed account takes its API key rows before the audit lock, as revoking a key does", async () => {
+ // revokeApiKey locks a key row and then the audit chain. Hold a key row of
+ // the account the way it does: the deletion has to wait for it without
+ // already holding the audit chain, or the two would deadlock.
+ await createUser("admin");
+
+ const leaver = await createUser("admin");
+ const { summary: key } = await createApiKey(
+ { email: `${leaver}@example.test`, userId: leaver },
+ { expiresInDays: null, name: "Leaver's app", scope: "write" },
+ database,
+ );
+
+ await closeAccount(leaver);
+
+ const holder = await database.connect();
+ let sweep: ReturnType<typeof runRetentionSweep> | undefined;
+
+ try {
+ await holder.query("begin");
+ await holder.query(`select id from api_keys where id = $1 for update`, [
+ key.id,
+ ]);
+
+ sweep = runRetentionSweep({ database, storageService });
+ await waitForLockWaiter();
+
+ const free = await holder.query<{ locked: boolean }>(
+ `select pg_try_advisory_xact_lock($1) as locked`,
+ [SYSTEM_AUDIT_LOCK_ID],
+ );
+
+ assert.equal(free.rows[0]?.locked, true);
+ } finally {
+ await holder.query("rollback").catch(() => undefined);
+ holder.release();
+ }
+
+ assert.ok(sweep);
+
+ const summary = await sweep;
+
+ assert.ok(!summary.accountPurgeFailures.includes(leaver));
+ assert.equal(await accountExists(leaver), false);
+ assert.equal(
+ (await database.query(`select 1 from api_keys where id = $1`, [key.id]))
+ .rowCount,
+ 0,
+ );
+});
++
+ test("the daily job's account deletion is logged as the system's, not a person's", async () => {
+ const leaver = await createUser();
+
+ await closeAccount(leaver);
+
+ // The JSON audit lines go to console.info once the change commits.
+ const lines: Record<string, unknown>[] = [];
+ const originalInfo = console.info;
+
+ console.info = (...args: unknown[]) => {
+ if (typeof args[0] === "string") {
+ try {
+ lines.push(JSON.parse(args[0]) as Record<string, unknown>);
+ } catch {
+ // Not a JSON line.
+ }
+ }
+ };
+
+ try {
+ const summary = await runRetentionSweep({ database, storageService });
+
+ assert.ok(!summary.accountPurgeFailures.includes(leaver));
+ } finally {
+ console.info = originalInfo;
+ }
+
+ assert.equal(await accountExists(leaver), false);
+
+ const deletion = lines.find(
+ (line) =>
+ line.trail === "site" &&
+ line.event === "account_deleted" &&
+ line.targetUserId === leaver,
+ );
+
+ assert.ok(deletion, "no audit line for the account deletion");
+ assert.equal(deletion.actorType, "system");
+ assert.equal(deletion.actorUserId, null);
+ assert.equal(deletion.actorEmail, null);
+ });
diff --cc src/lib/people.ts
index 774b731,7f9738d..8aec6d0
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@@ -6,7 -6,7 +6,8 @@@ import
queryOne,
withTransaction,
} from "./db/connection.ts";
+import { revokeApiKeysForUser } from "./api-keys.ts";
+ import type { RequestClient } from "./security/request.ts";
import { recordSystemAuditEvent } from "./services/system-audit.ts";
// The accounts on this install and who among them is an administrator.
diff --cc src/lib/services/system-audit.ts
index b494cbc,3f9b1d3..40886ea
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@@ -42,8 -42,10 +42,12 @@@ export const systemAuditEventTypes =
"two_factor_requirement_changed",
"logo_changed",
"email_domain_changed",
+ "api_key_created",
+ "api_key_revoked",
+ "envelope_deleted",
+ "envelope_file_downloaded",
+ "envelope_deletion_scheduled",
+ "envelope_deletion_cancelled",
] as const;
export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];