-
Notifications
You must be signed in to change notification settings - Fork 54
/
Extension.jsm
2752 lines (2357 loc) · 81.1 KB
/
Extension.jsm
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* 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";
var EXPORTED_SYMBOLS = [
"Dictionary",
"Extension",
"ExtensionData",
"getExtensionUUID",
"Langpack",
"Management",
"ExtensionAddonObserver",
];
/* exported Extension, ExtensionData */
/*
* This file is the main entry point for extensions. When an extension
* loads, its bootstrap.js file creates a Extension instance
* and calls .startup() on it. It calls .shutdown() when the extension
* unloads. Extension manages any extension-specific state in
* the chrome process.
*
* TODO(rpl): we are current restricting the extensions to a single process
* (set as the current default value of the "dom.ipc.processCount.extension"
* preference), if we switch to use more than one extension process, we have to
* be sure that all the browser's frameLoader are associated to the same process,
* e.g. by using the `sameProcessAsFrameLoader` property.
* (http://searchfox.org/mozilla-central/source/dom/interfaces/base/nsIBrowser.idl)
*
* At that point we are going to keep track of the existing browsers associated to
* a webextension to ensure that they are all running in the same process (and we
* are also going to do the same with the browser element provided to the
* addon debugging Remote Debugging actor, e.g. because the addon has been
* reloaded by the user, we have to ensure that the new extension pages are going
* to run in the same process of the existing addon debugging browser element).
*/
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
AddonManager: "resource://gre/modules/AddonManager.jsm",
AddonManagerPrivate: "resource://gre/modules/AddonManager.jsm",
AddonSettings: "resource://gre/modules/addons/AddonSettings.jsm",
AMTelemetry: "resource://gre/modules/AddonManager.jsm",
AppConstants: "resource://gre/modules/AppConstants.jsm",
AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
E10SUtils: "resource://gre/modules/E10SUtils.jsm",
ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.jsm",
ExtensionPreferencesManager:
"resource://gre/modules/ExtensionPreferencesManager.jsm",
ExtensionProcessScript: "resource://gre/modules/ExtensionProcessScript.jsm",
ExtensionStorage: "resource://gre/modules/ExtensionStorage.jsm",
ExtensionStorageIDB: "resource://gre/modules/ExtensionStorageIDB.jsm",
ExtensionTelemetry: "resource://gre/modules/ExtensionTelemetry.jsm",
FileSource: "resource://gre/modules/L10nRegistry.jsm",
L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
LightweightThemeManager: "resource://gre/modules/LightweightThemeManager.jsm",
Localization: "resource://gre/modules/Localization.jsm",
Log: "resource://gre/modules/Log.jsm",
MessageChannel: "resource://gre/modules/MessageChannel.jsm",
NetUtil: "resource://gre/modules/NetUtil.jsm",
OS: "resource://gre/modules/osfile.jsm",
PluralForm: "resource://gre/modules/PluralForm.jsm",
Schemas: "resource://gre/modules/Schemas.jsm",
XPIProvider: "resource://gre/modules/addons/XPIProvider.jsm",
});
// This is used for manipulating jar entry paths, which always use Unix
// separators.
XPCOMUtils.defineLazyGetter(this, "OSPath", () => {
let obj = {};
ChromeUtils.import("resource://gre/modules/osfile/ospath_unix.jsm", obj);
return obj;
});
XPCOMUtils.defineLazyGetter(this, "resourceProtocol", () =>
Services.io
.getProtocolHandler("resource")
.QueryInterface(Ci.nsIResProtocolHandler)
);
const { ExtensionCommon } = ChromeUtils.import(
"resource://gre/modules/ExtensionCommon.jsm"
);
const { ExtensionParent } = ChromeUtils.import(
"resource://gre/modules/ExtensionParent.jsm"
);
const { ExtensionUtils } = ChromeUtils.import(
"resource://gre/modules/ExtensionUtils.jsm"
);
XPCOMUtils.defineLazyServiceGetters(this, {
aomStartup: [
"@mozilla.org/addons/addon-manager-startup;1",
"amIAddonManagerStartup",
],
spellCheck: ["@mozilla.org/spellchecker/engine;1", "mozISpellCheckingEngine"],
uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
"processCount",
"dom.ipc.processCount.extension"
);
// Temporary pref to be turned on when ready.
XPCOMUtils.defineLazyPreferenceGetter(
this,
"allowPrivateBrowsingByDefault",
"extensions.allowPrivateBrowsingByDefault",
true
);
var {
GlobalManager,
ParentAPIManager,
StartupCache,
apiManager: Management,
} = ExtensionParent;
const { getUniqueId, promiseTimeout } = ExtensionUtils;
const { EventEmitter } = ExtensionCommon;
XPCOMUtils.defineLazyGetter(this, "console", ExtensionCommon.getConsole);
XPCOMUtils.defineLazyGetter(
this,
"LocaleData",
() => ExtensionCommon.LocaleData
);
const { sharedData } = Services.ppmm;
const PRIVATE_ALLOWED_PERMISSION = "internal:privateBrowsingAllowed";
// The userContextID reserved for the extension storage (its purpose is ensuring that the IndexedDB
// storage used by the browser.storage.local API is not directly accessible from the extension code,
// it is defined and reserved as "userContextIdInternal.webextStorageLocal" in ContextualIdentityService.jsm).
const WEBEXT_STORAGE_USER_CONTEXT_ID = -1 >>> 0;
// The maximum time to wait for extension child shutdown blockers to complete.
const CHILD_SHUTDOWN_TIMEOUT_MS = 8000;
// Permissions that are only available to privileged extensions.
const PRIVILEGED_PERMS = new Set([
"activityLog",
"mozillaAddons",
"geckoViewAddons",
"telemetry",
"urlbar",
"normandyAddonStudy",
"networkStatus",
]);
/**
* Classify an individual permission from a webextension manifest
* as a host/origin permission, an api permission, or a regular permission.
*
* @param {string} perm The permission string to classify
* @param {boolean} restrictSchemes
* @param {boolean} isPrivileged whether or not the webextension is privileged
*
* @returns {object}
* An object with exactly one of the following properties:
* "origin" to indicate this is a host/origin permission.
* "api" to indicate this is an api permission
* (as used for webextensions experiments).
* "permission" to indicate this is a regular permission.
* "invalid" to indicate that the given permission cannot be used.
*/
function classifyPermission(perm, restrictSchemes, isPrivileged) {
let match = /^(\w+)(?:\.(\w+)(?:\.\w+)*)?$/.exec(perm);
if (!match) {
try {
let { pattern } = new MatchPattern(perm, {
restrictSchemes,
ignorePath: true,
});
return { origin: pattern };
} catch (e) {
return { invalid: perm };
}
} else if (match[1] == "experiments" && match[2]) {
return { api: match[2] };
} else if (!isPrivileged && PRIVILEGED_PERMS.has(match[1])) {
return { invalid: perm };
}
return { permission: perm };
}
const LOGGER_ID_BASE = "addons.webextension.";
const UUID_MAP_PREF = "extensions.webextensions.uuids";
const LEAVE_STORAGE_PREF = "extensions.webextensions.keepStorageOnUninstall";
const LEAVE_UUID_PREF = "extensions.webextensions.keepUuidOnUninstall";
const COMMENT_REGEXP = new RegExp(
String.raw`
^
(
(?:
[^"\n] |
" (?:[^"\\\n] | \\.)* "
)*?
)
//.*
`.replace(/\s+/g, ""),
"gm"
);
// All moz-extension URIs use a machine-specific UUID rather than the
// extension's own ID in the host component. This makes it more
// difficult for web pages to detect whether a user has a given add-on
// installed (by trying to load a moz-extension URI referring to a
// web_accessible_resource from the extension). UUIDMap.get()
// returns the UUID for a given add-on ID.
var UUIDMap = {
_read() {
let pref = Services.prefs.getStringPref(UUID_MAP_PREF, "{}");
try {
return JSON.parse(pref);
} catch (e) {
Cu.reportError(`Error parsing ${UUID_MAP_PREF}.`);
return {};
}
},
_write(map) {
Services.prefs.setStringPref(UUID_MAP_PREF, JSON.stringify(map));
},
get(id, create = true) {
let map = this._read();
if (id in map) {
return map[id];
}
let uuid = null;
if (create) {
uuid = uuidGen.generateUUID().number;
uuid = uuid.slice(1, -1); // Strip { and } off the UUID.
map[id] = uuid;
this._write(map);
}
return uuid;
},
remove(id) {
let map = this._read();
delete map[id];
this._write(map);
},
};
var getExtensionUUID = function(id) {
return UUIDMap.get(id, false);
};
/**
* Observer AddonManager events and translate them into extension events,
* as well as handle any last cleanup after uninstalling an extension.
*/
var ExtensionAddonObserver = {
initialized: false,
init() {
if (!this.initialized) {
AddonManager.addAddonListener(this);
this.initialized = true;
}
},
// AddonTestUtils will call this as necessary.
uninit() {
if (this.initialized) {
AddonManager.removeAddonListener(this);
this.initialized = false;
}
},
onEnabling(addon) {
if (addon.type !== "extension") {
return;
}
Management._callHandlers([addon.id], "enabling", "onEnabling");
},
onDisabled(addon) {
if (addon.type !== "extension") {
return;
}
if (Services.appinfo.inSafeMode) {
// Ensure ExtensionPreferencesManager updates its data and
// modules can run any disable logic they need to. We only
// handle safeMode here because there is a bunch of additional
// logic that happens in Extension.shutdown when running in
// normal mode.
Management._callHandlers([addon.id], "disable", "onDisable");
}
},
onUninstalling(addon) {
let extension = GlobalManager.extensionMap.get(addon.id);
if (extension) {
// Let any other interested listeners respond
// (e.g., display the uninstall URL)
Management.emit("uninstalling", extension);
}
},
onUninstalled(addon) {
let uuid = UUIDMap.get(addon.id, false);
if (!uuid) {
return;
}
if (!Services.prefs.getBoolPref(LEAVE_STORAGE_PREF, false)) {
// Clear browser.storage.local backends.
AsyncShutdown.profileChangeTeardown.addBlocker(
`Clear Extension Storage ${addon.id} (File Backend)`,
ExtensionStorage.clear(addon.id, { shouldNotifyListeners: false })
);
// Clear any IndexedDB storage created by the extension
// If LSNG is enabled, this also clears localStorage.
let baseURI = Services.io.newURI(`moz-extension://${uuid}/`);
let principal = Services.scriptSecurityManager.createContentPrincipal(
baseURI,
{}
);
Services.qms.clearStoragesForPrincipal(principal);
// Clear any storage.local data stored in the IDBBackend.
let storagePrincipal = Services.scriptSecurityManager.createContentPrincipal(
baseURI,
{
userContextId: WEBEXT_STORAGE_USER_CONTEXT_ID,
}
);
Services.qms.clearStoragesForPrincipal(storagePrincipal);
ExtensionStorageIDB.clearMigratedExtensionPref(addon.id);
// If LSNG is not enabled, we need to clear localStorage explicitly using
// the old API.
if (!Services.lsm.nextGenLocalStorageEnabled) {
// Clear localStorage created by the extension
let storage = Services.domStorageManager.getStorage(
null,
principal,
principal
);
if (storage) {
storage.clear();
}
}
// Remove any permissions related to the unlimitedStorage permission
// if we are also removing all the data stored by the extension.
Services.perms.removeFromPrincipal(
principal,
"WebExtensions-unlimitedStorage"
);
Services.perms.removeFromPrincipal(principal, "indexedDB");
Services.perms.removeFromPrincipal(principal, "persistent-storage");
}
ExtensionPermissions.removeAll(addon.id);
if (!Services.prefs.getBoolPref(LEAVE_UUID_PREF, false)) {
// Clear the entry in the UUID map
UUIDMap.remove(addon.id);
}
},
};
ExtensionAddonObserver.init();
const manifestTypes = new Map([
["theme", "manifest.ThemeManifest"],
["langpack", "manifest.WebExtensionLangpackManifest"],
["dictionary", "manifest.WebExtensionDictionaryManifest"],
["extension", "manifest.WebExtensionManifest"],
]);
/**
* Represents the data contained in an extension, contained either
* in a directory or a zip file, which may or may not be installed.
* This class implements the functionality of the Extension class,
* primarily related to manifest parsing and localization, which is
* useful prior to extension installation or initialization.
*
* No functionality of this class is guaranteed to work before
* `loadManifest` has been called, and completed.
*/
class ExtensionData {
constructor(rootURI) {
this.rootURI = rootURI;
this.resourceURL = rootURI.spec;
this.manifest = null;
this.type = null;
this.id = null;
this.uuid = null;
this.localeData = null;
this.fluentL10n = null;
this._promiseLocales = null;
this.apiNames = new Set();
this.dependencies = new Set();
this.permissions = new Set();
this.startupData = null;
this.errors = [];
this.warnings = [];
}
get builtinMessages() {
return null;
}
get logger() {
let id = this.id || "<unknown>";
return Log.repository.getLogger(LOGGER_ID_BASE + id);
}
/**
* Report an error about the extension's manifest file.
* @param {string} message The error message
*/
manifestError(message) {
this.packagingError(`Reading manifest: ${message}`);
}
/**
* Report a warning about the extension's manifest file.
* @param {string} message The warning message
*/
manifestWarning(message) {
this.packagingWarning(`Reading manifest: ${message}`);
}
// Report an error about the extension's general packaging.
packagingError(message) {
this.errors.push(message);
this.logError(message);
}
packagingWarning(message) {
this.warnings.push(message);
this.logWarning(message);
}
logWarning(message) {
this._logMessage(message, "warn");
}
logError(message) {
this._logMessage(message, "error");
}
_logMessage(message, severity) {
this.logger[severity](`Loading extension '${this.id}': ${message}`);
}
/**
* Returns the moz-extension: URL for the given path within this
* extension.
*
* Must not be called unless either the `id` or `uuid` property has
* already been set.
*
* @param {string} path The path portion of the URL.
* @returns {string}
*/
getURL(path = "") {
if (!(this.id || this.uuid)) {
throw new Error(
"getURL may not be called before an `id` or `uuid` has been set"
);
}
if (!this.uuid) {
this.uuid = UUIDMap.get(this.id);
}
return `moz-extension://${this.uuid}/${path}`;
}
async readDirectory(path) {
if (this.rootURI instanceof Ci.nsIFileURL) {
let uri = Services.io.newURI("./" + path, null, this.rootURI);
let fullPath = uri.QueryInterface(Ci.nsIFileURL).file.path;
let iter = new OS.File.DirectoryIterator(fullPath);
let results = [];
try {
await iter.forEach(entry => {
results.push(entry);
});
} catch (e) {
// Always return a list, even if the directory does not exist (or is
// not a directory) for symmetry with the ZipReader behavior.
if (!e.becauseNoSuchFile) {
Cu.reportError(e);
}
}
iter.close();
return results;
}
let uri = this.rootURI.QueryInterface(Ci.nsIJARURI);
// Append the sub-directory path to the base JAR URI and normalize the
// result.
let entry = `${uri.JAREntry}/${path}/`
.replace(/\/\/+/g, "/")
.replace(/^\//, "");
uri = Services.io.newURI(`jar:${uri.JARFile.spec}!/${entry}`);
let results = [];
for (let name of aomStartup.enumerateJARSubtree(uri)) {
if (!name.startsWith(entry)) {
throw new Error("Unexpected ZipReader entry");
}
// The enumerator returns the full path of all entries.
// Trim off the leading path, and filter out entries from
// subdirectories.
name = name.slice(entry.length);
if (name && !/\/./.test(name)) {
results.push({
name: name.replace("/", ""),
isDir: name.endsWith("/"),
});
}
}
return results;
}
readJSON(path) {
return new Promise((resolve, reject) => {
let uri = this.rootURI.resolve(`./${path}`);
NetUtil.asyncFetch(
{ uri, loadUsingSystemPrincipal: true },
(inputStream, status) => {
if (!Components.isSuccessCode(status)) {
// Convert status code to a string
let e = Components.Exception("", status);
reject(new Error(`Error while loading '${uri}' (${e.name})`));
return;
}
try {
let text = NetUtil.readInputStreamToString(
inputStream,
inputStream.available(),
{ charset: "utf-8" }
);
text = text.replace(COMMENT_REGEXP, "$1");
resolve(JSON.parse(text));
} catch (e) {
reject(e);
}
}
);
});
}
get restrictSchemes() {
// ExtensionData can't check the signature (as it is not yet passed to its constructor
// as it is for the Extension class, where this getter is overridden to check both the
// signature and the permissions).
return !this.hasPermission("mozillaAddons");
}
/**
* Given an array of host and permissions, generate a structured permissions object
* that contains seperate host origins and permissions arrays.
*
* @param {Array} permissionsArray
* @returns {Object} permissions object
*/
permissionsObject(permissionsArray) {
let permissions = new Set();
let origins = new Set();
let { restrictSchemes, isPrivileged } = this;
for (let perm of permissionsArray || []) {
let type = classifyPermission(perm, restrictSchemes, isPrivileged);
if (type.origin) {
origins.add(perm);
} else if (type.permission) {
permissions.add(perm);
}
}
return {
permissions,
origins,
};
}
/**
* Returns an object representing any capabilities that the extension
* has access to based on fixed properties in the manifest. The result
* includes the contents of the "permissions" property as well as other
* capabilities that are derived from manifest fields that users should
* be informed of (e.g., origins where content scripts are injected).
*/
get manifestPermissions() {
if (this.type !== "extension") {
return null;
}
let { permissions, origins } = this.permissionsObject(
this.manifest.permissions
);
if (this.manifest.devtools_page) {
permissions.add("devtools");
}
for (let entry of this.manifest.content_scripts || []) {
for (let origin of entry.matches) {
origins.add(origin);
}
}
return {
permissions: Array.from(permissions),
origins: Array.from(origins),
};
}
get manifestOptionalPermissions() {
let { permissions, origins } = this.permissionsObject(
this.manifest.optional_permissions
);
return {
permissions: Array.from(permissions),
origins: Array.from(origins),
};
}
/**
* Returns an object representing all capabilities this extension has
* access to, including fixed ones from the manifest as well as dynamically
* granted permissions.
*/
get activePermissions() {
if (this.type !== "extension") {
return null;
}
let result = {
origins: this.whiteListedHosts.patterns
.map(matcher => matcher.pattern)
// moz-extension://id/* is always added to whiteListedHosts, but it
// is not a valid host permission in the API. So, remove it.
.filter(pattern => !pattern.startsWith("moz-extension:")),
apis: [...this.apiNames],
};
const EXP_PATTERN = /^experiments\.\w+/;
result.permissions = [...this.permissions].filter(
p => !result.origins.includes(p) && !EXP_PATTERN.test(p)
);
return result;
}
// Compute the difference between two sets of permissions, suitable
// for presenting to the user.
static comparePermissions(oldPermissions, newPermissions) {
let oldMatcher = new MatchPatternSet(oldPermissions.origins, {
restrictSchemes: false,
});
return {
// formatPermissionStrings ignores any scheme, so only look at the domain.
origins: newPermissions.origins.filter(
perm =>
!oldMatcher.subsumesDomain(
new MatchPattern(perm, { restrictSchemes: false })
)
),
permissions: newPermissions.permissions.filter(
perm => !oldPermissions.permissions.includes(perm)
),
};
}
// Return those permissions in oldPermissions that also exist in newPermissions.
static intersectPermissions(oldPermissions, newPermissions) {
let matcher = new MatchPatternSet(newPermissions.origins, {
restrictSchemes: false,
});
return {
origins: oldPermissions.origins.filter(perm =>
matcher.subsumesDomain(
new MatchPattern(perm, { restrictSchemes: false })
)
),
permissions: oldPermissions.permissions.filter(perm =>
newPermissions.permissions.includes(perm)
),
};
}
/**
* When updating the addon, find and migrate permissions that have moved from required
* to optional. This also handles any updates required for permission removal.
*
* @param {string} id The id of the addon being updated
* @param {Object} oldPermissions
* @param {Object} oldOptionalPermissions
* @param {Object} newPermissions
* @param {Object} newOptionalPermissions
*/
static async migratePermissions(
id,
oldPermissions,
oldOptionalPermissions,
newPermissions,
newOptionalPermissions
) {
let migrated = ExtensionData.intersectPermissions(
oldPermissions,
newOptionalPermissions
);
// If a permission is optional in this version and was mandatory in the previous
// version, it was already accepted by the user at install time so add it to the
// list of granted optional permissions now.
await ExtensionPermissions.add(id, migrated);
// Now we need to update ExtensionPreferencesManager, removing any settings
// for old permissions that no longer exist.
let permSet = new Set(
newPermissions.permissions.concat(newOptionalPermissions.permissions)
);
let oldPerms = oldPermissions.permissions.concat(
oldOptionalPermissions.permissions
);
let removed = oldPerms.filter(x => !permSet.has(x));
if (removed.length) {
await Management.asyncLoadSettingsModules();
for (let name of removed) {
await ExtensionPreferencesManager.removeSettingsForPermission(id, name);
}
}
// Remove any optional permissions that have been removed from the manifest.
await ExtensionPermissions.remove(id, {
permissions: removed,
origins: [],
});
}
canUseExperiment(manifest) {
return this.experimentsAllowed && manifest.experiment_apis;
}
/**
* Load a locale and return a localized manifest. The extension must
* be initialized, and manifest parsed prior to calling.
*
* @param {string} locale to load, if necessary.
* @returns {object} normalized manifest.
*/
async getLocalizedManifest(locale) {
if (!this.type || !this.localeData) {
throw new Error("The extension has not been initialized.");
}
// Upon update or reinstall, the Extension.manifest may be read from
// StartupCache.manifest, however rawManifest is *not*. We need the
// raw manifest in order to get a localized manifest.
if (!this.rawManifest) {
this.rawManifest = await this.readJSON("manifest.json");
}
if (!this.localeData.has(locale)) {
// Locales are not avialable until some additional
// initialization is done. We could just call initAllLocales,
// but that is heavy handed, especially when we likely only
// need one out of 20.
let locales = await this.promiseLocales();
if (locales.get(locale)) {
await this.initLocale(locale);
}
if (!this.localeData.has(locale)) {
throw new Error(`The extension does not contain the locale ${locale}`);
}
}
let normalized = await this._getNormalizedManifest(locale);
if (normalized.error) {
throw new Error(normalized.error);
}
return normalized.value;
}
async _getNormalizedManifest(locale) {
let manifestType = manifestTypes.get(this.type);
let context = {
url: this.baseURI && this.baseURI.spec,
principal: this.principal,
logError: error => {
this.manifestWarning(error);
},
preprocessors: {},
};
if (this.fluentL10n || this.localeData) {
context.preprocessors.localize = (value, context) =>
this.localize(value, locale);
}
return Schemas.normalize(this.rawManifest, manifestType, context);
}
// eslint-disable-next-line complexity
async parseManifest() {
let [manifest] = await Promise.all([
this.readJSON("manifest.json"),
Management.lazyInit(),
]);
this.manifest = manifest;
this.rawManifest = manifest;
if (
allowPrivateBrowsingByDefault &&
"incognito" in manifest &&
manifest.incognito == "not_allowed"
) {
throw new Error(
`manifest.incognito set to "not_allowed" is currently unvailable for use.`
);
}
if (manifest && manifest.default_locale) {
await this.initLocale();
}
// When parsing the manifest from an ExtensionData instance, we don't
// have isPrivileged, so ignore fluent localization in that pass.
// This means that fluent cannot be used to localize manifest properties
// read from the add-on manager (e.g., author, homepage, etc.)
if (manifest && manifest.l10n_resources && "isPrivileged" in this) {
if (this.isPrivileged) {
this.fluentL10n = new Localization(manifest.l10n_resources, true);
} else {
// Warn but don't make this fatal.
Cu.reportError("Ignoring l10n_resources in unprivileged extension");
}
}
if (this.manifest.theme) {
this.type = "theme";
} else if (this.manifest.langpack_id) {
this.type = "langpack";
} else if (this.manifest.dictionaries) {
this.type = "dictionary";
} else {
this.type = "extension";
}
let normalized = await this._getNormalizedManifest();
if (normalized.error) {
this.manifestError(normalized.error);
return null;
}
manifest = normalized.value;
let id;
try {
if (manifest.applications.gecko.id) {
id = manifest.applications.gecko.id;
}
} catch (e) {
// Errors are handled by the type checks above.
}
if (!this.id) {
this.id = id;
}
let apiNames = new Set();
let dependencies = new Set();
let originPermissions = new Set();
let permissions = new Set();
let webAccessibleResources = [];
let schemaPromises = new Map();
let result = {
apiNames,
dependencies,
id,
manifest,
modules: null,
originPermissions,
permissions,
schemaURLs: null,
type: this.type,
webAccessibleResources,
};
if (this.type === "extension") {
let { isPrivileged } = this;
let restrictSchemes = !(
isPrivileged && manifest.permissions.includes("mozillaAddons")
);
for (let perm of manifest.permissions) {
if (perm === "geckoProfiler" && !isPrivileged) {
const acceptedExtensions = Services.prefs.getStringPref(
"extensions.geckoProfiler.acceptedExtensionIds",
""
);
if (!acceptedExtensions.split(",").includes(id)) {
this.manifestError(
"Only whitelisted extensions are allowed to access the geckoProfiler."
);
continue;
}
}
let type = classifyPermission(perm, restrictSchemes, isPrivileged);
if (type.origin) {
perm = type.origin;
originPermissions.add(perm);
} else if (type.api) {
apiNames.add(type.api);
} else if (type.invalid) {
this.manifestWarning(`Invalid extension permission: ${perm}`);
continue;
}
permissions.add(perm);
}
if (this.id) {
// An extension always gets permission to its own url.
let matcher = new MatchPattern(this.getURL(), { ignorePath: true });
originPermissions.add(matcher.pattern);
// Apply optional permissions
let perms = await ExtensionPermissions.get(this.id);
for (let perm of perms.permissions) {
permissions.add(perm);
}
for (let origin of perms.origins) {
originPermissions.add(origin);
}
}
for (let api of apiNames) {
dependencies.add(`${api}@experiments.addons.mozilla.org`);
}
let moduleData = data => ({
url: this.rootURI.resolve(data.script),
events: data.events,
paths: data.paths,
scopes: data.scopes,
});
let computeModuleInit = (scope, modules) => {
let manager = new ExtensionCommon.SchemaAPIManager(scope);
return manager.initModuleJSON([modules]);
};
result.contentScripts = [];
for (let options of manifest.content_scripts || []) {
result.contentScripts.push({
allFrames: options.all_frames,
matchAboutBlank: options.match_about_blank,
frameID: options.frame_id,
runAt: options.run_at,
matches: options.matches,
excludeMatches: options.exclude_matches || [],
includeGlobs: options.include_globs,
excludeGlobs: options.exclude_globs,