Implementing csp trusted type in angular universal

132 Views Asked by At

I was trying to create a trusted type policy for my web application, it seems to be working as expected for client side rendering but for SSR, a default trusted type policy is already being creating and I'm getting the below error

image showing error in console

But as far as I know this default policy is not set anywhere except in my trusted-types.service.ts file which looks something like this

import { Injectable, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { UtilitiesService } from '@magneto/core';
import { TrustedTypePolicyFactory, trustedTypes } from 'trusted-types';

@Injectable({
  providedIn: 'root',
})
export class TrustedTypesService {
  tt: any;

  constructor(private domSanitizer: DomSanitizer, private utilitiesService: UtilitiesService) {}

  createTrustedTypePolicy() {
    let trustedTypePolicyFactory;
    if (this.utilitiesService.isServer()) {
      trustedTypePolicyFactory = trustedTypes;
    } else {
      trustedTypePolicyFactory = window.trustedTypes as TrustedTypePolicyFactory;
    }
    if (trustedTypePolicyFactory) {
      this.tt = trustedTypePolicyFactory.createPolicy('policy1', {
        createHTML: (string) => this.domSanitizer.sanitize(SecurityContext.HTML, string)!,
        createScriptURL: (string) => this.domSanitizer.sanitize(SecurityContext.URL, string)!,
        createScript: (string) => string,
      });
      trustedTypePolicyFactory.createPolicy('default', {
        createHTML: (string) => this.domSanitizer.sanitize(SecurityContext.HTML, string)!,
        createScriptURL: (string) => {
          console.log(this.domSanitizer.sanitize(SecurityContext.URL, string));
          return this.domSanitizer.sanitize(SecurityContext.URL, string)!;
        },
        createScript: (string) => string,
      });
    }
  }
}

so wanted to know if node server sets this globally somehow when it encounters trusted type directive in the csp

0

There are 0 best solutions below