Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add first-run setup at /setup
Claude16b83190889b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a6afdb1..24565ad 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -26,11 +26,11 @@ jobs:- run: npm run typecheck- run: npm run lint- run: npm test- # The build prerenders the legal pages, which read the support address.+ # With nothing configured, as on a first deployment whose database+ # has not been connected yet: the build must not need any of it.- run: npm run buildenv:NEXT_TELEMETRY_DISABLED: "1"- SUPPORT_EMAIL: [email protected]e2e:name: End-to-end testdiff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 913771f..176c401 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -1,9 +1,13 @@import { expect, test, type Page } from "@playwright/test";+import pg from "pg";+import { e2eDatabaseUrl, e2eSetupToken } from "../playwright.config";import { extractLink, extractLinks, waitForEmail } from "./support/outbox";import { writeSamplePdf } from "./support/sample-pdf";const PASSWORD = "correct horse battery staple 42";+// The ampersand is on purpose: the name goes into HTML emails and page titles.+const ORGANIZATION_NAME = "Harbour & Finch Legal";// The accent and the em dash are on purpose: download file names are built// from the title, and a header value cannot carry the em dash as it is.const ENVELOPE_TITLE = "Façade works agreement — phase 1";@@ -29,18 +33,129 @@ async function expectPdfResponse(response: {expect((await response.body()).subarray(0, 5).toString()).toBe("%PDF-");}-test("a sender can send a PDF and a recipient can sign it", async ({+test("a new install is set up, a sender sends a PDF and a recipient signs it", async ({browser,page,}, testInfo) => {const runId = String(Date.now());+ const adminEmail = `admin+${runId}@example.com`;const senderEmail = `sender+${runId}@example.com`;+ const outsiderEmail = `outsider+${runId}@elsewhere.example`;const signerEmail = `signer+${runId}@example.com`;const cspViolations: string[] = [];let envelopeId = "";watchForContentSecurityPolicyViolations(page, cspViolations);+ await test.step("the first visitor sets the site up", async () => {+ const adminContext = await browser.newContext({+ viewport: { height: 900, width: 1440 },+ });+ const adminPage = await adminContext.newPage();++ watchForContentSecurityPolicyViolations(adminPage, cspViolations);++ // Until someone has set it up, every front door leads to the setup page+ // and nobody can create an ordinary account.+ for (const frontDoor of ["/", "/login", "/signup"]) {+ await adminPage.goto(frontDoor);+ await expect(adminPage).toHaveURL(/\/setup$/);+ }++ const earlySignup = await adminContext.request.post(+ "/api/auth/sign-up/email",+ {+ data: {+ email: outsiderEmail,+ name: "Olive Outsider",+ password: PASSWORD,+ },+ headers: { origin: new URL(adminPage.url()).origin },+ },+ );++ expect(earlySignup.status()).toBe(403);+ expect(await earlySignup.json()).toMatchObject({ code: "setup_required" });++ await adminPage.getByLabel("Organization name").fill(ORGANIZATION_NAME);+ await adminPage.getByLabel("Your name").fill("Ada Admin");+ await adminPage.getByLabel("Your email").fill(adminEmail);+ await adminPage.getByLabel("Password").fill(PASSWORD);++ // 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();+ await expect(+ adminPage.getByText("This is not the setup token for this site"),+ ).toBeVisible();++ await adminPage.getByLabel("Setup token").fill(e2eSetupToken);+ await adminPage.getByRole("button", { name: "Finish setup" }).click();++ // Setup ends signed in, on the administrator's settings.+ await expect(adminPage).toHaveURL(/\/settings#organization$/);+ await expect(+ adminPage.getByRole("link", { exact: true, name: ORGANIZATION_NAME }),+ ).toBeVisible();+ await expect(adminPage.getByLabel("Organization name")).toHaveValue(+ ORGANIZATION_NAME,+ );+ // The starting sign-up rule is the administrator's own email domain.+ await expect(adminPage.getByLabel("Email domains")).toHaveValue(+ "example.com",+ );+ await expect(+ adminPage.getByText("Emails are being captured, not sent"),+ ).toBeVisible();++ const testEmailResponse = await adminContext.request.post(+ "/api/admin/email",+ { data: { action: "send_test" } },+ );++ expect(testEmailResponse.status()).toBe(200);++ const testEmail = await waitForEmail({+ template: "test_email",+ to: adminEmail,+ });++ expect(testEmail.subject).toBe(`Test email from ${ORGANIZATION_NAME}`);++ // Setup can only happen once.+ await adminPage.goto("/setup");+ await expect(adminPage).not.toHaveURL(/\/setup/);++ const secondSetup = await adminContext.request.post("/api/setup", {+ data: {+ email: outsiderEmail,+ fullName: "Olive Outsider",+ organizationName: "Someone Else",+ password: PASSWORD,+ setupToken: e2eSetupToken,+ },+ });++ expect(secondSetup.status()).toBe(409);++ await adminContext.close();+ });++ await test.step("an address outside the organization cannot sign up", async () => {+ await page.goto("/signup");+ await expect(page).toHaveTitle(ORGANIZATION_NAME);+ await page.getByLabel("Full name").fill("Olive Outsider");+ await page.getByLabel("Email").fill(outsiderEmail);+ await page.getByLabel("Password").fill(PASSWORD);+ await page.getByRole("button", { name: "Sign up" }).click();+ await expect(+ page.getByRole("alert").filter({+ hasText:+ "Accounts can be created with an email address at @example.com.",+ }),+ ).toBeVisible();+ });+await test.step("sign up and verify the email address", async () => {await page.goto("/signup");await page.getByLabel("Full name").fill("Sam Sender");@@ -56,6 +171,11 @@ test("a sender can send a PDF and a recipient can sign it", async ({to: senderEmail,});+ // Emails carry the organization's name, not the product's.+ expect(verificationEmail.text).toContain(+ `Sent by ${ORGANIZATION_NAME} using SignuDoc.`,+ );+await page.goto(extractLink(verificationEmail.text, "/api/auth/verify-email"),);@@ -70,6 +190,20 @@ test("a sender can send a PDF and a recipient can sign it", async ({await expect(page.getByRole("heading", { name: "No documents yet" }),).toBeVisible();++ // An ordinary account gets none of the administrator's controls.+ await page.goto("/settings");+ await expect(+ page.getByRole("heading", { name: "Organization" }),+ ).toHaveCount(0);+ expect((await page.request.get("/api/admin/email")).status()).toBe(403);+ expect(+ (+ await page.request.put("/api/admin/settings", {+ data: { organizationName: "Taken Over", signupMode: "open" },+ })+ ).status(),+ ).toBe(403);});await test.step("upload a PDF", async () => {@@ -135,6 +269,8 @@ test("a sender can send a PDF and a recipient can sign it", async ({});const signingLink = extractLink(invitation.text, "/sign/");+ expect(invitation.text).toContain(`through ${ORGANIZATION_NAME}.`);+await test.step("the recipient signs without an account", async () => {const recipientContext = await browser.newContext({viewport: { height: 900, width: 1440 },@@ -199,5 +335,59 @@ test("a sender can send a PDF and a recipient can sign it", async ({}});+ // An install from before there were administrators has accounts but+ // nobody in charge. One of its users takes charge with the setup token.+ await test.step("an install with no administrator is claimed with the setup token", async () => {+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });++ await database.connect();++ try {+ await database.query(`update public."user" set role = 'user'`);+ await database.query("delete from public.app_settings");+ } finally {+ await database.end();+ }++ const claim = { organizationName: "Second Wind Partners" };+ const anonymousContext = await browser.newContext();++ expect(+ (+ await anonymousContext.request.post("/api/setup", {+ data: { ...claim, setupToken: e2eSetupToken },+ })+ ).status(),+ ).toBe(401);+ await anonymousContext.close();++ expect(+ (await page.request.post("/api/setup", { data: claim })).status(),+ ).toBe(403);+ expect(+ (+ await page.request.post("/api/setup", {+ data: { ...claim, setupToken: "not the token" },+ })+ ).status(),+ ).toBe(403);++ const claimed = await page.request.post("/api/setup", {+ data: { ...claim, setupToken: e2eSetupToken },+ });++ expect(claimed.status()).toBe(201);++ await page.goto("/settings");+ await expect(+ page.getByRole("heading", { name: "Organization" }),+ ).toBeVisible();+ await expect(page.getByLabel("Organization name")).toHaveValue(+ claim.organizationName,+ );+ // Sign-up stays as it was before anyone was in charge: open.+ await expect(page.getByRole("radio", { name: /^Anyone/ })).toBeChecked();+ });+expect(cspViolations).toEqual([]);});diff --git a/playwright.config.ts b/playwright.config.tsindex d4c4eca..9315881 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -21,6 +21,8 @@ export const e2eDatabaseUrl ="postgres://signudoc:[email protected]:5432/signudoc_e2e";export const e2eDataDir = path.resolve(".data", "e2e");export const e2eOutboxDir = path.join(e2eDataDir, "outbox");+// First-run setup asks for this, as it does on a deployment that sets one.+export const e2eSetupToken = "e2e-setup-token";export default defineConfig({expect: { timeout: 20_000 },@@ -59,16 +61,19 @@ export default defineConfig({NEXT_TELEMETRY_DISABLED: "1",// The breach check calls an outside service; the test must not.PASSWORD_BREACH_CHECK: "off",+ SETUP_TOKEN: e2eSetupToken,// "local" unless E2E_STORAGE_DRIVER says otherwise. With "blob" and a// BLOB_READ_WRITE_TOKEN in the environment, the same test runs against// a real Vercel Blob store, direct browser upload included.STORAGE_DRIVER: process.env.E2E_STORAGE_DRIVER ?? "local",STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),- SUPPORT_EMAIL: "[email protected]",},reuseExistingServer: false,timeout: 300_000,- url: `${baseURL}/login`,+ // Playwright starts the server before the test database is wiped, so+ // the readiness check must not be a page: a page would look at last+ // run's data and remember for a minute that the site is already set up.+ url: `${baseURL}/api/auth/ok`,},workers: 1,});diff --git a/src/app/api/setup/route.ts b/src/app/api/setup/route.tsnew file mode 100644index 0000000..8c7c195--- /dev/null+++ b/src/app/api/setup/route.ts@@ -0,0 +1,166 @@+import { APIError } from "better-auth";+import { NextResponse } from "next/server";++import { getAuth, getAuthSessionFromHeaders } from "@/lib/auth/server";+import { runAsSetup } from "@/lib/auth/setup-context";+import { logRouteError, logSecurityEvent } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { completeSetup, SetupError } from "@/lib/setup";++// First-run setup. Open to anyone who reaches it while the install has no+// administrator, which is the point: there is nobody to sign in as yet.+// What keeps it safe is in completeSetup (one winner, and SETUP_TOKEN when+// the deployment sets one), a rate limit, and the JSON-only rule below.++function isJsonRequest(request: Request): boolean {+ return (request.headers.get("content-type") ?? "")+ .toLowerCase()+ .startsWith("application/json");+}++async function createAdminAccount(input: {+ email: string;+ name: string;+ password: string;+}) {+ try {+ const result = await runAsSetup(() =>+ getAuth().api.signUpEmail({+ body: {+ email: input.email,+ name: input.name,+ password: input.password,+ },+ }),+ );++ return { userId: result.user.id };+ } catch (error) {+ if (error instanceof APIError) {+ const code = String(error.body?.code ?? "");+ const message =+ error.body?.message ?? "The account could not be created.";++ if (code === "PASSWORD_COMPROMISED") {+ throw new SetupError("Choose a different password.", 400, {+ password: "This password has appeared in a breach. Choose another.",+ });+ }++ throw new SetupError(message, 400);+ }++ throw error;+ }+}++export async function POST(request: Request) {+ const ipAddress = getClientIpAddress(request.headers);+ const rateLimitResponse = applyRateLimit({+ category: "setup_submit",+ key: buildRateLimitKey(["setup", ipAddress ?? "unknown"]),+ limit: 10,+ request,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ // A page on another site can make a browser send a form here, but it+ // cannot make it send JSON without this site's permission. Insisting on+ // JSON keeps a stranger's page from running setup in a visitor's browser.+ if (!isJsonRequest(request)) {+ return NextResponse.json(+ { error: "Send this request as JSON." },+ { status: 415 },+ );+ }++ const body = (await request.json().catch(() => null)) as Record<+ string,+ unknown+ > | null;++ try {+ const session = await getAuthSessionFromHeaders(request.headers);+ const result = await completeSetup(body ?? {}, {+ createAdminAccount,+ sessionUser: session+ ? {+ email: session.user.email,+ emailVerified: session.user.emailVerified === true,+ id: session.user.id,+ }+ : null,+ });++ logSecurityEvent("info", {+ category: "setup_completed",+ ipAddress,+ message: `First-run setup completed (${result.mode}).`,+ path: getRequestPathname(request),+ userId: result.userId,+ });++ if (result.mode === "create") {+ // Sign the new administrator in, so setup ends inside the app rather+ // than at a sign-in form. If this fails the account still exists and+ // they can sign in by hand.+ try {+ await getAuth().api.signInEmail({+ body: {+ email: result.email,+ password: String(body?.password ?? ""),+ },+ headers: request.headers,+ });+ } catch (error) {+ console.error(+ "Setup finished, but signing in afterwards failed:",+ error,+ );++ return NextResponse.json({ redirectTo: "/login" }, { status: 201 });+ }+ }++ return NextResponse.json(+ { redirectTo: "/settings#organization" },+ { status: 201 },+ );+ } catch (error) {+ if (error instanceof SetupError) {+ if (error.statusCode === 403) {+ logSecurityEvent("warn", {+ category: "setup_refused",+ ipAddress,+ message: error.message,+ path: getRequestPathname(request),+ });+ }++ return NextResponse.json(+ { error: error.message, fieldErrors: error.fieldErrors },+ { status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "setup_failure",+ ipAddress,+ message: "Unexpected failure during first-run setup.",+ path: getRequestPathname(request),+ });++ return NextResponse.json(+ { error: "Setup could not be completed. Please try again." },+ { status: 500 },+ );+ }+}diff --git a/src/app/setup/page.tsx b/src/app/setup/page.tsxnew file mode 100644index 0000000..517873f--- /dev/null+++ b/src/app/setup/page.tsx@@ -0,0 +1,69 @@+import type { Metadata } from "next";+import { redirect } from "next/navigation";+import { connection } from "next/server";++import { BrandingProvider } from "@/components/layout/branding-provider";+import {+ SetupShell,+ type SetupShellView,+} from "@/components/setup/setup-shell";+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 { resolveSetupView } from "@/lib/setup";+import { isHostedMode } from "@/lib/utils/env";++export const metadata: Metadata = {+ description: "Create the administrator account for this site.",+ title: "Set up",+};++async function loadView(): Promise<SetupShellView> {+ try {+ const state = await getSetupState();+ // Only an install that already has accounts cares who is signed in.+ const session =+ state.status === "unclaimed" ? await getAuthSession() : null;++ return resolveSetupView(state, {+ sessionUser: session+ ? {+ email: session.user.email,+ emailVerified: session.user.emailVerified === true,+ id: session.user.id,+ }+ : null,+ });+ } catch (error) {+ // No database connected at all. The page can still say so.+ if (error instanceof ServiceConfigurationError) {+ return { view: "no_database" };+ }++ throw error;+ }+}++// First-run setup. Exists only until the install has an administrator;+// after that it sends everyone to the sign-in page.+export default async function SetupPage() {+ await connection();++ const view = await loadView();++ if (view.view === "complete") {+ redirect("/login");+ }++ return (+ // There is no organization yet, so the page goes by the product's name.+ <BrandingProvider branding={buildBranding(resolveSettings(null))}>+ <SetupShell+ hosted={isHostedMode()}+ onVercel={process.env.VERCEL === "1"}+ view={view}+ />+ </BrandingProvider>+ );+}diff --git a/src/components/setup/setup-shell.tsx b/src/components/setup/setup-shell.tsxnew file mode 100644index 0000000..95b4a3a--- /dev/null+++ b/src/components/setup/setup-shell.tsx@@ -0,0 +1,413 @@+"use client";++import Link from "next/link";+import {+ useState,+ type ChangeEvent,+ type FormEvent,+ type ReactNode,+} from "react";++import { Brand } from "@/components/layout/brand";+import { PublicLegalFooter } from "@/components/layout/public-legal-links";+import { FieldShell, ShellButton } from "@/components/shared/form-shell";+import type { SetupFieldName, SetupView } from "@/lib/setup";+import { getEmailDomain, suggestSignupPolicy } from "@/lib/signup-policy";++export type SetupShellView =+ | Exclude<SetupView, { view: "complete" }>+ | { view: "complete" }+ | { view: "no_database" };++type SetupShellProps = {+ hosted: boolean;+ onVercel: boolean;+ view: SetupShellView;+};++type SetupValues = Record<SetupFieldName, string>;+type SetupErrors = Partial<Record<SetupFieldName, string>>;++type SetupResponse = {+ error?: string;+ fieldErrors?: SetupErrors;+ redirectTo?: string;+} | null;++const GENERIC_ERROR_MESSAGE = "Setup could not be completed. Please try again.";++const emptyValues: SetupValues = {+ email: "",+ fullName: "",+ organizationName: "",+ password: "",+ senderAddress: "",+ setupToken: "",+};++export function SetupShell({ hosted, onVercel, view }: SetupShellProps) {+ return (+ <div className="flex min-h-screen flex-col bg-white">+ <header className="border-b border-(--border) bg-white">+ <div className="editorial-shell flex items-center justify-between gap-4 px-0 py-5">+ <Brand href="/setup" />+ <p className="editorial-meta">Setup</p>+ </div>+ </header>++ <main className="editorial-shell flex flex-1 items-start justify-center px-0 py-12 sm:py-16">+ <div className="flex w-full justify-center" data-animate="enter">+ <section className="editorial-panel w-full max-w-[520px] p-8 sm:p-10">+ <SetupContent hosted={hosted} onVercel={onVercel} view={view} />+ </section>+ </div>+ </main>++ <PublicLegalFooter />+ </div>+ );+}++function SetupContent({ hosted, onVercel, view }: SetupShellProps) {+ if (view.view === "no_database") {+ return (+ <SetupNotice title="Connect a database">+ <p>+ This site does not have a database yet, so there is nowhere to keep+ accounts or documents.+ </p>+ {onVercel ? (+ <p>+ In Vercel, open this project's Storage tab, add a Neon Postgres+ database and connect it to the project. Then deploy again and reload+ this page.+ </p>+ ) : (+ <p>+ Set the DATABASE_URL environment variable to a Postgres database,+ run <code>npm run db:migrate</code>, restart the app and reload this+ page.+ </p>+ )}+ </SetupNotice>+ );+ }++ if (view.view === "unmigrated") {+ return (+ <SetupNotice title="The database is not ready">+ <p>+ The database is connected, but its tables have not been created or are+ from an older version.+ </p>+ {onVercel ? (+ <p>+ Deploy this project again. Tables are created during a production+ deployment. Then reload this page.+ </p>+ ) : (+ <p>+ Run <code>npm run db:migrate</code>, restart the app and reload this+ page.+ </p>+ )}+ </SetupNotice>+ );+ }++ if (view.view === "claim") {+ if (!view.tokenConfigured) {+ return (+ <SetupNotice title="Choose an administrator">+ <p>+ This site already has accounts but no administrator. To choose one,+ set the SETUP_TOKEN environment variable to a secret of your own,+ deploy again, and come back to this page.+ </p>+ <p>+ The token is asked for here, so that only someone who controls the+ deployment can become the administrator.+ </p>+ </SetupNotice>+ );+ }++ if (!view.signedInEmail) {+ return (+ <SetupNotice title="Choose an administrator">+ <p>+ This site already has accounts but no administrator. Sign in with+ the account that should become the administrator, then open this+ page again.+ </p>+ <ShellButton className="w-full" href="/login" variant="primary">+ Go to log in+ </ShellButton>+ </SetupNotice>+ );+ }+ }++ if (view.view === "complete") {+ return null;+ }++ return <SetupForm hosted={hosted} view={view} />;+}++function SetupNotice({+ children,+ title,+}: {+ children: ReactNode;+ title: string;+}) {+ return (+ <div className="space-y-5">+ <div className="space-y-2">+ <p className="section-eyebrow">Setup</p>+ <h1 className="text-[clamp(2rem,4.6vw,2.7rem)] font-extrabold leading-[1.04] tracking-[-0.045em] text-black">+ {title}+ </h1>+ </div>+ <div className="space-y-4 text-sm leading-6 text-muted-foreground [&_code]:[font-family:var(--font-mono)] [&_code]:text-[0.82rem] [&_code]:text-(--fg)">+ {children}+ </div>+ </div>+ );+}++function describeSignupStart(email: string, hosted: boolean): string | null {+ if (hosted) {+ return null;+ }++ if (!getEmailDomain(email)) {+ return null;+ }++ const policy = suggestSignupPolicy(email);++ if (policy.signupMode === "domains") {+ return `Other people with an @${policy.allowedEmailDomains[0]} address will be able to create accounts. You can change this in Settings.`;+ }++ return "Only you will have an account to begin with. You can let other people in from Settings.";+}++function SetupForm({+ hosted,+ view,+}: {+ hosted: boolean;+ view: Extract<SetupShellView, { view: "claim" | "create" }>;+}) {+ const [values, setValues] = useState<SetupValues>(emptyValues);+ const [errors, setErrors] = useState<SetupErrors>({});+ const [bannerMessage, setBannerMessage] = useState<string | null>(null);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const isCreate = view.view === "create";+ const requiresToken = isCreate ? view.requiresToken : true;+ const asksForSender = isCreate && !view.senderAddressFromEnv;++ function handleChange(field: SetupFieldName) {+ return (event: ChangeEvent<HTMLInputElement>) => {+ const nextValue = event.target.value;++ setValues((currentValues) => ({ ...currentValues, [field]: nextValue }));+ setErrors((currentErrors) => ({ ...currentErrors, [field]: undefined }));+ setBannerMessage(null);+ };+ }++ async function handleSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();++ if (isSubmitting) {+ return;+ }++ setBannerMessage(null);+ setErrors({});+ setIsSubmitting(true);++ try {+ const response = await fetch("/api/setup", {+ body: JSON.stringify({+ organizationName: values.organizationName,+ setupToken: requiresToken ? values.setupToken : undefined,+ ...(isCreate+ ? {+ email: values.email,+ fullName: values.fullName,+ password: values.password,+ senderAddress: asksForSender ? values.senderAddress : undefined,+ }+ : {}),+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const payload = (await response+ .json()+ .catch(() => null)) as SetupResponse;++ if (!response.ok) {+ setErrors(payload?.fieldErrors ?? {});+ setBannerMessage(payload?.error ?? GENERIC_ERROR_MESSAGE);+ setIsSubmitting(false);+ return;+ }++ // A full page load, so the app starts again with the new session and+ // the organization's name.+ window.location.assign(payload?.redirectTo ?? "/dashboard");+ } catch {+ setBannerMessage(GENERIC_ERROR_MESSAGE);+ setIsSubmitting(false);+ }+ }++ const signupStart = isCreate+ ? describeSignupStart(values.email, hosted)+ : null;++ return (+ <div className="space-y-7">+ <div className="space-y-2">+ <p className="section-eyebrow">Setup</p>+ <h1 className="text-[clamp(2rem,4.6vw,2.7rem)] font-extrabold leading-[1.04] tracking-[-0.045em] text-black">+ {isCreate ? "Set up your site" : "Choose an administrator"}+ </h1>+ <p className="pt-1 text-sm leading-6 text-muted-foreground">+ {isCreate+ ? "You are the first person here. The account you create now is the administrator: it can change these settings later and decide who else may sign up."+ : `You are signed in as ${view.signedInEmail ?? ""}. This account will become the administrator, who decides who may sign up and how email is sent.`}+ </p>+ </div>++ {bannerMessage ? (+ <p+ className="rounded-[22px] border border-[rgba(180,35,53,0.16)] bg-[rgba(180,35,53,0.06)] px-4 py-3 text-sm font-medium text-(--accent)"+ role="alert"+ >+ {bannerMessage}+ </p>+ ) : null}++ <form className="space-y-5" noValidate onSubmit={handleSubmit}>+ <FieldShell+ autoComplete="organization"+ disabled={isSubmitting}+ error={errors.organizationName}+ helper="Shown in the header and in every email this site sends."+ label="Organization name"+ name="setup-organization-name"+ onChange={handleChange("organizationName")}+ placeholder="Acme Corp"+ readOnly={false}+ value={values.organizationName}+ />++ {isCreate ? (+ <>+ <FieldShell+ autoComplete="name"+ disabled={isSubmitting}+ error={errors.fullName}+ label="Your name"+ name="setup-full-name"+ onChange={handleChange("fullName")}+ placeholder="Jane Smith"+ readOnly={false}+ value={values.fullName}+ />+ <FieldShell+ autoComplete="email"+ disabled={isSubmitting}+ error={errors.email}+ helper={signupStart ?? undefined}+ label="Your email"+ name="setup-email"+ onChange={handleChange("email")}+ placeholder="[email protected]"+ readOnly={false}+ type="email"+ value={values.email}+ />+ <FieldShell+ autoComplete="new-password"+ disabled={isSubmitting}+ error={errors.password}+ helper="Must be at least 15 characters"+ label="Password"+ name="setup-password"+ onChange={handleChange("password")}+ placeholder="Enter a password"+ readOnly={false}+ type="password"+ value={values.password}+ />+ </>+ ) : null}++ {asksForSender ? (+ <FieldShell+ autoComplete="off"+ disabled={isSubmitting}+ error={errors.senderAddress}+ helper="Optional. An address at a domain you own, such as [email protected]. The next screen shows the DNS records that let this site send from it. Leave it empty to decide later."+ label="Send email from"+ name="setup-sender-address"+ onChange={handleChange("senderAddress")}+ placeholder="[email protected]"+ readOnly={false}+ type="email"+ value={values.senderAddress}+ />+ ) : null}++ {requiresToken ? (+ <FieldShell+ autoComplete="off"+ disabled={isSubmitting}+ error={errors.setupToken}+ helper="The value of the SETUP_TOKEN environment variable on this deployment."+ label="Setup token"+ name="setup-token"+ onChange={handleChange("setupToken")}+ readOnly={false}+ type="password"+ value={values.setupToken}+ />+ ) : null}++ <ShellButton+ className="w-full"+ disabled={isSubmitting}+ loading={isSubmitting}+ type="submit"+ variant="primary"+ >+ {isSubmitting+ ? "Setting up..."+ : isCreate+ ? "Finish setup"+ : "Become the administrator"}+ </ShellButton>+ </form>++ {!isCreate ? (+ <p className="border-t border-(--border) pt-5 text-sm text-muted-foreground">+ Not the right account?{" "}+ <Link+ className="font-semibold text-(--fg) transition hover:text-(--accent)"+ href="/login"+ >+ Log in as someone else+ </Link>+ </p>+ ) : null}+ </div>+ );+}diff --git a/src/lib/setup.test.ts b/src/lib/setup.test.tsnew file mode 100644index 0000000..12770ce--- /dev/null+++ b/src/lib/setup.test.ts@@ -0,0 +1,86 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import type { DbPool } from "./db/connection.ts";+import { completeSetup, resolveSetupView, SetupError } from "./setup.ts";++const signedIn = {+ email: "[email protected]",+ emailVerified: true,+ id: "user_1",+};++test("a set-up install has nothing to show on the setup page", () => {+ assert.deepEqual(resolveSetupView({ status: "complete" }, { env: {} }), {+ view: "complete",+ });+});++test("a database without this version's tables says so", () => {+ assert.deepEqual(resolveSetupView({ status: "unmigrated" }, { env: {} }), {+ view: "unmigrated",+ });+});++test("the first visitor to a fresh install creates the administrator", () => {+ assert.deepEqual(resolveSetupView({ status: "fresh" }, { env: {} }), {+ requiresToken: false,+ senderAddressFromEnv: false,+ view: "create",+ });+});++test("a fresh install with SETUP_TOKEN asks for it", () => {+ assert.deepEqual(+ resolveSetupView(+ { status: "fresh" },+ {+ env: {+ RESEND_FROM_EMAIL: "[email protected]",+ SETUP_TOKEN: "a-secret-of-the-owner",+ },+ },+ ),+ { requiresToken: true, senderAddressFromEnv: true, view: "create" },+ );+});++test("an install with accounts but no administrator is claimed by someone signed in", () => {+ assert.deepEqual(+ resolveSetupView(+ { status: "unclaimed" },+ { env: { SETUP_TOKEN: "a-secret-of-the-owner" }, sessionUser: signedIn },+ ),+ { signedInEmail: "[email protected]", tokenConfigured: true, view: "claim" },+ );+ assert.deepEqual(resolveSetupView({ status: "unclaimed" }, { env: {} }), {+ signedInEmail: null,+ tokenConfigured: false,+ view: "claim",+ });+});++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;+ const createAdminAccount = async () => {+ throw new Error("must not be reached");+ };++ await assert.rejects(+ completeSetup(+ { organizationName: " ", senderAddress: "not an address" },+ { createAdminAccount, database, env: {} },+ ),+ (error: unknown) => {+ assert.ok(error instanceof SetupError);+ assert.equal(error.statusCode, 400);+ assert.deepEqual(error.fieldErrors, {+ organizationName: "Enter the name of your organization",+ senderAddress: "Enter a valid email address, or leave this empty",+ });++ return true;+ },+ );+});diff --git a/src/lib/setup.ts b/src/lib/setup.tsnew file mode 100644index 0000000..950b5f0--- /dev/null+++ b/src/lib/setup.ts@@ -0,0 +1,398 @@+import { createHash, timingSafeEqual } from "node:crypto";++import { z } from "zod";++import { getDb, withTransaction, type DbPool } from "./db/connection.ts";+import { emailSchema, nameSchema } from "./schemas/common.ts";+import {+ invalidateSettingsCache,+ readSetupState,+ readStoredSettings,+ saveSettings,+ type SettingsUpdate,+ type SetupState,+} from "./settings.ts";+import { suggestSignupPolicy } from "./signup-policy.ts";+import { getEnv, isHostedMode, type EnvSource } from "./utils/env.ts";++// First-run setup: the step that turns a deployment into someone's install.+//+// On a database with no accounts, the first visitor to /setup creates the+// administrator and names the organization. Setting SETUP_TOKEN means the+// visitor must also know that token, for installs that sit on a public URL+// before their owner gets to them.+//+// On a database that already has accounts but no administrator (an install+// 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.++// Held for the length of the setup transaction, so two visitors cannot both+// become the first administrator.+const SETUP_ADVISORY_LOCK_ID = 746108322;++export type SetupFieldName =+ | "email"+ | "fullName"+ | "organizationName"+ | "password"+ | "senderAddress"+ | "setupToken";++export class SetupError extends Error {+ readonly fieldErrors: Partial<Record<SetupFieldName, string>>;+ readonly statusCode: number;++ constructor(+ message: string,+ statusCode: number,+ fieldErrors: Partial<Record<SetupFieldName, string>> = {},+ ) {+ super(message);+ this.name = "SetupError";+ this.fieldErrors = fieldErrors;+ this.statusCode = statusCode;+ }+}++/** What the setup page should show. */+export type SetupView =+ | { view: "complete" }+ | { view: "unmigrated" }+ | {+ /** Nobody has an account: the visitor creates the administrator. */+ view: "create";+ requiresToken: boolean;+ senderAddressFromEnv: boolean;+ }+ | {+ /** Accounts exist: a signed-in user becomes the administrator. */+ view: "claim";+ signedInEmail: string | null;+ tokenConfigured: boolean;+ };++type SetupSessionUser = {+ email: string;+ emailVerified: boolean;+ id: string;+};++type CreateAdminAccount = (input: {+ email: string;+ name: string;+ password: string;+}) => Promise<{ userId: string }>;++type CompleteSetupOptions = {+ /**+ * Creates the administrator's account through the auth library. Passed in+ * so this module does not depend on the auth setup (and can be tested).+ */+ createAdminAccount: CreateAdminAccount;+ database?: DbPool;+ env?: EnvSource;+ sessionUser?: SetupSessionUser | null;+};++export type CompleteSetupResult =+ | { mode: "create"; email: string; userId: string }+ | { mode: "claim"; email: string; userId: string };++const organizationNameSchema = z.string().trim().min(1).max(120);+const optionalEmailSchema = z.preprocess(+ (value) =>+ typeof value === "string" && value.trim().length === 0 ? undefined : value,+ emailSchema.optional(),+);++const baseSetupSchema = z.object({+ organizationName: organizationNameSchema,+ senderAddress: optionalEmailSchema,+ setupToken: z.string().max(512).optional(),+});++const createAccountSchema = z.object({+ email: emailSchema,+ fullName: nameSchema,+ password: z.string().min(15).max(128),+});++const FIELD_MESSAGES: Record<SetupFieldName, string> = {+ email: "Enter a valid email address",+ fullName: "Enter your full name",+ organizationName: "Enter the name of your organization",+ password: "Password must be at least 15 characters",+ senderAddress: "Enter a valid email address, or leave this empty",+ setupToken: "Enter the setup token",+};++function toFieldErrors(error: z.ZodError) {+ const fieldErrors: Partial<Record<SetupFieldName, string>> = {};++ for (const issue of error.issues) {+ const field = issue.path[0];++ if (typeof field === "string" && field in FIELD_MESSAGES) {+ fieldErrors[field as SetupFieldName] ??=+ FIELD_MESSAGES[field as SetupFieldName];+ }+ }++ return fieldErrors;+}++function tokensMatch(provided: string | undefined, expected: string): boolean {+ if (!provided) {+ return false;+ }++ // Hashing first makes both sides the same length, which timingSafeEqual+ // requires, without revealing how long the real token is.+ const providedDigest = createHash("sha256").update(provided.trim()).digest();+ const expectedDigest = createHash("sha256").update(expected).digest();++ return timingSafeEqual(providedDigest, expectedDigest);+}++/** 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 } = {},+): SetupView {+ const appEnv = getEnv(env);+ const tokenConfigured = appEnv.setup.token !== undefined;++ if (state.status === "complete") {+ return { view: "complete" };+ }++ if (state.status === "unmigrated") {+ return { view: "unmigrated" };+ }++ if (state.status === "fresh") {+ return {+ requiresToken: tokenConfigured,+ senderAddressFromEnv: appEnv.email.senderAddress !== undefined,+ view: "create",+ };+ }++ return {+ signedInEmail: sessionUser?.email ?? null,+ tokenConfigured,+ view: "claim",+ };+}++function assertSetupToken(+ state: SetupState,+ providedToken: string | undefined,+ env: EnvSource,+) {+ const expectedToken = getEnv(env).setup.token;++ if (state.status === "unclaimed" && expectedToken === undefined) {+ throw new SetupError(+ "This site already has accounts. Set the SETUP_TOKEN environment variable and redeploy to choose its administrator.",+ 403,+ );+ }++ if (+ expectedToken !== undefined &&+ !tokensMatch(providedToken, expectedToken)+ ) {+ throw new SetupError("The setup token is not correct.", 403, {+ setupToken: "This is not the setup token for this site",+ });+ }+}++/**+ * Runs first-run setup. Everything that decides who becomes administrator+ * happens inside one transaction under a lock, after the state has been read+ * again, so a second request that arrives at the same moment finds setup+ * already complete.+ */+export async function completeSetup(+ rawInput: unknown,+ {+ createAdminAccount,+ database = getDb(),+ env = process.env,+ sessionUser = null,+ }: CompleteSetupOptions,+): Promise<CompleteSetupResult> {+ const parsedBase = baseSetupSchema.safeParse(rawInput);++ if (!parsedBase.success) {+ throw new SetupError(+ "Check the highlighted fields.",+ 400,+ toFieldErrors(parsedBase.error),+ );+ }++ const base = parsedBase.data;+ // Set from inside the transaction callback, read again if it fails.+ const created: { userId: string | null } = { userId: null };++ try {+ const result = await withTransaction(async (tx) => {+ await tx.query("select pg_advisory_xact_lock($1)", [+ SETUP_ADVISORY_LOCK_ID,+ ]);++ const state = await readSetupState(tx);++ if (state.status === "complete") {+ throw new SetupError("This site has already been set up.", 409);+ }++ if (state.status === "unmigrated") {+ throw new SetupError(+ "The database is not ready yet. Deploy again so the tables can be created.",+ 503,+ );+ }++ assertSetupToken(state, base.setupToken, env);++ const now = Math.floor(Date.now() / 1000);+ const stored = await readStoredSettings(tx);+ const settingsUpdate: SettingsUpdate = {+ organizationName: base.organizationName,+ setupCompletedAt: now,+ };++ if (base.senderAddress !== undefined) {+ settingsUpdate.senderAddress = base.senderAddress.toLowerCase();+ }++ if (state.status === "fresh") {+ const parsedAccount = createAccountSchema.safeParse(rawInput);++ if (!parsedAccount.success) {+ throw new SetupError(+ "Check the highlighted fields.",+ 400,+ toFieldErrors(parsedAccount.error),+ );+ }++ const account = parsedAccount.data;+ const email = account.email.toLowerCase();+ const { userId } = await createAdminAccount({+ email,+ name: account.fullName,+ password: account.password,+ });++ created.userId = userId;++ // The account is verified here because email cannot work before+ // setup has finished, and there is nobody else to vouch for it.+ const promoted = await tx.query(+ `+ update public."user"+ set role = 'admin', "emailVerified" = true, "updatedAt" = now()+ where id = $1+ `,+ [userId],+ );++ if (promoted.rowCount !== 1) {+ throw new SetupError(+ "The administrator account was not created.",+ 500,+ );+ }++ // A hosted service takes sign-ups from anyone. Any other install+ // starts with the administrator's own email domain, or closed when+ // that domain is a public mailbox provider.+ const signupPolicy = isHostedMode(env)+ ? { allowedEmailDomains: [], signupMode: "open" as const }+ : suggestSignupPolicy(email);++ await saveSettings(+ {+ ...settingsUpdate,+ allowedEmailDomains: [...signupPolicy.allowedEmailDomains],+ signupMode: signupPolicy.signupMode,+ supportAddress: stored?.supportAddress ?? email,+ },+ tx,+ );++ return { email, mode: "create" as const, userId };+ }++ if (!sessionUser) {+ throw new SetupError(+ "Sign in with the account that should become the administrator, then open this page again.",+ 401,+ );+ }++ if (!sessionUser.emailVerified) {+ throw new SetupError(+ "Verify your email address before becoming the administrator.",+ 403,+ );+ }++ const promoted = await tx.query(+ `update public."user" set role = 'admin', "updatedAt" = now() where id = $1`,+ [sessionUser.id],+ );++ if (promoted.rowCount !== 1) {+ throw new SetupError("Your account was not found.", 404);+ }++ // An install that already has accounts keeps the sign-up rule it has+ // been running with (open, if it never had one) until the new+ // administrator changes it.+ await saveSettings(+ {+ ...settingsUpdate,+ ...(stored+ ? {}+ : { allowedEmailDomains: [], signupMode: "open" as const }),+ supportAddress: stored?.supportAddress ?? sessionUser.email,+ },+ tx,+ );++ return {+ email: sessionUser.email,+ mode: "claim" as const,+ userId: sessionUser.id,+ };+ }, database);++ invalidateSettingsCache();++ return result;+ } catch (error) {+ // The account is created on its own connection, so it survives a+ // rollback here. Left behind, it would make the install look claimed.+ if (created.userId) {+ await database+ .query(`delete from public."user" where id = $1 and role <> 'admin'`, [+ created.userId,+ ])+ .catch(() => undefined);+ }++ invalidateSettingsCache();++ throw error;+ }+}