hoelee-check: v1 skeleton — net-guard, cache, ratelimit, router, pages, three checks
Zero-dependency Node service mounted at www.hoelee.com/check/. net-guard pins the resolved IP, re-validates every redirect hop, and refuses private ranges; the certificate is read off the same socket as the request. Pages: hub, certificate, email auth, redirects/preview, about, report. Argon review applied: optional-hardening wording, DKIM/SHA-1 root rules, neutral not-evaluated, cache-before-scan, single-connection TLS.
This commit is contained in:
commit
b2707f49f7
19 files changed
+4722
No files matched your search
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
.DS_Store
|
||||
*.log
|
||||
tmp/
|
||||
@@ -0,0 +1,77 @@
|
||||
# AGENTS.md — hoelee-check
|
||||
|
||||
Public health checks for a domain, served at `https://www.hoelee.com/check/`.
|
||||
Node 24, **zero npm dependencies**, no build step. Read `SPEC.md` before writing code.
|
||||
|
||||
## Directory jail
|
||||
|
||||
```
|
||||
src/server.mjs router + static + HTML render (owned by the parent session)
|
||||
src/lib/net-guard.mjs THE ONLY network entry point — do not bypass it, do not edit it
|
||||
src/lib/cache.mjs in-memory TTL cache
|
||||
src/lib/ratelimit.mjs per-IP counters
|
||||
src/checks/*.mjs one module per check + its .test.mjs sibling in test/
|
||||
src/i18n/en.mjs all visitor-facing copy
|
||||
test/*.test.mjs node:test, fake resolver + fake fetcher, never the real network
|
||||
```
|
||||
|
||||
A check module may import `src/lib/net-guard.mjs`, `src/lib/cache.mjs` and node builtins. It must not
|
||||
import `node:http`/`node:https` directly, must not use the global `fetch`, and must not open sockets.
|
||||
|
||||
## Hard rules
|
||||
|
||||
1. **No npm dependencies.** No Fastify, no mailauth, no better-sqlite3, no dotenv. `package.json`
|
||||
keeps `"dependencies": {}` and the lockfile stays absent.
|
||||
2. **Every network call goes through `net-guard`.** A `fetch()` anywhere in this repo is a bug: it
|
||||
cannot pin the resolved IP, which is the whole SSRF defence.
|
||||
3. **No query log, no analytics, no third-party request.** Not even a font. The about page promises
|
||||
this and a visitor can verify it in DevTools.
|
||||
4. **`not-evaluated` is a first-class state.** A WAF answering 403, a timeout, a SERVFAIL — none of
|
||||
them is a finding against the visitor's site. Render it neutral (slate, no red, no "!"), and count
|
||||
it separately in the summary ("2 verified, 1 skipped by firewall").
|
||||
5. **Never claim what the data cannot support.** The exact wording rules are in `SPEC.md` §5; the
|
||||
three that get broken most often:
|
||||
- DKIM: "No key found among the 13 common selectors; a custom selector cannot be found from DNS alone."
|
||||
Never "DKIM is not configured".
|
||||
- TLS: judge signature algorithms on the **leaf and intermediates only** — RFC 5280 exempts a
|
||||
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.
|
||||
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.
|
||||
8. **Tests never touch the network.** Inject `lookup` (DNS) and pass fixture objects into the pure
|
||||
analysers. `npm test` must pass with the machine offline.
|
||||
|
||||
## Checks contract
|
||||
|
||||
```js
|
||||
// every check module exports exactly this
|
||||
export async function check(input, { lookup, now = Date.now(), cache } = {}) -> {
|
||||
id: 'mail-auth' | 'tls' | 'http',
|
||||
state: 'ok' | 'warn' | 'fail' | 'not-evaluated',
|
||||
summary: string, // one plain-English line for a non-technical owner
|
||||
evidence: Array<{label, value, note?}>,
|
||||
findings: Array<{level: 'ok'|'info'|'warn'|'fail', code, message, fix?}>,
|
||||
checkedAt: string, // ISO
|
||||
fromCache: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Export the pure analysers too (`parseSpf`, `summariseTls`, `analyseHttp`, …) so tests can hit them
|
||||
directly. `state` is the worst finding level, and `not-evaluated` wins over everything.
|
||||
|
||||
## Commands
|
||||
|
||||
```
|
||||
npm test # node --test "test/*.test.mjs"
|
||||
node src/server.mjs # http://127.0.0.1:8088
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
Docker image `node:24-alpine`, no host port; `nginx-www-hoelee` proxies `location ^~ /check/` to
|
||||
`http://hoelee-check:3000`. The nginx location must carry `access_log off;` — an access log of
|
||||
`/check/report/<domain>` would be exactly the query log the site promises not to keep.
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
FROM node:24-alpine
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
PORT=3000 \
|
||||
HOST=0.0.0.0
|
||||
|
||||
WORKDIR /app
|
||||
# No dependencies to install: zero npm packages is a design rule, not a temporary state.
|
||||
COPY package.json ./
|
||||
COPY src ./src
|
||||
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:3000/check/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
||||
|
||||
CMD ["node", "src/server.mjs"]
|
||||
@@ -0,0 +1,125 @@
|
||||
# SPEC — hoelee-check v1
|
||||
|
||||
**What this is.** Three public health checks for a domain — certificate, email authentication, and
|
||||
redirects/link-preview — served at `https://www.hoelee.com/check/`. Free, no account, no upload.
|
||||
Built so a Malaysian SME owner can see, in about a second, the three things that make a small
|
||||
business look careless online.
|
||||
|
||||
**Why here and not on `tools.hoelee.com`.** That site's entire promise is "nothing is uploaded —
|
||||
it runs in your tab", enforced by a build gate that fails on any third-party request. One `fetch()`
|
||||
would destroy it. Server-backed tools therefore live on the sales hostname, where the links they
|
||||
earn point at the business.
|
||||
|
||||
**Why `/check/` and not a subdomain.** Google treats a domain *or subdomain* as a site for Search
|
||||
Console, site names and preferred sources, so a subdirectory is not a "site" — but links still pass
|
||||
to the host, the report URLs still earn authority for the sales hostname, one Search Console property
|
||||
covers everything, there is no new certificate, and killing the experiment means deleting one nginx
|
||||
`location`. `/check/` was a plain 404 before this project.
|
||||
|
||||
---
|
||||
|
||||
## Topology
|
||||
|
||||
```
|
||||
browser → https://www.hoelee.com/check/…
|
||||
→ nginx-www-hoelee (unRaid)
|
||||
location ^~ /check/ { access_log off; proxy_pass http://hoelee-check:3000; }
|
||||
→ container hoelee-check (node:24-alpine, no published port)
|
||||
```
|
||||
|
||||
`access_log off` is a requirement, not a preference: an access log of `/check/report/<domain>` is
|
||||
exactly the query log the site promises not to keep.
|
||||
|
||||
## Runtime
|
||||
|
||||
Node 24, plain `node:http`, `node:dns`, `node:tls`, `node:sqlite` not used, **zero npm
|
||||
dependencies**, no build step. Deploys as an image with nothing to compile. The precedent on this
|
||||
host is the link shortener (`linkd`): node:24-alpine, hand-rolled router, no deps.
|
||||
|
||||
Dependency call (Argon review): dropping `mailauth` is correct — its weight is live SMTP session
|
||||
evaluation and DKIM signature verification, neither of which a record-shape checker performs.
|
||||
|
||||
## Routes
|
||||
|
||||
| Route | Purpose | Robots |
|
||||
|---|---|---|
|
||||
| `/check/` | hub, one input, runs all three | index |
|
||||
| `/check/ssl/` | certificate landing page | index |
|
||||
| `/check/spf-dkim-dmarc/` | email auth landing page | index |
|
||||
| `/check/headers/` | redirects + link preview landing page | index |
|
||||
| `/check/about/` | what is queried, what is kept, how to verify | index |
|
||||
| `/check/report/<domain>` | the report | `noindex, nofollow` + `X-Robots-Tag` |
|
||||
| `/check/api/health` | `{ok, version, commit, checks}` | noindex |
|
||||
|
||||
Every form posts `?d=` back to its own page, which 302s to the canonical `/check/report/<domain>`.
|
||||
That keeps one indexable URL per landing page and one shareable URL per result.
|
||||
|
||||
## Honesty contract
|
||||
|
||||
> We query only the public hostname you type. No query log — a per-IP request counter that dies with
|
||||
> the process, and a short cache of the public DNS/HTTP answers so a link shared on WhatsApp is not
|
||||
> re-fetched every time somebody opens it. Every result is a URL you can forward.
|
||||
|
||||
Wording rules that must not drift (each one is enforced by a test or a review item):
|
||||
|
||||
- **DKIM**: "No key found among the 13 common selectors; a custom selector cannot be found from DNS
|
||||
alone." Never "DKIM is not configured".
|
||||
- **SPF**: report record shape only. A pass/fail needs a sender IP we do not have, and the page says so.
|
||||
- **TLS**: judge signature algorithms on the leaf and intermediates only. RFC 5280 exempts a trust
|
||||
anchor, so a SHA-1 *root* is not a failure.
|
||||
- **Headers**: a missing CSP, XCTO, XFO or Permissions-Policy is "optional hardening not present" at
|
||||
level `info`. Only a broken redirect chain, a malformed HSTS, or a 4xx/5xx final page is `fail`.
|
||||
- **`not-evaluated`**: neutral slate badge, never red; counted separately as "skipped by firewall" so
|
||||
the page cannot be screenshotted as a security verdict.
|
||||
|
||||
## States and caching
|
||||
|
||||
`state` is `ok | warn | fail | not-evaluated`, equal to the worst finding. TTL is 1 hour for a clean
|
||||
result and 5 minutes for anything else — a warning cached for an hour makes somebody who just fixed
|
||||
their DNS conclude the tool is broken.
|
||||
|
||||
## Network guard (the actual engineering)
|
||||
|
||||
Everything dials through `src/lib/net-guard.mjs`:
|
||||
|
||||
- hostname only — no IP literals, no userinfo, no scheme but http/https, ports 80/443 only;
|
||||
- resolve **once** through getaddrinfo, validate every A/AAAA answer, refuse the whole host if any
|
||||
answer is private (a mixed answer set is a rebinding attempt, not a mistake);
|
||||
- dial the pinned address while keeping the real hostname for SNI and `Host` — a re-resolve at
|
||||
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;
|
||||
- 10 requests a minute and 100 a day per IP, `Retry-After` on 429.
|
||||
|
||||
## Cut from v1 (Argon review, accepted)
|
||||
|
||||
- `/check/badge/<domain>.svg` — hotlinked badges invite cache stampedes and rate-limit headaches, and
|
||||
SMEs do not embed them.
|
||||
- `/zh/check/` — translate after the copy stops moving, not before.
|
||||
- `/check/api/report` — call the runner inside SSR until an external consumer exists.
|
||||
|
||||
## Kept, non-negotiable
|
||||
|
||||
net-guard and its tests, single-connection HTTPS + certificate read, the WhatsApp preview card, the
|
||||
neutral `not-evaluated` rendering, and `/check/about/` with its falsification test.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. `npm test` green with the machine offline (fake DNS + fixture objects only).
|
||||
2. net-guard refuses `127.0.0.1`, `169.254.169.254`, `10.0.0.1`, `[::1]`, `0.0.0.0`, `2130706433`,
|
||||
`[::ffff:127.0.0.1]`, a host resolving private, a mixed public/private answer set, a redirect to a
|
||||
private address, and a redirect to port 8443.
|
||||
3. A real report for `hoelee.com` returns three checks in ~1–2 s with `checkedAt`.
|
||||
4. A 403/bot-wall target renders `not-evaluated` with zero header findings.
|
||||
5. Report page carries `noindex` + `X-Robots-Tag`, has no horizontal overflow at 390 px, and makes
|
||||
zero third-party requests.
|
||||
6. 11th request in a minute returns 429 with `Retry-After`.
|
||||
7. nginx location carries `access_log off`.
|
||||
|
||||
## Open questions for the owner
|
||||
|
||||
- Does `www.hoelee.com` need a link to `/check/` in its own navigation before launch? Without one the
|
||||
pages are crawlable but undiscoverable.
|
||||
- Who answers the email that arrives when somebody's certificate is 3 days from expiry?
|
||||
@@ -0,0 +1,24 @@
|
||||
# Runs beside nginx-www-hoelee on unRaid. No published port: the only way in is the nginx location
|
||||
# `^~ /check/`, which must also carry `access_log off;` — an access log of /check/report/<domain>
|
||||
# would be exactly the query log this service promises not to keep.
|
||||
services:
|
||||
hoelee-check:
|
||||
build: .
|
||||
image: hoelee-check:1.0.0
|
||||
container_name: hoelee-check
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- PORT=3000
|
||||
- APP_COMMIT=${APP_COMMIT:-dev}
|
||||
networks:
|
||||
- web
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "5m"
|
||||
max-file: "2"
|
||||
|
||||
networks:
|
||||
web:
|
||||
external: true
|
||||
name: ${WEB_NETWORK:-nginx-www-hoelee_default}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "hoelee-check",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Hoelee Check — public DNS/TLS/HTTP health checks for Malaysian SMEs, served at www.hoelee.com/check/",
|
||||
"engines": { "node": ">=24" },
|
||||
"scripts": {
|
||||
"start": "node src/server.mjs",
|
||||
"test": "node --test test/"
|
||||
},
|
||||
"dependencies": {}
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
// http.mjs — redirects, security headers and link-preview metadata for one page.
|
||||
//
|
||||
// Same split as the TLS check: fetchFollowing() is the single network call, analyseHttp() is pure.
|
||||
// The certificate of the final hop rides on the same socket response — result.final.tls — so the
|
||||
// report can show TLS without opening a second connection to the host (AGENTS.md rule 6).
|
||||
//
|
||||
// Severity ruling (Argon, do not change):
|
||||
// HSTS missing on an https page → warn ("HTTPS works but browsers are not told…")
|
||||
// HSTS without max-age, or max-age < 180 days → fail
|
||||
// CSP / X-Content-Type-Options / X-Frame-Options
|
||||
// (or CSP frame-ancestors) / Referrer-Policy
|
||||
// / Permissions-Policy missing → info ("optional hardening not present")
|
||||
// version banner (x-powered-by, Server/x.y.z) → info
|
||||
// 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';
|
||||
|
||||
const HSTS_MIN_AGE = 15_552_000; // 180 days, per the HSTS guidance browsers follow
|
||||
const MAX_HOPS = 5;
|
||||
const HEAD_SCAN_LIMIT = 200_000;
|
||||
const LEVEL_RANK = { ok: 0, info: 1, warn: 2, fail: 3 };
|
||||
|
||||
export const BLOCKED_MESSAGE =
|
||||
"The site's firewall or CDN blocked our automated probe — that is normal protection, not a fault.";
|
||||
|
||||
const BLOCK_STATUSES = new Set([401, 403, 429, 503]);
|
||||
const CHALLENGE_MARKERS = [
|
||||
'cf-browser-verification',
|
||||
'just a moment',
|
||||
'attention required',
|
||||
'captcha',
|
||||
'challenge-platform',
|
||||
'checking your browser',
|
||||
'_cf_chl_opt',
|
||||
'enable javascript and cookies to continue'
|
||||
];
|
||||
const EDGE_HEADERS = [
|
||||
'cf-ray', 'cf-cache-status', 'x-vercel-id', 'x-akamai-request-id', 'x-sucuri-id',
|
||||
'x-amz-cf-id', 'x-fastly-request-id', 'x-azure-ref'
|
||||
];
|
||||
const EDGE_SERVERS = /cloudflare|akamai|sucuri|incapsula|imperva|cloudfront|fastly|vercel|azure|ddos-guard|gws/i;
|
||||
|
||||
export function worstLevel(findings, fallback = 'ok') {
|
||||
let state = fallback;
|
||||
for (const finding of findings) {
|
||||
if ((LEVEL_RANK[finding.level] ?? 0) > (LEVEL_RANK[state] ?? 0)) state = finding.level;
|
||||
}
|
||||
// 'info' is a finding level, not a check state: a page that only has optional hardening
|
||||
// missing is still an 'ok' report, with the notes shown as info rows.
|
||||
return state === 'info' ? 'ok' : state;
|
||||
}
|
||||
|
||||
function schemeOf(url) {
|
||||
if (typeof url !== 'string') return null;
|
||||
const match = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url);
|
||||
return match ? match[1].toLowerCase() : null;
|
||||
}
|
||||
|
||||
function resolveUrl(value, base) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const raw = value.trim();
|
||||
if (raw === '') return null;
|
||||
try {
|
||||
return new URL(raw, base || undefined).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normaliseUrl(url) {
|
||||
if (typeof url !== 'string') return String(url);
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
parsed.hash = '';
|
||||
return parsed.toString().replace(/\/$/, '');
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function hostOf(input) {
|
||||
try {
|
||||
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`);
|
||||
return url.hostname;
|
||||
} catch {
|
||||
return String(input);
|
||||
}
|
||||
}
|
||||
|
||||
function headerValue(headers, name) {
|
||||
const value = headers[name] ?? headers[name.toLowerCase()];
|
||||
if (Array.isArray(value)) return value.join(', ');
|
||||
return typeof value === 'string' ? value : null;
|
||||
}
|
||||
|
||||
function decodeEntities(text) {
|
||||
return String(text)
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
|
||||
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
function parseAttrs(tag) {
|
||||
const out = {};
|
||||
const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'`=<>]+))/g;
|
||||
let match;
|
||||
while ((match = re.exec(tag)) !== null) {
|
||||
const name = match[1].toLowerCase();
|
||||
if (name in out) continue;
|
||||
out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? '');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the <head> only: stop at </head> or 200 KB, whichever comes first.
|
||||
* Returns { head, title, metas, favicon }.
|
||||
*/
|
||||
export function parseHead(body, { limit = HEAD_SCAN_LIMIT } = {}) {
|
||||
const empty = { head: '', title: null, metas: {}, favicon: null };
|
||||
if (typeof body !== 'string' || body === '') return empty;
|
||||
|
||||
let text = body.slice(0, limit);
|
||||
const end = text.search(/<\/head\s*>/i);
|
||||
if (end !== -1) text = text.slice(0, end);
|
||||
|
||||
const metas = {};
|
||||
const metaRe = /<meta\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
|
||||
let match;
|
||||
while ((match = metaRe.exec(text)) !== null) {
|
||||
const attrs = parseAttrs(match[0]);
|
||||
const key = attrs.property || attrs.name || attrs.itemprop;
|
||||
if (!key || typeof attrs.content !== 'string') continue;
|
||||
const name = key.toLowerCase();
|
||||
if (!(name in metas)) metas[name] = attrs.content;
|
||||
}
|
||||
|
||||
const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(text);
|
||||
const title = titleMatch ? decodeEntities(titleMatch[1]).replace(/\s+/g, ' ').trim() || null : null;
|
||||
|
||||
let favicon = null;
|
||||
const linkRe = /<link\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
|
||||
while ((match = linkRe.exec(text)) !== null) {
|
||||
const attrs = parseAttrs(match[0]);
|
||||
const rel = String(attrs.rel || '').toLowerCase();
|
||||
if (!attrs.href) continue;
|
||||
if (rel.split(/\s+/).includes('icon')) {
|
||||
favicon = attrs.href;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return { head: text, title, metas, favicon };
|
||||
}
|
||||
|
||||
function clean(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const text = value.replace(/\s+/g, ' ').trim();
|
||||
return text === '' ? null : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the WhatsApp-style card.
|
||||
*
|
||||
* Contract keys: {title, description, image, siteName, hasImage, imageIsAbsolute}.
|
||||
* Two extras the report uses: `favicon` (resolved) and `imageDeclared` (an og:image tag existed,
|
||||
* even if it could not be turned into a usable URL).
|
||||
*
|
||||
* `imageIsAbsolute` means the declared og:image was already a full http(s) URL. A relative path is
|
||||
* resolved for `image`, but some previewers ignore relative values, so the report can say so.
|
||||
*/
|
||||
export function buildPreview(parsed, finalUrl) {
|
||||
const { metas = {}, title: titleTag = null, favicon = null } = parsed || {};
|
||||
const rawTitle = metas['og:title'] || metas['twitter:title'] || null;
|
||||
const rawDescription = metas['og:description'] || metas['twitter:description'] || metas.description || null;
|
||||
const rawImage = metas['og:image'] || metas['og:image:url'] || metas['twitter:image'] || null;
|
||||
|
||||
const image = rawImage ? resolveUrl(rawImage, finalUrl) : null;
|
||||
const imageIsAbsolute = typeof rawImage === 'string' ? /^https?:\/\//i.test(rawImage.trim()) : false;
|
||||
const usableImage = image !== null && /^https?:\/\//i.test(image);
|
||||
const siteName = metas['og:site_name'] || (finalUrl ? hostOf(finalUrl) : null);
|
||||
|
||||
return {
|
||||
title: clean(rawTitle) || clean(titleTag),
|
||||
description: clean(rawDescription),
|
||||
image: usableImage ? image : null,
|
||||
siteName: clean(siteName),
|
||||
hasImage: usableImage,
|
||||
imageIsAbsolute,
|
||||
favicon: favicon ? resolveUrl(favicon, finalUrl) : null,
|
||||
imageDeclared: typeof rawImage === 'string' && rawImage.trim() !== ''
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Header audit. Returns findings only — the caller decides the state.
|
||||
* `url` is the FINAL url: HSTS is only meaningful on an https page.
|
||||
*/
|
||||
export function auditHeaders(headers = {}, { url = null } = {}) {
|
||||
const findings = [];
|
||||
const isHttps = schemeOf(url) === 'https';
|
||||
|
||||
// --- HSTS ---------------------------------------------------------------------------------
|
||||
const hsts = headerValue(headers, 'strict-transport-security');
|
||||
if (isHttps) {
|
||||
if (!hsts) {
|
||||
findings.push({
|
||||
level: 'warn',
|
||||
code: 'hsts_missing',
|
||||
message: 'HTTPS works but browsers are not told to always use it — add a Strict-Transport-Security header.',
|
||||
fix: 'Strict-Transport-Security: max-age=31536000; includeSubDomains'
|
||||
});
|
||||
} else {
|
||||
const maxAge = /(?:^|;)\s*max-age\s*=\s*"?(\d+)"?/i.exec(hsts);
|
||||
if (!maxAge) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'hsts_no_max_age',
|
||||
message: 'The Strict-Transport-Security header has no max-age value, so browsers ignore it entirely.',
|
||||
fix: 'Strict-Transport-Security: max-age=31536000; includeSubDomains'
|
||||
});
|
||||
} else if (Number(maxAge[1]) < HSTS_MIN_AGE) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'hsts_max_age_short',
|
||||
message: `The Strict-Transport-Security max-age is ${Number(maxAge[1])} seconds — below the 180-day minimum of ${HSTS_MIN_AGE}, so browsers will not enforce it.`,
|
||||
fix: 'Strict-Transport-Security: max-age=31536000; includeSubDomains'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- optional hardening -------------------------------------------------------------------
|
||||
const csp = headerValue(headers, 'content-security-policy');
|
||||
if (!csp) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'csp_missing',
|
||||
message: 'Content-Security-Policy is not set — optional hardening not present.',
|
||||
fix: "Start with default-src 'self' and widen only where a third-party script is genuinely needed."
|
||||
});
|
||||
}
|
||||
if (!headerValue(headers, 'x-content-type-options')) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'x_content_type_options_missing',
|
||||
message: 'X-Content-Type-Options is not set — optional hardening not present.',
|
||||
fix: 'X-Content-Type-Options: nosniff'
|
||||
});
|
||||
}
|
||||
const hasFrameOptions = Boolean(headerValue(headers, 'x-frame-options')) ||
|
||||
Boolean(csp && /frame-ancestors/i.test(csp));
|
||||
if (!hasFrameOptions) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'frame_ancestors_missing',
|
||||
message: 'X-Frame-Options / frame-ancestors is not set — optional hardening not present.',
|
||||
fix: "X-Frame-Options: DENY (or Content-Security-Policy: frame-ancestors 'none')"
|
||||
});
|
||||
}
|
||||
if (!headerValue(headers, 'referrer-policy')) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'referrer_policy_missing',
|
||||
message: 'Referrer-Policy is not set — optional hardening not present.',
|
||||
fix: 'Referrer-Policy: strict-origin-when-cross-origin'
|
||||
});
|
||||
}
|
||||
if (!headerValue(headers, 'permissions-policy')) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'permissions_policy_missing',
|
||||
message: 'Permissions-Policy is not set — optional hardening not present.',
|
||||
fix: 'Permissions-Policy: camera=(), microphone=(), geolocation=()'
|
||||
});
|
||||
}
|
||||
|
||||
// --- version banners ----------------------------------------------------------------------
|
||||
const poweredBy = headerValue(headers, 'x-powered-by');
|
||||
if (poweredBy) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'x_powered_by',
|
||||
message: `The x-powered-by header advertises ${poweredBy}. Version banners help an attacker pick an exploit — remove it.`,
|
||||
fix: 'Turn off expose_php / the framework banner in the server config.'
|
||||
});
|
||||
}
|
||||
const server = headerValue(headers, 'server');
|
||||
if (server && /\d+\.\d+/.test(server)) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'server_version_banner',
|
||||
message: `The Server header reports the exact version (${server}). That tells an attacker which exploit to try — trim it to the product name.`,
|
||||
fix: 'server_tokens off (nginx) / ServerTokens Prod (Apache) / remove the header at the CDN.'
|
||||
});
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
function protectionOf(headers = {}) {
|
||||
const server = String(headerValue(headers, 'server') || '');
|
||||
if (EDGE_SERVERS.test(server)) return server.split(/[\s/]/)[0];
|
||||
const edgeHeader = EDGE_HEADERS.find((name) => headerValue(headers, name) !== null);
|
||||
return edgeHeader ? `edge header ${edgeHeader}` : 'not identified';
|
||||
}
|
||||
|
||||
/** A 401/403/429/503, or a challenge page, means we were not allowed to look — not that the site is broken. */
|
||||
export function detectBlock({ hops = [], final = null, headers = {}, body = '' } = {}) {
|
||||
const status = final && typeof final.status === 'number'
|
||||
? final.status
|
||||
: (hops.length > 0 ? hops[hops.length - 1].status : 0);
|
||||
const text = typeof body === 'string' ? body.slice(0, HEAD_SCAN_LIMIT).toLowerCase() : '';
|
||||
|
||||
const marker = CHALLENGE_MARKERS.find((needle) => text.includes(needle));
|
||||
if (marker) {
|
||||
return { blocked: true, status, reason: `challenge page (${marker})`, protection: protectionOf(headers) };
|
||||
}
|
||||
if (BLOCK_STATUSES.has(status)) {
|
||||
return { blocked: true, status, reason: `answered ${status}`, protection: protectionOf(headers) };
|
||||
}
|
||||
return { blocked: false, status, reason: null, protection: null };
|
||||
}
|
||||
|
||||
function summarise(state, findings, ctx) {
|
||||
if (state === 'ok') {
|
||||
return ctx.upgraded
|
||||
? 'The page loads over HTTPS after upgrading from http, and nothing needs fixing.'
|
||||
: 'The page loads over HTTPS and nothing needs fixing.';
|
||||
}
|
||||
const worst = findings.find((finding) => finding.level === state);
|
||||
if (worst) return worst.message;
|
||||
return state === 'warn' ? 'The page works but something should be tidied up.' : 'The page has a problem.';
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() } = {}) {
|
||||
const source = result || {};
|
||||
const hops = Array.isArray(source.hops) ? source.hops : [];
|
||||
const final = source.final || null;
|
||||
const headers = source.headers || (final && final.headers) || {};
|
||||
const body = typeof source.body === 'string'
|
||||
? source.body
|
||||
: (final && typeof final.body === 'string' ? final.body : '');
|
||||
|
||||
const lastHop = hops.length > 0 ? hops[hops.length - 1] : null;
|
||||
const finalUrl = (final && final.url) || (lastHop && lastHop.url) || null;
|
||||
const finalStatus = final && typeof final.status === 'number'
|
||||
? final.status
|
||||
: (lastHop ? lastHop.status : 0);
|
||||
const redirectCount = Math.max(0, hops.length - 1);
|
||||
|
||||
const findings = [];
|
||||
const evidence = [];
|
||||
|
||||
if (hops.length === 0 && !final) {
|
||||
return {
|
||||
state: 'not-evaluated',
|
||||
summary: 'No response came back, so there is nothing to judge.',
|
||||
findings: [],
|
||||
evidence: [],
|
||||
preview: null,
|
||||
redirects: { count: 0, finalUrl: null, hops: [] },
|
||||
analysedAt: new Date(now).toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
for (let i = 0; i < hops.length; i += 1) {
|
||||
evidence.push({
|
||||
label: `hop ${i + 1}`,
|
||||
value: `${hops[i].status} ${hops[i].url}${hops[i].location ? ` → ${hops[i].location}` : ''}`
|
||||
});
|
||||
}
|
||||
if (finalUrl) evidence.push({ label: 'final address', value: finalUrl });
|
||||
evidence.push({ label: 'requests', value: `${hops.length} (${redirectCount} redirect${redirectCount === 1 ? '' : 's'})` });
|
||||
|
||||
// --- blocked by a firewall? Stop before saying anything about the site ---------------------
|
||||
const block = detectBlock({ hops, final, headers, body });
|
||||
if (block.blocked) {
|
||||
evidence.push({ label: 'response', value: `${block.status || 'unknown'} — ${block.reason}` });
|
||||
evidence.push({ label: 'protection', value: block.protection });
|
||||
return {
|
||||
state: 'not-evaluated',
|
||||
summary: BLOCKED_MESSAGE,
|
||||
findings: [],
|
||||
evidence,
|
||||
preview: null,
|
||||
redirects: { count: redirectCount, finalUrl, hops },
|
||||
analysedAt: new Date(now).toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
// --- redirect chain -----------------------------------------------------------------------
|
||||
if (hops.length > MAX_HOPS) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'http_too_many_hops',
|
||||
message: `The page took ${hops.length} requests to load (${redirectCount} redirects). Anything past ${MAX_HOPS} makes the site feel slow and wastes crawl budget.`,
|
||||
fix: 'Point the advertised address straight at the final page.'
|
||||
});
|
||||
}
|
||||
|
||||
const visited = new Set();
|
||||
let loopAt = -1;
|
||||
for (let i = 0; i < hops.length; i += 1) {
|
||||
const key = normaliseUrl(hops[i].url);
|
||||
if (visited.has(key) && loopAt === -1) loopAt = i;
|
||||
visited.add(key);
|
||||
if (loopAt === -1 && hops[i].location) {
|
||||
const next = resolveUrl(hops[i].location, hops[i].url) || hops[i].location;
|
||||
if (visited.has(normaliseUrl(next))) loopAt = i;
|
||||
}
|
||||
}
|
||||
if (loopAt !== -1) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'http_redirect_loop',
|
||||
message: `The redirect chain loops back on itself at ${hops[loopAt].url} — visitors get "too many redirects" instead of the page.`,
|
||||
fix: 'Remove the redirect that points back at an address already in the chain.'
|
||||
});
|
||||
}
|
||||
|
||||
// Walk every URL the chain touches, including the target of each Location header.
|
||||
const walked = [];
|
||||
for (const hop of hops) {
|
||||
walked.push(hop.url);
|
||||
if (hop.location) walked.push(resolveUrl(hop.location, hop.url) || hop.location);
|
||||
}
|
||||
let sawHttps = false;
|
||||
let downgradeAt = -1;
|
||||
for (let i = 0; i < walked.length; i += 1) {
|
||||
const scheme = schemeOf(walked[i]);
|
||||
if (scheme === 'https') sawHttps = true;
|
||||
else if (scheme === 'http' && sawHttps && downgradeAt === -1) downgradeAt = i;
|
||||
}
|
||||
if (downgradeAt !== -1) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'http_downgrade',
|
||||
message: `The chain goes back to plain http at ${walked[downgradeAt]} — everything after that point travels unencrypted and can be read on the network.`,
|
||||
fix: 'Make the https address the last hop; never redirect an https URL back to http.'
|
||||
});
|
||||
}
|
||||
|
||||
const firstScheme = schemeOf(hops.length > 0 ? hops[0].url : finalUrl);
|
||||
const finalScheme = schemeOf(finalUrl);
|
||||
const upgraded = firstScheme === 'http' && finalScheme === 'https';
|
||||
if (upgraded) {
|
||||
findings.push({
|
||||
level: 'ok',
|
||||
code: 'http_upgraded',
|
||||
message: 'The plain http address redirects to https — that is the correct setup.'
|
||||
});
|
||||
}
|
||||
if (!sawHttps && finalScheme === 'http') {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'http_no_https',
|
||||
message: 'The page is served over plain http and never redirects to https — anything a visitor types or reads can be seen and changed on the network.',
|
||||
fix: 'Install a certificate and redirect every http request to https.'
|
||||
});
|
||||
}
|
||||
|
||||
// --- final response -----------------------------------------------------------------------
|
||||
if (final && finalStatus >= 400) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'http_final_status',
|
||||
message: `The final page answered ${finalStatus}, so a visitor would see an error page instead of the site.`,
|
||||
fix: 'Fix the error the server reports, or point the redirect at a page that exists.'
|
||||
});
|
||||
}
|
||||
|
||||
// --- headers and preview, only when a real response came back ------------------------------
|
||||
let preview = null;
|
||||
if (final) {
|
||||
findings.push(...auditHeaders(headers, { url: finalUrl }));
|
||||
|
||||
const parsed = parseHead(body);
|
||||
preview = buildPreview(parsed, finalUrl);
|
||||
|
||||
if (!preview.hasImage) {
|
||||
findings.push({
|
||||
level: 'warn',
|
||||
code: 'og_image_missing',
|
||||
message: preview.imageDeclared
|
||||
? 'The og:image address is not a usable web link, so a shared link shows a blank card in WhatsApp, Telegram and Facebook.'
|
||||
: 'There is no og:image, so a link to this page shows a blank card in WhatsApp, Telegram and Facebook.',
|
||||
fix: 'Add <meta property="og:image" content="https://…/card.png"> — 1200×630 works everywhere.'
|
||||
});
|
||||
} else if (!preview.imageIsAbsolute) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'og_image_relative',
|
||||
message: 'og:image is a relative path; some apps ignore it. Use the full https:// address.',
|
||||
fix: 'Make og:image an absolute https URL.'
|
||||
});
|
||||
}
|
||||
|
||||
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' });
|
||||
if (source.truncated) evidence.push({ label: 'body', value: 'truncated at the size cap' });
|
||||
}
|
||||
|
||||
const state = worstLevel(findings);
|
||||
return {
|
||||
state,
|
||||
summary: summarise(state, findings, { upgraded }),
|
||||
findings,
|
||||
evidence,
|
||||
preview,
|
||||
redirects: { count: redirectCount, finalUrl, hops },
|
||||
analysedAt: new Date(now).toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
export function describeFetchError(err) {
|
||||
const code = err && err.code ? err.code : null;
|
||||
switch (code) {
|
||||
case 'timeout':
|
||||
return 'The site did not answer in time. Nothing was judged about it.';
|
||||
case 'refused':
|
||||
return 'The server refused the connection, so the page could not be checked.';
|
||||
case 'dns_nxdomain':
|
||||
return 'That domain did not resolve, so there is no page to check.';
|
||||
case 'tls_invalid':
|
||||
case 'tls_expired':
|
||||
return 'The certificate could not be verified, so the page could not be loaded and nothing was judged about it.';
|
||||
case 'too_many_redirects':
|
||||
return 'The site redirects in a loop and never reaches a page.';
|
||||
case 'private_address':
|
||||
case 'private_host':
|
||||
return 'That address points into a private network and was not contacted.';
|
||||
case 'ip_literal':
|
||||
case 'bad_input':
|
||||
case 'bad_port':
|
||||
case 'bad_scheme':
|
||||
return (err && err.message) || 'That address could not be checked.';
|
||||
default:
|
||||
return `The page could not be loaded${err && err.message ? `: ${err.message}` : '.'}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** The check entry point: one redirect-following fetch, then the pure analyser. */
|
||||
export async function checkHttp(input, { lookup } = {}) {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const host = hostOf(input);
|
||||
|
||||
try {
|
||||
const result = await fetchFollowing(input, { lookup });
|
||||
const analysis = analyseHttp(result, { host });
|
||||
return {
|
||||
id: 'http',
|
||||
state: analysis.state,
|
||||
summary: analysis.summary,
|
||||
evidence: analysis.evidence,
|
||||
findings: analysis.findings,
|
||||
checkedAt,
|
||||
fromCache: false
|
||||
};
|
||||
} catch (err) {
|
||||
// A chain that ran past the redirect cap still has hops worth showing, and is a real fault.
|
||||
if (err && err.code === 'too_many_redirects' && Array.isArray(err.hops) && err.hops.length > 0) {
|
||||
const analysis = analyseHttp({ hops: err.hops, final: err.final || null, headers: {}, body: '' }, { host });
|
||||
return {
|
||||
id: 'http',
|
||||
state: 'fail',
|
||||
summary: analysis.summary,
|
||||
evidence: analysis.evidence,
|
||||
findings: analysis.findings,
|
||||
checkedAt,
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
return {
|
||||
id: 'http',
|
||||
state: 'not-evaluated',
|
||||
summary: describeFetchError(err),
|
||||
evidence: [{ label: 'address', value: String(input) }],
|
||||
findings: [],
|
||||
checkedAt,
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,877 @@
|
||||
// mail-auth — is this domain's email set up so mail arrives, and so nobody can spoof it?
|
||||
//
|
||||
// The honest answer needs a sender IP, which this service does not have. A real SPF
|
||||
// pass/fail is therefore out of reach, and this module never pretends otherwise: it reports
|
||||
// the SHAPE of the published records and what that shape means for the owner. Every claim
|
||||
// here is something a resolver actually returned.
|
||||
//
|
||||
// DNS is injected (`opts.dns` with resolveTxt/resolveMx/resolve4) so tests never touch the
|
||||
// network; the default is a node:dns Resolver with a 2 s timeout and 2 tries.
|
||||
|
||||
import dns from 'node:dns';
|
||||
import { parseTarget } from '../lib/net-guard.mjs';
|
||||
|
||||
export const DKIM_SELECTORS = Object.freeze([
|
||||
'default',
|
||||
'google',
|
||||
'selector1',
|
||||
'selector2',
|
||||
's1',
|
||||
's2',
|
||||
'k1',
|
||||
'k2',
|
||||
'mail',
|
||||
'dkim',
|
||||
'mandrill',
|
||||
'amazonses',
|
||||
'smtp'
|
||||
]);
|
||||
|
||||
// RFC 7208 §4.6.4: include, a, mx, ptr, exists and redirect each cost one lookup; the
|
||||
// evaluation must stop (permerror) once the total passes 10.
|
||||
export const SPF_LOOKUP_LIMIT = 10;
|
||||
export const SPF_LOOKUP_WARN_AT = 8;
|
||||
export const SPF_MAX_DEPTH = 10;
|
||||
|
||||
export const DMARC_SUBDOMAIN = '_dmarc';
|
||||
|
||||
// The one sentence this module is allowed to say about an unfound DKIM key. Never
|
||||
// "DKIM is not configured" — 13 selectors are not all selectors.
|
||||
export const DKIM_NO_KEY_MESSAGE =
|
||||
'No key found among the 13 common selectors; a custom selector cannot be found from DNS alone.';
|
||||
|
||||
const QUALIFIERS = new Set(['+', '-', '~', '?']);
|
||||
const SPF_MECHANISMS = new Set(['all', 'include', 'a', 'mx', 'ptr', 'exists', 'ip4', 'ip6']);
|
||||
const SPF_LOOKUP_MECHANISMS = new Set(['include', 'a', 'mx', 'ptr', 'exists']);
|
||||
|
||||
// A name that exists with no record of this type answers with one of these: "empty", not "broken".
|
||||
const EMPTY_CODES = new Set(['ENODATA', 'ENOTFOUND', 'NXDOMAIN', 'ENONAME', 'NOTFOUND']);
|
||||
// "I could not find out" — never a finding against the visitor's domain.
|
||||
const TRANSIENT_CODES = new Set([
|
||||
'ESERVFAIL', 'SERVFAIL', 'ETIMEOUT', 'ETIMEDOUT', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET',
|
||||
'EREFUSED', 'REFUSED', 'TIMEOUT', 'ERESOLVE', 'EBADRESP', 'EFORMERR', 'ENOTIMP'
|
||||
]);
|
||||
|
||||
const MAX_LISTED_INCLUDES = 3;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// resolver
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createResolver() {
|
||||
const resolver = new dns.promises.Resolver({ timeout: 2000, tries: 2 });
|
||||
return {
|
||||
resolveTxt: (host) => resolver.resolveTxt(host),
|
||||
resolveMx: (host) => resolver.resolveMx(host),
|
||||
resolve4: (host) => resolver.resolve4(host)
|
||||
};
|
||||
}
|
||||
|
||||
function pickResolver(candidate) {
|
||||
if (!candidate || typeof candidate.resolveTxt !== 'function') return createResolver();
|
||||
const missing = (code) => Object.assign(new Error(code), { code });
|
||||
return {
|
||||
resolveTxt: (host) => candidate.resolveTxt(host),
|
||||
resolveMx: (host) =>
|
||||
typeof candidate.resolveMx === 'function' ? candidate.resolveMx(host) : Promise.reject(missing('ENOTIMP')),
|
||||
resolve4: (host) =>
|
||||
typeof candidate.resolve4 === 'function' ? candidate.resolve4(host) : Promise.reject(missing('ENOTIMP'))
|
||||
};
|
||||
}
|
||||
|
||||
function errorCode(err) {
|
||||
if (!err) return 'UNKNOWN';
|
||||
return String(err.code || err.errno || 'UNKNOWN').toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* TXT answers arrive as an array of chunk arrays. Join the chunks of each record with NO
|
||||
* separator: a record longer than 255 bytes is split on the wire, and parsing the chunks
|
||||
* separately silently truncates `include:exam` + `ple.com` into a mechanism nobody published.
|
||||
*/
|
||||
export function joinTxtChunks(records) {
|
||||
if (!Array.isArray(records)) return [];
|
||||
return records.map((record) => {
|
||||
if (Array.isArray(record)) return record.join('');
|
||||
if (record === null || record === undefined) return '';
|
||||
return String(record);
|
||||
});
|
||||
}
|
||||
|
||||
async function queryTxt(resolver, host) {
|
||||
try {
|
||||
const raw = await resolver.resolveTxt(host);
|
||||
return { ok: true, records: joinTxtChunks(raw), code: null };
|
||||
} catch (err) {
|
||||
const code = errorCode(err);
|
||||
if (EMPTY_CODES.has(code)) return { ok: true, records: [], code };
|
||||
// Anything that is not "this name has no such record" means "I could not find out".
|
||||
return { ok: false, records: [], code, transient: true, listed: TRANSIENT_CODES.has(code) };
|
||||
}
|
||||
}
|
||||
|
||||
async function queryMx(resolver, host) {
|
||||
try {
|
||||
const raw = await resolver.resolveMx(host);
|
||||
return { ok: true, records: Array.isArray(raw) ? raw : [], code: null };
|
||||
} catch (err) {
|
||||
const code = errorCode(err);
|
||||
if (EMPTY_CODES.has(code)) return { ok: true, records: [], code };
|
||||
return { ok: false, records: [], code, transient: true };
|
||||
}
|
||||
}
|
||||
|
||||
async function queryAddresses(resolver, host) {
|
||||
try {
|
||||
const raw = await resolver.resolve4(host);
|
||||
const addresses = (Array.isArray(raw) ? raw : []).filter((a) => typeof a === 'string' && a.length > 0);
|
||||
return { ok: addresses.length > 0, addresses, code: null, empty: addresses.length === 0 };
|
||||
} catch (err) {
|
||||
const code = errorCode(err);
|
||||
if (EMPTY_CODES.has(code)) return { ok: false, addresses: [], code, empty: true };
|
||||
return { ok: false, addresses: [], code, empty: false, unreadable: true };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SPF
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function normaliseTarget(raw) {
|
||||
const text = String(raw ?? '').trim().toLowerCase().replace(/\.$/, '');
|
||||
if (text.length === 0) return null;
|
||||
if (text.includes('%')) return null; // a macro such as %{i} cannot be resolved from here
|
||||
if (!/^[a-z0-9._-]+$/.test(text)) return null;
|
||||
return text;
|
||||
}
|
||||
|
||||
/** Every TXT record that claims to be SPF, in the order the resolver returned them. */
|
||||
export function findSpfRecords(txts) {
|
||||
if (!Array.isArray(txts)) return [];
|
||||
return txts.filter((record) => /^v=spf1(\s|$)/i.test(String(record ?? '').trim()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one SPF record. Pure: no DNS. `lookups` counts the terms in THIS record only;
|
||||
* countSpfLookups() adds the records reachable through include and redirect.
|
||||
*/
|
||||
export function parseSpf(record) {
|
||||
const text = String(record ?? '').trim();
|
||||
const out = {
|
||||
record: text,
|
||||
valid: false,
|
||||
mechanisms: [],
|
||||
modifiers: {},
|
||||
lookups: 0,
|
||||
all: null,
|
||||
redirect: null,
|
||||
unknown: [],
|
||||
exp: null
|
||||
};
|
||||
if (text.length === 0) return out;
|
||||
|
||||
const tokens = text.split(/\s+/);
|
||||
if (!/^v=spf1$/i.test(tokens[0])) return out;
|
||||
out.valid = true;
|
||||
|
||||
for (const token of tokens.slice(1)) {
|
||||
const lowered = token.toLowerCase();
|
||||
|
||||
if (lowered.startsWith('redirect=')) {
|
||||
const target = normaliseTarget(token.slice('redirect='.length));
|
||||
out.modifiers.redirect = token.slice('redirect='.length);
|
||||
out.redirect = target;
|
||||
out.lookups += 1; // redirect counts toward the 10
|
||||
continue;
|
||||
}
|
||||
if (lowered.startsWith('exp=')) {
|
||||
out.modifiers.exp = token.slice('exp='.length);
|
||||
out.exp = token.slice('exp='.length);
|
||||
continue;
|
||||
}
|
||||
|
||||
const modifier = /^([a-z][a-z0-9_.-]*)=(.*)$/i.exec(token);
|
||||
if (modifier) {
|
||||
out.modifiers[modifier[1].toLowerCase()] = modifier[2];
|
||||
continue;
|
||||
}
|
||||
|
||||
const qualifier = QUALIFIERS.has(token[0]) ? token[0] : '+';
|
||||
const body = QUALIFIERS.has(token[0]) ? token.slice(1) : token;
|
||||
if (body.length === 0) {
|
||||
out.unknown.push(token);
|
||||
continue;
|
||||
}
|
||||
|
||||
const colon = body.indexOf(':');
|
||||
const slash = body.indexOf('/');
|
||||
let cut = body.length;
|
||||
if (colon !== -1) cut = colon;
|
||||
else if (slash !== -1) cut = slash;
|
||||
|
||||
const name = body.slice(0, cut).toLowerCase();
|
||||
const tail = body.slice(cut);
|
||||
const cidrMatch = /\/\d{1,3}$/.exec(tail);
|
||||
const cidr = cidrMatch ? cidrMatch[0].slice(1) : null;
|
||||
const tailNoCidr = cidrMatch ? tail.slice(0, cidrMatch.index) : tail;
|
||||
const value = tailNoCidr.startsWith(':') ? tailNoCidr.slice(1) : '';
|
||||
|
||||
if (!SPF_MECHANISMS.has(name)) {
|
||||
out.unknown.push(token);
|
||||
continue;
|
||||
}
|
||||
if (SPF_LOOKUP_MECHANISMS.has(name)) out.lookups += 1;
|
||||
|
||||
const mechanism = { qualifier, name, value, cidr, raw: token };
|
||||
out.mechanisms.push(mechanism);
|
||||
if (name === 'all') out.all = { qualifier, raw: token };
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk include and redirect targets, adding each record's own lookup terms, with cycle
|
||||
* detection and a hard depth cap. Never throws: a loop or a dead include ends the walk.
|
||||
*/
|
||||
export async function countSpfLookups(domain, record, { dns: resolver, maxDepth = SPF_MAX_DEPTH } = {}) {
|
||||
const rootDomain = String(domain ?? '').trim().toLowerCase().replace(/\.$/, '');
|
||||
const visited = new Set(rootDomain ? [rootDomain] : []);
|
||||
const chain = [];
|
||||
const missingTargets = [];
|
||||
let lookups = 0;
|
||||
let cycles = 0;
|
||||
let depthCapped = false;
|
||||
let unreadable = 0;
|
||||
|
||||
const queue = [{ domain: rootDomain, record, depth: 0 }];
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift();
|
||||
const parsed = typeof current.record === 'string' ? parseSpf(current.record) : current.record;
|
||||
if (!parsed || !parsed.valid) continue;
|
||||
|
||||
lookups += parsed.lookups;
|
||||
chain.push({ domain: current.domain, depth: current.depth, lookups: parsed.lookups });
|
||||
|
||||
const targets = [];
|
||||
for (const mechanism of parsed.mechanisms) {
|
||||
if (mechanism.name === 'include') {
|
||||
const target = normaliseTarget(mechanism.value);
|
||||
if (target) targets.push(target);
|
||||
}
|
||||
}
|
||||
if (parsed.redirect) targets.push(parsed.redirect);
|
||||
|
||||
for (const target of targets) {
|
||||
if (visited.has(target)) {
|
||||
cycles += 1;
|
||||
continue;
|
||||
}
|
||||
if (current.depth + 1 > maxDepth) {
|
||||
depthCapped = true;
|
||||
continue;
|
||||
}
|
||||
visited.add(target);
|
||||
if (!resolver || typeof resolver.resolveTxt !== 'function') continue;
|
||||
|
||||
const answer = await queryTxt(resolver, target);
|
||||
if (!answer.ok) {
|
||||
unreadable += 1;
|
||||
continue;
|
||||
}
|
||||
const nested = findSpfRecords(answer.records);
|
||||
if (nested.length === 0) {
|
||||
missingTargets.push(target);
|
||||
continue;
|
||||
}
|
||||
queue.push({ domain: target, record: nested[0], depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
|
||||
return { lookups, cycles, depthCapped, unreadable, missingTargets, chain };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DMARC
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function splitUris(value) {
|
||||
if (!value) return [];
|
||||
return String(value)
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
}
|
||||
|
||||
/** Parse a _dmarc TXT record. Pure. Unknown tags are kept in `tags` for the report. */
|
||||
export function parseDmarc(record) {
|
||||
const text = String(record ?? '').trim();
|
||||
const out = {
|
||||
record: text,
|
||||
valid: false,
|
||||
version: null,
|
||||
p: null,
|
||||
sp: null,
|
||||
pct: 100,
|
||||
rua: [],
|
||||
ruf: [],
|
||||
adkim: null,
|
||||
aspf: null,
|
||||
fo: null,
|
||||
tags: {}
|
||||
};
|
||||
if (text.length === 0) return out;
|
||||
|
||||
for (const part of text.split(';')) {
|
||||
const equals = part.indexOf('=');
|
||||
if (equals <= 0) continue;
|
||||
const key = part.slice(0, equals).trim().toLowerCase();
|
||||
const value = part.slice(equals + 1).trim();
|
||||
if (key.length > 0) out.tags[key] = value;
|
||||
}
|
||||
|
||||
if (!/^dmarc1$/i.test(out.tags.v || '')) return out;
|
||||
out.valid = true;
|
||||
out.version = 'DMARC1';
|
||||
|
||||
const policy = (out.tags.p || '').toLowerCase();
|
||||
out.p = ['none', 'quarantine', 'reject'].includes(policy) ? policy : null;
|
||||
const subdomain = (out.tags.sp || '').toLowerCase();
|
||||
out.sp = ['none', 'quarantine', 'reject'].includes(subdomain) ? subdomain : null;
|
||||
|
||||
const pct = Number.parseInt(out.tags.pct ?? '100', 10);
|
||||
out.pct = Number.isFinite(pct) ? Math.min(100, Math.max(0, pct)) : 100;
|
||||
|
||||
out.rua = splitUris(out.tags.rua);
|
||||
out.ruf = splitUris(out.tags.ruf);
|
||||
out.adkim = (out.tags.adkim || '').toLowerCase() || null;
|
||||
out.aspf = (out.tags.aspf || '').toLowerCase() || null;
|
||||
out.fo = (out.tags.fo || '').toLowerCase() || null;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DKIM
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Read one selector's TXT records. `p=` empty means the key was revoked, not published. */
|
||||
export function readDkimKey(records) {
|
||||
const out = { key: false, revoked: false, tags: {} };
|
||||
for (const record of records) {
|
||||
const tags = {};
|
||||
for (const part of String(record).split(';')) {
|
||||
const equals = part.indexOf('=');
|
||||
if (equals <= 0) continue;
|
||||
tags[part.slice(0, equals).trim().toLowerCase()] = part.slice(equals + 1).trim();
|
||||
}
|
||||
const hasP = Object.prototype.hasOwnProperty.call(tags, 'p');
|
||||
if (hasP && tags.p.length > 0) {
|
||||
out.key = true;
|
||||
out.tags = tags;
|
||||
return out;
|
||||
}
|
||||
if (hasP && tags.p.length === 0) {
|
||||
out.revoked = true;
|
||||
out.tags = tags;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MX
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Normalise MX answers, detect a null MX, and sort by priority. Pure. */
|
||||
export function parseMx(records) {
|
||||
const list = (Array.isArray(records) ? records : [])
|
||||
.map((record) => {
|
||||
if (!record || typeof record !== 'object') return null;
|
||||
const exchange = String(record.exchange ?? '').trim().toLowerCase().replace(/\.$/, '');
|
||||
const priority = Number(record.priority);
|
||||
return { exchange, priority: Number.isFinite(priority) ? priority : 0 };
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
// RFC 7505: a single "0 ." says the domain accepts no mail on purpose.
|
||||
const nullMx = list.length > 0 && list.every((record) => record.exchange === '' || record.exchange === '.');
|
||||
const sorted = (nullMx ? [] : list.filter((record) => record.exchange !== '' && record.exchange !== '.'))
|
||||
.slice()
|
||||
.sort((a, b) => a.priority - b.priority || a.exchange.localeCompare(b.exchange));
|
||||
|
||||
return { records: sorted, nullMx, count: nullMx ? 0 : sorted.length };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// gather
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function gather(domain, resolver) {
|
||||
const gathered = {
|
||||
domain,
|
||||
fatal: null,
|
||||
spfRecords: [],
|
||||
spfLookups: null,
|
||||
dmarc: { checked: false, code: null, record: null, parsed: null },
|
||||
dkim: [],
|
||||
mx: { checked: false, code: null, records: [], nullMx: false, addresses: [] }
|
||||
};
|
||||
|
||||
const [apexTxt, apexMx] = await Promise.all([queryTxt(resolver, domain), queryMx(resolver, domain)]);
|
||||
|
||||
// The whole zone is unreadable: SERVFAIL/timeout is not a finding against the visitor.
|
||||
if (!apexTxt.ok || !apexMx.ok) {
|
||||
const code = !apexTxt.ok ? apexTxt.code : apexMx.code;
|
||||
gathered.fatal = { code, kind: 'unreadable' };
|
||||
return gathered;
|
||||
}
|
||||
if (apexTxt.code === 'ENOTFOUND' && apexMx.code === 'ENOTFOUND') {
|
||||
gathered.fatal = { code: 'ENOTFOUND', kind: 'not_found' };
|
||||
return gathered;
|
||||
}
|
||||
|
||||
gathered.spfRecords = findSpfRecords(apexTxt.records);
|
||||
|
||||
const mx = parseMx(apexMx.records);
|
||||
gathered.mx = { checked: true, code: apexMx.code, records: mx.records, nullMx: mx.nullMx, addresses: [] };
|
||||
|
||||
const dmarcAnswer = await queryTxt(resolver, `${DMARC_SUBDOMAIN}.${domain}`);
|
||||
gathered.dmarc.checked = dmarcAnswer.ok;
|
||||
gathered.dmarc.code = dmarcAnswer.code;
|
||||
const dmarcRecords = dmarcAnswer.records.filter((record) => /^v=dmarc1(\s*;|\s|$)/i.test(record.trim()));
|
||||
gathered.dmarc.record = dmarcRecords[0] ?? null;
|
||||
gathered.dmarc.parsed = dmarcRecords[0] ? parseDmarc(dmarcRecords[0]) : null;
|
||||
gathered.dmarc.count = dmarcRecords.length;
|
||||
|
||||
const dkim = await Promise.all(
|
||||
DKIM_SELECTORS.map(async (selector) => {
|
||||
const name = `${selector}._domainkey.${domain}`;
|
||||
const answer = await queryTxt(resolver, name);
|
||||
if (!answer.ok) return { selector, name, status: 'unreadable', key: false };
|
||||
const hit = readDkimKey(answer.records);
|
||||
if (hit.key) return { selector, name, status: 'key', key: true, tags: hit.tags };
|
||||
if (hit.revoked) return { selector, name, status: 'revoked', key: false, tags: hit.tags };
|
||||
return { selector, name, status: 'none', key: false };
|
||||
})
|
||||
);
|
||||
gathered.dkim = dkim;
|
||||
|
||||
if (!mx.nullMx) {
|
||||
gathered.mx.addresses = await Promise.all(
|
||||
mx.records.map(async (record) => ({ host: record.exchange, ...(await queryAddresses(resolver, record.exchange)) }))
|
||||
);
|
||||
}
|
||||
|
||||
if (gathered.spfRecords.length === 1) {
|
||||
gathered.spfLookups = await countSpfLookups(domain, gathered.spfRecords[0], { dns: resolver });
|
||||
}
|
||||
|
||||
return gathered;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// summary
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildSummary({ receive, send }) {
|
||||
if (receive === 'null') {
|
||||
return send === 'locked'
|
||||
? 'This domain deliberately accepts no mail, and only your own servers can send as it.'
|
||||
: 'This domain deliberately accepts no mail (a valid setup), but anyone can still send as it.';
|
||||
}
|
||||
if (receive === 'no-mx') {
|
||||
return send === 'locked'
|
||||
? 'Mail sent to this domain may bounce, because no mail server is listed, but only your own servers can send as it.'
|
||||
: 'Mail sent to this domain may bounce, and spoofed email is not blocked.';
|
||||
}
|
||||
if (receive === 'broken') {
|
||||
return 'Mail sent to this domain will bounce, because none of the listed mail servers resolve.';
|
||||
}
|
||||
if (send === 'locked') return 'Mail can be delivered, and only your own servers can send as your domain.';
|
||||
if (send === 'partial') return 'Mail can be delivered, but a spoofed email could still get through.';
|
||||
return 'Mail can be delivered, but anyone can send email pretending to be your domain.';
|
||||
}
|
||||
|
||||
function worstState(findings) {
|
||||
if (findings.some((finding) => finding.level === 'fail')) return 'fail';
|
||||
if (findings.some((finding) => finding.level === 'warn')) return 'warn';
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
function envelope({ state, summary, evidence, findings, checkedAt }) {
|
||||
// `note` is optional: drop the key entirely rather than emit `note: undefined`.
|
||||
const cleanEvidence = (evidence || []).map((item) =>
|
||||
item.note === undefined ? { label: item.label, value: item.value } : item
|
||||
);
|
||||
return { id: 'mail-auth', state, summary, evidence: cleanEvidence, findings, checkedAt, fromCache: false };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// analysis (pure)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Turn gathered DNS answers into the report. Pure and synchronous: everything it needs was
|
||||
* already fetched by gather(), so tests can feed it fixtures directly.
|
||||
*/
|
||||
export function analyseMailAuth(gathered, { now = Date.now() } = {}) {
|
||||
const checkedAt = new Date(now).toISOString();
|
||||
const findings = [];
|
||||
const evidence = [];
|
||||
const add = (level, code, message, fix) => {
|
||||
const finding = { level, code, message };
|
||||
if (fix) finding.fix = fix;
|
||||
findings.push(finding);
|
||||
};
|
||||
|
||||
const domain = gathered?.domain || 'this domain';
|
||||
|
||||
if (gathered?.fatal) {
|
||||
const notFound = gathered.fatal.kind === 'not_found';
|
||||
add(
|
||||
'info',
|
||||
notFound ? 'domain_not_found' : 'dns_unavailable',
|
||||
notFound
|
||||
? 'DNS has no records at all for this name, so nothing about its email could be read.'
|
||||
: 'The DNS server did not answer for this domain, so nothing here is a verdict.',
|
||||
notFound ? 'Check the spelling, or ask your registrar whether the domain is active.' : 'Try again in a minute.'
|
||||
);
|
||||
return envelope({
|
||||
state: 'not-evaluated',
|
||||
summary: notFound
|
||||
? 'This domain does not appear to exist in DNS, so there is nothing to check yet.'
|
||||
: 'We could not read this domain’s DNS just now, so this is not a verdict — try again in a minute.',
|
||||
evidence: [{ label: 'DNS', value: notFound ? 'no records' : `unreadable (${gathered.fatal.code})` }],
|
||||
findings,
|
||||
checkedAt
|
||||
});
|
||||
}
|
||||
|
||||
// ---- SPF ----------------------------------------------------------------
|
||||
let spf = null;
|
||||
let spfLookups = null;
|
||||
if (gathered.spfRecords.length === 0) {
|
||||
add(
|
||||
'fail',
|
||||
'spf_missing',
|
||||
'There is no SPF record, so anyone can send email claiming to come from this domain.',
|
||||
`Publish a TXT record at ${domain}: v=spf1 include:<your mail provider> -all`
|
||||
);
|
||||
evidence.push({ label: 'SPF record', value: 'none' });
|
||||
} else if (gathered.spfRecords.length > 1) {
|
||||
add(
|
||||
'fail',
|
||||
'spf_multiple',
|
||||
`${gathered.spfRecords.length} SPF records are published. Receivers cannot choose between them, so SPF returns permerror and the domain loses its protection.`,
|
||||
'Merge them into a single v=spf1 record and delete the others.'
|
||||
);
|
||||
evidence.push({
|
||||
label: 'SPF record',
|
||||
value: `${gathered.spfRecords.length} records (permerror)`,
|
||||
note: gathered.spfRecords.join(' | ')
|
||||
});
|
||||
} else {
|
||||
spf = parseSpf(gathered.spfRecords[0]);
|
||||
evidence.push({ label: 'SPF record', value: spf.record });
|
||||
|
||||
if (!spf.valid) {
|
||||
add('fail', 'spf_malformed', 'The SPF record does not start with v=spf1, so receivers ignore it.');
|
||||
}
|
||||
|
||||
if (spf.all) {
|
||||
if (spf.all.qualifier === '-') {
|
||||
add('ok', 'spf_all_hardfail', 'SPF ends in -all: servers you did not list are told to fail.');
|
||||
} else if (spf.all.qualifier === '~') {
|
||||
add(
|
||||
'warn',
|
||||
'spf_all_softfail',
|
||||
'SPF ends in ~all (softfail): unauthorised mail is marked but usually still delivered.',
|
||||
'Change ~all to -all once you are sure every legitimate sender is listed.'
|
||||
);
|
||||
} else if (spf.all.qualifier === '?') {
|
||||
add(
|
||||
'fail',
|
||||
'spf_all_neutral',
|
||||
'SPF ends in ?all (neutral), which tells receivers nothing — anyone can still send as this domain.',
|
||||
'Change ?all to -all.'
|
||||
);
|
||||
} else {
|
||||
add(
|
||||
'fail',
|
||||
'spf_all_pass_all',
|
||||
'SPF ends in +all, which authorises every server on the internet to send as this domain.',
|
||||
'Replace +all with -all.'
|
||||
);
|
||||
}
|
||||
} else if (spf.redirect) {
|
||||
add(
|
||||
'warn',
|
||||
'spf_no_all',
|
||||
`SPF has no all mechanism; it delegates to redirect=${spf.redirect}, so the result depends on that record.`
|
||||
);
|
||||
} else {
|
||||
add(
|
||||
'warn',
|
||||
'spf_no_all',
|
||||
'SPF has no all mechanism, so unmatched senders get a neutral result and mail is not blocked.',
|
||||
'Add -all to the end of the record.'
|
||||
);
|
||||
}
|
||||
|
||||
if (spf.mechanisms.some((mechanism) => mechanism.name === 'ptr')) {
|
||||
add(
|
||||
'info',
|
||||
'spf_ptr_deprecated',
|
||||
'SPF uses ptr, which RFC 7208 discourages because it is slow and unreliable.'
|
||||
);
|
||||
}
|
||||
if (spf.unknown.length > 0) {
|
||||
add(
|
||||
'warn',
|
||||
'spf_unknown_mechanism',
|
||||
`SPF contains ${spf.unknown.length} term(s) that are not valid mechanisms or modifiers: ${spf.unknown.slice(0, 3).join(' ')}`,
|
||||
'Remove or correct them; an unknown mechanism makes the record a permerror.'
|
||||
);
|
||||
}
|
||||
|
||||
spfLookups = gathered.spfLookups || null;
|
||||
if (spfLookups) {
|
||||
const count = spfLookups.lookups;
|
||||
if (count > SPF_LOOKUP_LIMIT) {
|
||||
add(
|
||||
'fail',
|
||||
'spf_lookup_limit',
|
||||
`SPF needs ${count} DNS lookups; the limit is ${SPF_LOOKUP_LIMIT}, so receivers return permerror and treat the mail as unprotected.`,
|
||||
'Flatten the record: replace some include: entries with the ip4/ip6 ranges they resolve to.'
|
||||
);
|
||||
} else if (count >= SPF_LOOKUP_WARN_AT) {
|
||||
add(
|
||||
'warn',
|
||||
'spf_lookups_near_limit',
|
||||
`SPF needs ${count} of the ${SPF_LOOKUP_LIMIT} allowed DNS lookups. One more include and it breaks.`,
|
||||
'Flatten the record before adding another provider.'
|
||||
);
|
||||
}
|
||||
if (spfLookups.cycles > 0) {
|
||||
add(
|
||||
'warn',
|
||||
'spf_include_loop',
|
||||
'SPF includes loop back to a domain already checked, so the evaluation never finishes cleanly.'
|
||||
);
|
||||
}
|
||||
if (spfLookups.depthCapped) {
|
||||
add('warn', 'spf_too_deep', 'The SPF include chain is deeper than 10 levels, which is a permerror.');
|
||||
}
|
||||
if (spfLookups.missingTargets.length > 0) {
|
||||
add(
|
||||
'warn',
|
||||
'spf_include_no_record',
|
||||
`An included domain has no SPF record: ${spfLookups.missingTargets.slice(0, MAX_LISTED_INCLUDES).join(', ')}. Receivers treat that as a permanent error.`,
|
||||
'Ask that provider for its current include: value, or drop the include.'
|
||||
);
|
||||
}
|
||||
evidence.push({
|
||||
label: 'SPF lookups',
|
||||
value: `${count} of ${SPF_LOOKUP_LIMIT}`,
|
||||
note: 'Counts include, a, mx, ptr, exists and redirect across the whole chain.'
|
||||
});
|
||||
} else {
|
||||
evidence.push({ label: 'SPF lookups', value: 'not counted' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- DMARC --------------------------------------------------------------
|
||||
let dmarc = null;
|
||||
if (!gathered.dmarc.checked) {
|
||||
// We could not read _dmarc: say so, and do not claim the record is missing.
|
||||
add(
|
||||
'info',
|
||||
'dmarc_not_checked',
|
||||
'The _dmarc record could not be read just now, so its policy is unknown rather than missing.'
|
||||
);
|
||||
evidence.push({ label: 'DMARC record', value: `unreadable (${gathered.dmarc.code || 'DNS error'})` });
|
||||
} else if (!gathered.dmarc.record) {
|
||||
add(
|
||||
'warn',
|
||||
'dmarc_missing',
|
||||
'There is no DMARC record, so receivers have no instruction for mail that fails SPF or DKIM.',
|
||||
`Publish a TXT record at _dmarc.${domain}: v=DMARC1; p=none; rua=mailto:dmarc@${domain} — then tighten to p=quarantine when the reports look clean.`
|
||||
);
|
||||
evidence.push({ label: 'DMARC record', value: 'none' });
|
||||
} else {
|
||||
dmarc = gathered.dmarc.parsed;
|
||||
evidence.push({ label: 'DMARC record', value: dmarc.record });
|
||||
|
||||
if (!dmarc.valid) {
|
||||
add('fail', 'dmarc_malformed', 'The _dmarc record does not start with v=DMARC1, so receivers ignore it.');
|
||||
} else if (dmarc.p === 'none') {
|
||||
add(
|
||||
'warn',
|
||||
'dmarc_none',
|
||||
'DMARC is set to p=none — monitoring only: spoofing is still allowed, you just get reports about it.',
|
||||
'Once the reports look clean, change p=none to p=quarantine, then p=reject.'
|
||||
);
|
||||
} else if (dmarc.p === 'quarantine') {
|
||||
add('ok', 'dmarc_quarantine', 'DMARC is set to p=quarantine: failing mail is sent to spam.');
|
||||
} else if (dmarc.p === 'reject') {
|
||||
add('ok', 'dmarc_reject', 'DMARC is set to p=reject: failing mail is refused outright.');
|
||||
} else {
|
||||
add('warn', 'dmarc_no_policy', 'The DMARC record has no usable p= policy, so it does nothing.');
|
||||
}
|
||||
|
||||
if (dmarc.valid && dmarc.pct < 100) {
|
||||
add(
|
||||
'info',
|
||||
'dmarc_partial_pct',
|
||||
`DMARC pct=${dmarc.pct}, so the policy is applied to only part of failing mail; the rest is delivered.`
|
||||
);
|
||||
}
|
||||
if (dmarc.valid && dmarc.rua.length === 0) {
|
||||
add('info', 'dmarc_no_rua', 'DMARC has no rua= address, so nobody collects the reports and you cannot see who is spoofing you.');
|
||||
}
|
||||
evidence.push({
|
||||
label: 'DMARC policy',
|
||||
value: dmarc.valid ? `p=${dmarc.p ?? 'none'}` : 'invalid',
|
||||
note: dmarc.valid
|
||||
? `pct=${dmarc.pct}${dmarc.sp ? `, sp=${dmarc.sp}` : ''}${dmarc.rua.length ? `, rua=${dmarc.rua.join(',')}` : ', no rua'}`
|
||||
: undefined
|
||||
});
|
||||
}
|
||||
|
||||
// ---- DKIM ---------------------------------------------------------------
|
||||
const withKey = gathered.dkim.filter((entry) => entry.status === 'key');
|
||||
const revoked = gathered.dkim.filter((entry) => entry.status === 'revoked');
|
||||
if (withKey.length > 0) {
|
||||
add('ok', 'dkim_key_found', `A DKIM key is published at ${withKey.map((entry) => entry.selector).join(', ')}.`);
|
||||
evidence.push({
|
||||
label: 'DKIM key',
|
||||
value: withKey.map((entry) => entry.selector).join(', '),
|
||||
note: `Found among the ${DKIM_SELECTORS.length} common selectors.`
|
||||
});
|
||||
} else {
|
||||
// Absence of evidence, not evidence of absence. The wording is fixed on purpose.
|
||||
add('info', 'dkim_no_key_found', DKIM_NO_KEY_MESSAGE);
|
||||
evidence.push({
|
||||
label: 'DKIM key',
|
||||
value: 'none of 13 selectors',
|
||||
note: revoked.length > 0 ? `Revoked key at ${revoked.map((entry) => entry.selector).join(', ')}.` : undefined
|
||||
});
|
||||
}
|
||||
if (revoked.length > 0 && withKey.length > 0) {
|
||||
add('info', 'dkim_revoked', `A key at ${revoked.map((entry) => entry.selector).join(', ')} is revoked (p= is empty).`);
|
||||
}
|
||||
|
||||
// ---- MX -----------------------------------------------------------------
|
||||
let receive;
|
||||
if (gathered.mx.nullMx) {
|
||||
receive = 'null';
|
||||
add(
|
||||
'ok',
|
||||
'mx_null',
|
||||
'A null MX record (0 .) is published: this domain explicitly accepts no email. That is a deliberate, valid setup, not a fault.'
|
||||
);
|
||||
evidence.push({ label: 'MX records', value: '0 . (null MX — no mail accepted)' });
|
||||
} else if (gathered.mx.records.length === 0) {
|
||||
receive = 'no-mx';
|
||||
add(
|
||||
'warn',
|
||||
'mx_missing',
|
||||
'No MX record is published, so senders have no mail server to deliver to.',
|
||||
`Add an MX record for ${domain} pointing at your mail provider (for example 10 mx.<provider>.com).`
|
||||
);
|
||||
evidence.push({ label: 'MX records', value: 'none' });
|
||||
} else {
|
||||
evidence.push({
|
||||
label: 'MX records',
|
||||
value: gathered.mx.records.map((record) => `${record.priority} ${record.exchange}`).join(', ')
|
||||
});
|
||||
|
||||
const resolved = gathered.mx.addresses.filter((entry) => entry.ok);
|
||||
const provablyEmpty = gathered.mx.addresses.filter((entry) => entry.empty);
|
||||
const unreadable = gathered.mx.addresses.filter((entry) => entry.unreadable);
|
||||
|
||||
for (const entry of gathered.mx.addresses) {
|
||||
evidence.push({
|
||||
label: 'MX address',
|
||||
value: entry.ok ? `${entry.host} → ${entry.addresses[0]}` : `${entry.host} → ${entry.unreadable ? 'not checked' : 'no address'}`,
|
||||
note: entry.ok && entry.addresses.length > 1 ? `${entry.addresses.length} addresses` : undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (resolved.length === 0 && provablyEmpty.length === gathered.mx.addresses.length) {
|
||||
receive = 'broken';
|
||||
add(
|
||||
'fail',
|
||||
'mx_no_address',
|
||||
'None of the listed mail servers resolve to an address, so mail sent here will bounce.',
|
||||
'Fix the MX hostnames or ask your provider for the correct ones.'
|
||||
);
|
||||
} else {
|
||||
receive = 'yes';
|
||||
const dead = provablyEmpty.filter((entry) => !entry.ok);
|
||||
if (dead.length > 0) {
|
||||
add(
|
||||
'warn',
|
||||
'mx_host_no_address',
|
||||
`${dead.map((entry) => entry.host).join(', ')} does not resolve, so part of your incoming mail will bounce.`,
|
||||
'Remove the dead MX record or point it at a host that resolves.'
|
||||
);
|
||||
}
|
||||
if (unreadable.length > 0) {
|
||||
add('info', 'mx_host_not_checked', `Could not check ${unreadable.map((entry) => entry.host).join(', ')} just now.`);
|
||||
}
|
||||
add('ok', 'mx_present', `${gathered.mx.records.length} mail server(s) listed, lowest priority tried first.`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- summary ------------------------------------------------------------
|
||||
const spfHard = Boolean(spf && spf.all && spf.all.qualifier === '-');
|
||||
const spfSoft = Boolean(spf && spf.all && spf.all.qualifier === '~');
|
||||
const dmarcEnforcing = Boolean(
|
||||
dmarc && dmarc.valid && (dmarc.p === 'reject' || dmarc.p === 'quarantine') && dmarc.pct >= 100
|
||||
);
|
||||
const dmarcPresent = Boolean(dmarc && dmarc.valid && dmarc.p && dmarc.p !== 'none');
|
||||
|
||||
let send = 'open';
|
||||
if (spfHard && dmarcEnforcing) send = 'locked';
|
||||
else if (spfHard || spfSoft || dmarcPresent) send = 'partial';
|
||||
|
||||
const state = worstState(findings);
|
||||
return envelope({ state, summary: buildSummary({ receive, send }), evidence, findings, checkedAt });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// check
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Check a domain's email setup.
|
||||
*
|
||||
* @param {string} input domain (or URL — the host is taken)
|
||||
* @param {{dns?: object, lookup?: object, now?: number, cache?: object}} options
|
||||
* `dns` (alias `lookup`) is an object with resolveTxt/resolveMx/resolve4; injected by tests.
|
||||
*/
|
||||
export async function check(input, { dns: resolver, lookup, now = Date.now(), cache } = {}) {
|
||||
const checkedAt = new Date(now).toISOString();
|
||||
|
||||
let host;
|
||||
try {
|
||||
host = parseTarget(typeof input === 'string' ? input : String(input ?? '')).host;
|
||||
} catch {
|
||||
return envelope({
|
||||
state: 'fail',
|
||||
summary: 'That does not look like a domain name, so there was nothing to check.',
|
||||
evidence: [],
|
||||
findings: [{ level: 'fail', code: 'bad_input', message: 'That does not look like a domain name.' }],
|
||||
checkedAt
|
||||
});
|
||||
}
|
||||
|
||||
void cache; // caching is the router's job; this module always reports fromCache: false
|
||||
const dnsClient = pickResolver(resolver || lookup);
|
||||
const gathered = await gather(host, dnsClient);
|
||||
return analyseMailAuth(gathered, { now });
|
||||
}
|
||||
|
||||
export const checkMailAuth = check;
|
||||
@@ -0,0 +1,381 @@
|
||||
// tls.mjs — certificate health for one host.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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';
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const URGENT_DAYS = 14;
|
||||
const WARN_DAYS = 30;
|
||||
|
||||
const LEVEL_RANK = { ok: 0, info: 1, warn: 2, fail: 3 };
|
||||
|
||||
const MONTHS = {
|
||||
jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5,
|
||||
jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11
|
||||
};
|
||||
|
||||
/** Worst level in a findings list. `not-evaluated` is not a finding level and is handled by callers. */
|
||||
export function worstLevel(findings, fallback = 'ok') {
|
||||
let state = fallback;
|
||||
for (const finding of findings) {
|
||||
if ((LEVEL_RANK[finding.level] ?? 0) > (LEVEL_RANK[state] ?? 0)) state = finding.level;
|
||||
}
|
||||
// 'info' is a finding level, not a check state: a page that only has optional hardening
|
||||
// missing is still an 'ok' report, with the notes shown as info rows.
|
||||
return state === 'info' ? 'ok' : state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an X.509 date. Node hands us OpenSSL's format, 'Mar 1 12:00:00 2027 GMT', which has a
|
||||
* double space before single-digit days — normalise whitespace first, then read it as UTC.
|
||||
* ISO strings are accepted too (fixtures and future callers).
|
||||
*/
|
||||
export function parseCertDate(value) {
|
||||
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.getTime();
|
||||
if (typeof value !== 'string') return null;
|
||||
const text = value.trim().replace(/\s+/g, ' ');
|
||||
if (text === '') return null;
|
||||
|
||||
const openssl = /^([A-Za-z]{3}) (\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4}) GMT$/i.exec(text);
|
||||
if (openssl) {
|
||||
const month = MONTHS[openssl[1].toLowerCase()];
|
||||
if (month === undefined) return null;
|
||||
const [, , day, hours, minutes, seconds, year] = openssl;
|
||||
return Date.UTC(Number(year), month, Number(day), Number(hours), Number(minutes), Number(seconds));
|
||||
}
|
||||
|
||||
const parsed = Date.parse(text);
|
||||
return Number.isNaN(parsed) ? null : parsed;
|
||||
}
|
||||
|
||||
/** 'DNS:example.com, DNS:*.example.com, IP:203.0.113.9' → [{type, value}, …] */
|
||||
export function parseSanList(subjectAltName) {
|
||||
if (typeof subjectAltName !== 'string' || subjectAltName.trim() === '') return [];
|
||||
return subjectAltName
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry !== '')
|
||||
.map((entry) => {
|
||||
const colon = entry.indexOf(':');
|
||||
if (colon === -1) return { type: 'DNS', value: entry };
|
||||
return { type: entry.slice(0, colon).trim(), value: entry.slice(colon + 1).trim() };
|
||||
})
|
||||
.filter((entry) => entry.value !== '');
|
||||
}
|
||||
|
||||
/** Exact match, or a single-label wildcard. `*.example.com` covers `www.example.com`, not `example.com`
|
||||
* and not `a.b.example.com`. */
|
||||
export function matchesName(host, pattern) {
|
||||
const h = String(host || '').toLowerCase().replace(/\.$/, '');
|
||||
const p = String(pattern || '').toLowerCase().replace(/\.$/, '');
|
||||
if (h === '' || p === '') return false;
|
||||
if (p === h) return true;
|
||||
if (!p.startsWith('*.')) return false;
|
||||
const suffix = p.slice(1); // '.example.com'
|
||||
if (!h.endsWith(suffix)) return false;
|
||||
const label = h.slice(0, h.length - suffix.length);
|
||||
return label !== '' && !label.includes('.');
|
||||
}
|
||||
|
||||
/** DNS names on the certificate, ignoring IP and email entries. */
|
||||
export function sanNames(subjectAltName) {
|
||||
return parseSanList(subjectAltName)
|
||||
.filter((entry) => entry.type.toUpperCase() === 'DNS')
|
||||
.map((entry) => entry.value);
|
||||
}
|
||||
|
||||
export function isWeakSignature(algorithm) {
|
||||
// sha1WithRSAEncryption, ecdsa-with-SHA1, md5WithRSA, rsa_pkcs1_sha1 …
|
||||
return /sha-?1|md5/i.test(String(algorithm || ''));
|
||||
}
|
||||
|
||||
/** A trust anchor signs itself. RFC 5280 §6.1 exempts it from the signature-algorithm rules. */
|
||||
function isTrustAnchor(entry) {
|
||||
if (!entry) return false;
|
||||
if (entry.selfSigned === true) return true;
|
||||
if (!entry.subject || !entry.issuer) return false;
|
||||
return JSON.stringify(entry.subject) === JSON.stringify(entry.issuer);
|
||||
}
|
||||
|
||||
function formatName(name) {
|
||||
if (!name) return 'unknown';
|
||||
if (typeof name === 'string') return name;
|
||||
const parts = [name.CN, name.O].filter(Boolean);
|
||||
return parts.length > 0 ? parts.join(', ') : 'unknown';
|
||||
}
|
||||
|
||||
function plural(count) {
|
||||
return count === 1 ? '' : 's';
|
||||
}
|
||||
|
||||
function describeAuthorizationError(code, host) {
|
||||
const text = String(code || '');
|
||||
if (/ALTNAME|HOSTNAME/i.test(text)) {
|
||||
return `The certificate is not issued for ${host || 'this address'}, so the chain does not verify.`;
|
||||
}
|
||||
if (/CERT_HAS_EXPIRED/i.test(text)) return 'The certificate has expired, so the chain does not verify.';
|
||||
if (/NOT_YET_VALID/i.test(text)) return "The certificate's start date is in the future — check the server clock.";
|
||||
if (/SELF_SIGNED|UNABLE_TO_VERIFY|UNABLE_TO_GET_ISSUER|DEPTH_ZERO/i.test(text)) {
|
||||
return 'Browsers cannot verify the certificate chain: the intermediate certificate that proves the site certificate is not being sent.';
|
||||
}
|
||||
return `The certificate chain did not verify${text ? ` (${text})` : ''}.`;
|
||||
}
|
||||
|
||||
function buildSummary(state, findings, { host, daysToExpiry }) {
|
||||
const who = host || 'this site';
|
||||
if (state === 'ok') {
|
||||
return daysToExpiry === null
|
||||
? `The certificate for ${who} is valid.`
|
||||
: `The certificate for ${who} is valid, covers the name, and expires in ${daysToExpiry} days.`;
|
||||
}
|
||||
const worst = findings.find((finding) => finding.level === state);
|
||||
if (worst) return worst.message;
|
||||
return state === 'warn' ? 'The certificate works but needs attention soon.' : 'The certificate has a problem.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure analysis. Accepts either inspectTls() output ({cert, chain, host, …}) or the bare
|
||||
* certificate object that requestOnce() attaches to a response ({cert: {…}} → the cert itself).
|
||||
* Returns { state, summary, findings, evidence, daysToExpiry, san, chainLength }.
|
||||
*/
|
||||
export function summariseTls(tlsInfo, { host, now = Date.now() } = {}) {
|
||||
const findings = [];
|
||||
const evidence = [];
|
||||
|
||||
if (!tlsInfo) {
|
||||
return {
|
||||
state: 'not-evaluated',
|
||||
summary: 'No certificate came back from that server, so there is nothing to judge.',
|
||||
findings: [],
|
||||
evidence: [],
|
||||
daysToExpiry: null,
|
||||
san: [],
|
||||
chainLength: 0
|
||||
};
|
||||
}
|
||||
|
||||
const cert = tlsInfo.cert || tlsInfo;
|
||||
const chain = Array.isArray(tlsInfo.chain) && tlsInfo.chain.length > 0
|
||||
? tlsInfo.chain
|
||||
: (Array.isArray(cert.chain) ? cert.chain : []);
|
||||
const leaf = chain[0] || cert;
|
||||
const queriedHost = host || tlsInfo.host || null;
|
||||
|
||||
const validToMs = parseCertDate(leaf.validTo || cert.validTo);
|
||||
const daysToExpiry = validToMs === null ? null : Math.floor((validToMs - now) / DAY_MS);
|
||||
|
||||
// --- expiry -------------------------------------------------------------------------------
|
||||
if (daysToExpiry === null) {
|
||||
findings.push({
|
||||
level: 'info',
|
||||
code: 'tls_expiry_unknown',
|
||||
message: 'The certificate expiry date could not be read, so the time left on it is unknown.'
|
||||
});
|
||||
} else if (daysToExpiry < 0) {
|
||||
const days = Math.abs(daysToExpiry);
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'tls_expired',
|
||||
message: `The certificate expired ${days} day${plural(days)} ago — every browser shows a full-page warning before the site loads.`,
|
||||
fix: 'Renew the certificate now. If the host offers free automatic renewal, switch it on.'
|
||||
});
|
||||
} else if (daysToExpiry < URGENT_DAYS) {
|
||||
findings.push({
|
||||
level: 'warn',
|
||||
code: 'tls_expiring_soon',
|
||||
message: `The certificate expires in ${daysToExpiry} day${plural(daysToExpiry)} — renew it now, before browsers start blocking the site.`,
|
||||
fix: 'Renew, or turn on automatic renewal (Let’s Encrypt or the host’s free SSL).'
|
||||
});
|
||||
} else if (daysToExpiry < WARN_DAYS) {
|
||||
findings.push({
|
||||
level: 'warn',
|
||||
code: 'tls_expiring',
|
||||
message: `The certificate expires in ${daysToExpiry} days. Nothing is broken yet, but renewal is due within the month.`,
|
||||
fix: 'Check that auto-renewal is switched on.'
|
||||
});
|
||||
} else {
|
||||
findings.push({
|
||||
level: 'ok',
|
||||
code: 'tls_valid',
|
||||
message: `The certificate is valid and expires in ${daysToExpiry} days.`
|
||||
});
|
||||
}
|
||||
|
||||
// --- name coverage ------------------------------------------------------------------------
|
||||
let names = [];
|
||||
if (queriedHost) {
|
||||
names = sanNames(leaf.subjectAltName || cert.subjectAltName || '');
|
||||
const matched = names.find((name) => matchesName(queriedHost, name)) || null;
|
||||
if (matched) {
|
||||
findings.push({
|
||||
level: 'ok',
|
||||
code: 'tls_name_match',
|
||||
message: `The certificate covers ${queriedHost}.`
|
||||
});
|
||||
} else if (names.length === 0) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'tls_no_san',
|
||||
message: `The certificate does not name ${queriedHost} anywhere, so browsers refuse it with a name-mismatch warning.`,
|
||||
fix: 'Reissue the certificate with a Subject Alternative Name for every hostname the site answers on.'
|
||||
});
|
||||
} else {
|
||||
const shown = names.slice(0, 3).join(', ');
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'tls_name_mismatch',
|
||||
message: `The certificate is issued for ${shown}${names.length > 3 ? ' and others' : ''}, not ${queriedHost} — visitors see a security warning.`,
|
||||
fix: 'Reissue the certificate to include this hostname. A wildcard covers one label only.'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- signature algorithms (leaf and intermediates only) -----------------------------------
|
||||
// A self-signed root is a trust anchor: never judged, never mentioned as a finding.
|
||||
const judged = chain.length > 0 ? chain : [cert];
|
||||
for (let i = 0; i < judged.length; i += 1) {
|
||||
const entry = judged[i];
|
||||
if (isTrustAnchor(entry)) continue;
|
||||
if (!isWeakSignature(entry.signatureAlgorithm)) continue;
|
||||
const where = i === 0 ? 'leaf' : 'intermediate';
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: i === 0 ? 'tls_weak_signature_leaf' : 'tls_weak_signature_intermediate',
|
||||
message: `The ${where} certificate is signed with ${entry.signatureAlgorithm}, which is no longer considered secure — some browsers and payment pages reject it.`,
|
||||
fix: 'Reissue the certificate with SHA-256.'
|
||||
});
|
||||
}
|
||||
|
||||
// --- chain shape --------------------------------------------------------------------------
|
||||
const chainLength = chain.length;
|
||||
if (chainLength > 0) {
|
||||
const leafFirst = typeof chain[0].fingerprint256 === 'string' && typeof cert.fingerprint256 === 'string'
|
||||
? chain[0].fingerprint256 === cert.fingerprint256
|
||||
: JSON.stringify(chain[0].subject) === JSON.stringify(cert.subject);
|
||||
|
||||
evidence.push({
|
||||
label: 'chain',
|
||||
value: `${chainLength} certificate${plural(chainLength)}${leafFirst ? ', site certificate first' : ', out of order'}`
|
||||
});
|
||||
|
||||
if (isTrustAnchor(chain[0])) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'tls_self_signed_leaf',
|
||||
message: 'The site is using a self-signed certificate, so no browser can confirm it belongs to the business — visitors get a warning page.',
|
||||
fix: 'Install a certificate from a public certificate authority. Free ones exist.'
|
||||
});
|
||||
} else if (chainLength < 2) {
|
||||
findings.push({
|
||||
level: 'warn',
|
||||
code: 'tls_chain_short',
|
||||
message: 'The server sends only its own certificate and not the intermediate that proves it, so some phones and older browsers fail to load the site.',
|
||||
fix: 'Serve the full chain (site certificate + intermediate) from the web server.'
|
||||
});
|
||||
}
|
||||
|
||||
if (!leafFirst) {
|
||||
findings.push({
|
||||
level: 'warn',
|
||||
code: 'tls_chain_order',
|
||||
message: 'The certificate chain is sent in the wrong order — the site certificate should come first.',
|
||||
fix: 'Reorder the chain file so the leaf is first.'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- did the TLS layer verify it? ---------------------------------------------------------
|
||||
if (cert.authorized === false) {
|
||||
findings.push({
|
||||
level: 'fail',
|
||||
code: 'tls_untrusted_chain',
|
||||
message: describeAuthorizationError(cert.authorizationError, queriedHost),
|
||||
fix: 'Serve the complete chain from a public certificate authority and make sure the hostname is on the certificate.'
|
||||
});
|
||||
}
|
||||
|
||||
// --- evidence -----------------------------------------------------------------------------
|
||||
evidence.push({ label: 'issued to', value: formatName(leaf.subject || cert.subject) });
|
||||
evidence.push({ label: 'issued by', value: formatName(leaf.issuer || cert.issuer) });
|
||||
if (validToMs !== null) evidence.push({ label: 'valid until', value: new Date(validToMs).toISOString() });
|
||||
if (daysToExpiry !== null) evidence.push({ label: 'days left', value: String(daysToExpiry) });
|
||||
if (names.length > 0) evidence.push({ label: 'names on certificate', value: names.join(', ') });
|
||||
if (leaf.signatureAlgorithm) evidence.push({ label: 'signature', value: leaf.signatureAlgorithm });
|
||||
if (cert.protocol) evidence.push({ label: 'protocol', value: cert.protocol });
|
||||
if (tlsInfo.cipher && tlsInfo.cipher.name) evidence.push({ label: 'cipher', value: tlsInfo.cipher.name });
|
||||
if (tlsInfo.address) evidence.push({ label: 'address', value: tlsInfo.address });
|
||||
|
||||
const state = worstLevel(findings);
|
||||
return {
|
||||
state,
|
||||
summary: buildSummary(state, findings, { host: queriedHost, daysToExpiry }),
|
||||
findings,
|
||||
evidence,
|
||||
daysToExpiry,
|
||||
san: names,
|
||||
chainLength
|
||||
};
|
||||
}
|
||||
|
||||
/** A handshake that never completed is not a finding against the site — nothing was judged. */
|
||||
export function describeHandshakeError(err) {
|
||||
const code = err && err.code ? err.code : null;
|
||||
switch (code) {
|
||||
case 'timeout':
|
||||
return 'The TLS handshake did not finish in time — the server may be down or filtering port 443. Nothing was judged about its certificate.';
|
||||
case 'refused':
|
||||
return 'The server refused the connection on port 443, so the certificate could not be read.';
|
||||
case 'dns_nxdomain':
|
||||
return 'That domain did not resolve, so there is no certificate to read.';
|
||||
case 'private_address':
|
||||
case 'private_host':
|
||||
return 'That address points into a private network and was not contacted.';
|
||||
case 'ip_literal':
|
||||
case 'bad_input':
|
||||
case 'bad_port':
|
||||
case 'bad_scheme':
|
||||
return (err && err.message) || 'That address could not be checked.';
|
||||
default:
|
||||
return `The certificate could not be read${err && err.message ? `: ${err.message}` : '.'}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// In-memory TTL cache. Deliberately not SQLite: this box must deploy with no native build step,
|
||||
// and the only state worth keeping across a restart is nothing — a cache that survives restarts
|
||||
// is how a "1 hour" promise turns into yesterday's DNS answer.
|
||||
|
||||
const store = new Map();
|
||||
const MAX_ENTRIES = 5000;
|
||||
|
||||
export function get(key) {
|
||||
const hit = store.get(key);
|
||||
if (!hit) return null;
|
||||
if (hit.expiresAt <= Date.now()) {
|
||||
store.delete(key);
|
||||
return null;
|
||||
}
|
||||
return hit.value;
|
||||
}
|
||||
|
||||
export function set(key, value, ttlMs) {
|
||||
if (store.size >= MAX_ENTRIES) {
|
||||
// drop the oldest insertion first; Map preserves order
|
||||
const oldest = store.keys().next();
|
||||
if (!oldest.done) store.delete(oldest.value);
|
||||
}
|
||||
store.set(key, { value, expiresAt: Date.now() + ttlMs });
|
||||
return value;
|
||||
}
|
||||
|
||||
export function drop(key) {
|
||||
store.delete(key);
|
||||
}
|
||||
|
||||
export function clear() {
|
||||
store.clear();
|
||||
}
|
||||
|
||||
export function size() {
|
||||
return store.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache the result of one check.
|
||||
* TTLs come from the honesty rule in AGENTS.md: a clean result is worth an hour, anything that
|
||||
* could be mid-fix by the visitor (a warning, an error, a blocked probe) is worth five minutes —
|
||||
* otherwise someone who just published a DNS change sees the old answer and concludes the tool
|
||||
* is broken.
|
||||
*/
|
||||
export const TTL_CLEAN_MS = 60 * 60 * 1000;
|
||||
export const TTL_DOUBT_MS = 5 * 60 * 1000;
|
||||
|
||||
export function ttlFor(state) {
|
||||
return state === 'ok' ? TTL_CLEAN_MS : TTL_DOUBT_MS;
|
||||
}
|
||||
|
||||
export async function cached(key, ttlMs, producer) {
|
||||
const hit = get(key);
|
||||
if (hit) return { ...hit, fromCache: true };
|
||||
const value = await producer();
|
||||
const ttl = typeof ttlMs === 'function' ? ttlMs(value) : ttlMs;
|
||||
set(key, value, ttl);
|
||||
return { ...value, fromCache: false };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Tiny HTML layer. No template engine: every string that reaches the page goes through esc(),
|
||||
// and the only dynamic markup is built from arrays.
|
||||
|
||||
export const PREFIX = '/check';
|
||||
export const ORIGIN = 'https://www.hoelee.com';
|
||||
|
||||
export function esc(value) {
|
||||
return String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
export function abs(path) {
|
||||
if (/^https?:\/\//.test(path)) return path;
|
||||
return `${ORIGIN}${PREFIX}${path.startsWith('/') ? path : `/${path}`}`;
|
||||
}
|
||||
|
||||
const NAV = [
|
||||
['/spf-dkim-dmarc/', 'Email', 'spf-dkim-dmarc'],
|
||||
['/ssl/', 'Certificate', 'ssl'],
|
||||
['/headers/', 'Redirects & headers', 'headers'],
|
||||
['/about/', 'How this works', 'about']
|
||||
];
|
||||
|
||||
export function layout({ title, description, body, active = '', robots = 'index,follow', canonical, extraHead = '' }) {
|
||||
const nav = NAV.map(([href, label, key]) => {
|
||||
const current = key === active ? ' aria-current="page"' : '';
|
||||
return `<a href="${esc(PREFIX + href)}"${current}>${esc(label)}</a>`;
|
||||
}).join('');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="en-MY">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${esc(title)}</title>
|
||||
<meta name="description" content="${esc(description)}">
|
||||
<meta name="robots" content="${esc(robots)}">
|
||||
<link rel="canonical" href="${esc(canonical || abs('/'))}">
|
||||
<link rel="stylesheet" href="${esc(PREFIX)}/assets/style.css">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="${esc(title)}">
|
||||
<meta property="og:description" content="${esc(description)}">
|
||||
<meta property="og:url" content="${esc(canonical || abs('/'))}">
|
||||
${extraHead}
|
||||
</head>
|
||||
<body>
|
||||
<header class="site"><div class="wrap">
|
||||
<a class="brand" href="${esc(PREFIX)}/">Hoelee Check <span>by Hoelee Enterprise</span></a>
|
||||
<nav>${nav}</nav>
|
||||
</div></header>
|
||||
<main><div class="wrap">
|
||||
${body}
|
||||
</div></main>
|
||||
<footer class="site"><div class="wrap">
|
||||
<p>Built and hosted by <a href="https://www.hoelee.com/">Hoelee Enterprise</a>, Perak, Malaysia.
|
||||
No trackers, no cookies, no account. Every check reads only what the public internet can already see.</p>
|
||||
<p><a href="${esc(PREFIX)}/about/">What this service queries, and what it refuses to do</a></p>
|
||||
</div></footer>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
export function badge(state, label) {
|
||||
const cls = state === 'not-evaluated' ? 'neutral' : state;
|
||||
return `<span class="badge ${esc(cls)}">${esc(label)}</span>`;
|
||||
}
|
||||
|
||||
export function form({ action = '/', value = '', label = 'Domain name', button = 'Run the check' }) {
|
||||
return `<form class="check" method="get" action="${esc(PREFIX + action)}">
|
||||
<label class="sr" for="d" hidden>${esc(label)}</label>
|
||||
<input id="d" name="d" type="text" inputmode="url" autocomplete="off" spellcheck="false"
|
||||
placeholder="yourbusiness.com.my" value="${esc(value)}" required>
|
||||
<button type="submit">${esc(button)}</button>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
export function evidenceTable(rows) {
|
||||
if (!rows || rows.length === 0) return '';
|
||||
const body = rows
|
||||
.map((r) => `<tr><th scope="row">${esc(r.label)}</th><td>${r.html ? r.html : `<span class="mono">${esc(r.value)}</span>`}${r.note ? `<div class="faint">${esc(r.note)}</div>` : ''}</td></tr>`)
|
||||
.join('');
|
||||
return `<table class="evidence">${body}</table>`;
|
||||
}
|
||||
|
||||
export function findingList(findings) {
|
||||
if (!findings || findings.length === 0) return '';
|
||||
return `<ul class="findings">${findings
|
||||
.map((f) => `<li class="${esc(f.level)}">${esc(f.message)}${f.fix ? `<span class="fix">${esc(f.fix)}</span>` : ''}</li>`)
|
||||
.join('')}</ul>`;
|
||||
}
|
||||
|
||||
export function whatsappPreview(preview, host) {
|
||||
const image = preview && preview.image
|
||||
? `<img src="${esc(preview.image)}" alt="" referrerpolicy="no-referrer" loading="lazy">`
|
||||
: 'No preview image found';
|
||||
return `<div class="wa">
|
||||
<div class="wa-label">How your link looks in WhatsApp</div>
|
||||
<div class="wa-img">${image}</div>
|
||||
<div class="wa-title">${esc((preview && preview.title) || host)}</div>
|
||||
<div class="wa-desc">${esc((preview && preview.description) || 'No description found — WhatsApp will show the bare link.')}</div>
|
||||
<div class="wa-url">${esc(host.toUpperCase())}</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
// net-guard — the only way this service is allowed to touch the network.
|
||||
//
|
||||
// Everything a visitor types passes through here first. The rules exist because a public "check
|
||||
// my website" box is otherwise an SSRF proxy into the home/office LAN it runs on, a way to read
|
||||
// cloud metadata, or an amplifier pointed at a third party.
|
||||
//
|
||||
// Rules, in order:
|
||||
// 1. a hostname only — no IP literals, no userinfo, no scheme other than http/https,
|
||||
// no port other than 80/443 (missing port = the scheme default);
|
||||
// 2. resolve once, validate EVERY A/AAAA answer; if any of them is private, refuse the whole
|
||||
// host (a host with one public and one private answer is a rebinding attempt, not a mistake);
|
||||
// 3. dial the pinned address (never re-resolve at connect time) while keeping the real hostname
|
||||
// for SNI and the Host header — that is the rebinding defence;
|
||||
// 4. redirects are followed by hand, one hop at a time, and every hop restarts at rule 1;
|
||||
// 5. bodies are capped and every request has a hard wall-clock deadline.
|
||||
|
||||
import net from 'node:net';
|
||||
import dns from 'node:dns';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import tls from 'node:tls';
|
||||
|
||||
export const ALLOWED_PORTS = new Set([80, 443]);
|
||||
export const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
export const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
|
||||
export const MAX_REDIRECTS = 5;
|
||||
|
||||
// IPv4 ranges that must never be reachable from a public tool.
|
||||
const BLOCKED_V4 = [
|
||||
['0.0.0.0', 8], // "this" network
|
||||
['10.0.0.0', 8], // private
|
||||
['100.64.0.0', 10], // CGNAT
|
||||
['127.0.0.0', 8], // loopback
|
||||
['169.254.0.0', 16], // link-local + cloud metadata (169.254.169.254)
|
||||
['172.16.0.0', 12], // private
|
||||
['192.0.0.0', 24], // IETF protocol assignments
|
||||
['192.0.2.0', 24], // documentation
|
||||
['192.88.99.0', 24], // 6to4 relay anycast
|
||||
['192.168.0.0', 16], // private
|
||||
['198.18.0.0', 15], // benchmarking
|
||||
['198.51.100.0', 24], // documentation
|
||||
['203.0.113.0', 24], // documentation
|
||||
['224.0.0.0', 4], // multicast
|
||||
['240.0.0.0', 4] // reserved + broadcast
|
||||
];
|
||||
|
||||
const BLOCKED_V6 = [
|
||||
['::', 128],
|
||||
['::1', 128],
|
||||
['fc00::', 7], // unique local
|
||||
['fe80::', 10], // link-local
|
||||
['ff00::', 8], // multicast
|
||||
['64:ff9b::', 96], // NAT64
|
||||
['2002::', 16], // 6to4
|
||||
['2001:db8::', 32] // documentation
|
||||
];
|
||||
|
||||
const BLOCKED_HOST_SUFFIXES = ['.local', '.internal', '.localhost', '.home', '.lan', '.intranet'];
|
||||
const BLOCKED_HOSTS = new Set(['localhost', 'localhost.localdomain', 'metadata.google.internal']);
|
||||
|
||||
export class NetGuardError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message);
|
||||
this.name = 'NetGuardError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function ipv4ToInt(ip) {
|
||||
const parts = ip.split('.');
|
||||
if (parts.length !== 4) return null;
|
||||
let out = 0;
|
||||
for (const part of parts) {
|
||||
if (!/^\d{1,3}$/.test(part)) return null;
|
||||
const n = Number(part);
|
||||
if (n > 255) return null;
|
||||
out = out * 256 + n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function ipv6ToBigInt(ip) {
|
||||
let text = ip.trim().toLowerCase();
|
||||
const zone = text.indexOf('%');
|
||||
if (zone !== -1) text = text.slice(0, zone); // fe80::1%eth0
|
||||
if (!text.includes(':')) return null;
|
||||
|
||||
// Embedded IPv4 tail (::ffff:127.0.0.1) is two groups, judged as IPv4 by the caller.
|
||||
let tail = [];
|
||||
const lastColon = text.lastIndexOf(':');
|
||||
const tailText = text.slice(lastColon + 1);
|
||||
if (tailText.includes('.')) {
|
||||
const v4 = ipv4ToInt(tailText);
|
||||
if (v4 === null) return null;
|
||||
tail = [(v4 >>> 16) & 0xffff, v4 & 0xffff];
|
||||
text = text.slice(0, lastColon + 1);
|
||||
if (!text.endsWith('::')) text = text.slice(0, -1);
|
||||
}
|
||||
|
||||
const halves = text.split('::');
|
||||
if (halves.length > 2) return null;
|
||||
const parseGroups = (s) => {
|
||||
if (s === '') return [];
|
||||
const out = [];
|
||||
for (const g of s.split(':')) {
|
||||
if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
|
||||
out.push(parseInt(g, 16));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
let groups;
|
||||
if (halves.length === 2) {
|
||||
const head = parseGroups(halves[0]);
|
||||
const rest = parseGroups(halves[1]);
|
||||
if (head === null || rest === null) return null;
|
||||
const fill = 8 - tail.length - head.length - rest.length;
|
||||
if (fill < 1) return null;
|
||||
groups = [...head, ...new Array(fill).fill(0), ...rest, ...tail];
|
||||
} else {
|
||||
const all = parseGroups(text);
|
||||
if (all === null) return null;
|
||||
groups = [...all, ...tail];
|
||||
}
|
||||
if (groups.length !== 8) return null;
|
||||
|
||||
let out = 0n;
|
||||
for (const g of groups) out = (out << 16n) + BigInt(g);
|
||||
return out;
|
||||
}
|
||||
|
||||
function inV4Range(value, base, bits) {
|
||||
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
||||
return (value & mask) === (base & mask);
|
||||
}
|
||||
|
||||
function inV6Range(value, base, bits) {
|
||||
const shift = BigInt(128 - bits);
|
||||
return (value >> shift) === (base >> shift);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the address must never be dialled by this service.
|
||||
* Unparseable input is treated as blocked: fail closed.
|
||||
*/
|
||||
export function isBlockedAddress(ip) {
|
||||
if (typeof ip !== 'string' || ip.length === 0) return true;
|
||||
const family = net.isIP(ip);
|
||||
if (family === 4) {
|
||||
const value = ipv4ToInt(ip);
|
||||
if (value === null) return true;
|
||||
return BLOCKED_V4.some(([base, bits]) => inV4Range(value, ipv4ToInt(base), bits));
|
||||
}
|
||||
if (family === 6) {
|
||||
const value = ipv6ToBigInt(ip);
|
||||
if (value === null) return true;
|
||||
// v4-mapped (::ffff:a.b.c.d) and v4-compatible must be judged as the v4 address
|
||||
const v4MappedBase = ipv6ToBigInt('::ffff:0:0');
|
||||
const v4CompatBase = ipv6ToBigInt('::');
|
||||
const high = value >> 32n;
|
||||
if (high === (v4MappedBase >> 32n) || value >> 32n === 0n) {
|
||||
const v4 = Number(value & 0xffffffffn);
|
||||
if (isBlockedAddress([(v4 >>> 24) & 255, (v4 >>> 16) & 255, (v4 >>> 8) & 255, v4 & 255].join('.'))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (value === v4CompatBase) return true;
|
||||
return BLOCKED_V6.some(([base, bits]) => inV6Range(value, ipv6ToBigInt(base), bits));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the hostname a visitor typed and normalise it.
|
||||
* Returns { host, port } — throws NetGuardError with a stable code otherwise.
|
||||
*/
|
||||
export function parseTarget(rawInput, { defaultPort = 443 } = {}) {
|
||||
if (typeof rawInput !== 'string') throw new NetGuardError('bad_input', 'No domain given.');
|
||||
let text = rawInput.trim().toLowerCase();
|
||||
if (text.length === 0) throw new NetGuardError('bad_input', 'No domain given.');
|
||||
if (text.length > 253) throw new NetGuardError('bad_input', 'That domain is too long.');
|
||||
if (text.startsWith('[')) throw new NetGuardError('ip_literal', 'Enter a domain name, not an IP address.');
|
||||
|
||||
let url = null;
|
||||
if (/^[a-z][a-z0-9+.-]*:\/\//.test(text)) {
|
||||
try { url = new URL(text); } catch { throw new NetGuardError('bad_input', 'That URL could not be read.'); }
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
throw new NetGuardError('bad_scheme', 'Only http and https addresses can be checked.');
|
||||
}
|
||||
if (url.username || url.password) {
|
||||
throw new NetGuardError('bad_input', 'Remove the username and password from the address.');
|
||||
}
|
||||
} else {
|
||||
if (text.includes('/')) text = text.split('/')[0];
|
||||
if (text.includes('@')) throw new NetGuardError('bad_input', 'Remove the username from the address.');
|
||||
}
|
||||
|
||||
let host;
|
||||
let port;
|
||||
if (url) {
|
||||
host = url.hostname.replace(/^\[|\]$/g, '');
|
||||
port = url.port ? Number(url.port) : (url.protocol === 'http:' ? 80 : 443);
|
||||
if (!url.port) {
|
||||
// keep the implicit default rather than inventing one
|
||||
port = url.protocol === 'http:' ? 80 : 443;
|
||||
}
|
||||
} else {
|
||||
const hostPort = text.split(':');
|
||||
host = hostPort[0];
|
||||
port = hostPort.length > 1 && hostPort[1] !== '' ? Number(hostPort[1]) : defaultPort;
|
||||
if (hostPort.length > 2) throw new NetGuardError('bad_input', 'That address has more than one colon.');
|
||||
}
|
||||
|
||||
host = host.replace(/\.$/, '');
|
||||
if (host.includes(':')) throw new NetGuardError('ip_literal', 'Enter a domain name, not an IP address.');
|
||||
if (net.isIP(host)) throw new NetGuardError('ip_literal', 'Enter a domain name, not an IP address.');
|
||||
|
||||
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(host)) {
|
||||
throw new NetGuardError('bad_input', 'That does not look like a domain name.');
|
||||
}
|
||||
if (!Number.isInteger(port) || !ALLOWED_PORTS.has(port)) {
|
||||
throw new NetGuardError('bad_port', 'Only ports 80 and 443 can be checked.');
|
||||
}
|
||||
if (BLOCKED_HOSTS.has(host) || BLOCKED_HOST_SUFFIXES.some((s) => host.endsWith(s))) {
|
||||
throw new NetGuardError('private_host', 'That is a private address and cannot be checked.');
|
||||
}
|
||||
return { host, port };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and validate. Every answer is checked; one private answer poisons the whole host.
|
||||
* `lookup` is injectable so tests never touch the network.
|
||||
*/
|
||||
export async function resolvePublic(host, { lookup, timeoutMs = 4000 } = {}) {
|
||||
const doLookup = lookup || defaultLookup;
|
||||
const answers = await withTimeout(doLookup(host, timeoutMs), timeoutMs, 'dns_timeout');
|
||||
const addresses = normaliseAnswers(answers);
|
||||
if (addresses.length === 0) throw new NetGuardError('dns_nxdomain', 'That domain did not resolve.');
|
||||
|
||||
for (const { address } of addresses) {
|
||||
if (isBlockedAddress(address)) {
|
||||
throw new NetGuardError('private_address', 'That domain points at a private address.');
|
||||
}
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
|
||||
function normaliseAnswers(answers) {
|
||||
if (!answers) return [];
|
||||
const list = Array.isArray(answers) ? answers : [answers];
|
||||
return list
|
||||
.map((a) => (typeof a === 'string' ? { address: a, family: net.isIP(a) } : a))
|
||||
.filter((a) => a && typeof a.address === 'string' && a.family);
|
||||
}
|
||||
|
||||
function defaultLookup(host) {
|
||||
// getaddrinfo via dns.lookup, not a hand-built Resolver: it is the same path curl and a browser
|
||||
// take, it honours the OS cache and hosts file, and it returns v4 and v6 answers in ONE call.
|
||||
// Two independent resolver queries (resolve4 + resolve6) meant a slow or broken IPv6 route could
|
||||
// stall every check for the full timeout even when the A record answered in 20 ms.
|
||||
return dns.promises.lookup(host, { all: true, verbatim: true });
|
||||
}
|
||||
|
||||
export function withTimeout(promise, ms, code) {
|
||||
let timer;
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new NetGuardError(code, 'That took too long.')), ms);
|
||||
})
|
||||
]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/**
|
||||
* One HTTP hop, dialling the pinned address. No redirect following here.
|
||||
* Returns { status, headers, body, url, address, timing }.
|
||||
*/
|
||||
export async function requestOnce(rawUrl, {
|
||||
lookup,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
maxBytes = DEFAULT_MAX_BYTES,
|
||||
method = 'GET',
|
||||
userAgent = defaultUserAgent()
|
||||
} = {}) {
|
||||
const { host, port } = parseTarget(rawUrl);
|
||||
const parsed = new URL(rawUrl.includes('://') ? rawUrl : `https://${rawUrl}`);
|
||||
parsed.hostname = host;
|
||||
parsed.port = String(port);
|
||||
const path = `${parsed.pathname || '/'}${parsed.search || ''}`;
|
||||
|
||||
const addresses = await resolvePublic(host, { lookup });
|
||||
const pinned = addresses[0];
|
||||
const started = Date.now();
|
||||
|
||||
const transport = port === 443 ? https : http;
|
||||
const result = await withTimeout(new Promise((resolve, reject) => {
|
||||
const req = transport.request({
|
||||
method,
|
||||
host, // Host header stays the real hostname
|
||||
servername: port === 443 ? host : undefined,
|
||||
path,
|
||||
port,
|
||||
agent: false,
|
||||
lookup: (_hostname, options, callback) => {
|
||||
const cb = typeof options === 'function' ? options : callback;
|
||||
if (options && options.all) return cb(null, [{ address: pinned.address, family: pinned.family }]);
|
||||
return cb(null, pinned.address, pinned.family);
|
||||
},
|
||||
headers: {
|
||||
host,
|
||||
'user-agent': userAgent,
|
||||
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
'accept-language': 'en-MY,en;q=0.9',
|
||||
'accept-encoding': 'identity',
|
||||
connection: 'close'
|
||||
},
|
||||
timeout: timeoutMs,
|
||||
rejectUnauthorized: true
|
||||
}, (res) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
let truncated = false;
|
||||
res.on('data', (chunk) => {
|
||||
size += chunk.length;
|
||||
if (size > maxBytes) {
|
||||
truncated = true;
|
||||
res.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
// The certificate is read off THIS socket: the report never opens a second connection
|
||||
// to the same host just to look at the cert (that would break the "one connection per
|
||||
// check" promise the about page makes and doubles the load on the target).
|
||||
let tls = null;
|
||||
try { tls = readCertificate(res.socket); } catch { tls = null; }
|
||||
const finish = () => resolve({
|
||||
status: res.statusCode || 0,
|
||||
headers: res.headers,
|
||||
body: Buffer.concat(chunks).toString('utf8'),
|
||||
url: parsed.toString(),
|
||||
address: pinned.address,
|
||||
family: pinned.family,
|
||||
truncated,
|
||||
tls,
|
||||
timing: { totalMs: Date.now() - started }
|
||||
});
|
||||
res.on('end', finish);
|
||||
res.on('close', finish);
|
||||
res.on('error', finish);
|
||||
});
|
||||
req.on('timeout', () => { req.destroy(new NetGuardError('timeout', 'The site did not answer in time.')); });
|
||||
req.on('error', (err) => reject(translateError(err)));
|
||||
req.end();
|
||||
}), timeoutMs + 500, 'timeout');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function translateError(err) {
|
||||
if (err instanceof NetGuardError) return err;
|
||||
const code = err && err.code ? err.code : 'request_failed';
|
||||
if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return new NetGuardError('dns_nxdomain', 'That domain did not resolve.');
|
||||
if (code === 'ECONNREFUSED') return new NetGuardError('refused', 'The server refused the connection.');
|
||||
if (code === 'CERT_HAS_EXPIRED') return new NetGuardError('tls_expired', 'The certificate on that site has expired.');
|
||||
if (['DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'ERR_TLS_CERT_ALTNAME_INVALID'].includes(code)) {
|
||||
return new NetGuardError('tls_invalid', 'The certificate on that site could not be verified.');
|
||||
}
|
||||
return new NetGuardError('request_failed', err && err.message ? err.message : 'The request failed.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow redirects by hand, re-validating every hop through parseTarget + resolvePublic.
|
||||
* Returns { hops: [...], final, body, headers, truncated } or throws a NetGuardError whose
|
||||
* `.final` carries whatever was fetched so far (so the report can still show a partial chain).
|
||||
*/
|
||||
export async function fetchFollowing(rawInput, {
|
||||
lookup,
|
||||
maxRedirects = MAX_REDIRECTS,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
maxBytes = DEFAULT_MAX_BYTES,
|
||||
userAgent,
|
||||
stopAfterBytes = null
|
||||
} = {}) {
|
||||
let current = /^[a-z][a-z0-9+.-]*:\/\//i.test(rawInput) ? rawInput : `https://${rawInput}`;
|
||||
const hops = [];
|
||||
const deadline = Date.now() + timeoutMs * (maxRedirects + 1);
|
||||
|
||||
for (let i = 0; i <= maxRedirects; i += 1) {
|
||||
if (Date.now() > deadline) throw new NetGuardError('timeout', 'That took too long.');
|
||||
const remaining = Math.max(1000, deadline - Date.now());
|
||||
const res = await requestOnce(current, { lookup, timeoutMs: Math.min(remaining, timeoutMs), maxBytes, userAgent });
|
||||
hops.push({
|
||||
url: res.url,
|
||||
status: res.status,
|
||||
location: res.headers.location || null,
|
||||
totalMs: res.timing.totalMs
|
||||
});
|
||||
const location = res.headers.location;
|
||||
if (res.status >= 300 && res.status < 400 && location) {
|
||||
const next = new URL(location, res.url).toString();
|
||||
const err = guardHop(next);
|
||||
if (err) {
|
||||
err.hops = hops;
|
||||
err.final = res;
|
||||
throw err;
|
||||
}
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
return { hops, final: res, body: res.body, headers: res.headers, truncated: res.truncated };
|
||||
}
|
||||
const err = new NetGuardError('too_many_redirects', `More than ${maxRedirects} redirects.`);
|
||||
err.hops = hops;
|
||||
throw err;
|
||||
}
|
||||
|
||||
export function guardHop(nextUrl) {
|
||||
try {
|
||||
const { host, port } = parseTarget(nextUrl);
|
||||
if (!ALLOWED_PORTS.has(port)) return new NetGuardError('bad_port', `Redirected to a port this tool will not open (${port}).`);
|
||||
if (BLOCKED_HOSTS.has(host) || BLOCKED_HOST_SUFFIXES.some((s) => host.endsWith(s))) {
|
||||
return new NetGuardError('private_host', 'Redirected to a private address.');
|
||||
}
|
||||
return null;
|
||||
} catch (err) {
|
||||
return err instanceof NetGuardError ? err : new NetGuardError('bad_input', 'Redirect target could not be read.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the peer certificate and its chain off a live socket (shared by TLS and HTTP paths). */
|
||||
export function readCertificate(socket) {
|
||||
if (!socket || typeof socket.getPeerCertificate !== 'function') return null;
|
||||
const cert = socket.getPeerCertificate(true);
|
||||
if (!cert || !cert.subject) return null;
|
||||
const chain = [];
|
||||
const seen = new Set();
|
||||
let cursor = cert;
|
||||
while (cursor && cursor.subject && !seen.has(cursor.fingerprint)) {
|
||||
seen.add(cursor.fingerprint);
|
||||
chain.push({
|
||||
subject: cursor.subject,
|
||||
issuer: cursor.issuer,
|
||||
validFrom: cursor.valid_from,
|
||||
validTo: cursor.valid_to,
|
||||
signatureAlgorithm: cursor.sigalg || null,
|
||||
fingerprint256: cursor.fingerprint256,
|
||||
selfSigned: JSON.stringify(cursor.subject) === JSON.stringify(cursor.issuer)
|
||||
});
|
||||
cursor = cursor.issuerCertificate;
|
||||
if (cursor && cursor.fingerprint === cert.fingerprint) break;
|
||||
}
|
||||
return {
|
||||
subject: cert.subject,
|
||||
issuer: cert.issuer,
|
||||
validFrom: cert.valid_from,
|
||||
validTo: cert.valid_to,
|
||||
subjectAltName: cert.subjectaltname || '',
|
||||
serialNumber: cert.serialNumber,
|
||||
fingerprint256: cert.fingerprint256,
|
||||
signatureAlgorithm: cert.sigalg || null,
|
||||
authorized: socket.authorized,
|
||||
authorizationError: socket.authorizationError || null,
|
||||
protocol: typeof socket.getProtocol === 'function' ? socket.getProtocol() : null,
|
||||
chain
|
||||
};
|
||||
}
|
||||
|
||||
/** One TLS handshake, pinned, with the real hostname as SNI. */
|
||||
export async function inspectTls(rawHost, { lookup, timeoutMs = 6000, port = 443 } = {}) {
|
||||
const { host } = parseTarget(rawHost, { defaultPort: port });
|
||||
const addresses = await resolvePublic(host, { lookup });
|
||||
const pinned = addresses[0];
|
||||
|
||||
return withTimeout(new Promise((resolve, reject) => {
|
||||
const socket = tls.connect({
|
||||
host: pinned.address,
|
||||
port,
|
||||
servername: host,
|
||||
rejectUnauthorized: false, // we inspect the certificate, we do not gate on it
|
||||
ALPNProtocols: ['http/1.1'],
|
||||
lookup: (_h, _o, cb) => cb(null, pinned.address, pinned.family)
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.once('secureConnect', () => {
|
||||
const cert = readCertificate(socket);
|
||||
const out = {
|
||||
host,
|
||||
port,
|
||||
address: pinned.address,
|
||||
alpn: socket.alpnProtocol || null,
|
||||
cipher: socket.getCipher(),
|
||||
cert,
|
||||
chain: cert ? cert.chain : []
|
||||
};
|
||||
socket.end();
|
||||
resolve(out);
|
||||
});
|
||||
socket.once('timeout', () => { socket.destroy(); reject(new NetGuardError('timeout', 'The TLS handshake timed out.')); });
|
||||
socket.once('error', (err) => reject(translateError(err)));
|
||||
}), timeoutMs + 500, 'timeout');
|
||||
}
|
||||
|
||||
export function defaultUserAgent() {
|
||||
return 'HoeleeCheck/1.0 (+https://www.hoelee.com/check/about/)';
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Per-IP request counters. In memory on purpose: a restart clearing the counters is a feature,
|
||||
// not a bug — it means the service holds no durable record of who asked what.
|
||||
//
|
||||
// 10 requests a minute keeps a person clicking around comfortable and a script out; 100 a day is
|
||||
// roughly "a whole office behind one NAT checked their own sites". Both are in the about page.
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const DAY = 24 * 60 * 60_000;
|
||||
|
||||
const buckets = new Map(); // ip -> { minuteStart, minuteCount, dayStart, dayCount }
|
||||
let lastSweep = Date.now();
|
||||
|
||||
function sweep(now) {
|
||||
if (now - lastSweep < 10 * MINUTE) return;
|
||||
lastSweep = now;
|
||||
for (const [ip, b] of buckets) {
|
||||
if (now - b.dayStart > DAY && now - b.minuteStart > MINUTE) buckets.delete(ip);
|
||||
}
|
||||
}
|
||||
|
||||
export function hit(ip, { perMinute = 10, perDay = 100, now = Date.now() } = {}) {
|
||||
sweep(now);
|
||||
const key = ip || 'unknown';
|
||||
let b = buckets.get(key);
|
||||
if (!b) {
|
||||
b = { minuteStart: now, minuteCount: 0, dayStart: now, dayCount: 0 };
|
||||
buckets.set(key, b);
|
||||
}
|
||||
if (now - b.minuteStart >= MINUTE) {
|
||||
b.minuteStart = now;
|
||||
b.minuteCount = 0;
|
||||
}
|
||||
if (now - b.dayStart >= DAY) {
|
||||
b.dayStart = now;
|
||||
b.dayCount = 0;
|
||||
}
|
||||
|
||||
const minuteExceeded = b.minuteCount >= perMinute;
|
||||
const dayExceeded = b.dayCount >= perDay;
|
||||
if (minuteExceeded || dayExceeded) {
|
||||
const retryAfterMs = minuteExceeded ? MINUTE - (now - b.minuteStart) : DAY - (now - b.dayStart);
|
||||
return {
|
||||
allowed: false,
|
||||
reason: minuteExceeded ? 'minute' : 'day',
|
||||
retryAfterSeconds: Math.max(1, Math.ceil(retryAfterMs / 1000)),
|
||||
remainingDay: Math.max(0, perDay - b.dayCount),
|
||||
resetAt: new Date(b.dayStart + DAY).toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
b.minuteCount += 1;
|
||||
b.dayCount += 1;
|
||||
return {
|
||||
allowed: true,
|
||||
remainingMinute: perMinute - b.minuteCount,
|
||||
remainingDay: perDay - b.dayCount,
|
||||
resetAt: new Date(b.dayStart + DAY).toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
export function reset() {
|
||||
buckets.clear();
|
||||
}
|
||||
|
||||
export function size() {
|
||||
return buckets.size;
|
||||
}
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
import { layout, esc, abs, PREFIX, badge, form, evidenceTable, findingList, whatsappPreview } from './lib/html.mjs';
|
||||
|
||||
const STATE_LABEL = {
|
||||
ok: 'Looks right',
|
||||
warn: 'Needs attention',
|
||||
fail: 'Broken',
|
||||
'not-evaluated': 'Skipped by firewall'
|
||||
};
|
||||
|
||||
const STATE_BADGE = {
|
||||
ok: ['ok', 'OK'],
|
||||
warn: ['warn', 'Attention'],
|
||||
fail: ['fail', 'Broken'],
|
||||
'not-evaluated': ['neutral', 'Skipped — not a fault']
|
||||
};
|
||||
|
||||
function stateBadge(state) {
|
||||
const [cls, label] = STATE_BADGE[state] || STATE_BADGE['not-evaluated'];
|
||||
return badge(cls, label);
|
||||
}
|
||||
|
||||
const CTA = `<div class="card">
|
||||
<h3>Want this fixed rather than explained?</h3>
|
||||
<p class="muted">Hoelee Enterprise is a one-person studio in Perak that looks after Malaysian business
|
||||
websites and business email. If a check above is red and you would rather someone just did it,
|
||||
<a href="https://www.hoelee.com/">have a look at what we do</a> or write to
|
||||
<a href="mailto:[email protected]">[email protected]</a>.</p>
|
||||
</div>`;
|
||||
|
||||
/* ---------------------------------------------------------------- hub */
|
||||
|
||||
export function hubPage() {
|
||||
const body = `
|
||||
<h1>Check your domain the way a customer meets it</h1>
|
||||
<p class="lede">Three things decide whether a Malaysian business looks real online: the padlock that
|
||||
expires without warning, the email settings that let anyone spoof your address, and the link preview
|
||||
your customer sees when you send them a WhatsApp. This service checks all three from the public
|
||||
internet, in about five seconds.</p>
|
||||
|
||||
${form({ action: '/', button: 'Run all three checks' })}
|
||||
<p class="faint">Enter the domain you send email from and put on your name card. Nothing is installed,
|
||||
nothing is uploaded, and no account is needed.</p>
|
||||
|
||||
<div class="grid" style="margin-top:28px">
|
||||
<div class="card">
|
||||
<h3><a href="${esc(PREFIX)}/ssl/">Certificate & HTTPS</a></h3>
|
||||
<p class="muted">When the padlock expires, Chrome shows a full-page warning and every customer
|
||||
turns back. We read the live certificate off the same connection a browser would make.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="${esc(PREFIX)}/spf-dkim-dmarc/">Email: SPF, DKIM, DMARC</a></h3>
|
||||
<p class="muted">Without these, anyone can send mail that claims to be from your address — and
|
||||
your own invoices start landing in spam.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><a href="${esc(PREFIX)}/headers/">Redirects, headers & link preview</a></h3>
|
||||
<p class="muted">We follow the redirect chain a visitor follows, then draw the card WhatsApp will
|
||||
show when someone pastes your link into a chat.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>What this is not</h2>
|
||||
<p>It is not a security audit, not a penetration test, and not a guarantee about where your email
|
||||
lands. It answers three narrow questions with evidence you can see, and it says
|
||||
<strong>skipped</strong> — not <strong>broken</strong> — when a site's firewall refuses to talk to a
|
||||
machine. <a href="${esc(PREFIX)}/about/">Exactly what it queries is written down here.</a></p>
|
||||
`;
|
||||
return layout({
|
||||
title: 'Hoelee Check — free domain, certificate and email check for Malaysian businesses',
|
||||
description:
|
||||
'Check the certificate, the SPF/DKIM/DMARC records and the WhatsApp link preview of any Malaysian business domain. Free, no account, nothing uploaded, results you can share.',
|
||||
canonical: abs('/'),
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- ssl page */
|
||||
|
||||
export function sslPage() {
|
||||
const body = `
|
||||
<h1>SSL certificate check — will the padlock still be there next month?</h1>
|
||||
<p class="lede">Most Malaysian SME sites do not break because of an attack. They break because a free
|
||||
certificate expired quietly on a Sunday and cPanel AutoSSL did not renew it. This check reads the
|
||||
certificate your server is presenting right now and tells you how many days are left.</p>
|
||||
|
||||
${form({ action: '/ssl/', button: 'Check the certificate' })}
|
||||
|
||||
<h2>What the check reads</h2>
|
||||
<ul class="muted">
|
||||
<li>The certificate the server actually presents on port 443 — not what a control panel claims.</li>
|
||||
<li>Days until expiry, and the exact expiry date.</li>
|
||||
<li>Whether the name you typed is listed in the certificate (including a wildcard match), because
|
||||
a valid certificate for the wrong name is still a warning page.</li>
|
||||
<li>The issuer, the chain, and the signature algorithm — SHA-1 certificates were deprecated years
|
||||
ago and some Android devices refuse them outright.</li>
|
||||
</ul>
|
||||
|
||||
<h2>What it cannot tell you</h2>
|
||||
<p>Whether the certificate is trusted on every old phone in Malaysia, and whether your host renews it
|
||||
automatically. It also cannot read a certificate that is only served on a port other than 443, and it
|
||||
cannot see a site behind a CDN that refuses automated visitors — in that case the result says
|
||||
<strong>skipped</strong>, and it does not pretend otherwise.</p>
|
||||
|
||||
<h2>How to read the result</h2>
|
||||
<p class="muted"><strong>Looks right</strong> means the certificate is valid for this name with more
|
||||
than a month left. <strong>Needs attention</strong> means under 30 days — plenty of time, which is
|
||||
exactly why it is worth acting on now. <strong>Broken</strong> means expired, wrong name, or a chain
|
||||
that browsers do not accept: visitors are seeing a warning page today.</p>
|
||||
|
||||
<h2>Frequently asked</h2>
|
||||
<h3>Is this the same as an SSL Labs grade?</h3>
|
||||
<p>No. A grade weighs cipher suites, protocol versions and dozens of other things. This answers a
|
||||
smaller question — is the certificate valid for this name, and when does it die — because that is the
|
||||
one that takes a small business offline.</p>
|
||||
<h3>Why does it say skipped?</h3>
|
||||
<p>The site's firewall or CDN refused an automated connection. Blocking bots is normal protection.
|
||||
We report it as skipped so nobody can screenshot our page and claim your site is unsafe.</p>
|
||||
<h3>How often should I check?</h3>
|
||||
<p>Once a month is enough for a certificate, or whenever a hosting bill changes. Set a reminder seven
|
||||
days before the expiry date shown.</p>
|
||||
${CTA}
|
||||
`;
|
||||
return layout({
|
||||
title: 'SSL certificate check for Malaysian websites — expiry, chain and wildcard match',
|
||||
description:
|
||||
'Read the live SSL certificate of any domain: days to expiry, issuer, chain and whether the name matches. Free, no account, nothing uploaded, and a firewall block is reported as skipped.',
|
||||
canonical: abs('/ssl/'),
|
||||
active: 'ssl',
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- email page */
|
||||
|
||||
export function emailAuthPage() {
|
||||
const body = `
|
||||
<h1>SPF, DKIM and DMARC check — can someone else send email as your business?</h1>
|
||||
<p class="lede">If your domain has no SPF record and no DMARC policy, a stranger can send an invoice
|
||||
from <span class="mono">[email protected]</span> and your customer has no way to tell.
|
||||
The same missing records are why your own quotations end up in the spam folder. This check reads the
|
||||
public DNS records and explains what they mean in business terms.</p>
|
||||
|
||||
${form({ action: '/spf-dkim-dmarc/', button: 'Check the email records' })}
|
||||
|
||||
<h2>What we look at</h2>
|
||||
<ul class="muted">
|
||||
<li><strong>SPF</strong> — which servers are allowed to send mail as your domain, what happens to
|
||||
everyone else, and how many DNS lookups the record costs (the limit is ten, and a record that
|
||||
quietly passes it fails for everybody).</li>
|
||||
<li><strong>DMARC</strong> — what your domain asks receivers to do with mail that fails the check.
|
||||
A policy of <span class="mono">p=none</span> only asks for reports: spoofing is still allowed.</li>
|
||||
<li><strong>DKIM</strong> — whether a public key exists at the common selector names, so receivers
|
||||
can prove a message was not altered on the way.</li>
|
||||
<li><strong>MX</strong> — the servers that receive your mail, in priority order, and whether a
|
||||
null MX says this domain deliberately accepts none.</li>
|
||||
</ul>
|
||||
|
||||
<h2>What this check cannot claim</h2>
|
||||
<p>A real SPF verdict is computed by the receiving mail server against the IP address that sent the
|
||||
message. We do not have that message, so we report the <em>shape</em> of your record and what it
|
||||
implies — never "SPF passes". Likewise, a DKIM key is published under a selector only the sender
|
||||
knows; we can look at the thirteen common ones, and if none answer we say so instead of declaring
|
||||
DKIM missing.</p>
|
||||
|
||||
<h2>How to read the result</h2>
|
||||
<p class="muted"><strong>Looks right</strong>: an SPF record that ends in a hard fail, a DMARC policy
|
||||
that rejects, at least one DKIM key, and mail servers that answer.
|
||||
<strong>Needs attention</strong>: monitoring-only DMARC, a soft SPF ending, or no key at the common
|
||||
selectors. <strong>Broken</strong>: no SPF record, more than one SPF record, or no MX at all — mail is
|
||||
either spoofable or not arriving.</p>
|
||||
|
||||
<h2>Frequently asked</h2>
|
||||
<h3>Does this read my email?</h3>
|
||||
<p>No. It reads public DNS records that anyone can look up, and nothing else. There is no mailbox
|
||||
access and no message content anywhere in this service.</p>
|
||||
<h3>I use Google Workspace or Microsoft 365. Is this still relevant?</h3>
|
||||
<p>Yes, and it is usually fine by default — but a domain that was migrated often keeps an old SPF
|
||||
record that no longer lists the right servers, and that is exactly what this check finds.</p>
|
||||
<h3>Somebody already spoofed us. What now?</h3>
|
||||
<p>Publish DMARC with <span class="mono">p=reject</span> after a month of reports, and make sure SPF
|
||||
and DKIM both align first. Doing it in the other order breaks your own outbound mail.</p>
|
||||
${CTA}
|
||||
`;
|
||||
return layout({
|
||||
title: 'SPF, DKIM and DMARC check for Malaysian domains — in plain English',
|
||||
description:
|
||||
'Read the SPF, DMARC, DKIM and MX records of any domain and see what they mean for spoofing and deliverability. Free, no account, nothing uploaded, with the limits of the check stated openly.',
|
||||
canonical: abs('/spf-dkim-dmarc/'),
|
||||
active: 'spf-dkim-dmarc',
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ headers page */
|
||||
|
||||
export function headersPage() {
|
||||
const body = `
|
||||
<h1>Redirect and link preview check — what a customer sees when you send your link</h1>
|
||||
<p class="lede">When you paste a link into a WhatsApp chat, the app fetches the page and draws a card:
|
||||
an image, a title, a short description. If those tags are missing the customer sees a bare grey URL,
|
||||
which looks like a scam. This check follows the same redirects a visitor's browser follows, then draws
|
||||
the card WhatsApp would draw.</p>
|
||||
|
||||
${form({ action: '/headers/', button: 'Check redirects and preview' })}
|
||||
|
||||
<h2>What the check reads</h2>
|
||||
<ul class="muted">
|
||||
<li>Every hop in the redirect chain, with its status code — including the common fault where
|
||||
<span class="mono">http://</span> redirects to <span class="mono">https://</span> and then straight
|
||||
back to <span class="mono">http://</span>.</li>
|
||||
<li>Whether the final page answers at all: a 404 or a 500 after two redirects is a broken link that
|
||||
passes a quick glance.</li>
|
||||
<li>The Open Graph tags that build the WhatsApp, Facebook and Telegram preview card: title,
|
||||
description, image, and whether the image URL is absolute and reachable.</li>
|
||||
<li>Security headers — HSTS, CSP, frame protection, referrer policy — with the honest label that a
|
||||
missing CSP is <em>optional hardening</em>, not a hole.</li>
|
||||
</ul>
|
||||
|
||||
<h2>What it cannot tell you</h2>
|
||||
<p>How Google ranks the page, whether the site is fast for a customer on Maxis in Ipoh, and what the
|
||||
page looks like once JavaScript runs — the check stops at the head of the HTML. A site that hides
|
||||
behind a bot wall is reported as <strong>skipped</strong>, because a 403 challenge page is not your
|
||||
website and we will not audit it as if it were.</p>
|
||||
|
||||
<h2>Frequently asked</h2>
|
||||
<h3>Why does my preview card look different from the one in this check?</h3>
|
||||
<p>WhatsApp caches previews it has already fetched. After fixing the tags, share the URL with
|
||||
<span class="mono">?v=2</span> appended to force a fresh fetch — a trick worth knowing before you
|
||||
conclude the fix did nothing.</p>
|
||||
<h3>Is a missing Content-Security-Policy a security problem?</h3>
|
||||
<p>It is missing hardening, not a break-in. Almost every small business site runs without one. We
|
||||
list it as information, not as a failure, because a red badge on something harmless teaches people to
|
||||
ignore red badges.</p>
|
||||
<h3>My site blocks bots on purpose. Will this always say skipped?</h3>
|
||||
<p>Yes, and that is the correct answer. We do not disguise the checker as a browser to get around a
|
||||
protection you deliberately turned on.</p>
|
||||
${CTA}
|
||||
`;
|
||||
return layout({
|
||||
title: 'Redirect chain and WhatsApp link preview check for any website',
|
||||
description:
|
||||
'Follow the redirects a visitor follows and see the WhatsApp link preview card your page builds from its Open Graph tags. Free, no account, nothing uploaded, firewall blocks reported as skipped.',
|
||||
canonical: abs('/headers/'),
|
||||
active: 'headers',
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- about page */
|
||||
|
||||
export function aboutPage() {
|
||||
const body = `
|
||||
<h1>What this service does, and how to prove it</h1>
|
||||
<p class="lede">A tool that asks you to trust it should let you check it. This page describes exactly
|
||||
what happens when you press the button, and gives you a way to test the central promise yourself.</p>
|
||||
|
||||
<h2>What happens when you run a check</h2>
|
||||
<ol class="muted">
|
||||
<li>Your domain is validated. IP addresses, private ranges, ports other than 80 and 443, and
|
||||
anything that resolves into a private network are refused. This service runs inside a home network
|
||||
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>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>
|
||||
|
||||
<h2>What is kept</h2>
|
||||
<p>No query log. No account. No cookie. No third-party script, font or image on these pages — open the
|
||||
network panel of your browser and you will see one stylesheet, served by this service.</p>
|
||||
<p>Two counters exist, in memory only, and both die when the process restarts: a per-IP request count
|
||||
(ten a minute, a hundred a day) and a cache of the public DNS and HTTP answers so that a link shared
|
||||
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
|
||||
<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>
|
||||
|
||||
<h2>What this service will not do</h2>
|
||||
<ul class="muted">
|
||||
<li>It will not test whether your email lands in the inbox — that needs a real message from a real
|
||||
server, and claiming otherwise would be dishonest.</li>
|
||||
<li>It will not check IP blacklists. The free DNSBL feeds that make this easy forbid commercial use
|
||||
and refuse queries from cloud resolvers, and a false positive there could cost somebody real mail.</li>
|
||||
<li>It will not crawl your site, measure its speed from one location, or identify your tech stack
|
||||
from a distance.</li>
|
||||
<li>It will not pretend a firewall is a fault. When a CDN refuses an automated probe, the row says
|
||||
<strong>skipped</strong> in grey, never red.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Who runs it</h2>
|
||||
<p>Hoelee Enterprise, a one-person studio in Perak, Malaysia, that builds websites and hosts business
|
||||
email for small Malaysian companies. This service is free because it is useful, and because a
|
||||
business that discovers a broken padlock here usually wants it fixed by somebody.</p>
|
||||
${CTA}
|
||||
`;
|
||||
return layout({
|
||||
title: 'How Hoelee Check works — what it queries, what it keeps, how to verify it',
|
||||
description:
|
||||
'Exactly what the domain check queries, what it refuses to do, what it keeps (nothing on disk) and how to prove the promise by watching your own server log.',
|
||||
canonical: abs('/about/'),
|
||||
active: 'about',
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- report page */
|
||||
|
||||
function section({ id, title, result, extra = '' }) {
|
||||
if (!result) return '';
|
||||
const bits = [
|
||||
`<div class="check-head"><h2>${esc(title)}</h2>${stateBadge(result.state)}</div>`,
|
||||
`<p class="muted">${esc(result.summary || '')}</p>`,
|
||||
extra,
|
||||
findingList(result.findings),
|
||||
`<details class="raw"><summary>What the check saw</summary>${evidenceTable(result.evidence)}</details>`
|
||||
];
|
||||
return `<section class="card" id="${esc(id)}">${bits.join('\n')}</section>`;
|
||||
}
|
||||
|
||||
export function reportPage({ host, results, httpResult, checkedAt, stale = false }) {
|
||||
const verified = results.filter((r) => r.state !== 'not-evaluated').length;
|
||||
const skipped = results.filter((r) => r.state === 'not-evaluated').length;
|
||||
const bad = results.filter((r) => r.state === 'fail').length;
|
||||
const warn = results.filter((r) => r.state === 'warn').length;
|
||||
|
||||
const headline = bad > 0
|
||||
? `${bad} thing${bad === 1 ? '' : 's'} broken${warn ? `, ${warn} worth a look` : ''}.`
|
||||
: warn > 0
|
||||
? `Nothing broken. ${warn} thing${warn === 1 ? '' : 's'} worth a look.`
|
||||
: 'Everything we can see looks right.';
|
||||
|
||||
const counts = [
|
||||
verified ? `<span class="badge ok">${verified} verified</span>` : '',
|
||||
warn ? `<span class="badge warn">${warn} to look at</span>` : '',
|
||||
bad ? `<span class="badge fail">${bad} broken</span>` : '',
|
||||
skipped ? `<span class="badge neutral">${skipped} skipped by firewall</span>` : ''
|
||||
].filter(Boolean).join('');
|
||||
|
||||
const preview = httpResult && httpResult.preview
|
||||
? whatsappPreview(httpResult.preview, host)
|
||||
: '';
|
||||
|
||||
const body = `
|
||||
<p class="faint"><a href="${esc(PREFIX)}/">Hoelee Check</a> · report for</p>
|
||||
<h1>${esc(host)}</h1>
|
||||
<div class="summary">
|
||||
<div>
|
||||
<p class="lede" style="margin-bottom:6px">${esc(headline)}</p>
|
||||
<div class="counts">${counts}</div>
|
||||
<p class="faint" style="margin-top:10px">Checked ${esc(new Date(checkedAt).toUTCString())}${stale ? ' · served from a short-lived cache' : ''}.
|
||||
Re-run for a fresh look: <a href="${esc(PREFIX)}/report/${esc(host)}?fresh=1">recheck now</a></p>
|
||||
</div>
|
||||
</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>
|
||||
<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}
|
||||
</section>` : ''}
|
||||
|
||||
${section({ id: 'tls', title: 'Certificate & HTTPS', result: results.find((r) => r.id === 'tls') })}
|
||||
${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') })}
|
||||
|
||||
${bad || warn ? CTA : ''}
|
||||
|
||||
<p class="faint">This report is not an audit and not a guarantee. It reads what the public internet
|
||||
can already see, once, from one machine in Malaysia.
|
||||
<a href="${esc(PREFIX)}/about/">What that means.</a></p>
|
||||
`;
|
||||
return layout({
|
||||
title: `${host} — certificate, email and link preview report`,
|
||||
description: `Certificate, email authentication and link preview results for ${host}.`,
|
||||
canonical: abs(`/report/${host}`),
|
||||
robots: 'noindex,nofollow',
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
export function errorPage({ title, message, status = 400 }) {
|
||||
const body = `
|
||||
<h1>${esc(title)}</h1>
|
||||
<p class="lede">${esc(message)}</p>
|
||||
${form({ action: '/', button: 'Try another domain' })}
|
||||
<p class="faint"><a href="${esc(PREFIX)}/about/">What this service accepts</a></p>
|
||||
`;
|
||||
return {
|
||||
status,
|
||||
html: layout({
|
||||
title: `${title} — Hoelee Check`,
|
||||
description: message,
|
||||
robots: 'noindex,follow',
|
||||
body
|
||||
})
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
:root {
|
||||
--bg: #0a0f1c;
|
||||
--panel: #121a2b;
|
||||
--panel-2: #16203442;
|
||||
--line: #24314b;
|
||||
--ink: #e8eefc;
|
||||
--ink-dim: #a9b6d0;
|
||||
--ink-faint: #7d8aa5;
|
||||
--brand: #7f9bff;
|
||||
--brand-fill: #3f5ce0;
|
||||
--ok: #4ade80;
|
||||
--warn: #fbbf24;
|
||||
--fail: #f87171;
|
||||
--neutral: #94a3b8;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font: 16px/1.6 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
|
||||
a { color: var(--brand); }
|
||||
a:hover { color: #a9baff; }
|
||||
|
||||
.wrap { max-width: 960px; margin: 0 auto; padding: 0 20px; }
|
||||
|
||||
header.site {
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #0c1322;
|
||||
}
|
||||
header.site .wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-height: 60px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
header.site .brand { font-weight: 700; letter-spacing: -0.01em; color: var(--ink); text-decoration: none; }
|
||||
header.site .brand span { color: var(--ink-faint); font-weight: 400; }
|
||||
header.site nav { margin-left: auto; display: flex; gap: 18px; flex-wrap: wrap; }
|
||||
header.site nav a { color: var(--ink-dim); text-decoration: none; font-size: 14px; }
|
||||
header.site nav a:hover, header.site nav a[aria-current="page"] { color: var(--ink); }
|
||||
|
||||
main { padding: 40px 0 64px; }
|
||||
|
||||
h1 { font-size: clamp(26px, 4vw, 38px); line-height: 1.2; letter-spacing: -0.02em; margin: 0 0 12px; }
|
||||
h2 { font-size: 22px; letter-spacing: -0.01em; margin: 40px 0 12px; }
|
||||
h3 { font-size: 17px; margin: 24px 0 8px; }
|
||||
p { margin: 0 0 14px; }
|
||||
.lede { font-size: 18px; color: var(--ink-dim); max-width: 62ch; }
|
||||
.muted { color: var(--ink-dim); }
|
||||
.faint { color: var(--ink-faint); font-size: 14px; }
|
||||
|
||||
form.check {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
margin: 24px 0 8px;
|
||||
}
|
||||
form.check input[type="text"] {
|
||||
flex: 1 1 320px;
|
||||
min-width: 0;
|
||||
padding: 14px 16px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0d1526;
|
||||
color: var(--ink);
|
||||
font-size: 16px;
|
||||
}
|
||||
form.check input[type="text"]:focus { outline: 2px solid var(--brand); outline-offset: 1px; }
|
||||
button, .button {
|
||||
padding: 14px 22px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid transparent;
|
||||
background: var(--brand-fill);
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
button:hover, .button:hover { background: #4a67ee; color: #fff; }
|
||||
|
||||
.card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 20px 22px;
|
||||
margin: 18px 0;
|
||||
}
|
||||
|
||||
.summary { display: flex; gap: 18px; align-items: flex-start; flex-wrap: wrap; }
|
||||
.summary .counts { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 6px; }
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
border: 1px solid;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge.ok { color: var(--ok); border-color: #4ade8055; background: #4ade8012; }
|
||||
.badge.warn { color: var(--warn); border-color: #fbbf2455; background: #fbbf2412; }
|
||||
.badge.fail { color: var(--fail); border-color: #f8717155; background: #f8717112; }
|
||||
.badge.neutral { color: var(--neutral); border-color: #94a3b855; background: #94a3b80f; }
|
||||
|
||||
.check-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.check-head h2 { margin: 0; }
|
||||
|
||||
.findings { list-style: none; padding: 0; margin: 14px 0 0; }
|
||||
.findings li { padding: 10px 0 10px 26px; position: relative; border-top: 1px solid var(--line); }
|
||||
.findings li:first-child { border-top: 0; }
|
||||
.findings li::before {
|
||||
position: absolute; left: 0; top: 10px; font-weight: 700;
|
||||
}
|
||||
.findings li.ok::before { content: "✓"; color: var(--ok); }
|
||||
.findings li.info::before { content: "i"; color: var(--ink-faint); font-style: italic; }
|
||||
.findings li.warn::before { content: "!"; color: var(--warn); }
|
||||
.findings li.fail::before { content: "×"; color: var(--fail); }
|
||||
.findings li .fix { display: block; color: var(--ink-dim); font-size: 14px; margin-top: 4px; }
|
||||
|
||||
/* WhatsApp-style link preview card */
|
||||
.wa {
|
||||
border-left: 4px solid #25d366;
|
||||
background: #0e1524;
|
||||
border-radius: 8px;
|
||||
padding: 12px 14px;
|
||||
max-width: 460px;
|
||||
}
|
||||
.wa .wa-label { color: #25d366; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; margin-bottom: 8px; }
|
||||
.wa .wa-img {
|
||||
width: 100%; aspect-ratio: 1.91 / 1; border-radius: 6px; background: #1a2438;
|
||||
display: flex; align-items: center; justify-content: center; color: var(--ink-faint);
|
||||
font-size: 13px; margin-bottom: 8px; overflow: hidden;
|
||||
}
|
||||
.wa .wa-img img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.wa .wa-title { font-weight: 600; margin-bottom: 2px; }
|
||||
.wa .wa-desc { color: var(--ink-dim); font-size: 14px; }
|
||||
.wa .wa-url { color: var(--ink-faint); font-size: 12px; margin-top: 6px; }
|
||||
|
||||
table.evidence { width: 100%; border-collapse: collapse; font-size: 14px; margin-top: 8px; }
|
||||
table.evidence th, table.evidence td { text-align: left; padding: 8px 10px; border-top: 1px solid var(--line); vertical-align: top; }
|
||||
table.evidence th { color: var(--ink-faint); font-weight: 500; width: 34%; }
|
||||
table.evidence code, .mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 13px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
details.raw { margin-top: 16px; border-top: 1px solid var(--line); padding-top: 12px; }
|
||||
details.raw summary { cursor: pointer; color: var(--ink-dim); font-size: 14px; }
|
||||
pre {
|
||||
background: #0d1526; border: 1px solid var(--line); border-radius: 10px;
|
||||
padding: 14px; overflow-x: auto; font-size: 13px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
|
||||
.grid .card { margin: 0; }
|
||||
.card h3 { margin-top: 0; }
|
||||
|
||||
footer.site { border-top: 1px solid var(--line); padding: 28px 0 40px; color: var(--ink-faint); font-size: 14px; }
|
||||
footer.site a { color: var(--ink-dim); }
|
||||
|
||||
.notice {
|
||||
border-left: 3px solid var(--brand);
|
||||
background: #121a2b;
|
||||
padding: 12px 16px;
|
||||
border-radius: 0 8px 8px 0;
|
||||
color: var(--ink-dim);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
form.check input[type="text"] { flex: 1 1 100%; }
|
||||
form.check button { width: 100%; }
|
||||
main { padding: 28px 0 48px; }
|
||||
}
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
// 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 = {
|
||||
'mail-auth': () => import('./checks/mail-auth.mjs'),
|
||||
tls: () => import('./checks/tls.mjs'),
|
||||
http: () => import('./checks/http.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' }
|
||||
};
|
||||
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
check,
|
||||
checkMailAuth,
|
||||
analyseMailAuth,
|
||||
parseSpf,
|
||||
parseDmarc,
|
||||
parseMx,
|
||||
readDkimKey,
|
||||
joinTxtChunks,
|
||||
findSpfRecords,
|
||||
countSpfLookups,
|
||||
DKIM_SELECTORS,
|
||||
DKIM_NO_KEY_MESSAGE,
|
||||
SPF_LOOKUP_LIMIT
|
||||
} from '../src/checks/mail-auth.mjs';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// fakes — nothing below this line opens a socket
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function dnsError(code) {
|
||||
const err = new Error(code);
|
||||
err.code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
/**
|
||||
* txt: { 'name': [['chunk','chunk'], ...] }
|
||||
* mx: { 'name': [{ exchange, priority }] }
|
||||
* a: { 'name': ['203.0.113.5'] }
|
||||
* A missing name answers `missing` (ENODATA = the name exists with no such record,
|
||||
* ENOTFOUND = the name does not exist); a value that is an Error is thrown as-is.
|
||||
*/
|
||||
function fakeDns({ txt = {}, mx = {}, a = {}, missing = 'ENODATA' } = {}) {
|
||||
const lookup = (table, host) => {
|
||||
const key = String(host).toLowerCase().replace(/\.$/, '');
|
||||
return Object.prototype.hasOwnProperty.call(table, key) ? table[key] : undefined;
|
||||
};
|
||||
const run = async (table, host) => {
|
||||
const value = lookup(table, host);
|
||||
if (value === undefined) throw dnsError(missing);
|
||||
if (value instanceof Error) throw value;
|
||||
return value;
|
||||
};
|
||||
return {
|
||||
resolveTxt: (host) => run(txt, host),
|
||||
resolveMx: (host) => run(mx, host),
|
||||
resolve4: (host) => run(a, host)
|
||||
};
|
||||
}
|
||||
|
||||
const KEDAI = 'kedai.my';
|
||||
|
||||
// A realistic Malaysian SME: one provider, hard SPF, reject DMARC, Google DKIM, two MX.
|
||||
function cleanFixture(overrides = {}) {
|
||||
return {
|
||||
txt: {
|
||||
[KEDAI]: [
|
||||
['v=spf1 include:spf.mailhost.my -all'],
|
||||
['google-site-verification=abc123']
|
||||
],
|
||||
'spf.mailhost.my': [['v=spf1 ip4:203.115.10.0/24 -all']],
|
||||
[`_dmarc.${KEDAI}`]: [['v=DMARC1; p=reject; rua=mailto:[email protected]']],
|
||||
[`google._domainkey.${KEDAI}`]: [['v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA']],
|
||||
...overrides.txt
|
||||
},
|
||||
mx: {
|
||||
[KEDAI]: [
|
||||
{ exchange: 'mx2.mailhost.my', priority: 20 },
|
||||
{ exchange: 'mx1.mailhost.my', priority: 10 }
|
||||
],
|
||||
...overrides.mx
|
||||
},
|
||||
a: {
|
||||
'mx1.mailhost.my': ['203.115.10.5'],
|
||||
'mx2.mailhost.my': ['203.115.10.6'],
|
||||
...overrides.a
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const codes = (result) => result.findings.map((finding) => finding.code);
|
||||
const finding = (result, code) => result.findings.find((entry) => entry.code === code);
|
||||
const evidence = (result, label) => result.evidence.find((entry) => entry.label === label);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (a) the clean setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('clean SME setup: SPF -all, DMARC reject, one DKIM selector, live MX — state ok', async () => {
|
||||
const result = await check(KEDAI, { dns: fakeDns(cleanFixture()), now: Date.parse('2026-11-10T04:00:00Z') });
|
||||
|
||||
assert.equal(result.id, 'mail-auth');
|
||||
assert.equal(result.state, 'ok', `unexpected findings: ${codes(result).join(',')}`);
|
||||
assert.equal(result.summary, 'Mail can be delivered, and only your own servers can send as your domain.');
|
||||
assert.equal(result.fromCache, false);
|
||||
assert.equal(result.checkedAt, '2026-11-10T04:00:00.000Z');
|
||||
|
||||
assert.equal(finding(result, 'spf_all_hardfail').level, 'ok');
|
||||
assert.equal(finding(result, 'dmarc_reject').level, 'ok');
|
||||
assert.equal(finding(result, 'dkim_key_found').level, 'ok');
|
||||
assert.equal(finding(result, 'mx_present').level, 'ok');
|
||||
|
||||
assert.equal(evidence(result, 'SPF record').value, 'v=spf1 include:spf.mailhost.my -all');
|
||||
assert.equal(evidence(result, 'SPF lookups').value, `1 of ${SPF_LOOKUP_LIMIT}`);
|
||||
assert.equal(evidence(result, 'DMARC policy').value, 'p=reject');
|
||||
assert.equal(evidence(result, 'DKIM key').value, 'google');
|
||||
|
||||
// MX evidence is sorted by priority, not by the order the resolver returned.
|
||||
assert.equal(evidence(result, 'MX records').value, '10 mx1.mailhost.my, 20 mx2.mailhost.my');
|
||||
assert.equal(checkMailAuth, check);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (b) TXT split across the 255-byte boundary
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('TXT record split mid-mechanism is joined before parsing', async () => {
|
||||
const records = [['v=spf1 include:exam', 'ple.com -all']];
|
||||
|
||||
// The join must not invent a separator: 'exam' + 'ple.com' = 'example.com'.
|
||||
assert.deepEqual(joinTxtChunks(records), ['v=spf1 include:example.com -all']);
|
||||
|
||||
const parsed = parseSpf(joinTxtChunks(records)[0]);
|
||||
const include = parsed.mechanisms.find((mechanism) => mechanism.name === 'include');
|
||||
assert.equal(include.value, 'example.com', 'the include target must survive the split intact');
|
||||
assert.equal(parsed.all.qualifier, '-');
|
||||
|
||||
const result = await check('split.my', {
|
||||
dns: fakeDns({
|
||||
txt: {
|
||||
'split.my': records,
|
||||
'example.com': [['v=spf1 ip4:203.0.113.10 -all']],
|
||||
'_dmarc.split.my': [['v=DMARC1; p=reject']]
|
||||
},
|
||||
mx: { 'split.my': [{ exchange: 'mx.split.my', priority: 10 }] },
|
||||
a: { 'mx.split.my': ['203.0.113.11'] }
|
||||
})
|
||||
});
|
||||
|
||||
assert.equal(evidence(result, 'SPF record').value, 'v=spf1 include:example.com -all');
|
||||
// The include target was actually followed, which can only happen if the name was intact.
|
||||
assert.equal(evidence(result, 'SPF lookups').value, `1 of ${SPF_LOOKUP_LIMIT}`);
|
||||
assert.ok(!codes(result).includes('spf_include_no_record'), 'example.com must have been resolved as an SPF target');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (c) two SPF records = permerror
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('two v=spf1 records is a fail with reason permerror', async () => {
|
||||
const result = await check('two.my', {
|
||||
dns: fakeDns({
|
||||
txt: {
|
||||
'two.my': [['v=spf1 include:a.my -all'], ['v=spf1 include:b.my ~all']],
|
||||
'_dmarc.two.my': [['v=DMARC1; p=reject']]
|
||||
},
|
||||
mx: { 'two.my': [{ exchange: 'mx.two.my', priority: 10 }] },
|
||||
a: { 'mx.two.my': ['203.0.113.20'] }
|
||||
})
|
||||
});
|
||||
|
||||
const spf = finding(result, 'spf_multiple');
|
||||
assert.equal(spf.level, 'fail');
|
||||
assert.match(spf.message, /permerror/, 'the reason must be named as permerror');
|
||||
assert.match(spf.message, /2 SPF records/);
|
||||
assert.equal(result.state, 'fail');
|
||||
assert.match(evidence(result, 'SPF record').value, /permerror/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (d) include loop
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('an include loop stops cleanly instead of throwing', async () => {
|
||||
const dns = fakeDns({
|
||||
txt: {
|
||||
'loop.my': [['v=spf1 include:b.my -all']],
|
||||
'b.my': [['v=spf1 include:loop.my -all']]
|
||||
},
|
||||
mx: { 'loop.my': [{ exchange: 'mx.loop.my', priority: 10 }] },
|
||||
a: { 'mx.loop.my': ['203.0.113.30'] }
|
||||
});
|
||||
|
||||
const walk = await countSpfLookups('loop.my', 'v=spf1 include:b.my -all', { dns });
|
||||
assert.equal(walk.lookups, 2, 'each side of the loop is counted once');
|
||||
assert.equal(walk.cycles, 1);
|
||||
assert.equal(walk.depthCapped, false);
|
||||
|
||||
const result = await check('loop.my', { dns });
|
||||
assert.equal(result.state !== undefined, true);
|
||||
assert.equal(finding(result, 'spf_include_loop').level, 'warn');
|
||||
assert.ok(!codes(result).includes('spf_lookup_limit'));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (e) lookup counting: 11 fails, 9 warns
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function manyIncludes(count, domain) {
|
||||
const names = Array.from({ length: count }, (_, i) => `spf${i}.example.my`);
|
||||
const txt = { [domain]: [[`v=spf1 ${names.map((name) => `include:${name}`).join(' ')} -all`]] };
|
||||
for (const name of names) txt[name] = [['v=spf1 ip4:203.0.113.9 -all']];
|
||||
return txt;
|
||||
}
|
||||
|
||||
test('11 DNS lookups is a fail at the RFC 7208 limit', async () => {
|
||||
const txt = manyIncludes(11, 'big.my');
|
||||
txt['_dmarc.big.my'] = [['v=DMARC1; p=reject']];
|
||||
const dns = fakeDns({ txt, mx: { 'big.my': [{ exchange: 'mx.big.my', priority: 10 }] }, a: { 'mx.big.my': ['203.0.113.40'] } });
|
||||
|
||||
const walk = await countSpfLookups('big.my', txt['big.my'][0][0], { dns });
|
||||
assert.equal(walk.lookups, 11);
|
||||
|
||||
const result = await check('big.my', { dns });
|
||||
const limit = finding(result, 'spf_lookup_limit');
|
||||
assert.equal(limit.level, 'fail');
|
||||
assert.match(limit.message, /11 DNS lookups/);
|
||||
assert.equal(result.state, 'fail');
|
||||
});
|
||||
|
||||
test('9 DNS lookups warns before the limit is reached', async () => {
|
||||
const txt = manyIncludes(9, 'near.my');
|
||||
txt['_dmarc.near.my'] = [['v=DMARC1; p=reject']];
|
||||
const dns = fakeDns({ txt, mx: { 'near.my': [{ exchange: 'mx.near.my', priority: 10 }] }, a: { 'mx.near.my': ['203.0.113.41'] } });
|
||||
|
||||
const result = await check('near.my', { dns });
|
||||
const near = finding(result, 'spf_lookups_near_limit');
|
||||
assert.equal(near.level, 'warn');
|
||||
assert.equal(evidence(result, 'SPF lookups').value, `9 of ${SPF_LOOKUP_LIMIT}`);
|
||||
assert.equal(result.state, 'warn');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (f) p=none
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('p=none reads as monitoring only, not as protection', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.txt[`_dmarc.${KEDAI}`] = [['v=DMARC1; p=none; rua=mailto:[email protected]']];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const none = finding(result, 'dmarc_none');
|
||||
|
||||
assert.equal(none.level, 'warn');
|
||||
assert.match(none.message, /monitoring only/);
|
||||
assert.match(none.message, /spoofing is still allowed/);
|
||||
assert.equal(evidence(result, 'DMARC policy').value, 'p=none');
|
||||
assert.equal(result.state, 'warn');
|
||||
assert.equal(result.summary, 'Mail can be delivered, but a spoofed email could still get through.');
|
||||
});
|
||||
|
||||
test('pct<100 and a missing rua are notes, not faults', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.txt[`_dmarc.${KEDAI}`] = [['v=DMARC1; p=reject; pct=50']];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
assert.equal(finding(result, 'dmarc_partial_pct').level, 'info');
|
||||
assert.equal(finding(result, 'dmarc_no_rua').level, 'info');
|
||||
assert.equal(result.state, 'ok', 'notes must not turn a working setup amber');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (g) no DMARC at all
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('missing DMARC is a warn with a one-line fix, never a fail', async () => {
|
||||
const fixture = cleanFixture();
|
||||
delete fixture.txt[`_dmarc.${KEDAI}`];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const dmarc = finding(result, 'dmarc_missing');
|
||||
|
||||
assert.equal(dmarc.level, 'warn');
|
||||
assert.match(dmarc.fix, /_dmarc\.kedai\.my/);
|
||||
assert.match(dmarc.fix, /v=DMARC1/);
|
||||
assert.ok(!dmarc.fix.includes('\n'), 'the fix must be one line');
|
||||
assert.equal(result.state, 'warn');
|
||||
assert.equal(evidence(result, 'DMARC record').value, 'none');
|
||||
});
|
||||
|
||||
test('an unreadable _dmarc lookup says unknown rather than missing', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.txt[`_dmarc.${KEDAI}`] = dnsError('SERVFAIL');
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
assert.ok(!codes(result).includes('dmarc_missing'), 'a SERVFAIL must not be reported as "no DMARC"');
|
||||
assert.equal(finding(result, 'dmarc_not_checked').level, 'info');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (h) no MX
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('no MX at all is a warn with a fix', async () => {
|
||||
const fixture = cleanFixture();
|
||||
delete fixture.mx[KEDAI];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const mx = finding(result, 'mx_missing');
|
||||
|
||||
assert.equal(mx.level, 'warn');
|
||||
assert.match(mx.fix, /MX record/);
|
||||
assert.match(result.summary, /may bounce/);
|
||||
assert.equal(result.state, 'warn');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (i) null MX is a deliberate setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('a null MX is reported as deliberate, not as a fault', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.mx[KEDAI] = [{ exchange: '.', priority: 0 }];
|
||||
delete fixture.a['mx1.mailhost.my'];
|
||||
delete fixture.a['mx2.mailhost.my'];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const nullMx = finding(result, 'mx_null');
|
||||
|
||||
assert.equal(nullMx.level, 'ok');
|
||||
assert.match(nullMx.message, /deliberate/);
|
||||
assert.match(nullMx.message, /valid setup/);
|
||||
assert.match(nullMx.message, /not a fault/);
|
||||
assert.ok(!codes(result).includes('mx_missing'), 'a null MX is not a missing MX');
|
||||
assert.equal(result.state, 'ok');
|
||||
assert.match(evidence(result, 'MX records').value, /null MX/);
|
||||
});
|
||||
|
||||
test('parseMx sorts by priority and detects a null MX', () => {
|
||||
const sorted = parseMx([
|
||||
{ exchange: 'mx-b.example.my', priority: 20 },
|
||||
{ exchange: 'mx-a.example.my', priority: 10 },
|
||||
{ exchange: 'mx-c.example.my', priority: 10 }
|
||||
]);
|
||||
assert.deepEqual(sorted.records.map((record) => record.exchange), ['mx-a.example.my', 'mx-c.example.my', 'mx-b.example.my']);
|
||||
assert.equal(sorted.nullMx, false);
|
||||
|
||||
const nullMx = parseMx([{ exchange: '.', priority: 0 }]);
|
||||
assert.equal(nullMx.nullMx, true);
|
||||
assert.equal(nullMx.count, 0);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (j) SERVFAIL / timeout
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('a SERVFAIL for the domain is not-evaluated, not a fail', async () => {
|
||||
const dns = fakeDns({
|
||||
txt: { [KEDAI]: dnsError('SERVFAIL') },
|
||||
mx: { [KEDAI]: dnsError('SERVFAIL') }
|
||||
});
|
||||
|
||||
const result = await check(KEDAI, { dns });
|
||||
assert.equal(result.state, 'not-evaluated');
|
||||
assert.equal(finding(result, 'dns_unavailable').level, 'info');
|
||||
assert.equal(result.findings.filter((entry) => entry.level === 'fail').length, 0, 'no failure may be pinned on the site');
|
||||
assert.match(result.summary, /not a verdict/);
|
||||
});
|
||||
|
||||
test('a timeout is also not-evaluated', async () => {
|
||||
const result = await check(KEDAI, {
|
||||
dns: fakeDns({ txt: { [KEDAI]: dnsError('ETIMEOUT') }, mx: { [KEDAI]: dnsError('ETIMEOUT') } })
|
||||
});
|
||||
assert.equal(result.state, 'not-evaluated');
|
||||
assert.ok(!codes(result).includes('spf_missing'));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// (k) DKIM wording
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('no DKIM key found uses the exact required sentence', async () => {
|
||||
const fixture = cleanFixture();
|
||||
delete fixture.txt[`google._domainkey.${KEDAI}`];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const dkim = finding(result, 'dkim_no_key_found');
|
||||
|
||||
assert.equal(
|
||||
dkim.message,
|
||||
'No key found among the 13 common selectors; a custom selector cannot be found from DNS alone.'
|
||||
);
|
||||
assert.equal(dkim.message, DKIM_NO_KEY_MESSAGE);
|
||||
assert.equal(dkim.level, 'info', 'an unfound key is absence of evidence, not a fault');
|
||||
assert.ok(!/not configured|broken/i.test(dkim.message), 'the forbidden wording must never appear');
|
||||
assert.equal(evidence(result, 'DKIM key').value, 'none of 13 selectors');
|
||||
// An unknown selector must not stop a working setup being reported as working.
|
||||
assert.equal(result.state, 'ok');
|
||||
});
|
||||
|
||||
test('the selector list is exactly the 13 required probes', () => {
|
||||
assert.deepEqual(
|
||||
[...DKIM_SELECTORS],
|
||||
['default', 'google', 'selector1', 'selector2', 's1', 's2', 'k1', 'k2', 'mail', 'dkim', 'mandrill', 'amazonses', 'smtp']
|
||||
);
|
||||
assert.equal(DKIM_SELECTORS.length, 13);
|
||||
assert.ok(DKIM_NO_KEY_MESSAGE.includes('13 common selectors'));
|
||||
});
|
||||
|
||||
test('a revoked DKIM key (p= empty) is not reported as a key', () => {
|
||||
const revoked = readDkimKey(['v=DKIM1; k=rsa; p=']);
|
||||
assert.equal(revoked.key, false);
|
||||
assert.equal(revoked.revoked, true);
|
||||
|
||||
const live = readDkimKey(['v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A']);
|
||||
assert.equal(live.key, true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SPF qualifier verdicts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('+all and ?all are fails: both authorise spoofing', async () => {
|
||||
for (const [record, code] of [
|
||||
['v=spf1 +all', 'spf_all_pass_all'],
|
||||
['v=spf1 ?all', 'spf_all_neutral'],
|
||||
['v=spf1 all', 'spf_all_pass_all']
|
||||
]) {
|
||||
const fixture = cleanFixture();
|
||||
fixture.txt[KEDAI] = [[record]];
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const found = finding(result, code);
|
||||
assert.ok(found, `${record} should raise ${code}`);
|
||||
assert.equal(found.level, 'fail');
|
||||
assert.equal(result.state, 'fail');
|
||||
}
|
||||
});
|
||||
|
||||
test('~all is a warn, not a pass', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.txt[KEDAI] = [['v=spf1 include:spf.mailhost.my ~all']];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
assert.equal(finding(result, 'spf_all_softfail').level, 'warn');
|
||||
assert.equal(result.state, 'warn');
|
||||
});
|
||||
|
||||
test('parseSpf reads qualifiers, cidr and modifiers without counting ip4/ip6', () => {
|
||||
const parsed = parseSpf('v=spf1 ip4:203.0.113.0/24 ip6:2001:db8::/32 a:mail.example.my/24 mx ptr exists:%{i}.example.my include:_spf.example.my redirect=_spf2.example.my -all');
|
||||
|
||||
assert.equal(parsed.valid, true);
|
||||
assert.equal(parsed.all.qualifier, '-');
|
||||
assert.equal(parsed.redirect, '_spf2.example.my');
|
||||
// a, mx, ptr, exists, include, redirect = 6; ip4/ip6/all cost nothing.
|
||||
assert.equal(parsed.lookups, 6);
|
||||
|
||||
const a = parsed.mechanisms.find((mechanism) => mechanism.name === 'a');
|
||||
assert.equal(a.value, 'mail.example.my');
|
||||
assert.equal(a.cidr, '24');
|
||||
|
||||
const ip6 = parsed.mechanisms.find((mechanism) => mechanism.name === 'ip6');
|
||||
assert.equal(ip6.value, '2001:db8::');
|
||||
|
||||
// A macro target cannot be resolved from here, so it is not followed.
|
||||
const exists = parsed.mechanisms.find((mechanism) => mechanism.name === 'exists');
|
||||
assert.equal(exists.value, '%{i}.example.my');
|
||||
});
|
||||
|
||||
test('parseDmarc defaults pct to 100 and keeps every tag', () => {
|
||||
const parsed = parseDmarc('v=DMARC1; p=quarantine; sp=reject; pct=75; adkim=s; aspf=r; rua=mailto:[email protected], mailto:[email protected]; fo=1');
|
||||
assert.equal(parsed.valid, true);
|
||||
assert.equal(parsed.p, 'quarantine');
|
||||
assert.equal(parsed.sp, 'reject');
|
||||
assert.equal(parsed.pct, 75);
|
||||
assert.equal(parsed.adkim, 's');
|
||||
assert.equal(parsed.aspf, 'r');
|
||||
assert.deepEqual(parsed.rua, ['mailto:[email protected]', 'mailto:[email protected]']);
|
||||
assert.equal(parseDmarc('v=DMARC1; p=reject').pct, 100);
|
||||
assert.equal(parseDmarc('p=reject').valid, false);
|
||||
});
|
||||
|
||||
test('findSpfRecords ignores lookalikes and keeps the real record', () => {
|
||||
const txts = ['google-site-verification=abc', 'v=spf10 -all', 'v=spf1 -all', 'spf2.0/pra -all'];
|
||||
assert.deepEqual(findSpfRecords(txts), ['v=spf1 -all']);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// contract + edges
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('the return value matches the checks contract', async () => {
|
||||
const now = Date.parse('2026-11-10T04:00:00Z');
|
||||
const result = await check(KEDAI, { dns: fakeDns(cleanFixture()), now });
|
||||
|
||||
assert.deepEqual(Object.keys(result).sort(), ['checkedAt', 'evidence', 'findings', 'fromCache', 'id', 'state', 'summary']);
|
||||
assert.equal(result.id, 'mail-auth');
|
||||
assert.equal(result.fromCache, false);
|
||||
assert.equal(result.checkedAt, new Date(now).toISOString());
|
||||
assert.ok(['ok', 'warn', 'fail', 'not-evaluated'].includes(result.state));
|
||||
assert.ok(result.summary.length > 0 && !result.summary.includes('\n'), 'summary is one line');
|
||||
|
||||
for (const item of result.evidence) {
|
||||
assert.equal(typeof item.label, 'string');
|
||||
assert.equal(typeof item.value, 'string');
|
||||
assert.ok(!('note' in item) || typeof item.note === 'string');
|
||||
}
|
||||
for (const item of result.findings) {
|
||||
assert.ok(['ok', 'info', 'warn', 'fail'].includes(item.level));
|
||||
assert.equal(typeof item.code, 'string');
|
||||
assert.equal(typeof item.message, 'string');
|
||||
assert.ok(!('fix' in item) || typeof item.fix === 'string');
|
||||
}
|
||||
});
|
||||
|
||||
test('state is the worst finding level', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.txt[KEDAI] = [['v=spf1 include:spf.mailhost.my +all']];
|
||||
fixture.txt[`_dmarc.${KEDAI}`] = [['v=DMARC1; p=none']];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
assert.equal(result.state, 'fail');
|
||||
assert.ok(result.findings.some((entry) => entry.level === 'fail'));
|
||||
});
|
||||
|
||||
test('a domain that does not exist is not-evaluated', async () => {
|
||||
const result = await check('nope.my', { dns: fakeDns({ missing: 'ENOTFOUND' }) });
|
||||
assert.equal(result.state, 'not-evaluated');
|
||||
assert.equal(finding(result, 'domain_not_found').level, 'info');
|
||||
assert.equal(evidence(result, 'DNS').value, 'no records');
|
||||
});
|
||||
|
||||
test('a domain that exists but publishes nothing at all fails SPF, never "not-evaluated"', async () => {
|
||||
// ENODATA means the name exists — that is a real (empty) email setup, not a DNS failure.
|
||||
const result = await check(KEDAI, { dns: fakeDns({}) });
|
||||
assert.equal(finding(result, 'spf_missing').level, 'fail');
|
||||
assert.equal(finding(result, 'mx_missing').level, 'warn');
|
||||
assert.equal(result.state, 'fail');
|
||||
});
|
||||
|
||||
test('a domain with MX but no TXT at all fails SPF and warns DMARC', async () => {
|
||||
const result = await check(KEDAI, {
|
||||
dns: fakeDns({
|
||||
mx: { [KEDAI]: [{ exchange: 'mx.mailhost.my', priority: 10 }] },
|
||||
a: { 'mx.mailhost.my': ['203.115.10.7'] }
|
||||
})
|
||||
});
|
||||
assert.equal(finding(result, 'spf_missing').level, 'fail');
|
||||
assert.equal(finding(result, 'dmarc_missing').level, 'warn');
|
||||
assert.equal(result.state, 'fail');
|
||||
});
|
||||
|
||||
test('bad input is refused instead of being checked', async () => {
|
||||
const result = await check('not a domain', { dns: fakeDns({}) });
|
||||
assert.equal(result.state, 'fail');
|
||||
assert.equal(finding(result, 'bad_input').level, 'fail');
|
||||
});
|
||||
|
||||
test('a dead MX host is reported without losing the working one', async () => {
|
||||
const fixture = cleanFixture();
|
||||
fixture.mx[KEDAI] = [
|
||||
{ exchange: 'mx1.mailhost.my', priority: 10 },
|
||||
{ exchange: 'mx9.oldhost.my', priority: 20 }
|
||||
];
|
||||
|
||||
const result = await check(KEDAI, { dns: fakeDns(fixture) });
|
||||
const dead = finding(result, 'mx_host_no_address');
|
||||
assert.equal(dead.level, 'warn');
|
||||
assert.match(dead.message, /mx9\.oldhost\.my/);
|
||||
assert.equal(evidence(result, 'MX address').value, 'mx1.mailhost.my → 203.115.10.5');
|
||||
});
|
||||
|
||||
test('analyseMailAuth is pure and usable without DNS', () => {
|
||||
const result = analyseMailAuth(
|
||||
{
|
||||
domain: 'pure.my',
|
||||
fatal: null,
|
||||
spfRecords: ['v=spf1 -all'],
|
||||
spfLookups: { lookups: 0, cycles: 0, depthCapped: false, unreadable: 0, missingTargets: [], chain: [] },
|
||||
dmarc: { checked: true, code: null, record: 'v=DMARC1; p=reject', parsed: parseDmarc('v=DMARC1; p=reject') },
|
||||
dkim: DKIM_SELECTORS.map((selector) => ({ selector, name: `${selector}._domainkey.pure.my`, status: 'none', key: false })),
|
||||
mx: {
|
||||
checked: true,
|
||||
code: null,
|
||||
records: [{ exchange: 'mx.pure.my', priority: 10 }],
|
||||
nullMx: false,
|
||||
addresses: [{ host: 'mx.pure.my', ok: true, addresses: ['203.0.113.50'], code: null, empty: false }]
|
||||
}
|
||||
},
|
||||
{ now: Date.parse('2026-11-10T04:00:00Z') }
|
||||
);
|
||||
|
||||
assert.equal(result.state, 'ok');
|
||||
assert.equal(result.checkedAt, '2026-11-10T04:00:00.000Z');
|
||||
assert.equal(result.summary, 'Mail can be delivered, and only your own servers can send as your domain.');
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
isBlockedAddress,
|
||||
parseTarget,
|
||||
resolvePublic,
|
||||
guardHop,
|
||||
NetGuardError
|
||||
} from '../src/lib/net-guard.mjs';
|
||||
|
||||
test('isBlockedAddress blocks every private and reserved range', () => {
|
||||
const blocked = [
|
||||
'127.0.0.1', '127.1.2.3', '10.0.0.1', '10.255.255.255', '172.16.0.1', '172.31.255.254',
|
||||
'192.168.1.1', '169.254.169.254', '0.0.0.0', '100.64.0.1', '192.0.2.5', '198.51.100.1',
|
||||
'203.0.113.9', '224.0.0.1', '255.255.255.255',
|
||||
'::1', '::', 'fe80::1', 'fc00::1', 'fd12:3456::1', 'ff02::1', '::ffff:127.0.0.1',
|
||||
'::ffff:192.168.1.6', '64:ff9b::7f00:1', '2002:7f00:1::1', '2001:db8::1'
|
||||
];
|
||||
for (const ip of blocked) {
|
||||
assert.equal(isBlockedAddress(ip), true, `${ip} must be blocked`);
|
||||
}
|
||||
});
|
||||
|
||||
test('isBlockedAddress allows real public addresses', () => {
|
||||
const allowed = ['8.8.8.8', '1.1.1.1', '180.73.34.45', '2606:4700:4700::1111', '2a00:1450:4001:80f::200e'];
|
||||
for (const ip of allowed) {
|
||||
assert.equal(isBlockedAddress(ip), false, `${ip} must be allowed`);
|
||||
}
|
||||
});
|
||||
|
||||
test('isBlockedAddress fails closed on junk', () => {
|
||||
for (const junk of ['', 'not-an-ip', '1234.1.1.1', '1.2.3', null, undefined, '2130706433']) {
|
||||
assert.equal(isBlockedAddress(junk), true, `${String(junk)} must be blocked`);
|
||||
}
|
||||
});
|
||||
|
||||
test('parseTarget accepts plain domains and full URLs', () => {
|
||||
assert.deepEqual(parseTarget('example.com'), { host: 'example.com', port: 443 });
|
||||
assert.deepEqual(parseTarget('Hoelee.COM'), { host: 'hoelee.com', port: 443 });
|
||||
assert.deepEqual(parseTarget('https://www.hoelee.com/advisory?x=1'), { host: 'www.hoelee.com', port: 443 });
|
||||
assert.deepEqual(parseTarget('http://example.com/path'), { host: 'example.com', port: 80 });
|
||||
assert.deepEqual(parseTarget('example.com:443'), { host: 'example.com', port: 443 });
|
||||
assert.deepEqual(parseTarget('example.com.'), { host: 'example.com', port: 443 });
|
||||
});
|
||||
|
||||
test('parseTarget refuses what must never be fetched', () => {
|
||||
const cases = [
|
||||
['127.0.0.1', 'ip_literal'],
|
||||
['1.2.3.4', 'ip_literal'],
|
||||
['[::1]', 'ip_literal'],
|
||||
['localhost', 'bad_input'],
|
||||
['printer.local', 'private_host'],
|
||||
['example.com:22', 'bad_port'],
|
||||
['example.com:8080', 'bad_port'],
|
||||
['ftp://example.com', 'bad_scheme'],
|
||||
['https://user:[email protected]', 'bad_input'],
|
||||
['', 'bad_input'],
|
||||
['no spaces allowed.com', 'bad_input']
|
||||
];
|
||||
for (const [input, code] of cases) {
|
||||
assert.throws(() => parseTarget(input), (err) => {
|
||||
assert.ok(err instanceof NetGuardError, `${input} should throw NetGuardError`);
|
||||
assert.equal(err.code, code, `${input} → expected ${code}, got ${err.code}`);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('resolvePublic refuses a host that answers with a private address', async () => {
|
||||
const lookup = async () => [{ address: '192.168.1.6', family: 4 }];
|
||||
await assert.rejects(() => resolvePublic('evil.example', { lookup }), (err) => err.code === 'private_address');
|
||||
});
|
||||
|
||||
test('resolvePublic refuses a mixed public + private answer set (rebinding shape)', async () => {
|
||||
const lookup = async () => [
|
||||
{ address: '93.184.216.34', family: 4 },
|
||||
{ address: '10.0.0.7', family: 4 }
|
||||
];
|
||||
await assert.rejects(() => resolvePublic('sneaky.example', { lookup }), (err) => err.code === 'private_address');
|
||||
});
|
||||
|
||||
test('resolvePublic returns public answers untouched', async () => {
|
||||
const lookup = async () => [{ address: '93.184.216.34', family: 4 }];
|
||||
const out = await resolvePublic('example.com', { lookup });
|
||||
assert.equal(out.length, 1);
|
||||
assert.equal(out[0].address, '93.184.216.34');
|
||||
});
|
||||
|
||||
test('resolvePublic refuses an empty answer', async () => {
|
||||
const lookup = async () => [];
|
||||
await assert.rejects(() => resolvePublic('nope.example', { lookup }), (err) => err.code === 'dns_nxdomain');
|
||||
});
|
||||
|
||||
test('guardHop refuses a redirect into the private network or a strange port', () => {
|
||||
assert.equal(guardHop('https://example.com/ok'), null);
|
||||
const priv = guardHop('http://192.168.1.6/admin');
|
||||
assert.ok(priv instanceof NetGuardError);
|
||||
assert.equal(priv.code, 'ip_literal'); // an IP is refused before any range check runs
|
||||
const port = guardHop('https://example.com:8443/');
|
||||
assert.ok(port instanceof NetGuardError);
|
||||
assert.equal(port.code, 'bad_port');
|
||||
const meta = guardHop('http://169.254.169.254/latest/meta-data/');
|
||||
assert.ok(meta instanceof NetGuardError);
|
||||
const host = guardHop('http://localhost/');
|
||||
assert.ok(host instanceof NetGuardError);
|
||||
});
|
||||
@@ -0,0 +1,291 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
summariseTls,
|
||||
checkTls,
|
||||
parseCertDate,
|
||||
parseSanList,
|
||||
sanNames,
|
||||
matchesName,
|
||||
isWeakSignature,
|
||||
worstLevel,
|
||||
describeHandshakeError
|
||||
} from '../src/checks/tls.mjs';
|
||||
import { NetGuardError } from '../src/lib/net-guard.mjs';
|
||||
|
||||
// Every fixture is built from plain objects shaped exactly like net-guard's readCertificate()
|
||||
// output. Nothing here resolves, connects, or reads the clock.
|
||||
const NOW = Date.UTC(2026, 0, 15, 12, 0, 0); // 15 Jan 2026 12:00 UTC
|
||||
|
||||
const LEAF_SUBJECT = { CN: 'example.com' };
|
||||
const INTERMEDIATE_SUBJECT = { CN: 'R3', O: "Let's Encrypt" };
|
||||
const ROOT_SUBJECT = { CN: 'ISRG Root X1', O: 'Internet Security Research Group' };
|
||||
|
||||
function certEntry({
|
||||
subject,
|
||||
issuer,
|
||||
sigalg = 'sha256WithRSAEncryption',
|
||||
fingerprint256,
|
||||
validFrom = 'Dec 1 00:00:00 2025 GMT',
|
||||
validTo = 'Jun 1 00:00:00 2026 GMT'
|
||||
}) {
|
||||
return {
|
||||
subject,
|
||||
issuer,
|
||||
validFrom,
|
||||
validTo,
|
||||
signatureAlgorithm: sigalg,
|
||||
fingerprint256,
|
||||
selfSigned: JSON.stringify(subject) === JSON.stringify(issuer)
|
||||
};
|
||||
}
|
||||
|
||||
function buildChain({
|
||||
leafSigalg = 'sha256WithRSAEncryption',
|
||||
intermediateSigalg = 'sha256WithRSAEncryption',
|
||||
rootSigalg = 'sha256WithRSAEncryption',
|
||||
includeRoot = true,
|
||||
includeIntermediate = true,
|
||||
validTo = 'Jun 1 00:00:00 2026 GMT'
|
||||
} = {}) {
|
||||
const leaf = certEntry({ subject: LEAF_SUBJECT, issuer: INTERMEDIATE_SUBJECT, sigalg: leafSigalg, fingerprint256: 'FP-LEAF', validTo });
|
||||
const intermediate = certEntry({ subject: INTERMEDIATE_SUBJECT, issuer: ROOT_SUBJECT, sigalg: intermediateSigalg, fingerprint256: 'FP-INTERMEDIATE' });
|
||||
const root = certEntry({ subject: ROOT_SUBJECT, issuer: ROOT_SUBJECT, sigalg: rootSigalg, fingerprint256: 'FP-ROOT' });
|
||||
if (!includeIntermediate) return [leaf];
|
||||
return includeRoot ? [leaf, intermediate, root] : [leaf, intermediate];
|
||||
}
|
||||
|
||||
function tlsFixture(options = {}) {
|
||||
const {
|
||||
san = 'DNS:example.com',
|
||||
authorized = true,
|
||||
authorizationError = null,
|
||||
chain = buildChain(options)
|
||||
} = options;
|
||||
const leaf = chain[0];
|
||||
const cert = {
|
||||
subject: leaf.subject,
|
||||
issuer: leaf.issuer,
|
||||
validFrom: leaf.validFrom,
|
||||
validTo: leaf.validTo,
|
||||
subjectAltName: san,
|
||||
serialNumber: '00AB',
|
||||
fingerprint256: leaf.fingerprint256,
|
||||
signatureAlgorithm: leaf.signatureAlgorithm,
|
||||
authorized,
|
||||
authorizationError,
|
||||
protocol: 'TLSv1.3',
|
||||
chain
|
||||
};
|
||||
return {
|
||||
host: 'example.com',
|
||||
port: 443,
|
||||
address: '93.184.216.34',
|
||||
alpn: 'http/1.1',
|
||||
cipher: { name: 'TLS_AES_256_GCM_SHA384' },
|
||||
cert,
|
||||
chain
|
||||
};
|
||||
}
|
||||
|
||||
function codes(analysis) {
|
||||
return analysis.findings.map((finding) => finding.code);
|
||||
}
|
||||
|
||||
function levels(analysis) {
|
||||
return analysis.findings.map((finding) => finding.level);
|
||||
}
|
||||
|
||||
// --- pure helpers ---------------------------------------------------------------------------
|
||||
|
||||
test('parseCertDate reads OpenSSL dates with the double space before single-digit days', () => {
|
||||
assert.equal(parseCertDate('Mar 1 12:00:00 2027 GMT'), Date.UTC(2027, 2, 1, 12, 0, 0));
|
||||
assert.equal(parseCertDate('Jan 8 00:00:00 2026 GMT'), Date.UTC(2026, 0, 8, 0, 0, 0));
|
||||
assert.equal(parseCertDate('Dec 31 23:59:59 2026 GMT'), Date.UTC(2026, 11, 31, 23, 59, 59));
|
||||
assert.equal(parseCertDate('2026-01-08T00:00:00.000Z'), Date.UTC(2026, 0, 8));
|
||||
assert.equal(parseCertDate('not a date'), null);
|
||||
assert.equal(parseCertDate(''), null);
|
||||
assert.equal(parseCertDate(null), null);
|
||||
});
|
||||
|
||||
test('SAN matching accepts an exact name and a single-label wildcard only', () => {
|
||||
assert.equal(matchesName('example.com', 'example.com'), true);
|
||||
assert.equal(matchesName('WWW.Example.com', '*.example.com'), true);
|
||||
assert.equal(matchesName('www.example.com', 'example.com'), false);
|
||||
assert.equal(matchesName('example.com', '*.example.com'), false); // wildcard covers one label, not the apex
|
||||
assert.equal(matchesName('a.b.example.com', '*.example.com'), false); // not two labels
|
||||
assert.equal(matchesName('www.example.com', 'www.example.com'), true);
|
||||
assert.equal(matchesName('www.example.com.', 'www.example.com'), true); // trailing dot
|
||||
assert.equal(matchesName('evil-example.com', '*.example.com'), false);
|
||||
});
|
||||
|
||||
test('parseSanList splits DNS and IP entries', () => {
|
||||
const parsed = parseSanList('DNS:example.com, DNS:*.example.com, IP:203.0.113.9');
|
||||
assert.deepEqual(parsed.map((entry) => entry.type), ['DNS', 'DNS', 'IP']);
|
||||
assert.deepEqual(sanNames('DNS:example.com, IP:203.0.113.9'), ['example.com']);
|
||||
assert.deepEqual(parseSanList(''), []);
|
||||
});
|
||||
|
||||
test('isWeakSignature flags SHA-1 and MD5 but not SHA-256', () => {
|
||||
assert.equal(isWeakSignature('sha1WithRSAEncryption'), true);
|
||||
assert.equal(isWeakSignature('ecdsa-with-SHA1'), true);
|
||||
assert.equal(isWeakSignature('md5WithRSAEncryption'), true);
|
||||
assert.equal(isWeakSignature('sha256WithRSAEncryption'), false);
|
||||
assert.equal(isWeakSignature('ecdsa-with-SHA384'), false);
|
||||
assert.equal(isWeakSignature(null), false);
|
||||
});
|
||||
|
||||
test('worstLevel never returns info as a state', () => {
|
||||
assert.equal(worstLevel([{ level: 'info' }, { level: 'info' }]), 'ok');
|
||||
assert.equal(worstLevel([{ level: 'info' }, { level: 'warn' }]), 'warn');
|
||||
assert.equal(worstLevel([{ level: 'warn' }, { level: 'fail' }]), 'fail');
|
||||
assert.equal(worstLevel([]), 'ok');
|
||||
});
|
||||
|
||||
// --- expiry ---------------------------------------------------------------------------------
|
||||
|
||||
test('an expired certificate is a failure', () => {
|
||||
const analysis = summariseTls(tlsFixture({ validTo: 'Jan 1 12:00:00 2026 GMT' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_expired'));
|
||||
assert.equal(analysis.daysToExpiry, -14);
|
||||
assert.match(analysis.summary, /expired/i);
|
||||
});
|
||||
|
||||
test('seven days left is a warning, and the day count is exact', () => {
|
||||
const analysis = summariseTls(tlsFixture({ validTo: 'Jan 22 12:00:00 2026 GMT' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.daysToExpiry, 7);
|
||||
assert.equal(analysis.state, 'warn');
|
||||
assert.ok(codes(analysis).includes('tls_expiring_soon'));
|
||||
assert.match(analysis.summary, /7 days/);
|
||||
});
|
||||
|
||||
test('under 30 days is the softer warning', () => {
|
||||
const analysis = summariseTls(tlsFixture({ validTo: 'Feb 9 12:00:00 2026 GMT' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.daysToExpiry, 25);
|
||||
assert.equal(analysis.state, 'warn');
|
||||
assert.ok(codes(analysis).includes('tls_expiring'));
|
||||
assert.ok(!codes(analysis).includes('tls_expiring_soon'));
|
||||
});
|
||||
|
||||
test('a healthy certificate more than 30 days out is ok', () => {
|
||||
const analysis = summariseTls(tlsFixture(), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'ok');
|
||||
assert.equal(analysis.daysToExpiry, 136);
|
||||
assert.deepEqual(levels(analysis).filter((level) => level !== 'ok'), []);
|
||||
assert.match(analysis.summary, /valid/i);
|
||||
});
|
||||
|
||||
// --- name coverage --------------------------------------------------------------------------
|
||||
|
||||
test('a wildcard SAN covers one subdomain', () => {
|
||||
const analysis = summariseTls(tlsFixture({ san: 'DNS:example.com, DNS:*.example.com' }), { host: 'www.example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'ok');
|
||||
assert.ok(codes(analysis).includes('tls_name_match'));
|
||||
});
|
||||
|
||||
test('a name that is not on the certificate is a failure', () => {
|
||||
const analysis = summariseTls(tlsFixture({ san: 'DNS:example.com, DNS:*.example.com' }), { host: 'shop.example.org', now: NOW });
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_name_mismatch'));
|
||||
assert.match(analysis.summary, /shop\.example\.org/);
|
||||
});
|
||||
|
||||
test('a certificate with no DNS names at all is a failure', () => {
|
||||
const analysis = summariseTls(tlsFixture({ san: '' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_no_san'));
|
||||
});
|
||||
|
||||
// --- signature algorithms -------------------------------------------------------------------
|
||||
|
||||
test('a SHA-1 leaf is a failure', () => {
|
||||
const analysis = summariseTls(tlsFixture({ leafSigalg: 'sha1WithRSAEncryption' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_weak_signature_leaf'));
|
||||
});
|
||||
|
||||
test('a SHA-1 ROOT is a trust anchor and produces no finding at all', () => {
|
||||
const analysis = summariseTls(tlsFixture({ rootSigalg: 'sha1WithRSAEncryption' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'ok');
|
||||
assert.ok(!codes(analysis).some((code) => code.startsWith('tls_weak_signature')));
|
||||
assert.ok(!analysis.findings.some((finding) => /root/i.test(finding.message)));
|
||||
// The root is still described in evidence — it is just not judged.
|
||||
assert.equal(analysis.chainLength, 3);
|
||||
});
|
||||
|
||||
test('a SHA-1 intermediate is a failure', () => {
|
||||
const analysis = summariseTls(tlsFixture({ intermediateSigalg: 'sha1WithRSAEncryption' }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_weak_signature_intermediate'));
|
||||
assert.ok(!codes(analysis).includes('tls_weak_signature_leaf'));
|
||||
});
|
||||
|
||||
// --- chain shape ----------------------------------------------------------------------------
|
||||
|
||||
test('a self-signed leaf is a failure', () => {
|
||||
const selfSigned = certEntry({ subject: { CN: 'shop.internal' }, issuer: { CN: 'shop.internal' }, fingerprint256: 'FP-SELF' });
|
||||
const analysis = summariseTls(tlsFixture({ san: 'DNS:shop.internal', chain: [selfSigned] }), { host: 'shop.internal', now: NOW });
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_self_signed_leaf'));
|
||||
assert.match(analysis.summary, /self-signed/i);
|
||||
});
|
||||
|
||||
test('a chain of only the leaf is a warning, not a failure', () => {
|
||||
const analysis = summariseTls(tlsFixture({ includeIntermediate: false }), { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'warn');
|
||||
assert.ok(codes(analysis).includes('tls_chain_short'));
|
||||
assert.equal(analysis.chainLength, 1);
|
||||
});
|
||||
|
||||
test('a chain sent out of order is reported', () => {
|
||||
const fixture = tlsFixture();
|
||||
const [leafEntry, intermediate, root] = fixture.chain;
|
||||
// The certificate stays the real leaf; only the chain array is reordered.
|
||||
const analysis = summariseTls({ ...fixture, chain: [intermediate, leafEntry, root] }, { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'warn');
|
||||
assert.ok(codes(analysis).includes('tls_chain_order'));
|
||||
});
|
||||
|
||||
test('an unverifiable chain is a failure described in plain English', () => {
|
||||
const analysis = summariseTls(
|
||||
tlsFixture({ authorized: false, authorizationError: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' }),
|
||||
{ host: 'example.com', now: NOW }
|
||||
);
|
||||
assert.equal(analysis.state, 'fail');
|
||||
assert.ok(codes(analysis).includes('tls_untrusted_chain'));
|
||||
const finding = analysis.findings.find((entry) => entry.code === 'tls_untrusted_chain');
|
||||
assert.match(finding.message, /intermediate certificate/i);
|
||||
assert.doesNotMatch(finding.message, /UNABLE_TO_VERIFY/);
|
||||
});
|
||||
|
||||
// --- input shapes and the network boundary ---------------------------------------------------
|
||||
|
||||
test('summariseTls accepts the bare certificate object from requestOnce().tls', () => {
|
||||
const fixture = tlsFixture();
|
||||
const analysis = summariseTls(fixture.cert, { host: 'example.com', now: NOW });
|
||||
assert.equal(analysis.state, 'ok');
|
||||
assert.equal(analysis.chainLength, 3);
|
||||
assert.ok(codes(analysis).includes('tls_name_match'));
|
||||
});
|
||||
|
||||
test('checkTls returns a standard envelope when the handshake never completes', async () => {
|
||||
const lookup = async () => {
|
||||
throw new NetGuardError('timeout', 'That took too long.');
|
||||
};
|
||||
const envelope = await checkTls('example.com', { lookup });
|
||||
assert.equal(envelope.id, 'tls');
|
||||
assert.equal(envelope.state, 'not-evaluated'); // never 'fail' — nothing was judged
|
||||
assert.deepEqual(envelope.findings, []);
|
||||
assert.equal(envelope.fromCache, false);
|
||||
assert.match(envelope.summary, /handshake|time/i);
|
||||
assert.ok(!Number.isNaN(Date.parse(envelope.checkedAt)));
|
||||
});
|
||||
|
||||
test('describeHandshakeError keeps a refusal out of the findings', () => {
|
||||
assert.match(describeHandshakeError(new NetGuardError('refused', 'x')), /refused/i);
|
||||
assert.match(describeHandshakeError(new NetGuardError('dns_nxdomain', 'x')), /did not resolve/i);
|
||||
assert.match(describeHandshakeError(new NetGuardError('private_address', 'x')), /private/i);
|
||||
assert.match(describeHandshakeError(new Error('boom')), /could not be read/i);
|
||||
});
|
||||
Reference in new issue
Block a user