Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Setup: guess the sending domain and default to a sign. subdomain
Clauded9d0f5a55046
diff --git a/src/app/api/setup/route.ts b/src/app/api/setup/route.tsindex bbef9dc..9c900ca 100644--- a/src/app/api/setup/route.ts+++ b/src/app/api/setup/route.ts@@ -3,6 +3,7 @@ import { NextResponse } from "next/server";import { getAuth, getAuthSessionFromHeaders } from "@/lib/auth/server";import { runAsSetup } from "@/lib/auth/setup-context";+import { addEmailDomain } from "@/lib/email-status";import { rejectBots } from "@/lib/security/botid";import { logRouteError, logSecurityEvent } from "@/lib/security/logging";import {@@ -59,6 +60,19 @@ async function createAdminAccount(input: {}}+// Adds the new sending domain to Resend straight away, so the Settings page+// that setup ends on already lists the DNS records to add. Anything that+// goes wrong here (no Resend key yet, a key that may only send, the free+// plan's domain limit) is left for that page to explain, where the+// administrator can try again.+async function addSenderDomain(): Promise<void> {+ try {+ await addEmailDomain();+ } catch (error) {+ console.error("Setup could not add the sending domain to Resend:", error);+ }+}+export async function POST(request: Request) {const ipAddress = getClientIpAddress(request.headers);const rateLimitResponse = await applyRateLimit({@@ -115,6 +129,10 @@ export async function POST(request: Request) {userId: result.userId,});+ if (typeof body?.senderAddress === "string" && body.senderAddress.trim()) {+ await addSenderDomain();+ }+if (result.mode === "create") {// Sign the new administrator in, so setup ends inside the app rather// than at a sign-in form. If this fails the account still exists anddiff --git a/src/app/setup/page.tsx b/src/app/setup/page.tsxindex 9476991..09bfc66 100644--- a/src/app/setup/page.tsx+++ b/src/app/setup/page.tsx@@ -16,7 +16,17 @@ import {resolveSettings,} from "@/lib/settings";import { resolveSetupView } from "@/lib/setup";-import { isHostedMode } from "@/lib/utils/env";+import { isHostedMode, resolveAppUrl } from "@/lib/utils/env";++function readSiteHost(): string | null {+ try {+ const appUrl = resolveAppUrl(process.env);++ return appUrl ? new URL(appUrl).hostname : null;+ } catch {+ return null;+ }+}export const metadata: Metadata = {description: "Create the administrator account for this site.",@@ -74,6 +84,7 @@ export default async function SetupPage() {<SetupShellhosted={isHostedMode()}onVercel={process.env.VERCEL === "1"}+ siteHost={readSiteHost()}view={view}/></BrandingProvider>diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex 2d80253..b07a957 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -20,6 +20,7 @@ import type { SignupMode } from "@/lib/signup-policy";const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";const RESEND_DOMAINS_URL = "https://resend.com/domains";+const RESEND_MARKETPLACE_URL = "https://vercel.com/marketplace/resend";type OrganizationSettingsProps = {initialSettings: OrganizationSettingsView;@@ -280,7 +281,7 @@ export function OrganizationSettings({helper={values.senderAddressFromEnv? "Set by the RESEND_FROM_EMAIL environment variable."- : "The address emails come from. Use one at a domain you own."+ : "The address emails come from, at a domain you own. A subdomain such as [email protected] keeps this site's mail apart from your everyday email."}label="Send email from"name="sender-address"@@ -527,6 +528,28 @@ function EmailSetupPanel() {{line}</p>))}+ {summary.steps ? (+ <ol className="list-decimal space-y-2 pl-5 text-sm leading-6 text-(--secondary) marker:font-semibold marker:text-(--fg)">+ {summary.steps.map((step) => (+ <li key={step.text}>+ {step.text}+ {step.link ? (+ <>+ {" "}+ <a+ className="font-semibold text-(--accent-ink) underline underline-offset-4"+ href={step.link.href}+ rel="noreferrer"+ target="_blank"+ >+ {step.link.label}+ </a>+ </>+ ) : null}+ </li>+ ))}+ </ol>+ ) : null}</div>)}@@ -590,9 +613,15 @@ function EmailSetupPanel() {);}+type EmailStep = {+ link?: { href: string; label: string };+ text: string;+};+function describeEmailStatus(status: EmailStatus): {lines: string[];ready: boolean;+ steps?: EmailStep[];title: string;} {switch (status.state) {@@ -605,14 +634,52 @@ function describeEmailStatus(status: EmailStatus): {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",- };+ return status.onVercel+ ? {+ lines: [+ "This site has no Resend API key, so it cannot send anything: no sign-up confirmations and no signing invitations.",+ ],+ ready: false,+ steps: [+ {+ link: {+ href: RESEND_MARKETPLACE_URL,+ label: "Resend on the Vercel Marketplace",+ },+ text: "Open Resend on the Vercel Marketplace. Choose Install (or Connect Project if your team already has Resend) and connect it to this project.",+ },+ {+ text: "In this project on Vercel, open Settings, then Environment Variables, and check that RESEND_API_KEY is listed for Production.",+ },+ {+ text: "Open Deployments, open the ••• menu on the latest Production deployment and choose Redeploy. Environment variables only reach deployments made after they were added, so a site deployed before Resend was connected still has no key until it is redeployed.",+ },+ {+ text: "When the new deployment is ready, reload this page.",+ },+ ],+ title: "Email is not connected",+ }+ : {+ lines: [+ "This site has no Resend API key, so it cannot send anything: no sign-up confirmations and no signing invitations.",+ ],+ ready: false,+ steps: [+ {+ link: {+ href: "https://resend.com/api-keys",+ label: "Resend API keys",+ },+ text: "Create an API key in Resend with full access, so this page can add your domain and check its DNS records.",+ },+ {+ text: "Set it as the RESEND_API_KEY environment variable where this site runs.",+ },+ { text: "Restart the app, then reload this page." },+ ],+ title: "Email is not connected",+ };case "test_sender":return {lines: [diff --git a/src/components/setup/setup-shell.tsx b/src/components/setup/setup-shell.tsxindex c221ebe..824008b 100644--- a/src/components/setup/setup-shell.tsx+++ b/src/components/setup/setup-shell.tsx@@ -11,7 +11,17 @@ import {import { Brand } from "@/components/layout/brand";import { PublicLegalFooter } from "@/components/layout/public-legal-links";import { FieldShell, ShellButton } from "@/components/shared/form-shell";+import { Input } from "@/components/ui/input";import { authClient } from "@/lib/auth/client";+import { cn } from "@/lib/cn";+import {+ buildSenderAddress,+ DEFAULT_SENDER_LOCAL_PART,+ DEFAULT_SENDING_SUBDOMAIN,+ joinSendingDomain,+ suggestSendingRootDomain,+ type SenderAddressParts,+} from "@/lib/sending-domain";import type { SetupFieldName, SetupView } from "@/lib/setup";import { getEmailDomain, suggestSignupPolicy } from "@/lib/signup-policy";@@ -23,6 +33,8 @@ export type SetupShellView =type SetupShellProps = {hosted: boolean;onVercel: boolean;+ /** The host this site answers on, used to guess the sending domain. */+ siteHost: string | null;view: SetupShellView;};@@ -47,7 +59,12 @@ const emptyValues: SetupValues = {supportAddress: "",};-export function SetupShell({ hosted, onVercel, view }: SetupShellProps) {+export function SetupShell({+ hosted,+ onVercel,+ siteHost,+ view,+}: SetupShellProps) {return (<div className="flex min-h-screen flex-col"><header>@@ -60,7 +77,12 @@ export function SetupShell({ hosted, onVercel, view }: SetupShellProps) {<main className="page-width flex flex-1 items-start justify-center py-8 sm:py-14"><div className="flex w-full justify-center" data-animate="enter"><section className="panel w-full max-w-[520px] p-8 sm:p-10">- <SetupContent hosted={hosted} onVercel={onVercel} view={view} />+ <SetupContent+ hosted={hosted}+ onVercel={onVercel}+ siteHost={siteHost}+ view={view}+ /></section></div></main>@@ -70,7 +92,7 @@ export function SetupShell({ hosted, onVercel, view }: SetupShellProps) {);}-function SetupContent({ hosted, onVercel, view }: SetupShellProps) {+function SetupContent({ hosted, onVercel, siteHost, view }: SetupShellProps) {if (view.view === "no_database") {return (<SetupNotice title="Connect a database">@@ -154,7 +176,7 @@ function SetupContent({ hosted, onVercel, view }: SetupShellProps) {return null;}- return <SetupForm hosted={hosted} view={view} />;+ return <SetupForm hosted={hosted} siteHost={siteHost} view={view} />;}function SetupNotice({@@ -196,14 +218,27 @@ function describeSignupStart(email: string, hosted: boolean): string | null {return "Only you will have an account to begin with. You can let other people in from Settings.";}+type SenderErrors = Partial<Record<keyof SenderAddressParts, string>>;+function SetupForm({hosted,+ siteHost,view,}: {hosted: boolean;+ siteHost: string | null;view: Extract<SetupShellView, { view: "claim" | "create" }>;}) {const [values, setValues] = useState<SetupValues>(emptyValues);+ const [sender, setSender] = useState<SenderAddressParts>({+ localPart: DEFAULT_SENDER_LOCAL_PART,+ rootDomain: "",+ subdomain: DEFAULT_SENDING_SUBDOMAIN,+ });+ // Until the administrator types a domain of their own, it follows what+ // setup can tell from the site's address and the emails typed above.+ const [rootDomainEdited, setRootDomainEdited] = useState(false);+ const [senderErrors, setSenderErrors] = useState<SenderErrors>({});const [errors, setErrors] = useState<SetupErrors>({});const [bannerMessage, setBannerMessage] = useState<string | null>(null);const [isSubmitting, setIsSubmitting] = useState(false);@@ -213,6 +248,33 @@ function SetupForm({const requiresToken = isCreate ? view.requiresToken : true;const asksForSender = isCreate && !view.senderAddressFromEnv;const asksForSupport = view.asksForSupportAddress;+ const suggestedRootDomain = asksForSender+ ? suggestSendingRootDomain({+ emails: [values.email, values.supportAddress],+ siteHost,+ })+ : null;+ const senderParts: SenderAddressParts = {+ ...sender,+ rootDomain: rootDomainEdited+ ? sender.rootDomain+ : (suggestedRootDomain ?? ""),+ };++ function handleSenderChange(field: keyof SenderAddressParts) {+ return (event: ChangeEvent<HTMLInputElement>) => {+ const nextValue = event.target.value;++ if (field === "rootDomain") {+ setRootDomainEdited(true);+ }++ setSender((current) => ({ ...current, [field]: nextValue }));+ setSenderErrors((current) => ({ ...current, [field]: undefined }));+ setErrors((current) => ({ ...current, senderAddress: undefined }));+ setBannerMessage(null);+ };+ }async function handleSwitchAccount() {if (isSwitchingAccount) {@@ -246,6 +308,18 @@ function SetupForm({setBannerMessage(null);setErrors({});+ setSenderErrors({});++ const builtSender = asksForSender+ ? buildSenderAddress(senderParts)+ : { address: null, error: null };++ if (builtSender.error) {+ setSenderErrors({ [builtSender.error.field]: builtSender.error.message });+ setBannerMessage("Check the address this site sends email from.");+ return;+ }+setIsSubmitting(true);try {@@ -259,7 +333,7 @@ function SetupForm({email: values.email,fullName: values.fullName,password: values.password,- senderAddress: asksForSender ? values.senderAddress : undefined,+ senderAddress: builtSender.address ?? undefined,}: {}),}),@@ -329,6 +403,7 @@ function SetupForm({disabled={isSubmitting}error={errors.supportAddress}helper="Signers and people with an account are told to write here for help, and replies to this site's emails come here. You can change it in Settings."+ ignorePasswordManagerslabel="Support email"name="setup-support-address"onChange={handleChange("supportAddress")}@@ -353,7 +428,9 @@ function SetupForm({value={values.fullName}/><FieldShell- autoComplete="email"+ // "username" tells password managers this is the login the+ // new password belongs to, so they save the two together.+ autoComplete="username"disabled={isSubmitting}error={errors.email}helper={signupStart ?? undefined}@@ -369,9 +446,12 @@ function SetupForm({autoComplete="new-password"disabled={isSubmitting}error={errors.password}- helper="Must be at least 15 characters"+ helper="At least 15 characters. Let your password manager make one."label="Password"+ maxLength={128}+ minLength={15}name="setup-password"+ passwordRules="minlength: 20; maxlength: 64; required: lower; required: upper; required: digit; allowed: [-_.!@#$%^&*];"onChange={handleChange("password")}placeholder="Enter a password"readOnly={false}@@ -382,18 +462,13 @@ function SetupForm({) : null}{asksForSender ? (- <FieldShell- autoComplete="off"+ <SenderFieldsdisabled={isSubmitting}- error={errors.senderAddress}- helper="Optional. An address at a domain you own, such as [email protected]. The next screen shows the DNS records that let this site send from it. Leave it empty to decide later."- label="Send email from"- name="setup-sender-address"- onChange={handleChange("senderAddress")}- placeholder="[email protected]"- readOnly={false}- type="email"- value={values.senderAddress}+ errors={senderErrors}+ onChange={handleSenderChange}+ parts={senderParts}+ serverError={errors.senderAddress}+ suggested={!rootDomainEdited && suggestedRootDomain !== null}/>) : null}@@ -403,6 +478,9 @@ function SetupForm({disabled={isSubmitting}error={errors.setupToken}helper="The value of the SETUP_TOKEN environment variable on this deployment."+ // Not a password of the account being made, so a password+ // manager should neither fill nor save it.+ ignorePasswordManagerslabel="Setup token"name="setup-token"onChange={handleChange("setupToken")}@@ -443,3 +521,164 @@ function SetupForm({</div>);}++const senderLabelClass = "text-[0.8125rem] font-semibold text-(--secondary)";+const senderHelperClass = "text-xs leading-5 text-(--tertiary)";+const senderErrorClass = "text-xs font-semibold text-(--danger)";++// The address this site sends from, asked for as its parts: the+// organization's domain (filled in when setup can tell it), a subdomain in+// front of it ("sign" unless changed) and the name before the @. Together+// they read as [email protected].+function SenderFields({+ disabled,+ errors,+ onChange,+ parts,+ serverError,+ suggested,+}: {+ disabled: boolean;+ errors: SenderErrors;+ onChange: (+ field: keyof SenderAddressParts,+ ) => (event: ChangeEvent<HTMLInputElement>) => void;+ parts: SenderAddressParts;+ serverError?: string;+ suggested: boolean;+}) {+ const built = buildSenderAddress(parts);+ const rootDomain = parts.rootDomain.trim().toLowerCase();+ const subdomain = parts.subdomain.trim().toLowerCase().replace(/\.+$/, "");+ const sendingDomain = rootDomain+ ? joinSendingDomain(rootDomain, subdomain)+ : null;+ const rootError = errors.rootDomain ?? serverError;+ const passwordManagerIgnore = {+ "data-1p-ignore": "true",+ "data-lpignore": "true",+ };++ return (+ <fieldset className="space-y-4 rounded-2xl border border-(--border) p-4 sm:p-5">+ <legend className="px-1 text-sm font-bold text-(--fg)">+ Send email from+ </legend>+ <p className={senderHelperClass}>+ Optional. Email is sent through Resend from a domain your organization+ owns. Leave the domain empty to decide later in Settings.+ </p>++ <div className="space-y-2 text-sm">+ <label className={senderLabelClass} htmlFor="setup-sender-domain">+ Your domain+ </label>+ <Input+ aria-describedby="setup-sender-domain-description"+ aria-invalid={rootError ? true : undefined}+ autoComplete="off"+ className={rootError ? "border-(--danger)" : undefined}+ disabled={disabled}+ id="setup-sender-domain"+ inputMode="url"+ name="setup-sender-domain"+ onChange={onChange("rootDomain")}+ placeholder="acmecorp.com"+ spellCheck={false}+ value={parts.rootDomain}+ {...passwordManagerIgnore}+ />+ <p+ className={rootError ? senderErrorClass : senderHelperClass}+ id="setup-sender-domain-description"+ >+ {rootError ??+ (suggested+ ? "Filled in from this site's address and the emails above. Change it if your organization uses another domain."+ : "The domain your organization's email uses, such as acmecorp.com.")}+ </p>+ </div>++ <div className="space-y-2 text-sm">+ <label className={senderLabelClass} htmlFor="setup-sender-subdomain">+ Subdomain+ </label>+ <div className="flex items-center gap-2">+ <Input+ aria-describedby="setup-sender-subdomain-description"+ aria-invalid={errors.subdomain ? true : undefined}+ autoComplete="off"+ className={cn(+ "w-40 flex-none",+ errors.subdomain ? "border-(--danger)" : "",+ )}+ disabled={disabled}+ id="setup-sender-subdomain"+ name="setup-sender-subdomain"+ onChange={onChange("subdomain")}+ placeholder="none"+ spellCheck={false}+ value={parts.subdomain}+ {...passwordManagerIgnore}+ />+ <span className="min-w-0 truncate text-sm text-(--secondary)">+ .{rootDomain || "acmecorp.com"}+ </span>+ </div>+ <p+ className={errors.subdomain ? senderErrorClass : senderHelperClass}+ id="setup-sender-subdomain-description"+ >+ {errors.subdomain ??+ (subdomain+ ? `Recommended. Mail comes from ${sendingDomain ?? `${subdomain}.acmecorp.com`}, so its DNS records and sending reputation stay apart from your everyday email. Clear it to send from ${rootDomain || "the domain"} itself.`+ : `Mail will come from ${rootDomain || "the domain"} itself. A subdomain such as ${DEFAULT_SENDING_SUBDOMAIN} keeps it apart from your everyday email.`)}+ </p>+ </div>++ <div className="space-y-2 text-sm">+ <label className={senderLabelClass} htmlFor="setup-sender-local-part">+ Address+ </label>+ <div className="flex items-center gap-2">+ <Input+ aria-describedby="setup-sender-local-part-description"+ aria-invalid={errors.localPart ? true : undefined}+ autoComplete="off"+ className={cn(+ "w-40 flex-none",+ errors.localPart ? "border-(--danger)" : "",+ )}+ disabled={disabled}+ id="setup-sender-local-part"+ name="setup-sender-local-part"+ onChange={onChange("localPart")}+ spellCheck={false}+ value={parts.localPart}+ {...passwordManagerIgnore}+ />+ <span className="min-w-0 truncate text-sm text-(--secondary)">+ @{sendingDomain ?? "acmecorp.com"}+ </span>+ </div>+ <p+ className={errors.localPart ? senderErrorClass : senderHelperClass}+ id="setup-sender-local-part-description"+ >+ {errors.localPart ??+ "Nobody needs to read this mailbox: replies go to the support email."}+ </p>+ </div>++ {built.address ? (+ <p className="rounded-xl bg-(--surface) px-4 py-3 text-xs leading-5 text-(--secondary)">+ Emails will come from{" "}+ <strong className="font-semibold text-(--fg)">{built.address}</strong>+ . If Resend is connected, setup adds {built.sendingDomain} to it, and+ the next screen lists the DNS records to add where your domain is+ managed.+ </p>+ ) : null}+ </fieldset>+ );+}diff --git a/src/components/shared/form-shell.tsx b/src/components/shared/form-shell.tsxindex 1f458ec..28e8560 100644--- a/src/components/shared/form-shell.tsx+++ b/src/components/shared/form-shell.tsx@@ -23,6 +23,20 @@ type FieldShellProps = {readOnly?: boolean;type?: "text" | "email" | "password";value?: string;+ /**+ * Keeps password managers from treating this field as part of a login,+ * for email fields that are not the account's own (a support address).+ */+ ignorePasswordManagers?: boolean;+ /** Length limits, which password managers read when they make a password. */+ maxLength?: number;+ minLength?: number;+ /**+ * The rules a generated password must follow, in the format password+ * managers (Safari, 1Password) read from the passwordrules attribute.+ * https://developer.apple.com/password-rules/+ */+ passwordRules?: string;};type ShellButtonProps = {@@ -51,8 +65,12 @@ export function FieldShell({disabled = false,error,helper,+ ignorePasswordManagers = false,label,+ maxLength,+ minLength,name,+ passwordRules,onChange,placeholder,readOnly = true,@@ -80,12 +98,18 @@ export function FieldShell({)}disabled={disabled}id={inputId}+ maxLength={maxLength}+ minLength={minLength}name={name}onChange={onChange}placeholder={placeholder}readOnly={readOnly}type={type}value={value ?? ""}+ {...(ignorePasswordManagers+ ? { "data-1p-ignore": "true", "data-lpignore": "true" }+ : {})}+ {...(passwordRules ? { passwordrules: passwordRules } : {})}/>{error ? (<FieldErrordiff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.tsindex 9d942e3..a54222a 100644--- a/src/lib/email-status.test.ts+++ b/src/lib/email-status.test.ts@@ -147,6 +147,11 @@ test("the capture driver is reported as such without asking anyone", async () =>test("no Resend key means email is not connected", async () => {assert.deepEqual(await getEmailStatus({ env: {}, settings }), {+ onVercel: false,+ state: "missing_key",+ });+ assert.deepEqual(await getEmailStatus({ env: { VERCEL: "1" }, settings }), {+ onVercel: true,state: "missing_key",});});diff --git a/src/lib/email-status.ts b/src/lib/email-status.tsindex 2e04230..707af7b 100644--- a/src/lib/email-status.ts+++ b/src/lib/email-status.ts@@ -38,8 +38,11 @@ export type EmailDnsRecord = {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" }+ /**+ * No Resend API key, so nothing can be sent. On Vercel the steps to fix it+ * are Vercel's, which the page spells out.+ */+ | { state: "missing_key"; onVercel: boolean }/** 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. */@@ -391,7 +394,10 @@ async function inspectEmail({client: null,domainId: null,markReady: noop,- status: { state: "missing_key" },+ status: {+ onVercel: readEnv(env, "VERCEL") === "1",+ state: "missing_key",+ },};}diff --git a/src/lib/sending-domain.test.ts b/src/lib/sending-domain.test.tsnew file mode 100644index 0000000..e61e43f--- /dev/null+++ b/src/lib/sending-domain.test.ts@@ -0,0 +1,120 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ buildSenderAddress,+ isOwnableDomain,+ normalizeSubdomain,+ suggestSendingRootDomain,+} from "./sending-domain.ts";++test("only a domain an organization could own is offered for sending", () => {+ assert.equal(isOwnableDomain("kevinrose.com"), true);+ assert.equal(isOwnableDomain("mail.acme.co.uk"), true);+ assert.equal(isOwnableDomain("gmail.com"), false);+ assert.equal(isOwnableDomain("signudoc-abc.vercel.app"), false);+ assert.equal(isOwnableDomain("onboarding.resend.dev"), false);+ assert.equal(isOwnableDomain("localhost"), false);+ assert.equal(isOwnableDomain("127.0.0.1"), false);+});++test("the root domain comes from the site's custom domain, cut back to the email domain", () => {+ assert.equal(+ suggestSendingRootDomain({+ emails: ["[email protected]"],+ siteHost: "esign.kevinrose.com",+ }),+ "kevinrose.com",+ );+ assert.equal(+ suggestSendingRootDomain({ siteHost: "sign.kevinrose.com" }),+ "kevinrose.com",+ );+ assert.equal(+ suggestSendingRootDomain({ siteHost: "documents.acme.com" }),+ "documents.acme.com",+ );+});++test("on a vercel.app address the emails decide, skipping public mailboxes", () => {+ assert.equal(+ suggestSendingRootDomain({+ emails: ["[email protected]", "[email protected]"],+ siteHost: "signudoc-kro.vercel.app",+ }),+ "kevinrose.com",+ );+ assert.equal(+ suggestSendingRootDomain({+ emails: ["[email protected]", ""],+ siteHost: "localhost",+ }),+ null,+ );+});++test("a subdomain is tidied up, and an empty one means the root domain", () => {+ assert.equal(normalizeSubdomain(" Sign. "), "sign");+ assert.equal(normalizeSubdomain("mail.sign"), "mail.sign");+ assert.equal(normalizeSubdomain(""), "");+ assert.equal(normalizeSubdomain("si gn"), null);+ assert.equal(normalizeSubdomain("-sign"), null);+});++test("the parts make one address, with sign. in front by default", () => {+ assert.deepEqual(+ buildSenderAddress({+ localPart: "Kro",+ rootDomain: "KevinRose.com",+ subdomain: "sign",+ }),+ {+ address: "[email protected]",+ error: null,+ sendingDomain: "sign.kevinrose.com",+ },+ );+ assert.deepEqual(+ buildSenderAddress({+ localPart: "kro",+ rootDomain: "kevinrose.com",+ subdomain: "",+ }),+ {+ address: "[email protected]",+ error: null,+ sendingDomain: "kevinrose.com",+ },+ );+});++test("no domain means deciding later, and bad parts name their field", () => {+ assert.deepEqual(+ buildSenderAddress({ localPart: "x", rootDomain: " ", subdomain: "sign" }),+ { address: null, error: null },+ );+ assert.equal(+ buildSenderAddress({+ localPart: "x",+ rootDomain: "gmail.com",+ subdomain: "sign",+ }).error?.field,+ "rootDomain",+ );+ assert.equal(+ buildSenderAddress({+ localPart: "x",+ rootDomain: "acme.com",+ subdomain: "bad_sub",+ }).error?.field,+ "subdomain",+ );+ assert.equal(+ buildSenderAddress({+ localPart: "no spaces",+ rootDomain: "acme.com",+ subdomain: "sign",+ }).error?.field,+ "localPart",+ );+});diff --git a/src/lib/sending-domain.ts b/src/lib/sending-domain.tsnew file mode 100644index 0000000..7cdfa64--- /dev/null+++ b/src/lib/sending-domain.ts@@ -0,0 +1,224 @@+import {+ getEmailDomain,+ isPublicMailboxDomain,+ normalizeEmailDomain,+} from "./signup-policy.ts";++// Where this site's email is sent from, as setup offers it.+//+// Mail is sent through Resend, which only sends from a domain whose DNS+// records prove it belongs to you. Setup does not ask for that address+// blind: it guesses the organization's domain from what it already knows+// (the site's own address, the administrator's email, the support email),+// and puts a subdomain in front of it, "sign." unless the administrator+// picks another or none.+//+// A subdomain is what Resend recommends. Its records (DKIM at+// resend._domainkey.sign.acme.com, SPF and the bounce MX at+// send.sign.acme.com) sit apart from whatever already sends mail for+// acme.com, and its sending reputation is its own.+// https://resend.com/docs/knowledge-base/is-it-better-to-send-emails-from-a-subdomain-or-the-root-domain++export const DEFAULT_SENDING_SUBDOMAIN = "sign";+export const DEFAULT_SENDER_LOCAL_PART = "notifications";++// Hosts that can never be a sending domain of the organization's own: the+// platform's shared domains, Resend's test domain and local names.+const SHARED_HOST_SUFFIXES = [+ "vercel.app",+ "vercel.dev",+ "now.sh",+ "resend.dev",+ "localhost",+ "local",+ "internal",+ "test",+ "example",+ "invalid",+];++const LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;+const LOCAL_PART_PATTERN = /^[a-z0-9](?:[a-z0-9._+-]{0,62}[a-z0-9])?$/;++function isSharedHost(domain: string): boolean {+ return SHARED_HOST_SUFFIXES.some(+ (suffix) => domain === suffix || domain.endsWith(`.${suffix}`),+ );+}++/**+ * A domain the organization could own and verify with Resend: a real+ * domain, not a public mailbox provider's and not a platform's shared one.+ */+export function isOwnableDomain(value: string): boolean {+ const domain = normalizeEmailDomain(value);++ return (+ domain !== null &&+ domain.includes(".") &&+ !isPublicMailboxDomain(domain) &&+ !isSharedHost(domain) &&+ !/^\d+(?:\.\d+){3}$/.test(domain)+ );+}++type SuggestionInput = {+ /** Email addresses typed into setup so far, most telling first. */+ emails?: readonly (string | null | undefined)[];+ /** The host the site answers on, such as sign.acme.com or acme.vercel.app. */+ siteHost?: string | null;+};++/**+ * The organization's own domain, as far as setup can tell, or null.+ *+ * The site's host wins when it is a custom domain, cut back to the email+ * domain it sits under (esign.acme.com with [email protected] gives acme.com).+ * A fresh Vercel deployment answers on vercel.app, which nobody can send+ * from, so then the email addresses decide.+ */+export function suggestSendingRootDomain({+ emails = [],+ siteHost,+}: SuggestionInput): string | null {+ const emailDomains = emails+ .map((email) => (email ? getEmailDomain(email) : null))+ .filter((domain): domain is string => domain !== null)+ .filter(isOwnableDomain);+ const host = siteHost ? normalizeEmailDomain(siteHost) : null;++ if (host && isOwnableDomain(host)) {+ const parent = emailDomains.find(+ (domain) => host === domain || host.endsWith(`.${domain}`),+ );++ if (parent) {+ return parent;+ }++ // A site that already lives at sign.acme.com sends from it as is.+ const prefix = `${DEFAULT_SENDING_SUBDOMAIN}.`;++ if (host.startsWith(prefix) && isOwnableDomain(host.slice(prefix.length))) {+ return host.slice(prefix.length);+ }++ return host;+ }++ return emailDomains[0] ?? null;+}++/** "Sign." becomes "sign". Returns null for anything that is not one or more DNS labels. */+export function normalizeSubdomain(value: string): string | null {+ const subdomain = value+ .trim()+ .toLowerCase()+ .replace(/^\.+|\.+$/g, "");++ if (subdomain.length === 0) {+ return "";+ }++ return subdomain.split(".").every((label) => LABEL_PATTERN.test(label))+ ? subdomain+ : null;+}++/** The part before the @, lower-cased, or null if it will not make an address. */+export function normalizeLocalPart(value: string): string | null {+ const localPart = value.trim().toLowerCase();++ return LOCAL_PART_PATTERN.test(localPart) && !localPart.includes("..")+ ? localPart+ : null;+}++/** The domain mail is sent from: the subdomain, if any, in front of the root. */+export function joinSendingDomain(+ rootDomain: string,+ subdomain: string,+): string {+ return subdomain ? `${subdomain}.${rootDomain}` : rootDomain;+}++export type SenderAddressParts = {+ localPart: string;+ rootDomain: string;+ subdomain: string;+};++export type SenderAddressResult =+ | { address: null; error: null }+ | { address: string; error: null; sendingDomain: string }+ | {+ address: null;+ error: { field: keyof SenderAddressParts; message: string };+ };++/**+ * Puts the three parts setup asks for together into one address. An empty+ * root domain means "decide later", which is not an error.+ */+export function buildSenderAddress(+ parts: SenderAddressParts,+): SenderAddressResult {+ if (parts.rootDomain.trim().length === 0) {+ return { address: null, error: null };+ }++ const rootDomain = normalizeEmailDomain(parts.rootDomain);++ if (!rootDomain || !rootDomain.includes(".")) {+ return {+ address: null,+ error: {+ field: "rootDomain",+ message: "Enter a domain, such as acmecorp.com",+ },+ };+ }++ if (!isOwnableDomain(rootDomain)) {+ return {+ address: null,+ error: {+ field: "rootDomain",+ message: `Mail cannot be sent from ${rootDomain}. Use a domain your organization owns.`,+ },+ };+ }++ const subdomain = normalizeSubdomain(parts.subdomain);++ if (subdomain === null) {+ return {+ address: null,+ error: {+ field: "subdomain",+ message: "Use letters, numbers and hyphens, such as sign",+ },+ };+ }++ const localPart = normalizeLocalPart(parts.localPart);++ if (localPart === null) {+ return {+ address: null,+ error: {+ field: "localPart",+ message:+ "Use letters, numbers, dots and hyphens, such as notifications",+ },+ };+ }++ const sendingDomain = joinSendingDomain(rootDomain, subdomain);++ return {+ address: `${localPart}@${sendingDomain}`,+ error: null,+ sendingDomain,+ };+}