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

+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') })}