Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Keep sign-up closed while setup runs, and tie email checks to their sender
Clauded8f2b28c9dff
diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.tsindex bc1538b..bcc4401 100644--- a/src/lib/auth/server.ts+++ b/src/lib/auth/server.ts@@ -18,8 +18,7 @@ import { withUserEmailLegalFooter } from "../services/email-legal-footer.ts";import { consumeRateLimit } from "../security/rate-limit.ts";import { getClientIpHeaderNames } from "../security/request.ts";import { requireConfigValue } from "../services/service-config.ts";-import { getBranding, getSettings, getSetupState } from "../settings.ts";-import { evaluateSignup } from "../signup-policy.ts";+import { evaluateSignupRequest, getBranding } from "../settings.ts";import {getEnv,resolveDeploymentOrigins,@@ -227,28 +226,6 @@ function sendAuthEmailInBackground(input: {}}-/**- * Applies this install's sign-up rule to one email address. Before first-run- * setup has happened nobody can sign up at all: the first account is the- * administrator's, and only the setup page creates it.- */-export async function evaluateSignupRequest(- email: string,- env: EnvSource = process.env,-) {- const setupState = await getSetupState();-- if (setupState.status === "fresh") {- return {- allowed: false as const,- code: "setup_required" as const,- message: "This site has not been set up yet.",- };- }-- return evaluateSignup(email, await getSettings(env));-}-// In production, new passwords are checked against the Have I Been Pwned// breach list, which needs outbound HTTPS to api.pwnedpasswords.com. If the// check cannot be reached, sign-up fails rather than accepting the password.diff --git a/src/lib/db/test-database.ts b/src/lib/db/test-database.tsindex eaa065a..9df8a15 100644--- a/src/lib/db/test-database.ts+++ b/src/lib/db/test-database.ts@@ -3,8 +3,9 @@ import pg from "pg";import { runMigrations } from "../../../db/migrate.mjs";// For the tests that need a real Postgres (npm run test:db). They use the-// same disposable database as the end-to-end test, bring its schema up to-// date, and leave whatever else is in it alone.+// same disposable database as the end-to-end test and bring its schema up+// to date. Some of them empty its accounts and settings, which the+// end-to-end test does on every run anyway.const DEFAULT_TEST_DATABASE_URL ="postgres://signudoc:[email protected]:5432/signudoc_e2e";diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.tsindex 4e42fd3..e359d97 100644--- a/src/lib/email-status.test.ts+++ b/src/lib/email-status.test.ts@@ -96,12 +96,21 @@ function fakeResend(return respond("get", () => domains.find((domain) => domain.id === id));},- list() {- calls.push("list");-- return respond("list", () => ({- data: domains.map(({ id, name, status }) => ({ id, name, status })),- }));+ // Pages like Resend does: up to "limit" domains after the "after" id.+ list({ after, limit = 20 }: { after?: string; limit?: number } = {}) {+ calls.push(after ? `list after ${after}` : "list");++ return respond("list", () => {+ const start = after+ ? domains.findIndex((domain) => domain.id === after) + 1+ : 0;+ const page = domains.slice(start, start + limit);++ return {+ data: page.map(({ id, name, status }) => ({ id, name, status })),+ has_more: start + limit < domains.length,+ };+ });},verify(id: string) {calls.push(`verify ${id}`);@@ -289,6 +298,75 @@ test("checking again asks Resend to verify, then reads the result", async () =>assert.equal((await recheckEmailDomain(resend.options)).state, "ready");});+test("a check that Resend refuses to start is reported, not passed off as still waiting", async () => {+ const resend = fakeResend({+ domains: [+ {+ id: "domain_1",+ name: "acme.com",+ records: [DKIM_RECORD],+ status: "pending",+ },+ ],+ errors: {+ verify: [+ {+ message: "Something went wrong on Resend's side.",+ name: "internal_server_error",+ statusCode: 500,+ },+ ],+ },+ });++ assert.deepEqual(await recheckEmailDomain(resend.options), {+ message: "Something went wrong on Resend's side.",+ senderAddress: "[email protected]",+ state: "error",+ });+ // The domain was not read again, and nothing was recorded either way.+ assert.deepEqual(resend.calls, ["list", "verify domain_1"]);+ assert.deepEqual(resend.readyMarks, []);+});++test("a domain beyond the first page of a large Resend account is still found", async () => {+ const others = Array.from({ length: 230 }, (_, index) => ({+ id: `other_${String(index)}`,+ name: `client-${String(index)}.example`,+ records: [],+ status: "verified",+ }));+ const resend = fakeResend({+ domains: [+ ...others,+ { id: "domain_acme", name: "acme.com", records: [], status: "verified" },+ ],+ });++ assert.equal((await getEmailStatus(resend.options)).state, "ready");+ assert.deepEqual(resend.calls, [+ "list",+ "list after other_99",+ "list after other_199",+ ]);+ assert.deepEqual(resend.readyMarks, [true]);+});++test("a domain is only called missing once every page has been read", async () => {+ const resend = fakeResend({+ domains: Array.from({ length: 150 }, (_, index) => ({+ id: `other_${String(index)}`,+ name: `client-${String(index)}.example`,+ records: [],+ status: "verified",+ })),+ });++ assert.equal((await getEmailStatus(resend.options)).state, "domain_missing");+ assert.deepEqual(resend.calls, ["list", "list after other_99"]);+ assert.deepEqual(resend.readyMarks, [false]);+});+test("a key that may only send points the administrator at Resend instead", async () => {const resend = fakeResend({errors: {diff --git a/src/lib/email-status.ts b/src/lib/email-status.tsindex b99c37d..9eb8187 100644--- a/src/lib/email-status.ts+++ b/src/lib/email-status.ts@@ -143,7 +143,7 @@ async function defaultRecordReady(return;}- await markEmailReady(ready);+ await markEmailReady(ready, settings);}const RATE_LIMIT_RETRY_DELAY_MS = 1_100;@@ -216,6 +216,69 @@ async function describeDomain(};}+const DOMAIN_PAGE_SIZE = 100;+// Enough for two thousand domains. Past that the answer is "could not+// tell", not "the domain is missing".+const MAX_DOMAIN_PAGES = 20;++type ListedDomain = { id: string; name: string; status: string };++type DomainSearch =+ | { error: null; match: ListedDomain | null }+ | {+ error: { message: string; name?: string; statusCode?: number | null };+ match: null;+ };++// Resend hands the account's domains over a page at a time, so the search+// follows the pages until the domain turns up or there are no more.+async function findDomain(+ client: ResendDomainsClient,+ domain: string,+): Promise<DomainSearch> {+ let after: string | undefined;++ for (let page = 0; page < MAX_DOMAIN_PAGES; page += 1) {+ const cursor = after;+ const listed = await callResend(() =>+ client.list(+ cursor+ ? { after: cursor, limit: DOMAIN_PAGE_SIZE }+ : { limit: DOMAIN_PAGE_SIZE },+ ),+ );++ if (listed.error) {+ return { error: listed.error, match: null };+ }++ const domains = listed.data.data;+ const match = domains.find(+ (candidate) => candidate.name.toLowerCase() === domain,+ );++ if (match) {+ return { error: null, match };+ }++ const last = domains[domains.length - 1];++ if (!listed.data.has_more || !last) {+ return { error: null, match: null };+ }++ after = last.id;+ }++ return {+ error: {+ message:+ "This Resend account has too many domains to search. Send a test email to check instead.",+ },+ match: null,+ };+}+// Finds out everything short of the domain's DNS records, which cost one// more request and are fetched by whoever needs them.async function inspectEmail({@@ -262,20 +325,18 @@ async function inspectEmail({return { ...base, status: { senderAddress, state: "test_sender" } };}- const listed = await callResend(() => client.list({ limit: 100 }));+ const found = await findDomain(client, domain);- if (listed.error) {+ if (found.error) {// Nothing is known either way, so the mark is left as it is. A test// email that gets through is what sets it in this case.return {...base,- status: toErrorStatus(listed.error, domain, senderAddress),+ status: toErrorStatus(found.error, domain, senderAddress),};}- const match = listed.data.data.find(- (candidate) => candidate.name.toLowerCase() === domain,- );+ const { match } = found;if (!match) {await markReady(false);@@ -375,7 +436,12 @@ export async function recheckEmailDomain(// Starts a check on Resend's side. Its result can take a moment to show,// so the status returned here may still say the records are pending.- await callResend(() => client.verify(domainId));+ const started = await callResend(() => client.verify(domainId));++ if (started.error) {+ // The check never started, which is not the same as "still waiting".+ return toErrorStatus(started.error, status.domain, status.senderAddress);+ }return describeDomain(client,diff --git a/src/lib/email-test.ts b/src/lib/email-test.tsindex a2861f2..14f8a4d 100644--- a/src/lib/email-test.ts+++ b/src/lib/email-test.ts@@ -5,7 +5,7 @@ import {type EmailService,} from "./services/email.ts";import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";-import { getBranding, markEmailReady } from "./settings.ts";+import { getBranding, getSettings, markEmailReady } from "./settings.ts";import { type EnvSource } from "./utils/env.ts";import { escapeHtml } from "./utils/html.ts";@@ -48,6 +48,11 @@ export async function sendTestEmail({env,);+ // Which sender this test is about to prove, noted before it is sent:+ // an administrator may save a different one while it is on its way.+ const testedSettings = await getSettings(env);+ const { senderAddress: testedSender } = await resolveEmailAddresses(env);+await (emailService ?? createEmailService({ env })).send({htmlBody: content.htmlBody,subject: `Test email from ${productName}`,@@ -60,10 +65,8 @@ export async function sendTestEmail({// address's domain is verified, even when the API key is not allowed to// say so. The shared test address proves nothing: it only ever reaches// the owner of the Resend account.- const { senderAddress } = await resolveEmailAddresses(env);-- if (!isResendTestSender(senderAddress)) {- await markEmailReady(true);+ if (!isResendTestSender(testedSender)) {+ await markEmailReady(true, testedSettings);}return { sent: true, to };diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex 7bb2ec6..98af550 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -1,6 +1,11 @@import { buildBranding, type Branding } from "./branding.ts";import { getDb, queryOne, type DbExecutor } from "./db/connection.ts";-import { type SignupMode, type SignupPolicy } from "./signup-policy.ts";+import {+ evaluateSignup,+ type SignupDecision,+ type SignupMode,+ type SignupPolicy,+} from "./signup-policy.ts";import { getEnv, isHostedMode, type EnvSource } from "./utils/env.ts";// Install-wide settings: one row in app_settings, written by the first-run@@ -46,6 +51,13 @@ export type SetupState = {status: "complete" | "fresh" | "unclaimed" | "unmigrated";};+/** The answer to a sign-up attempt on an install nobody has set up yet. */+export type SetupRequiredDecision = {+ allowed: false;+ code: "setup_required";+ message: string;+};+type AppSettingsRow = {allowed_email_domains: string[] | null;email_ready_at: number | null;@@ -288,13 +300,26 @@ export async function saveSettings(return row ? mapSettingsRow(row) : next;}+/** The sender address a check or a test email was made with. */+export type CheckedSender = Pick<+ ResolvedSettings,+ "senderAddress" | "senderAddressFromEnv"+>;+/**- * Records whether email has been seen working from the current sender- * address. Only touches an existing row: noticing that email works is not a- * reason to create settings nobody chose.+ * Records whether email has been seen working from the sender address that+ * was checked. Only touches an existing row: noticing that email works is+ * not a reason to create settings nobody chose.+ *+ * A check talks to the email provider and can take a while. If an+ * administrator saves a different sender address in the meantime, the+ * result belongs to the old address and is dropped, so it cannot vouch for+ * one that was never tried. An address fixed by the environment cannot+ * change under a running check, so there is nothing to compare.*/export async function markEmailReady(ready: boolean,+ checked: CheckedSender,database: DbExecutor = getDb(),): Promise<void> {const now = Math.floor(Date.now() / 1000);@@ -303,9 +328,44 @@ export async function markEmailReady(`update public.app_settingsset email_ready_at = $1, updated_at = $2- where id and (email_ready_at is null) = $3+ where id+ and (email_ready_at is null) = $3+ and ($4::boolean or sender_address is not distinct from $5)+ `,+ [+ ready ? now : null,+ now,+ ready,+ checked.senderAddressFromEnv,+ checked.senderAddressFromEnv ? null : checked.senderAddress,+ ],+ );++ invalidateSettingsCache();+}++/**+ * Closes sign-up on an install that has no stored rule yet, and leaves an+ * existing rule alone.+ *+ * First-run setup calls this just before it creates the administrator's+ * account. That account is created on its own connection and so can be seen+ * before setup's transaction commits; without a stored rule, an install+ * with an account counts as open to anyone. With this row in place nobody+ * else can register in that gap, or after a setup that failed halfway.+ */+export async function closeSignupUntilSetupFinishes(+ database: DbExecutor = getDb(),+): Promise<void> {+ const now = Math.floor(Date.now() / 1000);++ await database.query(+ `+ insert into public.app_settings (id, signup_mode, created_at, updated_at)+ values (true, 'closed', $1, $1)+ on conflict (id) do nothing`,- [ready ? now : null, now, ready],+ [now],);invalidateSettingsCache();@@ -369,6 +429,40 @@ export async function getSetupState(): Promise<SetupState> {return state;}+/**+ * Applies this install's sign-up rule to one email address. Before first-run+ * setup has happened nobody can sign up at all: the first account is the+ * administrator's, and only the setup page creates it.+ *+ * The rule is read from the database every time rather than from the short+ * cache the pages use. Sign-ups are rare, and a rule that an administrator+ * (or setup) has just saved has to hold at once on every instance, not+ * thirty seconds later.+ */+export async function evaluateSignupRequest(+ email: string,+ env: EnvSource = process.env,+ database: DbExecutor = getDb(),+): Promise<SignupDecision | SetupRequiredDecision> {+ const setupState =+ cache.setupCompleteUntil > Date.now()+ ? ({ status: "complete" } as const)+ : await readSetupState(database);++ if (setupState.status === "fresh") {+ return {+ allowed: false,+ code: "setup_required",+ message: "This site has not been set up yet.",+ };+ }++ return evaluateSignup(+ email,+ resolveSettings(await readStoredSettings(database), env),+ );+}+/** True when every visitor should be sent to the setup page. */export async function isFreshInstall(): Promise<boolean> {return (await getSetupState()).status === "fresh";diff --git a/src/lib/setup.dbtest.ts b/src/lib/setup.dbtest.tsnew file mode 100644index 0000000..a53d878--- /dev/null+++ b/src/lib/setup.dbtest.ts@@ -0,0 +1,209 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { after, before, beforeEach, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import {+ evaluateSignupRequest,+ invalidateSettingsCache,+ markEmailReady,+ readSetupState,+ readStoredSettings,+ saveSettings,+} from "./settings.ts";+import { completeSetup } from "./setup.ts";++// First-run setup and the sign-up rule against a real Postgres, where the+// order in which things become visible to other connections is the point.+// Run with `npm run test:db`.++const env = {};+const setupInput = {+ email: "[email protected]",+ fullName: "Olive Owner",+ organizationName: "Acme Corp",+ password: "a long enough passphrase",+};++let database: pg.Pool;++async function insertUser(email: string, role = "user"): Promise<string> {+ const id = randomUUID();++ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, $2, $3, $4)`,+ [id, "Someone", email, role],+ );++ return id;+}++async function countUsers(): Promise<number> {+ const result = await database.query<{ total: number }>(+ `select count(*)::int as total from public."user"`,+ );++ return result.rows[0]?.total ?? 0;+}++function signUp(email: string) {+ return evaluateSignupRequest(email, env, database);+}++before(async () => {+ database = await openTestDatabase();+});++beforeEach(async () => {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.app_settings");+ invalidateSettingsCache();+});++after(async () => {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.app_settings");+ await database.end();+});++test("before setup nobody can sign up, and after it the chosen rule applies", async () => {+ assert.deepEqual(await signUp("[email protected]"), {+ allowed: false,+ code: "setup_required",+ message: "This site has not been set up yet.",+ });++ const result = await completeSetup(setupInput, {+ createAdminAccount: async ({ email }) => ({+ userId: await insertUser(email),+ }),+ database,+ env,+ });++ assert.equal(result.mode, "create");+ assert.deepEqual(await readSetupState(database), { status: "complete" });+ assert.deepEqual(await signUp("[email protected]"), { allowed: true });+ assert.equal((await signUp("[email protected]")).allowed, false);+});++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, on+ // any other connection, is told.+ const duringSetup: unknown[] = [];++ await completeSetup(setupInput, {+ createAdminAccount: async ({ email }) => {+ const userId = await insertUser(email);++ duringSetup.push(await readSetupState(database));+ duringSetup.push(await signUp("[email protected]"));+ duringSetup.push(await signUp("[email protected]"));++ return { userId };+ },+ database,+ env,+ });++ const refused = {+ allowed: false,+ code: "signup_closed",+ message: "New accounts are not being accepted.",+ };++ assert.deepEqual(duringSetup, [{ status: "unclaimed" }, refused, refused]);+});++test("a setup that fails halfway leaves sign-up closed, not open", async () => {+ const afterTheAccount: unknown[] = [];++ await assert.rejects(+ completeSetup(setupInput, {+ createAdminAccount: async ({ email }) => {+ await insertUser(email);++ throw new Error("the auth library gave up after making the account");+ },+ database,+ env,+ }),+ /gave up/,+ );++ // That account was not removed, because setup never learned its id. The+ // install has an account and no administrator, and must not be open.+ assert.equal(await countUsers(), 1);+ afterTheAccount.push(await readSetupState(database));+ afterTheAccount.push((await readStoredSettings(database))?.signupMode);+ afterTheAccount.push((await signUp("[email protected]")).allowed);++ assert.deepEqual(afterTheAccount, [{ status: "unclaimed" }, "closed", false]);+});++test("an install from before settings existed stays open until it is claimed", async () => {+ await insertUser("[email protected]");++ assert.deepEqual(await readSetupState(database), { status: "unclaimed" });+ assert.equal(await readStoredSettings(database), null);+ assert.deepEqual(await signUp("[email protected]"), { allowed: true });+});++test("a sign-up rule changed a moment ago applies at once", async () => {+ await insertUser("[email protected]", "admin");+ await saveSettings({ setupCompletedAt: 1, signupMode: "open" }, database);++ assert.deepEqual(await signUp("[email protected]"), { allowed: true });++ // Changed behind the app's back, as another instance's save would be:+ // nothing here is told to forget what it had read.+ await database.query(+ "update public.app_settings set signup_mode = 'closed' where id",+ );++ assert.equal((await signUp("[email protected]")).allowed, false);+});++test("an email check only vouches for the sender address it was made with", async () => {+ const readyAt = async () =>+ (await readStoredSettings(database))?.emailReadyAt ?? null;+ const checkedOld = {+ senderAddress: "[email protected]",+ senderAddressFromEnv: false,+ };+ const checkedCurrent = {+ senderAddress: "[email protected]",+ senderAddressFromEnv: false,+ };++ await saveSettings(+ { senderAddress: "[email protected]", signupMode: "closed" },+ database,+ );++ // A check that started before the address was changed finishes late.+ await markEmailReady(true, checkedOld, database);+ assert.equal(await readyAt(), null);++ await markEmailReady(true, checkedCurrent, database);+ assert.notEqual(await readyAt(), null);++ // Nor can a stale failure take the mark away from the current address.+ await markEmailReady(false, checkedOld, database);+ assert.notEqual(await readyAt(), null);++ await markEmailReady(false, checkedCurrent, database);+ assert.equal(await readyAt(), null);++ // An address fixed by the environment is not the stored one, and cannot+ // change while a check runs, so its result is always recorded.+ await markEmailReady(+ true,+ { senderAddress: "Acme <[email protected]>", senderAddressFromEnv: true },+ database,+ );+ assert.notEqual(await readyAt(), null);+});diff --git a/src/lib/setup.ts b/src/lib/setup.tsindex 950b5f0..d2fdba3 100644--- a/src/lib/setup.ts+++ b/src/lib/setup.ts@@ -5,6 +5,7 @@ import { z } from "zod";import { getDb, withTransaction, type DbPool } from "./db/connection.ts";import { emailSchema, nameSchema } from "./schemas/common.ts";import {+ closeSignupUntilSetupFinishes,invalidateSettingsCache,readSetupState,readStoredSettings,@@ -287,6 +288,13 @@ export async function completeSetup(const account = parsedAccount.data;const email = account.email.toLowerCase();++ // The account below is created on its own connection, so it can be+ // seen before this transaction commits. Sign-up is closed first,+ // also outside the transaction, so nobody else can register while+ // an account exists and the rule chosen here has not landed yet.+ await closeSignupUntilSetupFinishes(database);+const { userId } = await createAdminAccount({email,name: account.fullName,