summaryrefslogtreecommitdiff
path: root/src/content/DocumentCSP.js
blob: 9991d4f3f63136355626f93049dc650bf5769a35 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'use strict';

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

  apply(capabilities, embedding = CSP.isEmbedType(this.document.contentType)) {
    let {document} = this;
    if (!(document instanceof HTMLDocument)) {
      // this is not HTML, hence we cannot inject a <meta> CSP
      if (!capabilites.has("script")) {
        // safety net for XML (especially SVG) documents
        document.defaultView.addEventListener("beforescriptexecute",
          e => e.preventDefault(), true);
      }
      return false;
    }
    let csp = this.builder;
    let blocker = csp.buildFromCapabilities(capabilities, embedding);
    if (!blocker) return true;

    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 root = document.documentElement;
    let {head} = document;
    let parent = head ||
      (root instanceof HTMLElement
        ? document.documentElement.appendChild(createHTMLElement("head"))
        : root);

    try {
      parent.insertBefore(meta, parent.firstElementChild);
      debug(`Failsafe <meta> CSP inserted in %s: "%s"`, document.URL, header.value);
      meta.remove();
      if (!head) parent.remove();
    } catch (e) {
      error(e, "Error inserting CSP %s in %s", document.URL, header && header.value);
      return false;
    }
    return true;
  }

}