New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@aegisjsproject/sanitizer

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aegisjsproject/sanitizer - npm Package Compare versions

Comparing version 0.0.10 to 0.1.0

.stylelintrc.json

10

CHANGELOG.md

@@ -0,1 +1,2 @@

<!-- markdownlint-disable -->
# Changelog

@@ -9,2 +10,11 @@ All notable changes to this project will be documented in this file.

## [v0.1.0] - 2024-04-08
### Added
- Add `setHTML` method on `DocumentFragment` (and therefore `ShadowRoot`)
- Add support for setting config directly instead of via `sanitizer` property
### Changed
- `html`, `svg`, and `mathml` policies now default to `comments = true` (`base` has `comments = false`)
## [v0.0.10] - 2024-04-03

@@ -11,0 +21,0 @@

32

config-utils.js

@@ -66,9 +66,9 @@ import { HTML as HTMLNS } from '@aegisjsproject/sanitizer/namespaces.js';

function normalizeCommentsConfig({ comments, allowComments }) {
if (typeof comments === 'boolean') {
return comments;
} else if (typeof allowComments === 'boolean') {
if (typeof allowComments === 'boolean') {
console.warn('Use of `allowComments` is deprecated. Please use `comments` instead.');
return allowComments;
} else if (typeof comments === 'boolean') {
return comments;
} else {
return false;
return true;
}

@@ -87,12 +87,16 @@ }

comments = false,
allowComments,
dataAttributes = true,
...rest
} = config;
return {
const cfg = {
elements: normalizeElementsConfig({ elements, allowElements }, elementNS),
attributes: normalizeAttrsConfig({ attributes, allowAttributes }, attributeNS),
comments,
comments: comments || allowComments,
dataAttributes,
...rest,
};
console.log(cfg);
return cfg;
}

@@ -124,18 +128,2 @@

throw new TypeError('Sanitizer config must be an object.');
} else if (config.getConfiguration instanceof Function) {
console.warn('`Sanitzer` objects are deprecated and will be removed.');
const {
allowElements: elements,
allowAttributes: attributes,
allowComments: comments,
...rest
} = config.getConfiguration();
return Object.freeze({
elements: convertElementConfig({ elements }, elementNS),
attributes: convertAttrConfig({ attributes }, attributeNS),
comments,
...rest
});
} else {

@@ -142,0 +130,0 @@ return Object.freeze({

import { elements as HTMLElements, attributes as HTMLAttributes } from '@aegisjsproject/sanitizer/config/html.js';
import { elements as SVGElements,attributes as SVGAttributes } from '@aegisjsproject/sanitizer/config/svg.js';
import { elements as SVGElements, attributes as SVGAttributes } from '@aegisjsproject/sanitizer/config/svg.js';

@@ -4,0 +4,0 @@ export const elements = Object.freeze([...HTMLElements, ...SVGElements]);

@@ -8,3 +8,3 @@ /**

import { attributes as globalAttrs } from '@aegisjsproject/sanitizer/config/global.js';
export const comments = false;
export const comments = true;

@@ -11,0 +11,0 @@ export const dataAttributes = true;

/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
*/
const e="http://www.w3.org/1999/xhtml";function a(e,a){if("string"==typeof e)return Object.freeze({name:e,namespace:a});if("object"==typeof e&&"string"==typeof e.name){const{name:r,namespace:t=a,elements:i,...o}=e;return Object.freeze({name:r,namespace:"string"==typeof t?t:a,elements:i,...o})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const r=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>a(e)))),t=!1,i=!0,o=Object.freeze(["html","head","link","meta","body","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","search","blockquote","cite","div","dd","dt","dl","figcaption","figure","hr","li","ol","ul","menu","p","pre","a","abbr","b","bdi","bdo","br","code","data","dfn","em","i","kbd","mark","q","rp","ruby","rt","s","del","ins","samp","small","span","strong","sub","sup","time","u","var","wbr","area","audio","img","map","track","video","picture","source","canvas","caption","col","colgroup","table","tbody","tr","td","tfoot","th","thead","button","datalist","option","fieldset","label","form","input","legend","meter","optgroup","select","output","progress","textarea","details","summary","dialog","slot","template","dir","strike","selectmenu","center"].map((a=>function(a,r=e){if("string"==typeof a)return Object.freeze({name:a,namespace:r});if("object"==typeof a&&"string"==typeof a.name){const{name:e,namespace:t=r,attributes:i}=a;return Object.freeze({name:e,namespace:"string"==typeof t&&0!==t.length?t:r,attributes:i})}throw new TypeError("Invalid config entry for `elements`.")}(a,e)))),n=Object.freeze(["abbr","accept","accept-charset","align","alink","allow","allowfullscreen","alt","anchor","archive","as","async","autocomplete","autocorrect","autopictureinpicture","autoplay","axis","background","behavior","border","bordercolor","capture","cellpadding","cellspacing","challenge","char","charoff","charset","checked","cite","classid","clear","code","codetype","color","cols","colspan","compact","content","controls","controlslist","conversiondestination","coords","crossorigin","csp","data","datetime","declare","decoding","default","defer","direction","dirname","disabled","disablepictureinpicture","disableremoteplayback","disallowdocumentaccess","download","elementtiming","enctype","end","for","form","formenctype","formmethod","formnovalidate","formtarget","frameborder","headers","height","high","href","hreflang","hreftranslate","hspace","imagesizes","imagesrcset","importance","impressiondata","impressionexpiry","incremental","integrity","invisible","invoketarget","invokeaction","is","ismap","keytype","kind","label","language","latencyhint","leftmargin","link","list","loading","longdesc","loop","low","lowsrc","manifest","marginheight","marginwidth","max","maxlength","mayscript","media","method","min","minlength","multiple","muted","name","nohref","nomodule","noresize","noshade","novalidate","nowrap","object","open","optimum","pattern","ping","placeholder","playsinline","policy","popovertarget","popovertargetaction","poster","preload","pseudo","readonly","referrerpolicy","rel","reportingorigin","required","resources","rev","reversed","role","rows","rowspan","rules","sandbox","scheme","scope","scopes","scrollamount","scrolldelay","scrolling","select","selected","shadowrootmode","shadowrootdelegatesfocus","shape","size","sizes","span","src","srcdoc","srclang","srcset","standby","start","step","summary","target","text","topmargin","truespeed","trusttoken","type","usemap","valign","value","valuetype","version","vlink","vspace","webkitdirectory","width","wrap"].map((e=>a(e))).concat(r)),s=Object.freeze({comments:t,elements:o,attributes:n,dataAttributes:i});
const e="http://www.w3.org/1999/xhtml";function a(e,a){if("string"==typeof e)return Object.freeze({name:e,namespace:a});if("object"==typeof e&&"string"==typeof e.name){const{name:r,namespace:t=a,elements:i,...o}=e;return Object.freeze({name:r,namespace:"string"==typeof t?t:a,elements:i,...o})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const r=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>a(e)))),t=!0,i=!0,o=Object.freeze(["html","head","link","meta","body","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","search","blockquote","cite","div","dd","dt","dl","figcaption","figure","hr","li","ol","ul","menu","p","pre","a","abbr","b","bdi","bdo","br","code","data","dfn","em","i","kbd","mark","q","rp","ruby","rt","s","del","ins","samp","small","span","strong","sub","sup","time","u","var","wbr","area","audio","img","map","track","video","picture","source","canvas","caption","col","colgroup","table","tbody","tr","td","tfoot","th","thead","button","datalist","option","fieldset","label","form","input","legend","meter","optgroup","select","output","progress","textarea","details","summary","dialog","slot","template","dir","strike","selectmenu","center"].map((a=>function(a,r=e){if("string"==typeof a)return Object.freeze({name:a,namespace:r});if("object"==typeof a&&"string"==typeof a.name){const{name:e,namespace:t=r,attributes:i}=a;return Object.freeze({name:e,namespace:"string"==typeof t&&0!==t.length?t:r,attributes:i})}throw new TypeError("Invalid config entry for `elements`.")}(a,e)))),n=Object.freeze(["abbr","accept","accept-charset","align","alink","allow","allowfullscreen","alt","anchor","archive","as","async","autocomplete","autocorrect","autopictureinpicture","autoplay","axis","background","behavior","border","bordercolor","capture","cellpadding","cellspacing","challenge","char","charoff","charset","checked","cite","classid","clear","code","codetype","color","cols","colspan","compact","content","controls","controlslist","conversiondestination","coords","crossorigin","csp","data","datetime","declare","decoding","default","defer","direction","dirname","disabled","disablepictureinpicture","disableremoteplayback","disallowdocumentaccess","download","elementtiming","enctype","end","for","form","formenctype","formmethod","formnovalidate","formtarget","frameborder","headers","height","high","href","hreflang","hreftranslate","hspace","imagesizes","imagesrcset","importance","impressiondata","impressionexpiry","incremental","integrity","invisible","invoketarget","invokeaction","is","ismap","keytype","kind","label","language","latencyhint","leftmargin","link","list","loading","longdesc","loop","low","lowsrc","manifest","marginheight","marginwidth","max","maxlength","mayscript","media","method","min","minlength","multiple","muted","name","nohref","nomodule","noresize","noshade","novalidate","nowrap","object","open","optimum","pattern","ping","placeholder","playsinline","policy","popovertarget","popovertargetaction","poster","preload","pseudo","readonly","referrerpolicy","rel","reportingorigin","required","resources","rev","reversed","role","rows","rowspan","rules","sandbox","scheme","scope","scopes","scrollamount","scrolldelay","scrolling","select","selected","shadowrootmode","shadowrootdelegatesfocus","shape","size","sizes","span","src","srcdoc","srclang","srcset","standby","start","step","summary","target","text","topmargin","truespeed","trusttoken","type","usemap","valign","value","valuetype","version","vlink","vspace","webkitdirectory","width","wrap"].map((e=>a(e))).concat(r)),s=Object.freeze({comments:t,elements:o,attributes:n,dataAttributes:i});
/**

@@ -6,0 +6,0 @@ * @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>

@@ -5,3 +5,3 @@ import { MATHML as MATHNS } from '@aegisjsproject/sanitizer/namespaces.js';

export const comments = false;
export const comments = true;

@@ -8,0 +8,0 @@ export const dataAttributes = true;

/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
*/
function e(e,a){if("string"==typeof e)return Object.freeze({name:e,namespace:a});if("object"==typeof e&&"string"==typeof e.name){const{name:t,namespace:r=a,elements:i,...n}=e;return Object.freeze({name:t,namespace:"string"==typeof r?r:a,elements:i,...n})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const a=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((a=>e(a)))),t=!1,r=!0,i=Object.freeze(["math","maction","annotation","annotation-xml","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","semantics","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"].map((e=>function(e,a="http://www.w3.org/1999/xhtml"){if("string"==typeof e)return Object.freeze({name:e,namespace:a});if("object"==typeof e&&"string"==typeof e.name){const{name:t,namespace:r=a,attributes:i}=e;return Object.freeze({name:t,namespace:"string"==typeof r&&0!==r.length?r:a,attributes:i})}throw new TypeError("Invalid config entry for `elements`.")}(e,"http://www.w3.org/1998/Math/MathML")))),n=Object.freeze(["accent","accentunder","actiontype","align","background","close","color","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","fence","fontfamily","fontsize","fontstyle","fontweight","frame","framespacing","height","href","id","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","superscriptshift","symmetric","voffset","width","xmlns"].map((a=>e(a))).concat(a)),o=Object.freeze({elements:i,attributes:n,comments:t,dataAttributes:r});export{n as attributes,t as comments,r as dataAttributes,i as elements,o as sanitizer};
function e(e,a){if("string"==typeof e)return Object.freeze({name:e,namespace:a});if("object"==typeof e&&"string"==typeof e.name){const{name:t,namespace:r=a,elements:i,...n}=e;return Object.freeze({name:t,namespace:"string"==typeof r?r:a,elements:i,...n})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const a=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((a=>e(a)))),t=!0,r=!0,i=Object.freeze(["math","maction","annotation","annotation-xml","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","semantics","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"].map((e=>function(e,a="http://www.w3.org/1999/xhtml"){if("string"==typeof e)return Object.freeze({name:e,namespace:a});if("object"==typeof e&&"string"==typeof e.name){const{name:t,namespace:r=a,attributes:i}=e;return Object.freeze({name:t,namespace:"string"==typeof r&&0!==r.length?r:a,attributes:i})}throw new TypeError("Invalid config entry for `elements`.")}(e,"http://www.w3.org/1998/Math/MathML")))),n=Object.freeze(["accent","accentunder","actiontype","align","background","close","color","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","fence","fontfamily","fontsize","fontstyle","fontweight","frame","framespacing","height","href","id","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","superscriptshift","symmetric","voffset","width","xmlns"].map((a=>e(a))).concat(a)),o=Object.freeze({elements:i,attributes:n,comments:t,dataAttributes:r});export{n as attributes,t as comments,r as dataAttributes,i as elements,o as sanitizer};
//# sourceMappingURL=mathml.min.js.map

@@ -9,3 +9,3 @@ import { SVG as SVGNS, XLINK, XML as XMLNS } from '@aegisjsproject/sanitizer/namespaces.js';

export const comments = false;
export const comments = true;

@@ -12,0 +12,0 @@ export const dataAttributes = true;

/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
*/
const e="http://www.w3.org/1999/xlink";function t(e,t){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:a,namespace:i=t,elements:r,...n}=e;return Object.freeze({name:a,namespace:"string"==typeof i?i:t,elements:r,...n})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const a=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>t(e)))),i=!1,r=!0,n=Object.freeze(["a","animate","animateMotion","animateTransform","circle","clipPath","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tspan","view","missing-glyph","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","hkern","vkern","glyph","glyphRef","tref","cursor","use"].map((e=>function(e,t="http://www.w3.org/1999/xhtml"){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:a,namespace:i=t,attributes:r}=e;return Object.freeze({name:a,namespace:"string"==typeof i&&0!==i.length?i:t,attributes:r})}throw new TypeError("Invalid config entry for `elements`.")}(e,"http://www.w3.org/2000/svg")))),o=Object.freeze(["accent-height","accumulate","additive","alignment-baseline","alphabetic","amplitude","arabic-form","ascent","attributeName","attributeType","azimuth","baseFrequency","baseline-shift","baseProfile","bbox","begin","bias","by","calcMode","cap-height","class","clip","clipPathUnits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","crossorigin","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominant-baseline","dur","dx","dy","edgeMode","elevation","enable-background","end","exponent","fill","fill-opacity","fill-rule","filter","filterUnits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","format","from","fr","fx","fy","g1","g2","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","glyphRef","gradientTransform","gradientUnits","hanging","height","href","hreflang","horiz-adv-x","horiz-origin-x","id","ideographic","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lang","lengthAdjust","letter-spacing","lighting-color","limitingConeAngle","local","marker-end","marker-mid","marker-start","markerHeight","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","max","media","method","min","mode","name","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overline-position","overline-thickness","panose-1","paint-order","path","pathLength","patternContentUnits","patternTransform","patternUnits","ping","pointer-events","points","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","referrerPolicy","refX","refY","rel","rendering-intent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","scale","seed","shape-rendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","string","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","style","surfaceScale","systemLanguage","tabindex","tableValues","target","targetX","targetY","text-anchor","text-decoration","text-rendering","textLength","to","transform","transform-origin","type","u1","u2","underline-position","underline-thickness","unicode","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","values","vector-effect","version","vert-adv-y","vert-origin-x","vert-origin-y","viewBox","visibility","width","widths","word-spacing","writing-mode","x","x-height","x1","x2","xChannelSelector","y","y1","y2","yChannelSelector","z","zoomAndPan","autoReverse","accelerate","xmlns",{name:"actuate",namespace:e},{name:"arcrole",namespaec:e},{name:"href",namespace:e},{name:"role",namespace:e},{name:"show",namespace:e},{name:"title",namespace:e},{name:"type",namespace:e},{name:"space",namespace:"http://www.w3.org/XML/1998/namespace"}].map((e=>t(e))).concat(a)),s=Object.freeze({elements:n,attributes:o,comments:i,dataAttributes:r});export{o as attributes,i as comments,r as dataAttributes,n as elements,s as sanitizer};
const e="http://www.w3.org/1999/xlink";function t(e,t){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:a,namespace:i=t,elements:r,...n}=e;return Object.freeze({name:a,namespace:"string"==typeof i?i:t,elements:r,...n})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const a=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>t(e)))),i=!0,r=!0,n=Object.freeze(["a","animate","animateMotion","animateTransform","circle","clipPath","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tspan","view","missing-glyph","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","hkern","vkern","glyph","glyphRef","tref","cursor","use"].map((e=>function(e,t="http://www.w3.org/1999/xhtml"){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:a,namespace:i=t,attributes:r}=e;return Object.freeze({name:a,namespace:"string"==typeof i&&0!==i.length?i:t,attributes:r})}throw new TypeError("Invalid config entry for `elements`.")}(e,"http://www.w3.org/2000/svg")))),o=Object.freeze(["accent-height","accumulate","additive","alignment-baseline","alphabetic","amplitude","arabic-form","ascent","attributeName","attributeType","azimuth","baseFrequency","baseline-shift","baseProfile","bbox","begin","bias","by","calcMode","cap-height","class","clip","clipPathUnits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","crossorigin","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominant-baseline","dur","dx","dy","edgeMode","elevation","enable-background","end","exponent","fill","fill-opacity","fill-rule","filter","filterUnits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","format","from","fr","fx","fy","g1","g2","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","glyphRef","gradientTransform","gradientUnits","hanging","height","href","hreflang","horiz-adv-x","horiz-origin-x","id","ideographic","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lang","lengthAdjust","letter-spacing","lighting-color","limitingConeAngle","local","marker-end","marker-mid","marker-start","markerHeight","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","max","media","method","min","mode","name","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overline-position","overline-thickness","panose-1","paint-order","path","pathLength","patternContentUnits","patternTransform","patternUnits","ping","pointer-events","points","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","referrerPolicy","refX","refY","rel","rendering-intent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","scale","seed","shape-rendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","string","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","style","surfaceScale","systemLanguage","tabindex","tableValues","target","targetX","targetY","text-anchor","text-decoration","text-rendering","textLength","to","transform","transform-origin","type","u1","u2","underline-position","underline-thickness","unicode","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","values","vector-effect","version","vert-adv-y","vert-origin-x","vert-origin-y","viewBox","visibility","width","widths","word-spacing","writing-mode","x","x-height","x1","x2","xChannelSelector","y","y1","y2","yChannelSelector","z","zoomAndPan","autoReverse","accelerate","xmlns",{name:"actuate",namespace:e},{name:"arcrole",namespaec:e},{name:"href",namespace:e},{name:"role",namespace:e},{name:"show",namespace:e},{name:"title",namespace:e},{name:"type",namespace:e},{name:"space",namespace:"http://www.w3.org/XML/1998/namespace"}].map((e=>t(e))).concat(a)),s=Object.freeze({elements:n,attributes:o,comments:i,dataAttributes:r});export{o as attributes,i as comments,r as dataAttributes,n as elements,s as sanitizer};
//# sourceMappingURL=svg.min.js.map
{
"name": "@aegisjsproject/sanitizer",
"version": "0.0.10",
"version": "0.1.0",
"description": "A polyfill for the Sanitizer API with various sanitizer configs",

@@ -56,3 +56,2 @@ "keywords": [

"test": "npm run lint:js && npm run build",
"foo": "node ./test.cjs",
"start": "http-server ${npm_package_config_serve_path} -c-1 --port ${npm_package_config_serve_port} --gzip true --brotli true -a ${npm_package_config_serve_domain} -o /test/",

@@ -96,3 +95,3 @@ "preversion": "npm test",

"@rollup/plugin-terser": "^0.4.4",
"eslint": "^8.57.0",
"eslint": "^9.0.0",
"http-server": "^14.1.1",

@@ -99,0 +98,0 @@ "rollup": "^4.13.0"

import { setHTML as html, parseHTML as parse } from '@aegisjsproject/sanitizer/sanitize.js';
import {
sanitizer as sanitizerConfig,
elements as els,
attributes as attrs,
comments as cmnts,
dataAttributes as dataAttrs,
} from '@aegisjsproject/sanitizer/config/html.js';

@@ -61,12 +54,29 @@ if (! (Promise.withResolvers instanceof Function)) {

Element.prototype.setHTML = function setHTML(content, {
sanitizer: {
elements = els,
attributes = attrs,
comments = cmnts,
dataAttributes = dataAttrs,
...rest
} = sanitizerConfig,
elements,
attributes,
comments,
dataAttributes,
sanitizer,
...rest
} = {}) {
html(this, content, { sanitizer: { elements, attributes, comments, dataAttributes, ...rest }});
/**
* @todo Remove legacy support for v1.0.0
*/
if (typeof sanitizer === 'object' && sanitizer !== null) {
console.warn('Use of `sanitizer` in config is deprecated. Please set config directly.');
html(this, content, sanitizer.getConfiguration instanceof Function
? sanitizer.getConfiguration()
: sanitizer);
} else {
html(this, content, { elements, attributes, comments, dataAttributes, ...rest });
}
};
DocumentFragment.prototype.setHTML = function setHTML(...args) {
Element.prototype.setHTML.apply(this, args);
};
HTMLTemplateElement.prototype.setHTML = function setHTML(html, config) {
this.content.setHTML(html, config);
};
}

@@ -76,12 +86,20 @@

Document.parseHTML = function parseHTML(content, {
sanitizer: {
elements = els,
attributes = attrs,
comments = cmnts,
dataAttributes = dataAttrs,
...rest
} = sanitizerConfig,
elements,
attributes,
comments,
dataAttributes,
sanitizer,
...rest
} = {}) {
return parse(content, { sanitizer: { elements, attributes, comments, dataAttributes, ...rest }});
/**
* @todo Remove legacy support for v1.0.0
*/
if (typeof sanitizer === 'object' && sanitizer !== null) {
return Document.parseHTML(content, sanitizer.getConfiguration instanceof Function
? sanitizer.getConfiguration()
: sanitizer);
} else {
return parse(content, { elements, attributes, comments, dataAttributes, ...rest });
}
};
}
!function(){"use strict";
/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
*/const e="http://www.w3.org/1999/xhtml",t=new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));function a(t,a=e){if("string"==typeof t)return Object.freeze({name:t,namespace:a});if("object"==typeof t&&"string"==typeof t.name){const{name:e,namespace:r=a,attributes:n}=t;return Object.freeze({name:e,namespace:"string"==typeof r&&0!==r.length?r:a,attributes:n})}throw new TypeError("Invalid config entry for `elements`.")}function r({elements:t,allowElements:n},o=e){if(Array.isArray(n))return console.warn("Use of `allowElements` is deprecated. Please use `elements` instead."),r({elements:n},o);if(Array.isArray(t))return t.map((e=>a(e,o)));throw new TypeError("`elements` expected to be an array.")}function n(e,t){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:a,namespace:r=t,elements:n,...o}=e;return Object.freeze({name:a,namespace:"string"==typeof r?r:t,elements:n,...o})}throw new TypeError("Invalid entry in `attributes` config.")}function o({attributes:e,allowAttributes:t},a){if(void 0!==t)return console.warn("Use of `allowAttributes` is deprecated. Please use `attributes` instead."),o({attributes:t},a);if(Array.isArray(e))return e.map((e=>n(e,a)));if("object"==typeof e&&null!==e)return console.warn("`attributes` should be an array, not an oobject."),o({attributes:Object.entries(e).map((([e,t])=>({name:e,elements:t})))},a);throw new TypeError("`attributes` expected to be an array.")}function i({comments:e,allowComments:t}){return"boolean"==typeof e?e:"boolean"==typeof t&&(console.warn("Use of `allowComments` is deprecated. Please use `comments` instead."),t)}function s({attributes:e,allowAttributes:t},a){return Object.freeze(Object.groupBy(o({attributes:e,allowAttributes:t},a),(({namespace:e})=>e??"")))}function c({elements:t,allowElements:a},n=e){return Object.freeze(Object.groupBy(r({elements:t,allowElements:a},n),(({namespace:e})=>e)))}const l=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>n(e)))),u=!1,m=!0,d=Object.freeze(["html","head","link","meta","body","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","search","blockquote","cite","div","dd","dt","dl","figcaption","figure","hr","li","ol","ul","menu","p","pre","a","abbr","b","bdi","bdo","br","code","data","dfn","em","i","kbd","mark","q","rp","ruby","rt","s","del","ins","samp","small","span","strong","sub","sup","time","u","var","wbr","area","audio","img","map","track","video","picture","source","canvas","caption","col","colgroup","table","tbody","tr","td","tfoot","th","thead","button","datalist","option","fieldset","label","form","input","legend","meter","optgroup","select","output","progress","textarea","details","summary","dialog","slot","template","dir","strike","selectmenu","center"].map((t=>a(t,e)))),p=Object.freeze(["abbr","accept","accept-charset","align","alink","allow","allowfullscreen","alt","anchor","archive","as","async","autocomplete","autocorrect","autopictureinpicture","autoplay","axis","background","behavior","border","bordercolor","capture","cellpadding","cellspacing","challenge","char","charoff","charset","checked","cite","classid","clear","code","codetype","color","cols","colspan","compact","content","controls","controlslist","conversiondestination","coords","crossorigin","csp","data","datetime","declare","decoding","default","defer","direction","dirname","disabled","disablepictureinpicture","disableremoteplayback","disallowdocumentaccess","download","elementtiming","enctype","end","for","form","formenctype","formmethod","formnovalidate","formtarget","frameborder","headers","height","high","href","hreflang","hreftranslate","hspace","imagesizes","imagesrcset","importance","impressiondata","impressionexpiry","incremental","integrity","invisible","invoketarget","invokeaction","is","ismap","keytype","kind","label","language","latencyhint","leftmargin","link","list","loading","longdesc","loop","low","lowsrc","manifest","marginheight","marginwidth","max","maxlength","mayscript","media","method","min","minlength","multiple","muted","name","nohref","nomodule","noresize","noshade","novalidate","nowrap","object","open","optimum","pattern","ping","placeholder","playsinline","policy","popovertarget","popovertargetaction","poster","preload","pseudo","readonly","referrerpolicy","rel","reportingorigin","required","resources","rev","reversed","role","rows","rowspan","rules","sandbox","scheme","scope","scopes","scrollamount","scrolldelay","scrolling","select","selected","shadowrootmode","shadowrootdelegatesfocus","shape","size","sizes","span","src","srcdoc","srclang","srcset","standby","start","step","summary","target","text","topmargin","truespeed","trusttoken","type","usemap","valign","value","valuetype","version","vlink","vspace","webkitdirectory","width","wrap"].map((e=>n(e))).concat(l)),f=Object.freeze({comments:u,elements:d,attributes:p,dataAttributes:m});
*/const e="http://www.w3.org/1999/xhtml",t=new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));function a(t,a=e){if("string"==typeof t)return Object.freeze({name:t,namespace:a});if("object"==typeof t&&"string"==typeof t.name){const{name:e,namespace:r=a,attributes:n}=t;return Object.freeze({name:e,namespace:"string"==typeof r&&0!==r.length?r:a,attributes:n})}throw new TypeError("Invalid config entry for `elements`.")}function r({elements:t,allowElements:n},o=e){if(Array.isArray(n))return console.warn("Use of `allowElements` is deprecated. Please use `elements` instead."),r({elements:n},o);if(Array.isArray(t))return t.map((e=>a(e,o)));throw new TypeError("`elements` expected to be an array.")}function n(e,t){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:a,namespace:r=t,elements:n,...o}=e;return Object.freeze({name:a,namespace:"string"==typeof r?r:t,elements:n,...o})}throw new TypeError("Invalid entry in `attributes` config.")}function o({attributes:e,allowAttributes:t},a){if(void 0!==t)return console.warn("Use of `allowAttributes` is deprecated. Please use `attributes` instead."),o({attributes:t},a);if(Array.isArray(e))return e.map((e=>n(e,a)));if("object"==typeof e&&null!==e)return console.warn("`attributes` should be an array, not an oobject."),o({attributes:Object.entries(e).map((([e,t])=>({name:e,elements:t})))},a);throw new TypeError("`attributes` expected to be an array.")}function i({comments:e,allowComments:t}){return"boolean"==typeof t?(console.warn("Use of `allowComments` is deprecated. Please use `comments` instead."),t):"boolean"!=typeof e||e}function s({attributes:e,allowAttributes:t},a){return Object.freeze(Object.groupBy(o({attributes:e,allowAttributes:t},a),(({namespace:e})=>e??"")))}function c({elements:t,allowElements:a},n=e){return Object.freeze(Object.groupBy(r({elements:t,allowElements:a},n),(({namespace:e})=>e)))}const l=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>n(e)))),u=Object.freeze(["html","head","link","meta","body","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","search","blockquote","cite","div","dd","dt","dl","figcaption","figure","hr","li","ol","ul","menu","p","pre","a","abbr","b","bdi","bdo","br","code","data","dfn","em","i","kbd","mark","q","rp","ruby","rt","s","del","ins","samp","small","span","strong","sub","sup","time","u","var","wbr","area","audio","img","map","track","video","picture","source","canvas","caption","col","colgroup","table","tbody","tr","td","tfoot","th","thead","button","datalist","option","fieldset","label","form","input","legend","meter","optgroup","select","output","progress","textarea","details","summary","dialog","slot","template","dir","strike","selectmenu","center"].map((t=>a(t,e)))),m=Object.freeze(["abbr","accept","accept-charset","align","alink","allow","allowfullscreen","alt","anchor","archive","as","async","autocomplete","autocorrect","autopictureinpicture","autoplay","axis","background","behavior","border","bordercolor","capture","cellpadding","cellspacing","challenge","char","charoff","charset","checked","cite","classid","clear","code","codetype","color","cols","colspan","compact","content","controls","controlslist","conversiondestination","coords","crossorigin","csp","data","datetime","declare","decoding","default","defer","direction","dirname","disabled","disablepictureinpicture","disableremoteplayback","disallowdocumentaccess","download","elementtiming","enctype","end","for","form","formenctype","formmethod","formnovalidate","formtarget","frameborder","headers","height","high","href","hreflang","hreftranslate","hspace","imagesizes","imagesrcset","importance","impressiondata","impressionexpiry","incremental","integrity","invisible","invoketarget","invokeaction","is","ismap","keytype","kind","label","language","latencyhint","leftmargin","link","list","loading","longdesc","loop","low","lowsrc","manifest","marginheight","marginwidth","max","maxlength","mayscript","media","method","min","minlength","multiple","muted","name","nohref","nomodule","noresize","noshade","novalidate","nowrap","object","open","optimum","pattern","ping","placeholder","playsinline","policy","popovertarget","popovertargetaction","poster","preload","pseudo","readonly","referrerpolicy","rel","reportingorigin","required","resources","rev","reversed","role","rows","rowspan","rules","sandbox","scheme","scope","scopes","scrollamount","scrolldelay","scrolling","select","selected","shadowrootmode","shadowrootdelegatesfocus","shape","size","sizes","span","src","srcdoc","srclang","srcset","standby","start","step","summary","target","text","topmargin","truespeed","trusttoken","type","usemap","valign","value","valuetype","version","vlink","vspace","webkitdirectory","width","wrap"].map((e=>n(e))).concat(l)),d=Object.freeze({comments:!0,elements:u,attributes:m,dataAttributes:!0});
/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
* @see https://wicg.github.io/sanitizer-api/#default-configuration-dictionary
*/const b=new Set(["href","src","action","xlink:href"]),h=new Set(["javascript:","data:","file:","ftp:"]),g=function(e,{createHTML:t,createScript:a,createScriptURL:r}){return"trustedTypes"in globalThis?trustedTypes.createPolicy(e,{createHTML:t,createScript:a,createScriptURL:r}):Object.freeze({[Symbol.for("policy-name")]:e.toString(),createHTML(a,...r){if(t instanceof Function){const e=t(a.toString(),...r).toString();return Object.freeze({toString:()=>e})}throw new TypeError(`Policy "${e}" does not provide a createHTML method.`)},createScript(t,...r){if(a instanceof Function){const e=a(t.toString(),...r).toString();return Object.freeze({toString:()=>e})}throw new TypeError(`Policy "${e}" does not provide a createScript method.`)},createScriptURL(t,...a){if(r instanceof Function){const e=r(t.toString(),...a).toString();return Object.freeze({toString:()=>e})}throw new TypeError(`Policy "${e}" does not provide a createScriptURL method.`)}})}("aegis-sanitizer#html",{createHTML:e=>e});function y(t,a=f,r=!1){if(t instanceof Node){const n=function(t,{elementNS:a=e,attributeNS:r}={}){if("object"!=typeof t||null===t)throw new TypeError("Sanitizer config must be an object.");if(t.getConfiguration instanceof Function){console.warn("`Sanitzer` objects are deprecated and will be removed.");const{allowElements:e,allowAttributes:n,allowComments:o,...i}=t.getConfiguration();return Object.freeze({elements:c({elements:e},a),attributes:s({attributes:n},r),comments:o,...i})}return Object.freeze({elements:c(t,a),attributes:s(t,r),comments:i(t),dataAttributes:void 0===t.dataAttributes||t.dataAttributes})}(a);return E(t,n,r)}throw new TypeError("Not a node.")}const w="trustedTypes"in globalThis?e=>null!==trustedTypes.getAttributeType(e.ownerElement.tagName,e.localName,e.ownerElement.namespaceURI,e.namespaceURI):e=>t.has(e.localName);function v(e,t,a=!1){const r=e.namespaceURI||"";return(!("dataAttributes"in t)||t.dataAttributes)&&e.name.startsWith("data-")||r in t.attributes&&t.attributes[r].some((t=>t.name===e.localName))&&!(a||w(e))&&!(a||function(e){if(b.has(e.name)){if(URL.canParse(e.value)){const{protocol:t}=new URL(e.value);return h.has(t)}return!1}return!1}(e))}function E(e,t,a=!1){switch(e.nodeType){case Node.ELEMENT_NODE:!function(e,t,a){if(function(e,t){return e.namespaceURI in t.elements&&t.elements[e.namespaceURI].some((t=>t.name===e.localName))}(e,t)){if(e.hasAttributes()){const r=e.attributes;for(let e=r.length-1;-1!==e;e--)T(r[e],t,a)}if("TEMPLATE"===e.tagName)N(e.content,t,a);else if(e.hasChildNodes()){const r=e.childNodes;for(let e=r.length-1;-1!==e;e--)E(r[e],t,a)}}else e.remove()}(e,t,a);break;case Node.DOCUMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:N(e,t,a);break;case Node.COMMENT_NODE:!function(e,t){t.comments||e.remove()}(e,t);break;case Node.ATTRIBUTE_NODE:T(e,t,a);break;case Node.TEXT_NODE:case Node.DOCUMENT_TYPE_NODE:break;default:e.ownerElement instanceof Element&&e.ownerElement.removeChild(e)}}function T(e,t,a=!1){!v(e,t,a)&&e.ownerElement instanceof Element&&e.ownerElement.removeAttributeNode(e)}function N(e,t,a=!1){if(e.hasChildNodes()){const r=e.childNodes;for(let e=r.length-1;-1!==e;e--)E(r[e],t,a)}}Promise.withResolvers instanceof Function||(Promise.withResolvers=function(){const e={};return e.promise=new Promise(((t,a)=>{e.resolve=t,e.reject=a})),e}),URL.canParse instanceof Function||(URL.canParse=function(e,t){try{return new URL(e,t),!0}catch{return!1}}),URL.parse instanceof Function||(URL.parse=function(e,t){return URL.canParse(e,t)?new URL(e,t):null}),Object.groupBy instanceof Function||(Object.groupBy=function(e,t){const a={};for(const r of e){const e=t(r);e in a?a[e].push(r):a[e]=[r]}return a}),Element.prototype.setHTML instanceof Function||(Element.prototype.setHTML=function(e,{sanitizer:{elements:t=d,attributes:a=p,comments:r=false,dataAttributes:n=true,...o}=f}={}){!function(e,t,{sanitizer:a=f,allowInsecure:r=!1}={}){const n=document.createElement("template");n.innerHTML=g.createHTML(t),y(n.content,a,r),e.replaceChildren(n.content)}(this,e,{sanitizer:{elements:t,attributes:a,comments:r,dataAttributes:n,...o}})}),Document.parseHTML instanceof Function||(Document.parseHTML=function(e,{sanitizer:{elements:t=d,attributes:a=p,comments:r=false,dataAttributes:n=true,...o}=f}={}){return function(e,{sanitizer:t=f,allowInsecure:a=!1}={}){const r=(new DOMParser).parseFromString(g.createHTML(e),"text/html");return y(r,t,a),r}(e,{sanitizer:{elements:t,attributes:a,comments:r,dataAttributes:n,...o}})})}();
*/const p=new Set(["href","src","action","xlink:href"]),f=new Set(["javascript:","data:","file:","ftp:"]),b=function(e,{createHTML:t,createScript:a,createScriptURL:r}){return"trustedTypes"in globalThis?trustedTypes.createPolicy(e,{createHTML:t,createScript:a,createScriptURL:r}):Object.freeze({[Symbol.for("policy-name")]:e.toString(),createHTML(a,...r){if(t instanceof Function){const e=t(a.toString(),...r).toString();return Object.freeze({toString:()=>e})}throw new TypeError(`Policy "${e}" does not provide a createHTML method.`)},createScript(t,...r){if(a instanceof Function){const e=a(t.toString(),...r).toString();return Object.freeze({toString:()=>e})}throw new TypeError(`Policy "${e}" does not provide a createScript method.`)},createScriptURL(t,...a){if(r instanceof Function){const e=r(t.toString(),...a).toString();return Object.freeze({toString:()=>e})}throw new TypeError(`Policy "${e}" does not provide a createScriptURL method.`)}})}("aegis-sanitizer#html",{createHTML:e=>e});function h(e,t,{elements:a=d.elements,attributes:r=d.attributes,comments:n=d.comments,dataAttributes:o=d.dataAttributes,...i}=d,{allowInsecure:s=!1}={}){const c=document.createElement("template");c.innerHTML=b.createHTML(t),y(c.content,{elements:a,attributes:r,comments:n,dataAttributes:o,...i},s),e.replaceChildren(c.content)}function g(e,{elements:t=d.elements,attributes:a=d.attributes,comments:r=d.comments,dataAttributes:n=d.dataAttributes,...o}=d,{allowInsecure:i=!1}={}){const s=(new DOMParser).parseFromString(b.createHTML(e),"text/html");return y(s,{elements:t,attributes:a,comments:r,dataAttributes:n,...o},i),s}function y(t,a=d,r=!1){if(t instanceof Node){const n=function(t,{elementNS:a=e,attributeNS:r}={}){if("object"!=typeof t||null===t)throw new TypeError("Sanitizer config must be an object.");return Object.freeze({elements:c(t,a),attributes:s(t,r),comments:i(t),dataAttributes:void 0===t.dataAttributes||t.dataAttributes})}(a);return v(t,n,r)}throw new TypeError("Not a node.")}const w="trustedTypes"in globalThis?e=>null!==trustedTypes.getAttributeType(e.ownerElement.tagName,e.localName,e.ownerElement.namespaceURI,e.namespaceURI):e=>t.has(e.localName);function T(e,t,a=!1){const r=e.namespaceURI||"";return(!("dataAttributes"in t)||t.dataAttributes)&&e.name.startsWith("data-")||r in t.attributes&&t.attributes[r].some((t=>t.name===e.localName))&&!(a||w(e))&&!(a||function(e){if(p.has(e.name)){if(URL.canParse(e.value)){const{protocol:t}=new URL(e.value);return f.has(t)}return!1}return!1}(e))}function v(e,t,a=!1){switch(e.nodeType){case Node.ELEMENT_NODE:!function(e,t,a){if(function(e,t){return e.namespaceURI in t.elements&&t.elements[e.namespaceURI].some((t=>t.name===e.localName))}(e,t)){if(e.hasAttributes()){const r=e.attributes;for(let e=r.length-1;-1!==e;e--)E(r[e],t,a)}if("TEMPLATE"===e.tagName)L(e.content,t,a);else if(e.hasChildNodes()){const r=e.childNodes;for(let e=r.length-1;-1!==e;e--)v(r[e],t,a)}}else e.remove()}(e,t,a);break;case Node.DOCUMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:L(e,t,a);break;case Node.COMMENT_NODE:!function(e,t){t.comments||e.remove()}(e,t);break;case Node.ATTRIBUTE_NODE:E(e,t,a);break;case Node.TEXT_NODE:case Node.DOCUMENT_TYPE_NODE:break;default:e.ownerElement instanceof Element&&e.ownerElement.removeChild(e)}}function E(e,t,a=!1){!T(e,t,a)&&e.ownerElement instanceof Element&&e.ownerElement.removeAttributeNode(e)}function L(e,t,a=!1){if(e.hasChildNodes()){const r=e.childNodes;for(let e=r.length-1;-1!==e;e--)v(r[e],t,a)}}Promise.withResolvers instanceof Function||(Promise.withResolvers=function(){const e={};return e.promise=new Promise(((t,a)=>{e.resolve=t,e.reject=a})),e}),URL.canParse instanceof Function||(URL.canParse=function(e,t){try{return new URL(e,t),!0}catch{return!1}}),URL.parse instanceof Function||(URL.parse=function(e,t){return URL.canParse(e,t)?new URL(e,t):null}),Object.groupBy instanceof Function||(Object.groupBy=function(e,t){const a={};for(const r of e){const e=t(r);e in a?a[e].push(r):a[e]=[r]}return a}),Element.prototype.setHTML instanceof Function||(Element.prototype.setHTML=function(e,{elements:t,attributes:a,comments:r,dataAttributes:n,sanitizer:o,...i}={}){"object"==typeof o&&null!==o?(console.warn("Use of `sanitizer` in config is deprecated. Please set config directly."),h(this,e,o.getConfiguration instanceof Function?o.getConfiguration():o)):h(this,e,{elements:t,attributes:a,comments:r,dataAttributes:n,...i})},DocumentFragment.prototype.setHTML=function(...e){Element.prototype.setHTML.apply(this,e)},HTMLTemplateElement.prototype.setHTML=function(e,t){this.content.setHTML(e,t)}),Document.parseHTML instanceof Function||(Document.parseHTML=function(e,{elements:t,attributes:a,comments:r,dataAttributes:n,sanitizer:o,...i}={}){return"object"==typeof o&&null!==o?Document.parseHTML(e,o.getConfiguration instanceof Function?o.getConfiguration():o):g(e,{elements:t,attributes:a,comments:r,dataAttributes:n,...i})})}();
//# sourceMappingURL=polyfill.min.js.map

@@ -75,5 +75,10 @@ # `@aegisjsproject/sanitizer`

</div>
<p>Bacon ipsum dolor amet pork belly frankfurter drumstick jowl brisket capicola short ribs. Cow chislic ham hock t-bone shoulder salami rump corned beef spare ribs prosciutto bresaola picanha drumstick. Swine tail pork belly ribeye beef kielbasa. Beef cupim ball tip pastrami spare ribs strip steak tongue salami venison. Venison cupim meatball strip steak meatloaf prosciutto buffalo frankfurter hamburger flank boudin.</p>
<p>Bacon ipsum dolor amet pork belly frankfurter drumstick jowl brisket capicola
short ribs.Cow chislic ham hock t-bone shoulder salami rump corned beef spare
ribs prosciutto bresaola picanha drumstick. Swine tail pork belly ribeye beef
kielbasa. Beef cupim ball tip pastrami spare ribs strip steak tongue salam
venison. Venison cupim meatball strip steak meatloaf prosciutto buffalo
frankfurter hamburger flank boudin.</p>
</div>
`, { sanitizer });
`, sanitizer);
```

@@ -94,3 +99,3 @@

const el = document.createElement('div');
el.setHTML(comment.body, { sanitizer });
el.setHTML(comment.body, sanitizer);
return el;

@@ -101,3 +106,3 @@ }));

### Adding to allowed elements / attributes:
### Adding to allowed elements / attributes

@@ -114,3 +119,17 @@ ```js

<hello-world foo="bar"></hello-world>
`, { sanitizer });
`, sanitizer);
```
### Enforce Sanitization by default (on eg `innerHTML`, where supported)
```js
if ('trustedTypes' in globalThis) {
trustedTypes.createPolicy('default', {
createHTML(input) {
const el = document.createElement('div');
el.setHTML(input);
return el.innerHTML;
}
});
}
```

@@ -10,12 +10,24 @@ import { sanitizer as sanitizerConfig } from '@aegisjsproject/sanitizer/config/html.js';

export function setHTML(el, content, { sanitizer = sanitizerConfig, allowInsecure = false } = {}) {
export function setHTML(el, content, {
elements = sanitizerConfig.elements,
attributes = sanitizerConfig.attributes,
comments = sanitizerConfig.comments,
dataAttributes = sanitizerConfig.dataAttributes,
...rest
} = sanitizerConfig, { allowInsecure = false } = {}) {
const tmp = document.createElement('template');
tmp.innerHTML = policy.createHTML(content);
sanitize(tmp.content, sanitizer, allowInsecure);
sanitize(tmp.content, { elements, attributes, comments, dataAttributes, ...rest }, allowInsecure);
el.replaceChildren(tmp.content);
}
export function parseHTML(content, { sanitizer = sanitizerConfig, allowInsecure = false } = {}) {
export function parseHTML(content, {
elements = sanitizerConfig.elements,
attributes = sanitizerConfig.attributes,
comments = sanitizerConfig.comments,
dataAttributes = sanitizerConfig.dataAttributes,
...rest
} = sanitizerConfig, { allowInsecure = false } = {}) {
const doc = new DOMParser().parseFromString(policy.createHTML(content), 'text/html');
sanitize(doc, sanitizer, allowInsecure);
sanitize(doc, { elements, attributes, comments, dataAttributes, ...rest }, allowInsecure);
return doc;

@@ -22,0 +34,0 @@ }

import '@aegisjsproject/trusted-types';
import '@aegisjsproject/sanitizer';
import '@aegisjsproject/sanitizer/trust-policy.js?policy=default';
// import '@aegisjsproject/sanitizer/trust-policy.js?policy=default';
import { sanitizer } from '@aegisjsproject/sanitizer/config/complete.js';
const policy = trustedTypes.createPolicy('default', {
createHTML(input, {
elements = sanitizer.elements,
attributes = sanitizer.attributes,
comments = sanitzier.comments,
dataAttributes = sanitizer.dataAttribtes,
...rest
} = sanitizer) {
const el = document.createElement('div');
el.setHTML(input, { elements, attributes, comments, dataAttributes, ...rest });
return el.innerHTML;
},
});
const params = new URLSearchParams(location.search);

@@ -25,3 +39,36 @@

document.getElementById('container').innerHTML = trustedTypes.defaultPolicy.createHTML(`
const attackURL = new URL(location.pathname, location.origin);
attackURL.searchParams.set('html', `<p>Trying to inject encoded script:</p>
<img src="icon.svg" alt="Onload attack" onload="alert('XSS')" />
<img src="icon.svg
onload=alert('XSS!')" alt="Encoded onerror with null byte">
<a href="javascript:alert('XSS!')">Click me (should be stripped)</a>
<a href="javascript:alert('XSS!')">Click me (encoded javascript URL)</a>
<a href="&#٣;avascript:alert('XSS!')">Click me (Arabic encoded javascript URL)</a>
<p>Testing nested event handlers:</p>
<button onclick="javascript:location.href='#' onmouseover='javascript:alert('XSS!')'>Click Me</button>
<button onclick="javascript:location.href='#' onmouseover='javascript:alert('XSS!')'>Click Me (encoded nested)</button>
<p>Testing character encoding confusion:</p>
<a href="<javascript:alert('XSS!')">Click Me (lt symbol in hex)</a>
<a href="<avascript:alert('XSS!')">Click Me (less than symbol in decimal)</a>
<a href="x�alert('XSS!')">Click Me (null byte in image source)</a>
<p>Testing self-XSS with unusual characters:</p>
<svg onload="alert('XSS!')">
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
<svg onload=alert('XSS!')>
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
<p>Testing data attributes (should be allowed based on your config):</p>
<p>Testing style injection:</p>
<button style="background-image: url('javascript:alert('XSS!')')">Style Injection</button>
<button style="background:url(javascript:alert('XSS!'))">Click Me (encoded background URL)</button>`);
// Tests Sanitizer via `trustedTypes.defaultPolicy
document.getElementById('container').innerHTML = policy.createHTML(`
<style>

@@ -49,3 +96,3 @@ h1::after {

<a href="chrome://flags"><code>chrome://flags</code></a>
<a href="?html=%3Cp%3ETrying+to+inject+encoded+script%3A%3C%2Fp%3E%0A++%3Cimg+src%3D%22notanimage.jpg%250Aonerror%3Dalert%28%27XSS%21%27%29%22+alt%3D%22Encoded+onerror%22%3E%0A++%3Cimg+src%3D%22notanotherimage.png%0Aonerror%3Dalert%28%27XSS%21%27%29%22+alt%3D%22Encoded+onerror+with+null+byte%22%3E%0A++%3Ca+href%3D%22javascript%3Aalert%28%27XSS%21%27%29%22%3EClick+me+%28should+be+stripped%29%3C%2Fa%3E%0A++%3Ca+href%3D%22javascript%3Aalert%28%27XSS%21%27%29%22%3EClick+me+%28encoded+javascript+URL%29%3C%2Fa%3E%0A++%3Ca+href%3D%22%26%23%D9%A3%3Bavascript%3Aalert%28%27XSS%21%27%29%22%3EClick+me+%28Arabic+encoded+javascript+URL%29%3C%2Fa%3E%0A%0A%3Cp%3ETesting+nested+event+handlers%3A%3C%2Fp%3E%0A++%3Cbutton+onclick%3D%22javascript%3Alocation.href%3D%27%23%27+onmouseover%3D%27javascript%3Aalert%28%27XSS%21%27%29%27%3EClick+Me%3C%2Fbutton%3E%0A++%3Cbutton+onclick%3D%22javascript%3Alocation.href%3D%27%23%27+onmouseover%3D%27javascript%3Aalert%28%27XSS%21%27%29%27%3EClick+Me+%28encoded+nested%29%3C%2Fbutton%3E%0A%0A%3Cp%3ETesting+character+encoding+confusion%3A%3C%2Fp%3E%0A++%3Ca+href%3D%22%3Cjavascript%3Aalert%28%27XSS%21%27%29%22%3EClick+Me+%28lt+symbol+in+hex%29%3C%2Fa%3E%0A++%3Ca+href%3D%22%3Cavascript%3Aalert%28%27XSS%21%27%29%22%3EClick+Me+%28less+than+symbol+in+decimal%29%3C%2Fa%3E%0A++%3Ca+href%3D%22x%00alert%28%27XSS%21%27%29%22%3EClick+Me+%28null+byte+in+image+source%29%3C%2Fa%3E%0A++%3Cimg+src%3D%22x%EF%BF%BDalert%28%27XSS%21%27%29%22+alt%3D%22Image+with+null+byte%22%3E%0A%0A%3Cp%3ETesting+self-XSS+with+unusual+characters%3A%3C%2Fp%3E%0A++%3Cimg+src%3D%22notanimage.jpg%00alert%28%27XSS%21%27%29%22+alt%3D%22Image+with+null+byte%22%3E%0A++%3Cimg+src%3D%22notanotherimage.png%01%22+alt%3D%22Image+with+strange+character%22%3E%0A++%3Csvg+onload%3D%22alert%28%27XSS%21%27%29%22%3E%0A++++%3Ccircle+cx%3D%2250%22+cy%3D%2250%22+r%3D%2240%22+fill%3D%22red%22+%2F%3E%0A++%3C%2Fsvg%3E%0A++%3Csvg+onload%3Dalert%28%27XSS%21%27%29%3E%0A++++%3Ccircle+cx%3D%2250%22+cy%3D%2250%22+r%3D%2240%22+fill%3D%22red%22+%2F%3E%0A++%3C%2Fsvg%3E%0A%0A%3Cp%3ETesting+data+attributes+%28should+be+allowed+based+on+your+config%29%3A%3C%2Fp%3E%0A++%3Cdiv+data-harmless%3D%22true%22%3EThis+is+a+harmless+data+attribute%3C%2Fdiv%3E%0A++%3Cdiv+data-evil%3D%22true%22+style%3D%22color%3A+red%3B%22%3EThis+is+an+evil+data+attribute+%28color+might+be+stripped%29%3C%2Fdiv%3E%0A%0A%3Cp%3ETesting+style+injection%3A%3C%2Fp%3E%0A++%3Cbutton+style%3D%22background-image%3A+url%28%27javascript%3Aalert%28%27XSS%21%27%29%27%29%22%3EClick+Me%3C%2Fbutton%3E%0A++%3Cbutton+style%3D%22background%3Aurl%28javascript%3Aalert%28%27XSS%21%27%29%29%22%3EClick+Me+%28encoded+background+URL%29%3C%2Fbutton%3E">Test Sanitizer</a>
<a href="${attackURL}">Test Sanitizer</a>
<a href="./">Clear Test</a>

@@ -97,3 +144,3 @@ </nav>

<div>${params.has('html') ? params.get('html') : 'No <code>?html=</code> search param given'}</div>
<form id="attack" method="GET" action="${location.href}">
<form id="attack" method="GET" action="${new URL(location.pathname, location.origin)}">
<fieldset>

@@ -116,4 +163,4 @@ <legend>Attack this Page</legend>

</template>
`, sanitizer);
`);
document.getElementById('main').append(document.getElementById('tmp').content);

@@ -57,3 +57,3 @@ export function createPolicy(name, { createHTML: html, createScript: script, createScriptURL: scriptURL }) {

const el = document.createElement('div');
el.setHTML(input, { sanitizer: { elements, attributes, comments, dataAttributes, ...rest }});
el.setHTML(input, { elements, attributes, comments, dataAttributes, ...rest });
return el.innerHTML;

@@ -60,0 +60,0 @@ }

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc