Torna agli aggiornamenti
New releaseSep 7, 2026

DOMPurify v3.4.15

DOMPurify - un sanitizer XSS DOM-only, super veloce, ultra-tollerante per HTML, MathML e SVG. DOMPurify funziona con impostazioni predefinite sicure, ma offre molta configurabilità e hook. Demo:

Condividi

DOMPurify

npm License Downloads dependents npm package minimized gzipped size (select exports) Cloudback

OpenSSF Best Practices Build & Test OpenSSF Scorecard Socket Badge snyk.io package health

DOMPurify è un sanitizzatore XSS per HTML, MathML e SVG, esclusivamente DOM-based, super veloce e ultra tollerante.

È anche molto semplice da usare e da iniziare. DOMPurify è stato avviato a febbraio 2014 e, nel frattempo, ha raggiunto la versione v3.4.15.

DOMPurify gira come JavaScript e funziona in tutti i browser moderni (Safari (10+), Opera (15+), Edge, Firefox e Chrome - oltre a quasi qualsiasi altro browser basato su Blink, Gecko o WebKit). Non si rompe su MSIE o altri browser legacy. Semplicemente non fa nulla.

Nota che DOMPurify v2.5.9 è l'ultima versione che supporta MSIE. Per importanti aggiornamenti di sicurezza compatibili con MSIE, utilizza il ramo 2.x.

I nostri test automatizzati coprono 9 combinazioni browser/OS sui motori attuali (Chromium, Firefox e WebKit su Ubuntu, macOS e Windows) a ogni push, e una matrice separata riesegue la suite su snapshot di motori più vecchi (fino a circa Chromium 110, Firefox 108 e WebKit 16.4, di circa tre anni fa) così da intercettare anche regressioni su browser obsoleti. Eseguiamo anche Node.js v20, v22, v24, v25 e v26 con DOMPurify su jsdom. Anche versioni più vecchie di Node sono note per funzionare, ma... nessuna garanzia.

DOMPurify è scritto da esperti di sicurezza con una vasta esperienza in attacchi web e XSS. Nessun timore. Per maggiori dettagli, ti invitiamo a leggere anche i nostri Obiettivi di Sicurezza e Modello di Minaccia. Per favore, leggilo. Sul serio. E se ti piacciono i dettagli cruenti, la pagina Classi di Attacco e Storia dei Bypass cataloga i trucchi di mutazione del parser, namespace, clobbering e template contro cui DOMPurify si difende.

Il progetto DOMPurify ha ispirato la creazione dell'API HTML Sanitizer, che è già disponibile in molti browser. La stessa capacità è ora in fase di standardizzazione direttamente nella specifica HTML del WHATWG.

Indice dei contenuti

Cosa fa?

DOMPurify sanifica l'HTML e previene gli attacchi XSS. Puoi fornire a DOMPurify, ad esempio, una stringa piena di HTML sporco e restituirà una stringa (a meno che non sia configurato diversamente) con HTML pulito. DOMPurify eliminerà tutto ciò che contiene HTML pericoloso e quindi previene attacchi XSS e altre cose sgradevoli. È anche dannatamente veloce. Utilizziamo le tecnologie che il browser fornisce e le trasformiamo in un filtro XSS. Più veloce è il tuo browser, più veloce sarà DOMPurify.

Come lo uso?

È facile. Basta includere DOMPurify sul tuo sito web.

Utilizzo della versione non minimizzata (source-map disponibile)```html

### Utilizzo della versione di produzione minificata e testata (source-map disponibile)```html
<script type="text/javascript" src="dist/purify.min.js"></script>

Dopodiché puoi sanificare le stringhe eseguendo il seguente codice:```js const clean = DOMPurify.sanitize(dirty);

Oppure questo, se ami lavorare con Angular o simili:```js
import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize('<b>hello there</b>');

L'HTML risultante può essere scritto in un elemento DOM tramite innerHTML o nel DOM usando document.write(). Dipende interamente da te. Nota che, per impostazione predefinita, consentiamo HTML, SVG e MathML. Se ti serve solo HTML, che potrebbe essere un caso d'uso molto comune, puoi configurarlo facilmente anche in quel modo:```js const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });

### Ci sono potenziali insidie?

Beh, tieni presente che se _prima_ sanifichi l'HTML e poi lo modifichi _successivamente_, potresti facilmente **annullare gli effetti della sanificazione**. Se passi il markup sanificato a un'altra libreria _dopo_ la sanificazione, assicurati che la libreria non alteri l'HTML di propria iniziativa. Consulta gli [Obiettivi di Sicurezza e il Modello di Minaccia](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model) per ricette di utilizzo sicuro e per i tag e gli attributi su cui vale la pena riflettere due volte, e le [Classi di Attacco e la Storia dei Bypass](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History) per capire perché la post-elaborazione e la modifica del contesto del markup compromettono la sanificazione.

### Ok, ha senso, andiamo avanti

Dopo aver sanificato il tuo markup, puoi anche dare un'occhiata alla proprietà `DOMPurify.removed` e scoprire quali elementi e attributi sono stati scartati. Ti preghiamo di **non utilizzare** questa proprietà per prendere decisioni critiche per la sicurezza. È solo un piccolo aiuto per le menti curiose.

### Eseguire DOMPurify sul server

DOMPurify tecnicamente funziona anche lato server con Node.js. Il nostro supporto cerca di seguire il [ciclo di rilascio di Node.js](https://nodejs.org/en/about/previous-releases).

Eseguire DOMPurify sul server richiede la presenza di un DOM, il che probabilmente non sorprende. Di solito, [jsdom](https://github.com/jsdom/jsdom) è lo strumento di elezione e **raccomandiamo vivamente** di utilizzare l'ultima versione di _jsdom_.

Perché? Perché le versioni precedenti di _jsdom_ sono note per essere difettose in modi che provocano XSS _anche se_ DOMPurify fa tutto correttamente al 100%. Esistono **vettori di attacco noti**, ad esempio in _jsdom v19.0.0_, che sono stati corretti in _jsdom v20.0.0_ - e per questo raccomandiamo davvero di mantenere _jsdom_ aggiornato.

Tieni inoltre presente che esistono strumenti come [happy-dom](https://github.com/capricorn86/happy-dom), ma **non sono considerati sicuri** al momento. Combinare DOMPurify con _happy-dom_ non è attualmente raccomandato e probabilmente porterà a XSS. Per capire perché il DOM lato server che scegli fa parte della tua base di calcolo fidata, consulta le [Classi di Attacco e la Storia dei Bypass](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History).

A parte questo, puoi tranquillamente usare DOMPurify sul server. Probabilmente. Questo dipende davvero da _jsdom_ o da qualunque DOM utilizzi lato server. Se puoi conviverci, ecco come farlo funzionare:```bash
npm install dompurify
npm install jsdom

Per jsdom (si prega di usare una versione aggiornata), questo dovrebbe fare al caso vostro:```js const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom');

const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window); const clean = DOMPurify.sanitize('hello there');

Oppure anche questo, se preferisci lavorare con gli import:```js
import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';

const window = new JSDOM('').window;
const purify = DOMPurify(window);
const clean = purify.sanitize('<b>hello there</b>');

Se hai problemi a farlo funzionare nella tua configurazione specifica, considera di dare un'occhiata al fantastico progetto isomorphic-dompurify che risolve molti dei problemi che le persone potrebbero incontrare.```bash npm install isomorphic-dompurify

Installazione

Requisiti

  • Python 3.8 o superiore
  • pip
  • Git

Passaggi di installazione

  1. Clona il repository:
git clone https://github.com/example/tool.git
cd tool
  1. Crea un ambiente virtuale (opzionale ma consigliato):
python -m venv venv
source venv/bin/activate  # Su Windows: venv\Scripts\activate
  1. Installa le dipendenze:
pip install -r requirements.txt
  1. Verifica l'installazione:
python tool.py --version

Risoluzione dei problemi

Se riscontri problemi durante l'installazione, controlla quanto segue:

  • Assicurati che la tua versione di Python soddisfi il requisito minimo.
  • Verifica che pip sia aggiornato: pip install --upgrade pip.
  • Se utilizzi un proxy o un firewall, potrebbe essere necessario configurare pip di conseguenza.

Per ulteriore assistenza, consulta la documentazione ufficiale o apri un problema nel repository.

import DOMPurify from 'isomorphic-dompurify';

const clean = DOMPurify.sanitize('<s>hello</s>');
```
## C'è una demo?

Certo che c'è una demo! [Gioca con DOMPurify](https://cure53.de/purify)

## E se trovo un bug di sicurezza?

Prima di tutto, contattaci subito via [email](mailto:[email protected]) così possiamo lavorare a una soluzione. [Chiave PGP](https://keyserver.ubuntu.com/pks/lookup?op=vindex&search=0xC26C858090F70ADA)

Inoltre, probabilmente hai diritto a un bug bounty! Le brave persone di [Fastmail](https://www.fastmail.com/) usano DOMPurify per i loro servizi e hanno aggiunto la nostra libreria al loro programma di bug bounty. Quindi, se trovi un modo per bypassare o indebolire DOMPurify, dai un'occhiata anche al loro sito e alle [informazioni sul bug bounty](https://www.fastmail.com/about/bugbounty/).

## Qualche esempio di purificazione, per favore?

Come appare il markup purificato? Beh, [la demo](https://cure53.de/purify) lo mostra per un bel po' di elementi dannosi. Ma mostriamo anche qualche esempio più piccolo!```js
DOMPurify.sanitize(''); // becomes <img src="https://raw.githubusercontent.com/cure53/dompurify/main/x">
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
DOMPurify.sanitize('<p>abcdef</p>'); // becomes <p>abc</p>
DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math>
DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table>
DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><li><a href="//google.com">click</a></li></ul>
```
Questi sono solo un assaggio. Per la tassonomia completa delle classi di attacco da cui provengono questi campioni - mutation XSS, namespace confusion, DOM clobbering, rawtext breakouts e altro - consulta [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History).

## Cosa è supportato?

DOMPurify supporta attualmente HTML5, SVG e MathML. DOMPurify per impostazione predefinita consente CSS e attributi dati personalizzati HTML. DOMPurify supporta anche il Shadow DOM - e sanifica i template DOM in modo ricorsivo. DOMPurify ti consente inoltre di sanificare HTML per essere utilizzato con le API jQuery `$()` e `elm.html()` senza alcun problema noto. Per l'insieme esatto di elementi e attributi consentiti per impostazione predefinita, consulta la pagina wiki [Default TAGs & ATTRIBUTEs allow-list & blocklist](https://github.com/cure53/DOMPurify/wiki/Default-TAGs-ATTRIBUTEs-allow-list-&-blocklist).

## E i browser legacy come Internet Explorer?

DOMPurify non fa assolutamente nulla. Restituisce semplicemente esattamente la stringa che gli hai fornito. DOMPurify espone una proprietà chiamata `isSupported`, che ti dice se sarà in grado di svolgere il suo lavoro, così puoi elaborare il tuo piano di riserva.

## E DOMPurify e Trusted Types?

Nella versione 1.0.9, è stato aggiunto a DOMPurify il supporto per la [Trusted Types API](https://github.com/w3c/webappsec-trusted-types) ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API)).
Nella versione 2.0.0, è stato aggiunto un flag di configurazione per controllare il comportamento di DOMPurify in merito.

Quando `DOMPurify.sanitize` viene utilizzato in un ambiente in cui la Trusted Types API è disponibile e `RETURN_TRUSTED_TYPE` è impostato su `true`, tenta di restituire un valore `TrustedHTML` invece di una stringa (il comportamento per le opzioni di configurazione `RETURN_DOM` e `RETURN_DOM_FRAGMENT` non cambia).

Nota che per creare una policy in `trustedTypes` utilizzando DOMPurify, è richiesto `RETURN_TRUSTED_TYPE: false`, poiché `createHTML` si aspetta una stringa normale, non `TrustedHTML`. L'esempio seguente lo mostra.```js
window.trustedTypes.createPolicy('default', {
  createHTML: (to_escape) =>
    DOMPurify.sanitize(to_escape, { RETURN_TRUSTED_TYPE: false }),
});
```
Quando non viene fornita una `TRUSTED_TYPES_POLICY`, DOMPurify tenta di creare una propria policy interna Trusted Types denominata `dompurify`. Se la tua pagina definisce già una propria policy insieme a una CSP rigorosa (ad esempio `trusted-types my-organization`) che non consente una policy denominata `dompurify`, questo tentativo viene bloccato dal browser e registra un avviso `TrustedTypes policy dompurify could not be created.` insieme a una violazione della CSP.

Per impedire a DOMPurify di creare la sua policy di fallback interna, passa `TRUSTED_TYPES_POLICY: null`. Questa è la scelta corretta quando chiami `DOMPurify.sanitize` dall'interno del `createHTML` della tua policy, e significa che non devi aggiungere `dompurify` alla allowlist `trusted-types` della tua CSP.```js
window.trustedTypes.createPolicy('my-organization', {
  createHTML: (input) =>
    DOMPurify.sanitize(input, { TRUSTED_TYPES_POLICY: null }),
});
```
Non passare la tua policy di wrapping a DOMPurify come sua `TRUSTED_TYPES_POLICY` (ad esempio tramite `DOMPurify.setConfig({ TRUSTED_TYPES_POLICY: myPolicy })`) quando la `createHTML` di quella policy chiama già `DOMPurify.sanitize`. Questo è circolare per definizione: la sanitizzazione chiamerebbe la policy, che sanitizza chiamando di nuovo DOMPurify — e DOMPurify lancerà un `TypeError` descrittivo per prevenire la ricorsione infinita. La tua policy dovrebbe chiamare DOMPurify; DOMPurify non dovrebbe essere configurato per chiamare la tua policy.

Se vuoi che questo pattern di policy `default` venga applicato automaticamente a un'intera pagina — così che ogni sink HTML venga sanitizzato, incluso codice legacy, widget di terze parti e le migliaia di assegnazioni `innerHTML` che non puoi facilmente trovare o riscrivere — dai un'occhiata a [DOMFortify](https://github.com/cure53/DOMFortify). Installa esattamente una policy Trusted Types `default` di questo tipo basata su DOMPurify e rifiuta categoricamente i sink di script (`eval`, `script.src`, ...). È volutamente un progetto separato: DOMPurify resta un sanitizer mirato, mentre DOMFortify gestisce il livello di enforcement a livello di documento che è intenzionalmente fuori dallo scope di DOMPurify.

## Posso configurare DOMPurify?

Sì. I valori di configurazione predefiniti inclusi sono già piuttosto buoni — ma puoi ovviamente sovrascriverli. Dai un'occhiata alla cartella [`/demos`](https://github.com/cure53/DOMPurify/tree/main/demos) per vedere una serie di esempi su come puoi [personalizzare DOMPurify](https://github.com/cure53/DOMPurify/tree/main/demos#what-is-this).

Prima di ampliare la allow-list (`ADD_TAGS`, `ADD_ATTR`, `CUSTOM_ELEMENT_HANDLING`, …) o allentare un'impostazione predefinita, vale la pena dare una scorsa a [tag e attributi su cui riflettere due volte](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model#dangerous-tags-and-attributes-think-twice-before-allow-listing) — alcuni sono pericolosi in modi non ovvi.

### Impostazioni generali```js
// 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.
const clean = DOMPurify.sanitize(dirty, { SAFE_FOR_TEMPLATES: true });

// 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.
const clean = DOMPurify.sanitize(dirty, { SAFE_FOR_XML: false });
```
### Controlla le nostre allow-list e block-list```js
// allow only <b> elements, very strict
const clean = DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ['b'] });

// allow only <b> and <q> with style attributes
const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_TAGS: ['b', 'q'],
  ALLOWED_ATTR: ['style'],
});

// allow all safe HTML elements but neither SVG nor MathML
// note that the USE_PROFILES setting will override the ALLOWED_TAGS setting
// so don't use them together
const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });

// allow all safe SVG elements and SVG Filters, no HTML or MathML
const clean = DOMPurify.sanitize(dirty, {
  USE_PROFILES: { svg: true, svgFilters: true },
});

// allow all safe MathML elements and SVG, but no SVG Filters
const clean = DOMPurify.sanitize(dirty, {
  USE_PROFILES: { mathMl: true, svg: true },
});

// change the default namespace from HTML to something different
const clean = DOMPurify.sanitize(dirty, {
  NAMESPACE: 'http://www.w3.org/2000/svg',
});

// leave all safe HTML as it is and add <style> elements to block-list
const clean = DOMPurify.sanitize(dirty, { FORBID_TAGS: ['style'] });

// leave all safe HTML as it is and add style attributes to block-list
const clean = DOMPurify.sanitize(dirty, { FORBID_ATTR: ['style'] });

// extend the existing array of allowed tags and add <my-tag> to allow-list
const clean = DOMPurify.sanitize(dirty, { ADD_TAGS: ['my-tag'] });

// extend the existing array of allowed attributes and add my-attr to allow-list
const clean = DOMPurify.sanitize(dirty, { ADD_ATTR: ['my-attr'] });

// use functions to control which additional tags and attributes are allowed
const allowlist = {
  one: ['attribute-one'],
  two: ['attribute-two'],
};
const clean = DOMPurify.sanitize(
  '<one attribute-one="1" attribute-two="2"></one><two attribute-one="1" attribute-two="2"></two>',
  {
    ADD_TAGS: (tagName) => {
      return Object.keys(allowlist).includes(tagName);
    },
    ADD_ATTR: (attributeName, tagName) => {
      return allowlist[tagName]?.includes(attributeName) || false;
    },
  }
); // <one attribute-one="1"></one><two attribute-two="2"></two>

// prohibit ARIA attributes, leave other safe HTML as is (default is true)
const clean = DOMPurify.sanitize(dirty, { ALLOW_ARIA_ATTR: false });

// prohibit HTML5 data attributes, leave other safe HTML as is (default is true)
const clean = DOMPurify.sanitize(dirty, { ALLOW_DATA_ATTR: false });
```
### Comportamento di controllo relativo ai Custom Elements```js
// DOMPurify allows to define rules for Custom Elements. When using the CUSTOM_ELEMENT_HANDLING
// literal, it is possible to define exactly what elements you wish to allow (by default, none are allowed).
//
// The same goes for their attributes. By default, the built-in or configured allow.list is used.
//
// You can use a RegExp literal to specify what is allowed or a predicate, examples for both can be seen below.
// When using a predicate function for attributeNameCheck, it can optionally receive the tagName as a second parameter
// for more granular control over which attributes are allowed for specific elements.
// The default values are very restrictive to prevent accidental XSS bypasses. Handle with great care!

const clean = DOMPurify.sanitize(
  '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: null, // no custom elements are allowed
      attributeNameCheck: null, // default / standard attribute allow-list is used
      allowCustomizedBuiltInElements: false, // no customized built-ins allowed
    },
  }
); // <div is=""></div>

const clean = DOMPurify.sanitize(
  '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: /^foo-/, // allow all tags starting with "foo-"
      attributeNameCheck: /baz/, // allow all attributes containing "baz"
      allowCustomizedBuiltInElements: true, // customized built-ins are allowed
    },
  }
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>

const clean = DOMPurify.sanitize(
  '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: (tagName) => tagName.match(/^foo-/), // allow all tags starting with "foo-"
      attributeNameCheck: (attr) => attr.match(/baz/), // allow all containing "baz"
      allowCustomizedBuiltInElements: true, // allow customized built-ins
    },
  }
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>

// Example with attributeNameCheck receiving tagName as a second parameter
const clean = DOMPurify.sanitize(
  '<element-one attribute-one="1" attribute-two="2"></element-one><element-two attribute-one="1" attribute-two="2"></element-two>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: (tagName) => tagName.match(/^element-(one|two)$/),
      attributeNameCheck: (attr, tagName) => {
        if (tagName === 'element-one') {
          return ['attribute-one'].includes(attr);
        } else if (tagName === 'element-two') {
          return ['attribute-two'].includes(attr);
        } else {
          return false;
        }
      },
      allowCustomizedBuiltInElements: false,
    },
  }
); // <element-one attribute-one="1"></element-one><element-two attribute-two="2"></element-two>
```
### Comportamento di controllo relativo ai valori URI```js
// extend the existing array of elements that can use Data URIs
const clean = DOMPurify.sanitize(dirty, { ADD_DATA_URI_TAGS: ['a', 'area'] });

// extend the existing array of elements that are safe for URI-like values (be careful, XSS risk)
const clean = DOMPurify.sanitize(dirty, { ADD_URI_SAFE_ATTR: ['my-attr'] });
```
### Controllo dei valori consentiti degli attributi```js
// 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, xmpp and matrix are allowed.
const clean = DOMPurify.sanitize(dirty, { ALLOW_UNKNOWN_PROTOCOLS: true });

// allow specific protocol handlers in URL attributes via regex (default is false, be careful, XSS risk)
// by default only (protocol-)relative URLs, http, https, ftp, ftps, tel, mailto, callto, sms, cid, xmpp and matrix are allowed.
// Default RegExp: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_URI_REGEXP:
    /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
});
```
### Influenza il tipo di ritorno```js
// return a DOM HTMLBodyElement instead of an HTML string (default is false)
const clean = DOMPurify.sanitize(dirty, { RETURN_DOM: true });

// return a DOM DocumentFragment instead of an HTML string (default is false)
const clean = DOMPurify.sanitize(dirty, { RETURN_DOM_FRAGMENT: true });

// use the RETURN_TRUSTED_TYPE flag to turn on Trusted Types support if available
const clean = DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: true }); // will return a TrustedHTML object instead of a string if possible

// use a provided Trusted Types policy
const clean = DOMPurify.sanitize(dirty, {
  // supplied policy must define createHTML and createScriptURL
  TRUSTED_TYPES_POLICY: trustedTypes.createPolicy('dompurify', {
    createHTML(s) {
      return s;
    },
    createScriptURL(s) {
      return s;
    },
  }),
});

// opt out of DOMPurify's internal `dompurify` Trusted Types policy entirely
// (useful when your CSP `trusted-types` allowlist does not include `dompurify`)
const clean = DOMPurify.sanitize(dirty, { TRUSTED_TYPES_POLICY: null });
```
### Influenza su come sanifichiamo```js
// return entire document including <html> tags (default is false)
const clean = DOMPurify.sanitize(dirty, { WHOLE_DOCUMENT: true });

// disable DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here)
const clean = DOMPurify.sanitize(dirty, { SANITIZE_DOM: false });

// 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-`
const clean = DOMPurify.sanitize(dirty, { SANITIZE_NAMED_PROPS: true });

// keep an element's content when the element is removed (default is true)
const clean = DOMPurify.sanitize(dirty, { KEEP_CONTENT: false });

// glue elements like style, script or others to document.body and prevent unintuitive browser behavior in several edge-cases (default is false)
const clean = DOMPurify.sanitize(dirty, { FORCE_BODY: true });

// remove all <a> elements under <p> elements that are removed
const clean = DOMPurify.sanitize(dirty, {
  FORBID_CONTENTS: ['a'],
  FORBID_TAGS: ['p'],
});

// extend the default FORBID_CONTENTS list to also remove <a> elements under <p> elements
const clean = DOMPurify.sanitize(dirty, {
  ADD_FORBID_CONTENTS: ['a'],
  FORBID_TAGS: ['p'],
});

// change the parser type so sanitized data is treated as XML and not as HTML, which is the default
const clean = DOMPurify.sanitize(dirty, {
  PARSER_MEDIA_TYPE: 'application/xhtml+xml',
});
```
### Influenza su dove sanifichiamo```js
// use the IN_PLACE mode to sanitize a node "in place", which is much faster depending on how you use DOMPurify
const dirty = document.createElement('a');
dirty.setAttribute('href', 'javascript:alert(1)');

const clean = DOMPurify.sanitize(dirty, { IN_PLACE: true }); // see https://github.com/cure53/DOMPurify/issues/288 for more info
```
Ci sono [altri esempi qui](https://github.com/cure53/DOMPurify/tree/main/demos#what-is-this), che mostrano come eseguire, personalizzare e configurare DOMPurify per soddisfare le tue esigenze.

## Configurazione Persistente

Invece di passare ripetutamente la stessa configurazione a `DOMPurify.sanitize`, puoi usare il metodo `DOMPurify.setConfig`. La tua configurazione persisterà fino alla successiva chiamata a `DOMPurify.setConfig`, o fino a quando non invocherai `DOMPurify.clearConfig` per reimpostarla. Ricorda che esiste una sola configurazione attiva, il che significa che una volta impostata, tutti i parametri di configurazione aggiuntivi passati a `DOMPurify.sanitize` vengono ignorati.

## Hooks

DOMPurify ti consente di potenziare le sue funzionalità allegando una o più funzioni con il metodo `DOMPurify.addHook` a uno dei seguenti hook:

- `beforeSanitizeElements`
- `uponSanitizeElement` (senza 's' - chiamato per ogni elemento)
- `afterSanitizeElements`
- `beforeSanitizeAttributes`
- `uponSanitizeAttribute`
- `afterSanitizeAttributes`
- `beforeSanitizeShadowDOM`
- `uponSanitizeShadowNode`
- `afterSanitizeShadowDOM`

Passa al callback il nodo DOM attualmente elaborato, quando necessario un letterale con dati verificati di nodo e attributo, e la configurazione di DOMPurify. Dai un'occhiata alla [demo dell'hook MentalJS](https://github.com/cure53/DOMPurify/blob/main/demos/hooks-mentaljs-demo.html) per vedere come l'API può essere utilizzata in modo efficace.

_Esempio_:```js
DOMPurify.addHook(
  'uponSanitizeAttribute',
  function (currentNode, hookEvent, config) {
    // Do something with the current node
    // You can also mutate hookEvent for current node (i.e. set hookEvent.forceKeepAttr = true)
    // For other than 'uponSanitizeAttribute' hook types hookEvent equals to null
  }
);
```
### Una nota sulla chiamata di `sanitize()` da un hook

**`DOMPurify.sanitize()` non è rientrante.** Non chiamatelo dall'interno di un hook, né da un callback di configurazione come `CUSTOM_ELEMENT_HANDLING.tagNameCheck` o `attributeNameCheck`. Questi callback vengono eseguiti _nel mezzo_ di un passaggio di sanitizzazione attivo.

Una chiamata annidata a `sanitize()` rilegge la configurazione che le viene passata e, così facendo, **sostituisce la configurazione che il passaggio esterno sta ancora utilizzando**. Il resto del documento esterno viene quindi sanitizzato con la configurazione della chiamata annidata invece che con la vostra. Poiché la chiamata annidata viene tipicamente eseguita con la configurazione predefinita, una allow-list `ALLOWED_TAGS` rigorosa può silenziosamente tornare ad ampliarsi a quella predefinita a metà documento, senza errori né avvisi.

Se avete bisogno di sanitizzare markup annidato, ad esempio un frammento HTML contenuto in un valore di attributo, avete due opzioni sicure. O impostate la vostra configurazione una sola volta con [`DOMPurify.setConfig`](#persistent-configuration) invece di passarla a ogni chiamata, poiché una configurazione persistente è condivisa dalla chiamata annidata e rimane in vigore per l'intero passaggio; oppure raccogliete i frammenti durante l'hook e sanitizzateli con una chiamata separata a `sanitize()` _dopo_ che quella esterna è terminata.

## Configurazione Rimossa

| Opzione          | Da | Nota                     |
| --------------- | ----- | ------------------------ |
| SAFE_FOR_JQUERY | 2.1.0 | Nessuna sostituzione richiesta. |

## Integrazione Continua

Attualmente utilizziamo GitHub Actions in combinazione con Playwright. Questo ci consente di confermare a ogni commit che tutto funzioni nei browser moderni pertinenti, e un workflow separato, pianificato e attivato al merge, riesegue la suite su snapshot di motori più vecchi, così anche le rotture su browser obsoleti vengono rilevate. Consultate i log di build qui: https://github.com/cure53/DOMPurify/actions

Potete inoltre eseguire test locali lanciando `npm run test`.

Tutti i commit pertinenti saranno firmati con la chiave `0x24BB6BF4` per una maggiore sicurezza (dall'8 aprile 2016).

### Sviluppo e contributi

#### Installazione (`npm i`)

Supportiamo ufficialmente `npm`. Il workflow di GitHub Actions è configurato per installare le dipendenze usando `npm`. Quando si utilizza una versione deprecata di `npm`, non possiamo garantire completamente le versioni delle dipendenze installate, il che potrebbe portare a problemi imprevisti.

#### Script

Utilizziamo ESLint tramite `xo` come parte del nostro workflow pre-commit per contribuire a garantire la coerenza del codice. Inoltre, usiamo [Prettier](https://github.com/prettier/prettier) per la formattazione del codice sorgente e dei Markdown, e gli asset in `/dist` vengono generati tramite `rollup`.

Questi sono i nostri script npm:

- `npm run dev` per generare il bundle UMD non minimizzato mentre osserva le modifiche ai sorgenti
- `npm run test` per eseguire il lint dei sorgenti, i test tramite jsdom e i test browser in Chromium via Playwright
  - `npm run test:jsdom` per eseguire solo i test tramite jsdom
  - `npm run test:happydom` per eseguire la suite tramite happy-dom (un ambiente non supportato; mantenuto come controllo di robustezza, non come promessa di compatibilità)
  - `npm run test:browser` per eseguire solo i test tramite Playwright
  - `npm run test:browser:legacy` per eseguire la suite su motori browser più vecchi (puntate `PW_MODULE` a una vecchia installazione di Playwright bloccata; vedi `.github/workflows/legacy-browsers.yml`)
  - `npm run test:ci` per eseguire il flusso di test CI per jsdom e Playwright
  - `npm run test:fuzz` per eseguire un piccolo fuzzer che copre `sanitize()` e CONFIG
- `npm run bench` per eseguire il micro-benchmark jsdom sul `dist/purify.cjs` generato (prima eseguite la build; `--json` e `--compare a.json b.json` supportano confronti A/B tra branch - i risultati sono indicativi, confermate le affermazioni rivolte agli utenti in browser reali)
- `npm run coverage` per generare un bundle instrumentato, eseguire la suite jsdom e scrivere un report locale HTML di copertura di righe/branch in `coverage/index.html` (solo ambito jsdom, non eseguito in CI)
  - `npm run build:cov` per generare solo il bundle di copertura instrumentato
- `npm run lint` per eseguire il lint dei sorgenti usando ESLint tramite xo
- `npm run format` per formattare i sorgenti JavaScript/TypeScript e Markdown con Prettier
  - `npm run format:js` per formattare solo i sorgenti JavaScript/TypeScript
  - `npm run format:md` per formattare solo i file Markdown
- `npm run build` per generare le dichiarazioni di tipo e i bundle di distribuzione, quindi correggere e ripulire i tipi generati
  - `npm run build:types` per emettere solo i file di dichiarazione TypeScript
  - `npm run build:rollup` per generare tutti i bundle Rollup
  - `npm run build:umd` per generare solo un bundle UMD non minimizzato
  - `npm run build:umd:min` per generare solo un bundle UMD minimizzato
  - `npm run build:es` per generare solo il bundle del modulo ES
  - `npm run build:cjs` per generare solo il bundle CommonJS
  - `npm run build:fix-types` per post-elaborare i file di tipo generati
  - `npm run build:cleanup` per ripulire l'output temporaneo dei tipi generati
- `npm run verify-typescript` per eseguire lo script di verifica TypeScript
- `npm run commit-amend-build` per eseguire lo script helper del maintainer per modificare l'output di build

Nota: tutti gli script vengono eseguiti tramite `npm run <script>`.

Ci sono altri script npm ma servono principalmente per l'integrazione con CI o sono pensati per essere "privati", ad esempio per modificare i file di distribuzione a ogni commit.

## Mailing List di Sicurezza

Manteniamo una mailing list che notifica ogni volta che viene pubblicata una release **critica per la sicurezza** di DOMPurify. Ciò significa che, se qualcuno trova un bypass e lo correggiamo con una release (cosa che accade sempre quando viene trovato un bypass), una mail verrà inviata a quella lista. Questo avviene di solito entro pochi minuti o poche ore dalla scoperta di un bypass. La lista può essere sottoscritta qui:

[https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security](https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security)

Le release di funzionalità non verranno annunciate su questa lista.

## Chi ha contribuito?

Molte persone hanno aiutato DOMPurify a diventare ciò che è oggi, e meritano di essere riconosciute!

[gnyselcuk](https://github.com/gnyselcuk), [leechristensen](https://github.com/leechristensen),[offset](https://github.com/offset), [Bankde](https://github.com/Bankde), [lukewarlow](https://github.com/lukewarlow), [DEMON1A](https://github.com/DEMON1A), [fg0x0](https://github.com/fg0x0), [kodareef5](https://github.com/kodareef5), [DavidOliver](https://github.com/DavidOliver), [1Jesper1](https://github.com/1Jesper1), [bencalif](https://github.com/bencalif), [trace37labs](https://github.com/trace37labs), [eddieran](https://github.com/eddieran), [christos-eth](https://github.com/christos-eth), [researchatfluidattacks](https://github.com/researchatfluidattacks), [frevadiscor](https://github.com/frevadiscor), [Rotzbua](https://github.com/Rotzbua), [binhpv](https://github.com/binhpv), [MariusRumpf](https://github.com/MariusRumpf), [prasadrajandran](https://github.com/prasadrajandran), [Cybozu 💛💸](https://github.com/cybozu), [hata6502 💸](https://github.com/hata6502), [openclaw 💸](https://github.com/openclaw), [intra-mart-dh 💸](https://github.com/intra-mart-dh), [nelstrom ❤️](https://github.com/nelstrom), [hash_kitten ❤️](https://twitter.com/hash_kitten), [kevin_mizu ❤️](https://twitter.com/kevin_mizu), [icesfont ❤️](https://github.com/icesfont), [reduckted ❤️](https://github.com/reduckted), [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), [davecardwell](https://github.com/davecardwell), [Develop-KIM](https://github.com/Develop-KIM), [asamuzaK](https://github.com/asamuzaK), [fishjojo1 ❤️](https://github.com/fishjojo1), [Rikuxx0](https://github.com/Rikuxx0), [donmccurdy](https://github.com/donmccurdy), [hhk-png](https://github.com/hhk-png), [elrion018](https://github.com/elrion018), [michalnieruchalski-tiugo](https://github.com/michalnieruchalski-tiugo), [reey](https://github.com/reey), [KanhaKanhaiya](https://github.com/KanhaKanhaiya), [odaysec](https://github.com/odaysec), [Akokonunes](https://github.com/Akokonunes), [alirezarouhbakhsh](https://github.com/alirezarouhbakhsh), [Jaybhade](https://github.com/Jaybhade) e in particolare [@securitymb ❤️](https://twitter.com/securitymb) e [@masatokinugawa ❤️](https://twitter.com/masatokinugawa)

Categorie