Files
hoelee-check/src/checks/host-shape.mjs
T
hoelee e407c0daba 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.
2026-11-10 18:45:36 +08:00

564 lines
22 KiB
JavaScript

// 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<object>} 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) };
}