Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Ask an administrator to agree before their own disclosure replaces the standard one
Claudede7eba038878
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db421f2..34fe053 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,25 @@ release says when it does.## [Unreleased]+### Settings++- An administrator can write the disclosure signers read and agree to before+ signing, under Settings, Organization, "What signers agree to before+ signing", or start from the standard text and edit it. Empty keeps the+ standard text. A line starting with `## ` is a heading, and `{sender}` and+ `{contact}` fill in who is asking and who to write to. Saving words of+ their own first shows a notice that the standard text covers what the U.S.+ E-SIGN Act requires, that changing it may make signatures invalid, and that+ nothing in SignuDoc is legal advice; the administrator presses "I agree",+ and that is recorded in the site audit trail. The version stored with each+ signer's agreement follows the text, and their audit trail keeps the words+ they read. The hosted service keeps the standard text (PR #193 by+ @carefulcomputer).++This needs one migration, `20261119130000_consent_disclosure.sql`, which adds+the `app_settings.consent_disclosure` column. Until it has run, the setting+reads as empty and signers see the standard text.+## [0.7.0] - 2026-11-20A sender can now send one template to many people at once from a CSV. Twodiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 40e94eb..8429c9c 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -154,7 +154,7 @@ The first time you open a new install it takes you to `/setup`. There you name y- **Who can sign up.** The install starts by letting people with an email address at the administrator's own domain create accounts (or nobody else, if the administrator used a public mailbox such as Gmail). The administrator can change this under Settings, Organization: people at listed domains, nobody, or anyone. People who are only sent a document to sign never need an account.- **More administrators.** Settings, Organization lists everyone with an account under People, where an administrator can make someone else an administrator or take that away. There is always at least one. When an account is closed, its finished documents and their audit trails move to the longest-standing administrator, because they are the organization's records. If that person later stops being an administrator, those documents move on to one who stays, and the documents they sent themselves stay with them.-- **What signers agree to before signing.** Before a signer can sign, they read a disclosure about using electronic records and signatures and tick a box to agree. The built-in disclosure says they may sign on paper instead, ask for a paper copy, and withdraw. Under Settings, Organization, "What signers agree to before signing", an administrator can write their own words in its place, or start from the standard text and change it. Separate paragraphs with a blank line, start a line with `## ` to make a heading, and write `{sender}` and `{contact}` where the sender's name and the address to write to go. Leave it empty to use the built-in text. A custom text is limited to 6,000 characters, and a heading needs words under it. Each signer's agreement records a version of the words they saw: the built-in text keeps its dated version, and a custom text is named by a fingerprint of the text, so the version changes whenever the text does. The words themselves are kept in that signer's audit trail, so the record stays complete if the setting is changed later, and each change to the setting is in the site audit trail. The consent step itself cannot be turned off. The hosted service always shows the built-in text. The built-in text follows what US law on electronic signatures expects for consumer signers. SignuDoc does not give legal advice, so check what applies to your documents and signers before shortening it.+- **What signers agree to before signing.** Before a signer can sign, they read a disclosure about using electronic records and signatures and tick a box to agree. The built-in disclosure says they may sign on paper instead, ask for a paper copy, and withdraw. Under Settings, Organization, "What signers agree to before signing", an administrator can write their own words in its place, or start from the standard text and change it. Separate paragraphs with a blank line, start a line with `## ` to make a heading, and write `{sender}` and `{contact}` where the sender's name and the address to write to go. Leave it empty to use the built-in text. A custom text is limited to 6,000 characters, and a heading needs words under it. Each signer's agreement records a version of the words they saw: the built-in text keeps its dated version, and a custom text is named by a fingerprint of the text, so the version changes whenever the text does. The words themselves, filled in as the signer read them, are kept in that signer's audit trail, so the record stays complete if the setting is changed later. Saving words of your own first shows a notice: the standard text covers what the U.S. E-SIGN Act requires before a consumer agrees to sign electronically (choosing paper, getting a paper copy, withdrawing and what that means, and the device and software needed), and removing or changing it may make signatures and records invalid. Saving needs an administrator to press "I agree", and each change to the setting is in the site audit trail with the version of the notice they agreed to. Saving the standard text unchanged, or going back to it, needs no notice. The consent step itself cannot be turned off. The hosted service always shows the built-in text. SignuDoc is not legal advice, and that includes the standard text: check any wording with your own legal counsel before you rely on it.- **Email.** Settings, Organization also shows whether email is working. While no sender address is set, mail goes out from Resend's test address, which only reaches the owner of the Resend account. Enter a sender address at your domain and the page shows the DNS records to add and checks them for you. Mail from that address is not delivered until its domain is verified.- **`SETUP_TOKEN`.** A new install can be claimed by whoever opens it first. If its URL will be public before you get to it, set `SETUP_TOKEN` to a secret of your own and the setup page will ask for it.- **An install from before this page existed** has accounts but no administrator. Set `SETUP_TOKEN`, sign in with the account that should be in charge, and open `/setup`. It asks for a support address if the install has none. Sign-up stays open, as it was, until that administrator changes it.diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 812dab5..93760b2 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -190,6 +190,55 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a).toBeVisible();await expect.poll(() => readAccentColor(adminPage)).toBe(BRAND_COLOR);+ // Words of the administrator's own in place of the standard disclosure+ // are saved only after they agree to the notice about E-SIGN. Cancel+ // saves nothing, and going back to the standard text needs no notice.+ const disclosureBox = adminPage.getByLabel("Disclosure text");+ const saveOrganization = adminPage.getByRole("button", {+ name: "Save organization settings",+ });+ const notice = adminPage.getByRole("dialog", {+ name: "Before you change what signers agree to",+ });++ await expect(+ adminPage.getByText(+ "We're not lawyers, and nothing here is legal advice",+ ),+ ).toBeVisible();+ await disclosureBox.fill("## Signing online\nWe send this online.");+ await saveOrganization.click();+ await expect(notice).toBeVisible();+ await expect(notice).toContainText("U.S. E-SIGN Act");+ await expect(notice).toContainText("Nothing in SignuDoc");+ await notice.getByRole("button", { name: "Cancel" }).click();+ await expect(notice).toBeHidden();+ await expect(+ adminPage.getByText("Organization settings saved."),+ ).toBeHidden();++ await saveOrganization.click();+ await notice.getByRole("button", { name: "I agree" }).click();+ await expect(+ adminPage.getByText("Organization settings saved."),+ ).toBeVisible();++ await adminPage.reload();+ await expect(disclosureBox).toHaveValue(+ "## Signing online\nWe send this online.",+ );++ await adminPage+ .getByRole("button", { name: "Use the standard text" })+ .click();+ await saveOrganization.click();+ await expect(notice).toBeHidden();+ await expect(+ adminPage.getByText("Organization settings saved."),+ ).toBeVisible();+ await adminPage.reload();+ await expect(disclosureBox).toHaveValue("");+// Setup can only happen once.await adminPage.goto("/setup");await expect(adminPage).not.toHaveURL(/\/setup/);diff --git a/src/app/api/admin/settings/route.ts b/src/app/api/admin/settings/route.tsindex 3eef699..e85b047 100644--- a/src/app/api/admin/settings/route.ts+++ b/src/app/api/admin/settings/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { requireAdminSession } from "@/lib/auth/admin";+import { CUSTOM_DISCLOSURE_NOTICE_VERSION } from "@/lib/consent-disclosure-notice";import { getDb, withTransaction } from "@/lib/db/connection";import {diffSettings,@@ -8,6 +9,7 @@ import {toOrganizationSettingsView,updateOrganizationSettings,} from "@/lib/organization-settings";+import { getDisclosureVersion } from "@/lib/electronic-records-disclosure";import { logRouteError } from "@/lib/security/logging";import {applyRateLimit,@@ -69,7 +71,22 @@ export async function PUT(request: Request) {actorUserId: session.user.id,event: "settings_changed",ipAddress: getClientIpAddress(request.headers),- metadata: { changes },+ metadata: {+ changes,+ // Saving their own disclosure needs the administrator to agree+ // to the notice first, and the record says which notice.+ ...(changes.consentDisclosure && after.consentDisclosure !== null+ ? {+ consentDisclosureNotice: {+ agreed: true,+ disclosureVersion: getDisclosureVersion(+ after.consentDisclosure,+ ),+ noticeVersion: CUSTOM_DISCLOSURE_NOTICE_VERSION,+ },+ }+ : {}),+ },userAgent: getRequestUserAgent(request.headers),},tx,diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex 8603098..3acca46 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -18,7 +18,20 @@ import {FieldError,FieldLabel,} from "@/components/ui/field";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";import { Textarea } from "@/components/ui/textarea";+import {+ CUSTOM_DISCLOSURE_LEGAL_NOTE,+ CUSTOM_DISCLOSURE_NOTICE,+ tidyDisclosureText,+} from "@/lib/consent-disclosure-notice";import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";import type {OrganizationSettingsField,@@ -92,6 +105,11 @@ export function OrganizationSettings({// Bumped after a save, so the email panel looks again: a new sender// address means a different domain to check.const [emailRevision, setEmailRevision] = useState(0);+ // The disclosure as last saved, to tell whether a save changes it.+ const [savedConsentDisclosure, setSavedConsentDisclosure] = useState(+ initialSettings.consentDisclosure,+ );+ const [isDisclosureNoticeOpen, setIsDisclosureNoticeOpen] = useState(false);function handleChange(field: OrganizationSettingsField) {return (event: ChangeEvent<HTMLInputElement>) => {@@ -128,13 +146,39 @@ export function OrganizationSettings({setFeedback(null);}- async function handleSubmit(event: FormEvent<HTMLFormElement>) {+ /**+ * Whether saving puts the administrator's own words in place of what+ * signers read now, which needs them to agree to the notice first. Going+ * back to the standard text, or saving the same words again, does not.+ */+ function savingChangesToOwnDisclosure(): boolean {+ const next = tidyDisclosureText(values.consentDisclosure);++ return (+ !values.hosted &&+ next.length > 0 &&+ next !== tidyDisclosureText(values.defaultConsentDisclosure) &&+ next !== tidyDisclosureText(savedConsentDisclosure)+ );+ }++ function handleSubmit(event: FormEvent<HTMLFormElement>) {event.preventDefault();if (isSaving) {return;}+ if (savingChangesToOwnDisclosure()) {+ setIsDisclosureNoticeOpen(true);+ return;+ }++ void saveSettings(false);+ }++ async function saveSettings(disclosureNoticeAgreed: boolean) {+ setIsDisclosureNoticeOpen(false);setErrors({});setFeedback(null);setIsSaving(true);@@ -145,6 +189,7 @@ export function OrganizationSettings({allowedEmailDomains: values.allowedEmailDomains,brandColor: values.brandColor,consentDisclosure: values.consentDisclosure,+ consentDisclosureAcknowledged: disclosureNoticeAgreed,organizationName: values.organizationName,privacyUrl: values.privacyUrl,retentionDays: values.retentionDays,@@ -170,6 +215,7 @@ export function OrganizationSettings({}setValues(payload.settings);+ setSavedConsentDisclosure(payload.settings.consentDisclosure);setEmailRevision((revision) => revision + 1);setFeedback({ message: "Organization settings saved.", tone: "success" });// The header and the accent color come from the layout around this@@ -388,9 +434,9 @@ export function OrganizationSettings({<p className="max-w-2xl text-sm leading-6 text-(--secondary)">Optional. Signers read this and tick a box to agree to useelectronic records and signatures before they sign. Leave it- empty to show the standard text. The words each signer saw are- kept with their record. Laws differ by place and by who signs,- so ask a lawyer before shortening it.+ empty to use the standard text, or press “Start from the+ standard text” to edit it. The words each signer saw are+ kept with their record.</p></div><Field className="gap-2 text-sm">@@ -434,6 +480,9 @@ export function OrganizationSettings({to write to goes.</FieldDescription>)}+ <p className="text-xs leading-5 text-(--secondary)">+ {CUSTOM_DISCLOSURE_LEGAL_NOTE}+ </p></Field><div className="flex flex-wrap gap-3"><ShellButton@@ -495,6 +544,48 @@ export function OrganizationSettings({</ShellButton></form>+ {isDisclosureNoticeOpen ? (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) {+ setIsDisclosureNoticeOpen(false);+ }+ }}+ >+ <DialogContent className="max-w-lg sm:p-8" showCloseButton={false}>+ <DialogHeader className="space-y-3">+ <DialogTitle>{CUSTOM_DISCLOSURE_NOTICE.title}</DialogTitle>+ <DialogDescription asChild>+ <div className="space-y-3 text-sm leading-6 text-(--secondary)">+ {CUSTOM_DISCLOSURE_NOTICE.paragraphs.map((paragraph) => (+ <p key={paragraph.text}>+ {paragraph.lead ? (+ <strong className="font-bold text-(--fg)">+ {paragraph.lead}{" "}+ </strong>+ ) : null}+ {paragraph.text}+ </p>+ ))}+ </div>+ </DialogDescription>+ </DialogHeader>+ <DialogFooter className="gap-3 sm:justify-end">+ <ShellButton+ onClick={() => setIsDisclosureNoticeOpen(false)}+ variant="secondary"+ >+ Cancel+ </ShellButton>+ <ShellButton onClick={() => void saveSettings(true)}>+ {CUSTOM_DISCLOSURE_NOTICE.agree}+ </ShellButton>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ ) : null}+<EmailSetupPanel key={emailRevision} />{/* The hosted service's accounts are strangers to each other, notdiff --git a/src/lib/consent-disclosure-notice.ts b/src/lib/consent-disclosure-notice.tsnew file mode 100644index 0000000..bed1f32--- /dev/null+++ b/src/lib/consent-disclosure-notice.ts@@ -0,0 +1,39 @@+// The notice an administrator agrees to before their own words replace the+// standard disclosure signers read. Kept apart from+// electronic-records-disclosure.ts, which runs only on the server, so the+// Organization form can show the same words.++/**+ * The notice an administrator must agree to before saving their own words+ * in place of the standard disclosure. The Organization form shows these+ * words, and the site audit trail keeps the version with each agreement, so+ * change the version whenever the words change.+ */+export const CUSTOM_DISCLOSURE_NOTICE_VERSION = "2026-11-20";++export const CUSTOM_DISCLOSURE_NOTICE = {+ title: "Before you change what signers agree to",+ paragraphs: [+ {+ lead: null,+ text: "The standard text tells signers what the U.S. E-SIGN Act requires before a consumer agrees to sign electronically: that they can choose paper instead, how to get a paper copy, how to withdraw and what that means, and what device and software they need. If you remove or change any of this, your signers' electronic signatures and records may not be valid under E-SIGN or other laws where you or your signers are.",+ },+ {+ lead: "One more thing, from us to you:",+ text: "we're software folks, not lawyers. Nothing in SignuDoc, including the standard text we include for your signers, is legal advice, and we can't promise any wording will hold up between you and the people who sign. Before you rely on this as part of a legal agreement, please run it past your own legal counsel. They know your business and where your signers are.",+ },+ ],+ agree: "I agree",+} as const;++/** Shown under the disclosure box in Settings, before anything is saved. */+export const CUSTOM_DISCLOSURE_LEGAL_NOTE =+ "We're not lawyers, and nothing here is legal advice, including the standard text we include for your signers. Please check any wording with your own legal counsel before you rely on it.";++/**+ * A disclosure tidied the way it is stored: the same line endings and the+ * ends trimmed. Empty means there is none.+ */+export function tidyDisclosureText(text: string | null | undefined): string {+ return (text ?? "").replace(/\r\n?/g, "\n").trim();+}diff --git a/src/lib/consent-disclosure.dbtest.ts b/src/lib/consent-disclosure.dbtest.tsnew file mode 100644index 0000000..595c018--- /dev/null+++ b/src/lib/consent-disclosure.dbtest.ts@@ -0,0 +1,233 @@+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 {+ ELECTRONIC_RECORDS_DISCLOSURE_VERSION,+ getDisclosureVersion,+} from "./electronic-records-disclosure.ts";+import { issueSigningLink } from "./services/signing-links.ts";+import { invalidateSettingsCache } from "./settings.ts";+import {+ getSigningPayloadForToken,+ recordSignerConsent,+ SigningMutationError,+} from "./signing.ts";++// An administrator's own disclosure against a real Postgres: the signing page+// shows it at once, consent is held to its version, and the audit trail keeps+// the words the signer read, filled in. Run with `npm run test:db`.++process.env.APP_URL ??= "https://sign.example.test";++let database: pg.Pool;+const createdUsers: string[] = [];+let disclosureBefore: string | null = null;+let hadSettingsRow = false;++before(async () => {+ database = await openTestDatabase();+ globalThis.__signudocPgPool = database;++ // There is one settings row for the whole database. Whatever other tests+ // left in it is put back afterwards.+ const existing = await database.query<{ consent_disclosure: string | null }>(+ "select consent_disclosure from public.app_settings where id",+ );++ hadSettingsRow = existing.rows.length > 0;+ disclosureBefore = existing.rows[0]?.consent_disclosure ?? null;+});++after(async () => {+ if (hadSettingsRow) {+ await database.query(+ "update public.app_settings set consent_disclosure = $1 where id",+ [disclosureBefore],+ );+ } else {+ await database.query("delete from public.app_settings where id");+ }++ invalidateSettingsCache();+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+});++async function setDisclosure(text: string | null) {+ const now = Math.floor(Date.now() / 1000);++ await database.query(+ `+ insert into public.app_settings (id, consent_disclosure, created_at, updated_at)+ values (true, $1, $2, $2)+ on conflict (id) do update set consent_disclosure = excluded.consent_disclosure+ `,+ [text, now],+ );+}++async function sentEnvelope() {+ const userId = randomUUID();+ const envelopeId = randomUUID();+ const signerId = randomUUID();+ const now = Math.floor(Date.now() / 1000);+ const link = await issueSigningLink({ expiresInSeconds: 600, issuedAt: now });++ createdUsers.push(userId);+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, 'Dollar $$ Consulting', $2, 'user')`,+ [userId, `${userId}@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+ ) values ($1, $2, 'Lease', 'sent', $3, 'lease.pdf', 10, 1, $4, $5)+ `,+ [envelopeId, userId, `test/${envelopeId}.pdf`, "a".repeat(64), now],+ );+ await database.query(+ `+ insert into signers (+ id, envelope_id, name, email, sign_order, status,+ signing_token_hash, signing_token_expires_at, last_notified_at+ ) values ($1, $2, 'Riley Recipient', $3, 1, 'notified', $4, $5, $6)+ `,+ [+ signerId,+ envelopeId,+ `${signerId}@example.test`,+ link.tokenHash,+ link.exp,+ now,+ ],+ );+ await database.query(+ `+ insert into fields (id, envelope_id, signer_id, type, page, x, y, width, height)+ values ($1, $2, $3, 'signature', 1, 0.1, 0.1, 0.2, 0.1)+ `,+ [randomUUID(), envelopeId, signerId],+ );++ return { envelopeId, token: link.token };+}++test("an administrator's own disclosure is shown, agreed to and kept, filled in", async () => {+ const custom = "## Signing with {sender}\nWe send this online.";++ await setDisclosure(custom);++ const { envelopeId, token } = await sentEnvelope();+ const payload = await getSigningPayloadForToken(token, { database });++ assert.equal(payload.disclosure.version, getDisclosureVersion(custom));+ assert.deepEqual(payload.disclosure.sections, [+ {+ heading: "Signing with Dollar $$ Consulting",+ text: "We send this online.",+ },+ ]);++ await recordSignerConsent(+ token,+ { disclosureVersion: payload.disclosure.version },+ { database },+ );++ const consented = await database.query<{+ metadata: { disclosureText?: string; disclosureVersion?: string };+ }>(+ `select metadata from audit_events where envelope_id = $1 and event = 'consented'`,+ [envelopeId],+ );++ assert.equal(consented.rows.length, 1);+ assert.equal(+ consented.rows[0]?.metadata.disclosureVersion,+ getDisclosureVersion(custom),+ );+ assert.equal(+ consented.rows[0]?.metadata.disclosureText,+ "Signing with Dollar $$ Consulting\nWe send this online.",+ );+});++test("a change to the disclosure shows at once, and the older version is refused", async () => {+ await setDisclosure("First words.");++ const { envelopeId, token } = await sentEnvelope();+ const first = await getSigningPayloadForToken(token, { database });++ // A change made elsewhere. The settings cache in this process still holds+ // the first words, and the signing page must not use it.+ await setDisclosure("Second words.");++ const second = await getSigningPayloadForToken(token, { database });++ assert.notEqual(second.disclosure.version, first.disclosure.version);+ assert.equal(+ second.disclosure.version,+ getDisclosureVersion("Second words."),+ );++ await assert.rejects(+ recordSignerConsent(+ token,+ { disclosureVersion: first.disclosure.version },+ { database },+ ),+ (error) => {+ assert.ok(error instanceof SigningMutationError);+ assert.equal(error.statusCode, 409);+ return true;+ },+ );++ await recordSignerConsent(+ token,+ { disclosureVersion: second.disclosure.version },+ { database },+ );++ const consented = await database.query(+ `select 1 from audit_events where envelope_id = $1 and event = 'consented'`,+ [envelopeId],+ );++ assert.equal(consented.rows.length, 1);+});++test("with no disclosure of its own the built-in one is used and no text is kept", async () => {+ await setDisclosure(null);++ const { envelopeId, token } = await sentEnvelope();+ const payload = await getSigningPayloadForToken(token, { database });++ assert.equal(+ payload.disclosure.version,+ ELECTRONIC_RECORDS_DISCLOSURE_VERSION,+ );++ await recordSignerConsent(+ token,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database },+ );++ const consented = await database.query<{+ metadata: { disclosureText?: string };+ }>(+ `select metadata from audit_events where envelope_id = $1 and event = 'consented'`,+ [envelopeId],+ );++ assert.equal(consented.rows[0]?.metadata.disclosureText, undefined);+});diff --git a/src/lib/electronic-records-disclosure.test.ts b/src/lib/electronic-records-disclosure.test.tsindex 8646a18..3a32aa3 100644--- a/src/lib/electronic-records-disclosure.test.ts+++ b/src/lib/electronic-records-disclosure.test.ts@@ -5,10 +5,12 @@ import {buildDisclosureSections,buildElectronicRecordsDisclosure,DISCLOSURE_MAX_LENGTH,+ disclosureSectionsAsText,ELECTRONIC_RECORDS_DISCLOSURE_VERSION,getDisclosureVersion,normalizeCustomDisclosure,standardDisclosureTemplate,+ toStoredCustomDisclosure,validateCustomDisclosure,} from "./electronic-records-disclosure.ts";@@ -137,3 +139,39 @@ test("the standard template, used as custom text, reads the same as the built-in}),);});++test("a dollar sign in a name or address is copied as it is", () => {+ const sections = buildDisclosureSections(+ { contactAddress: "[email protected]", senderName: "Dollar $$ $& Consulting" },+ "## From {sender}\nWrite to {contact}.",+ );++ assert.deepEqual(sections, [+ {+ heading: "From Dollar $$ $& Consulting",+ text: "Write to Dollar $$ $& Consulting at [email protected].",+ },+ ]);+});++test("the words a signer read are kept as one text, filled in", () => {+ const sections = buildDisclosureSections(+ party,+ "## Signing online\n{sender} asks you to sign online.\n\nWrite to {contact}.",+ );++ assert.equal(+ disclosureSectionsAsText(sections),+ "Signing online\nAcme Corp asks you to sign online.\n\nWrite to Acme Corp at [email protected].",+ );+});++test("the standard text saved unchanged is stored as no custom text", () => {+ assert.equal(toStoredCustomDisclosure(standardDisclosureTemplate()), null);+ assert.equal(+ toStoredCustomDisclosure(` ${standardDisclosureTemplate()}\r\n`),+ null,+ );+ assert.equal(toStoredCustomDisclosure("Our words."), "Our words.");+ assert.equal(toStoredCustomDisclosure(" "), null);+});diff --git a/src/lib/electronic-records-disclosure.ts b/src/lib/electronic-records-disclosure.tsindex e726664..27d6463 100644--- a/src/lib/electronic-records-disclosure.ts+++ b/src/lib/electronic-records-disclosure.ts@@ -10,6 +10,8 @@import { createHash } from "node:crypto";+import { tidyDisclosureText } from "./consent-disclosure-notice.ts";+export const ELECTRONIC_RECORDS_DISCLOSURE_VERSION = "2026-11-13";/** The longest custom disclosure, in characters. */@@ -88,7 +90,7 @@ export const CONSENT_STATEMENT =export function normalizeCustomDisclosure(text: string | null | undefined,): string | null {- const normalized = (text ?? "").replace(/\r\n?/g, "\n").trim();+ const normalized = tidyDisclosureText(text);return normalized.length === 0 ? null : normalized;}@@ -188,9 +190,41 @@ function fillPlaceholders(party: DisclosureParty,contact: string = contactFor(party),): string {+ // Callbacks, so a "$" in a name or address is copied as it is rather+ // than read as a replacement pattern.return text- .replaceAll("{sender}", party.senderName)- .replaceAll("{contact}", contact);+ .replaceAll("{sender}", () => party.senderName)+ .replaceAll("{contact}", () => contact);+}++/**+ * The sections as one text, the way the signer read them: a heading on its+ * own line above its paragraph, and a blank line between sections. It is+ * what the audit trail keeps of a custom disclosure.+ */+export function disclosureSectionsAsText(+ sections: readonly DisclosureSection[],+): string {+ return sections+ .map((section) =>+ section.heading ? `${section.heading}\n${section.text}` : section.text,+ )+ .join("\n\n");+}++/**+ * A custom disclosure as it is saved. The standard text saved unchanged is+ * the same as no custom text, so it is stored as none and keeps the+ * built-in version.+ */+export function toStoredCustomDisclosure(+ text: string | null | undefined,+): string | null {+ const normalized = normalizeCustomDisclosure(text);++ return normalized === normalizeCustomDisclosure(standardDisclosureTemplate())+ ? null+ : normalized;}/**diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.tsindex 38e9f75..6b96fa1 100644--- a/src/lib/organization-settings.test.ts+++ b/src/lib/organization-settings.test.ts@@ -2,7 +2,9 @@ import assert from "node:assert/strict";import { test } from "node:test";import type { DbExecutor } from "./db/connection.ts";+import { standardDisclosureTemplate } from "./electronic-records-disclosure.ts";import {+ CONSENT_DISCLOSURE_NOTICE_REQUIRED,diffSettings,OrganizationSettingsError,updateOrganizationSettings,@@ -293,6 +295,7 @@ test("a custom disclosure is tidied and saved, and empty puts the built-in one b{...form,consentDisclosure: " ## Signing online\r\nYou agree to sign online. ",+ consentDisclosureAcknowledged: true,},current,saved.database,@@ -314,6 +317,72 @@ test("a custom disclosure is tidied and saved, and empty puts the built-in one bassert.equal(cleared.consentDisclosure, null);});+test("saving words of one's own needs the notice agreed to first", async () => {+ const current = resolveSettings(stored, {});++ await assert.rejects(+ updateOrganizationSettings(+ { ...form, consentDisclosure: "You agree to sign online." },+ current,+ fakeDatabase().database,+ ),+ (error) => {+ assert.ok(error instanceof OrganizationSettingsError);+ assert.deepEqual(error.fieldErrors, {+ consentDisclosure: CONSENT_DISCLOSURE_NOTICE_REQUIRED,+ });+ return true;+ },+ );++ await assert.rejects(+ updateOrganizationSettings(+ {+ ...form,+ consentDisclosure: "You agree to sign online.",+ consentDisclosureAcknowledged: false,+ },+ current,+ fakeDatabase().database,+ ),+ OrganizationSettingsError,+ );+});++test("the same words again, the standard text, or none need no agreement", async () => {+ const withOwn = resolveSettings(+ { ...stored, consentDisclosure: "Custom words." },+ {},+ );+ const again = await updateOrganizationSettings(+ { ...form, consentDisclosure: " Custom words.\r\n" },+ withOwn,+ fakeDatabase({ ...storedRow, consent_disclosure: "Custom words." })+ .database,+ );++ assert.equal(again.consentDisclosure, "Custom words.");++ // The standard text saved unchanged is the built-in disclosure, so it is+ // stored as none and keeps the dated version.+ const standard = await updateOrganizationSettings(+ { ...form, consentDisclosure: standardDisclosureTemplate() },+ resolveSettings(stored, {}),+ fakeDatabase().database,+ );++ assert.equal(standard.consentDisclosure, null);++ const cleared = await updateOrganizationSettings(+ { ...form, consentDisclosure: "" },+ withOwn,+ fakeDatabase({ ...storedRow, consent_disclosure: "Custom words." })+ .database,+ );++ assert.equal(cleared.consentDisclosure, null);+});+test("a form that does not send the disclosure leaves it as it was", async () => {const current = resolveSettings({ ...stored, consentDisclosure: "Custom words." },diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.tsindex c39fcf0..248e9d4 100644--- a/src/lib/organization-settings.ts+++ b/src/lib/organization-settings.ts@@ -6,6 +6,7 @@ import { getDb, type DbExecutor } from "./db/connection.ts";import {normalizeCustomDisclosure,standardDisclosureTemplate,+ toStoredCustomDisclosure,validateCustomDisclosure,} from "./electronic-records-disclosure.ts";import { emailSchema } from "./schemas/common.ts";@@ -151,6 +152,9 @@ const organizationSettingsSchema = z.object({// Left out means unchanged. The length is judged after tidying, below; this// only keeps an absurd request from getting that far.consentDisclosure: z.string().max(20_000).optional(),+ // The administrator agreed to the notice about changing the disclosure.+ // Needed only when the saved words change to words of their own.+ consentDisclosureAcknowledged: z.boolean().optional(),organizationName: z.string().trim().min(1).max(120),privacyUrl: optionalWebUrl.default(null),retentionDays: z@@ -213,6 +217,30 @@ function withoutLockedFields(return input;}+export const CONSENT_DISCLOSURE_NOTICE_REQUIRED =+ 'Read the notice about changing what signers agree to, and press "I agree", before saving your own words.';++/**+ * Whether a save puts the administrator's own words in place of what+ * signers read now. Going back to the standard text, or saving the same+ * words again, does not.+ */+export function changesToOwnDisclosure(+ consentDisclosure: string | undefined,+ current: Pick<ResolvedSettings, "consentDisclosure">,+): boolean {+ if (consentDisclosure === undefined) {+ return false;+ }++ const next = toStoredCustomDisclosure(consentDisclosure);++ return (+ next !== null &&+ next !== normalizeCustomDisclosure(current.consentDisclosure)+ );+}+/*** Validates and saves the Organization form. Addresses that are fixed by an* environment variable are left as they are stored, since the stored value@@ -267,6 +295,11 @@ export async function updateOrganizationSettings(if (disclosureProblem !== null) {fieldErrors.consentDisclosure = disclosureProblem;+ } else if (+ changesToOwnDisclosure(input.consentDisclosure, current) &&+ input.consentDisclosureAcknowledged !== true+ ) {+ fieldErrors.consentDisclosure = CONSENT_DISCLOSURE_NOTICE_REQUIRED;}// Part 11 records are never deleted on a timer.@@ -292,7 +325,7 @@ export async function updateOrganizationSettings(...(input.consentDisclosure === undefined? {}: {- consentDisclosure: normalizeCustomDisclosure(+ consentDisclosure: toStoredCustomDisclosure(input.consentDisclosure,),}),diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex a43d3e4..cd0e225 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -47,7 +47,6 @@ import {} from "./schemas/signer.ts";import {getBranding,- getSettings,readStoredSettings,resolveSettings,} from "./settings.ts";@@ -106,6 +105,7 @@ import { describeEntryProblem, judgeRadioGroups } from "./field-choices.ts";import {buildDisclosureSections,CONSENT_STATEMENT,+ disclosureSectionsAsText,getDisclosureVersion,normalizeCustomDisclosure,} from "./electronic-records-disclosure.ts";@@ -1744,6 +1744,34 @@ export async function checkSigningFieldFit(: { fits: true };}+/**+ * The disclosure this signer reads, filled in for their sender. It is read+ * from the database, not the settings cache, so the signing page and the+ * consent check always agree on the words just after an administrator+ * changes them.+ */+async function readSignerDisclosure(+ context: SigningContext,+ database: DbExecutor,+) {+ const branding = await getBranding();+ const customDisclosure = normalizeCustomDisclosure(+ resolveSettings(await readStoredSettings(database)).consentDisclosure,+ );++ return {+ customDisclosure,+ sections: buildDisclosureSections(+ {+ contactAddress: branding.supportAddress ?? context.sender.email,+ senderName: normalizeSenderName(context.sender),+ },+ customDisclosure,+ ),+ version: getDisclosureVersion(customDisclosure),+ };+}+export async function recordSignerConsent(token: string,input: unknown,@@ -1761,12 +1789,8 @@ export async function recordSignerConsent(database,);- // Read from the database, not the settings cache, so that a disclosure an- // administrator has just changed is the one a signer is held to at once.- const customDisclosure = normalizeCustomDisclosure(- resolveSettings(await readStoredSettings(database)).consentDisclosure,- );- const disclosureVersion = getDisclosureVersion(customDisclosure);+ const disclosure = await readSignerDisclosure(context, database);+ const disclosureVersion = disclosure.version;if (parsed.disclosureVersion !== disclosureVersion) {throw new SigningMutationError(@@ -1834,10 +1858,13 @@ export async function recordSignerConsent(disclosureVersion,// The built-in words are known from their version. A custom// disclosure can be changed or taken away later, so the words the- // signer saw are kept with the record.- ...(customDisclosure === null+ // signer saw, filled in as they read them, are kept with the+ // record.+ ...(disclosure.customDisclosure === null? {}- : { disclosureText: customDisclosure }),+ : {+ disclosureText: disclosureSectionsAsText(disclosure.sections),+ }),statement: CONSENT_STATEMENT,},userAgent: requestMeta.userAgent ?? null,@@ -1990,10 +2017,7 @@ export async function getSigningPayloadForToken(database,);const storageService = createStorageService();- const branding = await getBranding();- const customDisclosure = normalizeCustomDisclosure(- (await getSettings()).consentDisclosure,- );+ const disclosure = await readSignerDisclosure(context, database);await recordViewedEventOnce(context, requestMeta, database);@@ -2064,15 +2088,9 @@ export async function getSigningPayloadForToken(consentedAt: checkState.consentedAt,currentSignerFields,disclosure: {- sections: buildDisclosureSections(- {- contactAddress: branding.supportAddress ?? context.sender.email,- senderName: normalizeSenderName(context.sender),- },- customDisclosure,- ),+ sections: disclosure.sections,statement: CONSENT_STATEMENT,- version: getDisclosureVersion(customDisclosure),+ version: disclosure.version,},declineUrl: getSigningDeclineUrl(token),documentUrl: getSigningDocumentUrl(token),