Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Ask for a support email at setup and drop the project's own addresses
Claude3625051a422f
diff --git a/.env.example b/.env.exampleindex ad59946..a878170 100644--- a/.env.example+++ b/.env.example@@ -23,9 +23,11 @@ EMAIL_DRIVER=capture# sets it.# RESEND_API_KEY=-# The address email is sent from and the address replies go to are chosen-# in the app, under Settings, Organization. Set these only to fix them from-# the environment instead; they then cannot be changed in the app.+# The support address, where replies go, is asked for when the site is set+# up. It and the address email is sent from can be changed in the app, under+# Settings, Organization. Set these only to fix them from the environment+# instead; they then cannot be changed in the app, and the setup page does+# not ask for a support address.# RESEND_FROM_EMAIL=# SUPPORT_EMAIL=diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdindex a3997d6..da552cd 100644--- a/CODE_OF_CONDUCT.md+++ b/CODE_OF_CONDUCT.md@@ -23,7 +23,12 @@ Examples of unacceptable behavior:Project maintainers may remove, edit, or reject comments, commits, issues, and pull requests that violate this Code of Conduct. Contributors who do not follow these standards may be temporarily or permanently banned from participating.-To report Code of Conduct issues, contact **[email protected]**. Reports will be reviewed and handled as confidentially as practical.+To report a Code of Conduct issue, use GitHub's own reporting. Open the menu (the three dots) on the issue, pull request or comment, choose **Report content**, and then pick one of:++- **Report to repository admins**, which sends your report to the people who administer this repository.+- **Report abuse to GitHub Support**, if the problem is with a maintainer, or if GitHub offers you only this choice.++The project has no email address for reports. Reports will be reviewed and handled as confidentially as practical.## Scopediff --git a/README.md b/README.mdindex 57763c7..404aa04 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@ The button puts your own copy on [Vercel](https://vercel.com) with a Postgres da- a private file store, [Vercel Blob](https://vercel.com/docs/vercel-blob), for the documents,- [Resend](https://resend.com) for sending email.4. **Click Deploy.** The build creates the database tables by itself.-5. **Open your new site.** It takes you to a setup page, where you name your organization and create the first account. That account is the administrator.+5. **Open your new site.** It takes you to a setup page, where you name your organization, give the email address people should write to for help, and create the first account. That account is the administrator.6. **Set up the address you send from.** Under Settings, Organization, enter an address at your own domain in "Send email from" and save (the setup page offers the same field). The site lists the DNS records for that domain and checks them for you. Add them where your domain is managed. If your Resend key is not allowed to manage domains, the page sends you to Resend's dashboard for this step instead.@@ -99,7 +99,7 @@ SignuDoc is not a law firm and does not give legal advice. Whoever runs an insta### Your responsibilities when you self-host-Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), set a support address, and choose how long finished documents are kept. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.+Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.## Signed PDFs and the seal@@ -192,13 +192,15 @@ Open [http://localhost:3000](http://localhost:3000).### 5. Set the site up-The first time you open a new install it takes you to `/setup`. There you name your organization and create the first account, which becomes the administrator. After that the setup page is gone for good.+The first time you open a new install it takes you to `/setup`. There you name your organization, give its support address, and create the first account, which becomes the administrator. After that the setup page is gone for good.++- **Support address.** Setup does not finish without one. It is the address signers and people with an account are told to write to, and where replies to the site's emails go. It is saved in your install's own settings and nowhere else; there is no SignuDoc address that it falls back to. The administrator can change it under Settings, Organization, but not remove it.- **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.- **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`. Sign-up stays open, as it was, until that administrator changes 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.### Hosted mode@@ -233,8 +235,8 @@ The schema lives in `db/migrations` as plain SQL files. `npm run db:migrate` appSignuDoc sends transactional email through Resend.-- The address email is sent from, and the support address replies go to, are set by the administrator under Settings, Organization. The sender address must be at a domain verified with Resend; the same page adds the domain to Resend, lists the DNS records and checks them. With a Resend API key that is only allowed to send, it points you at Resend's dashboard for that step instead.-- `RESEND_FROM_EMAIL` and `SUPPORT_EMAIL` are optional. When set they take the place of the addresses saved in Settings, which then cannot be changed there.+- The support address, where replies go, is asked for when the site is set up. It and the address email is sent from can be changed by the administrator under Settings, Organization. The sender address must be at a domain verified with Resend; the same page adds the domain to Resend, lists the DNS records and checks them. With a Resend API key that is only allowed to send, it points you at Resend's dashboard for that step instead.+- `RESEND_FROM_EMAIL` and `SUPPORT_EMAIL` are optional. When set they take the place of the addresses saved in Settings, which then cannot be changed there, and with `SUPPORT_EMAIL` set the setup page does not ask for a support address.- Until a sender address is set, mail goes out from `[email protected]`, which Resend only delivers to the owner of the Resend account.- In hosted mode the support address is also the contact shown on the Terms, Privacy, and Accessibility pages.- For local development, `EMAIL_DRIVER=capture` writes each email to `.data/outbox` as a JSON file instead of sending it. Open the newest file to find a verification or signing link. This driver refuses to run in production.@@ -308,7 +310,7 @@ Away from Vercel, a few things Vercel does for you are yours to set:Self-hosted operators are responsible for:- linking to their own terms and privacy policy under Settings, Organization;-- setting the correct support address and verifying a sending domain for email;+- keeping the support address pointed at a mailbox someone reads, and verifying a sending domain for email;- configuring retention, consent, and compliance requirements for their own deployment; and- scheduling the [daily cleanup](#daily-cleanup) if they are not on Vercel, where it is scheduled for them.@@ -364,3 +366,5 @@ This repository also redistributes third-party assets, including bundled fonts aIssues and pull requests are welcome.If you plan to contribute, keep the project style simple: small components, explicit server-side logic, and schema-validated inputs.++The project has no email address of its own. Report a security problem privately through GitHub, as [SECURITY.md](./SECURITY.md) describes, and a conduct problem as the [Code of Conduct](./CODE_OF_CONDUCT.md) describes. For help with one particular site that runs SignuDoc, write to the organization that runs it.diff --git a/SECURITY.md b/SECURITY.mdindex a8019fd..32b3334 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -2,15 +2,17 @@## Reporting a vulnerability-If you find a security vulnerability in SignuDoc, please report it privately. **Do not open a public GitHub issue.**+If you find a security vulnerability in SignuDoc, please report it privately. **Do not put the details in a public GitHub issue, discussion or pull request.**-Email your report to **[email protected]** with:+Send your report through GitHub's private vulnerability reporting: open the [Report a vulnerability](https://github.com/NYLLON-SOFTWARE/signudoc/security/advisories/new) form, which is also on this repository's security advisories page. The report stays between you and the repository's maintainers. Include:- A description of the vulnerability.- Steps to reproduce or a proof of concept.- The potential impact as you understand it.-If GitHub private vulnerability reporting is enabled for this repository, you may use that as well.+If that form is not available to you, open an issue that asks the maintainers for a private way to reach them, and leave every detail of the vulnerability out of it.++The project has no email address for reports. Each organization that runs SignuDoc gives its own install a support address, and that address reaches the organization, not the people who maintain this code. A problem with one particular site, such as its settings or the documents it holds, belongs with the organization that runs it.We will acknowledge your report within 7 days and aim to provide a fix or mitigation plan within 30 days, depending on severity and complexity.diff --git a/docs/images/setup.png b/docs/images/setup.pngindex 78aa729..547750b 100644Binary files a/docs/images/setup.png and b/docs/images/setup.png differdiff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex b992e43..aa97a1e 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -55,6 +55,8 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a}, testInfo) => {const runId = String(Date.now());const adminEmail = `admin+${runId}@example.com`;+ // Not the administrator's own address, so the two cannot be mixed up.+ const supportEmail = `help+${runId}@example.com`;const senderEmail = `sender+${runId}@example.com`;const outsiderEmail = `outsider+${runId}@elsewhere.example`;const signerEmail = `signer+${runId}@example.com`;@@ -100,6 +102,18 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aawait adminPage.getByLabel("Your email").fill(adminEmail);await adminPage.getByLabel("Password").fill(PASSWORD);+ // Setup does not finish without an address people can write to for+ // help. Nothing stands in for it, the administrator's own included.+ await adminPage.getByLabel("Setup token").fill(e2eSetupToken);+ await adminPage.getByRole("button", { name: "Finish setup" }).click();+ await expect(+ adminPage.getByText(+ "Enter an email address people can write to for help",+ ),+ ).toBeVisible();+ await expect(adminPage).toHaveURL(/\/setup$/);+ await adminPage.getByLabel("Support email").fill(supportEmail);+// The deployment sets SETUP_TOKEN, so knowing the URL is not enough.await adminPage.getByLabel("Setup token").fill("not the token");await adminPage.getByRole("button", { name: "Finish setup" }).click();@@ -118,6 +132,9 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aawait expect(adminPage.getByLabel("Organization name")).toHaveValue(ORGANIZATION_NAME,);+ await expect(adminPage.getByLabel("Support address")).toHaveValue(+ supportEmail,+ );// The starting sign-up rule is the administrator's own email domain.await expect(adminPage.getByLabel("Email domains")).toHaveValue("example.com",@@ -139,6 +156,9 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a});expect(testEmail.subject).toBe(`Test email from ${ORGANIZATION_NAME}`);+ // Replies and questions go to the address given at setup.+ expect(testEmail.replyTo).toBe(supportEmail);+ expect(testEmail.text).toContain(`Questions? Contact ${supportEmail}.`);// The organization puts its own logo and color on the site. The logo// is saved the moment it is chosen, the color with the form.@@ -213,7 +233,19 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", afooter.getByRole("link", { exact: true, name: hostedOnly }),).toHaveCount(0);}++ // The product's own link goes to its repository. There is no site+ // run by the project to send anyone to.+ await expect(+ footer.getByRole("link", { name: "Powered by SignuDoc" }),+ ).toHaveAttribute("href", "https://github.com/NYLLON-SOFTWARE/signudoc");}++ // A signer with a question is sent to the organization's own address.+ await page.goto("/signer-privacy");+ await expect(+ page.getByRole("link", { exact: true, name: supportEmail }),+ ).toHaveAttribute("href", `mailto:${supportEmail}`);});await test.step("an address outside the organization cannot sign up", async () => {@@ -437,6 +469,7 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aconst signingLink = extractLink(invitation.text, "/sign/");expect(invitation.text).toContain(`through ${ORGANIZATION_NAME}.`);+ expect(invitation.replyTo).toBe(supportEmail);// The logo opens the message, fetched from this site.expect(invitation.html).toMatch(new RegExp(@@ -662,7 +695,10 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aawait database.end();}- const claim = { organizationName: "Second Wind Partners" };+ const claim = {+ organizationName: "Second Wind Partners",+ supportAddress: `desk+${runId}@example.com`,+ };const anonymousContext = await browser.newContext();expect(@@ -686,6 +722,9 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aawait wrongAccountPage.getByRole("button", { name: "Log in" }).click();await expect(wrongAccountPage).toHaveURL(/\/dashboard$/);await wrongAccountPage.goto("/setup");+ // The settings went with the administrator, the support address among+ // them, so whoever takes charge is asked for one.+ await expect(wrongAccountPage.getByLabel("Support email")).toBeVisible();await wrongAccountPage.getByRole("button", { name: "Log in as someone else" }).click();@@ -719,6 +758,9 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aawait expect(page.getByLabel("Organization name")).toHaveValue(claim.organizationName,);+ await expect(page.getByLabel("Support address")).toHaveValue(+ claim.supportAddress,+ );// Sign-up stays as it was before anyone was in charge: open.await expect(page.getByRole("radio", { name: /^Anyone/ })).toBeChecked();});diff --git a/e2e/support/outbox.ts b/e2e/support/outbox.tsindex 5f4901c..5b6a0fe 100644--- a/e2e/support/outbox.ts+++ b/e2e/support/outbox.ts@@ -6,6 +6,7 @@ import { e2eOutboxDir } from "../../playwright.config";export type CapturedEmail = {attachments?: { filename: string; sha256: string }[];html?: string;+ replyTo?: string;subject: string;template: string;text: string;diff --git a/src/app/setup/page.tsx b/src/app/setup/page.tsxindex 517873f..9476991 100644--- a/src/app/setup/page.tsx+++ b/src/app/setup/page.tsx@@ -10,7 +10,11 @@ import {import { getAuthSession } from "@/lib/auth/server";import { buildBranding } from "@/lib/branding";import { ServiceConfigurationError } from "@/lib/services/service-config";-import { getSetupState, resolveSettings } from "@/lib/settings";+import {+ getSetupState,+ readStoredSettings,+ resolveSettings,+} from "@/lib/settings";import { resolveSetupView } from "@/lib/setup";import { isHostedMode } from "@/lib/utils/env";@@ -25,8 +29,16 @@ async function loadView(): Promise<SetupShellView> {// Only an install that already has accounts cares who is signed in.const session =state.status === "unclaimed" ? await getAuthSession() : null;+ // The form asks for a support address unless one is saved already.+ // Read fresh, not from the settings cache: this page is opened rarely,+ // and what it asks for should match what setup will accept.+ const stored =+ state.status === "fresh" || state.status === "unclaimed"+ ? await readStoredSettings()+ : null;return resolveSetupView(state, {+ storedSupportAddress: stored?.supportAddress ?? null,sessionUser: session? {email: session.user.email,diff --git a/src/components/setup/setup-shell.tsx b/src/components/setup/setup-shell.tsxindex 938cb4b..c221ebe 100644--- a/src/components/setup/setup-shell.tsx+++ b/src/components/setup/setup-shell.tsx@@ -44,6 +44,7 @@ const emptyValues: SetupValues = {password: "",senderAddress: "",setupToken: "",+ supportAddress: "",};export function SetupShell({ hosted, onVercel, view }: SetupShellProps) {@@ -211,6 +212,7 @@ function SetupForm({const isCreate = view.view === "create";const requiresToken = isCreate ? view.requiresToken : true;const asksForSender = isCreate && !view.senderAddressFromEnv;+ const asksForSupport = view.asksForSupportAddress;async function handleSwitchAccount() {if (isSwitchingAccount) {@@ -251,6 +253,7 @@ function SetupForm({body: JSON.stringify({organizationName: values.organizationName,setupToken: requiresToken ? values.setupToken : undefined,+ supportAddress: asksForSupport ? values.supportAddress : undefined,...(isCreate? {email: values.email,@@ -320,6 +323,22 @@ function SetupForm({value={values.organizationName}/>+ {asksForSupport ? (+ <FieldShell+ autoComplete="off"+ disabled={isSubmitting}+ error={errors.supportAddress}+ helper="Signers and people with an account are told to write here for help, and replies to this site's emails come here. You can change it in Settings."+ label="Support email"+ name="setup-support-address"+ onChange={handleChange("supportAddress")}+ placeholder="[email protected]"+ readOnly={false}+ type="email"+ value={values.supportAddress}+ />+ ) : null}+{isCreate ? (<><FieldShelldiff --git a/src/lib/branding.ts b/src/lib/branding.tsindex 3aca105..52dadcd 100644--- a/src/lib/branding.ts+++ b/src/lib/branding.ts@@ -10,7 +10,9 @@ import type { ResolvedSettings } from "./settings.ts";// pages. An install's own logo and color are not used there.export const SIGNUDOC_NAME = "SignuDoc";-export const SIGNUDOC_URL = "https://signudoc.app";+// The project's home is its repository. There is no SignuDoc-run site that+// an install should send its visitors to, and no address there to write to.+export const SIGNUDOC_URL = "https://github.com/NYLLON-SOFTWARE/signudoc";/** Where the install's logo is served. Public: it is shown to signers. */export const BRAND_LOGO_PATH = "/api/brand/logo";diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.tsindex 65c4cbd..1f13428 100644--- a/src/lib/organization-settings.test.ts+++ b/src/lib/organization-settings.test.ts@@ -42,7 +42,7 @@ const storedRow = {* Stands in for the database: answers the read with the stored row and* keeps what the save was asked to write.*/-function fakeDatabase() {+function fakeDatabase(row = storedRow) {const saved: { values: unknown[] | null } = { values: null };const database = {query: (text: string, values: unknown[] = []) => {@@ -52,7 +52,7 @@ function fakeDatabase() {return Promise.resolve({ rowCount: 0, rows: [] });}- return Promise.resolve({ rowCount: 1, rows: [storedRow] });+ return Promise.resolve({ rowCount: 1, rows: [row] });},} as unknown as DbExecutor;@@ -103,6 +103,60 @@ test("a support address fixed by the environment is not judged or changed eitherassert.equal(result.supportAddress, "[email protected]");});+test("the support address can be changed, but not taken away", async () => {+ const current = resolveSettings(stored, {});++ for (const supportAddress of ["", " ", null, undefined, "not an address"]) {+ const { database, saved } = fakeDatabase();++ await assert.rejects(+ updateOrganizationSettings(+ { ...form, supportAddress },+ current,+ database,+ ),+ (error: unknown) => {+ assert.ok(error instanceof OrganizationSettingsError);+ assert.deepEqual(error.fieldErrors, {+ supportAddress: "Enter an email address people can write to for help",+ });++ return true;+ },+ );+ assert.equal(saved.values, null);+ }++ const { database } = fakeDatabase();+ const result = await updateOrganizationSettings(+ { ...form, supportAddress: "[email protected]" },+ current,+ database,+ );++ assert.equal(result.supportAddress, "[email protected]");+});++test("an install whose support address comes from SUPPORT_EMAIL needs none of its own", async () => {+ const current = resolveSettings(+ { ...stored, supportAddress: null },+ { SUPPORT_EMAIL: "[email protected]" },+ );+ const { database, saved } = fakeDatabase({+ ...storedRow,+ support_address: null,+ });+ const result = await updateOrganizationSettings(+ { ...form, organizationName: "Acme Corporation", supportAddress: "" },+ current,+ database,+ );++ assert.equal(result.organizationName, "Acme Corporation");+ assert.equal(result.supportAddress, null);+ assert.ok(saved.values);+});+test("an address the administrator can edit is still checked", async () => {const current = resolveSettings(stored, {});const { database, saved } = fakeDatabase();diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.tsindex f9c9c43..8f5e2b0 100644--- a/src/lib/organization-settings.ts+++ b/src/lib/organization-settings.ts@@ -147,7 +147,7 @@ const FIELD_MESSAGES: Record<OrganizationSettingsField, string> = {retentionDays: "Enter a number of days, 30 or more, or leave this empty",senderAddress: "Enter a valid email address, or leave this empty",signupMode: "Choose who can create an account",- supportAddress: "Enter a valid email address, or leave this empty",+ supportAddress: "Enter an email address people can write to for help",termsUrl: "Enter a full web address starting with https://",};@@ -227,6 +227,13 @@ export async function updateOrganizationSettings(fieldErrors.allowedEmailDomains = FIELD_MESSAGES.allowedEmailDomains;}+ // Setup does not finish without a support address, and it cannot be+ // taken away afterwards: signers are told to write to it. An install+ // whose address comes from SUPPORT_EMAIL has one whatever is stored.+ if (!current.supportAddressFromEnv && input.supportAddress === null) {+ fieldErrors.supportAddress = FIELD_MESSAGES.supportAddress;+ }+if (Object.keys(fieldErrors).length > 0) {throw new OrganizationSettingsError(fieldErrors);}@@ -247,9 +254,9 @@ export async function updateOrganizationSettings(...(current.senderAddressFromEnv? {}: { senderAddress: input.senderAddress?.toLowerCase() ?? null }),- ...(current.supportAddressFromEnv+ ...(current.supportAddressFromEnv || input.supportAddress === null? {}- : { supportAddress: input.supportAddress?.toLowerCase() ?? null }),+ : { supportAddress: input.supportAddress.toLowerCase() }),},database,);diff --git a/src/lib/project-contact.test.ts b/src/lib/project-contact.test.tsnew file mode 100644index 0000000..d4025d1--- /dev/null+++ b/src/lib/project-contact.test.ts@@ -0,0 +1,76 @@+import assert from "node:assert/strict";+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { test } from "node:test";++// SignuDoc is run by whoever deploys it. The project keeps no site and no+// mailbox of its own, so nothing in the repository may send a person or a+// message to one. An install's contact address is the one its administrator+// gave at setup, and reports about the project itself go through GitHub.++const repoRoot = path.resolve(import.meta.dirname, "..", "..");++// The domain the project once ran a hosted site on. Written in two parts+// so that this file does not name it either.+const formerHostedDomain = ["signudoc", "app"].join(".");++const SKIPPED_DIRECTORIES = new Set([+ ".data",+ ".git",+ ".next",+ ".vercel",+ "node_modules",+ "playwright-report",+ "test-results",+]);+const TEXT_FILE =+ /\.(?:css|example|html|js|json|md|mjs|sql|ts|tsx|txt|yaml|yml)$/;++function listTextFiles(directory: string): string[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const entryPath = path.join(directory, entry.name);++ if (entry.isDirectory()) {+ return SKIPPED_DIRECTORIES.has(entry.name)+ ? []+ : listTextFiles(entryPath);+ }++ return entry.isFile() && TEXT_FILE.test(entry.name) ? [entryPath] : [];+ });+}++test("nothing in the repository points at a site or a mailbox run by the project", () => {+ const files = listTextFiles(repoRoot);+ const offenders = files+ .filter((file) =>+ readFileSync(file, "utf8").toLowerCase().includes(formerHostedDomain),+ )+ .map((file) => path.relative(repoRoot, file));++ // The search really did look at the places an address used to be.+ for (const looked of ["SECURITY.md", "README.md", "src/lib/branding.ts"]) {+ assert.ok(files.includes(path.join(repoRoot, looked)), looked);+ }++ assert.deepEqual(offenders, []);+});++test("security and conduct reports go through GitHub, not to an email address", () => {+ for (const name of ["SECURITY.md", "CODE_OF_CONDUCT.md"]) {+ const text = readFileSync(path.join(repoRoot, name), "utf8");++ assert.doesNotMatch(text, /[\w.+-]+@[\w-]+\.[a-z]{2,}/i, name);+ assert.doesNotMatch(text, /mailto:/i, name);+ }++ assert.ok(+ readFileSync(path.join(repoRoot, "SECURITY.md"), "utf8").includes(+ "https://github.com/NYLLON-SOFTWARE/signudoc/security/advisories/new",+ ),+ );+ assert.match(+ readFileSync(path.join(repoRoot, "CODE_OF_CONDUCT.md"), "utf8"),+ /Report content/,+ );+});diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.tsindex cbaad6e..f632129 100644--- a/src/lib/settings.test.ts+++ b/src/lib/settings.test.ts@@ -43,13 +43,13 @@ test("stored settings are used as they are when the environment says nothing", (test("email addresses set in the environment win over the stored ones", () => {const settings = resolveSettings(stored, {- RESEND_FROM_EMAIL: "SignuDoc <[email protected]>",- SUPPORT_EMAIL: "[email protected]",+ RESEND_FROM_EMAIL: "Acme Signing <[email protected]>",+ SUPPORT_EMAIL: "[email protected]",});- assert.equal(settings.senderAddress, "SignuDoc <[email protected]>");+ assert.equal(settings.senderAddress, "Acme Signing <[email protected]>");assert.equal(settings.senderAddressFromEnv, true);- assert.equal(settings.supportAddress, "[email protected]");+ assert.equal(settings.supportAddress, "[email protected]");assert.equal(settings.supportAddressFromEnv, true);});diff --git a/src/lib/setup.dbtest.ts b/src/lib/setup.dbtest.tsindex a333d93..42b01e9 100644--- a/src/lib/setup.dbtest.ts+++ b/src/lib/setup.dbtest.ts@@ -11,6 +11,7 @@ import {markEmailReady,readSetupState,readStoredSettings,+ resolveSettings,saveSettings,} from "./settings.ts";import { completeSetup, SetupError } from "./setup.ts";@@ -25,6 +26,7 @@ const setupInput = {fullName: "Olive Owner",organizationName: "Acme Corp",password: "a long enough passphrase",+ supportAddress: "[email protected]",};let database: pg.Pool;@@ -89,6 +91,159 @@ test("before setup nobody can sign up, and after it the chosen rule applies", asassert.equal((await signUp("[email protected]")).allowed, false);});+test("the support address given at setup is saved for this install, not guessed", async () => {+ await completeSetup(+ { ...setupInput, supportAddress: " [email protected] " },+ {+ createAdminAccount: async ({ email }) => ({+ userId: await insertUser(email),+ }),+ database,+ env,+ },+ );++ const stored = await readStoredSettings(database);++ // The address that was typed, and not the administrator's own.+ assert.equal(stored?.supportAddress, "[email protected]");+ assert.equal(resolveSettings(stored, env).supportAddress, "[email protected]");+});++test("setup without a support address is refused before any account exists", async () => {+ const withoutSupportAddress: Record<string, string> = { ...setupInput };++ delete withoutSupportAddress.supportAddress;++ for (const input of [+ withoutSupportAddress,+ { ...setupInput, supportAddress: " " },+ ]) {+ await assert.rejects(+ completeSetup(input, {+ createAdminAccount: async () => {+ throw new Error("no account may be created");+ },+ database,+ env,+ }),+ (error: unknown) => {+ assert.ok(error instanceof SetupError);+ assert.equal(error.statusCode, 400);+ assert.deepEqual(error.fieldErrors, {+ supportAddress: "Enter an email address people can write to for help",+ });++ return true;+ },+ );+ }++ // Nothing was left behind: the next visitor starts from the beginning.+ assert.equal(await countUsers(), 0);+ assert.equal(await readStoredSettings(database), null);+ assert.deepEqual(await readSetupState(database), { status: "fresh" });++ // Every field that needs attention is named at once.+ await assert.rejects(+ completeSetup(+ { ...withoutSupportAddress, password: "too short" },+ {+ createAdminAccount: async () => {+ throw new Error("no account may be created");+ },+ database,+ env,+ },+ ),+ (error: unknown) => {+ assert.ok(error instanceof SetupError);+ assert.deepEqual(Object.keys(error.fieldErrors).sort(), [+ "password",+ "supportAddress",+ ]);++ return true;+ },+ );+});++test("a deployment that sets SUPPORT_EMAIL is not asked for a support address", async () => {+ const fixed = { SUPPORT_EMAIL: "Acme Help <[email protected]>" };+ const withoutSupportAddress: Record<string, string> = { ...setupInput };++ delete withoutSupportAddress.supportAddress;++ await completeSetup(withoutSupportAddress, {+ createAdminAccount: async ({ email }) => ({+ userId: await insertUser(email),+ }),+ database,+ env: fixed,+ });++ const stored = await readStoredSettings(database);++ // Nothing is saved in its place, and the deployment's address is in use.+ assert.equal(stored?.supportAddress, null);+ assert.equal(+ resolveSettings(stored, fixed).supportAddress,+ "Acme Help <[email protected]>",+ );+});++test("someone who takes charge of an older install gives it a support address, unless it has one", async () => {+ const claimEnv = { SETUP_TOKEN: "a-secret-of-the-owner" };+ const claim = {+ organizationName: "Second Wind Partners",+ setupToken: claimEnv.SETUP_TOKEN,+ };+ const userId = await insertUser("[email protected]");+ const sessionUser = {+ email: "[email protected]",+ emailVerified: true,+ id: userId,+ };+ const createAdminAccount = async () => {+ throw new Error("nobody is created when an install is claimed");+ };+ const options = { createAdminAccount, database, env: claimEnv, sessionUser };++ await assert.rejects(completeSetup(claim, options), (error: unknown) => {+ assert.ok(error instanceof SetupError);+ assert.equal(error.statusCode, 400);+ assert.deepEqual(Object.keys(error.fieldErrors), ["supportAddress"]);++ return true;+ });+ // Still nobody in charge, and nothing saved.+ assert.deepEqual(await readSetupState(database), { status: "unclaimed" });+ assert.equal(await readStoredSettings(database), null);++ await completeSetup(+ { ...claim, supportAddress: "[email protected]" },+ options,+ );++ assert.deepEqual(await readSetupState(database), { status: "complete" });+ assert.equal(+ (await readStoredSettings(database))?.supportAddress,+ "[email protected]",+ );++ // The same install with nobody in charge again: the address it was+ // given is kept, and is not asked for a second time.+ await database.query(`update public."user" set role = 'user'`);+ invalidateSettingsCache();+ await completeSetup(claim, options);++ assert.deepEqual(await readSetupState(database), { status: "complete" });+ assert.equal(+ (await readStoredSettings(database))?.supportAddress,+ "[email protected]",+ );+});+test("while the administrator's account is being created, nobody else can sign up", async () => {// The account is committed on its own connection before setup's// transaction commits. This is what a sign-up arriving in that gap, ondiff --git a/src/lib/setup.test.ts b/src/lib/setup.test.tsindex 12770ce..31f6acb 100644--- a/src/lib/setup.test.ts+++ b/src/lib/setup.test.ts@@ -24,6 +24,7 @@ test("a database without this version's tables says so", () => {test("the first visitor to a fresh install creates the administrator", () => {assert.deepEqual(resolveSetupView({ status: "fresh" }, { env: {} }), {+ asksForSupportAddress: true,requiresToken: false,senderAddressFromEnv: false,view: "create",@@ -41,7 +42,12 @@ test("a fresh install with SETUP_TOKEN asks for it", () => {},},),- { requiresToken: true, senderAddressFromEnv: true, view: "create" },+ {+ asksForSupportAddress: true,+ requiresToken: true,+ senderAddressFromEnv: true,+ view: "create",+ },);});@@ -51,15 +57,49 @@ test("an install with accounts but no administrator is claimed by someone signed{ status: "unclaimed" },{ env: { SETUP_TOKEN: "a-secret-of-the-owner" }, sessionUser: signedIn },),- { signedInEmail: "[email protected]", tokenConfigured: true, view: "claim" },+ {+ asksForSupportAddress: true,+ signedInEmail: "[email protected]",+ tokenConfigured: true,+ view: "claim",+ },);assert.deepEqual(resolveSetupView({ status: "unclaimed" }, { env: {} }), {+ asksForSupportAddress: true,signedInEmail: null,tokenConfigured: false,view: "claim",});});+test("setup asks for a support address unless the install or the deployment has one", () => {+ const asks = (+ status: "fresh" | "unclaimed",+ options: Parameters<typeof resolveSetupView>[1],+ ) => {+ const view = resolveSetupView({ status }, options);++ assert.ok(view.view === "create" || view.view === "claim");++ return view.asksForSupportAddress;+ };++ for (const status of ["fresh", "unclaimed"] as const) {+ assert.equal(asks(status, { env: {} }), true);+ // Fixed for the deployment: there is nothing to ask.+ assert.equal(+ asks(status, { env: { SUPPORT_EMAIL: "[email protected]" } }),+ false,+ );+ // An install that was given one before keeps it.+ assert.equal(+ asks(status, { env: {}, storedSupportAddress: "[email protected]" }),+ false,+ );+ assert.equal(asks(status, { env: {}, storedSupportAddress: null }), true);+ }+});+test("setup refuses input it cannot use before touching the database", async () => {// Any use of this stand-in database would throw.const database = {} as DbPool;@@ -69,7 +109,11 @@ test("setup refuses input it cannot use before touching the database", async ()await assert.rejects(completeSetup(- { organizationName: " ", senderAddress: "not an address" },+ {+ organizationName: " ",+ senderAddress: "not an address",+ supportAddress: "nor is this",+ },{ createAdminAccount, database, env: {} },),(error: unknown) => {@@ -78,6 +122,7 @@ test("setup refuses input it cannot use before touching the database", async ()assert.deepEqual(error.fieldErrors, {organizationName: "Enter the name of your organization",senderAddress: "Enter a valid email address, or leave this empty",+ supportAddress: "Enter an email address people can write to for help",});return true;diff --git a/src/lib/setup.ts b/src/lib/setup.tsindex 10f35a9..95586a1 100644--- a/src/lib/setup.ts+++ b/src/lib/setup.ts@@ -27,6 +27,12 @@ import { getEnv, isHostedMode, type EnvSource } from "./utils/env.ts";// that predates settings), nobody is created. A signed-in user becomes the// administrator, and SETUP_TOKEN is required: without it, any account// holder could promote themselves.+//+// Either way, setup does not finish without a support address, the one+// signers and account holders are told to write to, unless SUPPORT_EMAIL+// already sets it for the deployment. It is saved in this install's own+// settings, and nothing stands in for it: any address written into the+// code would belong to somebody else.// Held for the length of the setup transaction, so two visitors cannot both// become the first administrator.@@ -38,7 +44,8 @@ export type SetupFieldName =| "organizationName"| "password"| "senderAddress"- | "setupToken";+ | "setupToken"+ | "supportAddress";export class SetupError extends Error {readonly fieldErrors: Partial<Record<SetupFieldName, string>>;@@ -63,12 +70,15 @@ export type SetupView =| {/** Nobody has an account: the visitor creates the administrator. */view: "create";+ /** False when SUPPORT_EMAIL sets the address, or one is saved already. */+ asksForSupportAddress: boolean;requiresToken: boolean;senderAddressFromEnv: boolean;}| {/** Accounts exist: a signed-in user becomes the administrator. */view: "claim";+ asksForSupportAddress: boolean;signedInEmail: string | null;tokenConfigured: boolean;};@@ -111,6 +121,9 @@ const baseSetupSchema = z.object({organizationName: organizationNameSchema,senderAddress: optionalEmailSchema,setupToken: z.string().max(512).optional(),+ // Whether one is needed depends on what is saved already, which is only+ // known once the database has been read.+ supportAddress: optionalEmailSchema,});const createAccountSchema = z.object({@@ -126,6 +139,7 @@ const FIELD_MESSAGES: Record<SetupFieldName, string> = {password: "Password must be at least 15 characters",senderAddress: "Enter a valid email address, or leave this empty",setupToken: "Enter the setup token",+ supportAddress: "Enter an email address people can write to for help",};function toFieldErrors(error: z.ZodError) {@@ -156,16 +170,36 @@ function tokensMatch(provided: string | undefined, expected: string): boolean {return timingSafeEqual(providedDigest, expectedDigest);}+/**+ * Whether setup still has to be given a support address: not when+ * SUPPORT_EMAIL sets it for this deployment, and not when one is saved.+ */+function needsSupportAddress(+ storedSupportAddress: string | null,+ env: EnvSource,+): boolean {+ return (+ getEnv(env).email.supportAddress === undefined && !storedSupportAddress+ );+}+/** Whether setup can be claimed right now, and what the page should ask for. */export function resolveSetupView(state: SetupState,{env = process.env,sessionUser = null,- }: { env?: EnvSource; sessionUser?: SetupSessionUser | null } = {},+ storedSupportAddress = null,+ }: {+ env?: EnvSource;+ sessionUser?: SetupSessionUser | null;+ /** The support address in the settings row, if there is one. */+ storedSupportAddress?: string | null;+ } = {},): SetupView {const appEnv = getEnv(env);const tokenConfigured = appEnv.setup.token !== undefined;+ const asksForSupportAddress = needsSupportAddress(storedSupportAddress, env);if (state.status === "complete") {return { view: "complete" };@@ -177,6 +211,7 @@ export function resolveSetupView(if (state.status === "fresh") {return {+ asksForSupportAddress,requiresToken: tokenConfigured,senderAddressFromEnv: appEnv.email.senderAddress !== undefined,view: "create",@@ -184,6 +219,7 @@ export function resolveSetupView(}return {+ asksForSupportAddress,signedInEmail: sessionUser?.email ?? null,tokenConfigured,view: "claim",@@ -287,15 +323,27 @@ export async function completeSetup(settingsUpdate.senderAddress = base.senderAddress.toLowerCase();}+ // The one given now, or else the one this install already has. It is+ // never guessed: not the administrator's own address, and not one+ // written into the code.+ const supportAddress =+ base.supportAddress?.toLowerCase() ?? stored?.supportAddress ?? null;+ const supportAddressErrors: Partial<Record<SetupFieldName, string>> =+ needsSupportAddress(supportAddress, env)+ ? { supportAddress: FIELD_MESSAGES.supportAddress }+ : {};+if (state.status === "fresh") {const parsedAccount = createAccountSchema.safeParse(rawInput);- if (!parsedAccount.success) {- throw new SetupError(- "Check the highlighted fields.",- 400,- toFieldErrors(parsedAccount.error),- );+ // Refused here, before any account exists.+ if (!parsedAccount.success || supportAddressErrors.supportAddress) {+ throw new SetupError("Check the highlighted fields.", 400, {+ ...(parsedAccount.success+ ? {}+ : toFieldErrors(parsedAccount.error)),+ ...supportAddressErrors,+ });}const account = parsedAccount.data;@@ -345,7 +393,7 @@ export async function completeSetup(...settingsUpdate,allowedEmailDomains: [...signupPolicy.allowedEmailDomains],signupMode: signupPolicy.signupMode,- supportAddress: stored?.supportAddress ?? email,+ supportAddress,},tx,);@@ -367,6 +415,14 @@ export async function completeSetup();}+ if (supportAddressErrors.supportAddress) {+ throw new SetupError(+ "Check the highlighted fields.",+ 400,+ supportAddressErrors,+ );+ }+const promoted = await tx.query(`update public."user" set role = 'admin', "updatedAt" = now() where id = $1`,[sessionUser.id],@@ -385,7 +441,7 @@ export async function completeSetup(...(stored? {}: { allowedEmailDomains: [], signupMode: "open" as const }),- supportAddress: stored?.supportAddress ?? sessionUser.email,+ supportAddress,},tx,);