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

+2 -2
View File
@@ -30,7 +30,7 @@ import `node:http`/`node:https` directly, must not use the global `fetch`, and m
them is a finding against the visitor's site. Render it neutral (slate, no red, no "!"), and count
it separately in the summary ("2 verified, 1 skipped by firewall").
5. **Never claim what the data cannot support.** The exact wording rules are in `SPEC.md` §5; the
five that get broken most often:
seven that get broken most often:
- DKIM: "No key found among the 13 common selectors; a custom selector cannot be found from DNS alone."
Never "DKIM is not configured".
- TLS: judge signature algorithms on the **leaf and intermediates only** — RFC 5280 exempts a
@@ -54,7 +54,7 @@ import `node:http`/`node:https` directly, must not use the global `fetch`, and m
```js
// every check module exports exactly this
export async function check(input, { lookup, now = Date.now(), cache } = {}) -> {
id: 'who-holds' | 'mail-auth' | 'tls' | 'http' | 'host-shape',
id: 'who-holds' | 'mail-auth' | 'mail-transport' | 'tls' | 'http' | 'host-shape' | 'hardening',
state: 'ok' | 'warn' | 'fail' | 'not-evaluated',
summary: string, // one plain-English line for a non-technical owner
evidence: Array<{label, value, note?}>,
+4 -4
View File
@@ -1,8 +1,8 @@
# SPEC — hoelee-check v1
**What this is.** Five public health checks for a domain — certificate, email authentication, and
**What this is.** Seven public health checks for a domain — certificate, email authentication, and
redirects/link-preview — served at `https://www.hoelee.com/check/`. Free, no account, no upload.
Built so a Malaysian SME owner can see, in a few seconds, the five things that make a small
Built so a Malaysian SME owner can see, in a few seconds, the seven things that make a small
business look careless online.
**Why here and not on `tools.hoelee.com`.** That site's entire promise is "nothing is uploaded —
@@ -43,7 +43,7 @@ evaluation and DKIM signature verification, neither of which a record-shape chec
| Route | Purpose | Robots |
|---|---|---|
| `/check/` | hub, one input, runs all five | index |
| `/check/` | hub, one input, runs all seven | index |
| `/check/ssl/` | certificate landing page | index |
| `/check/spf-dkim-dmarc/` | email auth landing page | index |
| `/check/headers/` | redirects + link preview landing page | index |
@@ -114,7 +114,7 @@ neutral `not-evaluated` rendering, and `/check/about/` with its falsification te
2. net-guard refuses `127.0.0.1`, `169.254.169.254`, `10.0.0.1`, `[::1]`, `0.0.0.0`, `2130706433`,
`[::ffff:127.0.0.1]`, a host resolving private, a mixed public/private answer set, a redirect to a
private address, and a redirect to port 8443.
3. A real report for `hoelee.com` returns five checks in ~1–3 s with `checkedAt`.
3. A real report for `hoelee.com` returns seven checks in ~2–4 s with `checkedAt`.
4. A 403/bot-wall target renders `not-evaluated` with zero header findings.
5. Report page carries `noindex` + `X-Robots-Tag`, has no horizontal overflow at 390 px, and makes
zero third-party requests.
+988
View File
@@ -0,0 +1,988 @@
// hardening.mjs — four small questions about *how* a page is served, answered from one response.
//
// 1. compression — did the server compress the page, and roughly how much did that save?
// 2. CAA — does the domain publish a CAA record, and does it authorise the CA that
// issued the certificate on this very connection?
// 3. cookies — are the cookies set on this response marked HttpOnly / Secure / SameSite?
// 4. banners — does the server advertise its own software version?
//
// REQUEST BUDGET: at most TWO outbound HTTP requests, enforced in code by createRequestBudget().
// slot 1 — GET https://<host>/ with `Accept-Encoding: br, gzip`, body capped at 256 KB
// (PAGE_MAX_BYTES). The certificate is read off that same socket (requestOnce returns
// .tls), so comparing CAA against the issuing CA costs no extra connection.
// slot 2 — spent only when the first answer is a redirect: one guarded follow so the headers
// audited are the ones a visitor actually receives. Nothing else may spend it.
// CAA itself is a DNS query and costs nothing.
//
// WHY COMPRESSION IS OFTEN REPORTED AS "NOT MEASURED": net-guard pins `accept-encoding: identity`
// (src/lib/net-guard.mjs:320) and requestOnce takes no override. A response fetched that way says
// nothing about whether the site compresses, so this module never turns it into "the site does not
// compress". It reports the question as not measured instead. GUARD_HONOURS_COMPRESSION is the one
// place that fact lives: set it to true on the day net-guard accepts an acceptEncoding option and
// the measured branch takes over with no other change.
//
// SEVERITY RULING (do not drift — SPEC.md §5, AGENTS.md rule 5):
// missing cookie flag on a session-looking cookie → warn
// missing cookie flag on anything else → info
// CAA record does not authorise the issuing CA → warn (never fail)
// no CAA record / no compression / version banner → info, never fail
// bot wall, 403, 429, timeout, SERVFAIL, NXDOMAIN → not-evaluated, no finding against the site
// There is no fail level in this check by design: none of these four answers is a fault on its own.
//
// Split, same as the other checks: checkHardening() does the network and DNS, analyseHardening() is
// pure over the gathered facts, so every branch is testable with a fake and zero sockets.
import dns from 'node:dns';
import { requestOnce, parseTarget, guardHop, NetGuardError, withTimeout } from '../lib/net-guard.mjs';
export const CHECK_ID = 'hardening';
export const REQUEST_BUDGET = 2;
export const PAGE_MAX_BYTES = 256 * 1024;
export const PAGE_TIMEOUT_MS = 8000;
export const COMPRESSION_ACCEPT = 'br, gzip';
export const PAGE_ACCEPT = 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5';
// See the header note. False today: net-guard asks for identity, so a missing Content-Encoding
// proves nothing and must never be reported as "this site does not compress".
// Net-guard accepts `acceptEncoding` now and returns the decoded body beside the wire size, so the
// compression question can finally be answered instead of excused.
export const GUARD_HONOURS_COMPRESSION = true;
const CAA_TIMEOUT_MS = 3000;
const CAA_MAX_NAMES = 4;
const LEVEL_RANK = { ok: 0, info: 1, warn: 2, fail: 3 };
const BLOCK_STATUSES = new Set([401, 403, 429, 503]);
const CHALLENGE_MARKERS = [
'cf-browser-verification',
'just a moment',
'attention required',
'challenge-platform',
'checking your browser',
'_cf_chl_opt',
'enable javascript and cookies to continue',
'captcha'
];
// Two-part public suffixes that matter for the sites this tool is aimed at. Only used to decide
// where the CAA walk stops, so an incomplete list costs one extra (free) DNS query, not a wrong
// answer: a CAA record at the parent name applies to the child anyway (RFC 8659 §3).
const TWO_PART_SUFFIXES = new Set([
'com.my', 'net.my', 'org.my', 'gov.my', 'edu.my', 'mil.my',
'co.uk', 'org.uk', 'me.uk', 'co.id', 'com.sg', 'com.bn', 'com.ph', 'com.vn',
'com.hk', 'com.tw', 'com.au', 'net.au', 'co.nz', 'co.th', 'co.jp', 'com.cn'
]);
// Cookies whose name says "this is who you are", plus anything with no expiry (a session cookie).
const SESSION_NAME = /(sess|sid|auth|login|logged|token|csrf|xsrf|remember|jwt|phpsessid|jsessionid|asp\.net|connect\.sid|laravel|wordpress_logged)/i;
// Analytics cookies that JavaScript has to read; a missing HttpOnly there is normal, not a fault.
const TRACKING_NAME = /^(_ga|_g1|_gid|_gat|_gcl|_fbp|_hjid|_hj|_clck|_clsk|_uetsid|_uetvid|__utm|_pin_unauth|_ttp|_tt_enable_cookie|ide|nid)/i;
// CAA `issue` domain → other names that appear in that CA's certificate issuer fields. Curated for
// the CAs small sites actually use; anything not listed here is matched on its own name only, and
// an unmatched pair is a hedged warn, never a failure.
const CA_ALIASES = new Map([
['letsencrypt.org', ['letsencrypt', 'isrg']],
['sectigo.com', ['sectigo', 'comodo', 'usertrust', 'zerossl']],
['zerossl.com', ['zerossl', 'sectigo']],
['digicert.com', ['digicert', 'thawte', 'geotrust', 'rapidssl']],
['globalsign.com', ['globalsign', 'alphassl']],
['pki.goog', ['googletrustservices', 'google']],
['amazon.com', ['amazon', 'awstrust']],
['amazontrust.com', ['amazon', 'awstrust']],
['godaddy.com', ['godaddy', 'starcert']],
['ssl.com', ['sslcom']]
]);
// ---------------------------------------------------------------------------------------------
// small helpers
// ---------------------------------------------------------------------------------------------
function rank(level) {
return LEVEL_RANK[level] ?? 0;
}
/** Worst finding level, with 'info' folded back into 'ok' — info is a note, not a state. */
export function worstLevel(findings = []) {
let state = 'ok';
for (const finding of findings) {
if (rank(finding.level) > rank(state)) state = finding.level;
}
return state === 'info' ? 'ok' : state;
}
export function formatBytes(value) {
if (!Number.isFinite(value) || value < 0) return 'unknown size';
if (value < 1024) return `${Math.round(value)} bytes`;
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
return `${(value / (1024 * 1024)).toFixed(1)} MB`;
}
function headerValue(headers, name) {
if (!headers) return null;
const direct = headers[name];
if (direct !== undefined && direct !== null) return Array.isArray(direct) ? direct.join(', ') : String(direct);
const lower = name.toLowerCase();
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === lower) return Array.isArray(value) ? value.join(', ') : String(value);
}
return null;
}
function numericHeader(headers, name) {
const raw = headerValue(headers, name);
if (raw === null) return null;
const parsed = Number(String(raw).trim());
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
}
function cookieList(headers) {
if (!headers) return [];
const raw = headers['set-cookie'] ?? headers['Set-Cookie'];
if (raw === undefined || raw === null) return [];
if (Array.isArray(raw)) return raw.filter((item) => typeof item === 'string');
return typeof raw === 'string' ? [raw] : [];
}
// ---------------------------------------------------------------------------------------------
// request budget — the cap lives in code, not in a comment
// ---------------------------------------------------------------------------------------------
export function createRequestBudget(limit = REQUEST_BUDGET) {
let used = 0;
return {
limit,
get used() {
return used;
},
get remaining() {
return limit - used;
},
spend(label = 'request') {
if (used >= limit) {
throw new NetGuardError(
'budget_exhausted',
`The ${label} would be request ${used + 1} of a ${limit}-request budget.`
);
}
used += 1;
return used;
}
};
}
// ---------------------------------------------------------------------------------------------
// question 1 — compression
// ---------------------------------------------------------------------------------------------
/**
* Pure: decide what can honestly be said about compression.
* facts = { contentEncoding, contentLength, receivedBytes, decodedBytes, requestedEncoding,
* honoured, vary }
* Returns { encoding, measured, transferredBytes, plainBytes, savingPercent, savedBytes }.
*/
export function analyseCompression(facts = {}) {
const encoding = normaliseEncoding(facts.contentEncoding);
const transferred = Number.isFinite(facts.contentLength) && facts.contentLength > 0
? facts.contentLength
: (Number.isFinite(facts.receivedBytes) && facts.receivedBytes > 0 ? facts.receivedBytes : null);
const plain = Number.isFinite(facts.decodedBytes) && facts.decodedBytes > 0 ? facts.decodedBytes : null;
const measured = Boolean(encoding && transferred !== null && plain !== null && plain > 0);
const out = {
encoding,
honoured: facts.honoured === true,
requested: typeof facts.requestedEncoding === 'string' ? facts.requestedEncoding : null,
vary: typeof facts.vary === 'string' ? facts.vary : null,
transferredBytes: transferred,
plainBytes: plain,
measured,
savedBytes: null,
savingPercent: null
};
if (measured) {
out.savedBytes = plain - transferred;
out.savingPercent = Math.round((1 - transferred / plain) * 100);
}
return out;
}
function normaliseEncoding(value) {
if (typeof value !== 'string') return null;
// Any coding other than identity means the bytes on the wire are not the plain HTML.
const first = value.split(',')[0].trim().toLowerCase();
if (first === '' || first === 'identity') return null;
return first;
}
function compressionFindings(compression) {
const findings = [];
const evidence = [];
let clause;
if (compression.encoding) {
if (compression.measured && compression.savedBytes > 0) {
findings.push({
level: 'ok',
code: 'hardening_compression_on',
message: `The page arrives ${compression.encoding}-compressed: ${formatBytes(compression.transferredBytes)} on the wire instead of ${formatBytes(compression.plainBytes)}, about ${compression.savingPercent}% smaller.`
});
evidence.push({
label: 'compression',
value: `${compression.encoding} — ${formatBytes(compression.transferredBytes)} on the wire instead of ${formatBytes(compression.plainBytes)} (about ${compression.savingPercent}% smaller)`
});
clause = 'the page arrives compressed';
} else if (compression.measured) {
findings.push({
level: 'info',
code: 'hardening_compression_no_gain',
message: `The page is ${compression.encoding}-compressed, but at ${formatBytes(compression.plainBytes)} it came out at ${formatBytes(compression.transferredBytes)} — on a page this small the compression saved nothing. Not a fault.`
});
evidence.push({
label: 'compression',
value: `${compression.encoding} — no saving at this size (${formatBytes(compression.transferredBytes)} vs ${formatBytes(compression.plainBytes)})`
});
clause = 'compression is on but saved nothing on a page this small';
} else {
// Compressed, but only one side of the comparison is known: say what was seen, no number.
const size = compression.transferredBytes === null
? ''
: ` (${formatBytes(compression.transferredBytes)} on the wire)`;
findings.push({
level: 'ok',
code: 'hardening_compression_on_unmeasured',
message: `The server sent the page ${compression.encoding}-compressed${size}, so it travels smaller than the plain HTML would; the exact saving was not measured.`
});
evidence.push({
label: 'compression',
value: `${compression.encoding} — saving not measured`
});
clause = 'the page arrives compressed';
}
} else if (compression.honoured) {
// Only say "not compressed" when the request really asked for compression.
findings.push({
level: 'info',
code: 'hardening_compression_off',
message: 'The page was served uncompressed even though the request asked for it, so every visitor downloads the full HTML. Not a fault — a missed saving.',
fix: 'Turn on gzip or brotli for text/html at the server or CDN.'
});
evidence.push({ label: 'compression', value: 'none in this response' });
clause = 'the page arrives uncompressed';
} else if (compression.vary && /accept-encoding/i.test(compression.vary)) {
// The server says its answer depends on Accept-Encoding, i.e. it can compress — but this probe
// asked for an uncompressed copy, so no saving was measured.
findings.push({
level: 'info',
code: 'hardening_compression_available',
message: 'The server says its response varies by Accept-Encoding, so it can compress, but this probe asked for an uncompressed copy — the saving was not measured.'
});
evidence.push({ label: 'compression', value: 'offered (Vary: Accept-Encoding) — not measured' });
clause = 'compression is offered but was not measured';
} else {
findings.push({
level: 'info',
code: 'hardening_compression_not_measured',
message: 'Compression was not measured on this request, so no saving is claimed either way. Not a fault.'
});
evidence.push({ label: 'compression', value: 'not measured' });
clause = 'compression was not measured';
}
return { findings, evidence, clause };
}
// ---------------------------------------------------------------------------------------------
// question 2 — CAA
// ---------------------------------------------------------------------------------------------
/** Accept node's {critical, issue, issuewild, iodef} objects and raw `0 issue "x"` strings. */
export function normaliseCaa(records) {
if (!records) return [];
const list = Array.isArray(records) ? records : [records];
const out = [];
for (const record of list) {
if (!record) continue;
if (typeof record === 'string') {
const match = /^\s*\d+\s+(issue|issuewild|iodef)\s+"?([^"]*)"?\s*$/i.exec(record);
if (!match) continue;
out.push({ [match[1].toLowerCase()]: match[2].trim() });
continue;
}
if (typeof record === 'object') {
const clean = {};
for (const key of ['issue', 'issuewild', 'iodef']) {
if (typeof record[key] === 'string') clean[key] = record[key].trim();
}
if (Object.keys(clean).length > 0) out.push(clean);
}
}
return out;
}
export function caaIssueValues(records) {
const out = [];
for (const record of records || []) {
for (const key of ['issue', 'issuewild']) {
if (typeof record[key] !== 'string') continue;
// `issue ";"` is the RFC 8659 way of saying "no CA at all", so it must survive the split.
const raw = record[key].trim();
const tag = raw === ';' ? ';' : raw.split(';')[0].trim();
if (tag === '') continue;
out.push({ key, tag, domain: tag === ';' ? null : tag.toLowerCase() });
}
}
return out;
}
function tokens(text) {
return String(text || '')
.toLowerCase()
.replace(/[^a-z0-9]/g, '');
}
function issuerTokens(issuer) {
if (!issuer || typeof issuer !== 'object') return [];
const out = [];
for (const key of ['O', 'OU', 'CN']) {
const value = issuer[key];
if (typeof value !== 'string') continue;
const token = tokens(value);
if (token.length >= 3) out.push(token);
}
return out;
}
export function describeIssuer(issuer) {
if (!issuer || typeof issuer !== 'object') return null;
const organisation = typeof issuer.O === 'string' ? issuer.O : null;
const common = typeof issuer.CN === 'string' ? issuer.CN : null;
if (organisation && common) return `${organisation} (${common})`;
return organisation || common || null;
}
/**
* Does the published CAA policy authorise the CA named in the certificate's issuer field?
* Returns { status: 'match'|'mismatch'|'deny-all'|'no-caa'|'no-issuer', allowed, matched, issuer }.
*/
export function caaAuthorisesIssuer(records, issuer) {
const normalised = normaliseCaa(records);
const issuerLabel = describeIssuer(issuer);
const values = caaIssueValues(normalised);
const domains = values.filter((value) => value.domain);
const allowed = domains.map((value) => value.domain);
if (values.length === 0) {
return { status: 'no-caa', allowed: [], matched: null, issuer: issuerLabel };
}
if (domains.length === 0) {
// Every issue tag is ";" — the record forbids all CAs.
return { status: 'deny-all', allowed: [], matched: null, issuer: issuerLabel };
}
const tokensOfIssuer = issuerTokens(issuer);
if (tokensOfIssuer.length === 0) {
return { status: 'no-issuer', allowed, matched: null, issuer: null };
}
for (const domain of allowed) {
if (domainMatches(domain, tokensOfIssuer)) {
return { status: 'match', allowed, matched: domain, issuer: issuerLabel };
}
}
return { status: 'mismatch', allowed, matched: null, issuer: issuerLabel };
}
function domainMatches(domain, issuerTokensList) {
const labels = domain.split('.').filter((label) => label.length >= 4);
const aliases = CA_ALIASES.get(domain) || [];
const candidates = [...labels, ...aliases];
const squeezed = tokens(domain);
for (const candidate of candidates) {
for (const token of issuerTokensList) {
if (token.includes(candidate) || candidate.includes(token)) return true;
}
}
return squeezed.length >= 4 && issuerTokensList.some((token) => token.includes(squeezed));
}
function caaFindings(caa, certificate) {
const findings = [];
const evidence = [];
let clause;
const issuer = certificate && certificate.issuer ? certificate.issuer : null;
const name = caa && caa.name ? caa.name : null;
const records = normaliseCaa(caa && caa.records ? caa.records : []);
const error = caa && caa.error ? caa.error : null;
if (error) {
findings.push({
level: 'info',
code: 'hardening_caa_unavailable',
message: 'The CAA lookup could not be completed here, so the domain\'s CAA record was not read. Nothing is claimed about it.'
});
evidence.push({ label: 'CAA', value: `not read (${error})` });
return { findings, evidence, clause: 'the CAA record could not be read' };
}
if (records.length === 0) {
findings.push({
level: 'info',
code: 'hardening_caa_absent',
message: 'No CAA record is published for this domain, which means any certificate authority may issue for it — not a fault, just no lock on the door.',
fix: 'Optional: add a CAA record naming the CA that issues your certificate.'
});
evidence.push({ label: 'CAA', value: 'none published' });
return { findings, evidence, clause: 'no CAA record is published (not a fault)' };
}
const policy = caaAuthorisesIssuer(records, issuer);
const recordText = records
.flatMap((record) => ['issue', 'issuewild', 'iodef'].filter((key) => record[key]).map((key) => `${key} "${record[key]}"`))
.join(', ');
evidence.push({ label: 'CAA', value: `${name || 'domain'}: ${recordText}` });
if (policy.issuer) evidence.push({ label: 'certificate issuer', value: policy.issuer });
if (policy.status === 'deny-all') {
findings.push({
level: 'info',
code: 'hardening_caa_deny_all',
message: 'The CAA record currently authorises no certificate authority at all (`issue ";"`), so the certificate being served was issued before that record was added. Nothing is broken today; a renewal needs an issue tag.',
fix: 'Replace `issue ";"` with the CA that should be allowed to renew the certificate.'
});
clause = 'the CAA record authorises no CA (renewal needs an issue tag)';
} else if (policy.status === 'no-issuer') {
findings.push({
level: 'info',
code: 'hardening_caa_not_compared',
message: `The CAA record allows ${policy.allowed.join(', ')}, but the certificate's issuer could not be read on this connection, so the two were not compared.`
});
clause = `the CAA record allows ${policy.allowed.join(', ')} (not compared)`;
} else if (policy.status === 'match') {
findings.push({
level: 'ok',
code: 'hardening_caa_authorises_issuer',
message: `The CAA record allows ${policy.matched}, the same authority that issued the certificate being served.`,
// no fix: this is the good case
});
clause = 'the CAA record names the CA that issued the certificate';
} else {
findings.push({
level: 'warn',
code: 'hardening_caa_issuer_mismatch',
message: `The certificate on this site was issued by ${policy.issuer || 'a CA the record does not name'}, but the CAA record only allows ${policy.allowed.join(', ')}. The current certificate keeps working; a renewal would be refused unless the record is updated.`,
fix: `Add ${policy.issuer || 'the issuing CA'} to the CAA record, or change the certificate to one the record allows.`
});
clause = `the CAA record does not name the issuing CA`;
}
return { findings, evidence, clause };
}
/** The names a CA would check, nearest first: the host, then each parent down to the apex. */
export function caaNames(host) {
const labels = String(host || '').toLowerCase().replace(/\.$/, '').split('.').filter(Boolean);
if (labels.length < 2) return [];
const out = [];
for (let i = 0; i < labels.length && out.length < CAA_MAX_NAMES; i += 1) {
const name = labels.slice(i).join('.');
out.push(name);
const remaining = labels.length - i;
const lastTwo = labels.slice(-2).join('.');
if (remaining === 2) break;
if (remaining === 3 && TWO_PART_SUFFIXES.has(lastTwo)) break;
}
return out;
}
// ---------------------------------------------------------------------------------------------
// question 3 — cookies
// ---------------------------------------------------------------------------------------------
export function parseSetCookie(raw) {
const text = String(raw || '');
const parts = text.split(';');
const [nameValue, ...attributes] = parts;
const equals = nameValue.indexOf('=');
const name = (equals === -1 ? nameValue : nameValue.slice(0, equals)).trim();
const value = equals === -1 ? '' : nameValue.slice(equals + 1).trim();
const cookie = {
name,
value,
httpOnly: false,
secure: false,
sameSite: null,
maxAge: null,
expires: null,
domain: null
};
for (const attribute of attributes) {
const [rawKey, ...rest] = attribute.split('=');
const key = rawKey.trim().toLowerCase();
const val = rest.join('=').trim();
if (key === 'httponly') cookie.httpOnly = true;
else if (key === 'secure') cookie.secure = true;
else if (key === 'samesite') cookie.sameSite = val || null;
else if (key === 'max-age') cookie.maxAge = Number(val);
else if (key === 'expires') cookie.expires = val;
else if (key === 'domain') cookie.domain = val;
}
return cookie;
}
/** A cookie that carries a login/session, or one with no expiry at all. */
export function isSessionCookie(cookie) {
if (!cookie || !cookie.name) return false;
if (TRACKING_NAME.test(cookie.name)) return false;
if (SESSION_NAME.test(cookie.name)) return true;
const persistent = Number.isFinite(cookie.maxAge) || Boolean(cookie.expires);
return !persistent;
}
export function analyseCookies(rawCookies) {
const cookies = (rawCookies || []).map(parseSetCookie).filter((cookie) => cookie.name);
const findings = [];
const evidence = [];
let clause;
if (cookies.length === 0) {
findings.push({
level: 'info',
code: 'hardening_cookies_none',
message: 'This response set no cookies, so there was nothing to check here.'
});
evidence.push({ label: 'cookies', value: 'none set on this response' });
return { findings, evidence, clause: 'no cookies were set' };
}
const session = cookies.filter(isSessionCookie);
const weak = session.filter((cookie) => !cookie.httpOnly || !cookie.secure);
const weakNames = weak.map((cookie) => cookie.name);
for (const cookie of weak) {
const missing = [];
if (!cookie.httpOnly) missing.push('HttpOnly');
if (!cookie.secure) missing.push('Secure');
const why = [];
if (!cookie.httpOnly) why.push('any script running on the page can read it');
if (!cookie.secure) why.push('it can travel over plain http');
findings.push({
level: 'warn',
code: 'hardening_cookie_missing_flag',
message: `The session cookie ${cookie.name} is set without ${missing.join(' and ')}, so ${why.join(' and ')}.`,
fix: `Add ${missing.join('; ')} to the Set-Cookie header for ${cookie.name}.`
});
}
const weakCosmetic = cookies.filter((cookie) => !isSessionCookie(cookie) && (!cookie.httpOnly || !cookie.secure));
for (const cookie of weakCosmetic) {
const missing = [];
if (!cookie.httpOnly) missing.push('HttpOnly');
if (!cookie.secure) missing.push('Secure');
findings.push({
level: 'info',
code: 'hardening_cookie_optional_flag',
message: `The ${cookie.name} cookie is set without ${missing.join(' and ')} — normal for a cookie a script has to read, so nothing needs fixing.`,
fix: `Optional: add ${missing.join('; ')} to ${cookie.name} if nothing on the page reads it.`
});
}
const noSameSite = session.filter((cookie) => !cookie.sameSite);
if (noSameSite.length > 0) {
findings.push({
level: 'info',
code: 'hardening_cookie_no_samesite',
message: `The session cookie ${noSameSite.map((cookie) => cookie.name).join(', ')} has no SameSite setting, so the browser falls back to its own default (Lax in current Chrome, Firefox and Safari).`,
fix: 'Optional: state SameSite=Lax (or Strict) explicitly so every browser agrees.'
});
}
if (session.length > 0 && weak.length === 0) {
findings.push({
level: 'ok',
code: 'hardening_cookies_flagged',
message: `Every session cookie on this response (${session.map((cookie) => cookie.name).join(', ')}) carries HttpOnly and Secure.`
});
}
evidence.push({
label: 'cookies',
value: cookies
.map((cookie) => {
const flags = [
cookie.httpOnly ? 'HttpOnly' : null,
cookie.secure ? 'Secure' : null,
cookie.sameSite ? `SameSite=${cookie.sameSite}` : null
].filter(Boolean);
return `${cookie.name} (${flags.length > 0 ? flags.join(', ') : 'no flags'})`;
})
.join(', ')
});
if (weak.length > 0) clause = `the session cookie ${weakNames.join(', ')} is missing a flag`;
else if (session.length > 0) clause = 'its session cookies carry HttpOnly and Secure';
else clause = 'its cookies are not session cookies';
return { findings, evidence, clause };
}
// ---------------------------------------------------------------------------------------------
// question 4 — version banners
// ---------------------------------------------------------------------------------------------
const SERVER_VERSION = /\b([a-z][a-z0-9._+-]*)\/(\d+(?:\.\d+)+[a-z0-9._-]*)/i;
/** Returns [{ header, value }] for every header that names a product version. */
export function detectVersionBanner(headers) {
const out = [];
const server = headerValue(headers, 'server');
if (server) {
const match = SERVER_VERSION.exec(server);
if (match) out.push({ header: 'Server', value: match[0] });
}
const poweredBy = headerValue(headers, 'x-powered-by');
if (poweredBy && poweredBy.trim() !== '') out.push({ header: 'X-Powered-By', value: poweredBy.trim() });
for (const [header, label] of [['x-aspnet-version', 'X-AspNet-Version'], ['x-aspnetmvc-version', 'X-AspNetMvc-Version']]) {
const value = headerValue(headers, header);
if (value && value.trim() !== '') out.push({ header: label, value: value.trim() });
}
return out;
}
function bannerFindings(headers) {
const banners = detectVersionBanner(headers);
const findings = [];
const evidence = [];
if (banners.length === 0) {
findings.push({
level: 'ok',
code: 'hardening_no_version_banner',
message: 'The server does not advertise its software version in the response headers.'
});
evidence.push({ label: 'version banner', value: 'none' });
return { findings, evidence, clause: 'it does not advertise its software version' };
}
findings.push({
level: 'info',
code: 'hardening_version_banner',
message: `The server names its software and version in a header (${banners.map((banner) => `${banner.header}: ${banner.value}`).join(', ')}), which lets an automated scanner match the exact version against a list of known bugs. Not a fault on its own.`,
fix: 'Turn off server tokens (nginx: server_tokens off; Apache: ServerTokens Prod; PHP: expose_php off).'
});
evidence.push({
label: 'version banner',
value: banners.map((banner) => `${banner.header}: ${banner.value}`).join(', ')
});
return { findings, evidence, clause: 'it advertises its software version' };
}
// ---------------------------------------------------------------------------------------------
// the envelope
// ---------------------------------------------------------------------------------------------
const FAILURE_TEXT = {
timeout: 'The site did not answer in time, so nothing was judged about how it serves pages.',
dns_timeout: 'The domain lookup took too long, so nothing was judged about how it serves pages.',
dns_nxdomain: 'That domain did not resolve, so there was no page to look at.',
refused: 'The server refused the connection, so there was nothing to look at.',
tls_expired: 'The certificate has expired, so the page was not read and nothing was judged.',
tls_invalid: 'The certificate could not be verified, so the page was not read and nothing was judged.',
too_many_redirects: 'The site redirects in a loop and never reaches a page, so nothing was judged.',
private_address: 'That address points into a private network and was not contacted.',
private_host: 'That is a private address and was not contacted.',
ip_literal: 'Enter a domain name, not an IP address.',
bad_port: 'Only ports 80 and 443 can be checked.',
bad_scheme: 'Only http and https addresses can be checked.',
bad_input: 'That does not look like a domain name.',
budget_exhausted: 'This check stopped at its request budget, so part of it was skipped.'
};
export function describeFailure(error) {
const code = error && error.code ? error.code : null;
if (code && FAILURE_TEXT[code]) return FAILURE_TEXT[code];
return 'The page could not be loaded, so nothing was judged about how it is served.';
}
function blockedReason(status, headers, body) {
const text = String(body || '').toLowerCase();
const marker = CHALLENGE_MARKERS.find((needle) => text.includes(needle));
const edge = headerValue(headers, 'cf-ray') || headerValue(headers, 'x-sucuri-id') || headerValue(headers, 'x-akamai-request-id');
if (marker) return `bot challenge${edge ? ' (CDN)' : ''}`;
if (BLOCK_STATUSES.has(status)) return `status ${status}`;
return null;
}
function notEvaluated(checkedAt, summary, evidence, error) {
// The reason rides in evidence, not as an extra envelope key: the contract is exactly
// {id, state, summary, evidence, findings, checkedAt, fromCache}.
const rows = [...evidence];
if (error && error.code) rows.push({ label: 'reason', value: error.code });
return {
id: CHECK_ID,
state: 'not-evaluated',
summary,
evidence: rows,
findings: [],
checkedAt,
fromCache: false
};
}
/**
* Pure analysis over the gathered facts.
*
* facts = {
* host, url,
* response: { status, headers, bodyBytes, truncated } | null,
* compression: { contentEncoding, contentLength, receivedBytes, decodedBytes, requestedEncoding, honoured, vary },
* caa: { name, records, error, queried },
* certificate: { issuer } | null,
* blocked: { blocked, reason } | null,
* error: { code, message } | null
* }
*/
export function analyseHardening(facts = {}, { now = Date.now() } = {}) {
const checkedAt = new Date(now).toISOString();
const host = facts.host || null;
const evidence = [];
if (host) evidence.push({ label: 'address', value: facts.url || host });
if (facts.error) {
return notEvaluated(checkedAt, describeFailure(facts.error), evidence, facts.error);
}
const response = facts.response || null;
if (!response) {
return notEvaluated(checkedAt, 'No page came back from that address, so there was nothing to look at.', evidence);
}
const headers = response.headers || {};
const status = Number.isFinite(response.status) ? response.status : 0;
if (facts.blocked && facts.blocked.blocked) {
evidence.push({ label: 'response', value: `${status} — ${facts.blocked.reason || 'blocked'}` });
return notEvaluated(
checkedAt,
"The site's firewall or CDN blocked our automated probe — that is normal protection, not a fault, so nothing was judged.",
evidence
);
}
evidence.push({
label: 'page',
value: `${status} ${facts.url || host || ''}${Number.isFinite(response.bodyBytes) ? ` (${formatBytes(response.bodyBytes)} received)` : ''}`
});
if (response.truncated) {
evidence.push({ label: 'body', value: 'read up to the 256 KB cap', note: 'the size comparison uses the bytes actually received' });
}
if (facts.redirects > 0) {
evidence.push({ label: 'redirects', value: `${facts.redirects} followed` });
}
const compression = analyseCompression(
facts.compression || { contentEncoding: headerValue(headers, 'content-encoding'), honoured: false }
);
const findings = [];
const clauses = [];
for (const part of [
compressionFindings(compression),
caaFindings(facts.caa || {}, facts.certificate || null),
analyseCookies(cookieList(headers)),
bannerFindings(headers)
]) {
findings.push(...part.findings);
evidence.push(...part.evidence);
clauses.push(part.clause);
}
if (facts.redirectNote) {
findings.push({ level: 'info', code: facts.redirectNote.code, message: facts.redirectNote.message });
}
const state = worstLevel(findings);
const summary = state === 'ok'
? `Checked how this page is served: ${clauses.join('; ')}.`
: (findings.find((finding) => finding.level === state) || {}).message || 'Something here is worth tidying up.';
return {
id: CHECK_ID,
state,
summary,
evidence,
findings,
checkedAt,
fromCache: false
};
}
// ---------------------------------------------------------------------------------------------
// the network half
// ---------------------------------------------------------------------------------------------
/** A resolver with resolveCaa. `dns: {}` in tests means "CAA is unavailable here". */
export function createCaaResolver() {
const resolver = new dns.promises.Resolver({ timeout: 2500, tries: 1 });
return { resolveCaa: (name) => resolver.resolveCaa(name) };
}
function pickResolver(dnsOption, lookup) {
if (dnsOption && typeof dnsOption === 'object') {
return typeof dnsOption.resolveCaa === 'function' ? dnsOption : null;
}
if (lookup && typeof lookup === 'object' && typeof lookup.resolveCaa === 'function') return lookup;
return createCaaResolver();
}
async function readCaa(host, resolver) {
if (!resolver) return { name: null, records: [], queried: [], error: 'no resolver' };
const queried = [];
for (const name of caaNames(host)) {
queried.push(name);
try {
const answer = await withTimeout(resolver.resolveCaa(name), CAA_TIMEOUT_MS, 'dns_timeout');
const records = normaliseCaa(answer);
// RFC 8659: the nearest ancestor with a record is the policy that applies.
if (records.length > 0) return { name, records, queried, error: null };
} catch (err) {
const code = err && err.code ? err.code : 'unknown';
if (code === 'ENODATA' || code === 'ENOTFOUND' || code === 'ENOTIMP') continue;
return { name: null, records: [], queried, error: code };
}
}
return { name: null, records: [], queried, error: null };
}
function compressionFactsFrom(response, { honoured }) {
const headers = response.headers || {};
const contentEncoding = headerValue(headers, 'content-encoding');
const compressed = normaliseEncoding(contentEncoding) !== null;
const receivedBytes = Number.isFinite(response.bodyBytes) ? response.bodyBytes : null;
const decoded = Number.isFinite(response.decodedBytes) ? response.decodedBytes : null;
return {
contentEncoding,
contentLength: numericHeader(headers, 'content-length'),
receivedBytes,
// requestOnce hands back a utf8 string, so a compressed body cannot be decoded here: only an
// identity response gives a trustworthy plain length.
decodedBytes: decoded !== null ? decoded : (compressed ? null : receivedBytes),
requestedEncoding: COMPRESSION_ACCEPT,
honoured,
vary: headerValue(headers, 'vary')
};
}
function bodyBytesOf(res) {
// Prefer the real wire size net-guard measured; fall back to the decoded body only when the
// transport did not report it (the test fakes).
if (Number.isFinite(res.bodyBytes)) return res.bodyBytes;
if (typeof res.body === 'string') return Buffer.byteLength(res.body, 'utf8');
if (Buffer.isBuffer(res.body)) return res.body.length;
return null;
}
/**
* Gather, then analyse. One GET (two when the first answer redirects), one DNS walk, no other
* socket. `request` is the transport seam for tests; it defaults to net-guard's requestOnce.
*/
export async function checkHardening(input, { lookup, dns: dnsOption, request = requestOnce, now = Date.now() } = {}) {
const checkedAt = new Date(now).toISOString();
const budget = createRequestBudget();
let target;
try {
target = parseTarget(input);
} catch (err) {
return notEvaluated(checkedAt, describeFailure(err), [{ label: 'address', value: String(input) }], err);
}
const scheme = target.port === 80 ? 'http' : 'https';
let url = `${scheme}://${target.host}/`;
const facts = {
host: target.host,
url,
response: null,
compression: null,
caa: null,
certificate: null,
blocked: null,
error: null,
redirects: 0
};
const resolver = pickResolver(dnsOption, lookup);
const caaPromise = readCaa(target.host, resolver);
const fetchPage = async (targetUrl, label) => {
budget.spend(label);
return request(targetUrl, {
lookup,
accept: PAGE_ACCEPT,
// Honoured only when net-guard learns the option; see GUARD_HONOURS_COMPRESSION.
acceptEncoding: COMPRESSION_ACCEPT,
maxBytes: PAGE_MAX_BYTES,
timeoutMs: PAGE_TIMEOUT_MS
});
};
try {
let res = await fetchPage(url, 'page fetch');
let body = typeof res.body === 'string' ? res.body : '';
let reason = blockedReason(res.status, res.headers || {}, body);
if (!reason && res.status >= 300 && res.status < 400 && res.headers && res.headers.location) {
// One guarded follow so the headers audited are the ones a visitor actually gets.
let next = null;
try {
next = new URL(res.headers.location, res.url || url).toString();
} catch {
next = null;
}
// guardHop re-validates the target with the same rules as the first hop: no port 8443, no
// private host, no scheme this tool will not open.
const hopError = next ? guardHop(next) : new NetGuardError('bad_input', 'The redirect target could not be read.');
if (hopError) {
facts.redirectNote = {
code: 'hardening_redirect_not_followed',
message: `The address redirects to somewhere this tool will not open (${hopError.message}), so the page behind it was not read.`
};
} else {
url = next;
facts.url = next;
res = await fetchPage(next, 'redirect follow');
facts.redirects = 1;
body = typeof res.body === 'string' ? res.body : '';
reason = blockedReason(res.status, res.headers || {}, body);
if (res.status >= 300 && res.status < 400) {
facts.redirectNote = {
code: 'hardening_redirect_chain',
message: 'The address redirects more than once, so these answers describe the first redirect rather than the final page.'
};
}
}
}
facts.response = {
status: res.status,
headers: res.headers || {},
bodyBytes: bodyBytesOf(res),
decodedBytes: Number.isFinite(res.decodedBytes) ? res.decodedBytes : null,
decodedBytes: Number.isFinite(res.decodedBytes) ? res.decodedBytes : null,
truncated: res.truncated === true
};
facts.compression = compressionFactsFrom(facts.response, { honoured: GUARD_HONOURS_COMPRESSION });
facts.certificate = res.tls && res.tls.issuer ? { issuer: res.tls.issuer } : null;
if (reason) facts.blocked = { blocked: true, reason };
} catch (err) {
facts.error = { code: err && err.code ? err.code : 'request_failed', message: err && err.message ? err.message : null };
}
try {
facts.caa = await caaPromise;
} catch (err) {
facts.caa = { name: null, records: [], queried: [], error: (err && err.code) || 'unknown' };
}
const result = analyseHardening(facts, { now });
return { ...result, checkedAt };
}
export const check = checkHardening;
export default checkHardening;
+781
View File
@@ -0,0 +1,781 @@
// mail-transport — the three records that sit NEXT TO SPF, DKIM and DMARC, and that almost no
// Malaysian SME has published: MTA-STS (a TXT record that promises a policy file, plus the policy
// file itself over HTTPS), TLS-RPT (the reporting address for failed TLS delivery) and BIMI
// (a logo for the inbox, which only counts when DMARC is actually enforcing).
//
// The honesty problem here is specific. A `_mta-sts` TXT record on its own protects nothing: it
// only points at https://mta-sts.<domain>/.well-known/mta-sts.txt, and the mode lives in that
// file. So this module never says "MTA-STS is protecting you" off the TXT alone — it says what it
// read, and names the file when it read the file. When the file cannot be fetched (timeout, WAF,
// refused connection) the answer is `not-evaluated` with the reason code, never a finding.
//
// Absence of all three is the normal state of a small business. It reads as info/opportunity, not
// as a fault, and the summary says which one is worth adding first.
//
// Budget: four DNS TXT queries and at most ONE outbound HTTPS request (the policy file, 32 KB,
// 3 s). Nothing else leaves this process.
import dns from 'node:dns';
import { parseTarget, requestOnce } from '../lib/net-guard.mjs';
import { registrableApex, parseDmarc, joinTxtChunks } from './mail-auth.mjs';
export const MTA_STS_NAME = '_mta-sts';
export const TLS_RPT_NAME = '_smtp._tls';
export const BIMI_NAME = 'default._bimi';
export const DMARC_NAME = '_dmarc';
export const POLICY_HOST_PREFIX = 'mta-sts';
export const POLICY_PATH = '/.well-known/mta-sts.txt';
export const POLICY_TIMEOUT_MS = 3_000;
export const POLICY_MAX_BYTES = 32 * 1024;
// One request, and only when a valid _mta-sts TXT record exists to justify it.
export const REQUEST_BUDGET = 1;
// 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 LEVELS = { ok: 0, info: 1, warn: 2, fail: 3 };
const MODES = new Set(['enforce', 'testing', 'none']);
// ---------------------------------------------------------------------------
// resolver
// ---------------------------------------------------------------------------
export function createResolver() {
const resolver = new dns.promises.Resolver({ timeout: 2000, tries: 2 });
return { resolveTxt: (host) => resolver.resolveTxt(host) };
}
/**
* mail-auth's seam is an injected resolver OBJECT (`{ dns }` or `{ lookup }` holding resolveTxt);
* who-holds' seam is net-guard's lookup FUNCTION. Accept both, so a caller can hand this module
* either shape and the tests still never reach the network.
*/
export function pickResolver({ dns: explicit, lookup } = {}) {
if (explicit && typeof explicit.resolveTxt === 'function') return explicit;
if (lookup && typeof lookup === 'object' && typeof lookup.resolveTxt === 'function') return lookup;
return createResolver();
}
/**
* net-guard wants a lookup FUNCTION. If the injected resolver can answer A/AAAA we build one from
* it, so an injected fake also covers the policy fetch; a resolver with only resolveTxt (all the
* tests need) leaves net-guard on its own resolver, and the fake `request` never uses it.
*/
function pickNetLookup({ lookup, resolver }) {
if (typeof lookup === 'function') return lookup;
if (!resolver || typeof resolver.resolve4 !== 'function') return undefined;
return async (host) => {
const answers = [];
for (const [method, family] of [[resolver.resolve4, 4], [resolver.resolve6, 6]]) {
if (typeof method !== 'function') continue;
try {
const raw = await method.call(resolver, host);
for (const entry of Array.isArray(raw) ? raw : []) {
if (typeof entry === 'string' && entry.length > 0) answers.push({ address: entry, family });
else if (entry && typeof entry.address === 'string') answers.push({ address: entry.address, family: entry.family || family });
}
} catch {
// one family missing is normal (a v4-only host has no AAAA)
}
}
if (answers.length === 0) throw Object.assign(new Error('dns_nxdomain'), { code: 'ENOTFOUND' });
return answers;
};
}
function errorCode(err) {
if (!err) return 'UNKNOWN';
return String(err.code || err.errno || 'UNKNOWN').toUpperCase();
}
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 };
return { ok: false, records: [], code, transient: TRANSIENT_CODES.has(code) };
}
}
// ---------------------------------------------------------------------------
// record parsing (pure)
// ---------------------------------------------------------------------------
/** Split `k=v; k=v` into a lowercase-keyed tag bag. Shared by all three record types. */
export function parseTags(record) {
const tags = {};
for (const part of String(record ?? '').split(';')) {
const equals = part.indexOf('=');
if (equals <= 0) continue;
const key = part.slice(0, equals).trim().toLowerCase();
if (key.length === 0) continue;
tags[key] = part.slice(equals + 1).trim();
}
return tags;
}
/**
* Parse the `_mta-sts` TXT record. It carries a version and an id — nothing about enforcement.
* `valid` means "this is an MTA-STS record at all", which is the only thing the TXT can prove.
*/
export function parseMtaStsTxt(records) {
const list = (Array.isArray(records) ? records : []).map((record) => String(record ?? '').trim()).filter(Boolean);
const candidates = list.filter((record) => /^v=stsv1(\s*;|\s|$)/i.test(record));
const record = candidates[0] ?? list[0] ?? null;
const tags = record ? parseTags(record) : {};
return {
present: list.length > 0,
valid: candidates.length > 0,
id: tags.id && tags.id.length > 0 ? tags.id : null,
record: candidates[0] ?? null,
count: candidates.length,
stray: list.length - candidates.length
};
}
/**
* Parse the policy FILE (https://mta-sts.<domain>/.well-known/mta-sts.txt).
*
* `isPolicy` is the only claim a fetch can make on its own: the body starts with version: STSv1.
* `valid` adds the three things RFC 8461 requires for the policy to be usable — a known mode, a
* numeric max_age, and at least one mx host.
*/
export function parseMtaStsPolicy(text) {
const out = {
isPolicy: false,
valid: false,
version: null,
mode: null,
modeKnown: false,
maxAge: null,
mx: [],
unknown: {},
lines: 0
};
const body = String(text ?? '');
if (body.trim().length === 0) return out;
for (const rawLine of body.split(/\r?\n/)) {
const line = rawLine.trim();
if (line.length === 0 || line.startsWith('#')) continue;
const colon = line.indexOf(':');
if (colon <= 0) continue;
const key = line.slice(0, colon).trim().toLowerCase();
const value = line.slice(colon + 1).trim();
out.lines += 1;
if (key === 'version') out.version = value;
else if (key === 'mode') out.mode = value.toLowerCase();
else if (key === 'max_age') out.maxAge = /^\d+$/.test(value) ? Number(value) : null;
else if (key === 'mx') {
const host = value.toLowerCase().replace(/\.$/, '');
if (host.length > 0 && !out.mx.includes(host)) out.mx.push(host);
} else out.unknown[key] = value;
}
out.isPolicy = /^stsv1$/i.test(out.version || '');
out.modeKnown = MODES.has(out.mode || '');
out.valid = out.isPolicy && out.modeKnown && Number.isFinite(out.maxAge) && out.mx.length > 0;
return out;
}
/** Parse `_smtp._tls` (TLS-RPT, RFC 8460). `rua` is the reporting address, and it is required. */
export function parseTlsRptTxt(records) {
const list = (Array.isArray(records) ? records : []).map((record) => String(record ?? '').trim()).filter(Boolean);
const candidates = list.filter((record) => /^v=tlsrptv1(\s*;|\s|$)/i.test(record));
const record = candidates[0] ?? null;
const tags = record ? parseTags(record) : {};
const rua = (tags.rua || '')
.split(',')
.map((part) => part.trim())
.filter((part) => part.length > 0);
return {
present: list.length > 0,
valid: candidates.length > 0 && rua.length > 0,
record,
rua,
count: candidates.length,
stray: list.length - candidates.length
};
}
/** Parse `default._bimi` (BIMI). `l` is the logo, `a` the optional VMC certificate. */
export function parseBimiTxt(records) {
const list = (Array.isArray(records) ? records : []).map((record) => String(record ?? '').trim()).filter(Boolean);
const candidates = list.filter((record) => /^v=bimi1(\s*;|\s|$)/i.test(record));
const record = candidates[0] ?? null;
const tags = record ? parseTags(record) : {};
const location = tags.l && tags.l.length > 0 ? tags.l : null;
const authority = tags.a && tags.a.length > 0 ? tags.a : null;
return {
present: list.length > 0,
valid: candidates.length > 0 && location !== null,
record,
location,
authority,
count: candidates.length,
stray: list.length - candidates.length
};
}
// ---------------------------------------------------------------------------
// the one fetch
// ---------------------------------------------------------------------------
export function policyUrl(domain) {
return `https://${POLICY_HOST_PREFIX}.${domain}${POLICY_PATH}`;
}
/**
* Read the policy file. Exactly one request, 32 KB and 3 s, `Accept: text/plain` (the default
* Accept is text/html, and a policy is not a page).
*
* Outcomes are deliberately three-way:
* ok — a body with `version: STSv1`
* missing — a real answer that no policy is served there (404, redirect, DNS has no such
* name, broken certificate). This is a broken promise and IS a finding.
* not-read — we were blocked or timed out. Not a finding, and it makes the card not-evaluated.
*/
async function readPolicy(domain, { request, lookup }) {
const url = policyUrl(domain);
let res;
try {
res = await request(url, {
lookup,
method: 'GET',
timeoutMs: POLICY_TIMEOUT_MS,
maxBytes: POLICY_MAX_BYTES,
accept: 'text/plain, text/*;q=0.9'
});
} catch (err) {
const code = errorCode(err).toLowerCase();
if (code === 'dns_nxdomain' || code === 'tls_invalid' || code === 'tls_expired') {
return { attempted: true, ok: false, kind: 'missing', code, url, reason: POLICY_REASONS[code] || 'the policy could not be read' };
}
return { attempted: true, ok: false, kind: 'not-read', code, url, reason: POLICY_REASONS[code] || 'the request did not complete' };
}
const status = res && typeof res.status === 'number' ? res.status : 0;
const body = res && typeof res.body === 'string' ? res.body : '';
const truncated = Boolean(res && res.truncated);
if (status >= 200 && status < 300) {
const parsed = parseMtaStsPolicy(body);
if (parsed.isPolicy) {
return { attempted: true, ok: true, kind: 'ok', code: null, url, status, text: body, truncated, parsed };
}
return { attempted: true, ok: false, kind: 'missing', code: 'not_a_policy', url, status, truncated, parsed };
}
if (status >= 300 && status < 400) {
return { attempted: true, ok: false, kind: 'missing', code: 'redirect', url, status, location: (res.headers && res.headers.location) || null };
}
if (status === 404 || status === 410) {
return { attempted: true, ok: false, kind: 'missing', code: `http_${status}`, url, status };
}
if (status === 401 || status === 403 || status === 407 || status === 429 || status >= 500) {
return { attempted: true, ok: false, kind: 'not-read', code: `http_${status}`, url, status };
}
return { attempted: true, ok: false, kind: 'missing', code: `http_${status}`, url, status };
}
// Predicates: they follow the policy URL in a sentence ("https://… did not answer within 3 s").
const POLICY_REASONS = {
timeout: 'did not answer within 3 seconds',
refused: 'refused the connection',
request_failed: 'could not be reached',
dns_nxdomain: 'does not resolve',
tls_invalid: 'has a certificate that could not be verified',
tls_expired: 'has an expired certificate',
bad_port: 'would need a port this tool does not open',
private_host: 'resolves to a private address',
too_many_redirects: 'redirected too many times'
};
function policyReason(policy) {
if (!policy) return 'was not read';
if (policy.code && POLICY_REASONS[policy.code]) return POLICY_REASONS[policy.code];
if (policy.code === 'not_a_policy') return 'answered without a version: STSv1 line';
if (policy.code === 'redirect') return `redirected (HTTP ${policy.status}) instead of serving the policy`;
if (policy.code === 'http_404' || policy.code === 'http_410') return `is not there (HTTP ${policy.status})`;
if (policy.status) return `answered HTTP ${policy.status}`;
return 'could not be read';
}
// ---------------------------------------------------------------------------
// gather
// ---------------------------------------------------------------------------
async function gather(domain, { resolver, request, lookup }) {
const [mtaAnswer, tlsAnswer, bimiAnswer, dmarcAnswer] = await Promise.all([
queryTxt(resolver, `${MTA_STS_NAME}.${domain}`),
queryTxt(resolver, `${TLS_RPT_NAME}.${domain}`),
queryTxt(resolver, `${BIMI_NAME}.${domain}`),
queryTxt(resolver, `${DMARC_NAME}.${domain}`)
]);
const mtaSts = { checked: mtaAnswer.ok, code: mtaAnswer.code, ...parseMtaStsTxt(mtaAnswer.records) };
const tlsRpt = { checked: tlsAnswer.ok, code: tlsAnswer.code, ...parseTlsRptTxt(tlsAnswer.records) };
const bimi = { checked: bimiAnswer.ok, code: bimiAnswer.code, ...parseBimiTxt(bimiAnswer.records) };
const dmarcRecord = dmarcAnswer.records.find((record) => /^v=dmarc1(\s*;|\s|$)/i.test(record.trim())) ?? null;
const dmarc = {
checked: dmarcAnswer.ok,
code: dmarcAnswer.code,
record: dmarcRecord,
parsed: dmarcRecord ? parseDmarc(dmarcRecord) : null
};
const gathered = { domain, mtaSts, tlsRpt, bimi, dmarc, policy: { attempted: false, ok: false, kind: 'skipped' }, fatal: null };
// Nothing was readable at all: a resolver refusal is a statement about our resolver, not the site.
if (!mtaAnswer.ok && !tlsAnswer.ok && !bimiAnswer.ok) {
const code = mtaAnswer.code || tlsAnswer.code || bimiAnswer.code;
gathered.fatal = { code, transient: TRANSIENT_CODES.has(code) };
return gathered;
}
// The one outbound request, and only when a valid record exists to justify it.
if (mtaSts.checked && mtaSts.valid) {
gathered.policy = await readPolicy(domain, { request, lookup });
}
return gathered;
}
// ---------------------------------------------------------------------------
// summary (pure)
// ---------------------------------------------------------------------------
function listClause(names) {
if (names.length === 1) return names[0];
if (names.length === 2) return `${names[0]} and ${names[1]}`;
return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
}
/**
* ONE plain-English sentence. No score, no delivery promise, and no claim that a TXT record
* protects anything on its own.
*/
export function buildSummary({ domain, mtaSts, policy, tlsRpt, bimi, dmarcEnforced, fatal }) {
if (fatal) {
return `We could not read the mail transport records for ${domain} just now (${fatal.code}), so this is not a verdict — try again in a minute.`;
}
const others = [];
if (tlsRpt.present && tlsRpt.valid) others.push('TLS-RPT');
if (bimi.present && bimi.valid) others.push('BIMI');
// An unreadable record is unknown, not absent: saying "none is published" here would be a
// claim about the domain that a refused or stalled query cannot support.
if (mtaSts.checked === false) {
return `We could not read the _mta-sts record for ${domain} just now (${mtaSts.code || 'DNS error'}), so MTA-STS is unknown rather than missing.`;
}
if (mtaSts.present && mtaSts.valid) {
if (policy.kind === 'not-read') {
return `Your _mta-sts record is published, but the policy file at ${policyUrl(domain)} could not be read from here (${policy.code}), so its mode is unchecked and this is not a verdict.`;
}
if (policy.kind === 'missing') {
return `Your _mta-sts record promises a policy, but ${policyUrl(domain)} ${policyReason(policy)}, so mail servers ignore MTA-STS on this domain.`;
}
if (policy.ok && policy.parsed) {
if (policy.parsed.mode === 'enforce') {
return `The MTA-STS policy file says mode=enforce, so mail servers that support MTA-STS will not quietly fall back to plain text when delivering to ${domain}.`;
}
if (policy.parsed.mode === 'testing') {
return `The MTA-STS policy is published and in testing mode: senders report failures but still deliver, so this is progress rather than protection yet.`;
}
return 'The MTA-STS policy file is published but says mode=none, so it neither reports nor enforces anything.';
}
}
if (mtaSts.present && !mtaSts.valid) {
return 'A _mta-sts record is published but it does not start with v=STSv1, so mail servers ignore it.';
}
if (others.length > 0) {
const bimiClause = bimi.present && bimi.valid && !dmarcEnforced
? ', and BIMI will not show until DMARC is set to quarantine or reject'
: '';
return `This domain publishes ${listClause(others)} but no MTA-STS record, so a mail server can still be talked into delivering plain text${bimiClause}.`;
}
return 'No MTA-STS, TLS-RPT or BIMI record is published, which is normal for a small business — MTA-STS is the one worth adding first, because it stops a silent downgrade to plain text.';
}
export function worstLevel(findings) {
let level = 'ok';
for (const finding of findings) {
if ((LEVELS[finding.level] ?? 0) > (LEVELS[level] ?? 0)) level = finding.level;
}
return level === 'info' ? 'ok' : level;
}
// ---------------------------------------------------------------------------
// analysis (pure)
// ---------------------------------------------------------------------------
/**
* Turn gathered answers into the card. Pure and synchronous: every fact it prints was already
* returned by DNS or by the single policy fetch, and it says which one.
*/
export function analyseMailTransport(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 && gathered.domain) || 'this domain';
const envelope = (state, summary, ev, fi) => ({
id: 'mail-transport', state, summary, evidence: ev, findings: fi, checkedAt, fromCache: false
});
const empty = {
mtaSts: { checked: false, present: false, valid: false, count: 0, record: null, id: null },
tlsRpt: { checked: false, present: false, valid: false, rua: [], record: null },
bimi: { checked: false, present: false, valid: false, location: null, authority: null, record: null },
dmarc: { checked: false, record: null, parsed: null },
policy: { attempted: false, ok: false, kind: 'skipped' }
};
const source = gathered || {};
const mtaSts = { ...empty.mtaSts, ...(source.mtaSts || {}) };
const tlsRpt = { ...empty.tlsRpt, ...(source.tlsRpt || {}) };
const bimi = { ...empty.bimi, ...(source.bimi || {}) };
const dmarc = { ...empty.dmarc, ...(source.dmarc || {}) };
const policy = { ...empty.policy, ...(source.policy || {}) };
const data = { ...empty, ...source, mtaSts, tlsRpt, bimi, dmarc, policy };
// ---- nothing readable at all -------------------------------------------------------------
if (data.fatal) {
add(
'info',
'dns_unavailable',
`The DNS for ${domain} did not answer just now (${data.fatal.code}), so none of MTA-STS, TLS-RPT or BIMI could be read. This is not a finding against the domain.`,
'Try again in a minute.'
);
return envelope(
'not-evaluated',
buildSummary({ domain, mtaSts, policy, tlsRpt, bimi, fatal: data.fatal }),
[{ label: 'DNS', value: `unreadable (${data.fatal.code})` }],
findings
);
}
// ---- MTA-STS ------------------------------------------------------------------------------
let policyState = 'absent';
if (!mtaSts.checked) {
add(
'info',
'mta_sts_not_checked',
`The _mta-sts record could not be read just now (${mtaSts.code}), so MTA-STS is unknown rather than missing.`
);
evidence.push({ label: 'MTA-STS record', value: `not checked (${mtaSts.code})` });
policyState = 'unknown';
} else if (!mtaSts.present) {
add(
'info',
'mta_sts_absent',
'No MTA-STS record is published: a mail server can still be told to downgrade the connection to plain text, and publishing a policy stops that.',
`Publish a TXT record at _mta-sts.${domain} (v=STSv1; id=<a token you change when the policy changes>) and serve the policy at ${policyUrl(domain)}.`
);
evidence.push({ label: 'MTA-STS record', value: 'none' });
} else if (!mtaSts.valid) {
add(
'warn',
'mta_sts_txt_malformed',
`A _mta-sts TXT record is published but it does not start with v=STSv1, so receivers ignore it: ${mtaSts.record || 'the record is empty'}.`,
'Rewrite the record as v=STSv1; id=<token>, then publish the policy file it points at.'
);
evidence.push({ label: 'MTA-STS record', value: 'malformed', note: mtaSts.record || undefined });
} else {
if (mtaSts.count > 1) {
add(
'warn',
'mta_sts_txt_multiple',
`${mtaSts.count} _mta-sts records are published. RFC 8461 allows one, so receivers may ignore all of them.`,
'Keep one v=STSv1 record and delete the others.'
);
}
evidence.push({
label: 'MTA-STS record',
value: mtaSts.record,
note: mtaSts.id ? `id=${mtaSts.id}; this record only points at the policy file` : 'this record only points at the policy file'
});
policyState = 'published';
}
if (mtaSts.checked && mtaSts.valid) {
const url = policyUrl(domain);
if (policy.kind === 'not-read') {
// Blocked or timed out: not a finding, and the card cannot be a verdict.
add(
'info',
'mta_sts_policy_not_read',
`The policy file at ${url} could not be read from here (${policy.code}), so its mode is unknown rather than absent.`
);
evidence.push({ label: 'MTA-STS policy', value: `not read (${policy.code})`, note: `the policy file ${policyReason(policy)}` });
policyState = 'not-evaluated';
} else if (policy.kind === 'missing') {
add(
'warn',
policy.code === 'not_a_policy' ? 'mta_sts_policy_not_a_policy' : 'mta_sts_policy_missing',
policy.code === 'not_a_policy'
? `The _mta-sts record promises a policy, but ${url} answered without a version: STSv1 line, so senders treat the domain as having no policy.`
: `The _mta-sts record promises a policy, but the file at ${url} ${policyReason(policy)}, so senders treat the domain as having no policy.`,
`Serve the policy file at ${url} with version: STSv1, mode: enforce, max_age: 86400 and one mx: line per mail host.`
);
evidence.push({ label: 'MTA-STS policy', value: `missing (${policy.code})`, note: policyReason(policy) });
policyState = 'broken';
} else if (policy.ok && policy.parsed) {
const parsed = policy.parsed;
evidence.push({
label: 'MTA-STS policy',
value: `mode=${parsed.mode ?? 'unknown'}, max_age=${Number.isFinite(parsed.maxAge) ? parsed.maxAge : 'missing'}`,
note: parsed.mx.length > 0 ? `mx: ${parsed.mx.join(', ')}` : 'no mx: line'
});
// An incomplete policy is not honoured, so the mode it names is never reported as being in
// force: the reader gets the missing lines instead of a claim the record cannot support.
const shape = [];
if (!parsed.modeKnown) shape.push(`a mode: line (found ${parsed.mode ?? 'none'})`);
if (!Number.isFinite(parsed.maxAge)) shape.push('a numeric max_age');
if (parsed.mx.length === 0) shape.push('an mx: line');
if (shape.length > 0) {
policyState = 'broken';
add(
'warn',
'mta_sts_policy_malformed',
`The policy file at ${url} is missing ${listClause(shape)}, which RFC 8461 requires, so senders ignore the policy${parsed.mode ? ` even though it says mode=${parsed.mode}` : ''}.`,
'Serve version: STSv1, mode: enforce, max_age: 86400 and one mx: line per mail host that receives mail for this domain.'
);
} else if (parsed.mode === 'enforce') {
add(
'ok',
'mta_sts_mode_enforce',
`The policy file at ${url} says mode=enforce, so senders that support MTA-STS will not fall back to an unencrypted connection to your mail hosts.`
);
policyState = 'enforced';
} else if (parsed.mode === 'testing') {
add(
'warn',
'mta_sts_mode_testing',
`The policy file at ${url} says mode=testing: senders report delivery failures but still deliver, so the policy is published but not enforced yet.`,
'Read the reports for a couple of weeks, then change mode: testing to mode: enforce.'
);
policyState = 'testing';
} else {
add(
'info',
'mta_sts_mode_none',
`The policy file at ${url} says mode=none, which tells senders not to enforce anything — the record is published, but nothing is protected.`
);
policyState = 'none';
}
}
}
// ---- TLS-RPT ------------------------------------------------------------------------------
if (!tlsRpt.checked) {
add('info', 'tls_rpt_not_checked', `The _smtp._tls record could not be read just now (${tlsRpt.code}), so TLS reporting is unknown rather than missing.`);
evidence.push({ label: 'TLS-RPT record', value: `not checked (${tlsRpt.code})` });
} else if (!tlsRpt.present) {
add(
'info',
'tls_rpt_absent',
'No TLS-RPT record is published, so nobody tells you when TLS delivery to your domain fails — the failures are silent.',
`Publish a TXT record at ${TLS_RPT_NAME}.${domain}: v=TLSRPTv1; rua=mailto:tls-reports@${domain}`
);
evidence.push({ label: 'TLS-RPT record', value: 'none' });
} else if (!tlsRpt.valid) {
add(
'warn',
'tls_rpt_no_rua',
`A _smtp._tls record is published but it has no usable rua= address, so the reports have nowhere to go: ${tlsRpt.record || 'the record is empty'}.`,
`Rewrite it as v=TLSRPTv1; rua=mailto:tls-reports@${domain}`
);
evidence.push({ label: 'TLS-RPT record', value: 'no reporting address', note: tlsRpt.record || undefined });
} else {
add('ok', 'tls_rpt_published', `TLS failure reports are sent to ${tlsRpt.rua.join(', ')}, read from the _smtp._tls record.`);
evidence.push({ label: 'TLS-RPT record', value: tlsRpt.rua.join(', ') });
}
// ---- BIMI ---------------------------------------------------------------------------------
const dmarcEnforced = Boolean(
dmarc.parsed && dmarc.parsed.valid
&& (dmarc.parsed.p === 'quarantine' || dmarc.parsed.p === 'reject')
&& dmarc.parsed.pct >= 100
);
if (!bimi.checked) {
add('info', 'bimi_not_checked', `The default._bimi record could not be read just now (${bimi.code}), so BIMI is unknown rather than missing.`);
evidence.push({ label: 'BIMI record', value: `not checked (${bimi.code})` });
} else if (!bimi.present) {
add(
'info',
'bimi_absent',
'No BIMI record is published, so mail from your domain shows no logo in the inbox — optional, and only worth doing after DMARC is enforced.',
`After DMARC is at p=quarantine or p=reject, publish default._bimi.${domain}: v=BIMI1; l=https://<your logo>.svg`
);
evidence.push({ label: 'BIMI record', value: 'none' });
} else if (!bimi.valid) {
add(
'warn',
'bimi_no_logo',
`A default._bimi record is published but it has no l= logo address, so there is nothing for a mailbox to display: ${bimi.record || 'the record is empty'}.`,
'Add l=https://… pointing at an SVG Tiny PS logo.'
);
evidence.push({ label: 'BIMI record', value: 'no logo address', note: bimi.record || undefined });
} else if (!dmarc.checked || !dmarc.parsed) {
add(
'info',
'bimi_dmarc_unknown',
'A BIMI record with a logo is published, but the _dmarc record could not be read, so whether BIMI would be honoured is unknown — most receivers require DMARC enforcement first.'
);
evidence.push({ label: 'BIMI record', value: bimi.location, note: 'DMARC policy unreadable' });
} else if (!dmarcEnforced) {
add(
'info',
'bimi_ignored_dmarc_weak',
`A BIMI record with a logo is published, but DMARC is p=${dmarc.parsed.p ?? 'missing'}${dmarc.parsed.pct < 100 ? ` with pct=${dmarc.parsed.pct}` : ''}, and most receivers ignore BIMI unless the DMARC policy is quarantine or reject at full strength.`,
'Enforce DMARC first (p=quarantine, then p=reject); BIMI starts working after that.'
);
evidence.push({ label: 'BIMI record', value: bimi.location, note: `ignored while DMARC is p=${dmarc.parsed.p ?? 'missing'}` });
} else {
add(
'ok',
'bimi_published',
`A BIMI logo is published at ${bimi.location}, and DMARC is p=${dmarc.parsed.p}, which is the combination most receivers require.`
);
evidence.push({ label: 'BIMI record', value: bimi.location });
if (!bimi.authority) {
add(
'info',
'bimi_no_vmc',
'The BIMI record has no a= certificate (a VMC), so Gmail and Yahoo will still not display the logo.',
'A Verified Mark Certificate from DigiCert or Entrust is what makes the logo appear in those mailboxes.'
);
}
}
if (dmarc.checked) {
evidence.push({
label: 'DMARC policy',
value: dmarc.parsed ? (dmarc.parsed.valid ? `p=${dmarc.parsed.p ?? 'none'}` : 'invalid') : 'none',
note: 'read only to judge whether BIMI counts'
});
}
// ---- absence of all three is normal -------------------------------------------------------
const allAbsent = mtaSts.checked && tlsRpt.checked && bimi.checked
&& !mtaSts.present && !tlsRpt.present && !bimi.present;
if (allAbsent) {
// One row instead of three: three "missing" rows would read as three faults.
const kept = findings.filter((finding) => !['mta_sts_absent', 'tls_rpt_absent', 'bimi_absent'].includes(finding.code));
kept.unshift({
level: 'info',
code: 'mail_transport_none',
message: 'None of MTA-STS, TLS-RPT or BIMI is published. That is the normal state of a small business, and all three are optional hardening rather than a fault.',
fix: `Start with MTA-STS: a TXT record at _mta-sts.${domain} plus a policy file at ${policyUrl(domain)}.`
});
findings.length = 0;
findings.push(...kept);
}
// ---- state --------------------------------------------------------------------------------
// 'unknown' (the _mta-sts TXT could not be read) is as much a non-verdict as a blocked policy
// fetch: this module exists to answer the MTA-STS question, and it could not be asked.
const blocked = policyState === 'not-evaluated' || policyState === 'unknown';
const state = blocked ? 'not-evaluated' : worstLevel(findings);
return envelope(
state,
buildSummary({ domain, mtaSts, policy, tlsRpt, bimi, dmarcEnforced, fatal: null }),
evidence,
findings
);
}
// ---------------------------------------------------------------------------
// host role: a subdomain with no mail transport records is a website
// ---------------------------------------------------------------------------
/**
* tools.example.com has no MTA-STS because it sends no mail — the mail comes from example.com.
* Reporting that as "no MTA-STS" is a false accusation against an ordinary setup, so a subdomain
* that publishes none of the three is reported as website-only with a pointer to the apex.
*/
export function applyHostRole(result, host, gathered) {
const apex = registrableApex(host);
if (apex === host) return result;
if (!gathered || gathered.fatal) return result;
const publishesNothing = !gathered.mtaSts.present && !gathered.tlsRpt.present && !gathered.bimi.present;
if (!publishesNothing) return result;
return {
...result,
state: 'ok',
summary: `This host does not send or receive email of its own, so MTA-STS, TLS-RPT and BIMI for ${apex} are what matter — check ${apex}.`,
findings: [
{
level: 'info',
code: 'subdomain_no_mail',
message: `${host} publishes no MTA-STS, TLS-RPT or BIMI record, which is normal for a subdomain that only hosts a website or an app.`,
fix: `Check ${apex}: that is the domain your mail is actually sent from.`
}
]
};
}
// ---------------------------------------------------------------------------
// check
// ---------------------------------------------------------------------------
/**
* Report the mail-transport records for a domain.
*
* @param {string} input domain (or URL — the host is taken)
* @param {{dns?: object, lookup?: object|Function, request?: Function, now?: number, cache?: object}} options
* `dns` (or an object `lookup`) is a resolver with resolveTxt, exactly mail-auth's seam; a
* FUNCTION `lookup` is net-guard's seam and is passed to the policy fetch. `request` is the fake
* used by the offline tests. `now` fixes the clock.
*/
export async function checkMailTransport(input, { dns: dnsSource, lookup, request = requestOnce, now = Date.now(), cache } = {}) {
const checkedAt = new Date(now).toISOString();
const envelope = (state, summary, evidence, findings) => ({
id: 'mail-transport', state, summary, evidence, findings, checkedAt, fromCache: false
});
let host;
try {
host = parseTarget(typeof input === 'string' ? input : String(input ?? '')).host;
} catch {
return envelope('fail', 'That does not look like a domain name, so there was nothing to check.', [], [
{ level: 'fail', code: 'bad_input', message: 'That does not look like a domain name.' }
]);
}
void cache; // caching is the router's job; this module always reports fromCache: false
const resolver = pickResolver({ dns: dnsSource, lookup });
const netLookup = pickNetLookup({ lookup, resolver });
const gathered = await gather(host, { resolver, request, lookup: netLookup });
return applyHostRole(analyseMailTransport(gathered, { now }), host, gathered);
}
export const check = checkMailTransport;
// Re-exported so a test can pin the apex rule this module judges subdomains by.
export { registrableApex };
+5
View File
@@ -45,6 +45,11 @@ export function layout({ title, description, body, active = '', robots = 'index,
<meta property="og:title" content="${esc(title)}">
<meta property="og:description" content="${esc(description)}">
<meta property="og:url" content="${esc(canonical || abs('/'))}">
<meta property="og:image" content="${esc(abs('/assets/og.png'))}">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Hoelee domain check: certificate, email records, WhatsApp card, www and registry in one pass">
<meta name="twitter:card" content="summary_large_image">
${extraHead}
</head>
<body>
+42 -13
View File
@@ -18,6 +18,7 @@ import net from 'node:net';
import dns from 'node:dns';
import http from 'node:http';
import https from 'node:https';
import nodeZlib from 'node:zlib';
import tls from 'node:tls';
export const ALLOWED_PORTS = new Set([80, 443]);
@@ -286,7 +287,11 @@ export async function requestOnce(rawUrl, {
// A caller fetching something that is NOT a page (an og:image, a robots.txt) can say what it
// wants. Without this, a server that content-negotiates answers text/html for an image URL and
// the report would call a perfectly good image "not an image".
accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
// Identity by default: the page checks parse the body, and asking for compression there would
// hand them bytes they cannot read. A caller that wants to MEASURE compression asks for it and
// gets the decoded body plus the wire size, so nothing has to decode a response twice.
acceptEncoding = 'identity'
} = {}) {
const { host, port } = parseTarget(rawUrl);
const parsed = new URL(rawUrl.includes('://') ? rawUrl : `https://${rawUrl}`);
@@ -317,7 +322,7 @@ export async function requestOnce(rawUrl, {
'user-agent': userAgent,
accept,
'accept-language': 'en-MY,en;q=0.9',
'accept-encoding': 'identity',
'accept-encoding': acceptEncoding,
connection: 'close'
},
timeout: timeoutMs,
@@ -340,17 +345,41 @@ export async function requestOnce(rawUrl, {
// check" promise the about page makes and doubles the load on the target).
let tls = null;
try { tls = readCertificate(res.socket); } catch { tls = null; }
const finish = () => resolve({
status: res.statusCode || 0,
headers: res.headers,
body: Buffer.concat(chunks).toString('utf8'),
url: parsed.toString(),
address: pinned.address,
family: pinned.family,
truncated,
tls,
timing: { totalMs: Date.now() - started }
});
const finish = () => {
const raw = Buffer.concat(chunks);
const encoding = String(res.headers['content-encoding'] || '').trim().toLowerCase();
// Decompress when we asked for it: the compressed size stays available as bodyBytes, and
// the caller gets a body it can actually read. A body we cannot decode is returned raw
// with decodedBytes null, which reads as "not measured" instead of a corrupted page.
let body = raw.toString('utf8');
let decodedBytes = encoding && encoding !== 'identity' ? null : raw.length;
if (encoding && encoding !== 'identity' && !truncated) {
try {
const unzlib = nodeZlib;
const out = encoding === 'br'
? unzlib.brotliDecompressSync(raw)
: (encoding === 'gzip' || encoding === 'x-gzip' ? unzlib.gunzipSync(raw) : unzlib.inflateSync(raw));
body = out.toString('utf8');
decodedBytes = out.length;
} catch { decodedBytes = null; }
} else if (encoding && encoding !== 'identity' && truncated) {
decodedBytes = null;
}
resolve({
status: res.statusCode || 0,
headers: res.headers,
body,
bodyBytes: raw.length,
decodedBytes,
contentEncoding: encoding || null,
url: parsed.toString(),
address: pinned.address,
family: pinned.family,
truncated,
tls,
timing: { totalMs: Date.now() - started }
});
};
res.on('end', finish);
res.on('close', finish);
res.on('error', finish);
+39 -13
View File
@@ -33,16 +33,27 @@ const CTA = `<div class="card">
export function hubPage() {
const body = `
<h1>Check your domain the way a customer meets it</h1>
<p class="lede">Five things decide whether a Malaysian business looks real online: the padlock that
expires without warning, the email settings that let anyone spoof your address, the link preview
your customer sees when you send them a WhatsApp, whether the address works both with and without
www, and who actually holds the domain, the mail and the hosting. This service reads all five from
the public internet, in a few seconds.</p>
<p class="lede">Seven things decide whether a Malaysian business looks real online: the padlock that
expires without warning, the email settings that let anyone spoof your address, the records that
stop mail being downgraded on the way, the link preview your customer sees when you send them a
WhatsApp, whether the address works both with and without www, who actually holds the domain, the
mail and the hosting, and whether the page is served with compression, cookie flags and a version
banner. This service reads all seven from the public internet, in a few seconds.</p>
${form({ action: '/', button: 'Run all five checks' })}
${form({ action: '/', button: 'Run all seven checks' })}
<p class="faint">Enter the domain you send email from and put on your name card. Nothing is installed,
nothing is uploaded, and no account is needed.</p>
<h2>What a customer&rsquo;s phone settles before it trusts your link</h2>
<div class="trust-flow">
<div class="node"><span class="step">01</span><h3>Registry</h3><p>The domain is registered, paid for and not on hold.</p></div>
<div class="node"><span class="step">02</span><h3>Redirects</h3><p>With and without www both land on the same live page.</p></div>
<div class="node"><span class="step">03</span><h3>HTTPS &amp; SSL</h3><p>The certificate is valid at the address a visitor actually reaches.</p></div>
<div class="node"><span class="step">04</span><h3>Mail &amp; preview</h3><p>Mail records hold, and the chat card shows your real image and title.</p></div>
</div>
<p class="faint">All four are public records and public responses. That is why this needs no login, installs
nothing, and can be re-run by anyone you send the report to.</p>
<div class="grid" style="margin-top:28px">
<div class="card">
<h3><a href="${esc(PREFIX)}/ssl/">Certificate &amp; HTTPS</a></h3>
@@ -64,6 +75,17 @@ nothing is uploaded, and no account is needed.</p>
<p class="muted">Both forms of your address are requested. If they end on different pages, a link
you share on WhatsApp opens the wrong one for half the people who tap it.</p>
</div>
<div class="card">
<h3>Mail transport: MTA-STS, TLS reports, BIMI</h3>
<p class="muted">SPF and DMARC say who may send as you. These three say the mail cannot be
downgraded in transit, that you hear about failures, and that your logo can appear in the inbox.</p>
</div>
<div class="card">
<h3>Compression, CAA, cookies, version banners</h3>
<p class="muted">Four small facts about how the page is served: whether it arrives compressed,
which authorities may issue a certificate, whether cookies are locked down, and whether the
server is advertising its own version.</p>
</div>
<div class="card">
<h3>Who holds the keys</h3>
<p class="muted">Registrar and expiry date from the registry, who runs your mail, where the site
@@ -74,7 +96,7 @@ nothing is uploaded, and no account is needed.</p>
<h2>What this is not</h2>
<p>It is not a security audit, not a penetration test, and not a guarantee about where your email
lands. It answers five narrow questions with evidence you can see, and it says
lands. It answers seven narrow questions with evidence you can see, and it says
<strong>skipped</strong> — not <strong>broken</strong> — when a site's firewall refuses to talk to a
machine. <a href="${esc(PREFIX)}/about/">Exactly what it queries is written down here.</a></p>
@@ -278,12 +300,14 @@ what happens when you press the button, and gives you a way to test the central
<li>The hostname is resolved once, and the address is checked again on every redirect hop, because
a redirect is the obvious way to smuggle a request somewhere it should not go.</li>
<li>Nothing is opened that the report does not need. One run spends at most: a handful of DNS
lookups; one TLS handshake; up to six page requests (the page itself, capped at 2 MB and ten
seconds, plus five HEAD hops following your redirects); one HEAD for the preview image your page
declares; three requests to compare your address with and without www; and two for the registry
record behind the expiry date. That is under twenty requests in the worst case, none of which
downloads a page body except the one page being checked. The certificate is read from the socket
the request already opened, so checking the padlock never creates a second visit.</li>
lookups (including the CAA, MTA-STS, TLS-report and BIMI records); one TLS handshake; up to six
page requests (the page itself, capped at 2 MB and ten seconds, plus five HEAD hops following your
redirects); one second page fetch to read compression, cookie flags and the server banner; one
policy file for MTA-STS; one HEAD for the preview image your page declares; three requests to
compare your address with and without www; and two for the registry record behind the expiry
date. That is under twenty-five requests in the worst case, none of which downloads a second page
body beyond the two named above. The certificate is read from the socket the request already
opened, so checking the padlock never creates a second visit.</li>
<li>The result is rendered and cached for an hour; results with a warning or a firewall block are
cached for five minutes, so a fix you just published shows up quickly.</li>
</ol>
@@ -411,8 +435,10 @@ ${preview ? `<section class="card">
${section({ id: 'who-holds', title: 'Who holds the keys', result: results.find((r) => r.id === 'who-holds') })}
${section({ id: 'tls', title: 'Certificate & HTTPS', result: tlsResult, extra: tlsNote })}
${section({ id: 'mail', title: 'Email: SPF, DKIM, DMARC', result: results.find((r) => r.id === 'mail-auth') })}
${section({ id: 'mail-transport', title: 'Mail transport: MTA-STS, TLS reports, BIMI', result: results.find((r) => r.id === 'mail-transport') })}
${section({ id: 'http', title: 'Redirects, headers & preview', result: results.find((r) => r.id === 'http') })}
${section({ id: 'host-shape', title: 'With and without www', result: results.find((r) => r.id === 'host-shape') })}
${section({ id: 'hardening', title: 'How the page is served: compression, CAA, cookies, banners', result: results.find((r) => r.id === 'hardening') })}
${bad || warn ? CTA : ''}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 213 KiB

+19
View File
@@ -166,6 +166,25 @@ pre {
padding: 14px; overflow-x: auto; font-size: 13px; line-height: 1.5;
}
/* The four things a phone settles before it shows your link as trustworthy. Drawn in CSS, not
shipped as a picture: an image here would be a second request, would not follow the palette,
would blur on a phone, and could never be corrected without re-exporting a file. */
.trust-flow { display: grid; grid-template-columns: repeat(4, 1fr); gap: 30px; margin: 26px 0 6px; }
.trust-flow .node { position: relative; padding: 14px; border: 1px solid rgba(63, 92, 224, 0.38); background: rgba(63, 92, 224, 0.07); border-radius: 10px; }
.trust-flow .step { font: 600 12px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; letter-spacing: 0.08em; color: var(--brand); }
.trust-flow h3 { font-size: 15px; margin: 8px 0 4px; }
.trust-flow p { margin: 0; font-size: 13px; line-height: 1.45; color: var(--ink-dim); }
.trust-flow .node:not(:last-child)::after {
content: "\2192"; position: absolute; right: -22px; top: 50%; transform: translateY(-50%);
color: var(--brand); font-size: 16px; line-height: 1;
}
@media (max-width: 760px) {
.trust-flow { grid-template-columns: 1fr; gap: 34px; }
.trust-flow .node:not(:last-child)::after {
content: "\2193"; right: auto; left: 50%; top: auto; bottom: -27px; transform: translateX(-50%);
}
}
.grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
.grid .card { margin: 0; }
.card h3 { margin-top: 0; }
+7 -2
View File
@@ -28,9 +28,11 @@ const COMMIT = process.env.APP_COMMIT || 'dev';
const loaders = {
'who-holds': () => import('./checks/who-holds.mjs'),
'mail-auth': () => import('./checks/mail-auth.mjs'),
'mail-transport': () => import('./checks/mail-transport.mjs'),
tls: () => import('./checks/tls.mjs'),
'http': () => import('./checks/http.mjs'),
'host-shape': () => import('./checks/host-shape.mjs')
'host-shape': () => import('./checks/host-shape.mjs'),
hardening: () => import('./checks/hardening.mjs')
};
const modules = {};
for (const [id, load] of Object.entries(loaders)) {
@@ -45,7 +47,10 @@ for (const [id, load] of Object.entries(loaders)) {
}
const STATIC = {
'/assets/style.css': { file: 'public/style.css', type: 'text/css; charset=utf-8' }
'/assets/style.css': { file: 'public/style.css', type: 'text/css; charset=utf-8' },
// The link-preview card. 1200x630, drawn in HTML and screenshotted, so it carries real type
// instead of the soft glyph soup a diffusion model produces at thumbnail size.
'/assets/og.png': { file: 'public/og.png', type: 'image/png' }
};
function send(res, status, headers, body) {
+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)/);
});