Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Give each install its own name, settings and sign-up rule

Claudee6e197c2f9b8
diff --git a/db/migrations/20261112060000_settings_and_roles.sql b/db/migrations/20261112060000_settings_and_roles.sql
new file mode 100644
index 0000000..80839ef
--- /dev/null
+++ b/db/migrations/20261112060000_settings_and_roles.sql
@@ -0,0 +1,42 @@
+-- Install-wide settings and the administrator role.
+--
+-- app_settings holds exactly one row (the boolean primary key can only be
+-- true). It is written by the first-run setup page and by an administrator
+-- in Settings. Until that row exists the app behaves as it did before this
+-- migration: anyone can create an account, and email addresses come from
+-- environment variables.
+
+create table if not exists public.app_settings (
+ id boolean primary key default true check (id),
+ organization_name text,
+ sender_address text,
+ support_address text,
+ signup_mode text not null default 'closed'
+ check (signup_mode in ('closed', 'domains', 'open')),
+ allowed_email_domains text[] not null default '{}',
+ terms_url text,
+ privacy_url text,
+ -- Set once email has been seen working from the current sender address,
+ -- and cleared whenever that address changes.
+ email_ready_at bigint,
+ setup_completed_at bigint,
+ created_at bigint not null,
+ updated_at bigint not null
+);
+
+alter table public."user"
+ add column if not exists role text not null default 'user';
+
+do $$
+begin
+ if not exists (
+ select 1 from pg_constraint where conname = 'user_role_check'
+ ) then
+ alter table public."user"
+ add constraint user_role_check check (role in ('user', 'admin'));
+ end if;
+end
+$$;
+
+create index if not exists user_role_admin_idx
+ on public."user" (role) where role = 'admin';
diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx
index 2c34f1b..41b2f5d 100644
--- a/src/app/(app)/layout.tsx
+++ b/src/app/(app)/layout.tsx
@@ -1,8 +1,19 @@
+import type { Metadata } from "next";
import type { ReactNode } from "react";
import { redirect } from "next/navigation";
import { AppShell } from "@/components/layout/app-shell";
+import { BrandingProvider } from "@/components/layout/branding-provider";
+import { isAdminUser } from "@/lib/auth/admin";
import { getAuthSession } from "@/lib/auth/server";
+import { buildBranding } from "@/lib/branding";
+import { emailNeedsAttention } from "@/lib/email-status";
+import { getInstallMetadata } from "@/lib/install";
+import { getSettings } from "@/lib/settings";
+
+export function generateMetadata(): Promise<Metadata> {
+ return getInstallMetadata();
+}
export default async function AuthenticatedAppLayout({
children,
@@ -15,14 +26,24 @@ export default async function AuthenticatedAppLayout({
redirect("/login");
}
+ const [settings, isAdmin] = await Promise.all([
+ getSettings(),
+ isAdminUser(session.user.id),
+ ]);
+
return (
- <AppShell
- user={{
- email: session.user.email,
- name: session.user.name,
- }}
- >
- {children}
- </AppShell>
+ <BrandingProvider branding={buildBranding(settings)}>
+ <AppShell
+ // Only the administrator can do anything about email, so only the
+ // administrator is told when it still needs setting up.
+ showEmailSetupNotice={isAdmin && emailNeedsAttention(settings)}
+ user={{
+ email: session.user.email,
+ name: session.user.name,
+ }}
+ >
+ {children}
+ </AppShell>
+ </BrandingProvider>
);
}
diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx
index e8d5c51..53e7cca 100644
--- a/src/app/(app)/settings/page.tsx
+++ b/src/app/(app)/settings/page.tsx
@@ -1,15 +1,31 @@
+import { OrganizationSettings } from "@/components/settings/organization-settings";
import { SettingsShell } from "@/components/settings/settings-shell";
+import { isAdminUser } from "@/lib/auth/admin";
import { getAuthSession } from "@/lib/auth/server";
+import { toOrganizationSettingsView } from "@/lib/organization-settings";
+import { readStoredSettings, resolveSettings } from "@/lib/settings";
export default async function SettingsPage() {
const session = await getAuthSession();
+ const isAdmin = session ? await isAdminUser(session.user.id) : false;
return (
- <SettingsShell
- initialProfile={{
- email: session?.user.email ?? "",
- fullName: session?.user.name ?? "",
- }}
- />
+ <div className="space-y-8">
+ <SettingsShell
+ initialProfile={{
+ email: session?.user.email ?? "",
+ fullName: session?.user.name ?? "",
+ }}
+ />
+ {isAdmin ? (
+ <OrganizationSettings
+ // Read fresh, not from the short-lived cache, so the form never
+ // shows a value that was just replaced.
+ initialSettings={toOrganizationSettingsView(
+ resolveSettings(await readStoredSettings()),
+ )}
+ />
+ ) : null}
+ </div>
);
}
diff --git a/src/app/(auth)/layout.tsx b/src/app/(auth)/layout.tsx
index 8d953af..f43bbe3 100644
--- a/src/app/(auth)/layout.tsx
+++ b/src/app/(auth)/layout.tsx
@@ -1,11 +1,29 @@
+import type { Metadata } from "next";
import type { ReactNode } from "react";
+import { connection } from "next/server";
import { AuthShell } from "@/components/layout/auth-shell";
+import { BrandingProvider } from "@/components/layout/branding-provider";
+import { getInstallMetadata, redirectToSetupIfNeeded } from "@/lib/install";
+import { getBranding } from "@/lib/settings";
-export default function UnauthenticatedLayout({
+export async function generateMetadata(): Promise<Metadata> {
+ await connection();
+
+ return getInstallMetadata();
+}
+
+export default async function UnauthenticatedLayout({
children,
}: Readonly<{
children: ReactNode;
}>) {
- return <AuthShell>{children}</AuthShell>;
+ await connection();
+ await redirectToSetupIfNeeded();
+
+ return (
+ <BrandingProvider branding={await getBranding()}>
+ <AuthShell>{children}</AuthShell>
+ </BrandingProvider>
+ );
}
diff --git a/src/app/(auth)/signup/page.tsx b/src/app/(auth)/signup/page.tsx
index e0b9f34..b7b1e65 100644
--- a/src/app/(auth)/signup/page.tsx
+++ b/src/app/(auth)/signup/page.tsx
@@ -1,5 +1,19 @@
import { SignupShell } from "@/components/auth/signup-shell";
+import { buildBranding } from "@/lib/branding";
+import { getSettings } from "@/lib/settings";
+import { describeSignupPolicy } from "@/lib/signup-policy";
-export default function SignupPage() {
- return <SignupShell />;
+export default async function SignupPage() {
+ const settings = await getSettings();
+
+ return (
+ <SignupShell
+ signupAvailable={buildBranding(settings).signupAvailable}
+ // Says who can sign up before anyone fills the form in. Nothing to
+ // say when anyone can.
+ signupRule={
+ settings.signupMode === "open" ? null : describeSignupPolicy(settings)
+ }
+ />
+ );
}
diff --git a/src/app/(canvas)/layout.tsx b/src/app/(canvas)/layout.tsx
index a8b07c4..d4a4f4e 100644
--- a/src/app/(canvas)/layout.tsx
+++ b/src/app/(canvas)/layout.tsx
@@ -1,7 +1,15 @@
+import type { Metadata } from "next";
import type { ReactNode } from "react";
import { redirect } from "next/navigation";
+import { BrandingProvider } from "@/components/layout/branding-provider";
import { getAuthSession } from "@/lib/auth/server";
+import { getInstallMetadata } from "@/lib/install";
+import { getBranding } from "@/lib/settings";
+
+export function generateMetadata(): Promise<Metadata> {
+ return getInstallMetadata();
+}
export default async function CanvasLayout({
children,
@@ -14,5 +22,9 @@ export default async function CanvasLayout({
redirect("/login");
}
- return children;
+ return (
+ <BrandingProvider branding={await getBranding()}>
+ {children}
+ </BrandingProvider>
+ );
}
diff --git a/src/app/accessibility/page.tsx b/src/app/accessibility/page.tsx
index 2b2f9d7..a9443f2 100644
--- a/src/app/accessibility/page.tsx
+++ b/src/app/accessibility/page.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import Link from "next/link";
import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { requireHostedMode } from "@/lib/hosted-pages";
import { resolvePublicSupportAddress } from "@/lib/public-contact";
export const metadata: Metadata = {
@@ -10,8 +11,10 @@ export const metadata: Metadata = {
title: "Accessibility Statement | SignuDoc",
};
-export default function AccessibilityPage() {
- const supportAddress = resolvePublicSupportAddress();
+export default async function AccessibilityPage() {
+ await requireHostedMode();
+
+ const supportAddress = await resolvePublicSupportAddress();
return (
<PublicDocumentShell
diff --git a/src/app/api/admin/email/route.ts b/src/app/api/admin/email/route.ts
new file mode 100644
index 0000000..158c752
--- /dev/null
+++ b/src/app/api/admin/email/route.ts
@@ -0,0 +1,103 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import {
+ addEmailDomain,
+ getEmailStatus,
+ recheckEmailDomain,
+} from "@/lib/email-status";
+import { sendTestEmail } from "@/lib/email-test";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+
+// Email setup for the Organization tab in Settings: whether email works,
+// and the steps an administrator can take from the app when it does not.
+
+const actionSchema = z.object({
+ action: z.enum(["add_domain", "recheck", "send_test"]),
+});
+
+function failure(request: Request, error: unknown, userId: string) {
+ logRouteError(error, {
+ category: "email_setup_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while checking email setup.",
+ path: getRequestPathname(request),
+ userId,
+ });
+
+ return NextResponse.json(
+ { error: "Email setup could not be checked. Please try again." },
+ { status: 500 },
+ );
+}
+
+export async function GET(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ try {
+ return NextResponse.json({ status: await getEmailStatus() });
+ } catch (error) {
+ return failure(request, error, sessionResult.user.id);
+ }
+}
+
+export async function POST(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const rateLimitResponse = applyRateLimit({
+ category: "email_setup_action",
+ key: buildRateLimitKey(["email-setup", session.user.id]),
+ limit: 20,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ const parsed = actionSchema.safeParse(await request.json().catch(() => null));
+
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Unknown action." }, { status: 400 });
+ }
+
+ try {
+ if (parsed.data.action === "send_test") {
+ const result = await sendTestEmail({
+ name: session.user.name,
+ to: session.user.email,
+ });
+
+ return NextResponse.json(
+ { status: await getEmailStatus(), test: result },
+ { status: result.sent ? 200 : 502 },
+ );
+ }
+
+ const status =
+ parsed.data.action === "add_domain"
+ ? await addEmailDomain()
+ : await recheckEmailDomain();
+
+ return NextResponse.json({ status });
+ } catch (error) {
+ return failure(request, error, session.user.id);
+ }
+}
diff --git a/src/app/api/admin/settings/route.ts b/src/app/api/admin/settings/route.ts
new file mode 100644
index 0000000..1140a12
--- /dev/null
+++ b/src/app/api/admin/settings/route.ts
@@ -0,0 +1,75 @@
+import { NextResponse } from "next/server";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import {
+ OrganizationSettingsError,
+ toOrganizationSettingsView,
+ updateOrganizationSettings,
+} from "@/lib/organization-settings";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import {
+ getSettings,
+ readStoredSettings,
+ resolveSettings,
+} from "@/lib/settings";
+
+// The Organization tab in Settings. Administrators only.
+
+export async function PUT(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const rateLimitResponse = applyRateLimit({
+ category: "organization_settings_update",
+ key: buildRateLimitKey(["organization-settings", session.user.id]),
+ limit: 30,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ const body: unknown = await request.json().catch(() => null);
+
+ try {
+ await updateOrganizationSettings(body ?? {}, await getSettings());
+
+ // Read back rather than trusting the cache, so the form shows exactly
+ // what is stored.
+ const saved = resolveSettings(await readStoredSettings());
+
+ return NextResponse.json({ settings: toOrganizationSettingsView(saved) });
+ } catch (error) {
+ if (error instanceof OrganizationSettingsError) {
+ return NextResponse.json(
+ { error: error.message, fieldErrors: error.fieldErrors },
+ { status: 400 },
+ );
+ }
+
+ logRouteError(error, {
+ category: "organization_settings_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while saving organization settings.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The settings could not be saved." },
+ { status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/contact/route.ts b/src/app/api/contact/route.ts
index fdda56e..f3e4bce 100644
--- a/src/app/api/contact/route.ts
+++ b/src/app/api/contact/route.ts
@@ -14,8 +14,15 @@ import {
getRequestPathname,
getRequestUserAgent,
} from "@/lib/security/request";
+import { isHostedMode } from "@/lib/utils/env";
export async function POST(request: Request) {
+ // The public contact form belongs to the hosted service. Other installs
+ // have no such page, so there is nothing for this route to accept.
+ if (!isHostedMode()) {
+ return NextResponse.json({ error: "Not found." }, { status: 404 });
+ }
+
const ipAddress = getClientIpAddress(request.headers);
const userAgent = getRequestUserAgent(request.headers);
const rateLimitResponse = applyRateLimit({
diff --git a/src/app/contact/page.tsx b/src/app/contact/page.tsx
index 8459cb0..80a90b7 100644
--- a/src/app/contact/page.tsx
+++ b/src/app/contact/page.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { ContactForm } from "@/components/contact/contact-form";
import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { requireHostedMode } from "@/lib/hosted-pages";
export const metadata: Metadata = {
description:
@@ -9,7 +10,9 @@ export const metadata: Metadata = {
title: "Contact | SignuDoc",
};
-export default function ContactPage() {
+export default async function ContactPage() {
+ await requireHostedMode();
+
return (
<PublicDocumentShell
description="Use the form below for product support, privacy requests, accessibility accommodations, legal notices, or questions about a document sent through SignuDoc."
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 8818d56..b9eda79 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -1,5 +1,25 @@
+import { redirect } from "next/navigation";
+import { connection } from "next/server";
+
import { LandingShell } from "@/components/landing/landing-shell";
+import { getAuthSession } from "@/lib/auth/server";
+import { redirectToSetupIfNeeded } from "@/lib/install";
+import { isHostedMode } from "@/lib/utils/env";
+
+// The front door. A new install sends its first visitor to setup. After
+// that, the hosted service shows its landing page, and every other install
+// goes straight to the app: the documents for someone who is signed in, the
+// sign-in page for everyone else.
+export default async function Home() {
+ // Decided per request, not when the app was built.
+ await connection();
+ await redirectToSetupIfNeeded();
+
+ if (isHostedMode()) {
+ return <LandingShell />;
+ }
+
+ const session = await getAuthSession();
-export default function Home() {
- return <LandingShell />;
+ redirect(session ? "/dashboard" : "/login");
}
diff --git a/src/app/privacy/page.tsx b/src/app/privacy/page.tsx
index 1a5252f..5705cc0 100644
--- a/src/app/privacy/page.tsx
+++ b/src/app/privacy/page.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import Link from "next/link";
import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { requireHostedMode } from "@/lib/hosted-pages";
import { resolvePublicSupportAddress } from "@/lib/public-contact";
export const metadata: Metadata = {
@@ -10,8 +11,10 @@ export const metadata: Metadata = {
title: "Privacy Policy | SignuDoc",
};
-export default function PrivacyPage() {
- const privacyAddress = resolvePublicSupportAddress();
+export default async function PrivacyPage() {
+ await requireHostedMode();
+
+ const privacyAddress = await resolvePublicSupportAddress();
return (
<PublicDocumentShell
diff --git a/src/app/sign/[token]/layout.tsx b/src/app/sign/[token]/layout.tsx
new file mode 100644
index 0000000..1ac0f8a
--- /dev/null
+++ b/src/app/sign/[token]/layout.tsx
@@ -0,0 +1,28 @@
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+import { connection } from "next/server";
+
+import { BrandingProvider } from "@/components/layout/branding-provider";
+import { getInstallMetadata } from "@/lib/install";
+import { getBranding } from "@/lib/settings";
+
+export async function generateMetadata(): Promise<Metadata> {
+ await connection();
+
+ return getInstallMetadata();
+}
+
+// Signing pages carry the name of the organization that sent the document.
+export default async function SigningLayout({
+ children,
+}: Readonly<{
+ children: ReactNode;
+}>) {
+ await connection();
+
+ return (
+ <BrandingProvider branding={await getBranding()}>
+ {children}
+ </BrandingProvider>
+ );
+}
diff --git a/src/app/terms/page.tsx b/src/app/terms/page.tsx
index 48ef3e6..514697d 100644
--- a/src/app/terms/page.tsx
+++ b/src/app/terms/page.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import Link from "next/link";
import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { requireHostedMode } from "@/lib/hosted-pages";
import { resolvePublicSupportAddress } from "@/lib/public-contact";
export const metadata: Metadata = {
@@ -10,8 +11,10 @@ export const metadata: Metadata = {
title: "Terms of Service | SignuDoc",
};
-export default function TermsPage() {
- const supportAddress = resolvePublicSupportAddress();
+export default async function TermsPage() {
+ await requireHostedMode();
+
+ const supportAddress = await resolvePublicSupportAddress();
return (
<PublicDocumentShell
diff --git a/src/components/auth/login-shell.tsx b/src/components/auth/login-shell.tsx
index bd898d8..ef3d261 100644
--- a/src/components/auth/login-shell.tsx
+++ b/src/components/auth/login-shell.tsx
@@ -4,6 +4,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, type ChangeEvent, type FormEvent } from "react";
+import { useBranding } from "@/components/layout/branding-provider";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
import { authClient } from "@/lib/auth/client";
import { forgotPasswordSchema, loginSchema } from "@/lib/schemas/auth";
@@ -112,6 +113,7 @@ function LiveLoginShell({
resetToken = null,
}: LoginShellProps) {
const router = useRouter();
+ const { signupAvailable } = useBranding();
const [values, setValues] = useState<LoginFormValues>(
createLoginFormValues(),
);
@@ -412,15 +414,17 @@ function LiveLoginShell({
>
Forgot your password?
</button>
- <p>
- Don&apos;t have an account?{" "}
- <Link
- className="font-semibold text-(--fg) transition hover:text-(--accent)"
- href="/signup"
- >
- Sign up
- </Link>
- </p>
+ {signupAvailable ? (
+ <p>
+ Don&apos;t have an account?{" "}
+ <Link
+ className="font-semibold text-(--fg) transition hover:text-(--accent)"
+ href="/signup"
+ >
+ Sign up
+ </Link>
+ </p>
+ ) : null}
</div>
</div>
</section>
diff --git a/src/components/auth/signup-shell.tsx b/src/components/auth/signup-shell.tsx
index 0115bf8..5baafc1 100644
--- a/src/components/auth/signup-shell.tsx
+++ b/src/components/auth/signup-shell.tsx
@@ -15,9 +15,25 @@ import { signUpSchema } from "@/lib/schemas/auth";
const defaultSuccessMessage = "Check your email to verify your sender account.";
type AuthErrorLike = {
+ code?: string;
message?: string;
};
+// Codes the server answers with when this install's sign-up rule turns an
+// address away. The message that comes with them says what the rule is.
+const SIGNUP_RULE_ERROR_CODES = new Set([
+ "setup_required",
+ "signup_closed",
+ "signup_domain_not_allowed",
+]);
+
+type SignupShellProps = {
+ /** False when this install is not taking new accounts at all. */
+ signupAvailable?: boolean;
+ /** One sentence on who can create an account, or null when anyone can. */
+ signupRule?: string | null;
+};
+
type SignupFormValues = {
email: string;
fullName: string;
@@ -60,6 +76,7 @@ type SignupFormCardProps = {
onResendVerification?: () => void | Promise<void>;
onSubmit: (event: FormEvent<HTMLFormElement>) => void | Promise<void>;
showSuccess: boolean;
+ signupRule: string | null;
successMessage: string | null;
values: SignupFormValues;
};
@@ -76,6 +93,7 @@ function SignupFormCard({
onResendVerification,
onSubmit,
showSuccess,
+ signupRule,
successMessage,
values,
}: SignupFormCardProps) {
@@ -87,6 +105,11 @@ function SignupFormCard({
<h1 className="text-[clamp(2.2rem,5vw,3rem)] font-extrabold leading-[1.02] tracking-[-0.045em] text-black">
Create your account
</h1>
+ {signupRule ? (
+ <p className="pt-1 text-sm leading-6 text-muted-foreground">
+ {signupRule}
+ </p>
+ ) : null}
</div>
{bannerMessage ? (
@@ -194,11 +217,41 @@ function SignupFormCard({
);
}
-export function SignupShell() {
- return <LiveSignupShell />;
+export function SignupShell({
+ signupAvailable = true,
+ signupRule = null,
+}: SignupShellProps) {
+ if (!signupAvailable) {
+ return <SignupClosedCard />;
+ }
+
+ return <LiveSignupShell signupRule={signupRule} />;
+}
+
+function SignupClosedCard() {
+ return (
+ <section className="editorial-panel w-full max-w-[460px] p-8 sm:p-10">
+ <div className="space-y-7">
+ <div className="space-y-2">
+ <p className="section-eyebrow">Create account</p>
+ <h1 className="text-[clamp(2.2rem,5vw,3rem)] font-extrabold leading-[1.02] tracking-[-0.045em] text-black">
+ Sign-up is closed
+ </h1>
+ <p className="pt-1 text-sm leading-6 text-muted-foreground">
+ New accounts are not being accepted on this site. If you were sent
+ a document to sign, use the link in that email. You do not need an
+ account.
+ </p>
+ </div>
+ <ShellButton className="w-full" href="/login" variant="primary">
+ Go to log in
+ </ShellButton>
+ </div>
+ </section>
+ );
}
-function LiveSignupShell() {
+function LiveSignupShell({ signupRule }: { signupRule: string | null }) {
const [values, setValues] = useState<SignupFormValues>(
createSignupFormValues(),
);
@@ -321,7 +374,11 @@ function LiveSignupShell() {
if (result.error) {
const normalizedErrorMessage = normalizeAuthErrorMessage(result.error);
- if (
+ if (SIGNUP_RULE_ERROR_CODES.has(result.error.code ?? "")) {
+ setBannerMessage(
+ result.error.message ?? "New accounts are not being accepted.",
+ );
+ } else if (
normalizedErrorMessage.includes("user already exists") ||
normalizedErrorMessage.includes("use another email")
) {
@@ -363,6 +420,7 @@ function LiveSignupShell() {
onResendVerification={handleResendVerification}
onSubmit={handleSubmit}
showSuccess={showSuccess}
+ signupRule={signupRule}
successMessage={successMessage}
values={values}
/>
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index e9a4df7..75b3f4f 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -1,8 +1,8 @@
"use client";
-import Link from "next/link";
import { useEffect, useRef, useState } from "react";
+import { useBranding } from "@/components/layout/branding-provider";
import { ShellButton } from "@/components/shared/form-shell";
import { PageHeader } from "@/components/shared/page-header";
import { StatusPanel } from "@/components/shared/status-panel";
@@ -390,6 +390,7 @@ function SendConfirmationDialog({
title,
}: SendConfirmationDialogProps) {
const [isPermittedUseConfirmed, setIsPermittedUseConfirmed] = useState(false);
+ const { termsUrl } = useBranding();
return (
<Dialog
@@ -436,22 +437,30 @@ function SendConfirmationDialog({
<span className="text-sm leading-6 text-muted-foreground">
By sending, you confirm this document is an ordinary business
agreement and not a will, court order, legally required consumer
- disclosure, or other excluded document type described in the{" "}
- <Link
- className="font-semibold text-(--fg)"
- href="/terms"
- rel="noreferrer"
- style={{
- textDecorationColor: "rgba(17,17,17,0.35)",
- textDecorationLine: "underline",
- textDecorationThickness: "1px",
- textUnderlineOffset: "4px",
- }}
- target="_blank"
- >
- Terms of Service
- </Link>
- .
+ disclosure, or other
+ {termsUrl ? (
+ <>
+ {" "}
+ excluded document type described in the{" "}
+ <a
+ className="font-semibold text-(--fg)"
+ href={termsUrl}
+ rel="noreferrer"
+ style={{
+ textDecorationColor: "rgba(17,17,17,0.35)",
+ textDecorationLine: "underline",
+ textDecorationThickness: "1px",
+ textUnderlineOffset: "4px",
+ }}
+ target="_blank"
+ >
+ Terms of Service
+ </a>
+ .
+ </>
+ ) : (
+ " document that cannot be signed electronically."
+ )}
</span>
</span>
</label>
diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx
index 8afe53c..85808fd 100644
--- a/src/components/layout/app-shell.tsx
+++ b/src/components/layout/app-shell.tsx
@@ -44,6 +44,8 @@ import { authClient } from "@/lib/auth/client";
type AppShellProps = {
children: ReactNode;
+ /** Shown to the administrator until email can reach signers. */
+ showEmailSetupNotice?: boolean;
user: {
email: string;
name: string;
@@ -59,7 +61,11 @@ const sectionLabelMap: Record<ShellSection, string> = {
workspace: "Workspace",
};
-export function AppShell({ children, user }: AppShellProps) {
+export function AppShell({
+ children,
+ showEmailSetupNotice = false,
+ user,
+}: AppShellProps) {
const pathname = usePathname() ?? "/dashboard";
const router = useRouter();
const [isSigningOut, setIsSigningOut] = useState(false);
@@ -213,7 +219,29 @@ export function AppShell({ children, user }: AppShellProps) {
</header>
<main className="flex-1 px-4 py-5 sm:px-6 sm:py-7 lg:px-8 xl:px-10">
- <div className="mx-auto w-full max-w-[1080px]">{children}</div>
+ <div className="mx-auto w-full max-w-[1080px]">
+ {showEmailSetupNotice && currentSection !== "settings" ? (
+ <div
+ className="mb-6 flex flex-col gap-3 border border-[rgba(180,35,53,0.18)] bg-[rgba(180,35,53,0.04)] px-5 py-4 sm:flex-row sm:items-center sm:justify-between"
+ role="status"
+ >
+ <p className="text-sm leading-6 text-(--fg)">
+ <span className="font-semibold">
+ Email is not set up yet.
+ </span>{" "}
+ Until it is, signers and new users will not receive
+ messages from this site.
+ </p>
+ <Link
+ className="shrink-0 text-sm font-semibold text-(--accent) underline underline-offset-4"
+ href="/settings#organization"
+ >
+ Finish email setup
+ </Link>
+ </div>
+ ) : null}
+ {children}
+ </div>
</main>
</SidebarInset>
</SidebarProvider>
diff --git a/src/components/layout/auth-shell.tsx b/src/components/layout/auth-shell.tsx
index 9bb2d39..5d9a4d0 100644
--- a/src/components/layout/auth-shell.tsx
+++ b/src/components/layout/auth-shell.tsx
@@ -5,6 +5,7 @@ import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import { Brand } from "@/components/layout/brand";
+import { useBranding } from "@/components/layout/branding-provider";
import { PublicLegalFooter } from "@/components/layout/public-legal-links";
import { PublicSessionMenu } from "@/components/layout/public-session-menu";
@@ -33,7 +34,10 @@ function getAuthNavAction(pathname: string): AuthNavAction {
export function AuthShell({ children }: AuthShellProps) {
const pathname = usePathname() ?? "/login";
+ const { signupAvailable } = useBranding();
const navAction = getAuthNavAction(pathname);
+ // No "Sign up" link to a page that would only say sign-up is closed.
+ const showNavAction = navAction.href !== "/signup" || signupAvailable;
return (
<div className="flex min-h-screen flex-col bg-white">
@@ -45,13 +49,15 @@ export function AuthShell({ children }: AuthShellProps) {
className="flex items-center gap-3"
>
<PublicSessionMenu>
- <Link
- className="editorial-meta transition-colors hover:text-(--fg)"
- href={navAction.href}
- prefetch
- >
- {navAction.label}
- </Link>
+ {showNavAction ? (
+ <Link
+ className="editorial-meta transition-colors hover:text-(--fg)"
+ href={navAction.href}
+ prefetch
+ >
+ {navAction.label}
+ </Link>
+ ) : null}
</PublicSessionMenu>
</nav>
</div>
diff --git a/src/components/layout/brand.tsx b/src/components/layout/brand.tsx
index a48203f..0044350 100644
--- a/src/components/layout/brand.tsx
+++ b/src/components/layout/brand.tsx
@@ -1,5 +1,10 @@
+"use client";
+
import Link from "next/link";
+import { useBranding } from "@/components/layout/branding-provider";
+import { SIGNUDOC_NAME } from "@/lib/branding";
+
type BrandProps = {
className?: string;
compact?: boolean;
@@ -13,17 +18,25 @@ export function Brand({
href = "/",
labelClassName = "",
}: BrandProps) {
+ const { productName } = useBranding();
+
return (
<Link
- aria-label="SignuDoc"
- className={`inline-flex items-center text-(--fg) ${className}`}
+ aria-label={productName}
+ className={`inline-flex min-w-0 items-center text-(--fg) ${className}`}
href={href}
>
{!compact ? (
<span
- className={`text-[1.28rem] font-extrabold tracking-[-0.035em] sm:text-[1.45rem] ${labelClassName}`}
+ className={`max-w-[60vw] truncate text-[1.28rem] font-extrabold tracking-[-0.035em] sm:max-w-[22rem] sm:text-[1.45rem] ${labelClassName}`}
>
- Signu<span className="text-(--accent)">Doc</span>
+ {productName === SIGNUDOC_NAME ? (
+ <>
+ Signu<span className="text-(--accent)">Doc</span>
+ </>
+ ) : (
+ productName
+ )}
</span>
) : null}
</Link>
diff --git a/src/components/layout/branding-provider.tsx b/src/components/layout/branding-provider.tsx
new file mode 100644
index 0000000..52b915f
--- /dev/null
+++ b/src/components/layout/branding-provider.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { createContext, useContext, type ReactNode } from "react";
+
+import { HOSTED_BRANDING, type Branding } from "@/lib/branding";
+
+// What this install calls itself, handed down from the server layouts that
+// looked it up. A page outside those layouts (the landing page, the legal
+// pages) only exists in hosted mode, which is also the default here.
+const BrandingContext = createContext<Branding>(HOSTED_BRANDING);
+
+type BrandingProviderProps = {
+ branding: Branding;
+ children: ReactNode;
+};
+
+export function BrandingProvider({
+ branding,
+ children,
+}: BrandingProviderProps) {
+ return (
+ <BrandingContext.Provider value={branding}>
+ {children}
+ </BrandingContext.Provider>
+ );
+}
+
+export function useBranding(): Branding {
+ return useContext(BrandingContext);
+}
diff --git a/src/components/layout/public-legal-links.tsx b/src/components/layout/public-legal-links.tsx
index 9e2360e..8228c6e 100644
--- a/src/components/layout/public-legal-links.tsx
+++ b/src/components/layout/public-legal-links.tsx
@@ -1,10 +1,11 @@
+"use client";
+
import Link from "next/link";
import { IBM_Plex_Mono } from "next/font/google";
-import {
- PUBLIC_COPYRIGHT_YEAR,
- publicFooterLinks,
-} from "@/lib/legal";
+import { useBranding } from "@/components/layout/branding-provider";
+import { SIGNUDOC_NAME, SIGNUDOC_URL } from "@/lib/branding";
+import { PUBLIC_COPYRIGHT_YEAR, publicFooterLinks } from "@/lib/legal";
import { cn } from "@/lib/cn";
const ibmPlexMono = IBM_Plex_Mono({
@@ -20,13 +21,51 @@ type PublicLegalFooterProps = {
linkClassName?: string;
};
+type FooterLink = {
+ external: boolean;
+ href: string;
+ label: string;
+};
+
export function PublicLegalFooter({
className = "",
contentClassName = "",
labelVariant = "short",
linkClassName,
}: PublicLegalFooterProps) {
+ const branding = useBranding();
const monoClassName = ibmPlexMono.className;
+ const resolvedLinkClassName =
+ linkClassName ??
+ `${monoClassName} text-xs text-[#71717a] transition-colors hover:text-black`;
+ // The hosted service links to its own pages. Any other install links to
+ // whatever terms and privacy policy its organization has published.
+ const links: FooterLink[] = branding.hosted
+ ? publicFooterLinks.map((link) => ({
+ external: false,
+ href: link.href,
+ label: labelVariant === "long" ? link.longLabel : link.shortLabel,
+ }))
+ : [
+ ...(branding.termsUrl
+ ? [
+ {
+ external: true,
+ href: branding.termsUrl,
+ label: labelVariant === "long" ? "Terms of Service" : "Terms",
+ },
+ ]
+ : []),
+ ...(branding.privacyUrl
+ ? [
+ {
+ external: true,
+ href: branding.privacyUrl,
+ label: labelVariant === "long" ? "Privacy Policy" : "Privacy",
+ },
+ ]
+ : []),
+ ];
return (
<footer
@@ -43,31 +82,53 @@ export function PublicLegalFooter({
>
<div className="flex flex-col items-center justify-between gap-4 sm:flex-row">
<p className={`${monoClassName} text-xs text-[#71717a]`}>
- © {PUBLIC_COPYRIGHT_YEAR} SignuDoc
+ © {PUBLIC_COPYRIGHT_YEAR} {branding.productName}
</p>
- <nav
- aria-label="Footer"
- className="flex flex-wrap items-center justify-center gap-6"
- >
- {publicFooterLinks.map((link) => (
- <Link
- className={
- linkClassName ??
- `${monoClassName} text-xs text-[#71717a] transition-colors hover:text-black`
- }
- href={link.href}
- key={link.href}
- >
- {labelVariant === "long" ? link.longLabel : link.shortLabel}
- </Link>
- ))}
- </nav>
+ {links.length > 0 ? (
+ <nav
+ aria-label="Footer"
+ className="flex flex-wrap items-center justify-center gap-6"
+ >
+ {links.map((link) =>
+ link.external ? (
+ <a
+ className={resolvedLinkClassName}
+ href={link.href}
+ key={link.href}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {link.label}
+ </a>
+ ) : (
+ <Link
+ className={resolvedLinkClassName}
+ href={link.href}
+ key={link.href}
+ >
+ {link.label}
+ </Link>
+ ),
+ )}
+ </nav>
+ ) : null}
- <div className="hidden items-center gap-2 sm:flex">
- <span className="h-[2px] w-8 bg-[#e50000]" />
- <span className="inline-block h-[6px] w-[6px] rounded-full bg-[#e50000]" />
- </div>
+ {branding.hosted ? (
+ <div className="hidden items-center gap-2 sm:flex">
+ <span className="h-[2px] w-8 bg-[#e50000]" />
+ <span className="inline-block h-[6px] w-[6px] rounded-full bg-[#e50000]" />
+ </div>
+ ) : (
+ <a
+ className={`${monoClassName} text-xs text-[#71717a] transition-colors hover:text-black`}
+ href={SIGNUDOC_URL}
+ rel="noreferrer"
+ target="_blank"
+ >
+ Powered by {SIGNUDOC_NAME}
+ </a>
+ )}
</div>
</div>
</footer>
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
new file mode 100644
index 0000000..3b5ceb0
--- /dev/null
+++ b/src/components/settings/organization-settings.tsx
@@ -0,0 +1,658 @@
+"use client";
+
+import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
+
+import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";
+import type {
+ OrganizationSettingsField,
+ OrganizationSettingsView,
+} from "@/lib/organization-settings";
+import type { SignupMode } from "@/lib/signup-policy";
+
+// The administrator's part of Settings: what the install is called, who can
+// sign up, where email comes from, and whether email works yet.
+
+const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";
+const RESEND_DOMAINS_URL = "https://resend.com/domains";
+
+type OrganizationSettingsProps = {
+ initialSettings: OrganizationSettingsView;
+};
+
+type FormErrors = Partial<Record<OrganizationSettingsField, string>>;
+
+type Feedback = {
+ message: string;
+ tone: "error" | "success";
+} | null;
+
+type SettingsResponse = {
+ error?: string;
+ fieldErrors?: FormErrors;
+ settings?: OrganizationSettingsView;
+} | null;
+
+type EmailResponse = {
+ error?: string;
+ status?: EmailStatus;
+ test?: { sent: true; to: string } | { sent: false; message: string };
+} | null;
+
+type EmailAction = "add_domain" | "recheck" | "send_test";
+
+const signupModeOptions: Array<{
+ description: string;
+ label: string;
+ value: SignupMode;
+}> = [
+ {
+ description:
+ "Only people whose email address is at one of your domains can create an account.",
+ label: "People at my organization",
+ value: "domains",
+ },
+ {
+ description: "Nobody new can create an account.",
+ label: "Nobody",
+ value: "closed",
+ },
+ {
+ description: "Anyone who finds this site can create an account.",
+ label: "Anyone",
+ value: "open",
+ },
+];
+
+export function OrganizationSettings({
+ initialSettings,
+}: OrganizationSettingsProps) {
+ const [values, setValues] = useState(initialSettings);
+ const [errors, setErrors] = useState<FormErrors>({});
+ const [feedback, setFeedback] = useState<Feedback>(null);
+ const [isSaving, setIsSaving] = useState(false);
+ // Bumped after a save, so the email panel looks again: a new sender
+ // address means a different domain to check.
+ const [emailRevision, setEmailRevision] = useState(0);
+
+ function handleChange(field: OrganizationSettingsField) {
+ return (event: ChangeEvent<HTMLInputElement>) => {
+ const nextValue = event.target.value;
+
+ setValues((currentValues) => ({ ...currentValues, [field]: nextValue }));
+ setErrors((currentErrors) => ({ ...currentErrors, [field]: undefined }));
+ setFeedback(null);
+ };
+ }
+
+ function handleSignupModeChange(signupMode: SignupMode) {
+ setValues((currentValues) => ({ ...currentValues, signupMode }));
+ setErrors((currentErrors) => ({
+ ...currentErrors,
+ allowedEmailDomains: undefined,
+ signupMode: undefined,
+ }));
+ setFeedback(null);
+ }
+
+ async function handleSubmit(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+
+ if (isSaving) {
+ return;
+ }
+
+ setErrors({});
+ setFeedback(null);
+ setIsSaving(true);
+
+ try {
+ const response = await fetch("/api/admin/settings", {
+ body: JSON.stringify({
+ allowedEmailDomains: values.allowedEmailDomains,
+ organizationName: values.organizationName,
+ privacyUrl: values.privacyUrl,
+ senderAddress: values.senderAddress,
+ signupMode: values.signupMode,
+ supportAddress: values.supportAddress,
+ termsUrl: values.termsUrl,
+ }),
+ headers: { "content-type": "application/json" },
+ method: "PUT",
+ });
+ const payload = (await response
+ .json()
+ .catch(() => null)) as SettingsResponse;
+
+ if (!response.ok || !payload?.settings) {
+ setErrors(payload?.fieldErrors ?? {});
+ setFeedback({
+ message: payload?.error ?? GENERIC_ERROR_MESSAGE,
+ tone: "error",
+ });
+ return;
+ }
+
+ setValues(payload.settings);
+ setEmailRevision((revision) => revision + 1);
+ setFeedback({ message: "Organization settings saved.", tone: "success" });
+ } catch {
+ setFeedback({ message: GENERIC_ERROR_MESSAGE, tone: "error" });
+ } finally {
+ setIsSaving(false);
+ }
+ }
+
+ return (
+ <section
+ className="editorial-panel scroll-mt-6 p-6 sm:p-8"
+ data-animate="enter"
+ data-animate-delay="2"
+ id="organization"
+ >
+ <div className="space-y-8">
+ <div className="space-y-2">
+ <p className="section-eyebrow">Administrator</p>
+ <h2 className="text-2xl font-bold tracking-[-0.035em] text-(--fg)">
+ Organization
+ </h2>
+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">
+ These settings apply to everyone who uses this site. Only you, the
+ administrator, can see and change them.
+ </p>
+ </div>
+
+ {feedback ? (
+ <p
+ className={`border px-5 py-4 text-sm font-semibold ${
+ feedback.tone === "success"
+ ? "border-[rgba(5,150,105,0.18)] bg-[rgba(5,150,105,0.05)] text-chart-4"
+ : "border-[rgba(180,35,53,0.18)] bg-[rgba(180,35,53,0.04)] text-(--accent)"
+ }`}
+ role={feedback.tone === "error" ? "alert" : "status"}
+ >
+ {feedback.message}
+ </p>
+ ) : null}
+
+ <form className="space-y-8" noValidate onSubmit={handleSubmit}>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <FieldShell
+ disabled={isSaving}
+ error={errors.organizationName}
+ helper="Shown in the header and in every email this site sends."
+ label="Organization name"
+ name="organization-name"
+ onChange={handleChange("organizationName")}
+ readOnly={false}
+ value={values.organizationName}
+ />
+ </div>
+
+ <fieldset className="space-y-4 border-t border-(--border) pt-8">
+ <legend className="float-left mb-4 w-full text-xl font-bold tracking-[-0.03em] text-(--fg)">
+ Who can create an account
+ </legend>
+ <p className="clear-both max-w-2xl text-sm leading-6 text-muted-foreground">
+ This is about people who send documents. People who are sent a
+ document to sign never need an account.
+ </p>
+ <div className="space-y-3">
+ {signupModeOptions.map((option) => (
+ <label
+ className="flex cursor-pointer items-start gap-3 border border-(--border) bg-white px-4 py-3 has-[:checked]:border-black"
+ key={option.value}
+ >
+ <input
+ checked={values.signupMode === option.value}
+ className="mt-1 accent-black"
+ disabled={isSaving}
+ name="signup-mode"
+ onChange={() => handleSignupModeChange(option.value)}
+ type="radio"
+ value={option.value}
+ />
+ <span className="space-y-1">
+ <span className="block text-sm font-semibold text-(--fg)">
+ {option.label}
+ </span>
+ <span className="block text-sm leading-6 text-muted-foreground">
+ {option.description}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ {values.signupMode === "domains" ? (
+ <div className="max-w-xl">
+ <FieldShell
+ disabled={isSaving}
+ error={errors.allowedEmailDomains}
+ helper="Separate several domains with commas."
+ label="Email domains"
+ name="allowed-email-domains"
+ onChange={handleChange("allowedEmailDomains")}
+ placeholder="yourcompany.com"
+ readOnly={false}
+ value={values.allowedEmailDomains}
+ />
+ </div>
+ ) : null}
+ </fieldset>
+
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <h3 className="text-xl font-bold tracking-[-0.03em] text-(--fg)">
+ Email addresses
+ </h3>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <FieldShell
+ disabled={isSaving || values.senderAddressFromEnv}
+ error={errors.senderAddress}
+ helper={
+ values.senderAddressFromEnv
+ ? "Set by the RESEND_FROM_EMAIL environment variable."
+ : "The address emails come from. Use one at a domain you own."
+ }
+ label="Send email from"
+ name="sender-address"
+ onChange={handleChange("senderAddress")}
+ placeholder="[email protected]"
+ readOnly={values.senderAddressFromEnv}
+ type="email"
+ value={values.senderAddress}
+ />
+ <FieldShell
+ disabled={isSaving || values.supportAddressFromEnv}
+ error={errors.supportAddress}
+ helper={
+ values.supportAddressFromEnv
+ ? "Set by the SUPPORT_EMAIL environment variable."
+ : "Where replies and questions from signers go."
+ }
+ label="Support address"
+ name="support-address"
+ onChange={handleChange("supportAddress")}
+ placeholder="[email protected]"
+ readOnly={values.supportAddressFromEnv}
+ type="email"
+ value={values.supportAddress}
+ />
+ </div>
+ </div>
+
+ {!values.hosted ? (
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-xl font-bold tracking-[-0.03em] text-(--fg)">
+ Your terms and privacy policy
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">
+ Optional. Links to pages on your own website, shown in the
+ footer of this site and of its emails.
+ </p>
+ </div>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <FieldShell
+ disabled={isSaving}
+ error={errors.termsUrl}
+ label="Terms link"
+ name="terms-url"
+ onChange={handleChange("termsUrl")}
+ placeholder="https://yourcompany.com/terms"
+ readOnly={false}
+ value={values.termsUrl}
+ />
+ <FieldShell
+ disabled={isSaving}
+ error={errors.privacyUrl}
+ label="Privacy policy link"
+ name="privacy-url"
+ onChange={handleChange("privacyUrl")}
+ placeholder="https://yourcompany.com/privacy"
+ readOnly={false}
+ value={values.privacyUrl}
+ />
+ </div>
+ </div>
+ ) : null}
+
+ <ShellButton className="w-fit" loading={isSaving} type="submit">
+ {isSaving ? "Saving..." : "Save organization settings"}
+ </ShellButton>
+ </form>
+
+ <EmailSetupPanel key={emailRevision} />
+ </div>
+ </section>
+ );
+}
+
+async function fetchEmailStatus(
+ signal: AbortSignal,
+): Promise<{ error: string; status: null } | { status: EmailStatus }> {
+ const response = await fetch("/api/admin/email", { signal });
+ const payload = (await response.json().catch(() => null)) as EmailResponse;
+
+ if (!response.ok || !payload?.status) {
+ return { error: payload?.error ?? GENERIC_ERROR_MESSAGE, status: null };
+ }
+
+ return { status: payload.status };
+}
+
+function EmailSetupPanel() {
+ const [status, setStatus] = useState<EmailStatus | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [pendingAction, setPendingAction] = useState<EmailAction | null>(null);
+ const [testResult, setTestResult] = useState<Feedback>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+
+ fetchEmailStatus(controller.signal)
+ .then((result) => {
+ if (result.status) {
+ setLoadError(null);
+ setStatus(result.status);
+ } else {
+ setLoadError(result.error);
+ }
+ })
+ .catch((error: unknown) => {
+ // Leaving the page cancels the request; that is not a failure.
+ if (!(error instanceof DOMException && error.name === "AbortError")) {
+ setLoadError(GENERIC_ERROR_MESSAGE);
+ }
+ });
+
+ return () => controller.abort();
+ }, []);
+
+ async function runAction(action: EmailAction) {
+ if (pendingAction) {
+ return;
+ }
+
+ setPendingAction(action);
+ setTestResult(null);
+
+ try {
+ const response = await fetch("/api/admin/email", {
+ body: JSON.stringify({ action }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response
+ .json()
+ .catch(() => null)) as EmailResponse;
+
+ if (payload?.status) {
+ setLoadError(null);
+ setStatus(payload.status);
+ }
+
+ if (payload?.test) {
+ setTestResult(
+ payload.test.sent
+ ? {
+ message: `Test email sent to ${payload.test.to}. Check that inbox.`,
+ tone: "success",
+ }
+ : { message: payload.test.message, tone: "error" },
+ );
+ } else if (!response.ok) {
+ setLoadError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ }
+ } catch {
+ setLoadError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setPendingAction(null);
+ }
+ }
+
+ const summary = status ? describeEmailStatus(status) : null;
+ const canSendTest =
+ status !== null &&
+ status.state !== "missing_key" &&
+ status.state !== "capture";
+
+ return (
+ <div className="space-y-5 border-t border-(--border) pt-8" id="email-setup">
+ <h3 className="text-xl font-bold tracking-[-0.03em] text-(--fg)">
+ Email setup
+ </h3>
+
+ {loadError ? (
+ <p
+ className="border border-[rgba(180,35,53,0.18)] bg-[rgba(180,35,53,0.04)] px-5 py-4 text-sm font-semibold text-(--accent)"
+ role="alert"
+ >
+ {loadError}
+ </p>
+ ) : null}
+
+ {!summary ? (
+ loadError ? null : (
+ <p className="text-sm text-muted-foreground">Checking email…</p>
+ )
+ ) : (
+ <div
+ className={`space-y-3 border px-5 py-4 ${
+ summary.ready
+ ? "border-[rgba(5,150,105,0.18)] bg-[rgba(5,150,105,0.05)]"
+ : "border-(--border) bg-(--surface)"
+ }`}
+ data-email-state={status?.state}
+ >
+ <p className="text-sm font-semibold text-(--fg)">{summary.title}</p>
+ {summary.lines.map((line) => (
+ <p className="text-sm leading-6 text-muted-foreground" key={line}>
+ {line}
+ </p>
+ ))}
+ </div>
+ )}
+
+ {status?.state === "domain_pending" ? (
+ <DnsRecordsTable domain={status.domain} records={status.records} />
+ ) : null}
+
+ <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
+ {status?.state === "domain_missing" ? (
+ <ShellButton
+ disabled={pendingAction !== null}
+ loading={pendingAction === "add_domain"}
+ onClick={() => void runAction("add_domain")}
+ >
+ {pendingAction === "add_domain"
+ ? "Adding..."
+ : `Set up ${status.domain}`}
+ </ShellButton>
+ ) : null}
+ {status?.state === "domain_pending" ? (
+ <ShellButton
+ disabled={pendingAction !== null}
+ loading={pendingAction === "recheck"}
+ onClick={() => void runAction("recheck")}
+ >
+ {pendingAction === "recheck" ? "Checking..." : "Check DNS records"}
+ </ShellButton>
+ ) : null}
+ {canSendTest ? (
+ <ShellButton
+ disabled={pendingAction !== null}
+ loading={pendingAction === "send_test"}
+ onClick={() => void runAction("send_test")}
+ variant="secondary"
+ >
+ {pendingAction === "send_test"
+ ? "Sending..."
+ : "Send me a test email"}
+ </ShellButton>
+ ) : null}
+ {status?.state === "restricted_key" ||
+ status?.state === "error" ||
+ status?.state === "test_sender" ? (
+ <ShellButton href={RESEND_DOMAINS_URL} variant="ghost">
+ Open Resend
+ </ShellButton>
+ ) : null}
+ </div>
+
+ {testResult ? (
+ <p
+ className={`border px-5 py-4 text-sm font-semibold ${
+ testResult.tone === "success"
+ ? "border-[rgba(5,150,105,0.18)] bg-[rgba(5,150,105,0.05)] text-chart-4"
+ : "border-[rgba(180,35,53,0.18)] bg-[rgba(180,35,53,0.04)] text-(--accent)"
+ }`}
+ role={testResult.tone === "error" ? "alert" : "status"}
+ >
+ {testResult.message}
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+function describeEmailStatus(status: EmailStatus): {
+ lines: string[];
+ ready: boolean;
+ title: string;
+} {
+ switch (status.state) {
+ case "capture":
+ return {
+ lines: [
+ "This is a development setup. Emails are saved to a folder on this machine instead of being sent.",
+ ],
+ ready: true,
+ title: "Emails are being captured, not sent",
+ };
+ case "missing_key":
+ return {
+ lines: [
+ "This site has no email provider connected, so it cannot send anything: no sign-up confirmations and no signing invitations.",
+ "Connect Resend to the project (on Vercel, from the project's Integrations tab), or set the RESEND_API_KEY environment variable, then deploy again.",
+ ],
+ ready: false,
+ title: "Email is not connected",
+ };
+ case "test_sender":
+ return {
+ lines: [
+ `Emails are going out from Resend's shared test address (${status.senderAddress}). Resend only delivers those to the owner of the Resend account, so signers and new users will not receive anything yet.`,
+ 'Enter an address at your own domain in "Send email from" above and save. The DNS records to add will appear here.',
+ ],
+ ready: false,
+ title: "Email only reaches you so far",
+ };
+ case "domain_missing":
+ return {
+ lines: [
+ `${status.domain} has not been added to your Resend account yet. Set it up here to get the DNS records that prove you own it.`,
+ ],
+ ready: false,
+ title: `${status.domain} needs to be set up`,
+ };
+ case "domain_pending":
+ return {
+ lines: [
+ `Add these records where ${status.domain}'s DNS is managed, then check them. DNS changes can take a few minutes to be seen, and sometimes longer.`,
+ ],
+ ready: false,
+ title: `Waiting for ${status.domain}'s DNS records`,
+ };
+ case "restricted_key":
+ return {
+ lines: [
+ `This site's Resend key is only allowed to send email, so it cannot check ${status.domain} from here. Open Resend to add the domain and see its DNS records.`,
+ "When that is done, send yourself a test email. If it arrives, email is working.",
+ ],
+ ready: false,
+ title: "Finish the domain in Resend",
+ };
+ case "ready":
+ return {
+ lines: [
+ `Emails are sent from ${status.senderAddress}, and ${status.domain} is verified.`,
+ ],
+ ready: true,
+ title: "Email is working",
+ };
+ case "error":
+ return {
+ lines: [
+ `Resend could not be asked about this site's email: ${status.message}`,
+ ],
+ ready: false,
+ title: "Email could not be checked",
+ };
+ }
+}
+
+function DnsRecordsTable({
+ domain,
+ records,
+}: {
+ domain: string;
+ records: readonly EmailDnsRecord[];
+}) {
+ if (records.length === 0) {
+ return (
+ <p className="text-sm leading-6 text-muted-foreground">
+ Resend did not list any records for {domain}. Open Resend to see them.
+ </p>
+ );
+ }
+
+ return (
+ <div className="overflow-x-auto border border-(--border)">
+ <table className="w-full min-w-[640px] border-collapse text-left text-sm">
+ <caption className="sr-only">DNS records to add for {domain}</caption>
+ <thead>
+ <tr className="border-b border-(--border) bg-(--surface) text-xs uppercase tracking-[0.14em] text-(--tertiary)">
+ <th className="px-4 py-3 font-semibold" scope="col">
+ Type
+ </th>
+ <th className="px-4 py-3 font-semibold" scope="col">
+ Name
+ </th>
+ <th className="px-4 py-3 font-semibold" scope="col">
+ Value
+ </th>
+ <th className="px-4 py-3 font-semibold" scope="col">
+ Status
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {records.map((record) => (
+ <tr
+ className="border-b border-(--border) align-top last:border-b-0"
+ key={`${record.type}-${record.name}-${record.value}`}
+ >
+ <td className="px-4 py-3 font-semibold text-(--fg)">
+ {record.type}
+ {record.priority !== null ? (
+ <span className="block text-xs font-normal text-(--tertiary)">
+ Priority {record.priority}
+ </span>
+ ) : null}
+ </td>
+ <td className="px-4 py-3 [font-family:var(--font-mono)] text-[0.8rem] break-all text-(--fg)">
+ {record.name}
+ </td>
+ <td className="px-4 py-3 [font-family:var(--font-mono)] text-[0.8rem] break-all text-(--fg)">
+ {record.value}
+ </td>
+ <td className="px-4 py-3 text-muted-foreground">
+ {record.status === "verified" ? "Found" : "Not found yet"}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsx
index 4ee1065..401c139 100644
--- a/src/components/settings/settings-shell.tsx
+++ b/src/components/settings/settings-shell.tsx
@@ -2,6 +2,7 @@
import { useState, type ChangeEvent, type FormEvent } from "react";
+import { useBranding } from "@/components/layout/branding-provider";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
import { PageHeader } from "@/components/shared/page-header";
import {
@@ -160,6 +161,7 @@ function isNoOpEmailChangeMessage(message: string) {
export function SettingsShell({
initialProfile = defaultProfileValues,
}: SettingsShellProps) {
+ const { productName } = useBranding();
const [profileValues, setProfileValues] = useState(initialProfile);
const [savedProfileValues, setSavedProfileValues] = useState(initialProfile);
const [profileErrors, setProfileErrors] = useState<ProfileErrors>({});
@@ -664,7 +666,7 @@ export function SettingsShell({
<SectionHeading title="Danger zone" />
<p className="max-w-2xl text-sm leading-6 text-muted-foreground">
Before closing your account, download any documents you want to
- keep. After closure, SignuDoc may provide a 30-day export window
+ keep. After closure, {productName} may provide a 30-day export window
and then delete stored document files and related envelope
records.
</p>
@@ -740,6 +742,8 @@ function AccountClosureDialog({
onChange,
onConfirm,
}: AccountClosureDialogProps) {
+ const { productName } = useBranding();
+
return (
<Dialog
open
@@ -760,7 +764,7 @@ function AccountClosureDialog({
</DialogTitle>
<DialogDescription className="text-sm leading-6 text-muted-foreground">
Before closing your account, download any documents you want to
- keep. After closure, SignuDoc may provide a 30-day export window
+ keep. After closure, {productName} may provide a 30-day export window
and then delete stored document files and related envelope
records.
</DialogDescription>
diff --git a/src/lib/account.ts b/src/lib/account.ts
index 6f244f9..10107fd 100644
--- a/src/lib/account.ts
+++ b/src/lib/account.ts
@@ -17,9 +17,10 @@ import {
ACCOUNT_CLOSURE_EXPORT_WINDOW_DAYS,
scheduleAccountClosure,
} from "./retention.ts";
+import { resolvePublicSupportAddress } from "./public-contact.ts";
import { createEmailService } from "./services/email.ts";
-import { ServiceConfigurationError } from "./services/service-config.ts";
-import { getEnv, type EnvSource } from "./utils/env.ts";
+import { getBranding } from "./settings.ts";
+import { type EnvSource } from "./utils/env.ts";
type SenderAccountRow = {
email: string;
@@ -215,15 +216,6 @@ async function formatEnvelopeCounts(
);
}
-function resolveSupportAddress(env: EnvSource): string {
- const supportAddress = getEnv(env).email.supportAddress;
-
- if (supportAddress) {
- return supportAddress;
- }
-
- throw new ServiceConfigurationError("email", ["SUPPORT_EMAIL"]);
-}
function formatRetentionDeadline(timestamp: number): string {
return new Date(timestamp * 1000).toISOString().replace(".000Z", " UTC");
@@ -253,13 +245,15 @@ export async function requestAccountClosure(
try {
const emailService = createEmailService({ env });
+ const supportAddress = await resolvePublicSupportAddress(env);
+ const { productName } = await getBranding(env);
await emailService.send({
replyTo: account.email,
subject: `Account closure request — ${account.name}`,
template: "account_closure_request",
textBody: [
- "A sender requested account closure from the SignuDoc settings page.",
+ `A sender requested account closure from the ${productName} settings page.`,
"",
`Sender: ${account.name} <${account.email}>`,
`User ID: ${userId}`,
@@ -273,7 +267,7 @@ export async function requestAccountClosure(
"",
"This request came through the guarded in-app danger-zone flow.",
].join("\n"),
- to: resolveSupportAddress(env),
+ to: supportAddress,
});
} catch (error) {
console.error(
diff --git a/src/lib/auth/admin.ts b/src/lib/auth/admin.ts
new file mode 100644
index 0000000..6471aa7
--- /dev/null
+++ b/src/lib/auth/admin.ts
@@ -0,0 +1,49 @@
+import { NextResponse } from "next/server";
+
+import { getDb, queryOne, type DbExecutor } from "../db/connection.ts";
+import { isMissingSchemaError } from "../settings.ts";
+import { requireVerifiedSenderSession } from "./route-session.ts";
+
+/**
+ * Whether this user is the install's administrator. Asked of the database
+ * every time rather than read from the session, which is cached in a cookie
+ * for a few minutes and could be out of date.
+ */
+export async function isAdminUser(
+ userId: string,
+ database: DbExecutor = getDb(),
+): Promise<boolean> {
+ try {
+ const row = await queryOne<{ role: string }>(
+ database,
+ `select role from public."user" where id = $1`,
+ [userId],
+ );
+
+ return row?.role === "admin";
+ } catch (error) {
+ if (isMissingSchemaError(error)) {
+ return false;
+ }
+
+ throw error;
+ }
+}
+
+/** For API routes only an administrator may call. */
+export async function requireAdminSession(request: Request) {
+ const sessionResult = await requireVerifiedSenderSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ if (!(await isAdminUser(sessionResult.user.id))) {
+ return NextResponse.json(
+ { error: "Only an administrator can do this." },
+ { status: 403 },
+ );
+ }
+
+ return sessionResult;
+}
diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.ts
index c8b3a4e..2f75d0c 100644
--- a/src/lib/auth/server.ts
+++ b/src/lib/auth/server.ts
@@ -1,10 +1,13 @@
-import { betterAuth } from "better-auth";
+import { APIError, betterAuth } from "better-auth";
+import { createAuthMiddleware } from "better-auth/api";
import { nextCookies } from "better-auth/next-js";
import { haveIBeenPwned } from "better-auth/plugins";
import { headers } from "next/headers";
+import { after } from "next/server";
import type { Pool } from "pg";
import { cache } from "react";
+import { type Branding } from "../branding.ts";
import { getDb } from "../db/connection.ts";
import {
createEmailService,
@@ -13,11 +16,15 @@ import {
} from "../services/email.ts";
import { withUserEmailLegalFooter } from "../services/email-legal-footer.ts";
import { requireConfigValue } from "../services/service-config.ts";
+import { getBranding, getSettings, getSetupState } from "../settings.ts";
+import { evaluateSignup } from "../signup-policy.ts";
import {
getEnv,
resolveDeploymentOrigins,
type EnvSource,
} from "../utils/env.ts";
+import { escapeHtml } from "../utils/html.ts";
+import { isRunningSetup } from "./setup-context.ts";
type CreateAppAuthOptions = {
database?: Pool;
@@ -67,81 +74,177 @@ function addTrustedOrigin(
}
}
-function buildEmailVerificationMessage(input: { name: string; url: string }) {
+function buildEmailVerificationMessage(input: {
+ branding: Branding;
+ name: string;
+ url: string;
+}) {
+ const { productName } = input.branding;
const textBody = [
`Hi ${input.name},`,
"",
- "Verify your email address to finish setting up your SignuDoc sender account:",
+ `Verify your email address to finish setting up your ${productName} sender account:`,
input.url,
"",
"If you didn't request this, you can ignore this email.",
].join("\n");
const htmlBody = [
- `<p>Hi ${input.name},</p>`,
- "<p>Verify your email address to finish setting up your SignuDoc sender account.</p>",
- `<p><a href="${input.url}">Verify your email</a></p>`,
+ `<p>Hi ${escapeHtml(input.name)},</p>`,
+ `<p>Verify your email address to finish setting up your ${escapeHtml(productName)} sender account.</p>`,
+ `<p><a href="${escapeHtml(input.url)}">Verify your email</a></p>`,
"<p>If you didn't request this, you can ignore this email.</p>",
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
- subject: "Verify your SignuDoc email",
+ subject: `Verify your ${productName} email`,
template: "email_verification" as const,
textBody: legalFooter.textBody,
};
}
function buildChangeEmailConfirmationMessage(input: {
+ branding: Branding;
name: string;
newEmail: string;
url: string;
}) {
+ const { productName } = input.branding;
const textBody = [
`Hi ${input.name},`,
"",
- `Confirm that you want to change your SignuDoc sender email to ${input.newEmail}:`,
+ `Confirm that you want to change your ${productName} sender email to ${input.newEmail}:`,
input.url,
"",
"If you didn't request this, you can ignore this email.",
].join("\n");
const htmlBody = [
- `<p>Hi ${input.name},</p>`,
- `<p>Confirm that you want to change your SignuDoc sender email to ${input.newEmail}.</p>`,
- `<p><a href="${input.url}">Confirm this email change</a></p>`,
+ `<p>Hi ${escapeHtml(input.name)},</p>`,
+ `<p>Confirm that you want to change your ${escapeHtml(productName)} sender email to ${escapeHtml(input.newEmail)}.</p>`,
+ `<p><a href="${escapeHtml(input.url)}">Confirm this email change</a></p>`,
"<p>If you didn't request this, you can ignore this email.</p>",
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
- subject: "Confirm your SignuDoc email change",
+ subject: `Confirm your ${productName} email change`,
template: "change_email_confirmation" as const,
textBody: legalFooter.textBody,
};
}
-// The email service is created when a message is sent, not when auth is set
-// up. Email that is not configured yet then fails that one message (and is
-// logged) instead of taking sign-in down with it.
-function sendAuthEmailInBackground(
- getEmailService: () => EmailService,
- message: TransactionalEmailMessage,
-) {
- void Promise.resolve()
- .then(() => getEmailService().send(message))
- .catch((error: unknown) => {
+function buildPasswordResetMessage(input: {
+ branding: Branding;
+ name: string;
+ url: string;
+}) {
+ const { productName } = input.branding;
+ const textBody = [
+ `Hi ${input.name},`,
+ "",
+ `Use the link below to reset your ${productName} password:`,
+ input.url,
+ "",
+ "If you didn't request this reset, you can ignore this email.",
+ ].join("\n");
+ const htmlBody = [
+ `<p>Hi ${escapeHtml(input.name)},</p>`,
+ `<p>Use the link below to reset your ${escapeHtml(productName)} password.</p>`,
+ `<p><a href="${escapeHtml(input.url)}">Reset your password</a></p>`,
+ "<p>If you didn't request this reset, you can ignore this email.</p>",
+ ].join("");
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
+
+ return {
+ htmlBody: legalFooter.htmlBody,
+ subject: `Reset your ${productName} password`,
+ template: "password_reset" as const,
+ textBody: legalFooter.textBody,
+ };
+}
+
+type AuthEmailContent = Omit<TransactionalEmailMessage, "to">;
+
+// Auth emails are sent after the response, so sign-in is never slowed down
+// by the mail provider, and a message that cannot be sent (email that is not
+// configured yet, for one) is logged instead of failing the request.
+//
+// after() keeps a Vercel function alive until the message has gone out. A
+// promise that nothing waits for could be cut off when the function is
+// suspended at the end of the response.
+// https://nextjs.org/docs/app/api-reference/functions/after
+function sendAuthEmailInBackground(input: {
+ buildContent: (branding: Branding) => AuthEmailContent;
+ env: EnvSource;
+ getEmailService: () => EmailService;
+ template: TransactionalEmailMessage["template"];
+ to: string;
+}) {
+ const deliver = async () => {
+ try {
+ const branding = await getBranding(input.env);
+
+ await input.getEmailService().send({
+ ...input.buildContent(branding),
+ to: input.to,
+ });
+ } catch (error) {
console.error(
- `Failed to send auth email "${message.template}" to ${message.to}:`,
+ `Failed to send auth email "${input.template}" to ${input.to}:`,
error,
);
- });
+ }
+ };
+
+ try {
+ after(deliver);
+ } catch {
+ // Not inside a request (a script or the auth CLI), so there is no
+ // response to wait for.
+ void deliver();
+ }
+}
+
+/**
+ * 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
@@ -216,11 +319,22 @@ export function createAppAuth({
sendOnSignIn: true,
sendOnSignUp: true,
sendVerificationEmail: async ({ url, user }) => {
- sendAuthEmailInBackground(emailService, {
- ...buildEmailVerificationMessage({
- name: user.name,
- url,
- }),
+ // The administrator created by first-run setup is verified by
+ // setup itself; there is no working email to send through yet.
+ if (isRunningSetup()) {
+ return;
+ }
+
+ sendAuthEmailInBackground({
+ buildContent: (branding) =>
+ buildEmailVerificationMessage({
+ branding,
+ name: user.name,
+ url,
+ }),
+ env,
+ getEmailService: emailService,
+ template: "email_verification",
to: user.email,
});
},
@@ -232,34 +346,51 @@ export function createAppAuth({
requireEmailVerification: true,
revokeSessionsOnPasswordReset: true,
sendResetPassword: async ({ url, user }) => {
- const textBody = [
- `Hi ${user.name},`,
- "",
- "Use the link below to reset your SignuDoc password:",
- url,
- "",
- "If you didn't request this reset, you can ignore this email.",
- ].join("\n");
- const htmlBody = [
- `<p>Hi ${user.name},</p>`,
- "<p>Use the link below to reset your SignuDoc password.</p>",
- `<p><a href="${url}">Reset your password</a></p>`,
- "<p>If you didn't request this reset, you can ignore this email.</p>",
- ].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
-
- sendAuthEmailInBackground(emailService, {
- htmlBody: legalFooter.htmlBody,
- subject: "Reset your SignuDoc password",
+ sendAuthEmailInBackground({
+ buildContent: (branding) =>
+ buildPasswordResetMessage({
+ branding,
+ name: user.name,
+ url,
+ }),
+ env,
+ getEmailService: emailService,
template: "password_reset",
- textBody: legalFooter.textBody,
to: user.email,
});
},
},
+ hooks: {
+ // The sign-up rule, asked before anything else so the person filling
+ // in the form is told. The same rule is enforced again in
+ // validateUserInfo below, but a refusal there is answered as if the
+ // sign-up had worked: Better Auth cannot let it look different from
+ // "this address already has an account". The rule is about the
+ // address's domain and is printed on the sign-up page, so saying it
+ // here gives nothing away.
+ before: createAuthMiddleware(async (ctx) => {
+ if (ctx.path !== "/sign-up/email" || isRunningSetup()) {
+ return;
+ }
+
+ const body: unknown = ctx.body;
+ const email =
+ typeof body === "object" &&
+ body !== null &&
+ "email" in body &&
+ typeof body.email === "string"
+ ? body.email
+ : "";
+ const decision = await evaluateSignupRequest(email, env);
+
+ if (!decision.allowed) {
+ throw new APIError("FORBIDDEN", {
+ code: decision.code,
+ message: decision.message,
+ });
+ }
+ }),
+ },
session: {
cookieCache: {
enabled: true,
@@ -273,17 +404,42 @@ export function createAppAuth({
changeEmail: {
enabled: true,
sendChangeEmailConfirmation: async ({ newEmail, url, user }) => {
- sendAuthEmailInBackground(emailService, {
- ...buildChangeEmailConfirmationMessage({
- name: user.name,
- newEmail,
- url,
- }),
+ sendAuthEmailInBackground({
+ buildContent: (branding) =>
+ buildChangeEmailConfirmationMessage({
+ branding,
+ name: user.name,
+ newEmail,
+ url,
+ }),
+ env,
+ getEmailService: emailService,
+ template: "change_email_confirmation",
to: user.email,
});
},
updateEmailWithoutVerification: false,
},
+ // Decides who may create an account. Runs for every new user, however
+ // the account comes to be created, so the check in hooks.before above
+ // is not the only thing standing in the way.
+ validateUserInfo: async ({ source, user }) => {
+ if (source.action !== "create-user" || isRunningSetup()) {
+ return;
+ }
+
+ const decision = await evaluateSignupRequest(
+ typeof user.email === "string" ? user.email : "",
+ env,
+ );
+
+ if (!decision.allowed) {
+ return {
+ error: decision.code,
+ errorDescription: decision.message,
+ };
+ }
+ },
},
});
}
diff --git a/src/lib/auth/setup-context.ts b/src/lib/auth/setup-context.ts
new file mode 100644
index 0000000..ea5c390
--- /dev/null
+++ b/src/lib/auth/setup-context.ts
@@ -0,0 +1,23 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+
+declare global {
+ var __signudocSetupStorage: AsyncLocalStorage<true> | undefined;
+}
+
+// First-run setup creates the administrator through the same sign-up code as
+// everyone else. While it does, two rules have to stand aside: the sign-up
+// rule (there is no administrator yet to have chosen one) and the
+// verification email (email cannot work before setup has finished).
+//
+// Kept on globalThis so the setup route and the auth code read the same
+// store even if a bundler gives each its own copy of this module.
+const setupStorage = (globalThis.__signudocSetupStorage ??=
+ new AsyncLocalStorage<true>());
+
+export function runAsSetup<T>(run: () => Promise<T>): Promise<T> {
+ return setupStorage.run(true, run);
+}
+
+export function isRunningSetup(): boolean {
+ return setupStorage.getStore() === true;
+}
diff --git a/src/lib/branding.ts b/src/lib/branding.ts
new file mode 100644
index 0000000..ea34fa1
--- /dev/null
+++ b/src/lib/branding.ts
@@ -0,0 +1,67 @@
+import type { ResolvedSettings } from "./settings.ts";
+
+// What an install calls itself.
+//
+// A neutral install (the default) carries the name of the organization that
+// runs it, links to that organization's own terms and privacy policy, and
+// says "Powered by SignuDoc" in the footer. Hosted mode (HOSTED_MODE=1) is
+// SignuDoc run as a public service: its own name, landing page and legal
+// pages.
+
+export const SIGNUDOC_NAME = "SignuDoc";
+export const SIGNUDOC_URL = "https://signudoc.app";
+
+export type Branding = {
+ /** Where "Contact" should point: a page on this site, or null. */
+ contactUrl: string | null;
+ hosted: boolean;
+ /** The organization's name, when one has been set. */
+ organizationName: string | null;
+ privacyUrl: string | null;
+ /** The name shown in the header, in page titles and in emails. */
+ productName: string;
+ /** False when new accounts are not being accepted at all. */
+ signupAvailable: boolean;
+ supportAddress: string | null;
+ termsUrl: string | null;
+};
+
+/** SignuDoc under its own name. Also what a page shows before it knows better. */
+export const HOSTED_BRANDING: Branding = {
+ contactUrl: "/contact",
+ hosted: true,
+ organizationName: null,
+ privacyUrl: "/privacy",
+ productName: SIGNUDOC_NAME,
+ signupAvailable: true,
+ supportAddress: null,
+ termsUrl: "/terms",
+};
+
+export function buildBranding(settings: ResolvedSettings): Branding {
+ const signupAvailable =
+ settings.signupMode === "open" ||
+ (settings.signupMode === "domains" &&
+ settings.allowedEmailDomains.length > 0);
+
+ if (settings.hosted) {
+ return {
+ ...HOSTED_BRANDING,
+ signupAvailable,
+ supportAddress: settings.supportAddress,
+ };
+ }
+
+ const organizationName = settings.organizationName?.trim() || null;
+
+ return {
+ contactUrl: null,
+ hosted: false,
+ organizationName,
+ privacyUrl: settings.privacyUrl,
+ productName: organizationName ?? SIGNUDOC_NAME,
+ signupAvailable,
+ supportAddress: settings.supportAddress,
+ termsUrl: settings.termsUrl,
+ };
+}
diff --git a/src/lib/contact.ts b/src/lib/contact.ts
index 3246ce4..14d2110 100644
--- a/src/lib/contact.ts
+++ b/src/lib/contact.ts
@@ -103,7 +103,7 @@ export async function submitPublicContactMessage(
};
}
- const supportAddress = resolvePublicSupportAddress(env);
+ const supportAddress = await resolvePublicSupportAddress(env);
const submittedAt = formatSubmittedAt();
const escapedMessageHtml = escapeHtml(parsedInput.message).replaceAll(
"\n",
diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.ts
new file mode 100644
index 0000000..4e42fd3
--- /dev/null
+++ b/src/lib/email-status.test.ts
@@ -0,0 +1,365 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ addEmailDomain,
+ emailNeedsAttention,
+ getEmailStatus,
+ recheckEmailDomain,
+ type ResendDomainsClient,
+} from "./email-status.ts";
+import { resolveSettings, type AppSettings } from "./settings.ts";
+
+const stored: AppSettings = {
+ allowedEmailDomains: ["acme.com"],
+ emailReadyAt: null,
+ organizationName: "Acme Corp",
+ privacyUrl: null,
+ senderAddress: "[email protected]",
+ setupCompletedAt: 1_800_000_000,
+ signupMode: "domains",
+ supportAddress: null,
+ termsUrl: null,
+};
+
+const env = { RESEND_API_KEY: "re_test_key" };
+const settings = resolveSettings(stored, env);
+
+const DKIM_RECORD = {
+ name: "resend._domainkey",
+ record: "DKIM",
+ status: "pending",
+ ttl: "Auto",
+ type: "TXT",
+ value: "p=MIGfMA0GCSqGSIb3DQEB",
+};
+const SPF_MX_RECORD = {
+ name: "send",
+ priority: 10,
+ record: "SPF",
+ status: "pending",
+ ttl: "Auto",
+ type: "MX",
+ value: "feedback-smtp.us-east-1.amazonses.com",
+};
+// Resend lists records for features this app does not use without a name
+// or a value.
+const TRACKING_RECORD = { record: "Tracking", status: "not_started" };
+
+type FakeError = { message: string; name: string; statusCode: number };
+type FakeDomain = {
+ id: string;
+ name: string;
+ records: unknown[];
+ status: string;
+};
+
+/** Stands in for Resend's domains API and remembers what was asked of it. */
+function fakeResend(
+ initial: {
+ domains?: FakeDomain[];
+ errors?: Record<string, FakeError[]>;
+ } = {},
+) {
+ const domains = [...(initial.domains ?? [])];
+ const errors = initial.errors ?? {};
+ const calls: string[] = [];
+ const readyMarks: boolean[] = [];
+
+ function respond<T>(method: string, data: () => T) {
+ const error = errors[method]?.shift();
+
+ return Promise.resolve(
+ error ? { data: null, error } : { data: data(), error: null },
+ );
+ }
+
+ const client = {
+ create({ name }: { name: string }) {
+ calls.push(`create ${name}`);
+
+ return respond("create", () => {
+ const created = {
+ id: `domain_${String(domains.length + 1)}`,
+ name,
+ records: [DKIM_RECORD, SPF_MX_RECORD, TRACKING_RECORD],
+ status: "not_started",
+ };
+
+ domains.push(created);
+
+ return created;
+ });
+ },
+ get(id: string) {
+ calls.push(`get ${id}`);
+
+ 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 })),
+ }));
+ },
+ verify(id: string) {
+ calls.push(`verify ${id}`);
+
+ return respond("verify", () => ({ id }));
+ },
+ };
+
+ return {
+ calls,
+ domains,
+ options: {
+ domainsClient: client as unknown as ResendDomainsClient,
+ env,
+ recordReady: async (ready: boolean) => {
+ readyMarks.push(ready);
+ },
+ settings,
+ },
+ readyMarks,
+ };
+}
+
+test("the capture driver is reported as such without asking anyone", async () => {
+ assert.deepEqual(await getEmailStatus({ env: { EMAIL_DRIVER: "capture" } }), {
+ state: "capture",
+ });
+});
+
+test("no Resend key means email is not connected", async () => {
+ assert.deepEqual(await getEmailStatus({ env: {}, settings }), {
+ state: "missing_key",
+ });
+});
+
+test("Resend's test address is reported without asking Resend about domains", async () => {
+ const resend = fakeResend();
+ const status = await getEmailStatus({
+ ...resend.options,
+ settings: resolveSettings({ ...stored, senderAddress: null }, env),
+ });
+
+ assert.deepEqual(status, {
+ senderAddress: "[email protected]",
+ state: "test_sender",
+ });
+ assert.deepEqual(resend.calls, []);
+ assert.deepEqual(resend.readyMarks, [false]);
+});
+
+test("a sender address in the environment is the one that is checked", async () => {
+ const resend = fakeResend();
+ const status = await getEmailStatus({
+ ...resend.options,
+ settings: resolveSettings(stored, {
+ ...env,
+ RESEND_FROM_EMAIL: "Acme <[email protected]>",
+ }),
+ });
+
+ assert.deepEqual(status, {
+ domain: "mail.acme.com",
+ senderAddress: "[email protected]",
+ state: "domain_missing",
+ });
+});
+
+test("a domain Resend has not heard of needs setting up", async () => {
+ const resend = fakeResend();
+
+ assert.deepEqual(await getEmailStatus(resend.options), {
+ domain: "acme.com",
+ senderAddress: "[email protected]",
+ state: "domain_missing",
+ });
+ assert.deepEqual(resend.calls, ["list"]);
+ assert.deepEqual(resend.readyMarks, [false]);
+});
+
+test("setting the domain up adds it to Resend and returns the DNS records to add", async () => {
+ const resend = fakeResend();
+ const status = await addEmailDomain(resend.options);
+
+ assert.deepEqual(status, {
+ domain: "acme.com",
+ records: [
+ {
+ name: "resend._domainkey",
+ priority: null,
+ purpose: "DKIM",
+ status: "pending",
+ type: "TXT",
+ value: "p=MIGfMA0GCSqGSIb3DQEB",
+ },
+ {
+ name: "send",
+ priority: 10,
+ purpose: "SPF",
+ status: "pending",
+ type: "MX",
+ value: "feedback-smtp.us-east-1.amazonses.com",
+ },
+ ],
+ senderAddress: "[email protected]",
+ state: "domain_pending",
+ });
+ assert.deepEqual(resend.calls, ["list", "create acme.com"]);
+});
+
+test("setting up a domain that is already there shows its records instead of adding it twice", async () => {
+ const resend = fakeResend({
+ domains: [
+ {
+ id: "domain_1",
+ name: "Acme.com",
+ records: [DKIM_RECORD],
+ status: "pending",
+ },
+ ],
+ });
+ const status = await addEmailDomain(resend.options);
+
+ assert.equal(status.state, "domain_pending");
+ assert.deepEqual(resend.calls, ["list", "get domain_1"]);
+});
+
+test("a domain whose records are not verified yet is pending, with its records", async () => {
+ const resend = fakeResend({
+ domains: [
+ {
+ id: "domain_1",
+ name: "acme.com",
+ records: [DKIM_RECORD],
+ status: "pending",
+ },
+ ],
+ });
+ const status = await getEmailStatus(resend.options);
+
+ assert.equal(status.state, "domain_pending");
+ assert.equal(
+ status.state === "domain_pending" ? status.records.length : 0,
+ 1,
+ );
+ assert.deepEqual(resend.calls, ["list", "get domain_1"]);
+ assert.deepEqual(resend.readyMarks, [false]);
+});
+
+test("a verified domain means email is working, and that is recorded", async () => {
+ const resend = fakeResend({
+ domains: [
+ { id: "domain_1", name: "acme.com", records: [], status: "verified" },
+ ],
+ });
+
+ assert.deepEqual(await getEmailStatus(resend.options), {
+ domain: "acme.com",
+ senderAddress: "[email protected]",
+ state: "ready",
+ });
+ assert.deepEqual(resend.calls, ["list"]);
+ assert.deepEqual(resend.readyMarks, [true]);
+});
+
+test("checking again asks Resend to verify, then reads the result", async () => {
+ const resend = fakeResend({
+ domains: [
+ {
+ id: "domain_1",
+ name: "acme.com",
+ records: [DKIM_RECORD],
+ status: "pending",
+ },
+ ],
+ });
+
+ // The DNS records were found between the two requests.
+ const pending = await recheckEmailDomain(resend.options);
+
+ assert.equal(pending.state, "domain_pending");
+ assert.deepEqual(resend.calls, ["list", "verify domain_1", "get domain_1"]);
+
+ resend.domains[0]!.status = "verified";
+
+ assert.equal((await recheckEmailDomain(resend.options)).state, "ready");
+});
+
+test("a key that may only send points the administrator at Resend instead", async () => {
+ const resend = fakeResend({
+ errors: {
+ list: [
+ {
+ message: "This API key is restricted to only send emails",
+ name: "restricted_api_key",
+ statusCode: 401,
+ },
+ ],
+ },
+ });
+
+ assert.deepEqual(await getEmailStatus(resend.options), {
+ domain: "acme.com",
+ senderAddress: "[email protected]",
+ state: "restricted_key",
+ });
+ // Nothing was learned about the domain, so the mark is left alone.
+ assert.deepEqual(resend.readyMarks, []);
+});
+
+test("any other failure is reported in Resend's own words", async () => {
+ const resend = fakeResend({
+ errors: {
+ list: [
+ {
+ message: "Something went wrong on our side",
+ name: "internal_server_error",
+ statusCode: 500,
+ },
+ ],
+ },
+ });
+
+ assert.deepEqual(await getEmailStatus(resend.options), {
+ message: "Something went wrong on our side",
+ senderAddress: "[email protected]",
+ state: "error",
+ });
+});
+
+test("a request turned away for going too fast is tried once more", async () => {
+ const resend = fakeResend({
+ errors: {
+ list: [
+ {
+ message: "Too many requests",
+ name: "rate_limit_exceeded",
+ statusCode: 429,
+ },
+ ],
+ },
+ });
+
+ assert.equal((await getEmailStatus(resend.options)).state, "domain_missing");
+ assert.deepEqual(resend.calls, ["list", "list"]);
+});
+
+test("the administrator is told about email until it has been seen working", () => {
+ assert.equal(emailNeedsAttention(settings, env), true);
+ assert.equal(
+ emailNeedsAttention(
+ resolveSettings({ ...stored, emailReadyAt: 1_800_000_100 }, env),
+ env,
+ ),
+ false,
+ );
+ // Nothing to set up when messages are only being captured.
+ assert.equal(
+ emailNeedsAttention(settings, { EMAIL_DRIVER: "capture" }),
+ false,
+ );
+});
diff --git a/src/lib/email-status.ts b/src/lib/email-status.ts
new file mode 100644
index 0000000..b99c37d
--- /dev/null
+++ b/src/lib/email-status.ts
@@ -0,0 +1,403 @@
+import { Resend } from "resend";
+
+import {
+ buildEmailAddresses,
+ extractEmailAddress,
+ getAddressDomain,
+ isResendTestSender,
+} from "./services/email-addresses.ts";
+import { resolveEmailDriver } from "./services/email.ts";
+import {
+ getSettings,
+ markEmailReady,
+ type ResolvedSettings,
+} from "./settings.ts";
+import { getEnv, type EnvSource } from "./utils/env.ts";
+
+// Whether this install can send email to anyone, and what is left to do if
+// it cannot. Shown to the administrator in Settings.
+//
+// Sending from an organization's own address needs that address's domain to
+// be verified with Resend, which means adding DNS records. Resend's API can
+// add the domain and hand back the records, so the app can show them itself.
+// A Resend API key that is only allowed to send cannot do that; then the
+// administrator is pointed at Resend's dashboard instead.
+// https://resend.com/docs/api-reference/domains/create-domain
+
+export const RESEND_DOMAINS_URL = "https://resend.com/domains";
+
+export type EmailDnsRecord = {
+ name: string;
+ priority: number | null;
+ purpose: string;
+ status: string;
+ type: string;
+ value: string;
+};
+
+export type EmailStatus =
+ /** Development: messages are written to disk, not sent. */
+ | { state: "capture" }
+ /** No Resend API key, so nothing can be sent. */
+ | { state: "missing_key" }
+ /** Sending from Resend's shared test address: only reaches the Resend account owner. */
+ | { state: "test_sender"; senderAddress: string }
+ /** The API key can send, but is not allowed to look at domains. */
+ | { state: "restricted_key"; domain: string; senderAddress: string }
+ /** The sender's domain has not been added to the Resend account. */
+ | { state: "domain_missing"; domain: string; senderAddress: string }
+ /** The domain is in Resend but its DNS records have not been verified. */
+ | {
+ state: "domain_pending";
+ domain: string;
+ records: EmailDnsRecord[];
+ senderAddress: string;
+ }
+ | { state: "ready"; domain: string; senderAddress: string }
+ | { state: "error"; message: string; senderAddress: string };
+
+/** The parts of the Resend SDK used here. Replaced by a fake in tests. */
+export type ResendDomainsClient = Pick<
+ Resend["domains"],
+ "create" | "get" | "list" | "verify"
+>;
+
+type EmailStatusOptions = {
+ domainsClient?: ResendDomainsClient;
+ env?: EnvSource;
+ /** Replaced in tests, where there is no database to write the result to. */
+ recordReady?: (ready: boolean) => Promise<void>;
+ settings?: ResolvedSettings;
+};
+
+function isRestrictedKeyError(error: {
+ name?: string;
+ statusCode?: number | null;
+}): boolean {
+ return (
+ error.name === "restricted_api_key" ||
+ error.name === "invalid_access" ||
+ error.statusCode === 401 ||
+ error.statusCode === 403
+ );
+}
+
+function toDnsRecords(records: readonly unknown[]): EmailDnsRecord[] {
+ const dnsRecords: EmailDnsRecord[] = [];
+
+ for (const record of records) {
+ if (typeof record !== "object" || record === null) {
+ continue;
+ }
+
+ const {
+ name,
+ priority,
+ record: purpose,
+ status,
+ type,
+ value,
+ } = record as {
+ name?: unknown;
+ priority?: unknown;
+ record?: unknown;
+ status?: unknown;
+ type?: unknown;
+ value?: unknown;
+ };
+
+ // Records for features this app does not use (receiving, tracking)
+ // arrive without a name and value, and are left out.
+ if (
+ typeof name !== "string" ||
+ typeof type !== "string" ||
+ typeof value !== "string"
+ ) {
+ continue;
+ }
+
+ dnsRecords.push({
+ name,
+ priority: typeof priority === "number" ? priority : null,
+ purpose: typeof purpose === "string" ? purpose : "",
+ status: typeof status === "string" ? status : "pending",
+ type,
+ value,
+ });
+ }
+
+ return dnsRecords;
+}
+
+function createDomainsClient(env: EnvSource): ResendDomainsClient | null {
+ const apiKey = getEnv(env).email.apiKey;
+
+ return apiKey ? new Resend(apiKey).domains : null;
+}
+
+async function defaultRecordReady(
+ ready: boolean,
+ settings: ResolvedSettings,
+): Promise<void> {
+ if (ready === (settings.emailReadyAt !== null)) {
+ return;
+ }
+
+ await markEmailReady(ready);
+}
+
+const RATE_LIMIT_RETRY_DELAY_MS = 1_100;
+
+type ResendResult = { error: { name?: string } | null };
+
+// Resend allows only a couple of requests a second, and checking a domain
+// takes two or three in a row. One that is turned away for that reason is
+// tried once more after a pause.
+async function callResend<T extends ResendResult>(
+ call: () => Promise<T>,
+): Promise<T> {
+ const result = await call();
+
+ if (result.error?.name !== "rate_limit_exceeded") {
+ return result;
+ }
+
+ await new Promise((resolve) =>
+ setTimeout(resolve, RATE_LIMIT_RETRY_DELAY_MS),
+ );
+
+ return call();
+}
+
+type Inspection = {
+ client: ResendDomainsClient | null;
+ /** The domain's id in Resend, when the domain is there. */
+ domainId: string | null;
+ markReady: (ready: boolean) => Promise<void>;
+ status: EmailStatus;
+};
+
+function toErrorStatus(
+ error: { message: string; name?: string; statusCode?: number | null },
+ domain: string,
+ senderAddress: string,
+): EmailStatus {
+ return isRestrictedKeyError(error)
+ ? { domain, senderAddress, state: "restricted_key" }
+ : { message: error.message, senderAddress, state: "error" };
+}
+
+async function describeDomain(
+ client: ResendDomainsClient,
+ domainId: string,
+ domain: string,
+ senderAddress: string,
+ markReady: (ready: boolean) => Promise<void>,
+): Promise<EmailStatus> {
+ const details = await callResend(() => client.get(domainId));
+
+ if (details.error) {
+ return toErrorStatus(details.error, domain, senderAddress);
+ }
+
+ if (details.data.status === "verified") {
+ await markReady(true);
+
+ return { domain, senderAddress, state: "ready" };
+ }
+
+ await markReady(false);
+
+ return {
+ domain,
+ records: toDnsRecords(details.data.records),
+ senderAddress,
+ state: "domain_pending",
+ };
+}
+
+// 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({
+ domainsClient,
+ env = process.env,
+ recordReady,
+ settings,
+}: EmailStatusOptions): Promise<Inspection> {
+ const noop = async () => undefined;
+
+ if (!domainsClient && resolveEmailDriver(env) === "capture") {
+ return {
+ client: null,
+ domainId: null,
+ markReady: noop,
+ status: { state: "capture" },
+ };
+ }
+
+ const client = domainsClient ?? createDomainsClient(env);
+
+ if (!client) {
+ return {
+ client: null,
+ domainId: null,
+ markReady: noop,
+ status: { state: "missing_key" },
+ };
+ }
+
+ const resolvedSettings = settings ?? (await getSettings(env));
+ const markReady =
+ recordReady ??
+ ((ready: boolean) => defaultRecordReady(ready, resolvedSettings));
+ const senderAddress = extractEmailAddress(
+ buildEmailAddresses(resolvedSettings).senderAddress,
+ );
+ const domain = getAddressDomain(senderAddress);
+ const base = { client, domainId: null, markReady };
+
+ if (!domain || isResendTestSender(senderAddress)) {
+ await markReady(false);
+
+ return { ...base, status: { senderAddress, state: "test_sender" } };
+ }
+
+ const listed = await callResend(() => client.list({ limit: 100 }));
+
+ if (listed.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),
+ };
+ }
+
+ const match = listed.data.data.find(
+ (candidate) => candidate.name.toLowerCase() === domain,
+ );
+
+ if (!match) {
+ await markReady(false);
+
+ return {
+ ...base,
+ status: { domain, senderAddress, state: "domain_missing" },
+ };
+ }
+
+ if (match.status === "verified") {
+ await markReady(true);
+
+ return {
+ ...base,
+ domainId: match.id,
+ status: { domain, senderAddress, state: "ready" },
+ };
+ }
+
+ return {
+ ...base,
+ domainId: match.id,
+ // The records are filled in by the caller.
+ status: { domain, records: [], senderAddress, state: "domain_pending" },
+ };
+}
+
+/**
+ * Works out whether email can be sent, asking Resend about the sender's
+ * domain when there is one to ask about. Also keeps the "email works" mark
+ * in settings in step with what it finds.
+ */
+export async function getEmailStatus(
+ options: EmailStatusOptions = {},
+): Promise<EmailStatus> {
+ const { client, domainId, markReady, status } = await inspectEmail(options);
+
+ if (status.state !== "domain_pending" || !client || !domainId) {
+ return status;
+ }
+
+ return describeDomain(
+ client,
+ domainId,
+ status.domain,
+ status.senderAddress,
+ markReady,
+ );
+}
+
+/** Adds the sender's domain to the Resend account, then reports the new status. */
+export async function addEmailDomain(
+ options: EmailStatusOptions = {},
+): Promise<EmailStatus> {
+ const { client, domainId, markReady, status } = await inspectEmail(options);
+
+ if (status.state === "domain_pending" && client && domainId) {
+ return describeDomain(
+ client,
+ domainId,
+ status.domain,
+ status.senderAddress,
+ markReady,
+ );
+ }
+
+ if (status.state !== "domain_missing" || !client) {
+ return status;
+ }
+
+ const created = await callResend(() =>
+ client.create({ name: status.domain }),
+ );
+
+ if (created.error) {
+ return toErrorStatus(created.error, status.domain, status.senderAddress);
+ }
+
+ return {
+ domain: status.domain,
+ records: toDnsRecords(created.data.records),
+ senderAddress: status.senderAddress,
+ state: "domain_pending",
+ };
+}
+
+/** Asks Resend to look at the domain's DNS records again, then reports the status. */
+export async function recheckEmailDomain(
+ options: EmailStatusOptions = {},
+): Promise<EmailStatus> {
+ const { client, domainId, markReady, status } = await inspectEmail(options);
+
+ if (status.state !== "domain_pending" || !client || !domainId) {
+ return status;
+ }
+
+ // 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));
+
+ return describeDomain(
+ client,
+ domainId,
+ status.domain,
+ status.senderAddress,
+ markReady,
+ );
+}
+
+/** True when an administrator should be told that email still needs work. */
+export function emailNeedsAttention(
+ settings: ResolvedSettings,
+ env: EnvSource = process.env,
+): boolean {
+ try {
+ if (resolveEmailDriver(env) === "capture") {
+ return false;
+ }
+ } catch {
+ return true;
+ }
+
+ return settings.emailReadyAt === null;
+}
diff --git a/src/lib/email-test.ts b/src/lib/email-test.ts
new file mode 100644
index 0000000..a2861f2
--- /dev/null
+++ b/src/lib/email-test.ts
@@ -0,0 +1,79 @@
+import { isResendTestSender } from "./services/email-addresses.ts";
+import {
+ createEmailService,
+ resolveEmailAddresses,
+ type EmailService,
+} from "./services/email.ts";
+import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
+import { getBranding, markEmailReady } from "./settings.ts";
+import { type EnvSource } from "./utils/env.ts";
+import { escapeHtml } from "./utils/html.ts";
+
+export type TestEmailResult =
+ { sent: true; to: string } | { sent: false; message: string };
+
+type SendTestEmailInput = {
+ emailService?: EmailService;
+ env?: EnvSource;
+ name: string;
+ to: string;
+};
+
+/**
+ * Sends the administrator a message through the real email setup, so they
+ * can see it arrive. A failure comes back with the mail provider's own
+ * words, which usually say exactly what is wrong.
+ */
+export async function sendTestEmail({
+ emailService,
+ env = process.env,
+ name,
+ to,
+}: SendTestEmailInput): Promise<TestEmailResult> {
+ try {
+ const branding = await getBranding(env);
+ const { productName } = branding;
+ const textBody = [
+ `Hi ${name},`,
+ "",
+ `This is a test message from ${productName}. If you are reading it, email is working.`,
+ ].join("\n");
+ const htmlBody = [
+ `<p>Hi ${escapeHtml(name)},</p>`,
+ `<p>This is a test message from ${escapeHtml(productName)}. If you are reading it, email is working.</p>`,
+ ].join("");
+ const content = withUserEmailLegalFooter(
+ { htmlBody, textBody },
+ branding,
+ env,
+ );
+
+ await (emailService ?? createEmailService({ env })).send({
+ htmlBody: content.htmlBody,
+ subject: `Test email from ${productName}`,
+ template: "test_email",
+ textBody: content.textBody,
+ to,
+ });
+
+ // A message accepted from the organization's own address means that
+ // 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);
+ }
+
+ return { sent: true, to };
+ } catch (error) {
+ return {
+ message:
+ error instanceof Error && error.message
+ ? error.message
+ : "The test email could not be sent.",
+ sent: false,
+ };
+ }
+}
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index f86f582..c1afa76 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
+import { type Branding } from "./branding.ts";
import {
type DbExecutor,
type DbPool,
@@ -38,6 +39,7 @@ import {
type ReplaceSignersResponse,
type SignerRecord,
} from "./schemas/signer.ts";
+import { getBranding } from "./settings.ts";
import { importPdfDocument } from "./services/document-import.ts";
import {
listAuditEventsForEnvelope,
@@ -848,6 +850,7 @@ function getMissingSignatureSigner(
}
function buildVoidNotificationEmail(input: {
+ branding: Branding;
envelopeId: string;
envelopeTitle: string;
senderName: string;
@@ -858,18 +861,21 @@ function buildVoidNotificationEmail(input: {
const textBody = [
`Hi ${input.signerName},`,
"",
- `${input.senderName} voided "${input.envelopeTitle}" in SignuDoc.`,
+ `${input.senderName} voided "${input.envelopeTitle}" in ${input.branding.productName}.`,
"The signing process has been canceled. No further action is needed.",
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
- `<p>${escapeHtml(input.senderName)} voided &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; in SignuDoc.</p>`,
+ `<p>${escapeHtml(input.senderName)} voided &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; in ${escapeHtml(input.branding.productName)}.</p>`,
"<p>The signing process has been canceled. No further action is needed.</p>",
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
@@ -1495,6 +1501,7 @@ export async function sendDraftEnvelope(
try {
await emailService.send(
buildSigningInvitationEmail({
+ branding: await getBranding(),
envelopeTitle: envelope.title,
senderName: input.senderName,
signerEmail: firstSigner.email,
@@ -1769,11 +1776,18 @@ export async function voidSentEnvelope(
throw error;
}
+ const branding = await getBranding().catch(() => null);
+
await Promise.all(
notifiedSigners.map(async (signer) => {
try {
+ if (!branding) {
+ throw new Error("Could not load settings for the notification email.");
+ }
+
await emailService.send(
buildVoidNotificationEmail({
+ branding,
envelopeId,
envelopeTitle: envelope.title,
senderName: input.senderName,
diff --git a/src/lib/hosted-pages.ts b/src/lib/hosted-pages.ts
new file mode 100644
index 0000000..82543f1
--- /dev/null
+++ b/src/lib/hosted-pages.ts
@@ -0,0 +1,19 @@
+import { notFound } from "next/navigation";
+import { connection } from "next/server";
+
+import { isHostedMode } from "./utils/env.ts";
+
+/**
+ * For pages that only exist when SignuDoc runs as a public service under its
+ * own name: the landing page's legal pages and the contact form. On any
+ * other install they are not found, and the organization links to its own.
+ */
+export async function requireHostedMode() {
+ // Decided when the page is requested, not when the app was built, so the
+ // same build works with HOSTED_MODE on or off.
+ await connection();
+
+ if (!isHostedMode()) {
+ notFound();
+ }
+}
diff --git a/src/lib/install.ts b/src/lib/install.ts
new file mode 100644
index 0000000..10fa3a7
--- /dev/null
+++ b/src/lib/install.ts
@@ -0,0 +1,59 @@
+import type { Metadata } from "next";
+import { redirect } from "next/navigation";
+
+import type { Branding } from "./branding.ts";
+import { ServiceConfigurationError } from "./services/service-config.ts";
+import { getBranding, isFreshInstall } from "./settings.ts";
+
+/**
+ * Page title and description for an install that is not the hosted service:
+ * the organization's name instead of SignuDoc's own. The hosted service
+ * keeps what the root layout says.
+ */
+export async function getInstallMetadata(): Promise<Metadata> {
+ let branding: Branding;
+
+ try {
+ branding = await getBranding();
+ } catch {
+ // A page title is not worth failing a page over. Whatever went wrong
+ // (no database, most likely) is reported by the page itself.
+ return {};
+ }
+
+ if (branding.hosted) {
+ return {};
+ }
+
+ return {
+ description: `Send and sign documents with ${branding.productName}.`,
+ title: branding.productName,
+ };
+}
+
+/**
+ * For the pages a first visitor can land on. While the install has no
+ * accounts and has never been set up, they all lead to /setup. So does a
+ * deployment with no database connected, where /setup explains what to do.
+ */
+export async function redirectToSetupIfNeeded() {
+ let needsSetup: boolean;
+
+ try {
+ needsSetup = await isFreshInstall();
+ } catch (error) {
+ if (error instanceof ServiceConfigurationError) {
+ needsSetup = true;
+ } else {
+ // The database could not be asked. That is not a reason to send
+ // visitors of a working site to the setup page, or to fail a page
+ // that may not need the database at all.
+ console.error("[setup] Could not read the setup state:", error);
+ needsSetup = false;
+ }
+ }
+
+ if (needsSetup) {
+ redirect("/setup");
+ }
+}
diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.ts
new file mode 100644
index 0000000..2e9e201
--- /dev/null
+++ b/src/lib/organization-settings.ts
@@ -0,0 +1,163 @@
+import { z } from "zod";
+
+import { getDb, type DbExecutor } from "./db/connection.ts";
+import { emailSchema } from "./schemas/common.ts";
+import {
+ saveSettings,
+ type AppSettings,
+ type ResolvedSettings,
+} from "./settings.ts";
+import { parseEmailDomainList, SIGNUP_MODES } from "./signup-policy.ts";
+
+// What an administrator can change on the Organization tab in Settings.
+
+export type OrganizationSettingsField =
+ | "allowedEmailDomains"
+ | "organizationName"
+ | "privacyUrl"
+ | "senderAddress"
+ | "signupMode"
+ | "supportAddress"
+ | "termsUrl";
+
+export class OrganizationSettingsError extends Error {
+ readonly fieldErrors: Partial<Record<OrganizationSettingsField, string>>;
+
+ constructor(fieldErrors: Partial<Record<OrganizationSettingsField, string>>) {
+ super("Check the highlighted fields.");
+ this.name = "OrganizationSettingsError";
+ this.fieldErrors = fieldErrors;
+ }
+}
+
+/** The values the Organization form shows and sends back. */
+export type OrganizationSettingsView = {
+ allowedEmailDomains: string;
+ hosted: boolean;
+ organizationName: string;
+ privacyUrl: string;
+ senderAddress: string;
+ senderAddressFromEnv: boolean;
+ signupMode: AppSettings["signupMode"];
+ supportAddress: string;
+ supportAddressFromEnv: boolean;
+ termsUrl: string;
+};
+
+export function toOrganizationSettingsView(
+ settings: ResolvedSettings,
+): OrganizationSettingsView {
+ return {
+ allowedEmailDomains: settings.allowedEmailDomains.join(", "),
+ hosted: settings.hosted,
+ organizationName: settings.organizationName ?? "",
+ privacyUrl: settings.privacyUrl ?? "",
+ senderAddress: settings.senderAddress ?? "",
+ senderAddressFromEnv: settings.senderAddressFromEnv,
+ signupMode: settings.signupMode,
+ supportAddress: settings.supportAddress ?? "",
+ supportAddressFromEnv: settings.supportAddressFromEnv,
+ termsUrl: settings.termsUrl ?? "",
+ };
+}
+
+function blankToNull(value: unknown): unknown {
+ return typeof value === "string" && value.trim().length === 0 ? null : value;
+}
+
+const optionalEmail = z.preprocess(blankToNull, emailSchema.nullable());
+const optionalWebUrl = z.preprocess(
+ blankToNull,
+ z
+ .string()
+ .trim()
+ .max(2048)
+ .refine((value) => {
+ try {
+ const url = new URL(value);
+
+ return url.protocol === "https:" || url.protocol === "http:";
+ } catch {
+ return false;
+ }
+ })
+ .nullable(),
+);
+
+const organizationSettingsSchema = z.object({
+ allowedEmailDomains: z.string().max(4000).default(""),
+ organizationName: z.string().trim().min(1).max(120),
+ privacyUrl: optionalWebUrl.default(null),
+ senderAddress: optionalEmail.default(null),
+ signupMode: z.enum(SIGNUP_MODES),
+ supportAddress: optionalEmail.default(null),
+ termsUrl: optionalWebUrl.default(null),
+});
+
+const FIELD_MESSAGES: Record<OrganizationSettingsField, string> = {
+ allowedEmailDomains: "Enter one or more domains, such as yourcompany.com",
+ organizationName: "Enter the name of your organization",
+ privacyUrl: "Enter a full web address starting with https://",
+ 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",
+ termsUrl: "Enter a full web address starting with https://",
+};
+
+/**
+ * Validates and saves the Organization form. Addresses that are fixed by an
+ * environment variable are left as they are stored, since the stored value
+ * is not the one in use.
+ */
+export async function updateOrganizationSettings(
+ rawInput: unknown,
+ current: ResolvedSettings,
+ database: DbExecutor = getDb(),
+): Promise<AppSettings> {
+ const parsed = organizationSettingsSchema.safeParse(rawInput);
+ const fieldErrors: Partial<Record<OrganizationSettingsField, string>> = {};
+
+ if (!parsed.success) {
+ for (const issue of parsed.error.issues) {
+ const field = issue.path[0];
+
+ if (typeof field === "string" && field in FIELD_MESSAGES) {
+ fieldErrors[field as OrganizationSettingsField] ??=
+ FIELD_MESSAGES[field as OrganizationSettingsField];
+ }
+ }
+
+ throw new OrganizationSettingsError(fieldErrors);
+ }
+
+ const input = parsed.data;
+ const { domains, invalid } = parseEmailDomainList(input.allowedEmailDomains);
+
+ if (invalid.length > 0) {
+ fieldErrors.allowedEmailDomains = `Not a domain: ${invalid.slice(0, 3).join(", ")}`;
+ } else if (input.signupMode === "domains" && domains.length === 0) {
+ fieldErrors.allowedEmailDomains = FIELD_MESSAGES.allowedEmailDomains;
+ }
+
+ if (Object.keys(fieldErrors).length > 0) {
+ throw new OrganizationSettingsError(fieldErrors);
+ }
+
+ return saveSettings(
+ {
+ allowedEmailDomains: domains,
+ organizationName: input.organizationName,
+ signupMode: input.signupMode,
+ ...(current.hosted
+ ? {}
+ : { privacyUrl: input.privacyUrl, termsUrl: input.termsUrl }),
+ ...(current.senderAddressFromEnv
+ ? {}
+ : { senderAddress: input.senderAddress?.toLowerCase() ?? null }),
+ ...(current.supportAddressFromEnv
+ ? {}
+ : { supportAddress: input.supportAddress?.toLowerCase() ?? null }),
+ },
+ database,
+ );
+}
diff --git a/src/lib/public-contact.ts b/src/lib/public-contact.ts
index f2f6aed..f33d617 100644
--- a/src/lib/public-contact.ts
+++ b/src/lib/public-contact.ts
@@ -1,8 +1,15 @@
-import { getEnv, type EnvSource } from "./utils/env";
import { ServiceConfigurationError } from "./services/service-config.ts";
+import { getSettings } from "./settings.ts";
+import { type EnvSource } from "./utils/env.ts";
-export function resolvePublicSupportAddress(env: EnvSource = process.env) {
- const supportAddress = getEnv(env).email.supportAddress;
+/**
+ * The address people are told to write to. SUPPORT_EMAIL when it is set,
+ * otherwise the support address saved in the install's settings.
+ */
+export async function resolvePublicSupportAddress(
+ env: EnvSource = process.env,
+): Promise<string> {
+ const { supportAddress } = await getSettings(env);
if (supportAddress) {
return supportAddress;
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index a38914b..ea0e1b7 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -1,3 +1,4 @@
+import { type Branding } from "./branding.ts";
import {
type DbExecutor,
type DbPool,
@@ -10,6 +11,7 @@ import {
type EnvelopeRecord,
} from "./schemas/envelope.ts";
import { type SignerRecord } from "./schemas/signer.ts";
+import { getBranding } from "./settings.ts";
import { recordAuditEvent } from "./services/audit.ts";
import { createEmailService } from "./services/email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
@@ -154,6 +156,7 @@ async function getCurrentSignerForEnvelope(
}
function buildReminderEmail(input: {
+ branding: Branding;
envelopeId: string;
envelopeTitle: string;
senderName: string;
@@ -162,7 +165,7 @@ function buildReminderEmail(input: {
signingUrl: string;
}) {
const subject = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}"`;
- const introLine = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}" through SignuDoc.`;
+ const introLine = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}" through ${input.branding.productName}.`;
const textBody = [
`Hi ${input.signerName},`,
"",
@@ -171,20 +174,23 @@ function buildReminderEmail(input: {
"Review and sign the document here:",
input.signingUrl,
"",
- "You do not need a SignuDoc account to sign.",
+ `You do not need a ${input.branding.productName} account to sign.`,
"If you receive a newer invitation or reminder link, use the newest one.",
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
`<p>${escapeHtml(introLine)}</p>`,
`<p><a href="${escapeHtml(input.signingUrl)}">Review and sign the document</a></p>`,
- "<p>You do not need a SignuDoc account to sign.</p>",
+ `<p>You do not need a ${escapeHtml(input.branding.productName)} account to sign.</p>`,
"<p>If you receive a newer invitation or reminder link, use the newest one.</p>",
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
@@ -375,6 +381,7 @@ export async function sendManualEnvelopeNudge(
try {
await emailService.send(
buildReminderEmail({
+ branding: await getBranding(),
envelopeId: persisted.envelopeId,
envelopeTitle: persisted.envelopeTitle,
senderName: persisted.senderName,
diff --git a/src/lib/services/email-addresses.test.ts b/src/lib/services/email-addresses.test.ts
new file mode 100644
index 0000000..d75214e
--- /dev/null
+++ b/src/lib/services/email-addresses.test.ts
@@ -0,0 +1,93 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ buildEmailAddresses,
+ extractEmailAddress,
+ getAddressDomain,
+ isResendTestSender,
+} from "./email-addresses.ts";
+
+const base = {
+ hosted: false,
+ organizationName: "Acme Corp",
+ senderAddress: null,
+ supportAddress: null,
+};
+
+test("before a domain is set up, mail goes out from Resend's test address under the organization's name", () => {
+ assert.deepEqual(buildEmailAddresses(base), {
+ senderAddress: "Acme Corp <[email protected]>",
+ supportAddress: null,
+ });
+});
+
+test("the organization's own address gets its name in front", () => {
+ assert.deepEqual(
+ buildEmailAddresses({
+ ...base,
+ senderAddress: " [email protected] ",
+ supportAddress: " [email protected] ",
+ }),
+ {
+ senderAddress: "Acme Corp <[email protected]>",
+ supportAddress: "[email protected]",
+ },
+ );
+});
+
+test("a sender that already carries a display name is left alone", () => {
+ assert.equal(
+ buildEmailAddresses({
+ ...base,
+ senderAddress: "Acme Signing Desk <[email protected]>",
+ }).senderAddress,
+ "Acme Signing Desk <[email protected]>",
+ );
+});
+
+test("characters that mean something in an email header are dropped from the name", () => {
+ assert.equal(
+ buildEmailAddresses({
+ ...base,
+ organizationName: 'Smith, Jones & "Co" <partners>\r\nBcc: [email protected]',
+ }).senderAddress,
+ "Smith Jones & Co partners Bcc x evil.example <[email protected]>",
+ );
+});
+
+test("an install with no name, and the hosted service, send as SignuDoc", () => {
+ assert.equal(
+ buildEmailAddresses({ ...base, organizationName: null }).senderAddress,
+ "SignuDoc <[email protected]>",
+ );
+ assert.equal(
+ buildEmailAddresses({ ...base, hosted: true }).senderAddress,
+ "SignuDoc <[email protected]>",
+ );
+});
+
+test("the capture driver's fallback address is used when one is given", () => {
+ assert.equal(
+ buildEmailAddresses(base, "[email protected]").senderAddress,
+ "Acme Corp <[email protected]>",
+ );
+});
+
+test("the bare address and its domain can be read back out", () => {
+ assert.equal(
+ extractEmailAddress("Acme Corp <[email protected]>"),
+ );
+ assert.equal(extractEmailAddress(" [email protected] "), "[email protected]");
+ assert.equal(getAddressDomain("Acme Corp <[email protected]>"), "acme.com");
+ assert.equal(getAddressDomain("not an address"), null);
+ assert.equal(getAddressDomain("sign@"), null);
+});
+
+test("Resend's test address is recognized with or without a display name", () => {
+ assert.equal(isResendTestSender("[email protected]"), true);
+ assert.equal(isResendTestSender("Acme <[email protected]>"), true);
+ assert.equal(isResendTestSender("[email protected]"), false);
+ assert.equal(isResendTestSender("[email protected]"), false);
+});
diff --git a/src/lib/services/email-addresses.ts b/src/lib/services/email-addresses.ts
new file mode 100644
index 0000000..c1dfd42
--- /dev/null
+++ b/src/lib/services/email-addresses.ts
@@ -0,0 +1,86 @@
+import { SIGNUDOC_NAME } from "../branding.ts";
+
+// Which addresses email is sent from and replied to.
+//
+// Until an organization has verified its own domain with Resend, mail goes
+// out from Resend's shared testing address. Resend only delivers that mail
+// to the email address of the Resend account's owner, which is enough to try
+// the install but not to send documents to anyone else.
+// https://resend.com/docs/knowledge-base/403-error-resend-dev-domain
+
+export const RESEND_TEST_SENDER_ADDRESS = "[email protected]";
+export const RESEND_TEST_SENDER_DOMAIN = "resend.dev";
+
+export type EmailAddresses = {
+ /** The From header, with a display name. */
+ senderAddress: string;
+ /** Where replies go when a message does not say otherwise. */
+ supportAddress: string | null;
+};
+
+type EmailAddressSettings = {
+ hosted: boolean;
+ organizationName: string | null;
+ senderAddress: string | null;
+ supportAddress: string | null;
+};
+
+/** "Acme <[email protected]>" becomes "[email protected]". */
+export function extractEmailAddress(value: string): string {
+ const match = /<([^<>]+)>\s*$/.exec(value);
+
+ return (match?.[1] ?? value).trim().toLowerCase();
+}
+
+export function getAddressDomain(value: string): string | null {
+ const address = extractEmailAddress(value);
+ const separatorIndex = address.lastIndexOf("@");
+
+ if (separatorIndex <= 0 || separatorIndex === address.length - 1) {
+ return null;
+ }
+
+ return address.slice(separatorIndex + 1);
+}
+
+export function isResendTestSender(value: string): boolean {
+ return getAddressDomain(value) === RESEND_TEST_SENDER_DOMAIN;
+}
+
+// A display name goes into an email header, so anything with a meaning there
+// (quotes, angle brackets, separators, line breaks) is dropped.
+function cleanDisplayName(value: string | null): string {
+ const cleaned = (value ?? "")
+ .replace(/[\u0000-\u001f\u007f"<>()[\]\\,;:@]/g, " ")
+ .replace(/\s+/g, " ")
+ .trim()
+ .slice(0, 80);
+
+ return cleaned || SIGNUDOC_NAME;
+}
+
+function hasDisplayName(value: string): boolean {
+ return /<[^<>]+>\s*$/.test(value);
+}
+
+export function buildEmailAddresses(
+ settings: EmailAddressSettings,
+ fallbackSenderAddress: string = RESEND_TEST_SENDER_ADDRESS,
+): EmailAddresses {
+ const configuredSender = settings.senderAddress?.trim() || null;
+ const displayName = cleanDisplayName(
+ settings.hosted ? SIGNUDOC_NAME : settings.organizationName,
+ );
+ let senderAddress: string;
+
+ if (configuredSender && hasDisplayName(configuredSender)) {
+ senderAddress = configuredSender;
+ } else {
+ senderAddress = `${displayName} <${configuredSender ?? fallbackSenderAddress}>`;
+ }
+
+ return {
+ senderAddress,
+ supportAddress: settings.supportAddress?.trim() || null,
+ };
+}
diff --git a/src/lib/services/email-legal-footer.test.ts b/src/lib/services/email-legal-footer.test.ts
new file mode 100644
index 0000000..d99b808
--- /dev/null
+++ b/src/lib/services/email-legal-footer.test.ts
@@ -0,0 +1,117 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { HOSTED_BRANDING, type Branding } from "../branding.ts";
+import { withUserEmailLegalFooter } from "./email-legal-footer.ts";
+
+const env = { APP_URL: "https://sign.acme.com" };
+const body = { htmlBody: "<p>Hello</p>", textBody: "Hello" };
+
+const neutral: Branding = {
+ contactUrl: null,
+ hosted: false,
+ organizationName: "Acme Corp",
+ privacyUrl: null,
+ productName: "Acme Corp",
+ signupAvailable: true,
+ supportAddress: null,
+ termsUrl: null,
+};
+
+test("the hosted service links to its own terms, privacy and contact pages", () => {
+ const result = withUserEmailLegalFooter(body, HOSTED_BRANDING, env);
+
+ assert.equal(
+ result.textBody,
+ [
+ "Hello",
+ "",
+ "Terms of Service:",
+ "https://sign.acme.com/terms",
+ "",
+ "Privacy Policy:",
+ "https://sign.acme.com/privacy",
+ "",
+ "Contact:",
+ "https://sign.acme.com/contact",
+ ].join("\n"),
+ );
+ assert.match(
+ result.htmlBody,
+ /<a href="https:\/\/sign\.acme\.com\/terms">Terms of Service<\/a>/,
+ );
+ assert.doesNotMatch(result.textBody, /Sent by|Sent using/);
+});
+
+test("a neutral install with nothing else set says only who sent the message", () => {
+ const result = withUserEmailLegalFooter(body, neutral, env);
+
+ assert.equal(result.textBody, "Hello\n\nSent by Acme Corp using SignuDoc.");
+ assert.doesNotMatch(result.htmlBody, /<a /);
+});
+
+test("a neutral install links to the organization's own pages and support address", () => {
+ const result = withUserEmailLegalFooter(
+ body,
+ {
+ ...neutral,
+ privacyUrl: "https://acme.com/privacy",
+ supportAddress: "[email protected]",
+ termsUrl: "https://acme.com/terms",
+ },
+ env,
+ );
+
+ assert.equal(
+ result.textBody,
+ [
+ "Hello",
+ "",
+ "Terms of Service:",
+ "https://acme.com/terms",
+ "",
+ "Privacy Policy:",
+ "https://acme.com/privacy",
+ "",
+ "Questions? Contact [email protected].",
+ "",
+ "Sent by Acme Corp using SignuDoc.",
+ ].join("\n"),
+ );
+ assert.match(
+ result.htmlBody,
+ /<a href="mailto:help@acme\.com">help@acme\.com<\/a>/,
+ );
+});
+
+test("an install that has not been named yet does not invent a name", () => {
+ const result = withUserEmailLegalFooter(
+ body,
+ { ...neutral, organizationName: null, productName: "SignuDoc" },
+ env,
+ );
+
+ assert.equal(result.textBody, "Hello\n\nSent using SignuDoc.");
+});
+
+test("the organization's name and links are escaped in the HTML part", () => {
+ const result = withUserEmailLegalFooter(
+ body,
+ {
+ ...neutral,
+ organizationName: "Harbour & <Finch>",
+ termsUrl: 'https://acme.com/terms?a=1&b="2"',
+ },
+ env,
+ );
+
+ assert.match(result.htmlBody, /Sent by Harbour &amp; &lt;Finch&gt; using/);
+ assert.doesNotMatch(result.htmlBody, /<Finch>/);
+ assert.doesNotMatch(result.htmlBody, /b="2"/);
+ // The plain-text part is not HTML and carries the name as it is.
+ assert.match(result.textBody, /Sent by Harbour & <Finch> using SignuDoc\./);
+});
+
+test("a neutral install with no links does not need to know its own URL", () => {
+ assert.doesNotThrow(() => withUserEmailLegalFooter(body, neutral, {}));
+});
diff --git a/src/lib/services/email-legal-footer.ts b/src/lib/services/email-legal-footer.ts
index 43f798a..a40c8d0 100644
--- a/src/lib/services/email-legal-footer.ts
+++ b/src/lib/services/email-legal-footer.ts
@@ -1,4 +1,4 @@
-import { publicLegalLinks } from "../legal.ts";
+import { SIGNUDOC_NAME, type Branding } from "../branding.ts";
import { getEnv, type EnvSource } from "../utils/env.ts";
import { escapeHtml } from "../utils/html.ts";
import { requireConfigValue } from "./service-config.ts";
@@ -8,38 +8,84 @@ type EmailBodyContent = {
textBody: string;
};
-function getAbsoluteLegalLinks(env: EnvSource = process.env) {
+type FooterLink = {
+ label: string;
+ url: string;
+};
+
+// Links may be pages on this site ("/terms") or the organization's own
+// absolute URLs. Either way the email gets an absolute URL.
+function buildFooterLinks(branding: Branding, env: EnvSource): FooterLink[] {
+ const candidates: Array<[label: string, url: string | null]> = [
+ ["Terms of Service", branding.termsUrl],
+ ["Privacy Policy", branding.privacyUrl],
+ ["Contact", branding.contactUrl],
+ ];
+ const links = candidates.filter((candidate): candidate is [string, string] =>
+ Boolean(candidate[1]),
+ );
+
+ if (links.length === 0) {
+ return [];
+ }
+
const appUrl = requireConfigValue("app", "APP_URL", getEnv(env).appUrl);
- return publicLegalLinks.map((link) => ({
- ...link,
- url: new URL(link.href, appUrl).toString(),
+ return links.map(([label, url]) => ({
+ label,
+ url: new URL(url, appUrl).toString(),
}));
}
+/**
+ * Appends the footer every email to a person carries: the install's terms,
+ * privacy and contact links, where it has them. On a neutral install the
+ * footer also names the organization's support address and says the message
+ * was sent with SignuDoc.
+ */
export function withUserEmailLegalFooter(
input: EmailBodyContent,
+ branding: Branding,
env: EnvSource = process.env,
): EmailBodyContent {
- const [termsLink, privacyLink, contactLink] = getAbsoluteLegalLinks(env);
- const textFooter = [
- "",
- "Terms of Service:",
- termsLink.url,
- "",
- "Privacy Policy:",
- privacyLink.url,
- "",
- "Contact:",
- contactLink.url,
- ].join("\n");
+ const links = buildFooterLinks(branding, env);
+ const textLines: string[] = [];
+ const htmlLines: string[] = [];
+
+ for (const link of links) {
+ textLines.push("", `${link.label}:`, link.url);
+ htmlLines.push(`<a href="${escapeHtml(link.url)}">${link.label}</a>`);
+ }
+
+ if (!branding.hosted) {
+ if (branding.supportAddress) {
+ textLines.push("", `Questions? Contact ${branding.supportAddress}.`);
+ htmlLines.push(
+ `Questions? Contact <a href="mailto:${escapeHtml(branding.supportAddress)}">${escapeHtml(branding.supportAddress)}</a>.`,
+ );
+ }
+
+ const sentBy = branding.organizationName
+ ? `Sent by ${branding.organizationName} using ${SIGNUDOC_NAME}.`
+ : `Sent using ${SIGNUDOC_NAME}.`;
+
+ textLines.push("", sentBy);
+ htmlLines.push(escapeHtml(sentBy));
+ }
+
+ if (htmlLines.length === 0) {
+ return input;
+ }
+
const htmlFooter = [
'<hr style="margin:24px 0;border:none;border-top:1px solid #e2e2e2;" />',
- `<p><a href="${escapeHtml(termsLink.url)}">${termsLink.longLabel}</a><br /><a href="${escapeHtml(privacyLink.url)}">${privacyLink.longLabel}</a><br /><a href="${escapeHtml(contactLink.url)}">${contactLink.longLabel}</a></p>`,
+ `<p>${htmlLines.join("<br />")}</p>`,
].join("");
return {
htmlBody: `${input.htmlBody}${htmlFooter}`,
- textBody: `${input.textBody}${textFooter}`,
+ // Each entry starts with an empty line; one more newline puts that
+ // empty line between the message and the footer.
+ textBody: `${input.textBody}\n${textLines.join("\n")}`,
};
}
diff --git a/src/lib/services/email.ts b/src/lib/services/email.ts
index eecdb14..6d254a4 100644
--- a/src/lib/services/email.ts
+++ b/src/lib/services/email.ts
@@ -4,19 +4,19 @@ import path from "node:path";
import { Resend } from "resend";
+import { getSettings } from "../settings.ts";
import { type EmailTemplateKind } from "../types/domain.ts";
import { getEnv, isLocalDeployment, type EnvSource } from "../utils/env.ts";
+import { buildEmailAddresses, type EmailAddresses } from "./email-addresses.ts";
import { assertServiceConfig } from "./service-config.ts";
-const EMAIL_ENV_KEYS = [
- "RESEND_API_KEY",
- "RESEND_FROM_EMAIL",
- "SUPPORT_EMAIL",
-] as const;
+// The addresses mail is sent from and replied to are not needed here: they
+// come from RESEND_FROM_EMAIL and SUPPORT_EMAIL when those are set, and from
+// the install's settings otherwise, and are looked up when a message is sent.
+const EMAIL_ENV_KEYS = ["RESEND_API_KEY"] as const;
const DEFAULT_CAPTURE_DIR = ".data/outbox";
-const DEFAULT_CAPTURE_SENDER_ADDRESS = "SignuDoc <[email protected]>";
-const DEFAULT_CAPTURE_SUPPORT_ADDRESS = "[email protected]";
+const DEFAULT_CAPTURE_SENDER_ADDRESS = "[email protected]";
export type EmailDriver = "capture" | "resend";
@@ -41,6 +41,8 @@ export type EmailSendOptions = {
type CreateEmailServiceOptions = {
env?: EnvSource;
+ /** Replaced in tests, where there is no database to read settings from. */
+ resolveAddresses?: () => Promise<EmailAddresses>;
resendClient?: Resend;
};
@@ -67,15 +69,12 @@ function buildResendOptions(options?: EmailSendOptions) {
function buildResendPayload(
message: TransactionalEmailMessage,
- config: {
- senderAddress: string;
- supportAddress: string;
- },
+ config: EmailAddresses,
) {
return {
from: config.senderAddress,
html: message.htmlBody,
- replyTo: message.replyTo ?? config.supportAddress,
+ replyTo: message.replyTo ?? config.supportAddress ?? undefined,
subject: message.subject,
tags: [
{
@@ -119,7 +118,10 @@ export function resolveEmailDriver(env: EnvSource = process.env): EmailDriver {
* Development and test driver: nothing is sent. Each message is written as a
* JSON file so a person (or the end-to-end test) can read the links in it.
*/
-function createCaptureEmailService(env: EnvSource): EmailService {
+function createCaptureEmailService(
+ env: EnvSource,
+ resolveAddresses: () => Promise<EmailAddresses>,
+): EmailService {
// Allowed in development, and for a production build that is being run on
// localhost (which is what the end-to-end test does). Never on a real site.
if (env.NODE_ENV === "production" && !isLocalDeployment(env)) {
@@ -128,21 +130,17 @@ function createCaptureEmailService(env: EnvSource): EmailService {
);
}
- const emailEnv = getEnv(env).email;
// The comment stops Turbopack from tracing the whole project into the
// server bundle because of a path it cannot analyse.
const captureDir = path.resolve(
/*turbopackIgnore: true*/ env.EMAIL_CAPTURE_DIR?.trim() ||
DEFAULT_CAPTURE_DIR,
);
- const config = {
- senderAddress: emailEnv.senderAddress ?? DEFAULT_CAPTURE_SENDER_ADDRESS,
- supportAddress: emailEnv.supportAddress ?? DEFAULT_CAPTURE_SUPPORT_ADDRESS,
- };
async function capture(
message: TransactionalEmailMessage,
): Promise<EmailDeliveryResult> {
+ const config = await resolveAddresses();
const messageId = `capture-${randomUUID()}`;
const filePath = path.join(
/*turbopackIgnore: true*/ captureDir,
@@ -193,25 +191,35 @@ function createCaptureEmailService(env: EnvSource): EmailService {
};
}
+/** The addresses this install sends from, as configured right now. */
+export async function resolveEmailAddresses(
+ env: EnvSource = process.env,
+): Promise<EmailAddresses> {
+ const settings = await getSettings(env);
+
+ return resolveEmailDriver(env) === "capture"
+ ? buildEmailAddresses(settings, DEFAULT_CAPTURE_SENDER_ADDRESS)
+ : buildEmailAddresses(settings);
+}
+
export function createEmailService({
env = process.env,
+ resolveAddresses = () => resolveEmailAddresses(env),
resendClient,
}: CreateEmailServiceOptions = {}): EmailService {
if (!resendClient && resolveEmailDriver(env) === "capture") {
- return createCaptureEmailService(env);
+ return createCaptureEmailService(env, resolveAddresses);
}
- assertServiceConfig("email", EMAIL_ENV_KEYS, env);
+ if (!resendClient) {
+ assertServiceConfig("email", EMAIL_ENV_KEYS, env);
+ }
- const emailEnv = getEnv(env).email;
- const client = resendClient ?? new Resend(emailEnv.apiKey!);
- const config = {
- senderAddress: emailEnv.senderAddress!,
- supportAddress: emailEnv.supportAddress!,
- };
+ const client = resendClient ?? new Resend(getEnv(env).email.apiKey!);
return {
async send(message, options) {
+ const config = await resolveAddresses();
const { data, error } = await client.emails.send(
buildResendPayload(message, config),
buildResendOptions(options),
@@ -233,6 +241,7 @@ export function createEmailService({
return [];
}
+ const config = await resolveAddresses();
const { data, error } = await client.batch.send(
messages.map((message) => buildResendPayload(message, config)),
buildResendOptions(options),
diff --git a/src/lib/services/signing-invitation-email.ts b/src/lib/services/signing-invitation-email.ts
index 5b90079..76ef743 100644
--- a/src/lib/services/signing-invitation-email.ts
+++ b/src/lib/services/signing-invitation-email.ts
@@ -1,8 +1,10 @@
+import { type Branding } from "../branding.ts";
import { escapeHtml } from "../utils/html.ts";
import { withUserEmailLegalFooter } from "./email-legal-footer.ts";
import { type TransactionalEmailMessage } from "./email.ts";
type SigningInvitationEmailInput = {
+ branding: Branding;
envelopeTitle: string;
senderName: string;
signerEmail: string;
@@ -13,29 +15,33 @@ type SigningInvitationEmailInput = {
export function buildSigningInvitationEmail(
input: SigningInvitationEmailInput,
): TransactionalEmailMessage {
+ const { productName } = input.branding;
const subject = `${input.senderName} requested your signature on "${input.envelopeTitle}"`;
const textBody = [
`Hi ${input.signerName},`,
"",
- `${input.senderName} sent you "${input.envelopeTitle}" through SignuDoc.`,
+ `${input.senderName} sent you "${input.envelopeTitle}" through ${productName}.`,
"",
"Review and sign the document here:",
input.signingUrl,
"",
- "You do not need a SignuDoc account to sign.",
+ `You do not need a ${productName} account to sign.`,
"If you receive a newer invitation or reminder link, use the newest one.",
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
- `<p>${escapeHtml(input.senderName)} sent you &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; through SignuDoc.</p>`,
+ `<p>${escapeHtml(input.senderName)} sent you &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; through ${escapeHtml(productName)}.</p>`,
`<p><a href="${escapeHtml(input.signingUrl)}">Review and sign the document</a></p>`,
- "<p>You do not need a SignuDoc account to sign.</p>",
+ `<p>You do not need a ${escapeHtml(productName)} account to sign.</p>`,
"<p>If you receive a newer invitation or reminder link, use the newest one.</p>",
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
new file mode 100644
index 0000000..d45d665
--- /dev/null
+++ b/src/lib/settings.test.ts
@@ -0,0 +1,115 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { buildBranding } from "./branding.ts";
+import {
+ isMissingSchemaError,
+ resolveSettings,
+ type AppSettings,
+} from "./settings.ts";
+
+const stored: AppSettings = {
+ allowedEmailDomains: ["acme.com"],
+ emailReadyAt: null,
+ organizationName: "Acme Corp",
+ privacyUrl: "https://acme.com/privacy",
+ senderAddress: "[email protected]",
+ setupCompletedAt: 1_800_000_000,
+ signupMode: "domains",
+ supportAddress: "[email protected]",
+ termsUrl: "https://acme.com/terms",
+};
+
+test("an install with no settings row behaves as it did before settings existed", () => {
+ const settings = resolveSettings(null, {});
+
+ assert.equal(settings.signupMode, "open");
+ assert.equal(settings.organizationName, null);
+ assert.equal(settings.senderAddress, null);
+ assert.equal(settings.hosted, false);
+});
+
+test("stored settings are used as they are when the environment says nothing", () => {
+ const settings = resolveSettings(stored, {});
+
+ assert.equal(settings.senderAddress, "[email protected]");
+ assert.equal(settings.senderAddressFromEnv, false);
+ assert.equal(settings.supportAddress, "[email protected]");
+ assert.equal(settings.supportAddressFromEnv, false);
+});
+
+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]",
+ });
+
+ assert.equal(settings.senderAddress, "SignuDoc <[email protected]>");
+ assert.equal(settings.senderAddressFromEnv, true);
+ assert.equal(settings.supportAddress, "[email protected]");
+ assert.equal(settings.supportAddressFromEnv, true);
+});
+
+test("hosted mode is switched on by HOSTED_MODE", () => {
+ assert.equal(resolveSettings(null, { HOSTED_MODE: "1" }).hosted, true);
+ assert.equal(resolveSettings(null, { HOSTED_MODE: "true" }).hosted, true);
+ assert.equal(resolveSettings(null, { HOSTED_MODE: "0" }).hosted, false);
+ assert.equal(resolveSettings(null, { HOSTED_MODE: "" }).hosted, false);
+});
+
+test("a neutral install goes by the organization's name and links", () => {
+ assert.deepEqual(buildBranding(resolveSettings(stored, {})), {
+ contactUrl: null,
+ hosted: false,
+ organizationName: "Acme Corp",
+ privacyUrl: "https://acme.com/privacy",
+ productName: "Acme Corp",
+ signupAvailable: true,
+ supportAddress: "[email protected]",
+ termsUrl: "https://acme.com/terms",
+ });
+});
+
+test("a neutral install with no name yet goes by SignuDoc and has no legal links", () => {
+ const branding = buildBranding(resolveSettings(null, {}));
+
+ assert.equal(branding.productName, "SignuDoc");
+ assert.equal(branding.organizationName, null);
+ assert.equal(branding.termsUrl, null);
+ assert.equal(branding.privacyUrl, null);
+ assert.equal(branding.contactUrl, null);
+});
+
+test("hosted mode keeps SignuDoc's own name and pages whatever is stored", () => {
+ const branding = buildBranding(resolveSettings(stored, { HOSTED_MODE: "1" }));
+
+ assert.equal(branding.hosted, true);
+ assert.equal(branding.productName, "SignuDoc");
+ assert.equal(branding.organizationName, null);
+ assert.equal(branding.termsUrl, "/terms");
+ assert.equal(branding.privacyUrl, "/privacy");
+ assert.equal(branding.contactUrl, "/contact");
+ assert.equal(branding.supportAddress, "[email protected]");
+});
+
+test("sign-up is offered only when someone could actually sign up", () => {
+ const available = (update: Partial<AppSettings>) =>
+ buildBranding(resolveSettings({ ...stored, ...update }, {}))
+ .signupAvailable;
+
+ assert.equal(available({ signupMode: "open" }), true);
+ assert.equal(available({ signupMode: "domains" }), true);
+ assert.equal(
+ available({ allowedEmailDomains: [], signupMode: "domains" }),
+ false,
+ );
+ assert.equal(available({ signupMode: "closed" }), false);
+});
+
+test("a missing table or column is recognized, other failures are not", () => {
+ assert.equal(isMissingSchemaError({ code: "42P01" }), true);
+ assert.equal(isMissingSchemaError({ code: "42703" }), true);
+ assert.equal(isMissingSchemaError({ code: "23505" }), false);
+ assert.equal(isMissingSchemaError(new Error("connection refused")), false);
+ assert.equal(isMissingSchemaError(null), false);
+});
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
new file mode 100644
index 0000000..7bb2ec6
--- /dev/null
+++ b/src/lib/settings.ts
@@ -0,0 +1,375 @@
+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 { getEnv, isHostedMode, type EnvSource } from "./utils/env.ts";
+
+// Install-wide settings: one row in app_settings, written by the first-run
+// setup page and by an administrator in Settings.
+//
+// Environment variables win over the row (RESEND_FROM_EMAIL, SUPPORT_EMAIL),
+// so a deployment that was configured that way before settings existed keeps
+// working without anyone touching it.
+
+/** What is stored. Null means "not set". */
+export type AppSettings = {
+ allowedEmailDomains: string[];
+ emailReadyAt: number | null;
+ organizationName: string | null;
+ privacyUrl: string | null;
+ senderAddress: string | null;
+ setupCompletedAt: number | null;
+ signupMode: SignupMode;
+ supportAddress: string | null;
+ termsUrl: string | null;
+};
+
+/** What the app should use: the stored row with environment overrides applied. */
+export type ResolvedSettings = AppSettings & {
+ hosted: boolean;
+ senderAddressFromEnv: boolean;
+ supportAddressFromEnv: boolean;
+};
+
+export type SettingsUpdate = Partial<AppSettings>;
+
+/**
+ * Where an install stands on first-run setup.
+ *
+ * - complete: someone is the administrator.
+ * - fresh: nobody has an account and setup has never run. The first visitor
+ * may claim the install.
+ * - unclaimed: accounts exist (or setup ran once) but nobody is the
+ * administrator. Claiming it needs SETUP_TOKEN.
+ * - unmigrated: the database does not have this version's tables yet.
+ */
+export type SetupState = {
+ status: "complete" | "fresh" | "unclaimed" | "unmigrated";
+};
+
+type AppSettingsRow = {
+ allowed_email_domains: string[] | null;
+ email_ready_at: number | null;
+ organization_name: string | null;
+ privacy_url: string | null;
+ sender_address: string | null;
+ setup_completed_at: number | null;
+ signup_mode: SignupMode;
+ support_address: string | null;
+ terms_url: string | null;
+};
+
+const SETTINGS_COLUMNS = `
+ allowed_email_domains,
+ email_ready_at,
+ organization_name,
+ privacy_url,
+ sender_address,
+ setup_completed_at,
+ signup_mode,
+ support_address,
+ terms_url
+`;
+
+// How an install behaves before it has a settings row. This is what the app
+// did before settings existed, so an upgraded deployment does not change
+// until someone decides otherwise.
+const UNSET_SETTINGS: AppSettings = {
+ allowedEmailDomains: [],
+ emailReadyAt: null,
+ organizationName: null,
+ privacyUrl: null,
+ senderAddress: null,
+ setupCompletedAt: null,
+ signupMode: "open",
+ supportAddress: null,
+ termsUrl: null,
+};
+
+// Other instances pick up a change within this time; the instance that made
+// the change sees it at once.
+const SETTINGS_CACHE_MS = 30_000;
+const SETUP_COMPLETE_CACHE_MS = 60_000;
+
+type SettingsCache = {
+ settings: { expiresAt: number; value: AppSettings | null } | null;
+ setupCompleteUntil: number;
+};
+
+declare global {
+ var __signudocSettingsCache: SettingsCache | undefined;
+}
+
+// Kept on globalThis, like the rate limit store, so every copy of this
+// module in one process shares it and a change clears it for all of them.
+const cache: SettingsCache = (globalThis.__signudocSettingsCache ??= {
+ settings: null,
+ setupCompleteUntil: 0,
+});
+
+export function invalidateSettingsCache() {
+ cache.settings = null;
+ cache.setupCompleteUntil = 0;
+}
+
+/**
+ * True when a query failed because a table or column from a newer migration
+ * is not there. That happens on a preview deployment that shares a database
+ * with production, and on a first deployment whose build ran before the
+ * database was connected.
+ */
+export function isMissingSchemaError(error: unknown): boolean {
+ const code =
+ typeof error === "object" && error !== null && "code" in error
+ ? (error as { code?: unknown }).code
+ : undefined;
+
+ return code === "42P01" || code === "42703";
+}
+
+function mapSettingsRow(row: AppSettingsRow): AppSettings {
+ return {
+ allowedEmailDomains: row.allowed_email_domains ?? [],
+ emailReadyAt: row.email_ready_at,
+ organizationName: row.organization_name,
+ privacyUrl: row.privacy_url,
+ senderAddress: row.sender_address,
+ setupCompletedAt: row.setup_completed_at,
+ signupMode: row.signup_mode,
+ supportAddress: row.support_address,
+ termsUrl: row.terms_url,
+ };
+}
+
+/** Reads the stored row. Null when there is none (or no table for it yet). */
+export async function readStoredSettings(
+ database: DbExecutor = getDb(),
+): Promise<AppSettings | null> {
+ try {
+ const row = await queryOne<AppSettingsRow>(
+ database,
+ `select ${SETTINGS_COLUMNS} from public.app_settings where id`,
+ );
+
+ return row ? mapSettingsRow(row) : null;
+ } catch (error) {
+ if (isMissingSchemaError(error)) {
+ return null;
+ }
+
+ throw error;
+ }
+}
+
+async function getStoredSettings(): Promise<AppSettings | null> {
+ const now = Date.now();
+
+ if (cache.settings && cache.settings.expiresAt > now) {
+ return cache.settings.value;
+ }
+
+ const value = await readStoredSettings();
+
+ cache.settings = { expiresAt: now + SETTINGS_CACHE_MS, value };
+
+ return value;
+}
+
+export function resolveSettings(
+ stored: AppSettings | null,
+ env: EnvSource = process.env,
+): ResolvedSettings {
+ const emailEnv = getEnv(env).email;
+ const settings = stored ?? UNSET_SETTINGS;
+
+ return {
+ ...settings,
+ hosted: isHostedMode(env),
+ senderAddress: emailEnv.senderAddress ?? settings.senderAddress,
+ senderAddressFromEnv: emailEnv.senderAddress !== undefined,
+ supportAddress: emailEnv.supportAddress ?? settings.supportAddress,
+ supportAddressFromEnv: emailEnv.supportAddress !== undefined,
+ };
+}
+
+/** The settings the app should use right now. Cached for a short time. */
+export async function getSettings(
+ env: EnvSource = process.env,
+): Promise<ResolvedSettings> {
+ return resolveSettings(await getStoredSettings(), env);
+}
+
+/** What this install calls itself, for pages and emails. */
+export async function getBranding(
+ env: EnvSource = process.env,
+): Promise<Branding> {
+ return buildBranding(await getSettings(env));
+}
+
+export function toSignupPolicy(settings: AppSettings): SignupPolicy {
+ return {
+ allowedEmailDomains: settings.allowedEmailDomains,
+ signupMode: settings.signupMode,
+ };
+}
+
+/**
+ * Writes settings, creating the row if there is none. Only the fields given
+ * are changed. Changing the sender address clears the "email works" mark,
+ * because that mark was earned by the old address.
+ */
+export async function saveSettings(
+ update: SettingsUpdate,
+ database: DbExecutor = getDb(),
+): Promise<AppSettings> {
+ const current = (await readStoredSettings(database)) ?? {
+ ...UNSET_SETTINGS,
+ // A row that is being created is a decision about this install, and the
+ // safe starting point for sign-up is closed, not open.
+ signupMode: "closed" as const,
+ };
+ const next: AppSettings = { ...current, ...update };
+
+ if (
+ update.senderAddress !== undefined &&
+ update.senderAddress !== current.senderAddress &&
+ update.emailReadyAt === undefined
+ ) {
+ next.emailReadyAt = null;
+ }
+
+ const now = Math.floor(Date.now() / 1000);
+ const row = await queryOne<AppSettingsRow>(
+ database,
+ `
+ insert into public.app_settings (
+ id,
+ allowed_email_domains,
+ email_ready_at,
+ organization_name,
+ privacy_url,
+ sender_address,
+ setup_completed_at,
+ signup_mode,
+ support_address,
+ terms_url,
+ created_at,
+ updated_at
+ )
+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10)
+ on conflict (id) do update set
+ allowed_email_domains = excluded.allowed_email_domains,
+ email_ready_at = excluded.email_ready_at,
+ organization_name = excluded.organization_name,
+ privacy_url = excluded.privacy_url,
+ sender_address = excluded.sender_address,
+ setup_completed_at = excluded.setup_completed_at,
+ signup_mode = excluded.signup_mode,
+ support_address = excluded.support_address,
+ terms_url = excluded.terms_url,
+ updated_at = excluded.updated_at
+ returning ${SETTINGS_COLUMNS}
+ `,
+ [
+ next.allowedEmailDomains,
+ next.emailReadyAt,
+ next.organizationName,
+ next.privacyUrl,
+ next.senderAddress,
+ next.setupCompletedAt,
+ next.signupMode,
+ next.supportAddress,
+ next.termsUrl,
+ now,
+ ],
+ );
+
+ invalidateSettingsCache();
+
+ return row ? mapSettingsRow(row) : next;
+}
+
+/**
+ * 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.
+ */
+export async function markEmailReady(
+ ready: boolean,
+ database: DbExecutor = getDb(),
+): Promise<void> {
+ const now = Math.floor(Date.now() / 1000);
+
+ await database.query(
+ `
+ update public.app_settings
+ set email_ready_at = $1, updated_at = $2
+ where id and (email_ready_at is null) = $3
+ `,
+ [ready ? now : null, now, ready],
+ );
+
+ invalidateSettingsCache();
+}
+
+type SetupStateRow = {
+ has_admin: boolean;
+ has_users: boolean;
+ setup_completed_at: number | null;
+};
+
+/** Reads the setup state straight from the database, with no caching. */
+export async function readSetupState(
+ database: DbExecutor = getDb(),
+): Promise<SetupState> {
+ try {
+ const row = await queryOne<SetupStateRow>(
+ database,
+ `
+ select
+ exists (select 1 from public."user" where role = 'admin') as has_admin,
+ exists (select 1 from public."user") as has_users,
+ (select setup_completed_at from public.app_settings where id)
+ as setup_completed_at
+ `,
+ );
+
+ if (row?.has_admin) {
+ return { status: "complete" };
+ }
+
+ if (!row?.has_users && (row?.setup_completed_at ?? null) === null) {
+ return { status: "fresh" };
+ }
+
+ return { status: "unclaimed" };
+ } catch (error) {
+ if (isMissingSchemaError(error)) {
+ return { status: "unmigrated" };
+ }
+
+ throw error;
+ }
+}
+
+/**
+ * Where this install stands on first-run setup. "Complete" is remembered for
+ * a minute, so pages on a set-up install do not ask the database every time.
+ */
+export async function getSetupState(): Promise<SetupState> {
+ if (cache.setupCompleteUntil > Date.now()) {
+ return { status: "complete" };
+ }
+
+ const state = await readSetupState();
+
+ if (state.status === "complete") {
+ cache.setupCompleteUntil = Date.now() + SETUP_COMPLETE_CACHE_MS;
+ }
+
+ return state;
+}
+
+/** 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/signing.ts b/src/lib/signing.ts
index b52820b..e8117a3 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -1,6 +1,7 @@
import { Buffer } from "node:buffer";
import { randomUUID } from "node:crypto";
+import { type Branding } from "./branding.ts";
import {
type DbExecutor,
type DbPool,
@@ -31,6 +32,7 @@ import {
type SigningUnavailableResponse,
} from "./schemas/signing.ts";
import { declineEnvelopeSchema, signerRecordSchema } from "./schemas/signer.ts";
+import { getBranding } from "./settings.ts";
import {
listAuditEventsForEnvelope,
recordAuditEvent,
@@ -241,6 +243,7 @@ const RECIPIENT_DOWNLOAD_LINK_TTL_DAYS =
RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS / (24 * 60 * 60);
function buildCompletionSenderEmail(input: {
+ branding: Branding;
envelopeId: string;
envelopeTitle: string;
senderEmail: string;
@@ -251,7 +254,7 @@ function buildCompletionSenderEmail(input: {
const textBody = [
`Hi ${input.senderName},`,
"",
- `"${input.envelopeTitle}" has been fully signed in SignuDoc.`,
+ `"${input.envelopeTitle}" has been fully signed in ${input.branding.productName}.`,
"The final signed PDF and certificate are ready in your dashboard.",
"",
"Review the completed envelope:",
@@ -259,14 +262,17 @@ function buildCompletionSenderEmail(input: {
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.senderName)},</p>`,
- `<p>&ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; has been fully signed in SignuDoc.</p>`,
+ `<p>&ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; has been fully signed in ${escapeHtml(input.branding.productName)}.</p>`,
"<p>The final signed PDF and certificate are ready in your dashboard.</p>",
`<p><a href="${escapeHtml(completedUrl)}">Review the completed envelope</a></p>`,
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
@@ -278,6 +284,7 @@ function buildCompletionSenderEmail(input: {
}
function buildDeclineNotificationEmail(input: {
+ branding: Branding;
declineReason?: string;
envelopeId: string;
envelopeTitle: string;
@@ -294,7 +301,7 @@ function buildDeclineNotificationEmail(input: {
const textBody = [
`Hi ${input.senderName},`,
"",
- `${input.signerName} (${input.signerEmail}) declined "${input.envelopeTitle}" in SignuDoc.`,
+ `${input.signerName} (${input.signerEmail}) declined "${input.envelopeTitle}" in ${input.branding.productName}.`,
...(reasonLine ? ["", reasonLine] : []),
"",
"Review the envelope:",
@@ -302,16 +309,19 @@ function buildDeclineNotificationEmail(input: {
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.senderName)},</p>`,
- `<p>${escapeHtml(input.signerName)} (${escapeHtml(input.signerEmail)}) declined &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; in SignuDoc.</p>`,
+ `<p>${escapeHtml(input.signerName)} (${escapeHtml(input.signerEmail)}) declined &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; in ${escapeHtml(input.branding.productName)}.</p>`,
reasonLine
? `<p><strong>Reason provided:</strong> ${escapeHtml(input.declineReason!.trim())}</p>`
: "",
`<p><a href="${escapeHtml(envelopeUrl)}">Review the envelope</a></p>`,
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
@@ -323,6 +333,7 @@ function buildDeclineNotificationEmail(input: {
}
function buildCompletionSignerEmail(input: {
+ branding: Branding;
evidenceDownloadUrl: string;
envelopeId: string;
envelopeTitle: string;
@@ -335,7 +346,7 @@ function buildCompletionSignerEmail(input: {
const textBody = [
`Hi ${input.signerName},`,
"",
- `"${input.envelopeTitle}" from ${input.senderName} has been fully signed in SignuDoc.`,
+ `"${input.envelopeTitle}" from ${input.senderName} has been fully signed in ${input.branding.productName}.`,
"The completed document and redacted certificate are ready.",
"",
`Download links (available for ${RECIPIENT_DOWNLOAD_LINK_TTL_DAYS} days):`,
@@ -344,15 +355,18 @@ function buildCompletionSignerEmail(input: {
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
- `<p>&ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; from ${escapeHtml(input.senderName)} has been fully signed in SignuDoc.</p>`,
+ `<p>&ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; from ${escapeHtml(input.senderName)} has been fully signed in ${escapeHtml(input.branding.productName)}.</p>`,
"<p>The completed document and redacted certificate are ready.</p>",
`<p>Download links are available for ${RECIPIENT_DOWNLOAD_LINK_TTL_DAYS} days.</p>`,
`<p><a href="${escapeHtml(input.signedDownloadUrl)}">Download signed PDF</a><br /><a href="${escapeHtml(input.evidenceDownloadUrl)}">Download redacted certificate</a></p>`,
].join("");
- const legalFooter = withUserEmailLegalFooter({
- htmlBody,
- textBody,
- });
+ const legalFooter = withUserEmailLegalFooter(
+ {
+ htmlBody,
+ textBody,
+ },
+ input.branding,
+ );
return {
htmlBody: legalFooter.htmlBody,
@@ -838,6 +852,7 @@ async function sendCompletionEmails(input: {
}) {
const senderName = normalizeSenderName(input.sender);
const issuedAt = Math.floor(Date.now() / 1000);
+ const branding = await getBranding();
const signerMessages = await Promise.all(
input.signers.map(async (signer) => {
if (!signer.id) {
@@ -874,6 +889,7 @@ async function sendCompletionEmails(input: {
]);
return buildCompletionSignerEmail({
+ branding,
envelopeId: input.envelopeId,
envelopeTitle: input.envelopeTitle,
evidenceDownloadUrl: redactedEvidenceLink.url,
@@ -886,6 +902,7 @@ async function sendCompletionEmails(input: {
);
const messages = [
buildCompletionSenderEmail({
+ branding,
envelopeId: input.envelopeId,
envelopeTitle: input.envelopeTitle,
senderEmail: input.sender.email,
@@ -1420,6 +1437,7 @@ export async function submitSigningForToken(
try {
await emailService.send(
buildSigningInvitationEmail({
+ branding: await getBranding(),
envelopeTitle: context.envelope.title,
senderName: normalizeSenderName(context.sender),
signerEmail: nextSigner.email,
@@ -1844,6 +1862,7 @@ export async function declineSigningForToken(
try {
await emailService.send(
buildDeclineNotificationEmail({
+ branding: await getBranding(),
declineReason,
envelopeId: context.envelope.id,
envelopeTitle: context.envelope.title,
diff --git a/src/lib/signup-policy.test.ts b/src/lib/signup-policy.test.ts
new file mode 100644
index 0000000..0f998d0
--- /dev/null
+++ b/src/lib/signup-policy.test.ts
@@ -0,0 +1,123 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ describeSignupPolicy,
+ evaluateSignup,
+ getEmailDomain,
+ normalizeEmailDomain,
+ parseEmailDomainList,
+ suggestSignupPolicy,
+} from "./signup-policy.ts";
+
+test("a domain is tidied up, and anything else is turned away", () => {
+ assert.equal(normalizeEmailDomain(" @Acme.com "), "acme.com");
+ assert.equal(normalizeEmailDomain("mail.acme.co.uk"), "mail.acme.co.uk");
+ assert.equal(normalizeEmailDomain("acme"), null);
+ assert.equal(normalizeEmailDomain("[email protected]"), null);
+ assert.equal(normalizeEmailDomain("-acme.com"), null);
+ assert.equal(normalizeEmailDomain("*.acme.com"), null);
+ assert.equal(normalizeEmailDomain(""), null);
+});
+
+test("the domain of an address is whatever follows the last @", () => {
+ assert.equal(getEmailDomain("[email protected]"), "acme.com");
+ assert.equal(getEmailDomain('"odd@name"@acme.com'), "acme.com");
+ assert.equal(getEmailDomain("@acme.com"), null);
+ assert.equal(getEmailDomain("jane"), null);
+});
+
+test("a typed list of domains is split, cleaned and de-duplicated", () => {
+ assert.deepEqual(
+ parseEmailDomainList("acme.com, @Acme.com;\n acme.co.uk not a domain"),
+ {
+ domains: ["acme.co.uk", "acme.com"],
+ invalid: ["not", "a", "domain"],
+ },
+ );
+ assert.deepEqual(parseEmailDomainList(""), { domains: [], invalid: [] });
+});
+
+test("a new install starts with the administrator's own domain", () => {
+ assert.deepEqual(suggestSignupPolicy("[email protected]"), {
+ allowedEmailDomains: ["acme.com"],
+ signupMode: "domains",
+ });
+});
+
+test("a public mailbox domain does not open the install to everyone at it", () => {
+ for (const email of ["[email protected]", "[email protected]", "[email protected]"]) {
+ assert.deepEqual(suggestSignupPolicy(email), {
+ allowedEmailDomains: [],
+ signupMode: "closed",
+ });
+ }
+});
+
+test("open sign-up takes anyone", () => {
+ assert.deepEqual(
+ evaluateSignup("[email protected]", {
+ allowedEmailDomains: [],
+ signupMode: "open",
+ }),
+ { allowed: true },
+ );
+});
+
+test("domain sign-up takes addresses at the listed domains and no others", () => {
+ const policy = {
+ allowedEmailDomains: ["acme.com", "acme.co.uk"],
+ signupMode: "domains" as const,
+ };
+
+ assert.deepEqual(evaluateSignup("[email protected]", policy), { allowed: true });
+ assert.deepEqual(evaluateSignup("[email protected]", policy), { allowed: true });
+
+ // A subdomain, a look-alike and a domain hidden in the local part are
+ // all somewhere else.
+ for (const email of [
+ "not an address",
+ ]) {
+ assert.deepEqual(evaluateSignup(email, policy), {
+ allowed: false,
+ code: "signup_domain_not_allowed",
+ message:
+ "Accounts can be created with an email address at @acme.com or @acme.co.uk.",
+ });
+ }
+});
+
+test("closed sign-up takes nobody, and so does a domain rule with no domains", () => {
+ for (const policy of [
+ { allowedEmailDomains: ["acme.com"], signupMode: "closed" as const },
+ { allowedEmailDomains: [], signupMode: "domains" as const },
+ ]) {
+ assert.deepEqual(evaluateSignup("[email protected]", policy), {
+ allowed: false,
+ code: "signup_closed",
+ message: "New accounts are not being accepted.",
+ });
+ }
+});
+
+test("the rule is described in one sentence", () => {
+ assert.equal(
+ describeSignupPolicy({ allowedEmailDomains: [], signupMode: "open" }),
+ "Anyone can create an account.",
+ );
+ assert.equal(
+ describeSignupPolicy({
+ allowedEmailDomains: ["a.com", "b.com", "c.com"],
+ signupMode: "domains",
+ }),
+ "Accounts can be created with an email address at @a.com, @b.com or @c.com.",
+ );
+ assert.equal(
+ describeSignupPolicy({ allowedEmailDomains: [], signupMode: "closed" }),
+ "New accounts are not being accepted.",
+ );
+});
diff --git a/src/lib/signup-policy.ts b/src/lib/signup-policy.ts
new file mode 100644
index 0000000..48472a7
--- /dev/null
+++ b/src/lib/signup-policy.ts
@@ -0,0 +1,169 @@
+// Who may create an account on this install. Signers never need an account,
+// so none of this affects people who are only sent a document to sign.
+
+export const SIGNUP_MODES = ["closed", "domains", "open"] as const;
+
+export type SignupMode = (typeof SIGNUP_MODES)[number];
+
+export type SignupPolicy = {
+ allowedEmailDomains: readonly string[];
+ signupMode: SignupMode;
+};
+
+export type SignupDecision =
+ | { allowed: true }
+ | {
+ allowed: false;
+ code: "signup_closed" | "signup_domain_not_allowed";
+ message: string;
+ };
+
+const DOMAIN_PATTERN =
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
+
+// Mailbox providers anyone can get an address at. An administrator who signs
+// up with one of these does not get "everyone at my domain may join" as the
+// starting rule, because that would mean everyone on the internet.
+const PUBLIC_MAILBOX_DOMAINS = new Set([
+ "aol.com",
+ "duck.com",
+ "fastmail.com",
+ "gmail.com",
+ "gmx.com",
+ "gmx.net",
+ "googlemail.com",
+ "hey.com",
+ "hotmail.com",
+ "icloud.com",
+ "live.com",
+ "mac.com",
+ "mail.com",
+ "me.com",
+ "msn.com",
+ "outlook.com",
+ "pm.me",
+ "proton.me",
+ "protonmail.com",
+ "tuta.com",
+ "tutanota.com",
+ "yahoo.com",
+ "yandex.com",
+ "ymail.com",
+ "zoho.com",
+]);
+
+/** "@Acme.com " becomes "acme.com". Returns null for anything that is not a domain. */
+export function normalizeEmailDomain(value: string): string | null {
+ const domain = value.trim().toLowerCase().replace(/^@/, "");
+
+ return DOMAIN_PATTERN.test(domain) ? domain : null;
+}
+
+export function getEmailDomain(email: string): string | null {
+ const separatorIndex = email.lastIndexOf("@");
+
+ if (separatorIndex <= 0) {
+ return null;
+ }
+
+ return normalizeEmailDomain(email.slice(separatorIndex + 1));
+}
+
+export function isPublicMailboxDomain(domain: string): boolean {
+ return PUBLIC_MAILBOX_DOMAINS.has(domain.trim().toLowerCase());
+}
+
+/**
+ * Splits what an administrator typed ("acme.com, @acme.co.uk") into a clean
+ * list. Entries that are not domains are returned separately so the form can
+ * point at them.
+ */
+export function parseEmailDomainList(value: string | readonly string[]): {
+ domains: string[];
+ invalid: string[];
+} {
+ const entries = (typeof value === "string" ? value.split(/[\s,;]+/) : value)
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0);
+ const domains = new Set<string>();
+ const invalid: string[] = [];
+
+ for (const entry of entries) {
+ const domain = normalizeEmailDomain(entry);
+
+ if (domain) {
+ domains.add(domain);
+ } else {
+ invalid.push(entry);
+ }
+ }
+
+ return { domains: Array.from(domains).sort(), invalid };
+}
+
+/** The rule a new install starts with, taken from the administrator's own address. */
+export function suggestSignupPolicy(adminEmail: string): SignupPolicy {
+ const domain = getEmailDomain(adminEmail);
+
+ if (!domain || isPublicMailboxDomain(domain)) {
+ return { allowedEmailDomains: [], signupMode: "closed" };
+ }
+
+ return { allowedEmailDomains: [domain], signupMode: "domains" };
+}
+
+export function describeSignupPolicy(policy: SignupPolicy): string {
+ if (policy.signupMode === "open") {
+ return "Anyone can create an account.";
+ }
+
+ if (
+ policy.signupMode === "domains" &&
+ policy.allowedEmailDomains.length > 0
+ ) {
+ return `Accounts can be created with an email address at ${formatDomainList(policy.allowedEmailDomains)}.`;
+ }
+
+ return "New accounts are not being accepted.";
+}
+
+function formatDomainList(domains: readonly string[]): string {
+ const labels = domains.map((domain) => `@${domain}`);
+
+ if (labels.length <= 1) {
+ return labels[0] ?? "";
+ }
+
+ return `${labels.slice(0, -1).join(", ")} or ${labels[labels.length - 1]}`;
+}
+
+export function evaluateSignup(
+ email: string,
+ policy: SignupPolicy,
+): SignupDecision {
+ if (policy.signupMode === "open") {
+ return { allowed: true };
+ }
+
+ if (policy.signupMode === "domains") {
+ const domain = getEmailDomain(email);
+
+ if (domain && policy.allowedEmailDomains.includes(domain)) {
+ return { allowed: true };
+ }
+
+ if (policy.allowedEmailDomains.length > 0) {
+ return {
+ allowed: false,
+ code: "signup_domain_not_allowed",
+ message: describeSignupPolicy(policy),
+ };
+ }
+ }
+
+ return {
+ allowed: false,
+ code: "signup_closed",
+ message: "New accounts are not being accepted.",
+ };
+}
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index 73555c2..a09e254 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -55,6 +55,7 @@ export const emailTemplateKinds = [
"decline_notification",
"void_notification",
"password_reset",
+ "test_email",
] as const;
export type EnvelopeStatus = (typeof envelopeStatuses)[number];
diff --git a/src/lib/utils/env.ts b/src/lib/utils/env.ts
index cc0609d..6c75dab 100644
--- a/src/lib/utils/env.ts
+++ b/src/lib/utils/env.ts
@@ -244,6 +244,18 @@ export function hasEnv(
return readEnv(env, variableName) !== undefined;
}
+/**
+ * Hosted mode is for running SignuDoc as a public service under its own
+ * name: the landing page, the built-in legal and contact pages, and the
+ * SignuDoc name everywhere. Without it an install is neutral and carries
+ * the name of the organization that runs it.
+ */
+export function isHostedMode(env: EnvSource = process.env): boolean {
+ const value = readEnv(env, "HOSTED_MODE")?.toLowerCase();
+
+ return value === "1" || value === "true";
+}
+
// Every value is optional here. Code that needs one checks it at the point of
// use (see requireConfigValue), so a missing email setting cannot stop a page
// that never sends email from rendering.
@@ -263,6 +275,9 @@ export function getEnv(env: EnvSource = process.env) {
internal: {
retentionJobSecret: readEnv(env, "RETENTION_JOB_SECRET"),
},
+ setup: {
+ token: readEnv(env, "SETUP_TOKEN"),
+ },
};
}