summaryrefslogtreecommitdiff
path: root/src/bg/ChildPolicies.js
blob: e8608ad84f74cb900e849b3c2f0a541765b806e4 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"use strict";
{
  let marker = JSON.stringify(uuid());
  let allUrls = ["<all_urls>"];

  let Scripts = {
    references: new Set(),
    opts: {
      js: [{}],
      allFrames: true,
      matchAboutBlank: true,
      runAt: "document_start"
    },
    async init() {
      let opts = Object.assign({}, this.opts);
      opts.js = [{file: "/content/dynamicNS.js"}];
      opts.matches = allUrls;
      delete opts.excludedMatches;
      this._stubScript = await browser.contentScripts.register(opts);

      this.init = this.forget;
    },
    forget() {
      for (let script of [...this.references]) {
        script.unregister();
        this.references.delete(script);
      }
    },
    debug: false,
    trace(code) {
      return this.debug
        ? `console.debug("Executing child policy on %s", document.URL, ${JSON.stringify(code)});${code}`
        : code
        ;
    },
    async register(code, matches, excludeMatches) {
      debug("Registering child policy.", code, matches, excludeMatches);
      if (!matches.length) return;
      try {
        let opts = Object.assign({}, this.opts);
        opts.js[0].code = this.trace(code);
        opts.matches = matches;
        if (excludeMatches && excludeMatches.length) {
          opts.excludeMatches = excludeMatches;
        }
        this.references.add(await browser.contentScripts.register(opts));
      } catch (e) {
        error(e);
      }
    },

    buildPerms(perms, finalizeSetup = false) {
      if (typeof perms !== "string") {
        perms = JSON.stringify(perms);
      }
      return finalizeSetup
        ? `ns.setup(${perms}, ${marker});`
        : `ns.config.CURRENT = ${perms};`
        ;
    }
  };

  let flatten = arr => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);

  let protocolRx = /^(\w+):/i;
  let pathRx = /(?:[^:/]\/|:\/{3})$/;
  let portRx = /:\d+(?=\/|$)/;
  let validMatchPatternRx = /^(?:\*|(?:http|ws|ftp)s?|file):\/\/(?:\*\.)?(?:[\w\u0100-\uf000][\w\u0100-\uf000.-]*)?\/(\*|[^*]*)$/;

  let siteKey2MatchPattern = site => {
    let hasProtocol = site.match(protocolRx);
    let mp = site;
    if (hasProtocol) {
      mp = Sites.cleanUrl(mp);
      if (!mp) return false;
    } else {
      let protocol = Sites.isSecureDomainKey(site) ? "https://" : "*://";
      let hostname = Sites.toggleSecureDomainKey(site, false).replace(portRx, '');
      if (!tld.preserveFQDNs) hostname = tld.normalize(hostname);
      mp = `${protocol}*.${hostname}`;
      if (!hostname.includes("/")) mp += "/";
    }

    return validMatchPatternRx.test(mp) && (
      mp.endsWith("/") ? `${mp}*` : [mp, `${mp}?*`, `${mp}#*`]);
  };

  let withFQDNs = patterns => {
    return tld.preserveFQDNs ? patterns : patterns.concat(
      patterns.map(p => p.replace(/^(?:\w+|\*):\/\/[^/]*[^./]/, '$&.'))
    );
  }

  let siteKeys2MatchPatterns = keys =>
    keys && withFQDNs(flatten(keys.map(siteKey2MatchPattern))
      .filter(p => !!p))
      || [];

  var ChildPolicies = {
    async storeTabInfo(tabId, info) {
      try {
        let preamble = info ? `${marker} + ${JSON.stringify(JSON.stringify([info]))} + ${marker} + "," + ` : "";
        await browser.tabs.executeScript(tabId, {
          code: `window.name = ${preamble}window.name.split(${marker} + ",").pop();`,
          allFrames: true,
          matchAboutBlank: true,
          runAt: "document_start",
        });
      } catch (e) {
        error(e);
      }
    },
    async update(policy, debug) {
      if (debug !== "undefined") Scripts.debug = debug;

      await Scripts.init();

      if (!policy.enforced) {
        await Scripts.register(`ns.setup(null, ${marker});`, allUrls);
        return;
      }

      let serialized = policy.dry ? policy.dry(true) : policy;
      let permsMap = new Map();
      let trusted = JSON.stringify(serialized.TRUSTED);
      let untrusted = JSON.stringify(serialized.UNTRUSTED);
      let presets = {
        trusted,
        untrusted,
        temp: trusted
      };
      // map presets to site keys
      for (let [container, perms] of Object.entries(presets)) {
        let newKeys = serialized.sites[container];
        if (!(newKeys && newKeys.length)) continue;
        let keys = permsMap.get(perms);
        if (keys) {
          newKeys = keys.concat(newKeys);
        }
        permsMap.set(perms, newKeys);
      }
      // map custom permissions to site keys
      for (let [key, perms] of Object.entries(serialized.sites.custom)) {
        let permsKey = JSON.stringify(perms);
        let keys = permsMap.get(permsKey);
        if (keys) {
          keys.push(key);
        } else {
          permsMap.set(permsKey, [key]);
        }
      }

      // compute exclusions
      let permsMapEntries = [...permsMap];
      let excludeMap = new Map();

      for (let [perms, keys] of permsMapEntries) {
        excludeMap.set(perms, siteKeys2MatchPatterns(flatten(
          permsMapEntries.filter(([other]) => other !== perms)
            .map(([otherPerms, otherKeys]) => otherKeys))
              .filter(k => k && k.includes("/") && keys.some(by => Sites.isImplied(k, by)))
          ));
      }

      // register new content scripts
      for (let [perms, keys] of [...permsMap]) {
        await Scripts.register(Scripts.buildPerms(perms), siteKeys2MatchPatterns(keys), excludeMap.get(perms));
      }
      await Scripts.register(Scripts.buildPerms(serialized.DEFAULT, true), allUrls);
    },

    getForDocument(policy, url, context = null) {
      return {
        CURRENT: policy.get(url, context).perms.dry(),
        DEFAULT: policy.DEFAULT.dry(),
        MARKER: marker
      };
    },

    async updateFrame(tabId, frameId, perms, defaultPreset) {
      let code = Scripts.buildPerms(perms) + Scripts.buildPerms(defaultPreset, true);
      await browser.tabs.executeScript(tabId, {
        code,
        frameId,
        matchAboutBlank: true,
        runAt: "document_start"
      });
    }
  };
}