@arraypress/url-sanitize
v1.0.0
Published
URL sanitization and validation. Prevent XSS via javascript:, data:, and other dangerous URL schemes.
Maintainers
Readme
@arraypress/url-sanitize
URL sanitization and validation. Prevents XSS via dangerous URL schemes (javascript:, data:, vbscript:, blob:). Zero dependencies.
Installation
npm install @arraypress/url-sanitizeUsage
import { isSafe, sanitize, isExternal, externalRel } from '@arraypress/url-sanitize';
// Check if a URL is safe
isSafe('https://example.com'); // true
isSafe('javascript:alert(1)'); // false
isSafe('/about'); // true
// Sanitize — returns '' for dangerous URLs
sanitize('javascript:void(0)'); // ''
sanitize('https://example.com'); // 'https://example.com'
// External link detection
isExternal('https://other.com', 'https://mystore.com'); // true
externalRel('https://other.com', 'https://mystore.com'); // 'noopener noreferrer'API
isSafe(href)
Check if a URL is safe for HTML attributes. Allows http/https, mailto, tel, sms, ftp, relative paths, and fragments. Blocks javascript:, data:, vbscript:, blob: (including case variations and whitespace obfuscation).
sanitize(href)
Returns the trimmed URL if safe, empty string if dangerous.
sanitizeOr(href, fallback?)
Returns the URL if safe, or the fallback (default '#') if dangerous.
isAbsolute(href)
Check if a URL has a scheme (is absolute).
isExternal(href, baseOrigin)
Check if a URL points to a different origin.
externalRel(href, baseOrigin?)
Returns 'noopener noreferrer' for external links, '' for internal.
License
MIT
