fix: IPv4-first dialling, and a mail-less subdomain is not a broken domain

Two false results found by running the real checks, not by reading the code:
example.com reported its certificate as skipped because dns.lookup returned the
AAAA answer first and the local IPv6 route stalls; tools.hoelee.com reported
'Broken' email because a website-only subdomain publishes no MX, SPF or DMARC,
which is normal. resolvePublic now sorts IPv4 first, and applyHostRole points
such a host at its registrable apex (keeping .com.my intact).

96 tests green.
This commit is contained in:
hoelee committed 2026-11-10 13:00:52 +08:00
1 parent b2707f49f7
commit bc29f2a963
4 files changed
+480 -2

No files matched your search

+49 -1
View File
@@ -871,7 +871,55 @@ export async function check(input, { dns: resolver, lookup, now = Date.now(), ca
void cache; // caching is the router's job; this module always reports fromCache: false
const dnsClient = pickResolver(resolver || lookup);
const gathered = await gather(host, dnsClient);
return analyseMailAuth(gathered, { now });
return applyHostRole(analyseMailAuth(gathered, { now }), host, gathered);
}
// ---------------------------------------------------------------------------
// Host role: a subdomain with no mail setup is normal, not a broken domain
// ---------------------------------------------------------------------------
const SECOND_LEVEL = new Set(['com', 'net', 'org', 'edu', 'gov', 'mil', 'name', 'biz', 'sch', 'co', 'ac', 'or', 'ne', 'go', 'web']);
/** The registrable domain: tools.hoelee.com → hoelee.com, shop.example.com.my → example.com.my. */
export function registrableApex(host) {
const labels = String(host).split('.');
if (labels.length <= 2) return host;
const tld = labels[labels.length - 1];
const sld = labels[labels.length - 2];
if (tld.length === 2 && SECOND_LEVEL.has(sld)) return labels.slice(-3).join('.');
return labels.slice(-2).join('.');
}
/**
* tools.hoelee.com has no MX and no SPF because it only serves a website — the mail comes from
* hoelee.com. Reporting that as "anyone can spoof this domain" is a false accusation against a
* perfectly ordinary setup, so a subdomain with no mail surface at all reads as OK with a pointer
* to the domain that actually sends the mail.
*/
export function applyHostRole(result, host, gathered) {
const apex = registrableApex(host);
if (apex === host) return result;
if (gathered?.fatal) return result;
const publishesNothing =
gathered.spfRecords.length === 0 &&
!gathered.mx.nullMx &&
gathered.mx.records.length === 0 &&
!gathered.dmarc.record &&
!gathered.dkim.some((entry) => entry.key);
if (!publishesNothing) return result;
return {
...result,
state: 'ok',
summary: `This host does not send or receive email of its own. Email for ${apex} is what matters — check ${apex}.`,
findings: [
{
level: 'info',
code: 'subdomain_no_mail',
message: `${host} publishes no mail servers and no email records, which is normal for a subdomain that only hosts a website or an app.`,
fix: `Check ${apex} for SPF, DKIM and DMARC — that is the domain your mail is actually sent from.`
}
]
};
}
export const checkMailAuth = check;
+3 -1
View File
@@ -242,7 +242,9 @@ export async function resolvePublic(host, { lookup, timeoutMs = 4000 } = {}) {
throw new NetGuardError('private_address', 'That domain points at a private address.');
}
}
return addresses;
// Prefer IPv4. On a home connection with a broken or slow IPv6 route, dialling the AAAA answer
// first turns a 40 ms check into a timeout, and the visitor reads "skipped" when the site is fine.
return [...addresses].sort((a, b) => (a.family === 4 ? 0 : 1) - (b.family === 4 ? 0 : 1));
}
function normaliseAnswers(answers) {
+67
View File
@@ -0,0 +1,67 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { registrableApex, applyHostRole, analyseMailAuth } from '../src/checks/mail-auth.mjs';
import { resolvePublic } from '../src/lib/net-guard.mjs';
test('registrableApex keeps a Malaysian second-level suffix intact', () => {
assert.equal(registrableApex('example.com.my'), 'example.com.my');
assert.equal(registrableApex('www.example.com.my'), 'example.com.my');
assert.equal(registrableApex('tools.hoelee.com'), 'hoelee.com');
assert.equal(registrableApex('hoelee.com'), 'hoelee.com');
assert.equal(registrableApex('a.b.example.org.my'), 'example.org.my');
assert.equal(registrableApex('localhost'), 'localhost');
});
const NOTHING = {
domain: 'tools.example.com',
fatal: null,
spfRecords: [],
dmarc: { checked: true, code: null, record: null, parsed: null },
dkim: [{ selector: 'default', status: 'none', key: false }],
mx: { checked: true, code: null, records: [], nullMx: false, addresses: [] }
};
function envelopeOf(state, findings) {
return { id: 'mail-auth', state, summary: 'x', evidence: [], findings, checkedAt: new Date(0).toISOString(), fromCache: false };
}
test('a subdomain that publishes no mail reads as OK, pointing at the domain that does', () => {
const analysed = analyseMailAuth(NOTHING, { now: 0 });
assert.equal(analysed.state, 'fail', 'the raw analysis does accuse a bare subdomain');
const fixed = applyHostRole(analysed, 'tools.example.com', NOTHING);
assert.equal(fixed.state, 'ok');
assert.equal(fixed.findings.length, 1);
assert.equal(fixed.findings[0].code, 'subdomain_no_mail');
assert.match(fixed.summary, /example\.com/);
assert.match(fixed.summary, /does not send or receive email/);
});
test('a subdomain that does publish SPF keeps its real verdict', () => {
const gathered = { ...NOTHING, spfRecords: ['v=spf1 include:_spf.example.com -all'] };
const analysed = analyseMailAuth(gathered, { now: 0 });
const out = applyHostRole(analysed, 'mail.example.com', gathered);
assert.equal(out.state, analysed.state);
assert.equal(out.findings[0].code === 'subdomain_no_mail', false);
});
test('the apex itself is never downgraded', () => {
const analysed = analyseMailAuth(NOTHING, { now: 0 });
const out = applyHostRole(analysed, 'example.com', NOTHING);
assert.equal(out.state, 'fail');
});
test('a null MX subdomain is a deliberate setup, not "publishes nothing"', () => {
const gathered = { ...NOTHING, mx: { checked: true, code: null, records: [], nullMx: true, addresses: [] } };
const out = applyHostRole(analyseMailAuth(gathered, { now: 0 }), 'sub.example.com', gathered);
assert.equal(out.findings.some((f) => f.code === 'subdomain_no_mail'), false);
});
test('resolvePublic hands back IPv4 first so a broken IPv6 route cannot stall a check', async () => {
const lookup = async () => [
{ address: '2606:4700:4700::1111', family: 6 },
{ address: '93.184.216.34', family: 4 }
];
const out = await resolvePublic('example.com', { lookup });
assert.equal(out[0].family, 4);
assert.equal(out[1].family, 6);
});
+361
View File
@@ -0,0 +1,361 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
analyseHttp,
checkHttp,
auditHeaders,
parseHead,
buildPreview,
detectBlock,
worstLevel,
BLOCKED_MESSAGE
} from '../src/checks/http.mjs';
import { NetGuardError } from '../src/lib/net-guard.mjs';
// Fixtures are plain objects shaped exactly like net-guard's fetchFollowing() output.
// No server is started, no socket is opened, nothing is resolved.
const NOW = Date.UTC(2026, 0, 15, 12, 0, 0);
const SECURE_HEADERS = {
'strict-transport-security': 'max-age=31536000; includeSubDomains',
'content-security-policy': "default-src 'self'; frame-ancestors 'none'",
'x-content-type-options': 'nosniff',
'x-frame-options': 'DENY',
'referrer-policy': 'strict-origin-when-cross-origin',
'permissions-policy': 'camera=(), microphone=()',
'content-type': 'text/html; charset=utf-8'
};
const OG_BODY = `<!doctype html><html><head>
<meta property="og:title" content="Hoelee Check">
<meta property="og:description" content="Plain-English health checks for a domain.">
<meta property="og:image" content="https://www.hoelee.com/card.png">
<meta property="og:url" content="https://www.hoelee.com/check/">
<meta property="og:site_name" content="Hoelee">
<meta name="twitter:card" content="summary_large_image">
<link rel="icon" href="/favicon.ico">
<title>Fallback title</title>
</head><body><p>hello</p></body></html>`;
function hop(status, url, location = null) {
return { url, status, location, totalMs: 40 };
}
function page(hops, { headers = {}, body = '' } = {}) {
const last = hops[hops.length - 1];
return {
hops,
final: { status: last.status, headers, body, url: last.url, truncated: false, tls: { authorized: true }, timing: { totalMs: 90 } },
body,
headers,
truncated: false
};
}
function codes(analysis) {
return analysis.findings.map((finding) => finding.code);
}
function byCode(analysis, code) {
return analysis.findings.find((finding) => finding.code === code);
}
// --- clean page -----------------------------------------------------------------------------
test('a clean https page with every header and an og:image is ok', () => {
const analysis = analyseHttp(page([hop(200, 'https://www.hoelee.com/check/')], { headers: SECURE_HEADERS, body: OG_BODY }), {
host: 'www.hoelee.com',
now: NOW
});
assert.equal(analysis.state, 'ok');
assert.deepEqual(analysis.findings.filter((finding) => finding.level !== 'ok'), []);
assert.equal(analysis.redirects.count, 0);
assert.equal(analysis.preview.title, 'Hoelee Check');
assert.equal(analysis.preview.hasImage, true);
assert.equal(analysis.preview.imageIsAbsolute, true);
});
test('http → https is recorded as a win', () => {
const hops = [hop(301, 'http://example.com/', 'https://example.com/'), hop(200, 'https://example.com/')];
const analysis = analyseHttp(page(hops, { headers: SECURE_HEADERS, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'ok');
assert.ok(codes(analysis).includes('http_upgraded'));
assert.equal(byCode(analysis, 'http_upgraded').level, 'ok');
assert.equal(analysis.redirects.count, 1);
assert.equal(analysis.redirects.finalUrl, 'https://example.com/');
});
test('a page served only over http is a failure', () => {
const analysis = analyseHttp(page([hop(200, 'http://example.com/')], { headers: {}, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
assert.ok(codes(analysis).includes('http_no_https'));
});
// --- redirect chain -------------------------------------------------------------------------
test('six requests is more hops than the limit and fails', () => {
const hops = [
hop(301, 'https://example.com/a', 'https://example.com/b'),
hop(301, 'https://example.com/b', 'https://example.com/c'),
hop(301, 'https://example.com/c', 'https://example.com/d'),
hop(301, 'https://example.com/d', 'https://example.com/e'),
hop(301, 'https://example.com/e', 'https://example.com/f'),
hop(200, 'https://example.com/f')
];
const analysis = analyseHttp(page(hops, { headers: SECURE_HEADERS, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
assert.ok(codes(analysis).includes('http_too_many_hops'));
assert.equal(analysis.redirects.count, 5);
});
test('a redirect loop fails and names the address it loops on', () => {
const hops = [
hop(301, 'https://example.com/a', 'https://example.com/b'),
hop(301, 'https://example.com/b', 'https://example.com/a')
];
const analysis = analyseHttp(page(hops, { headers: SECURE_HEADERS, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
const loop = byCode(analysis, 'http_redirect_loop');
assert.ok(loop);
assert.match(loop.message, /loops back/i);
});
test('http → https → http ping-pong fails as a downgrade', () => {
const hops = [
hop(301, 'http://example.com/', 'https://example.com/'),
hop(301, 'https://example.com/', 'http://example.com/old'),
hop(200, 'http://example.com/old')
];
const analysis = analyseHttp(page(hops, { headers: {}, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
assert.ok(codes(analysis).includes('http_downgrade'));
assert.ok(!codes(analysis).includes('http_upgraded'));
});
test('a 404 on the final hop fails with the real status code', () => {
const analysis = analyseHttp(page([hop(404, 'https://example.com/missing')], { headers: SECURE_HEADERS, body: '<html><head><title>Not found</title></head></html>' }), {
host: 'example.com',
now: NOW
});
assert.equal(analysis.state, 'fail');
const finding = byCode(analysis, 'http_final_status');
assert.ok(finding);
assert.match(finding.message, /404/);
});
// --- firewall / CDN -------------------------------------------------------------------------
test('a Cloudflare 403 challenge is not-evaluated and produces no header findings', () => {
const result = page([hop(403, 'https://shop.example/')], {
headers: { server: 'cloudflare', 'cf-ray': '8a1b2c3d-KUL', 'content-type': 'text/html' },
body: '<!doctype html><html><head><title>Attention Required! | Cloudflare</title></head><body>Just a moment...</body></html>'
});
const analysis = analyseHttp(result, { host: 'shop.example', now: NOW });
assert.equal(analysis.state, 'not-evaluated');
assert.equal(analysis.summary, BLOCKED_MESSAGE);
assert.match(analysis.summary, /firewall or CDN blocked/);
assert.deepEqual(analysis.findings, []); // no HSTS/CSP/banner noise from a blocked probe
assert.equal(analysis.preview, null);
});
test('a 200 JavaScript challenge page is treated as blocked too', () => {
const body = '<html><head><title>Just a moment...</title></head><body><div id="challenge-platform"></div></body></html>';
const result = page([hop(200, 'https://shop.example/')], { headers: { server: 'cloudflare' }, body });
const analysis = analyseHttp(result, { host: 'shop.example', now: NOW });
assert.equal(analysis.state, 'not-evaluated');
assert.deepEqual(analysis.findings, []);
});
test('detectBlock identifies the edge provider', () => {
const block = detectBlock({ hops: [hop(403, 'https://x.example/')], final: { status: 403 }, headers: { server: 'cloudflare' }, body: '' });
assert.equal(block.blocked, true);
assert.equal(block.protection, 'cloudflare');
});
// --- headers --------------------------------------------------------------------------------
test('missing HSTS on an https page is a warning with the agreed wording', () => {
const headers = { ...SECURE_HEADERS };
delete headers['strict-transport-security'];
const analysis = analyseHttp(page([hop(200, 'https://example.com/')], { headers, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'warn');
const finding = byCode(analysis, 'hsts_missing');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /HTTPS works but browsers are not told to always use it/);
});
test('HSTS without max-age is a failure', () => {
const headers = { ...SECURE_HEADERS, 'strict-transport-security': 'includeSubDomains' };
const analysis = analyseHttp(page([hop(200, 'https://example.com/')], { headers, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
assert.equal(byCode(analysis, 'hsts_no_max_age').level, 'fail');
});
test('HSTS with a max-age under 180 days is a failure', () => {
const headers = { ...SECURE_HEADERS, 'strict-transport-security': 'max-age=86400' };
const analysis = analyseHttp(page([hop(200, 'https://example.com/')], { headers, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
const finding = byCode(analysis, 'hsts_max_age_short');
assert.equal(finding.level, 'fail');
assert.match(finding.message, /15552000/);
});
test('optional headers are info, never fail, and never called insecure', () => {
const findings = auditHeaders({}, { url: 'https://example.com/' });
const optional = findings.filter((finding) => finding.code !== 'hsts_missing');
assert.equal(optional.length, 5);
for (const finding of optional) {
assert.equal(finding.level, 'info', `${finding.code} must be info`);
assert.match(finding.message, /optional hardening not present/);
assert.doesNotMatch(finding.message, /insecure/i);
}
assert.deepEqual(
optional.map((finding) => finding.code).sort(),
['csp_missing', 'frame_ancestors_missing', 'permissions_policy_missing', 'referrer_policy_missing', 'x_content_type_options_missing']
);
});
test('a CSP frame-ancestors directive satisfies the clickjacking check', () => {
const findings = auditHeaders(
{ 'content-security-policy': "default-src 'self'; frame-ancestors 'none'" },
{ url: 'https://example.com/' }
);
assert.ok(!findings.some((finding) => finding.code === 'frame_ancestors_missing'));
});
test('version banners are info, not failures', () => {
const headers = { ...SECURE_HEADERS, 'x-powered-by': 'PHP/8.2.11', server: 'nginx/1.24.0' };
const analysis = analyseHttp(page([hop(200, 'https://example.com/')], { headers, body: OG_BODY }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'ok');
assert.equal(byCode(analysis, 'x_powered_by').level, 'info');
assert.equal(byCode(analysis, 'server_version_banner').level, 'info');
assert.match(byCode(analysis, 'server_version_banner').message, /nginx\/1\.24\.0/);
});
test('HSTS is not judged on a plain http page', () => {
const findings = auditHeaders({}, { url: 'http://example.com/' });
assert.ok(!findings.some((finding) => finding.code.startsWith('hsts_')));
});
// --- link preview ---------------------------------------------------------------------------
test('a missing og:image is a warning — the card would look blank', () => {
const body = '<html><head><title>No image here</title></head><body></body></html>';
const analysis = analyseHttp(page([hop(200, 'https://example.com/')], { headers: SECURE_HEADERS, body }), { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'warn');
const finding = byCode(analysis, 'og_image_missing');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /blank card/);
assert.equal(analysis.preview.hasImage, false);
assert.equal(analysis.preview.title, 'No image here');
});
test('a relative og:image is resolved against the final URL and flagged', () => {
const body = '<html><head><meta property="og:image" content="/img/card.png"><title>T</title></head></html>';
const analysis = analyseHttp(page([hop(200, 'https://example.com/blog/post')], { headers: SECURE_HEADERS, body }), {
host: 'example.com',
now: NOW
});
assert.equal(analysis.preview.image, 'https://example.com/img/card.png');
assert.equal(analysis.preview.hasImage, true);
assert.equal(analysis.preview.imageIsAbsolute, false);
assert.equal(byCode(analysis, 'og_image_relative').level, 'info');
});
test('the preview carries title, description, image, site name and favicon', () => {
const analysis = analyseHttp(page([hop(200, 'https://www.hoelee.com/check/')], { headers: SECURE_HEADERS, body: OG_BODY }), {
host: 'www.hoelee.com',
now: NOW
});
assert.deepEqual(
{
title: analysis.preview.title,
description: analysis.preview.description,
image: analysis.preview.image,
siteName: analysis.preview.siteName,
hasImage: analysis.preview.hasImage,
imageIsAbsolute: analysis.preview.imageIsAbsolute
},
{
title: 'Hoelee Check',
description: 'Plain-English health checks for a domain.',
image: 'https://www.hoelee.com/card.png',
siteName: 'Hoelee',
hasImage: true,
imageIsAbsolute: true
}
);
assert.equal(analysis.preview.favicon, 'https://www.hoelee.com/favicon.ico');
});
test('the head parser stops at </head> and never reads the body', () => {
const body = '<html><head><title>Head</title></head><body><meta property="og:image" content="https://example.com/body.png"></body></html>';
const parsed = parseHead(body);
assert.equal(parsed.title, 'Head');
assert.equal(parsed.metas['og:image'], undefined);
});
test('the head parser stops at 200 KB', () => {
const padding = `<meta name="pad" content="${'x'.repeat(300_000)}">`;
const body = `<html><head>${padding}<meta property="og:image" content="https://example.com/late.png"></head></html>`;
const preview = buildPreview(parseHead(body), 'https://example.com/');
assert.equal(preview.hasImage, false);
});
test('og:image entities are decoded', () => {
const body = '<html><head><meta property="og:image" content="https://example.com/a.png?x=1&amp;y=2"></head></html>';
const preview = buildPreview(parseHead(body), 'https://example.com/');
assert.equal(preview.image, 'https://example.com/a.png?x=1&y=2');
});
// --- envelope -------------------------------------------------------------------------------
test('checkHttp reports not-evaluated when the domain does not resolve', async () => {
const lookup = async () => {
throw new NetGuardError('dns_nxdomain', 'That domain did not resolve.');
};
const envelope = await checkHttp('nope.example', { lookup });
assert.equal(envelope.id, 'http');
assert.equal(envelope.state, 'not-evaluated');
assert.deepEqual(envelope.findings, []);
assert.equal(envelope.fromCache, false);
assert.match(envelope.summary, /did not resolve/i);
assert.ok(!Number.isNaN(Date.parse(envelope.checkedAt)));
});
test('a partial chain from an aborted redirect loop still fails, without inventing headers', () => {
// net-guard throws too_many_redirects with the hops it collected; checkHttp feeds them back in.
const hops = [
hop(301, 'https://example.com/1', 'https://example.com/2'),
hop(301, 'https://example.com/2', 'https://example.com/3'),
hop(301, 'https://example.com/3', 'https://example.com/4'),
hop(301, 'https://example.com/4', 'https://example.com/5'),
hop(301, 'https://example.com/5', 'https://example.com/6'),
hop(301, 'https://example.com/6', 'https://example.com/7')
];
const analysis = analyseHttp({ hops, final: null, headers: {}, body: '' }, { host: 'example.com', now: NOW });
assert.equal(analysis.state, 'fail');
assert.ok(codes(analysis).includes('http_too_many_hops'));
// No response body came back, so no header or preview findings may be invented.
assert.ok(!codes(analysis).some((code) => code.startsWith('hsts_')));
assert.ok(!codes(analysis).includes('og_image_missing'));
assert.equal(analysis.preview, null);
});
test('checkHttp reports not-evaluated when the redirect chain is abandoned', async () => {
const lookup = async () => {
throw new NetGuardError('too_many_redirects', 'More than 5 redirects.');
};
const envelope = await checkHttp('loop.example', { lookup });
assert.equal(envelope.id, 'http');
assert.equal(envelope.state, 'not-evaluated');
assert.deepEqual(envelope.findings, []);
assert.match(envelope.summary, /loop/i);
});
test('worstLevel never returns info as a state', () => {
assert.equal(worstLevel([{ level: 'info' }]), 'ok');
assert.equal(worstLevel([{ level: 'info' }, { level: 'warn' }]), 'warn');
assert.equal(worstLevel([{ level: 'fail' }, { level: 'warn' }]), 'fail');
});