-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathmanifestjson.js
1324 lines (1197 loc) · 41.8 KB
/
manifestjson.js
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
/* eslint-disable import/namespace */
import path from 'path';
import RJSON from 'relaxed-json';
import { oneLine } from 'common-tags';
import getImageSize from 'image-size';
import upath from 'upath';
import bcd from '@mdn/browser-compat-data';
import { mozCompare } from 'addons-moz-compare';
import { getDefaultConfigValue } from 'yargs-options';
import {
validateAddon,
validateDictionary,
validateLangPack,
validateSitePermission,
validateStaticTheme,
} from 'schema/validator';
import {
CSP_KEYWORD_RE,
DEPRECATED_MANIFEST_PROPERTIES,
FILE_EXTENSIONS_TO_MIME,
IMAGE_FILE_EXTENSIONS,
INSTALL_ORIGINS_DATAPATH_REGEX,
MANIFEST_JSON,
MESSAGES_JSON,
LOCALES_DIRECTORY,
PACKAGE_EXTENSION,
PERMS_DATAPATH_REGEX,
RESTRICTED_HOMEPAGE_URLS,
RESTRICTED_PERMISSIONS,
SCHEMA_KEYWORDS,
STATIC_THEME_IMAGE_MIMES,
} from 'const';
import log from 'logger';
import * as messages from 'messages';
import JSONParser from 'parsers/json';
import {
androidStrictMinVersion,
basicCompatVersionComparison,
firefoxStrictMinVersion,
firstStableVersion,
isToolkitVersionString,
isValidVersionString,
normalizePath,
parseCspPolicy,
} from 'utils';
import BLOCKED_CONTENT_SCRIPT_HOSTS from 'blocked_content_script_hosts.txt';
async function getStreamImageSize(stream) {
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
try {
return getImageSize(Buffer.concat(chunks));
} catch (error) {
/* The size information isn't available yet */
}
}
return getImageSize(Buffer.concat(chunks));
}
async function getImageMetadata(io, iconPath) {
// Get a non-utf8 input stream by setting encoding to null.
let encoding = null;
if (iconPath.endsWith('.svg')) {
encoding = 'utf-8';
}
const fileStream = await io.getFileAsStream(iconPath, { encoding });
const data = await getStreamImageSize(fileStream);
return {
width: data.width,
height: data.height,
mime: FILE_EXTENSIONS_TO_MIME[data.type],
};
}
function getNormalizedExtension(_path) {
return path.extname(_path).substring(1).toLowerCase();
}
export default class ManifestJSONParser extends JSONParser {
constructor(
jsonString,
collector,
{
filename = MANIFEST_JSON,
RelaxedJSON = RJSON,
selfHosted = getDefaultConfigValue('self-hosted'),
schemaValidatorOptions,
io = null,
isAlreadySigned = false,
restrictedPermissions = RESTRICTED_PERMISSIONS,
} = {}
) {
super(jsonString, collector, { filename });
this.parse(RelaxedJSON);
// Set up some defaults in case parsing fails.
if (typeof this.parsedJSON === 'undefined' || this.isValid === false) {
this.parsedJSON = {
manifest_version: null,
name: null,
type: PACKAGE_EXTENSION,
version: null,
};
} else {
// We've parsed the JSON; now we can validate the manifest.
this.selfHosted = selfHosted;
this.schemaValidatorOptions = schemaValidatorOptions;
const hasManifestKey = (key) =>
Object.prototype.hasOwnProperty.call(this.parsedJSON, key);
this.isStaticTheme = false;
this.isLanguagePack = false;
this.isDictionary = false;
this.isSitePermission = false;
// Keep the addon type detection in sync with the most updated logic
// used on the Firefox side, as defined in ExtensionData parseManifest
// method.
if (hasManifestKey('theme')) {
this.isStaticTheme = true;
} else if (hasManifestKey('langpack_id')) {
this.isLanguagePack = true;
} else if (hasManifestKey('dictionaries')) {
this.isDictionary = true;
} else if (hasManifestKey('site_permissions')) {
this.isSitePermission = true;
}
this.io = io;
this.isAlreadySigned = isAlreadySigned;
this.isPrivilegedAddon = this.schemaValidatorOptions?.privileged ?? false;
this.restrictedPermissions = restrictedPermissions;
this._validate();
}
}
checkKeySupport(
support,
minFirefoxVersion,
minAndroidVersion,
key,
isPermission = false
) {
if (support.firefox && minFirefoxVersion) {
// We don't have to support gaps in the `@mdn/browser-compat-data`
// information for Firefox Desktop so far.
const versionAdded = support.firefox.version_added;
if (basicCompatVersionComparison(versionAdded, minFirefoxVersion)) {
if (!isPermission) {
this.collector.addWarning(
messages.keyFirefoxUnsupportedByMinVersion(
key,
minFirefoxVersion,
versionAdded
)
);
} else {
this.collector.addNotice(
messages.permissionFirefoxUnsupportedByMinVersion(
key,
minFirefoxVersion,
versionAdded
)
);
}
}
}
if (support.firefox_android && minAndroidVersion) {
// `@mdn/browser-compat-data` sometimes provides data with gaps, e.g., a
// feature was supported in Fennec (added in 56 and removed in 79) and
// then re-added in Fenix (added in 85) and this is expressed with an
// array of objects instead of a single object.
//
// This is the case of the `permissions.browsingData` on Android for
// instance and we decided to only warn the developer if the minVersion
// required by the extension is not greater or equal of the first version
// where the feature was officially supported for the first time (and do
// not warn if the minVersion is in one of the few version gaps).
const versionAddedAndroid = firstStableVersion(support.firefox_android);
if (
basicCompatVersionComparison(versionAddedAndroid, minAndroidVersion)
) {
if (!isPermission) {
this.collector.addWarning(
messages.keyFirefoxAndroidUnsupportedByMinVersion(
key,
minAndroidVersion,
versionAddedAndroid
)
);
} else {
this.collector.addNotice(
messages.permissionFirefoxAndroidUnsupportedByMinVersion(
key,
minAndroidVersion,
versionAddedAndroid
)
);
}
}
}
}
checkCompatInfo(
compatInfo,
minFirefoxVersion,
minAndroidVersion,
key,
manifestKeyValue
) {
for (const subkey in compatInfo) {
if (Object.prototype.hasOwnProperty.call(compatInfo, subkey)) {
const subkeyInfo = compatInfo[subkey];
if (subkey === '__compat') {
this.checkKeySupport(
subkeyInfo.support,
minFirefoxVersion,
minAndroidVersion,
key
);
} else if (
typeof manifestKeyValue === 'object' &&
manifestKeyValue !== null &&
Object.prototype.hasOwnProperty.call(manifestKeyValue, subkey)
) {
this.checkCompatInfo(
subkeyInfo,
minFirefoxVersion,
minAndroidVersion,
`${key}.${subkey}`,
manifestKeyValue[subkey]
);
} else if (
(key === 'permissions' || key === 'optional_permissions') &&
manifestKeyValue.includes(subkey)
) {
this.checkKeySupport(
subkeyInfo.__compat.support,
minFirefoxVersion,
minAndroidVersion,
`${key}:${subkey}`,
true
);
}
}
}
}
errorLookup(error) {
// This is the default message.
let baseObject = messages.JSON_INVALID;
// This is the default from webextension-manifest-schema, but it's not a
// super helpful error. We'll tidy it up a bit:
if (error && error.message) {
const lowerCaseMessage = error.message.toLowerCase();
if (lowerCaseMessage === 'must match a schema in anyof') {
// eslint-disable-next-line no-param-reassign
error.message = 'is not a valid key or has invalid extra properties';
}
}
const overrides = {
message: `"${error.instancePath || '/'}" ${error.message}`,
instancePath: error.instancePath,
};
if (error.keyword === SCHEMA_KEYWORDS.REQUIRED) {
baseObject = messages.MANIFEST_FIELD_REQUIRED;
} else if (error.keyword === SCHEMA_KEYWORDS.DEPRECATED) {
if (
Object.prototype.hasOwnProperty.call(
DEPRECATED_MANIFEST_PROPERTIES,
error.instancePath
)
) {
baseObject =
messages[DEPRECATED_MANIFEST_PROPERTIES[error.instancePath]];
if (baseObject === null) {
baseObject = messages.MANIFEST_FIELD_DEPRECATED;
}
let errorDescription = baseObject.description;
if (errorDescription === null) {
errorDescription = error.message;
}
// Set the description to the actual message from the schema
overrides.message = baseObject.message;
overrides.description = errorDescription;
}
// TODO(#2462): add a messages.MANIFEST_FIELD_DEPRECATED and ensure that deprecated
// properties are handled properly (e.g. we should also detect when the deprecated
// keyword is actually used to warn the developer of additional properties not
// explicitly defined in the schemas).
} else if (
error.keyword === SCHEMA_KEYWORDS.MIN_MANIFEST_VERSION ||
error.keyword === SCHEMA_KEYWORDS.MAX_MANIFEST_VERSION
) {
// Choose a different message for permissions unsupported with the
// add-on manifest_version.
if (PERMS_DATAPATH_REGEX.test(error.instancePath)) {
baseObject = messages.manifestPermissionUnsupported(error.data, error);
} else if (error.instancePath === '/applications') {
baseObject = messages.APPLICATIONS_INVALID;
} else {
baseObject = messages.manifestFieldUnsupported(
error.instancePath,
error
);
}
// Set the message and description from the one generated by the
// choosen message.
overrides.message = baseObject.message;
overrides.description = baseObject.description;
} else if (
error.instancePath.startsWith('/permissions') &&
error.keyword === SCHEMA_KEYWORDS.VALIDATE_PRIVILEGED_PERMISSIONS &&
error.params.privilegedPermissions
) {
if (this.isPrivilegedAddon) {
baseObject = error.params.privilegedPermissions.length
? messages.mozillaAddonsPermissionRequired(error)
: messages.privilegedFeaturesRequired(error);
} else {
baseObject = messages.manifestPermissionsPrivileged(error);
}
overrides.message = baseObject.message;
overrides.description = baseObject.description;
} else if (
error.instancePath.startsWith('/permissions') &&
typeof error.data !== 'undefined' &&
typeof error.data !== 'string'
) {
baseObject = messages.MANIFEST_BAD_PERMISSION;
overrides.message = `Permissions ${error.message}.`;
} else if (
error.instancePath.startsWith('/optional_permissions') &&
typeof error.data !== 'undefined' &&
typeof error.data !== 'string'
) {
baseObject = messages.MANIFEST_BAD_OPTIONAL_PERMISSION;
overrides.message = `Permissions ${error.message}.`;
} else if (
error.instancePath.startsWith('/host_permissions') &&
typeof error.data !== 'undefined' &&
typeof error.data !== 'string'
) {
baseObject = messages.MANIFEST_BAD_HOST_PERMISSION;
overrides.message = `Permissions ${error.message}.`;
} else if (error.keyword === SCHEMA_KEYWORDS.TYPE) {
baseObject = messages.MANIFEST_FIELD_INVALID;
} else if (error.keyword === SCHEMA_KEYWORDS.PRIVILEGED) {
baseObject = this.isPrivilegedAddon
? messages.mozillaAddonsPermissionRequired(error)
: messages.manifestFieldPrivileged(error);
overrides.message = baseObject.message;
overrides.description = baseObject.description;
}
// Arrays can be extremely verbose, this tries to make them a little
// more sane. Using a regex because there will likely be more as we
// expand the schema.
// Note that this works because the 2 regexps use similar patterns. We'll
// want to adjust this if they start to differ.
const match =
error.instancePath.match(PERMS_DATAPATH_REGEX) ||
error.instancePath.match(INSTALL_ORIGINS_DATAPATH_REGEX);
if (
match &&
baseObject.code !== messages.MANIFEST_BAD_PERMISSION.code &&
baseObject.code !== messages.MANIFEST_BAD_OPTIONAL_PERMISSION.code &&
baseObject.code !== messages.MANIFEST_BAD_HOST_PERMISSION.code &&
baseObject.code !== messages.MANIFEST_PERMISSION_UNSUPPORTED
) {
baseObject = messages[`MANIFEST_${match[1].toUpperCase()}`];
overrides.message = oneLine`/${match[1]}: Invalid ${match[1]}
"${error.data}" at ${match[2]}.`;
}
// Make sure we filter out warnings and errors code that should never be reported
// on manifest version 2 extensions.
const ignoredOnMV2 = [
messages.MANIFEST_HOST_PERMISSIONS.code,
messages.MANIFEST_BAD_HOST_PERMISSION.code,
];
if (
this.parsedJSON.manifest_version === 2 &&
ignoredOnMV2.includes(baseObject.code)
) {
return null;
}
return { ...baseObject, ...overrides };
}
_validate() {
// Not all messages returned by the schema are fatal to Firefox, messages
// that are just warnings should be added to this array.
const warnings = [
messages.MANIFEST_PERMISSIONS.code,
messages.MANIFEST_OPTIONAL_PERMISSIONS.code,
messages.MANIFEST_HOST_PERMISSIONS.code,
messages.MANIFEST_PERMISSION_UNSUPPORTED,
messages.MANIFEST_FIELD_UNSUPPORTED,
];
// Message with the following codes will be:
//
// - omitted if the add-on is being explicitly validated as privileged
// when the `--privileged` cli option was passed or `privileged` is
// set to true in the linter config. This is the case for privileged
// extensions in the https://github.com/mozilla-extensions/ org.
//
// - reported as warnings if the add-on is already signed
// (because it is expected for addons signed as privileged to be
// submitted to AMO to become listed, and so the warning is meant to
// be just informative and to let extension developers and reviewers
// to know that the extension is expected to be signed as privileged
// or it wouldn't work).
//
// - reported as errors if the add-on isn't signed, which should
// reject the submission of a privileged extension on AMO (and
// have it signed with a non privileged certificate by mistake).
const privilegedManifestMessages = [
messages.MANIFEST_PERMISSIONS_PRIVILEGED,
messages.MANIFEST_FIELD_PRIVILEGED,
];
if (this.isAlreadySigned) {
warnings.push(...privilegedManifestMessages);
}
let validate = validateAddon;
if (this.isStaticTheme) {
validate = validateStaticTheme;
} else if (this.isLanguagePack) {
validate = validateLangPack;
} else if (this.isDictionary) {
validate = validateDictionary;
} else if (this.isSitePermission) {
validate = validateSitePermission;
}
this.isValid = validate(this.parsedJSON, this.schemaValidatorOptions);
if (!this.isValid) {
log.debug(
'Schema Validation messages',
JSON.stringify(validate.errors, null, 2)
);
validate.errors.forEach((error) => {
const message = this.errorLookup(error);
// errorLookup call returned a null or undefined message,
// and so the error should be ignored.
if (!message) {
return;
}
if (warnings.includes(message.code)) {
this.collector.addWarning(message);
} else {
this.collector.addError(message);
}
// Add-ons with bad permissions will fail to install in Firefox, so
// we consider them invalid.
if (message.code === messages.MANIFEST_BAD_PERMISSION.code) {
this.isValid = false;
}
});
}
if (this.parsedJSON.applications?.gecko_android) {
this.collector.addError(
messages.manifestFieldUnsupported('/applications/gecko_android')
);
this.isValid = false;
}
if (this.parsedJSON.manifest_version < 3) {
if (
this.parsedJSON.browser_specific_settings?.gecko &&
this.parsedJSON.applications
) {
this.collector.addWarning(messages.IGNORED_APPLICATIONS_PROPERTY);
} else if (this.parsedJSON.applications) {
this.collector.addWarning(messages.APPLICATIONS_DEPRECATED);
}
}
if (
this.parsedJSON.browser_specific_settings &&
(this.parsedJSON.browser_specific_settings.gecko ||
this.parsedJSON.browser_specific_settings.gecko_android)
) {
this.parsedJSON.applications = {
...(this.parsedJSON.applications || {}),
...this.parsedJSON.browser_specific_settings,
};
}
if (
this.parsedJSON.manifest_version >= 3 &&
this.parsedJSON.browser_specific_settings?.gecko_android
) {
this.collector.addWarning(
messages.MANIFEST_V3_FIREFOX_ANDROID_LIMITATIONS
);
}
if (this.parsedJSON.content_security_policy != null) {
this.validateCspPolicy(this.parsedJSON.content_security_policy);
}
if (this.parsedJSON.update_url) {
this.collector.addNotice(messages.MANIFEST_UNUSED_UPDATE);
}
if (this.parsedJSON.granted_host_permissions) {
this.collector.addWarning(
messages.manifestFieldPrivilegedOnly('granted_host_permissions')
);
}
if (this.parsedJSON.background) {
const hasScripts = Array.isArray(this.parsedJSON.background.scripts);
if (hasScripts) {
this.parsedJSON.background.scripts.forEach((script) => {
this.validateFileExistsInPackage(script, 'script');
});
}
const hasPage = !!this.parsedJSON.background.page;
if (hasPage) {
this.validateFileExistsInPackage(
this.parsedJSON.background.page,
'page'
);
}
if (this.parsedJSON.background.service_worker) {
if (!this.schemaValidatorOptions?.enableBackgroundServiceWorker) {
// Report an error and mark the manifest as invalid if background
// service worker support isn't enabled by the addons-linter feature
// flag.
if (hasScripts || hasPage) {
this.collector.addWarning(
messages.manifestFieldUnsupported('/background/service_worker')
);
} else {
this.collector.addError(
messages.manifestFieldUnsupported('/background/service_worker')
);
this.isValid = false;
}
} else if (this.parsedJSON.manifest_version >= 3) {
this.validateFileExistsInPackage(
this.parsedJSON.background.service_worker,
'script'
);
}
}
}
if (
this.parsedJSON.content_scripts &&
this.parsedJSON.content_scripts.length
) {
this.parsedJSON.content_scripts.forEach((scriptRule) => {
if (scriptRule.matches && scriptRule.matches.length) {
// Since `include_globs` only get's checked for patterns that are in
// `matches` we only need to validate `matches`
scriptRule.matches.forEach((matchPattern) => {
this.validateContentScriptMatchPattern(matchPattern);
});
}
if (scriptRule.js && scriptRule.js.length) {
scriptRule.js.forEach((script) => {
this.validateFileExistsInPackage(
script,
'script',
messages.manifestContentScriptFileMissing
);
});
}
if (scriptRule.css && scriptRule.css.length) {
scriptRule.css.forEach((style) => {
this.validateFileExistsInPackage(
style,
'css',
messages.manifestContentScriptFileMissing
);
});
}
});
}
if (this.parsedJSON.dictionaries) {
if (!this.getAddonId()) {
this.collector.addError(messages.MANIFEST_DICT_MISSING_ID);
this.isValid = false;
}
const numberOfDictionaries = Object.keys(
this.parsedJSON.dictionaries
).length;
if (numberOfDictionaries < 1) {
this.collector.addError(messages.MANIFEST_EMPTY_DICTS);
this.isValid = false;
} else if (numberOfDictionaries > 1) {
this.collector.addError(messages.MANIFEST_MULTIPLE_DICTS);
this.isValid = false;
}
Object.keys(this.parsedJSON.dictionaries).forEach((locale) => {
const filepath = this.parsedJSON.dictionaries[locale];
this.validateFileExistsInPackage(
filepath,
'binary',
messages.manifestDictionaryFileMissing
);
// A corresponding .aff file should exist for every .dic.
this.validateFileExistsInPackage(
filepath.replace(/\.dic$/, '.aff'),
'binary',
messages.manifestDictionaryFileMissing
);
});
}
if (
!this.selfHosted &&
this.parsedJSON.applications &&
this.parsedJSON.applications.gecko &&
this.parsedJSON.applications.gecko.update_url
) {
if (this.isPrivilegedAddon) {
// We cannot know whether a privileged add-on will be listed or
// unlisted so we only emit a warning for MANIFEST_UPDATE_URL (not an
// error).
this.collector.addWarning(messages.MANIFEST_UPDATE_URL);
} else {
this.collector.addError(messages.MANIFEST_UPDATE_URL);
this.isValid = false;
}
}
if (
!this.isLanguagePack &&
(this.parsedJSON.applications?.gecko?.strict_max_version ||
this.parsedJSON.applications?.gecko_android?.strict_max_version)
) {
if (this.isDictionary) {
// Dictionaries should not have a strict_max_version at all.
this.isValid = false;
this.collector.addError(messages.STRICT_MAX_VERSION);
} else {
// Rest of the extensions can, even though it's not recommended.
this.collector.addNotice(messages.STRICT_MAX_VERSION);
}
}
const minFirefoxVersion = firefoxStrictMinVersion(this.parsedJSON);
const minAndroidVersion = androidStrictMinVersion(this.parsedJSON);
if (
!this.isLanguagePack &&
!this.isDictionary &&
(minFirefoxVersion || minAndroidVersion)
) {
for (const key in bcd.webextensions.manifest) {
if (Object.prototype.hasOwnProperty.call(this.parsedJSON, key)) {
const compatInfo = bcd.webextensions.manifest[key];
this.checkCompatInfo(
compatInfo,
minFirefoxVersion,
minAndroidVersion,
key,
this.parsedJSON[key]
);
}
}
}
this.validateName();
this.validateVersionString();
if (this.parsedJSON.default_locale) {
const msg = path.join(
LOCALES_DIRECTORY,
this.parsedJSON.default_locale,
'messages.json'
);
// Convert filename to unix path separator before
// searching it into the scanned files map.
if (!this.io.files[upath.toUnix(msg)]) {
this.collector.addError(messages.NO_MESSAGES_FILE);
this.isValid = false;
}
}
if (this?.io?.files) {
const fileList = Object.keys(this.io.files);
const localeDirRe = new RegExp(`^${LOCALES_DIRECTORY}/(.*?)/`);
const localeFileRe = new RegExp(
`^${LOCALES_DIRECTORY}/.*?/${MESSAGES_JSON}$`
);
const locales = [];
const localesWithMessagesJson = [];
const errors = [];
// Collect distinct locales (based on the content of `_locales/`) as
// well as the locales for which we have a `messages.json` file.
for (let i = 0; i < fileList.length; i++) {
const matches = fileList[i].match(localeDirRe);
if (matches && !locales.includes(matches[1])) {
locales.push(matches[1]);
}
if (matches && fileList[i].match(localeFileRe)) {
localesWithMessagesJson.push(matches[1]);
}
}
// Emit an error for each locale without a `messages.json` file.
for (let i = 0; i < locales.length; i++) {
if (!localesWithMessagesJson.includes(locales[i])) {
errors.push(
messages.noMessagesFileInLocales(
path.join(LOCALES_DIRECTORY, locales[i])
)
);
}
}
// When there is no default locale, we do not want to emit errors for
// missing locale files because we ignore those files.
if (!this.parsedJSON.default_locale) {
if (localesWithMessagesJson.length) {
this.collector.addError(messages.NO_DEFAULT_LOCALE);
this.isValid = false;
}
} else if (errors.length > 0) {
for (const error of errors) {
this.collector.addError(error);
}
this.isValid = false;
}
}
if (this.parsedJSON.developer) {
const { name, url } = this.parsedJSON.developer;
if (name) {
this.parsedJSON.author = name;
}
if (url) {
this.parsedJSON.homepage_url = url;
}
}
if (this.parsedJSON.homepage_url) {
this.validateHomePageURL(this.parsedJSON.homepage_url);
}
this.validateRestrictedPermissions();
this.validateExtensionID();
this.validateHiddenAddon();
this.validateDeprecatedBrowserStyle();
}
/**
* This method validates the manifest's name property in addition to the
* basic json schema validation. The name should not contain unnecessary
* whitespaces.
*/
validateName() {
const { name } = this.parsedJSON;
// The JSON schema validation already emits an error for non-string values.
if (typeof name !== 'string') {
return;
}
// We are relying on the `trim` function to remove the whitespaces but it
// doesn't cover all possible whitespace-like chars. See:
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/trim
const trimmedName = name.trim();
if (trimmedName !== name || trimmedName.length < 2) {
this.collector.addError(messages.PROP_NAME_INVALID);
this.isValid = false;
}
}
/**
* This method determines whether the value of the `version` manifest key is
* valid for both AMO and Firefox, and strictness is a bit different depending
* on the manifest version.
*
* For MV3+: we enforce the following format: the value must be a string that
* has between 1 and 4 numbers, separated with dots. Each number must have up
* to 9 digits and leading zeros are not allowed.
*
* For MV2 only: if the value matches the toolkit version, we emit a warning.
* Otherwise, we enforce the same format as defined above for MV3 and above.
*/
validateVersionString() {
const { version } = this.parsedJSON;
if (isValidVersionString(version)) {
return;
}
if (
this.parsedJSON.manifest_version < 3 &&
isToolkitVersionString(version)
) {
this.collector.addWarning(messages.VERSION_FORMAT_DEPRECATED);
} else {
this.collector.addError(messages.VERSION_FORMAT_INVALID);
this.isValid = false;
}
}
validateHiddenAddon() {
// Only privileged add-ons can use the `hidden` manifest property.
if (!this.isPrivilegedAddon) {
return;
}
if (
this.parsedJSON.hidden &&
('action' in this.parsedJSON ||
'browser_action' in this.parsedJSON ||
// Note: When this was introduced, it was stricter than the Firefox
// side because Firefox didn't restrict `page_action` in Bug 1781998.
'page_action' in this.parsedJSON)
) {
this.collector.addError(messages.HIDDEN_NO_ACTION);
this.isValid = false;
}
}
validateDeprecatedBrowserStyle() {
if (this.parsedJSON.manifest_version !== 3) {
// The deprecation only affects MV2 -> MV3.
return;
}
const checkBrowserStyleInManifestKey = (manifestKey) => {
// Warn about `browser_style:true` because it is not compatible with
// "future" Firefox versions (Firefox 118+). We don't warn about
// `browser_style:false` because it is equivalent to not setting the
// property. Furthermore, setting it to false ensures a consistent
// appearance of MV3 extensions in Firefox 114 and earlier, because the
// default of options_ui.browser_style and sidebar_action.browser_style
// changed from true to false in Firefox 115.
if (this.parsedJSON[manifestKey]?.browser_style) {
const instancePath = `/${manifestKey}/browser_style`;
// Minimal parameters to trigger manifest error.
const errorParam = { params: { max_manifest_version: 2 } };
this.collector.addWarning({
instancePath,
...messages.manifestFieldUnsupported(instancePath, errorParam),
});
}
};
checkBrowserStyleInManifestKey('action');
checkBrowserStyleInManifestKey('options_ui');
checkBrowserStyleInManifestKey('page_action');
checkBrowserStyleInManifestKey('sidebar_action');
}
validateRestrictedPermissions() {
const permissions = Array.isArray(this.parsedJSON.permissions)
? this.parsedJSON.permissions
: [];
const permissionsInManifest = permissions.map((permission) =>
String(permission).toLowerCase()
);
if (permissionsInManifest.length === 0) {
return;
}
const minVersionSetInManifest = String(
this.getMetadata().firefoxMinVersion
);
for (const permission of this.restrictedPermissions.keys()) {
if (permissionsInManifest.includes(permission)) {
const permMinVersion = this.restrictedPermissions.get(permission);
if (
!minVersionSetInManifest ||
mozCompare(minVersionSetInManifest, permMinVersion) === -1
) {
this.collector.addError(
messages.makeRestrictedPermission(permission, permMinVersion)
);
this.isValid = false;
}
}
}
}
validateExtensionID() {
if (this.parsedJSON.manifest_version < 3) {
return;
}
if (!this.parsedJSON.applications?.gecko?.id) {
this.collector.addError(messages.EXTENSION_ID_REQUIRED);
this.isValid = false;
}
}
async validateIcon(iconPath, expectedSize) {
try {
const info = await getImageMetadata(this.io, iconPath);
if (info.width !== info.height) {
if (info.mime !== 'image/svg+xml') {
this.collector.addError(messages.iconIsNotSquare(iconPath));
this.isValid = false;
} else {
this.collector.addWarning(messages.iconIsNotSquare(iconPath));
}
} else if (
expectedSize !== null &&
info.mime !== 'image/svg+xml' &&
parseInt(info.width, 10) !== parseInt(expectedSize, 10)
) {
this.collector.addWarning(
messages.iconSizeInvalid({
path: iconPath,
expected: parseInt(expectedSize, 10),
actual: parseInt(info.width, 10),
})
);
}
} catch (err) {
log.debug(
`Unexpected error raised while validating icon "${iconPath}"`,
err
);
this.collector.addWarning(
messages.corruptIconFile({
path: iconPath,
})
);
}
}
validateIcons() {
const icons = [];
if (this.parsedJSON.icons) {
Object.keys(this.parsedJSON.icons).forEach((size) => {
icons.push([size, this.parsedJSON.icons[size]]);
});
}
// Check for default_icon key at each of the action properties
['browser_action', 'page_action', 'sidebar_action'].forEach((key) => {
if (this.parsedJSON[key] && this.parsedJSON[key].default_icon) {
if (typeof this.parsedJSON[key].default_icon === 'string') {
icons.push([null, this.parsedJSON[key].default_icon]);
} else {
Object.keys(this.parsedJSON[key].default_icon).forEach((size) => {
icons.push([size, this.parsedJSON[key].default_icon[size]]);
});
}
}
});
// Check for the theme_icons from the browser_action
if (
this.parsedJSON.browser_action &&