Skip to content

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

TypeScript

Add Part 11 mode for FDA 21 CFR Part 11 records

Claude37302e11f724
diff --git a/db/migrations/20261115090000_part11_mode.sql b/db/migrations/20261115090000_part11_mode.sql
new file mode 100644
index 0000000..b93df74
--- /dev/null
+++ b/db/migrations/20261115090000_part11_mode.sql
@@ -0,0 +1,88 @@
+-- Part 11 mode: the controls FDA 21 CFR Part 11 asks of a system that keeps
+-- signed electronic records. Off unless an administrator turns it on.
+--
+-- * app_settings.part11_mode: the switch.
+-- * user: whether an administrator has checked who the person is (11.100(b)),
+-- and the lock that wrong passwords at signing put on the account (11.300).
+-- * envelopes.part11: the envelope was sent while the mode was on, so its
+-- signers sign with their accounts. Kept with the envelope, so turning the
+-- mode off later does not change the rules an envelope went out under.
+-- * signers: the account that must sign, and what the signature means
+-- (11.50: approval, review, responsibility or authorship).
+-- * audit_events: a new event kind for a wrong password at signing.
+-- * system_audit_events: one hash chain for the changes that are not about a
+-- single envelope (settings, roles, identity checks, locks), 11.10(e).
+
+alter table public.app_settings
+ add column if not exists part11_mode boolean not null default false;
+
+alter table public."user"
+ add column if not exists identity_verified_at bigint,
+ add column if not exists identity_verified_by text,
+ add column if not exists identity_verification_note text,
+ add column if not exists signing_failed_attempts integer not null default 0,
+ add column if not exists signing_locked_at bigint;
+
+alter table public.envelopes
+ add column if not exists part11 boolean not null default false;
+
+alter table public.signers
+ add column if not exists user_id text,
+ add column if not exists signature_meaning text;
+
+do $$
+begin
+ if not exists (
+ select 1 from pg_constraint where conname = 'signers_signature_meaning_check'
+ ) then
+ alter table public.signers
+ add constraint signers_signature_meaning_check
+ check (
+ signature_meaning is null
+ or signature_meaning in ('approval', 'review', 'responsibility', 'authorship')
+ );
+ end if;
+end
+$$;
+
+alter table public.audit_events
+ drop constraint if exists audit_events_event_check;
+
+alter table public.audit_events
+ add constraint audit_events_event_check
+ check (event in (
+ 'created',
+ 'sent',
+ 'viewed',
+ 'consented',
+ 'verified',
+ 'verification_failed',
+ 'signed',
+ 'declined',
+ 'reminded_manual',
+ 'email_sent',
+ 'completed',
+ 'voided',
+ 'deadline_changed',
+ 'expired',
+ 'reminded_auto',
+ 'reauthentication_failed'
+ ));
+
+create table if not exists public.system_audit_events (
+ id text primary key,
+ sequence integer not null unique,
+ event text not null,
+ actor_user_id text,
+ actor_email text,
+ target_user_id text,
+ ip_address text,
+ user_agent text,
+ metadata jsonb,
+ created_at bigint not null,
+ prev_hash text,
+ row_hash text not null
+);
+
+create index if not exists idx_system_audit_events_created_at
+ on public.system_audit_events (created_at desc);
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index dcef1fa..c4523fd 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -767,3 +767,240 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a
expect(cspViolations).toEqual([]);
});
+
+// Runs after the test above, on the install it left behind: one
+// administrator, sign-up open to anyone, no retention period.
+test("in Part 11 mode a verified account signs, with its password and a stated meaning", async ({
+ browser,
+ page,
+}, testInfo) => {
+ const runId = String(Date.now());
+ const signerEmail = `part11+${runId}@example.com`;
+ const signerName = "Pat Part";
+ 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 administrator turns Part 11 mode on", 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.getByRole("button", { name: "Turn on Part 11 mode" }).click();
+ await expect(
+ page.getByRole("button", { name: "Turn off Part 11 mode" }),
+ ).toBeVisible();
+ // A retention period would delete regulated records on a timer.
+ await expect(page.getByLabel("Days to keep")).toBeDisabled();
+ });
+
+ await test.step("the signer makes an account and confirms their email", async () => {
+ const signerContext = await browser.newContext();
+ const signerPage = await signerContext.newPage();
+
+ await signerPage.goto("/signup");
+ await signerPage.getByLabel("Full name").fill(signerName);
+ await signerPage.getByLabel("Email").fill(signerEmail);
+ await signerPage.getByLabel("Password").fill(PASSWORD);
+ await signerPage.getByRole("button", { name: "Sign up" }).click();
+
+ const verificationEmail = await waitForEmail({
+ template: "email_verification",
+ to: signerEmail,
+ });
+
+ await signerPage.goto(
+ extractLink(verificationEmail.text, "/api/auth/verify-email"),
+ );
+ await expect(signerPage).toHaveURL(/\/login/);
+ await signerContext.close();
+ });
+
+ let envelopeId = "";
+
+ await test.step("a draft names the signer and what their signature means", async () => {
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("batch.pdf"));
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill("Batch record 42");
+ 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(signerName);
+ await page.getByLabel("Signer 1 email").fill(signerEmail);
+ // No meaning, no way on.
+ await expect(page.getByRole("button", { name: "Next →" })).toBeDisabled();
+ await page
+ .getByLabel("Signer 1 signature meaning")
+ .selectOption("approval");
+ await expect(page.getByText("I approve this document.")).toBeVisible();
+ 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$/);
+ });
+
+ async function trySend() {
+ 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 test.step("it is not sent until an administrator confirms who the signer is", async () => {
+ await trySend();
+ await expect(
+ page.getByText(
+ `An administrator has to confirm ${signerName}'s identity under Settings, People before they can sign.`,
+ ),
+ ).toBeVisible();
+
+ await page.goto("/settings");
+ await page
+ .getByRole("button", { name: `Confirm ${signerName}'s identity` })
+ .click();
+ await page
+ .getByLabel("How did you check who this is?")
+ .fill("Badge checked in person");
+ await page.getByRole("button", { exact: true, name: "Save" }).click();
+ await expect(
+ page.getByRole("button", {
+ name: `Take back ${signerName}'s identity confirmation`,
+ }),
+ ).toBeVisible();
+
+ await page.goto(`/envelopes/${envelopeId}/review`);
+ await trySend();
+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));
+ });
+
+ await test.step("the signer gives their password to open it and again to sign", 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/"));
+ await expect(
+ signerPage.getByRole("heading", { name: "Confirm it's you" }),
+ ).toBeVisible();
+ await signerPage.getByLabel("Email address").fill(signerEmail);
+ await signerPage.getByLabel("Password").fill(PASSWORD);
+ await signerPage.getByRole("button", { name: "Continue" }).click();
+
+ 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: "Signature" })
+ .click();
+ await signerPage
+ .getByRole("dialog", { name: "Add your signature" })
+ .getByRole("button", { name: "Apply signature" })
+ .click();
+ await signerPage.getByRole("button", { name: "Finish" }).click();
+
+ const finish = signerPage.getByRole("dialog", { name: "Finish signing?" });
+ const finishButton = finish.getByRole("button", { name: "Finish signing" });
+
+ await expect(
+ finish.getByText("Approval: I approve this document."),
+ ).toBeVisible();
+ await expect(finishButton).toBeDisabled();
+ await finish
+ .getByRole("checkbox", { name: "I confirm the meaning of my signature" })
+ .check();
+ await finish.getByLabel("Email address").fill(signerEmail);
+ await finish.getByLabel("Password").fill("not my password");
+ await finishButton.click();
+ await expect(finish.getByRole("alert")).toBeVisible();
+
+ await finish.getByLabel("Password").fill(PASSWORD);
+ await finishButton.click();
+ await expect(signerPage).toHaveURL(/\/sign\/[^/]+\/done/);
+ await signerContext.close();
+ });
+
+ await test.step("the audit trails record it and export as CSV", async () => {
+ await waitForEmail({ template: "completion_notification", to: adminEmail });
+
+ const envelopeCsv = await (
+ await page.request.get(`/api/envelopes/${envelopeId}/audit`)
+ ).text();
+
+ expect(envelopeCsv).toContain("Part 11 envelope,yes");
+ expect(envelopeCsv).toMatch(/Hash chain check,intact/);
+ expect(envelopeCsv).toContain("reauthentication_failed");
+ expect(envelopeCsv).toMatch(/,signed,/);
+ expect(envelopeCsv).toContain("approval");
+
+ const siteAudit = (await (
+ await page.request.get("/api/admin/audit")
+ ).json()) as { chain: { ok: boolean }; events: { event: string }[] };
+
+ expect(siteAudit.chain.ok).toBe(true);
+
+ const events = siteAudit.events.map((event) => event.event);
+
+ expect(events).toContain("part11_mode_changed");
+ expect(events).toContain("identity_verified");
+ expect(events).toContain("reauthentication_failed");
+
+ // The signed PDF still downloads, with the manifestation stamped on it.
+ const signed = await page.request.get(
+ `/api/envelopes/${envelopeId}/download?type=signed`,
+ );
+
+ expect(signed.status()).toBe(200);
+ });
+
+ await test.step("the mode can be turned off again", async () => {
+ expect(
+ (
+ await page.request.put("/api/admin/part11", {
+ data: { enabled: false },
+ })
+ ).status(),
+ ).toBe(200);
+ });
+});
diff --git a/src/app/api/admin/audit/route.ts b/src/app/api/admin/audit/route.ts
new file mode 100644
index 0000000..144d7b6
--- /dev/null
+++ b/src/app/api/admin/audit/route.ts
@@ -0,0 +1,78 @@
+import { NextResponse } from "next/server";
+
+import { exportSystemAuditCsv } from "@/lib/audit-export";
+import { requireAdminSession } from "@/lib/auth/admin";
+import { logRouteError } from "@/lib/security/logging";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import {
+ listSystemAuditEvents,
+ verifySystemAuditChain,
+} from "@/lib/services/system-audit";
+
+const noStore = { "cache-control": "private, no-store" };
+
+function readTimestamp(value: string | null): number | null {
+ if (!value) {
+ return null;
+ }
+
+ const parsed = Date.parse(value);
+
+ return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : null;
+}
+
+// The install's own audit trail, for administrators. ?format=csv&from=&to=
+// (ISO dates) downloads a range; otherwise a page of the newest events,
+// with ?before=<sequence> for the next page.
+export async function GET(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const url = new URL(request.url);
+
+ try {
+ if (url.searchParams.get("format") === "csv") {
+ const to =
+ readTimestamp(url.searchParams.get("to")) ??
+ Math.floor(Date.now() / 1000);
+ const from = readTimestamp(url.searchParams.get("from")) ?? 0;
+ const file = await exportSystemAuditCsv({ from, to });
+
+ return new Response(file.body, {
+ headers: {
+ ...noStore,
+ "content-disposition": `attachment; filename="${file.fileName}"`,
+ "content-type": "text/csv; charset=utf-8",
+ "x-content-type-options": "nosniff",
+ },
+ });
+ }
+
+ const before = Number(url.searchParams.get("before"));
+ const events = await listSystemAuditEvents({
+ before: Number.isInteger(before) && before > 0 ? before : null,
+ limit: 50,
+ });
+
+ return NextResponse.json(
+ { chain: await verifySystemAuditChain(), events },
+ { headers: noStore },
+ );
+ } catch (error) {
+ logRouteError(error, {
+ category: "system_audit_read_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while reading the install's audit trail.",
+ path: getRequestPathname(request),
+ userId: sessionResult.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The audit trail could not be read." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/admin/part11/route.ts b/src/app/api/admin/part11/route.ts
new file mode 100644
index 0000000..9b44701
--- /dev/null
+++ b/src/app/api/admin/part11/route.ts
@@ -0,0 +1,95 @@
+import { NextResponse } from "next/server";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import { Part11Error, setPart11Mode } from "@/lib/part11";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import { getSettings } from "@/lib/settings";
+
+const noStore = { "cache-control": "private, no-store" };
+
+// Turns Part 11 mode on or off. Administrators only.
+export async function PUT(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const rateLimitResponse = await applyRateLimit({
+ category: "part11_mode_change",
+ key: buildRateLimitKey(["part11-mode", session.user.id]),
+ limit: 20,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ const body = (await request.json().catch(() => null)) as {
+ enabled?: unknown;
+ } | null;
+
+ if (typeof body?.enabled !== "boolean") {
+ return NextResponse.json(
+ { error: "Say whether Part 11 mode should be on." },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ if ((await getSettings()).hosted) {
+ return NextResponse.json(
+ { error: "Part 11 mode is for self-hosted installs." },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ try {
+ await setPart11Mode(
+ {
+ email: session.user.email,
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ userId: session.user.id,
+ },
+ body.enabled,
+ );
+
+ return NextResponse.json(
+ { part11Mode: (await getSettings()).part11Mode },
+ { headers: noStore },
+ );
+ } catch (error) {
+ if (error instanceof Part11Error) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "part11_mode_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while changing Part 11 mode.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "That change could not be saved." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/admin/people/[id]/part11/route.ts b/src/app/api/admin/people/[id]/part11/route.ts
new file mode 100644
index 0000000..1c5fddf
--- /dev/null
+++ b/src/app/api/admin/people/[id]/part11/route.ts
@@ -0,0 +1,112 @@
+import { NextResponse } from "next/server";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import {
+ Part11Error,
+ setIdentityVerification,
+ unlockSigning,
+} from "@/lib/part11";
+import { listPeople } from "@/lib/people";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+
+type PersonRouteContext = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+const noStore = { "cache-control": "private, no-store" };
+
+// Part 11 controls on one account: confirm who the person is ("verify",
+// with a note saying how), take that back ("revoke"), or let them sign again
+// after wrong passwords locked them ("unlock"). Administrators only.
+// Answers with the list as it now stands, narrowed by the page's `search`.
+export async function POST(request: Request, context: PersonRouteContext) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const { id } = await context.params;
+ const rateLimitResponse = await applyRateLimit({
+ category: "people_part11_change",
+ key: buildRateLimitKey(["people-part11", session.user.id]),
+ limit: 60,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ const body = (await request.json().catch(() => null)) as {
+ action?: unknown;
+ note?: unknown;
+ search?: unknown;
+ } | null;
+ const actor = {
+ email: session.user.email,
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ userId: session.user.id,
+ };
+ const search = typeof body?.search === "string" ? body.search : "";
+
+ try {
+ switch (body?.action) {
+ case "verify":
+ case "revoke":
+ await setIdentityVerification(actor, id, {
+ note: typeof body.note === "string" ? body.note : null,
+ verified: body.action === "verify",
+ });
+ break;
+ case "unlock":
+ await unlockSigning(actor, id);
+ break;
+ default:
+ return NextResponse.json(
+ { error: "Choose verify, revoke or unlock." },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ return NextResponse.json(
+ { ...(await listPeople({ search })), you: session.user.id },
+ { headers: noStore },
+ );
+ } catch (error) {
+ if (error instanceof Part11Error) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "people_part11_failure",
+ ipAddress: actor.ipAddress,
+ message: "Unexpected failure while changing an account's Part 11 status.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "That change could not be saved." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/admin/settings/route.ts b/src/app/api/admin/settings/route.ts
index 2ec2829..0a11914 100644
--- a/src/app/api/admin/settings/route.ts
+++ b/src/app/api/admin/settings/route.ts
@@ -1,7 +1,9 @@
import { NextResponse } from "next/server";
import { requireAdminSession } from "@/lib/auth/admin";
+import { getDb, withTransaction } from "@/lib/db/connection";
import {
+ diffSettings,
OrganizationSettingsError,
toOrganizationSettingsView,
updateOrganizationSettings,
@@ -11,7 +13,12 @@ import {
applyRateLimit,
buildRateLimitKey,
} from "@/lib/security/route-controls";
-import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import { recordSystemAuditEvent } from "@/lib/services/system-audit";
import {
getSettings,
readStoredSettings,
@@ -44,7 +51,28 @@ export async function PUT(request: Request) {
const body: unknown = await request.json().catch(() => null);
try {
- await updateOrganizationSettings(body ?? {}, await getSettings());
+ const current = await getSettings();
+
+ // The change and its line in the install's audit trail land together.
+ await withTransaction(async (tx) => {
+ const before = await readStoredSettings(tx);
+ const after = await updateOrganizationSettings(body ?? {}, current, tx);
+ const changes = diffSettings(before, after);
+
+ if (Object.keys(changes).length > 0) {
+ await recordSystemAuditEvent(
+ {
+ actorEmail: session.user.email,
+ actorUserId: session.user.id,
+ event: "settings_changed",
+ ipAddress: getClientIpAddress(request.headers),
+ metadata: { changes },
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ tx,
+ );
+ }
+ }, getDb());
// Read back rather than trusting the cache, so the form shows exactly
// what is stored.
diff --git a/src/app/api/envelopes/[id]/audit/route.ts b/src/app/api/envelopes/[id]/audit/route.ts
new file mode 100644
index 0000000..7f4c79f
--- /dev/null
+++ b/src/app/api/envelopes/[id]/audit/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse } from "next/server";
+
+import { AuditExportError, exportEnvelopeAuditCsv } from "@/lib/audit-export";
+import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
+import { logRouteError } from "@/lib/security/logging";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+
+type EnvelopeAuditRouteContext = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+// The envelope's audit trail as a CSV file, for its sender.
+export async function GET(
+ request: Request,
+ context: EnvelopeAuditRouteContext,
+) {
+ const sessionResult = await requireVerifiedSenderSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const { id } = await context.params;
+
+ try {
+ const file = await exportEnvelopeAuditCsv(sessionResult.user.id, id);
+
+ return new Response(file.body, {
+ headers: {
+ "cache-control": "private, no-store",
+ "content-disposition": `attachment; filename="${file.fileName}"`,
+ "content-type": "text/csv; charset=utf-8",
+ "x-content-type-options": "nosniff",
+ },
+ });
+ } catch (error) {
+ if (error instanceof AuditExportError) {
+ return NextResponse.json(
+ { error: error.message },
+ { status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "envelope_audit_export_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while exporting an audit trail.",
+ path: getRequestPathname(request),
+ userId: sessionResult.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The audit trail could not be exported." },
+ { status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/envelopes/[id]/void/route.ts b/src/app/api/envelopes/[id]/void/route.ts
index baf6285..9ed9721 100644
--- a/src/app/api/envelopes/[id]/void/route.ts
+++ b/src/app/api/envelopes/[id]/void/route.ts
@@ -4,7 +4,10 @@ import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
import { getDb } from "@/lib/db/connection";
import { EnvelopeMutationError, voidSentEnvelope } from "@/lib/envelopes";
import { logRouteError } from "@/lib/security/logging";
-import { applyRateLimit, buildRateLimitKey } from "@/lib/security/route-controls";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
import {
getClientIpAddress,
getRequestPathname,
@@ -44,12 +47,17 @@ export async function POST(
return rateLimitResponse;
}
+ const body = (await request.json().catch(() => null)) as {
+ reason?: unknown;
+ } | null;
+
try {
const result = await voidSentEnvelope(
session.user.id,
id,
{
ipAddress,
+ reason: typeof body?.reason === "string" ? body.reason : null,
senderEmail: session.user.email,
senderName:
typeof session.user.name === "string" && session.user.name.trim()
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index 0092468..53fc47c 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -9,10 +9,11 @@ import {
type LucideIcon,
} from "lucide-react";
import Link from "next/link";
-import { useState } from "react";
+import { type ReactNode, useState } from "react";
import { DocumentThumbnail } from "@/components/shared/document-thumbnail";
import { ShellButton } from "@/components/shared/form-shell";
+import { Textarea } from "@/components/ui/textarea";
import { StatusPanel } from "@/components/shared/status-panel";
import { SaveTemplateDialog } from "@/components/templates/save-template-dialog";
import {
@@ -131,6 +132,7 @@ export function EnvelopeDetailShell({
const [isDeletingDraft, setIsDeletingDraft] = useState(false);
const [isSendingReminder, setIsSendingReminder] = useState(false);
const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);
+ const [voidReason, setVoidReason] = useState("");
const [savedTemplateName, setSavedTemplateName] = useState<string | null>(
null,
);
@@ -340,6 +342,8 @@ export function EnvelopeDetailShell({
try {
const response = await fetch(`/api/envelopes/${envelopeId}/void`, {
+ body: JSON.stringify({ reason: voidReason }),
+ headers: { "content-type": "application/json" },
method: "POST",
});
const payload = (await response.json().catch(() => null)) as {
@@ -472,6 +476,21 @@ export function EnvelopeDetailShell({
Download certificate
</ShellButton>
) : null}
+
+ {activeRecord.status !== "draft" ? (
+ <ShellButton
+ onClick={() =>
+ // A file download from an API route, not a page navigation.
+ // eslint-disable-next-line @next/next/no-location-assign-relative-destination
+ window.location.assign(
+ `/api/envelopes/${encodeURIComponent(envelopeId)}/audit`,
+ )
+ }
+ variant="secondary"
+ >
+ Export audit trail
+ </ShellButton>
+ ) : null}
</div>
</div>
@@ -762,12 +781,29 @@ export function EnvelopeDetailShell({
"Notified signers will be informed that the envelope has been voided.",
"This action cannot be undone.",
]}
+ confirmDisabled={record.part11 && voidReason.trim().length === 0}
errorMessage={actionError}
onCancel={() => setActiveModal(null)}
onConfirm={handleConfirmVoidEnvelope}
processing={isVoidingEnvelope}
title="Void this envelope?"
- />
+ >
+ <label className="grid gap-2 text-sm">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ {record.part11 ? "Reason (required)" : "Reason (optional)"}
+ </span>
+ <Textarea
+ disabled={isVoidingEnvelope}
+ maxLength={1000}
+ onChange={(event) => setVoidReason(event.target.value)}
+ rows={3}
+ value={voidReason}
+ />
+ <span className="text-xs leading-5 text-(--tertiary)">
+ Kept in the envelope&apos;s audit trail.
+ </span>
+ </label>
+ </ConfirmationDialog>
) : null}
</div>
);
@@ -964,6 +1000,8 @@ function RemindersDialog({
}
type ConfirmationDialogProps = {
+ children?: ReactNode;
+ confirmDisabled?: boolean;
confirmLabel: string;
description: readonly string[];
errorMessage?: string | null;
@@ -974,6 +1012,8 @@ type ConfirmationDialogProps = {
};
function ConfirmationDialog({
+ children,
+ confirmDisabled = false,
confirmLabel,
description,
errorMessage,
@@ -1004,6 +1044,8 @@ function ConfirmationDialog({
</DialogDescription>
</DialogHeader>
+ {children}
+
{errorMessage ? (
<div className="notice notice-danger" role="alert">
<p>{errorMessage}</p>
@@ -1019,6 +1061,7 @@ function ConfirmationDialog({
Cancel
</ShellButton>
<ShellButton
+ disabled={confirmDisabled}
loading={processing}
onClick={onConfirm}
variant="danger"
diff --git a/src/components/envelopes/signers-shell.tsx b/src/components/envelopes/signers-shell.tsx
index c1d42b1..ebcd81a 100644
--- a/src/components/envelopes/signers-shell.tsx
+++ b/src/components/envelopes/signers-shell.tsx
@@ -16,9 +16,12 @@ import {
duplicateSignerEmailMessage,
type ReplaceSignersResponse,
} from "@/lib/schemas/signer";
+import { SIGNATURE_MEANING_DETAILS } from "@/lib/signature-meanings";
import {
MAX_COPY_RECIPIENTS_PER_ENVELOPE,
MAX_SIGNERS_PER_ENVELOPE,
+ signatureMeanings,
+ type SignatureMeaning,
} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
@@ -41,6 +44,8 @@ type SignerChecks = {
hasAccessCode: boolean;
removeAccessCode: boolean;
requireEmailCode: boolean;
+ /** Part 11 mode: what this signature means (21 CFR 11.50). */
+ signatureMeaning: SignatureMeaning | null;
};
type ShellSigner = SignerChecks & {
@@ -86,6 +91,7 @@ function createSigner(
removeAccessCode: false,
requireEmailCode: overrides?.requireEmailCode ?? false,
name: overrides?.name ?? "",
+ signatureMeaning: overrides?.signatureMeaning ?? null,
signerId: overrides?.signerId,
touched: {
email: overrides?.touched?.email ?? false,
@@ -105,6 +111,7 @@ function buildInitialModel(record?: DraftSignerStepData): InitialModel {
hasAccessCode: signer.hasAccessCode,
name: signer.name,
requireEmailCode: signer.requireEmailCode,
+ signatureMeaning: signer.signatureMeaning ?? null,
signerId: signer.id,
touched: { email: true, name: true },
}),
@@ -257,6 +264,7 @@ function buildSignerRequest(
id: signer.signerId,
name: signer.name,
requireEmailCode: signer.requireEmailCode,
+ signatureMeaning: signer.signatureMeaning,
signOrder: index + 1,
})),
};
@@ -301,9 +309,11 @@ function SignerCard({
onMove,
onRemove,
accessCodeError,
+ part11Mode = false,
signer,
}: {
accessCodeError?: string;
+ part11Mode?: boolean;
onChecksChange: (patch: Partial<SignerChecks>) => void;
canMoveEarlier: boolean;
canMoveLater: boolean;
@@ -440,6 +450,48 @@ function SignerCard({
</label>
</div>
+ {part11Mode ? (
+ <label className="grid gap-2 rounded-2xl bg-white p-4 text-sm text-(--fg) sm:p-5">
+ <span className="font-bold text-(--fg)">
+ What this signature means
+ </span>
+ <span className="text-[0.8125rem] leading-5 text-(--secondary)">
+ Part 11 mode is on. The meaning is printed beside the signature
+ with the signer&apos;s name and the time. The signer needs an
+ account here with a confirmed email address, and an administrator
+ must have confirmed who they are.
+ </span>
+ <select
+ aria-invalid={!signer.signatureMeaning ? true : undefined}
+ aria-label={`Signer ${order} signature meaning`}
+ className="field-input"
+ disabled={disabled}
+ onChange={(event: ChangeEvent<HTMLSelectElement>) =>
+ onChecksChange({
+ signatureMeaning: (
+ signatureMeanings as readonly string[]
+ ).includes(event.target.value)
+ ? (event.target.value as SignatureMeaning)
+ : null,
+ })
+ }
+ value={signer.signatureMeaning ?? ""}
+ >
+ <option value="">Choose a meaning</option>
+ {signatureMeanings.map((meaning) => (
+ <option key={meaning} value={meaning}>
+ {SIGNATURE_MEANING_DETAILS[meaning].label}
+ </option>
+ ))}
+ </select>
+ {signer.signatureMeaning ? (
+ <span className="text-[0.8125rem] leading-5 text-(--secondary)">
+ {SIGNATURE_MEANING_DETAILS[signer.signatureMeaning].statement}
+ </span>
+ ) : null}
+ </label>
+ ) : null}
+
<fieldset className="grid gap-3 rounded-2xl bg-white p-4 text-sm text-(--fg) sm:p-5">
<legend className="sr-only">Extra check before signing</legend>
<p className="font-bold text-(--fg)">
@@ -655,7 +707,9 @@ export function SignersShell({
copyRecipients.every(
(recipient) =>
!hasSignerErrors(errorsByCopyRecipientId[recipient.localId] ?? {}),
- );
+ ) &&
+ (!record?.part11Mode ||
+ signers.every((signer) => signer.signatureMeaning !== null));
function clearSubmitError() {
setSubmissionError(null);
@@ -920,6 +974,7 @@ export function SignersShell({
handleMoveSigner(signer.localId, direction)
}
onRemove={() => handleRemoveSigner(signer.localId)}
+ part11Mode={record?.part11Mode ?? false}
signer={signer}
/>
);
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index 09d2a17..2d80253 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -5,6 +5,7 @@ import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
import { BrandingPanel } from "@/components/settings/branding-panel";
+import { Part11Panel } from "@/components/settings/part11-panel";
import { PeoplePanel } from "@/components/settings/people-panel";
import { SignerDataPanel } from "@/components/settings/signer-data-panel";
import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";
@@ -370,8 +371,13 @@ export function OrganizationSettings({
</div>
<div className="max-w-xs">
<FieldShell
- disabled={isSaving}
+ disabled={isSaving || values.part11Mode}
error={errors.retentionDays}
+ helper={
+ values.part11Mode
+ ? "Off while Part 11 mode is on: those records are deleted by hand only."
+ : undefined
+ }
label="Days to keep"
name="retention-days"
onChange={handleChange("retentionDays")}
@@ -391,7 +397,11 @@ export function OrganizationSettings({
{/* The hosted service's accounts are strangers to each other, not
one organization, so it has no list of them here. */}
- {!values.hosted ? <PeoplePanel /> : null}
+ {!values.hosted ? <PeoplePanel part11Mode={values.part11Mode} /> : null}
+
+ {!values.hosted ? (
+ <Part11Panel initialEnabled={values.part11Mode} />
+ ) : null}
<SignerDataPanel />
</div>
diff --git a/src/components/settings/part11-panel.tsx b/src/components/settings/part11-panel.tsx
new file mode 100644
index 0000000..44bf87d
--- /dev/null
+++ b/src/components/settings/part11-panel.tsx
@@ -0,0 +1,238 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import type { SystemAuditEvent } from "@/lib/services/system-audit";
+
+// Part 11 mode and the install's own audit trail. Administrators only.
+
+const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";
+
+type AuditResponse = {
+ chain?:
+ | { events: number; ok: true }
+ | { brokenAtSequence: number; events: number; ok: false };
+ error?: string;
+ events?: SystemAuditEvent[];
+} | null;
+
+const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
+ identity_verification_revoked: "Identity confirmation taken back",
+ identity_verified: "Identity confirmed",
+ part11_mode_changed: "Part 11 mode changed",
+ reauthentication_failed: "Wrong password while signing",
+ role_changed: "Role changed",
+ settings_changed: "Settings changed",
+ signing_locked: "Signing locked",
+ signing_unlocked: "Signing unlocked",
+};
+
+function describeEvent(event: SystemAuditEvent): string {
+ const metadata = event.metadata ?? {};
+ const target =
+ typeof metadata.targetName === "string"
+ ? `${metadata.targetName}${typeof metadata.targetEmail === "string" ? ` <${metadata.targetEmail}>` : ""}`
+ : null;
+
+ switch (event.event) {
+ case "part11_mode_changed":
+ return metadata.to === true ? "Turned on" : "Turned off";
+ case "role_changed":
+ return `${target ?? "Account"}: ${String(metadata.from)} to ${String(metadata.to)}`;
+ case "settings_changed":
+ return typeof metadata.changes === "object" && metadata.changes
+ ? Object.keys(metadata.changes).join(", ")
+ : "";
+ case "identity_verified":
+ return `${target ?? ""}${typeof metadata.note === "string" ? `: ${metadata.note}` : ""}`;
+ case "reauthentication_failed":
+ case "signing_locked":
+ return typeof metadata.failedAttempts === "number"
+ ? `${String(metadata.failedAttempts)} wrong in a row`
+ : "";
+ default:
+ return target ?? "";
+ }
+}
+
+export function Part11Panel({ initialEnabled }: { initialEnabled: boolean }) {
+ const enabled = initialEnabled;
+ const [error, setError] = useState<string | null>(null);
+ const [isSaving, setIsSaving] = useState(false);
+ const [audit, setAudit] = useState<AuditResponse>(null);
+ const [auditRevision, setAuditRevision] = useState(0);
+
+ useEffect(() => {
+ const controller = new AbortController();
+
+ fetch("/api/admin/audit", { signal: controller.signal })
+ .then(async (response) => {
+ const payload = (await response
+ .json()
+ .catch(() => null)) as AuditResponse;
+
+ setAudit(
+ response.ok
+ ? payload
+ : { error: payload?.error ?? GENERIC_ERROR_MESSAGE },
+ );
+ })
+ .catch((loadError: unknown) => {
+ if (!(
+ loadError instanceof DOMException && loadError.name === "AbortError"
+ )) {
+ setAudit({ error: GENERIC_ERROR_MESSAGE });
+ }
+ });
+
+ return () => controller.abort();
+ }, [auditRevision]);
+
+ async function changeMode(next: boolean) {
+ setIsSaving(true);
+ setError(null);
+
+ try {
+ const response = await fetch("/api/admin/part11", {
+ body: JSON.stringify({ enabled: next }),
+ headers: { "content-type": "application/json" },
+ method: "PUT",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ part11Mode?: boolean;
+ } | null;
+
+ if (!response.ok || typeof payload?.part11Mode !== "boolean") {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ // The People list and the retention field depend on the mode.
+ window.location.reload();
+ } catch {
+ setError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setIsSaving(false);
+ }
+ }
+
+ return (
+ <div className="space-y-5 border-t border-(--border) pt-8" id="part11">
+ <div className="space-y-2">
+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
+ FDA 21 CFR Part 11 mode
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ For regulated records. While it is on, envelopes are sent only to
+ people with an account here whose identity an administrator has
+ confirmed under People. Each signer gives their email address and
+ password to open the document and again to sign, and confirms what the
+ signature means, which is printed beside it with their name and the
+ time. Five wrong passwords lock the account for signing and email the
+ administrators. Finished envelopes are never deleted by the retention
+ period or a data request, and a void needs a reason.
+ </p>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ Turning it on does not by itself make this site compliant. Your
+ organization still validates the system, writes and follows its own
+ procedures, trains its people and certifies its electronic signatures
+ to the FDA.
+ </p>
+ </div>
+
+ {error ? (
+ <div className="notice notice-danger" role="alert">
+ {error}
+ </div>
+ ) : null}
+
+ <div className="flex flex-wrap items-center gap-3">
+ <span className={`pill ${enabled ? "pill-success" : "pill-neutral"}`}>
+ {enabled ? "On" : "Off"}
+ </span>
+ <button
+ className={enabled ? "btn-quiet btn-quiet-danger" : "btn-quiet"}
+ disabled={isSaving}
+ onClick={() => void changeMode(!enabled)}
+ type="button"
+ >
+ {isSaving
+ ? "Saving..."
+ : enabled
+ ? "Turn off Part 11 mode"
+ : "Turn on Part 11 mode"}
+ </button>
+ </div>
+
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h4 className="text-[0.9375rem] font-bold text-(--fg)">
+ Site audit trail
+ </h4>
+ <div className="flex flex-wrap gap-2">
+ <button
+ className="btn-quiet"
+ onClick={() => setAuditRevision((value) => value + 1)}
+ type="button"
+ >
+ Refresh
+ </button>
+ <a className="btn-quiet" href="/api/admin/audit?format=csv">
+ Download as CSV
+ </a>
+ </div>
+ </div>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ Changes to settings, roles, identity confirmations and signing locks.
+ Each envelope has its own trail too, which its sender can export from
+ the envelope&apos;s page.
+ </p>
+
+ {audit?.error ? (
+ <div className="notice notice-danger" role="alert">
+ {audit.error}
+ </div>
+ ) : null}
+
+ {audit?.chain ? (
+ <p
+ className={`notice ${audit.chain.ok ? "notice-success" : "notice-danger"}`}
+ role="status"
+ >
+ {audit.chain.ok
+ ? `Hash chain intact across ${String(audit.chain.events)} events.`
+ : `The hash chain is broken at event ${String(audit.chain.brokenAtSequence)}: a row was changed or removed.`}
+ </p>
+ ) : null}
+
+ {audit?.events ? (
+ audit.events.length === 0 ? (
+ <p className="text-sm text-(--secondary)">Nothing recorded yet.</p>
+ ) : (
+ <ul aria-label="Site audit trail" className="space-y-2">
+ {audit.events.map((event) => (
+ <li className="well p-3 text-sm" key={event.id}>
+ <p className="font-semibold text-(--fg)">
+ {EVENT_LABELS[event.event] ?? event.event}
+ <span className="font-normal text-(--secondary)">
+ {" "}
+ {describeEvent(event)}
+ </span>
+ </p>
+ <p className="text-xs text-(--tertiary)">
+ {new Date(event.createdAt * 1000)
+ .toISOString()
+ .replace("T", " ")
+ .replace(/\.\d{3}Z$/, " UTC")}
+ {event.actorEmail ? ` · ${event.actorEmail}` : ""}
+ </p>
+ </li>
+ ))}
+ </ul>
+ )
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/settings/people-panel.tsx b/src/components/settings/people-panel.tsx
index 0666061..08d6c05 100644
--- a/src/components/settings/people-panel.tsx
+++ b/src/components/settings/people-panel.tsx
@@ -34,7 +34,7 @@ function readPeopleList(payload: PeopleResponse): PeopleList | null {
};
}
-export function PeoplePanel() {
+export function PeoplePanel({ part11Mode = false }: { part11Mode?: boolean }) {
const [list, setList] = useState<PeopleList | null>(null);
const [you, setYou] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -46,6 +46,9 @@ export function PeoplePanel() {
const [reloads, setReloads] = useState(0);
// The search as it stands now, for an answer that arrives after it moved.
const latestSearch = useRef(search);
+ // Part 11: the person whose identity is being confirmed, and how.
+ const [verifyingId, setVerifyingId] = useState<string | null>(null);
+ const [verificationNote, setVerificationNote] = useState("");
useEffect(() => {
latestSearch.current = search;
@@ -142,6 +145,56 @@ export function PeoplePanel() {
}
}
+ async function changePart11(
+ person: Person,
+ action: "revoke" | "unlock" | "verify",
+ ) {
+ if (pendingId) {
+ return;
+ }
+
+ setPendingId(person.id);
+ setError(null);
+
+ try {
+ const response = await fetch(
+ `/api/admin/people/${encodeURIComponent(person.id)}/part11`,
+ {
+ body: JSON.stringify({
+ action,
+ note: action === "verify" ? verificationNote : undefined,
+ search,
+ }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ },
+ );
+ const payload = (await response
+ .json()
+ .catch(() => null)) as PeopleResponse;
+ const changed = readPeopleList(payload);
+
+ if (!response.ok || !changed) {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ setVerifyingId(null);
+ setVerificationNote("");
+
+ if (latestSearch.current !== search) {
+ setReloads((count) => count + 1);
+ return;
+ }
+
+ setList(changed);
+ } catch {
+ setError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setPendingId(null);
+ }
+ }
+
const people = list?.people ?? null;
const administratorCount = list?.administratorCount ?? 0;
const searching = filter.trim().length > 0 || search.length > 0;
@@ -225,7 +278,106 @@ export function PeoplePanel() {
{person.closing ? (
<span className="pill pill-warning">Closing</span>
) : null}
+ {part11Mode || person.identityVerifiedAt !== null ? (
+ person.identityVerifiedAt !== null ? (
+ <span
+ className="pill pill-success"
+ title={person.identityVerificationNote ?? undefined}
+ >
+ Identity confirmed
+ </span>
+ ) : (
+ <span className="pill pill-neutral">
+ Identity not confirmed
+ </span>
+ )
+ ) : null}
+ {person.signingLockedAt !== null ? (
+ <span className="pill pill-danger">Signing locked</span>
+ ) : null}
</div>
+ {part11Mode ? (
+ <div className="flex flex-wrap gap-2 pt-1">
+ {person.identityVerifiedAt === null ? (
+ <button
+ aria-label={`Confirm ${person.name}'s identity`}
+ className="btn-quiet"
+ disabled={
+ pendingId !== null ||
+ !person.emailVerified ||
+ verifyingId === person.id
+ }
+ onClick={() => {
+ setVerifyingId(person.id);
+ setVerificationNote("");
+ }}
+ type="button"
+ >
+ Confirm identity
+ </button>
+ ) : (
+ <button
+ aria-label={`Take back ${person.name}'s identity confirmation`}
+ className="btn-quiet btn-quiet-danger"
+ disabled={pendingId !== null}
+ onClick={() => void changePart11(person, "revoke")}
+ type="button"
+ >
+ Take back confirmation
+ </button>
+ )}
+ {person.signingLockedAt !== null ? (
+ <button
+ aria-label={`Unlock signing for ${person.name}`}
+ className="btn-quiet"
+ disabled={pendingId !== null}
+ onClick={() => void changePart11(person, "unlock")}
+ type="button"
+ >
+ Unlock signing
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ {verifyingId === person.id ? (
+ <div className="grid max-w-md gap-2 pt-2">
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ How did you check who this is?
+ </span>
+ <input
+ className="field-input"
+ maxLength={500}
+ onChange={(event) =>
+ setVerificationNote(event.target.value)
+ }
+ placeholder="For example: passport seen in person, HR record 4417"
+ value={verificationNote}
+ />
+ </label>
+ <div className="flex gap-2">
+ <button
+ className="btn-quiet"
+ disabled={
+ pendingId !== null ||
+ verificationNote.trim().length === 0
+ }
+ onClick={() => void changePart11(person, "verify")}
+ type="button"
+ >
+ {pendingId === person.id ? "Saving..." : "Save"}
+ </button>
+ <button
+ className="btn-quiet"
+ disabled={pendingId !== null}
+ onClick={() => setVerifyingId(null)}
+ type="button"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : null}
</div>
{isAdmin ? (
diff --git a/src/components/settings/signer-data-panel.tsx b/src/components/settings/signer-data-panel.tsx
index cb36a0c..29c9a7c 100644
--- a/src/components/settings/signer-data-panel.tsx
+++ b/src/components/settings/signer-data-panel.tsx
@@ -10,6 +10,7 @@ import { FieldShell, ShellButton } from "@/components/shared/form-shell";
type ErasureResult = {
deletedEnvelopes: number;
removedFromDrafts: number;
+ keptPart11?: { id: string; title: string }[];
skippedInProgress: { id: string; title: string }[];
};
@@ -48,9 +49,12 @@ export function SignerDataPanel() {
const skipped = payload.skippedInProgress.length
? ` ${String(payload.skippedInProgress.length)} envelope(s) still out for signature were left alone: void them first, then erase again.`
: "";
+ const kept = payload.keptPart11?.length
+ ? ` ${String(payload.keptPart11.length)} Part 11 record(s) were kept: they are deleted by hand only, once the rules that apply to them allow it.`
+ : "";
setMessage({
- text: `Deleted ${String(payload.deletedEnvelopes)} finished envelope(s) and removed the signer from ${String(payload.removedFromDrafts)} draft(s).${skipped}`,
+ text: `Deleted ${String(payload.deletedEnvelopes)} finished envelope(s) and removed the signer from ${String(payload.removedFromDrafts)} draft(s).${skipped}${kept}`,
tone: "success",
});
setConfirmation("");
diff --git a/src/components/signing/signer-verification-screen.tsx b/src/components/signing/signer-verification-screen.tsx
index 9648782..8164f8e 100644
--- a/src/components/signing/signer-verification-screen.tsx
+++ b/src/components/signing/signer-verification-screen.tsx
@@ -15,6 +15,11 @@ const METHOD_COPY: Record<Method, { helper: string; label: string }> = {
helper: "The sender gave you this code separately, for example by phone.",
label: "Access code",
},
+ account: {
+ helper:
+ "This document is signed with your own account here. Enter the password you sign in with.",
+ label: "Password",
+ },
email_code: {
helper: "We email a 6-digit code to the address this document was sent to.",
label: "Code from your email",
@@ -30,6 +35,7 @@ export function SignerVerificationScreen({
}) {
const method = state.pending[0]!;
const [code, setCode] = useState("");
+ const [email, setEmail] = useState("");
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(
state.emailCodeSentAt && method === "email_code"
@@ -75,7 +81,11 @@ export function SignerVerificationScreen({
try {
const response = await fetch(`${base}/verify`, {
- body: JSON.stringify({ code, method }),
+ body: JSON.stringify(
+ method === "account"
+ ? { email, method, password: code }
+ : { code, method },
+ ),
headers: { "content-type": "application/json" },
method: "POST",
});
@@ -130,13 +140,28 @@ export function SignerVerificationScreen({
: ""}
</p>
<form className="mt-8 grid gap-5" onSubmit={handleSubmit}>
+ {method === "account" ? (
+ <FieldShell
+ autoComplete="username"
+ helper={`The address this document was sent to (${state.maskedEmail}).`}
+ label="Email address"
+ name="signer-email"
+ onChange={(event) => setEmail(event.target.value)}
+ readOnly={false}
+ type="email"
+ value={email}
+ />
+ ) : null}
<FieldShell
- autoComplete="one-time-code"
+ autoComplete={
+ method === "account" ? "current-password" : "one-time-code"
+ }
helper={copy.helper}
label={copy.label}
name="signer-code"
onChange={(event) => setCode(event.target.value)}
readOnly={false}
+ type={method === "account" ? "password" : "text"}
value={code}
/>
{notice ? (
@@ -151,7 +176,10 @@ export function SignerVerificationScreen({
) : null}
<div className="flex flex-col gap-3 sm:flex-row">
<ShellButton
- disabled={code.trim().length === 0}
+ disabled={
+ code.trim().length === 0 ||
+ (method === "account" && email.trim().length === 0)
+ }
loading={isChecking}
type="submit"
>
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index 48b8b96..3f38151 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -30,7 +30,7 @@ import {
type DocumentPanGesture,
DOCUMENT_ZOOM_STEP,
} from "@/components/shared/document-viewport";
-import { ShellButton } from "@/components/shared/form-shell";
+import { FieldShell, ShellButton } from "@/components/shared/form-shell";
import {
Dialog,
DialogContent,
@@ -449,6 +449,17 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
const [isFinishDialogOpen, setIsFinishDialogOpen] = useState(false);
const [isDocumentPanning, setIsDocumentPanning] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
+ // Part 11 envelopes: the signer's email address and password, given again
+ // for this signature, and their confirmation of what it means.
+ const [reauthEmail, setReauthEmail] = useState("");
+ const [reauthPassword, setReauthPassword] = useState("");
+ const [isMeaningConfirmed, setIsMeaningConfirmed] = useState(false);
+ const part11 = record.part11 ?? null;
+ const isReauthReady =
+ part11 === null ||
+ (isMeaningConfirmed &&
+ reauthEmail.trim().length > 0 &&
+ reauthPassword.length > 0);
const [pdfRenderState, setPdfRenderState] =
useState<PdfPageRenderState>("loading");
const [signatureValues, setSignatureValues] = useState<
@@ -573,7 +584,7 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
}
async function handleFinishSigning() {
- if (!canFinish || isSubmitting) {
+ if (!canFinish || isSubmitting || !isReauthReady) {
return;
}
@@ -582,9 +593,18 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
try {
const response = await fetch(record.submitUrl, {
- body: JSON.stringify(
- buildSigningSubmissionPayload(record, enteredValues),
- ),
+ body: JSON.stringify({
+ ...buildSigningSubmissionPayload(record, enteredValues),
+ ...(part11
+ ? {
+ reauthentication: {
+ email: reauthEmail,
+ meaningConfirmed: true,
+ password: reauthPassword,
+ },
+ }
+ : {}),
+ }),
headers: {
"content-type": "application/json",
},
@@ -603,6 +623,7 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
}
setSubmitError(payload?.error ?? defaultSubmitErrorMessage);
+ setReauthPassword("");
setIsSubmitting(false);
return;
}
@@ -1094,6 +1115,56 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
By clicking Finish, you confirm that your electronic signature is
intended to be binding for this document.
</p>
+ {part11 ? (
+ <div className="grid gap-4">
+ <div className="well rounded-xl px-3.5 py-3">
+ <p className="text-xs font-semibold text-(--tertiary)">
+ Meaning of your signature
+ </p>
+ <p className="mt-0.5 text-sm font-semibold text-(--fg)">
+ {part11.meaningLabel}: {part11.meaningStatement}
+ </p>
+ </div>
+ <label className="flex items-start gap-3 text-sm leading-6 text-(--secondary)">
+ <Checkbox
+ aria-label="I confirm the meaning of my signature"
+ checked={isMeaningConfirmed}
+ className="mt-1"
+ disabled={isSubmitting}
+ onCheckedChange={(checked) =>
+ setIsMeaningConfirmed(checked === true)
+ }
+ />
+ <span>
+ I confirm this meaning. My name, the date and time, and this
+ meaning will be printed with my signature.
+ </span>
+ </label>
+ <p className="text-sm leading-6 text-(--secondary)">
+ Enter your account&apos;s email address and password to sign.
+ </p>
+ <FieldShell
+ autoComplete="username"
+ disabled={isSubmitting}
+ label="Email address"
+ name="reauth-email"
+ onChange={(event) => setReauthEmail(event.target.value)}
+ readOnly={false}
+ type="email"
+ value={reauthEmail}
+ />
+ <FieldShell
+ autoComplete="current-password"
+ disabled={isSubmitting}
+ label="Password"
+ name="reauth-password"
+ onChange={(event) => setReauthPassword(event.target.value)}
+ readOnly={false}
+ type="password"
+ value={reauthPassword}
+ />
+ </div>
+ ) : null}
{submitError ? (
<div className="notice notice-danger" role="alert">
{submitError}
@@ -1110,7 +1181,11 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
>
Back
</ShellButton>
- <ShellButton loading={isSubmitting} onClick={handleFinishSigning}>
+ <ShellButton
+ disabled={!isReauthReady}
+ loading={isSubmitting}
+ onClick={handleFinishSigning}
+ >
{isSubmitting ? "Finishing..." : "Finish signing"}
</ShellButton>
</div>
diff --git a/src/lib/audit-export.ts b/src/lib/audit-export.ts
new file mode 100644
index 0000000..070e9bb
--- /dev/null
+++ b/src/lib/audit-export.ts
@@ -0,0 +1,204 @@
+import {
+ type DbExecutor,
+ getDb,
+ queryMany,
+ queryOne,
+} from "./db/connection.ts";
+import { verifyAuditChain } from "./services/audit.ts";
+import {
+ listSystemAuditEventsBetween,
+ verifySystemAuditChain,
+} from "./services/system-audit.ts";
+import { sanitizeFileNameSegment } from "./downloads.ts";
+
+// Audit trails as CSV, for an inspector or a records review (21 CFR
+// 11.10(b): accurate and complete copies in a form people can read and a
+// program can process). Each file starts with the result of checking the
+// hash chain, so a copy shows whether the trail was intact when exported.
+
+/**
+ * One CSV line. A cell that a spreadsheet would run as a formula is
+ * prefixed with an apostrophe, so an exported value can never execute.
+ */
+function csvRow(cells: readonly unknown[]): string {
+ return cells
+ .map((cell) => {
+ let text =
+ cell === null || cell === undefined
+ ? ""
+ : typeof cell === "object"
+ ? JSON.stringify(cell)
+ : String(cell);
+
+ if (/^[=+\-@\t\r]/.test(text)) {
+ text = `'${text}`;
+ }
+
+ return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
+ })
+ .join(",");
+}
+
+export function toCsv(rows: readonly (readonly unknown[])[]): string {
+ return `${rows.map(csvRow).join("\r\n")}\r\n`;
+}
+
+function isoTime(timestamp: number | null | undefined): string {
+ return typeof timestamp === "number"
+ ? new Date(timestamp * 1000).toISOString()
+ : "";
+}
+
+export type AuditCsvExport = { body: string; fileName: string };
+
+export class AuditExportError extends Error {
+ readonly statusCode: number;
+
+ constructor(message: string, statusCode: number) {
+ super(message);
+ this.name = "AuditExportError";
+ this.statusCode = statusCode;
+ }
+}
+
+/** The audit trail of one envelope its sender owns. */
+export async function exportEnvelopeAuditCsv(
+ userId: string,
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+): Promise<AuditCsvExport> {
+ const envelope = await queryOne<{ part11: boolean; title: string }>(
+ database,
+ `SELECT title, part11 FROM envelopes WHERE id = $1 AND user_id = $2`,
+ [envelopeId, userId],
+ );
+
+ if (!envelope) {
+ throw new AuditExportError("Envelope not found.", 404);
+ }
+
+ const rows = await queryMany<{
+ actorEmail: string | null;
+ actorType: string;
+ createdAt: number;
+ event: string;
+ id: string;
+ ipAddress: string | null;
+ metadata: Record<string, unknown> | null;
+ prevHash: string | null;
+ rowHash: string | null;
+ sequence: number | null;
+ userAgent: string | null;
+ }>(
+ database,
+ `
+ SELECT
+ id,
+ sequence,
+ event,
+ actor_type AS "actorType",
+ actor_email AS "actorEmail",
+ ip_address AS "ipAddress",
+ user_agent AS "userAgent",
+ metadata,
+ created_at AS "createdAt",
+ prev_hash AS "prevHash",
+ row_hash AS "rowHash"
+ FROM audit_events
+ WHERE envelope_id = $1
+ ORDER BY sequence ASC NULLS FIRST, created_at ASC, id ASC
+ `,
+ [envelopeId],
+ );
+ const chain = await verifyAuditChain(envelopeId, database);
+ const body = toCsv([
+ ["Envelope", envelopeId, envelope.title],
+ ["Part 11 envelope", envelope.part11 ? "yes" : "no"],
+ ["Exported at (UTC)", new Date().toISOString()],
+ [
+ "Hash chain check",
+ chain.ok
+ ? `intact (${chain.chainedEvents} chained events)`
+ : `BROKEN at sequence ${chain.brokenAtSequence}`,
+ ],
+ [],
+ [
+ "sequence",
+ "time_utc",
+ "event",
+ "actor_type",
+ "actor_email",
+ "ip_address",
+ "user_agent",
+ "details",
+ "event_id",
+ "previous_hash",
+ "row_hash",
+ ],
+ ...rows.map((row) => [
+ row.sequence,
+ isoTime(row.createdAt),
+ row.event,
+ row.actorType,
+ row.actorEmail,
+ row.ipAddress,
+ row.userAgent,
+ row.metadata,
+ row.id,
+ row.prevHash,
+ row.rowHash,
+ ]),
+ ]);
+
+ return {
+ body,
+ fileName: `${sanitizeFileNameSegment(envelope.title) || "envelope"}-audit-trail.csv`,
+ };
+}
+
+/** The install's own audit trail between two times, for an administrator. */
+export async function exportSystemAuditCsv(
+ { from, to }: { from: number; to: number },
+ database: DbExecutor = getDb(),
+): Promise<AuditCsvExport> {
+ const events = await listSystemAuditEventsBetween(from, to, database);
+ const chain = await verifySystemAuditChain(database);
+ const body = toCsv([
+ ["Install audit trail"],
+ ["From (UTC)", isoTime(from), "To (UTC)", isoTime(to)],
+ ["Exported at (UTC)", new Date().toISOString()],
+ [
+ "Hash chain check (whole trail)",
+ chain.ok
+ ? `intact (${chain.events} events)`
+ : `BROKEN at sequence ${chain.brokenAtSequence}`,
+ ],
+ [],
+ [
+ "sequence",
+ "time_utc",
+ "event",
+ "actor_email",
+ "actor_user_id",
+ "target_user_id",
+ "ip_address",
+ "user_agent",
+ "details",
+ "event_id",
+ ],
+ ...events.map((event) => [
+ event.sequence,
+ isoTime(event.createdAt),
+ event.event,
+ event.actorEmail,
+ event.actorUserId,
+ event.targetUserId,
+ event.ipAddress,
+ event.userAgent,
+ event.metadata,
+ event.id,
+ ]),
+ ]);
+
+ return { body, fileName: "install-audit-trail.csv" };
+}
diff --git a/src/lib/draft-changes.dbtest.ts b/src/lib/draft-changes.dbtest.ts
index 325cf3a..cc51aa7 100644
--- a/src/lib/draft-changes.dbtest.ts
+++ b/src/lib/draft-changes.dbtest.ts
@@ -261,6 +261,7 @@ test("erasing a signer leaves a row that was given someone else's address meanwh
]);
assert.deepEqual(result, {
deletedEnvelopes: 0,
+ keptPart11: [],
removedFromDrafts: 0,
skippedInProgress: [],
});
diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.ts
index 4e58775..9d942e3 100644
--- a/src/lib/email-status.test.ts
+++ b/src/lib/email-status.test.ts
@@ -17,6 +17,7 @@ const stored: AppSettings = {
emailReadyAt: null,
logoVersion: null,
organizationName: "Acme Corp",
+ part11Mode: false,
privacyUrl: null,
retentionDays: null,
senderAddress: "[email protected]",
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 53db589..27b970f 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -55,7 +55,14 @@ import {
type ReplaceSignersResponse,
type SignerRecord,
} from "./schemas/signer.ts";
-import { getBranding } from "./settings.ts";
+import {
+ describePart11SignerProblem,
+ findSignerAccounts,
+ parseSignatureMeaning,
+ signatureMeaningLabel,
+} from "./part11.ts";
+import { getBranding, readStoredSettings } from "./settings.ts";
+import { type SignatureMeaning } from "./types/domain.ts";
import { importPdfDocument } from "./services/document-import.ts";
import {
listAuditEventsForEnvelope,
@@ -122,6 +129,8 @@ type SendDraftEnvelopeInput = {
type VoidEnvelopeInput = {
ipAddress?: string | null;
+ /** Why it is voided. Required for a Part 11 envelope. */
+ reason?: string | null;
senderEmail: string;
senderName: string;
userAgent?: string | null;
@@ -144,6 +153,7 @@ type EnvelopeRow = {
id: string;
reminderIntervalDays: number | null;
pageCount: number;
+ part11: boolean;
sentAt: number | null;
signedPdfKey: string | null;
sourcePdfFilename: string;
@@ -167,6 +177,7 @@ type SignerRow = {
lastNotifiedAt: number | null;
lastNudgedAt: number | null;
name: string;
+ signatureMeaning: SignatureMeaning | null;
signedAt: number | null;
signOrder: number;
signingTokenExpiresAt: number | null;
@@ -294,11 +305,15 @@ export type DraftSignerStepSigner = {
name: string;
order: number;
requireEmailCode?: boolean;
+ /** Set on the signers step only. */
+ signatureMeaning?: SignatureMeaning | null;
};
export type DraftSignerStepData = {
copyRecipients: readonly CopyRecipientRecord[];
envelopeId: string;
+ /** Part 11 mode is on, so each signer needs a meaning and an account. */
+ part11Mode?: boolean;
signers: readonly DraftSignerStepSigner[];
status: EnvelopeRecord["status"];
};
@@ -353,6 +368,8 @@ export type EnvelopeDetailData = {
reminderIntervalDays: number | null;
envelopeId: string;
manualReminder: EnvelopeDetailManualReminderState | null;
+ /** Sent in Part 11 mode: a void needs a reason. */
+ part11: boolean;
signers: readonly EnvelopeDetailSignerView[];
status: EnvelopeRecord["status"];
timeline: readonly EnvelopeDetailTimelineItem[];
@@ -438,6 +455,7 @@ const TIMELINE_TONE_MAP: Record<
declined: "danger",
email_sent: "neutral",
expired: "danger",
+ reauthentication_failed: "danger",
reminded_auto: "neutral",
reminded_manual: "neutral",
sent: "neutral",
@@ -730,6 +748,7 @@ async function getEnvelopeByIdForUser(
voided_at AS "voidedAt",
expires_at AS "expiresAt",
reminder_interval_days AS "reminderIntervalDays",
+ part11,
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -768,6 +787,7 @@ async function listSignersForEnvelopeIds(
signed_at AS "signedAt",
declined_at AS "declinedAt",
decline_reason AS "declineReason",
+ signature_meaning AS "signatureMeaning",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM signers
@@ -859,18 +879,29 @@ export async function listCopyRecipientsForEnvelopeId(
async function listSignerCheckSettings(
envelopeId: string,
database: DbExecutor,
-): Promise<Map<string, { hasAccessCode: boolean; requireEmailCode: boolean }>> {
+): Promise<
+ Map<
+ string,
+ {
+ hasAccessCode: boolean;
+ requireEmailCode: boolean;
+ signatureMeaning: SignatureMeaning | null;
+ }
+ >
+> {
const rows = await queryMany<{
hasAccessCode: boolean;
id: string;
requireEmailCode: boolean;
+ signatureMeaning: string | null;
}>(
database,
`
SELECT
id,
access_code_hash IS NOT NULL AS "hasAccessCode",
- require_email_code AS "requireEmailCode"
+ require_email_code AS "requireEmailCode",
+ signature_meaning AS "signatureMeaning"
FROM signers
WHERE envelope_id = $1
`,
@@ -883,6 +914,7 @@ async function listSignerCheckSettings(
{
hasAccessCode: Boolean(row.hasAccessCode),
requireEmailCode: Boolean(row.requireEmailCode),
+ signatureMeaning: parseSignatureMeaning(row.signatureMeaning),
},
]),
);
@@ -1161,7 +1193,12 @@ function buildTimelineDescription(event: AuditEventRecord): string {
case "viewed":
return `Viewed by ${targetLabel}`;
case "signed":
- return `Signed by ${targetLabel}`;
+ return typeof event.metadata?.part11 === "object" &&
+ event.metadata.part11 !== null &&
+ "meaning" in event.metadata.part11 &&
+ typeof event.metadata.part11.meaning === "string"
+ ? `Signed by ${targetLabel} (${signatureMeaningLabel(parseSignatureMeaning(event.metadata.part11.meaning)) ?? event.metadata.part11.meaning}, password given again)`
+ : `Signed by ${targetLabel}`;
case "declined":
return declineReason
? `Declined by ${targetLabel} — ${declineReason}`
@@ -1183,7 +1220,11 @@ function buildTimelineDescription(event: AuditEventRecord): string {
case "completed":
return "Final signed PDF and certificate generated";
case "voided":
- return "Envelope voided by sender";
+ return declineReason
+ ? `Envelope voided by sender — ${declineReason}`
+ : "Envelope voided by sender";
+ case "reauthentication_failed":
+ return `Wrong password given while signing for ${targetLabel}`;
case "deadline_changed":
return typeof event.metadata?.expiresAt === "number"
? `Deadline set to ${formatDeadline(event.metadata.expiresAt)}`
@@ -1320,6 +1361,7 @@ export async function listEnvelopesForUser(
voided_at AS "voidedAt",
expires_at AS "expiresAt",
reminder_interval_days AS "reminderIntervalDays",
+ part11,
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -1466,6 +1508,7 @@ export async function getEnvelopeDetailDataForUser(
? (envelope.reminderIntervalDays ?? null)
: null,
manualReminder,
+ part11: Boolean(envelope.part11),
signers: signerViews,
status: envelope.status,
timeline,
@@ -1489,6 +1532,7 @@ export async function getDraftSignerStepDataForUser(
return {
copyRecipients: await listCopyRecipientsForEnvelopeId(envelopeId, database),
envelopeId,
+ part11Mode: (await readStoredSettings(database))?.part11Mode ?? false,
signers: (await listSignersForEnvelopeId(envelopeId, database)).map(
(signer) => ({
email: signer.email,
@@ -1497,6 +1541,7 @@ export async function getDraftSignerStepDataForUser(
name: signer.name,
order: signer.signOrder,
requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,
+ signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,
}),
),
status: envelope.status,
@@ -1829,6 +1874,40 @@ export async function sendDraftEnvelope(
throw new EnvelopeMutationError(choiceProblem, 400);
}
+ // In Part 11 mode each signer signs with their own verified account, and
+ // the envelope keeps that rule even if the mode is turned off later.
+ const part11 = (await readStoredSettings(database))?.part11Mode ?? false;
+ const part11SignerAccounts = new Map<string, string>();
+
+ if (part11) {
+ const checks = await listSignerCheckSettings(envelopeId, database);
+ const accounts = await findSignerAccounts(
+ signers.map((signer) => signer.email),
+ database,
+ );
+
+ for (const signer of signers) {
+ const account = accounts.get(signer.email.toLowerCase());
+ const problem = describePart11SignerProblem(
+ {
+ email: signer.email,
+ name: signer.name,
+ signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,
+ },
+ account,
+ );
+
+ if (problem || !account) {
+ throw new EnvelopeMutationError(
+ problem ?? "A signer cannot sign in Part 11 mode.",
+ 400,
+ );
+ }
+
+ part11SignerAccounts.set(signer.id, account.userId);
+ }
+ }
+
const firstSigner = signers[0];
if (!firstSigner) {
@@ -1919,12 +1998,39 @@ export async function sendDraftEnvelope(
signed_at = NULL,
declined_at = NULL,
decline_reason = NULL,
+ user_id = NULL,
updated_at = $1
WHERE envelope_id = $2
`,
[sentAt, envelopeId],
);
+ if (part11) {
+ await tx.query(`UPDATE envelopes SET part11 = true WHERE id = $1`, [
+ envelopeId,
+ ]);
+
+ for (const [signerId, accountId] of part11SignerAccounts) {
+ const bound = await tx.query(
+ `
+ UPDATE signers
+ SET user_id = $1
+ WHERE id = $2
+ AND envelope_id = $3
+ AND signature_meaning IS NOT NULL
+ `,
+ [accountId, signerId, envelopeId],
+ );
+
+ if (bound.rowCount !== 1) {
+ throw new EnvelopeMutationError(
+ "This envelope was changed while it was being sent. Check it and send it again.",
+ 409,
+ );
+ }
+ }
+ }
+
const updatedSigner = await tx.query(
`
UPDATE signers
@@ -1970,6 +2076,7 @@ export async function sendDraftEnvelope(
reminderIntervalDays: input.reminderIntervalDays ?? null,
permittedUseConfirmed: true,
permittedUseVersion: PERMITTED_USE_VERSION,
+ ...(part11 ? { part11: true } : {}),
signerEmail: firstSigner.email,
signerId: firstSigner.id,
signerName: firstSigner.name,
@@ -2009,6 +2116,7 @@ export async function sendDraftEnvelope(
sent_at = NULL,
expires_at = NULL,
reminder_interval_days = NULL,
+ part11 = false,
updated_at = $1
WHERE id = $2
AND user_id = $3
@@ -2030,6 +2138,7 @@ export async function sendDraftEnvelope(
signed_at = NULL,
declined_at = NULL,
decline_reason = NULL,
+ user_id = NULL,
updated_at = $1
WHERE envelope_id = $2
`,
@@ -2231,6 +2340,15 @@ export async function voidSentEnvelope(
throw new EnvelopeMutationError("Only sent envelopes can be voided.", 409);
}
+ const reason = input.reason?.trim().slice(0, 1000) || null;
+
+ if (envelope.part11 && !reason) {
+ throw new EnvelopeMutationError(
+ "Give a reason for voiding. Part 11 records keep it in the audit trail.",
+ 400,
+ );
+ }
+
const signers = await listSignersForEnvelopeId(envelopeId, database);
const notifiedSigners = signers.filter(
(signer) => signer.status === "notified",
@@ -2256,14 +2374,20 @@ export async function voidSentEnvelope(
event: "voided",
id: randomUUID(),
ipAddress: input.ipAddress ?? null,
- metadata: currentSigner
- ? {
- signerEmail: currentSigner.email,
- signerId: currentSigner.id,
- signerName: currentSigner.name,
- signerOrder: currentSigner.signOrder,
- }
- : null,
+ metadata:
+ currentSigner || reason
+ ? {
+ ...(currentSigner
+ ? {
+ signerEmail: currentSigner.email,
+ signerId: currentSigner.id,
+ signerName: currentSigner.name,
+ signerOrder: currentSigner.signOrder,
+ }
+ : {}),
+ ...(reason ? { reason } : {}),
+ }
+ : null,
userAgent: input.userAgent ?? null,
};
const storageIdentity = {
@@ -2723,6 +2847,7 @@ export async function replaceDraftEnvelopeSigners(
id: persistedSignerId,
name: signer.name,
requireEmailCode: signer.requireEmailCode,
+ signatureMeaning: signer.signatureMeaning,
signOrder: index + 1,
};
});
@@ -2762,7 +2887,8 @@ export async function replaceDraftEnvelopeSigners(
sign_order = $3,
updated_at = $4,
access_code_hash = CASE WHEN $7::boolean THEN $8 ELSE access_code_hash END,
- require_email_code = COALESCE($9, require_email_code)
+ require_email_code = COALESCE($9, require_email_code),
+ signature_meaning = CASE WHEN $10::boolean THEN $11 ELSE signature_meaning END
WHERE id = $5 AND envelope_id = $6
`,
[
@@ -2775,6 +2901,8 @@ export async function replaceDraftEnvelopeSigners(
signer.accessCodeHash !== undefined,
signer.accessCodeHash ?? null,
signer.requireEmailCode ?? null,
+ signer.signatureMeaning !== undefined,
+ signer.signatureMeaning ?? null,
],
);
} else {
@@ -2798,9 +2926,10 @@ export async function replaceDraftEnvelopeSigners(
created_at,
updated_at,
access_code_hash,
- require_email_code
+ require_email_code,
+ signature_meaning
) VALUES (
- $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9
+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10
)
`,
[
@@ -2813,6 +2942,7 @@ export async function replaceDraftEnvelopeSigners(
updatedAt,
signer.accessCodeHash ?? null,
signer.requireEmailCode ?? false,
+ signer.signatureMeaning ?? null,
],
);
}
@@ -2873,6 +3003,7 @@ export async function replaceDraftEnvelopeSigners(
id: signer.id,
name: signer.name,
requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,
+ signatureMeaning: checks.get(signer.id)?.signatureMeaning ?? null,
signOrder: signer.signOrder,
}),
),
diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.ts
index 1f13428..452af04 100644
--- a/src/lib/organization-settings.test.ts
+++ b/src/lib/organization-settings.test.ts
@@ -14,6 +14,7 @@ const stored: AppSettings = {
emailReadyAt: null,
logoVersion: null,
organizationName: "Acme Corp",
+ part11Mode: false,
privacyUrl: null,
retentionDays: null,
senderAddress: "[email protected]",
diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.ts
index 8f5e2b0..2972a67 100644
--- a/src/lib/organization-settings.ts
+++ b/src/lib/organization-settings.ts
@@ -40,6 +40,8 @@ export type OrganizationSettingsView = {
/** "#rrggbb", or empty for the default color. */
brandColor: string;
hosted: boolean;
+ /** Part 11 mode is on: the retention period cannot be set. */
+ part11Mode: boolean;
/** Where the logo is served, or null when there is none. */
logoUrl: string | null;
organizationName: string;
@@ -66,6 +68,7 @@ export function toOrganizationSettingsView(
? null
: buildBrandLogoPath(settings.logoVersion),
organizationName: settings.organizationName ?? "",
+ part11Mode: settings.part11Mode,
privacyUrl: settings.privacyUrl ?? "",
retentionDays:
settings.retentionDays === null ? "" : String(settings.retentionDays),
@@ -234,6 +237,12 @@ export async function updateOrganizationSettings(
fieldErrors.supportAddress = FIELD_MESSAGES.supportAddress;
}
+ // Part 11 records are never deleted on a timer.
+ if (current.part11Mode && input.retentionDays !== null) {
+ fieldErrors.retentionDays =
+ "Part 11 mode is on, so finished envelopes are kept until you delete them. Leave this empty.";
+ }
+
if (Object.keys(fieldErrors).length > 0) {
throw new OrganizationSettingsError(fieldErrors);
}
@@ -261,3 +270,34 @@ export async function updateOrganizationSettings(
database,
);
}
+
+const AUDITED_SETTINGS = [
+ "allowedEmailDomains",
+ "brandColor",
+ "organizationName",
+ "privacyUrl",
+ "retentionDays",
+ "senderAddress",
+ "signupMode",
+ "supportAddress",
+ "termsUrl",
+] as const satisfies readonly (keyof AppSettings)[];
+
+/** What changed between two versions of the settings, for the audit trail. */
+export function diffSettings(
+ before: AppSettings | null,
+ after: AppSettings,
+): Record<string, { from: unknown; to: unknown }> {
+ const changes: Record<string, { from: unknown; to: unknown }> = {};
+
+ for (const key of AUDITED_SETTINGS) {
+ const from = before ? before[key] : null;
+ const to = after[key];
+
+ if (JSON.stringify(from) !== JSON.stringify(to)) {
+ changes[key] = { from, to };
+ }
+ }
+
+ return changes;
+}
diff --git a/src/lib/part11.dbtest.ts b/src/lib/part11.dbtest.ts
new file mode 100644
index 0000000..ee9af8f
--- /dev/null
+++ b/src/lib/part11.dbtest.ts
@@ -0,0 +1,275 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import { eraseSignerData } from "./signer-data.ts";
+import {
+ checkSigningCredentials,
+ MAX_SIGNING_PASSWORD_ATTEMPTS,
+ type PasswordVerifier,
+} from "./part11.ts";
+import type {
+ EmailService,
+ TransactionalEmailMessage,
+} from "./services/email.ts";
+import {
+ recordSystemAuditEvent,
+ verifySystemAuditChain,
+} from "./services/system-audit.ts";
+
+// Part 11 mode against a real Postgres: the install audit chain and the
+// password check at signing, with its lock after five wrong passwords.
+// Run with `npm run test:db`.
+
+let database: pg.Pool;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+});
+
+after(async () => {
+ await database.query(`delete from account where "userId" = any($1)`, [
+ createdUsers,
+ ]);
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+});
+
+async function createUser(role: "admin" | "user" = "user") {
+ const id = randomUUID();
+
+ createdUsers.push(id);
+ await database.query(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ values ($1, $2, $3, $4, true)
+ `,
+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`, role],
+ );
+ await database.query(
+ `
+ insert into account (id, "accountId", "providerId", "userId", password, "createdAt", "updatedAt")
+ values ($1, $2, 'credential', $2, 'stored-hash', now(), now())
+ `,
+ [randomUUID(), id],
+ );
+
+ return { email: `${id}@example.test`, id };
+}
+
+// The real check runs Better Auth's hash. Here the stored hash is a stand-in
+// and only "right" passes.
+const verifyPassword: PasswordVerifier = async ({ hash, password }) =>
+ hash === "stored-hash" && password === "right";
+
+function recordingEmailService() {
+ const sent: TransactionalEmailMessage[] = [];
+ const service: EmailService = {
+ async send(message) {
+ sent.push(message);
+ return { accepted: [message.to], messageId: "m-1", rejected: [] };
+ },
+ async sendBatch() {
+ throw new Error("not used");
+ },
+ };
+
+ return { sent, service };
+}
+
+test("the install audit trail is one hash chain that shows a changed row", async () => {
+ const before = await verifySystemAuditChain(database);
+
+ assert.equal(before.ok, true);
+
+ const first = await recordSystemAuditEvent(
+ {
+ actorEmail: "[email protected]",
+ event: "settings_changed",
+ metadata: { changes: { x: 1 } },
+ },
+ database,
+ );
+ const second = await recordSystemAuditEvent(
+ {
+ actorEmail: "[email protected]",
+ event: "part11_mode_changed",
+ metadata: { to: true },
+ },
+ database,
+ );
+
+ assert.equal(second.sequence, first.sequence + 1);
+ assert.deepEqual(await verifySystemAuditChain(database), {
+ events: before.events + 2,
+ ok: true,
+ });
+
+ await database.query(
+ `update system_audit_events set metadata = '{"to": false}' where id = $1`,
+ [second.id],
+ );
+
+ try {
+ assert.deepEqual(await verifySystemAuditChain(database), {
+ brokenAtSequence: second.sequence,
+ events: before.events + 2,
+ ok: false,
+ });
+ } finally {
+ await database.query(
+ `update system_audit_events set metadata = '{"to": true}' where id = $1`,
+ [second.id],
+ );
+ }
+
+ assert.equal((await verifySystemAuditChain(database)).ok, true);
+});
+
+test("a right password signs and clears earlier misses", async () => {
+ const user = await createUser();
+ const options = { database, verifyPassword };
+
+ assert.deepEqual(
+ await checkSigningCredentials(
+ { email: user.email, password: "wrong", userId: user.id },
+ options,
+ ),
+ {
+ attemptsLeft: MAX_SIGNING_PASSWORD_ATTEMPTS - 1,
+ locked: false,
+ ok: false,
+ },
+ );
+ assert.deepEqual(
+ await checkSigningCredentials(
+ { email: user.email.toUpperCase(), password: "right", userId: user.id },
+ options,
+ ),
+ { ok: true },
+ );
+
+ const row = await database.query(
+ `select signing_failed_attempts from "user" where id = $1`,
+ [user.id],
+ );
+
+ assert.equal(row.rows[0].signing_failed_attempts, 0);
+});
+
+test("a right password with someone else's email address is a miss", async () => {
+ const user = await createUser();
+
+ assert.equal(
+ (
+ await checkSigningCredentials(
+ { email: "[email protected]", password: "right", userId: user.id },
+ { database, verifyPassword },
+ )
+ ).ok,
+ false,
+ );
+});
+
+test("five wrong passwords lock signing, tell the administrators and are audited", async () => {
+ const admin = await createUser("admin");
+ const user = await createUser();
+ const { sent, service } = recordingEmailService();
+ const options = { database, emailService: service, verifyPassword };
+
+ for (
+ let attempt = 1;
+ attempt <= MAX_SIGNING_PASSWORD_ATTEMPTS;
+ attempt += 1
+ ) {
+ const result = await checkSigningCredentials(
+ { email: user.email, password: "wrong", userId: user.id },
+ options,
+ );
+
+ assert.deepEqual(result, {
+ attemptsLeft: MAX_SIGNING_PASSWORD_ATTEMPTS - attempt,
+ locked: attempt === MAX_SIGNING_PASSWORD_ATTEMPTS,
+ ok: false,
+ });
+ }
+
+ // Locked: even the right password is refused now.
+ assert.deepEqual(
+ await checkSigningCredentials(
+ { email: user.email, password: "right", userId: user.id },
+ options,
+ ),
+ { attemptsLeft: 0, locked: true, ok: false },
+ );
+
+ const alerts = sent.filter(
+ (message) => message.template === "signing_lock_alert",
+ );
+
+ assert.ok(alerts.some((message) => message.to === admin.email));
+
+ const events = await database.query(
+ `
+ select event from system_audit_events
+ where target_user_id = $1 order by sequence
+ `,
+ [user.id],
+ );
+
+ assert.deepEqual(
+ events.rows.map((row) => row.event),
+ [
+ ...Array(MAX_SIGNING_PASSWORD_ATTEMPTS - 1).fill(
+ "reauthentication_failed",
+ ),
+ "signing_locked",
+ ],
+ );
+ assert.equal((await verifySystemAuditChain(database)).ok, true);
+});
+
+test("a data request does not erase a finished Part 11 envelope", async () => {
+ const sender = await createUser();
+ const envelopeId = randomUUID();
+ const signerEmail = `${randomUUID()}@example.test`;
+
+ await database.query(
+ `
+ insert into envelopes (
+ id, user_id, title, status, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at,
+ completed_at, part11
+ ) values ($1, $2, 'Batch record', 'completed', $3, 'batch.pdf', 4, 1,
+ $4, 1, 2, true)
+ `,
+ [envelopeId, sender.id, `test/${envelopeId}.pdf`, "a".repeat(64)],
+ );
+ await database.query(
+ `
+ insert into signers (id, envelope_id, name, email, sign_order, status, signature_meaning)
+ values ($1, $2, 'Signer', $3, 1, 'signed', 'approval')
+ `,
+ [randomUUID(), envelopeId, signerEmail],
+ );
+
+ const result = await eraseSignerData(signerEmail, signerEmail, database);
+
+ assert.equal(result.deletedEnvelopes, 0);
+ assert.deepEqual(result.keptPart11, [
+ { id: envelopeId, title: "Batch record" },
+ ]);
+
+ const kept = await database.query(`select 1 from envelopes where id = $1`, [
+ envelopeId,
+ ]);
+
+ assert.equal(kept.rowCount, 1);
+ await database.query(`delete from envelopes where id = $1`, [envelopeId]);
+});
diff --git a/src/lib/part11.test.ts b/src/lib/part11.test.ts
new file mode 100644
index 0000000..fe7ddfb
--- /dev/null
+++ b/src/lib/part11.test.ts
@@ -0,0 +1,126 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { toCsv } from "./audit-export.ts";
+import { describePart11SignerProblem } from "./part11.ts";
+import { computeSystemAuditRowHash } from "./services/system-audit.ts";
+import {
+ buildSignatureManifestation,
+ parseSignatureMeaning,
+} from "./signature-meanings.ts";
+import { requiredSignerChecks } from "./signer-checks.ts";
+
+// Part 11 mode's pure parts: the line printed beside a signature, the CSV
+// export, the reasons a send is refused and the install audit hash.
+
+test("the manifestation gives the name, the UTC time and the meaning", () => {
+ assert.equal(
+ buildSignatureManifestation({
+ name: "Ada Lovelace",
+ signatureMeaning: "approval",
+ signedAt: Date.UTC(2026, 10, 13, 9, 5, 7) / 1000,
+ }),
+ "Signed by Ada Lovelace | 2026-11-13 09:05:07 UTC | Meaning: Approval",
+ );
+});
+
+test("only the four Part 11 meanings parse", () => {
+ assert.equal(parseSignatureMeaning("review"), "review");
+ assert.equal(parseSignatureMeaning("authorship"), "authorship");
+ assert.equal(parseSignatureMeaning("Approval"), null);
+ assert.equal(parseSignatureMeaning(undefined), null);
+});
+
+test("a CSV cell never runs as a spreadsheet formula and quotes are escaped", () => {
+ const csv = toCsv([
+ ['=HYPERLINK("x")', "+1", "-2", "@cmd", "plain"],
+ ['say "hi", then', { a: 1 }, null],
+ ]);
+
+ assert.equal(
+ csv,
+ `"'=HYPERLINK(""x"")",'+1,'-2,'@cmd,plain\r\n"say ""hi"", then","{""a"":1}",\r\n`,
+ );
+});
+
+test("a send is refused for each missing Part 11 condition, in order", () => {
+ const signer = { email: "[email protected]", name: "Ada" };
+ const ready = {
+ email: "[email protected]",
+ emailVerified: true,
+ identityVerifiedAt: 1,
+ name: "Ada",
+ signingLockedAt: null,
+ userId: "u1",
+ };
+
+ assert.match(
+ describePart11SignerProblem(signer, undefined) ?? "",
+ /needs an account/,
+ );
+ assert.match(
+ describePart11SignerProblem(signer, { ...ready, emailVerified: false }) ??
+ "",
+ /not confirmed their email/,
+ );
+ assert.match(
+ describePart11SignerProblem(signer, {
+ ...ready,
+ identityVerifiedAt: null,
+ }) ?? "",
+ /confirm Ada's identity/,
+ );
+ assert.match(
+ describePart11SignerProblem(signer, { ...ready, signingLockedAt: 5 }) ?? "",
+ /locked for signing/,
+ );
+ assert.match(
+ describePart11SignerProblem(signer, ready) ?? "",
+ /Choose what Ada's signature means/,
+ );
+ assert.equal(
+ describePart11SignerProblem(
+ { ...signer, signatureMeaning: "approval" },
+ ready,
+ ),
+ null,
+ );
+});
+
+test("a signer bound to an account must pass the account check first", () => {
+ assert.deepEqual(
+ requiredSignerChecks({
+ accessCodeHash: null,
+ accountUserId: "u1",
+ requireEmailCode: true,
+ }),
+ ["account", "email_code"],
+ );
+});
+
+test("the install audit hash changes when any field or the previous hash does", () => {
+ const fields = {
+ actorEmail: "[email protected]",
+ actorUserId: "a1",
+ createdAt: 100,
+ event: "role_changed" as const,
+ id: "e1",
+ ipAddress: null,
+ metadata: { from: "user", to: "admin" },
+ sequence: 1,
+ targetUserId: "u1",
+ userAgent: null,
+ };
+ const hash = computeSystemAuditRowHash(null, fields);
+
+ assert.match(hash, /^[0-9a-f]{64}$/);
+ assert.equal(computeSystemAuditRowHash(null, { ...fields }), hash);
+ assert.notEqual(computeSystemAuditRowHash("x", fields), hash);
+ assert.notEqual(
+ computeSystemAuditRowHash(null, {
+ ...fields,
+ metadata: { from: "user", to: "user" },
+ }),
+ hash,
+ );
+});
diff --git a/src/lib/part11.ts b/src/lib/part11.ts
new file mode 100644
index 0000000..aa8b647
--- /dev/null
+++ b/src/lib/part11.ts
@@ -0,0 +1,534 @@
+import {
+ type DbExecutor,
+ type DbPool,
+ getDb,
+ queryMany,
+ queryOne,
+ withTransaction,
+} from "./db/connection.ts";
+import { SIGNUDOC_NAME } from "./branding.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
+import { recordSystemAuditEvent } from "./services/system-audit.ts";
+import { getBranding, getSettings } from "./settings.ts";
+import { type SignatureMeaning } from "./types/domain.ts";
+
+// Part 11 mode: the controls 21 CFR Part 11 asks of a system that keeps
+// signed electronic records, for installs that turn it on.
+//
+// - Every signer signs with their own account on this install (11.100(a)),
+// and an administrator has recorded that they checked who the person is
+// (11.100(b)).
+// - The signer gives their email address and password to open the document
+// and again for each signature (11.200(a)). Five wrong passwords lock the
+// account for signing until an administrator unlocks it, and the
+// administrators are told (11.300(d)).
+// - Each signature says what it means: approval, review, responsibility or
+// authorship, printed beside it with the signer's name and the time
+// (11.50).
+// - Finished envelopes are never deleted by the retention period or a data
+// request, and a void needs a reason.
+//
+// Whether an install meets Part 11 depends on how it is validated and run.
+// This is the software's part only.
+
+export const MAX_SIGNING_PASSWORD_ATTEMPTS = 5;
+
+export {
+ parseSignatureMeaning,
+ SIGNATURE_MEANING_DETAILS,
+ signatureMeaningLabel,
+} from "./signature-meanings.ts";
+
+export class Part11Error extends Error {
+ readonly statusCode: number;
+
+ constructor(message: string, statusCode: number) {
+ super(message);
+ this.name = "Part11Error";
+ this.statusCode = statusCode;
+ }
+}
+
+/** Whether the install is in Part 11 mode right now. */
+export async function isPart11ModeOn(): Promise<boolean> {
+ return (await getSettings()).part11Mode;
+}
+
+export type Part11SignerAccount = {
+ email: string;
+ emailVerified: boolean;
+ identityVerifiedAt: number | null;
+ name: string;
+ signingLockedAt: number | null;
+ userId: string;
+};
+
+/** The accounts these addresses belong to, keyed by lower-case address. */
+export async function findSignerAccounts(
+ emails: readonly string[],
+ database: DbExecutor = getDb(),
+): Promise<Map<string, Part11SignerAccount>> {
+ if (emails.length === 0) {
+ return new Map();
+ }
+
+ const rows = await queryMany<Part11SignerAccount>(
+ database,
+ `
+ SELECT
+ u.id AS "userId",
+ u.email,
+ u.name,
+ u."emailVerified" AS "emailVerified",
+ u.identity_verified_at AS "identityVerifiedAt",
+ u.signing_locked_at AS "signingLockedAt"
+ FROM "user" u
+ WHERE lower(u.email) = ANY($1)
+ `,
+ [emails.map((email) => email.toLowerCase())],
+ );
+
+ return new Map(rows.map((row) => [row.email.toLowerCase(), row]));
+}
+
+/**
+ * Why this signer cannot sign a Part 11 envelope, or null when they can.
+ * Said in words the sender can act on.
+ */
+export function describePart11SignerProblem(
+ signer: {
+ email: string;
+ name: string;
+ signatureMeaning?: SignatureMeaning | null;
+ },
+ account: Part11SignerAccount | undefined,
+): string | null {
+ if (!account) {
+ return `${signer.name} (${signer.email}) needs an account on this site before they can sign. Part 11 mode only lets people sign with their own account.`;
+ }
+
+ if (!account.emailVerified) {
+ return `${signer.name} has not confirmed their email address yet.`;
+ }
+
+ if (account.identityVerifiedAt === null) {
+ return `An administrator has to confirm ${signer.name}'s identity under Settings, People before they can sign.`;
+ }
+
+ if (account.signingLockedAt !== null) {
+ return `${signer.name}'s account is locked for signing after too many wrong passwords. An administrator can unlock it under Settings, People.`;
+ }
+
+ if (!signer.signatureMeaning) {
+ return `Choose what ${signer.name}'s signature means (approval, review, responsibility or authorship).`;
+ }
+
+ return null;
+}
+
+type Actor = {
+ email: string;
+ ipAddress?: string | null;
+ userAgent?: string | null;
+ userId: string;
+};
+
+async function assertActorIsAdmin(actor: Actor, tx: DbExecutor) {
+ const row = await queryOne<{ role: string }>(
+ tx,
+ `SELECT role FROM "user" WHERE id = $1`,
+ [actor.userId],
+ );
+
+ if (row?.role !== "admin") {
+ throw new Part11Error("Only an administrator can do this.", 403);
+ }
+}
+
+type TargetRow = {
+ email: string;
+ emailVerified: boolean;
+ identityVerifiedAt: number | null;
+ name: string;
+ signingLockedAt: number | null;
+};
+
+async function lockTarget(
+ targetUserId: string,
+ tx: DbExecutor,
+): Promise<TargetRow> {
+ const target = await queryOne<TargetRow>(
+ tx,
+ `
+ SELECT
+ email,
+ name,
+ "emailVerified" AS "emailVerified",
+ identity_verified_at AS "identityVerifiedAt",
+ signing_locked_at AS "signingLockedAt"
+ FROM "user"
+ WHERE id = $1
+ FOR UPDATE
+ `,
+ [targetUserId],
+ );
+
+ if (!target) {
+ throw new Part11Error("That account no longer exists.", 404);
+ }
+
+ return target;
+}
+
+/**
+ * Records that an administrator checked who this person is (for example
+ * against an ID document or an HR record), or takes that back. The note
+ * says how, and goes in the install's audit trail with the change.
+ */
+export async function setIdentityVerification(
+ actor: Actor,
+ targetUserId: string,
+ input: { note?: string | null; verified: boolean },
+ database: DbPool = getDb(),
+): Promise<void> {
+ const note = input.note?.trim().slice(0, 500) || null;
+
+ if (input.verified && !note) {
+ throw new Part11Error(
+ "Say how you checked this person's identity, for example the document you saw.",
+ 400,
+ );
+ }
+
+ await withTransaction(async (tx) => {
+ await assertActorIsAdmin(actor, tx);
+
+ const target = await lockTarget(targetUserId, tx);
+
+ if (input.verified && !target.emailVerified) {
+ throw new Part11Error(
+ "This person has not confirmed their email address yet.",
+ 409,
+ );
+ }
+
+ const now = Math.floor(Date.now() / 1000);
+
+ await tx.query(
+ `
+ UPDATE "user"
+ SET
+ identity_verified_at = $1,
+ identity_verified_by = $2,
+ identity_verification_note = $3,
+ "updatedAt" = now()
+ WHERE id = $4
+ `,
+ input.verified
+ ? [now, actor.userId, note, targetUserId]
+ : [null, null, null, targetUserId],
+ );
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ createdAt: now,
+ event: input.verified
+ ? "identity_verified"
+ : "identity_verification_revoked",
+ ipAddress: actor.ipAddress ?? null,
+ metadata: {
+ note,
+ previousVerifiedAt: target.identityVerifiedAt,
+ targetEmail: target.email,
+ targetName: target.name,
+ },
+ targetUserId,
+ userAgent: actor.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+}
+
+/** Lets a person whose wrong passwords locked them sign again. */
+export async function unlockSigning(
+ actor: Actor,
+ targetUserId: string,
+ database: DbPool = getDb(),
+): Promise<void> {
+ await withTransaction(async (tx) => {
+ await assertActorIsAdmin(actor, tx);
+
+ const target = await lockTarget(targetUserId, tx);
+
+ if (target.signingLockedAt === null) {
+ return;
+ }
+
+ await tx.query(
+ `
+ UPDATE "user"
+ SET signing_locked_at = NULL, signing_failed_attempts = 0
+ WHERE id = $1
+ `,
+ [targetUserId],
+ );
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "signing_unlocked",
+ ipAddress: actor.ipAddress ?? null,
+ metadata: {
+ lockedAt: target.signingLockedAt,
+ targetEmail: target.email,
+ targetName: target.name,
+ },
+ targetUserId,
+ userAgent: actor.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+}
+
+/** Checks a password against an account's stored hash. */
+export type PasswordVerifier = (input: {
+ hash: string;
+ password: string;
+}) => Promise<boolean>;
+
+async function defaultPasswordVerifier(input: {
+ hash: string;
+ password: string;
+}): Promise<boolean> {
+ // The same hashing Better Auth signs people in with. Loaded here, not at
+ // the top, so this module can be used where the auth server is not set up.
+ const { getAuth } = await import("./auth/server.ts");
+ const context = await getAuth().$context;
+
+ return context.password.verify(input);
+}
+
+export type SigningPasswordResult =
+ { ok: true } | { attemptsLeft: number; locked: boolean; ok: false };
+
+/**
+ * The two parts of a Part 11 signature: the account's email address (its
+ * identification code) and its password. Wrong answers count against the
+ * account, and the fifth in a row locks it for signing and tells the
+ * administrators. A right answer clears the count.
+ */
+export async function checkSigningCredentials(
+ input: {
+ email: string;
+ ipAddress?: string | null;
+ password: string;
+ userAgent?: string | null;
+ userId: string;
+ },
+ {
+ database = getDb(),
+ emailService,
+ verifyPassword = defaultPasswordVerifier,
+ }: {
+ database?: DbPool;
+ emailService?: EmailService;
+ verifyPassword?: PasswordVerifier;
+ } = {},
+): Promise<SigningPasswordResult> {
+ const outcome = await withTransaction(async (tx) => {
+ const account = await queryOne<{
+ email: string;
+ failedAttempts: number;
+ hash: string | null;
+ lockedAt: number | null;
+ name: string;
+ }>(
+ tx,
+ `
+ SELECT
+ u.email,
+ u.name,
+ u.signing_failed_attempts AS "failedAttempts",
+ u.signing_locked_at AS "lockedAt",
+ (
+ SELECT a.password FROM account a
+ WHERE a."userId" = u.id AND a."providerId" = 'credential'
+ LIMIT 1
+ ) AS hash
+ FROM "user" u
+ WHERE u.id = $1
+ FOR UPDATE OF u
+ `,
+ [input.userId],
+ );
+
+ if (!account) {
+ return { attemptsLeft: 0, locked: true, ok: false as const };
+ }
+
+ if (account.lockedAt !== null) {
+ return { attemptsLeft: 0, locked: true, ok: false as const };
+ }
+
+ const emailMatches =
+ input.email.trim().toLowerCase() === account.email.toLowerCase();
+ const passwordMatches =
+ account.hash !== null && input.password.length > 0
+ ? await verifyPassword({ hash: account.hash, password: input.password })
+ : false;
+
+ if (emailMatches && passwordMatches) {
+ if (account.failedAttempts > 0) {
+ await tx.query(
+ `UPDATE "user" SET signing_failed_attempts = 0 WHERE id = $1`,
+ [input.userId],
+ );
+ }
+
+ return { ok: true as const };
+ }
+
+ const failedAttempts = account.failedAttempts + 1;
+ const locked = failedAttempts >= MAX_SIGNING_PASSWORD_ATTEMPTS;
+ const now = Math.floor(Date.now() / 1000);
+
+ await tx.query(
+ `
+ UPDATE "user"
+ SET signing_failed_attempts = $1, signing_locked_at = $2
+ WHERE id = $3
+ `,
+ [failedAttempts, locked ? now : null, input.userId],
+ );
+ await recordSystemAuditEvent(
+ {
+ actorEmail: account.email,
+ actorUserId: input.userId,
+ createdAt: now,
+ event: locked ? "signing_locked" : "reauthentication_failed",
+ ipAddress: input.ipAddress ?? null,
+ metadata: { failedAttempts },
+ targetUserId: input.userId,
+ userAgent: input.userAgent ?? null,
+ },
+ tx,
+ );
+
+ return {
+ account,
+ attemptsLeft: Math.max(0, MAX_SIGNING_PASSWORD_ATTEMPTS - failedAttempts),
+ locked,
+ ok: false as const,
+ };
+ }, database);
+
+ if (
+ !outcome.ok &&
+ "account" in outcome &&
+ outcome.account &&
+ outcome.locked
+ ) {
+ await alertAdministrators(
+ { email: outcome.account.email, name: outcome.account.name },
+ { database, emailService },
+ );
+ }
+
+ if (outcome.ok) {
+ return { ok: true };
+ }
+
+ return {
+ attemptsLeft: outcome.attemptsLeft,
+ locked: outcome.locked,
+ ok: false,
+ };
+}
+
+/** Tells every administrator that an account was locked for signing. */
+async function alertAdministrators(
+ person: { email: string; name: string },
+ {
+ database,
+ emailService,
+ }: { database: DbExecutor; emailService?: EmailService },
+): Promise<void> {
+ try {
+ const admins = await queryMany<{ email: string }>(
+ database,
+ `SELECT email FROM "user" WHERE role = 'admin'`,
+ );
+ // The alert goes out even when the branding cannot be read.
+ const productName = await getBranding()
+ .then((branding) => branding.productName)
+ .catch(() => SIGNUDOC_NAME);
+ const service = emailService ?? createEmailService();
+ const textBody = [
+ `${person.name} <${person.email}> gave the wrong password ${MAX_SIGNING_PASSWORD_ATTEMPTS} times in a row while signing on ${productName}.`,
+ "",
+ "Their account can no longer sign until an administrator unlocks it under Settings, People.",
+ "If this was not them, someone may be trying to sign in their name. Check with them before unlocking.",
+ ].join("\n");
+
+ for (const admin of admins) {
+ await service.send({
+ subject: `Signing locked for ${person.name}`,
+ template: "signing_lock_alert",
+ textBody,
+ to: admin.email,
+ });
+ }
+ } catch (error) {
+ // The lock is in place and in the audit trail; the email is a courtesy.
+ console.error("Failed to tell administrators about a signing lock:", error);
+ }
+}
+
+/**
+ * Turns Part 11 mode on or off for the install. Turning it on needs the
+ * retention period off first, because Part 11 records are kept for as long
+ * as the regulations that apply to them say, not by a timer here.
+ */
+export async function setPart11Mode(
+ actor: Actor,
+ enabled: boolean,
+ database: DbPool = getDb(),
+): Promise<void> {
+ const { readStoredSettings, saveSettings } = await import("./settings.ts");
+
+ await withTransaction(async (tx) => {
+ await assertActorIsAdmin(actor, tx);
+ // Settings are one row; holding it keeps two changes from crossing.
+ await tx.query(`SELECT id FROM app_settings WHERE id FOR UPDATE`);
+
+ const current = await readStoredSettings(tx);
+ const wasEnabled = current?.part11Mode ?? false;
+
+ if (wasEnabled === enabled) {
+ return;
+ }
+
+ if (enabled && current?.retentionDays != null) {
+ throw new Part11Error(
+ "Turn off the retention period under Organization first. Part 11 records are kept for as long as the rules that apply to them require.",
+ 409,
+ );
+ }
+
+ await saveSettings({ part11Mode: enabled }, tx);
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "part11_mode_changed",
+ ipAddress: actor.ipAddress ?? null,
+ metadata: { from: wasEnabled, to: enabled },
+ userAgent: actor.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+}
diff --git a/src/lib/people.ts b/src/lib/people.ts
index 61fb9ab..006a640 100644
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@ -6,6 +6,7 @@ import {
queryOne,
withTransaction,
} from "./db/connection.ts";
+import { recordSystemAuditEvent } from "./services/system-audit.ts";
// The accounts on this install and who among them is an administrator.
//
@@ -28,8 +29,13 @@ export type Person = {
email: string;
emailVerified: boolean;
id: string;
+ /** When an administrator confirmed who this is, for Part 11 signing. */
+ identityVerifiedAt: number | null;
+ identityVerificationNote: string | null;
name: string;
role: PersonRole;
+ /** When wrong passwords at signing locked the account for signing. */
+ signingLockedAt: number | null;
};
export type PeopleList = {
@@ -57,8 +63,11 @@ type PersonRow = {
email: string;
emailVerified: boolean;
id: string;
+ identityVerificationNote: string | null;
+ identityVerifiedAt: number | null;
name: string;
role: string;
+ signingLockedAt: number | null;
};
const PERSON_COLUMNS = `
@@ -68,6 +77,9 @@ const PERSON_COLUMNS = `
u.role,
u."emailVerified" AS "emailVerified",
u."createdAt" AS "createdAt",
+ u.identity_verified_at AS "identityVerifiedAt",
+ u.identity_verification_note AS "identityVerificationNote",
+ u.signing_locked_at AS "signingLockedAt",
EXISTS (
SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id
) AS closing
@@ -80,8 +92,11 @@ function mapPerson(row: PersonRow): Person {
email: row.email,
emailVerified: row.emailVerified,
id: row.id,
+ identityVerificationNote: row.identityVerificationNote ?? null,
+ identityVerifiedAt: row.identityVerifiedAt ?? null,
name: row.name,
role: row.role === "admin" ? "admin" : "user",
+ signingLockedAt: row.signingLockedAt ?? null,
};
}
@@ -190,9 +205,9 @@ export async function setPersonRole(
return withTransaction(async (tx) => {
await tx.query("SELECT pg_advisory_xact_lock($1)", [ROLE_CHANGE_LOCK_ID]);
- const actor = await queryOne<{ role: string }>(
+ const actor = await queryOne<{ email: string; role: string }>(
tx,
- `SELECT u.role FROM "user" u WHERE u.id = $1`,
+ `SELECT u.role, u.email FROM "user" u WHERE u.id = $1`,
[actingUserId],
);
@@ -246,6 +261,21 @@ export async function setPersonRole(
`UPDATE "user" SET role = $1, "updatedAt" = now() WHERE id = $2`,
[role, targetUserId],
);
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actingUserId,
+ event: "role_changed",
+ metadata: {
+ from: target.role,
+ targetEmail: target.email,
+ targetName: target.name,
+ to: role,
+ },
+ targetUserId,
+ },
+ tx,
+ );
if (keeperId) {
// The account's row has been held since it was read above. A closed
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index eafd294..847fe2f 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -364,7 +364,8 @@ async function handOverFinishedEnvelopes(
`
SELECT count(*)::text AS count
FROM envelopes
- WHERE user_id = $1 AND status = ANY($2::text[])
+ WHERE user_id = $1
+ AND (status = ANY($2::text[]) OR (part11 AND status <> 'draft'))
`,
[userId, FINISHED_ENVELOPE_STATUSES],
);
@@ -400,7 +401,9 @@ async function handOverFinishedEnvelopes(
)
FOR SHARE OF u
) k
- WHERE e.user_id = $2 AND e.status = ANY($3::text[])
+ WHERE e.user_id = $2
+ -- A Part 11 envelope still out for signature is a record too.
+ AND (e.status = ANY($3::text[]) OR (e.part11 AND e.status <> 'draft'))
`,
[keeperId, userId, FINISHED_ENVELOPE_STATUSES, now],
);
@@ -633,6 +636,9 @@ async function listFinishedEnvelopesToHandle(
FROM envelopes e
JOIN "user" u ON u.id = e.user_id
WHERE e.status IN ('completed', 'declined', 'voided')
+ -- Part 11 records are kept for as long as the rules that apply to
+ -- them say, never by this timer.
+ AND NOT e.part11
AND (
(
e.retention_warned_at IS NULL
diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.ts
index 9208b28..864cf03 100644
--- a/src/lib/schemas/envelope.ts
+++ b/src/lib/schemas/envelope.ts
@@ -148,6 +148,8 @@ export const envelopeRecordSchema = z.object({
expiresAt: unixTimestampSchema.nullable().optional(),
/** Days between automatic reminders, or null for none. */
reminderIntervalDays: reminderIntervalDaysSchema.optional(),
+ /** Sent in Part 11 mode. See part11.ts. */
+ part11: z.boolean().optional(),
createdAt: unixTimestampSchema,
updatedAt: unixTimestampSchema,
});
diff --git a/src/lib/schemas/field.ts b/src/lib/schemas/field.ts
index 50cdc18..fe2abed 100644
--- a/src/lib/schemas/field.ts
+++ b/src/lib/schemas/field.ts
@@ -247,6 +247,16 @@ export const signingFieldSubmissionSchema = z.union([
export const signingSubmissionSchema = z.object({
clientTimezoneOffsetMinutes: z.number().int().min(-840).max(840),
fields: z.array(signingFieldSubmissionSchema),
+ // Part 11 envelopes: both parts of the signer's electronic signature,
+ // given again for this signature (21 CFR 11.200(a)), and their confirmation
+ // of what it means.
+ reauthentication: z
+ .object({
+ email: z.string().trim().min(1).max(320),
+ meaningConfirmed: z.literal(true),
+ password: z.string().min(1).max(128),
+ })
+ .optional(),
});
export type FieldPlacement = z.infer<typeof fieldPlacementSchema>;
diff --git a/src/lib/schemas/signer.ts b/src/lib/schemas/signer.ts
index 7978ae8..861642d 100644
--- a/src/lib/schemas/signer.ts
+++ b/src/lib/schemas/signer.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import {
MAX_COPY_RECIPIENTS_PER_ENVELOPE,
MAX_SIGNERS_PER_ENVELOPE,
+ signatureMeanings,
signerStatuses,
} from "../types/domain.ts";
import {
@@ -36,6 +37,9 @@ export const draftSignerSchema = z.object({
// it, and leaving it out keeps the code already saved.
accessCode: z.string().trim().min(4).max(64).nullable().optional(),
requireEmailCode: z.boolean().optional(),
+ // What the signature means, for Part 11 envelopes. Null clears it, and
+ // leaving it out keeps the one already saved.
+ signatureMeaning: z.enum(signatureMeanings).nullable().optional(),
});
export const signerListSchema = z
@@ -117,6 +121,7 @@ export const replaceSignersResponseSchema = z.object({
hasAccessCode: z.boolean(),
name: nameSchema,
requireEmailCode: z.boolean(),
+ signatureMeaning: z.enum(signatureMeanings).nullable(),
signOrder: z.number().int().positive(),
}),
),
diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.ts
index 129667f..ea8a17b 100644
--- a/src/lib/schemas/signing.ts
+++ b/src/lib/schemas/signing.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { signatureMeanings } from "../types/domain.ts";
import { envelopePageSchema } from "./envelope.ts";
import { fieldInputMethodSchema, fieldTypeSchema } from "./field.ts";
import {
@@ -72,6 +73,18 @@ export const signingPayloadSchema = z.object({
envelopeTitle: envelopeTitleSchema,
pageCount: z.number().int().positive(),
pages: z.array(envelopePageSchema),
+ /**
+ * Set for a Part 11 envelope: the signer gives their email address and
+ * password again to sign, and confirms what the signature means.
+ */
+ part11: z
+ .object({
+ meaning: z.enum(signatureMeanings),
+ meaningLabel: z.string().trim().min(1),
+ meaningStatement: z.string().trim().min(1),
+ })
+ .nullable()
+ .optional(),
senderName: z.string().trim().min(1).max(320),
signer: z.object({
email: emailSchema,
@@ -111,10 +124,19 @@ export type SigningVisibleField = z.infer<typeof signingVisibleFieldSchema>;
export type SigningPayload = z.infer<typeof signingPayloadSchema>;
export type SigningDisclosure = z.infer<typeof signingDisclosureSchema>;
-export const signerCheckRequestSchema = z.object({
- code: z.string().trim().min(1).max(64),
- method: z.enum(["access_code", "email_code"]),
-});
+export const signerCheckRequestSchema = z.discriminatedUnion("method", [
+ z.object({
+ code: z.string().trim().min(1).max(64),
+ method: z.enum(["access_code", "email_code"]),
+ }),
+ // Part 11 envelopes: the signer's own account, by its email address and
+ // password.
+ z.object({
+ email: z.string().trim().min(1).max(320),
+ method: z.literal("account"),
+ password: z.string().min(1).max(128),
+ }),
+]);
export const signerConsentRequestSchema = z.object({
disclosureVersion: z.string().trim().min(1).max(40),
@@ -124,8 +146,8 @@ export type SigningVerificationState = {
emailCodeSentAt: number | null;
envelopeTitle: string;
maskedEmail: string;
- pending: Array<"access_code" | "email_code">;
- required: Array<"access_code" | "email_code">;
+ pending: Array<"access_code" | "account" | "email_code">;
+ required: Array<"access_code" | "account" | "email_code">;
senderName: string;
};
export type SigningDeclineResponse = z.infer<
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index 30b8053..16a5566 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -9,6 +9,7 @@ import {
} from "../schemas/envelope.ts";
import type { FieldRecord } from "../schemas/field.ts";
import type { SignerRecord } from "../schemas/signer.ts";
+import { buildSignatureManifestation } from "../signature-meanings.ts";
import { canonicalJson } from "../utils/canonical-json.ts";
import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";
import { embedTextFaces, type TextFace } from "./pdf-fonts.ts";
@@ -524,6 +525,36 @@ async function stampFieldValue(
}
}
+/**
+ * Prints a Part 11 signature's manifestation just under the signature, or
+ * just above it when the field sits at the foot of the page.
+ */
+function stampSignatureManifestation(
+ field: FieldRecord,
+ page: PDFPage,
+ font: TextFace,
+ text: string,
+): void {
+ const rect = normalizedRectToPdfRect(field, {
+ heightPt: page.getHeight(),
+ widthPt: page.getWidth(),
+ });
+ const maxWidth = Math.max(
+ rect.widthPt,
+ Math.min(240, page.getWidth() - rect.xPt - 4),
+ );
+ const size = fitTextSize(font, text, maxWidth, 7, 6.5);
+ const below = rect.yPt - size - 1.5;
+ const y = below >= 2 ? below : rect.yPt + rect.heightPt + 1.5;
+
+ font.drawText(page, text, {
+ color: rgb(0.2, 0.2, 0.24),
+ size,
+ x: rect.xPt,
+ y,
+ });
+}
+
function buildAuditLines(input: {
auditEvents: AuditEventRecord[];
auditFingerprint?: string | null;
@@ -721,6 +752,7 @@ function buildAuditLines(input: {
const AUTHENTICATION_LABELS: Record<string, string> = {
access_code: "access code from the sender",
+ account: "own account, with email address and password to open it",
email_code: "one-time code sent by email",
};
@@ -749,10 +781,31 @@ function describeSignerEvidence(
),
];
+ const part11 =
+ signed?.metadata?.part11 && typeof signed.metadata.part11 === "object"
+ ? (signed.metadata.part11 as Record<string, unknown>)
+ : null;
+
+ if (part11) {
+ checks.push("email address and password given again to sign");
+ }
+
if (signed || signer.status === "declined") {
details.push(`Identified by: ${checks.join(", ")}`);
}
+ const manifestation = buildSignatureManifestation(signer);
+
+ if (part11 && manifestation) {
+ details.push(manifestation);
+
+ if (typeof part11.meaningStatement === "string") {
+ details.push(
+ `Meaning confirmed by the signer: "${part11.meaningStatement}"`,
+ );
+ }
+ }
+
if (consented) {
details.push(
`Agreed to use electronic records and signatures at ${formatAuditTimestamp(consented.createdAt)}${
@@ -1091,12 +1144,26 @@ export async function renderFinalizedEnvelopePdf(
const stampedFields = input.fields
.filter(shouldStampField)
.sort((left, right) => left.page - right.page || left.y - right.y);
+ // Part 11: the signer's name, the time and the meaning, printed beside
+ // each of their signatures (21 CFR 11.50).
+ const manifestations = new Map<string, string>();
+
+ if (input.envelope.part11) {
+ for (const signer of input.signers) {
+ const text = signer.id ? buildSignatureManifestation(signer) : null;
+
+ if (text && signer.id) {
+ manifestations.set(signer.id, text);
+ }
+ }
+ }
// The signed document embeds glyphs for the stamped values only. The
// certificate's wording is added when the audit trail is appended to it.
const faces = await embedTextFaces(
pdfDocument,
[
stampedFields.map((field) => field.value),
+ [...manifestations.values()],
input.includeAuditTrail
? [
input.envelope,
@@ -1135,6 +1202,13 @@ export async function renderFinalizedEnvelopePdf(
pdfDocument,
storageService,
);
+
+ const manifestation =
+ field.type === "signature" ? manifestations.get(field.signerId) : null;
+
+ if (manifestation) {
+ stampSignatureManifestation(field, page, faces.regular, manifestation);
+ }
}
try {
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
new file mode 100644
index 0000000..f4f411e
--- /dev/null
+++ b/src/lib/services/system-audit.ts
@@ -0,0 +1,248 @@
+import { createHash, randomUUID } from "node:crypto";
+
+import {
+ type DbExecutor,
+ getDb,
+ queryMany,
+ withTransaction,
+} from "../db/connection.ts";
+import { canonicalJson } from "../utils/canonical-json.ts";
+
+// The install's own audit trail: changes that are not about one envelope,
+// such as a setting, a role, an identity check or a signing lock. Part 11
+// (11.10(e)) asks for a computer-made, time-stamped record of what was done
+// to the records and to who may sign them, which never hides what came
+// before. Like each envelope's trail, the rows form one hash chain, so a
+// changed, removed or reordered row shows.
+
+export const systemAuditEventTypes = [
+ "settings_changed",
+ "part11_mode_changed",
+ "role_changed",
+ "identity_verified",
+ "identity_verification_revoked",
+ "signing_locked",
+ "signing_unlocked",
+ "reauthentication_failed",
+] as const;
+
+export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];
+
+export type SystemAuditEvent = {
+ actorEmail: string | null;
+ actorUserId: string | null;
+ createdAt: number;
+ event: SystemAuditEventType;
+ id: string;
+ ipAddress: string | null;
+ metadata: Record<string, unknown> | null;
+ sequence: number;
+ targetUserId: string | null;
+ userAgent: string | null;
+};
+
+export type RecordSystemAuditEventInput = {
+ actorEmail?: string | null;
+ actorUserId?: string | null;
+ createdAt?: number;
+ event: SystemAuditEventType;
+ ipAddress?: string | null;
+ metadata?: Record<string, unknown> | null;
+ targetUserId?: string | null;
+ userAgent?: string | null;
+};
+
+/** One key for the whole chain: writers take turns. */
+const SYSTEM_AUDIT_LOCK_ID = 746108325;
+
+type ChainedFields = Omit<SystemAuditEvent, never>;
+
+export function computeSystemAuditRowHash(
+ previousHash: string | null,
+ fields: ChainedFields,
+): string {
+ return createHash("sha256")
+ .update(previousHash ?? "")
+ .update("\n")
+ .update(canonicalJson(fields))
+ .digest("hex");
+}
+
+function isPool(database: DbExecutor): database is ReturnType<typeof getDb> {
+ return "connect" in database && "totalCount" in database;
+}
+
+async function insertChained(
+ input: RecordSystemAuditEventInput,
+ database: DbExecutor,
+): Promise<SystemAuditEvent> {
+ await database.query("SELECT pg_advisory_xact_lock($1)", [
+ SYSTEM_AUDIT_LOCK_ID,
+ ]);
+
+ const previous = await database.query<{
+ rowHash: string;
+ sequence: number;
+ }>(
+ `
+ SELECT sequence, row_hash AS "rowHash"
+ FROM system_audit_events
+ ORDER BY sequence DESC
+ LIMIT 1
+ `,
+ );
+ const previousRow = previous.rows[0];
+ const fields: ChainedFields = {
+ actorEmail: input.actorEmail ?? null,
+ actorUserId: input.actorUserId ?? null,
+ createdAt: input.createdAt ?? Math.floor(Date.now() / 1000),
+ event: input.event,
+ id: randomUUID(),
+ ipAddress: input.ipAddress ?? null,
+ metadata: input.metadata ?? null,
+ sequence: (previousRow?.sequence ?? 0) + 1,
+ targetUserId: input.targetUserId ?? null,
+ userAgent: input.userAgent ?? null,
+ };
+ const previousHash = previousRow?.rowHash ?? null;
+
+ await database.query(
+ `
+ INSERT INTO system_audit_events (
+ id, sequence, event, actor_user_id, actor_email, target_user_id,
+ ip_address, user_agent, metadata, created_at, prev_hash, row_hash
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+ `,
+ [
+ fields.id,
+ fields.sequence,
+ fields.event,
+ fields.actorUserId,
+ fields.actorEmail,
+ fields.targetUserId,
+ fields.ipAddress,
+ fields.userAgent,
+ fields.metadata,
+ fields.createdAt,
+ previousHash,
+ computeSystemAuditRowHash(previousHash, fields),
+ ],
+ );
+
+ return fields;
+}
+
+/**
+ * Adds an event to the install's trail. Given a transaction, the event
+ * lands or rolls back with the change it describes.
+ */
+export async function recordSystemAuditEvent(
+ input: RecordSystemAuditEventInput,
+ database: DbExecutor = getDb(),
+): Promise<SystemAuditEvent> {
+ if (isPool(database)) {
+ return withTransaction((client) => insertChained(input, client), database);
+ }
+
+ return insertChained(input, database);
+}
+
+type SystemAuditRow = SystemAuditEvent & {
+ prevHash: string | null;
+ rowHash: string;
+};
+
+const SYSTEM_AUDIT_COLUMNS = `
+ id,
+ sequence,
+ event,
+ actor_user_id AS "actorUserId",
+ actor_email AS "actorEmail",
+ target_user_id AS "targetUserId",
+ ip_address AS "ipAddress",
+ user_agent AS "userAgent",
+ metadata,
+ created_at AS "createdAt"
+`;
+
+/** The newest events first, a page at a time. */
+export async function listSystemAuditEvents(
+ {
+ before,
+ limit = 100,
+ }: {
+ /** Only events with a lower sequence than this. */
+ before?: number | null;
+ limit?: number;
+ } = {},
+ database: DbExecutor = getDb(),
+): Promise<SystemAuditEvent[]> {
+ return queryMany<SystemAuditEvent>(
+ database,
+ `
+ SELECT ${SYSTEM_AUDIT_COLUMNS}
+ FROM system_audit_events
+ WHERE ($1::int IS NULL OR sequence < $1)
+ ORDER BY sequence DESC
+ LIMIT $2
+ `,
+ [before ?? null, Math.max(1, Math.min(limit, 1000))],
+ );
+}
+
+/** Every event in a time range, oldest first, for an export. */
+export async function listSystemAuditEventsBetween(
+ from: number,
+ to: number,
+ database: DbExecutor = getDb(),
+): Promise<SystemAuditEvent[]> {
+ return queryMany<SystemAuditEvent>(
+ database,
+ `
+ SELECT ${SYSTEM_AUDIT_COLUMNS}
+ FROM system_audit_events
+ WHERE created_at >= $1 AND created_at <= $2
+ ORDER BY sequence ASC
+ `,
+ [from, to],
+ );
+}
+
+export type SystemAuditChainCheck =
+ | { events: number; ok: true }
+ | { brokenAtSequence: number; events: number; ok: false };
+
+/** Recomputes the whole chain and reports the first row that disagrees. */
+export async function verifySystemAuditChain(
+ database: DbExecutor = getDb(),
+): Promise<SystemAuditChainCheck> {
+ const rows = await queryMany<SystemAuditRow>(
+ database,
+ `
+ SELECT ${SYSTEM_AUDIT_COLUMNS},
+ prev_hash AS "prevHash",
+ row_hash AS "rowHash"
+ FROM system_audit_events
+ ORDER BY sequence ASC
+ `,
+ );
+ let previousHash: string | null = null;
+ let expected = 1;
+
+ for (const row of rows) {
+ const { prevHash, rowHash, ...fields } = row;
+
+ if (
+ row.sequence !== expected ||
+ prevHash !== previousHash ||
+ rowHash !== computeSystemAuditRowHash(previousHash, fields)
+ ) {
+ return { brokenAtSequence: expected, events: rows.length, ok: false };
+ }
+
+ previousHash = rowHash;
+ expected += 1;
+ }
+
+ return { events: rows.length, ok: true };
+}
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
index f632129..739b95e 100644
--- a/src/lib/settings.test.ts
+++ b/src/lib/settings.test.ts
@@ -14,6 +14,7 @@ const stored: AppSettings = {
emailReadyAt: null,
logoVersion: null,
organizationName: "Acme Corp",
+ part11Mode: false,
privacyUrl: "https://acme.com/privacy",
retentionDays: null,
senderAddress: "[email protected]",
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 66d185a..302ada0 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -27,6 +27,12 @@ export type AppSettings = {
*/
logoVersion: string | null;
organizationName: string | null;
+ /**
+ * Part 11 mode: signers sign with their own verified accounts, give the
+ * meaning of each signature, and records are never deleted on a timer.
+ * See part11.ts.
+ */
+ part11Mode: boolean;
privacyUrl: string | null;
/**
* Days a finished envelope is kept before the nightly job deletes it, or
@@ -76,6 +82,7 @@ type AppSettingsRow = {
email_ready_at: number | null;
logo_hash: string | null;
organization_name: string | null;
+ part11_mode: boolean;
privacy_url: string | null;
retention_days: number | null;
sender_address: string | null;
@@ -106,6 +113,7 @@ const FIRST_SETTINGS_COLUMNS = [
const LATER_SETTINGS_COLUMNS = [
["retention_days"], // 20261113090000_signature_evidence
["brand_color", "logo_hash"], // 20261114120000_branding
+ ["part11_mode"], // 20261115090000_part11_mode
] as const;
type LaterSettingsColumn = (typeof LATER_SETTINGS_COLUMNS)[number][number];
@@ -133,6 +141,7 @@ const UNSET_SETTINGS: AppSettings = {
emailReadyAt: null,
logoVersion: null,
organizationName: null,
+ part11Mode: false,
privacyUrl: null,
retentionDays: null,
senderAddress: null,
@@ -198,6 +207,7 @@ function mapSettingsRow(row: StoredSettingsRow): AppSettings {
emailReadyAt: row.email_ready_at,
logoVersion: row.logo_hash ?? null,
organizationName: row.organization_name,
+ part11Mode: row.part11_mode ?? false,
privacyUrl: row.privacy_url,
retentionDays: row.retention_days ?? null,
senderAddress: row.sender_address,
@@ -343,10 +353,11 @@ export async function saveSettings(
terms_url,
retention_days,
brand_color,
+ part11_mode,
created_at,
updated_at
)
- values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $10, $10)
+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $10, $10)
on conflict (id) do update set
allowed_email_domains = excluded.allowed_email_domains,
email_ready_at = excluded.email_ready_at,
@@ -359,6 +370,7 @@ export async function saveSettings(
terms_url = excluded.terms_url,
retention_days = excluded.retention_days,
brand_color = excluded.brand_color,
+ part11_mode = excluded.part11_mode,
updated_at = excluded.updated_at
returning ${SETTINGS_COLUMNS}
`,
@@ -375,6 +387,7 @@ export async function saveSettings(
now,
next.retentionDays,
next.brandColor,
+ next.part11Mode,
],
);
diff --git a/src/lib/signature-meanings.ts b/src/lib/signature-meanings.ts
new file mode 100644
index 0000000..a70492f
--- /dev/null
+++ b/src/lib/signature-meanings.ts
@@ -0,0 +1,59 @@
+import { signatureMeanings, type SignatureMeaning } from "./types/domain.ts";
+
+// What a Part 11 signature means (21 CFR 11.50(a)(3)), in words for the
+// signer, the signed document and the certificate. No database or server
+// code here, so the PDF and the browser can use it too.
+
+export const SIGNATURE_MEANING_DETAILS: Record<
+ SignatureMeaning,
+ { label: string; statement: string }
+> = {
+ approval: { label: "Approval", statement: "I approve this document." },
+ authorship: {
+ label: "Authorship",
+ statement: "I am the author of this document.",
+ },
+ responsibility: {
+ label: "Responsibility",
+ statement: "I take responsibility for this document.",
+ },
+ review: {
+ label: "Review",
+ statement: "I have reviewed this document.",
+ },
+};
+
+export function parseSignatureMeaning(value: unknown): SignatureMeaning | null {
+ return typeof value === "string" &&
+ (signatureMeanings as readonly string[]).includes(value)
+ ? (value as SignatureMeaning)
+ : null;
+}
+
+export function signatureMeaningLabel(
+ meaning: SignatureMeaning | null | undefined,
+): string | null {
+ return meaning ? SIGNATURE_MEANING_DETAILS[meaning].label : null;
+}
+
+/**
+ * The words printed beside a Part 11 signature: the signer's printed name,
+ * the date and time in UTC, and the meaning (21 CFR 11.50(a)). Null when
+ * the signer has not signed or the signature has no meaning.
+ */
+export function buildSignatureManifestation(signer: {
+ name: string;
+ signatureMeaning?: SignatureMeaning | null;
+ signedAt?: number | null;
+}): string | null {
+ if (!signer.signatureMeaning || typeof signer.signedAt !== "number") {
+ return null;
+ }
+
+ const signedAt = new Date(signer.signedAt * 1000)
+ .toISOString()
+ .replace(/\.\d{3}Z$/, " UTC")
+ .replace("T", " ");
+
+ return `Signed by ${signer.name} | ${signedAt} | Meaning: ${SIGNATURE_MEANING_DETAILS[signer.signatureMeaning].label}`;
+}
diff --git a/src/lib/signer-checks.ts b/src/lib/signer-checks.ts
index 8931172..0ad7693 100644
--- a/src/lib/signer-checks.ts
+++ b/src/lib/signer-checks.ts
@@ -17,10 +17,17 @@ import { isProduction, resolveAuthSecret } from "./utils/env.ts";
// - email_code: a one-time code emailed when the signer opens the link.
// Proves the person signing controls the mailbox at that moment, not just
// that they hold a forwarded link.
+// - account: Part 11 envelopes only. The signer gives the email address and
+// password of their own account on this install, which was bound to them
+// when the envelope was sent.
//
// Passing a check sets a cookie for this link only, valid for a few hours.
-export const signerCheckMethods = ["access_code", "email_code"] as const;
+export const signerCheckMethods = [
+ "access_code",
+ "account",
+ "email_code",
+] as const;
export type SignerCheckMethod = (typeof signerCheckMethods)[number];
export const EMAIL_CODE_TTL_SECONDS = 10 * 60;
@@ -31,6 +38,8 @@ const COOKIE_CONTEXT = "signudoc/signer-verification/v1";
export type SignerCheckState = {
accessCodeHash: string | null;
+ /** The account that must sign, for a Part 11 envelope. */
+ accountUserId: string | null;
consentedAt: number | null;
emailCodeAttempts: number;
emailCodeExpiresAt: number | null;
@@ -48,6 +57,7 @@ export async function getSignerCheckState(
`
SELECT
access_code_hash AS "accessCodeHash",
+ user_id AS "accountUserId",
consented_at AS "consentedAt",
email_code_attempts AS "emailCodeAttempts",
email_code_expires_at AS "emailCodeExpiresAt",
@@ -63,6 +73,7 @@ export async function getSignerCheckState(
return (
row ?? {
accessCodeHash: null,
+ accountUserId: null,
consentedAt: null,
emailCodeAttempts: 0,
emailCodeExpiresAt: null,
@@ -74,10 +85,12 @@ export async function getSignerCheckState(
}
export function requiredSignerChecks(
- state: Pick<SignerCheckState, "accessCodeHash" | "requireEmailCode">,
+ state: Pick<SignerCheckState, "accessCodeHash" | "requireEmailCode"> &
+ Partial<Pick<SignerCheckState, "accountUserId">>,
): SignerCheckMethod[] {
return [
...(state.accessCodeHash ? (["access_code"] as const) : []),
+ ...(state.accountUserId ? (["account"] as const) : []),
...(state.requireEmailCode ? (["email_code"] as const) : []),
];
}
diff --git a/src/lib/signer-data.ts b/src/lib/signer-data.ts
index e305b02..9501a91 100644
--- a/src/lib/signer-data.ts
+++ b/src/lib/signer-data.ts
@@ -32,6 +32,8 @@ type SignerEnvelopeRow = {
envelopeId: string;
envelopeStatus: string;
envelopeTitle: string;
+ /** Sent in Part 11 mode: never erased here. */
+ part11: boolean;
signedAt: number | null;
signerEmail: string;
signerId: string;
@@ -70,6 +72,7 @@ async function listSignerEnvelopes(
e.id AS "envelopeId",
e.title AS "envelopeTitle",
e.status AS "envelopeStatus",
+ e.part11,
e.created_at AS "envelopeCreatedAt"
FROM signers s
JOIN envelopes e ON e.id = s.envelope_id
@@ -150,6 +153,8 @@ export async function exportSignerData(
export type SignerErasureResult = {
deletedEnvelopes: number;
+ /** Part 11 records, which an erasure request does not delete. */
+ keptPart11: { id: string; title: string }[];
removedFromDrafts: number;
skippedInProgress: { id: string; title: string }[];
};
@@ -177,9 +182,13 @@ export async function eraseSignerData(
const envelopes = await listSignerEnvelopes(email, database);
const drafts = envelopes.filter((row) => row.envelopeStatus === "draft");
- const finished = envelopes.filter((row) =>
+ const allFinished = envelopes.filter((row) =>
["completed", "declined", "voided"].includes(row.envelopeStatus),
);
+ // Part 11 records are kept for as long as their own rules require, which
+ // an erasure request does not override. They are reported instead.
+ const keptPart11 = allFinished.filter((row) => row.part11);
+ const finished = allFinished.filter((row) => !row.part11);
const inProgress = envelopes.filter((row) => row.envelopeStatus === "sent");
// Lock the drafts and look again, at their status and at who is on them.
@@ -233,6 +242,10 @@ export async function eraseSignerData(
return {
deletedEnvelopes,
+ keptPart11: keptPart11.map((row) => ({
+ id: row.envelopeId,
+ title: row.envelopeTitle,
+ })),
removedFromDrafts: erasedFromDrafts.removed,
skippedInProgress: [...inProgress, ...raced].map((row) => ({
id: row.envelopeId,
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index cc09b85..ab0e5af 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -43,6 +43,12 @@ import {
type CopyRecipientRecord,
} from "./schemas/signer.ts";
import { getBranding } from "./settings.ts";
+import {
+ checkSigningCredentials,
+ MAX_SIGNING_PASSWORD_ATTEMPTS,
+ type PasswordVerifier,
+ SIGNATURE_MEANING_DETAILS,
+} from "./part11.ts";
import {
listAuditEventsForEnvelope,
recordAuditEvent,
@@ -128,6 +134,7 @@ type SigningEnvelopeRow = {
expiresAt: number | null;
id: string;
pageCount: number;
+ part11: boolean;
sentAt: number | null;
signedPdfKey: string | null;
sourcePdfFilename: string;
@@ -152,10 +159,13 @@ type SigningSignerRow = {
lastNudgedAt: number | null;
name: string;
signOrder: number;
+ signatureMeaning:
+ "approval" | "authorship" | "responsibility" | "review" | null;
signedAt: number | null;
signingTokenExpiresAt: number | null;
signingTokenHash: string | null;
status: "declined" | "notified" | "pending" | "signed";
+ userId: string | null;
turnStartedAt: number | null;
updatedAt: number;
};
@@ -212,6 +222,8 @@ type SubmitSigningOptions = {
storageService?: StorageService;
/** The extra checks this browser has passed for the link (from its cookie). */
verifiedMethods?: readonly SignerCheckMethod[];
+ /** Replaced in tests: checks a Part 11 signer's password. */
+ verifyPassword?: PasswordVerifier;
};
const signingUnavailableStatusCodeMap: Record<
@@ -500,6 +512,7 @@ async function getEnvelopeRow(
evidence_key AS "evidenceKey",
source_pdf_hash AS "sourcePdfHash",
page_count AS "pageCount",
+ part11,
sent_at AS "sentAt",
completed_at AS "completedAt",
declined_at AS "declinedAt",
@@ -537,6 +550,8 @@ async function listSignerRows(
signed_at AS "signedAt",
declined_at AS "declinedAt",
decline_reason AS "declineReason",
+ signature_meaning AS "signatureMeaning",
+ user_id AS "userId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM signers
@@ -878,9 +893,19 @@ function assertRadioGroupsAnswered(
}
}
+type Part11SignatureRecord = {
+ /** How the signer gave both parts of their signature again. */
+ credential: "account_password";
+ meaning: NonNullable<SigningSignerRow["signatureMeaning"]>;
+ meaningStatement: string;
+ reauthenticatedAt: number;
+ userId: string;
+};
+
function buildSignedAuditEvent(input: {
authMethods: readonly SignerCheckMethod[];
envelopeId: string;
+ part11?: Part11SignatureRecord | null;
signatureMethods: readonly string[];
requestMeta: SigningRequestMeta;
signer: ReturnType<typeof signerRecordSchema.parse>;
@@ -903,6 +928,7 @@ function buildSignedAuditEvent(input: {
authMethods: [...input.authMethods],
signatureMethods: [...input.signatureMethods],
timezoneOffsetMinutes: input.timezoneOffsetMinutes,
+ ...(input.part11 ? { part11: input.part11 } : {}),
},
userAgent: input.requestMeta.userAgent ?? null,
};
@@ -1332,13 +1358,26 @@ export async function sendSignerEmailCode(
* Checks an access code or emailed code. Returns every check this browser
* has now passed, for the caller to store in the link's cookie.
*/
+function describeCredentialFailure(result: {
+ attemptsLeft: number;
+ locked: boolean;
+}): string {
+ if (result.locked) {
+ return `This account is locked for signing after ${MAX_SIGNING_PASSWORD_ATTEMPTS} wrong passwords. Ask an administrator to unlock it.`;
+ }
+
+ return `That email address or password is not right. ${result.attemptsLeft} ${result.attemptsLeft === 1 ? "try is" : "tries are"} left before the account is locked for signing.`;
+}
+
export async function verifySignerCheck(
token: string,
input: unknown,
{
database = getDb(),
+ emailService,
requestMeta = {},
verifiedMethods = [],
+ verifyPassword,
}: SubmitSigningOptions = {},
): Promise<SignerCheckMethod[]> {
const parsed = signerCheckRequestSchema.parse(input);
@@ -1351,7 +1390,41 @@ export async function verifySignerCheck(
throw new SigningMutationError("This check is not needed.", 400);
}
- if (parsed.method === "access_code") {
+ if (parsed.method === "account") {
+ const result = await checkSigningCredentials(
+ {
+ email: parsed.email,
+ ipAddress: requestMeta.ipAddress ?? null,
+ password: parsed.password,
+ userAgent: requestMeta.userAgent ?? null,
+ userId: state.accountUserId!,
+ },
+ { database, emailService, verifyPassword },
+ );
+
+ passed = result.ok;
+
+ if (!result.ok) {
+ await recordAuditEvent(
+ {
+ actorEmail: context.signer.email,
+ actorType: "signer",
+ envelopeId: context.envelope.id,
+ event: "verification_failed",
+ ipAddress: requestMeta.ipAddress ?? null,
+ metadata: {
+ ...signerAuditMetadata(context),
+ locked: result.locked,
+ method: parsed.method,
+ },
+ userAgent: requestMeta.userAgent ?? null,
+ },
+ database,
+ );
+
+ throw new SigningMutationError(describeCredentialFailure(result), 400);
+ }
+ } else if (parsed.method === "access_code") {
passed = checkAccessCode(parsed.code, state.accessCodeHash!);
} else {
// Count the attempt and read the code in one statement, so parallel
@@ -1670,6 +1743,17 @@ export async function getSigningPayloadForToken(
envelopeTitle: context.envelope.title,
pageCount: context.envelope.pageCount,
pages: context.pages,
+ part11:
+ context.envelope.part11 && context.signer.signatureMeaning
+ ? {
+ meaning: context.signer.signatureMeaning,
+ meaningLabel:
+ SIGNATURE_MEANING_DETAILS[context.signer.signatureMeaning].label,
+ meaningStatement:
+ SIGNATURE_MEANING_DETAILS[context.signer.signatureMeaning]
+ .statement,
+ }
+ : null,
senderName: normalizeSenderName(context.sender),
signer: {
email: context.signer.email,
@@ -1683,6 +1767,85 @@ export async function getSigningPayloadForToken(
});
}
+/**
+ * For a Part 11 envelope: checks the signer's email address and password
+ * again for this signature, and that they confirmed what it means. Returns
+ * what goes in the "signed" audit event, or null for other envelopes.
+ */
+async function reauthenticatePart11Signer(
+ context: ResolvedSigningContext,
+ state: SignerCheckState,
+ reauthentication:
+ { email: string; meaningConfirmed: true; password: string } | undefined,
+ {
+ database,
+ emailService,
+ requestMeta,
+ verifyPassword,
+ }: {
+ database: DbPool;
+ emailService: EmailService;
+ requestMeta: SigningRequestMeta;
+ verifyPassword?: PasswordVerifier;
+ },
+): Promise<Part11SignatureRecord | null> {
+ if (!context.envelope.part11 && !state.accountUserId) {
+ return null;
+ }
+
+ const meaning = context.signer.signatureMeaning;
+
+ if (!state.accountUserId || !meaning) {
+ throw new SigningMutationError(
+ "This document was sent for Part 11 signatures but has no account or meaning for you. Ask the sender to send it again.",
+ 409,
+ );
+ }
+
+ if (!reauthentication) {
+ throw new SigningMutationError(
+ "Enter your email address and password to sign.",
+ 400,
+ );
+ }
+
+ const result = await checkSigningCredentials(
+ {
+ email: reauthentication.email,
+ ipAddress: requestMeta.ipAddress ?? null,
+ password: reauthentication.password,
+ userAgent: requestMeta.userAgent ?? null,
+ userId: state.accountUserId,
+ },
+ { database, emailService, verifyPassword },
+ );
+
+ if (!result.ok) {
+ await recordAuditEvent(
+ {
+ actorEmail: context.signer.email,
+ actorType: "signer",
+ envelopeId: context.envelope.id,
+ event: "reauthentication_failed",
+ ipAddress: requestMeta.ipAddress ?? null,
+ metadata: { ...signerAuditMetadata(context), locked: result.locked },
+ userAgent: requestMeta.userAgent ?? null,
+ },
+ database,
+ );
+
+ throw new SigningMutationError(describeCredentialFailure(result), 400);
+ }
+
+ return {
+ credential: "account_password",
+ meaning,
+ meaningStatement: SIGNATURE_MEANING_DETAILS[meaning].statement,
+ reauthenticatedAt: Math.floor(Date.now() / 1000),
+ userId: state.accountUserId,
+ };
+}
+
export async function submitSigningForToken(
token: string,
input: unknown,
@@ -1692,6 +1855,7 @@ export async function submitSigningForToken(
requestMeta = {},
storageService: givenStorageService,
verifiedMethods = [],
+ verifyPassword,
}: SubmitSigningOptions = {},
): Promise<SigningSubmitResponse> {
const parsedInput = signingSubmissionSchema.parse(input);
@@ -1710,6 +1874,12 @@ export async function submitSigningForToken(
}
const emailService = givenEmailService ?? createEmailService();
+ const part11Signature = await reauthenticatePart11Signer(
+ context,
+ signerChecks.state,
+ parsedInput.reauthentication,
+ { database, emailService, requestMeta, verifyPassword },
+ );
const storageService = givenStorageService ?? createStorageService();
const currentSignerId = context.signer.id;
@@ -1934,6 +2104,7 @@ export async function submitSigningForToken(
const signedAuditEvent = buildSignedAuditEvent({
authMethods: signerChecks.passed,
envelopeId: context.envelope.id,
+ part11: part11Signature,
signatureMethods: [
...new Set(
[...fieldUpdates.values()]
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index 35b7078..b801d81 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -63,6 +63,18 @@ export const auditEventTypes = [
"deadline_changed",
"expired",
"reminded_auto",
+ "reauthentication_failed",
+] as const;
+
+/**
+ * What a signature means, for Part 11 envelopes (21 CFR 11.50(a)(3)). The
+ * sender picks one for each signer, and it is printed beside the signature.
+ */
+export const signatureMeanings = [
+ "approval",
+ "review",
+ "responsibility",
+ "authorship",
] as const;
export const auditActorTypes = ["sender", "signer", "system"] as const;
@@ -86,6 +98,7 @@ export const emailTemplateKinds = [
"retention_notice",
"expiry_notice",
"test_email",
+ "signing_lock_alert",
] as const;
export type EnvelopeStatus = (typeof envelopeStatuses)[number];
@@ -95,4 +108,5 @@ export type FieldInputMethod = (typeof fieldInputMethods)[number];
export type AuditEventType = (typeof auditEventTypes)[number];
export type AuditActorType = (typeof auditActorTypes)[number];
export type DownloadFileType = (typeof downloadFileTypes)[number];
+export type SignatureMeaning = (typeof signatureMeanings)[number];
export type EmailTemplateKind = (typeof emailTemplateKinds)[number];