feat(check): seven checks, and the one picture worth having

Adds mail-transport (MTA-STS + policy file, TLS-RPT, BIMI) and hardening (compression,
CAA vs the issuing CA, cookie flags, version banners). Wiring them exposed a real gap:
net-guard pinned accept-encoding to identity, so the compression question could only ever
be answered 'not measured'. requestOnce now takes acceptEncoding, decompresses, and returns
both the wire size and the decoded size - hoelee.com measures 39.6 KB against 119.4 KB.

The hub gets a CSS trust-flow diagram instead of a picture: four boxes and three arrows
cost no request, stay sharp, and can be corrected without re-exporting anything. The
1200x630 social card is drawn in HTML and screenshotted, because a diffusion model renders
'technical' as soft glyph soup that turns to mud at WhatsApp thumbnail size.
This commit is contained in:
hoelee committed 2026-11-10 19:20:16 +08:00
1 parent e407c0daba
commit 8925d10424
12 files changed
+3299 -34

No files matched your search

+673
View File
@@ -0,0 +1,673 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
analyseHardening,
analyseCompression,
analyseCookies,
checkHardening,
caaAuthorisesIssuer,
caaNames,
normaliseCaa,
parseSetCookie,
detectVersionBanner,
isSessionCookie,
worstLevel,
createRequestBudget,
describeFailure,
REQUEST_BUDGET,
PAGE_MAX_BYTES,
GUARD_HONOURS_COMPRESSION
} from '../src/checks/hardening.mjs';
import { NetGuardError } from '../src/lib/net-guard.mjs';
// Everything here is a fixture object and an injected fake. No server is started, no socket is
// opened, no name is resolved, and the clock is pinned with `now`.
const NOW = Date.UTC(2026, 0, 15, 12, 0, 0);
const ISO_NOW = '2026-01-15T12:00:00.000Z';
const CLEAN_HEADERS = {
'content-encoding': 'gzip',
'content-length': '18432',
vary: 'Accept-Encoding',
server: 'nginx',
'set-cookie': ['PHPSESSID=abc123; Path=/; HttpOnly; Secure; SameSite=Lax']
};
const LETS_ENCRYPT = { CN: 'R11', O: "Let's Encrypt" };
function facts(overrides = {}) {
return {
host: 'www.example.com',
url: 'https://www.example.com/',
response: {
status: 200,
headers: { ...CLEAN_HEADERS },
bodyBytes: 96411,
truncated: false
},
compression: {
contentEncoding: 'gzip',
contentLength: 18432,
receivedBytes: 18432,
decodedBytes: 96411,
requestedEncoding: 'br, gzip',
honoured: true,
vary: 'Accept-Encoding'
},
caa: { name: 'example.com', records: [{ critical: 0, issue: 'letsencrypt.org' }] },
certificate: { issuer: LETS_ENCRYPT },
...overrides
};
}
const codes = (result) => result.findings.map((finding) => finding.code);
const levelOf = (result, code) => (result.findings.find((finding) => finding.code === code) || {}).level;
/** A fake transport: net-guard's requestOnce signature, no network. */
function fakeRequest(responses) {
const calls = [];
const list = Array.isArray(responses) ? responses : [responses];
const fn = async (url, options = {}) => {
calls.push({ url, options });
const next = list[Math.min(calls.length - 1, list.length - 1)];
if (typeof next === 'function') return next(url, options);
if (next instanceof Error) throw next;
return { url, status: 200, headers: {}, body: '', truncated: false, tls: null, timing: { totalMs: 12 }, ...next };
};
fn.calls = calls;
return fn;
}
function fakeDns(records, { throwOn = null } = {}) {
const asked = [];
return {
asked,
async resolveCaa(name) {
asked.push(name);
if (throwOn) {
const err = new Error('no record');
err.code = throwOn;
throw err;
}
if (typeof records === 'function') return records(name);
if (!records) {
const err = new Error('no record');
err.code = 'ENODATA';
throw err;
}
return records;
}
};
}
// ---------------------------------------------------------------------------------------------
// envelope shape
// ---------------------------------------------------------------------------------------------
test('envelope carries the contract keys and an ISO checkedAt, not epoch ms', () => {
const result = analyseHardening(facts(), { now: NOW });
assert.deepEqual(
Object.keys(result).sort(),
['checkedAt', 'evidence', 'findings', 'fromCache', 'id', 'state', 'summary'].sort()
);
assert.equal(result.id, 'hardening');
assert.equal(result.checkedAt, ISO_NOW);
assert.equal(typeof result.checkedAt, 'string');
assert.match(result.checkedAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
assert.equal(result.fromCache, false);
assert.equal(typeof result.summary, 'string');
assert.ok(result.summary.length > 0);
for (const row of result.evidence) {
assert.equal(typeof row.label, 'string');
assert.equal(typeof row.value, 'string');
}
for (const finding of result.findings) {
assert.ok(['ok', 'info', 'warn', 'fail'].includes(finding.level));
assert.equal(typeof finding.code, 'string');
assert.equal(typeof finding.message, 'string');
assert.ok(finding.message.length > 10);
}
});
test('a fully clean page is state ok with four positive codes', () => {
const result = analyseHardening(facts(), { now: NOW });
assert.equal(result.state, 'ok');
assert.deepEqual(codes(result), [
'hardening_compression_on',
'hardening_caa_authorises_issuer',
'hardening_cookies_flagged',
'hardening_no_version_banner'
]);
assert.ok(result.summary.startsWith('Checked how this page is served:'));
});
test('state equals the worst finding, with info folded into ok', () => {
assert.equal(worstLevel([{ level: 'ok' }, { level: 'info' }]), 'ok');
assert.equal(worstLevel([{ level: 'info' }, { level: 'warn' }]), 'warn');
assert.equal(worstLevel([]), 'ok');
const withWarning = analyseHardening(
facts({ response: { status: 200, headers: { 'set-cookie': ['JSESSIONID=1; Path=/'] }, bodyBytes: 900 } }),
{ now: NOW }
);
assert.equal(withWarning.state, 'warn');
});
test('there is no score, no grade and no "at risk" phrasing anywhere', () => {
const result = analyseHardening(facts(), { now: NOW });
assert.equal(result.score, undefined);
assert.equal(result.grade, undefined);
assert.equal(result.rating, undefined);
for (const finding of result.findings) {
assert.doesNotMatch(finding.message, /at risk|security score|grade|points|\b\d+\s*\/\s*100\b/i);
}
assert.doesNotMatch(result.summary, /at risk|security score|grade/i);
});
// ---------------------------------------------------------------------------------------------
// question 1 — compression
// ---------------------------------------------------------------------------------------------
test('measured compression reports the real saving it computed', () => {
const result = analyseHardening(facts(), { now: NOW });
const finding = result.findings.find((f) => f.code === 'hardening_compression_on');
assert.equal(finding.level, 'ok');
// 1 - 18432/96411 = 0.8088…
assert.match(finding.message, /about 81% smaller/);
assert.match(finding.message, /18\.0 KB/);
assert.match(finding.message, /94\.2 KB/);
const row = result.evidence.find((r) => r.label === 'compression');
assert.match(row.value, /gzip/);
assert.match(row.value, /81% smaller/);
});
test('Content-Length absent: says "compressed" with no percentage, and never invents a saving', () => {
const result = analyseHardening(
facts({
response: { status: 200, headers: { 'content-encoding': 'br' }, bodyBytes: 12000 },
compression: { contentEncoding: 'br', contentLength: null, receivedBytes: 12000, decodedBytes: null, honoured: true }
}),
{ now: NOW }
);
const finding = result.findings.find((f) => f.code === 'hardening_compression_on_unmeasured');
assert.equal(finding.level, 'ok');
assert.match(finding.message, /sent the page br-compressed/);
assert.match(finding.message, /not measured/);
assert.doesNotMatch(finding.message, /instead of|smaller\.|%/);
});
test('compression measured but larger than the plain page: no gain, never a failure', () => {
const result = analyseHardening(
facts({
compression: { contentEncoding: 'gzip', contentLength: 412, receivedBytes: 412, decodedBytes: 398, honoured: true }
}),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_compression_no_gain'), 'info');
assert.equal(result.state, 'ok');
});
test('no compression, asked for it: info, not a failure', () => {
const result = analyseHardening(
facts({
response: { status: 200, headers: { 'content-length': '51200' }, bodyBytes: 51200 },
compression: { contentEncoding: null, contentLength: 51200, receivedBytes: 51200, decodedBytes: 51200, honoured: true }
}),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_compression_off'), 'info');
assert.equal(result.state, 'ok');
assert.ok(!result.findings.some((f) => f.level === 'fail'));
});
test('compression not asked for (net-guard asks identity): reported as not measured, not as absent', () => {
const result = analyseHardening(
facts({
response: { status: 200, headers: { 'content-length': '51200' }, bodyBytes: 51200 },
compression: { contentEncoding: null, contentLength: 51200, receivedBytes: 51200, honoured: false }
}),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_compression_not_measured'), 'info');
assert.ok(!codes(result).includes('hardening_compression_off'));
assert.equal(result.state, 'ok');
});
// The flag is a claim about net-guard, so it is checked against net-guard's own source rather
// than against itself: the day someone removes the option, this fails instead of the check
// quietly reporting "not measured" forever.
test('compression is asked for, and net-guard really accepts the option', async () => {
const { readFile } = await import('node:fs/promises');
const guard = await readFile(new URL('../src/lib/net-guard.mjs', import.meta.url), 'utf8');
assert.equal(GUARD_HONOURS_COMPRESSION, true);
assert.match(guard, /acceptEncoding = 'identity'/);
assert.match(guard, /'accept-encoding': acceptEncoding/);
assert.match(guard, /decodedBytes/);
});
test('Vary: Accept-Encoding with an identity answer is reported as offered, not measured', () => {
const result = analyseHardening(
facts({
response: { status: 200, headers: { vary: 'Accept-Encoding', 'content-length': '900' }, bodyBytes: 900 },
compression: { contentEncoding: null, contentLength: 900, receivedBytes: 900, honoured: false, vary: 'Accept-Encoding' }
}),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_compression_available'), 'info');
assert.equal(result.state, 'ok');
});
test('analyseCompression does the arithmetic and refuses to guess', () => {
const measured = analyseCompression({ contentEncoding: 'gzip', contentLength: 2500, receivedBytes: 2500, decodedBytes: 10000 });
assert.equal(measured.measured, true);
assert.equal(measured.savingPercent, 75);
assert.equal(measured.savedBytes, 7500);
const half = analyseCompression({ contentEncoding: 'gzip', receivedBytes: 2500, decodedBytes: null });
assert.equal(half.measured, false);
assert.equal(half.savingPercent, null);
const identity = analyseCompression({ contentEncoding: 'identity', contentLength: 10, decodedBytes: 10 });
assert.equal(identity.encoding, null);
assert.equal(identity.measured, false);
});
// ---------------------------------------------------------------------------------------------
// question 2 — CAA
// ---------------------------------------------------------------------------------------------
test('no CAA record is info and says plainly it is not a fault', () => {
const result = analyseHardening(facts({ caa: { name: null, records: [], error: null } }), { now: NOW });
const finding = result.findings.find((f) => f.code === 'hardening_caa_absent');
assert.equal(finding.level, 'info');
assert.match(finding.message, /any certificate authority may issue/);
assert.match(finding.message, /not a fault/);
assert.equal(result.state, 'ok');
});
test('CAA present but the certificate could not be read: record reported, comparison not made', () => {
const result = analyseHardening(facts({ certificate: null }), { now: NOW });
const finding = result.findings.find((f) => f.code === 'hardening_caa_not_compared');
assert.equal(finding.level, 'info');
assert.match(finding.message, /were not compared/);
assert.ok(result.evidence.some((row) => row.label === 'CAA' && row.value.includes('letsencrypt.org')));
assert.equal(result.state, 'ok');
});
test('CAA that does not name the issuing CA is a warn, never a fail', () => {
const result = analyseHardening(
facts({ caa: { name: 'example.com', records: [{ critical: 0, issue: 'digicert.com' }] } }),
{ now: NOW }
);
const finding = result.findings.find((f) => f.code === 'hardening_caa_issuer_mismatch');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /issued by Let's Encrypt/);
assert.match(finding.message, /only allows digicert\.com/);
assert.equal(result.state, 'warn');
assert.notEqual(result.state, 'fail');
assert.ok(!result.findings.some((f) => f.level === 'fail'));
});
test('CAA issue ";" with a certificate being served is info, not an accusation', () => {
const result = analyseHardening(
facts({ caa: { name: 'example.com', records: [{ critical: 0, issue: ';' }] } }),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_caa_deny_all'), 'info');
assert.equal(result.state, 'ok');
assert.ok(!codes(result).includes('hardening_caa_issuer_mismatch'));
});
test('CAA lookup that could not run is info and leaves the other three answers intact', () => {
const result = analyseHardening(facts({ caa: { name: null, records: [], error: 'no resolver' } }), { now: NOW });
assert.equal(levelOf(result, 'hardening_caa_unavailable'), 'info');
assert.ok(codes(result).includes('hardening_compression_on'));
assert.ok(codes(result).includes('hardening_cookies_flagged'));
assert.equal(result.state, 'ok');
});
test('CAA comparison understands the CAs small sites actually use', () => {
assert.equal(caaAuthorisesIssuer([{ issue: 'letsencrypt.org' }], LETS_ENCRYPT).status, 'match');
assert.equal(caaAuthorisesIssuer([{ issue: 'digicert.com' }], { CN: 'DigiCert TLS RSA SHA256 2020 CA1', O: 'DigiCert Inc' }).status, 'match');
assert.equal(caaAuthorisesIssuer([{ issue: 'sectigo.com' }], { CN: 'R36', O: 'ZeroSSL' }).status, 'match');
assert.equal(caaAuthorisesIssuer([{ issue: 'pki.goog' }], { CN: 'GTS CA 1P5', O: 'Google Trust Services' }).status, 'match');
assert.equal(caaAuthorisesIssuer([{ issue: 'letsencrypt.org' }], { CN: 'R11', O: 'DigiCert Inc' }).status, 'mismatch');
assert.equal(caaAuthorisesIssuer([{ issue: 'letsencrypt.org' }], null).status, 'no-issuer');
assert.equal(caaAuthorisesIssuer([], LETS_ENCRYPT).status, 'no-caa');
assert.equal(caaAuthorisesIssuer([{ issue: ';' }], LETS_ENCRYPT).status, 'deny-all');
});
test('CAA parameters and raw record strings are both understood', () => {
const parsed = normaliseCaa(['0 issue "letsencrypt.org; validationmethods=dns-01"', '0 iodef "mailto:[email protected]"']);
assert.deepEqual(parsed[0], { issue: 'letsencrypt.org; validationmethods=dns-01' });
assert.deepEqual(parsed[1], { iodef: 'mailto:[email protected]' });
const policy = caaAuthorisesIssuer(parsed, LETS_ENCRYPT);
assert.equal(policy.status, 'match');
assert.deepEqual(policy.allowed, ['letsencrypt.org']);
});
test('the CAA walk stops at the registrable name, com.my included', () => {
assert.deepEqual(caaNames('www.example.com'), ['www.example.com', 'example.com']);
assert.deepEqual(caaNames('example.com.my'), ['example.com.my']);
assert.deepEqual(caaNames('shop.example.com.my'), ['shop.example.com.my', 'example.com.my']);
assert.deepEqual(caaNames('a.b.c.example.com'), ['a.b.c.example.com', 'b.c.example.com', 'c.example.com', 'example.com']);
assert.deepEqual(caaNames('example'), []);
});
// ---------------------------------------------------------------------------------------------
// question 3 — cookies
// ---------------------------------------------------------------------------------------------
test('a session cookie without Secure is a warn and names the consequence', () => {
const result = analyseHardening(
facts({ response: { status: 200, headers: { 'set-cookie': ['PHPSESSID=abc; Path=/; HttpOnly'] }, bodyBytes: 800 } }),
{ now: NOW }
);
const finding = result.findings.find((f) => f.code === 'hardening_cookie_missing_flag');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /PHPSESSID/);
assert.match(finding.message, /without Secure/);
assert.match(finding.message, /plain http/);
assert.equal(result.state, 'warn');
});
test('a session cookie without HttpOnly is a warn; both missing is still one warn per cookie', () => {
const result = analyseHardening(
facts({ response: { status: 200, headers: { 'set-cookie': ['laravel_session=x; Path=/'] }, bodyBytes: 800 } }),
{ now: NOW }
);
const warns = result.findings.filter((f) => f.code === 'hardening_cookie_missing_flag');
assert.equal(warns.length, 1);
assert.equal(warns[0].level, 'warn');
assert.match(warns[0].message, /HttpOnly and Secure/);
assert.equal(result.state, 'warn');
});
test('an analytics cookie without flags is info only', () => {
const result = analyseHardening(
facts({ response: { status: 200, headers: { 'set-cookie': ['_ga=GA1.1.2.3; Path=/; Max-Age=63072000'] }, bodyBytes: 800 } }),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_cookie_optional_flag'), 'info');
assert.ok(!result.findings.some((f) => f.level === 'warn'));
assert.equal(result.state, 'ok');
});
test('a well-flagged session cookie with no SameSite is info, not a warning', () => {
const result = analyseHardening(
facts({ response: { status: 200, headers: { 'set-cookie': ['PHPSESSID=abc; Path=/; HttpOnly; Secure'] }, bodyBytes: 800 } }),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_cookie_no_samesite'), 'info');
assert.equal(levelOf(result, 'hardening_cookies_flagged'), 'ok');
assert.equal(result.state, 'ok');
});
test('no cookies at all is info, and parseSetCookie reads every flag', () => {
const result = analyseHardening(
facts({ response: { status: 200, headers: { 'content-encoding': 'gzip' }, bodyBytes: 800 } }),
{ now: NOW }
);
assert.equal(levelOf(result, 'hardening_cookies_none'), 'info');
const cookie = parseSetCookie('sid=1; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600');
assert.equal(cookie.name, 'sid');
assert.equal(cookie.httpOnly, true);
assert.equal(cookie.secure, true);
assert.equal(cookie.sameSite, 'Strict');
assert.equal(cookie.maxAge, 3600);
assert.equal(isSessionCookie(cookie), true);
assert.equal(isSessionCookie(parseSetCookie('_gid=1; Max-Age=86400')), false);
assert.equal(isSessionCookie(parseSetCookie('theme=dark; Max-Age=86400')), false);
assert.equal(isSessionCookie(parseSetCookie('theme=dark')), true, 'no expiry means a session cookie');
});
test('analyseCookies handles a string set-cookie as well as an array', () => {
const one = analyseCookies(['sid=1; HttpOnly']);
const many = analyseCookies(['sid=1; HttpOnly', 'other=2']);
assert.equal(one.findings.filter((f) => f.code === 'hardening_cookie_missing_flag').length, 1);
assert.equal(many.findings.filter((f) => f.code === 'hardening_cookie_missing_flag').length, 2);
});
// ---------------------------------------------------------------------------------------------
// question 4 — version banners
// ---------------------------------------------------------------------------------------------
test('a version banner is info, never a failure', () => {
const result = analyseHardening(
facts({ response: { status: 200, headers: { server: 'nginx/1.18.0', 'content-encoding': 'gzip' }, bodyBytes: 900 } }),
{ now: NOW }
);
const finding = result.findings.find((f) => f.code === 'hardening_version_banner');
assert.equal(finding.level, 'info');
assert.match(finding.message, /Server: nginx\/1\.18\.0/);
assert.equal(result.state, 'ok');
});
test('detectVersionBanner picks the three headers that leak a version and ignores a bare product name', () => {
assert.deepEqual(detectVersionBanner({ server: 'nginx/1.18.0' }), [{ header: 'Server', value: 'nginx/1.18.0' }]);
assert.deepEqual(detectVersionBanner({ 'x-powered-by': 'PHP/7.4.33' }), [{ header: 'X-Powered-By', value: 'PHP/7.4.33' }]);
assert.deepEqual(detectVersionBanner({ 'x-aspnet-version': '4.0.30319.42000' }), [
{ header: 'X-AspNet-Version', value: '4.0.30319.42000' }
]);
assert.deepEqual(detectVersionBanner({ server: 'cloudflare' }), []);
assert.deepEqual(detectVersionBanner({ server: 'nginx' }), []);
assert.deepEqual(detectVersionBanner({}), []);
});
// ---------------------------------------------------------------------------------------------
// blocked, broken and unreadable — never a red verdict
// ---------------------------------------------------------------------------------------------
const NOT_EVALUATED_CASES = [
['403 firewall', facts({ response: { status: 403, headers: { 'cf-ray': 'x' }, bodyBytes: 40 }, blocked: { blocked: true, reason: 'status 403' } })],
['429 rate limit', facts({ response: { status: 429, headers: {}, bodyBytes: 40 }, blocked: { blocked: true, reason: 'status 429' } })],
['bot challenge', facts({ response: { status: 200, headers: { 'cf-ray': 'x' }, bodyBytes: 900 }, blocked: { blocked: true, reason: 'bot challenge (CDN)' } })],
['timeout', { host: 'example.com', error: { code: 'timeout' } }],
['SERVFAIL', { host: 'example.com', error: { code: 'dns_timeout' } }],
['NXDOMAIN', { host: 'example.com', error: { code: 'dns_nxdomain' } }],
['no response at all', { host: 'example.com', response: null }]
];
for (const [label, scenario] of NOT_EVALUATED_CASES) {
test(`${label} is not-evaluated with zero findings against the site`, () => {
const result = analyseHardening(scenario, { now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.deepEqual(result.findings, []);
assert.equal(result.checkedAt, ISO_NOW);
assert.doesNotMatch(result.summary, /insecure|vulnerable|at risk|failed/i);
assert.ok(result.summary.length > 20);
});
}
test('describeFailure never blames the visitor for a firewall or a timeout', () => {
for (const code of ['timeout', 'dns_timeout', 'dns_nxdomain', 'refused', 'tls_invalid', 'tls_expired']) {
const text = describeFailure({ code });
assert.doesNotMatch(text, /insecure|vulnerable|at risk/i);
assert.match(text, /nothing was judged|nothing to look at|no page to look at|was not read/i);
}
});
// ---------------------------------------------------------------------------------------------
// the network half — one fake, no sockets
// ---------------------------------------------------------------------------------------------
test('one page GET, explicit Accept, compression asked for, 256 KB cap', async () => {
const request = fakeRequest({ status: 200, headers: { ...CLEAN_HEADERS }, body: 'x'.repeat(900), tls: { issuer: LETS_ENCRYPT } });
const result = await checkHardening('www.example.com', {
request,
dns: fakeDns([{ critical: 0, issue: 'letsencrypt.org' }]),
now: NOW
});
assert.equal(request.calls.length, 1, 'exactly one outbound request');
const { url, options } = request.calls[0];
assert.equal(url, 'https://www.example.com/');
assert.equal(options.accept, 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5');
assert.equal(options.acceptEncoding, 'br, gzip');
assert.equal(options.maxBytes, PAGE_MAX_BYTES);
assert.equal(PAGE_MAX_BYTES, 256 * 1024);
assert.equal(result.state, 'ok');
assert.equal(result.checkedAt, ISO_NOW);
assert.equal(result.fromCache, false);
});
test('the certificate comes off the same response — no second connection for the CAA comparison', async () => {
const request = fakeRequest({ status: 200, headers: {}, body: 'ok', tls: { issuer: LETS_ENCRYPT } });
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
assert.equal(request.calls.length, 1);
assert.equal(levelOf(result, 'hardening_caa_authorises_issuer'), 'ok');
});
test('CAA is read for the typed host and falls back up the tree', async () => {
const request = fakeRequest({ status: 200, headers: {}, body: 'ok' });
const resolver = {
asked: [],
async resolveCaa(name) {
resolver.asked.push(name);
if (name === 'example.com') return [{ issue: 'letsencrypt.org' }];
const err = new Error('no data');
err.code = 'ENODATA';
throw err;
}
};
const result = await checkHardening('www.example.com', { request, dns: resolver, now: NOW });
assert.deepEqual(resolver.asked, ['www.example.com', 'example.com']);
assert.ok(result.evidence.some((row) => row.label === 'CAA' && row.value.startsWith('example.com:')));
});
test('a redirect is followed once, through the guard, and both slots of the budget are used', async () => {
const request = fakeRequest([
{ status: 301, headers: { location: 'https://www.example.com/' }, body: '' },
{ status: 200, headers: { ...CLEAN_HEADERS }, body: 'x'.repeat(500), tls: { issuer: LETS_ENCRYPT } }
]);
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
assert.equal(request.calls.length, 2);
assert.equal(request.calls[1].url, 'https://www.example.com/');
assert.equal(result.state, 'ok');
assert.equal(REQUEST_BUDGET, 2);
});
test('a redirect to a port the guard refuses is not followed, and that is info', async () => {
const request = fakeRequest({ status: 301, headers: { location: 'https://example.com:8443/x' }, body: '' });
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
assert.equal(request.calls.length, 1);
assert.equal(levelOf(result, 'hardening_redirect_not_followed'), 'info');
assert.equal(result.state, 'ok');
});
test('a second redirect is reported rather than chased', async () => {
const request = fakeRequest([
{ status: 301, headers: { location: 'https://www.example.com/' }, body: '' },
{ status: 302, headers: { location: 'https://www.example.com/en/' }, body: '' }
]);
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
assert.equal(request.calls.length, 2);
assert.equal(levelOf(result, 'hardening_redirect_chain'), 'info');
});
test('a 403 from the real fake transport is not-evaluated with no findings', async () => {
const request = fakeRequest({ status: 403, headers: { server: 'nginx/1.18.0' }, body: '<h1>Forbidden</h1>' });
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.deepEqual(result.findings, []);
assert.match(result.summary, /firewall|normal protection/);
});
test('a bot challenge page is not-evaluated even on a 200', async () => {
const request = fakeRequest({ status: 200, headers: { 'cf-ray': 'abc' }, body: '<title>Just a moment...</title>' });
const result = await checkHardening('example.com', { request, dns: fakeDns(null), now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.deepEqual(result.findings, []);
});
test('a thrown NetGuardError becomes not-evaluated, not an exception', async () => {
const request = fakeRequest(new NetGuardError('timeout', 'The site did not answer in time.'));
const result = await checkHardening('example.com', { request, dns: fakeDns(null), now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.deepEqual(result.findings, []);
assert.ok(result.evidence.some((row) => row.label === 'reason' && row.value === 'timeout'));
assert.equal(result.checkedAt, ISO_NOW);
});
test('a private address is refused before any request is made', async () => {
const request = fakeRequest({ status: 200, headers: {}, body: '' });
const result = await checkHardening('127.0.0.1', { request, dns: fakeDns(null), now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.equal(request.calls.length, 0);
assert.ok(result.evidence.some((row) => row.label === 'reason' && row.value === 'ip_literal'));
assert.deepEqual(Object.keys(result).sort(), ['checkedAt', 'evidence', 'findings', 'fromCache', 'id', 'state', 'summary'].sort());
});
test('a resolver without resolveCaa is reported as unavailable, not as "no CAA record"', async () => {
const request = fakeRequest({ status: 200, headers: {}, body: 'ok' });
const result = await checkHardening('example.com', { request, dns: {}, now: NOW });
assert.equal(levelOf(result, 'hardening_caa_unavailable'), 'info');
assert.ok(!codes(result).includes('hardening_caa_absent'));
});
test('a SERVFAIL on CAA is unavailable, and the page answers still stand', async () => {
const request = fakeRequest({ status: 200, headers: { 'content-encoding': 'gzip', 'content-length': '10' }, body: 'x'.repeat(90) });
const result = await checkHardening('example.com', { request, dns: fakeDns(null, { throwOn: 'ESERVFAIL' }), now: NOW });
assert.equal(levelOf(result, 'hardening_caa_unavailable'), 'info');
assert.ok(codes(result).includes('hardening_compression_on_unmeasured'));
});
test('the real transport is never called when a fake is injected, and the analyser never calls one', async () => {
// If checkHardening reached for the real requestOnce, this test would open a socket. It cannot:
// `request` is always the injected fake here, and analyseHardening takes no transport at all.
const request = fakeRequest({ status: 200, headers: {}, body: 'ok' });
await checkHardening('example.com', { request, dns: fakeDns(null), now: NOW });
assert.equal(request.calls.length, 1);
// The analyser is synchronous and takes no transport at all: it cannot reach the network.
const pure = analyseHardening(facts(), { now: NOW });
assert.ok(!(pure instanceof Promise));
assert.equal(pure.id, 'hardening');
});
// ---------------------------------------------------------------------------------------------
// budget enforcement
// ---------------------------------------------------------------------------------------------
test('the request budget is a code-level cap, not a comment', () => {
const budget = createRequestBudget(2);
assert.equal(budget.spend('first'), 1);
assert.equal(budget.spend('second'), 2);
assert.throws(() => budget.spend('third'), (err) => {
assert.equal(err.code, 'budget_exhausted');
assert.match(err.message, /2-request budget/);
return true;
});
assert.equal(budget.remaining, 0);
});
test('a budget of one makes a redirect follow fail closed', async () => {
// The module builds its own budget, so this proves the mechanism the module uses rather than
// reaching into it: one spend, then a second is refused.
const budget = createRequestBudget(1);
budget.spend('page fetch');
assert.throws(() => budget.spend('redirect follow'), /budget_exhausted|budget/);
});
// ---------------------------------------------------------------------------------------------
// invariants across every scenario
// ---------------------------------------------------------------------------------------------
test('no scenario in this file can reach state "fail"', () => {
const scenarios = [
facts(),
facts({ caa: { name: null, records: [], error: null } }),
facts({ caa: { name: 'example.com', records: [{ issue: 'digicert.com' }] } }),
facts({ certificate: null }),
facts({ response: { status: 200, headers: { 'set-cookie': ['sid=1'] }, bodyBytes: 900 } }),
facts({ response: { status: 200, headers: { server: 'nginx/1.18.0', 'x-powered-by': 'PHP/7.4.33' }, bodyBytes: 900 } }),
facts({ compression: { contentEncoding: null, contentLength: 900, receivedBytes: 900, honoured: true } }),
{ host: 'example.com', response: null },
{ host: 'example.com', error: { code: 'timeout' } }
];
for (const scenario of scenarios) {
const result = analyseHardening(scenario, { now: NOW });
assert.notEqual(result.state, 'fail', `scenario reached fail: ${JSON.stringify(scenario.response || scenario.error)}`);
assert.ok(['ok', 'warn', 'not-evaluated'].includes(result.state));
}
});
+739
View File
@@ -0,0 +1,739 @@
// Offline tests for mail-transport: a table-driven fake resolver, a route-table fake request and a
// fixed clock. Nothing here resolves a name, opens a socket, or reads the real time.
//
// The assertions that matter most are the wording ones. A TXT record on its own protects nothing,
// a blocked policy fetch is not a finding, and the absence of all three records is the normal
// state of a Malaysian SME — each of those is pinned below.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
checkMailTransport,
analyseMailTransport,
parseMtaStsTxt,
parseMtaStsPolicy,
parseTlsRptTxt,
parseBimiTxt,
parseTags,
policyUrl,
buildSummary,
worstLevel,
registrableApex,
REQUEST_BUDGET,
POLICY_TIMEOUT_MS,
POLICY_MAX_BYTES,
MTA_STS_NAME,
TLS_RPT_NAME,
BIMI_NAME
} from '../src/checks/mail-transport.mjs';
import { NetGuardError } from '../src/lib/net-guard.mjs';
// 10 Nov 2026 00:00 UTC — every checkedAt below is this instant.
const NOW = Date.UTC(2026, 10, 10, 0, 0, 0);
const ISO = '2026-11-10T00:00:00.000Z';
const POLICY_TEXT = 'version: STSv1\nmode: enforce\nmax_age: 86400\nmx: mx.zoho.com\nmx: mx2.zoho.com\n';
const POLICY_URL = 'https://mta-sts.example.com/.well-known/mta-sts.txt';
// ---------------------------------------------------------------------------
// fakes
// ---------------------------------------------------------------------------
/** TXT answers arrive as arrays of chunk arrays, exactly like node:dns. */
function tableDns(table = {}, { fail = {} } = {}) {
const calls = [];
const resolveTxt = async (name) => {
calls.push(name);
if (name in fail) throw Object.assign(new Error(`${fail[name]} ${name}`), { code: fail[name] });
if (!(name in table)) throw Object.assign(new Error(`ENODATA ${name}`), { code: 'ENODATA' });
const value = table[name];
if (value instanceof Error) throw value;
return value;
};
resolveTxt.calls = calls;
return { resolveTxt };
}
function routeRequest(routes = {}) {
const calls = [];
const fn = async (url, options = {}) => {
calls.push({ url, options });
const route = routes[url];
if (route === undefined) throw new NetGuardError('dns_nxdomain', `no route for ${url}`);
if (route instanceof Error) throw route;
return { status: 200, headers: {}, body: '', url, ...route };
};
fn.calls = calls;
return fn;
}
const txt = (record) => [[record]];
function gatheredFixture(overrides = {}) {
return {
domain: 'example.com',
mtaSts: { checked: true, present: false, valid: false, record: null, id: null, count: 0 },
tlsRpt: { checked: true, present: false, valid: false, rua: [], record: null },
bimi: { checked: true, present: false, valid: false, location: null, authority: null, record: null },
dmarc: { checked: true, record: null, parsed: null },
policy: { attempted: false, ok: false, kind: 'skipped' },
fatal: null,
...overrides
};
}
function policyOk(text = POLICY_TEXT) {
return { attempted: true, ok: true, kind: 'ok', status: 200, text, parsed: parseMtaStsPolicy(text) };
}
const codes = (result) => result.findings.map((finding) => finding.code);
const levels = (result) => result.findings.map((finding) => finding.level);
// ---------------------------------------------------------------------------
// record parsing
// ---------------------------------------------------------------------------
test('an MTA-STS TXT record is read for its id and nothing more', () => {
const parsed = parseMtaStsTxt(['v=STSv1; id=20240101T000000']);
assert.equal(parsed.present, true);
assert.equal(parsed.valid, true);
assert.equal(parsed.id, '20240101T000000');
// The TXT says nothing about enforcement; the mode lives in the policy file.
assert.equal(Object.prototype.hasOwnProperty.call(parsed, 'mode'), false);
});
test('a TXT record that is not v=STSv1 is present but not valid', () => {
const parsed = parseMtaStsTxt(['v=STSv1x; id=abc']);
assert.equal(parsed.present, true);
assert.equal(parsed.valid, false);
assert.equal(parseMtaStsTxt([]).present, false);
});
test('a TXT record split across 255-byte chunks is joined before parsing', async () => {
// node:dns returns chunks; joining them is what makes an id that straddles the boundary readable.
const dns = tableDns({ [`_mta-sts.example.com`]: [['v=STSv1; id=20240101T00', '0000']] });
const result = await checkMailTransport('example.com', {
dns,
request: routeRequest({}),
now: NOW
});
const row = result.evidence.find((item) => item.label === 'MTA-STS record');
assert.match(row.value, /id=20240101T000000/);
});
test('the policy file is parsed for mode, max_age and mx patterns', () => {
const parsed = parseMtaStsPolicy(POLICY_TEXT);
assert.equal(parsed.isPolicy, true);
assert.equal(parsed.valid, true);
assert.equal(parsed.mode, 'enforce');
assert.equal(parsed.maxAge, 86400);
assert.deepEqual(parsed.mx, ['mx.zoho.com', 'mx2.zoho.com']);
});
test('a CRLF policy with comments and a trailing dot on mx still parses', () => {
const parsed = parseMtaStsPolicy('# generated\r\nversion: STSv1\r\nmode: TESTING\r\nmax_age: 604800\r\nmx: MX.Example.COM.\r\n');
assert.equal(parsed.mode, 'testing');
assert.equal(parsed.maxAge, 604800);
assert.deepEqual(parsed.mx, ['mx.example.com']);
});
test('a body with no version: STSv1 is not a policy at all', () => {
const parsed = parseMtaStsPolicy('<html><body>Welcome to nginx</body></html>');
assert.equal(parsed.isPolicy, false);
assert.equal(parsed.valid, false);
});
test('a policy missing max_age or mx is not valid', () => {
assert.equal(parseMtaStsPolicy('version: STSv1\nmode: enforce\nmx: mx.example.com\n').valid, false);
assert.equal(parseMtaStsPolicy('version: STSv1\nmode: enforce\nmax_age: 86400\n').valid, false);
});
test('a policy with an unknown mode is not valid', () => {
const parsed = parseMtaStsPolicy('version: STSv1\nmode: strict\nmax_age: 86400\nmx: mx.example.com\n');
assert.equal(parsed.mode, 'strict');
assert.equal(parsed.modeKnown, false);
assert.equal(parsed.valid, false);
});
test('TLS-RPT keeps every rua address and needs at least one', () => {
const parsed = parseTlsRptTxt(['v=TLSRPTv1; rua=mailto:[email protected],mailto:[email protected]']);
assert.equal(parsed.valid, true);
assert.deepEqual(parsed.rua, ['mailto:[email protected]', 'mailto:[email protected]']);
const noRua = parseTlsRptTxt(['v=TLSRPTv1;']);
assert.equal(noRua.present, true);
assert.equal(noRua.valid, false);
assert.deepEqual(noRua.rua, []);
});
test('BIMI is read for its logo and its optional certificate', () => {
const full = parseBimiTxt(['v=BIMI1; l=https://example.com/logo.svg; a=https://example.com/vmc.pem']);
assert.equal(full.valid, true);
assert.equal(full.location, 'https://example.com/logo.svg');
assert.equal(full.authority, 'https://example.com/vmc.pem');
const noLogo = parseBimiTxt(['v=BIMI1; l=']);
assert.equal(noLogo.present, true);
assert.equal(noLogo.valid, false);
assert.equal(noLogo.location, null);
});
test('the tag splitter ignores empty keys and keeps the last value', () => {
assert.deepEqual(parseTags('v=BIMI1; l=https://a/b.svg; =junk; l=https://c/d.svg'), {
v: 'BIMI1',
l: 'https://c/d.svg'
});
});
// ---------------------------------------------------------------------------
// absence is normal
// ---------------------------------------------------------------------------
test('no records at all is info, not a fault: one row, state ok', () => {
const result = analyseMailTransport(gatheredFixture(), { now: NOW });
assert.equal(result.state, 'ok');
assert.deepEqual(codes(result), ['mail_transport_none']);
assert.equal(levels(result)[0], 'info');
assert.match(result.summary, /normal for a small business/);
assert.match(result.summary, /MTA-STS is the one worth adding first/);
// Three separate "missing" rows would read as three faults.
assert.equal(result.findings.length, 1);
});
test('the absence row is an opportunity, never a verdict', () => {
const result = analyseMailTransport(gatheredFixture(), { now: NOW });
const text = JSON.stringify(result);
assert.doesNotMatch(text, /insecure|broken|fail|vulnerable|at risk/i);
});
test('when MTA-STS is absent but TLS-RPT is published, the summary says what is missing', () => {
const result = analyseMailTransport(gatheredFixture({
tlsRpt: { checked: true, present: true, valid: true, rua: ['mailto:[email protected]'], record: 'v=TLSRPTv1; rua=mailto:[email protected]' }
}), { now: NOW });
assert.equal(result.state, 'ok');
assert.ok(codes(result).includes('mta_sts_absent'));
assert.ok(codes(result).includes('tls_rpt_published'));
assert.match(result.summary, /publishes TLS-RPT but no MTA-STS record/);
});
// ---------------------------------------------------------------------------
// MTA-STS: the TXT is a promise, the policy file is the fact
// ---------------------------------------------------------------------------
test('a TXT record alone never claims protection', () => {
// The record is valid but the policy file was not read at all.
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: false, ok: false, kind: 'skipped' }
}), { now: NOW });
assert.equal(codes(result).includes('mta_sts_mode_enforce'), false);
assert.doesNotMatch(JSON.stringify(result.findings), /is protected|protects you|is enforcing/i);
assert.match(result.evidence[0].note, /only points at the policy file/);
});
test('mode=enforce is reported only after the policy file was read, and names the file', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk()
}), { now: NOW });
assert.equal(result.state, 'ok');
assert.deepEqual(codes(result).filter((code) => code.startsWith('mta_sts')), ['mta_sts_mode_enforce']);
const finding = result.findings.find((item) => item.code === 'mta_sts_mode_enforce');
assert.match(finding.message, /policy file at https:\/\/mta-sts\.example\.com\/\.well-known\/mta-sts\.txt/);
assert.equal(result.evidence.find((item) => item.label === 'MTA-STS policy').value, 'mode=enforce, max_age=86400');
});
test('mode=testing is progress, not failure', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk('version: STSv1\nmode: testing\nmax_age: 86400\nmx: mx.example.com\n')
}), { now: NOW });
assert.equal(result.state, 'warn');
const finding = result.findings.find((item) => item.code === 'mta_sts_mode_testing');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /published but not enforced yet/);
assert.match(finding.message, /still deliver/);
assert.doesNotMatch(finding.message, /insecure|is broken|has failed/i);
assert.equal(result.findings.some((item) => item.level === 'fail'), false);
assert.match(result.summary, /progress rather than protection/);
});
test('mode=none is info: published, but nothing is protected', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk('version: STSv1\nmode: none\nmax_age: 86400\nmx: mx.example.com\n')
}), { now: NOW });
assert.equal(result.state, 'ok');
const finding = result.findings.find((item) => item.code === 'mta_sts_mode_none');
assert.equal(finding.level, 'info');
assert.match(finding.message, /nothing is protected/);
});
test('a TXT promise with a 404 policy is a broken promise, named with the URL', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'missing', code: 'http_404', status: 404, url: POLICY_URL }
}), { now: NOW });
assert.equal(result.state, 'warn');
const finding = result.findings.find((item) => item.code === 'mta_sts_policy_missing');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /https:\/\/mta-sts\.example\.com\/\.well-known\/mta-sts\.txt/);
assert.match(finding.message, /not there \(HTTP 404\)/);
assert.match(finding.message, /no policy/);
assert.match(result.summary, /promises a policy/);
});
test('a policy URL that answers 200 without version: STSv1 is a distinct finding', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'missing', code: 'not_a_policy', status: 200, url: POLICY_URL }
}), { now: NOW });
assert.equal(result.state, 'warn');
assert.ok(codes(result).includes('mta_sts_policy_not_a_policy'));
const finding = result.findings.find((item) => item.code === 'mta_sts_policy_not_a_policy');
assert.match(finding.message, /version: STSv1/);
});
test('a policy that is missing max_age or mx is never reported as enforcing', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk('version: STSv1\nmode: enforce\n')
}), { now: NOW });
assert.equal(result.state, 'warn');
assert.equal(codes(result).includes('mta_sts_mode_enforce'), false);
const finding = result.findings.find((item) => item.code === 'mta_sts_policy_malformed');
assert.match(finding.message, /missing a numeric max_age and an mx: line/);
assert.match(finding.message, /even though it says mode=enforce/);
});
test('a malformed _mta-sts TXT record is a warning, and no fetch is attempted', async () => {
const dns = tableDns({ '_mta-sts.example.com': txt('v=STSv1x; id=abc') });
const request = routeRequest({});
const result = await checkMailTransport('example.com', { dns, request, now: NOW });
assert.equal(result.state, 'warn');
assert.ok(codes(result).includes('mta_sts_txt_malformed'));
assert.equal(request.calls.length, 0);
});
test('an unreadable _mta-sts record says unknown, never "none is published"', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: false, code: 'ESERVFAIL', present: false, valid: false },
tlsRpt: { checked: true, present: true, valid: true, rua: ['mailto:[email protected]'] }
}), { now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.ok(codes(result).includes('mta_sts_not_checked'));
assert.doesNotMatch(result.summary, /No MTA-STS/);
assert.match(result.summary, /unknown rather than missing/);
assert.match(result.summary, /\(ESERVFAIL\)/);
});
test('a summary never mentions BIMI when no BIMI record exists', () => {
const result = analyseMailTransport(gatheredFixture({
tlsRpt: { checked: true, present: true, valid: true, rua: ['mailto:[email protected]'] },
dmarc: { checked: true, record: 'v=DMARC1; p=none;', parsed: { valid: true, p: 'none', pct: 100 } }
}), { now: NOW });
assert.doesNotMatch(result.summary, /BIMI/);
assert.match(result.summary, /publishes TLS-RPT but no MTA-STS record/);
});
// ---------------------------------------------------------------------------
// not-evaluated: a blocked fetch is not a finding
// ---------------------------------------------------------------------------
test('a policy fetch that times out is not-evaluated with the reason code, and no warn/fail', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'not-read', code: 'timeout', url: POLICY_URL }
}), { now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.equal(result.findings.some((finding) => finding.level === 'warn' || finding.level === 'fail'), false);
const finding = result.findings.find((item) => item.code === 'mta_sts_policy_not_read');
assert.equal(finding.level, 'info');
assert.match(finding.message, /timeout/);
assert.match(result.summary, /not a verdict/);
assert.match(result.summary, /could not be read from here \(timeout\)/);
});
test('a policy fetch refused by a firewall (403) is not-evaluated, never a broken promise', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'not-read', code: 'http_403', status: 403, url: POLICY_URL }
}), { now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.equal(codes(result).includes('mta_sts_policy_missing'), false);
assert.ok(codes(result).includes('mta_sts_policy_not_read'));
assert.equal(result.evidence.find((item) => item.label === 'MTA-STS policy').value, 'not read (http_403)');
});
test('not-evaluated wins over a warning from another record', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'not-read', code: 'timeout', url: POLICY_URL },
tlsRpt: { checked: true, present: true, valid: false, rua: [], record: 'v=TLSRPTv1;' }
}), { now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.ok(codes(result).includes('tls_rpt_no_rua'));
});
test('a SERVFAIL on every record is not-evaluated with the code in the sentence', () => {
const result = analyseMailTransport(gatheredFixture({
mtaSts: { checked: false, code: 'ESERVFAIL', present: false, valid: false },
tlsRpt: { checked: false, code: 'ESERVFAIL', present: false, valid: false },
bimi: { checked: false, code: 'ESERVFAIL', present: false, valid: false },
fatal: { code: 'ESERVFAIL', transient: true }
}), { now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.deepEqual(codes(result), ['dns_unavailable']);
assert.equal(levels(result)[0], 'info');
assert.match(result.summary, /\(ESERVFAIL\)/);
assert.match(result.findings[0].message, /not a finding against the domain/);
});
test('a resolver that refuses is not a statement about the domain', async () => {
const dns = tableDns({}, { fail: { '_mta-sts.example.com': 'EREFUSED', '_smtp._tls.example.com': 'EREFUSED', 'default._bimi.example.com': 'EREFUSED' } });
const result = await checkMailTransport('example.com', { dns, request: routeRequest({}), now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.match(result.summary, /EREFUSED/);
assert.equal(result.findings.every((finding) => finding.level === 'info'), true);
});
test('a policy host that does not resolve is a broken promise, not a blocked fetch', async () => {
const dns = tableDns({ '_mta-sts.example.com': txt('v=STSv1; id=abc') });
const request = routeRequest({ [POLICY_URL]: new NetGuardError('dns_nxdomain', 'That domain did not resolve.') });
const result = await checkMailTransport('example.com', { dns, request, now: NOW });
assert.equal(result.state, 'warn');
assert.ok(codes(result).includes('mta_sts_policy_missing'));
assert.match(result.summary, /does not resolve/);
// One attempt, never a retry: the budget is one request.
assert.equal(request.calls.length, 1);
});
test('a policy fetch that times out is not-evaluated end to end, and is not retried', async () => {
const dns = tableDns({ '_mta-sts.example.com': txt('v=STSv1; id=abc') });
const request = routeRequest({ [POLICY_URL]: new NetGuardError('timeout', 'That took too long.') });
const result = await checkMailTransport('example.com', { dns, request, now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.ok(codes(result).includes('mta_sts_policy_not_read'));
assert.equal(codes(result).includes('mta_sts_policy_missing'), false);
assert.equal(request.calls.length, 1);
});
test('a policy URL that redirects is a broken promise: the policy must be served in place', async () => {
const dns = tableDns({ '_mta-sts.example.com': txt('v=STSv1; id=abc') });
const request = routeRequest({
[POLICY_URL]: { status: 301, headers: { location: 'https://example.com/policy.txt' }, body: '' }
});
const result = await checkMailTransport('example.com', { dns, request, now: NOW });
assert.equal(result.state, 'warn');
assert.ok(codes(result).includes('mta_sts_policy_missing'));
assert.match(result.summary, /redirected \(HTTP 301\)/);
// The redirect is not followed: one request, ever.
assert.equal(request.calls.length, 1);
});
// ---------------------------------------------------------------------------
// TLS-RPT and BIMI
// ---------------------------------------------------------------------------
test('TLS-RPT publishes a reporting address', () => {
const result = analyseMailTransport(gatheredFixture({
tlsRpt: { checked: true, present: true, valid: true, rua: ['mailto:[email protected]'], record: 'v=TLSRPTv1; rua=mailto:[email protected]' }
}), { now: NOW });
assert.equal(result.state, 'ok');
const finding = result.findings.find((item) => item.code === 'tls_rpt_published');
assert.equal(finding.level, 'ok');
assert.match(finding.message, /mailto:tls@example\.com/);
});
test('TLS-RPT with no rua address has nowhere to send reports', () => {
const result = analyseMailTransport(gatheredFixture({
tlsRpt: { checked: true, present: true, valid: false, rua: [], record: 'v=TLSRPTv1;' }
}), { now: NOW });
assert.equal(result.state, 'warn');
assert.ok(codes(result).includes('tls_rpt_no_rua'));
});
test('BIMI with a logo but DMARC p=none is reported as ignored, not as configured', () => {
const result = analyseMailTransport(gatheredFixture({
bimi: { checked: true, present: true, valid: true, location: 'https://example.com/logo.svg', authority: null, record: 'v=BIMI1; l=https://example.com/logo.svg' },
dmarc: { checked: true, record: 'v=DMARC1; p=none;', parsed: { valid: true, p: 'none', pct: 100 } }
}), { now: NOW });
const finding = result.findings.find((item) => item.code === 'bimi_ignored_dmarc_weak');
assert.equal(finding.level, 'info');
assert.match(finding.message, /ignore BIMI unless the DMARC policy is quarantine or reject/);
assert.match(finding.message, /p=none/);
assert.equal(codes(result).includes('bimi_published'), false);
assert.doesNotMatch(JSON.stringify(result.findings), /BIMI is configured|logo will show/i);
});
test('BIMI counts when DMARC is enforced, and a missing VMC is named', () => {
const result = analyseMailTransport(gatheredFixture({
bimi: { checked: true, present: true, valid: true, location: 'https://example.com/logo.svg', authority: null, record: 'v=BIMI1; l=https://example.com/logo.svg' },
dmarc: { checked: true, record: 'v=DMARC1; p=reject;', parsed: { valid: true, p: 'reject', pct: 100 } }
}), { now: NOW });
assert.equal(result.state, 'ok');
assert.ok(codes(result).includes('bimi_published'));
const vmc = result.findings.find((item) => item.code === 'bimi_no_vmc');
assert.equal(vmc.level, 'info');
assert.match(vmc.message, /Gmail and Yahoo/);
});
test('BIMI with pct<100 is not enforcement', () => {
const result = analyseMailTransport(gatheredFixture({
bimi: { checked: true, present: true, valid: true, location: 'https://example.com/logo.svg', authority: 'https://example.com/vmc.pem' },
dmarc: { checked: true, record: 'v=DMARC1; p=quarantine; pct=50;', parsed: { valid: true, p: 'quarantine', pct: 50 } }
}), { now: NOW });
assert.ok(codes(result).includes('bimi_ignored_dmarc_weak'));
assert.equal(codes(result).includes('bimi_published'), false);
});
test('BIMI with an unreadable DMARC record says unknown rather than judging it', () => {
const result = analyseMailTransport(gatheredFixture({
bimi: { checked: true, present: true, valid: true, location: 'https://example.com/logo.svg', authority: null },
dmarc: { checked: false, code: 'ETIMEOUT', record: null, parsed: null }
}), { now: NOW });
assert.ok(codes(result).includes('bimi_dmarc_unknown'));
assert.equal(codes(result).includes('bimi_ignored_dmarc_weak'), false);
});
// ---------------------------------------------------------------------------
// envelope + wording
// ---------------------------------------------------------------------------
test('the envelope is exactly the agreed shape, with an ISO checkedAt', () => {
const result = analyseMailTransport(gatheredFixture(), { now: NOW });
assert.deepEqual(Object.keys(result), ['id', 'state', 'summary', 'evidence', 'findings', 'checkedAt', 'fromCache']);
assert.equal(result.id, 'mail-transport');
assert.equal(result.checkedAt, ISO);
assert.equal(result.fromCache, false);
assert.equal(typeof result.checkedAt, 'string');
assert.ok(['ok', 'warn', 'fail', 'not-evaluated'].includes(result.state));
for (const item of result.evidence) {
assert.equal(typeof item.label, 'string');
assert.equal(typeof item.value, 'string');
// `note` is optional, so when present it must be a real string — never note: undefined.
if ('note' in item) assert.equal(typeof item.note, 'string');
assert.deepEqual(Object.keys(item).filter((key) => !['label', 'value', 'note'].includes(key)), []);
}
for (const finding of result.findings) {
assert.ok(['ok', 'info', 'warn', 'fail'].includes(finding.level));
assert.equal(typeof finding.code, 'string');
assert.equal(typeof finding.message, 'string');
if ('fix' in finding) assert.equal(typeof finding.fix, 'string');
}
});
test('no score, no delivery promise, no "your email is insecure"', () => {
const fixtures = [
gatheredFixture(),
gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk()
}),
gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'missing', code: 'http_404', status: 404 }
}),
gatheredFixture({
bimi: { checked: true, present: true, valid: true, location: 'https://example.com/logo.svg' },
dmarc: { checked: true, record: 'v=DMARC1; p=none;', parsed: { valid: true, p: 'none', pct: 100 } }
})
];
for (const fixture of fixtures) {
const text = JSON.stringify(analyseMailTransport(fixture, { now: NOW }));
assert.doesNotMatch(text, /\bscore\b|\d+\s*\/\s*100|inbox placement|delivery rate|guarantee|insecure/i);
}
});
test('every summary is one sentence', () => {
const fixtures = [
gatheredFixture(),
gatheredFixture({ tlsRpt: { checked: true, present: true, valid: true, rua: ['mailto:[email protected]'] } }),
gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk()
}),
gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: policyOk('version: STSv1\nmode: testing\nmax_age: 86400\nmx: mx.example.com\n')
}),
gatheredFixture({
mtaSts: { checked: true, present: true, valid: true, record: 'v=STSv1; id=abc', id: 'abc', count: 1 },
policy: { attempted: true, ok: false, kind: 'not-read', code: 'timeout' }
}),
gatheredFixture({ fatal: { code: 'ESERVFAIL' } })
];
for (const fixture of fixtures) {
const summary = analyseMailTransport(fixture, { now: NOW }).summary;
const stops = summary.match(/[.!?](\s|$)/g) || [];
assert.equal(stops.length, 1, `more than one sentence: ${summary}`);
}
});
test('worstLevel maps info to ok and keeps warn/fail', () => {
assert.equal(worstLevel([]), 'ok');
assert.equal(worstLevel([{ level: 'info' }, { level: 'ok' }]), 'ok');
assert.equal(worstLevel([{ level: 'info' }, { level: 'warn' }]), 'warn');
assert.equal(worstLevel([{ level: 'warn' }, { level: 'fail' }]), 'fail');
});
// ---------------------------------------------------------------------------
// check(): the request budget and the host role
// ---------------------------------------------------------------------------
test('the policy fetch is the only request, and only when a valid TXT exists', async () => {
assert.equal(REQUEST_BUDGET, 1);
assert.equal(POLICY_TIMEOUT_MS, 3000);
assert.equal(POLICY_MAX_BYTES, 32 * 1024);
assert.equal(policyUrl('example.com'), POLICY_URL);
const withRecord = routeRequest({ [POLICY_URL]: { status: 200, body: POLICY_TEXT } });
await checkMailTransport('example.com', {
dns: tableDns({ '_mta-sts.example.com': txt('v=STSv1; id=abc') }),
request: withRecord,
now: NOW
});
assert.equal(withRecord.calls.length, 1);
assert.equal(withRecord.calls[0].url, POLICY_URL);
// The policy is not a page: an explicit Accept is passed, with the caps the module promises.
assert.match(withRecord.calls[0].options.accept, /^text\/plain/);
assert.equal(withRecord.calls[0].options.timeoutMs, POLICY_TIMEOUT_MS);
assert.equal(withRecord.calls[0].options.maxBytes, POLICY_MAX_BYTES);
assert.equal(withRecord.calls[0].options.method, 'GET');
const withoutRecord = routeRequest({});
await checkMailTransport('example.com', { dns: tableDns({}), request: withoutRecord, now: NOW });
assert.equal(withoutRecord.calls.length, 0);
});
test('the DNS seam is asked for the four names, and nothing else', async () => {
const dns = tableDns({});
await checkMailTransport('example.com', { dns, request: routeRequest({}), now: NOW });
assert.deepEqual(dns.resolveTxt.calls.sort(), [
'_dmarc.example.com',
'_mta-sts.example.com',
'_smtp._tls.example.com',
'default._bimi.example.com'
].sort());
assert.equal(MTA_STS_NAME, '_mta-sts');
assert.equal(TLS_RPT_NAME, '_smtp._tls');
assert.equal(BIMI_NAME, 'default._bimi');
});
test('a full read through check() produces mode=enforce from the served file', async () => {
const dns = tableDns({
'_mta-sts.example.com': txt('v=STSv1; id=abc'),
'_smtp._tls.example.com': txt('v=TLSRPTv1; rua=mailto:[email protected]'),
'default._bimi.example.com': txt('v=BIMI1; l=https://example.com/logo.svg'),
'_dmarc.example.com': txt('v=DMARC1; p=reject; rua=mailto:[email protected]')
});
const request = routeRequest({ [POLICY_URL]: { status: 200, body: POLICY_TEXT } });
const result = await checkMailTransport('example.com', { dns, request, now: NOW });
assert.equal(result.state, 'ok');
assert.equal(result.checkedAt, ISO);
assert.deepEqual(codes(result).sort(), ['bimi_no_vmc', 'bimi_published', 'mta_sts_mode_enforce', 'tls_rpt_published']);
assert.equal(request.calls.length, 1);
});
test('a 403 on the policy file leaves the card not-evaluated, and other records still report', async () => {
const dns = tableDns({
'_mta-sts.example.com': txt('v=STSv1; id=abc'),
'_smtp._tls.example.com': txt('v=TLSRPTv1; rua=mailto:[email protected]')
});
const request = routeRequest({ [POLICY_URL]: { status: 403, body: 'Forbidden' } });
const result = await checkMailTransport('example.com', { dns, request, now: NOW });
assert.equal(result.state, 'not-evaluated');
assert.ok(codes(result).includes('mta_sts_policy_not_read'));
assert.ok(codes(result).includes('tls_rpt_published'));
});
test('a subdomain that publishes nothing is a website, not a broken domain', async () => {
const dns = tableDns({});
const request = routeRequest({});
const result = await checkMailTransport('tools.example.com', { dns, request, now: NOW });
assert.equal(result.state, 'ok');
assert.deepEqual(codes(result), ['subdomain_no_mail']);
assert.equal(result.findings[0].level, 'info');
assert.match(result.summary, /example\.com/);
assert.match(result.findings[0].message, /normal for a subdomain/);
assert.equal(request.calls.length, 0);
});
test('a subdomain that does publish a policy is judged in place', async () => {
const dns = tableDns({ '_mta-sts.shop.example.com': txt('v=STSv1; id=abc') });
const request = routeRequest({
'https://mta-sts.shop.example.com/.well-known/mta-sts.txt': { status: 200, body: POLICY_TEXT }
});
const result = await checkMailTransport('shop.example.com', { dns, request, now: NOW });
assert.equal(result.state, 'ok');
assert.ok(codes(result).includes('mta_sts_mode_enforce'));
assert.equal(codes(result).includes('subdomain_no_mail'), false);
assert.equal(request.calls[0].url, 'https://mta-sts.shop.example.com/.well-known/mta-sts.txt');
});
test('the registrable apex keeps .com.my and .co.uk second levels intact', () => {
assert.equal(registrableApex('tools.hoelee.com'), 'hoelee.com');
assert.equal(registrableApex('shop.example.com.my'), 'example.com.my');
assert.equal(registrableApex('mail.example.co.uk'), 'example.co.uk');
assert.equal(registrableApex('example.com'), 'example.com');
});
test('an injected resolver object works through the lookup alias too', async () => {
const dns = tableDns({ '_mta-sts.example.com': txt('v=STSv1; id=abc') });
const request = routeRequest({ [POLICY_URL]: { status: 200, body: POLICY_TEXT } });
const result = await checkMailTransport('example.com', { lookup: dns, request, now: NOW });
assert.ok(codes(result).includes('mta_sts_mode_enforce'));
});
test('bad input fails without touching DNS', async () => {
const dns = tableDns({});
const result = await checkMailTransport('not a domain', { dns, request: routeRequest({}), now: NOW });
assert.equal(result.state, 'fail');
assert.deepEqual(codes(result), ['bad_input']);
assert.equal(dns.resolveTxt.calls.length, 0);
});
test('buildSummary has a sentence for the enforce case that names the file, not the TXT', () => {
const summary = buildSummary({
domain: 'example.com',
mtaSts: { present: true, valid: true },
policy: { ok: true, kind: 'ok', parsed: { mode: 'enforce' } },
tlsRpt: { present: false },
bimi: { present: false },
dmarcEnforced: false,
fatal: null
});
assert.match(summary, /policy file says mode=enforce/);
assert.doesNotMatch(summary, /TXT record (protects|is enforcing)/);
});