Files
hoelee-check/src/server.mjs
T
hoelee 8925d10424 feat(check): seven checks, and the one picture worth having
Adds mail-transport (MTA-STS + policy file, TLS-RPT, BIMI) and hardening (compression,
CAA vs the issuing CA, cookie flags, version banners). Wiring them exposed a real gap:
net-guard pinned accept-encoding to identity, so the compression question could only ever
be answered 'not measured'. requestOnce now takes acceptEncoding, decompresses, and returns
both the wire size and the decoded size - hoelee.com measures 39.6 KB against 119.4 KB.

The hub gets a CSS trust-flow diagram instead of a picture: four boxes and three arrows
cost no request, stay sharp, and can be corrected without re-exporting anything. The
1200x630 social card is drawn in HTML and screenshotted, because a diffusion model renders
'technical' as soft glyph soup that turns to mud at WhatsApp thumbnail size.
2026-11-10 19:20:16 +08:00

297 lines
11 KiB
JavaScript

// hoelee-check — the whole service. Node 24, zero dependencies, no build step.
//
// Mounted by nginx at https://www.hoelee.com/check/ and therefore prefix-aware: every path this
// service emits starts with /check so it works unchanged in a browser, behind the proxy, and in a
// shared WhatsApp link.
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import * as cache from './lib/cache.mjs';
import * as ratelimit from './lib/ratelimit.mjs';
import { parseTarget, NetGuardError, defaultUserAgent } from './lib/net-guard.mjs';
import { PREFIX } from './lib/html.mjs';
import {
hubPage, sslPage, emailAuthPage, headersPage, aboutPage, reportPage, errorPage
} from './pages.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT || 3000);
const HOST = process.env.HOST || '0.0.0.0';
const VERSION = process.env.APP_VERSION || '1.0.0';
const COMMIT = process.env.APP_COMMIT || 'dev';
// The check modules are written independently of this file; accept either export shape so a
// naming difference between modules never takes the service down.
const loaders = {
'who-holds': () => import('./checks/who-holds.mjs'),
'mail-auth': () => import('./checks/mail-auth.mjs'),
'mail-transport': () => import('./checks/mail-transport.mjs'),
tls: () => import('./checks/tls.mjs'),
'http': () => import('./checks/http.mjs'),
'host-shape': () => import('./checks/host-shape.mjs'),
hardening: () => import('./checks/hardening.mjs')
};
const modules = {};
for (const [id, load] of Object.entries(loaders)) {
try {
const mod = await load();
const fn = mod.check || mod[`check${id.replace(/(^|-)(\w)/g, (_, __, c) => c.toUpperCase())}`];
if (typeof fn !== 'function') throw new Error(`no check() export in checks/${id}.mjs`);
modules[id] = fn;
} catch (err) {
console.error(`[startup] check "${id}" is unavailable: ${err.message}`);
}
}
const STATIC = {
'/assets/style.css': { file: 'public/style.css', type: 'text/css; charset=utf-8' },
// The link-preview card. 1200x630, drawn in HTML and screenshotted, so it carries real type
// instead of the soft glyph soup a diffusion model produces at thumbnail size.
'/assets/og.png': { file: 'public/og.png', type: 'image/png' }
};
function send(res, status, headers, body) {
const payload = typeof body === 'string' ? Buffer.from(body) : body;
res.writeHead(status, {
'content-type': 'text/html; charset=utf-8',
'content-length': payload.length,
'x-content-type-options': 'nosniff',
'referrer-policy': 'strict-origin-when-cross-origin',
'x-frame-options': 'DENY',
'content-security-policy':
"default-src 'none'; img-src 'self' https: data:; style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
...headers
});
res.end(payload);
}
function clientIp(req) {
const forwarded = req.headers['x-forwarded-for'];
if (typeof forwarded === 'string' && forwarded.length > 0) return forwarded.split(',')[0].trim();
return (req.socket && req.socket.remoteAddress) || 'unknown';
}
/**
* Run every check for one host. Checks run in parallel, each cached separately, and a check that
* throws becomes a not-evaluated result rather than a 500 — a visitor must never get a blank page
* because one probe timed out.
*/
async function runChecks(host, { fresh = false, lookup } = {}) {
const wanted = Object.keys(modules);
const settled = await Promise.allSettled(wanted.map(async (id) => {
const key = `check:${id}:${host}`;
if (fresh) cache.drop(key);
return cache.cached(key, (value) => cache.ttlFor(value.state), async () => {
const started = Date.now();
const result = await modules[id](host, { lookup });
return { ...result, id, checkedAt: result.checkedAt || new Date().toISOString(), ms: Date.now() - started };
});
}));
const results = settled.map((outcome, index) => {
const id = wanted[index];
if (outcome.status === 'fulfilled') return outcome.value;
const err = outcome.reason;
const code = err instanceof NetGuardError ? err.code : 'error';
return {
id,
state: 'not-evaluated',
summary: messageForError(code),
evidence: [{ label: 'Reason', value: code }],
findings: [{ level: 'info', code, message: messageForError(code) }],
checkedAt: new Date().toISOString(),
fromCache: false,
ms: 0
};
});
const httpResult = results.find((r) => r.id === 'http') || null;
return { results, httpResult };
}
function messageForError(code) {
switch (code) {
case 'timeout': return 'That site did not answer in time, so this part was skipped.';
case 'refused': return 'The server refused the connection, so this part was skipped.';
case 'dns_nxdomain': return 'That domain does not resolve, so this part was skipped.';
case 'private_address': return 'That domain points at a private address, which this service will not open.';
case 'tls_expired': return 'The certificate has expired — a browser would show a warning page.';
case 'tls_invalid': return 'The certificate could not be verified, so the page could not be read safely.';
default: return 'This part of the check could not be completed.';
}
}
function stripPrefix(pathname) {
if (pathname === PREFIX) return '/';
if (pathname.startsWith(`${PREFIX}/`)) return pathname.slice(PREFIX.length);
return null;
}
function redirect(res, location, status = 302) {
res.writeHead(status, { location, 'content-length': 0, 'cache-control': 'no-store' });
res.end();
}
async function handle(req, res) {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const route = stripPrefix(url.pathname);
if (route === null) {
return send(res, 404, {}, errorPage({ title: 'Not here', message: 'This service lives under /check/.', status: 404 }).html);
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
return send(res, 405, { allow: 'GET, HEAD' }, 'Method not allowed');
}
// static
const asset = STATIC[route];
if (asset) {
const body = await readFile(path.join(HERE, asset.file));
res.writeHead(200, {
'content-type': asset.type,
'content-length': body.length,
'cache-control': 'public, max-age=86400',
'x-content-type-options': 'nosniff'
});
return res.end(req.method === 'HEAD' ? undefined : body);
}
if (route === '/api/health') {
return send(res, 200, {
'cache-control': 'no-store',
'content-type': 'application/json; charset=utf-8'
}, JSON.stringify({ ok: true, version: VERSION, commit: COMMIT, checks: Object.keys(modules) }));
}
const indexable = {
'/': () => hubPage(),
'/ssl/': () => sslPage(),
'/spf-dkim-dmarc/': () => emailAuthPage(),
'/headers/': () => headersPage(),
'/about/': () => aboutPage()
};
// A report is addressed by its own URL so it can be forwarded. Every form posts back to its own
// page with ?d=, which redirects to the canonical report URL — that keeps one indexable URL per
// landing page and one shareable URL per result.
if (url.searchParams.get('d') && (route === '/' || route === '/ssl/' || route === '/spf-dkim-dmarc/' || route === '/headers/')) {
return startReport(req, res, url.searchParams.get('d'));
}
if (indexable[route]) {
const html = indexable[route]();
return send(res, 200, { 'cache-control': 'public, max-age=600' }, html);
}
if (route.startsWith('/report/')) {
const raw = decodeURIComponent(route.slice('/report/'.length)).replace(/\/+$/, '');
return renderReport(req, res, raw, { fresh: url.searchParams.get('fresh') === '1' });
}
return send(res, 404, {}, errorPage({
title: 'Page not found',
message: 'That address is not part of Hoelee Check. Start from the front page.',
status: 404
}).html);
}
async function startReport(req, res, rawDomain) {
const limited = ratelimit.hit(clientIp(req));
if (!limited.allowed) return tooMany(res, limited);
try {
const { host } = parseTarget(rawDomain);
return redirect(res, `${PREFIX}/report/${encodeURIComponent(host)}`);
} catch (err) {
const code = err instanceof NetGuardError ? err.code : 'bad_input';
return send(res, 400, { 'cache-control': 'no-store' },
errorPage({ title: 'That is not a domain we can check', message: err.message, status: 400 }).html);
}
}
async function renderReport(req, res, rawDomain, { fresh = false } = {}) {
let host;
try {
({ host } = parseTarget(rawDomain));
} catch (err) {
return send(res, 400, { 'cache-control': 'no-store' },
errorPage({ title: 'That is not a domain we can check', message: err.message, status: 400 }).html);
}
// Cached reports are served without spending a rate-limit token or touching the target: WhatsApp
// and Telegram prefetch every shared link, and that prefetch must not become a fresh scan.
const cacheKey = `report:${host}`;
const cachedReport = fresh ? null : cache.get(cacheKey);
if (cachedReport) {
return send(res, 200, reportHeaders(), reportPage({ ...cachedReport, stale: true }));
}
const limited = ratelimit.hit(clientIp(req));
if (!limited.allowed) return tooMany(res, limited);
const started = Date.now();
const { results, httpResult } = await runChecks(host, { fresh });
const checkedAt = new Date().toISOString();
const paid = {
host,
results,
httpResult,
checkedAt,
durationMs: Date.now() - started,
agent: defaultUserAgent()
};
cache.set(cacheKey, paid, cache.ttlFor(worst(results)));
console.log(`[check] ${host} ${results.map((r) => `${r.id}=${r.state}`).join(' ')} ${Date.now() - started}ms`);
return send(res, 200, reportHeaders(), reportPage(paid));
}
function reportHeaders() {
return {
'cache-control': 'public, max-age=300',
'x-robots-tag': 'noindex, nofollow'
};
}
function worst(results) {
const order = ['fail', 'warn', 'not-evaluated', 'ok'];
for (const state of order) if (results.some((r) => r.state === state)) return state;
return 'ok';
}
function tooMany(res, info) {
return send(res, 429, {
'retry-after': String(info.retryAfterSeconds),
'cache-control': 'no-store'
}, errorPage({
title: 'Too many checks from this connection',
message:
`This service allows ten checks a minute and a hundred a day, because it is one small machine ` +
`and every check dials out to somebody else's server. Try again in ${info.retryAfterSeconds} seconds.`,
status: 429
}).html);
}
const server = http.createServer((req, res) => {
handle(req, res).catch((err) => {
console.error('[error]', err && err.stack ? err.stack : err);
if (!res.headersSent) {
send(res, 500, { 'cache-control': 'no-store' },
errorPage({ title: 'Something went wrong', message: 'The check failed on our side, not yours. Try again in a moment.', status: 500 }).html);
} else {
res.end();
}
});
});
server.listen(PORT, HOST, () => {
console.log(`hoelee-check ${VERSION} (${COMMIT}) on http://${HOST}:${PORT}${PREFIX}/ — checks loaded: ${Object.keys(modules).join(', ') || 'none'}`);
});
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => {
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 5000).unref();
});
}