diff --git a/src/checks/mail-auth.mjs b/src/checks/mail-auth.mjs index add95c8..31ab567 100644 --- a/src/checks/mail-auth.mjs +++ b/src/checks/mail-auth.mjs @@ -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; diff --git a/src/lib/net-guard.mjs b/src/lib/net-guard.mjs index 26114c1..4c5b77c 100644 --- a/src/lib/net-guard.mjs +++ b/src/lib/net-guard.mjs @@ -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) { diff --git a/test/host-role.test.mjs b/test/host-role.test.mjs new file mode 100644 index 0000000..99fe202 --- /dev/null +++ b/test/host-role.test.mjs @@ -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); +}); diff --git a/test/http.test.mjs b/test/http.test.mjs new file mode 100644 index 0000000..7f083d9 --- /dev/null +++ b/test/http.test.mjs @@ -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 = ` + + + + + + + +Fallback title +

hello

`; + +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: 'Not found' }), { + 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: 'Attention Required! | CloudflareJust a moment...' + }); + 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 = 'Just a moment...
'; + 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 = 'No image here'; + 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 = 'T'; + 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 and never reads the body', () => { + const body = 'Head'; + 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 = ``; + const body = `${padding}`; + const preview = buildPreview(parseHead(body), 'https://example.com/'); + assert.equal(preview.hasImage, false); +}); + +test('og:image entities are decoded', () => { + const body = ''; + 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'); +});