SPB Git

Repository Public

links.ts 2.2 KB 60 lines typescript

1// Liens dans un message : destination réelle et détection des libellés trompeurs (hameçonnage).2import { relatedDomains } from "./address"34export type LinkWarning = "text-domain-mismatch" | "credentials-in-url" | "punycode-host" | "ip-host"56const SAFE_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:", "tel:"])78/** Rend l'URL normalisée si le protocole est permis pour un lien cliquable, sinon null. Aucune URL relative. */9export function safeLinkHref(raw: string | null | undefined): string | null {10  if (!raw) return null11  // L'analyseur d'URL du navigateur retire lui-même tabulations, retours de ligne et espaces de tête (« java\tscript: »).12  let u: URL13  try {14    u = new URL(raw)15  } catch {16    return null17  }18  if (!SAFE_LINK_PROTOCOLS.has(u.protocol)) return null19  return u.href20}2122/** Hôte que le texte visible d'un lien prétend désigner (« www.banque.ca », « https://banque.ca/connexion »), sinon null. */23export function hostClaimedByText(text: string): string | null {24  const t = text.trim().toLowerCase()25  if (!t) return null26  if (/\s/.test(t)) {27    // texte en plusieurs mots : on ne retient qu'une adresse explicite (schéma ou « www. »)28    const w = t.match(/(?:https?:\/\/|\bwww\.)((?:[a-z0-9-]+\.)+[a-z]{2,})/)29    return w ? (w[0].startsWith("www.") ? "www." + w[1] : w[1]) : null30  }31  const m = t.match(/^(?:https?:\/\/)?(?:[^@/\s]*@)?((?:[a-z0-9-]+\.)+[a-z]{2,})(?::\d+)?(?:[/?#].*)?$/)32  return m ? m[1] : null33}3435export function linkWarnings(text: string, href: string): LinkWarning[] {36  const out: LinkWarning[] = []37  let u: URL38  try {39    u = new URL(href)40  } catch {41    return out42  }43  if (u.protocol !== "http:" && u.protocol !== "https:") return out44  const host = u.hostname.toLowerCase()45  if (u.username || u.password) out.push("credentials-in-url")46  if (/(^|\.)xn--/.test(host)) out.push("punycode-host")47  if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.startsWith("[")) out.push("ip-host")48  const claimed = hostClaimedByText(text)49  if (claimed && !relatedDomains(claimed, host)) out.push("text-domain-mismatch")50  return out51}5253export function hostOf(href: string): string {54  try {55    return new URL(href).hostname56  } catch {57    return ""58  }59}60
Files main
Menu

Theme