From e407c0dabaf6e2b74082e019b51ebe06a41955fd Mon Sep 17 00:00:00 2001 From: hoelee Date: Tue, 10 Nov 2026 18:45:36 +0800 Subject: [PATCH] feat(check): who-holds and host-shape, wired and honest about what they cannot see Two new checks: the registry/mail/hosting card, and whether the address works with and without www. Wiring forced three corrections that are the point of this commit: - who-holds emitted a numeric checkedAt while the envelope contract is an ISO string; a second shape in the same results array breaks any staleness comparison. - Linode's pattern matched 'akamai', so maybank2u.com.my - a bank behind Akamai's edge - was reported as sitting on Linode. Two brands, one owner, different platforms. - A refused DNS query was printed as 'this domain does not resolve', which is a claim about the customer's domain rather than about our resolver. Transient codes now get one retry, and only NXDOMAIN is allowed to say a name does not exist. about page now lists the real request budget (page + five HEAD hops + image + three www-form requests + two registry), and the hub says five checks instead of three. --- AGENTS.md | 4 +- SPEC.md | 8 +- src/checks/host-shape.mjs | 563 +++++++++++++++++++++++++ src/checks/who-holds.mjs | 837 ++++++++++++++++++++++++++++++++++++++ src/pages.mjs | 47 ++- src/server.mjs | 4 +- test/host-shape.test.mjs | 343 ++++++++++++++++ test/who-holds.test.mjs | 685 +++++++++++++++++++++++++++++++ 8 files changed, 2469 insertions(+), 22 deletions(-) create mode 100644 src/checks/host-shape.mjs create mode 100644 src/checks/who-holds.mjs create mode 100644 test/host-shape.test.mjs create mode 100644 test/who-holds.test.mjs diff --git a/AGENTS.md b/AGENTS.md index 8e9125d..c0fd69a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 - three that get broken most often: + five 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: 'mail-auth' | 'tls' | 'http', + id: 'who-holds' | 'mail-auth' | 'tls' | 'http' | 'host-shape', state: 'ok' | 'warn' | 'fail' | 'not-evaluated', summary: string, // one plain-English line for a non-technical owner evidence: Array<{label, value, note?}>, diff --git a/SPEC.md b/SPEC.md index 0145227..98c8356 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,8 +1,8 @@ # SPEC — hoelee-check v1 -**What this is.** Three public health checks for a domain — certificate, email authentication, and +**What this is.** Five 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 about a second, the three things that make a small +Built so a Malaysian SME owner can see, in a few seconds, the five 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 three | index | +| `/check/` | hub, one input, runs all five | 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 three checks in ~1–2 s with `checkedAt`. +3. A real report for `hoelee.com` returns five checks in ~1–3 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. diff --git a/src/checks/host-shape.mjs b/src/checks/host-shape.mjs new file mode 100644 index 0000000..4be45be --- /dev/null +++ b/src/checks/host-shape.mjs @@ -0,0 +1,563 @@ +// host-shape -- does the site answer on both the bare domain and on www, and do the two forms +// end on the same page? +// +// This is the breakage we meet most often on Malaysian SME sites. The designer tested +// www.example.com, the link in the WhatsApp group says www.example.com, and nobody in the office +// ever types the bare domain -- so a customer who does is the first person to discover that it +// does not resolve, or that it lands on a half-finished page. The two forms drifting apart is +// also what quietly breaks a login: the session cookie is set on example.com and the form the +// customer is filling in is served from www.example.com, so the site forgets them on every click. +// +// The check is deliberately small: three requests at most, HEAD only, no page body. It reports +// what it saw and nothing else -- a form that refuses the probe is "not evaluated", never broken. + +import { requestOnce, guardHop, MAX_REDIRECTS } from '../lib/net-guard.mjs'; +import { registrableApex } from './mail-auth.mjs'; + +/** Two forms, plus one retry. Every request in this module is counted against this number. */ +export const REQUEST_BUDGET = 3; +/** A HEAD that has not answered in five seconds is not going to tell us anything useful. */ +export const PROBE_TIMEOUT_MS = 5000; +/** Only ever read when a server refuses HEAD and we have to ask for the first kilobyte. */ +const GET_FALLBACK_BYTES = 1024; +/** 405/501 mean "this server does not implement HEAD", not "this site is down". */ +const HEAD_REFUSED = new Set([405, 501]); + +// Domains where the "customer's site" is one subdomain of somebody else's platform. There is no +// www.myshop.github.io for the owner to create, so inventing that probe would report a missing +// address that was never supposed to exist -- a false accusation against a working site. +const SHARED_HOSTING = new Set([ + 'github.io', + 'githubusercontent.com', + 'gitlab.io', + 'bitbucket.io', + 'netlify.app', + 'netlify.com', + 'vercel.app', + 'now.sh', + 'pages.dev', + 'workers.dev', + 'web.app', + 'firebaseapp.com', + 'herokuapp.com', + 'azurewebsites.net', + 'cloudapp.azure.com', + 'onrender.com', + 'railway.app', + 'fly.dev', + 'deno.dev', + 'glitch.me', + 'surge.sh', + 'wordpress.com', + 'blogspot.com', + 'wixsite.com', + 'myshopify.com', + 'webflow.io', + 'notion.site', + 'substack.com', + 'medium.com', + 'tumblr.com', + 'readthedocs.io', + 'carrd.co', + 'godaddysites.com', + 'weebly.com', + 'jimdo.com', + 'strikingly.com' +]); + +// An error that means the name does not exist. That is a measured fact about the address, so it +// can be reported as a broken form. A refused connection is NOT in this set: a site that only +// runs on http refuses https on purpose, and calling that dead would be a false alarm -- it is +// decided after the plain-http probe below comes back empty. +const DEAD_CODES = new Set(['dns_nxdomain']); +// Everything that is not a dead name -- a timeout, an unverifiable certificate, a loop, a spent +// budget -- only means we could not look, so it stays neutral and is never a finding. +// When https does not complete at all, one plain-http HEAD is worth spending: a site that only +// answers on http is a real finding, and it is invisible from the https side. +const HTTP_FALLBACK_CODES = new Set(['refused', 'timeout', 'request_failed', 'tls_invalid', 'tls_expired']); + +// --------------------------------------------------------------------------- +// Planning: which two addresses does this visitor actually have? +// --------------------------------------------------------------------------- + +function normaliseHost(input) { + return String(input ?? '') + .trim() + .toLowerCase() + .replace(/^[a-z][a-z0-9+.-]*:\/\//, '') + .replace(/[/?#].*$/, '') + .replace(/:\d+$/, '') + .replace(/\.$/, ''); +} + +export function startUrlFor(form) { + return `https://${form}/`; +} + +/** + * The two forms worth comparing. + * + * - example.com -> example.com and www.example.com + * - www.example.com -> www.example.com and example.com + * - shop.example.com -> shop.example.com and example.com (the apex is what a customer would + * type if they dropped the "shop.") + * - myshop.github.io -> one form only: github.io is not the customer's domain, and + * www.myshop.github.io is not an address they can create. + */ +export function planForms(input) { + const typed = normaliseHost(input); + if (!typed) return { typed: '', forms: [], single: 'empty' }; + + const apex = registrableApex(typed); + if (typed !== apex && SHARED_HOSTING.has(apex)) { + return { typed, forms: [typed], single: 'platform' }; + } + if (typed === apex) return { typed, forms: [typed, `www.${typed}`], single: null }; + if (typed === `www.${apex}`) return { typed, forms: [typed, apex], single: null }; + return { typed, forms: [typed, apex], single: null }; +} + +/** + * Compare addresses the way a browser does: case, default port and a missing trailing slash on + * the root are not two different pages. A different path, query or scheme is. + */ +export function normaliseAddress(raw) { + try { + const url = new URL(String(raw)); + const port = url.port && url.port !== (url.protocol === 'https:' ? '443' : '80') ? `:${url.port}` : ''; + return `${url.protocol}//${url.hostname.toLowerCase()}${port}${url.pathname || '/'}${url.search}`; + } catch { + return String(raw); + } +} + +// --------------------------------------------------------------------------- +// Probing: at most three HEADs, shared across both forms +// --------------------------------------------------------------------------- + +function looksLikeCdn(headers = {}) { + const server = String(headers.server || '').toLowerCase(); + if (/(cloudflare|akamai|sucuri|incapsula|imperva|fastly|cloudfront|varnish|ddos-guard|stackpath)/.test(server)) return true; + return ['cf-ray', 'cf-mitigated', 'x-sucuri-id', 'x-akamai-request-id', 'x-azure-ref', 'x-fastly-request-id', 'x-iinfo', 'x-cdn'].some( + (name) => headers[name] + ); +} + +/** + * A status code is only a broken form when it is a 5xx that is not a bot wall. A 403 from a CDN + * challenge page is not the customer's website, and calling it "broken" would be a false alarm + * about a site that is fine for every real browser. + */ +function classifyStatus(status, headers) { + if (status >= 200 && status < 300) return { outcome: 'answered', reason: null }; + if (status === 403 || status === 429) return { outcome: 'blocked', reason: 'status' }; + if (status === 503 && looksLikeCdn(headers)) return { outcome: 'blocked', reason: 'status' }; + if (status >= 500) return { outcome: 'dead', reason: `status_${status}` }; + // Any other 4xx (404, 410, 451) is an answer: the address exists and the server replied. The + // page itself is the HTTP check's business, not this one's. + return { outcome: 'answered', reason: null }; +} + +function errorCode(err) { + return (err && err.code) || 'request_failed'; +} + +async function fetchHop(url, { lookup, request, budget, reserve }) { + if (budget.left <= 0) return { error: { code: 'budget' }, requests: 0 }; + budget.left -= 1; + let res; + try { + res = await request(url, { lookup, method: 'HEAD', timeoutMs: PROBE_TIMEOUT_MS }); + } catch (err) { + return { error: { code: errorCode(err) }, requests: 1 }; + } + + let requests = 1; + if (HEAD_REFUSED.has(res.status) && budget.left > reserve) { + budget.left -= 1; + requests += 1; + try { + res = await request(url, { lookup, method: 'GET', timeoutMs: PROBE_TIMEOUT_MS, maxBytes: GET_FALLBACK_BYTES }); + } catch (err) { + return { error: { code: errorCode(err) }, requests }; + } + } + + const headers = res.headers || {}; + return { + status: res.status || 0, + headers, + location: headers.location || null, + url: res.url || url, + requests + }; +} + +/** + * A form that answers on http but not on https. One HEAD, no redirect following: either the + * address serves a page (a finding) or it sends the visitor to https (which means the https + * failure is a certificate or connection question, and not this check's to judge). + */ +async function probeHttpFallback(form, { lookup, request, budget }) { + if (budget.left <= 0) return null; + const url = `http://${form}/`; + budget.left -= 1; + + let res; + try { + res = await request(url, { lookup, method: 'HEAD', timeoutMs: PROBE_TIMEOUT_MS }); + } catch { + return null; + } + + const headers = res.headers || {}; + const location = headers.location || null; + if (res.status >= 300 && res.status < 400 && location) { + let next; + try { + next = new URL(location, url).toString(); + } catch { + return null; + } + if (new URL(next).protocol === 'https:') return null; + if (guardHop(next)) return null; + return { outcome: 'answered', reason: null, finalUrl: next, status: res.status, httpOnly: true }; + } + if (res.status >= 200 && res.status < 400) { + return { outcome: 'answered', reason: null, finalUrl: url, status: res.status, httpOnly: true }; + } + if (res.status === 403 || res.status === 429) { + return { outcome: 'blocked', reason: 'status', finalUrl: null, status: res.status, httpOnly: false }; + } + return null; +} + +/** + * Follow one form to the page a browser would land on, spending at most what the shared budget + * allows. `stopAt` holds the other form's address: when the chain arrives there, the other + * probe answers it and a second request would only re-measure the same page. + */ +async function probeForm(form, { lookup, request, budget, stopAt, reserve }) { + const startUrl = startUrlFor(form); + const probe = { + form, + startUrl, + finalUrl: null, + status: 0, + outcome: 'unjudged', + reason: null, + httpOnly: false, + requests: 0 + }; + + let current = startUrl; + const seen = new Set(); + + for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) { + const key = normaliseAddress(current); + if (seen.has(key)) { + probe.reason = 'loop'; + probe.finalUrl = current; + return probe; + } + seen.add(key); + + // Keep one request back for the other form: a long redirect chain on the first form must not + // leave the second address unmeasured. + if (budget.left <= reserve) { + probe.reason = 'budget'; + probe.finalUrl = current; + return probe; + } + + const result = await fetchHop(current, { lookup, request, budget, reserve }); + probe.requests += result.requests; + + if (result.error) { + probe.reason = result.error.code; + probe.outcome = DEAD_CODES.has(probe.reason) ? 'dead' : 'unjudged'; + probe.finalUrl = current; + break; + } + + probe.status = result.status; + + if (result.status >= 300 && result.status < 400 && result.location) { + let next; + try { + next = new URL(result.location, result.url).toString(); + } catch { + probe.reason = 'unread'; + probe.finalUrl = result.url; + return probe; + } + // Every hop restarts at the guard: a public site must not be able to make this service + // dial the LAN through a redirect. + const blocked = guardHop(next); + if (blocked) { + probe.reason = blocked.code; + probe.outcome = 'unjudged'; + probe.finalUrl = next; + return probe; + } + if (stopAt.has(normaliseAddress(next))) { + probe.outcome = 'answered'; + probe.finalUrl = next; + return probe; + } + current = next; + continue; + } + + const verdict = classifyStatus(result.status, result.headers); + probe.outcome = verdict.outcome; + probe.reason = verdict.reason; + probe.finalUrl = result.url; + break; + } + + // The chain ran past the redirect cap without an answer: the visitor would keep being sent on, + // so say so rather than presenting the last hop as a final page. + if (probe.outcome === 'unjudged' && !probe.reason) probe.reason = 'too_many_redirects'; + if (!probe.finalUrl) probe.finalUrl = current; + + if (probe.outcome === 'unjudged' && HTTP_FALLBACK_CODES.has(probe.reason) && budget.left > 0) { + const http = await probeHttpFallback(form, { lookup, request, budget }); + if (http) { + Object.assign(probe, http); + } else if (probe.reason === 'refused') { + // Nothing answers on http either, so the refusal is not "https is switched off" -- this + // address genuinely has no server behind it. + probe.outcome = 'dead'; + } + } + + return probe; +} + +// --------------------------------------------------------------------------- +// Analysis: pure, so the tests can hand it probes and read the verdict +// --------------------------------------------------------------------------- + +function reasonPhrase(probe) { + switch (probe.reason) { + case 'dns_nxdomain': return 'the name does not exist in DNS'; + case 'refused': return 'the server refuses the connection'; + case 'timeout': return 'it did not answer in time'; + case 'tls_invalid': return 'its certificate could not be verified'; + case 'tls_expired': return 'its certificate has expired'; + case 'private_host': return 'it points at a private network address'; + case 'ip_literal': return 'it points at a bare IP address'; + case 'bad_port': return 'it uses a port this tool will not open'; + case 'budget': return 'the check ran out of its three requests before reaching it'; + case 'loop': return 'it redirects in a loop'; + case 'unread': return 'it would not say where it redirects'; + default: + if (probe.status >= 500) return `the server returns a ${probe.status} error`; + return 'the request failed'; + } +} + +function describeProbe(probe) { + switch (probe.outcome) { + case 'answered': { + const redirected = normaliseAddress(probe.finalUrl) !== normaliseAddress(probe.startUrl); + return redirected ? `${probe.finalUrl} (${probe.status}, after a redirect)` : `${probe.finalUrl} (${probe.status})`; + } + case 'dead': + return `no answer -- ${reasonPhrase(probe)}`; + case 'blocked': + return `refused our automated request (${probe.status})`; + default: + return `not judged -- ${reasonPhrase(probe)}`; + } +} + +function endedOnHttp(probe) { + return /^http:\/\//i.test(probe.finalUrl || ''); +} + +function describeRefusal(probe) { + if (probe.outcome === 'blocked') { + return `The site refused our automated request at ${probe.form} (${probe.status}), so nothing was judged about its two addresses.`; + } + switch (probe.reason) { + case 'private_host': + case 'ip_literal': + return `${probe.form} points at a private network address, so we did not contact it and nothing was judged about it.`; + case 'timeout': + return `${probe.form} did not answer in time, so nothing was judged about its two addresses.`; + case 'tls_invalid': + case 'tls_expired': + return `${probe.form} would not complete a secure connection, so nothing was judged about its two addresses.`; + case 'budget': + return `The first address used the whole request budget before ${probe.form} could be reached, so nothing was judged about it.`; + default: + return `${probe.form} could not be reached, so nothing was judged about its two addresses.`; + } +} + +function otherForm(plan, probe) { + const other = plan.forms.find((form) => form !== probe.form); + return other || plan.typed; +} + +/** + * @param {{typed: string, forms: string[], single: string|null}} plan + * @param {Array} probes one per planned form, in plan order + */ +export function analyseHostShape(plan, probes, { now = Date.now() } = {}) { + const checkedAt = new Date(now).toISOString(); + const findings = []; + + const answered = probes.filter((probe) => probe.outcome === 'answered'); + const dead = probes.filter((probe) => probe.outcome === 'dead'); + const refused = probes.filter((probe) => probe.outcome === 'blocked' || probe.outcome === 'unjudged'); + + // A redirect that points at a form which does not answer must not read as "lands here": the + // visitor following it gets an error page, not that address. + const evidence = probes.map((probe) => { + const landsOnDead = + probe.outcome === 'answered' && + dead.some((entry) => normaliseAddress(entry.startUrl) === normaliseAddress(probe.finalUrl)); + return { + label: probe.startUrl, + value: landsOnDead ? `${probe.finalUrl} (redirects to an address that does not answer)` : describeProbe(probe) + }; + }); + + // --- a form that is measurably dead -------------------------------------------------------- + for (const probe of dead) { + findings.push({ + level: 'fail', + code: 'host_form_dead', + message: `${probe.form} does not answer at all -- ${reasonPhrase(probe)}, so a customer who types it sees an error page.`, + fix: `Point ${probe.form} at the same server as ${otherForm(plan, probe)}, or redirect it there with a permanent (301) redirect.` + }); + } + + // --- encryption ---------------------------------------------------------------------------- + for (const probe of answered) { + if (!probe.httpOnly && !endedOnHttp(probe)) continue; + findings.push({ + level: 'warn', + code: 'host_form_http', + message: probe.httpOnly + ? `${probe.form} answers on http://${probe.form}/ but not on https, so the page a customer gets is not encrypted.` + : `${probe.form} sends the visitor to ${probe.finalUrl}, which is a plain http address, so the page is not encrypted.`, + fix: 'Serve the site on https and send every http request to the https address with a permanent (301) redirect.' + }); + } + + // --- do the two forms end on the same page? ------------------------------------------------ + const comparable = answered.filter((probe) => probe.finalUrl); + if (comparable.length === 2) { + const [first, second] = comparable; + if (normaliseAddress(first.finalUrl) === normaliseAddress(second.finalUrl)) { + findings.push({ + level: 'ok', + code: 'host_forms_converge', + message: `${first.form} and ${second.form} both end on ${first.finalUrl}.` + }); + } else { + findings.push({ + level: 'warn', + code: 'host_forms_split', + message: `${first.form} ends on ${first.finalUrl} but ${second.form} ends on ${second.finalUrl}, so the same site has two addresses.`, + fix: 'Redirect one form to the other with a permanent (301) redirect so both land on the same page.' + }); + } + } + + // --- nothing to compare -------------------------------------------------------------------- + for (const probe of refused) { + findings.push({ + level: 'info', + code: probe.outcome === 'blocked' ? 'host_forms_blocked' : 'host_form_unjudged', + message: + probe.outcome === 'blocked' + ? `${probe.form} answered with a ${probe.status} to our automated request, so nothing was judged about it.` + : `${probe.form} could not be judged -- ${reasonPhrase(probe)}.` + }); + } + + if (plan.single && probes.length === 1 && answered.length === 1) { + findings.push({ + level: 'info', + code: 'host_form_single', + message: `${plan.typed} is a hosted subdomain, so there is no separate www address of your own to compare it with.` + }); + } + + // --- state and the one sentence an owner reads --------------------------------------------- + const has = (code) => findings.some((finding) => finding.code === code); + let state = 'ok'; + if (findings.some((finding) => finding.level === 'fail')) state = 'fail'; + else if (findings.some((finding) => finding.level === 'warn')) state = 'warn'; + else if (probes.length === 0 || answered.length === 0) state = 'not-evaluated'; + else if (!plan.single && answered.length < 2) state = 'not-evaluated'; + + let summary; + if (state === 'fail') { + summary = dead.length === probes.length && dead.length > 1 + ? `Neither ${dead[0].form} nor ${dead[1].form} answers, so a customer cannot reach the site by either address.` + : `${dead[0].form} does not answer at all, so a customer who types it sees an error page.`; + } else if (has('host_forms_split')) { + const [first, second] = comparable; + summary = `${first.form} ends on ${first.finalUrl} but ${second.form} ends on ${second.finalUrl}, so the same site has two addresses and a shared link can land on the wrong one.`; + } else if (has('host_form_http')) { + const probe = answered.find((entry) => entry.httpOnly || endedOnHttp(entry)); + summary = probe.httpOnly + ? `${probe.form} only answers on http, so a customer who types it gets an unencrypted page.` + : `${probe.form} sends visitors back to a plain http address, so the page they land on is not encrypted.`; + } else if (state === 'not-evaluated') { + summary = describeRefusal(refused[0] || probes[0] || { form: plan.typed, outcome: 'unjudged' }); + } else if (has('host_forms_converge')) { + const [first, second] = comparable; + summary = `Typing ${first.form} or ${second.form} both land on the same page, so a shared link works however a customer types it.`; + } else if (plan.single) { + summary = `${plan.typed} is a hosted subdomain with no separate www address, so there was nothing to compare.`; + } else { + summary = `Both ${plan.forms.join(' and ')} answer.`; + } + + return { state, summary, evidence, findings, checkedAt, fromCache: false }; +} + +// --------------------------------------------------------------------------- +// check +// --------------------------------------------------------------------------- + +/** + * Check that a domain works both with and without "www", and that both forms end on one page. + * + * `request` is the transport seam for the offline tests; production never passes it, so every + * request still goes through net-guard (pinned DNS, guarded redirects, capped body). + */ +export async function checkHostShape(host, { lookup, request = requestOnce } = {}) { + const plan = planForms(host); + + if (plan.forms.length === 0) { + return { + id: 'host-shape', + state: 'not-evaluated', + summary: 'That does not look like a domain name, so there were no two addresses to compare.', + evidence: [], + findings: [], + checkedAt: new Date().toISOString(), + fromCache: false + }; + } + + const budget = { left: REQUEST_BUDGET }; + const probes = []; + + for (const [index, form] of plan.forms.entries()) { + const stopAt = new Set(plan.forms.filter((other) => other !== form).map(startUrlFor)); + // Only hold a request back while a form is still unmeasured; the last one may spend the rest. + const reserve = index < plan.forms.length - 1 ? 1 : 0; + probes.push(await probeForm(form, { lookup, request, budget, stopAt, reserve })); + } + + return { id: 'host-shape', ...analyseHostShape(plan, probes) }; +} diff --git a/src/checks/who-holds.mjs b/src/checks/who-holds.mjs new file mode 100644 index 0000000..5df67ca --- /dev/null +++ b/src/checks/who-holds.mjs @@ -0,0 +1,837 @@ +// who-holds - the four facts a business owner usually does not know about their own domain: +// who the registry says holds it and when it lapses, who answers the mail, where the website +// actually sits, and how much of it rests on one nameserver. +// +// Budget: two external requests at most (RDAP, plus one HEAD for the hosting headers) and a +// handful of DNS queries. Every fact that could not be read is reported as "not checked" WITH +// the reason it could not be read. Nothing here is inferred from a table lookup unless the +// evidence names it, and every hostname-pattern judgement is labelled as a likely one: a guess +// printed as a fact is the one thing this service cannot afford, because the whole card is +// designed to be screenshotted and forwarded to somebody's boss. + +import dns from 'node:dns'; + +import { requestOnce, guardHop } from '../lib/net-guard.mjs'; +import { registrableApex } from './mail-auth.mjs'; + +export const RDAP_TIMEOUT_MS = 5_000; +export const HEAD_TIMEOUT_MS = 5_000; +export const RDAP_MAX_BYTES = 256 * 1024; +// rdap.org redirects to the registry that actually holds the record. One redirect is normal +// (rdap.org -> rdap.verisign.com); two is the cap, because a chain longer than that is not a +// registry we want to chase with a visitor's budget. +export const MAX_RDAP_HOPS = 2; +// Initial RDAP request + up to two redirects + one HEAD. The happy path spends two. +export const REQUEST_BUDGET = 1 + MAX_RDAP_HOPS + 1; +export const EXPIRING_SOON_DAYS = 30; +export const MAX_PTR = 2; + +const DAY_MS = 86_400_000; + +// A name that exists with no record of this type: "empty", not "broken". +const EMPTY_CODES = new Set(['ENODATA', 'ENOTFOUND', 'NXDOMAIN', 'ENONAME', 'NOTFOUND']); + +const LEVELS = { ok: 0, info: 1, warn: 2, fail: 3 }; + +// --------------------------------------------------------------------------- +// mail provider attribution (hostname patterns only - never a claim of certainty) +// --------------------------------------------------------------------------- + +const MAIL_PROVIDERS = [ + { name: 'Google Workspace', test: (h) => /(^|\.)(aspmx\.l\.google\.com|googlemail\.com|google\.com)$/.test(h) }, + { name: 'Microsoft 365', test: (h) => /(^|\.)(mail\.protection\.outlook\.com|outlook\.com)$/.test(h) }, + { name: 'Zoho Mail', test: (h) => /(^|\.)zoho\.(com|eu|in|jp|com\.au)$/.test(h) }, + { name: 'Cloudflare Email Routing', test: (h) => /(^|\.)mx\.cloudflare\.net$/.test(h) }, + { name: 'Amazon WorkMail', test: (h) => /(^|\.)awsapps\.com$/.test(h) }, + { name: 'Amazon SES', test: (h) => /(^|\.)(amazonaws\.com|amazonses\.com)$/.test(h) }, + { name: 'Titan', test: (h) => /(^|\.)titan\.email$/.test(h) }, + { name: 'GoDaddy', test: (h) => /(^|\.)secureserver\.net$/.test(h) }, + { name: 'ImprovMX', test: (h) => /(^|\.)improvmx\.com$/.test(h) }, + { name: 'ForwardEmail', test: (h) => /(^|\.)forwardemail\.net$/.test(h) }, + { name: 'Mailgun', test: (h) => /(^|\.)mailgun\.org$/.test(h) }, + { name: 'Proofpoint', test: (h) => /(^|\.)pphosted\.com$/.test(h) }, + { name: 'Mimecast', test: (h) => /(^|\.)mimecast\.com$/.test(h) }, + { name: 'Barracuda', test: (h) => /(^|\.)barracudanetworks\.com$/.test(h) }, + // Malaysian hosters, recognised by name only. If one of these is wrong the reader sees a + // hostname in the evidence row next to it and can judge for themselves. + { name: 'Exabytes (Malaysian host)', test: (h) => h.includes('exabytes') }, + { name: 'Shinjiru (Malaysian host)', test: (h) => h.includes('shinjiru') }, + { name: 'IPServerOne (Malaysian host)', test: (h) => h.includes('ipserverone') }, + { name: 'ServerFreak (Malaysian host)', test: (h) => h.includes('serverfreak') }, + // A suffix is not a provider. '.com.my' says the mail server is in Malaysia, nothing more, and + // naming a hosting company off a suffix would be a guess printed as a fact. + { name: 'a Malaysian mail server (.com.my or .my)', test: (h) => h.endsWith('.com.my') || h.endsWith('.my') } +]; + +/** Provider name for one MX hostname, or null when we do not recognise it. */ +export function attributeMailProvider(hostname) { + const host = String(hostname ?? '').trim().toLowerCase().replace(/\.$/, ''); + if (host.length === 0) return null; + for (const provider of MAIL_PROVIDERS) { + if (provider.test(host)) return provider.name; + } + return null; +} + +// --------------------------------------------------------------------------- +// hosting attribution (headers first, then a reverse name - never an invented ASN) +// --------------------------------------------------------------------------- + +const PTR_PROVIDERS = [ + { name: 'Amazon AWS', test: (p) => p.includes('amazonaws.com') }, + { name: 'Google Cloud', test: (p) => p.includes('googleusercontent.com') || /(^|\.)google\.com$/.test(p) }, + { name: 'Cloudflare', test: (p) => p.includes('cloudflare') }, + { name: 'Microsoft Azure', test: (p) => p.includes('cloudapp.azure.com') || p.includes('azure') }, + { name: 'DigitalOcean', test: (p) => p.includes('digitalocean.com') }, + // Akamai and Linode are the same company since 2022, but they are not the same platform: a + // bank behind Akamai's CDN reverse-resolves to *.akamaitechnologies.com and is NOT on Linode. + // Telling a business owner their site sits on Linode when it is served by Akamai's edge is a + // false fact, so the two patterns stay separate and Akamai never falls through to Linode. + { name: 'Akamai', test: (p) => p.includes('akamai') }, + { name: 'Linode', test: (p) => p.includes('linode.com') || p.includes('linodeusercontent') }, + { name: 'OVH', test: (p) => p.includes('ovh.net') || p.includes('ovh.com') || p.includes('ovhcloud') }, + { name: 'Hetzner', test: (p) => p.includes('hetzner') || p.includes('your-server.de') }, + { name: 'Contabo', test: (p) => p.includes('contabo') }, + { name: 'Vultr', test: (p) => p.includes('vultr') }, + { name: 'Hostinger', test: (p) => p.includes('hostinger') }, + { name: 'Exabytes (Malaysian host)', test: (p) => p.includes('exabytes') }, + { name: 'Shinjiru (Malaysian host)', test: (p) => p.includes('shinjiru') }, + { name: 'IPServerOne (Malaysian host)', test: (p) => p.includes('ipserverone') }, + { name: 'ServerFreak (Malaysian host)', test: (p) => p.includes('serverfreak') } +]; + +function header(headers, name) { + if (!headers || typeof headers !== 'object') return null; + const wanted = name.toLowerCase(); + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() !== wanted) continue; + if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : null; + return value === undefined || value === null ? null : String(value); + } + return null; +} + +/** + * Attribute hosting from evidence that names a platform. A bare `server: nginx` names software, + * not a host, so it is deliberately not attributed - "we cannot tell from outside" is the + * truthful answer and it is what the card says. + */ +export function attributeHosting({ headers, ptr = [] } = {}) { + // x-powered-by names a framework (Express, PHP), which says nothing about who hosts the site, + // so it is read for the evidence row and never used to attribute a host. + const server = (header(headers, 'server') || '').toLowerCase(); + + if (header(headers, 'x-vercel-id') || header(headers, 'x-vercel-cache') || server.includes('vercel')) { + return { name: 'Vercel', basis: 'the x-vercel headers in the response' }; + } + if (server.includes('cloudflare') || header(headers, 'cf-ray')) { + return { name: 'Cloudflare', basis: 'the server header in the response' }; + } + if (header(headers, 'x-amz-cf-id')) { + return { name: 'Amazon CloudFront', basis: 'the x-amz-cf-id header in the response' }; + } + if (server.includes('amazons3')) { + return { name: 'Amazon S3', basis: 'the server header in the response' }; + } + if (header(headers, 'x-github-request-id')) { + return { name: 'GitHub Pages', basis: 'the x-github-request-id header in the response' }; + } + if (header(headers, 'x-azure-ref')) { + return { name: 'Microsoft Azure', basis: 'the x-azure-ref header in the response' }; + } + if (header(headers, 'x-served-by') && String(header(headers, 'x-served-by')).toLowerCase().includes('cache')) { + return { name: 'Fastly', basis: 'the x-served-by header in the response' }; + } + if (server === 'gws' || server === 'gse') { + return { name: 'Google Cloud', basis: 'the server header in the response' }; + } + + for (const name of ptr) { + const lowered = String(name ?? '').toLowerCase(); + if (lowered.length === 0) continue; + for (const provider of PTR_PROVIDERS) { + if (provider.test(lowered)) return { name: provider.name, basis: `the address reverse-resolves to ${lowered}`, likely: true }; + } + } + return null; +} + +// --------------------------------------------------------------------------- +// RDAP +// --------------------------------------------------------------------------- + +function parseRdapDate(value) { + if (typeof value !== 'string' || value.trim().length === 0) return null; + const ms = Date.parse(value); + return Number.isFinite(ms) ? ms : null; +} + +/** RFC 9083 vcardArray -> the formatted name, if the registrar published one. */ +function vcardName(vcardArray) { + if (!Array.isArray(vcardArray) || !Array.isArray(vcardArray[1])) return null; + for (const entry of vcardArray[1]) { + if (!Array.isArray(entry) || entry.length < 4) continue; + if (String(entry[0]).toLowerCase() !== 'fn') continue; + const value = typeof entry[3] === 'string' ? entry[3].trim() : ''; + if (value.length > 0) return value; + } + return null; +} + +/** + * Read only the fields this card needs, and treat every one of them as optional: a registry + * that publishes no `events`, a registrar entity with no vcard, a status that is a string + * instead of an array - all of them must degrade to null, never throw. + */ +export function parseRdap(data) { + const out = { registrar: null, registered: null, expires: null, statuses: [] }; + if (!data || typeof data !== 'object') return out; + + if (Array.isArray(data.events)) { + for (const event of data.events) { + if (!event || typeof event !== 'object') continue; + const action = String(event.eventAction ?? '').trim().toLowerCase(); + const at = parseRdapDate(event.eventDate); + if (at === null) continue; + if (action === 'registration') out.registered = at; + else if (action === 'expiration') out.expires = at; + } + } + + if (Array.isArray(data.entities)) { + for (const entity of data.entities) { + if (!entity || typeof entity !== 'object') continue; + const roles = Array.isArray(entity.roles) ? entity.roles.map((role) => String(role).toLowerCase()) : []; + if (!roles.includes('registrar')) continue; + const name = vcardName(entity.vcardArray); + if (name) { + out.registrar = name; + break; + } + } + } + + if (Array.isArray(data.status)) { + out.statuses = data.status.map((status) => String(status).trim()).filter((status) => status.length > 0); + } else if (typeof data.status === 'string' && data.status.trim().length > 0) { + out.statuses = [data.status.trim()]; + } + return out; +} + +// A hold means the name is suspended at the registry: mail and web can stop resolving even +// though the registration is paid for. A transfer lock is the opposite kind of fact - it is +// what stops somebody stealing the name - so it is reported, but it is not a warning. Warning +// on the default state of every .com would teach the reader to ignore warnings. +const HOLD_PATTERNS = ['clienthold', 'serverhold', 'pendingdelete', 'redemptionperiod', 'pending delete', 'redemption period', 'suspended', 'inactive']; +const LOCK_PATTERNS = ['clienttransferprohibited', 'servertransferprohibited', 'client transfer prohibited', 'server transfer prohibited', 'clientupdateprohibited', 'clientdeleteprohibited']; + +export function classifyStatuses(statuses) { + const holds = []; + const locks = []; + for (const raw of Array.isArray(statuses) ? statuses : []) { + const status = String(raw ?? '').trim(); + if (status.length === 0) continue; + const flat = status.toLowerCase().replace(/[\s_-]+/g, ''); + if (HOLD_PATTERNS.some((pattern) => flat.includes(pattern.replace(/[\s_-]+/g, '')))) holds.push(status); + else if (LOCK_PATTERNS.some((pattern) => flat.includes(pattern.replace(/[\s_-]+/g, '')))) locks.push(status); + } + return { holds, locks }; +} + +/** Days left / days overdue, from a real registry date and the injected clock. */ +export function expiryFacts(expiresMs, now) { + if (!Number.isFinite(expiresMs)) return { known: false }; + const remaining = expiresMs - now; + const expired = remaining <= 0; + return { + known: true, + expiresMs, + expired, + // A domain that lapsed two hours ago is "expired today", not "expired 1 day ago". + days: expired ? 0 : Math.floor(remaining / DAY_MS), + daysAgo: expired ? Math.floor(-remaining / DAY_MS) : 0, + today: !expired && remaining < DAY_MS, + soon: !expired && remaining <= EXPIRING_SOON_DAYS * DAY_MS + }; +} + +function isoDate(ms) { + return new Date(ms).toISOString().slice(0, 10); +} + +// --------------------------------------------------------------------------- +// DNS +// --------------------------------------------------------------------------- + +function pickResolver({ lookup, dns: explicit }) { + const source = explicit + || (lookup && typeof lookup !== 'function' ? lookup : null) + || dns.promises; + const method = (name) => (typeof source[name] === 'function' ? source[name].bind(source) : null); + return { + resolve4: method('resolve4'), + resolve6: method('resolve6'), + resolveMx: method('resolveMx'), + resolveNs: method('resolveNs'), + reverse: method('reverse') + }; +} + +/** + * net-guard wants a lookup FUNCTION; mail-auth's modules inject a resolver OBJECT. Accept both: + * an object is turned into one lookup that answers v4 and v6 together, so a caller can hand the + * same fake in either shape and the check still never reaches the network. + */ +function pickNetLookup({ lookup, resolver }) { + if (typeof lookup === 'function') return lookup; + return async (host) => { + const answers = []; + for (const [method, family] of [[resolver.resolve4, 4], [resolver.resolve6, 6]]) { + if (!method) continue; + try { + const raw = await method(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 failing is normal (a v4-only host has no AAAA); the other still answers + } + } + if (answers.length === 0) throw Object.assign(new Error('dns_nxdomain'), { code: 'ENOTFOUND' }); + return answers; + }; +} + +// A resolver that refuses or stalls is not a statement about the domain. These codes are worth one +// quiet retry: the alternative is telling a business owner their domain "does not resolve" because +// our own resolver hiccuped, which is both wrong and alarming. +const TRANSIENT_CODES = new Set(['EREFUSED', 'ESERVFAIL', 'SERVFAIL', 'ETIMEOUT', 'ETIMEDOUT', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ENOTIMP']); + +function isTransient(code) { + return TRANSIENT_CODES.has(String(code || '').toUpperCase()); +} + +async function query(method, name, { retry = true } = {}) { + if (typeof method !== 'function') return { ok: false, code: 'ENOTIMP', values: [], transient: true }; + try { + const raw = await method(name); + return { ok: true, code: null, values: Array.isArray(raw) ? raw : [] }; + } catch (err) { + const code = String(err && err.code ? err.code : 'UNKNOWN').toUpperCase(); + if (retry && isTransient(code)) { + await new Promise((resolve) => setTimeout(resolve, 150)); + return query(method, name, { retry: false }); + } + return { ok: false, code, empty: EMPTY_CODES.has(code), transient: isTransient(code), values: [] }; + } +} + +export function normaliseMx(raw) { + const records = []; + let nullMx = false; + for (const entry of Array.isArray(raw) ? raw : []) { + if (!entry) continue; + const exchangeRaw = typeof entry === 'string' ? entry : String(entry.exchange ?? ''); + const exchange = exchangeRaw.trim().toLowerCase(); + // RFC 7505: "0 ." is a published statement that this domain accepts no mail at all. + if (exchange === '.' || exchange === '') { + nullMx = true; + continue; + } + const priority = typeof entry === 'object' && Number.isFinite(Number(entry.priority)) ? Number(entry.priority) : 0; + records.push({ priority, exchange: exchange.replace(/\.$/, '') }); + } + records.sort((a, b) => a.priority - b.priority); + return { records, nullMx }; +} + +function normaliseAddresses(raw, family) { + const out = []; + for (const entry of Array.isArray(raw) ? raw : []) { + if (typeof entry === 'string' && entry.length > 0) out.push({ address: entry, family }); + else if (entry && typeof entry.address === 'string') out.push({ address: entry.address, family: entry.family || family }); + } + return out; +} + +// --------------------------------------------------------------------------- +// the two external requests +// --------------------------------------------------------------------------- + +const RDAP_FAILURES = { + rdap_not_found: 'the registry for this name publishes no RDAP record', + rdap_blocked: 'the RDAP service refused the request', + rdap_unreadable: 'the registry answered with something that was not readable RDAP', + rdap_redirect_blocked: 'the RDAP lookup redirected somewhere this tool will not follow', + rdap_too_many_redirects: 'the RDAP lookup redirected more times than this tool follows', + timeout: 'the registry did not answer within 5 seconds', + dns_nxdomain: 'the RDAP service hostname did not resolve from here', + budget: 'the request budget for this check was already spent' +}; + +function rdapFailureReason(result) { + if (!result) return 'the registry record could not be read'; + if (result.code === 'rdap_status') return `the registry answered HTTP ${result.status}`; + if (result.code === 'request_failed') return 'the connection to the RDAP service failed'; + return RDAP_FAILURES[result.code] || 'the registry record could not be read'; +} + +async function readRdap(apex, { request, lookup, budget }) { + let url = `https://rdap.org/domain/${encodeURIComponent(apex)}`; + + for (let hop = 0; hop <= MAX_RDAP_HOPS; hop += 1) { + if (budget.used >= budget.limit) return { ok: false, code: 'budget' }; + budget.used += 1; + + let res; + try { + res = await request(url, { + lookup, + method: 'GET', + timeoutMs: RDAP_TIMEOUT_MS, + maxBytes: RDAP_MAX_BYTES, + accept: 'application/rdap+json, application/json;q=0.9' + }); + } catch (err) { + return { ok: false, code: (err && err.code) || 'request_failed', message: err && err.message }; + } + + const location = res && res.headers ? res.headers.location : null; + if (res && res.status >= 300 && res.status < 400 && location) { + let next; + try { + next = new URL(location, res.url || url).toString(); + } catch { + return { ok: false, code: 'rdap_redirect_blocked' }; + } + // Every hop restarts at the same guard as the visitor's input: RDAP is still a fetch this + // service performs, and a registry-controlled redirect must not become an SSRF hole. + const blocked = guardHop(next); + if (blocked) return { ok: false, code: 'rdap_redirect_blocked', message: blocked.message }; + url = next; + continue; + } + + if (!res || typeof res.status !== 'number') return { ok: false, code: 'request_failed' }; + if (res.status === 404 || res.status === 410) return { ok: false, code: 'rdap_not_found' }; + if (res.status === 403 || res.status === 429) return { ok: false, code: 'rdap_blocked', status: res.status }; + if (res.status < 200 || res.status >= 300) return { ok: false, code: 'rdap_status', status: res.status }; + + try { + return { ok: true, data: JSON.parse(res.body), status: res.status }; + } catch { + return { ok: false, code: 'rdap_unreadable' }; + } + } + + return { ok: false, code: 'rdap_too_many_redirects' }; +} + +async function readWeb(host, { request, lookup, budget }) { + if (budget.used >= budget.limit) return { ok: false, code: 'budget' }; + budget.used += 1; + try { + const res = await request(`https://${host}/`, { + lookup, + method: 'HEAD', + timeoutMs: HEAD_TIMEOUT_MS, + maxBytes: 8192 + }); + return { ok: true, status: res && res.status, headers: (res && res.headers) || {}, address: (res && res.address) || null }; + } catch (err) { + return { ok: false, code: (err && err.code) || 'request_failed', message: err && err.message }; + } +} + +// --------------------------------------------------------------------------- +// summary +// --------------------------------------------------------------------------- + +function mailClause(mail) { + switch (mail.kind) { + case 'provider': + return `your mail runs on ${mail.provider}`; + case 'mixed': + return `your mail runs on ${mail.provider}, alongside a mail host we do not recognise`; + case 'unknown-host': + return `your mail is answered by ${mail.hosts[0]}, a provider we do not recognise`; + case 'null': + return 'nobody can receive mail at this domain because its MX record is intentionally empty'; + case 'none': + return 'no mail server is listed for this domain, so mail sent to it will bounce'; + default: + return 'we could not read the mail records just now'; + } +} + +function webClause(web) { + switch (web.kind) { + case 'attributed': + return `and the website is on ${web.hosting}`; + case 'unattributed': + return `and the website answers from ${web.address} but we cannot tell who hosts it from outside`; + case 'no-address': + return 'and the website has no address in DNS'; + default: + return 'and the website did not answer, so we could not see where it sits'; + } +} + +/** ONE sentence, comma-joined. This is the line the boss screenshots. */ +export function buildSummary({ apex, registrar, expiry, mail, web, ns }) { + const parts = []; + + if (expiry && expiry.known) { + const holder = registrar ? `Your domain is registered with ${registrar}` : 'Your domain'; + if (expiry.expired) { + const when = expiry.daysAgo > 0 ? `${expiry.daysAgo} day${expiry.daysAgo === 1 ? '' : 's'} ago` : 'today'; + parts.push(registrar + ? `Your domain expired ${when} and is registered with ${registrar}` + : `Your domain expired ${when}`); + } else if (expiry.today) { + parts.push(`${holder} and expires today`); + } else { + parts.push(`${holder} and expires in ${expiry.days} day${expiry.days === 1 ? '' : 's'}`); + } + } else { + parts.push(`We could not read the registry record for ${apex}, so the registrar and the expiry date are unchecked`); + } + + parts.push(mailClause(mail)); + parts.push(webClause(web)); + if (ns && ns.count === 1) parts.push(`with all of its DNS resting on a single nameserver (${ns.names[0]})`); + + const [first, ...rest] = parts; + return rest.length === 0 ? `${first}.` : `${first}; ${rest.join(', ')}.`; +} + +// --------------------------------------------------------------------------- +// check +// --------------------------------------------------------------------------- + +/** + * The card state is the worst finding level, but 'info' is not a state: an info row is a fact + * worth printing, not something the visitor has to act on, so it maps to 'ok'. + */ +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; +} + +/** + * Who holds the keys for this domain. + * + * @param {string} input host or URL + * @param {{lookup?: Function|object, request?: Function, dns?: object, now?: number}} options + * `lookup` is net-guard's lookup seam (a function) or a mail-auth style resolver object; + * `request` is the fake used by the offline tests. `now` fixes the clock so day counts are + * deterministic. + */ +export async function checkWhoHolds(input, { lookup, request = requestOnce, dns: dnsSource, now = Date.now() } = {}) { + // AGENTS.md fixes the envelope to an ISO string; a number here would compare unequal to every + // other check's checkedAt and quietly break any staleness test over the results array. + const checkedAt = new Date(now).toISOString(); + const envelope = (state, summary, evidence, findings) => ({ + id: 'who-holds', state, summary, evidence, findings, checkedAt, fromCache: false + }); + + let typedHost; + try { + const text = String(input ?? '').trim().toLowerCase(); + if (text.length === 0) throw new Error('empty'); + typedHost = new URL(/^[a-z][a-z0-9+.-]*:\/\//.test(text) ? text : `https://${text}`).hostname.replace(/\.$/, ''); + if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(typedHost)) throw new Error('bad'); + } catch { + return envelope('fail', 'That does not look like a domain name, so nothing was read.', [], [ + { level: 'fail', code: 'bad_input', message: 'That does not look like a domain name.' } + ]); + } + + const apex = registrableApex(typedHost); + const resolver = pickResolver({ lookup, dns: dnsSource }); + const netLookup = pickNetLookup({ lookup, resolver }); + const budget = { used: 0, limit: REQUEST_BUDGET }; + + const findings = []; + const evidence = []; + const add = (level, code, message, fix) => { + findings.push(fix ? { level, code, message, fix } : { level, code, message }); + }; + + // --- DNS first: it is cheap, and its answers decide whether the two requests are worth it --- + const needsApexAddress = typedHost !== apex; + const nothing = Promise.resolve({ ok: true, code: null, values: [] }); + const [mxResult, nsResult, typedV4, typedV6, apexV4, apexV6] = await Promise.all([ + query(resolver.resolveMx, apex), + query(resolver.resolveNs, apex), + query(resolver.resolve4, typedHost), + query(resolver.resolve6, typedHost), + needsApexAddress ? query(resolver.resolve4, apex) : nothing, + needsApexAddress ? query(resolver.resolve6, apex) : nothing + ]); + const typedAddresses = [...normaliseAddresses(typedV4.values, 4), ...normaliseAddresses(typedV6.values, 6)]; + const apexAddresses = needsApexAddress + ? [...normaliseAddresses(apexV4.values, 4), ...normaliseAddresses(apexV6.values, 6)] + : typedAddresses; + + // At most two reverse lookups: the typed host and, if different, the apex. A missing PTR is + // normal and is never reported as a fault - most small hosts do not publish one. + const ptrTargets = [...new Set([typedAddresses[0], apexAddresses[0]].filter(Boolean).map((entry) => entry.address))].slice(0, MAX_PTR); + const ptrAnswers = await Promise.all(ptrTargets.map((address) => query(resolver.reverse, address))); + const typedPtrIndex = typedAddresses.length > 0 ? ptrTargets.indexOf(typedAddresses[0].address) : -1; + const typedPtr = typedPtrIndex >= 0 && ptrAnswers[typedPtrIndex].ok + ? ptrAnswers[typedPtrIndex].values.map((name) => String(name).toLowerCase()) + : []; + + // --- the two external requests, in parallel so the card costs one round trip, not two ------ + const [rdapResult, webResult] = await Promise.all([ + readRdap(apex, { request, lookup: netLookup, budget }), + readWeb(typedHost, { request, lookup: netLookup, budget }) + ]); + + const rdap = rdapResult.ok ? parseRdap(rdapResult.data) : { registrar: null, expires: null, statuses: [] }; + const expiry = expiryFacts(rdap.expires, now); + + evidence.push({ label: 'Domain', value: apex, note: typedHost === apex ? undefined : `checked from ${typedHost}` }); + evidence.push({ + label: 'Registrar', + value: rdap.registrar || 'not checked', + note: rdap.registrar ? undefined : rdapFailureReason(rdapResult) + }); + evidence.push({ + label: 'Expires', + value: expiry.known + ? `${isoDate(expiry.expiresMs)} (${expiry.expired + ? `expired ${expiry.daysAgo > 0 ? `${expiry.daysAgo} day${expiry.daysAgo === 1 ? '' : 's'} ago` : 'today'}` + : (expiry.today ? 'expires today' : `${expiry.days} day${expiry.days === 1 ? '' : 's'} left`)})` + : 'not checked', + note: expiry.known ? undefined : rdapFailureReason(rdapResult) + }); + + const statuses = classifyStatuses(rdap.statuses); + evidence.push({ + label: 'Registry status', + value: rdapResult.ok + ? (rdap.statuses.length > 0 ? rdap.statuses.join(', ') : 'none reported') + : 'not checked', + note: !rdapResult.ok + ? rdapFailureReason(rdapResult) + : (statuses.locks.length > 0 ? 'a transfer lock, which is normal and protects the name' : undefined) + }); + + // --- 1. the domain clock ---------------------------------------------------------------- + if (!rdapResult.ok) { + add('info', 'domain_expiry_unknown', `Expiry date not checked: ${rdapFailureReason(rdapResult)}.`); + if (rdapResult.code !== 'rdap_not_found') { + add('info', 'rdap_blocked', `The registry lookup did not complete (${rdapResult.code}), so the registrar and expiry were not read.`); + } + } else if (expiry.expired) { + add( + 'fail', + 'domain_expired', + `The registry says this domain expired on ${isoDate(expiry.expiresMs)}, ${expiry.daysAgo > 0 ? `${expiry.daysAgo} day${expiry.daysAgo === 1 ? '' : 's'} ago` : 'today'}.`, + 'Renew or restore it through your registrar immediately: after the grace period the name goes to auction or back to the open market.' + ); + } else if (expiry.soon) { + add( + 'warn', + 'domain_expiring_soon', + `The registry says this domain expires on ${isoDate(expiry.expiresMs)}, which is ${expiry.days === 0 ? 'today' : `${expiry.days} day${expiry.days === 1 ? '' : 's'} away`}.`, + 'Renew it now. Most registrars allow renewal a year ahead, and a lapsed domain can be registered by someone else within days.' + ); + } + + for (const status of statuses.holds) { + add( + 'warn', + 'domain_hold_status', + `The registry reports the status "${status}", which can stop this domain resolving even though it is still registered.`, + 'Ask your registrar why the hold is set; it is usually an unpaid invoice, an unverified contact address, or a legal dispute.' + ); + } + if (statuses.locks.length > 0) { + // Deliberately info, not warn: this is the state that stops a hijack, and flagging the + // default state of every .com would train the reader to ignore the yellow rows. + add('info', 'domain_hold_status', `The registry reports "${statuses.locks.join('", "')}": a transfer lock. That is normal, and it is what stops somebody moving the domain without you.`); + } + + // --- 2. who answers the mail ------------------------------------------------------------- + const mx = normaliseMx(mxResult.values); + const mailEvidenceValue = mx.nullMx + ? '0 . (null MX - no mail accepted)' + : (mx.records.length > 0 + ? mx.records.map((record) => `${record.exchange} (${record.priority})`).join(', ') + // ENODATA is a real answer ("no MX here"); anything else is "I could not find out". + : (mxResult.ok || mxResult.empty ? 'none' : 'not checked')); + + let mail; + if (!mxResult.ok && !mxResult.empty) { + mail = { kind: 'unchecked' }; + } else if (mx.nullMx) { + mail = { kind: 'null' }; + add( + 'warn', + 'null_mx', + 'An empty MX record (0 .) is published, so nobody can receive mail at this domain at all.', + 'If that is deliberate, nothing to do. If you expected mail here, ask your provider for the correct MX records.' + ); + } else if (mx.records.length === 0) { + mail = { kind: 'none' }; + add( + 'warn', + 'no_mx', + 'No MX record is published, so mail sent to this domain has no server to arrive at.', + `Ask your mail provider for their MX records and add them at ${apex}.` + ); + } else { + const hosts = mx.records.map((record) => record.exchange); + const named = []; + const unknown = []; + for (const host of hosts) { + const provider = attributeMailProvider(host); + if (provider) { + if (!named.includes(provider)) named.push(provider); + } else if (!unknown.includes(host)) unknown.push(host); + } + + if (named.length > 0 && unknown.length === 0) { + mail = { kind: 'provider', provider: named.join(', ') }; + add('info', 'mail_provider_identified', `Mail is handled by ${named.join(', ')}, judged from the MX hostnames (${hosts.join(', ')}).`); + } else if (named.length > 0) { + mail = { kind: 'mixed', provider: named.join(', '), hosts: unknown }; + add('info', 'mail_provider_identified', `Mail is handled by ${named.join(', ')}, judged from the MX hostnames, plus ${unknown.join(', ')}.`); + add('info', 'mail_provider_unknown', `${unknown.join(', ')} is not a mail provider we recognise, so it is self-hosted or one we do not know.`); + } else { + mail = { kind: 'unknown-host', hosts: unknown }; + add('info', 'mail_provider_unknown', `The mail server ${unknown.join(', ')} is not a provider we recognise, so it is self-hosted or one we do not know.`); + } + } + + evidence.push({ + label: 'Mail servers', + value: mailEvidenceValue, + note: mxResult.ok || mxResult.empty ? undefined : `the DNS query failed (${mxResult.code})` + }); + evidence.push({ + label: 'Mail provider', + value: mail.kind === 'provider' || mail.kind === 'mixed' + ? mail.provider + : (mail.kind === 'unknown-host' ? 'not recognised' : (mail.kind === 'null' ? 'none - mail refused by design' : (mail.kind === 'none' ? 'none' : 'not checked'))), + note: mail.kind === 'provider' || mail.kind === 'mixed' ? 'judged from the MX hostnames, not from the provider itself' : undefined + }); + + // --- 3. where the website sits ----------------------------------------------------------- + const addresses = typedAddresses.map((entry) => entry.address); + // "ENODATA" is a real answer (this name has no address); a SERVFAIL is not. Only the first + // one lets the card say "no address in DNS" instead of "not checked". + const addressKnownEmpty = (typedV4.ok || typedV4.empty) && (typedV6.ok || typedV6.empty); + evidence.push({ + label: 'Web address', + value: addresses.length > 0 ? addresses[0] : (addressKnownEmpty ? 'no A or AAAA record' : 'not checked'), + note: addresses.length > 1 + ? `${addresses.length} addresses, showing the first` + : (addresses.length === 0 && !addressKnownEmpty ? `DNS said ${typedV4.code || typedV6.code}` : undefined) + }); + + const webHeaders = webResult.ok ? webResult.headers : null; + const serverHeader = header(webHeaders, 'server'); + evidence.push({ + label: 'Web server', + value: webResult.ok ? (serverHeader || 'no server header') : 'the site did not answer', + note: webResult.ok ? undefined : `a HEAD request failed (${webResult.code})` + }); + + let web; + if (addresses.length === 0) { + web = addressKnownEmpty ? { kind: 'no-address' } : { kind: 'unreachable' }; + add('info', 'hosting_unknown', addressKnownEmpty + ? `We cannot tell who hosts the website because ${typedHost} has no A or AAAA record to look at.` + : `We cannot tell who hosts the website because its address could not be read from DNS (${typedV4.code || typedV6.code}).`); + } else if (!webResult.ok) { + web = { kind: 'unreachable' }; + add('info', 'hosting_unknown', `We cannot tell who hosts the website: a HEAD request to https://${typedHost}/ did not complete (${webResult.code}).`); + } else { + const hosting = attributeHosting({ headers: webHeaders, ptr: typedPtr }); + if (hosting) { + web = { kind: 'attributed', hosting: hosting.name }; + evidence.push({ + label: 'Hosting', + value: hosting.likely ? `likely ${hosting.name}` : hosting.name, + note: hosting.basis + }); + } else { + web = { kind: 'unattributed', address: addresses[0] }; + add( + 'info', + 'hosting_unknown', + `We cannot tell who hosts the website from outside: ${addresses[0]} has ${typedPtr.length > 0 ? `the reverse name ${typedPtr[0]}, which names no host we know` : 'no reverse name'}, and the server header names no platform.` + ); + evidence.push({ label: 'Hosting', value: 'we cannot tell from outside', note: 'no reverse name or header that names a host' }); + } + } + if (web.kind === 'no-address') { + evidence.push({ label: 'Hosting', value: 'no address to look at' }); + } + + // --- 4. nameserver footprint ------------------------------------------------------------- + const nameservers = (nsResult.values || []) + .map((entry) => String(typeof entry === 'string' ? entry : (entry && entry.value) || '').trim().toLowerCase().replace(/\.$/, '')) + .filter((name) => name.length > 0); + + evidence.push({ + label: 'Nameservers', + value: nameservers.length > 0 + ? `${nameservers.join(', ')} (${nameservers.length})` + : (nsResult.ok ? 'none published' : 'not checked'), + note: nsResult.ok || nsResult.empty ? undefined : `the DNS query failed (${nsResult.code})` + }); + + if (nameservers.length === 1) { + add( + 'warn', + 'single_nameserver', + `All DNS for this domain rests on one nameserver (${nameservers[0]}): if it is down or unreachable, the domain disappears from the internet.`, + 'Most registrars and DNS hosts give two or more nameservers free. Add the second one your provider lists.' + ); + } + + // --- nothing read at all ---------------------------------------------------------------- + const readNothing = !rdapResult.ok && addresses.length === 0 && nameservers.length === 0 && !mxResult.ok && !webResult.ok; + if (readNothing) { + // A name that does not exist has no records of ANY type, so "no MX, mail will bounce" would + // read as a configured domain with a broken mail setup. Keep the facts, drop the warnings. + const kept = findings.filter((finding) => finding.level === 'info' && finding.code === 'domain_expiry_unknown'); + // "Does not resolve" is a claim about the domain. A refused or stalled query is a claim about + // our resolver, and printing the first when the second happened is exactly the false verdict + // this service exists to avoid (seen live: a domain that answered fine one minute earlier). + const dnsCodes = [typedV4.code, typedV6.code, mxResult.code, nsResult.code].filter(Boolean); + const resolverTrouble = dnsCodes.find(isTransient); + const message = resolverTrouble + ? `The public DNS for ${apex} could not be read from here (${resolverTrouble}), and the registry did not answer either, so nothing was judged about it.` + : `${apex} does not resolve from here and the registry did not answer, so there is no address or mail server to look at.`; + kept.push({ level: 'info', code: 'hosting_unknown', message }); + const summary = resolverTrouble + ? `The DNS lookup for ${apex} did not complete from here (${resolverTrouble}) and the registry did not answer either, so nothing was judged either way.` + : `Nothing could be read for ${apex}: the registry did not answer and the name does not resolve from here.`; + return envelope('not-evaluated', summary, evidence, kept); + } + + // --- the green row ----------------------------------------------------------------------- + const clean = expiry.known && !expiry.expired && !expiry.soon + && statuses.holds.length === 0 + && Boolean(rdap.registrar) + && nameservers.length > 1 + && (mail.kind === 'provider' || mail.kind === 'mixed' || mail.kind === 'null' || mail.kind === 'none'); + if (clean) { + add('ok', 'keys_card_ok', 'Registrar, expiry date, nameservers and mail routing were all read from public records and nothing needs attention.'); + } + + return envelope(worstLevel(findings), buildSummary({ apex, registrar: rdap.registrar, expiry, mail, web, ns: { count: nameservers.length, names: nameservers } }), evidence, findings); +} + +export const check = checkWhoHolds; diff --git a/src/pages.mjs b/src/pages.mjs index 5424ce0..c8093db 100644 --- a/src/pages.mjs +++ b/src/pages.mjs @@ -33,12 +33,13 @@ const CTA = `
export function hubPage() { const body = `

Check your domain the way a customer meets it

-

Three things decide whether a Malaysian business looks real online: the padlock that -expires without warning, the email settings that let anyone spoof your address, and the link preview -your customer sees when you send them a WhatsApp. This service checks all three from the public -internet, in about five seconds.

+

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.

-${form({ action: '/', button: 'Run all three checks' })} +${form({ action: '/', button: 'Run all five checks' })}

Enter the domain you send email from and put on your name card. Nothing is installed, nothing is uploaded, and no account is needed.

@@ -58,11 +59,22 @@ nothing is uploaded, and no account is needed.

We follow the redirect chain a visitor follows, then draw the card WhatsApp will show when someone pastes your link into a chat.

+
+

With and without www

+

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.

+
+
+

Who holds the keys

+

Registrar and expiry date from the registry, who runs your mail, where the site + sits and how many nameservers hold it up — the facts a business owner is usually paying somebody + else to remember.

+

What this is not

It is not a security audit, not a penetration test, and not a guarantee about where your email -lands. It answers three narrow questions with evidence you can see, and it says +lands. It answers five narrow questions with evidence you can see, and it says skipped — not broken — when a site's firewall refuses to talk to a machine. Exactly what it queries is written down here.

@@ -265,11 +277,13 @@ what happens when you press the button, and gives you a way to test the central in Perak; without those rules a public box like this would be a way into that network.
  • 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.
  • -
  • Nothing is opened that the report does not need: a DNS lookup; one TLS handshake; one HTTPS - request for the page, capped at 2 MB and ten seconds; up to five HEAD requests with no page body - when the site redirects, so the certificate is judged where a visitor actually lands; and one HEAD - for the preview image the page declares. The certificate is read from the socket the request - already opened, so checking the padlock does not create a second visit.
  • +
  • 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.
  • 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.
  • @@ -283,8 +297,9 @@ on WhatsApp is not re-fetched every time somebody opens it. Nothing is written t

    How to prove it

    Point the checker at a host you control and watch its log. One run shows at most: one request for -the page, up to five HEAD hops if you redirect, and one HEAD for the image your page declares as -og:image — all carrying the user agent +the page, up to five HEAD hops if you redirect, one HEAD for the image your page declares as +og:image, three requests comparing your address with and without www, and two to the +domain registry — all carrying the user agent HoeleeCheck/1.0 (+https://www.hoelee.com/check/about/), and nothing else. If you see more, or from somewhere unexpected, that is a bug worth reporting.

    @@ -393,9 +408,11 @@ ${preview ? `
    ${imageProbe ? `

    The declared image was fetched once: ${esc(describeImageProbe(imageProbe))}.

    ` : ''}
    ` : ''} +${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: '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') })} ${bad || warn ? CTA : ''} @@ -407,8 +424,8 @@ can already see, once, from one machine in Malaysia. What that means.

    `; return layout({ - title: `${host} — certificate, email and link preview report`, - description: `Certificate, email authentication and link preview results for ${host}.`, + title: `${host} — certificate, email, link preview, www and domain ownership report`, + description: `Certificate, email authentication, link preview, www consistency and domain ownership for ${host}.`, canonical: abs(`/report/${host}`), robots: 'noindex,nofollow', body diff --git a/src/server.mjs b/src/server.mjs index f736b21..2a88d0e 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -26,9 +26,11 @@ const COMMIT = process.env.APP_COMMIT || 'dev'; // The check modules are written independently of this file; accept either export shape so a // naming difference between modules never takes the service down. const loaders = { + 'who-holds': () => import('./checks/who-holds.mjs'), 'mail-auth': () => import('./checks/mail-auth.mjs'), tls: () => import('./checks/tls.mjs'), - http: () => import('./checks/http.mjs') + 'http': () => import('./checks/http.mjs'), + 'host-shape': () => import('./checks/host-shape.mjs') }; const modules = {}; for (const [id, load] of Object.entries(loaders)) { diff --git a/test/host-shape.test.mjs b/test/host-shape.test.mjs new file mode 100644 index 0000000..983e8a5 --- /dev/null +++ b/test/host-shape.test.mjs @@ -0,0 +1,343 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { checkHostShape, analyseHostShape, planForms, normaliseAddress, startUrlFor, REQUEST_BUDGET } from '../src/checks/host-shape.mjs'; +import { NetGuardError } from '../src/lib/net-guard.mjs'; + +// Every fixture here is a plain object shaped like net-guard's requestOnce() result. The resolver +// is never called and no socket is opened: `lookup` is undefined throughout, and the only +// transport is the fake below. + +/** Routes by "scheme://hostname"; a handler may be a function (for path-based chains) or an Error. */ +function fakeRequest(routes) { + const calls = []; + const fn = async (url, options = {}) => { + const method = options.method || 'GET'; + calls.push({ url, method }); + const parsed = new URL(url); + const key = `${parsed.protocol}//${parsed.hostname}`; + const handler = routes[key]; + if (handler === undefined) throw new NetGuardError('dns_nxdomain', 'That domain did not resolve.'); + const res = typeof handler === 'function' ? handler(options, url) : handler; + if (res instanceof Error) throw res; + return { url, status: 200, headers: {}, body: '', timing: { totalMs: 1 }, tls: null, ...res }; + }; + fn.calls = calls; + return fn; +} + +function codes(result) { + return result.findings.map((finding) => finding.code); +} + +function finding(result, code) { + return result.findings.find((entry) => entry.code === code); +} + +function evidenceValue(result, label) { + const row = result.evidence.find((entry) => entry.label === label); + return row ? row.value : undefined; +} + +// --- both forms, one page --------------------------------------------------------------------- + +test('a bare domain that redirects to www is reported as one page, in two requests', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 301, headers: { location: 'https://www.example.com/' } }, + 'https://www.example.com': { status: 200 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.id, 'host-shape'); + assert.equal(result.state, 'ok'); + assert.equal(result.fromCache, false); + assert.match(result.summary, /same page/); + assert.equal(finding(result, 'host_forms_converge').level, 'ok'); + assert.match(finding(result, 'host_forms_converge').message, /https:\/\/www\.example\.com\//); + assert.equal(evidenceValue(result, 'https://example.com/'), 'https://www.example.com/ (301, after a redirect)'); + assert.equal(evidenceValue(result, 'https://www.example.com/'), 'https://www.example.com/ (200)'); + assert.equal(request.calls.length, 2, 'the apex redirect target is the other form, so it is not fetched twice'); + assert.equal(typeof result.checkedAt, 'string'); + assert.ok(Number.isFinite(Date.parse(result.checkedAt))); +}); + +test('typing www.example.com checks www first and the bare domain as its counter-form', async () => { + const request = fakeRequest({ + 'https://www.example.com': { status: 200 }, + 'https://example.com': { status: 301, headers: { location: 'https://www.example.com/' } } + }); + + const result = await checkHostShape('www.example.com', { request }); + + assert.equal(result.state, 'ok'); + assert.deepEqual(planForms('www.example.com').forms, ['www.example.com', 'example.com']); + assert.equal(request.calls[0].url, 'https://www.example.com/'); +}); + +test('two addresses that land on different pages are a warning naming both', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 200 }, + 'https://www.example.com': { status: 200 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'warn'); + const split = finding(result, 'host_forms_split'); + assert.equal(split.level, 'warn'); + assert.match(split.message, /example\.com ends on https:\/\/example\.com\//); + assert.match(split.message, /www\.example\.com ends on https:\/\/www\.example\.com\//); + assert.match(result.summary, /two addresses/); + assert.equal(finding(result, 'host_forms_converge'), undefined); +}); + +test('the same page reached by a different path is still a split', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 301, headers: { location: 'https://www.example.com/home' } }, + 'https://www.example.com': (options, url) => ({ status: 200, url }) + }); + + const result = await checkHostShape('example.com', { request }); + + // The apex chain lands on /home, and the www probe itself is asked for "/", so the two forms do + // not end on the same URL. + assert.equal(result.state, 'warn'); + assert.ok(codes(result).includes('host_forms_split')); +}); + +// --- a form that is not there ---------------------------------------------------------------- + +test('a www name that does not resolve is a failure that names www', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 301, headers: { location: 'https://www.example.com/' } } + // https://www.example.com is absent -> the fake throws dns_nxdomain, as net-guard would + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'fail'); + const dead = finding(result, 'host_form_dead'); + assert.equal(dead.level, 'fail'); + assert.match(dead.message, /^www\.example\.com does not answer at all/); + assert.match(dead.message, /does not exist in DNS/); + assert.match(result.summary, /www\.example\.com does not answer at all/); + assert.equal(evidenceValue(result, 'https://www.example.com/'), 'no answer -- the name does not exist in DNS'); + assert.match( + evidenceValue(result, 'https://example.com/'), + /redirects to an address that does not answer/, + 'the apex must not claim it lands on a name that does not exist' + ); +}); + +test('a form returning a 500 is a failure, not a warning', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 200 }, + 'https://www.example.com': { status: 500 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'fail'); + assert.match(finding(result, 'host_form_dead').message, /returns a 500 error/); +}); + +test('a 404 is an answer, so it is reported as a split rather than a dead form', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 200 }, + 'https://www.example.com': { status: 404 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'warn'); + assert.equal(finding(result, 'host_form_dead'), undefined); + assert.ok(codes(result).includes('host_forms_split')); +}); + +// --- encryption ------------------------------------------------------------------------------ + +test('a site that only answers on http is a warning about the unencrypted page', async () => { + const request = fakeRequest({ + 'https://example.com': new NetGuardError('refused', 'The server refused the connection.'), + 'http://example.com': { status: 200 }, + 'https://www.example.com': { status: 301, headers: { location: 'http://example.com/' } } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'warn'); + const http = result.findings.filter((entry) => entry.code === 'host_form_http'); + assert.ok(http.length >= 1); + assert.match(http[0].message, /not encrypted|plain http/); + assert.match(result.summary, /http/); + assert.ok(request.calls.length <= REQUEST_BUDGET); +}); + +test('a redirect that drops to http is a warning that names the http address', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 301, headers: { location: 'http://example.com/' } }, + 'http://example.com': { status: 200 }, + 'https://www.example.com': { status: 200 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'warn'); + assert.match(finding(result, 'host_form_http').message, /http:\/\/example\.com\//); +}); + +// --- refusals are never findings against the site -------------------------------------------- + +test('a CDN challenge page is not evaluated, and nothing is called broken', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 403, headers: { server: 'cloudflare', 'cf-ray': '8a1b2c3d' } }, + 'https://www.example.com': { status: 200 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'not-evaluated'); + assert.equal(finding(result, 'host_forms_blocked').level, 'info'); + assert.match(result.summary, /refused our automated request/); + assert.equal(result.findings.filter((entry) => entry.level === 'fail').length, 0); + assert.equal(result.findings.filter((entry) => entry.level === 'warn').length, 0); +}); + +test('a counter-form that points into a private network is not evaluated, with the reason', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 200 }, + 'https://www.example.com': new NetGuardError('private_host', 'That address is private.') + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'not-evaluated'); + assert.match(result.summary, /private network address/); + assert.equal(finding(result, 'host_form_unjudged').level, 'info'); + assert.equal(finding(result, 'host_form_dead'), undefined); +}); + +test('a timeout is not judged either', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 200 }, + 'https://www.example.com': new NetGuardError('timeout', 'That took too long.') + }); + + const result = await checkHostShape('example.com', { request }); + + assert.equal(result.state, 'not-evaluated'); + assert.match(result.summary, /did not answer in time/); +}); + +// --- one form only --------------------------------------------------------------------------- + +test('a hosted subdomain has no second form, so only one address is probed', async () => { + const request = fakeRequest({ 'https://myshop.github.io': { status: 200 } }); + + const result = await checkHostShape('myshop.github.io', { request }); + + assert.equal(result.state, 'ok'); + assert.equal(finding(result, 'host_form_single').level, 'info'); + assert.match(result.summary, /hosted subdomain/); + assert.equal(request.calls.length, 1); + assert.equal(request.calls[0].url, 'https://myshop.github.io/'); +}); + +test('a deeper subdomain is compared with the registrable apex', async () => { + const request = fakeRequest({ + 'https://shop.example.com.my': { status: 200 }, + 'https://example.com.my': { status: 200 } + }); + + const result = await checkHostShape('shop.example.com.my', { request }); + + assert.deepEqual(planForms('shop.example.com.my').forms, ['shop.example.com.my', 'example.com.my']); + assert.equal(result.state, 'warn', 'a subdomain that lands somewhere else is still two addresses'); + assert.ok(codes(result).includes('host_forms_split')); +}); + +// --- budget ---------------------------------------------------------------------------------- + +test('a long redirect chain cannot spend more than three requests, and still checks www', async () => { + const request = fakeRequest({ + 'https://example.com': (options, url) => { + const path = new URL(url).pathname; + if (path === '/') return { status: 301, headers: { location: '/one' } }; + if (path === '/one') return { status: 301, headers: { location: '/two' } }; + if (path === '/two') return { status: 301, headers: { location: '/three' } }; + return { status: 200 }; + }, + 'https://www.example.com': { status: 200 } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.ok(request.calls.length <= REQUEST_BUDGET, `made ${request.calls.length} requests`); + assert.ok( + request.calls.some((call) => call.url.includes('www.example.com')), + 'one request is held back for the counter-form' + ); + assert.equal(result.state, 'not-evaluated', 'the first form was not followed to a page'); +}); + +test('a server that refuses HEAD gets one GET of the first kilobyte, inside the same budget', async () => { + const request = fakeRequest({ + 'https://example.com': (options) => (options.method === 'HEAD' ? { status: 405 } : { status: 200 }), + 'https://www.example.com': { status: 301, headers: { location: 'https://example.com/' } } + }); + + const result = await checkHostShape('example.com', { request }); + + assert.deepEqual(request.calls.map((call) => call.method), ['HEAD', 'GET', 'HEAD']); + assert.equal(result.state, 'ok'); + assert.ok(codes(result).includes('host_forms_converge')); +}); + +test('two forms and a redirect fit inside three requests', async () => { + const request = fakeRequest({ + 'https://example.com': { status: 301, headers: { location: 'https://www.example.com/' } }, + 'https://www.example.com': { status: 200 } + }); + + await checkHostShape('example.com', { request }); + assert.equal(request.calls.length, 2); + assert.ok(request.calls.every((call) => call.method === 'HEAD'), 'no page bodies are downloaded'); +}); + +// --- the analyser is pure -------------------------------------------------------------------- + +test('the analyser reads probes without touching the network', () => { + const plan = planForms('example.com'); + const now = Date.UTC(2026, 0, 15, 12, 0, 0); + const probes = [ + { form: 'example.com', startUrl: 'https://example.com/', finalUrl: 'https://www.example.com/', status: 301, outcome: 'answered', reason: null, httpOnly: false }, + { form: 'www.example.com', startUrl: 'https://www.example.com/', finalUrl: 'https://www.example.com/', status: 200, outcome: 'answered', reason: null, httpOnly: false } + ]; + + const result = analyseHostShape(plan, probes, { now }); + + assert.equal(result.state, 'ok'); + assert.equal(result.checkedAt, new Date(now).toISOString()); + assert.deepEqual(result.evidence.map((row) => row.label), ['https://example.com/', 'https://www.example.com/']); + assert.ok(codes(result).includes('host_forms_converge')); +}); + +// --- planning and comparison ---------------------------------------------------------------- + +test('planForms picks the two addresses a customer could type', () => { + assert.deepEqual(planForms('example.com').forms, ['example.com', 'www.example.com']); + assert.deepEqual(planForms('www.example.com').forms, ['www.example.com', 'example.com']); + assert.deepEqual(planForms('https://Example.COM./').forms, ['example.com', 'www.example.com']); + assert.deepEqual(planForms('myshop.github.io').forms, ['myshop.github.io']); + assert.equal(planForms('myshop.github.io').single, 'platform'); + assert.deepEqual(planForms('').forms, []); +}); + +test('normaliseAddress ignores what a browser ignores and nothing else', () => { + assert.equal(normaliseAddress('https://WWW.Example.com'), normaliseAddress('https://www.example.com/')); + assert.equal(normaliseAddress('https://example.com:443/'), normaliseAddress('https://example.com/')); + assert.notEqual(normaliseAddress('https://example.com/'), normaliseAddress('https://example.com/Home')); + assert.notEqual(normaliseAddress('http://example.com/'), normaliseAddress('https://example.com/')); + assert.equal(startUrlFor('example.com'), 'https://example.com/'); +}); diff --git a/test/who-holds.test.mjs b/test/who-holds.test.mjs new file mode 100644 index 0000000..3124ae6 --- /dev/null +++ b/test/who-holds.test.mjs @@ -0,0 +1,685 @@ +// Offline tests for who-holds: 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. + +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + checkWhoHolds, + parseRdap, + attributeMailProvider, + attributeHosting, + classifyStatuses, + expiryFacts, + normaliseMx, + buildSummary, + worstLevel, + REQUEST_BUDGET, + EXPIRING_SOON_DAYS, + MAX_PTR +} from '../src/checks/who-holds.mjs'; +import { NetGuardError } from '../src/lib/net-guard.mjs'; + +// A bank behind Akamai's CDN reverse-resolves to *.akamaitechnologies.com. Linode is a brand +// that Akamai owns, but printing "Linode" for an Akamai edge is a false fact about where the +// site runs - this was a real wrong answer on maybank2u.com.my before the patterns were split. +test('an Akamai reverse name is reported as Akamai, never as Linode', () => { + const akamai = attributeHosting({ + headers: { server: 'AkamaiGHost' }, + ptr: ['a23-52-40-99.deploy.static.akamaitechnologies.com'] + }); + assert.equal(akamai.name, 'Akamai'); + assert.ok(!/linode/i.test(JSON.stringify(akamai))); +}); + +test('a suffix never becomes a named provider', () => { + // maybank2u.com.my runs its own MX; a .com.my suffix must not be dressed up as a hoster. + const provider = attributeMailProvider('stmts.maybank2u.com.my'); + assert.equal(provider, 'a Malaysian mail server (.com.my or .my)'); + assert.ok(!/exabytes|shinjiru|ipserverone|serverfreak/i.test(provider)); +}); + +// 10 Nov 2026 00:00 UTC. Every day count below is measured from here. +const NOW = Date.UTC(2026, 10, 10, 0, 0, 0); +const DAY = 86_400_000; + +// --------------------------------------------------------------------------- +// fakes +// --------------------------------------------------------------------------- + +function tableDns({ a4 = {}, a6 = {}, mx = {}, ns = {}, ptr = {} } = {}) { + const calls = { resolve4: [], resolve6: [], resolveMx: [], resolveNs: [], reverse: [] }; + const make = (kind, table) => async (name) => { + calls[kind].push(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; + }; + return { + calls, + resolve4: make('resolve4', a4), + resolve6: make('resolve6', a6), + resolveMx: make('resolveMx', mx), + resolveNs: make('resolveNs', ns), + reverse: make('reverse', ptr) + }; +} + +function routeRequest(routes) { + const calls = []; + const fn = async (url, options = {}) => { + const method = options.method || 'GET'; + calls.push({ url, method }); + const route = routes[`${method} ${url}`] ?? 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; +} + +function rdapFixture({ + registrar = 'NameSilo, LLC', + registered = '2017-05-21T00:08:00Z', + expires = '2027-05-21T00:08:00Z', + status = ['client transfer prohibited'] +} = {}) { + return { + objectClassName: 'domain', + ldhName: 'example.com', + status, + events: [ + { eventAction: 'registration', eventDate: registered }, + { eventAction: 'expiration', eventDate: expires }, + { eventAction: 'last changed', eventDate: '2026-01-27T16:41:51Z' }, + { eventAction: 'last update of RDAP database', eventDate: '2026-11-10T10:05:00Z' } + ], + entities: [ + { handle: '1479', roles: ['registrar'], vcardArray: ['vcard', [['version', {}, 'text', '4.0'], ['fn', {}, 'text', registrar]]] } + ] + }; +} + +const RDAP_URL = 'https://rdap.org/domain/example.com'; +const HEAD_URL = 'https://example.com/'; + +function baseDns(overrides = {}) { + return tableDns({ + a4: { 'example.com': ['93.184.216.34'], ...(overrides.a4 || {}) }, + a6: { ...(overrides.a6 || {}) }, + mx: { + 'example.com': [ + { priority: 10, exchange: 'mx.zoho.com' }, + { priority: 20, exchange: 'mx2.zoho.com' } + ], + ...(overrides.mx || {}) + }, + ns: { 'example.com': ['kirk.ns.cloudflare.com', 'liv.ns.cloudflare.com'], ...(overrides.ns || {}) }, + ptr: { ...(overrides.ptr || {}) } + }); +} + +async function run({ dns: dnsOverrides = {}, routes = {}, host = 'example.com' } = {}) { + const dns = baseDns(dnsOverrides); + const request = routeRequest({ + [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture()) }, + [HEAD_URL]: { status: 200, headers: { server: 'nginx' } }, + ...routes + }); + const result = await checkWhoHolds(host, { lookup: dns, request, now: NOW }); + return { result, dns, request }; +} + +const codes = (result) => result.findings.map((finding) => finding.code); +// A real resolver throws ENODATA for "this name has no record of that type", and that is an +// answer, not a failure - the tests must not fake it as one. +const nodata = () => Object.assign(new Error('ENODATA'), { code: 'ENODATA' }); +const level = (result, code) => result.findings.find((finding) => finding.code === code)?.level ?? null; +const evidenceValue = (result, label) => result.evidence.find((row) => row.label === label)?.value ?? null; + +// --------------------------------------------------------------------------- +// envelope and the happy path +// --------------------------------------------------------------------------- + +test('the happy path reads registrar, expiry, mail, web and nameservers in two requests', async () => { + const { result, request } = await run(); + + assert.equal(result.id, 'who-holds'); + assert.equal(result.state, 'ok'); + assert.equal(result.fromCache, false); + // The envelope contract (AGENTS.md) is an ISO string, like every other check. + assert.equal(result.checkedAt, new Date(NOW).toISOString()); + assert.equal(typeof result.checkedAt, 'string'); + assert.equal(request.calls.length, 2, 'one RDAP request plus one HEAD'); + assert.equal(request.calls.filter((call) => call.method === 'HEAD').length, 1); + + assert.equal(evidenceValue(result, 'Registrar'), 'NameSilo, LLC'); + assert.equal(evidenceValue(result, 'Domain'), 'example.com'); + const days = Math.floor((Date.parse('2027-05-21T00:08:00Z') - NOW) / DAY); + assert.match(evidenceValue(result, 'Expires'), new RegExp(`${days} days left`)); + assert.match(evidenceValue(result, 'Expires'), /^2027-05-21/); + assert.ok(codes(result).includes('keys_card_ok')); + assert.ok(codes(result).includes('mail_provider_identified')); + assert.match(result.summary, /registered with NameSilo, LLC/); + assert.match(result.summary, /expires in \d+ days/); + assert.match(result.summary, /your mail runs on Zoho Mail/); +}); + +test('the summary is exactly one sentence', async () => { + const { result } = await run(); + // A sentence break is a period followed by space or end. Dots inside an IP or a hostname are + // not sentence breaks, which is exactly why this is asserted this way rather than by count. + assert.equal(result.summary.match(/\.\s/g), null, result.summary); + assert.ok(result.summary.endsWith('.')); + assert.ok(!result.summary.includes('!')); +}); + +test('evidence rows are emitted in a fixed order so the card is stable', async () => { + const { result } = await run(); + assert.deepEqual(result.evidence.map((row) => row.label), [ + 'Domain', 'Registrar', 'Expires', 'Registry status', + 'Mail servers', 'Mail provider', + 'Web address', 'Web server', 'Hosting', + 'Nameservers' + ]); +}); + +// --------------------------------------------------------------------------- +// RDAP: the domain clock +// --------------------------------------------------------------------------- + +test('parseRdap reads a real registry record shape', () => { + const parsed = parseRdap(rdapFixture()); + assert.equal(parsed.registrar, 'NameSilo, LLC'); + assert.equal(parsed.expires, Date.parse('2027-05-21T00:08:00Z')); + assert.equal(parsed.registered, Date.parse('2017-05-21T00:08:00Z')); + assert.deepEqual(parsed.statuses, ['client transfer prohibited']); +}); + +test('parseRdap never throws on a registry that publishes less than it should', () => { + for (const fixture of [null, undefined, {}, [], 'text', { events: 'nope', entities: 7, status: 42 }]) { + const parsed = parseRdap(fixture); + assert.equal(parsed.registrar, null); + assert.equal(parsed.expires, null); + assert.deepEqual(parsed.statuses, []); + } +}); + +test('parseRdap survives an expiration event with an unreadable date', () => { + const parsed = parseRdap({ events: [{ eventAction: 'expiration', eventDate: 'not a date' }] }); + assert.equal(parsed.expires, null); +}); + +test('a domain expiring within 30 days is a warn with the real day count', async () => { + const expires = new Date(NOW + 19 * DAY).toISOString(); + const { result } = await run({ routes: { [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture({ expires })) } } }); + + assert.equal(level(result, 'domain_expiring_soon'), 'warn'); + assert.equal(result.state, 'warn'); + const message = result.findings.find((finding) => finding.code === 'domain_expiring_soon').message; + assert.match(message, /19 days away/); + assert.match(result.summary, /expires in 19 days/); + assert.ok(!codes(result).includes('domain_expired')); +}); + +test('a domain that already lapsed is a fail, and the summary leads with it', async () => { + const expires = new Date(NOW - 40 * DAY).toISOString(); + const { result } = await run({ routes: { [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture({ expires })) } } }); + + assert.equal(level(result, 'domain_expired'), 'fail'); + assert.equal(result.state, 'fail'); + assert.match(result.findings.find((finding) => finding.code === 'domain_expired').message, /40 days ago/); + assert.match(result.summary, /expired 40 days ago/); + assert.ok(!codes(result).includes('keys_card_ok')); +}); + +test('a domain that lapsed hours ago reads as expired today, not yesterday', () => { + const facts = expiryFacts(NOW - 2 * 60 * 60 * 1000, NOW); + assert.equal(facts.expired, true); + assert.equal(facts.daysAgo, 0); +}); + +test('RDAP 404 means expiry unknown with the reason, and the rest of the card still fills in', async () => { + const { result, request } = await run({ routes: { [RDAP_URL]: { status: 404, body: '' } } }); + + assert.equal(level(result, 'domain_expiry_unknown'), 'info'); + assert.match(result.findings.find((finding) => finding.code === 'domain_expiry_unknown').message, /no RDAP record/); + assert.equal(evidenceValue(result, 'Registrar'), 'not checked'); + assert.equal(evidenceValue(result, 'Expires'), 'not checked'); + assert.ok(!codes(result).includes('rdap_blocked'), 'a 404 is a thin registry, not a block'); + assert.notEqual(result.state, 'fail'); + assert.notEqual(result.state, 'not-evaluated'); + + // mail, nameservers and hosting were read anyway + assert.match(evidenceValue(result, 'Mail servers'), /mx\.zoho\.com/); + assert.match(evidenceValue(result, 'Nameservers'), /kirk\.ns\.cloudflare\.com/); + assert.equal(evidenceValue(result, 'Web address'), '93.184.216.34'); + assert.match(result.summary, /could not read the registry record for example\.com/); + assert.equal(request.calls.length, 2); +}); + +test('an RDAP timeout costs the expiry row only, never the whole check', async () => { + const { result } = await run({ routes: { [RDAP_URL]: new NetGuardError('timeout', 'That took too long.') } }); + + assert.equal(result.state, 'ok', 'everything else is fine, so no red and no yellow'); + assert.equal(level(result, 'domain_expiry_unknown'), 'info'); + assert.match(result.findings.find((finding) => finding.code === 'domain_expiry_unknown').message, /did not answer within 5 seconds/); + assert.equal(level(result, 'rdap_blocked'), 'info'); + assert.match(evidenceValue(result, 'Mail servers'), /mx\.zoho\.com/); + assert.match(evidenceValue(result, 'Nameservers'), /cloudflare/); + assert.match(result.summary, /could not read the registry record/); + assert.match(result.summary, /your mail runs on Zoho Mail/); +}); + +test('RDAP is followed through one registry redirect and stays inside the budget', async () => { + const registry = 'https://rdap.verisign.com/com/v1/domain/example.com'; + const { result, request } = await run({ + routes: { + [RDAP_URL]: { status: 302, headers: { location: registry } }, + [registry]: { status: 200, body: JSON.stringify(rdapFixture()) } + } + }); + + assert.equal(request.calls.filter((call) => call.url.includes('rdap')).length, 2); + assert.ok(request.calls.length <= REQUEST_BUDGET); + assert.equal(evidenceValue(result, 'Registrar'), 'NameSilo, LLC'); + assert.equal(level(result, 'domain_expiry_unknown'), null); +}); + +test('an RDAP redirect at a private address is refused, not dialled', async () => { + const { result, request } = await run({ + routes: { [RDAP_URL]: { status: 302, headers: { location: 'https://127.0.0.1/domain/example.com' } } } + }); + + assert.equal(request.calls.length, 2, 'the HEAD still runs; the private hop is never fetched'); + assert.equal(level(result, 'domain_expiry_unknown'), 'info'); + assert.match(result.findings.find((finding) => finding.code === 'domain_expiry_unknown').message, /will not follow/); +}); + +test('a registry answering with broken JSON degrades to expiry unknown', async () => { + const { result } = await run({ routes: { [RDAP_URL]: { status: 200, body: 'nope' } } }); + assert.equal(level(result, 'domain_expiry_unknown'), 'info'); + assert.match(result.findings.find((finding) => finding.code === 'domain_expiry_unknown').message, /not readable RDAP/); +}); + +test('a registry rate limit is reported as a block, not as a problem with the domain', async () => { + const { result } = await run({ routes: { [RDAP_URL]: { status: 429, body: '' } } }); + assert.equal(level(result, 'rdap_blocked'), 'info'); + assert.match(result.findings.find((finding) => finding.code === 'rdap_blocked').message, /429|did not complete/); + assert.notEqual(result.state, 'fail'); +}); + +// --------------------------------------------------------------------------- +// registry status +// --------------------------------------------------------------------------- + +test('client hold is a warning that names the status', async () => { + const { result } = await run({ + routes: { [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture({ status: ['clientHold'] })) } } + }); + assert.equal(level(result, 'domain_hold_status'), 'warn'); + assert.match(result.findings.find((finding) => finding.code === 'domain_hold_status').message, /clientHold/); + assert.equal(result.state, 'warn'); +}); + +test('a transfer lock is reported as normal, not as a warning', async () => { + const { result } = await run({ + routes: { [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture({ status: ['clientTransferProhibited'] })) } } + }); + const finding = result.findings.find((entry) => entry.code === 'domain_hold_status'); + assert.equal(finding.level, 'info', 'the default state of every .com must not read as a problem'); + assert.match(finding.message, /transfer lock/); + assert.equal(result.state, 'ok'); +}); + +test('classifyStatuses separates holds from locks', () => { + const { holds, locks } = classifyStatuses(['client hold', 'clientTransferProhibited', 'ok', 'serverHold']); + assert.deepEqual(holds, ['client hold', 'serverHold']); + assert.deepEqual(locks, ['clientTransferProhibited']); +}); + +// --------------------------------------------------------------------------- +// mail +// --------------------------------------------------------------------------- + +test('MX hostnames are attributed to the providers that publish them', () => { + assert.equal(attributeMailProvider('aspmx.l.google.com'), 'Google Workspace'); + assert.equal(attributeMailProvider('alt1.aspmx.l.google.com'), 'Google Workspace'); + assert.equal(attributeMailProvider('example-com.mail.protection.outlook.com'), 'Microsoft 365'); + assert.equal(attributeMailProvider('mx.zoho.com'), 'Zoho Mail'); + assert.equal(attributeMailProvider('mx3.zoho.eu'), 'Zoho Mail'); + assert.equal(attributeMailProvider('mx.cloudflare.net'), 'Cloudflare Email Routing'); + assert.equal(attributeMailProvider('inbound-smtp.ap-southeast-5.amazonaws.com'), 'Amazon SES'); + assert.equal(attributeMailProvider('titan.email'), 'Titan'); + assert.equal(attributeMailProvider('mail.exabytes.com'), 'Exabytes (Malaysian host)'); + assert.equal(attributeMailProvider('mail.unknown-host.net'), null); + assert.equal(attributeMailProvider(''), null); +}); + +test('each recognised provider reaches the card as an identified mail provider', async () => { + const cases = [ + [['aspmx.l.google.com'], 'Google Workspace'], + [['example.mail.protection.outlook.com'], 'Microsoft 365'], + [['mx.zoho.com'], 'Zoho Mail'], + [['mx.cloudflare.net'], 'Cloudflare Email Routing'] + ]; + for (const [hosts, provider] of cases) { + const { result } = await run({ + dns: { mx: { 'example.com': hosts.map((exchange, index) => ({ priority: 10 * (index + 1), exchange })) } } + }); + assert.equal(level(result, 'mail_provider_identified'), 'info', provider); + assert.equal(evidenceValue(result, 'Mail provider'), provider); + assert.match(result.summary, new RegExp(`your mail runs on ${provider.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`)); + } +}); + +test('an unrecognised MX host is printed and called self-hosted or unknown', async () => { + const { result } = await run({ dns: { mx: { 'example.com': [{ priority: 10, exchange: 'mail.example.com' }] } } }); + + assert.equal(level(result, 'mail_provider_unknown'), 'info'); + assert.match(result.findings.find((finding) => finding.code === 'mail_provider_unknown').message, /mail\.example\.com/); + assert.equal(evidenceValue(result, 'Mail provider'), 'not recognised'); + assert.match(result.summary, /mail\.example\.com, a provider we do not recognise/); + assert.equal(result.state, 'ok'); +}); + +test('null MX is a real fact worth saying out loud', async () => { + const { result } = await run({ dns: { mx: { 'example.com': [{ priority: 0, exchange: '.' }] } } }); + + assert.equal(level(result, 'null_mx'), 'warn'); + assert.equal(result.state, 'warn'); + assert.match(evidenceValue(result, 'Mail servers'), /null MX/); + assert.match(result.summary, /nobody can receive mail at this domain because its MX record is intentionally empty/); + assert.ok(!codes(result).includes('no_mx')); +}); + +test('no MX at all is a different fact from a null MX', async () => { + const { result } = await run({ dns: { mx: { 'example.com': nodata() } } }); + + assert.equal(level(result, 'no_mx'), 'warn'); + assert.ok(!codes(result).includes('null_mx')); + assert.equal(evidenceValue(result, 'Mail servers'), 'none'); + assert.match(result.summary, /no mail server is listed/); +}); + +test('normaliseMx sorts by priority and spots the null MX', () => { + const { records, nullMx } = normaliseMx([ + { priority: 20, exchange: 'mx2.zoho.com' }, + { priority: 10, exchange: 'mx.zoho.com.' } + ]); + assert.equal(nullMx, false); + assert.deepEqual(records, [{ priority: 10, exchange: 'mx.zoho.com' }, { priority: 20, exchange: 'mx2.zoho.com' }]); + assert.equal(normaliseMx([{ priority: 0, exchange: '.' }]).nullMx, true); +}); + +test('a mail lookup that fails is reported as unchecked, not as missing mail', async () => { + const { result } = await run({ dns: { mx: { 'example.com': Object.assign(new Error('servfail'), { code: 'ESERVFAIL' }) } } }); + + assert.ok(!codes(result).includes('no_mx')); + assert.ok(!codes(result).includes('null_mx')); + assert.equal(evidenceValue(result, 'Mail servers'), 'not checked'); + assert.match(result.summary, /could not read the mail records/); +}); + +// --------------------------------------------------------------------------- +// hosting +// --------------------------------------------------------------------------- + +test('hosting is attributed from a server header that names a platform', () => { + assert.deepEqual(attributeHosting({ headers: { server: 'cloudflare' } }).name, 'Cloudflare'); + assert.deepEqual(attributeHosting({ headers: { 'x-vercel-id': 'sin1::abc' } }).name, 'Vercel'); + assert.deepEqual(attributeHosting({ headers: { 'x-amz-cf-id': 'abc' } }).name, 'Amazon CloudFront'); + assert.deepEqual(attributeHosting({ headers: { 'x-github-request-id': 'abc' } }).name, 'GitHub Pages'); +}); + +test('a bare nginx header is not a hosting claim', () => { + assert.equal(attributeHosting({ headers: { server: 'nginx' } }), null); + assert.equal(attributeHosting({ headers: { server: 'Apache', 'x-powered-by': 'PHP/8.2' } }), null); + assert.equal(attributeHosting({}), null); +}); + +test('a reverse name that names a host is labelled likely, never as fact', async () => { + const { result } = await run({ + dns: { ptr: { '93.184.216.34': ['ec2-93-184-216-34.ap-southeast-5.compute.amazonaws.com'] } } + }); + + assert.equal(evidenceValue(result, 'Hosting'), 'likely Amazon AWS'); + assert.match(result.evidence.find((row) => row.label === 'Hosting').note, /reverse-resolves/); + assert.equal(result.state, 'ok'); + assert.match(result.summary, /the website is on Amazon AWS/); +}); + +test('no PTR and no telling header means we say we cannot tell', async () => { + const { result } = await run(); + assert.equal(level(result, 'hosting_unknown'), 'info'); + assert.equal(evidenceValue(result, 'Hosting'), 'we cannot tell from outside'); + assert.match(result.summary, /we cannot tell who hosts it from outside/); + assert.equal(result.state, 'ok', 'a missing PTR is normal, never a fault'); +}); + +test('a missing PTR is not reported as a failure of the domain', () => { + const dns = tableDns({ a4: { 'example.com': ['93.184.216.34'] } }); + assert.equal(dns.calls.reverse.length, 0, 'nothing is looked up before the check runs'); +}); + +test('the site not answering leaves the address visible and hosting unknown', async () => { + const { result } = await run({ routes: { [HEAD_URL]: new NetGuardError('timeout', 'no answer') } }); + + assert.equal(evidenceValue(result, 'Web address'), '93.184.216.34'); + assert.equal(evidenceValue(result, 'Web server'), 'the site did not answer'); + assert.equal(level(result, 'hosting_unknown'), 'info'); + assert.equal(result.state, 'ok'); + assert.match(result.summary, /the website did not answer/); +}); + +test('no A or AAAA record at all is stated plainly', async () => { + const { result } = await run({ dns: { a4: { 'example.com': nodata() } } }); + assert.equal(evidenceValue(result, 'Web address'), 'no A or AAAA record'); + assert.match(result.summary, /no address in DNS/); +}); + +// --------------------------------------------------------------------------- +// nameservers +// --------------------------------------------------------------------------- + +test('one nameserver is a single point of failure and says so', async () => { + const { result } = await run({ dns: { ns: { 'example.com': ['ns1.only.com'] } } }); + + assert.equal(level(result, 'single_nameserver'), 'warn'); + assert.equal(result.state, 'warn'); + assert.match(result.findings.find((finding) => finding.code === 'single_nameserver').message, /ns1\.only\.com/); + assert.match(evidenceValue(result, 'Nameservers'), /\(1\)/); + assert.match(result.summary, /resting on a single nameserver \(ns1\.only\.com\)/); +}); + +test('two nameservers is not a warning', async () => { + const { result } = await run(); + assert.equal(level(result, 'single_nameserver'), null); + assert.match(evidenceValue(result, 'Nameservers'), /\(2\)/); +}); + +// --------------------------------------------------------------------------- +// budget, subdomains, dead ends +// --------------------------------------------------------------------------- + +test('the check never spends more requests than the budget', async () => { + const registry = 'https://rdap.example-registry.net/domain/example.com'; + const { request } = await run({ + routes: { + [RDAP_URL]: { status: 302, headers: { location: registry } }, + [registry]: { status: 302, headers: { location: 'https://rdap.example-registry.net/v2/domain/example.com' } } + } + }); + assert.ok(request.calls.length <= REQUEST_BUDGET, `${request.calls.length} calls`); + assert.equal(request.calls.filter((call) => call.method === 'HEAD').length, 1, 'the HEAD is never dropped for RDAP'); +}); + +test('a subdomain is checked against its registrable apex', async () => { + const dns = tableDns({ + a4: { 'shop.example.com': ['203.0.113.9'], 'example.com': ['93.184.216.34'] }, + mx: { 'example.com': [{ priority: 10, exchange: 'mx.zoho.com' }] }, + ns: { 'example.com': ['kirk.ns.cloudflare.com', 'liv.ns.cloudflare.com'] } + }); + const request = routeRequest({ + [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture()) }, + 'https://shop.example.com/': { status: 200, headers: { server: 'cloudflare' } } + }); + const result = await checkWhoHolds('shop.example.com', { lookup: dns, request, now: NOW }); + + assert.equal(evidenceValue(result, 'Domain'), 'example.com'); + assert.equal(evidenceValue(result, 'Registrar'), 'NameSilo, LLC'); + assert.equal(evidenceValue(result, 'Web address'), '203.0.113.9'); + assert.ok(dns.calls.reverse.length <= MAX_PTR, 'at most two reverse lookups'); + assert.ok(dns.calls.resolve4.includes('example.com'), 'the apex address is read too'); +}); + +test('a name nothing answers for is not-evaluated, not a failure of the visitor', async () => { + const dns = tableDns({}); + const request = routeRequest({ + [RDAP_URL]: new NetGuardError('dns_nxdomain', 'no'), + [HEAD_URL]: new NetGuardError('dns_nxdomain', 'no') + }); + const result = await checkWhoHolds('example.com', { lookup: dns, request, now: NOW }); + + assert.equal(result.state, 'not-evaluated'); + assert.equal(result.findings.some((finding) => finding.level === 'fail'), false); + assert.equal(result.findings.some((finding) => finding.level === 'warn'), false, 'a name that does not exist must not be accused of a broken mail setup'); + assert.ok(!codes(result).includes('no_mx')); + assert.ok(!codes(result).includes('null_mx')); + assert.match(result.summary, /Nothing could be read/); +}); + +test('bad input fails fast without spending a request', async () => { + const request = routeRequest({}); + const result = await checkWhoHolds('not a domain', { lookup: tableDns({}), request, now: NOW }); + assert.equal(result.state, 'fail'); + assert.equal(codes(result)[0], 'bad_input'); + assert.equal(request.calls.length, 0); +}); + +test('worstLevel ranks info below warn below fail, and info is not a state', () => { + assert.equal(worstLevel([{ level: 'ok' }, { level: 'info' }]), 'ok', 'an info row never turns the card yellow'); + assert.equal(worstLevel([{ level: 'info' }, { level: 'warn' }]), 'warn'); + assert.equal(worstLevel([{ level: 'warn' }, { level: 'fail' }]), 'fail'); + assert.equal(worstLevel([]), 'ok'); +}); + +test('a lookup passed as a function is used by net-guard and the resolver still answers records', async () => { + const dns = baseDns(); + const seen = []; + const lookup = async (host) => { + seen.push(host); + return [{ address: '93.184.216.34', family: 4 }]; + }; + const request = routeRequest({ + [RDAP_URL]: { status: 200, body: JSON.stringify(rdapFixture()) }, + [HEAD_URL]: { status: 200, headers: { server: 'cloudflare' } } + }); + // Both shapes at once: net-guard's function seam plus the resolver object for records. + const result = await checkWhoHolds('example.com', { lookup, dns, request, now: NOW }); + + assert.equal(evidenceValue(result, 'Registrar'), 'NameSilo, LLC'); + assert.equal(evidenceValue(result, 'Hosting'), 'Cloudflare'); + assert.equal(seen.length, 0, 'the fake request never resolves, so net-guard is not reached'); +}); + +// --------------------------------------------------------------------------- +// summary +// --------------------------------------------------------------------------- + +test('buildSummary keeps the documented voice for the two worked examples', () => { + const expirySoon = expiryFacts(NOW + 19 * DAY, NOW); + const expired = expiryFacts(NOW - 3 * DAY, NOW); + + const soon = buildSummary({ + apex: 'example.com', + registrar: 'Shinjiru', + expiry: expirySoon, + mail: { kind: 'provider', provider: 'Google Workspace' }, + web: { kind: 'unattributed', address: '93.184.216.34' }, + ns: { count: 2, names: ['a', 'b'] } + }); + assert.equal( + soon, + 'Your domain is registered with Shinjiru and expires in 19 days; your mail runs on Google Workspace, and the website answers from 93.184.216.34 but we cannot tell who hosts it from outside.' + ); + + const nullMx = buildSummary({ + apex: 'example.com', + registrar: 'NameSilo, LLC', + expiry: expiryFacts(NOW + 214 * DAY, NOW), + mail: { kind: 'null' }, + web: { kind: 'attributed', hosting: 'Cloudflare' }, + ns: { count: 2, names: ['a', 'b'] } + }); + assert.match(nullMx, /expires in 214 days; nobody can receive mail at this domain because its MX record is intentionally empty/); + assert.equal(nullMx.match(/\.\s/g), null); + + const lapsed = buildSummary({ + apex: 'example.com', + registrar: null, + expiry: expired, + mail: { kind: 'none' }, + web: { kind: 'no-address' }, + ns: { count: 1, names: ['ns1.only.com'] } + }); + assert.match(lapsed, /^Your domain expired 3 days ago;/); + assert.match(lapsed, /resting on a single nameserver/); +}); + +test('the expiring-soon threshold is 30 days, inclusive', () => { + assert.equal(expiryFacts(NOW + EXPIRING_SOON_DAYS * DAY, NOW).soon, true); + assert.equal(expiryFacts(NOW + (EXPIRING_SOON_DAYS + 1) * DAY, NOW).soon, false); +}); + +// A resolver that refuses or stalls is not a statement about the domain. Live run showed a domain +// that answered fine one minute earlier reported as "does not resolve from here" - that sentence +// belongs to NXDOMAIN only. +test('a refused DNS query is reported as our lookup failing, not as a missing domain', async () => { + const refusal = () => Object.assign(new Error('refused'), { code: 'EREFUSED' }); + const resolver = { + resolve4: async () => { throw refusal(); }, + resolve6: async () => { throw refusal(); }, + resolveMx: async () => { throw refusal(); }, + resolveNs: async () => { throw refusal(); }, + resolveCname: async () => { throw refusal(); }, + resolvePtr: async () => { throw refusal(); }, + reverse: async () => { throw refusal(); } + }; + const request = async () => { throw Object.assign(new Error('timeout'), { code: 'ETIMEOUT' }); }; + const result = await checkWhoHolds('example.com', { lookup: resolver, request, now: NOW }); + assert.equal(result.state, 'not-evaluated'); + assert.ok(!/does not resolve/i.test(result.summary), result.summary); + assert.match(result.summary, /did not complete from here \(EREFUSED\)/i); +}); + +test('one transient DNS failure is retried before it is believed', async () => { + let calls = 0; + const resolver = { + resolve4: async () => { + calls += 1; + if (calls === 1) throw Object.assign(new Error('refused'), { code: 'EREFUSED' }); + return ['93.184.216.34']; + }, + resolve6: async () => { throw Object.assign(new Error('nope'), { code: 'ENODATA' }); }, + resolveMx: async () => [{ exchange: 'mx.zoho.com', priority: 10 }], + resolveNs: async () => ['ns1.example.com', 'ns2.example.com'], + resolveCname: async () => [], + resolvePtr: async () => [], + reverse: async () => [] + }; + const rdap = { + ok: true, status: 200, + body: JSON.stringify({ + events: [{ eventAction: 'expiration', eventDate: '2027-05-21T00:00:00Z' }], + entities: [{ roles: ['registrar'], vcardArray: ['vcard', [['fn', {}, 'text', 'NameSilo, LLC']]] }], + status: ['client transfer prohibited'] + }) + }; + const request = async () => rdap; + const result = await checkWhoHolds('example.com', { lookup: resolver, request, now: NOW }); + assert.equal(calls, 2, 'the refused query was retried exactly once'); + assert.match(JSON.stringify(result.evidence), /93\.184\.216\.34/); +});