import { ALLOWED_PROTOCOLS } from '../constants'; const INVISIBLE_CHARS = /[\u200b\u200c\u200d\ufeff\u00ad\u2060\u180e]/g; // eslint-disable-next-line regexp/no-control-character const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/; const DANGEROUS_SCHEME = /^(?:javascript|vbscript|data|jscript)\s*:/i; // eslint-disable-next-line regexp/no-useless-non-capturing-group const ENCODED_COLON_SCHEME = /^(?:javascript|vbscript|data|jscript)(?:%3a)/i; const IPV6_BRACKETS = /^\[|\]$/g; const NUMERIC_IP = /^[\d.]+$/; const HEX_IP = /^0x[0-9a-f]+$/i; export function sanitiseHref(href: string): string | undefined { const cleaned = href.replace(INVISIBLE_CHARS, ''); const trimmed = cleaned.trim(); if (!trimmed) { return undefined; } if (CONTROL_CHARS.test(trimmed)) { return undefined; } if (DANGEROUS_SCHEME.test(trimmed)) { return undefined; } if (ENCODED_COLON_SCHEME.test(trimmed)) { return undefined; } if (trimmed.startsWith('//')) { return undefined; } if (trimmed.startsWith('\\')) { return undefined; } if (trimmed.startsWith('/')) { return trimmed[1] !== '\\' ? trimmed : undefined; } if (trimmed.startsWith('#')) { return trimmed; } if (trimmed.startsWith('./') || trimmed.startsWith('../')) { return undefined; } try { const url = new URL(trimmed); if (!ALLOWED_PROTOCOLS.includes(url.protocol)) { return undefined; } if (url.protocol === 'https:') { if (!trimmed.startsWith('https://')) { return undefined; } if (!url.hostname) { return undefined; } if (url.username || url.password) { return undefined; } if (isInternalHost(url.hostname)) { return undefined; } } if (url.protocol === 'mailto:') { if (url.search) { return undefined; } if (!url.pathname) { return undefined; } } return trimmed; } catch { return undefined; } } export type AllowLinksMode = 'internal' | 'all' | 'none'; // Synthetic origin used to resolve relative paths via the WHATWG URL parser. // If the resolved origin still equals this sentinel, the path stays on-origin. const SSR_SENTINEL_ORIGIN = 'https://internal.invalid'; export function isHrefAllowedByMode(href: string, mode: AllowLinksMode): boolean { switch (mode) { case 'none': return false; case 'all': return true; case 'internal': try { if (!href.startsWith('/')) { const parsed = new URL(href); return parsed.protocol === 'https:' && parsed.hostname === 'wise.com'; } const parsed = new URL(href, SSR_SENTINEL_ORIGIN); return parsed.origin === SSR_SENTINEL_ORIGIN; } catch { return false; } } } function isInternalHost(hostname: string): boolean { const stripped = hostname.replace(IPV6_BRACKETS, ''); const host = stripped.endsWith('.') ? stripped.slice(0, -1) : stripped; if (NUMERIC_IP.test(host)) return true; if (HEX_IP.test(host)) return true; if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true; if (host === 'localhost') return true; if (host.endsWith('.internal')) return true; return false; }