import test from 'node:test'; import assert from 'node:assert/strict'; import { check, checkMailAuth, analyseMailAuth, parseSpf, parseDmarc, parseMx, readDkimKey, joinTxtChunks, findSpfRecords, countSpfLookups, DKIM_SELECTORS, DKIM_NO_KEY_MESSAGE, SPF_LOOKUP_LIMIT } from '../src/checks/mail-auth.mjs'; // --------------------------------------------------------------------------- // fakes — nothing below this line opens a socket // --------------------------------------------------------------------------- function dnsError(code) { const err = new Error(code); err.code = code; return err; } /** * txt: { 'name': [['chunk','chunk'], ...] } * mx: { 'name': [{ exchange, priority }] } * a: { 'name': ['203.0.113.5'] } * A missing name answers `missing` (ENODATA = the name exists with no such record, * ENOTFOUND = the name does not exist); a value that is an Error is thrown as-is. */ function fakeDns({ txt = {}, mx = {}, a = {}, missing = 'ENODATA' } = {}) { const lookup = (table, host) => { const key = String(host).toLowerCase().replace(/\.$/, ''); return Object.prototype.hasOwnProperty.call(table, key) ? table[key] : undefined; }; const run = async (table, host) => { const value = lookup(table, host); if (value === undefined) throw dnsError(missing); if (value instanceof Error) throw value; return value; }; return { resolveTxt: (host) => run(txt, host), resolveMx: (host) => run(mx, host), resolve4: (host) => run(a, host) }; } const KEDAI = 'kedai.my'; // A realistic Malaysian SME: one provider, hard SPF, reject DMARC, Google DKIM, two MX. function cleanFixture(overrides = {}) { return { txt: { [KEDAI]: [ ['v=spf1 include:spf.mailhost.my -all'], ['google-site-verification=abc123'] ], 'spf.mailhost.my': [['v=spf1 ip4:203.115.10.0/24 -all']], [`_dmarc.${KEDAI}`]: [['v=DMARC1; p=reject; rua=mailto:dmarc@kedai.my']], [`google._domainkey.${KEDAI}`]: [['v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA']], ...overrides.txt }, mx: { [KEDAI]: [ { exchange: 'mx2.mailhost.my', priority: 20 }, { exchange: 'mx1.mailhost.my', priority: 10 } ], ...overrides.mx }, a: { 'mx1.mailhost.my': ['203.115.10.5'], 'mx2.mailhost.my': ['203.115.10.6'], ...overrides.a } }; } const codes = (result) => result.findings.map((finding) => finding.code); const finding = (result, code) => result.findings.find((entry) => entry.code === code); const evidence = (result, label) => result.evidence.find((entry) => entry.label === label); // --------------------------------------------------------------------------- // (a) the clean setup // --------------------------------------------------------------------------- test('clean SME setup: SPF -all, DMARC reject, one DKIM selector, live MX — state ok', async () => { const result = await check(KEDAI, { dns: fakeDns(cleanFixture()), now: Date.parse('2026-11-10T04:00:00Z') }); assert.equal(result.id, 'mail-auth'); assert.equal(result.state, 'ok', `unexpected findings: ${codes(result).join(',')}`); assert.equal(result.summary, 'Mail can be delivered, and only your own servers can send as your domain.'); assert.equal(result.fromCache, false); assert.equal(result.checkedAt, '2026-11-10T04:00:00.000Z'); assert.equal(finding(result, 'spf_all_hardfail').level, 'ok'); assert.equal(finding(result, 'dmarc_reject').level, 'ok'); assert.equal(finding(result, 'dkim_key_found').level, 'ok'); assert.equal(finding(result, 'mx_present').level, 'ok'); assert.equal(evidence(result, 'SPF record').value, 'v=spf1 include:spf.mailhost.my -all'); assert.equal(evidence(result, 'SPF lookups').value, `1 of ${SPF_LOOKUP_LIMIT}`); assert.equal(evidence(result, 'DMARC policy').value, 'p=reject'); assert.equal(evidence(result, 'DKIM key').value, 'google'); // MX evidence is sorted by priority, not by the order the resolver returned. assert.equal(evidence(result, 'MX records').value, '10 mx1.mailhost.my, 20 mx2.mailhost.my'); assert.equal(checkMailAuth, check); }); // --------------------------------------------------------------------------- // (b) TXT split across the 255-byte boundary // --------------------------------------------------------------------------- test('TXT record split mid-mechanism is joined before parsing', async () => { const records = [['v=spf1 include:exam', 'ple.com -all']]; // The join must not invent a separator: 'exam' + 'ple.com' = 'example.com'. assert.deepEqual(joinTxtChunks(records), ['v=spf1 include:example.com -all']); const parsed = parseSpf(joinTxtChunks(records)[0]); const include = parsed.mechanisms.find((mechanism) => mechanism.name === 'include'); assert.equal(include.value, 'example.com', 'the include target must survive the split intact'); assert.equal(parsed.all.qualifier, '-'); const result = await check('split.my', { dns: fakeDns({ txt: { 'split.my': records, 'example.com': [['v=spf1 ip4:203.0.113.10 -all']], '_dmarc.split.my': [['v=DMARC1; p=reject']] }, mx: { 'split.my': [{ exchange: 'mx.split.my', priority: 10 }] }, a: { 'mx.split.my': ['203.0.113.11'] } }) }); assert.equal(evidence(result, 'SPF record').value, 'v=spf1 include:example.com -all'); // The include target was actually followed, which can only happen if the name was intact. assert.equal(evidence(result, 'SPF lookups').value, `1 of ${SPF_LOOKUP_LIMIT}`); assert.ok(!codes(result).includes('spf_include_no_record'), 'example.com must have been resolved as an SPF target'); }); // --------------------------------------------------------------------------- // (c) two SPF records = permerror // --------------------------------------------------------------------------- test('two v=spf1 records is a fail with reason permerror', async () => { const result = await check('two.my', { dns: fakeDns({ txt: { 'two.my': [['v=spf1 include:a.my -all'], ['v=spf1 include:b.my ~all']], '_dmarc.two.my': [['v=DMARC1; p=reject']] }, mx: { 'two.my': [{ exchange: 'mx.two.my', priority: 10 }] }, a: { 'mx.two.my': ['203.0.113.20'] } }) }); const spf = finding(result, 'spf_multiple'); assert.equal(spf.level, 'fail'); assert.match(spf.message, /permerror/, 'the reason must be named as permerror'); assert.match(spf.message, /2 SPF records/); assert.equal(result.state, 'fail'); assert.match(evidence(result, 'SPF record').value, /permerror/); }); // --------------------------------------------------------------------------- // (d) include loop // --------------------------------------------------------------------------- test('an include loop stops cleanly instead of throwing', async () => { const dns = fakeDns({ txt: { 'loop.my': [['v=spf1 include:b.my -all']], 'b.my': [['v=spf1 include:loop.my -all']] }, mx: { 'loop.my': [{ exchange: 'mx.loop.my', priority: 10 }] }, a: { 'mx.loop.my': ['203.0.113.30'] } }); const walk = await countSpfLookups('loop.my', 'v=spf1 include:b.my -all', { dns }); assert.equal(walk.lookups, 2, 'each side of the loop is counted once'); assert.equal(walk.cycles, 1); assert.equal(walk.depthCapped, false); const result = await check('loop.my', { dns }); assert.equal(result.state !== undefined, true); assert.equal(finding(result, 'spf_include_loop').level, 'warn'); assert.ok(!codes(result).includes('spf_lookup_limit')); }); // --------------------------------------------------------------------------- // (e) lookup counting: 11 fails, 9 warns // --------------------------------------------------------------------------- function manyIncludes(count, domain) { const names = Array.from({ length: count }, (_, i) => `spf${i}.example.my`); const txt = { [domain]: [[`v=spf1 ${names.map((name) => `include:${name}`).join(' ')} -all`]] }; for (const name of names) txt[name] = [['v=spf1 ip4:203.0.113.9 -all']]; return txt; } test('11 DNS lookups is a fail at the RFC 7208 limit', async () => { const txt = manyIncludes(11, 'big.my'); txt['_dmarc.big.my'] = [['v=DMARC1; p=reject']]; const dns = fakeDns({ txt, mx: { 'big.my': [{ exchange: 'mx.big.my', priority: 10 }] }, a: { 'mx.big.my': ['203.0.113.40'] } }); const walk = await countSpfLookups('big.my', txt['big.my'][0][0], { dns }); assert.equal(walk.lookups, 11); const result = await check('big.my', { dns }); const limit = finding(result, 'spf_lookup_limit'); assert.equal(limit.level, 'fail'); assert.match(limit.message, /11 DNS lookups/); assert.equal(result.state, 'fail'); }); test('9 DNS lookups warns before the limit is reached', async () => { const txt = manyIncludes(9, 'near.my'); txt['_dmarc.near.my'] = [['v=DMARC1; p=reject']]; const dns = fakeDns({ txt, mx: { 'near.my': [{ exchange: 'mx.near.my', priority: 10 }] }, a: { 'mx.near.my': ['203.0.113.41'] } }); const result = await check('near.my', { dns }); const near = finding(result, 'spf_lookups_near_limit'); assert.equal(near.level, 'warn'); assert.equal(evidence(result, 'SPF lookups').value, `9 of ${SPF_LOOKUP_LIMIT}`); assert.equal(result.state, 'warn'); }); // --------------------------------------------------------------------------- // (f) p=none // --------------------------------------------------------------------------- test('p=none reads as monitoring only, not as protection', async () => { const fixture = cleanFixture(); fixture.txt[`_dmarc.${KEDAI}`] = [['v=DMARC1; p=none; rua=mailto:dmarc@kedai.my']]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const none = finding(result, 'dmarc_none'); assert.equal(none.level, 'warn'); assert.match(none.message, /monitoring only/); assert.match(none.message, /spoofing is still allowed/); assert.equal(evidence(result, 'DMARC policy').value, 'p=none'); assert.equal(result.state, 'warn'); assert.equal(result.summary, 'Mail can be delivered, but a spoofed email could still get through.'); }); test('pct<100 and a missing rua are notes, not faults', async () => { const fixture = cleanFixture(); fixture.txt[`_dmarc.${KEDAI}`] = [['v=DMARC1; p=reject; pct=50']]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); assert.equal(finding(result, 'dmarc_partial_pct').level, 'info'); assert.equal(finding(result, 'dmarc_no_rua').level, 'info'); assert.equal(result.state, 'ok', 'notes must not turn a working setup amber'); }); // --------------------------------------------------------------------------- // (g) no DMARC at all // --------------------------------------------------------------------------- test('missing DMARC is a warn with a one-line fix, never a fail', async () => { const fixture = cleanFixture(); delete fixture.txt[`_dmarc.${KEDAI}`]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const dmarc = finding(result, 'dmarc_missing'); assert.equal(dmarc.level, 'warn'); assert.match(dmarc.fix, /_dmarc\.kedai\.my/); assert.match(dmarc.fix, /v=DMARC1/); assert.ok(!dmarc.fix.includes('\n'), 'the fix must be one line'); assert.equal(result.state, 'warn'); assert.equal(evidence(result, 'DMARC record').value, 'none'); }); test('an unreadable _dmarc lookup says unknown rather than missing', async () => { const fixture = cleanFixture(); fixture.txt[`_dmarc.${KEDAI}`] = dnsError('SERVFAIL'); const result = await check(KEDAI, { dns: fakeDns(fixture) }); assert.ok(!codes(result).includes('dmarc_missing'), 'a SERVFAIL must not be reported as "no DMARC"'); assert.equal(finding(result, 'dmarc_not_checked').level, 'info'); }); // --------------------------------------------------------------------------- // (h) no MX // --------------------------------------------------------------------------- test('no MX at all is a warn with a fix', async () => { const fixture = cleanFixture(); delete fixture.mx[KEDAI]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const mx = finding(result, 'mx_missing'); assert.equal(mx.level, 'warn'); assert.match(mx.fix, /MX record/); assert.match(result.summary, /may bounce/); assert.equal(result.state, 'warn'); }); // --------------------------------------------------------------------------- // (i) null MX is a deliberate setup // --------------------------------------------------------------------------- test('a null MX is reported as deliberate, not as a fault', async () => { const fixture = cleanFixture(); fixture.mx[KEDAI] = [{ exchange: '.', priority: 0 }]; delete fixture.a['mx1.mailhost.my']; delete fixture.a['mx2.mailhost.my']; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const nullMx = finding(result, 'mx_null'); assert.equal(nullMx.level, 'ok'); assert.match(nullMx.message, /deliberate/); assert.match(nullMx.message, /valid setup/); assert.match(nullMx.message, /not a fault/); assert.ok(!codes(result).includes('mx_missing'), 'a null MX is not a missing MX'); assert.equal(result.state, 'ok'); assert.match(evidence(result, 'MX records').value, /null MX/); }); test('parseMx sorts by priority and detects a null MX', () => { const sorted = parseMx([ { exchange: 'mx-b.example.my', priority: 20 }, { exchange: 'mx-a.example.my', priority: 10 }, { exchange: 'mx-c.example.my', priority: 10 } ]); assert.deepEqual(sorted.records.map((record) => record.exchange), ['mx-a.example.my', 'mx-c.example.my', 'mx-b.example.my']); assert.equal(sorted.nullMx, false); const nullMx = parseMx([{ exchange: '.', priority: 0 }]); assert.equal(nullMx.nullMx, true); assert.equal(nullMx.count, 0); }); // --------------------------------------------------------------------------- // (j) SERVFAIL / timeout // --------------------------------------------------------------------------- test('a SERVFAIL for the domain is not-evaluated, not a fail', async () => { const dns = fakeDns({ txt: { [KEDAI]: dnsError('SERVFAIL') }, mx: { [KEDAI]: dnsError('SERVFAIL') } }); const result = await check(KEDAI, { dns }); assert.equal(result.state, 'not-evaluated'); assert.equal(finding(result, 'dns_unavailable').level, 'info'); assert.equal(result.findings.filter((entry) => entry.level === 'fail').length, 0, 'no failure may be pinned on the site'); assert.match(result.summary, /not a verdict/); }); test('a timeout is also not-evaluated', async () => { const result = await check(KEDAI, { dns: fakeDns({ txt: { [KEDAI]: dnsError('ETIMEOUT') }, mx: { [KEDAI]: dnsError('ETIMEOUT') } }) }); assert.equal(result.state, 'not-evaluated'); assert.ok(!codes(result).includes('spf_missing')); }); // --------------------------------------------------------------------------- // (k) DKIM wording // --------------------------------------------------------------------------- test('no DKIM key found uses the exact required sentence', async () => { const fixture = cleanFixture(); delete fixture.txt[`google._domainkey.${KEDAI}`]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const dkim = finding(result, 'dkim_no_key_found'); assert.equal( dkim.message, 'No key found among the 13 common selectors; a custom selector cannot be found from DNS alone.' ); assert.equal(dkim.message, DKIM_NO_KEY_MESSAGE); assert.equal(dkim.level, 'info', 'an unfound key is absence of evidence, not a fault'); assert.ok(!/not configured|broken/i.test(dkim.message), 'the forbidden wording must never appear'); assert.equal(evidence(result, 'DKIM key').value, 'none of 13 selectors'); // An unknown selector must not stop a working setup being reported as working. assert.equal(result.state, 'ok'); }); test('the selector list is exactly the 13 required probes', () => { assert.deepEqual( [...DKIM_SELECTORS], ['default', 'google', 'selector1', 'selector2', 's1', 's2', 'k1', 'k2', 'mail', 'dkim', 'mandrill', 'amazonses', 'smtp'] ); assert.equal(DKIM_SELECTORS.length, 13); assert.ok(DKIM_NO_KEY_MESSAGE.includes('13 common selectors')); }); test('a revoked DKIM key (p= empty) is not reported as a key', () => { const revoked = readDkimKey(['v=DKIM1; k=rsa; p=']); assert.equal(revoked.key, false); assert.equal(revoked.revoked, true); const live = readDkimKey(['v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A']); assert.equal(live.key, true); }); // --------------------------------------------------------------------------- // SPF qualifier verdicts // --------------------------------------------------------------------------- test('+all and ?all are fails: both authorise spoofing', async () => { for (const [record, code] of [ ['v=spf1 +all', 'spf_all_pass_all'], ['v=spf1 ?all', 'spf_all_neutral'], ['v=spf1 all', 'spf_all_pass_all'] ]) { const fixture = cleanFixture(); fixture.txt[KEDAI] = [[record]]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const found = finding(result, code); assert.ok(found, `${record} should raise ${code}`); assert.equal(found.level, 'fail'); assert.equal(result.state, 'fail'); } }); test('~all is a warn, not a pass', async () => { const fixture = cleanFixture(); fixture.txt[KEDAI] = [['v=spf1 include:spf.mailhost.my ~all']]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); assert.equal(finding(result, 'spf_all_softfail').level, 'warn'); assert.equal(result.state, 'warn'); }); test('parseSpf reads qualifiers, cidr and modifiers without counting ip4/ip6', () => { const parsed = parseSpf('v=spf1 ip4:203.0.113.0/24 ip6:2001:db8::/32 a:mail.example.my/24 mx ptr exists:%{i}.example.my include:_spf.example.my redirect=_spf2.example.my -all'); assert.equal(parsed.valid, true); assert.equal(parsed.all.qualifier, '-'); assert.equal(parsed.redirect, '_spf2.example.my'); // a, mx, ptr, exists, include, redirect = 6; ip4/ip6/all cost nothing. assert.equal(parsed.lookups, 6); const a = parsed.mechanisms.find((mechanism) => mechanism.name === 'a'); assert.equal(a.value, 'mail.example.my'); assert.equal(a.cidr, '24'); const ip6 = parsed.mechanisms.find((mechanism) => mechanism.name === 'ip6'); assert.equal(ip6.value, '2001:db8::'); // A macro target cannot be resolved from here, so it is not followed. const exists = parsed.mechanisms.find((mechanism) => mechanism.name === 'exists'); assert.equal(exists.value, '%{i}.example.my'); }); test('parseDmarc defaults pct to 100 and keeps every tag', () => { const parsed = parseDmarc('v=DMARC1; p=quarantine; sp=reject; pct=75; adkim=s; aspf=r; rua=mailto:a@x.my, mailto:b@y.my; fo=1'); assert.equal(parsed.valid, true); assert.equal(parsed.p, 'quarantine'); assert.equal(parsed.sp, 'reject'); assert.equal(parsed.pct, 75); assert.equal(parsed.adkim, 's'); assert.equal(parsed.aspf, 'r'); assert.deepEqual(parsed.rua, ['mailto:a@x.my', 'mailto:b@y.my']); assert.equal(parseDmarc('v=DMARC1; p=reject').pct, 100); assert.equal(parseDmarc('p=reject').valid, false); }); test('findSpfRecords ignores lookalikes and keeps the real record', () => { const txts = ['google-site-verification=abc', 'v=spf10 -all', 'v=spf1 -all', 'spf2.0/pra -all']; assert.deepEqual(findSpfRecords(txts), ['v=spf1 -all']); }); // --------------------------------------------------------------------------- // contract + edges // --------------------------------------------------------------------------- test('the return value matches the checks contract', async () => { const now = Date.parse('2026-11-10T04:00:00Z'); const result = await check(KEDAI, { dns: fakeDns(cleanFixture()), now }); assert.deepEqual(Object.keys(result).sort(), ['checkedAt', 'evidence', 'findings', 'fromCache', 'id', 'state', 'summary']); assert.equal(result.id, 'mail-auth'); assert.equal(result.fromCache, false); assert.equal(result.checkedAt, new Date(now).toISOString()); assert.ok(['ok', 'warn', 'fail', 'not-evaluated'].includes(result.state)); assert.ok(result.summary.length > 0 && !result.summary.includes('\n'), 'summary is one line'); for (const item of result.evidence) { assert.equal(typeof item.label, 'string'); assert.equal(typeof item.value, 'string'); assert.ok(!('note' in item) || typeof item.note === 'string'); } for (const item of result.findings) { assert.ok(['ok', 'info', 'warn', 'fail'].includes(item.level)); assert.equal(typeof item.code, 'string'); assert.equal(typeof item.message, 'string'); assert.ok(!('fix' in item) || typeof item.fix === 'string'); } }); test('state is the worst finding level', async () => { const fixture = cleanFixture(); fixture.txt[KEDAI] = [['v=spf1 include:spf.mailhost.my +all']]; fixture.txt[`_dmarc.${KEDAI}`] = [['v=DMARC1; p=none']]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); assert.equal(result.state, 'fail'); assert.ok(result.findings.some((entry) => entry.level === 'fail')); }); test('a domain that does not exist is not-evaluated', async () => { const result = await check('nope.my', { dns: fakeDns({ missing: 'ENOTFOUND' }) }); assert.equal(result.state, 'not-evaluated'); assert.equal(finding(result, 'domain_not_found').level, 'info'); assert.equal(evidence(result, 'DNS').value, 'no records'); }); test('a domain that exists but publishes nothing at all fails SPF, never "not-evaluated"', async () => { // ENODATA means the name exists — that is a real (empty) email setup, not a DNS failure. const result = await check(KEDAI, { dns: fakeDns({}) }); assert.equal(finding(result, 'spf_missing').level, 'fail'); assert.equal(finding(result, 'mx_missing').level, 'warn'); assert.equal(result.state, 'fail'); }); test('a domain with MX but no TXT at all fails SPF and warns DMARC', async () => { const result = await check(KEDAI, { dns: fakeDns({ mx: { [KEDAI]: [{ exchange: 'mx.mailhost.my', priority: 10 }] }, a: { 'mx.mailhost.my': ['203.115.10.7'] } }) }); assert.equal(finding(result, 'spf_missing').level, 'fail'); assert.equal(finding(result, 'dmarc_missing').level, 'warn'); assert.equal(result.state, 'fail'); }); test('bad input is refused instead of being checked', async () => { const result = await check('not a domain', { dns: fakeDns({}) }); assert.equal(result.state, 'fail'); assert.equal(finding(result, 'bad_input').level, 'fail'); }); test('a dead MX host is reported without losing the working one', async () => { const fixture = cleanFixture(); fixture.mx[KEDAI] = [ { exchange: 'mx1.mailhost.my', priority: 10 }, { exchange: 'mx9.oldhost.my', priority: 20 } ]; const result = await check(KEDAI, { dns: fakeDns(fixture) }); const dead = finding(result, 'mx_host_no_address'); assert.equal(dead.level, 'warn'); assert.match(dead.message, /mx9\.oldhost\.my/); assert.equal(evidence(result, 'MX address').value, 'mx1.mailhost.my → 203.115.10.5'); }); test('analyseMailAuth is pure and usable without DNS', () => { const result = analyseMailAuth( { domain: 'pure.my', fatal: null, spfRecords: ['v=spf1 -all'], spfLookups: { lookups: 0, cycles: 0, depthCapped: false, unreadable: 0, missingTargets: [], chain: [] }, dmarc: { checked: true, code: null, record: 'v=DMARC1; p=reject', parsed: parseDmarc('v=DMARC1; p=reject') }, dkim: DKIM_SELECTORS.map((selector) => ({ selector, name: `${selector}._domainkey.pure.my`, status: 'none', key: false })), mx: { checked: true, code: null, records: [{ exchange: 'mx.pure.my', priority: 10 }], nullMx: false, addresses: [{ host: 'mx.pure.my', ok: true, addresses: ['203.0.113.50'], code: null, empty: false }] } }, { now: Date.parse('2026-11-10T04:00:00Z') } ); assert.equal(result.state, 'ok'); assert.equal(result.checkedAt, '2026-11-10T04:00:00.000Z'); assert.equal(result.summary, 'Mail can be delivered, and only your own servers can send as your domain.'); });