Port-43 WHOIS servers are painful to automate at scale. Every TLD registry formats its plain-text output differently, rate limits kick in unpredictably, and you end up maintaining brittle regex parsers for dozens of registrars. For most B2B domain audits (figuring out whether a company runs Google Workspace or Microsoft 365, checking SPF and DMARC enforcement, spotting expiring TLS certificates, and pulling registration dates), Node 22 already ships everything you need in node:dns/promises, node:tls, and fetch.
With all three running in parallel per domain, a full check on stripe.com, shopify.com, apify.com, and microsoft.com finishes in 239ms to 364ms per domain with zero third-party npm packages.
Detecting Google Workspace vs Microsoft 365 from MX records
dns.resolveMx(domain) returns an array of { exchange, priority } objects, and it does not guarantee sorted order. Some domains also publish an RFC 7505 null MX record (exchange: "" or ".") to declare that the domain accepts no mail at all.
Sort by ascending priority (breaking ties alphabetically), filter out empty exchanges, strip trailing dots, and match the lowest-priority host against known mail exchangers:
const EMAIL_PROVIDER_RULES = [
{
name: 'Google Workspace',
patterns: [
/(?:^|\.)aspmx\.l\.google\.com$/,
/(?:^|\.)alt\d*\.aspmx\.l\.google\.com$/,
/(?:^|\.)smtp\.google\.com$/,
/(?:^|\.)googlemail\.com$/,
],
},
{
name: 'Microsoft 365',
patterns: [
/(?:^|\.)mail\.protection\.outlook\.com$/,
/(?:^|\.)protection\.outlook\.com$/,
/(?:^|\.)eo\.outlook\.com$/,
],
},
{
name: 'Proofpoint',
patterns: [/(?:^|\.)pphosted\.com$/, /(?:^|\.)ppe-hosted\.com$/],
},
{
name: 'Mimecast',
patterns: [/(?:^|\.)mimecast\.com$/, /(?:^|\.)mimecast-offshore\.com$/],
},
];
export function classifyEmailProvider(mxRecords) {
if (!Array.isArray(mxRecords) || mxRecords.length === 0) return 'None';
const sorted = mxRecords
.map((m) => ({
exchange: String(m.exchange || '').trim().toLowerCase().replace(/\.+$/, ''),
priority: Number.isFinite(Number(m.priority)) ? Number(m.priority) : 9999,
}))
.filter((m) => m.exchange.length > 0 && m.exchange.includes('.'))
.sort((a, b) => a.priority - b.priority || a.exchange.localeCompare(b.exchange));
if (sorted.length === 0) return 'None';
for (const { exchange } of sorted) {
for (const rule of EMAIL_PROVIDER_RULES) {
if (rule.patterns.some((p) => p.test(exchange))) return rule.name;
}
}
return 'Custom / Self-Hosted';
}
Checking enterprise gateways like Proofpoint and Mimecast matters for B2B lists. Plenty of large companies sit behind *.pphosted.com even when their actual mailboxes live on Microsoft 365 or Google Workspace; if you only check Google and Microsoft hostnames, those domains get dumped into "Custom / Self-Hosted".
Multi-chunk TXT records, SPF, and _dmarc.<domain>
A classic bug when parsing DNS TXT records in Node.js comes from how DNS encodes strings longer than 255 bytes on the wire. dns.resolveTxt() returns string[][] (an array of records, where each record is an array of chunks). If you join chunks with a space instead of an empty string, a long SPF record split mid-domain turns include:_spf.google.com into include:_spf.goo gle.com and breaks parsing.
Flatten each record with entry.join(''), and query both the root domain TXT records and _dmarc.<domain> in parallel with per-query timeouts:
import dns from 'node:dns/promises';
function withTimeout(promise, timeoutMs) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(Object.assign(new Error('DNS timeout'), { code: 'ETIMEOUT' })), timeoutMs);
timer.unref?.();
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
function flattenTxt(records) {
if (!Array.isArray(records)) return [];
return records
.map((entry) => (Array.isArray(entry) ? entry.join('') : String(entry || '')).trim())
.filter(Boolean);
}
export function parseSpf(txtRecords) {
const spf = flattenTxt(txtRecords).find((r) => /^v=spf1(?:\s|$)/i.test(r)) || null;
if (!spf) return { hasSpf: false, spfQualifier: null, spfIncludes: [] };
const includes = new Set();
let qualifier = 'none';
let hasRedirect = false;
for (const token of spf.split(/\s+/)) {
const lower = token.toLowerCase();
if (lower.startsWith('include:')) {
includes.add(lower.slice('include:'.length).replace(/\.+$/, ''));
} else if (lower.startsWith('redirect=')) {
includes.add(lower.slice('redirect='.length).replace(/\.+$/, ''));
hasRedirect = true;
} else if (/^[-~?+]?all$/.test(lower)) {
qualifier = lower === 'all' ? '+all' : lower;
}
}
if (qualifier === 'none' && hasRedirect) qualifier = 'redirect';
return { hasSpf: true, spfQualifier: qualifier, spfIncludes: [...includes] };
}
export function parseDmarc(dmarcTxtRecords) {
const rec = flattenTxt(dmarcTxtRecords).find((r) => /^v=dmarc1(?:\s*;|\s|$)/i.test(r)) || null;
if (!rec) return { hasDmarc: false, dmarcPolicy: null, dmarcPct: null, dmarcRua: [] };
const tags = new Map();
for (const part of rec.split(';')) {
const eq = part.indexOf('=');
if (eq === -1) continue;
const key = part.slice(0, eq).trim().toLowerCase();
const val = part.slice(eq + 1).trim();
if (key && !tags.has(key)) tags.set(key, val);
}
const rawPolicy = (tags.get('p') || '').toLowerCase();
const dmarcPolicy = ['reject', 'quarantine', 'none'].includes(rawPolicy) ? rawPolicy : null;
const parsedPct = tags.has('pct') ? Number.parseInt(tags.get('pct'), 10) : 100;
const dmarcPct = Number.isFinite(parsedPct) && parsedPct >= 0 && parsedPct <= 100 ? parsedPct : 100;
const dmarcRua = (tags.get('rua') || '').split(',').map((s) => s.trim()).filter(Boolean);
return { hasDmarc: true, dmarcPolicy, dmarcPct, dmarcRua };
}
export async function lookupEmailAuth(domain, timeoutMs = 8000) {
const safe = (p) => withTimeout(p, timeoutMs).catch(() => []);
const [mx, rootTxt, dmarcTxt] = await Promise.all([
safe(dns.resolveMx(domain)),
safe(dns.resolveTxt(domain)),
safe(dns.resolveTxt(`_dmarc.${domain}`)),
]);
return {
mx,
...parseSpf(rootTxt),
...parseDmarc(dmarcTxt),
};
}
Calling timer.unref?.() on the timeout timer is easy to overlook. Without it, a CLI script that finishes early can sit open for several seconds waiting for leftover timers. Also notice how bare all in SPF is normalized to +all (per RFC 7208, an unqualified all defaults to pass, which lets any host send mail as the domain).
Checking TLS expiry with node:tls without leaking sockets
When inspecting certificates across hundreds of domains, two tls.connect options trip people up:
- Omitting
servername: domaindisables SNI. Shared CDN endpoints on Cloudflare, Fastly, and AWS CloudFront then hand back a fallback certificate instead of the domain's real cert, causing bogus hostname mismatch errors. - Leaving
rejectUnauthorized: truethrows inside the handshake when a cert is expired or self-signed, which hides the issuer, subject, and expiration timestamp you wanted to log.
Set rejectUnauthorized: false, let secureConnect fire, inspect socket.authorized and socket.authorizationError, and destroy the socket in a single guarded cleanup callback so error and timeout events never double-resolve or leak file descriptors:
import tls from 'node:tls';
const MS_PER_DAY = 86_400_000;
export function inspectSsl(domain, timeoutMs = 8000) {
return new Promise((resolve) => {
let settled = false;
let socket = null;
let timer = null;
const finish = (result) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
if (socket && !socket.destroyed) socket.destroy();
resolve(result);
};
const fail = (sslError) =>
finish({ sslValid: false, sslIssuer: null, sslDaysRemaining: null, sslProtocol: null, sslError });
timer = setTimeout(() => fail(`TLS handshake timed out after ${timeoutMs}ms`), timeoutMs);
timer.unref?.();
try {
socket = tls.connect({
host: domain,
port: 443,
servername: domain,
rejectUnauthorized: false,
});
} catch (err) {
fail(err?.code || err?.message || 'TLS connection failed');
return;
}
socket.setTimeout(timeoutMs);
socket.once('secureConnect', () => {
const cert = socket.getPeerCertificate(false);
if (!cert || Object.keys(cert).length === 0) {
fail('No peer TLS certificate presented');
return;
}
const validToMs = cert.valid_to ? Date.parse(cert.valid_to) : Number.NaN;
const sslDaysRemaining = Number.isFinite(validToMs)
? Math.floor((validToMs - Date.now()) / MS_PER_DAY)
: null;
const notExpired = sslDaysRemaining === null ? true : sslDaysRemaining >= 0;
const sslValid = Boolean(socket.authorized) && notExpired;
finish({
sslValid,
sslIssuer: cert.issuer?.O || cert.issuer?.CN || null,
sslDaysRemaining,
sslProtocol: socket.getProtocol() || null,
sslError: sslValid ? null : String(socket.authorizationError || 'CERT_HAS_EXPIRED'),
});
});
socket.once('timeout', () => fail(`TLS socket timed out after ${timeoutMs}ms`));
socket.once('error', (err) => fail(err?.code || err?.message || 'TLS connection error'));
});
}
Replacing port-43 WHOIS with RDAP JSON
RDAP (RFC 7483) gives you structured JSON over HTTPS instead of unstructured WHOIS text. You do not even need to maintain the IANA bootstrap table locally: https://rdap.org/domain/<domain> returns an HTTP 302 redirect straight to the authoritative registry (Verisign for .com, PIR for .org, and so on).
export async function fetchRdap(domain, timeoutMs = 8000) {
const url = `https://rdap.org/domain/${encodeURIComponent(domain)}`;
const res = await fetch(url, {
redirect: 'follow',
signal: AbortSignal.timeout(timeoutMs),
headers: { Accept: 'application/rdap+json, application/json' },
});
if (!res.ok) {
if (res.body) await res.body.cancel().catch(() => {});
return null;
}
const json = await res.json();
const events = Array.isArray(json.events) ? json.events : [];
const findDate = (action) =>
events.find((e) => e?.eventAction?.toLowerCase() === action)?.eventDate || null;
const registrarEntity = (json.entities || []).find(
(e) => Array.isArray(e?.roles) && e.roles.includes('registrar')
);
const vcardProps = registrarEntity?.vcardArray?.[1] || [];
const fnProp = vcardProps.find((p) => Array.isArray(p) && p[0] === 'fn');
return {
registrar: fnProp?.[3] || registrarEntity?.handle || null,
createdAt: findDate('registration'),
expiresAt: findDate('expiration'),
dnssecSigned: json.secureDNS?.delegationSigned ?? null,
};
}
One quirk to watch for: some ccTLDs still lack an RDAP server or return 404 through rdap.org. Keep RDAP optional alongside DNS and TLS so a null RDAP response does not fail the whole domain record.
Live output across four production domains
Running DNS, TLS, and RDAP concurrently on four well-known domains produced these exact measurements:
| Domain | Email provider | SPF / DMARC | DNS provider | TLS issuer & days left | Registrar / Created | DNSSEC | Latency |
|---|---|---|---|---|---|---|---|
stripe.com |
Google Workspace |
~all (3 includes) / reject
|
AWS Route 53 | DigiCert (158d, TLSv1.3) | SafeNames Ltd. (1995-09-12) | false |
364ms |
shopify.com |
Google Workspace |
~all (3 includes) / reject
|
Cloudflare | Google Trust Services (35d, TLSv1.3) | MarkMonitor Inc. (2005-03-11) | false |
244ms |
apify.com |
Google Workspace |
-all (4 includes) / reject
|
AWS Route 53 | Amazon (45d, TLSv1.3) | Amazon Registrar (2009-06-02) | true |
239ms |
microsoft.com |
Microsoft 365 |
-all (4 includes) / reject
|
Azure DNS | Microsoft Corp. (59d, TLSv1.3) | MarkMonitor Inc. (1991-05-02) | false |
298ms |
Look closely at shopify.com: its NS records point to gold.foundationdns.com, .net, and .org instead of *.ns.cloudflare.com. That is Cloudflare's enterprise Foundation DNS namespace, so an NS classifier that only checks cloudflare.com mislabels Shopify as "Other". Meanwhile apify.com is the only one of the four with both -all SPF and signed DNSSEC, scoring 100/100 on our deliverability and transport rubric while stripe.com and shopify.com land at 85/100.
Running bulk batches via REST or MCP
If you want to run this across a CSV of prospects or a fleet of customer domains without managing concurrency and digest aggregation yourself, we published this exact zero-dependency Node 22 checker as our own Apify Actor: Bulk Domain DNS, WHOIS/RDAP, SSL & Email Auth Checker. It returns one structured JSON record per domain plus a DOMAIN_AUDIT_DIGEST summary flagging any TLS certificates with fewer than 30 days left. You can call it over REST (or wire it into an AI agent via the Apify MCP server):
curl -s "https://api.apify.com/v2/acts/immortal_swale~domain-whois-dns-enricher/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"domains": ["stripe.com", "shopify.com", "apify.com"], "includeRdap": true, "includeSsl": true}'
Top comments (0)