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:
hoelee committed 2026-11-10 12:56:48 +08:00
commit b2707f49f7
19 files changed
+4722

No files matched your search

+588
View File
@@ -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.');
});
+106
View File
@@ -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);
});
+291
View File
@@ -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);
});