summaryrefslogtreecommitdiff
path: root/src/content/DocumentCSP.js
blob: 7632ce7d8dd964a32eb9c47af30544b095dde6c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
'use strict';

class DocumentCSP {
  constructor(document) {
    this.document = document;
    this.builder = new CapsCSP();
  }

  apply(capabilities, embedding = CSP.isEmbedType(this.document.contentType)) {
    let csp = this.builder;
    let blocker = csp.buildFromCapabilities(capabilities, embedding);
    if (!blocker) return;

    let document = this.document;
    let createHTMLElement =
      tagName => document.createElementNS("http://www.w3.org/1999/xhtml", tagName);

    let header = csp.asHeader(blocker);
    let meta = createHTMLElement("meta");
    meta.setAttribute("http-equiv", header.name);
    meta.setAttribute("content", header.value);
    let {head} = document;
    let parent = head ||
      document.documentElement.appendChild(createHTMLElement("head"));

    try {
      parent.insertBefore(meta, parent.firstChild);
      debug(`Failsafe <meta> CSP inserted in the DOM: "%s"`, header.value);
      meta.remove();
      if (!head) parent.remove();
    } catch (e) {
      error(e, "Error inserting CSP %s in the DOM", header && header.value);
    }
  }

}