summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/parent/ext-webRequest.js
blob: 4f0ea90abde59963ca1cd19e01714a9a6ea00383 (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
/* 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";

ChromeUtils.defineESModuleGetters(this, {
  WebRequest: "resource://gre/modules/WebRequest.sys.mjs",
});

var { parseMatchPatterns } = ExtensionUtils;

// The guts of a WebRequest event handler.  Takes care of converting
// |details| parameter when invoking listeners.
function registerEvent(
  extension,
  eventName,
  fire,
  filter,
  info,
  remoteTab = null
) {
  let listener = async data => {
    let event = data.serialize(eventName);
    if (data.registerTraceableChannel) {
      // If this is a primed listener, no tabParent was passed in here,
      // but the convert() callback later in this function will be called
      // when the background page is started.  Force that to happen here
      // after which we'll have a valid tabParent.
      if (fire.wakeup) {
        await fire.wakeup();
      }
      data.registerTraceableChannel(extension.policy, remoteTab);
    }

    return fire.sync(event);
  };

  let filter2 = {};
  if (filter.urls) {
    let perms = new MatchPatternSet([
      ...extension.allowedOrigins.patterns,
      ...extension.optionalOrigins.patterns,
    ]);

    filter2.urls = parseMatchPatterns(filter.urls);

    if (!perms.overlapsAll(filter2.urls)) {
      Cu.reportError(
        "The webRequest.addListener filter doesn't overlap with host permissions."
      );
    }
  }
  if (filter.types) {
    filter2.types = filter.types;
  }
  if (filter.tabId !== undefined) {
    filter2.tabId = filter.tabId;
  }
  if (filter.windowId !== undefined) {
    filter2.windowId = filter.windowId;
  }
  if (filter.incognito !== undefined) {
    filter2.incognito = filter.incognito;
  }

  let blockingAllowed = extension.hasPermission("webRequestBlocking");

  let info2 = [];
  if (info) {
    for (let desc of info) {
      if (desc == "blocking" && !blockingAllowed) {
        // This is usually checked in the child process (based on the API schemas, where these options
        // should be checked with the "webRequestBlockingPermissionRequired" postprocess property),
        // but it is worth to also check it here just in case a new webRequest has been added and
        // it has not yet using the expected postprocess property).
        Cu.reportError(
          "Using webRequest.addListener with the blocking option " +
            "requires the 'webRequestBlocking' permission."
        );
      } else {
        info2.push(desc);
      }
    }
  }

  let listenerDetails = {
    addonId: extension.id,
    policy: extension.policy,
    blockingAllowed,
  };
  WebRequest[eventName].addListener(listener, filter2, info2, listenerDetails);

  return {
    unregister: () => {
      WebRequest[eventName].removeListener(listener);
    },
    convert(_fire, context) {
      fire = _fire;
      remoteTab = context.xulBrowser.frameLoader.remoteTab;
    },
  };
}

function makeWebRequestEventAPI(context, event, extensionApi) {
  return new EventManager({
    context,
    module: "webRequest",
    event,
    extensionApi,
  }).api();
}

function makeWebRequestEventRegistrar(event) {
  return function ({ fire, context }, params) {
    // ExtensionAPIPersistent makes sure this function will be bound
    // to the ExtensionAPIPersistent instance.
    const { extension } = this;

    const [filter, info] = params;

    // When we are registering the real listener coming from the extension context,
    // we should get the additional remoteTab parameter value from the extension context
    // (which is then used by the registerTraceableChannel helper to register stream
    // filters to the channel and associate them to the extension context that has
    // created it and will be handling the filter onstart/ondata/onend events).
    let remoteTab;
    if (context) {
      remoteTab = context.xulBrowser.frameLoader.remoteTab;
    }

    return registerEvent(extension, event, fire, filter, info, remoteTab);
  };
}

this.webRequest = class extends ExtensionAPIPersistent {
  primeListener(event, fire, params, isInStartup) {
    // During early startup if the listener does not use blocking we do not prime it.
    if (!isInStartup || params[1]?.includes("blocking")) {
      return super.primeListener(event, fire, params, isInStartup);
    }
  }

  PERSISTENT_EVENTS = {
    onBeforeRequest: makeWebRequestEventRegistrar("onBeforeRequest"),
    onBeforeSendHeaders: makeWebRequestEventRegistrar("onBeforeSendHeaders"),
    onSendHeaders: makeWebRequestEventRegistrar("onSendHeaders"),
    onHeadersReceived: makeWebRequestEventRegistrar("onHeadersReceived"),
    onAuthRequired: makeWebRequestEventRegistrar("onAuthRequired"),
    onBeforeRedirect: makeWebRequestEventRegistrar("onBeforeRedirect"),
    onResponseStarted: makeWebRequestEventRegistrar("onResponseStarted"),
    onErrorOccurred: makeWebRequestEventRegistrar("onErrorOccurred"),
    onCompleted: makeWebRequestEventRegistrar("onCompleted"),
  };

  getAPI(context) {
    return {
      webRequest: {
        onBeforeRequest: makeWebRequestEventAPI(
          context,
          "onBeforeRequest",
          this
        ),
        onBeforeSendHeaders: makeWebRequestEventAPI(
          context,
          "onBeforeSendHeaders",
          this
        ),
        onSendHeaders: makeWebRequestEventAPI(context, "onSendHeaders", this),
        onHeadersReceived: makeWebRequestEventAPI(
          context,
          "onHeadersReceived",
          this
        ),
        onAuthRequired: makeWebRequestEventAPI(context, "onAuthRequired", this),
        onBeforeRedirect: makeWebRequestEventAPI(
          context,
          "onBeforeRedirect",
          this
        ),
        onResponseStarted: makeWebRequestEventAPI(
          context,
          "onResponseStarted",
          this
        ),
        onErrorOccurred: makeWebRequestEventAPI(
          context,
          "onErrorOccurred",
          this
        ),
        onCompleted: makeWebRequestEventAPI(context, "onCompleted", this),
        getSecurityInfo: function (requestId, options = {}) {
          return WebRequest.getSecurityInfo({
            id: requestId,
            policy: context.extension.policy,
            remoteTab: context.xulBrowser.frameLoader.remoteTab,
            options,
          });
        },
        handlerBehaviorChanged: function () {
          // TODO: Flush all caches.
        },
      },
    };
  }
};