summaryrefslogtreecommitdiffstats
path: root/browser/extensions/webcompat/experiment-apis/trackingProtection.js
blob: 0f5d9a4233c8290a6dc171796bc64d008c9b1e5c (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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/* global ExtensionAPI, ExtensionCommon, ExtensionParent, Services, XPCOMUtils */

// eslint-disable-next-line mozilla/reject-importGlobalProperties
XPCOMUtils.defineLazyGlobalGetters(this, ["URL", "ChannelWrapper"]);

class AllowList {
  constructor(id) {
    this._id = id;
  }

  setShims(patterns, notHosts) {
    this._shimPatterns = patterns;
    this._shimMatcher = new MatchPatternSet(patterns || []);
    this._shimNotHosts = notHosts || [];
    return this;
  }

  setAllows(patterns, hosts) {
    this._allowPatterns = patterns;
    this._allowMatcher = new MatchPatternSet(patterns || []);
    this._allowHosts = hosts || [];
    return this;
  }

  shims(url, topHost) {
    return (
      this._shimMatcher?.matches(url) && !this._shimNotHosts?.includes(topHost)
    );
  }

  allows(url, topHost) {
    return (
      this._allowMatcher?.matches(url) && this._allowHosts?.includes(topHost)
    );
  }
}

class Manager {
  constructor() {
    this._allowLists = new Map();
  }

  _getAllowList(id) {
    if (!this._allowLists.has(id)) {
      this._allowLists.set(id, new AllowList(id));
    }
    return this._allowLists.get(id);
  }

  _ensureStarted() {
    if (this._classifierObserver) {
      return;
    }

    this._unblockedChannelIds = new Set();
    this._channelClassifier = Cc[
      "@mozilla.org/url-classifier/channel-classifier-service;1"
    ].getService(Ci.nsIChannelClassifierService);
    this._classifierObserver = {};
    this._classifierObserver.observe = (subject, topic, data) => {
      switch (topic) {
        case "http-on-stop-request": {
          const { channelId } = subject.QueryInterface(Ci.nsIIdentChannel);
          this._unblockedChannelIds.delete(channelId);
          break;
        }
        case "urlclassifier-before-block-channel": {
          const channel = subject.QueryInterface(
            Ci.nsIUrlClassifierBlockedChannel
          );
          const { channelId, url } = channel;
          let topHost;
          try {
            topHost = new URL(channel.topLevelUrl).hostname;
          } catch (_) {
            return;
          }
          // If anti-tracking webcompat is disabled, we only permit replacing
          // channels, not fully unblocking them.
          if (Manager.ENABLE_WEBCOMPAT) {
            // if any allowlist unblocks the request entirely, we allow it
            for (const allowList of this._allowLists.values()) {
              if (allowList.allows(url, topHost)) {
                this._unblockedChannelIds.add(channelId);
                channel.allow();
                return;
              }
            }
          }
          // otherwise, if any allowlist shims the request we say it's replaced
          for (const allowList of this._allowLists.values()) {
            if (allowList.shims(url, topHost)) {
              this._unblockedChannelIds.add(channelId);
              channel.replace();
              return;
            }
          }
          break;
        }
      }
    };
    Services.obs.addObserver(this._classifierObserver, "http-on-stop-request");
    this._channelClassifier.addListener(this._classifierObserver);
  }

  stop() {
    if (!this._classifierObserver) {
      return;
    }

    Services.obs.removeObserver(
      this._classifierObserver,
      "http-on-stop-request"
    );
    this._channelClassifier.removeListener(this._classifierObserver);
    delete this._channelClassifier;
    delete this._classifierObserver;
  }

  wasChannelIdUnblocked(channelId) {
    return this._unblockedChannelIds?.has(channelId);
  }

  allow(allowListId, patterns, hosts) {
    this._ensureStarted();
    this._getAllowList(allowListId).setAllows(patterns, hosts);
  }

  shim(allowListId, patterns, notHosts) {
    this._ensureStarted();
    this._getAllowList(allowListId).setShims(patterns, notHosts);
  }

  revoke(allowListId) {
    this._allowLists.delete(allowListId);
  }
}
var manager = new Manager();

function getChannelId(context, requestId) {
  const wrapper = ChannelWrapper.getRegisteredChannel(
    requestId,
    context.extension.policy,
    context.xulBrowser.frameLoader.remoteTab
  );
  return wrapper?.channel?.QueryInterface(Ci.nsIIdentChannel)?.channelId;
}

var dFPIPrefName = "network.cookie.cookieBehavior";
var dFPIPbPrefName = "network.cookie.cookieBehavior.pbmode";
var dFPIStatus;
function updateDFPIStatus() {
  dFPIStatus = {
    nonPbMode: 5 == Services.prefs.getIntPref(dFPIPrefName),
    pbMode: 5 == Services.prefs.getIntPref(dFPIPbPrefName),
  };
}

this.trackingProtection = class extends ExtensionAPI {
  onShutdown(isAppShutdown) {
    if (manager) {
      manager.stop();
    }
    Services.prefs.removeObserver(dFPIPrefName, updateDFPIStatus);
    Services.prefs.removeObserver(dFPIPbPrefName, updateDFPIStatus);
  }

  getAPI(context) {
    Services.prefs.addObserver(dFPIPrefName, updateDFPIStatus);
    Services.prefs.addObserver(dFPIPbPrefName, updateDFPIStatus);
    updateDFPIStatus();

    return {
      trackingProtection: {
        async shim(allowListId, patterns, notHosts) {
          manager.shim(allowListId, patterns, notHosts);
        },
        async allow(allowListId, patterns, hosts) {
          manager.allow(allowListId, patterns, hosts);
        },
        async revoke(allowListId) {
          manager.revoke(allowListId);
        },
        async wasRequestUnblocked(requestId) {
          if (!manager) {
            return false;
          }
          const channelId = getChannelId(context, requestId);
          if (!channelId) {
            return false;
          }
          return manager.wasChannelIdUnblocked(channelId);
        },
        async isDFPIActive(isPrivate) {
          if (isPrivate) {
            return dFPIStatus.pbMode;
          }
          return dFPIStatus.nonPbMode;
        },
      },
    };
  }
};

XPCOMUtils.defineLazyPreferenceGetter(
  Manager,
  "ENABLE_WEBCOMPAT",
  "privacy.antitracking.enableWebcompat",
  false
);