Giter Club home page Giter Club logo

ng-dompurify's Introduction

NgDompurify

npm bundle size Coverage Status npm version code style: @tinkoff/linters

This library implements DOMPurify as Angular Sanitizer or Pipe. It delegates sanitizing to DOMPurify and supports the same configuration. See DOMPurify.

Read more about Sanitization in Angular and how ng-dompurify works in this article.

Install

npm install @tinkoff/ng-dompurify

If you do not have dompurify in your package, install also:

npm install dompurify
npm install --save-dev @types/dompurify

How to use

Either use pipe to sanitize your content when binding to [innerHTML] or use NgDompurifySanitizer service manually.

import {NgDompurifyModule} from '@tinkoff/ng-dompurify';

@NgModule({
  imports: [NgDompurifyModule],
})
export class MyModule {}

As a pipe:

<div [innerHtml]="value | dompurify"></div>

As a service:

import {SecurityContext} from '@angular/core';
import {NgDompurifySanitizer} from '@tinkoff/ng-dompurify';

@Component({})
export class MyComponent {
  constructor(private readonly dompurifySanitizer: NgDompurifySanitizer) {}

  purify(value: string): string {
    return this.dompurifySanitizer.sanitize(SecurityContext.HTML, value);
  }
}

You can also substitute Angular Sanitizer with DOMPurify so it is automatically used all the time:

import {NgModule, Sanitizer} from '@angular/core';
import {NgDompurifySanitizer} from '@tinkoff/ng-dompurify';
// ...

@NgModule({
  // ...
  providers: [
    {
      provide: Sanitizer,
      useClass: NgDompurifySanitizer,
    },
  ],
  // ...
})
export class AppModule {}

Configuring

Config for NgDompurifySanitizer or NgDompurifyDomSanitizer can be provided using token DOMPURIFY_CONFIG. NgDompurifyPipe supports passing DOMPurify config as an argument to override config from DI.

import {NgModule, Sanitizer} from '@angular/core';
import {NgDompurifySanitizer, DOMPURIFY_CONFIG} from '@tinkoff/ng-dompurify';
// ...

@NgModule({
  // ...
  providers: [
    {
      provide: Sanitizer,
      useClass: NgDompurifySanitizer,
    },
    {
      provide: DOMPURIFY_CONFIG,
      useValue: {FORBID_ATTR: ['id']},
    },
  ],
  // ...
})
export class AppModule {}

CSS sanitization

DOMPurify does not support sanitizing CSS. Angular starting version 10 dropped CSS sanitation as something that presents no threat in supported browsers. You can still provide a handler to sanitize CSS rules values upon binding if you want to:

import {NgModule, Sanitizer} from '@angular/core';
import {NgDompurifySanitizer, SANITIZE_STYLE} from '@tinkoff/ng-dompurify';

@NgModule({
  // ...
  providers: [
    {
      provide: Sanitizer,
      useClass: NgDompurifySanitizer,
    },
    {
      provide: SANITIZE_STYLE,
      useValue: yourImplementation, // <---
    },
  ],
  // ...
})
export class AppModule {}

Hooks

DOMPurify supports various hooks. You can provide them using DOMPURIFY_HOOKS token:

import {NgModule, Sanitizer} from '@angular/core';
import {NgDompurifySanitizer, DOMPURIFY_HOOKS, SANITIZE_STYLE} from '@tinkoff/ng-dompurify';

@NgModule({
  // ...
  providers: [
    {
      provide: Sanitizer,
      useClass: NgDompurifySanitizer,
    },
    {
      provide: SANITIZE_STYLE,
      useValue: yourImplementation,
    },
    {
      provide: DOMPURIFY_HOOKS,
      useValue: [
        {
          name: 'beforeSanitizeAttributes',
          hook: (node: Element) => {
            node.removeAttribute('id');
          },
        },
      ],
    },
  ],
  // ...
})
export class AppModule {}

Maintained

@tinkoff/ng-dompurify is a part of Taiga UI libraries family which is backed and used by a large enterprise. This means you can rely on timely support and continuous development.

License

๐Ÿ†“ Feel free to use our library in your commercial and private applications

All @tinkoff/ng-dompurify packages are covered by Apache 2.0

Read more about this license here

Demo

You can see live demo here: https://stackblitz.com/github/TinkoffCreditSystems/ng-dompurify/tree/master/projects/demo

ng-dompurify's People

Contributors

dependabot[bot] avatar marsibarsi avatar splincode avatar waterplea avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-dompurify's Issues

Describe advantages in readme

Readme tells about easy drop-in replacement angular sanitizer by this package. But readme doesn't suggest - have I any reasons or cases to do this switch? If I already implements my functionality with default sanitizer? If I starts new project? Any other cases? Please add some useful info for easy decision make: use this lib or not?

Routing problem when using hooks

Hi,

I recently tried using hooks in app.module but it creates a collateral effect : the routing isn't working anymore ! Weird problem. The hooks is working and the link is not sanitized but as soon as I add this in app.module provider section :

{ provide: DOMPURIFY_HOOKS,
useValue: [
{
name: 'uponSanitizeAttribute',
hook: (node: Element, hookEvt ) => {
if (hookEvt.attrValue.startsWith('functionName('))
hookEvt.forceKeepAttr=true;
},
}
]
}

I get Error in promise Cannot find module ... If I remove those lines, routing works fine.

Thanks

Cannot find module 'dompurify'

๐Ÿž Bug report

Description

After npm install @tinkoff/ng-dompurify - ng serve - I get the error

"Cannot find module 'dompurify'"

image

image

Versions

{
"name": "angular8-scan-poc",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod --base-href /tests/survey/surveyor/2.0/app/",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular-devkit/build-angular": "^0.803.21",
"@angular/animations": "^8.2.14",
"@angular/cdk": "^8.2.3",
"@angular/common": "^8.2.14",
"@angular/compiler": "^8.2.14",
"@angular/core": "^8.2.14",
"@angular/flex-layout": "^8.0.0-beta.27",
"@angular/forms": "^8.2.14",
"@angular/material": "^8.2.3",
"@angular/platform-browser": "^8.2.14",
"@angular/platform-browser-dynamic": "^8.2.14",
"@angular/router": "^8.2.14",
"@tinkoff/ng-dompurify": "^2.0.0",
"caniuse-lite": "^1.0.30001019",
"core-js": "2.6.9",
"hammerjs": "^2.0.8",
"hjson": "^3.2.1",
"npm": "^6.13.4",
"rxjs": "^6.5.4",
"tslib": "^1.10.0",
"zone.js": "^0.9.1"
},
"devDependencies": {
"@angular/cli": "^8.3.21",
"@angular/compiler-cli": "^8.2.14",
"@angular/language-service": "^8.2.14",
"@types/jasmine": "^3.5.0",
"@types/jasminewd2": "^2.0.8",
"@types/node": "^12.12.24",
"codelyzer": "^5.2.1",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.4.1",
"karma-chrome-launcher": "~3.0.0",
"karma-coverage-istanbul-reporter": "~2.0.6",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.5.1",
"protractor": "^5.4.2",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"typescript": "~3.4.0"
}
}

I hope you can help

[BUG] SSR: ReferenceError: SVGStyleElement is not defined

๐Ÿž Bug report

Description

Using the dompurify pipe results in ReferenceError: SVGStyleElement is not defined in Angular Universal environment. It works in the browser.

Reproduction

In order to sanitize styles, I am using this in my AppBrowserModule as mentioned here:

{
    provide: SANITIZE_STYLE,
    useValue: ษต_sanitizeStyle
}

Expected behavior

Error should not be thrown.

Versions

  • OS: Ubuntu 18.04.3 LTS
  • Node: v12.16.1
  • Angular: 8.2.14
  • @tinkoff/ng-dompurify: 2.1.0
  • dompurify: 2.0.8

Please let me know if you need any further information.

Improve workflow

Right now, linting is not forced on code and even unused imports can be committed and pushed. Please add precommit hooks to prevent code quality degradation.

not compatible with Angular Ivy

i have created a project in angular 9 , and added @tinkoff/ng-dompurify and its peer dependencies. when i import it in my app.module.ts i am getting error:
ERROR in node_modules/@tinkoff/ng-dompurify/lib/ng-dompurify.module.d.ts:1:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the library (@tinkoff/ng-dompurify) which declares NgDompurifyModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

1 export declare class NgDompurifyModule {
                       ~~~~~~~~~~~~~~~~~

Error in Angular 8 DOMPurify can only be imported using the 'allowSyntheticDefaultImports' flag

๐Ÿž Bug report

ERROR in app/person/chart/chart.component.ts:13:8 - error TS1259: Module '"../src/main/angular/node_modules/@types/dompurify/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flag

13 import DOMPurify from 'dompurify';
~~~~~~~~~

../node_modules/@types/dompurify/index.d.ts:13:1
13 export = DOMPurify;
~~~~~~~~~~~~~~~~~~~
This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.

Possible Documentation Update

I ran into an issue when using the Ivy compiler that was causing the dompurifer not to work if the sanitized html has embeded styles.

I posted this bug ticket on the angular site:
angular/angular#36794

And was provided with the solution to change from using DomSanitizer to use Sanitizer instead:

@NgModule({
    // ...
    providers: [
        {
            provide: DomSanitizer,
            useClass: NgDompurifyDomSanitizer,
        },
    ],
    // ...
})

to be

@NgModule({
    // ...
    providers: [
        {
            provide: Sanitizer,
            useClass: NgDompurifyDomSanitizer,
        },
    ],
    // ...
})

I'm not sure if there are any features in the ng-dompurify code that this will break but its working for me so I thought, maybe the documentation for ng-dompurify may need to be updated to match.

Needed to cast html content via template literals

I tried to implement the dompurify in order to use inline styles for a blog that i created, the data was obtained directly from the server:

    this.service.getBlog(url).pipe(
        take(1),
       ) .subscribe(  res => this.data = res; );

and passed via

 <div class="blog" @items>
        <h1>{{data.title | uppercase}}</h1>
        <div class="blog__content" [innerHTML]="data.html"></div>
   </div>

the app.module is implemented this way:

...
  providers: [
      {
      provide: DomSanitizer,
      useClass: NgDompurifyDomSanitizer,
    },
    {
      provide: SANITIZE_STYLE,
      useValue: ษต_sanitizeStyle,
    },
  ],
...

for some reason the sanitizer for [innerHTML] was deleting my inline styles but when i reproduce it in a stackblitz, the sanitizer works correctly.

https://stackblitz.com/edit/dompurify-example

i found that the solution was wrap the html property in a template literal ( as i did it in stackblitz):

    this.service.getBlog(url).pipe(
        take(1),
       ) .subscribe(  res => {
        this.data = res; 
        this.html = `${this.data.html}`;
        });

  ...
 <div class="blog" @items>
        <h1>{{data.title | uppercase}}</h1>
        <div class="blog__content" [innerHTML]="html"></div>
   </div>

Do you know why doesn't work with the object property option? It works as intended or it's some type of bug?

Cheers!

[BUG] Version range of DOMPurify is invalid and does not work with latest DOMPurify on SSR

๐Ÿž Bug report

Description

ng-dompurify is incompatible with [email protected] (latest at the time of writing) and [email protected] in SSR mode, but [email protected] works as expected. It seems that the actual underlying method to retrieve the parentNode getter is invalid to work with domino, the DOM emulation used in SSR setups, and was changed in the diff below.

https://github.com/cure53/DOMPurify/compare/2.2.4..2.2.6

The error is like this:

 An error was catched by the global error handler.
 TypeError: getParentNode is not a function
    at _sanitizeElements (.../main.js:2630:26)
    at Function.DOMPurify.sanitize (.../main.js:2943:11)
    at NgDompurifySanitizer.sanitize (.../main.js:67707:30

Reproduction

Install latest ng-dompurify and dompurify@>=2.2.5, and use it in a SSR setup on platform-server.

Expected behavior

This should work as expected

Versions

  • OS: [e.g. iOS]: Node
  • Browser [e.g. chrome, safari]: Node
  • Angular [e.g. 8]: 11.x.x

Additional context

Using SSR is important to reproduce the error, since it does not define the parentNode as a proper property using Object.defineProperty, thus causing the invalid behavior in DOMPurify. Maybe this would be relevant to inform the dompurify maintainer about this issue, but this dependency version range should nonetheless be excluded from this package. This could also be reverted if a later version of domino changes its property definition method.

I managed to fix this issue by specifying the following in my app's package.json:

{
  // ...
  "dependencies": {
    // ...
    "dompurify": "^2.0.0 <2.2.5",
    // ...
  }
}

[BUG] Something wrong with special svg icon

๐Ÿž Bug report

Description

https://stackblitz.com/edit/angular-vynurc-jtnqw4?file=src%2Fstyles.less,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts,src%2Findex.html

Invalid for

<svg xmlns="http://www.w3.org/2000/svg" width="440" height="232" viewBox="0 0 440 232" fill="none">
    <mask id="path-1-outside-1" maskUnits="userSpaceOnUse" x="-2" y="-2" width="444" height="235" fill="black">
        <rect fill="white" x="-2" y="-2" width="444" height="235"/>
        <path fill-rule="evenodd" clip-rule="evenodd" d="M440 4C440 1.79086 438.209 0 436 0H4C1.79086 0 0 1.79087 0 4.00001V227C0 229.209 1.79086 231 4 231H436C438.209 231 440 229.209 440 227V4ZM117 4.00195C112.582 4.00195 109 7.58367 109 12.002V219.002C109 223.42 112.582 227.002 117 227.002H324C328.418 227.002 332 223.42 332 219.002V12.002C332 7.58368 328.418 4.00195 324 4.00195H117Z"/>
    </mask>
    <path fill-rule="evenodd" clip-rule="evenodd" d="M440 4C440 1.79086 438.209 0 436 0H4C1.79086 0 0 1.79087 0 4.00001V227C0 229.209 1.79086 231 4 231H436C438.209 231 440 229.209 440 227V4ZM117 4.00195C112.582 4.00195 109 7.58367 109 12.002V219.002C109 223.42 112.582 227.002 117 227.002H324C328.418 227.002 332 223.42 332 219.002V12.002C332 7.58368 328.418 4.00195 324 4.00195H117Z" fill="black" fill-opacity="0.24"/>
    <path d="M4 2H436V-2H4V2ZM2 227V4.00001H-2V227H2ZM436 229H4V233H436V229ZM438 4V227H442V4H438ZM111 12.002C111 8.68824 113.686 6.00195 117 6.00195V2.00195C111.477 2.00195 107 6.4791 107 12.002H111ZM111 219.002V12.002H107V219.002H111ZM117 225.002C113.686 225.002 111 222.316 111 219.002H107C107 224.525 111.477 229.002 117 229.002V225.002ZM324 225.002H117V229.002H324V225.002ZM330 219.002C330 222.316 327.314 225.002 324 225.002V229.002C329.523 229.002 334 224.525 334 219.002H330ZM330 12.002V219.002H334V12.002H330ZM324 6.00195C327.314 6.00195 330 8.68825 330 12.002H334C334 6.47911 329.523 2.00195 324 2.00195V6.00195ZM117 6.00195H324V2.00195H117V6.00195ZM436 233C439.314 233 442 230.314 442 227H438C438 228.105 437.105 229 436 229V233ZM-2 227C-2 230.314 0.686285 233 4 233V229C2.89543 229 2 228.105 2 227H-2ZM436 2C437.105 2 438 2.89543 438 4H442C442 0.686294 439.314 -2 436 -2V2ZM4 -2C0.686287 -2 -2 0.686302 -2 4.00001H2C2 2.89543 2.89543 2 4 2V-2Z" fill="white" mask="url(#path-1-outside-1)"/>
</svg>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.