Neo Zero

sanitize

Pool

Modern, zero-dependency HTML sanitization library - XSS prevention for browsers and Node.js

$ lpm install @lpm.dev/neo.sanitize
94 exportsTypeScript

dist

Variables

DEFAULT_OPTIONSRequired<SanitizeOptions>

Default sanitization options Safe defaults for general HTML sanitization: - Allows common formatting tags (p, div, strong, etc.) - Allows safe attributes (href, src, alt, etc.) - Allows safe protocols (http, https, mailto, tel) - Forbids all event handlers (onclick, onerror, etc.) - Allows ARIA attributes for accessibility - Denies data-* attributes by default (privacy) - Denies id/class attributes by default (CSS collision) - Denies style attribute by default (CSS injection)

DEFAULT_ALLOWED_TAGSreadonly string[]

Default allowed HTML tags (safe for basic formatting) Covers common formatting needs while blocking dangerous tags like: - <script>, <iframe>, <object>, <embed> (code execution) - <style>, <link> (CSS injection) - <form>, <input>, <button> (phishing, CSRF) - <base> (URL hijacking)

DEFAULT_ALLOWED_ATTRIBUTESReadonly<Record<string, readonly string[]>>

Default allowed attributes per tag Only safe attributes that don't allow code execution: - href/src: Protocol validation required - alt/title: Safe text content - class/id: Only if explicitly enabled

FORBIDDEN_ATTRIBUTESreadonly string[]

Forbidden attributes (always removed, regardless of tag) Blocks all event handlers and dangerous attributes: - Event handlers: onclick, onerror, onload, etc. (XSS vectors) - Script-related: onfocus, onblur, onchange, etc. - Form-related: onsubmit, onreset, etc.

ALLOWED_PROTOCOLSreadonly string[]

Allowed URL protocols for href, src, and similar attributes Only safe protocols that don't allow code execution: - http/https: Web URLs - mailto: Email links - tel: Phone links - ftp: File transfer (safe in href context) Blocked protocols: - javascript: Direct code execution - data: Can contain HTML/scripts - vbscript: VBScript execution (IE) - file: Local file access - about: Browser internals

DANGEROUS_PROTOCOLSreadonly string[]

Dangerous URL protocols (always blocked) These protocols allow code execution or data injection: - javascript: Executes JavaScript code - data: Can contain HTML, SVG, scripts - vbscript: Executes VBScript (legacy IE) - about: Access to browser internals - file: Access to local file system

VOID_ELEMENTSreadonly string[]

Void elements (self-closing, have no content) These elements cannot have child nodes: - <br>, <hr>, <img>, <input>, etc. Important for parsing and serialization.

URL_ATTRIBUTESreadonly string[]

Attributes that accept URLs and require protocol validation These attributes can be vectors for javascript:, data:, etc.: - href: Links (<a>, <area>, <link>) - src: Resources (<img>, <script>, <iframe>, <embed>, etc.) - action: Form submissions - formaction: Button/input form actions - cite: Blockquote/q citations - data: Object data - poster: Video posters

EVENT_HANDLER_REGEXRegExp

Regular expression to match event handler attributes Matches any attribute starting with "on" followed by letters: - onclick, onerror, onload, etc. Used as fallback if event handler is not in FORBIDDEN_ATTRIBUTES list.

DATA_ATTRIBUTE_REGEXRegExp

Regular expression to match data-* attributes Matches any attribute starting with "data-": - data-id, data-value, data-test, etc. Generally safe, but can be used for client-side tracking.

ARIA_ATTRIBUTE_REGEXRegExp

Regular expression to match aria-* attributes Matches any attribute starting with "aria-": - aria-label, aria-hidden, aria-describedby, etc. Safe and important for accessibility.

dist/config/schemas

Functions

getSchema
function getSchema(schemaName: 'BASIC' | 'RELAXED' | 'STRICT'): Required<SanitizeOptions>

Get schema by name

ParameterTypeDescription
schemaName
'BASIC' | 'RELAXED' | 'STRICT'- Schema name ('BASIC', 'RELAXED', 'STRICT')
mergeSchema
function mergeSchema(schemaName: 'BASIC' | 'RELAXED' | 'STRICT', customOptions: Partial<SanitizeOptions>): Required<SanitizeOptions>

Merge schema with custom options Allows overriding specific options while using a schema as base.

ParameterTypeDescription
schemaName
'BASIC' | 'RELAXED' | 'STRICT'- Schema name
customOptions
Partial<SanitizeOptions>- Custom options to override

Variables

BASIC_SCHEMARequired<SanitizeOptions>

BASIC schema - Minimal HTML (text formatting only) Use cases: - User comments (simple formatting) - Text messages with basic formatting - Email signatures Allowed: - Text formatting: p, br, strong, em, u, code, pre - Lists: ul, ol, li - Links: a (href only) - No images, no tables, no classes/ids Security level: HIGH Usability: LOW (very limited HTML)

RELAXED_SCHEMARequired<SanitizeOptions>

RELAXED schema - Rich HTML (images, links, tables, formatting) Use cases: - Blog posts - Rich text editors - Documentation - User-generated content with formatting Allowed: - All text formatting - Images (with src, alt) - Links (with href, title, rel, target) - Tables (full table markup) - Headings (h1-h6) - Blockquotes, code blocks - Class attributes (for syntax highlighting) Security level: MEDIUM Usability: HIGH (rich HTML editing)

STRICT_SCHEMARequired<SanitizeOptions>

STRICT schema - Paranoid security (text only, no HTML) Use cases: - Untrusted user input - High-security applications - Text-only content (strip all HTML) Allowed: - No HTML tags (all stripped) - Only plain text - All dangerous content removed Security level: MAXIMUM Usability: NONE (all HTML stripped)

dist/config/schemas

Functions

getSchema
function getSchema(schemaName: 'BASIC' | 'RELAXED' | 'STRICT'): Required<SanitizeOptions>

Get schema by name

ParameterTypeDescription
schemaName
'BASIC' | 'RELAXED' | 'STRICT'- Schema name ('BASIC', 'RELAXED', 'STRICT')
mergeSchema
function mergeSchema(schemaName: 'BASIC' | 'RELAXED' | 'STRICT', customOptions: Partial<SanitizeOptions>): Required<SanitizeOptions>

Merge schema with custom options Allows overriding specific options while using a schema as base.

ParameterTypeDescription
schemaName
'BASIC' | 'RELAXED' | 'STRICT'- Schema name
customOptions
Partial<SanitizeOptions>- Custom options to override

Variables

BASIC_SCHEMARequired<SanitizeOptions>

BASIC schema - Minimal HTML (text formatting only) Use cases: - User comments (simple formatting) - Text messages with basic formatting - Email signatures Allowed: - Text formatting: p, br, strong, em, u, code, pre - Lists: ul, ol, li - Links: a (href only) - No images, no tables, no classes/ids Security level: HIGH Usability: LOW (very limited HTML)

RELAXED_SCHEMARequired<SanitizeOptions>

RELAXED schema - Rich HTML (images, links, tables, formatting) Use cases: - Blog posts - Rich text editors - Documentation - User-generated content with formatting Allowed: - All text formatting - Images (with src, alt) - Links (with href, title, rel, target) - Tables (full table markup) - Headings (h1-h6) - Blockquotes, code blocks - Class attributes (for syntax highlighting) Security level: MEDIUM Usability: HIGH (rich HTML editing)

STRICT_SCHEMARequired<SanitizeOptions>

STRICT schema - Paranoid security (text only, no HTML) Use cases: - Untrusted user input - High-security applications - Text-only content (strip all HTML) Allowed: - No HTML tags (all stripped) - Only plain text - All dangerous content removed Security level: MAXIMUM Usability: NONE (all HTML stripped)

dist/core

Functions

sanitize
function sanitize(html: string, options?: Partial<SanitizeOptions>): string | DocumentFragment

Sanitize HTML string Main sanitization function that removes dangerous HTML: - Blocks XSS vectors (script tags, event handlers, javascript: URLs) - Whitelists safe tags and attributes - Validates URL protocols - Returns safe HTML

ParameterTypeDescription
html
string- HTML string to sanitize
optionsoptional
Partial<SanitizeOptions>- Sanitization options
createSanitizer
function createSanitizer(options?: Partial<SanitizeOptions>): {
    /**
     * Sanitize HTML with preset configuration
     */
    sanitize(html: string): string | DocumentFragment;
    /**
     * Get current configuration
     */
    getConfig(): Readonly<Required<SanitizeOptions>>;
    /**
     * Update configuration
     */
    updateConfig(newOptions: Partial<SanitizeOptions>): void;
}

Create a reusable sanitizer instance with preset configuration Useful for sanitizing multiple HTML strings with the same options. Avoids re-merging options on every call.

ParameterTypeDescription
optionsoptional
Partial<SanitizeOptions>- Sanitization options
sanitizeBasic
function sanitizeBasic(html: string): string

Convenience function: Sanitize with BASIC schema

ParameterTypeDescription
html
string
sanitizeRelaxed
function sanitizeRelaxed(html: string): string

Convenience function: Sanitize with RELAXED schema

ParameterTypeDescription
html
string
sanitizeStrict
function sanitizeStrict(html: string): string

Convenience function: Sanitize with STRICT schema

ParameterTypeDescription
html
string
parseHTML
function parseHTML(html: string): DocumentFragment

Parse HTML string to DocumentFragment Uses browser's native DOMParser which is: - Highly performant (native C++ implementation) - Resistant to mXSS (consistent parsing) - Safe for untrusted HTML (doesn't execute scripts)

ParameterTypeDescription
html
string- HTML string to parse
serializeHTML
function serializeHTML(fragment: DocumentFragment): string

Serialize DocumentFragment to HTML string Converts DOM tree back to HTML string.

ParameterTypeDescription
fragment
DocumentFragment- DocumentFragment to serialize
isBrowser
function isBrowser(): boolean

Check if we're in a browser environment

isNode
function isNode(): boolean

Check if we're in a Node.js environment

dist/core

Functions

sanitize
function sanitize(html: string, options?: Partial<SanitizeOptions>): string | DocumentFragment

Sanitize HTML string Main sanitization function that removes dangerous HTML: - Blocks XSS vectors (script tags, event handlers, javascript: URLs) - Whitelists safe tags and attributes - Validates URL protocols - Returns safe HTML

ParameterTypeDescription
html
string- HTML string to sanitize
optionsoptional
Partial<SanitizeOptions>- Sanitization options
createSanitizer
function createSanitizer(options?: Partial<SanitizeOptions>): {
    /**
     * Sanitize HTML with preset configuration
     */
    sanitize(html: string): string | DocumentFragment;
    /**
     * Get current configuration
     */
    getConfig(): Readonly<Required<SanitizeOptions>>;
    /**
     * Update configuration
     */
    updateConfig(newOptions: Partial<SanitizeOptions>): void;
}

Create a reusable sanitizer instance with preset configuration Useful for sanitizing multiple HTML strings with the same options. Avoids re-merging options on every call.

ParameterTypeDescription
optionsoptional
Partial<SanitizeOptions>- Sanitization options
sanitizeBasic
function sanitizeBasic(html: string): string

Convenience function: Sanitize with BASIC schema

ParameterTypeDescription
html
string
sanitizeRelaxed
function sanitizeRelaxed(html: string): string

Convenience function: Sanitize with RELAXED schema

ParameterTypeDescription
html
string
sanitizeStrict
function sanitizeStrict(html: string): string

Convenience function: Sanitize with STRICT schema

ParameterTypeDescription
html
string
parseHTML
function parseHTML(html: string): DocumentFragment

Parse HTML string to DocumentFragment Uses browser's native DOMParser which is: - Highly performant (native C++ implementation) - Resistant to mXSS (consistent parsing) - Safe for untrusted HTML (doesn't execute scripts)

ParameterTypeDescription
html
string- HTML string to parse
serializeHTML
function serializeHTML(fragment: DocumentFragment): string

Serialize DocumentFragment to HTML string Converts DOM tree back to HTML string.

ParameterTypeDescription
fragment
DocumentFragment- DocumentFragment to serialize
isBrowser
function isBrowser(): boolean

Check if we're in a browser environment

isNode
function isNode(): boolean

Check if we're in a Node.js environment

dist

Variables

DEFAULT_OPTIONSRequired<SanitizeOptions>

Default sanitization options Safe defaults for general HTML sanitization: - Allows common formatting tags (p, div, strong, etc.) - Allows safe attributes (href, src, alt, etc.) - Allows safe protocols (http, https, mailto, tel) - Forbids all event handlers (onclick, onerror, etc.) - Allows ARIA attributes for accessibility - Denies data-* attributes by default (privacy) - Denies id/class attributes by default (CSS collision) - Denies style attribute by default (CSS injection)

DEFAULT_ALLOWED_TAGSreadonly string[]

Default allowed HTML tags (safe for basic formatting) Covers common formatting needs while blocking dangerous tags like: - <script>, <iframe>, <object>, <embed> (code execution) - <style>, <link> (CSS injection) - <form>, <input>, <button> (phishing, CSRF) - <base> (URL hijacking)

DEFAULT_ALLOWED_ATTRIBUTESReadonly<Record<string, readonly string[]>>

Default allowed attributes per tag Only safe attributes that don't allow code execution: - href/src: Protocol validation required - alt/title: Safe text content - class/id: Only if explicitly enabled

FORBIDDEN_ATTRIBUTESreadonly string[]

Forbidden attributes (always removed, regardless of tag) Blocks all event handlers and dangerous attributes: - Event handlers: onclick, onerror, onload, etc. (XSS vectors) - Script-related: onfocus, onblur, onchange, etc. - Form-related: onsubmit, onreset, etc.

ALLOWED_PROTOCOLSreadonly string[]

Allowed URL protocols for href, src, and similar attributes Only safe protocols that don't allow code execution: - http/https: Web URLs - mailto: Email links - tel: Phone links - ftp: File transfer (safe in href context) Blocked protocols: - javascript: Direct code execution - data: Can contain HTML/scripts - vbscript: VBScript execution (IE) - file: Local file access - about: Browser internals

DANGEROUS_PROTOCOLSreadonly string[]

Dangerous URL protocols (always blocked) These protocols allow code execution or data injection: - javascript: Executes JavaScript code - data: Can contain HTML, SVG, scripts - vbscript: Executes VBScript (legacy IE) - about: Access to browser internals - file: Access to local file system

VOID_ELEMENTSreadonly string[]

Void elements (self-closing, have no content) These elements cannot have child nodes: - <br>, <hr>, <img>, <input>, etc. Important for parsing and serialization.

URL_ATTRIBUTESreadonly string[]

Attributes that accept URLs and require protocol validation These attributes can be vectors for javascript:, data:, etc.: - href: Links (<a>, <area>, <link>) - src: Resources (<img>, <script>, <iframe>, <embed>, etc.) - action: Form submissions - formaction: Button/input form actions - cite: Blockquote/q citations - data: Object data - poster: Video posters

EVENT_HANDLER_REGEXRegExp

Regular expression to match event handler attributes Matches any attribute starting with "on" followed by letters: - onclick, onerror, onload, etc. Used as fallback if event handler is not in FORBIDDEN_ATTRIBUTES list.

DATA_ATTRIBUTE_REGEXRegExp

Regular expression to match data-* attributes Matches any attribute starting with "data-": - data-id, data-value, data-test, etc. Generally safe, but can be used for client-side tracking.

ARIA_ATTRIBUTE_REGEXRegExp

Regular expression to match aria-* attributes Matches any attribute starting with "aria-": - aria-label, aria-hidden, aria-describedby, etc. Safe and important for accessibility.

dist/validators

Functions

getProtocol
function getProtocol(url: string): string | null

Extract protocol from a URL string Handles various URL formats: - Absolute URLs: "https://example.com" - Protocol-relative URLs: "//example.com" - Relative URLs: "/path" or "path" - Protocol-only: "javascript:alert('xss')"

ParameterTypeDescription
url
string- URL string to parse
isProtocolAllowed
function isProtocolAllowed(protocol: string | null, allowedProtocols?: readonly string[] | string[]): boolean

Check if a protocol is allowed

ParameterTypeDescription
protocol
string | null- Protocol name (lowercase)
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
isDangerousProtocol
function isDangerousProtocol(protocol: string | null): boolean

Check if a protocol is dangerous

ParameterTypeDescription
protocol
string | null- Protocol name (lowercase)
validateProtocol
function validateProtocol(url: string, allowedProtocols?: readonly string[] | string[]): ProtocolValidationResult

Validate a URL protocol Comprehensive protocol validation with detailed result: - Extracts protocol - Checks if allowed - Checks if dangerous - Provides reason for rejection

ParameterTypeDescription
url
string- URL string to validate
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
sanitizeURL
function sanitizeURL(url: string, allowedProtocols?: readonly string[] | string[], fallback?: string): string

Sanitize a URL by removing dangerous protocols If the URL has a dangerous or disallowed protocol: - Returns an empty string (safest approach) - OR returns '#' to preserve link functionality without danger

ParameterTypeDescription
url
string- URL string to sanitize
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
fallbackoptional
string- Fallback value for invalid URLs (default: '')
isSafeURL
function isSafeURL(url: string, allowedProtocols?: readonly string[] | string[]): boolean

Check if a URL is safe (convenience function) Returns true if URL has a safe protocol (or is relative).

ParameterTypeDescription
url
string- URL string to check
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
normalizeTagName
function normalizeTagName(tagName: string): string

Normalize tag name to lowercase HTML tag names are case-insensitive, but we normalize to lowercase for consistent comparison.

ParameterTypeDescription
tagName
string- Tag name to normalize
isTagAllowed
function isTagAllowed(tagName: string, allowedTags?: readonly string[] | string[]): boolean

Check if a tag is allowed

ParameterTypeDescription
tagName
string- Tag name to check (case-insensitive)
allowedTagsoptional
readonly string[] | string[]- List of allowed tags
isDangerousTag
function isDangerousTag(tagName: string): boolean

Check if a tag is dangerous

ParameterTypeDescription
tagName
string- Tag name to check (case-insensitive)
validateTag
function validateTag(tagName: string, allowedTags?: readonly string[] | string[]): TagValidationResult

Validate a tag name Comprehensive tag validation with detailed result: - Normalizes tag name to lowercase - Checks if allowed - Provides reason for rejection

ParameterTypeDescription
tagName
string- Tag name to validate
allowedTagsoptional
readonly string[] | string[]- List of allowed tags
filterAllowedTags
function filterAllowedTags(tagNames: string[], allowedTags?: readonly string[] | string[]): string[]

Filter allowed tags from a list Returns only tags that are in the allowed list.

ParameterTypeDescription
tagNames
string[]- List of tag names to filter
allowedTagsoptional
readonly string[] | string[]- List of allowed tags
getDangerousTags
function getDangerousTags(tagNames: string[]): string[]

Get dangerous tags from a list Returns only tags that are dangerous.

ParameterTypeDescription
tagNames
string[]- List of tag names to check
normalizeAttributeName
function normalizeAttributeName(attrName: string): string

Normalize attribute name to lowercase Attribute names are case-insensitive in HTML.

ParameterTypeDescription
attrName
string- Attribute name to normalize
isEventHandler
function isEventHandler(attrName: string): boolean

Check if an attribute is an event handler Matches attributes like: onclick, onerror, onload, etc.

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isDataAttribute
function isDataAttribute(attrName: string): boolean

Check if an attribute is a data-* attribute Matches attributes like: data-id, data-value, data-test

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isAriaAttribute
function isAriaAttribute(attrName: string): boolean

Check if an attribute is an aria-* attribute Matches attributes like: aria-label, aria-hidden, aria-describedby

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isURLAttribute
function isURLAttribute(attrName: string): boolean

Check if an attribute is a URL attribute Matches attributes that accept URLs: href, src, action, etc.

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isForbiddenAttribute
function isForbiddenAttribute(attrName: string, forbiddenAttributes?: readonly string[] | string[]): boolean

Check if an attribute is forbidden Checks both the forbidden list and event handler pattern.

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
forbiddenAttributesoptional
readonly string[] | string[]- Additional forbidden attributes
isAttributeAllowed
function isAttributeAllowed(tagName: string, attrName: string, allowedAttributes?: Readonly<Record<string, readonly string[]>> | Record<string, string[]>, options?: Partial<SanitizeOptions>): boolean

Check if an attribute is allowed for a given tag

ParameterTypeDescription
tagName
string- Tag name (lowercase)
attrName
string- Attribute name (case-insensitive)
allowedAttributesoptional
Readonly<Record<string, readonly string[]>> | Record<string, string[]>- Allowed attributes per tag
optionsoptional
Partial<SanitizeOptions>- Sanitization options
validateAttribute
function validateAttribute(tagName: string, attrName: string, attrValue: string, allowedAttributes?: Readonly<Record<string, readonly string[]>> | Record<string, string[]>, options?: Partial<SanitizeOptions>): AttributeValidationResult

Validate an attribute Comprehensive attribute validation with detailed result: - Normalizes attribute name - Checks if forbidden (event handlers, etc.) - Checks if allowed for the tag - Validates URL protocols for URL attributes - Sanitizes attribute value if needed

ParameterTypeDescription
tagName
string- Tag name (lowercase)
attrName
string- Attribute name (case-insensitive)
attrValue
string- Attribute value
allowedAttributesoptional
Readonly<Record<string, readonly string[]>> | Record<string, string[]>- Allowed attributes per tag
optionsoptional
Partial<SanitizeOptions>- Sanitization options
filterAllowedAttributes
function filterAllowedAttributes(tagName: string, attributes: Record<string, string>, allowedAttributes?: Readonly<Record<string, readonly string[]>> | Record<string, string[]>, options?: Partial<SanitizeOptions>): Record<string, string>

Filter allowed attributes for an element Returns only attributes that are allowed for the given tag.

ParameterTypeDescription
tagName
string- Tag name (lowercase)
attributes
Record<string, string>- Map of attribute name → value
allowedAttributesoptional
Readonly<Record<string, readonly string[]>> | Record<string, string[]>- Allowed attributes per tag
optionsoptional
Partial<SanitizeOptions>- Sanitization options

Variables

DANGEROUS_TAGSreadonly string[]

Dangerous HTML tags that should never be allowed These tags can execute code or inject malicious content: - script: Direct JavaScript execution - iframe: Can load any URL, including malicious sites - object, embed: Can load plugins, Flash, etc. - style, link: CSS injection (expression(),

dist/validators

Functions

getProtocol
function getProtocol(url: string): string | null

Extract protocol from a URL string Handles various URL formats: - Absolute URLs: "https://example.com" - Protocol-relative URLs: "//example.com" - Relative URLs: "/path" or "path" - Protocol-only: "javascript:alert('xss')"

ParameterTypeDescription
url
string- URL string to parse
isProtocolAllowed
function isProtocolAllowed(protocol: string | null, allowedProtocols?: readonly string[] | string[]): boolean

Check if a protocol is allowed

ParameterTypeDescription
protocol
string | null- Protocol name (lowercase)
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
isDangerousProtocol
function isDangerousProtocol(protocol: string | null): boolean

Check if a protocol is dangerous

ParameterTypeDescription
protocol
string | null- Protocol name (lowercase)
validateProtocol
function validateProtocol(url: string, allowedProtocols?: readonly string[] | string[]): ProtocolValidationResult

Validate a URL protocol Comprehensive protocol validation with detailed result: - Extracts protocol - Checks if allowed - Checks if dangerous - Provides reason for rejection

ParameterTypeDescription
url
string- URL string to validate
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
sanitizeURL
function sanitizeURL(url: string, allowedProtocols?: readonly string[] | string[], fallback?: string): string

Sanitize a URL by removing dangerous protocols If the URL has a dangerous or disallowed protocol: - Returns an empty string (safest approach) - OR returns '#' to preserve link functionality without danger

ParameterTypeDescription
url
string- URL string to sanitize
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
fallbackoptional
string- Fallback value for invalid URLs (default: '')
isSafeURL
function isSafeURL(url: string, allowedProtocols?: readonly string[] | string[]): boolean

Check if a URL is safe (convenience function) Returns true if URL has a safe protocol (or is relative).

ParameterTypeDescription
url
string- URL string to check
allowedProtocolsoptional
readonly string[] | string[]- List of allowed protocols
normalizeTagName
function normalizeTagName(tagName: string): string

Normalize tag name to lowercase HTML tag names are case-insensitive, but we normalize to lowercase for consistent comparison.

ParameterTypeDescription
tagName
string- Tag name to normalize
isTagAllowed
function isTagAllowed(tagName: string, allowedTags?: readonly string[] | string[]): boolean

Check if a tag is allowed

ParameterTypeDescription
tagName
string- Tag name to check (case-insensitive)
allowedTagsoptional
readonly string[] | string[]- List of allowed tags
isDangerousTag
function isDangerousTag(tagName: string): boolean

Check if a tag is dangerous

ParameterTypeDescription
tagName
string- Tag name to check (case-insensitive)
validateTag
function validateTag(tagName: string, allowedTags?: readonly string[] | string[]): TagValidationResult

Validate a tag name Comprehensive tag validation with detailed result: - Normalizes tag name to lowercase - Checks if allowed - Provides reason for rejection

ParameterTypeDescription
tagName
string- Tag name to validate
allowedTagsoptional
readonly string[] | string[]- List of allowed tags
filterAllowedTags
function filterAllowedTags(tagNames: string[], allowedTags?: readonly string[] | string[]): string[]

Filter allowed tags from a list Returns only tags that are in the allowed list.

ParameterTypeDescription
tagNames
string[]- List of tag names to filter
allowedTagsoptional
readonly string[] | string[]- List of allowed tags
getDangerousTags
function getDangerousTags(tagNames: string[]): string[]

Get dangerous tags from a list Returns only tags that are dangerous.

ParameterTypeDescription
tagNames
string[]- List of tag names to check
normalizeAttributeName
function normalizeAttributeName(attrName: string): string

Normalize attribute name to lowercase Attribute names are case-insensitive in HTML.

ParameterTypeDescription
attrName
string- Attribute name to normalize
isEventHandler
function isEventHandler(attrName: string): boolean

Check if an attribute is an event handler Matches attributes like: onclick, onerror, onload, etc.

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isDataAttribute
function isDataAttribute(attrName: string): boolean

Check if an attribute is a data-* attribute Matches attributes like: data-id, data-value, data-test

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isAriaAttribute
function isAriaAttribute(attrName: string): boolean

Check if an attribute is an aria-* attribute Matches attributes like: aria-label, aria-hidden, aria-describedby

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isURLAttribute
function isURLAttribute(attrName: string): boolean

Check if an attribute is a URL attribute Matches attributes that accept URLs: href, src, action, etc.

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
isForbiddenAttribute
function isForbiddenAttribute(attrName: string, forbiddenAttributes?: readonly string[] | string[]): boolean

Check if an attribute is forbidden Checks both the forbidden list and event handler pattern.

ParameterTypeDescription
attrName
string- Attribute name to check (case-insensitive)
forbiddenAttributesoptional
readonly string[] | string[]- Additional forbidden attributes
isAttributeAllowed
function isAttributeAllowed(tagName: string, attrName: string, allowedAttributes?: Readonly<Record<string, readonly string[]>> | Record<string, string[]>, options?: Partial<SanitizeOptions>): boolean

Check if an attribute is allowed for a given tag

ParameterTypeDescription
tagName
string- Tag name (lowercase)
attrName
string- Attribute name (case-insensitive)
allowedAttributesoptional
Readonly<Record<string, readonly string[]>> | Record<string, string[]>- Allowed attributes per tag
optionsoptional
Partial<SanitizeOptions>- Sanitization options
validateAttribute
function validateAttribute(tagName: string, attrName: string, attrValue: string, allowedAttributes?: Readonly<Record<string, readonly string[]>> | Record<string, string[]>, options?: Partial<SanitizeOptions>): AttributeValidationResult

Validate an attribute Comprehensive attribute validation with detailed result: - Normalizes attribute name - Checks if forbidden (event handlers, etc.) - Checks if allowed for the tag - Validates URL protocols for URL attributes - Sanitizes attribute value if needed

ParameterTypeDescription
tagName
string- Tag name (lowercase)
attrName
string- Attribute name (case-insensitive)
attrValue
string- Attribute value
allowedAttributesoptional
Readonly<Record<string, readonly string[]>> | Record<string, string[]>- Allowed attributes per tag
optionsoptional
Partial<SanitizeOptions>- Sanitization options
filterAllowedAttributes
function filterAllowedAttributes(tagName: string, attributes: Record<string, string>, allowedAttributes?: Readonly<Record<string, readonly string[]>> | Record<string, string[]>, options?: Partial<SanitizeOptions>): Record<string, string>

Filter allowed attributes for an element Returns only attributes that are allowed for the given tag.

ParameterTypeDescription
tagName
string- Tag name (lowercase)
attributes
Record<string, string>- Map of attribute name → value
allowedAttributesoptional
Readonly<Record<string, readonly string[]>> | Record<string, string[]>- Allowed attributes per tag
optionsoptional
Partial<SanitizeOptions>- Sanitization options

Variables

DANGEROUS_TAGSreadonly string[]

Dangerous HTML tags that should never be allowed These tags can execute code or inject malicious content: - script: Direct JavaScript execution - iframe: Can load any URL, including malicious sites - object, embed: Can load plugins, Flash, etc. - style, link: CSS injection (expression(),

Unlimited AccessInstall as many Pool packages as you need.
Fund Real WorkEvery install you run sends revenue directly to the developer who built it.

Taxes calculated at checkout based on your location.

Weekly Installs
3
Version
1.0.0
Published
LicenseMIT
Size592.16 KB
Files32
Node version>= 18
TypeScriptYes