Email Header Analyzer — JavaScript source
Paste raw email headers to trace the message path, detect spoofing, and check SPF/DKIM/DMARC authentication results. Runs entirely in your browser.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* email-header-analyzer — RFC 5322 header parser + spoofing / authentication analysis.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* CosmoDev polyglot showcase port of the `email-header-analyzer` tool, ported
* from src/lib/email-header-analyzer.ts (the canonical TypeScript implementation).
*
* Pure string parsing — no imports, no DOM, deterministic. Feeding it a raw
* header block yields unfolded headers, chronological Received hops with
* per-leg delays, SPF/DKIM/DMARC verdicts, and spoofing anomalies.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
const SUSPICIOUS_MAILERS = ['bulk', 'mass mail', 'massmail', 'storm', 'flood', 'bomber', 'grabber', 'harvest', 'spambot', 'stealth', 'anonymous', 'dark', 'crack'];
const noAuth = () => ({ result: 'none', domain: null, selector: null, policy: null, detail: null });
/** Split raw header text into unfolded name/value pairs. Stops at the first empty line (body separator). */
export function parseHeaderLines(raw) {
const headers = [];
let current = null;
for (const line of raw.replace(/\r\n/g, '\n').split('\n')) {
if (line.trim() === '') break; // end of headers / blank separator
if (/^[ \t]/.test(line) && current) {
current.value += ' ' + line.trim(); // RFC 5322 folding continuation
continue;
}
const colon = line.indexOf(':');
if (colon <= 0) continue; // not a header line — skip garbage
current = { name: line.slice(0, colon).trim(), value: line.slice(colon + 1).trim() };
headers.push(current);
}
return headers;
}
/** All values for a header name, case-insensitive, in file order. */
export function getHeaders(headers, name) {
const lower = name.toLowerCase();
return headers.filter((h) => h.name.toLowerCase() === lower).map((h) => h.value);
}
/** Extract an email address: prefers <addr>, falls back to the first bare address; null when none. */
export function extractAddress(value) {
const bracket = value.match(/<([^<>\s]+)>/);
if (bracket) return bracket[1];
const bare = value.match(/[^\s<>,;"']+@[^\s<>,;"']+/);
return bare ? bare[0] : null;
}
/** Parse an RFC 2822 date, ignoring trailing "(ZONE)" comments. Returns null when unparseable. */
export function parseRfc2822Date(value) {
const cleaned = value.replace(/\([^)]*\)/g, ' ').trim();
const ts = cleaned ? Date.parse(cleaned) : NaN;
return Number.isNaN(ts) ? null : new Date(ts);
}
/** Parse one Received header value into a hop (delay is filled in by parseHeaders). */
export function parseReceived(value) {
let timestamp = null;
const lastSemi = value.lastIndexOf(';');
if (lastSemi !== -1) timestamp = parseRfc2822Date(value.slice(lastSemi + 1));
if (!timestamp) {
// Some clients omit the ';' — fall back to the first date-looking token.
const guess = value.match(/\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s+[^\n]+/);
if (guess) timestamp = parseRfc2822Date(guess[0]);
}
const capture = (re) => (value.match(re) || ['', ''])[1];
const trimDot = (s) => s.replace(/[.,]$/, '');
return {
from: trimDot(capture(/\bfrom\s+([^\s(;]+)/i)),
by: trimDot(capture(/\bby\s+([^\s(;]+)/i)),
timestamp,
delay: null,
protocol: capture(/\bwith\s+([^\s;()]+)/i),
};
}
/** Parse Authentication-Results clauses, e.g. "mx.google.com; spf=pass smtp.mailfrom=a@b.com; dmarc=pass (p=REJECT) header.from=b.com". */
export function parseAuthResults(values) {
const auth = { spf: noAuth(), dkim: noAuth(), dmarc: noAuth() };
const token = (clause, key) => {
const m = clause.match(new RegExp(`\\b${key}=([^\\s;)]+)`, 'i'));
return m ? m[1].replace(/[.,]$/, '') : null;
};
for (const value of values) {
for (const rawClause of value.split(';')) {
const clause = rawClause.trim();
const kind = ['spf', 'dkim', 'dmarc'].find((k) => clause.toLowerCase().startsWith(`${k}=`));
if (!kind || auth[kind].result !== 'none') continue; // first result wins
const target = auth[kind];
const word = clause.match(/=\s*([a-z]+)\b/i);
target.result = word ? word[1].toLowerCase() : 'unknown';
target.detail = clause;
if (kind === 'spf') {
target.domain = token(clause, 'smtp.mailfrom') ?? token(clause, 'mailfrom');
} else if (kind === 'dkim') {
target.domain = token(clause, 'header.d') ?? token(clause, 'header.i');
target.selector = token(clause, 'header.s');
} else {
target.domain = token(clause, 'header.from');
const policy = clause.match(/\bp=([a-z]+)/i);
target.policy = policy ? policy[1].toLowerCase() : null;
}
}
}
return auth;
}
/** Classic spoofing checks: sender mismatch, Reply-To misdirection, bulk mailers, chain gaps. */
function detectAnomalies(headers, hops) {
const anomalies = [];
const add = (type, severity, message) => anomalies.push({ type, severity, message });
const first = (name) => getHeaders(headers, name)[0] ?? '';
const fromAddr = extractAddress(first('From'));
const returnPath = extractAddress(first('Return-Path'));
if (fromAddr && returnPath && fromAddr.toLowerCase() !== returnPath.toLowerCase()) {
add('from-return-path-mismatch', 'critical', `Return-Path (${returnPath}) does not match From (${fromAddr}) — the envelope sender differs from the displayed sender. Common in spoofing and mailing-list relay.`);
}
const replyTo = extractAddress(first('Reply-To'));
if (fromAddr && replyTo && replyTo.toLowerCase() !== fromAddr.toLowerCase()) {
add('reply-to-mismatch', 'warning', `Reply-To (${replyTo}) differs from From (${fromAddr}) — replies would go to a different address than the visible sender.`);
}
const mailer = first('X-Mailer') || first('User-Agent');
const hit = mailer ? SUSPICIOUS_MAILERS.find((s) => mailer.toLowerCase().includes(s)) : null;
if (mailer && hit) {
add('suspicious-mailer', 'warning', `Mailer string "${mailer}" contains a suspicious token ("${hit}") often seen in bulk sending tools.`);
}
hops.forEach((hop, i) => {
if (!hop.timestamp) {
add('hop-missing-timestamp', 'info', `Hop ${i + 1} (${hop.from || hop.by || 'unknown'}) has no parseable timestamp — delay for this leg cannot be computed.`);
} else if (i > 0 && hops[i - 1].timestamp) {
const delta = (hop.timestamp - hops[i - 1].timestamp) / 1000;
if (delta < 0) {
add('negative-delay', 'warning', `Hop ${i + 1} is timestamped ${Math.abs(delta).toFixed(1)}s BEFORE hop ${i} — clock skew between servers or a forged Received header.`);
}
}
});
if (getHeaders(headers, 'Authentication-Results').length === 0) {
add('no-auth-results', 'info', 'No Authentication-Results header found — SPF/DKIM/DMARC status cannot be verified from this message.');
}
return anomalies;
}
/** Parse raw email headers (RFC 5322): headers, chronological hops, auth verdicts, anomalies. */
export function parseHeaders(raw) {
const headers = parseHeaderLines(raw);
// Received headers are listed newest-first; parse bottom-up so hops[0] is the oldest.
const hops = getHeaders(headers, 'Received').map(parseReceived).reverse();
for (let i = 1; i < hops.length; i++) {
if (hops[i].timestamp && hops[i - 1].timestamp) {
hops[i].delay = (hops[i].timestamp - hops[i - 1].timestamp) / 1000;
}
}
return {
headers,
hops,
auth: parseAuthResults(getHeaders(headers, 'Authentication-Results')),
anomalies: detectAnomalies(headers, hops),
};
}
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 →