// mail-auth — is this domain's email set up so mail arrives, and so nobody can spoof it? // // The honest answer needs a sender IP, which this service does not have. A real SPF // pass/fail is therefore out of reach, and this module never pretends otherwise: it reports // the SHAPE of the published records and what that shape means for the owner. Every claim // here is something a resolver actually returned. // // DNS is injected (`opts.dns` with resolveTxt/resolveMx/resolve4) so tests never touch the // network; the default is a node:dns Resolver with a 2 s timeout and 2 tries. import dns from 'node:dns'; import { parseTarget } from '../lib/net-guard.mjs'; export const DKIM_SELECTORS = Object.freeze([ 'default', 'google', 'selector1', 'selector2', 's1', 's2', 'k1', 'k2', 'mail', 'dkim', 'mandrill', 'amazonses', 'smtp' ]); // RFC 7208 §4.6.4: include, a, mx, ptr, exists and redirect each cost one lookup; the // evaluation must stop (permerror) once the total passes 10. export const SPF_LOOKUP_LIMIT = 10; export const SPF_LOOKUP_WARN_AT = 8; export const SPF_MAX_DEPTH = 10; export const DMARC_SUBDOMAIN = '_dmarc'; // The one sentence this module is allowed to say about an unfound DKIM key. Never // "DKIM is not configured" — 13 selectors are not all selectors. export const DKIM_NO_KEY_MESSAGE = 'No key found among the 13 common selectors; a custom selector cannot be found from DNS alone.'; const QUALIFIERS = new Set(['+', '-', '~', '?']); const SPF_MECHANISMS = new Set(['all', 'include', 'a', 'mx', 'ptr', 'exists', 'ip4', 'ip6']); const SPF_LOOKUP_MECHANISMS = new Set(['include', 'a', 'mx', 'ptr', 'exists']); // A name that exists with no record of this type answers with one of these: "empty", not "broken". const EMPTY_CODES = new Set(['ENODATA', 'ENOTFOUND', 'NXDOMAIN', 'ENONAME', 'NOTFOUND']); // "I could not find out" — never a finding against the visitor's domain. const TRANSIENT_CODES = new Set([ 'ESERVFAIL', 'SERVFAIL', 'ETIMEOUT', 'ETIMEDOUT', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EREFUSED', 'REFUSED', 'TIMEOUT', 'ERESOLVE', 'EBADRESP', 'EFORMERR', 'ENOTIMP' ]); const MAX_LISTED_INCLUDES = 3; // --------------------------------------------------------------------------- // resolver // --------------------------------------------------------------------------- export function createResolver() { const resolver = new dns.promises.Resolver({ timeout: 2000, tries: 2 }); return { resolveTxt: (host) => resolver.resolveTxt(host), resolveMx: (host) => resolver.resolveMx(host), resolve4: (host) => resolver.resolve4(host) }; } function pickResolver(candidate) { if (!candidate || typeof candidate.resolveTxt !== 'function') return createResolver(); const missing = (code) => Object.assign(new Error(code), { code }); return { resolveTxt: (host) => candidate.resolveTxt(host), resolveMx: (host) => typeof candidate.resolveMx === 'function' ? candidate.resolveMx(host) : Promise.reject(missing('ENOTIMP')), resolve4: (host) => typeof candidate.resolve4 === 'function' ? candidate.resolve4(host) : Promise.reject(missing('ENOTIMP')) }; } function errorCode(err) { if (!err) return 'UNKNOWN'; return String(err.code || err.errno || 'UNKNOWN').toUpperCase(); } /** * TXT answers arrive as an array of chunk arrays. Join the chunks of each record with NO * separator: a record longer than 255 bytes is split on the wire, and parsing the chunks * separately silently truncates `include:exam` + `ple.com` into a mechanism nobody published. */ export function joinTxtChunks(records) { if (!Array.isArray(records)) return []; return records.map((record) => { if (Array.isArray(record)) return record.join(''); if (record === null || record === undefined) return ''; return String(record); }); } async function queryTxt(resolver, host) { try { const raw = await resolver.resolveTxt(host); return { ok: true, records: joinTxtChunks(raw), code: null }; } catch (err) { const code = errorCode(err); if (EMPTY_CODES.has(code)) return { ok: true, records: [], code }; // Anything that is not "this name has no such record" means "I could not find out". return { ok: false, records: [], code, transient: true, listed: TRANSIENT_CODES.has(code) }; } } async function queryMx(resolver, host) { try { const raw = await resolver.resolveMx(host); return { ok: true, records: Array.isArray(raw) ? raw : [], code: null }; } catch (err) { const code = errorCode(err); if (EMPTY_CODES.has(code)) return { ok: true, records: [], code }; return { ok: false, records: [], code, transient: true }; } } async function queryAddresses(resolver, host) { try { const raw = await resolver.resolve4(host); const addresses = (Array.isArray(raw) ? raw : []).filter((a) => typeof a === 'string' && a.length > 0); return { ok: addresses.length > 0, addresses, code: null, empty: addresses.length === 0 }; } catch (err) { const code = errorCode(err); if (EMPTY_CODES.has(code)) return { ok: false, addresses: [], code, empty: true }; return { ok: false, addresses: [], code, empty: false, unreadable: true }; } } // --------------------------------------------------------------------------- // SPF // --------------------------------------------------------------------------- function normaliseTarget(raw) { const text = String(raw ?? '').trim().toLowerCase().replace(/\.$/, ''); if (text.length === 0) return null; if (text.includes('%')) return null; // a macro such as %{i} cannot be resolved from here if (!/^[a-z0-9._-]+$/.test(text)) return null; return text; } /** Every TXT record that claims to be SPF, in the order the resolver returned them. */ export function findSpfRecords(txts) { if (!Array.isArray(txts)) return []; return txts.filter((record) => /^v=spf1(\s|$)/i.test(String(record ?? '').trim())); } /** * Parse one SPF record. Pure: no DNS. `lookups` counts the terms in THIS record only; * countSpfLookups() adds the records reachable through include and redirect. */ export function parseSpf(record) { const text = String(record ?? '').trim(); const out = { record: text, valid: false, mechanisms: [], modifiers: {}, lookups: 0, all: null, redirect: null, unknown: [], exp: null }; if (text.length === 0) return out; const tokens = text.split(/\s+/); if (!/^v=spf1$/i.test(tokens[0])) return out; out.valid = true; for (const token of tokens.slice(1)) { const lowered = token.toLowerCase(); if (lowered.startsWith('redirect=')) { const target = normaliseTarget(token.slice('redirect='.length)); out.modifiers.redirect = token.slice('redirect='.length); out.redirect = target; out.lookups += 1; // redirect counts toward the 10 continue; } if (lowered.startsWith('exp=')) { out.modifiers.exp = token.slice('exp='.length); out.exp = token.slice('exp='.length); continue; } const modifier = /^([a-z][a-z0-9_.-]*)=(.*)$/i.exec(token); if (modifier) { out.modifiers[modifier[1].toLowerCase()] = modifier[2]; continue; } const qualifier = QUALIFIERS.has(token[0]) ? token[0] : '+'; const body = QUALIFIERS.has(token[0]) ? token.slice(1) : token; if (body.length === 0) { out.unknown.push(token); continue; } const colon = body.indexOf(':'); const slash = body.indexOf('/'); let cut = body.length; if (colon !== -1) cut = colon; else if (slash !== -1) cut = slash; const name = body.slice(0, cut).toLowerCase(); const tail = body.slice(cut); const cidrMatch = /\/\d{1,3}$/.exec(tail); const cidr = cidrMatch ? cidrMatch[0].slice(1) : null; const tailNoCidr = cidrMatch ? tail.slice(0, cidrMatch.index) : tail; const value = tailNoCidr.startsWith(':') ? tailNoCidr.slice(1) : ''; if (!SPF_MECHANISMS.has(name)) { out.unknown.push(token); continue; } if (SPF_LOOKUP_MECHANISMS.has(name)) out.lookups += 1; const mechanism = { qualifier, name, value, cidr, raw: token }; out.mechanisms.push(mechanism); if (name === 'all') out.all = { qualifier, raw: token }; } return out; } /** * Walk include and redirect targets, adding each record's own lookup terms, with cycle * detection and a hard depth cap. Never throws: a loop or a dead include ends the walk. */ export async function countSpfLookups(domain, record, { dns: resolver, maxDepth = SPF_MAX_DEPTH } = {}) { const rootDomain = String(domain ?? '').trim().toLowerCase().replace(/\.$/, ''); const visited = new Set(rootDomain ? [rootDomain] : []); const chain = []; const missingTargets = []; let lookups = 0; let cycles = 0; let depthCapped = false; let unreadable = 0; const queue = [{ domain: rootDomain, record, depth: 0 }]; while (queue.length > 0) { const current = queue.shift(); const parsed = typeof current.record === 'string' ? parseSpf(current.record) : current.record; if (!parsed || !parsed.valid) continue; lookups += parsed.lookups; chain.push({ domain: current.domain, depth: current.depth, lookups: parsed.lookups }); const targets = []; for (const mechanism of parsed.mechanisms) { if (mechanism.name === 'include') { const target = normaliseTarget(mechanism.value); if (target) targets.push(target); } } if (parsed.redirect) targets.push(parsed.redirect); for (const target of targets) { if (visited.has(target)) { cycles += 1; continue; } if (current.depth + 1 > maxDepth) { depthCapped = true; continue; } visited.add(target); if (!resolver || typeof resolver.resolveTxt !== 'function') continue; const answer = await queryTxt(resolver, target); if (!answer.ok) { unreadable += 1; continue; } const nested = findSpfRecords(answer.records); if (nested.length === 0) { missingTargets.push(target); continue; } queue.push({ domain: target, record: nested[0], depth: current.depth + 1 }); } } return { lookups, cycles, depthCapped, unreadable, missingTargets, chain }; } // --------------------------------------------------------------------------- // DMARC // --------------------------------------------------------------------------- function splitUris(value) { if (!value) return []; return String(value) .split(',') .map((part) => part.trim()) .filter((part) => part.length > 0); } /** Parse a _dmarc TXT record. Pure. Unknown tags are kept in `tags` for the report. */ export function parseDmarc(record) { const text = String(record ?? '').trim(); const out = { record: text, valid: false, version: null, p: null, sp: null, pct: 100, rua: [], ruf: [], adkim: null, aspf: null, fo: null, tags: {} }; if (text.length === 0) return out; for (const part of text.split(';')) { const equals = part.indexOf('='); if (equals <= 0) continue; const key = part.slice(0, equals).trim().toLowerCase(); const value = part.slice(equals + 1).trim(); if (key.length > 0) out.tags[key] = value; } if (!/^dmarc1$/i.test(out.tags.v || '')) return out; out.valid = true; out.version = 'DMARC1'; const policy = (out.tags.p || '').toLowerCase(); out.p = ['none', 'quarantine', 'reject'].includes(policy) ? policy : null; const subdomain = (out.tags.sp || '').toLowerCase(); out.sp = ['none', 'quarantine', 'reject'].includes(subdomain) ? subdomain : null; const pct = Number.parseInt(out.tags.pct ?? '100', 10); out.pct = Number.isFinite(pct) ? Math.min(100, Math.max(0, pct)) : 100; out.rua = splitUris(out.tags.rua); out.ruf = splitUris(out.tags.ruf); out.adkim = (out.tags.adkim || '').toLowerCase() || null; out.aspf = (out.tags.aspf || '').toLowerCase() || null; out.fo = (out.tags.fo || '').toLowerCase() || null; return out; } // --------------------------------------------------------------------------- // DKIM // --------------------------------------------------------------------------- /** Read one selector's TXT records. `p=` empty means the key was revoked, not published. */ export function readDkimKey(records) { const out = { key: false, revoked: false, tags: {} }; for (const record of records) { const tags = {}; for (const part of String(record).split(';')) { const equals = part.indexOf('='); if (equals <= 0) continue; tags[part.slice(0, equals).trim().toLowerCase()] = part.slice(equals + 1).trim(); } const hasP = Object.prototype.hasOwnProperty.call(tags, 'p'); if (hasP && tags.p.length > 0) { out.key = true; out.tags = tags; return out; } if (hasP && tags.p.length === 0) { out.revoked = true; out.tags = tags; } } return out; } // --------------------------------------------------------------------------- // MX // --------------------------------------------------------------------------- /** Normalise MX answers, detect a null MX, and sort by priority. Pure. */ export function parseMx(records) { const list = (Array.isArray(records) ? records : []) .map((record) => { if (!record || typeof record !== 'object') return null; const exchange = String(record.exchange ?? '').trim().toLowerCase().replace(/\.$/, ''); const priority = Number(record.priority); return { exchange, priority: Number.isFinite(priority) ? priority : 0 }; }) .filter(Boolean); // RFC 7505: a single "0 ." says the domain accepts no mail on purpose. const nullMx = list.length > 0 && list.every((record) => record.exchange === '' || record.exchange === '.'); const sorted = (nullMx ? [] : list.filter((record) => record.exchange !== '' && record.exchange !== '.')) .slice() .sort((a, b) => a.priority - b.priority || a.exchange.localeCompare(b.exchange)); return { records: sorted, nullMx, count: nullMx ? 0 : sorted.length }; } // --------------------------------------------------------------------------- // gather // --------------------------------------------------------------------------- async function gather(domain, resolver) { const gathered = { domain, fatal: null, spfRecords: [], spfLookups: null, dmarc: { checked: false, code: null, record: null, parsed: null }, dkim: [], mx: { checked: false, code: null, records: [], nullMx: false, addresses: [] } }; const [apexTxt, apexMx] = await Promise.all([queryTxt(resolver, domain), queryMx(resolver, domain)]); // The whole zone is unreadable: SERVFAIL/timeout is not a finding against the visitor. if (!apexTxt.ok || !apexMx.ok) { const code = !apexTxt.ok ? apexTxt.code : apexMx.code; gathered.fatal = { code, kind: 'unreadable' }; return gathered; } if (apexTxt.code === 'ENOTFOUND' && apexMx.code === 'ENOTFOUND') { gathered.fatal = { code: 'ENOTFOUND', kind: 'not_found' }; return gathered; } gathered.spfRecords = findSpfRecords(apexTxt.records); const mx = parseMx(apexMx.records); gathered.mx = { checked: true, code: apexMx.code, records: mx.records, nullMx: mx.nullMx, addresses: [] }; const dmarcAnswer = await queryTxt(resolver, `${DMARC_SUBDOMAIN}.${domain}`); gathered.dmarc.checked = dmarcAnswer.ok; gathered.dmarc.code = dmarcAnswer.code; const dmarcRecords = dmarcAnswer.records.filter((record) => /^v=dmarc1(\s*;|\s|$)/i.test(record.trim())); gathered.dmarc.record = dmarcRecords[0] ?? null; gathered.dmarc.parsed = dmarcRecords[0] ? parseDmarc(dmarcRecords[0]) : null; gathered.dmarc.count = dmarcRecords.length; const dkim = await Promise.all( DKIM_SELECTORS.map(async (selector) => { const name = `${selector}._domainkey.${domain}`; const answer = await queryTxt(resolver, name); if (!answer.ok) return { selector, name, status: 'unreadable', key: false }; const hit = readDkimKey(answer.records); if (hit.key) return { selector, name, status: 'key', key: true, tags: hit.tags }; if (hit.revoked) return { selector, name, status: 'revoked', key: false, tags: hit.tags }; return { selector, name, status: 'none', key: false }; }) ); gathered.dkim = dkim; if (!mx.nullMx) { gathered.mx.addresses = await Promise.all( mx.records.map(async (record) => ({ host: record.exchange, ...(await queryAddresses(resolver, record.exchange)) })) ); } if (gathered.spfRecords.length === 1) { gathered.spfLookups = await countSpfLookups(domain, gathered.spfRecords[0], { dns: resolver }); } return gathered; } // --------------------------------------------------------------------------- // summary // --------------------------------------------------------------------------- function buildSummary({ receive, send }) { if (receive === 'null') { return send === 'locked' ? 'This domain deliberately accepts no mail, and only your own servers can send as it.' : 'This domain deliberately accepts no mail (a valid setup), but anyone can still send as it.'; } if (receive === 'no-mx') { return send === 'locked' ? 'Mail sent to this domain may bounce, because no mail server is listed, but only your own servers can send as it.' : 'Mail sent to this domain may bounce, and spoofed email is not blocked.'; } if (receive === 'broken') { return 'Mail sent to this domain will bounce, because none of the listed mail servers resolve.'; } if (send === 'locked') return 'Mail can be delivered, and only your own servers can send as your domain.'; if (send === 'partial') return 'Mail can be delivered, but a spoofed email could still get through.'; return 'Mail can be delivered, but anyone can send email pretending to be your domain.'; } function worstState(findings) { if (findings.some((finding) => finding.level === 'fail')) return 'fail'; if (findings.some((finding) => finding.level === 'warn')) return 'warn'; return 'ok'; } function envelope({ state, summary, evidence, findings, checkedAt }) { // `note` is optional: drop the key entirely rather than emit `note: undefined`. const cleanEvidence = (evidence || []).map((item) => item.note === undefined ? { label: item.label, value: item.value } : item ); return { id: 'mail-auth', state, summary, evidence: cleanEvidence, findings, checkedAt, fromCache: false }; } // --------------------------------------------------------------------------- // analysis (pure) // --------------------------------------------------------------------------- /** * Turn gathered DNS answers into the report. Pure and synchronous: everything it needs was * already fetched by gather(), so tests can feed it fixtures directly. */ export function analyseMailAuth(gathered, { now = Date.now() } = {}) { const checkedAt = new Date(now).toISOString(); const findings = []; const evidence = []; const add = (level, code, message, fix) => { const finding = { level, code, message }; if (fix) finding.fix = fix; findings.push(finding); }; const domain = gathered?.domain || 'this domain'; if (gathered?.fatal) { const notFound = gathered.fatal.kind === 'not_found'; add( 'info', notFound ? 'domain_not_found' : 'dns_unavailable', notFound ? 'DNS has no records at all for this name, so nothing about its email could be read.' : 'The DNS server did not answer for this domain, so nothing here is a verdict.', notFound ? 'Check the spelling, or ask your registrar whether the domain is active.' : 'Try again in a minute.' ); return envelope({ state: 'not-evaluated', summary: notFound ? 'This domain does not appear to exist in DNS, so there is nothing to check yet.' : 'We could not read this domain’s DNS just now, so this is not a verdict — try again in a minute.', evidence: [{ label: 'DNS', value: notFound ? 'no records' : `unreadable (${gathered.fatal.code})` }], findings, checkedAt }); } // ---- SPF ---------------------------------------------------------------- let spf = null; let spfLookups = null; if (gathered.spfRecords.length === 0) { add( 'fail', 'spf_missing', 'There is no SPF record, so anyone can send email claiming to come from this domain.', `Publish a TXT record at ${domain}: v=spf1 include: -all` ); evidence.push({ label: 'SPF record', value: 'none' }); } else if (gathered.spfRecords.length > 1) { add( 'fail', 'spf_multiple', `${gathered.spfRecords.length} SPF records are published. Receivers cannot choose between them, so SPF returns permerror and the domain loses its protection.`, 'Merge them into a single v=spf1 record and delete the others.' ); evidence.push({ label: 'SPF record', value: `${gathered.spfRecords.length} records (permerror)`, note: gathered.spfRecords.join(' | ') }); } else { spf = parseSpf(gathered.spfRecords[0]); evidence.push({ label: 'SPF record', value: spf.record }); if (!spf.valid) { add('fail', 'spf_malformed', 'The SPF record does not start with v=spf1, so receivers ignore it.'); } if (spf.all) { if (spf.all.qualifier === '-') { add('ok', 'spf_all_hardfail', 'SPF ends in -all: servers you did not list are told to fail.'); } else if (spf.all.qualifier === '~') { add( 'warn', 'spf_all_softfail', 'SPF ends in ~all (softfail): unauthorised mail is marked but usually still delivered.', 'Change ~all to -all once you are sure every legitimate sender is listed.' ); } else if (spf.all.qualifier === '?') { add( 'fail', 'spf_all_neutral', 'SPF ends in ?all (neutral), which tells receivers nothing — anyone can still send as this domain.', 'Change ?all to -all.' ); } else { add( 'fail', 'spf_all_pass_all', 'SPF ends in +all, which authorises every server on the internet to send as this domain.', 'Replace +all with -all.' ); } } else if (spf.redirect) { add( 'warn', 'spf_no_all', `SPF has no all mechanism; it delegates to redirect=${spf.redirect}, so the result depends on that record.` ); } else { add( 'warn', 'spf_no_all', 'SPF has no all mechanism, so unmatched senders get a neutral result and mail is not blocked.', 'Add -all to the end of the record.' ); } if (spf.mechanisms.some((mechanism) => mechanism.name === 'ptr')) { add( 'info', 'spf_ptr_deprecated', 'SPF uses ptr, which RFC 7208 discourages because it is slow and unreliable.' ); } if (spf.unknown.length > 0) { add( 'warn', 'spf_unknown_mechanism', `SPF contains ${spf.unknown.length} term(s) that are not valid mechanisms or modifiers: ${spf.unknown.slice(0, 3).join(' ')}`, 'Remove or correct them; an unknown mechanism makes the record a permerror.' ); } spfLookups = gathered.spfLookups || null; if (spfLookups) { const count = spfLookups.lookups; if (count > SPF_LOOKUP_LIMIT) { add( 'fail', 'spf_lookup_limit', `SPF needs ${count} DNS lookups; the limit is ${SPF_LOOKUP_LIMIT}, so receivers return permerror and treat the mail as unprotected.`, 'Flatten the record: replace some include: entries with the ip4/ip6 ranges they resolve to.' ); } else if (count >= SPF_LOOKUP_WARN_AT) { add( 'warn', 'spf_lookups_near_limit', `SPF needs ${count} of the ${SPF_LOOKUP_LIMIT} allowed DNS lookups. One more include and it breaks.`, 'Flatten the record before adding another provider.' ); } if (spfLookups.cycles > 0) { add( 'warn', 'spf_include_loop', 'SPF includes loop back to a domain already checked, so the evaluation never finishes cleanly.' ); } if (spfLookups.depthCapped) { add('warn', 'spf_too_deep', 'The SPF include chain is deeper than 10 levels, which is a permerror.'); } if (spfLookups.missingTargets.length > 0) { add( 'warn', 'spf_include_no_record', `An included domain has no SPF record: ${spfLookups.missingTargets.slice(0, MAX_LISTED_INCLUDES).join(', ')}. Receivers treat that as a permanent error.`, 'Ask that provider for its current include: value, or drop the include.' ); } evidence.push({ label: 'SPF lookups', value: `${count} of ${SPF_LOOKUP_LIMIT}`, note: 'Counts include, a, mx, ptr, exists and redirect across the whole chain.' }); } else { evidence.push({ label: 'SPF lookups', value: 'not counted' }); } } // ---- DMARC -------------------------------------------------------------- let dmarc = null; if (!gathered.dmarc.checked) { // We could not read _dmarc: say so, and do not claim the record is missing. add( 'info', 'dmarc_not_checked', 'The _dmarc record could not be read just now, so its policy is unknown rather than missing.' ); evidence.push({ label: 'DMARC record', value: `unreadable (${gathered.dmarc.code || 'DNS error'})` }); } else if (!gathered.dmarc.record) { add( 'warn', 'dmarc_missing', 'There is no DMARC record, so receivers have no instruction for mail that fails SPF or DKIM.', `Publish a TXT record at _dmarc.${domain}: v=DMARC1; p=none; rua=mailto:dmarc@${domain} — then tighten to p=quarantine when the reports look clean.` ); evidence.push({ label: 'DMARC record', value: 'none' }); } else { dmarc = gathered.dmarc.parsed; evidence.push({ label: 'DMARC record', value: dmarc.record }); if (!dmarc.valid) { add('fail', 'dmarc_malformed', 'The _dmarc record does not start with v=DMARC1, so receivers ignore it.'); } else if (dmarc.p === 'none') { add( 'warn', 'dmarc_none', 'DMARC is set to p=none — monitoring only: spoofing is still allowed, you just get reports about it.', 'Once the reports look clean, change p=none to p=quarantine, then p=reject.' ); } else if (dmarc.p === 'quarantine') { add('ok', 'dmarc_quarantine', 'DMARC is set to p=quarantine: failing mail is sent to spam.'); } else if (dmarc.p === 'reject') { add('ok', 'dmarc_reject', 'DMARC is set to p=reject: failing mail is refused outright.'); } else { add('warn', 'dmarc_no_policy', 'The DMARC record has no usable p= policy, so it does nothing.'); } if (dmarc.valid && dmarc.pct < 100) { add( 'info', 'dmarc_partial_pct', `DMARC pct=${dmarc.pct}, so the policy is applied to only part of failing mail; the rest is delivered.` ); } if (dmarc.valid && dmarc.rua.length === 0) { add('info', 'dmarc_no_rua', 'DMARC has no rua= address, so nobody collects the reports and you cannot see who is spoofing you.'); } evidence.push({ label: 'DMARC policy', value: dmarc.valid ? `p=${dmarc.p ?? 'none'}` : 'invalid', note: dmarc.valid ? `pct=${dmarc.pct}${dmarc.sp ? `, sp=${dmarc.sp}` : ''}${dmarc.rua.length ? `, rua=${dmarc.rua.join(',')}` : ', no rua'}` : undefined }); } // ---- DKIM --------------------------------------------------------------- const withKey = gathered.dkim.filter((entry) => entry.status === 'key'); const revoked = gathered.dkim.filter((entry) => entry.status === 'revoked'); if (withKey.length > 0) { add('ok', 'dkim_key_found', `A DKIM key is published at ${withKey.map((entry) => entry.selector).join(', ')}.`); evidence.push({ label: 'DKIM key', value: withKey.map((entry) => entry.selector).join(', '), note: `Found among the ${DKIM_SELECTORS.length} common selectors.` }); } else { // Absence of evidence, not evidence of absence. The wording is fixed on purpose. add('info', 'dkim_no_key_found', DKIM_NO_KEY_MESSAGE); evidence.push({ label: 'DKIM key', value: 'none of 13 selectors', note: revoked.length > 0 ? `Revoked key at ${revoked.map((entry) => entry.selector).join(', ')}.` : undefined }); } if (revoked.length > 0 && withKey.length > 0) { add('info', 'dkim_revoked', `A key at ${revoked.map((entry) => entry.selector).join(', ')} is revoked (p= is empty).`); } // ---- MX ----------------------------------------------------------------- let receive; if (gathered.mx.nullMx) { receive = 'null'; add( 'ok', 'mx_null', 'A null MX record (0 .) is published: this domain explicitly accepts no email. That is a deliberate, valid setup, not a fault.' ); evidence.push({ label: 'MX records', value: '0 . (null MX — no mail accepted)' }); } else if (gathered.mx.records.length === 0) { receive = 'no-mx'; add( 'warn', 'mx_missing', 'No MX record is published, so senders have no mail server to deliver to.', `Add an MX record for ${domain} pointing at your mail provider (for example 10 mx..com).` ); evidence.push({ label: 'MX records', value: 'none' }); } else { evidence.push({ label: 'MX records', value: gathered.mx.records.map((record) => `${record.priority} ${record.exchange}`).join(', ') }); const resolved = gathered.mx.addresses.filter((entry) => entry.ok); const provablyEmpty = gathered.mx.addresses.filter((entry) => entry.empty); const unreadable = gathered.mx.addresses.filter((entry) => entry.unreadable); for (const entry of gathered.mx.addresses) { evidence.push({ label: 'MX address', value: entry.ok ? `${entry.host} → ${entry.addresses[0]}` : `${entry.host} → ${entry.unreadable ? 'not checked' : 'no address'}`, note: entry.ok && entry.addresses.length > 1 ? `${entry.addresses.length} addresses` : undefined }); } if (resolved.length === 0 && provablyEmpty.length === gathered.mx.addresses.length) { receive = 'broken'; add( 'fail', 'mx_no_address', 'None of the listed mail servers resolve to an address, so mail sent here will bounce.', 'Fix the MX hostnames or ask your provider for the correct ones.' ); } else { receive = 'yes'; const dead = provablyEmpty.filter((entry) => !entry.ok); if (dead.length > 0) { add( 'warn', 'mx_host_no_address', `${dead.map((entry) => entry.host).join(', ')} does not resolve, so part of your incoming mail will bounce.`, 'Remove the dead MX record or point it at a host that resolves.' ); } if (unreadable.length > 0) { add('info', 'mx_host_not_checked', `Could not check ${unreadable.map((entry) => entry.host).join(', ')} just now.`); } add('ok', 'mx_present', `${gathered.mx.records.length} mail server(s) listed, lowest priority tried first.`); } } // ---- summary ------------------------------------------------------------ const spfHard = Boolean(spf && spf.all && spf.all.qualifier === '-'); const spfSoft = Boolean(spf && spf.all && spf.all.qualifier === '~'); const dmarcEnforcing = Boolean( dmarc && dmarc.valid && (dmarc.p === 'reject' || dmarc.p === 'quarantine') && dmarc.pct >= 100 ); const dmarcPresent = Boolean(dmarc && dmarc.valid && dmarc.p && dmarc.p !== 'none'); let send = 'open'; if (spfHard && dmarcEnforcing) send = 'locked'; else if (spfHard || spfSoft || dmarcPresent) send = 'partial'; const state = worstState(findings); return envelope({ state, summary: buildSummary({ receive, send }), evidence, findings, checkedAt }); } // --------------------------------------------------------------------------- // check // --------------------------------------------------------------------------- /** * Check a domain's email setup. * * @param {string} input domain (or URL — the host is taken) * @param {{dns?: object, lookup?: object, now?: number, cache?: object}} options * `dns` (alias `lookup`) is an object with resolveTxt/resolveMx/resolve4; injected by tests. */ export async function check(input, { dns: resolver, lookup, now = Date.now(), cache } = {}) { const checkedAt = new Date(now).toISOString(); let host; try { host = parseTarget(typeof input === 'string' ? input : String(input ?? '')).host; } catch { return envelope({ state: 'fail', summary: 'That does not look like a domain name, so there was nothing to check.', evidence: [], findings: [{ level: 'fail', code: 'bad_input', message: 'That does not look like a domain name.' }], checkedAt }); } void cache; // caching is the router's job; this module always reports fromCache: false const dnsClient = pickResolver(resolver || lookup); const gathered = await gather(host, dnsClient); return analyseMailAuth(gathered, { now }); } export const checkMailAuth = check;