Email for professionals and teams
Check MX and the Resend DKIM record in public DNS for manual zones (#132)
Can K.6ffb698dd723
diff --git a/src/lib/domains/dns-audit.ts b/src/lib/domains/dns-audit.tsindex 52723cc..b779f92 100644--- a/src/lib/domains/dns-audit.ts+++ b/src/lib/domains/dns-audit.ts@@ -55,6 +55,7 @@ async function check(export async function auditDomainDns(hostname: string,view: AuditInput,+ sendingProvider?: string,): Promise<DomainDnsAudit> {const expected = [...view.routing.records, ...view.routing.missing, ...view.sending];// Cloudflare reports the selector it signs with, which is more reliable than@@ -63,7 +64,8 @@ export async function auditDomainDns((view.dkimSelector? `${view.dkimSelector}._domainkey.${hostname}`: undefined) ??- expected.find((record) => isTxt(record) && /_domainkey/i.test(record.name ?? ""))?.name;+ expected.find((record) => isTxt(record) && /_domainkey/i.test(record.name ?? ""))?.name ??+ (sendingProvider === "resend" ? `resend._domainkey.${hostname}` : undefined);const [mx, spf, dmarc] = await Promise.all([check("mx", "MX", hostname, "MX", (value) => !/^0\s*\.?$/.test(value.trim())),diff --git a/src/lib/domains/dns-view.ts b/src/lib/domains/dns-view.tsindex 3222e09..f42d8bd 100644--- a/src/lib/domains/dns-view.ts+++ b/src/lib/domains/dns-view.ts@@ -11,7 +11,7 @@ export async function getDomainDnsView(domain: DomainRow,): Promise<DomainDnsViewWithAudit> {const dns = await getDomainDns(env, domain);- const audit = await auditDomainDns(domain.hostname, dns);+ const audit = await auditDomainDns(domain.hostname, dns, domain.sendingProvider);return { ...dns, audit };}@@ -21,7 +21,7 @@ export async function summariseDomainDns(domain: DomainRow,): Promise<{ summary: DnsStatusSummary; sendingEnabled: boolean }> {const view = await getDomainDns(env, domain);- const audit = await auditDomainDns(domain.hostname, view);+ const audit = await auditDomainDns(domain.hostname, view, domain.sendingProvider);return {summary: summariseDns(view.routing.records,diff --git a/src/lib/domains/receiving-dns.ts b/src/lib/domains/receiving-dns.tsindex 397b9de..800d6f9 100644--- a/src/lib/domains/receiving-dns.ts+++ b/src/lib/domains/receiving-dns.ts@@ -1,3 +1,4 @@+import { queryDns } from "@/lib/dns-query";import { createDnsRecord, deleteDnsRecord, listMxRecords } from "@/lib/cloudflare-dns";import { isManualZone } from "@/lib/domains/provision";import type { CfDnsRecord } from "@/lib/cloudflare-api.types";@@ -21,9 +22,18 @@ export async function listDomainMx(env: CloudflareEnv, domain: DomainRow): Promireturn listMxRecords(env, domain.zoneId, domain.hostname);}-/** Whether an MX record for `content` is in the zone; null when DNS is manual. */+async function hasPublicMx(hostname: string, content: string): Promise<boolean | null> {+ try {+ const answers = await queryDns(hostname, "MX");+ return answers.some((answer) => same(answer.replace(/^\d+\s+/, ""), content));+ } catch {+ return null;+ }+}++/** Whether an MX record for `content` is in the zone, or in public DNS when the zone is manual; null when it cannot be checked. */export async function hasMx(env: CloudflareEnv, domain: DomainRow, content: string): Promise<boolean | null> {- if (isManualZone(domain.zoneId)) return null;+ if (isManualZone(domain.zoneId)) return hasPublicMx(domain.hostname, content);return (await listDomainMx(env, domain)).some((record) => same(record.content ?? "", content));}diff --git a/src/lib/domains/resend-receiving.ts b/src/lib/domains/resend-receiving.tsindex cc7a9db..855adad 100644--- a/src/lib/domains/resend-receiving.ts+++ b/src/lib/domains/resend-receiving.ts@@ -86,7 +86,7 @@ export async function getResendReceivingView(env: CloudflareEnv, domain: DomainRsteps.push({ key: "domain", label: "Receiving enabled for this domain", ok: enabled, detail: !resend ? "Domain is not in Resend yet" : undefined });const mx = inboundMx(resend?.records);const mxOk = mx ? await hasMx(env, domain, mx.value) : false;- steps.push({ key: "mx", label: "MX record points to Resend", ok: mxOk === true, detail: mx?.value ?? undefined });+ steps.push({ key: "mx", label: "MX record points to Resend", ok: mxOk === true, detail: mxOk === null ? "Could not check DNS from here" : mx?.value ?? undefined });steps.push({ key: "verified", label: "Domain verified", ok: resend?.status === "verified", detail: resend ? resend.status.replace(/_/g, " ") : undefined });const hooks = await listResendWebhooks(key.apiKey);const hookOk = hooks.some((webhook) => webhook.endpoint === resendWebhookUrl(origin)) && !!(await getResendWebhookSecret(env));diff --git a/tests/manual-dns-checks.test.mjs b/tests/manual-dns-checks.test.mjsnew file mode 100644index 0000000..025cce2--- /dev/null+++ b/tests/manual-dns-checks.test.mjs@@ -0,0 +1,67 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const bundleDirectory = mkdtempSync(join(root, "node_modules", "mailflare-dns-bundle-"));+await build({+ stdin: {+ contents: `+ export { hasMx } from "./src/lib/domains/receiving-dns.ts";+ export { auditDomainDns } from "./src/lib/domains/dns-audit.ts";+ `,+ resolveDir: root,+ sourcefile: "dns-test-entry.ts",+ },+ outfile: join(bundleDirectory, "entry.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node24",+ tsconfig: join(root, "tsconfig.json"),+ packages: "external",+ alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" },+ logLevel: "silent",+});+const { hasMx, auditDomainDns } = await import(pathToFileURL(join(bundleDirectory, "entry.mjs")).href);+rmSync(bundleDirectory, { recursive: true, force: true });++const manualDomain = { hostname: "example.com", zoneId: "manual" };++function answerDns(answers) {+ const asked = [];+ globalThis.fetch = async (url) => {+ const parsed = new URL(url);+ const name = parsed.searchParams.get("name");+ asked.push(name);+ const data = answers[`${name}|${parsed.searchParams.get("type")}`];+ return Response.json(data === undefined ? { Status: 3 } : { Status: 0, Answer: data.map((value) => ({ name, type: 0, TTL: 60, data: value })) });+ };+ return asked;+}++test("a manual zone's MX is read from public DNS", async () => {+ answerDns({ "example.com|MX": ["10 inbound-smtp.ap-northeast-1.amazonaws.com."] });+ assert.equal(await hasMx({}, manualDomain, "inbound-smtp.ap-northeast-1.amazonaws.com"), true);+ assert.equal(await hasMx({}, manualDomain, "mail.example.net"), false);+});++test("a manual zone with no MX answers false, and a failed lookup stays unknown", async () => {+ answerDns({});+ assert.equal(await hasMx({}, manualDomain, "mail.example.net"), false);+ globalThis.fetch = async () => { throw new Error("offline"); };+ assert.equal(await hasMx({}, manualDomain, "mail.example.net"), null);+});++test("DKIM for a Resend domain is checked at Resend's selector when nothing else names one", async () => {+ const asked = answerDns({ "resend._domainkey.example.com|TXT": ["p=abc"] });+ const view = { routing: { records: [], missing: [] }, sending: [] };+ const resend = await auditDomainDns("example.com", view, "resend");+ assert.equal(resend.dkim.status, "ok");+ assert.ok(asked.includes("resend._domainkey.example.com"));+ const other = await auditDomainDns("example.com", view, "none");+ assert.equal(other.dkim.status, "unknown");+});