fix(check): judge the certificate where the visitor lands, and actually fetch the declared og:image

Two false-verdict classes, both found by an outside review of the v1 wording:

- TLS read the certificate of the host the visitor typed. When apex redirects to www,
  or a CDN name fronts the site, the report judged the redirector. It now walks the
  chain with HEAD requests (no page bodies) and judges the final address, keeps the
  typed certificate as evidence, and takes the worse of the two. A blocked or
  unreachable target stays 'not checked' with a reason, never 'broken'.
- The WhatsApp preview read og:image and printed its URL without fetching it. A 404,
  an HTML page, a 2 MB PNG or a WebP all looked like a working card. It now sends one
  guarded HEAD (1 KB GET fallback) and reports status, type and size.

Also: requestOnce takes an explicit Accept header so an image fetch is not answered
with text/html, and the about page no longer claims 'exactly one connection' now that
two bounded HEAD requests exist.
This commit is contained in:
hoelee committed 2026-11-10 16:25:00 +08:00
1 parent 4049d663a7
commit e4f50e9cf4
8 files changed
+1391 -50

No files matched your search

+319
View File
@@ -0,0 +1,319 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
analyseHttp,
analyseHttpWithImageProbe,
probePreviewImage,
describeImageProbe
} from '../src/checks/http.mjs';
import { NetGuardError } from '../src/lib/net-guard.mjs';
// The declared og:image is the half of the preview check that used to be taken on faith: the tag
// was parsed and its address printed, but nobody asked what that address returns. Every test here
// runs offline through the injectable `request` transport - no socket, no resolver, no server.
const NOW = Date.UTC(2026, 0, 15, 12, 0, 0);
const IMAGE = 'https://www.hoelee.com/card.png';
const SECURE_HEADERS = {
'strict-transport-security': 'max-age=31536000; includeSubDomains',
'content-security-policy': "default-src 'self'; frame-ancestors 'none'",
'x-content-type-options': 'nosniff',
'x-frame-options': 'DENY',
'referrer-policy': 'strict-origin-when-cross-origin',
'permissions-policy': 'camera=(), microphone=()',
'content-type': 'text/html; charset=utf-8'
};
function bodyWithImage(image = IMAGE) {
return `<!doctype html><html><head>
<meta property="og:title" content="Hoelee Check">
<meta property="og:description" content="Plain-English health checks for a domain.">
<meta property="og:image" content="${image}">
<title>Fallback title</title>
</head><body><p>hello</p></body></html>`;
}
const NO_IMAGE_BODY = `<!doctype html><html><head>
<meta property="og:title" content="No card here">
<title>No card here</title>
</head><body><p>hello</p></body></html>`;
function page(body, { status = 200, url = 'https://www.hoelee.com/check/', headers = SECURE_HEADERS } = {}) {
return {
hops: [{ url, status, location: null, totalMs: 40 }],
final: { status, headers, body, url, truncated: false, tls: { authorized: true }, timing: { totalMs: 90 } },
body,
headers,
truncated: false
};
}
/** A response shaped like net-guard's requestOnce(), built without a request. */
function response({ status = 200, headers = {}, truncated = false } = {}) {
return {
status,
headers,
body: '',
url: IMAGE,
address: '203.0.113.10',
family: 4,
truncated,
tls: null,
timing: { totalMs: 12 }
};
}
/** Recording stub transport: `handler(url, options, callNumber)` decides each answer. */
function transport(handler) {
const calls = [];
const fn = async (url, options = {}) => {
calls.push({ url, ...options });
return handler(url, options, calls.length);
};
fn.calls = calls;
return fn;
}
function byCode(analysis, code) {
return analysis.findings.find((finding) => finding.code === code);
}
// --- the image is fine ------------------------------------------------------------------------
test('a 200 image/png at 120 KB is fetched with one HEAD and reported as usable', async () => {
const request = transport(() => response({
status: 200,
headers: { 'content-type': 'image/png', 'content-length': String(120 * 1024) }
}));
const probe = await probePreviewImage(IMAGE, { request });
assert.equal(probe.checked, true);
assert.equal(probe.status, 200);
assert.equal(probe.type, 'image/png');
assert.equal(probe.bytes, 122_880);
assert.equal(probe.problem, null);
assert.equal(request.calls.length, 1);
assert.equal(request.calls[0].method, 'HEAD', 'a healthy image must not be downloaded');
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW, request });
assert.equal(analysis.state, 'ok');
assert.deepEqual(analysis.findings.filter((finding) => finding.level === 'warn' || finding.level === 'fail'), []);
assert.equal(analysis.preview.imageProbe.checked, true);
assert.match(describeImageProbe(analysis.preview.imageProbe), /200 image\/png, 120 KB/);
});
// --- the image is broken ----------------------------------------------------------------------
test('an og:image that answers 404 is a warning that names the status', async () => {
const request = transport(() => response({ status: 404, headers: { 'content-type': 'text/html' } }));
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW, request });
const finding = byCode(analysis, 'og_image_unreachable');
assert.ok(finding, 'a 404 on the declared image must produce og_image_unreachable');
assert.equal(finding.level, 'warn');
assert.match(finding.message, /404/);
assert.equal(analysis.state, 'warn', 'a missing preview image is a warning, never a failure');
assert.equal(analysis.preview.hasImage, true, 'the tag is still declared, the card still points at it');
});
test('a 2 MB og:image warns about the size with the real number', async () => {
const request = transport(() => response({
status: 200,
headers: { 'content-type': 'image/png', 'content-length': String(2 * 1024 * 1024) }
}));
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW, request });
const finding = byCode(analysis, 'og_image_too_large');
assert.ok(finding);
assert.equal(finding.level, 'warn');
assert.match(finding.message, /2\.0 MB/);
assert.match(finding.message, /300 KB/);
assert.equal(analysis.state, 'warn');
assert.notEqual(analysis.state, 'fail');
});
test('an og:image that returns text/html is a warning about the wrong type', async () => {
const request = transport(() => response({
status: 200,
headers: { 'content-type': 'text/html; charset=utf-8', 'content-length': '5321' }
}));
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW, request });
const finding = byCode(analysis, 'og_image_not_an_image');
assert.ok(finding);
assert.equal(finding.level, 'warn');
assert.match(finding.message, /text\/html/);
assert.match(finding.message, /blank or wrong card/);
});
test('a WebP image is mentioned as a rendering risk, never called broken', async () => {
const request = transport(() => response({
status: 200,
headers: { 'content-type': 'image/webp', 'content-length': '48000' }
}));
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW, request });
const finding = byCode(analysis, 'og_image_type_weak');
assert.ok(finding);
assert.equal(finding.level, 'info', 'WebP renders in most current clients: a note, not a warning');
assert.match(finding.message, /WebP/);
assert.doesNotMatch(finding.message, /broken|invalid|corrupt/i);
assert.match(finding.message, /may appear without a picture/);
assert.equal(analysis.state, 'ok', 'an info row must not change the state');
});
// --- we could not look ------------------------------------------------------------------------
test('a loopback og:image is never requested and never called broken', async () => {
const request = transport(() => {
throw new Error('the stub transport must not be called for a blocked address');
});
const probe = await probePreviewImage('http://127.0.0.1/card.png', { request });
assert.equal(probe.checked, false);
assert.equal(request.calls.length, 0, 'net-guard refuses the address before any socket is opened');
assert.doesNotMatch(probe.reason, /broken/i);
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage('http://127.0.0.1/card.png')), {
host: 'www.hoelee.com',
now: NOW,
request
});
assert.equal(request.calls.length, 0);
const finding = byCode(analysis, 'og_image_not_checked');
assert.ok(finding);
assert.equal(finding.level, 'info');
assert.doesNotMatch(finding.message, /broken|fails|failed/i);
assert.equal(analysis.state, 'ok', 'an image we refused to fetch says nothing about the page');
});
test('a private hostname resolved by DNS is reported as not checked', async () => {
const request = transport(() => {
throw new NetGuardError('private_address', 'That domain points at a private address.');
});
const probe = await probePreviewImage(IMAGE, { request });
assert.equal(probe.checked, false);
assert.match(probe.reason, /not one this tool will fetch/);
});
test('a timed-out og:image is not checked, and the page keeps the state it had', async () => {
const request = transport(() => {
throw new NetGuardError('timeout', 'That took too long.');
});
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW, request });
const finding = byCode(analysis, 'og_image_not_checked');
assert.ok(finding);
assert.equal(finding.level, 'info');
assert.match(finding.message, /did not answer within the time allowed/);
assert.equal(analysis.state, 'ok');
assert.equal(analysis.preview.imageProbe.checked, false);
assert.equal(analysis.preview.imageProbe.problem, null);
});
// --- when there is nothing to probe -----------------------------------------------------------
test('a page with no og:image is not probed at all', async () => {
const request = transport(() => {
throw new Error('the stub transport must not be called when no image is declared');
});
const analysis = await analyseHttpWithImageProbe(page(NO_IMAGE_BODY), { host: 'www.hoelee.com', now: NOW, request });
assert.equal(request.calls.length, 0);
assert.equal(byCode(analysis, 'og_image_missing').level, 'warn');
assert.equal(analysis.preview.imageProbe, undefined);
assert.equal(analysis.state, 'warn');
});
test('a challenge page is not probed, even when it carries an og:image tag', async () => {
const request = transport(() => {
throw new Error('the stub transport must not be called for a challenge page');
});
const body = `<html><head><title>Just a moment...</title><meta property="og:image" content="${IMAGE}"></head></html>`;
const analysis = await analyseHttpWithImageProbe(page(body, {
status: 403,
headers: { server: 'cloudflare', 'cf-ray': '8a1b2c3d-KUL', 'content-type': 'text/html' }
}), { host: 'shop.example', now: NOW, request });
assert.equal(request.calls.length, 0);
assert.equal(analysis.state, 'not-evaluated');
assert.equal(analysis.preview, null);
});
// --- the HEAD/GET dance -----------------------------------------------------------------------
test('a 405 on HEAD falls back to one small GET and reads the type from it', async () => {
const request = transport((url, options, call) => {
if (call === 1) return response({ status: 405, headers: { allow: 'GET' } });
return response({ status: 200, headers: { 'content-type': 'image/jpeg', 'content-length': '90000' }, truncated: true });
});
const probe = await probePreviewImage(IMAGE, { request });
assert.equal(request.calls.length, 2);
assert.equal(request.calls[0].method, 'HEAD');
assert.equal(request.calls[1].method, 'GET');
assert.ok(request.calls[1].maxBytes <= 1024, 'the fallback must not download the image');
assert.equal(probe.checked, true);
assert.equal(probe.type, 'image/jpeg');
assert.equal(probe.bytes, 90_000, 'the content-length the server reported is the number published');
assert.equal(probe.problem, null);
});
test('a truncated GET reports a lower bound, not an invented byte count', async () => {
const request = transport((url, options, call) => {
if (call === 1) return response({ status: 200, headers: {} }); // HEAD without type or length
return response({ status: 200, headers: { 'content-type': 'image/png' }, truncated: true });
});
const probe = await probePreviewImage(IMAGE, { request });
assert.equal(probe.checked, true);
assert.equal(probe.bytes, null, 'no content-length came back, so no exact size may be claimed');
assert.equal(probe.bytesAtLeast, 1024);
assert.match(describeImageProbe(probe), /at least 1 KB/);
});
test('a chunked image with no content-length says the size is unknown', async () => {
const request = transport(() => response({ status: 200, headers: { 'content-type': 'image/png' } }));
const probe = await probePreviewImage(IMAGE, { request });
assert.equal(probe.checked, true);
assert.equal(probe.bytes, null);
assert.equal(probe.bytesAtLeast, null);
assert.equal(probe.problem, null);
assert.match(probe.reason, /did not report its size/);
assert.match(describeImageProbe(probe), /size not reported/);
});
test('a redirecting image is left unchecked rather than judged', async () => {
const request = transport(() => response({ status: 301, headers: { location: 'https://cdn.example.com/card.png' } }));
const probe = await probePreviewImage(IMAGE, { request });
assert.equal(probe.checked, false);
assert.match(probe.reason, /301/);
assert.equal(probe.problem, null);
});
test('a relative og:image is probed at the address it resolves to', async () => {
const request = transport(() => response({ status: 200, headers: { 'content-type': 'image/png', 'content-length': '40000' } }));
const analysis = await analyseHttpWithImageProbe(page(bodyWithImage('/img/card.png')), {
host: 'www.hoelee.com',
now: NOW,
request
});
assert.equal(request.calls.length, 1);
assert.equal(request.calls[0].url, 'https://www.hoelee.com/img/card.png');
assert.equal(byCode(analysis, 'og_image_relative').level, 'info');
assert.equal(analysis.preview.imageProbe.problem, null);
});
// --- purity -----------------------------------------------------------------------------------
test('analyseHttp stays pure: without a probe result the report is exactly the old one', () => {
const analysis = analyseHttp(page(bodyWithImage()), { host: 'www.hoelee.com', now: NOW });
assert.equal(analysis.state, 'ok');
assert.equal(analysis.preview.imageProbe, undefined);
assert.equal(analysis.findings.some((finding) => finding.code.startsWith('og_image_')), false);
assert.equal(analysis.findings.some((finding) => finding.code === 'og_image_missing'), false);
});
+302
View File
@@ -0,0 +1,302 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { checkTls, discoverFinalHost } from '../src/checks/tls.mjs';
import { NetGuardError } from '../src/lib/net-guard.mjs';
// The TLS check now asks two questions: what certificate the typed host serves, and what
// certificate the host a browser is redirected to serves. These tests drive both with injected
// stubs — no resolver, no socket, no clock dependence (dates are relative to real now).
const DAY = 86_400_000;
const daysFromNow = (days) => new Date(Date.now() + days * DAY).toISOString();
function tlsInfo(host, { san = `DNS:${host}`, validTo = daysFromNow(120), authorized = true, includeIntermediate = true } = {}) {
const subject = { CN: host };
const issuer = { CN: 'R3', O: "Let's Encrypt" };
const leaf = {
subject,
issuer,
validFrom: daysFromNow(-30),
validTo,
signatureAlgorithm: 'sha256WithRSAEncryption',
fingerprint256: `FP-${host}`,
selfSigned: false
};
const intermediate = {
subject: issuer,
issuer: { CN: 'ISRG Root X1' },
validFrom: daysFromNow(-300),
validTo: daysFromNow(900),
signatureAlgorithm: 'sha256WithRSAEncryption',
fingerprint256: `FP-INT-${host}`,
selfSigned: false
};
const chain = [leaf, intermediate];
const cert = { ...leaf, subjectAltName: san, authorized, authorizationError: null, protocol: 'TLSv1.3', chain };
return {
host,
port: 443,
address: '93.184.216.34',
cipher: { name: 'TLS_AES_256_GCM_SHA384' },
cert,
chain: includeIntermediate ? chain : [leaf]
};
}
/** Routes by hostname; a handler may throw a NetGuardError to model a failed hop. */
function fakeRequest(byHost) {
const calls = [];
const fn = async (url, options = {}) => {
calls.push({ url, method: options.method || 'GET' });
const host = new URL(url).hostname;
const handler = byHost[host];
if (!handler) throw new Error(`unexpected request to ${url}`);
const res = typeof handler === 'function' ? handler(options, url) : handler;
return { url, status: 200, headers: {}, body: '', timing: { totalMs: 1 }, tls: null, ...res };
};
fn.calls = calls;
return fn;
}
/** Returns fixture info per host; a NetGuardError value means the handshake failed. */
function fakeInspect(byHost) {
const calls = [];
const fn = async (host) => {
calls.push(host);
const value = byHost[host];
if (value === undefined) throw new Error(`unexpected inspect of ${host}`);
if (value instanceof Error) throw value;
return value;
};
fn.calls = calls;
return fn;
}
function codes(result) {
return result.findings.map((finding) => finding.code);
}
function evidenceValue(result, label) {
const row = result.evidence.find((entry) => entry.label === label);
return row ? row.value : undefined;
}
// --- no redirect: behaviour must be the old behaviour ----------------------------------------
test('a host with no redirect is inspected once and judged as before', async () => {
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') });
const request = fakeRequest({ 'example.com': { status: 200, tls: tlsInfo('example.com').cert } });
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'ok');
assert.equal(inspect.calls.length, 1, 'only the typed host gets a handshake');
assert.equal(request.calls.length, 1, 'one HEAD request discovers there is no redirect');
assert.equal(request.calls[0].method, 'HEAD');
assert.equal(evidenceValue(result, 'checked at'), 'https://example.com');
assert.equal(evidenceValue(result, 'redirects'), 'none');
assert.equal(evidenceValue(result, 'typed address'), undefined, 'no second address to name');
assert.ok(codes(result).includes('tls_name_match'));
});
// --- apex -> www, one certificate covering both ---------------------------------------------
test('an apex that redirects to www is judged at www, and the summary names it', async () => {
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com', { san: 'DNS:example.com, DNS:*.example.com' }) });
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'https://www.example.com/' } },
'www.example.com': { status: 200, tls: tlsInfo('www.example.com', { san: 'DNS:*.example.com' }).cert }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'ok');
// The final certificate rides back on the redirect's own socket, so no second handshake.
assert.equal(inspect.calls.length, 1);
assert.equal(request.calls.length, 2);
assert.match(result.summary, /www\.example\.com/);
assert.equal(evidenceValue(result, 'checked at'), 'https://www.example.com/');
assert.equal(evidenceValue(result, 'typed address'), 'example.com');
assert.ok(String(evidenceValue(result, 'certificate at typed address')).includes('issued to example.com'));
assert.ok(codes(result).includes('tls_redirect_typed_ok'));
});
test('a problem on the typed certificate still counts when the redirect target is healthy', async () => {
// A short chain does not stop a browser from loading the page, so this is the realistic shape of
// "the first hop is imperfect but the site still redirects onwards".
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com', { includeIntermediate: false }) });
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'https://www.example.com/' } },
'www.example.com': { status: 200, tls: tlsInfo('www.example.com').cert }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'warn');
assert.ok(codes(result).includes('tls_chain_short'));
assert.match(result.summary, /example\.com/);
assert.doesNotMatch(result.summary, /www\.example\.com is valid/i);
});
// --- the broken certificate is at the end of the chain, where visitors land ------------------
test('a healthy typed host redirecting to an expired host fails, and the summary names the broken address', async () => {
const expired = tlsInfo('www.example.com', { validTo: daysFromNow(-10) });
const inspect = fakeInspect({
'example.com': tlsInfo('example.com'),
'www.example.com': expired
});
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'https://www.example.com/' } },
// rejectUnauthorized is on for a real request, so a broken certificate throws at the hop.
'www.example.com': () => { throw new NetGuardError('tls_expired', 'The certificate on that site has expired.'); }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'fail');
assert.ok(codes(result).includes('tls_expired'));
assert.match(result.summary, /www\.example\.com/);
assert.match(result.summary, /expired/i);
// Exactly one extra handshake: the typed host plus the host that actually failed.
assert.equal(inspect.calls.length, 2);
});
test('a name-mismatched certificate at the redirect target fails with the target named', async () => {
const wrongName = tlsInfo('www.example.com', { san: 'DNS:other.example.net' });
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com'), 'www.example.com': wrongName });
const request = fakeRequest({
'example.com': { status: 302, headers: { location: 'https://www.example.com/' } },
'www.example.com': () => { throw new NetGuardError('tls_invalid', 'The certificate on that site could not be verified.'); }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'fail');
assert.ok(codes(result).includes('tls_name_mismatch'));
assert.match(result.summary, /www\.example\.com/);
});
// --- the redirect target is somewhere this service will not go ------------------------------
test('a redirect into a private address keeps the typed verdict and says the target was not checked', async () => {
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') });
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'http://192.168.1.1/' } }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'ok', 'we did not look, so the typed host is not called broken');
assert.equal(request.calls.length, 1, 'the private target is never dialled');
assert.equal(inspect.calls.length, 1, 'and never handshaked');
const note = result.findings.find((finding) => finding.code === 'tls_redirect_unchecked');
assert.ok(note, 'the skipped target is recorded, not silently dropped');
assert.equal(note.level, 'info');
assert.match(note.message, /not checked/i);
assert.match(note.message, /example\.com only/);
assert.match(note.message, /IP address/);
assert.doesNotMatch(note.message, /Enter a domain/);
});
// --- a chain that never settles -------------------------------------------------------------
test('a redirect loop is bounded, adds no false failure, and says only the typed host was judged', async () => {
const inspect = fakeInspect({ 'loop.example.com': tlsInfo('loop.example.com') });
const request = fakeRequest({
'loop.example.com': { status: 301, headers: { location: 'https://loop2.example.com/' } },
'loop2.example.com': { status: 301, headers: { location: 'https://loop.example.com/' } }
});
const result = await checkTls('loop.example.com', { inspect, request });
assert.equal(result.state, 'ok');
assert.ok(request.calls.length <= 6, 'the walk stays inside the redirect cap');
assert.ok(codes(result).includes('tls_redirect_unresolved'));
assert.match(result.summary, /valid/i);
});
test('more than five redirects stops at the cap without throwing', async () => {
const hosts = ['h1.example.com', 'h2.example.com', 'h3.example.com', 'h4.example.com', 'h5.example.com', 'h6.example.com', 'h7.example.com'];
const routes = {};
for (let i = 0; i < hosts.length - 1; i += 1) {
routes[hosts[i]] = { status: 301, headers: { location: `https://${hosts[i + 1]}/` } };
}
routes[hosts[hosts.length - 1]] = { status: 200, tls: tlsInfo(hosts[hosts.length - 1]).cert };
const inspect = fakeInspect({ 'h1.example.com': tlsInfo('h1.example.com') });
const request = fakeRequest(routes);
const result = await checkTls('h1.example.com', { inspect, request });
assert.equal(result.state, 'ok');
assert.equal(request.calls.length, 6, 'MAX_REDIRECTS + the first request, no more');
assert.ok(codes(result).includes('tls_redirect_unresolved'));
});
// --- HEAD refusals and plain-http landings --------------------------------------------------
test('a server that refuses HEAD is asked again with a capped GET', async () => {
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') });
const request = fakeRequest({
'example.com': (options) => (options.method === 'HEAD'
? { status: 405, headers: {} }
: { status: 200, tls: tlsInfo('example.com').cert })
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'ok');
assert.deepEqual(request.calls.map((call) => call.method), ['HEAD', 'GET']);
});
test('a redirect to plain http is recorded as no certificate there, not as a TLS failure', async () => {
const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') });
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'http://other.example.com/' } },
'other.example.com': { status: 200 }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'ok');
assert.ok(codes(result).includes('tls_final_not_https'));
assert.match(result.summary, /plain http/);
});
// --- the hop that fails cannot even be read -------------------------------------------------
test('a TLS failure at a redirect target that cannot be inspected is still reported as a failure', async () => {
const inspect = fakeInspect({
'example.com': tlsInfo('example.com'),
'broken.example.com': new NetGuardError('timeout', 'The TLS handshake timed out.')
});
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'https://broken.example.com/' } },
'broken.example.com': () => { throw new NetGuardError('tls_invalid', 'The certificate on that site could not be verified.'); }
});
const result = await checkTls('example.com', { inspect, request });
assert.equal(result.state, 'fail');
const failed = result.findings.find((finding) => finding.code === 'tls_redirect_hop_failed');
assert.ok(failed);
assert.equal(failed.level, 'fail');
assert.match(failed.message, /broken\.example\.com/);
assert.match(result.summary, /broken\.example\.com/);
});
// --- the discovery seam itself --------------------------------------------------------------
test('discoverFinalHost reports the final address and the trail without analysing anything', async () => {
const request = fakeRequest({
'example.com': { status: 301, headers: { location: 'https://www.example.com/' } },
'www.example.com': { status: 200 }
});
const found = await discoverFinalHost('example.com', { request });
assert.equal(found.finalHost, 'www.example.com');
assert.equal(found.stop, null);
assert.equal(found.hops.length, 2);
assert.equal(found.hops[0].status, 301);
});