Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let organization settings save when a field is locked or hidden
Claude025dc5d3c17d
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex 3b5ceb0..d456881 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -223,7 +223,7 @@ export function OrganizationSettings({</label>))}</div>- {values.signupMode === "domains" ? (+ {values.signupMode === "domains" || errors.allowedEmailDomains ? (<div className="max-w-xl"><FieldShelldisabled={isSaving}diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.tsnew file mode 100644index 0000000..98414a1--- /dev/null+++ b/src/lib/organization-settings.test.ts@@ -0,0 +1,168 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import type { DbExecutor } from "./db/connection.ts";+import {+ OrganizationSettingsError,+ updateOrganizationSettings,+} from "./organization-settings.ts";+import { resolveSettings, type AppSettings } from "./settings.ts";++const stored: AppSettings = {+ allowedEmailDomains: ["acme.com"],+ emailReadyAt: null,+ organizationName: "Acme Corp",+ privacyUrl: null,+ senderAddress: "[email protected]",+ setupCompletedAt: 1_800_000_000,+ signupMode: "domains",+ supportAddress: "[email protected]",+ termsUrl: null,+};++const storedRow = {+ allowed_email_domains: stored.allowedEmailDomains,+ email_ready_at: stored.emailReadyAt,+ organization_name: stored.organizationName,+ privacy_url: stored.privacyUrl,+ sender_address: stored.senderAddress,+ setup_completed_at: stored.setupCompletedAt,+ signup_mode: stored.signupMode,+ support_address: stored.supportAddress,+ terms_url: stored.termsUrl,+};++/**+ * Stands in for the database: answers the read with the stored row and+ * keeps what the save was asked to write.+ */+function fakeDatabase() {+ const saved: { values: unknown[] | null } = { values: null };+ const database = {+ query: (text: string, values: unknown[] = []) => {+ if (text.includes("insert into public.app_settings")) {+ saved.values = values;++ return Promise.resolve({ rowCount: 0, rows: [] });+ }++ return Promise.resolve({ rowCount: 1, rows: [storedRow] });+ },+ } as unknown as DbExecutor;++ return { database, saved };+}++// What the form sends: every field, as it is shown.+const form = {+ allowedEmailDomains: "acme.com",+ organizationName: "Acme Corp",+ privacyUrl: "",+ senderAddress: "[email protected]",+ signupMode: "domains",+ supportAddress: "[email protected]",+ termsUrl: "",+};++test("a sender fixed by the environment, display name and all, does not block saving the rest", async () => {+ const env = { RESEND_FROM_EMAIL: "Acme Signing <[email protected]>" };+ const current = resolveSettings(stored, env);+ const { database, saved } = fakeDatabase();+ const result = await updateOrganizationSettings(+ {+ ...form,+ organizationName: "Acme Corporation",+ // The locked field comes back exactly as it was displayed.+ senderAddress: "Acme Signing <[email protected]>",+ },+ current,+ database,+ );++ assert.equal(result.organizationName, "Acme Corporation");+ // The stored sender is left as it was: the one in use is the environment's.+ assert.equal(result.senderAddress, "[email protected]");+ assert.ok(saved.values);+});++test("a support address fixed by the environment is not judged or changed either", async () => {+ const current = resolveSettings(stored, { SUPPORT_EMAIL: "[email protected]" });+ const { database } = fakeDatabase();+ const result = await updateOrganizationSettings(+ { ...form, supportAddress: "not an address" },+ current,+ database,+ );++ assert.equal(result.supportAddress, "[email protected]");+});++test("an address the administrator can edit is still checked", async () => {+ const current = resolveSettings(stored, {});+ const { database, saved } = fakeDatabase();++ await assert.rejects(+ updateOrganizationSettings(+ { ...form, senderAddress: "Acme Signing <[email protected]>" },+ current,+ database,+ ),+ (error: unknown) => {+ assert.ok(error instanceof OrganizationSettingsError);+ assert.deepEqual(Object.keys(error.fieldErrors), ["senderAddress"]);++ return true;+ },+ );+ assert.equal(saved.values, null);+});++test("what is left in the hidden domain field does not block closing or opening sign-up", async () => {+ const current = resolveSettings(stored, {});++ for (const signupMode of ["closed", "open"]) {+ const { database } = fakeDatabase();+ const result = await updateOrganizationSettings(+ { ...form, allowedEmailDomains: "not a domain, ???", signupMode },+ current,+ database,+ );++ assert.equal(result.signupMode, signupMode);+ // The list from before is kept for when the rule is switched back.+ assert.deepEqual(result.allowedEmailDomains, ["acme.com"]);+ }+});++test("under the domain rule the list is checked and saved", async () => {+ const current = resolveSettings(stored, {});+ const accepted = fakeDatabase();+ const result = await updateOrganizationSettings(+ { ...form, allowedEmailDomains: "acme.com, Acme.co.uk" },+ current,+ accepted.database,+ );++ assert.deepEqual(result.allowedEmailDomains, ["acme.co.uk", "acme.com"]);++ for (const allowedEmailDomains of ["not a domain", ""]) {+ const refused = fakeDatabase();++ await assert.rejects(+ updateOrganizationSettings(+ { ...form, allowedEmailDomains },+ current,+ refused.database,+ ),+ (error: unknown) => {+ assert.ok(error instanceof OrganizationSettingsError);+ assert.deepEqual(Object.keys(error.fieldErrors), [+ "allowedEmailDomains",+ ]);++ return true;+ },+ );+ assert.equal(refused.saved.values, null);+ }+});diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.tsindex 2e9e201..bde036c 100644--- a/src/lib/organization-settings.ts+++ b/src/lib/organization-settings.ts@@ -104,6 +104,38 @@ const FIELD_MESSAGES: Record<OrganizationSettingsField, string> = {termsUrl: "Enter a full web address starting with https://",};+/**+ * Drops the fields the form shows but cannot change, before anything is+ * checked. The form sends them back as displayed, and a value fixed by the+ * environment need not pass the form's rules: RESEND_FROM_EMAIL may carry a+ * display name ("Acme <[email protected]>"), which is not a bare address.+ */+function withoutLockedFields(+ rawInput: unknown,+ current: ResolvedSettings,+): unknown {+ if (typeof rawInput !== "object" || rawInput === null) {+ return rawInput;+ }++ const input: Record<string, unknown> = { ...rawInput };++ if (current.senderAddressFromEnv) {+ delete input.senderAddress;+ }++ if (current.supportAddressFromEnv) {+ delete input.supportAddress;+ }++ if (current.hosted) {+ delete input.privacyUrl;+ delete input.termsUrl;+ }++ return input;+}+/*** Validates and saves the Organization form. Addresses that are fixed by an* environment variable are left as they are stored, since the stored value@@ -114,7 +146,9 @@ export async function updateOrganizationSettings(current: ResolvedSettings,database: DbExecutor = getDb(),): Promise<AppSettings> {- const parsed = organizationSettingsSchema.safeParse(rawInput);+ const parsed = organizationSettingsSchema.safeParse(+ withoutLockedFields(rawInput, current),+ );const fieldErrors: Partial<Record<OrganizationSettingsField, string>> = {};if (!parsed.success) {@@ -131,11 +165,17 @@ export async function updateOrganizationSettings(}const input = parsed.data;- const { domains, invalid } = parseEmailDomainList(input.allowedEmailDomains);+ // The list of domains only means something, and is only shown, when+ // sign-up is limited to domains. Under any other rule the stored list is+ // kept as it is, and whatever was left in the hidden field is not judged.+ const domainRule = input.signupMode === "domains";+ const { domains, invalid } = parseEmailDomainList(+ domainRule ? input.allowedEmailDomains : "",+ );if (invalid.length > 0) {fieldErrors.allowedEmailDomains = `Not a domain: ${invalid.slice(0, 3).join(", ")}`;- } else if (input.signupMode === "domains" && domains.length === 0) {+ } else if (domainRule && domains.length === 0) {fieldErrors.allowedEmailDomains = FIELD_MESSAGES.allowedEmailDomains;}@@ -145,7 +185,7 @@ export async function updateOrganizationSettings(return saveSettings({- allowedEmailDomains: domains,+ ...(domainRule ? { allowedEmailDomains: domains } : {}),organizationName: input.organizationName,signupMode: input.signupMode,...(current.hosted