cure53 / DOMPurify

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:
https://cure53.de/purify
Other
14.14k stars 735 forks source link

Changed the type of the "node" in hooks to be as specific as possible #1031

Closed reduckted closed 1 week ago

reduckted commented 1 week ago

Fixes #1029.

Prior to the TypeScript type declarations being provided by this package, the @types/dompurify package defined all hooks as taking an Element as the first parameter. That was incorrect because some hooks can be given a Node or DocumentFragment. When the type declarations were moved into this repository, the hook's first parameter type was changed to Node. This change was overzealous because some hooks are guaranteed to only be given an Element or DocumentFragment.

To account for those hooks, this pull request adds two additional hook types - ElementHook and DocumentFragmentHook (plus Hook has been renamed to NodeHook to disambiguate it). Hook Type of currentNode
beforeSanitizeElements Node
afterSanitizeElements Node
beforeSanitizeShadowDOM DocumentFragment
uponSanitizeShadowNode Node
afterSanitizeShadowDOM DocumentFragment
beforeSanitizeAttributes Element
afterSanitizeAttributes Element
uponSanitizeElement Node
uponSanitizeAttribute Element

To make this as type-safe as possible internally, I've changed the hooks to be stored in an object with properties named after each hook rather than just in an object that keys a string to an array of functions. The _executeHooks function now takes in the array of hooks to execute rather than the name of the hook. This allows the "node" and "data" parameters for the hook to have type-checking applied at compile time to ensure that, for example, you don't call _executeHooks with a Node when the hooks you are executing require an Element.

cure53 commented 1 week ago

Awesome, thank you!