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

+6 -2
View File
@@ -37,8 +37,12 @@ import `node:http`/`node:https` directly, must not use the global `fetch`, and m
trust anchor, so a SHA-1 root is not a failure.
- HTTP headers: a missing CSP or Permissions-Policy is **"optional hardening not present"**, not
"insecure". Only a broken redirect chain or malformed HSTS is a failure.
6. **One connection per check.** The certificate comes off the same socket as the HTTPS request
(`requestOnce` already returns `.tls`). Do not open a second connection to the same host.
6. **No redundant connections.** The certificate comes off the same socket as the HTTPS request
(`requestOnce` already returns `.tls`); when a site redirects, the certificate at the final
address is read from that redirect's own socket rather than a fresh handshake. The only extra
traffic allowed is bounded and named: up to five HEAD hops with no page body to find where a
redirect lands, and one HEAD for the declared `og:image`. If you add a sub-request, say why and
cap it.
7. **Cache before you scan.** A shared report URL is prefetched by WhatsApp/Telegram, so a cached
report is served without touching the target. Negative and warning results cache for 5 minutes;
clean results for 1 hour.
+5 -2
View File
@@ -89,8 +89,11 @@ Everything dials through `src/lib/net-guard.mjs`:
connect time is the hole;
- redirects followed by hand, max 5, every hop re-validated;
- 2 MB body cap, 10 s wall clock, `HoeleeCheck/1.0` user agent that names the about page;
- the certificate is read off the **same socket** as the HTTPS request, so the report never opens a
second connection to the target;
- the certificate is read off the **same socket** as the HTTPS request; when the site redirects to
another address, the certificate there is read from that redirect's own socket too, so a padlock
is never re-visited just to read a cert;
- two bounded additions: up to five HEAD hops (no body) to find where a redirect lands, and one HEAD
for the declared `og:image`;
- 10 requests a minute and 100 a day per IP, `Retry-After` on 429.
## Cut from v1 (Argon review, accepted)
+266 -5
View File
@@ -14,7 +14,7 @@
// The only failures here are a broken redirect chain, malformed HSTS, a final 4xx/5xx, and a page
// served with no HTTPS anywhere in the chain. Missing optional headers are never called insecure.
import { fetchFollowing } from '../lib/net-guard.mjs';
import { fetchFollowing, requestOnce, guardHop } from '../lib/net-guard.mjs';
const HSTS_MIN_AGE = 15_552_000; // 180 days, per the HSTS guidance browsers follow
// A redirect budget is counted in REDIRECTS, not requests. Counting requests made a site with
@@ -201,6 +201,234 @@ export function buildPreview(parsed, finalUrl) {
};
}
// --- declared og:image probe ----------------------------------------------------------------
//
// buildPreview() reads the og:image tag and prints the address; it never asks whether that address
// serves a picture. The card above is only as good as the file behind it: an address that 404s,
// answers an HTML page, or points at a 2 MB PNG all leave WhatsApp with no image, and the report
// used to present all three as a working card. One HEAD (plus a 1 KB GET only when HEAD is refused)
// settles it without pulling the picture down.
const IMAGE_SIZE_LIMIT = 300 * 1024; // WhatsApp silently drops preview images above roughly this
const IMAGE_GET_BYTES = 1024; // the GET fallback reads just enough to prove bytes exist
const IMAGE_PROBE_MS = 3000; // hard budget for the whole probe, HEAD and fallback together
function formatBytes(bytes) {
if (!Number.isFinite(bytes)) return 'unknown size';
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
return `${bytes} bytes`;
}
function contentLengthOf(headers) {
const raw = headerValue(headers || {}, 'content-length');
if (raw === null) return null;
const text = String(raw).trim();
return /^\d+$/.test(text) ? Number(text) : null;
}
function contentTypeOf(headers) {
const raw = headerValue(headers || {}, 'content-type');
if (raw === null) return null;
const type = String(raw).split(';')[0].trim().toLowerCase();
return type === '' ? null : type;
}
function probeNotChecked(reason) {
return {
checked: false,
status: null,
type: null,
bytes: null,
bytesAtLeast: null,
truncated: false,
problem: null,
reason
};
}
function probeErrorReason(err) {
const code = err && err.code ? err.code : null;
switch (code) {
case 'timeout':
return 'the image address did not answer within the time allowed';
case 'private_address':
case 'private_host':
case 'ip_literal':
case 'bad_port':
case 'bad_scheme':
case 'bad_input':
return `the image address is not one this tool will fetch (${(err && err.message) || code})`;
case 'refused':
return 'the server refused the connection for the image';
case 'dns_nxdomain':
return 'the image address does not resolve';
case 'tls_invalid':
case 'tls_expired':
return 'the certificate on the image address could not be verified';
default:
return `the image address could not be fetched (${(err && err.message) || 'unknown error'})`;
}
}
function needsGetFallback(status, headers) {
if (status === 405 || status === 501) return true; // HEAD not implemented: ask once as GET
if (status < 200 || status >= 300) return false; // a 4xx/5xx answer is already an answer
return contentTypeOf(headers) === null && contentLengthOf(headers) === null;
}
/**
* Turn one response into the honest verdict. `checked` means the address really answered; a
* `problem` is only set when the answer itself proves the image is a poor preview asset.
*/
function classifyImageResponse(response, { usedGet = false } = {}) {
const status = Number(response && response.status) || 0;
const headers = (response && response.headers) || {};
const type = contentTypeOf(headers);
const bytes = contentLengthOf(headers);
const truncated = Boolean(response && response.truncated);
// Only a truncated GET proves a lower bound; a HEAD without content-length proves nothing, and
// guessing "2 MB" from a missing header would be exactly the invented number this check must not
// publish.
const bytesAtLeast = truncated && usedGet ? IMAGE_GET_BYTES : null;
const base = { checked: true, status, type, bytes, bytesAtLeast, truncated, problem: null };
if (!status) {
return { ...base, problem: 'unreachable', reason: 'the image address did not answer' };
}
if (status >= 300 && status < 400) {
// Previewers follow this hop themselves; this probe does not, so it cannot judge the file.
return {
...base,
checked: false,
reason: `the image address answers ${status} and this probe does not follow redirects on the image`
};
}
if (status >= 400) {
return { ...base, problem: 'unreachable', reason: `the image address answered ${status}` };
}
if (type && !type.startsWith('image/')) {
return { ...base, problem: 'not_an_image', reason: `the image address answered ${status} with ${type}, not an image` };
}
const size = bytes !== null ? bytes : bytesAtLeast;
if (size !== null && size > IMAGE_SIZE_LIMIT) {
return { ...base, problem: 'too_large', reason: `the image is ${formatBytes(size)}, over the ${formatBytes(IMAGE_SIZE_LIMIT)} WhatsApp keeps` };
}
if (type === 'image/webp') {
// WebP is a fine format; it is only the previewers that vary. Never call it broken.
return { ...base, problem: 'type_weak', reason: 'the image is a WebP file, which WhatsApp and older previewers do not always render' };
}
if (size === null) {
return { ...base, reason: `the image answered ${status}${type ? ` as ${type}` : ''} but did not report its size` };
}
return { ...base, reason: `the image answered ${status}${type ? ` as ${type}` : ''}, ${formatBytes(size)}` };
}
/**
* Fetch the declared og:image once and say what came back.
*
* Never throws and never fetches an address net-guard would refuse: a blocked or slow image is
* reported as `checked: false` with a reason, because "we could not look" is not "the site is
* broken". `request` is injectable so tests run with no network at all.
*/
export async function probePreviewImage(imageUrl, { lookup, timeoutMs = IMAGE_PROBE_MS, request = requestOnce } = {}) {
if (typeof imageUrl !== 'string' || !/^https?:\/\//i.test(imageUrl)) {
return probeNotChecked('there is no absolute http(s) image address to fetch');
}
const guarded = guardHop(imageUrl);
if (guarded) {
return probeNotChecked(`the image address is not one this tool will fetch (${guarded.message})`);
}
const deadline = Date.now() + timeoutMs;
let response;
let usedGet = false;
try {
response = await request(imageUrl, {
method: 'HEAD', timeoutMs, maxBytes: IMAGE_GET_BYTES, lookup, accept: 'image/*,*/*;q=0.5'
});
} catch (err) {
// A refused or timed-out HEAD is not worth a second attempt at the visitor's expense.
return probeNotChecked(probeErrorReason(err));
}
if (needsGetFallback(Number(response && response.status) || 0, response && response.headers)) {
const remaining = deadline - Date.now();
if (remaining < 250) {
return probeNotChecked('the image address did not report its type or size, and there was no time left to ask again');
}
usedGet = true;
try {
response = await request(imageUrl, {
method: 'GET', timeoutMs: remaining, maxBytes: IMAGE_GET_BYTES, lookup, accept: 'image/*,*/*;q=0.5'
});
} catch (err) {
return probeNotChecked(probeErrorReason(err));
}
}
return classifyImageResponse(response, { usedGet });
}
/** One plain line for the evidence table, reused by the renderer if it wants it. */
export function describeImageProbe(probe) {
if (!probe) return 'not checked';
if (!probe.checked) return `not checked — ${probe.reason}`;
const size = probe.bytes !== null
? formatBytes(probe.bytes)
: (probe.bytesAtLeast !== null ? `at least ${formatBytes(probe.bytesAtLeast)}` : 'size not reported');
const verdict = {
too_large: `over the ${formatBytes(IMAGE_SIZE_LIMIT)} WhatsApp limit`,
not_an_image: 'not an image',
type_weak: 'WebP, which not every previewer renders',
unreachable: 'the image does not load'
}[probe.problem];
return `${probe.status} ${probe.type || 'type not reported'}, ${size}${verdict ? ` — ${verdict}` : ''}`;
}
/** Findings for the probe result. Warn at most: an unhelpful image never fails the page. */
function imageProbeFindings(probe) {
if (!probe) return [];
if (!probe.checked) {
return [{
level: 'info',
code: 'og_image_not_checked',
message: `The og:image was not fetched: ${probe.reason}. Nothing was judged about it.`
}];
}
switch (probe.problem) {
case 'unreachable':
return [{
level: 'warn',
code: 'og_image_unreachable',
message: `The og:image address answered ${probe.status}, so WhatsApp, Telegram and Facebook draw the card without a picture.`,
fix: 'Point og:image at a file that returns 200, or remove the tag so the missing image is visible in the HTML.'
}];
case 'too_large':
return [{
level: 'warn',
code: 'og_image_too_large',
message: `The og:image is ${formatBytes(probe.bytes ?? probe.bytesAtLeast)} — WhatsApp drops preview images over 300 KB, so the card appears without a picture.`,
fix: 'Resize the card to 1200x630 and compress it under 300 KB.'
}];
case 'not_an_image':
return [{
level: 'warn',
code: 'og_image_not_an_image',
message: `The og:image address returns ${probe.type} instead of an image, so previewers draw a blank or wrong card.`,
fix: 'Point og:image at a PNG or JPEG file, not at a page.'
}];
case 'type_weak':
return [{
level: 'info',
code: 'og_image_type_weak',
message: 'The og:image is a WebP file. WhatsApp and some older previewers do not render WebP, so the card may appear without a picture — a PNG or JPEG is safer.',
fix: 'Export the card as PNG or JPEG for the og:image tag.'
}];
default:
return [];
}
}
/**
* Header audit. Returns findings only — the caller decides the state.
* `url` is the FINAL url: HSTS is only meaningful on an https page.
@@ -346,7 +574,7 @@ function summarise(state, findings, ctx) {
* Pure analysis over fetchFollowing() output {hops, final, headers, body, truncated}.
* Returns { state, summary, findings, evidence, preview, redirects, analysedAt }.
*/
export function analyseHttp(result, { host, now = Date.now() } = {}) {
export function analyseHttp(result, { host, now = Date.now(), imageProbe = null } = {}) {
const source = result || {};
const hops = Array.isArray(source.hops) ? source.hops : [];
const final = source.final || null;
@@ -512,6 +740,14 @@ export function analyseHttp(result, { host, now = Date.now() } = {}) {
});
}
// Only ever present when analyseHttpWithImageProbe() actually fetched the image. The pure
// analyser stays pure, so a unit test that calls it directly sees exactly the old report.
if (preview.hasImage && imageProbe) {
preview.imageProbe = imageProbe;
findings.push(...imageProbeFindings(imageProbe));
evidence.push({ label: 'og:image check', value: describeImageProbe(imageProbe) });
}
if (preview.title) evidence.push({ label: 'preview title', value: preview.title });
if (preview.image) evidence.push({ label: 'preview image', value: preview.image });
evidence.push({ label: 'favicon', value: preview.favicon || 'none declared' });
@@ -530,6 +766,26 @@ export function analyseHttp(result, { host, now = Date.now() } = {}) {
};
}
/**
* analyseHttp() plus the one network step it cannot do itself: fetching the declared og:image.
*
* The probe runs only when there is an absolute http(s) image to fetch AND the page was a real
* page. A firewall or challenge answer returns `not-evaluated` with no preview, and an image tag on
* a challenge page says nothing about the site, so nothing is fetched there.
*
* The analyser is called twice on purpose: the first pass is pure and cheap and tells us whether a
* probe is warranted at all, and the second pass merges the result so the report has a single
* source of truth for its findings. `now` is pinned once so both passes agree on analysedAt.
*/
export async function analyseHttpWithImageProbe(result, { host, now = Date.now(), lookup, request, timeoutMs } = {}) {
const first = analyseHttp(result, { host, now });
if (!first.preview || !first.preview.hasImage) return first;
if (first.state === 'not-evaluated') return first;
const imageProbe = await probePreviewImage(first.preview.image, { lookup, request, timeoutMs });
return analyseHttp(result, { host, now, imageProbe });
}
export function describeFetchError(err) {
const code = err && err.code ? err.code : null;
switch (code) {
@@ -557,14 +813,19 @@ export function describeFetchError(err) {
}
}
/** The check entry point: one redirect-following fetch, then the pure analyser. */
export async function checkHttp(input, { lookup } = {}) {
/**
* The check entry point: one redirect-following fetch, one guarded HEAD at the declared og:image,
* then the pure analyser.
*/
export async function checkHttp(input, { lookup, request } = {}) {
const checkedAt = new Date().toISOString();
const host = hostOf(input);
try {
const result = await fetchFollowing(input, { lookup });
const analysis = analyseHttp(result, { host });
// `request` is the transport seam for the image probe only; the page fetch stays inside
// fetchFollowing so every request still goes through net-guard.
const analysis = await analyseHttpWithImageProbe(result, { host, lookup, request });
return {
id: 'http',
state: analysis.state,
+455 -32
View File
@@ -1,21 +1,55 @@
// tls.mjs — certificate health for one host.
// tls.mjs — certificate health for the address a visitor actually ends up on.
//
// Two layers, deliberately separated:
// inspectTls() — the one network call (net-guard owns it)
// summariseTls() — pure function over what that call returned, so every branch is testable
// offline from a fixture and nothing in it can touch the network.
// inspectTls() / discoverFinalHost() — the network calls (net-guard owns them)
// summariseTls() — pure function over what those calls returned, so every
// branch is testable offline and cannot touch the network.
//
// Why the redirect walk exists: a browser that opens example.com and is redirected to
// www.example.com validates the certificate of www.example.com. Judging only the typed host
// reported a healthy certificate on a domain whose real site was serving an expired one, which is
// the opposite of what the visitor meets. The typed host's certificate is still read and shown —
// it is the first thing a visitor meets — but the verdict follows the chain to its end.
//
// The rule that shapes the signature section: RFC 5280 exempts the trust anchor, so a self-signed
// root is never judged. A SHA-1 root on an old enterprise CA is not the fault of the site being
// checked; a SHA-1 leaf or intermediate is a real defect. So the signature loop skips trust
// anchors and judges everything else.
import { inspectTls } from '../lib/net-guard.mjs';
import { inspectTls, requestOnce, guardHop, MAX_REDIRECTS } from '../lib/net-guard.mjs';
const DAY_MS = 86_400_000;
const URGENT_DAYS = 14;
const WARN_DAYS = 30;
// Redirect discovery is a side question ("where does the browser end up"), so it gets a smaller
// budget than the certificate read. A site that redirects slowly must not turn a 6 s check into a
// 30 s one; when the budget runs out the report falls back to the typed host and says so.
const REDIRECT_BUDGET_MS = 5000;
const HOP_TIMEOUT_MS = 3000;
const HOP_MAX_BYTES = 32 * 1024;
// A server that refuses HEAD still answers the question with a GET; only these two mean "refused",
// and the GET is capped so a redirecting page cannot download a body just to hand back a Location.
const HEAD_REFUSED = new Set([405, 501]);
const TLS_FAILURE_CODES = new Set(['tls_expired', 'tls_invalid']);
// Short clauses for the one-sentence summary. The finding messages are longer because they carry
// the fix; the summary has to fit in a line above the badge and still name the failing address.
const PROBLEM_CLAUSE = {
tls_expired: 'has expired',
tls_expiring_soon: 'expires in a few days',
tls_expiring: 'expires within the month',
tls_expiry_unknown: 'has an expiry date that could not be read',
tls_name_mismatch: 'is issued for a different name',
tls_no_san: 'does not name that address',
tls_untrusted_chain: 'cannot be verified',
tls_self_signed_leaf: 'is self-signed',
tls_weak_signature_leaf: 'uses an outdated signature',
tls_weak_signature_intermediate: 'uses an outdated signature',
tls_chain_short: 'is missing its intermediate certificate',
tls_chain_order: 'is sent in the wrong order'
};
const LEVEL_RANK = { ok: 0, info: 1, warn: 2, fail: 3 };
const MONTHS = {
@@ -349,33 +383,422 @@ export function describeHandshakeError(err) {
}
}
/**
* The check entry point: one connection, then the pure analyser.
* A failed handshake yields 'not-evaluated' with the reason — never 'fail'.
*/
export async function checkTls(host, { lookup } = {}) {
const checkedAt = new Date().toISOString();
// --- redirect discovery ----------------------------------------------------------------------
function hostOfUrl(value) {
try {
const info = await inspectTls(host, { lookup });
const analysis = summariseTls(info, { host: info.host || host });
return {
id: 'tls',
state: analysis.state,
summary: analysis.summary,
evidence: analysis.evidence,
findings: analysis.findings,
checkedAt,
fromCache: false
};
} catch (err) {
return {
id: 'tls',
state: 'not-evaluated',
summary: describeHandshakeError(err),
evidence: [{ label: 'address', value: String(host) }],
findings: [],
checkedAt,
fromCache: false
};
return new URL(value).hostname.toLowerCase() || null;
} catch {
return null;
}
}
function schemeOfUrl(value) {
try {
return new URL(value).protocol.replace(':', '').toLowerCase();
} catch {
return null;
}
}
/** Same address, ignoring a trailing slash and the fragment — used only to spot a loop. */
function normaliseUrl(value) {
try {
const url = new URL(value);
url.hash = '';
return url.toString().replace(/\/$/, '');
} catch {
return String(value);
}
}
async function fetchHop(url, { lookup, request, timeoutMs }) {
let res = await request(url, { lookup, method: 'HEAD', maxBytes: HOP_MAX_BYTES, timeoutMs });
if (HEAD_REFUSED.has(res.status)) {
res = await request(url, { lookup, method: 'GET', maxBytes: HOP_MAX_BYTES, timeoutMs });
}
return res;
}
/**
* Follow the chain a browser would follow and report where it ends. Never throws for a site-level
* problem: "we could not follow the redirect" is not evidence that a certificate is broken, and
* turning it into a finding is the exact dishonesty this module is meant to avoid.
*
* `request` is injectable so tests can drive a redirect chain without a socket.
* Returns { hops, finalUrl, finalHost, finalTls, stop } where stop is null on a clean landing and
* otherwise { kind, url, host, code?, message? } with kind one of
* 'blocked' | 'hop_error' | 'loop' | 'too_many' | 'timeout' | 'bad_location'.
*/
export async function discoverFinalHost(rawHost, {
lookup,
request = requestOnce,
maxRedirects = MAX_REDIRECTS,
budgetMs = REDIRECT_BUDGET_MS
} = {}) {
const deadline = Date.now() + budgetMs;
const hops = [];
const seen = new Set();
let current = /^[a-z][a-z0-9+.-]*:\/\//i.test(rawHost) ? rawHost : `https://${rawHost}`;
for (let i = 0; i <= maxRedirects; i += 1) {
const remaining = deadline - Date.now();
if (remaining < 300) {
return {
hops,
finalUrl: current,
finalHost: hostOfUrl(current),
finalTls: null,
stop: {
kind: 'timeout',
url: current,
host: hostOfUrl(current),
message: 'The redirect chain did not finish inside the time budget.'
}
};
}
const key = normaliseUrl(current);
if (seen.has(key)) {
return {
hops,
finalUrl: current,
finalHost: hostOfUrl(current),
finalTls: null,
stop: { kind: 'loop', url: current, host: hostOfUrl(current), message: 'The redirect chain loops.' }
};
}
seen.add(key);
let res;
try {
res = await fetchHop(current, { lookup, request, timeoutMs: Math.min(HOP_TIMEOUT_MS, remaining) });
} catch (err) {
const host = hostOfUrl(current);
// Record the hop that was attempted: the visitor's browser stops here, so the report has to
// be able to name it even though no response came back.
hops.push({ url: current, status: 0, location: null, host, failed: true });
return {
hops,
finalUrl: current,
finalHost: host,
finalTls: null,
stop: {
kind: 'hop_error',
url: current,
host,
code: (err && err.code) || 'request_failed',
message: (err && err.message) || 'The request failed.'
}
};
}
const url = res.url || current;
const host = hostOfUrl(url);
const location = res.headers && res.headers.location ? res.headers.location : null;
hops.push({ url, status: res.status, location, host });
if (res.status >= 300 && res.status < 400 && location) {
let next;
try {
next = new URL(location, url).toString();
} catch {
return {
hops,
finalUrl: url,
finalHost: host,
finalTls: null,
stop: { kind: 'bad_location', url: location, host, message: 'The redirect target could not be read.' }
};
}
// Every hop restarts at the guard: a public host that redirects to 192.168.1.1 must not make
// this service dial the LAN.
const blocked = guardHop(next);
if (blocked) {
return {
hops,
finalUrl: next,
finalHost: hostOfUrl(next),
finalTls: null,
stop: { kind: 'blocked', url: next, host: hostOfUrl(next), code: blocked.code, message: blocked.message }
};
}
if (seen.has(normaliseUrl(next))) {
return {
hops,
finalUrl: next,
finalHost: hostOfUrl(next),
finalTls: null,
stop: { kind: 'loop', url: next, host: hostOfUrl(next), message: 'The redirect chain loops.' }
};
}
current = next;
continue;
}
// The certificate read off this response's own socket is the one a browser validates here, so
// no second handshake is opened when it is available (AGENTS.md rule 6).
return { hops, finalUrl: url, finalHost: host, finalTls: res.tls || null, stop: null };
}
return {
hops,
finalUrl: current,
finalHost: hostOfUrl(current),
finalTls: null,
stop: {
kind: 'too_many',
url: current,
host: hostOfUrl(current),
message: `More than ${maxRedirects} redirects.`
}
};
}
// --- redirect-aware assembly -----------------------------------------------------------------
function problemClause(analysis) {
const worst = analysis.findings.find((finding) => finding.level === analysis.state)
|| analysis.findings.find((finding) => finding.level === 'fail' || finding.level === 'warn');
return (worst && PROBLEM_CLAUSE[worst.code]) || 'has a certificate problem';
}
/**
* One sentence that names the address that actually failed. When both ends are healthy the final
* host's own summary already says the right thing, so it is reused rather than rewritten.
*/
function redirectSummary({ typed, final, typedHost, finalHost }) {
if (final.state === 'fail') {
return `The certificate at ${finalHost} ${problemClause(final)}, so the page a visitor lands on shows a browser warning.`;
}
if (typed.state === 'fail') {
return `The certificate at ${typedHost} ${problemClause(typed)}, so a visitor sees a browser warning before the redirect to ${finalHost} even starts.`;
}
if (final.state === 'warn') {
return `The certificate at ${finalHost} ${problemClause(final)}, so the page a visitor lands on still loads but needs fixing soon.`;
}
if (typed.state === 'warn') {
return `The certificate at ${typedHost} ${problemClause(typed)}, and it is the first thing a visitor meets before the redirect to ${finalHost}.`;
}
return final.summary;
}
function certificateLine(analysis) {
const issued = analysis.evidence.find((row) => row.label === 'issued to');
const until = analysis.evidence.find((row) => row.label === 'valid until');
const parts = [];
if (issued) parts.push(`issued to ${issued.value}`);
if (until) parts.push(`valid until ${String(until.value).slice(0, 10)}`);
return parts.length > 0 ? parts.join(', ') : 'read, but nothing usable in it';
}
function redirectLine(hops) {
if (!Array.isArray(hops) || hops.length === 0) return 'none';
const trail = [];
for (const hop of hops) {
const name = hop.host || hop.url;
if (trail[trail.length - 1] !== name) trail.push(name);
}
return `${trail.join(' -> ')} (${hops.length} request${hops.length === 1 ? '' : 's'})`;
}
function describeHopFailure(stop) {
switch (stop.code) {
case 'tls_expired': return 'its certificate has expired';
case 'tls_invalid': return 'its certificate cannot be verified';
case 'timeout': return 'it did not answer in time';
case 'refused': return 'the server refused the connection';
case 'dns_nxdomain': return 'that name did not resolve';
default: return 'the connection failed';
}
}
/**
* guardHop's messages are written for the form ("Enter a domain name, not an IP address"), which
* reads wrongly when the address came from a redirect. Say why this service will not follow it.
*/
function describeBlockedTarget(stop) {
switch (stop.code) {
case 'ip_literal': return 'it points at a bare IP address rather than a domain name';
case 'private_host': return 'it is a private address';
case 'bad_port': return 'it uses a port this tool will not open';
case 'bad_scheme': return 'it is not an http or https address';
default: return 'this tool will not open it';
}
}
function envelope(state, summary, evidence, findings, checkedAt) {
return { id: 'tls', state, summary, evidence, findings, checkedAt, fromCache: false };
}
/**
* The check entry point: read the typed host's certificate, find where a browser would end up,
* then judge the certificate at that address too. A failed handshake on the typed host still
* yields 'not-evaluated' with the reason — never 'fail'.
*
* `inspect` and `request` are injectable seams for the offline tests; production never passes them.
*/
export async function checkTls(host, { lookup, inspect = inspectTls, request = requestOnce } = {}) {
const checkedAt = new Date().toISOString();
let typedInfo;
try {
typedInfo = await inspect(host, { lookup });
} catch (err) {
return envelope('not-evaluated', describeHandshakeError(err), [{ label: 'address', value: String(host) }], [], checkedAt);
}
const typedHost = String(typedInfo.host || host).toLowerCase();
const typed = summariseTls(typedInfo, { host: typedHost });
const discovery = await discoverFinalHost(typedHost, { lookup, request });
const finalHost = discovery.finalHost || typedHost;
const crossed = finalHost !== typedHost;
let finalInfo = null;
let stop = discovery.stop;
if (crossed && !stop) {
if (discovery.finalTls) {
finalInfo = { host: finalHost, cert: discovery.finalTls, chain: discovery.finalTls.chain || [] };
} else if (schemeOfUrl(discovery.finalUrl) === 'https') {
// No certificate rode back on the redirect's own socket. This is the one extra handshake
// the check is allowed, and it is only spent when the final address is https.
try {
finalInfo = await inspect(finalHost, { lookup });
} catch (err) {
stop = {
kind: 'hop_error',
url: discovery.finalUrl,
host: finalHost,
code: (err && err.code) || 'request_failed',
message: (err && err.message) || 'The request failed.'
};
}
}
} else if (crossed && stop && stop.kind === 'hop_error' && stop.host !== typedHost && TLS_FAILURE_CODES.has(stop.code)) {
// The chain died on a certificate error at a redirect target. Read that certificate anyway
// (rejectUnauthorized is off in inspectTls) so the report can say why it is broken instead of
// only that something went wrong.
try {
finalInfo = await inspect(stop.host, { lookup });
} catch {
finalInfo = null;
}
}
const findings = [];
const evidence = [];
// --- both ends read: judge the final certificate, still show the typed one ------------------
if (crossed && finalInfo) {
const final = summariseTls(finalInfo, { host: finalHost });
findings.push(...final.findings);
// The typed certificate is the first thing a visitor meets, so its problems still count. Its
// 'all good' rows would only repeat the final host's, so they are summarised in one line.
// Identical messages (two hosts on the same misconfigured server) are collapsed: a bullet
// repeated twice reads like two separate faults.
const seenFindings = new Set(findings.map((finding) => `${finding.code}|${finding.message}`));
for (const finding of typed.findings) {
if (finding.level === 'ok') continue;
const key = `${finding.code}|${finding.message}`;
if (seenFindings.has(key)) continue;
seenFindings.add(key);
findings.push(finding);
}
if (typed.state === 'ok') {
findings.push({
level: 'ok',
code: 'tls_redirect_typed_ok',
message: `The address you typed (${typedHost}) redirects to ${finalHost}, and its own certificate is also valid.`
});
}
evidence.push({ label: 'checked at', value: discovery.finalUrl || finalHost });
evidence.push({
label: 'typed address',
value: typedHost,
note: 'where the check started, before any redirect'
});
evidence.push(...final.evidence);
evidence.push({
label: 'certificate at typed address',
value: certificateLine(typed),
note: `${typedHost}, read before the redirect was followed`
});
evidence.push({ label: 'redirects', value: redirectLine(discovery.hops) });
const state = worstLevel(findings);
return envelope(state, redirectSummary({ typed, final, typedHost, finalHost }), evidence, findings, checkedAt);
}
// --- the redirect could not be followed, or landed somewhere without a certificate ---------
findings.push(...typed.findings);
evidence.push({ label: 'checked at', value: crossed ? typedHost : (discovery.finalUrl || typedHost) });
evidence.push(...typed.evidence);
const sawRedirect = discovery.hops.some((hop) => hop.location);
evidence.push({ label: 'redirects', value: sawRedirect ? redirectLine(discovery.hops) : 'none' });
let summary = typed.summary;
if (stop) {
if (stop.kind === 'blocked') {
findings.push({
level: 'info',
code: 'tls_redirect_unchecked',
message: `The site redirects to ${stop.url}, but ${describeBlockedTarget(stop)}, so the certificate there was not checked. The verdict above is for ${typedHost} only.`
});
} else if (stop.kind === 'hop_error') {
const atTypedHost = stop.host === typedHost;
if (!atTypedHost && TLS_FAILURE_CODES.has(stop.code)) {
// The browser stops at that hop with a warning, so this is a real fault — not "skipped".
findings.push({
level: 'fail',
code: 'tls_redirect_hop_failed',
message: `The redirect to ${stop.host} stops at a certificate warning because ${describeHopFailure(stop)}, so a visitor never reaches the page.`,
fix: 'Fix the certificate at that address, or stop redirecting to it.'
});
summary = `The redirect to ${stop.host} stops at a certificate warning, so a visitor never reaches the page.`;
} else if (!atTypedHost || typed.state !== 'fail') {
findings.push({
level: 'info',
code: 'tls_redirect_unchecked',
message: `The redirect to ${stop.host || stop.url} could not be followed (${describeHopFailure(stop)}), so the certificate there was not checked. The verdict above is for ${typedHost} only.`
});
}
} else if (stop.kind === 'loop' || stop.kind === 'too_many') {
findings.push({
level: 'info',
code: 'tls_redirect_unresolved',
message: `The site redirects in a loop and never reaches a page, so only the certificate at ${typedHost} was judged.`
});
} else if (stop.kind === 'timeout') {
findings.push({
level: 'info',
code: 'tls_redirect_unchecked',
message: `The redirect chain did not finish in time, so the certificate at the address a visitor lands on was not checked. The verdict above is for ${typedHost} only.`
});
} else {
findings.push({
level: 'info',
code: 'tls_redirect_unchecked',
message: `The redirect target could not be read, so the certificate at the address a visitor lands on was not checked. The verdict above is for ${typedHost} only.`
});
}
} else if (crossed) {
// It reached the end, but the end is plain http: there is no certificate there to judge. The
// http check owns the downgrade verdict; this one only records that nothing was measured.
findings.push({
level: 'info',
code: 'tls_final_not_https',
message: `The site redirects visitors to ${discovery.finalUrl}, which is plain http, so there is no certificate at the address they end on.`
});
summary = typed.state === 'ok'
? `The certificate at ${typedHost} is valid, but the site sends visitors on to ${discovery.finalUrl} over plain http, where there is no certificate.`
: `The certificate at ${typedHost} ${problemClause(typed)}, and the site then sends visitors to ${discovery.finalUrl} over plain http.`;
}
return envelope(worstLevel(findings), summary, evidence, findings, checkedAt);
}
+6 -2
View File
@@ -282,7 +282,11 @@ export async function requestOnce(rawUrl, {
timeoutMs = DEFAULT_TIMEOUT_MS,
maxBytes = DEFAULT_MAX_BYTES,
method = 'GET',
userAgent = defaultUserAgent()
userAgent = defaultUserAgent(),
// A caller fetching something that is NOT a page (an og:image, a robots.txt) can say what it
// wants. Without this, a server that content-negotiates answers text/html for an image URL and
// the report would call a perfectly good image "not an image".
accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
} = {}) {
const { host, port } = parseTarget(rawUrl);
const parsed = new URL(rawUrl.includes('://') ? rawUrl : `https://${rawUrl}`);
@@ -311,7 +315,7 @@ export async function requestOnce(rawUrl, {
headers: {
host,
'user-agent': userAgent,
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
accept,
'accept-language': 'en-MY,en;q=0.9',
'accept-encoding': 'identity',
connection: 'close'
+32 -7
View File
@@ -1,4 +1,5 @@
import { layout, esc, abs, PREFIX, badge, form, evidenceTable, findingList, whatsappPreview } from './lib/html.mjs';
import { describeImageProbe } from './checks/http.mjs';
const STATE_LABEL = {
ok: 'Looks right',
@@ -261,9 +262,11 @@ 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.</li>
<li>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.</li>
<li>One connection is made per check: a DNS lookup, a TLS handshake, or a single HTTPS request
capped at 2 MB and ten seconds. The certificate is read from the same socket as the request, so
checking the padlock does not create a second visit.</li>
<li>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.</li>
<li>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.</li>
</ol>
@@ -276,8 +279,9 @@ network panel of your browser and you will see one stylesheet, served by this se
on WhatsApp is not re-fetched every time somebody opens it. Nothing is written to disk.</p>
<h2>How to prove it</h2>
<p>Point the checker at a host you control and watch its log. You should see exactly one connection
from this service, carrying the user agent
<p>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
<code>og:image</code> — all carrying the user agent
<span class="mono">HoeleeCheck/1.0 (+https://www.hoelee.com/check/about/)</span>, and nothing else.
If you see more, or from somewhere unexpected, that is a bug worth reporting.</p>
@@ -346,6 +350,26 @@ export function reportPage({ host, results, httpResult, checkedAt, stale = false
? whatsappPreview(httpResult.preview, host)
: '';
// A declared image is not a working image. The badge follows what the HEAD found, not the tag:
// "og:image is present" and "the card shows a picture" are different claims.
const imageProbe = httpResult && httpResult.preview ? httpResult.preview.imageProbe : null;
const imageBadge = !httpResult || !httpResult.preview || !httpResult.preview.hasImage
? stateBadge('warn')
: (!imageProbe || !imageProbe.checked || !imageProbe.problem ? stateBadge('ok') : stateBadge('warn'));
// When the site redirects to another address, say which certificate was judged and where the
// visitor actually lands, otherwise a pass on example.com reads as a pass on www.example.com.
const tlsResult = results.find((r) => r.id === 'tls');
const tlsAt = tlsResult && tlsResult.evidence
? tlsResult.evidence.find((row) => row.label === 'checked at')
: null;
const tlsTyped = tlsResult && tlsResult.evidence
? tlsResult.evidence.find((row) => row.label === 'typed address')
: null;
const tlsNote = tlsAt && tlsTyped
? `<p class="faint">You typed <span class="mono">${esc(tlsTyped.value)}</span>; the certificate was judged at <span class="mono">${esc(tlsAt.value)}</span>, where the site sends visitors.</p>`
: '';
const body = `
<p class="faint"><a href="${esc(PREFIX)}/">Hoelee Check</a> · report for</p>
<h1>${esc(host)}</h1>
@@ -359,13 +383,14 @@ export function reportPage({ host, results, httpResult, checkedAt, stale = false
</div>
${preview ? `<section class="card">
<div class="check-head"><h2>What your customer sees</h2>${httpResult && httpResult.preview && httpResult.preview.hasImage ? stateBadge('ok') : stateBadge('warn')}</div>
<div class="check-head"><h2>What your customer sees</h2>${imageBadge}</div>
<p class="muted">Paste your link into a WhatsApp chat and this is the card that appears. No image,
no description, or a generic title makes a real business look like a forwarded scam.</p>
${preview}
${imageProbe ? `<p class="faint">The declared image was fetched once: ${esc(describeImageProbe(imageProbe))}.</p>` : ''}
</section>` : ''}
${section({ id: 'tls', title: 'Certificate & HTTPS', result: results.find((r) => r.id === 'tls') })}
${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') })}
+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);
});