Repository Public
1// Adresses de courriel : analyse d'une saisie libre, formatage RFC 5322, détection d'usurpation du nom affiché.2export interface Addr {3 name?: string | null4 email: string5}67const EMAIL_RE = /^[^\s@<>(),;:"\\]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i89export function isValidEmail(s: string): boolean {10 return s.length <= 254 && EMAIL_RE.test(s)11}1213export function domainOf(email: string): string {14 const i = email.lastIndexOf("@")15 return i < 0 ? "" : email.slice(i + 1).toLowerCase()16}1718/** Découpe sur les virgules / points-virgules / retours de ligne situés hors guillemets et hors chevrons. */19function splitList(input: string): string[] {20 const out: string[] = []21 let cur = ""22 let quoted = false23 let angle = false24 for (let i = 0; i < input.length; i++) {25 const c = input[i]26 if (quoted) {27 if (c === "\\" && i + 1 < input.length) cur += c + input[++i]28 else {29 if (c === '"') quoted = false30 cur += c31 }32 } else if (c === '"') {33 quoted = true34 cur += c35 } else if (c === "<") {36 angle = true37 cur += c38 } else if (c === ">") {39 angle = false40 cur += c41 } else if (!angle && (c === "," || c === ";" || c === "\n")) {42 out.push(cur)43 cur = ""44 } else cur += c45 }46 out.push(cur)47 return out.map((s) => s.trim()).filter(Boolean)48}4950function unquote(s: string): string {51 s = s.trim()52 if (s.startsWith('"') && s.endsWith('"') && s.length >= 2) s = s.slice(1, -1).replace(/\\(.)/g, "$1")53 return s.trim()54}5556/** Analyse « Nom <a@b>, c@d ; "Nom, Prénom" <e@f> ». Les entrées invalides sont rendues dans `invalid`. */57export function parseAddressList(input: string): { valid: Addr[]; invalid: string[] } {58 const valid: Addr[] = []59 const invalid: string[] = []60 for (const part of splitList(input)) {61 const m = part.match(/^(.*)<([^<>]*)>\s*$/s)62 const email = (m ? m[2] : part).trim().replace(/^mailto:/i, "")63 const name = m ? unquote(m[1]) : ""64 if (isValidEmail(email)) valid.push(name ? { name, email } : { email })65 else invalid.push(part)66 }67 return { valid, invalid }68}6970export function formatAddress(a: Addr): string {71 const name = (a.name ?? "").trim()72 if (!name || name === a.email) return a.email73 const needsQuote = /[",;:<>@()[\]\\.]/.test(name)74 return `${needsQuote ? `"${name.replace(/(["\\])/g, "\\$1")}"` : name} <${a.email}>`75}7677export function displayName(a: Addr | undefined | null): string {78 if (!a) return ""79 return (a.name ?? "").trim() || a.email80}8182export function sameEmail(a: string, b: string): boolean {83 return a.trim().toLowerCase() === b.trim().toLowerCase()84}8586export function dedupeAddrs(list: Addr[]): Addr[] {87 const seen = new Set<string>()88 const out: Addr[] = []89 for (const a of list) {90 const k = a.email.toLowerCase()91 if (seen.has(k)) continue92 seen.add(k)93 out.push(a)94 }95 return out96}9798export function initials(a: Addr | undefined | null): string {99 if (a && !(a.name ?? "").trim()) return (a.email[0] ?? "?").toUpperCase()100 const s = displayName(a).replace(/[^\p{L}\p{N} ]/gu, " ").trim()101 if (!s) return "?"102 const parts = s.split(/\s+/)103 return ((parts[0][0] ?? "") + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase()104}105106export type SpoofReason = "name-has-other-address" | "name-has-other-domain"107108/**109 * Le nom affiché prétend-il être quelqu'un d'autre ? Cas classique d'hameçonnage :110 * « "service@banque.ca" <x@evil.example> » ou « "Banque (banque.ca)" <x@evil.example> ».111 */112export function spoofedDisplayName(from: Addr | undefined | null): SpoofReason | null {113 if (!from?.name) return null114 const real = domainOf(from.email)115 if (!real) return null116 const name = from.name.toLowerCase()117 const emails = name.match(/[^\s@<>()"',;]+@[a-z0-9.-]+\.[a-z]{2,}/g) ?? []118 for (const e of emails) if (!relatedDomains(domainOf(e), real)) return "name-has-other-address"119 const rest = emails.reduce((s, e) => s.replace(e, " "), name)120 const domains = rest.match(/\b(?:[a-z0-9-]+\.)+(?:com|net|org|ca|fr|ai|io|co|gov|edu|info|biz|uk|de|us|eu|quebec|app|dev|bank|me)\b/g) ?? []121 for (const d of domains) if (!relatedDomains(d, real)) return "name-has-other-domain"122 return null123}124125/** Même hôte, ou l'un est un sous-domaine de l'autre. */126export function relatedDomains(a: string, b: string): boolean {127 a = a.toLowerCase().replace(/^www\./, "")128 b = b.toLowerCase().replace(/^www\./, "")129 return a === b || a.endsWith("." + b) || b.endsWith("." + a)130}131