DKIM / SPF / DMARC Builder & Checker — JavaScript source
Build the three email-authentication DNS records — SPF, DKIM, and DMARC — as ready-to-paste TXT values, or look up a domain's live records over DNS-over-HTTPS. Import existing records, catch publishing mistakes, share via URL. Entirely client-side.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// dkim-spf-dmarc — Email authentication (SPF / DKIM / DMARC) record parsing and lookup.
//
// Language: JavaScript (ES module; runs in browsers, Node >= 18, Bun, Deno —
// global fetch, no imports, no dependencies)
// Ported from src/lib/dkim-spf-dmarc.ts
// display source — part of CosmoDev's polyglot tool pages
//
// Two layers, mirroring the TypeScript reference:
// - Pure parsers (parseSPF / parseDKIM / parseDMARC) — deterministic, never
// throw, testable without network.
// - Check functions (checkSPF / checkDKIM / checkDMARC) — one DNS-over-HTTPS
// fetch to Cloudflare's public resolver, then a pure parse. No backend.
//
// Specs: SPF RFC 7208, DKIM RFC 6376, DMARC RFC 7489.
const DOMAIN_RE = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/;
const SELECTOR_RE = /^[a-z0-9][a-z0-9._-]*$/i;
const SPF_KINDS = ['all', 'include', 'a', 'mx', 'ip4', 'ip6', 'exists', 'ptr'];
const SPF_LOOKUP_KINDS = new Set(['include', 'a', 'mx', 'exists', 'ptr']);
const DMARC_POLICIES = ['none', 'quarantine', 'reject'];
const DOH_ENDPOINT = 'https://cloudflare-dns.com/dns-query';
/** Strip a leading scheme, userinfo, path, query, port, and trailing dot. */
export function normalizeDomain(raw) {
let s = String(raw).trim();
s = s.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ''); // scheme://
s = s.replace(/^mailto:/i, ''); // mailto:user@domain
if (s.includes('@')) s = s.slice(s.lastIndexOf('@') + 1); // keep host of user@host
s = s.split('/')[0].split('?')[0].split(':')[0]; // drop path, query, port
s = s.replace(/\.+$/, ''); // trailing dot(s)
return s.toLowerCase();
}
/** True when the string looks like a plausible multi-label domain. */
export function isDomainLike(domain) {
return DOMAIN_RE.test(domain) && domain.length <= 253;
}
/** True when the selector is a safe DNS label chain (no spaces, no traversal). */
export function isValidSelector(selector) {
const s = selector.trim();
return s.length > 0 && s.length <= 100 && SELECTOR_RE.test(s) && !s.includes('..');
}
/** Strip one layer of surrounding double quotes, as TXT records carry. */
const unquote = (v) => v.replace(/^"(.*)"$/, '$1');
/** Split a `k=v; k=v` tag list into a Map, recording malformed terms. */
function parseTagList(txt, warnings) {
const tags = new Map();
for (const part of txt.split(';')) {
const term = unquote(part.trim()).trim();
if (!term) continue;
const eq = term.indexOf('=');
if (eq <= 0) {
warnings.push(`Malformed tag "${term}" ignored.`);
continue;
}
tags.set(term.slice(0, eq).trim().toLowerCase(), term.slice(eq + 1).trim());
}
return tags;
}
/** Parse one or more (newline-joined) TXT record strings for SPF. Pure. */
export function parseSPF(txt) {
const lines = txt.split('\n').map((l) => unquote(l.trim())).filter(Boolean);
const spfLines = lines.filter((l) => /^v=spf1(?:\s|$)/i.test(l));
const warnings = [];
if (spfLines.length === 0) {
return { valid: false, mechanisms: [], lookupCount: 0, recordCount: 0, warnings: ['No v=spf1 record found in the supplied text.'] };
}
if (spfLines.length > 1) {
warnings.push(`${spfLines.length} SPF records found — RFC 7208 allows exactly one. Receivers treat this as a permanent error and ignore SPF for the whole domain.`);
}
const terms = spfLines[0].split(/\s+/);
const mechanisms = [];
let redirect, exp;
for (const term of terms.slice(1)) {
const modifier = /^([a-z][a-z0-9-]*)=(.*)$/i.exec(term);
if (modifier) {
const name = modifier[1].toLowerCase();
if (name === 'redirect') redirect = modifier[2];
else if (name === 'exp') exp = modifier[2];
else warnings.push(`Unknown modifier "${term}" ignored.`);
continue;
}
const m = /^([+\-~?])?([a-z0-9]+)(?::(.*))?$/i.exec(term);
if (!m) { warnings.push(`Unrecognized term "${term}" ignored.`); continue; }
const qualifier = m[1] ?? '+';
const kind = m[2].toLowerCase();
const value = m[3];
if (!SPF_KINDS.includes(kind)) { warnings.push(`Unknown mechanism "${term}" ignored.`); continue; }
if (!value && (kind === 'include' || kind === 'exists')) {
warnings.push(`Mechanism "${term}" is missing its required value.`);
continue;
}
mechanisms.push({ qualifier, kind, value });
}
const lookupCount = mechanisms.filter((mech) => SPF_LOOKUP_KINDS.has(mech.kind)).length + (redirect ? 1 : 0);
const all = mechanisms.find((mech) => mech.kind === 'all');
if (!all && !redirect) {
warnings.push('No "all" mechanism and no "redirect=" — unmatched senders get a Neutral result, so anyone can still send mail that looks like this domain.');
}
if (all && all.qualifier === '+') {
warnings.push('"+all" explicitly allows every host on the internet to send mail as this domain — this defeats SPF entirely.');
} else if (all && all.qualifier === '?') {
warnings.push('"?all" (Neutral) lets unmatched senders through with no protection. Prefer "~all" or "-all".');
}
if (mechanisms.some((mech) => mech.kind === 'ptr')) {
warnings.push('The "ptr" mechanism is deprecated (RFC 7208 §5.5) and should not be used.');
}
if (redirect && all) warnings.push('A "redirect=" modifier is ignored when an "all" mechanism is present.');
if (lookupCount > 10) {
warnings.push(`${lookupCount} DNS-lookup mechanisms — RFC 7208 §4.6.4 caps SPF at 10. Receivers that hit the cap return permerror and ignore the record.`);
}
return { valid: true, version: terms[0], mechanisms, redirect, exp, lookupCount, recordCount: spfLines.length, warnings };
}
/** Decode base64 to a byte string without throwing on bad input. */
function decodeBase64Lenient(b64) {
const clean = b64.replace(/\s+/g, '');
const padded = clean + '='.repeat((4 - (clean.length % 4)) % 4);
try { return atob(padded); } catch { return undefined; }
}
/** Parse a `<selector>._domainkey` TXT record. Pure. */
export function parseDKIM(txt) {
const warnings = [];
const tags = parseTagList(txt, warnings);
const version = tags.get('v');
if (version && version.toUpperCase() !== 'DKIM1') {
warnings.push(`Unusual version tag v=${version} (expected DKIM1).`);
}
const keyType = tags.get('k') ?? 'rsa';
const p = tags.get('p');
const colonList = (v) => (v ?? '').split(':').map((s) => s.trim()).filter(Boolean);
const hashes = colonList(tags.get('h'));
const services = colonList(tags.get('s'));
const flags = colonList(tags.get('t'));
const record = { valid: true, keyType, hashes, services, flags, warnings };
if (version) record.version = version.toUpperCase();
if (p === undefined) {
record.valid = false;
warnings.push('No p= tag — this record is not a usable DKIM key.');
return record;
}
if (p === '') {
warnings.push('p= is empty — the key is revoked. Receivers will treat mail signed with this selector as unsigned.');
return record;
}
const decoded = decodeBase64Lenient(p);
if (decoded === undefined) {
warnings.push('The p= value is not valid base64 — the key could not be read.');
return record;
}
record.publicKey = p.replace(/\s+/g, '');
if (keyType === 'rsa') {
// SubjectPublicKeyInfo DER ≈ modulus bits/8 + ~24 bytes of ASN.1 overhead.
const bits = Math.max(0, decoded.length - 24) * 8;
record.keyBits = bits;
if (bits < 1024) {
warnings.push(`Weak RSA key (~${bits} bits). Keys under 1024 bits are considered breakable; RFC 8301 discourages short keys.`);
} else if (bits < 2048) {
warnings.push(`RSA key of ~${bits} bits works today but is below the recommended 2048 bits (RFC 8301).`);
}
}
if (flags.includes('y')) warnings.push('t=y — the key is in test mode: receivers must treat signatures as if unsigned.');
if (flags.includes('s')) warnings.push('t=s — strict domain matching: the key cannot be used for subdomain signatures (informational).');
return record;
}
/** Parse a `_dmarc` TXT record. Pure. */
export function parseDMARC(txt) {
const warnings = [];
const tags = parseTagList(txt, warnings);
const record = { valid: true, aggregateUris: [], forensicUris: [], warnings };
const version = tags.get('v');
if (!version) {
record.valid = false;
warnings.push('No v= tag — this is not a DMARC record.');
return record;
}
if (version.toUpperCase() !== 'DMARC1') {
record.valid = false;
warnings.push(`Unknown version v=${version} (expected DMARC1).`);
return record;
}
const p = (tags.get('p') ?? '').toLowerCase();
if (!p) {
record.valid = false;
warnings.push('No p= policy tag — DMARC requires it.');
return record;
}
if (!DMARC_POLICIES.includes(p)) {
record.valid = false;
warnings.push(`Invalid policy p=${p} (expected none, quarantine, or reject).`);
return record;
}
record.policy = p;
const sp = (tags.get('sp') ?? '').toLowerCase();
if (sp) {
if (DMARC_POLICIES.includes(sp)) record.subdomainPolicy = sp;
else warnings.push(`Invalid sp=${sp} ignored (expected none, quarantine, or reject).`);
}
const commaList = (v) => (v ?? '').split(',').map((u) => u.trim()).filter(Boolean);
record.aggregateUris = commaList(tags.get('rua'));
record.forensicUris = commaList(tags.get('ruf'));
const pct = tags.get('pct');
if (pct !== undefined) {
const n = Number(pct);
if (!Number.isInteger(n) || n < 0 || n > 100) warnings.push(`Invalid pct=${pct} ignored (must be 0-100).`);
else record.percent = n;
}
for (const [tag, key] of [['adkim', 'dkimAlignment'], ['aspf', 'spfAlignment']]) {
const v = tags.get(tag);
if (v) {
if (v === 'r' || v === 's') record[key] = v;
else warnings.push(`Invalid ${tag}=${v} ignored (expected r or s).`);
}
}
if (record.policy === 'none') {
warnings.push('p=none is monitor-only — no mail is quarantined or rejected, but you still need SPF/DKIM to pass for reports to be useful.');
}
if (record.aggregateUris.length === 0) {
warnings.push('No rua= address — without aggregate reports you cannot see who is failing authentication. Add rua=mailto:reports@example.com.');
} else if (record.forensicUris.length > 0) {
warnings.push('ruf= (forensic reports) is supported by few receivers and may leak message content to the report address (informational).');
}
if (record.percent !== undefined && record.percent < 100 && record.policy !== 'none') {
warnings.push(`pct=${record.percent} applies the policy to only ${record.percent}% of mail — the other ${100 - record.percent}% is unaffected.`);
}
return record;
}
/** Query TXT records for a name via Cloudflare's DoH JSON API. */
async function queryTxt(name) {
const res = await fetch(`${DOH_ENDPOINT}?name=${encodeURIComponent(name)}&type=TXT`, {
headers: { Accept: 'application/dns-json' },
});
if (!res.ok) throw new Error(`DNS resolver responded with HTTP ${res.status}.`);
const json = await res.json();
if (json.Status === 3) return []; // NXDOMAIN — no such domain
if (json.Status !== 0) throw new Error(`DNS query failed with status ${json.Status}.`);
return (json.Answer ?? [])
.filter((a) => a.type === 16)
.map((a) => unquote(a.data).replace(/" "/g, '')); // multi-chunk TXT: "part1" "part2"
}
const invalidDomain = () => ({ status: 'fail', found: false, message: 'Enter a valid domain, e.g. example.com.' });
/** Look up and evaluate a domain's SPF record. */
export async function checkSPF(domain) {
const host = normalizeDomain(domain);
if (!isDomainLike(host)) return invalidDomain();
try {
const record = parseSPF((await queryTxt(host)).join('\n'));
if (!record.valid) return { status: 'fail', found: false, message: `No SPF record found for ${host}. Receivers cannot verify which servers may send mail for it.` };
const status = record.warnings.length > 0 ? 'warn' : 'pass';
return { status, found: true, record, message: status === 'pass' ? 'SPF record found and looks healthy.' : undefined };
} catch (err) {
return { status: 'fail', found: false, message: err instanceof Error ? err.message : 'DNS lookup failed.' };
}
}
/** Look up and evaluate a domain's DKIM public key for one selector. */
export async function checkDKIM(domain, selector) {
const host = normalizeDomain(domain);
if (!isDomainLike(host)) return invalidDomain();
const sel = selector.trim().toLowerCase();
if (!isValidSelector(sel)) return { status: 'fail', found: false, message: 'Enter a valid selector (letters, digits, dots, hyphens, underscores).' };
try {
const record = parseDKIM((await queryTxt(`${sel}._domainkey.${host}`)).join('\n'));
if (!record.valid) {
return { status: 'fail', found: false, message: `No DKIM record found at ${sel}._domainkey.${host}. Try another selector — only one is checked per lookup.` };
}
const revoked = record.warnings.some((w) => w.includes('revoked'));
const status = revoked ? 'fail' : record.warnings.length > 0 ? 'warn' : 'pass';
return { status, found: true, record };
} catch (err) {
return { status: 'fail', found: false, message: err instanceof Error ? err.message : 'DNS lookup failed.' };
}
}
/** Look up and evaluate a domain's DMARC policy. */
export async function checkDMARC(domain) {
const host = normalizeDomain(domain);
if (!isDomainLike(host)) return invalidDomain();
try {
const record = parseDMARC((await queryTxt(`_dmarc.${host}`)).join('\n'));
if (!record.valid) {
return { status: 'fail', found: false, message: `No DMARC record found at _dmarc.${host}. Receivers have no policy to apply when SPF or DKIM fails.` };
}
const status = record.warnings.length > 0 ? 'warn' : 'pass';
return { status, found: true, record };
} catch (err) {
return { status: 'fail', found: false, message: err instanceof Error ? err.message : 'DNS lookup failed.' };
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →