Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(legal-pages): render hosted legal pages without SUPPORT_EMAIL (#229)
Kevin Roseeebb02fc4721
diff --git a/src/app/accessibility/page.tsx b/src/app/accessibility/page.tsxindex bd9ade1..393e215 100644--- a/src/app/accessibility/page.tsx+++ b/src/app/accessibility/page.tsx@@ -1,9 +1,10 @@import type { Metadata } from "next";-import Link from "next/link";+import { LegalInlineText } from "@/components/layout/legal-inline-text";import { PublicDocumentShell } from "@/components/layout/public-document-shell";import { requireHostedMode } from "@/lib/hosted-pages";-import { resolvePublicSupportAddress } from "@/lib/public-contact";+import { buildLegalContactParts } from "@/lib/legal";+import { findPublicSupportAddress } from "@/lib/public-contact";export const metadata: Metadata = {description:@@ -14,7 +15,7 @@ export const metadata: Metadata = {export default async function AccessibilityPage() {await requireHostedMode();- const supportAddress = await resolvePublicSupportAddress();+ const supportAddress = await findPublicSupportAddress();return (<PublicDocumentShell@@ -90,15 +91,13 @@ export default async function AccessibilityPage() {Alternative assistance</h2><p>- If you need help creating, sending, reviewing, or signing a document,- email{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href={`mailto:${supportAddress}`}- >- {supportAddress}- </Link>- . Tell us what part of the workflow you are trying to complete, what+ <LegalInlineText+ parts={buildLegalContactParts(+ "accessibility_assistance",+ supportAddress,+ )}+ />{" "}+ Tell us what part of the workflow you are trying to complete, whatassistive technology you use if you are comfortable sharing it, andwhat kind of accommodation would help.</p>@@ -131,22 +130,12 @@ export default async function AccessibilityPage() {Feedback</h2><p>- Accessibility feedback helps us prioritize the right fixes. If you- find a barrier, email{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href={`mailto:${supportAddress}`}- >- {supportAddress}- </Link>{" "}- or use the{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href="/contact"- >- Contact- </Link>{" "}- page.+ <LegalInlineText+ parts={buildLegalContactParts(+ "accessibility_feedback",+ supportAddress,+ )}+ /></p></section></PublicDocumentShell>diff --git a/src/app/electronic-signatures/page.tsx b/src/app/electronic-signatures/page.tsxindex 9803654..acd8139 100644--- a/src/app/electronic-signatures/page.tsx+++ b/src/app/electronic-signatures/page.tsx@@ -2,6 +2,7 @@ import type { Metadata } from "next";import { connection } from "next/server";import { PublicDocumentShell } from "@/components/layout/public-document-shell";+import { buildBranding } from "@/lib/branding";import {EU_LIMITS,PERMITTED_USE_VERSION,@@ -9,7 +10,7 @@ import {WHAT_IT_IS,WHAT_IT_IS_NOT,} from "@/lib/permitted-uses";-import { getBranding } from "@/lib/settings";+import { getBranding, resolveSettings } from "@/lib/settings";export const metadata: Metadata = {description:@@ -27,12 +28,20 @@ function List({ items }: { items: string[] }) {);}+async function loadProductName(): Promise<string> {+ try {+ return (await getBranding()).productName;+ } catch {+ return buildBranding(resolveSettings(null)).productName;+ }+}+// On every install, hosted or not: senders confirm this list before each// send, and signers can read it.export default async function ElectronicSignaturesPage() {await connection();- const { productName } = await getBranding();+ const productName = await loadProductName();return (<PublicDocumentShelldiff --git a/src/app/privacy/page.tsx b/src/app/privacy/page.tsxindex b6bbc89..e0a6755 100644--- a/src/app/privacy/page.tsx+++ b/src/app/privacy/page.tsx@@ -1,9 +1,10 @@import type { Metadata } from "next";-import Link from "next/link";+import { LegalInlineText } from "@/components/layout/legal-inline-text";import { PublicDocumentShell } from "@/components/layout/public-document-shell";import { requireHostedMode } from "@/lib/hosted-pages";-import { resolvePublicSupportAddress } from "@/lib/public-contact";+import { buildLegalContactParts } from "@/lib/legal";+import { findPublicSupportAddress } from "@/lib/public-contact";export const metadata: Metadata = {description:@@ -14,7 +15,7 @@ export const metadata: Metadata = {export default async function PrivacyPage() {await requireHostedMode();- const privacyAddress = await resolvePublicSupportAddress();+ const privacyAddress = await findPublicSupportAddress();return (<PublicDocumentShell@@ -217,14 +218,9 @@ export default async function PrivacyPage() {9. How to exercise your rights</h2><p>- To request access, correction, deletion, or account closure, email{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href={`mailto:${privacyAddress}`}- >- {privacyAddress}- </Link>{" "}- or use the in-app account-closure request flow when available.+ <LegalInlineText+ parts={buildLegalContactParts("privacy_rights", privacyAddress)}+ /></p><p>We may ask you to verify your identity before we act on a request. For@@ -284,21 +280,9 @@ export default async function PrivacyPage() {unless a later date is stated.</p><p>- Privacy questions, requests, and complaints may be sent to{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href={`mailto:${privacyAddress}`}- >- {privacyAddress}- </Link>{" "}- or through the{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href="/contact"- >- Contact- </Link>{" "}- page.+ <LegalInlineText+ parts={buildLegalContactParts("privacy_contact", privacyAddress)}+ /></p></section></PublicDocumentShell>diff --git a/src/app/signer-privacy/page.tsx b/src/app/signer-privacy/page.tsxindex f1ef9cf..21b1833 100644--- a/src/app/signer-privacy/page.tsx+++ b/src/app/signer-privacy/page.tsx@@ -3,21 +3,43 @@ import { redirect } from "next/navigation";import { connection } from "next/server";import { PublicDocumentShell } from "@/components/layout/public-document-shell";-import { getSettings } from "@/lib/settings";+import { ServiceConfigurationError } from "@/lib/services/service-config";+import {+ getSettings,+ resolveSettings,+ type ResolvedSettings,+} from "@/lib/settings";import { STALE_DRAFT_RETENTION_DAYS } from "@/lib/retention";+import { isHostedMode } from "@/lib/utils/env";export const metadata: Metadata = {description: "How your information is used when you sign a document here.",title: "Privacy notice for signers",};+async function loadSignerPrivacySettings(): Promise<ResolvedSettings> {+ try {+ return await getSettings();+ } catch (error) {+ if (error instanceof ServiceConfigurationError) {+ return resolveSettings(null);+ }++ throw error;+ }+}+// A GDPR Article 13 notice for signers, built from the install's settings.// Shown in the footer when the organization has not linked its own privacy// policy. The organization remains the controller and should check it.export default async function SignerPrivacyPage() {await connection();- const settings = await getSettings();+ if (isHostedMode()) {+ redirect("/privacy");+ }++ const settings = await loadSignerPrivacySettings();if (settings.hosted) {redirect("/privacy");diff --git a/src/app/terms/page.tsx b/src/app/terms/page.tsxindex ad739f3..4cb6d26 100644--- a/src/app/terms/page.tsx+++ b/src/app/terms/page.tsx@@ -1,9 +1,10 @@import type { Metadata } from "next";-import Link from "next/link";+import { LegalInlineText } from "@/components/layout/legal-inline-text";import { PublicDocumentShell } from "@/components/layout/public-document-shell";import { requireHostedMode } from "@/lib/hosted-pages";-import { resolvePublicSupportAddress } from "@/lib/public-contact";+import { buildLegalContactParts } from "@/lib/legal";+import { findPublicSupportAddress } from "@/lib/public-contact";export const metadata: Metadata = {description:@@ -14,7 +15,7 @@ export const metadata: Metadata = {export default async function TermsPage() {await requireHostedMode();- const supportAddress = await resolvePublicSupportAddress();+ const supportAddress = await findPublicSupportAddress();return (<PublicDocumentShell@@ -226,17 +227,12 @@ export default async function TermsPage() {security, fraud, or legal risk.</p><p>- Account-closure requests may be submitted through the settings page or- by contacting{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href={`mailto:${supportAddress}`}- >- {supportAddress}- </Link>- . Before closing your account, download any documents you want to- keep. After closure, SignuDoc may provide a limited export window and- then delete stored document files and related envelope records, except+ <LegalInlineText+ parts={buildLegalContactParts("terms_closure", supportAddress)}+ />{" "}+ Before closing your account, download any documents you want to keep.+ After closure, SignuDoc may provide a limited export window and then+ delete stored document files and related envelope records, exceptlimited information kept for security, fraud prevention, legalcompliance, or dispute resolution.</p>@@ -322,21 +318,9 @@ export default async function TermsPage() {14. Contact</h2><p>- Questions about these Terms may be sent to{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href={`mailto:${supportAddress}`}- >- {supportAddress}- </Link>{" "}- or through the{" "}- <Link- className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"- href="/contact"- >- Contact- </Link>{" "}- page.+ <LegalInlineText+ parts={buildLegalContactParts("terms_contact", supportAddress)}+ /></p></section></PublicDocumentShell>diff --git a/src/components/layout/legal-inline-text.tsx b/src/components/layout/legal-inline-text.tsxnew file mode 100644index 0000000..bfc6768--- /dev/null+++ b/src/components/layout/legal-inline-text.tsx@@ -0,0 +1,37 @@+import Link from "next/link";+import { Fragment } from "react";++import type { LegalInlinePart } from "@/lib/legal";++const legalLinkClassName =+ "font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4";++export function LegalInlineText({+ parts,+}: {+ parts: readonly LegalInlinePart[];+}) {+ return (+ <>+ {parts.map((part, index) => {+ if (part.type === "text") {+ return <Fragment key={index}>{part.text}</Fragment>;+ }++ if (part.type === "email") {+ return (+ <a className={legalLinkClassName} href={part.href} key={index}>+ {part.address}+ </a>+ );+ }++ return (+ <Link className={legalLinkClassName} href={part.href} key={index}>+ {part.label}+ </Link>+ );+ })}+ </>+ );+}diff --git a/src/lib/contact.ts b/src/lib/contact.tsindex 14d2110..60ff6e7 100644--- a/src/lib/contact.ts+++ b/src/lib/contact.ts@@ -103,7 +103,6 @@ export async function submitPublicContactMessage(};}- const supportAddress = await resolvePublicSupportAddress(env);const submittedAt = formatSubmittedAt();const escapedMessageHtml = escapeHtml(parsedInput.message).replaceAll("\n",@@ -111,6 +110,7 @@ export async function submitPublicContactMessage();try {+ const supportAddress = await resolvePublicSupportAddress(env);const emailService = createEmailService({ env });const deliveryResult = await emailService.send({htmlBody: [diff --git a/src/lib/legal.ts b/src/lib/legal.tsindex 4da9513..4aea2ba 100644--- a/src/lib/legal.ts+++ b/src/lib/legal.ts@@ -28,3 +28,216 @@ export const publicFooterLinks = [},publicLegalLinks[2],] as const;++export type PublicSupportLink = {+ /** The bare email address shown in text, e.g. "[email protected]". */+ address: string;+ /** The `mailto:` target, stripped of any RFC 5322 display name. */+ href: string;+};++export type LegalInlinePart =+ | { text: string; type: "text" }+ | { address: string; href: string; type: "email" }+ | { href: "/contact"; label: string; type: "contact" };++export type LegalContactPassage =+ | "accessibility_assistance"+ | "accessibility_feedback"+ | "privacy_contact"+ | "privacy_rights"+ | "terms_closure"+ | "terms_contact";++const CONTACT_PAGE_LINK: LegalInlinePart = {+ href: "/contact",+ label: "Contact",+ type: "contact",+};++/**+ * Turns a configured support address (bare email or "Name <email>") into a+ * safe display string and `mailto:` href, or null when unset or invalid.+ */+export function buildPublicSupportLink(+ supportAddress: string | null | undefined,+): PublicSupportLink | null {+ const trimmed = supportAddress?.trim();++ if (!trimmed) {+ return null;+ }++ const angleMatch = /<([^<>]+)>\s*$/.exec(trimmed);+ const bareAddress = (angleMatch?.[1] ?? trimmed).trim();++ if (!bareAddress || !bareAddress.includes("@") || /\s/.test(bareAddress)) {+ return null;+ }++ return {+ address: bareAddress,+ href: `mailto:${bareAddress}`,+ };+}++/**+ * Builds the contact sentences for the hosted legal pages. When no support+ * address is configured yet (for example on a fresh hosted install before+ * setup finishes), every passage points to the Contact page instead of+ * failing or rendering a broken mailto link.+ */+export function buildLegalContactParts(+ passage: LegalContactPassage,+ supportAddress: string | null | undefined,+): LegalInlinePart[] {+ const email = buildPublicSupportLink(supportAddress);+ const emailPart: LegalInlinePart | null = email+ ? { address: email.address, href: email.href, type: "email" }+ : null;++ switch (passage) {+ case "privacy_rights":+ return emailPart+ ? [+ {+ text: "To request access, correction, deletion, or account closure, email ",+ type: "text",+ },+ emailPart,+ {+ text: " or use the in-app account-closure request flow when available.",+ type: "text",+ },+ ]+ : [+ {+ text: "To request access, correction, deletion, or account closure, submit a request through the ",+ type: "text",+ },+ CONTACT_PAGE_LINK,+ {+ text: " page or use the in-app account-closure request flow when available.",+ type: "text",+ },+ ];++ case "privacy_contact":+ return emailPart+ ? [+ {+ text: "Privacy questions, requests, and complaints may be sent to ",+ type: "text",+ },+ emailPart,+ { text: " or through the ", type: "text" },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ]+ : [+ {+ text: "Privacy questions, requests, and complaints may be sent through the ",+ type: "text",+ },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ];++ case "terms_closure":+ return emailPart+ ? [+ {+ text: "Account-closure requests may be submitted through the settings page or by contacting ",+ type: "text",+ },+ emailPart,+ { text: ".", type: "text" },+ ]+ : [+ {+ text: "Account-closure requests may be submitted through the settings page or through the ",+ type: "text",+ },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ];++ case "terms_contact":+ return emailPart+ ? [+ {+ text: "Questions about these Terms may be sent to ",+ type: "text",+ },+ emailPart,+ { text: " or through the ", type: "text" },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ]+ : [+ {+ text: "Questions about these Terms may be sent through the ",+ type: "text",+ },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ];++ case "accessibility_assistance":+ return emailPart+ ? [+ {+ text: "If you need help creating, sending, reviewing, or signing a document, email ",+ type: "text",+ },+ emailPart,+ { text: ".", type: "text" },+ ]+ : [+ {+ text: "If you need help creating, sending, reviewing, or signing a document, reach out through the ",+ type: "text",+ },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ];++ case "accessibility_feedback":+ return emailPart+ ? [+ {+ text: "Accessibility feedback helps us prioritize the right fixes. If you find a barrier, email ",+ type: "text",+ },+ emailPart,+ { text: " or use the ", type: "text" },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ]+ : [+ {+ text: "Accessibility feedback helps us prioritize the right fixes. If you find a barrier, use the ",+ type: "text",+ },+ CONTACT_PAGE_LINK,+ { text: " page.", type: "text" },+ ];+ }+}++export function formatLegalInlineParts(+ parts: readonly LegalInlinePart[],+): string {+ return parts+ .map((part) => {+ switch (part.type) {+ case "text":+ return part.text;+ case "email":+ return part.address;+ case "contact":+ return part.label;+ }+ })+ .join("");+}diff --git a/src/lib/public-contact.test.ts b/src/lib/public-contact.test.tsnew file mode 100644index 0000000..1e56a79--- /dev/null+++ b/src/lib/public-contact.test.ts@@ -0,0 +1,337 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ ContactSubmissionError,+ submitPublicContactMessage,+} from "./contact.ts";+import { replaceDbPoolForTests, type DbPool } from "./db/connection.ts";+import {+ buildLegalContactParts,+ buildPublicSupportLink,+ formatLegalInlineParts,+ type LegalContactPassage,+} from "./legal.ts";+import {+ findPublicSupportAddress,+ resolvePublicSupportAddress,+} from "./public-contact.ts";+import { ServiceConfigurationError } from "./services/service-config.ts";+import { invalidateSettingsCache } from "./settings.ts";++const ALL_LEGAL_PASSAGES: readonly LegalContactPassage[] = [+ "privacy_rights",+ "privacy_contact",+ "terms_closure",+ "terms_contact",+ "accessibility_assistance",+ "accessibility_feedback",+];++async function withFakeSettingsDb(+ query: (sql: string) => Promise<{ rows: Record<string, unknown>[] }>,+ run: () => Promise<void>,+): Promise<void> {+ const previous = replaceDbPoolForTests({ query } as unknown as DbPool);+ invalidateSettingsCache();++ try {+ await run();+ } finally {+ replaceDbPoolForTests(previous as unknown as DbPool);+ invalidateSettingsCache();+ }+}++test("findPublicSupportAddress returns null when neither SUPPORT_EMAIL nor DB settings configure one", async () => {+ const address = await findPublicSupportAddress(+ { HOSTED_MODE: "1" },+ async () => ({ supportAddress: null }),+ );++ assert.equal(address, null);++ const blankDb = await findPublicSupportAddress(+ { HOSTED_MODE: "1", SUPPORT_EMAIL: " " },+ async () => ({ supportAddress: " " }),+ );++ assert.equal(blankDb, null);+});++test("findPublicSupportAddress prefers SUPPORT_EMAIL over stored settings and ignores placeholders", async () => {+ let loadedFromDb = false;+ const fromEnv = await findPublicSupportAddress(+ { HOSTED_MODE: "1", SUPPORT_EMAIL: " [email protected] " },+ async () => {+ loadedFromDb = true;+ return { supportAddress: "[email protected]" };+ },+ );++ assert.equal(fromEnv, "[email protected]");+ assert.equal(loadedFromDb, false);++ const fromDbWhenPlaceholder = await findPublicSupportAddress(+ { HOSTED_MODE: "1", SUPPORT_EMAIL: "replace-with-support-email" },+ async () => ({ supportAddress: " [email protected] " }),+ );++ assert.equal(fromDbWhenPlaceholder, "[email protected]");+});++test("findPublicSupportAddress returns null instead of throwing when settings cannot be loaded", async () => {+ const withoutDatabase = await findPublicSupportAddress(+ { HOSTED_MODE: "1" },+ async () => {+ throw new ServiceConfigurationError("database", ["DATABASE_URL"]);+ },+ );++ assert.equal(withoutDatabase, null);++ const unreachableDb = await findPublicSupportAddress(+ { HOSTED_MODE: "1" },+ async () => {+ throw new Error("connection refused");+ },+ );++ assert.equal(unreachableDb, null);++ // Env SUPPORT_EMAIL still resolves even when the database is unavailable.+ const envDespiteDbError = await findPublicSupportAddress(+ { HOSTED_MODE: "1", SUPPORT_EMAIL: "[email protected]" },+ async () => {+ throw new Error("connection refused");+ },+ );++ assert.equal(envDespiteDbError, "[email protected]");+});++test("resolvePublicSupportAddress throws ServiceConfigurationError when unconfigured, and resolves env or DB when configured", async () => {+ await assert.rejects(+ resolvePublicSupportAddress({ HOSTED_MODE: "1" }, async () => ({+ supportAddress: null,+ })),+ (error: unknown) => {+ assert.ok(error instanceof ServiceConfigurationError);+ assert.match(error.message, /SUPPORT_EMAIL/);+ return true;+ },+ );++ assert.equal(+ await resolvePublicSupportAddress(+ { SUPPORT_EMAIL: "[email protected]" },+ async () => ({ supportAddress: "[email protected]" }),+ ),+ "[email protected]",+ );++ assert.equal(+ await resolvePublicSupportAddress({}, async () => ({+ supportAddress: "[email protected]",+ })),+ "[email protected]",+ );+});++test("public contact helpers integrate with getSettings across fresh DB, stored DB row, and env override", async () => {+ // Fresh migrated hosted install: app_settings has no rows yet, SUPPORT_EMAIL unset.+ await withFakeSettingsDb(+ async () => ({ rows: [] }),+ async () => {+ assert.equal(await findPublicSupportAddress({ HOSTED_MODE: "1" }), null);++ await assert.rejects(+ resolvePublicSupportAddress({ HOSTED_MODE: "1" }),+ ServiceConfigurationError,+ );+ },+ );++ // Completed setup / saved organization settings row in DB.+ await withFakeSettingsDb(+ async () => ({+ rows: [+ {+ allowed_email_domains: [],+ brand_color: null,+ consent_disclosure: null,+ email_ready_at: null,+ logo_hash: null,+ organization_name: "Acme Corp",+ part11_mode: false,+ privacy_url: null,+ require_two_factor: false,+ retention_days: null,+ sender_address: null,+ session_idle_minutes: null,+ session_max_hours: null,+ setup_completed_at: 1_800_000_000,+ signup_mode: "open",+ support_address: "[email protected]",+ terms_url: null,+ },+ ],+ }),+ async () => {+ assert.equal(+ await findPublicSupportAddress({ HOSTED_MODE: "1" }),+ "[email protected]",+ );+ assert.equal(+ await resolvePublicSupportAddress({ HOSTED_MODE: "1" }),+ "[email protected]",+ );++ // SUPPORT_EMAIL env var overrides the stored DB support address.+ assert.equal(+ await findPublicSupportAddress({+ HOSTED_MODE: "1",+ SUPPORT_EMAIL: "[email protected]",+ }),+ "[email protected]",+ );+ assert.equal(+ await resolvePublicSupportAddress({+ HOSTED_MODE: "1",+ SUPPORT_EMAIL: "[email protected]",+ }),+ "[email protected]",+ );+ },+ );+});++test("submitPublicContactMessage returns 503 instead of throwing an unhandled configuration error when support email is unset", async () => {+ await withFakeSettingsDb(+ async () => ({ rows: [] }),+ async () => {+ await assert.rejects(+ submitPublicContactMessage(+ {+ email: "[email protected]",+ message: "Hello from a fresh hosted install.",+ name: "Jordan Lee",+ },+ { env: { HOSTED_MODE: "1" } },+ ),+ (error: unknown) => {+ assert.ok(error instanceof ContactSubmissionError);+ assert.equal(error.statusCode, 503);+ assert.equal(+ error.message,+ "Contact form is temporarily unavailable.",+ );+ return true;+ },+ );+ },+ );+});++test("buildPublicSupportLink normalizes bare emails, display-name addresses, and invalid values", () => {+ assert.deepEqual(buildPublicSupportLink("[email protected]"), {+ address: "[email protected]",+ href: "mailto:[email protected]",+ });+ assert.deepEqual(buildPublicSupportLink(" [email protected] "), {+ address: "[email protected]",+ href: "mailto:[email protected]",+ });+ assert.deepEqual(buildPublicSupportLink("Acme Help <[email protected]>"), {+ address: "[email protected]",+ href: "mailto:[email protected]",+ });++ for (const invalid of [+ null,+ undefined,+ "",+ " ",+ "not-an-email",+ "Acme <>",+ "bad [email protected]",+ ]) {+ assert.equal(buildPublicSupportLink(invalid), null);+ }+});++test("legal page contact passages fall back cleanly to /contact when support email is unset", () => {+ const expected: Record<LegalContactPassage, string> = {+ privacy_rights:+ "To request access, correction, deletion, or account closure, submit a request through the Contact page or use the in-app account-closure request flow when available.",+ privacy_contact:+ "Privacy questions, requests, and complaints may be sent through the Contact page.",+ terms_closure:+ "Account-closure requests may be submitted through the settings page or through the Contact page.",+ terms_contact:+ "Questions about these Terms may be sent through the Contact page.",+ accessibility_assistance:+ "If you need help creating, sending, reviewing, or signing a document, reach out through the Contact page.",+ accessibility_feedback:+ "Accessibility feedback helps us prioritize the right fixes. If you find a barrier, use the Contact page.",+ };++ for (const passage of ALL_LEGAL_PASSAGES) {+ for (const unset of [null, undefined, "", " "]) {+ const parts = buildLegalContactParts(passage, unset);+ const rendered = formatLegalInlineParts(parts);++ assert.equal(rendered, expected[passage]);+ assert.doesNotMatch(rendered, / /);+ assert.equal(+ parts.some((part) => part.type === "email"),+ false,+ `${passage} must not include a mailto link when support email is unset`,+ );+ assert.equal(+ parts.some(+ (part) => part.type === "contact" && part.href === "/contact",+ ),+ true,+ `${passage} should link to /contact when support email is unset`,+ );+ }+ }+});++test("legal page contact passages render the configured support address with a valid mailto link", () => {+ const expected: Record<LegalContactPassage, string> = {+ privacy_rights:+ "To request access, correction, deletion, or account closure, email [email protected] or use the in-app account-closure request flow when available.",+ privacy_contact:+ "Privacy questions, requests, and complaints may be sent to [email protected] or through the Contact page.",+ terms_closure:+ "Account-closure requests may be submitted through the settings page or by contacting [email protected].",+ terms_contact:+ "Questions about these Terms may be sent to [email protected] or through the Contact page.",+ accessibility_assistance:+ "If you need help creating, sending, reviewing, or signing a document, email [email protected].",+ accessibility_feedback:+ "Accessibility feedback helps us prioritize the right fixes. If you find a barrier, email [email protected] or use the Contact page.",+ };++ for (const passage of ALL_LEGAL_PASSAGES) {+ for (const input of ["[email protected]", "Acme Support <[email protected]>"]) {+ const parts = buildLegalContactParts(passage, input);+ const rendered = formatLegalInlineParts(parts);++ assert.equal(rendered, expected[passage]);+ assert.doesNotMatch(rendered, / /);+ assert.equal(+ parts.some(+ (part) =>+ part.type === "email" &&+ part.address === "[email protected]" &&+ part.href === "mailto:[email protected]",+ ),+ true,+ `${passage} should include a valid mailto link for ${input}`,+ );+ }+ }+});diff --git a/src/lib/public-contact.ts b/src/lib/public-contact.tsindex f33d617..1b4f7bc 100644--- a/src/lib/public-contact.ts+++ b/src/lib/public-contact.ts@@ -1,18 +1,63 @@import { ServiceConfigurationError } from "./services/service-config.ts";-import { getSettings } from "./settings.ts";-import { type EnvSource } from "./utils/env.ts";+import { getSettings, type ResolvedSettings } from "./settings.ts";+import { getEnv, type EnvSource } from "./utils/env.ts";++export { buildPublicSupportLink, type PublicSupportLink } from "./legal.ts";++type PublicContactSettings = Pick<ResolvedSettings, "supportAddress">;+type LoadPublicContactSettings = (+ env: EnvSource,+) => Promise<PublicContactSettings>;++/**+ * The address people are told to write to: SUPPORT_EMAIL when it is set,+ * otherwise the support address saved in the install's settings, or null when+ * neither is configured yet (or the database cannot be reached).+ *+ * Public legal pages read this so they render cleanly before first-run setup+ * completes, instead of failing with HTTP 500.+ */+export async function findPublicSupportAddress(+ env: EnvSource = process.env,+ loadSettings: LoadPublicContactSettings = getSettings,+): Promise<string | null> {+ const envAddress = getEnv(env).email.supportAddress;++ if (envAddress) {+ return envAddress;+ }++ try {+ const { supportAddress } = await loadSettings(env);++ return supportAddress?.trim() || null;+ } catch {+ return null;+ }+}/*** The address people are told to write to. SUPPORT_EMAIL when it is set,* otherwise the support address saved in the install's settings.+ *+ * Throws ServiceConfigurationError when no support address is configured, for+ * callers that must deliver mail to a mailbox (contact form, account closure).*/export async function resolvePublicSupportAddress(env: EnvSource = process.env,+ loadSettings: LoadPublicContactSettings = getSettings,): Promise<string> {- const { supportAddress } = await getSettings(env);+ const envAddress = getEnv(env).email.supportAddress;++ if (envAddress) {+ return envAddress;+ }++ const { supportAddress } = await loadSettings(env);+ const trimmed = supportAddress?.trim();- if (supportAddress) {- return supportAddress;+ if (trimmed) {+ return trimmed;}throw new ServiceConfigurationError("email", ["SUPPORT_EMAIL"]);