Skip to content

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

TypeScript

Let an administrator write the consent disclosure signers read

carefulcomputer15b71bd80d19
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 043f3b7..22c7f33 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,20 @@ 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". It starts from the built-in text, which stays the default when the
+ setting is empty. A heading line starts with `## `, and `{sender}` and
+ `{contact}` fill in who is asking and who to write to. The version recorded
+ with each signer's agreement follows the text, and the audit trail keeps the
+ words the signer saw. The hosted service keeps the built-in text.
+
+This release adds one database column, `app_settings.consent_disclosure`.
+The migration runs with the production build. Until it has, the setting reads
+as empty and signers see the built-in text.
+
## [0.5.2] - 2026-11-19
Twenty-four bug fixes. Seventeen fix reported issues (sixteen from @coygeek,
diff --git a/db/migrations/20261119130000_consent_disclosure.sql b/db/migrations/20261119130000_consent_disclosure.sql
new file mode 100644
index 0000000..a58797b
--- /dev/null
+++ b/db/migrations/20261119130000_consent_disclosure.sql
@@ -0,0 +1,14 @@
+-- Consent disclosure: the words a signer reads and agrees to before signing,
+-- which an administrator can now write for their own organization.
+--
+-- * app_settings.consent_disclosure: the administrator's own text. Null
+-- means the built-in disclosure is shown, as it was before this column.
+-- Blank lines separate paragraphs, and a paragraph that starts with "## "
+-- has a heading. See electronic-records-disclosure.ts.
+
+alter table public.app_settings
+ add column if not exists consent_disclosure text
+ check (
+ consent_disclosure is null
+ or char_length(consent_disclosure) between 1 and 6000
+ );
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 1ffbacb..e3a7162 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -154,6 +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.
- **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/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index 61f3fcd..b4a9b62 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -9,6 +9,13 @@ import { Part11Panel } from "@/components/settings/part11-panel";
import { PeoplePanel } from "@/components/settings/people-panel";
import { SecurityPanel } from "@/components/settings/security-panel";
import { SignerDataPanel } from "@/components/settings/signer-data-panel";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+} from "@/components/ui/field";
+import { Textarea } from "@/components/ui/textarea";
import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";
import type {
OrganizationSettingsField,
@@ -93,6 +100,15 @@ export function OrganizationSettings({
};
}
+ function setConsentDisclosure(consentDisclosure: string) {
+ setValues((currentValues) => ({ ...currentValues, consentDisclosure }));
+ setErrors((currentErrors) => ({
+ ...currentErrors,
+ consentDisclosure: undefined,
+ }));
+ setFeedback(null);
+ }
+
function handleBrandColorChange(brandColor: string) {
setValues((currentValues) => ({ ...currentValues, brandColor }));
setErrors((currentErrors) => ({ ...currentErrors, brandColor: undefined }));
@@ -125,6 +141,7 @@ export function OrganizationSettings({
body: JSON.stringify({
allowedEmailDomains: values.allowedEmailDomains,
brandColor: values.brandColor,
+ consentDisclosure: values.consentDisclosure,
organizationName: values.organizationName,
privacyUrl: values.privacyUrl,
retentionDays: values.retentionDays,
@@ -358,6 +375,85 @@ export function OrganizationSettings({
</div>
) : null}
+ {!values.hosted ? (
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
+ What signers agree to before signing
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ Optional. Signers read this and tick a box to agree to use
+ electronic 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.
+ </p>
+ </div>
+ <Field className="gap-2 text-sm">
+ <FieldLabel
+ className="text-[0.8125rem] font-semibold text-(--secondary)"
+ htmlFor="consent-disclosure"
+ >
+ Disclosure text
+ </FieldLabel>
+ <Textarea
+ aria-describedby="consent-disclosure-description"
+ aria-invalid={errors.consentDisclosure ? true : undefined}
+ className={
+ errors.consentDisclosure
+ ? "min-h-48 border-(--danger)"
+ : "min-h-48"
+ }
+ disabled={isSaving}
+ id="consent-disclosure"
+ maxLength={6000}
+ name="consent-disclosure"
+ onChange={(event) => setConsentDisclosure(event.target.value)}
+ placeholder="Standard text"
+ value={values.consentDisclosure}
+ />
+ {errors.consentDisclosure ? (
+ <FieldError
+ className="text-xs font-semibold text-(--danger)"
+ id="consent-disclosure-description"
+ >
+ {errors.consentDisclosure}
+ </FieldError>
+ ) : (
+ <FieldDescription
+ className="text-xs leading-5 text-(--tertiary)"
+ id="consent-disclosure-description"
+ >
+ Separate paragraphs with a blank line. Start a line with ##
+ and a space to make a heading. Write {"{sender}"} where the
+ sender&apos;s name goes and {"{contact}"} where the address
+ to write to goes.
+ </FieldDescription>
+ )}
+ </Field>
+ <div className="flex flex-wrap gap-3">
+ <ShellButton
+ disabled={isSaving}
+ onClick={() =>
+ setConsentDisclosure(values.defaultConsentDisclosure)
+ }
+ variant="secondary"
+ >
+ Start from the standard text
+ </ShellButton>
+ {values.consentDisclosure.length > 0 ? (
+ <ShellButton
+ disabled={isSaving}
+ onClick={() => setConsentDisclosure("")}
+ variant="ghost"
+ >
+ Use the standard text
+ </ShellButton>
+ ) : null}
+ </div>
+ </div>
+ ) : null}
+
<div className="space-y-5 border-t border-(--border) pt-8">
<div className="space-y-2">
<h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index 197de9f..76c9c36 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -1492,10 +1492,20 @@ export function SigningLiveShell({
title="Before you sign"
>
<div className="well max-h-[45vh] space-y-4 overflow-y-auto px-4 py-4 text-sm leading-6 text-(--secondary) sm:px-5">
- {record.disclosure.sections.map((section) => (
- <section key={section.heading}>
- <h3 className="font-bold text-(--fg)">{section.heading}</h3>
- <p className="mt-1">{section.text}</p>
+ {record.disclosure.sections.map((section, index) => (
+ <section key={`${index}-${section.heading}`}>
+ {section.heading ? (
+ <h3 className="font-bold text-(--fg)">{section.heading}</h3>
+ ) : null}
+ <p
+ className={
+ section.heading
+ ? "mt-1 whitespace-pre-line"
+ : "whitespace-pre-line"
+ }
+ >
+ {section.text}
+ </p>
</section>
))}
</div>
diff --git a/src/lib/electronic-records-disclosure.test.ts b/src/lib/electronic-records-disclosure.test.ts
new file mode 100644
index 0000000..8646a18
--- /dev/null
+++ b/src/lib/electronic-records-disclosure.test.ts
@@ -0,0 +1,139 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ buildDisclosureSections,
+ buildElectronicRecordsDisclosure,
+ DISCLOSURE_MAX_LENGTH,
+ ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ getDisclosureVersion,
+ normalizeCustomDisclosure,
+ standardDisclosureTemplate,
+ validateCustomDisclosure,
+} from "./electronic-records-disclosure.ts";
+
+const party = { contactAddress: "[email protected]", senderName: "Acme Corp" };
+
+test("with no custom text the built-in disclosure and its dated version are used", () => {
+ for (const custom of [null, undefined, "", " \n "]) {
+ assert.deepEqual(
+ buildDisclosureSections(party, custom),
+ buildElectronicRecordsDisclosure(party),
+ );
+ assert.equal(
+ getDisclosureVersion(custom),
+ ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ );
+ }
+});
+
+test("a custom disclosure is split on blank lines, with headings where marked", () => {
+ const sections = buildDisclosureSections(
+ party,
+ "## Signing online\nBy signing you agree to use electronic records.\n\nContact us any time.\r\n\r\n\r\n Thank you. ",
+ );
+
+ assert.deepEqual(sections, [
+ {
+ heading: "Signing online",
+ text: "By signing you agree to use electronic records.",
+ },
+ { heading: "", text: "Contact us any time." },
+ { heading: "", text: "Thank you." },
+ ]);
+});
+
+test("{sender} and {contact} are filled in, in the heading and the text", () => {
+ const sections = buildDisclosureSections(
+ party,
+ "## From {sender}\n{sender} asks you to sign. Write to {contact}.",
+ );
+
+ assert.deepEqual(sections, [
+ {
+ heading: "From Acme Corp",
+ text: "Acme Corp asks you to sign. Write to Acme Corp at [email protected].",
+ },
+ ]);
+
+ // With no address to write to, the contact is just the sender.
+ assert.equal(
+ buildDisclosureSections(
+ { contactAddress: null, senderName: "Acme Corp" },
+ "Write to {contact}.",
+ )[0]?.text,
+ "Write to Acme Corp.",
+ );
+});
+
+test("the version of a custom text follows the text and nothing else", () => {
+ const first = getDisclosureVersion("Agree to sign online.");
+
+ assert.match(first, /^custom-[0-9a-f]{12}$/);
+ // The consent request allows a version of up to 40 characters.
+ assert.ok(first.length <= 40);
+ // Line endings and the ends of the text do not make a new version.
+ assert.equal(getDisclosureVersion(" Agree to sign online.\r\n"), first);
+ assert.notEqual(getDisclosureVersion("Agree to sign online!"), first);
+ assert.notEqual(first, ELECTRONIC_RECORDS_DISCLOSURE_VERSION);
+});
+
+test("normalizing makes line endings the same and treats blank text as none", () => {
+ assert.equal(normalizeCustomDisclosure(" a\r\nb\rc "), "a\nb\nc");
+ assert.equal(normalizeCustomDisclosure(""), null);
+ assert.equal(normalizeCustomDisclosure(" \n"), null);
+ assert.equal(normalizeCustomDisclosure(null), null);
+ assert.equal(normalizeCustomDisclosure(undefined), null);
+});
+
+test("a heading needs words under it, and the text has a length limit", () => {
+ assert.equal(validateCustomDisclosure(null), null);
+ assert.equal(validateCustomDisclosure(""), null);
+ assert.equal(validateCustomDisclosure("## Heading\nWords."), null);
+ assert.equal(validateCustomDisclosure("Just a paragraph."), null);
+
+ assert.match(
+ validateCustomDisclosure("## Heading only") ?? "",
+ /under each heading/,
+ );
+ assert.match(
+ validateCustomDisclosure("Fine.\n\n## Heading only") ?? "",
+ /under each heading/,
+ );
+ assert.match(validateCustomDisclosure("## \nWords.") ?? "", /under each/);
+
+ assert.equal(
+ validateCustomDisclosure("a".repeat(DISCLOSURE_MAX_LENGTH)),
+ null,
+ );
+ assert.match(
+ validateCustomDisclosure("a".repeat(DISCLOSURE_MAX_LENGTH + 1)) ?? "",
+ /characters or fewer/,
+ );
+});
+
+test("a heading with nothing under it is shown as a paragraph, not dropped", () => {
+ assert.deepEqual(buildDisclosureSections(party, "## Only a heading"), [
+ { heading: "", text: "Only a heading" },
+ ]);
+});
+
+test("the standard template, used as custom text, reads the same as the built-in words", () => {
+ const template = standardDisclosureTemplate();
+
+ assert.equal(validateCustomDisclosure(template), null);
+ assert.deepEqual(
+ buildDisclosureSections(party, template),
+ buildElectronicRecordsDisclosure(party),
+ );
+ assert.deepEqual(
+ buildDisclosureSections(
+ { contactAddress: null, senderName: "Jordan Lee" },
+ template,
+ ),
+ buildElectronicRecordsDisclosure({
+ contactAddress: null,
+ senderName: "Jordan Lee",
+ }),
+ );
+});
diff --git a/src/lib/electronic-records-disclosure.ts b/src/lib/electronic-records-disclosure.ts
index b78dae2..e726664 100644
--- a/src/lib/electronic-records-disclosure.ts
+++ b/src/lib/electronic-records-disclosure.ts
@@ -3,32 +3,48 @@
// works as a plain statement of terms elsewhere. Its version is stored with
// each signer's agreement, so the record shows which words they saw. Change
// the version whenever the words change.
+//
+// An administrator can replace the built-in words with their own under
+// Settings, Organization. That text has no number to bump, so its version is
+// taken from the text itself: change a word and the version changes.
+
+import { createHash } from "node:crypto";
export const ELECTRONIC_RECORDS_DISCLOSURE_VERSION = "2026-11-13";
+/** The longest custom disclosure, in characters. */
+export const DISCLOSURE_MAX_LENGTH = 6000;
+
+const HEADING_MARK = "## ";
+
export type DisclosureParty = {
/** Who to ask for a paper copy or to withdraw: the organization or sender. */
contactAddress: string | null;
senderName: string;
};
+/** A section with no heading is shown as a plain paragraph. */
export type DisclosureSection = { heading: string; text: string };
-export function buildElectronicRecordsDisclosure(
- party: DisclosureParty,
-): DisclosureSection[] {
- const contact = party.contactAddress
+function contactFor(party: DisclosureParty): string {
+ return party.contactAddress
? `${party.senderName} at ${party.contactAddress}`
: party.senderName;
+}
+/** The built-in words, with who is asking and who to write to given as text. */
+function standardSections(
+ sender: string,
+ contact: string,
+): DisclosureSection[] {
return [
{
heading: "Using electronic records and signatures",
- text: `${party.senderName} asks you to receive this document and sign it electronically instead of on paper. If you agree, your electronic signature has the same effect as a handwritten one, and the documents you receive this way count as delivered to you in writing.`,
+ text: `${sender} asks you to receive this document and sign it electronically instead of on paper. If you agree, your electronic signature has the same effect as a handwritten one, and the documents you receive this way count as delivered to you in writing.`,
},
{
heading: "You can choose paper instead",
- text: `You do not have to agree. To sign on paper instead, or to ask for a paper copy of any document after signing, contact ${contact}. A paper copy is free unless ${party.senderName} tells you otherwise before you ask.`,
+ text: `You do not have to agree. To sign on paper instead, or to ask for a paper copy of any document after signing, contact ${contact}. A paper copy is free unless ${sender} tells you otherwise before you ask.`,
},
{
heading: "Withdrawing your agreement",
@@ -45,5 +61,156 @@ export function buildElectronicRecordsDisclosure(
];
}
+export function buildElectronicRecordsDisclosure(
+ party: DisclosureParty,
+): DisclosureSection[] {
+ return standardSections(party.senderName, contactFor(party));
+}
+
+/**
+ * The built-in words written as a custom disclosure, with {sender} and
+ * {contact} where the sender's name and the address to write to go. It is
+ * what the Organization form offers as a starting point to change.
+ */
+export function standardDisclosureTemplate(): string {
+ return standardSections("{sender}", "{contact}")
+ .map((section) => `${HEADING_MARK}${section.heading}\n${section.text}`)
+ .join("\n\n");
+}
+
export const CONSENT_STATEMENT =
"I have read the disclosure above, I can open and save PDF files on this device, and I agree to use electronic records and signatures for this document.";
+
+/**
+ * A custom disclosure as it is stored: line endings made the same and the
+ * ends trimmed. Empty means there is none, and the built-in words are used.
+ */
+export function normalizeCustomDisclosure(
+ text: string | null | undefined,
+): string | null {
+ const normalized = (text ?? "").replace(/\r\n?/g, "\n").trim();
+
+ return normalized.length === 0 ? null : normalized;
+}
+
+/** Splits a custom disclosure into its paragraphs, before anything is filled in. */
+function splitParagraphs(text: string): string[] {
+ return text
+ .split(/\n[ \t]*\n/)
+ .map((paragraph) => paragraph.trim())
+ .filter((paragraph) => paragraph.length > 0);
+}
+
+function splitHeading(paragraph: string): {
+ body: string;
+ heading: string | null;
+} {
+ if (!paragraph.startsWith(HEADING_MARK)) {
+ return { body: paragraph, heading: null };
+ }
+
+ const [firstLine = "", ...rest] = paragraph.split("\n");
+
+ return {
+ body: rest.join("\n").trim(),
+ heading: firstLine.slice(HEADING_MARK.length).trim(),
+ };
+}
+
+/**
+ * Why a custom disclosure cannot be saved, or null when it can. A heading
+ * needs words under it, because a section with only a heading would show
+ * the signer nothing to agree to.
+ */
+export function validateCustomDisclosure(
+ text: string | null | undefined,
+): string | null {
+ const normalized = normalizeCustomDisclosure(text);
+
+ if (normalized === null) {
+ return null;
+ }
+
+ if (normalized.length > DISCLOSURE_MAX_LENGTH) {
+ return `Keep this to ${DISCLOSURE_MAX_LENGTH} characters or fewer.`;
+ }
+
+ for (const paragraph of splitParagraphs(normalized)) {
+ const { body, heading } = splitHeading(paragraph);
+
+ if (heading !== null && (heading.length === 0 || body.length === 0)) {
+ return 'Put some words under each heading. A heading is a line that starts with "## ".';
+ }
+ }
+
+ return null;
+}
+
+/**
+ * The sections a signer reads. A custom disclosure is split on blank lines,
+ * and {sender} and {contact} are filled in with who is asking and who to
+ * write to, as the built-in words do.
+ */
+export function buildDisclosureSections(
+ party: DisclosureParty,
+ customText: string | null | undefined,
+): DisclosureSection[] {
+ const normalized = normalizeCustomDisclosure(customText);
+
+ if (normalized === null) {
+ return buildElectronicRecordsDisclosure(party);
+ }
+
+ const contact = contactFor(party);
+ const sections: DisclosureSection[] = [];
+
+ for (const paragraph of splitParagraphs(normalized)) {
+ const { body, heading } = splitHeading(paragraph);
+ // A heading with nothing under it cannot be saved, but is not dropped if
+ // one got in: its words are shown as a paragraph.
+ const text = body.length > 0 ? body : (heading ?? "");
+
+ if (text.length === 0) {
+ continue;
+ }
+
+ sections.push({
+ heading: body.length > 0 ? fillPlaceholders(heading ?? "", party) : "",
+ text: fillPlaceholders(text, party, contact),
+ });
+ }
+
+ return sections;
+}
+
+function fillPlaceholders(
+ text: string,
+ party: DisclosureParty,
+ contact: string = contactFor(party),
+): string {
+ return text
+ .replaceAll("{sender}", party.senderName)
+ .replaceAll("{contact}", contact);
+}
+
+/**
+ * Names the words a signer agreed to. The built-in words keep their dated
+ * version. A custom text is named by a short fingerprint of the text, so the
+ * version changes whenever the text does, whoever wrote it.
+ */
+export function getDisclosureVersion(
+ customText: string | null | undefined,
+): string {
+ const normalized = normalizeCustomDisclosure(customText);
+
+ if (normalized === null) {
+ return ELECTRONIC_RECORDS_DISCLOSURE_VERSION;
+ }
+
+ const fingerprint = createHash("sha256")
+ .update(normalized)
+ .digest("hex")
+ .slice(0, 12);
+
+ return `custom-${fingerprint}`;
+}
diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.ts
index aa5d1a2..b1b42ac 100644
--- a/src/lib/email-status.test.ts
+++ b/src/lib/email-status.test.ts
@@ -14,6 +14,7 @@ import { resolveSettings, type AppSettings } from "./settings.ts";
const stored: AppSettings = {
allowedEmailDomains: ["acme.com"],
brandColor: null,
+ consentDisclosure: null,
emailReadyAt: null,
logoVersion: null,
organizationName: "Acme Corp",
diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.ts
index e9b5c77..38e9f75 100644
--- a/src/lib/organization-settings.test.ts
+++ b/src/lib/organization-settings.test.ts
@@ -3,6 +3,7 @@ import { test } from "node:test";
import type { DbExecutor } from "./db/connection.ts";
import {
+ diffSettings,
OrganizationSettingsError,
updateOrganizationSettings,
} from "./organization-settings.ts";
@@ -11,6 +12,7 @@ import { resolveSettings, type AppSettings } from "./settings.ts";
const stored: AppSettings = {
allowedEmailDomains: ["acme.com"],
brandColor: null,
+ consentDisclosure: null,
emailReadyAt: null,
logoVersion: null,
organizationName: "Acme Corp",
@@ -30,6 +32,7 @@ const stored: AppSettings = {
const storedRow = {
allowed_email_domains: stored.allowedEmailDomains,
brand_color: stored.brandColor,
+ consent_disclosure: stored.consentDisclosure,
email_ready_at: stored.emailReadyAt,
logo_hash: stored.logoVersion,
organization_name: stored.organizationName,
@@ -282,3 +285,93 @@ test("the hosted service keeps its own color whatever the form sends", async ()
assert.equal(result.brandColor, null);
});
+
+test("a custom disclosure is tidied and saved, and empty puts the built-in one back", async () => {
+ const current = resolveSettings(stored, {});
+ const saved = fakeDatabase();
+ const result = await updateOrganizationSettings(
+ {
+ ...form,
+ consentDisclosure: " ## Signing online\r\nYou agree to sign online. ",
+ },
+ current,
+ saved.database,
+ );
+
+ assert.equal(
+ result.consentDisclosure,
+ "## Signing online\nYou agree to sign online.",
+ );
+ assert.ok(saved.saved.values?.includes(result.consentDisclosure));
+
+ const cleared = await updateOrganizationSettings(
+ { ...form, consentDisclosure: " " },
+ resolveSettings({ ...stored, consentDisclosure: "Custom words." }, {}),
+ 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." },
+ {},
+ );
+ const result = await updateOrganizationSettings(
+ { ...form, organizationName: "Acme Corporation" },
+ current,
+ fakeDatabase({ ...storedRow, consent_disclosure: "Custom words." })
+ .database,
+ );
+
+ assert.equal(result.organizationName, "Acme Corporation");
+ assert.equal(result.consentDisclosure, "Custom words.");
+});
+
+test("a disclosure with a heading and no words, or one that is too long, is refused", async () => {
+ const current = resolveSettings(stored, {});
+
+ for (const consentDisclosure of ["## Only a heading", "a".repeat(6001)]) {
+ const { database, saved } = fakeDatabase();
+
+ await assert.rejects(
+ updateOrganizationSettings(
+ { ...form, consentDisclosure },
+ current,
+ database,
+ ),
+ (error: unknown) => {
+ assert.ok(error instanceof OrganizationSettingsError);
+ assert.deepEqual(Object.keys(error.fieldErrors), ["consentDisclosure"]);
+
+ return true;
+ },
+ );
+ assert.equal(saved.values, null);
+ }
+});
+
+test("the hosted service keeps its own disclosure whatever the form sends", async () => {
+ const current = resolveSettings(stored, { HOSTED_MODE: "1" });
+ const { database } = fakeDatabase();
+ const result = await updateOrganizationSettings(
+ { ...form, consentDisclosure: "Our own words." },
+ current,
+ database,
+ );
+
+ assert.equal(result.consentDisclosure, null);
+});
+
+test("a change to the disclosure is listed in the audit trail", () => {
+ const changes = diffSettings(stored, {
+ ...stored,
+ consentDisclosure: "Custom words.",
+ });
+
+ assert.deepEqual(changes, {
+ consentDisclosure: { from: null, to: "Custom words." },
+ });
+});
diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.ts
index f8d105f..c39fcf0 100644
--- a/src/lib/organization-settings.ts
+++ b/src/lib/organization-settings.ts
@@ -3,6 +3,11 @@ import { z } from "zod";
import { normalizeBrandColor } from "./brand-color.ts";
import { buildBrandLogoPath } from "./branding.ts";
import { getDb, type DbExecutor } from "./db/connection.ts";
+import {
+ normalizeCustomDisclosure,
+ standardDisclosureTemplate,
+ validateCustomDisclosure,
+} from "./electronic-records-disclosure.ts";
import { emailSchema } from "./schemas/common.ts";
import {
saveSettings,
@@ -16,6 +21,7 @@ import { parseEmailDomainList, SIGNUP_MODES } from "./signup-policy.ts";
export type OrganizationSettingsField =
| "allowedEmailDomains"
| "brandColor"
+ | "consentDisclosure"
| "organizationName"
| "privacyUrl"
| "retentionDays"
@@ -39,6 +45,10 @@ export type OrganizationSettingsView = {
allowedEmailDomains: string;
/** "#rrggbb", or empty for the default color. */
brandColor: string;
+ /** The administrator's own disclosure, or empty for the built-in one. */
+ consentDisclosure: string;
+ /** The built-in disclosure as a template, to start a custom one from. */
+ defaultConsentDisclosure: string;
hosted: boolean;
/** Part 11 mode is on: the retention period cannot be set. */
part11Mode: boolean;
@@ -68,6 +78,8 @@ export function toOrganizationSettingsView(
return {
allowedEmailDomains: settings.allowedEmailDomains.join(", "),
brandColor: settings.brandColor ?? "",
+ consentDisclosure: settings.consentDisclosure ?? "",
+ defaultConsentDisclosure: standardDisclosureTemplate(),
hosted: settings.hosted,
logoUrl:
settings.logoVersion === null
@@ -136,6 +148,9 @@ const optionalBrandColor = z.preprocess(
const organizationSettingsSchema = z.object({
allowedEmailDomains: z.string().max(4000).default(""),
brandColor: optionalBrandColor.default(null),
+ // 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(),
organizationName: z.string().trim().min(1).max(120),
privacyUrl: optionalWebUrl.default(null),
retentionDays: z
@@ -154,6 +169,7 @@ const organizationSettingsSchema = z.object({
const FIELD_MESSAGES: Record<OrganizationSettingsField, string> = {
allowedEmailDomains: "Enter one or more domains, such as yourcompany.com",
brandColor: "Enter a color as six letters and digits, such as #1a73e8",
+ consentDisclosure: "Enter the words signers should read, or leave this empty",
organizationName: "Enter the name of your organization",
privacyUrl: "Enter a full web address starting with https://",
retentionDays: "Enter a number of days, 30 or more, or leave this empty",
@@ -189,6 +205,7 @@ function withoutLockedFields(
if (current.hosted) {
delete input.brandColor;
+ delete input.consentDisclosure;
delete input.privacyUrl;
delete input.termsUrl;
}
@@ -246,6 +263,12 @@ export async function updateOrganizationSettings(
fieldErrors.supportAddress = FIELD_MESSAGES.supportAddress;
}
+ const disclosureProblem = validateCustomDisclosure(input.consentDisclosure);
+
+ if (disclosureProblem !== null) {
+ fieldErrors.consentDisclosure = disclosureProblem;
+ }
+
// Part 11 records are never deleted on a timer.
if (current.part11Mode && input.retentionDays !== null) {
fieldErrors.retentionDays =
@@ -266,6 +289,13 @@ export async function updateOrganizationSettings(
? {}
: {
brandColor: input.brandColor,
+ ...(input.consentDisclosure === undefined
+ ? {}
+ : {
+ consentDisclosure: normalizeCustomDisclosure(
+ input.consentDisclosure,
+ ),
+ }),
privacyUrl: input.privacyUrl,
termsUrl: input.termsUrl,
}),
@@ -283,6 +313,7 @@ export async function updateOrganizationSettings(
const AUDITED_SETTINGS = [
"allowedEmailDomains",
"brandColor",
+ "consentDisclosure",
"organizationName",
"privacyUrl",
"retentionDays",
diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.ts
index f8630af..7a0e063 100644
--- a/src/lib/schemas/signing.ts
+++ b/src/lib/schemas/signing.ts
@@ -55,7 +55,8 @@ export const signingVisibleFieldSchema = signingFieldBaseSchema.extend({
export const signingDisclosureSchema = z.object({
sections: z.array(
z.object({
- heading: z.string().trim().min(1),
+ // Empty when the section is a plain paragraph with no heading.
+ heading: z.string().trim(),
text: z.string().trim().min(1),
}),
),
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
index 0cc3247..e254ef3 100644
--- a/src/lib/settings.test.ts
+++ b/src/lib/settings.test.ts
@@ -11,6 +11,7 @@ import {
const stored: AppSettings = {
allowedEmailDomains: ["acme.com"],
brandColor: null,
+ consentDisclosure: null,
emailReadyAt: null,
logoVersion: null,
organizationName: "Acme Corp",
@@ -64,6 +65,17 @@ test("hosted mode is switched on by HOSTED_MODE", () => {
assert.equal(resolveSettings(null, { HOSTED_MODE: "" }).hosted, false);
});
+test("a stored disclosure is used, except on the hosted service", () => {
+ const custom = { ...stored, consentDisclosure: "Our own words." };
+
+ assert.equal(resolveSettings(custom, {}).consentDisclosure, "Our own words.");
+ assert.equal(
+ resolveSettings(custom, { HOSTED_MODE: "1" }).consentDisclosure,
+ null,
+ );
+ assert.equal(resolveSettings(null, {}).consentDisclosure, null);
+});
+
test("a neutral install goes by the organization's name and links", () => {
assert.deepEqual(buildBranding(resolveSettings(stored, {})), {
brandColor: null,
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 801c135..5a083c6 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -27,6 +27,12 @@ export type AppSettings = {
allowedEmailDomains: string[];
/** The install's own color as "#rrggbb", or null for the default. */
brandColor: string | null;
+ /**
+ * The administrator's own words for what a signer reads and agrees to
+ * before signing, or null for the built-in disclosure. See
+ * electronic-records-disclosure.ts.
+ */
+ consentDisclosure: string | null;
emailReadyAt: number | null;
/**
* A short hash of the install's logo, or null when it has none. The logo
@@ -98,6 +104,7 @@ export type SetupRequiredDecision = {
type AppSettingsRow = {
allowed_email_domains: string[] | null;
brand_color: string | null;
+ consent_disclosure: string | null;
email_ready_at: number | null;
logo_hash: string | null;
organization_name: string | null;
@@ -138,6 +145,7 @@ const LATER_SETTINGS_COLUMNS = [
["part11_mode"], // 20261115090000_part11_mode
["require_two_factor"], // 20261117090000_sign_in_security
["session_idle_minutes", "session_max_hours"], // 20261117100000_session_controls
+ ["consent_disclosure"], // 20261119130000_consent_disclosure
] as const;
type LaterSettingsColumn = (typeof LATER_SETTINGS_COLUMNS)[number][number];
@@ -162,6 +170,7 @@ const SETTINGS_COLUMNS = settingsColumnsAfter(LATER_SETTINGS_COLUMNS.length);
const UNSET_SETTINGS: AppSettings = {
allowedEmailDomains: [],
brandColor: null,
+ consentDisclosure: null,
emailReadyAt: null,
logoVersion: null,
organizationName: null,
@@ -240,6 +249,7 @@ function mapSettingsRow(row: StoredSettingsRow): AppSettings {
return {
allowedEmailDomains: row.allowed_email_domains ?? [],
brandColor: row.brand_color ?? null,
+ consentDisclosure: row.consent_disclosure ?? null,
emailReadyAt: row.email_ready_at,
logoVersion: row.logo_hash ?? null,
organizationName: row.organization_name,
@@ -323,10 +333,13 @@ export function resolveSettings(
): ResolvedSettings {
const emailEnv = getEnv(env).email;
const settings = stored ?? UNSET_SETTINGS;
+ const hosted = isHostedMode(env);
return {
...settings,
- hosted: isHostedMode(env),
+ // The hosted service shows its own disclosure whatever is stored.
+ consentDisclosure: hosted ? null : settings.consentDisclosure,
+ hosted,
senderAddress: emailEnv.senderAddress ?? settings.senderAddress,
senderAddressFromEnv: emailEnv.senderAddress !== undefined,
supportAddress: emailEnv.supportAddress ?? settings.supportAddress,
@@ -420,10 +433,11 @@ async function saveSettingsLocked(
require_two_factor,
session_idle_minutes,
session_max_hours,
+ consent_disclosure,
created_at,
updated_at
)
- values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $14, $15, $16, $10, $10)
+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $14, $15, $16, $17, $10, $10)
on conflict (id) do update set
allowed_email_domains = excluded.allowed_email_domains,
email_ready_at = excluded.email_ready_at,
@@ -440,6 +454,7 @@ async function saveSettingsLocked(
require_two_factor = excluded.require_two_factor,
session_idle_minutes = excluded.session_idle_minutes,
session_max_hours = excluded.session_max_hours,
+ consent_disclosure = excluded.consent_disclosure,
updated_at = excluded.updated_at
returning ${SETTINGS_COLUMNS}
`,
@@ -460,6 +475,7 @@ async function saveSettingsLocked(
next.requireTwoFactor,
next.sessionIdleMinutes,
next.sessionMaxHours,
+ next.consentDisclosure,
],
);
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index e721ff4..99428d1 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -45,7 +45,12 @@ import {
signerRecordSchema,
type CopyRecipientRecord,
} from "./schemas/signer.ts";
-import { getBranding } from "./settings.ts";
+import {
+ getBranding,
+ getSettings,
+ readStoredSettings,
+ resolveSettings,
+} from "./settings.ts";
import {
checkSigningCredentials,
MAX_SIGNING_PASSWORD_ATTEMPTS,
@@ -98,9 +103,10 @@ import {
} from "./envelope-deadline.ts";
import { describeEntryProblem, judgeRadioGroups } from "./field-choices.ts";
import {
- buildElectronicRecordsDisclosure,
+ buildDisclosureSections,
CONSENT_STATEMENT,
- ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ getDisclosureVersion,
+ normalizeCustomDisclosure,
} from "./electronic-records-disclosure.ts";
import {
checkAccessCode,
@@ -1732,7 +1738,14 @@ export async function recordSignerConsent(
database,
);
- if (parsed.disclosureVersion !== ELECTRONIC_RECORDS_DISCLOSURE_VERSION) {
+ // 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);
+
+ if (parsed.disclosureVersion !== disclosureVersion) {
throw new SigningMutationError(
"The disclosure has changed. Reload the page to read the current one.",
409,
@@ -1795,7 +1808,13 @@ export async function recordSignerConsent(
ipAddress: requestMeta.ipAddress ?? null,
metadata: {
...signerAuditMetadata(context),
- disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ 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
+ ? {}
+ : { disclosureText: customDisclosure }),
statement: CONSENT_STATEMENT,
},
userAgent: requestMeta.userAgent ?? null,
@@ -1949,6 +1968,9 @@ export async function getSigningPayloadForToken(
);
const storageService = createStorageService();
const branding = await getBranding();
+ const customDisclosure = normalizeCustomDisclosure(
+ (await getSettings()).consentDisclosure,
+ );
await recordViewedEventOnce(context, requestMeta, database);
@@ -2019,12 +2041,15 @@ export async function getSigningPayloadForToken(
consentedAt: checkState.consentedAt,
currentSignerFields,
disclosure: {
- sections: buildElectronicRecordsDisclosure({
- contactAddress: branding.supportAddress ?? context.sender.email,
- senderName: normalizeSenderName(context.sender),
- }),
+ sections: buildDisclosureSections(
+ {
+ contactAddress: branding.supportAddress ?? context.sender.email,
+ senderName: normalizeSenderName(context.sender),
+ },
+ customDisclosure,
+ ),
statement: CONSENT_STATEMENT,
- version: ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ version: getDisclosureVersion(customDisclosure),
},
declineUrl: getSigningDeclineUrl(token),
documentUrl: getSigningDocumentUrl(token),