summaryrefslogtreecommitdiffstats
path: root/browser/modules/FirefoxBridgeExtensionUtils.sys.mjs
blob: 7b0094205d3a0e1806fda33da2936481cd0e339f (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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/* 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/. */

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  ObjectUtils: "resource://gre/modules/ObjectUtils.sys.mjs",
});

/**
 * Default implementation of the helper class to assist in deleting the firefox protocols.
 * See maybeDeleteBridgeProtocolRegistryEntries for more info.
 */
class DeleteBridgeProtocolRegistryEntryHelperImplementation {
  getApplicationPath() {
    return Services.dirsvc.get("XREExeF", Ci.nsIFile).path;
  }

  openRegistryRoot() {
    const wrk = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
      Ci.nsIWindowsRegKey
    );

    wrk.open(wrk.ROOT_KEY_CURRENT_USER, "Software\\Classes", wrk.ACCESS_ALL);

    return wrk;
  }

  deleteChildren(start) {
    // Recursively delete all of the children of the children
    // Go through the list in reverse order, so that shrinking
    // the list doesn't rearrange things while iterating
    for (let i = start.childCount; i > 0; i--) {
      const childName = start.getChildName(i - 1);
      const child = start.openChild(childName, start.ACCESS_ALL);
      this.deleteChildren(child);
      child.close();

      start.removeChild(childName);
    }
  }

  deleteRegistryTree(root, toDeletePath) {
    var start = root.openChild(toDeletePath, root.ACCESS_ALL);
    this.deleteChildren(start);
    start.close();

    root.removeChild(toDeletePath);
  }
}

export const FirefoxBridgeExtensionUtils = {
  /**
   * In Firefox 122, we enabled the firefox and firefox-private protocols.
   * We switched over to using firefox-bridge and firefox-private-bridge,
   *
   * but we want to clean up the use of the other protocols.
   *
   * deleteBridgeProtocolRegistryEntryHelper handles everything outside of the logic needed for
   * this method so that the logic in maybeDeleteBridgeProtocolRegistryEntries can be unit tested
   *
   * We only delete the entries for the firefox and firefox-private protocols if
   * they were set up to use this install and in the format that Firefox installed
   * them with. If the entries are changed in any way, it is assumed that the user
   * mucked with them manually and knows what they are doing.
   */
  maybeDeleteBridgeProtocolRegistryEntries(
    deleteBridgeProtocolRegistryEntryHelper = new DeleteBridgeProtocolRegistryEntryHelperImplementation()
  ) {
    try {
      var wrk = deleteBridgeProtocolRegistryEntryHelper.openRegistryRoot();
      const path = deleteBridgeProtocolRegistryEntryHelper.getApplicationPath();

      const maybeDeleteRegistryKey = (protocol, protocolCommand) => {
        const openCommandPath = protocol + "\\shell\\open\\command";
        if (wrk.hasChild(openCommandPath)) {
          let deleteProtocolEntry = false;

          try {
            var openCommandKey = wrk.openChild(
              openCommandPath,
              wrk.ACCESS_READ
            );
            if (openCommandKey.valueCount == 1) {
              const defaultKeyName = "";
              if (openCommandKey.getValueName(0) == defaultKeyName) {
                if (
                  openCommandKey.getValueType(defaultKeyName) ==
                  Ci.nsIWindowsRegKey.TYPE_STRING
                ) {
                  const val = openCommandKey.readStringValue(defaultKeyName);
                  if (val == protocolCommand) {
                    deleteProtocolEntry = true;
                  }
                }
              }
            }
          } finally {
            openCommandKey.close();
          }

          if (deleteProtocolEntry) {
            deleteBridgeProtocolRegistryEntryHelper.deleteRegistryTree(
              wrk,
              protocol
            );
          }
        }
      };

      maybeDeleteRegistryKey("firefox", `\"${path}\" -osint -url \"%1\"`);
      maybeDeleteRegistryKey(
        "firefox-private",
        `\"${path}\" -osint -private-window \"%1\"`
      );
    } catch (err) {
      console.error(err);
    } finally {
      wrk.close();
    }
  },

  /**
   * Registers the firefox-bridge and firefox-private-bridge protocols
   * on the Windows platform.
   */
  maybeRegisterFirefoxBridgeProtocols() {
    const FIREFOX_BRIDGE_HANDLER_NAME = "firefox-bridge";
    const FIREFOX_PRIVATE_BRIDGE_HANDLER_NAME = "firefox-private-bridge";
    const path = Services.dirsvc.get("XREExeF", Ci.nsIFile).path;
    let wrk = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
      Ci.nsIWindowsRegKey
    );
    try {
      wrk.open(wrk.ROOT_KEY_CLASSES_ROOT, "", wrk.ACCESS_READ);
      let FxSet = wrk.hasChild(FIREFOX_BRIDGE_HANDLER_NAME);
      let FxPrivateSet = wrk.hasChild(FIREFOX_PRIVATE_BRIDGE_HANDLER_NAME);
      wrk.close();
      if (FxSet && FxPrivateSet) {
        return;
      }
      wrk.open(wrk.ROOT_KEY_CURRENT_USER, "Software\\Classes", wrk.ACCESS_ALL);
      const maybeUpdateRegistry = (isSetAlready, handler, protocolName) => {
        if (isSetAlready) {
          return;
        }
        let FxKey = wrk.createChild(handler, wrk.ACCESS_ALL);
        try {
          // Write URL protocol key
          FxKey.writeStringValue("", protocolName);
          FxKey.writeStringValue("URL Protocol", "");
          FxKey.close();
          // Write defaultIcon key
          FxKey.create(
            FxKey.ROOT_KEY_CURRENT_USER,
            "Software\\Classes\\" + handler + "\\DefaultIcon",
            FxKey.ACCESS_ALL
          );
          FxKey.open(
            FxKey.ROOT_KEY_CURRENT_USER,
            "Software\\Classes\\" + handler + "\\DefaultIcon",
            FxKey.ACCESS_ALL
          );
          FxKey.writeStringValue("", `\"${path}\",1`);
          FxKey.close();
          // Write shell\\open\\command key
          FxKey.create(
            FxKey.ROOT_KEY_CURRENT_USER,
            "Software\\Classes\\" + handler + "\\shell",
            FxKey.ACCESS_ALL
          );
          FxKey.create(
            FxKey.ROOT_KEY_CURRENT_USER,
            "Software\\Classes\\" + handler + "\\shell\\open",
            FxKey.ACCESS_ALL
          );
          FxKey.create(
            FxKey.ROOT_KEY_CURRENT_USER,
            "Software\\Classes\\" + handler + "\\shell\\open\\command",
            FxKey.ACCESS_ALL
          );
          FxKey.open(
            FxKey.ROOT_KEY_CURRENT_USER,
            "Software\\Classes\\" + handler + "\\shell\\open\\command",
            FxKey.ACCESS_ALL
          );
          if (handler == FIREFOX_PRIVATE_BRIDGE_HANDLER_NAME) {
            FxKey.writeStringValue(
              "",
              `\"${path}\" -osint -private-window \"%1\"`
            );
          } else {
            FxKey.writeStringValue("", `\"${path}\" -osint -url \"%1\"`);
          }
        } catch (ex) {
          console.error(ex);
        } finally {
          FxKey.close();
        }
      };

      try {
        maybeUpdateRegistry(
          FxSet,
          FIREFOX_BRIDGE_HANDLER_NAME,
          "URL:Firefox Bridge Protocol"
        );
      } catch (ex) {
        console.error(ex);
      }

      try {
        maybeUpdateRegistry(
          FxPrivateSet,
          FIREFOX_PRIVATE_BRIDGE_HANDLER_NAME,
          "URL:Firefox Private Bridge Protocol"
        );
      } catch (ex) {
        console.error(ex);
      }
    } catch (ex) {
      console.error(ex);
    } finally {
      wrk.close();
    }
  },

  getNativeMessagingHostId() {
    let nativeMessagingHostId = "org.mozilla.firefox_bridge_nmh";
    if (AppConstants.NIGHTLY_BUILD) {
      nativeMessagingHostId += "_nightly";
    } else if (AppConstants.MOZ_DEV_EDITION) {
      nativeMessagingHostId += "_dev";
    } else if (AppConstants.IS_ESR) {
      nativeMessagingHostId += "_esr";
    }
    return nativeMessagingHostId;
  },

  getExtensionOrigins() {
    return Services.prefs
      .getStringPref("browser.firefoxbridge.extensionOrigins", "")
      .split(",");
  },

  async maybeWriteManifestFiles(
    nmhManifestFolder,
    nativeMessagingHostId,
    dualBrowserExtensionOrigins
  ) {
    try {
      let binFile = Services.dirsvc.get("XREExeF", Ci.nsIFile).parent;
      if (AppConstants.platform == "win") {
        binFile.append("nmhproxy.exe");
      } else if (AppConstants.platform == "macosx") {
        binFile.append("nmhproxy");
      } else {
        throw new Error("Unsupported platform");
      }

      let jsonContent = {
        name: nativeMessagingHostId,
        description: "Firefox Native Messaging Host",
        path: binFile.path,
        type: "stdio",
        allowed_origins: dualBrowserExtensionOrigins,
      };
      let nmhManifestFile = await IOUtils.getFile(
        nmhManifestFolder,
        `${nativeMessagingHostId}.json`
      );

      // This throws an error if the JSON file doesn't exist
      // or if it's corrupt.
      let correctFileExists = true;
      try {
        correctFileExists = lazy.ObjectUtils.deepEqual(
          await IOUtils.readJSON(nmhManifestFile.path),
          jsonContent
        );
      } catch (e) {
        correctFileExists = false;
      }
      if (!correctFileExists) {
        await IOUtils.writeJSON(nmhManifestFile.path, jsonContent);
      }
    } catch (e) {
      console.error(e);
    }
  },

  async ensureRegistered() {
    let nmhManifestFolder = null;
    if (AppConstants.platform == "win") {
      // We don't have permission to write to the application install directory
      // so instead write to %AppData%\Mozilla\Firefox.
      nmhManifestFolder = PathUtils.join(
        Services.dirsvc.get("AppData", Ci.nsIFile).path,
        "Mozilla",
        "Firefox"
      );
    } else if (AppConstants.platform == "macosx") {
      nmhManifestFolder =
        "~/Library/Application Support/Google/Chrome/NativeMessagingHosts/";
    } else {
      throw new Error("Unsupported platform");
    }
    await this.maybeWriteManifestFiles(
      nmhManifestFolder,
      this.getNativeMessagingHostId(),
      this.getExtensionOrigins()
    );
    if (AppConstants.platform == "win") {
      this.maybeWriteNativeMessagingRegKeys(
        "Software\\Google\\Chrome\\NativeMessagingHosts",
        nmhManifestFolder,
        this.getNativeMessagingHostId()
      );
    }
  },

  maybeWriteNativeMessagingRegKeys(
    regPath,
    nmhManifestFolder,
    NATIVE_MESSAGING_HOST_ID
  ) {
    let wrk = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
      Ci.nsIWindowsRegKey
    );
    try {
      let expectedValue = PathUtils.join(
        nmhManifestFolder,
        `${NATIVE_MESSAGING_HOST_ID}.json`
      );
      try {
        // If the key already exists it will just be opened
        wrk.create(
          wrk.ROOT_KEY_CURRENT_USER,
          regPath + `\\${NATIVE_MESSAGING_HOST_ID}`,
          wrk.ACCESS_ALL
        );
        if (wrk.readStringValue("") == expectedValue) {
          return;
        }
      } catch (e) {
        // The key either doesn't have a value or doesn't exist
        // In either case we need to write it.
      }
      wrk.writeStringValue("", expectedValue);
    } catch (e) {
      // The method fails if we can't access the key
      // which means it doesn't exist. That's a normal situation.
      // We don't need to do anything here.
    } finally {
      wrk.close();
    }
  },
};