Generated type declaration files.

This commit is contained in:
reduckted
2024-10-18 22:15:55 +10:00
parent 18ec503da4
commit 805164dd34
8 changed files with 923 additions and 55 deletions
+1 -5
View File
@@ -57,10 +57,6 @@ Note that by default, we permit HTML, SVG **and** MathML. If you only need HTML,
const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });
```
### Where are the TypeScript type definitions?
They can be found here: [@types/dompurify](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/dompurify)
### Is there any foot-gun potential?
Well, please note, if you _first_ sanitize HTML and then modify it _afterwards_, you might easily **void the effects of sanitization**. If you feed the sanitized markup to another library _after_ sanitization, please be certain that the library doesn't mess around with the HTML on its own.
@@ -433,7 +429,7 @@ Feature releases will not be announced to this list.
Many people helped and help DOMPurify become what it is and need to be acknowledged here!
[hash_kitten ❤️](https://twitter.com/hash_kitten), [kevin_mizu ❤️](https://twitter.com/kevin_mizu), [icesfont ❤️](https://github.com/icesfont) [dcramer 💸](https://github.com/dcramer), [JGraph 💸](https://github.com/jgraph), [baekilda 💸](https://github.com/baekilda), [Healthchecks 💸](https://github.com/healthchecks), [Sentry 💸](https://github.com/getsentry), [jarrodldavis 💸](https://github.com/jarrodldavis), [CynegeticIO](https://github.com/CynegeticIO), [ssi02014 ❤️](https://github.com/ssi02014), [GrantGryczan](https://github.com/GrantGryczan), [Lowdefy](https://twitter.com/lowdefy), [granlem](https://twitter.com/MaximeVeit), [oreoshake](https://github.com/oreoshake), [tdeekens ❤️](https://github.com/tdeekens), [peernohell ❤️](https://github.com/peernohell), [is2ei](https://github.com/is2ei), [SoheilKhodayari](https://github.com/SoheilKhodayari), [franktopel](https://github.com/franktopel), [NateScarlet](https://github.com/NateScarlet), [neilj](https://github.com/neilj), [fhemberger](https://github.com/fhemberger), [Joris-van-der-Wel](https://github.com/Joris-van-der-Wel), [ydaniv](https://github.com/ydaniv), [terjanq](https://twitter.com/terjanq), [filedescriptor](https://github.com/filedescriptor), [ConradIrwin](https://github.com/ConradIrwin), [gibson042](https://github.com/gibson042), [choumx](https://github.com/choumx), [0xSobky](https://github.com/0xSobky), [styfle](https://github.com/styfle), [koto](https://github.com/koto), [tlau88](https://github.com/tlau88), [strugee](https://github.com/strugee), [oparoz](https://github.com/oparoz), [mathiasbynens](https://github.com/mathiasbynens), [edg2s](https://github.com/edg2s), [dnkolegov](https://github.com/dnkolegov), [dhardtke](https://github.com/dhardtke), [wirehead](https://github.com/wirehead), [thorn0](https://github.com/thorn0), [styu](https://github.com/styu), [mozfreddyb](https://github.com/mozfreddyb), [mikesamuel](https://github.com/mikesamuel), [jorangreef](https://github.com/jorangreef), [jimmyhchan](https://github.com/jimmyhchan), [jameydeorio](https://github.com/jameydeorio), [jameskraus](https://github.com/jameskraus), [hyderali](https://github.com/hyderali), [hansottowirtz](https://github.com/hansottowirtz), [hackvertor](https://github.com/hackvertor), [freddyb](https://github.com/freddyb), [flavorjones](https://github.com/flavorjones), [djfarrelly](https://github.com/djfarrelly), [devd](https://github.com/devd), [camerondunford](https://github.com/camerondunford), [buu700](https://github.com/buu700), [buildog](https://github.com/buildog), [alabiaga](https://github.com/alabiaga), [Vector919](https://github.com/Vector919), [Robbert](https://github.com/Robbert), [GreLI](https://github.com/GreLI), [FuzzySockets](https://github.com/FuzzySockets), [ArtemBernatskyy](https://github.com/ArtemBernatskyy), [@garethheyes](https://twitter.com/garethheyes), [@shafigullin](https://twitter.com/shafigullin), [@mmrupp](https://twitter.com/mmrupp), [@irsdl](https://twitter.com/irsdl),[ShikariSenpai](https://github.com/ShikariSenpai), [ansjdnakjdnajkd](https://github.com/ansjdnakjdnajkd), [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro), [@CmdEngineer\_](https://twitter.com/CmdEngineer_), [@avr4mit](https://twitter.com/avr4mit) and especially [@securitymb ❤️](https://twitter.com/securitymb) & [@masatokinugawa ❤️](https://twitter.com/masatokinugawa)
[hash_kitten ❤️](https://twitter.com/hash_kitten), [kevin_mizu ❤️](https://twitter.com/kevin_mizu), [icesfont ❤️](https://github.com/icesfont) [dcramer 💸](https://github.com/dcramer), [JGraph 💸](https://github.com/jgraph), [baekilda 💸](https://github.com/baekilda), [Healthchecks 💸](https://github.com/healthchecks), [Sentry 💸](https://github.com/getsentry), [jarrodldavis 💸](https://github.com/jarrodldavis), [CynegeticIO](https://github.com/CynegeticIO), [ssi02014 ❤️](https://github.com/ssi02014), [GrantGryczan](https://github.com/GrantGryczan), [Lowdefy](https://twitter.com/lowdefy), [granlem](https://twitter.com/MaximeVeit), [oreoshake](https://github.com/oreoshake), [tdeekens ❤️](https://github.com/tdeekens), [peernohell ❤️](https://github.com/peernohell), [is2ei](https://github.com/is2ei), [SoheilKhodayari](https://github.com/SoheilKhodayari), [franktopel](https://github.com/franktopel), [NateScarlet](https://github.com/NateScarlet), [neilj](https://github.com/neilj), [fhemberger](https://github.com/fhemberger), [Joris-van-der-Wel](https://github.com/Joris-van-der-Wel), [ydaniv](https://github.com/ydaniv), [terjanq](https://twitter.com/terjanq), [filedescriptor](https://github.com/filedescriptor), [ConradIrwin](https://github.com/ConradIrwin), [gibson042](https://github.com/gibson042), [choumx](https://github.com/choumx), [0xSobky](https://github.com/0xSobky), [styfle](https://github.com/styfle), [koto](https://github.com/koto), [tlau88](https://github.com/tlau88), [strugee](https://github.com/strugee), [oparoz](https://github.com/oparoz), [mathiasbynens](https://github.com/mathiasbynens), [edg2s](https://github.com/edg2s), [dnkolegov](https://github.com/dnkolegov), [dhardtke](https://github.com/dhardtke), [wirehead](https://github.com/wirehead), [thorn0](https://github.com/thorn0), [styu](https://github.com/styu), [mozfreddyb](https://github.com/mozfreddyb), [mikesamuel](https://github.com/mikesamuel), [jorangreef](https://github.com/jorangreef), [jimmyhchan](https://github.com/jimmyhchan), [jameydeorio](https://github.com/jameydeorio), [jameskraus](https://github.com/jameskraus), [hyderali](https://github.com/hyderali), [hansottowirtz](https://github.com/hansottowirtz), [hackvertor](https://github.com/hackvertor), [freddyb](https://github.com/freddyb), [flavorjones](https://github.com/flavorjones), [djfarrelly](https://github.com/djfarrelly), [devd](https://github.com/devd), [camerondunford](https://github.com/camerondunford), [buu700](https://github.com/buu700), [buildog](https://github.com/buildog), [alabiaga](https://github.com/alabiaga), [Vector919](https://github.com/Vector919), [Robbert](https://github.com/Robbert), [GreLI](https://github.com/GreLI), [FuzzySockets](https://github.com/FuzzySockets), [ArtemBernatskyy](https://github.com/ArtemBernatskyy), [@garethheyes](https://twitter.com/garethheyes), [@shafigullin](https://twitter.com/shafigullin), [@mmrupp](https://twitter.com/mmrupp), [@irsdl](https://twitter.com/irsdl),[ShikariSenpai](https://github.com/ShikariSenpai), [ansjdnakjdnajkd](https://github.com/ansjdnakjdnajkd), [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro), [@CmdEngineer\_](https://twitter.com/CmdEngineer_), [@avr4mit](https://twitter.com/avr4mit) and especially [@securitymb ❤️](https://twitter.com/securitymb) & [@masatokinugawa ❤️](https://twitter.com/masatokinugawa)
## Testing powered by
+401
View File
@@ -0,0 +1,401 @@
/*! @license DOMPurify 3.1.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.7/LICENSE */
/**
* Configuration to control DOMPurify behavior.
*/
interface Config {
/**
* Extend the existing array of allowed attributes.
*/
ADD_ATTR?: string[] | undefined;
/**
* Extend the existing array of elements that can use Data URIs.
*/
ADD_DATA_URI_TAGS?: string[] | undefined;
/**
* Extend the existing array of allowed tags.
*/
ADD_TAGS?: string[] | undefined;
/**
* Extend the existing array of elements that are safe for URI-like values (be careful, XSS risk).
*/
ADD_URI_SAFE_ATTR?: string[] | undefined;
/**
* Allow ARIA attributes, leave other safe HTML as is (default is true).
*/
ALLOW_ARIA_ATTR?: boolean | undefined;
/**
* Allow HTML5 data attributes, leave other safe HTML as is (default is true).
*/
ALLOW_DATA_ATTR?: boolean | undefined;
/**
* Allow external protocol handlers in URL attributes (default is false, be careful, XSS risk).
* By default only `http`, `https`, `ftp`, `ftps`, `tel`, `mailto`, `callto`, `sms`, `cid` and `xmpp` are allowed.
*/
ALLOW_UNKNOWN_PROTOCOLS?: boolean | undefined;
/**
* Decide if self-closing tags in attributes are allowed.
* Usually removed due to a mXSS issue in jQuery 3.0.
*/
ALLOW_SELF_CLOSE_IN_ATTR?: boolean | undefined;
/**
* Allow only specific attributes.
*/
ALLOWED_ATTR?: string[] | undefined;
/**
* Allow only specific elements.
*/
ALLOWED_TAGS?: string[] | undefined;
/**
* Allow only specific namespaces. Defaults to:
* - `http://www.w3.org/1999/xhtml`
* - `http://www.w3.org/2000/svg`
* - `http://www.w3.org/1998/Math/MathML`
*/
ALLOWED_NAMESPACES?: string[] | undefined;
/**
* Allow specific protocols handlers in URL attributes via regex (be careful, XSS risk).
* Default RegExp:
* ```
* /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
* ```
*/
ALLOWED_URI_REGEXP?: RegExp | undefined;
/**
* Define how custom elements are handled.
*/
CUSTOM_ELEMENT_HANDLING?: {
/**
* Regular expression or function to match to allowed elements.
* Default is null (disallow any custom elements).
*/
tagNameCheck?: RegExp | ((tagName: string) => boolean) | null | undefined;
/**
* Regular expression or function to match to allowed attributes.
* Default is null (disallow any attributes not on the allow list).
*/
attributeNameCheck?: RegExp | ((attributeName: string) => boolean) | null | undefined;
/**
* Allow custom elements derived from built-ins if they pass `tagNameCheck`. Default is false.
*/
allowCustomizedBuiltInElements?: boolean | undefined;
};
/**
* Add attributes to block-list.
*/
FORBID_ATTR?: string[] | undefined;
/**
* Add child elements to be removed when their parent is removed.
*/
FORBID_CONTENTS?: string[] | undefined;
/**
* Add elements to block-list.
*/
FORBID_TAGS?: string[] | undefined;
/**
* Glue elements like style, script or others to `document.body` and prevent unintuitive browser behavior in several edge-cases (default is false).
*/
FORCE_BODY?: boolean | undefined;
/**
* Map of non-standard HTML element names to support. Map to true to enable support. For example:
*
* ```
* HTML_INTEGRATION_POINTS: { foreignobject: true }
* ```
*/
HTML_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
/**
* Sanitize a node "in place", which is much faster depending on how you use DOMPurify.
*/
IN_PLACE?: boolean | undefined;
/**
* Keep an element's content when the element is removed (default is true).
*/
KEEP_CONTENT?: boolean | undefined;
/**
* Map of MathML element names to support. Map to true to enable support. For example:
*
* ```
* MATHML_TEXT_INTEGRATION_POINTS: { mtext: true }
* ```
*/
MATHML_TEXT_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
/**
* Change the default namespace from HTML to something different.
*/
NAMESPACE?: string | undefined;
/**
* Change the parser type so sanitized data is treated as XML and not as HTML, which is the default.
*/
PARSER_MEDIA_TYPE?: DOMParserSupportedType | undefined;
/**
* Return a DOM `DocumentFragment` instead of an HTML string (default is false).
*/
RETURN_DOM_FRAGMENT?: boolean | undefined;
/**
* Return a DOM `HTMLBodyElement` instead of an HTML string (default is false).
*/
RETURN_DOM?: boolean | undefined;
/**
* Return a TrustedHTML object instead of a string if possible.
*/
RETURN_TRUSTED_TYPE?: boolean | undefined;
/**
* Strip `{{ ... }}`, `${ ... }` and `<% ... %>` to make output safe for template systems.
* Be careful please, this mode is not recommended for production usage.
* Allowing template parsing in user-controlled HTML is not advised at all.
* Only use this mode if there is really no alternative.
*/
SAFE_FOR_TEMPLATES?: boolean | undefined;
/**
* Change how e.g. comments containing risky HTML characters are treated.
* Be very careful, this setting should only be set to `false` if you really only handle
* HTML and nothing else, no SVG, MathML or the like.
* Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
*/
SAFE_FOR_XML?: boolean | undefined;
/**
* Use DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here).
*/
SANITIZE_DOM?: boolean | undefined;
/**
* Enforce strict DOM Clobbering protection via namespace isolation (default is false).
* When enabled, isolates the namespace of named properties (i.e., `id` and `name` attributes)
* from JS variables by prefixing them with the string `user-content-`
*/
SANITIZE_NAMED_PROPS?: boolean | undefined;
/**
* Supplied policy must define `createHTML` and `createScriptURL`.
*/
TRUSTED_TYPES_POLICY?: TrustedTypePolicy | undefined;
/**
* Controls categories of allowed elements.
*
* Note that the `USE_PROFILES` setting will override the `ALLOWED_TAGS` setting
* so don't use them together.
*/
USE_PROFILES?: false | UseProfilesConfig | undefined;
/**
* Return entire document including <html> tags (default is false).
*/
WHOLE_DOCUMENT?: boolean | undefined;
}
/**
* Defines categories of allowed elements.
*/
interface UseProfilesConfig {
/**
* Allow all safe MathML elements.
*/
mathMl?: boolean | undefined;
/**
* Allow all safe SVG elements.
*/
svg?: boolean | undefined;
/**
* Allow all save SVG Filters.
*/
svgFilters?: boolean | undefined;
/**
* Allow all safe HTML elements.
*/
html?: boolean | undefined;
}
declare const _default: DOMPurify;
interface DOMPurify {
/**
* Creates a DOMPurify instance using the given window-like object.
*/
(root: WindowLike): DOMPurify;
/**
* Version label, exposed for easier checks
* if DOMPurify is up to date or not
*/
version: string;
/**
* Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed.
*/
removed: Array<RemovedElement | RemovedAttribute>;
/**
* Expose whether this browser supports running the full DOMPurify.
*/
isSupported: boolean;
/**
* Set the configuration once.
*
* @param cfg configuration object
*/
setConfig(cfg?: Config): void;
/**
* Removes the configuration.
*/
clearConfig(): void;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized TrustedHTML.
*/
sanitize(dirty: string | Node, cfg: Config & {
RETURN_TRUSTED_TYPE: true;
}): TrustedHTML;
/**
* Provides core sanitation functionality.
*
* @param dirty DOM node
* @param cfg object
* @return Sanitized DOM node.
*/
sanitize(dirty: Node, cfg: Config & {
IN_PLACE: true;
}): Node;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized DOM node.
*/
sanitize(dirty: string | Node, cfg: Config & {
RETURN_DOM: true;
}): Node;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized document fragment.
*/
sanitize(dirty: string | Node, cfg: Config & {
RETURN_DOM_FRAGMENT: true;
}): DocumentFragment;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized string.
*/
sanitize(dirty: string | Node, cfg?: Config): string;
/**
* Checks if an attribute value is valid.
* Uses last set config, if any. Otherwise, uses config defaults.
*
* @param tag Tag name of containing element.
* @param attr Attribute name.
* @param value Attribute value.
* @return Returns true if `value` is valid. Otherwise, returns false.
*/
isValidAttribute(tag: string, attr: string, value: string): boolean;
/**
* Adds a DOMPurify hook.
*
* @param entryPoint entry point for the hook to add
* @param hookFunction function to execute
*/
addHook(entryPoint: 'beforeSanitizeElements' | 'afterSanitizeElements' | 'beforeSanitizeAttributes' | 'afterSanitizeAttributes' | 'beforeSanitizeShadowDOM' | 'uponSanitizeShadowNode' | 'afterSanitizeShadowDOM', hookFunction: Hook): void;
/**
* Adds a DOMPurify hook.
*
* @param entryPoint entry point for the hook to add
* @param hookFunction function to execute
*/
addHook(entryPoint: 'uponSanitizeElement', hookFunction: UponSanitizeElementHook): void;
/**
* Adds a DOMPurify hook.
*
* @param entryPoint entry point for the hook to add
* @param hookFunction function to execute
*/
addHook(entryPoint: 'uponSanitizeAttribute', hookFunction: UponSanitizeAttributeHook): void;
/**
* Remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param entryPoint entry point for the hook to remove
* @return removed(popped) hook
*/
removeHook(entryPoint: BasicHookName): Hook | undefined;
/**
* Remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param entryPoint entry point for the hook to remove
* @return removed(popped) hook
*/
removeHook(entryPoint: 'uponSanitizeElement'): UponSanitizeElementHook | undefined;
/**
* Remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param entryPoint entry point for the hook to remove
* @return removed(popped) hook
*/
removeHook(entryPoint: 'uponSanitizeAttribute'): UponSanitizeAttributeHook | undefined;
/**
* Removes all DOMPurify hooks at a given entryPoint
*
* @param entryPoint entry point for the hooks to remove
*/
removeHooks(entryPoint: HookName): void;
/**
* Removes all DOMPurify hooks.
*/
removeAllHooks(): void;
}
/**
* An element removed by DOMPurify.
*/
interface RemovedElement {
/**
* The element that was removed.
*/
element: Node;
}
/**
* An element removed by DOMPurify.
*/
interface RemovedAttribute {
/**
* The attribute that was removed.
*/
attribute: Attr | null;
/**
* The element that the attribute was removed.
*/
from: Node;
}
type BasicHookName = 'beforeSanitizeElements' | 'afterSanitizeElements' | 'beforeSanitizeAttributes' | 'afterSanitizeAttributes' | 'beforeSanitizeShadowDOM' | 'uponSanitizeShadowNode' | 'afterSanitizeShadowDOM';
type UponSanitizeElementHookName = 'uponSanitizeElement';
type UponSanitizeAttributeHookName = 'uponSanitizeAttribute';
type HookName = BasicHookName | UponSanitizeElementHookName | UponSanitizeAttributeHookName;
type Hook = (this: DOMPurify, currentNode: Node, hookEvent: null, config: Config) => void;
type UponSanitizeElementHook = (this: DOMPurify, currentNode: Node, hookEvent: UponSanitizeElementHookEvent, config: Config) => void;
type UponSanitizeAttributeHook = (this: DOMPurify, currentNode: Node, hookEvent: UponSanitizeAttributeHookEvent, config: Config) => void;
interface UponSanitizeElementHookEvent {
tagName: string;
allowedTags: Record<string, boolean>;
}
interface UponSanitizeAttributeHookEvent {
attrName: string;
attrValue: string;
keepAttr: boolean;
allowedAttributes: Record<string, boolean>;
forceKeepAttr: boolean | undefined;
}
/**
* A `Window`-like object containing the properties and types that DOMPurify requires.
*/
type WindowLike = Pick<typeof globalThis, 'DocumentFragment' | 'HTMLTemplateElement' | 'Node' | 'Element' | 'NodeFilter' | 'NamedNodeMap' | 'HTMLFormElement' | 'DOMParser'> & {
document?: Document;
MozNamedAttrMap?: typeof window.NamedNodeMap;
trustedTypes?: typeof window.trustedTypes;
};
export { type Hook, type HookName, type RemovedAttribute, type RemovedElement, type UponSanitizeAttributeHook, type UponSanitizeAttributeHookEvent, type UponSanitizeElementHook, type UponSanitizeElementHookEvent, type WindowLike };
export = _default;
+399
View File
@@ -0,0 +1,399 @@
/*! @license DOMPurify 3.1.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.7/LICENSE */
/**
* Configuration to control DOMPurify behavior.
*/
interface Config {
/**
* Extend the existing array of allowed attributes.
*/
ADD_ATTR?: string[] | undefined;
/**
* Extend the existing array of elements that can use Data URIs.
*/
ADD_DATA_URI_TAGS?: string[] | undefined;
/**
* Extend the existing array of allowed tags.
*/
ADD_TAGS?: string[] | undefined;
/**
* Extend the existing array of elements that are safe for URI-like values (be careful, XSS risk).
*/
ADD_URI_SAFE_ATTR?: string[] | undefined;
/**
* Allow ARIA attributes, leave other safe HTML as is (default is true).
*/
ALLOW_ARIA_ATTR?: boolean | undefined;
/**
* Allow HTML5 data attributes, leave other safe HTML as is (default is true).
*/
ALLOW_DATA_ATTR?: boolean | undefined;
/**
* Allow external protocol handlers in URL attributes (default is false, be careful, XSS risk).
* By default only `http`, `https`, `ftp`, `ftps`, `tel`, `mailto`, `callto`, `sms`, `cid` and `xmpp` are allowed.
*/
ALLOW_UNKNOWN_PROTOCOLS?: boolean | undefined;
/**
* Decide if self-closing tags in attributes are allowed.
* Usually removed due to a mXSS issue in jQuery 3.0.
*/
ALLOW_SELF_CLOSE_IN_ATTR?: boolean | undefined;
/**
* Allow only specific attributes.
*/
ALLOWED_ATTR?: string[] | undefined;
/**
* Allow only specific elements.
*/
ALLOWED_TAGS?: string[] | undefined;
/**
* Allow only specific namespaces. Defaults to:
* - `http://www.w3.org/1999/xhtml`
* - `http://www.w3.org/2000/svg`
* - `http://www.w3.org/1998/Math/MathML`
*/
ALLOWED_NAMESPACES?: string[] | undefined;
/**
* Allow specific protocols handlers in URL attributes via regex (be careful, XSS risk).
* Default RegExp:
* ```
* /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
* ```
*/
ALLOWED_URI_REGEXP?: RegExp | undefined;
/**
* Define how custom elements are handled.
*/
CUSTOM_ELEMENT_HANDLING?: {
/**
* Regular expression or function to match to allowed elements.
* Default is null (disallow any custom elements).
*/
tagNameCheck?: RegExp | ((tagName: string) => boolean) | null | undefined;
/**
* Regular expression or function to match to allowed attributes.
* Default is null (disallow any attributes not on the allow list).
*/
attributeNameCheck?: RegExp | ((attributeName: string) => boolean) | null | undefined;
/**
* Allow custom elements derived from built-ins if they pass `tagNameCheck`. Default is false.
*/
allowCustomizedBuiltInElements?: boolean | undefined;
};
/**
* Add attributes to block-list.
*/
FORBID_ATTR?: string[] | undefined;
/**
* Add child elements to be removed when their parent is removed.
*/
FORBID_CONTENTS?: string[] | undefined;
/**
* Add elements to block-list.
*/
FORBID_TAGS?: string[] | undefined;
/**
* Glue elements like style, script or others to `document.body` and prevent unintuitive browser behavior in several edge-cases (default is false).
*/
FORCE_BODY?: boolean | undefined;
/**
* Map of non-standard HTML element names to support. Map to true to enable support. For example:
*
* ```
* HTML_INTEGRATION_POINTS: { foreignobject: true }
* ```
*/
HTML_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
/**
* Sanitize a node "in place", which is much faster depending on how you use DOMPurify.
*/
IN_PLACE?: boolean | undefined;
/**
* Keep an element's content when the element is removed (default is true).
*/
KEEP_CONTENT?: boolean | undefined;
/**
* Map of MathML element names to support. Map to true to enable support. For example:
*
* ```
* MATHML_TEXT_INTEGRATION_POINTS: { mtext: true }
* ```
*/
MATHML_TEXT_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
/**
* Change the default namespace from HTML to something different.
*/
NAMESPACE?: string | undefined;
/**
* Change the parser type so sanitized data is treated as XML and not as HTML, which is the default.
*/
PARSER_MEDIA_TYPE?: DOMParserSupportedType | undefined;
/**
* Return a DOM `DocumentFragment` instead of an HTML string (default is false).
*/
RETURN_DOM_FRAGMENT?: boolean | undefined;
/**
* Return a DOM `HTMLBodyElement` instead of an HTML string (default is false).
*/
RETURN_DOM?: boolean | undefined;
/**
* Return a TrustedHTML object instead of a string if possible.
*/
RETURN_TRUSTED_TYPE?: boolean | undefined;
/**
* Strip `{{ ... }}`, `${ ... }` and `<% ... %>` to make output safe for template systems.
* Be careful please, this mode is not recommended for production usage.
* Allowing template parsing in user-controlled HTML is not advised at all.
* Only use this mode if there is really no alternative.
*/
SAFE_FOR_TEMPLATES?: boolean | undefined;
/**
* Change how e.g. comments containing risky HTML characters are treated.
* Be very careful, this setting should only be set to `false` if you really only handle
* HTML and nothing else, no SVG, MathML or the like.
* Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
*/
SAFE_FOR_XML?: boolean | undefined;
/**
* Use DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here).
*/
SANITIZE_DOM?: boolean | undefined;
/**
* Enforce strict DOM Clobbering protection via namespace isolation (default is false).
* When enabled, isolates the namespace of named properties (i.e., `id` and `name` attributes)
* from JS variables by prefixing them with the string `user-content-`
*/
SANITIZE_NAMED_PROPS?: boolean | undefined;
/**
* Supplied policy must define `createHTML` and `createScriptURL`.
*/
TRUSTED_TYPES_POLICY?: TrustedTypePolicy | undefined;
/**
* Controls categories of allowed elements.
*
* Note that the `USE_PROFILES` setting will override the `ALLOWED_TAGS` setting
* so don't use them together.
*/
USE_PROFILES?: false | UseProfilesConfig | undefined;
/**
* Return entire document including <html> tags (default is false).
*/
WHOLE_DOCUMENT?: boolean | undefined;
}
/**
* Defines categories of allowed elements.
*/
interface UseProfilesConfig {
/**
* Allow all safe MathML elements.
*/
mathMl?: boolean | undefined;
/**
* Allow all safe SVG elements.
*/
svg?: boolean | undefined;
/**
* Allow all save SVG Filters.
*/
svgFilters?: boolean | undefined;
/**
* Allow all safe HTML elements.
*/
html?: boolean | undefined;
}
declare const _default: DOMPurify;
interface DOMPurify {
/**
* Creates a DOMPurify instance using the given window-like object.
*/
(root: WindowLike): DOMPurify;
/**
* Version label, exposed for easier checks
* if DOMPurify is up to date or not
*/
version: string;
/**
* Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed.
*/
removed: Array<RemovedElement | RemovedAttribute>;
/**
* Expose whether this browser supports running the full DOMPurify.
*/
isSupported: boolean;
/**
* Set the configuration once.
*
* @param cfg configuration object
*/
setConfig(cfg?: Config): void;
/**
* Removes the configuration.
*/
clearConfig(): void;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized TrustedHTML.
*/
sanitize(dirty: string | Node, cfg: Config & {
RETURN_TRUSTED_TYPE: true;
}): TrustedHTML;
/**
* Provides core sanitation functionality.
*
* @param dirty DOM node
* @param cfg object
* @return Sanitized DOM node.
*/
sanitize(dirty: Node, cfg: Config & {
IN_PLACE: true;
}): Node;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized DOM node.
*/
sanitize(dirty: string | Node, cfg: Config & {
RETURN_DOM: true;
}): Node;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized document fragment.
*/
sanitize(dirty: string | Node, cfg: Config & {
RETURN_DOM_FRAGMENT: true;
}): DocumentFragment;
/**
* Provides core sanitation functionality.
*
* @param dirty string or DOM node
* @param cfg object
* @return Sanitized string.
*/
sanitize(dirty: string | Node, cfg?: Config): string;
/**
* Checks if an attribute value is valid.
* Uses last set config, if any. Otherwise, uses config defaults.
*
* @param tag Tag name of containing element.
* @param attr Attribute name.
* @param value Attribute value.
* @return Returns true if `value` is valid. Otherwise, returns false.
*/
isValidAttribute(tag: string, attr: string, value: string): boolean;
/**
* Adds a DOMPurify hook.
*
* @param entryPoint entry point for the hook to add
* @param hookFunction function to execute
*/
addHook(entryPoint: 'beforeSanitizeElements' | 'afterSanitizeElements' | 'beforeSanitizeAttributes' | 'afterSanitizeAttributes' | 'beforeSanitizeShadowDOM' | 'uponSanitizeShadowNode' | 'afterSanitizeShadowDOM', hookFunction: Hook): void;
/**
* Adds a DOMPurify hook.
*
* @param entryPoint entry point for the hook to add
* @param hookFunction function to execute
*/
addHook(entryPoint: 'uponSanitizeElement', hookFunction: UponSanitizeElementHook): void;
/**
* Adds a DOMPurify hook.
*
* @param entryPoint entry point for the hook to add
* @param hookFunction function to execute
*/
addHook(entryPoint: 'uponSanitizeAttribute', hookFunction: UponSanitizeAttributeHook): void;
/**
* Remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param entryPoint entry point for the hook to remove
* @return removed(popped) hook
*/
removeHook(entryPoint: BasicHookName): Hook | undefined;
/**
* Remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param entryPoint entry point for the hook to remove
* @return removed(popped) hook
*/
removeHook(entryPoint: 'uponSanitizeElement'): UponSanitizeElementHook | undefined;
/**
* Remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param entryPoint entry point for the hook to remove
* @return removed(popped) hook
*/
removeHook(entryPoint: 'uponSanitizeAttribute'): UponSanitizeAttributeHook | undefined;
/**
* Removes all DOMPurify hooks at a given entryPoint
*
* @param entryPoint entry point for the hooks to remove
*/
removeHooks(entryPoint: HookName): void;
/**
* Removes all DOMPurify hooks.
*/
removeAllHooks(): void;
}
/**
* An element removed by DOMPurify.
*/
interface RemovedElement {
/**
* The element that was removed.
*/
element: Node;
}
/**
* An element removed by DOMPurify.
*/
interface RemovedAttribute {
/**
* The attribute that was removed.
*/
attribute: Attr | null;
/**
* The element that the attribute was removed.
*/
from: Node;
}
type BasicHookName = 'beforeSanitizeElements' | 'afterSanitizeElements' | 'beforeSanitizeAttributes' | 'afterSanitizeAttributes' | 'beforeSanitizeShadowDOM' | 'uponSanitizeShadowNode' | 'afterSanitizeShadowDOM';
type UponSanitizeElementHookName = 'uponSanitizeElement';
type UponSanitizeAttributeHookName = 'uponSanitizeAttribute';
type HookName = BasicHookName | UponSanitizeElementHookName | UponSanitizeAttributeHookName;
type Hook = (this: DOMPurify, currentNode: Node, hookEvent: null, config: Config) => void;
type UponSanitizeElementHook = (this: DOMPurify, currentNode: Node, hookEvent: UponSanitizeElementHookEvent, config: Config) => void;
type UponSanitizeAttributeHook = (this: DOMPurify, currentNode: Node, hookEvent: UponSanitizeAttributeHookEvent, config: Config) => void;
interface UponSanitizeElementHookEvent {
tagName: string;
allowedTags: Record<string, boolean>;
}
interface UponSanitizeAttributeHookEvent {
attrName: string;
attrValue: string;
keepAttr: boolean;
allowedAttributes: Record<string, boolean>;
forceKeepAttr: boolean | undefined;
}
/**
* A `Window`-like object containing the properties and types that DOMPurify requires.
*/
type WindowLike = Pick<typeof globalThis, 'DocumentFragment' | 'HTMLTemplateElement' | 'Node' | 'Element' | 'NodeFilter' | 'NamedNodeMap' | 'HTMLFormElement' | 'DOMParser'> & {
document?: Document;
MozNamedAttrMap?: typeof window.NamedNodeMap;
trustedTypes?: typeof window.trustedTypes;
};
export { type Hook, type HookName, type RemovedAttribute, type RemovedElement, type UponSanitizeAttributeHook, type UponSanitizeAttributeHookEvent, type UponSanitizeElementHook, type UponSanitizeElementHookEvent, type WindowLike, _default as default };
+18 -2
View File
@@ -7,11 +7,15 @@
"commit-amend-build": "scripts/commit-amend-build.sh",
"prebuild": "rimraf dist/**",
"dev": "cross-env NODE_ENV=development BABEL_ENV=rollup rollup -w -c -o dist/purify.js",
"build": "rollup -c",
"build": "run-s build:types build:rollup build:fix-cjs-types build:cleanup",
"build:types": "tsc --outDir dist/types --declaration --emitDeclarationOnly",
"build:rollup": "rollup -c",
"build:fix-cjs-types": "node ./scripts/fix-cjs-types.js",
"build:umd": "rollup -c -f umd -o dist/purify.js",
"build:umd:min": "rollup -c -f umd -o dist/purify.min.js -p terser",
"build:es": "rollup -c -f es -o dist/purify.es.mjs",
"build:cjs": "rollup -c -f cjs -o dist/purify.cjs.js",
"build:cleanup": "rimraf dist/types",
"test:jsdom": "cross-env NODE_ENV=test BABEL_ENV=rollup node test/jsdom-node-runner --dot",
"test:karma": "cross-env NODE_ENV=test BABEL_ENV=rollup karma start test/karma.conf.js --log-level warn ",
"test:ci": "cross-env NODE_ENV=test BABEL_ENV=rollup npm run test:jsdom && npm run test:karma -- --log-level error --reporters dots --single-run --shouldTestOnBrowserStack=\"${TEST_BROWSERSTACK}\" --shouldProbeOnly=\"${TEST_PROBE_ONLY}\"",
@@ -19,9 +23,21 @@
},
"main": "./dist/purify.cjs.js",
"module": "./dist/purify.es.mjs",
"es2020": "./dist/purify.es.mjs",
"browser": "./dist/purify.js",
"production": "./dist/purify.min.js",
"types": "./dist/purify.cjs.d.ts",
"exports": {
".": {
"require": {
"types": "./dist/purify.cjs.d.ts",
"default": "./dist/purify.cjs.js"
},
"import": {
"types": "./dist/purify.es.d.mts",
"default": "./dist/purify.es.mjs"
}
}
},
"files": [
"dist"
],
+71 -46
View File
@@ -5,6 +5,7 @@ const nodeResolve = require('@rollup/plugin-node-resolve').nodeResolve;
const replace = require('@rollup/plugin-replace');
const terser = require('@rollup/plugin-terser');
const typescript = require('rollup-plugin-typescript2');
const { dts } = require('rollup-plugin-dts');
const pkg = require('./package.json');
const env = process.env.NODE_ENV;
@@ -21,52 +22,76 @@ const commonOutputConfig = {
exports: 'default',
};
const config = {
input: 'src/purify.ts',
external: [],
output: [
{
...commonOutputConfig,
file: pkg.browser,
format: 'umd',
},
{
...commonOutputConfig,
file: pkg.production,
format: 'umd',
plugins: event === 'build' ? [terser()] : [],
},
{
...commonOutputConfig,
file: pkg.module,
format: 'es',
},
{
...commonOutputConfig,
file: pkg.main,
format: 'cjs',
},
],
plugins: [
typescript({
clean: true,
}),
babel({
// It is recommended to configure this option explicitly (even if with its default value) so an informed decision is taken on how those babel helpers are inserted into the code.
// Ref: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers
babelHelpers: 'bundled',
exclude: ['**/node_modules/**'],
extensions: [...DEFAULT_EXTENSIONS, '.ts'],
}),
nodeResolve(),
replace({
preventAssignment: true,
values: {
'process.env.NODE_ENV': JSON.stringify(env),
VERSION: `'${version}'`,
const config = [
{
input: 'src/purify.ts',
external: [],
output: [
{
...commonOutputConfig,
file: pkg.browser,
format: 'umd',
},
}),
],
};
{
...commonOutputConfig,
file: pkg.production,
format: 'umd',
plugins: event === 'build' ? [terser()] : [],
},
{
...commonOutputConfig,
file: pkg.module,
format: 'es',
},
{
...commonOutputConfig,
file: pkg.main,
format: 'cjs',
},
],
plugins: [
typescript({
clean: true,
}),
babel({
// It is recommended to configure this option explicitly (even if with its default value) so an informed decision is taken on how those babel helpers are inserted into the code.
// Ref: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers
babelHelpers: 'bundled',
exclude: ['**/node_modules/**'],
extensions: [...DEFAULT_EXTENSIONS, '.ts'],
}),
nodeResolve(),
replace({
preventAssignment: true,
values: {
'process.env.NODE_ENV': JSON.stringify(env),
VERSION: `'${version}'`,
},
}),
],
},
{
input: './dist/types/purify.d.ts',
output: [
{
file: pkg.module.replace(/\.mjs$/, '.d.mts'),
format: 'es',
banner: commonOutputConfig.banner,
},
],
plugins: [dts()],
},
{
input: './dist/types/purify.d.ts',
output: [
{
file: pkg.main.replace(/\.js$/, '.d.ts'),
format: 'cjs',
banner: commonOutputConfig.banner,
},
],
plugins: [dts()],
},
];
module.exports = config;
+1 -1
View File
@@ -1,3 +1,3 @@
echo "# Amending minified assets to HEAD"
git add ./dist/purify.js ./dist/purify.js.map ./dist/purify.min.js ./dist/purify.min.js.map ./dist/purify.cjs.js ./dist/purify.cjs.js.map ./dist/purify.es.mjs ./dist/purify.es.mjs.map
git add ./dist/purify.js ./dist/purify.js.map ./dist/purify.min.js ./dist/purify.min.js.map ./dist/purify.cjs.js ./dist/purify.cjs.js.map ./dist/purify.cjs.d.ts ./dist/purify.es.mjs ./dist/purify.es.mjs.map ./dist/purify.es.d.mts
+31
View File
@@ -0,0 +1,31 @@
const fs = require('node:fs/promises');
const path = require('node:path');
(async () => {
// Note that this script is intended to run on the type declaration file that is
// output by Rollup, and not the type declaration file generated from TypeScript.
let fileName = path.resolve(__dirname, '../dist/purify.cjs.d.ts');
let types = await fs.readFile(fileName, { encoding: 'utf-8' });
// DOMPurify is exported as a default export, but rollup changes
// it to be assigned to `module.exports`. We need to change the
// type declarations to match what rollup changed it to. Remove
// the "default" export from the `export { ... }` statement.
let fixed = types.replace(', _default as default', '');
// Verify that we actually removed something in case the
// type declarations are different to what we expected.
if (fixed === types) {
throw new Error('Failed to fix CommonJS type declarations.');
}
// Append `export = _default;` to match the
// `module.exports = DOMPurify` statement
// that Rollup creates.
fixed += '\nexport = _default;\n';
await fs.writeFile(fileName, fixed);
})().catch((ex) => {
console.error(ex);
process.exitCode = 1;
});
+1 -1
View File
@@ -1,5 +1,5 @@
const includePaths = require('rollup-plugin-includepaths');
const rollupConfig = require('../rollup.config.js');
const rollupConfig = require('../rollup.config.js')[0];
const customLaunchers =
require('./karma.custom-launchers.config.js').customLaunchers;
const browsers = require('./karma.custom-launchers.config.js').browsers;