From d167f676a167b1392a4e29f14ddf25613468680b Mon Sep 17 00:00:00 2001 From: Mark H Weaver Date: Tue, 26 Sep 2023 23:22:45 -0400 Subject: Update LibreJS to 7.21.1. --- .../META-INF/manifest.mf | 115 +- .../META-INF/mozilla.rsa | Bin 4345 -> 4345 bytes .../META-INF/mozilla.sf | 4 +- .../jid1-KtlZuoiikVfFew@jetpack/bundle.js | 3230 ++++++++++---------- .../jid1-KtlZuoiikVfFew@jetpack/common/Storage.js | 38 +- .../jid1-KtlZuoiikVfFew@jetpack/common/Test.js | 17 +- .../jid1-KtlZuoiikVfFew@jetpack/common/checks.js | 448 +++ .../jid1-KtlZuoiikVfFew@jetpack/common/debug.js | 37 + .../common/fname_data.json | 832 +++++ .../common/license_definitions.json | 449 +++ .../common/pattern_utils.js | 49 + .../content/contactFinder.js | 449 ++- .../jid1-KtlZuoiikVfFew@jetpack/content/dialog.css | 2 +- .../content/externalLicenseChecker.js | 74 +- .../html/preferences_panel/pref.js | 121 +- .../html/preferences_panel/prefs.css | 2 +- .../jid1-KtlZuoiikVfFew@jetpack/manifest.json | 2 +- 17 files changed, 3860 insertions(+), 2009 deletions(-) create mode 100644 data/extensions/jid1-KtlZuoiikVfFew@jetpack/common/checks.js create mode 100644 data/extensions/jid1-KtlZuoiikVfFew@jetpack/common/debug.js create mode 100644 data/extensions/jid1-KtlZuoiikVfFew@jetpack/common/fname_data.json create mode 100644 data/extensions/jid1-KtlZuoiikVfFew@jetpack/common/license_definitions.json create mode 100644 data/extensions/jid1-KtlZuoiikVfFew@jetpack/common/pattern_utils.js diff --git a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/manifest.mf b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/manifest.mf index a14b39d..880acb7 100644 --- a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/manifest.mf +++ b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/manifest.mf @@ -2,23 +2,53 @@ Manifest-Version: 1.0 Name: bundle.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: kfS6rxCTsJqlIABAaSlNYBhqVyg= -SHA256-Digest: G4dk5konL8+DuSbsLqcpd6Zc2ALYRuyD/xhW+nszVRE= +SHA1-Digest: PY5wNcArdIAD2nK4Dh5zga11nCo= +SHA256-Digest: s6fI2KZ67T6DWhemP4A41og9KqbyZF1ibKL90db3PGE= Name: manifest.json Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: yfYBwFqHoCmXUqWmFcGoJJ5pu6I= -SHA256-Digest: 2KaatpAW4OUZHE3LqwDi47d0YQ1N32sVfoxG14TBeyI= +SHA1-Digest: wCGdz91EnD1SMJtaueaYOid6aq0= +SHA256-Digest: wAjq7aq3LoE5GBwvhtM2S6m7eHwUNuk17NrPulGKzUM= + +Name: common/pattern_utils.js +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: tksSJk5+tTH9EPRHveXWcQLQasQ= +SHA256-Digest: qYPJnlgXiU4mqNh2AuwFXU6bCwFnVpZgCWH1p9If9Mc= + +Name: common/license_definitions.json +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: L75MS8yrqhw+f5rnAokuSpBCzn4= +SHA256-Digest: TzyEeprYDmHVgqVryo/HqmkZRvAl6K/glfFIUfhg7kw= + +Name: common/fname_data.json +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: jq9YJ+695dacLhTc/PeLv/q/ZNc= +SHA256-Digest: dHE8MO6HJ95u4fAUcD+z64kXxSs4yopRxC5FKhyH5zU= + +Name: common/debug.js +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: tuyQoLerC7uG2Sm4fPy+iOHCIz8= +SHA256-Digest: xBJ7o0qr23+bNRmPItKYgnKCEFKg5lme8AkW1oWKppQ= Name: common/Test.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: NW/C7GoVV05NEaSRbehFcj+u8kI= -SHA256-Digest: FKUY1ZzZ9Wjmp3i9TTRme4jwv1JrKUHTM8u6z6zjO90= +SHA1-Digest: vcjjROLgBC4613FPab/FFghFP/E= +SHA256-Digest: kRRBvCl7OsQ3WFlsNcO7ER3KlR5k9yJ1nvxlqTik7cs= + +Name: common/checks.js +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: 5pkcaLFV6WatdmjajuOhDMY4rG0= +SHA256-Digest: PfCrIUlJZlPSBS3DvwV5u/NvbViRMNW1KFbXO/CBYiw= Name: common/Storage.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: 3iw7sqXV1YrhhjAmiJ9mhX86gWs= -SHA256-Digest: EbTsZj1io4dPJuIsZDq9klk/p1JSOchOKS1cuOV+6QA= +SHA1-Digest: 8qL8gYXwPOy/9O+TtuQcsalQ6Dc= +SHA256-Digest: N2Jewna8j5H9/jg2MNuMSq9WbnYtoDjihZcdpOEcZJ8= + +Name: content/dialog.css +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: okq2m3So2NJ21mnToCkVzAyTzhw= +SHA256-Digest: AgEeTDzYIgN8yZUFHrM/J7ZUJA9a/q7ofOV6FIzQUHw= Name: content/overlay.css Digest-Algorithms: SHA1 SHA256 @@ -27,23 +57,13 @@ SHA256-Digest: QpbfWaEXXtxpCOA7o11c0plSmemhdrEp/AJF8uegrME= Name: content/externalLicenseChecker.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: 7JPFTnU/EfbKRLC6/AEUiGACRkA= -SHA256-Digest: gqn0deU0/EED+6+t2D69LeRCghlvMPH6RiHQgpleftc= - -Name: content/dialog.css -Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: OtHx7b2GxD8MYhJ2WJ6+FESRLt0= -SHA256-Digest: PmP1jGEKgeLl698KLlhzFHKr1kKuXGjs2fekHWfri40= +SHA1-Digest: oEfxR3QHQdaZLOGDI07NSoWzCCc= +SHA256-Digest: SLyZEsZWTs19zA/Ozt8dHJCY0xaX3T+0MTmtEp772jw= Name: content/contactFinder.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: 0pS9aGtJeDesXiN1PoDl1t5zcLQ= -SHA256-Digest: UU7DS2RDzLoty+2DKA2hp350m7oB/anwBa5cIdn6BYA= - -Name: html/mobile.js -Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: Rlsaps0mwLl0HJwPkcAwP10WUds= -SHA256-Digest: DjCIuaq2tQRZSL8nZCAZo3XhZyT0H8oNsVoUBwbSK2Q= +SHA1-Digest: 504SqJllyv+PlUAHh22CYi7Kea8= +SHA256-Digest: w22Jr0CHOtQAge2oh0wEASdhby0vw+30Zjtbhkgss8U= Name: html/librejs-title.png Digest-Algorithms: SHA1 SHA256 @@ -65,46 +85,51 @@ Digest-Algorithms: SHA1 SHA256 SHA1-Digest: VxWUQ31bhir4PZrxeCczHaTFB/Q= SHA256-Digest: XtMPewrOTJxncjL2YsgherVtMMFCHAv211GoiErGwgU= -Name: html/background-panel.png -Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: I7A+/TQ6qxT/KL1l28vAX/Hk6Vc= -SHA256-Digest: 8QXq/xEzAlvUjmlnoLZsSUNRzJVMlXfxvHXg+CjQCeo= - Name: html/README Digest-Algorithms: SHA1 SHA256 SHA1-Digest: KSboZB1+wr79Fe37Ilvk9wHbFUI= SHA256-Digest: woimzHpj0kwEyX4pkh/OEWZg+nZMy//j3FFaxIUUSqE= -Name: html/preferences_panel/prefs.css +Name: html/background-panel.png Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: pcsCRYBKnwUyTcRWuvjCTuQ/1ow= -SHA256-Digest: tka3B4VXzE/NnqA5QUSqUWqMGtGsjOyYaqrbB/mISdk= +SHA1-Digest: I7A+/TQ6qxT/KL1l28vAX/Hk6Vc= +SHA256-Digest: 8QXq/xEzAlvUjmlnoLZsSUNRzJVMlXfxvHXg+CjQCeo= -Name: html/preferences_panel/preferences_panel.html +Name: html/mobile.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: p4bT3dvEpLwlx+HSbEjaN/m/sWM= -SHA256-Digest: 5ulelouZj4FWFWe6RKw5CEOOMcrY8M8uc+O5xLM5mTg= +SHA1-Digest: Rlsaps0mwLl0HJwPkcAwP10WUds= +SHA256-Digest: DjCIuaq2tQRZSL8nZCAZo3XhZyT0H8oNsVoUBwbSK2Q= -Name: html/preferences_panel/pref.js +Name: html/display_panel/content/main_panel.js Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: EKekJYTJobwbWThLq7pr3+8u3EY= -SHA256-Digest: i7PL7oBaTDL2TCq/z1C0tshTUqsjSdm0Ko/X3anrZRQ= +SHA1-Digest: O82uqXfzRlRx34uSKSjXHmTAMTg= +SHA256-Digest: EMiM3Q3G7JDvUcfRQk0Vj/Aa3D/hzY1d+GqH9pAsxHQ= Name: html/display_panel/content/panel-styles.css Digest-Algorithms: SHA1 SHA256 SHA1-Digest: f2hf4t1D4PAI9c2BbxoBQd9kcko= SHA256-Digest: xD1r4fotCgzI4D6L2wvcPgmQYnu2CtmkpH4oVeK6Ci0= -Name: html/display_panel/content/main_panel.js -Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: O82uqXfzRlRx34uSKSjXHmTAMTg= -SHA256-Digest: EMiM3Q3G7JDvUcfRQk0Vj/Aa3D/hzY1d+GqH9pAsxHQ= - Name: html/display_panel/content/display-panel.html Digest-Algorithms: SHA1 SHA256 SHA1-Digest: u8VzSDA0kDQQXfsD6UD158yJolg= SHA256-Digest: XvtYXtpNj6tzZFz5HHVk94N6mwvJ+dL0Efpd+bmicWE= +Name: html/preferences_panel/preferences_panel.html +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: p4bT3dvEpLwlx+HSbEjaN/m/sWM= +SHA256-Digest: 5ulelouZj4FWFWe6RKw5CEOOMcrY8M8uc+O5xLM5mTg= + +Name: html/preferences_panel/prefs.css +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: N4XJ2uubM7Ml2KRGHim2/JtebHw= +SHA256-Digest: I58QSjVZ2zDQcw9ZtmqknHRIPo8/IYCYNmekNg/GSkM= + +Name: html/preferences_panel/pref.js +Digest-Algorithms: SHA1 SHA256 +SHA1-Digest: vdLhVkb7iHVcGbg0B5Wx97w7Y9E= +SHA256-Digest: KJogHfMXaOzOMvREEn/LhMUgaECHdMUfsvfU8Zxo0yk= + Name: icons/librejs.png Digest-Algorithms: SHA1 SHA256 SHA1-Digest: Q9vvlNA4dFCgNvsckbkM3AcbqC4= @@ -112,11 +137,11 @@ SHA256-Digest: iZ50DcoVMy8qEArQPbLCQyuf/vGeVkTS6Ja8K/E1nvU= Name: META-INF/cose.manifest Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: JkQ6mNTpcKj5WL49pTTemiOVIfU= -SHA256-Digest: ZfGRtCyTQNLUYzf+dI80KQVUpDTlGF0kiwjKDQh2bAM= +SHA1-Digest: yDADf2wkPCCFioJk2alq9/ZnL4w= +SHA256-Digest: ROldUBx5VGLIWpYENeK9dkakBYTE70U3TTFbqRGZtXM= Name: META-INF/cose.sig Digest-Algorithms: SHA1 SHA256 -SHA1-Digest: maGMCOBrVinIXQrNfJ73GpXA5Jc= -SHA256-Digest: 4HtoUWDsu3irZotYt1PoXHlCtFBWcLVnxoiB/ESBeqU= +SHA1-Digest: sfzJLkS1WXA73PQxT6ZuZ+4gt+U= +SHA256-Digest: uOTLvSqEVP0gP0KUVDjlmFlMuvU0IlfGezDN+TUl55o= diff --git a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.rsa b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.rsa index d02ceac..6ce26e4 100644 Binary files a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.rsa and b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.rsa differ diff --git a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.sf b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.sf index 2d68b25..9b0b5b3 100644 --- a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.sf +++ b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/META-INF/mozilla.sf @@ -1,4 +1,4 @@ Signature-Version: 1.0 -SHA1-Digest-Manifest: +ToYgqf4tDQIltPqzrnrF/W/sXI= -SHA256-Digest-Manifest: wc/XLVkYU3jngp1pOchNOLrMcLEa5J2buxYW+PXnzd4= +SHA1-Digest-Manifest: o88Sl4XaPgbvnq/pk8fUx96fdR8= +SHA256-Digest-Manifest: BHDk1+Y5OkPbjfUAstcgyxu7TJW24Kk7T5vQCP1Yx9k= diff --git a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/bundle.js b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/bundle.js index c6ce36e..5814f8c 100644 --- a/data/extensions/jid1-KtlZuoiikVfFew@jetpack/bundle.js +++ b/data/extensions/jid1-KtlZuoiikVfFew@jetpack/bundle.js @@ -3,6 +3,7 @@ * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. * * Copyright (C) 2018 Giorgio Maone +* Copyright (C) 2022 Yuchen Pei * * This file is part of GNU LibreJS. * @@ -26,45 +27,45 @@ 'use strict'; -let licensesByLabel = new Map(); -let licensesByUrl = new Map(); -{ - let { licenses } = require('../license_definitions'); - let mapByLabel = (label, license) => licensesByLabel.set(label.toUpperCase(), license); - for (let [id, l] of Object.entries(licenses)) { - let { identifier, canonicalUrl, licenseName } = l; - if (identifier) { - mapByLabel(identifier, l); - } else { - l.identifier = id; - } - if (id !== identifier) { - mapByLabel(id, l); - } - if (licenseName) { - mapByLabel(licenseName, l); - } - if (Array.isArray(canonicalUrl)) { - for (let url of canonicalUrl) { - licensesByUrl.set(url, l); - } - } +const licenses = require('../common/license_definitions.json') +const licensesByLabel = new Map(Object.entries(licenses).map(([id, license]) => + [ + [license.identifier.toUpperCase(), license], + [id.toUpperCase(), license], + [license.licenseName.toUpperCase(), license] + ]).flat()); +const licensesByUrl = new Map(Object.values(licenses).map(license => + license.canonicalUrl.map(url => [url, license])).flat()); +for (const [id, license] of Object.entries(licenses)) { + if (!license.identifier) { + license.identifier = id; } } -let cachedHrefs = new Map(); +const cachedHrefs = new Map(); -var ExternalLicenses = { +const ExternalLicenses = { purgeCache(tabId) { cachedHrefs.delete(tabId); }, + /** + * Checks external script using web labels + * + * If the script cannot be found in the web labels table, returns null. + * + * If the script can be found in the web labels table, and at least + * one of its licenses can be found in our free license DB, returns + * "free". + * + * Otherwise returns "nonfree". + */ async check(script) { - let { url, tabId, frameId, documentUrl } = script; - let tabCache = cachedHrefs.get(tabId); - let frameCache = tabCache && tabCache.get(frameId); - let cache = frameCache && frameCache.get(documentUrl); - let scriptInfo = await browser.tabs.sendMessage(tabId, { + const { url, tabId, frameId, documentUrl } = script; + const tabCache = cachedHrefs.get(tabId); + const frameCache = tabCache && tabCache.get(frameId); + const cache = frameCache && frameCache.get(documentUrl); + const scriptInfo = await browser.tabs.sendMessage(tabId, { action: 'checkLicensedScript', url, cache, @@ -73,26 +74,13 @@ var ExternalLicenses = { if (!(scriptInfo && scriptInfo.licenseLinks.length)) { return null; } - scriptInfo.licenses = new Set(); - scriptInfo.toString = function() { - let licenseIds = [...this.licenses].map(l => l.identifier).sort().join(', '); - return licenseIds - ? `Free license${this.licenses.size > 1 ? 's' : ''} (${licenseIds})` - : 'Unknown license(s)'; - } - let match = (map, key) => { - if (map.has(key)) { - scriptInfo.licenses.add(map.get(key)); - return true; - } - return false; - }; - - for (let { label, url } of scriptInfo.licenseLinks) { - match(licensesByLabel, label = label.trim().toUpperCase()) || - match(licensesByUrl, url) || - match(licensesByLabel, label.replace(/^GNU-|-(?:OR-LATER|ONLY)$/, '')); - } + scriptInfo.licenses = new Set(scriptInfo.licenseLinks.map( + ({ label, url }) => { + const uLabel = label.trim().toUpperCase(); + const license = licensesByLabel.get(uLabel) || licensesByUrl.get(url) || + licensesByLabel.get(uLabel.replace(/^GNU-|-(?:OR-LATER|ONLY)$/, '')); + return license ? [license] : []; + }).flat()); scriptInfo.free = scriptInfo.licenses.size > 0; return scriptInfo; }, @@ -105,34 +93,33 @@ var ExternalLicenses = { * Returns true if the document has been actually modified, false otherwise. */ optimizeDocument(doc, cachePointer) { - let cache = {}; - let { tabId, frameId, documentUrl } = cachePointer; - let frameCache = cachedHrefs.get(tabId); - if (!frameCache) { - cachedHrefs.set(tabId, frameCache = new Map()); - } + const cache = {}; + const { tabId, frameId, documentUrl } = cachePointer; + const frameCache = cachedHrefs.get(tabId) || new Map(); + cachedHrefs.set(tabId, frameCache); frameCache.set(frameId, new Map([[documentUrl, cache]])); - let link = doc.querySelector('link[rel="jslicense"], link[data-jslicense="1"], a[rel="jslicense"], a[data-jslicense="1"]'); + const link = doc.querySelector('link[rel="jslicense"], link[data-jslicense="1"], a[rel="jslicense"], a[data-jslicense="1"]'); if (link) { - let href = link.getAttribute('href'); + const href = link.getAttribute('href'); cache.webLabels = { href }; - let move = () => !!doc.head.insertBefore(link, doc.head.firstChild); + const move = (link) => !!doc.head.insertBefore(link, doc.head.firstChild); if (link.parentNode === doc.head) { + // TODO: eliminate let let node = link.previousElementSibling; for (; node; node = node.previousElementSibling) { if (node.tagName.toUpperCase() === 'SCRIPT') { - return move(); + return move(link); } } } else { // the reference is only in the body if (link.tagName.toUpperCase() === 'A') { - let newLink = doc.createElement('link'); + const newLink = doc.createElement('link'); newLink.rel = 'jslicense'; newLink.setAttribute('href', href); - link = newLink; + return move(newLink); } - return move(); + return move(link); } } @@ -143,11 +130,12 @@ var ExternalLicenses = { module.exports = { ExternalLicenses }; -},{"../license_definitions":10}],2:[function(require,module,exports){ +},{"../common/license_definitions.json":10}],2:[function(require,module,exports){ /** * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. * * Copyright (C) 2018 Giorgio Maone +* Copyright (C) 2022 Yuchen Pei * * This file is part of GNU LibreJS. * @@ -169,7 +157,7 @@ module.exports = { ExternalLicenses }; A class to manage whitelist/blacklist operations */ -let { ListStore } = require('../common/Storage'); +const { ListStore } = require('../common/Storage'); class ListManager { constructor(whitelist, blacklist, builtInHashes) { @@ -195,8 +183,8 @@ class ListManager { Returns "blacklisted", "whitelisted" or defValue */ getStatus(key, defValue = 'unknown') { - let { blacklist, whitelist } = this.lists; - let inline = ListStore.inlineItem(key); + const { blacklist, whitelist } = this.lists; + const inline = ListStore.inlineItem(key); if (inline) { return blacklist.contains(inline) ? 'blacklisted' @@ -204,10 +192,10 @@ class ListManager { : defValue; } - let match = key.match(/\(([^)]+)\)(?=[^()]*$)/); + const match = key.match(/\(([^)]+)\)(?=[^()]*$)/); if (!match) { - let url = ListStore.urlItem(key); - let site = ListStore.siteItem(key); + const url = ListStore.urlItem(key); + const site = ListStore.siteItem(key); return (blacklist.contains(url) || ListManager.siteMatch(site, blacklist) ? 'blacklisted' : whitelist.contains(url) || ListManager.siteMatch(site, whitelist) @@ -215,7 +203,7 @@ class ListManager { ); } - let [hashItem, srcHash] = match; // (hash), hash + const [hashItem, srcHash] = match; // (hash), hash return blacklist.contains(hashItem) ? 'blacklisted' : this.builtInHashes.has(srcHash) || whitelist.contains(hashItem) ? 'whitelisted' @@ -227,20 +215,14 @@ class ListManager { wildcarded subdomains ("https://*.domain.com/*"). */ static siteMatch(url, list) { - let site = ListStore.siteItem(url); - if (list.contains(site)) { - return site; - } - site = site.replace(/^([\w-]+:\/\/)?(\w)/, '$1*.$2'); - for (; ;) { - if (list.contains(site)) { - return site; - } - let oldKey = site; - site = site.replace(/(?:\*\.)*\w+(?=\.)/, '*'); - if (site === oldKey) { - return null; - } + const site = ListStore.siteItem(url); + if (list.contains(site)) return site; + // TODO: get rid of let + for (let replaced = site.replace(/^([\w-]+:\/\/)?(\w)/, '$1*.$2'); ;) { + if (list.contains(replaced)) return replaced; + const oldKey = replaced; + replaced = replaced.replace(/(?:\*\.)*\w+(?=\.)/, '*'); + if (oldKey === replaced) return null; } } } @@ -359,6 +341,7 @@ module.exports = { ResponseMetaData }; * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. * * Copyright (C) 2018 Giorgio Maone +* Copyright (C) 2022 Yuchen Pei * * This file is part of GNU LibreJS. * @@ -381,16 +364,21 @@ module.exports = { ResponseMetaData }; only the "interesting" HTML and script requests and leaving the other alone */ -let { ResponseMetaData } = require('./ResponseMetaData'); +const { ResponseMetaData } = require('./ResponseMetaData'); -let listeners = new WeakMap(); -let webRequestEvent = browser.webRequest.onHeadersReceived; +const listeners = new WeakMap(); +const webRequestEvent = browser.webRequest.onHeadersReceived; +// Some hardcoded return values for the onHeadersReceived callback. +const BLOCKING_RESPONSES = { + ACCEPT: {}, // Do nothing + REJECT: { cancel: true }, // Cancel the request. See docs of BlockingResponse +}; class ResponseProcessor { static install(handler, types = ['main_frame', 'sub_frame', 'script']) { if (listeners.has(handler)) return false; - let listener = + const listener = async request => await new ResponseTextFilter(request).process(handler); listeners.set(handler, listener); webRequestEvent.addListener( @@ -402,25 +390,18 @@ class ResponseProcessor { } static uninstall(handler) { - let listener = listeners.get(handler); + const listener = listeners.get(handler); if (listener) { webRequestEvent.removeListener(listener); } } } -Object.assign(ResponseProcessor, { - // control flow values to be returned by handler.pre() callbacks - ACCEPT: {}, - REJECT: { cancel: true }, - CONTINUE: null -}); - class ResponseTextFilter { constructor(request) { this.request = request; - let { type, statusCode } = request; - let md = this.metaData = new ResponseMetaData(request); + const { type, statusCode } = request; + const md = this.metaData = new ResponseMetaData(request); this.canProcess = // we want to process html documents and scripts only (statusCode < 300 || statusCode >= 400) && // skip redirections !md.disposition && // skip forced downloads @@ -428,30 +409,35 @@ class ResponseTextFilter { } async process(handler) { - if (!this.canProcess) return ResponseProcessor.ACCEPT; - let { metaData, request } = this; - let response = { request, metaData }; // we keep it around allowing callbacks to store state - if (typeof handler.pre === 'function') { - let res = await handler.pre(response); - if (res) return res; - if (handler.post) handler = handler.post; - if (typeof handler !== 'function') return ResponseProcessor.ACCEPT; - } - - let { requestId } = request; - let filter = browser.webRequest.filterResponseData(requestId); + if (!this.canProcess) return BlockingResponses.ACCEPT; + const { metaData, request } = this; + const response = { request, metaData }; // we keep it around allowing callbacks to store state + + if (typeof handler.pre !== 'function' || typeof handler.post !== 'function') { + throw new Error('handler should have a pre and post function.'); + } + + // If can determine without checking and filtering response + // payload then return. + const res = await handler.pre(response); + if (res) return res; + + const { requestId } = request; + // create a filter to modify response data, see + // Mozilla/Add-ons/WebExtensions/API/webRequest/filterResponseData + const filter = browser.webRequest.filterResponseData(requestId); let buffer = []; filter.ondata = event => { buffer.push(event.data); }; - filter.onstop = async unused => { + filter.onstop = async _ => { // concatenate chunks - let size = buffer.reduce((sum, chunk) => sum + chunk.byteLength, 0) + const size = buffer.reduce((sum, chunk) => sum + chunk.byteLength, 0) let allBytes = new Uint8Array(size); let pos = 0; - for (let chunk of buffer) { + for (const chunk of buffer) { allBytes.set(new Uint8Array(chunk), pos); pos += chunk.byteLength; } @@ -470,13 +456,13 @@ class ResponseTextFilter { } let editedText = null; try { - editedText = await handler(response); + editedText = await handler.post(response); } catch (e) { console.error(e); } - if (editedText !== null && editedText.indexOf('/* LibreJS: script accepted') !== 0) { + if (editedText !== null && editedText !== response.text) { // we changed the content, let's re-encode - let encoded = new TextEncoder().encode(editedText); + const encoded = new TextEncoder().encode(editedText); // pre-pending the UTF-8 BOM will force the charset per HTML 5 specs allBytes = new Uint8Array(encoded.byteLength + 3); allBytes.set(ResponseMetaData.UTF8BOM, 0); // UTF-8 BOM @@ -486,17 +472,19 @@ class ResponseTextFilter { filter.close(); } - return ResponseProcessor.ACCEPT; + // Accepting the filtered payload. + return BLOCKING_RESPONSES.ACCEPT; } } -module.exports = { ResponseProcessor }; +module.exports = { ResponseProcessor, BLOCKING_RESPONSES }; },{"./ResponseMetaData":3}],5:[function(require,module,exports){ /** * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. * * Copyright (C) 2018 Giorgio Maone +* Copyright (C) 2022 Yuchen Pei * * This file is part of GNU LibreJS. * @@ -520,13 +508,13 @@ module.exports = { ResponseProcessor }; */ 'use strict'; -var Storage = { + +const Storage = { ARRAY: { async load(key, array = undefined) { - if (array === undefined) { - array = (await browser.storage.local.get(key))[key]; - } - return array ? new Set(array) : new Set(); + const result = array === undefined ? + (await browser.storage.local.get(key))[key] : array; + return result ? new Set(result) : new Set(); }, async save(key, list) { return await browser.storage.local.set({ [key]: [...list] }); @@ -535,7 +523,7 @@ var Storage = { CSV: { async load(key) { - let csv = (await browser.storage.local.get(key))[key]; + const csv = (await browser.storage.local.get(key))[key]; return csv ? new Set(csv.split(/\s*,\s*/)) : new Set(); }, @@ -572,7 +560,7 @@ class ListStore { return hash.startsWith('(') ? hash : `(${hash})`; } static urlItem(url) { - let queryPos = url.indexOf('?'); + const queryPos = url.indexOf('?'); return queryPos === -1 ? url : url.substring(0, queryPos); } static siteItem(url) { @@ -603,24 +591,14 @@ class ListStore { } async store(...items) { - let size = this.items.size; - let changed = false; - for (let item of items) { - if (size !== this.items.add(item).size) { - changed = true; - } - } - return changed && await this.save(); + const size = this.items.size; + const changed = items.reduce((current, item) => size !== this.items.add(item).size || current, false); + changed && await this.save(); } async remove(...items) { - let changed = false; - for (let item of items) { - if (this.items.delete(item)) { - changed = true; - } - } - return changed && await this.save(); + const changed = items.reduce((current, item) => this.items.delete(item) || current, false); + changed && await this.save(); } contains(item) { @@ -629,21 +607,23 @@ class ListStore { } function hash(source) { - var shaObj = new jssha('SHA-256', 'TEXT') + const shaObj = new jssha('SHA-256', 'TEXT') shaObj.update(source); return shaObj.getHash('HEX'); } if (typeof module === 'object') { module.exports = { ListStore, Storage, hash }; + // TODO: eliminate the var var jssha = require('jssha'); } -},{"jssha":13}],6:[function(require,module,exports){ +},{"jssha":14}],6:[function(require,module,exports){ /** * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. * * Copyright (C) 2018 Giorgio Maone +* Copyright (C) 2022 Yuchen Pei * * This file is part of GNU LibreJS. * @@ -662,27 +642,25 @@ if (typeof module === 'object') { */ 'use strict'; -var Test = (() => { - const RUNNER_URL = browser.extension.getURL('/test/SpecRunner.html'); +const Test = (() => { + const RUNNER_URL = browser.runtime.getURL('/test/SpecRunner.html'); return { /* returns RUNNER_URL if it's a test-enabled build or an about:debugging temporary extension session, null otherwise */ async getURL() { - let url = RUNNER_URL; try { - await fetch(url); + await fetch(RUNNER_URL); + return RUNNER_URL; } catch (e) { - url = null; + return null; } - this.getURL = () => url; - return url; }, async getTab(activate = false) { - let url = await this.getURL(); - let tab = url ? (await browser.tabs.query({ url }))[0] || + const url = await this.getURL(); + const tab = url ? (await browser.tabs.query({ url }))[0] || (await browser.tabs.create({ url })) : null; if (tab && activate) { @@ -697,231 +675,720 @@ if (typeof module === 'object') { } },{}],7:[function(require,module,exports){ -module.exports={ - "fname_data": { - "WebGLShader": true, - "WebGLShaderPrecisionFormat": true, - "WebGLQuery": true, - "WebGLRenderbuffer": true, - "WebGLSampler": true, - "WebGLUniformLocation": true, - "WebGLFramebuffer": true, - "WebGLProgram": true, - "WebGLContextEvent": true, - "WebGL2RenderingContext": true, - "WebGLTexture": true, - "WebGLRenderingContext": true, - "WebGLVertexArrayObject": true, - "WebGLActiveInfo": true, - "WebGLTransformFeedback": true, - "WebGLSync": true, - "WebGLBuffer": true, - "cat_svg": true, - "SVGPoint": true, - "SVGEllipseElement": true, - "SVGRadialGradientElement": true, - "SVGComponentTransferFunctionElement": true, - "SVGPathSegCurvetoQuadraticAbs": true, - "SVGAnimatedNumberList": true, - "SVGPathSegCurvetoQuadraticSmoothRel": true, - "SVGFEColorMatrixElement": true, - "SVGPathSegLinetoHorizontalAbs": true, - "SVGLinearGradientElement": true, - "SVGStyleElement": true, - "SVGPathSegMovetoRel": true, - "SVGStopElement": true, - "SVGPathSegLinetoRel": true, - "SVGFEConvolveMatrixElement": true, - "SVGAnimatedAngle": true, - "SVGPathSegLinetoAbs": true, - "SVGPreserveAspectRatio": true, - "SVGFEOffsetElement": true, - "SVGFEImageElement": true, - "SVGFEDiffuseLightingElement": true, - "SVGAnimatedNumber": true, - "SVGTextElement": true, - "SVGFESpotLightElement": true, - "SVGFEMorphologyElement": true, - "SVGAngle": true, - "SVGScriptElement": true, - "SVGFEDropShadowElement": true, - "SVGPathSegArcRel": true, - "SVGNumber": true, - "SVGPathSegLinetoHorizontalRel": true, - "SVGFEFuncBElement": true, - "SVGClipPathElement": true, - "SVGPathSeg": true, - "SVGUseElement": true, - "SVGPathSegArcAbs": true, - "SVGPathSegCurvetoQuadraticSmoothAbs": true, - "SVGRect": true, - "SVGAnimatedPreserveAspectRatio": true, - "SVGImageElement": true, - "SVGAnimatedEnumeration": true, - "SVGAnimatedLengthList": true, - "SVGFEFloodElement": true, - "SVGFECompositeElement": true, - "SVGAElement": true, - "SVGAnimatedBoolean": true, - "SVGMaskElement": true, - "SVGFilterElement": true, - "SVGPathSegLinetoVerticalRel": true, - "SVGAnimatedInteger": true, - "SVGTSpanElement": true, - "SVGMarkerElement": true, - "SVGStringList": true, - "SVGTransform": true, - "SVGTitleElement": true, - "SVGFEBlendElement": true, - "SVGTextPositioningElement": true, - "SVGFEFuncGElement": true, - "SVGFEPointLightElement": true, - "SVGAnimateElement": true, - "SVGPolylineElement": true, - "SVGDefsElement": true, - "SVGPathSegList": true, - "SVGAnimatedTransformList": true, - "SVGPathSegClosePath": true, - "SVGGradientElement": true, - "SVGSwitchElement": true, - "SVGViewElement": true, - "SVGUnitTypes": true, - "SVGPathSegMovetoAbs": true, - "SVGSymbolElement": true, - "SVGFEFuncAElement": true, - "SVGAnimatedString": true, - "SVGFEMergeElement": true, - "SVGPathSegLinetoVerticalAbs": true, - "SVGAnimationElement": true, - "SVGPathSegCurvetoCubicAbs": true, - "SVGLength": true, - "SVGTextPathElement": true, - "SVGPolygonElement": true, - "SVGAnimatedRect": true, - "SVGPathSegCurvetoCubicRel": true, - "SVGFEFuncRElement": true, - "SVGLengthList": true, - "SVGTextContentElement": true, - "SVGFETurbulenceElement": true, - "SVGMatrix": true, - "SVGZoomAndPan": true, - "SVGMetadataElement": true, - "SVGFEDistantLightElement": true, - "SVGAnimateMotionElement": true, - "SVGDescElement": true, - "SVGPathSegCurvetoCubicSmoothRel": true, - "SVGFESpecularLightingElement": true, - "SVGFEGaussianBlurElement": true, - "SVGFEComponentTransferElement": true, - "SVGNumberList": true, - "SVGTransformList": true, - "SVGForeignObjectElement": true, - "SVGRectElement": true, - "SVGFEDisplacementMapElement": true, - "SVGAnimateTransformElement": true, - "SVGAnimatedLength": true, - "SVGPointList": true, - "SVGPatternElement": true, - "SVGPathSegCurvetoCubicSmoothAbs": true, - "SVGCircleElement": true, - "SVGSetElement": true, - "SVGFETileElement": true, - "SVGMPathElement": true, - "SVGFEMergeNodeElement": true, - "SVGPathSegCurvetoQuadraticRel": true, - "SVGElement": true, - "SVGGraphicsElement": true, - "SVGSVGElement": true, - "SVGGElement": true, - "SVGGeometryElement": true, - "SVGPathElement": true, - "SVGLineElement": true, - "cat_html": true, - "HTMLTimeElement": true, - "HTMLPictureElement": true, - "HTMLMenuItemElement": true, - "HTMLFormElement": true, - "HTMLOptionElement": true, - "HTMLCanvasElement": true, - "HTMLTableSectionElement": true, - "HTMLSelectElement": true, - "HTMLUListElement": true, - "HTMLMetaElement": true, - "HTMLLinkElement": true, - "HTMLBaseElement": true, - "HTMLDataListElement": true, - "HTMLInputElement": true, - "HTMLMeterElement": true, - "HTMLSourceElement": true, - "HTMLTrackElement": true, - "HTMLTableColElement": true, - "HTMLFieldSetElement": true, - "HTMLDirectoryElement": true, - "HTMLTableCellElement": true, - "HTMLStyleElement": true, - "HTMLAudioElement": true, - "HTMLLegendElement": true, - "HTMLOListElement": true, - "HTMLEmbedElement": true, - "HTMLQuoteElement": true, - "HTMLMenuElement": true, - "HTMLHeadElement": true, - "HTMLUnknownElement": true, - "HTMLBRElement": true, - "HTMLProgressElement": true, - "HTMLMediaElement": true, - "HTMLFormControlsCollection": true, - "HTMLCollection": true, - "HTMLLIElement": true, - "HTMLDetailsElement": true, - "HTMLObjectElement": true, - "HTMLHeadingElement": true, - "HTMLTableCaptionElement": true, - "HTMLPreElement": true, - "HTMLAllCollection": true, - "HTMLFrameSetElement": true, - "HTMLFontElement": true, - "HTMLFrameElement": true, - "HTMLAnchorElement": true, - "HTMLOptGroupElement": true, - "HTMLVideoElement": true, - "HTMLModElement": true, - "HTMLBodyElement": true, - "HTMLTableElement": true, - "HTMLButtonElement": true, - "HTMLTableRowElement": true, - "HTMLAreaElement": true, - "HTMLDataElement": true, - "HTMLParamElement": true, - "HTMLLabelElement": true, - "HTMLTemplateElement": true, - "HTMLOptionsCollection": true, - "HTMLIFrameElement": true, - "HTMLTitleElement": true, - "HTMLMapElement": true, - "HTMLOutputElement": true, - "HTMLDListElement": true, - "HTMLParagraphElement": true, - "HTMLHRElement": true, - "HTMLImageElement": true, - "HTMLDocument": true, - "HTMLElement": true, - "HTMLScriptElement": true, - "HTMLHtmlElement": true, - "HTMLTextAreaElement": true, - "HTMLDivElement": true, - "HTMLSpanElement": true, - "cat_css": true, - "CSSStyleRule": true, - "CSSFontFaceRule": true, - "CSSPrimitiveValue": true, - "CSSStyleDeclaration": true, - "CSSStyleSheet": true, - "CSSPageRule": true, - "CSSSupportsRule": true, - "CSSMozDocumentRule": true, - "CSSKeyframeRule": true, - "CSSGroupingRule": true, +/** +* GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. +* * +* Copyright (C) 2018 Nathan Nichols +* Copyright (C) 2022 Yuchen Pei +* +* This file is part of GNU LibreJS. +* +* GNU LibreJS is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* GNU LibreJS is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with GNU LibreJS. If not, see . +*/ + +const acorn = require('acorn'); +const licenses = require('./license_definitions.json'); +const { patternUtils } = require('./pattern_utils.js'); +const { makeDebugLogger } = require('./debug.js'); +const fnameData = require('./fname_data.json').fname_data; + +const LIC_RE = /@licstartThefollowingistheentirelicensenoticefortheJavaScriptcodeinthis(?:page|file)(.*)?@licendTheaboveistheentirelicensenoticefortheJavaScriptcodeinthis(?:page|file)/mi; + +/* + NONTRIVIAL THINGS: + - Fetch + - XMLhttpRequest + - eval() + - ? + JAVASCRIPT CAN BE FOUND IN: + - Event handlers (onclick, onload, onsubmit, etc.) + - + - + WAYS TO DETERMINE PASS/FAIL: + - "// @license [magnet link] [identifier]" then "// @license-end" (may also use /* comments) + - Automatic whitelist: (http://bzr.savannah.gnu.org/lh/librejs/dev/annotate/head:/data/script_libraries/script-libraries.json_ +*/ +// These are objects that it will search for in an initial regex pass over non-free scripts. +const RESERVED_OBJECTS = [ + //"document", + //"window", + 'fetch', + 'XMLHttpRequest', + 'chrome', // only on chrome + 'browser', // only on firefox + 'eval' +]; +const LOOPKEYS = new Set(['for', 'if', 'while', 'switch']); +const OPERATORS = new Set(['||', '&&', '=', '==', '++', '--', '+=', '-=', '*']); +// @license match, second and third capture groups are canonicalUrl +// and license name +// Caveat: will not work in a commented out star comments: +// '// /* @license */ ... /* @license-end */' will be checked, though +// the whole thing is a comment +const OPENING_LICENSE_RE1 = /^\s*\/\/\s*@license\s+(\S+)\s+(\S+).*$/mi; +const OPENING_LICENSE_RE2 = /\/\*\s*?@license\s+(\S+)\s+([^/*]+).*\*\//mi; +const CLOSING_LICENSE_RE1 = /^\s*\/\/\s*@license-end\s*/mi; +const CLOSING_LICENSE_RE2 = /\/\*\s*@license-end\s*\*\//mi; +/** +* If this is true, it evaluates entire scripts instead of returning as soon as it encounters a violation. +* +* Also, it controls whether or not this part of the code logs to the console. +* +*/ +const DEBUG = false; // debug the JS evaluation +const PRINT_DEBUG = false; +const dbg_print = makeDebugLogger('checks.js', PRINT_DEBUG, Date.now()); + +/** + * stripLicenseToRegexp + * + * Removes all non-alphanumeric characters except for the + * special tokens, and replace the text values that are + * hardcoded in license_definitions.js. Puts the result in + * the regex field of the fragments. + * + */ +const stripLicenseToRegexp = function(license) { + for (const frag of license.licenseFragments) { + frag.regex = patternUtils.removeNonalpha(frag.text); + frag.regex = new RegExp( + patternUtils.replaceTokens(frag.regex), ''); + } +}; + +const init = function() { + console.log('initializing regexes'); + for (const key in licenses) { + stripLicenseToRegexp(licenses[key]); + } +} + +/** +* +* Takes in the declaration that has been preprocessed and +* tests it against regexes in licenses. +*/ +const searchTable = function(strippedComment) { + const stripped = patternUtils.removeNonalpha(strippedComment); + // looking up license + for (const key in licenses) { + const license = licenses[key]; + for (const frag of license.licenseFragments) { + if (frag.regex.test(stripped)) { + return license.licenseName; + } + } + } + console.log('No global license found.'); + return null; +} + +/** + * Checks whether licenseText, modulo whitespace, starts with + * a @licstart .. @licend with a free license, returns the license name + * if so, and null otherwise. + */ +const checkLicenseText = function(licenseText) { + if (licenseText === undefined || licenseText === null) { + return null; + } + // remove whitespace + const stripped = patternUtils.removeWhitespace(licenseText); + // Search for @licstart/@licend + const matches = stripped.match(LIC_RE); + return matches && searchTable(matches[0]); +}; + +//************************this part can be tested in the HTML file index.html's script test.js**************************** + +/** + * Checks whether script is trivial by analysing its tokens. + * + * Returns an array of + * [flag (boolean, true if trivial), reason (string, human readable report)]. + */ +function fullEvaluate(script) { + if (script === undefined || script == '') { + return [true, 'Harmless null script']; + } + + let tokens; + + try { + tokens = acorn.tokenizer(script); + } catch (e) { + console.warn('Tokenizer could not be initiated (probably invalid code)'); + return [false, 'Tokenizer could not be initiated (probably invalid code)']; + } + try { + var toke = tokens.getToken(); + } catch (e) { + console.log(script); + console.log(e); + console.warn('couldn\'t get first token (probably invalid code)'); + console.warn('Continuing evaluation'); + } + + let amtloops = 0; + let definesFunctions = false; + + /** + * Given the end of an identifer token, it tests for parentheses + */ + function is_bsn(end) { + let i = 0; + while (script.charAt(end + i).match(/\s/g) !== null) { + i++; + if (i >= script.length - 1) { + return false; + } + } + return script.charAt(end + i) == '['; + } + + function evaluateByTokenValue(toke) { + const value = toke.value; + if (OPERATORS.has(value)) { + // It's just an operator. Javascript doesn't have operator overloading so it must be some + // kind of primitive (I.e. a number) + } else { + const status = fnameData[value]; + if (status === true) { // is the identifier banned? + dbg_print('%c NONTRIVIAL: nontrivial token: \'' + value + '\'', 'color:red'); + if (DEBUG == false) { + return [false, 'NONTRIVIAL: nontrivial token: \'' + value + '\'']; + } + } else if (status === false || status === undefined) {// is the identifier not banned or user defined? + // Is there bracket suffix notation? + if (is_bsn(toke.end)) { + dbg_print('%c NONTRIVIAL: Bracket suffix notation on variable \'' + value + '\'', 'color:red'); + if (DEBUG == false) { + return [false, '%c NONTRIVIAL: Bracket suffix notation on variable \'' + value + '\'']; + } + } + } else { + dbg_print('trivial token:' + value); + } + } + return [true, '']; + } + + function evaluateByTokenTypeKeyword(keyword) { + if (toke.type.keyword == 'function') { + dbg_print('%c NOTICE: Function declaration.', 'color:green'); + definesFunctions = true; + } + + if (LOOPKEYS.has(keyword)) { + amtloops++; + if (amtloops > 3) { + dbg_print('%c NONTRIVIAL: Too many loops/conditionals.', 'color:red'); + if (DEBUG == false) { + return [false, 'NONTRIVIAL: Too many loops/conditionals.']; + } + } + } + return [true, '']; + } + + while (toke !== undefined && toke.type != acorn.tokTypes.eof) { + if (toke.type.keyword !== undefined) { + //dbg_print("Keyword:"); + //dbg_print(toke); + + // This type of loop detection ignores functional loop alternatives and ternary operators + const tokeTypeRes = evaluateByTokenTypeKeyword(toke.type.keyword); + if (tokeTypeRes[0] === false) { + return tokeTypeRes; + } + } else if (toke.value !== undefined) { + const tokeValRes = evaluateByTokenValue(toke); + if (tokeValRes[0] === false) { + return tokeValRes; + } + } + // If not a keyword or an identifier it's some kind of operator, field parenthesis, brackets + try { + toke = tokens.getToken(); + } catch (e) { + dbg_print('Denied script because it cannot be parsed.'); + return [false, 'NONTRIVIAL: Cannot be parsed. This could mean it is a 404 error.']; + } + } + + dbg_print('%cAppears to be trivial.', 'color:green;'); + if (definesFunctions === true) + return [true, 'Script appears to be trivial but defines functions.']; + else + return [true, 'Script appears to be trivial.']; +} + + +//**************************************************************************************************** +/** +* This is the entry point for full code evaluation for triviality. +* +* Performs the initial pass on code to see if it needs to be completely parsed +* +* This can only determine if a script is bad, not if it's good +* +* If it passes the intitial pass, it runs the full pass and returns the result + +* It returns an array of [flag (boolean, false if "bad"), reason (string, human readable report)] +* +*/ +function evaluate(script, name) { + const reservedResult = evaluateForReservedObj(script, name); + if (reservedResult[0] === true) { + dbg_print('%c pass', 'color:green;'); + } else { + return reservedResult; + } + + return fullEvaluate(script); +} + +function evaluateForReservedObj(script, name) { + function reservedObjectRegex(object) { + const arithOperators = '\\+\\-\\*\\/\\%\\='; + return new RegExp('(?:[^\\w\\d]|^|(?:' + arithOperators + '))' + object + '(?:\\s*?(?:[\\;\\,\\.\\(\\[])\\s*?)', 'g'); + } + const mlComment = /\/\*([\s\S]+?)\*\//g; + const ilComment = /\/\/.+/gm; + const temp = script.replace(/'.+?'+/gm, '\'string\'').replace(/".+?"+/gm, '"string"').replace(mlComment, '').replace(ilComment, ''); + dbg_print('%c ------evaluation results for ' + name + '------', 'color:white'); + dbg_print('Script accesses reserved objects?'); + + // This is where individual "passes" are made over the code + for (const reserved of RESERVED_OBJECTS) { + if (reservedObjectRegex(reserved).exec(temp) != null) { + dbg_print('%c fail', 'color:red;'); + return [false, 'Script uses a reserved object (' + reserved + ')']; + } + } + return [true, 'Reserved object not found.']; +} + +/** + * Checks whether url is the magnet link of a license. + * + * Returns the licenseName if so, otherwise returns null. If a key is + * supplied, checks for the license with the key only. + */ +function checkMagnet(url, key = null) { + const fixedUrl = url.replace(/&/g, '&'); + // Match by magnet link + const checkLicenseMagnet = license => { + for (const cUrl of license.canonicalUrl) { + if (cUrl.startsWith('magnet:') && fixedUrl === cUrl) { + return license.licenseName; + } + } + return null; + } + + if (key) { + try { + return checkLicenseMagnet(licenses[key]); + } catch (error) { + return null; + } + } else { + for (const key in licenses) { + const result = checkLicenseMagnet(licenses[key]); + if (result) return result; + } + return null; + } +} + + +/** + * + * Evaluates the content of a script for licenses and triviality + * scriptSrc: content of the script; name: script name; external: + * whether the script is external + * + * Returns + * [ + * true (accepted) or false (denied), + * edited content, + * reason text + * ] + */ +function checkScriptSource(scriptSrc, name, external = false) { + let inSrc = scriptSrc.trim(); + if (!inSrc) return [true, scriptSrc, 'Empty source.']; + + // Check for @licstart .. @licend method + const license = checkLicenseText(scriptSrc); + if (license) { + return [true, scriptSrc, `Licensed under: ${license}`]; + } + + let outSrc = ''; + let reason = ''; + let partsDenied = false; + let partsAccepted = false; + + function checkTriviality(s) { + if (!patternUtils.removeJsComments(s).trim()) { + return true; // empty, ignore it + } + const [trivial, message] = external ? + [false, 'External script with no known license'] + : evaluate(s, name); + if (trivial) { + partsAccepted = true; + outSrc += s; + } else { + partsDenied = true; + if (s.startsWith('javascript:')) + outSrc += `# LIBREJS BLOCKED: ${message}`; + else + outSrc += `/*\nLIBREJS BLOCKED: ${message}\n*/`; + } + reason += `\n${message}`; + } + + // Consume inSrc by checking licenses in all @license / @license-end + // blocks and triviality outside these blocks + while (inSrc) { + const openingMatch1 = OPENING_LICENSE_RE1.exec(inSrc); + const openingMatch2 = OPENING_LICENSE_RE2.exec(inSrc); + const openingMatch = + (openingMatch1 && openingMatch2) ? + (openingMatch1.index < openingMatch2.index ? openingMatch1 + : openingMatch2) + : (openingMatch1 || openingMatch2); + const openingIndex = openingMatch ? openingMatch.index : inSrc.length; + // checks the triviality of the code before the license tag, if any + checkTriviality(inSrc.substring(0, openingIndex)); + inSrc = inSrc.substring(openingIndex); + if (!inSrc) break; + + // checks the remaining part, that starts with an @license + const closureMatch1 = CLOSING_LICENSE_RE1.exec(inSrc); + const closureMatch2 = CLOSING_LICENSE_RE2.exec(inSrc); + const closureMatch = + (closureMatch1 && closureMatch2) ? + (closureMatch1.index < closureMatch2.index ? closureMatch1 + : closureMatch2) + : (closureMatch1 || closureMatch2); + if (!closureMatch) { + const msg = 'ERROR: @license with no @license-end'; + return [false, `\n/*\n ${msg} \n*/\n`, msg]; + } + const closureEndIndex = closureMatch.index + closureMatch[0].length; + + if (!(Array.isArray(openingMatch) && openingMatch.length >= 3)) { + return [false, 'Malformed or unrecognized license tag.']; + } + const licenseName = checkMagnet(openingMatch[1]); + let message; + if (licenseName) { + outSrc += inSrc.substr(0, closureEndIndex); + partsAccepted = true; + message = `Recognized license: "${licenseName}".` + } else { + outSrc += `\n/*\n${message}\n*/\n`; + partsDenied = true; + message = `Unrecognized license tag: "${openingMatch[0]}"`; + } + reason += `\n${message}`; + + // trim off everything we just evaluated + inSrc = inSrc.substring(closureEndIndex).trim(); + } + + if (partsDenied) { + if (partsAccepted) { + reason = `Some parts of the script have been disabled (check the source for details).\n^--- ${reason}`; + } + return [false, outSrc, reason]; + } + + return [true, scriptSrc, reason]; +} + +module.exports = { init, checkLicenseText, checkMagnet, checkScriptSource }; + +},{"./debug.js":8,"./fname_data.json":9,"./license_definitions.json":10,"./pattern_utils.js":11,"acorn":13}],8:[function(require,module,exports){ +/** +* GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. +* * +* Copyright (C) 2017, 2018 Nathan Nichols +* Copyright (C) 2018 Ruben Rodriguez +* Copyright (C) 2022 Yuchen Pei +* +* This file is part of GNU LibreJS. +* +* GNU LibreJS is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* GNU LibreJS is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with GNU LibreJS. If not, see . +*/ + +const makeDebugLogger = (origin, enabled, time) => { + return (a, b) => { + if (enabled) { + console.log('[' + origin + '] Time spent so far: ' + (Date.now() - time) / 1000 + ' seconds'); + if (b === undefined) { + console.log(a); + } else { + console.log(a, b); + } + } + } +} + +module.exports = { makeDebugLogger }; + +},{}],9:[function(require,module,exports){ +module.exports={ + "fname_data": { + "WebGLShader": true, + "WebGLShaderPrecisionFormat": true, + "WebGLQuery": true, + "WebGLRenderbuffer": true, + "WebGLSampler": true, + "WebGLUniformLocation": true, + "WebGLFramebuffer": true, + "WebGLProgram": true, + "WebGLContextEvent": true, + "WebGL2RenderingContext": true, + "WebGLTexture": true, + "WebGLRenderingContext": true, + "WebGLVertexArrayObject": true, + "WebGLActiveInfo": true, + "WebGLTransformFeedback": true, + "WebGLSync": true, + "WebGLBuffer": true, + "cat_svg": true, + "SVGPoint": true, + "SVGEllipseElement": true, + "SVGRadialGradientElement": true, + "SVGComponentTransferFunctionElement": true, + "SVGPathSegCurvetoQuadraticAbs": true, + "SVGAnimatedNumberList": true, + "SVGPathSegCurvetoQuadraticSmoothRel": true, + "SVGFEColorMatrixElement": true, + "SVGPathSegLinetoHorizontalAbs": true, + "SVGLinearGradientElement": true, + "SVGStyleElement": true, + "SVGPathSegMovetoRel": true, + "SVGStopElement": true, + "SVGPathSegLinetoRel": true, + "SVGFEConvolveMatrixElement": true, + "SVGAnimatedAngle": true, + "SVGPathSegLinetoAbs": true, + "SVGPreserveAspectRatio": true, + "SVGFEOffsetElement": true, + "SVGFEImageElement": true, + "SVGFEDiffuseLightingElement": true, + "SVGAnimatedNumber": true, + "SVGTextElement": true, + "SVGFESpotLightElement": true, + "SVGFEMorphologyElement": true, + "SVGAngle": true, + "SVGScriptElement": true, + "SVGFEDropShadowElement": true, + "SVGPathSegArcRel": true, + "SVGNumber": true, + "SVGPathSegLinetoHorizontalRel": true, + "SVGFEFuncBElement": true, + "SVGClipPathElement": true, + "SVGPathSeg": true, + "SVGUseElement": true, + "SVGPathSegArcAbs": true, + "SVGPathSegCurvetoQuadraticSmoothAbs": true, + "SVGRect": true, + "SVGAnimatedPreserveAspectRatio": true, + "SVGImageElement": true, + "SVGAnimatedEnumeration": true, + "SVGAnimatedLengthList": true, + "SVGFEFloodElement": true, + "SVGFECompositeElement": true, + "SVGAElement": true, + "SVGAnimatedBoolean": true, + "SVGMaskElement": true, + "SVGFilterElement": true, + "SVGPathSegLinetoVerticalRel": true, + "SVGAnimatedInteger": true, + "SVGTSpanElement": true, + "SVGMarkerElement": true, + "SVGStringList": true, + "SVGTransform": true, + "SVGTitleElement": true, + "SVGFEBlendElement": true, + "SVGTextPositioningElement": true, + "SVGFEFuncGElement": true, + "SVGFEPointLightElement": true, + "SVGAnimateElement": true, + "SVGPolylineElement": true, + "SVGDefsElement": true, + "SVGPathSegList": true, + "SVGAnimatedTransformList": true, + "SVGPathSegClosePath": true, + "SVGGradientElement": true, + "SVGSwitchElement": true, + "SVGViewElement": true, + "SVGUnitTypes": true, + "SVGPathSegMovetoAbs": true, + "SVGSymbolElement": true, + "SVGFEFuncAElement": true, + "SVGAnimatedString": true, + "SVGFEMergeElement": true, + "SVGPathSegLinetoVerticalAbs": true, + "SVGAnimationElement": true, + "SVGPathSegCurvetoCubicAbs": true, + "SVGLength": true, + "SVGTextPathElement": true, + "SVGPolygonElement": true, + "SVGAnimatedRect": true, + "SVGPathSegCurvetoCubicRel": true, + "SVGFEFuncRElement": true, + "SVGLengthList": true, + "SVGTextContentElement": true, + "SVGFETurbulenceElement": true, + "SVGMatrix": true, + "SVGZoomAndPan": true, + "SVGMetadataElement": true, + "SVGFEDistantLightElement": true, + "SVGAnimateMotionElement": true, + "SVGDescElement": true, + "SVGPathSegCurvetoCubicSmoothRel": true, + "SVGFESpecularLightingElement": true, + "SVGFEGaussianBlurElement": true, + "SVGFEComponentTransferElement": true, + "SVGNumberList": true, + "SVGTransformList": true, + "SVGForeignObjectElement": true, + "SVGRectElement": true, + "SVGFEDisplacementMapElement": true, + "SVGAnimateTransformElement": true, + "SVGAnimatedLength": true, + "SVGPointList": true, + "SVGPatternElement": true, + "SVGPathSegCurvetoCubicSmoothAbs": true, + "SVGCircleElement": true, + "SVGSetElement": true, + "SVGFETileElement": true, + "SVGMPathElement": true, + "SVGFEMergeNodeElement": true, + "SVGPathSegCurvetoQuadraticRel": true, + "SVGElement": true, + "SVGGraphicsElement": true, + "SVGSVGElement": true, + "SVGGElement": true, + "SVGGeometryElement": true, + "SVGPathElement": true, + "SVGLineElement": true, + "cat_html": true, + "HTMLTimeElement": true, + "HTMLPictureElement": true, + "HTMLMenuItemElement": true, + "HTMLFormElement": true, + "HTMLOptionElement": true, + "HTMLCanvasElement": true, + "HTMLTableSectionElement": true, + "HTMLSelectElement": true, + "HTMLUListElement": true, + "HTMLMetaElement": true, + "HTMLLinkElement": true, + "HTMLBaseElement": true, + "HTMLDataListElement": true, + "HTMLInputElement": true, + "HTMLMeterElement": true, + "HTMLSourceElement": true, + "HTMLTrackElement": true, + "HTMLTableColElement": true, + "HTMLFieldSetElement": true, + "HTMLDirectoryElement": true, + "HTMLTableCellElement": true, + "HTMLStyleElement": true, + "HTMLAudioElement": true, + "HTMLLegendElement": true, + "HTMLOListElement": true, + "HTMLEmbedElement": true, + "HTMLQuoteElement": true, + "HTMLMenuElement": true, + "HTMLHeadElement": true, + "HTMLUnknownElement": true, + "HTMLBRElement": true, + "HTMLProgressElement": true, + "HTMLMediaElement": true, + "HTMLFormControlsCollection": true, + "HTMLCollection": true, + "HTMLLIElement": true, + "HTMLDetailsElement": true, + "HTMLObjectElement": true, + "HTMLHeadingElement": true, + "HTMLTableCaptionElement": true, + "HTMLPreElement": true, + "HTMLAllCollection": true, + "HTMLFrameSetElement": true, + "HTMLFontElement": true, + "HTMLFrameElement": true, + "HTMLAnchorElement": true, + "HTMLOptGroupElement": true, + "HTMLVideoElement": true, + "HTMLModElement": true, + "HTMLBodyElement": true, + "HTMLTableElement": true, + "HTMLButtonElement": true, + "HTMLTableRowElement": true, + "HTMLAreaElement": true, + "HTMLDataElement": true, + "HTMLParamElement": true, + "HTMLLabelElement": true, + "HTMLTemplateElement": true, + "HTMLOptionsCollection": true, + "HTMLIFrameElement": true, + "HTMLTitleElement": true, + "HTMLMapElement": true, + "HTMLOutputElement": true, + "HTMLDListElement": true, + "HTMLParagraphElement": true, + "HTMLHRElement": true, + "HTMLImageElement": true, + "HTMLDocument": true, + "HTMLElement": true, + "HTMLScriptElement": true, + "HTMLHtmlElement": true, + "HTMLTextAreaElement": true, + "HTMLDivElement": true, + "HTMLSpanElement": true, + "cat_css": true, + "CSSStyleRule": true, + "CSSFontFaceRule": true, + "CSSPrimitiveValue": true, + "CSSStyleDeclaration": true, + "CSSStyleSheet": true, + "CSSPageRule": true, + "CSSSupportsRule": true, + "CSSMozDocumentRule": true, + "CSSKeyframeRule": true, + "CSSGroupingRule": true, "CSS2Properties": true, "CSSFontFeatureValuesRule": true, "CSSRuleList": true, @@ -1413,7 +1880,7 @@ module.exports={ "RadioNodeList": true, "KeyframeEffectReadOnly": true, "InstallTrigger": true, - "Function": false, + "Function": true, "Object": false, "eval": true, "Window": false, @@ -1530,528 +1997,515 @@ module.exports={ } } -},{}],8:[function(require,module,exports){ -module.exports = { - whitelist: {"jquery":[{"filename":"core.js","version":"3.3.1","hash":"6026ca247eaee2c88fa54964d77d2e76efc97a974a5695e3744cb38defb3d691"},{"filename":"jquery.js","version":"3.3.1","hash":"d8aa24ecc6cecb1a60515bc093f1c9da38a0392612d9ab8ae0f7f36e6eee1fad"},{"filename":"jquery.min.js","version":"3.3.1","hash":"160a426ff2894252cd7cebbdd6d6b7da8fcd319c65b70468f10b6690c45d02ef"},{"filename":"jquery.slim.js","version":"3.3.1","hash":"7cd5c914895c6b4e4120ed98e73875c6b4a12b7304fbf9586748fe0a1c57d830"},{"filename":"jquery.slim.min.js","version":"3.3.1","hash":"dde76b9b2b90d30eb97fc81f06caa8c338c97b688cea7d2729c88f529f32fbb1"},{"filename":"core.js","version":"3.3.0","hash":"58db1cc9582b20320c552043b5880b40c8eaec3e6d4b46994222862a049330a1"},{"filename":"jquery.js","version":"3.3.0","hash":"4c5592b8326dea44be86e57ebd59725758ccdddc0675e356a9ece14f15c1fd7f"},{"filename":"jquery.min.js","version":"3.3.0","hash":"453432f153a63654fa6f63c846eaf7ee9e8910165413ba3cc0f80cbeed7c302e"},{"filename":"jquery.slim.js","version":"3.3.0","hash":"ec89a3d1f2cab57e4d144092d6e9a8429ecd0b594482be270536ac366ee004b6"},{"filename":"jquery.slim.min.js","version":"3.3.0","hash":"00c83723bc9aefa38b3c3f4cf8c93b92aac0dbd1d49ff16e1817d3ffd51ff65b"},{"filename":"core.js","version":"3.2.1","hash":"052b1b5ec0c4ae78aafc7a6e8542c5a2bf31d42a40dac3cfc102e512812b8bed"},{"filename":"jquery.js","version":"3.2.1","hash":"0d9027289ffa5d9f6c8b4e0782bb31bbff2cef5ee3708ccbcb7a22df9128bb21"},{"filename":"jquery.min.js","version":"3.2.1","hash":"87083882cc6015984eb0411a99d3981817f5dc5c90ba24f0940420c5548d82de"},{"filename":"jquery.slim.js","version":"3.2.1","hash":"b40f32d17aa2c27a7098e225dd218070597646fc478c0f2aa74fb5b821a64668"},{"filename":"jquery.slim.min.js","version":"3.2.1","hash":"9365920887b11b33a3dc4ba28a0f93951f200341263e3b9cefd384798e4be398"},{"filename":"core.js","version":"3.2.0","hash":"7c5c8f96ac182ed4d2c9ac74fda37941745f2793814fbd8b28624a9a720f9d39"},{"filename":"jquery.js","version":"3.2.0","hash":"c0f149348165558e3d07e0ae008ac3afddf65d26fa264dc9d4cdb6337136ca54"},{"filename":"jquery.min.js","version":"3.2.0","hash":"2405bdf4c255a4904671bcc4b97938033d39b3f5f20dd068985a8d94cde273e2"},{"filename":"jquery.slim.js","version":"3.2.0","hash":"f18ac10930e84233b80814f5595bcc1f6ffad74047d038d997114e08880aec03"},{"filename":"jquery.slim.min.js","version":"3.2.0","hash":"a8b02fd240408a170764b2377efdd621329e46c517dbb85deaea4105ad0c4a8c"},{"filename":"core.js","version":"3.1.1","hash":"4a4dec7ca8f2567b4327c82b873c8d7dd774f74b9009d2ff65431a8154693dea"},{"filename":"jquery.js","version":"3.1.1","hash":"d7a71d3dd740e95755227ba6446a3a21b8af6c4444f29ec2411dc7cd306e10b0"},{"filename":"jquery.min.js","version":"3.1.1","hash":"85556761a8800d14ced8fcd41a6b8b26bf012d44a318866c0d81a62092efd9bf"},{"filename":"jquery.slim.js","version":"3.1.1","hash":"e62fe6437d3433befd3763950eb975ea56e88705cd51dccbfd1d9a5545f25d60"},{"filename":"jquery.slim.min.js","version":"3.1.1","hash":"fd222b36abfc87a406283b8da0b180e22adeb7e9327ac0a41c6cd5514574b217"},{"filename":"core.js","version":"3.1.0","hash":"55994528e7efe901e92a76761a54ba0c3ae3f1f8d1c3a4da9a23a3e4a06d0eaa"},{"filename":"jquery.js","version":"3.1.0","hash":"b25a2092f0752b754e933008f10213c55dd5ce93a791e355b0abed9182cc8df9"},{"filename":"jquery.min.js","version":"3.1.0","hash":"702b9e051e82b32038ffdb33a4f7eb5f7b38f4cf6f514e4182d8898f4eb0b7fb"},{"filename":"jquery.slim.js","version":"3.1.0","hash":"2faa690232fa8e0b5199f8ae8a0784139030348da91ff5fd2016cfc9a9c9799c"},{"filename":"jquery.slim.min.js","version":"3.1.0","hash":"711a568e848ec3929cc8839a64da388ba7d9f6d28f85861bea2e53f51495246f"},{"filename":"core.js","version":"3.0.0-rc1","hash":"11853583eb5ce8ab1aacc380430145de705cdfff0e72c54d3dca17d01466999b"},{"filename":"jquery.js","version":"3.0.0-rc1","hash":"65ded5fa34aa91b976dae0af5888ce4c06fed34271f3665b2924505b704025c7"},{"filename":"jquery.min.js","version":"3.0.0-rc1","hash":"df68e90250b9a60fc184ef194d1769d3af8aa67396cc064281cb77e2ef6bf876"},{"filename":"jquery.slim.js","version":"3.0.0-rc1","hash":"c96eeff335114aa55df0328bbe5f9202ed7a3266b6e81fcd357cd17837fa9756"},{"filename":"jquery.slim.min.js","version":"3.0.0-rc1","hash":"e92bbd6e77604b75e910952f20f3c95ce29050c7b1137dc1edddad000c236b5d"},{"filename":"jquery.js","version":"3.0.0-beta1","hash":"78f27c3d7cb5d766466703adc7f7ad7706b7fb05514eec39be0aa253449bd0f8"},{"filename":"jquery.min.js","version":"3.0.0-beta1","hash":"b72a0aa436a8a8965041beda30577232677ef6588bb933b5bebed2de02c04dc8"},{"filename":"jquery.slim.js","version":"3.0.0-beta1","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"3.0.0-beta1","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"3.0.0-alpha1","hash":"10b3ccff4cf14cdb5e7c31b2d323be750a13125cea8ded9ca5c1da4150a69238"},{"filename":"jquery.min.js","version":"3.0.0-alpha1","hash":"19e065eaadf26f58c0e1081a2e0e64450eec2983eebb08f998ecaacac8642a47"},{"filename":"core.js","version":"3.0.0","hash":"bad41b5e9f7c6b952b3a840b84ce2e97e3029bd2b2773c58a69a33e73217d1e4"},{"filename":"jquery.js","version":"3.0.0","hash":"8eb3cb67ef2f0f1b76167135cef6570a409c79b23f0bc0ede71c9a4018f1408a"},{"filename":"jquery.min.js","version":"3.0.0","hash":"266bcea0bb58b26aa5b16c5aee60d22ccc1ae9d67daeb21db6bad56119c3447d"},{"filename":"jquery.slim.js","version":"3.0.0","hash":"1a9ea1a741fe03b6b1835b44ac2b9c59e39cdfc8abb64556a546c16528fc2828"},{"filename":"jquery.slim.min.js","version":"3.0.0","hash":"45fe0169d7f20adb2f1e63bcf4151971b62f34dbd9bce4f4f002df133bc2b03d"},{"filename":"jquery.js","version":"2.2.4","hash":"893e90f6230962e42231635df650f20544ad22affc3ee396df768eaa6bc5a6a2"},{"filename":"jquery.min.js","version":"2.2.4","hash":"05b85d96f41fff14d8f608dad03ab71e2c1017c2da0914d7c59291bad7a54f8e"},{"filename":"jquery.js","version":"2.2.3","hash":"95a5d6b46c9da70a89f0903e5fdc769a2c266a22a19fcb5598e5448a044db4fe"},{"filename":"jquery.min.js","version":"2.2.3","hash":"6b6de0d4db7876d1183a3edb47ebd3bbbf93f153f5de1ba6645049348628109a"},{"filename":"jquery.slim.js","version":"2.2.3","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"2.2.3","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"2.2.2","hash":"e3fcd40aa8aad24ab1859232a781b41a4f803ad089b18d53034d24e4296c6581"},{"filename":"jquery.min.js","version":"2.2.2","hash":"dfa729d82a3effadab1000181cb99108f232721e3b0af74cfae4c12704b35a32"},{"filename":"jquery.slim.js","version":"2.2.2","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"2.2.2","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"2.2.1","hash":"78d714ccede3b2fd179492ef7851246c1f1b03bfc2ae83693559375e99a7c077"},{"filename":"jquery.min.js","version":"2.2.1","hash":"82f420005cd31fab6b4ab016a07d623e8f5773de90c526777de5ba91e9be3b4d"},{"filename":"jquery.slim.js","version":"2.2.1","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"2.2.1","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"2.2.0","hash":"a18aa92dea997bd71eb540d5f931620591e9dee27e5f817978bb385bab924d21"},{"filename":"jquery.min.js","version":"2.2.0","hash":"8a102873a33f24f7eb22221e6b23c4f718e29f85168ecc769a35bfaed9b12cce"},{"filename":"jquery.js","version":"2.1.4","hash":"b2215cce5830e2350b9d420271d9bd82340f664c3f60f0ea850f7e9c0392704e"},{"filename":"jquery.min.js","version":"2.1.4","hash":"22642f202577f0ba2f22cbe56b6cf291a09374487567cd3563e0d2a29f75c0c5"},{"filename":"jquery.js","version":"2.1.3","hash":"828cbbcacb430f9c5b5d27fe9302f8795eb338f2421010f5141882125226f94f"},{"filename":"jquery.min.js","version":"2.1.3","hash":"2051d61446d4dbffb03727031022a08c84528ab44d203a7669c101e5fbdd5515"},{"filename":"jquery.js","version":"2.1.2","hash":"07cb07bdfba40ceff869b329eb48eeede41740ba6ce833dd3830bd0af49e4898"},{"filename":"jquery.min.js","version":"2.1.2","hash":"64c51d974a342e9df3ed548082a4ad7816d407b8c36b67356dde9e487b819cbe"},{"filename":"jquery.js","version":"2.1.1-rc2","hash":"dc0083a233768ed8554d770d9d4eed91c0e27de031b3d9cbdcecabc034265010"},{"filename":"jquery.min.js","version":"2.1.1-rc2","hash":"293c9966a4fea0fed0adc1aae242bb37e428e649337dcab65d9af5934a7cc775"},{"filename":"jquery.js","version":"2.1.1-rc1","hash":"5adbbda8312291291162ab054df8927291426dbfb550099945ece85b49707290"},{"filename":"jquery.min.js","version":"2.1.1-rc1","hash":"d246298c351558d4847d237bb2d052f22001ca24ea4a32c28de378c95af523c8"},{"filename":"jquery.js","version":"2.1.1-beta1","hash":"e96b9e8d7a12b381d2ed1efd785faef3c7bad0ea03edf42fb15c9fde533e761f"},{"filename":"jquery.min.js","version":"2.1.1-beta1","hash":"5aed44447956d7933861d56003dbd0f95504d79e19d094edacbe4a55e6cf8736"},{"filename":"jquery.js","version":"2.1.1","hash":"140ff438eaaede046f1ceba27579d16dc980595709391873fa9bf74d7dbe53ac"},{"filename":"jquery.min.js","version":"2.1.1","hash":"c0d4098bc8b34c6f87a3d7723988ae81214a53a0bb4a1d4d36a67640f98ed079"},{"filename":"jquery.js","version":"2.1.0-rc1","hash":"88d96de8ccf65e57a3f28134616e3abfe0af2b3712302beb0a73f77f6b873fd0"},{"filename":"jquery.min.js","version":"2.1.0-rc1","hash":"11f94218bacdd4dbdc5c1736ca7aa1f27bb9632bc0a1696175b408da8dcf16b3"},{"filename":"jquery.js","version":"2.1.0-beta3","hash":"8eb83f00967dd0e18877b71349f5a3641b1046a1667c54e602a5682ac0f07ab9"},{"filename":"jquery.min.js","version":"2.1.0-beta3","hash":"7ebd0c0a5a088da45a5ec48f4379dbe457129f2cbe434f2e045ef838136746a9"},{"filename":"jquery.js","version":"2.1.0-beta2","hash":"97efd5af482f4e74c37c04970421fdbd17388fd605d992a2aa0077d388b32b6d"},{"filename":"jquery.min.js","version":"2.1.0-beta2","hash":"22966516a31e64225df5e08e35f0fadb27d29a8fb2618ddca17ec171215fc323"},{"filename":"jquery.js","version":"2.1.0","hash":"0fa7752926a95e3ab6b5f67a21ef40628ce4447c81ddf4f6cacf663b6fb85af7"},{"filename":"jquery.min.js","version":"2.1.0","hash":"f284353a7cc4d97f6fe20a5155131bd43587a0f1c98a56eeaf52cff72910f47d"},{"filename":"jquery.js","version":"2.0.3","hash":"9427fe2df51f7d4c6bf35f96d19169714d0b432b99dc18f41760d0342c538122"},{"filename":"jquery.min.js","version":"2.0.3","hash":"a57b5242b9a9adc4c1ef846c365147b89c472b9cd770face331efcb965346b25"},{"filename":"jquery.js","version":"2.0.2","hash":"d2ed0720108a75db0d53248ba8e36332658064c4189714d16c0f117efb42016d"},{"filename":"jquery.min.js","version":"2.0.2","hash":"9d7d1c727e1cd32745764098a76e5d3d5fb7acd3b6527c5aacd85b7c6f8ce341"},{"filename":"jquery.js","version":"2.0.1","hash":"820fb338fe8c7478a1b820e2708b4fd306a68825de1194803e7a93fbc2177a16"},{"filename":"jquery.min.js","version":"2.0.1","hash":"4e1354fc542b617c58cbba3aeb5116a528cf08bb1299f5dc7f3bc77a3b902b68"},{"filename":"jquery.js","version":"2.0.0","hash":"896e379d334cf0b16c78d9962a1579147156d4a72355032fce0de5f673d4e287"},{"filename":"jquery.min.js","version":"2.0.0","hash":"d482871a5e948cb4884fa0972ea98a81abca057b6bd3f8c995a18c12487e761c"},{"filename":"jquery.js","version":"1.12.4","hash":"430f36f9b5f21aae8cc9dca6a81c4d3d84da5175eaedcf2fdc2c226302cb3575"},{"filename":"jquery.min.js","version":"1.12.4","hash":"668b046d12db350ccba6728890476b3efee53b2f42dbb84743e5e9f1ae0cc404"},{"filename":"jquery.js","version":"1.12.3","hash":"d5732912d03878a5cd3695dc275a6630fb3c255fa7c0b744ab08897824049327"},{"filename":"jquery.min.js","version":"1.12.3","hash":"69a3831c082fc105b56c53865cc797fa90b83d920fb2f9f6875b00ad83a18174"},{"filename":"jquery.slim.js","version":"1.12.3","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"1.12.3","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"1.12.2","hash":"5540b2af46570795610626e8d8391356176ca639b1520c4319a2d0c7ba9bef16"},{"filename":"jquery.min.js","version":"1.12.2","hash":"95914789b5f3307a3718679e867d61b9d4c03f749cd2e2970570331d7d6c8ed9"},{"filename":"jquery.slim.js","version":"1.12.2","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"1.12.2","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"1.12.1","hash":"56e843a66b2bf7188ac2f4c81df61608843ce144bd5aa66c2df4783fba85e8ef"},{"filename":"jquery.min.js","version":"1.12.1","hash":"2359d383bf2d4ab65ebf7923bdf74ce40e4093f6e58251b395a64034b3c39772"},{"filename":"jquery.slim.js","version":"1.12.1","hash":"4db510700e5773fc7065f36363affd4885c9d9ef257fd7757744f91ac9da5671"},{"filename":"jquery.slim.min.js","version":"1.12.1","hash":"4c369c555423651822c2f7772d5e0b9a56a2372a92657bd2a696fe539b24be9e"},{"filename":"jquery.js","version":"1.12.0","hash":"c85537acad72f0d7d409dfc1e2d2daa59032f71d29642a8b64b9852f70166fbb"},{"filename":"jquery.min.js","version":"1.12.0","hash":"5f1ab65fe2ad6b381a1ae036716475bf78c9b2e309528cf22170c1ddeefddcbf"},{"filename":"jquery.js","version":"1.11.3","hash":"2065aecca0fb9b0567358d352ed5f1ab72fce139bf449b4d09805f5d9c3725ed"},{"filename":"jquery.min.js","version":"1.11.3","hash":"aec3d419d50f05781a96f223e18289aeb52598b5db39be82a7b71dc67d6a7947"},{"filename":"jquery.js","version":"1.11.2","hash":"58c27035b7a2e589df397e5d7e05424b90b8c1aaaf73eff47d5ed6daecb70f25"},{"filename":"jquery.min.js","version":"1.11.2","hash":"d4ec583c7604001f87233d1fe0076cbd909f15a5f8c6b4c3f5dd81b462d79d32"},{"filename":"jquery.js","version":"1.11.1-rc2","hash":"648dbce0f3731ebce091c283b52f60b100d73807501eea1a99f7b23140bfcefa"},{"filename":"jquery.min.js","version":"1.11.1-rc2","hash":"06d766022172da3774651a3ccfeef893185f9ba46823bcbfcba744ab5e25a4bf"},{"filename":"jquery.js","version":"1.11.1-rc1","hash":"8241d4982de8a6fea3e0ebc47e99445337675a777054c09221f670adb3748995"},{"filename":"jquery.min.js","version":"1.11.1-rc1","hash":"a581c274adebdbc44022e45d9febf0b92c572481c58bfe562b3d74d5e8972c5a"},{"filename":"jquery.js","version":"1.11.1-beta1","hash":"0aab28e2fd1f61b6282132553325bd890fef40989b698311c5b00b7b38a1e19d"},{"filename":"jquery.min.js","version":"1.11.1-beta1","hash":"99ec4d1ab56cf49ee4c202cc41509ada5eeb334694815f75675792433828a527"},{"filename":"jquery.js","version":"1.11.1","hash":"3029834a820c79c154c377f52e2719fc3ff2a27600a07ae089ea7fde9087f6bc"},{"filename":"jquery.min.js","version":"1.11.1","hash":"540bc6dec1dd4b92ea4d3fb903f69eabf6d919afd48f4e312b163c28cff0f441"},{"filename":"jquery.js","version":"1.11.0-rc1","hash":"84792d2b1ab8a2d57dcc113abb910b4c31dda357a7acd3b46ed282dd03f15d25"},{"filename":"jquery.min.js","version":"1.11.0-rc1","hash":"5f58804382f5258bb6b187c1b5af1ec0b8ccbe2c904a5163580371352ca63424"},{"filename":"jquery.js","version":"1.11.0-beta3","hash":"847a61382a55d0c0e5244d0621f1e0674292dee6b850640c669fd1516ec9f4f5"},{"filename":"jquery.min.js","version":"1.11.0-beta3","hash":"51fc79c1828a885f3776e35d56a22895e3656d014b502b869bd05f891bd91602"},{"filename":"jquery.js","version":"1.11.0","hash":"ce0343e1d6f489768eeefe022c12181c6a0822e756239851310acf076d23d10c"},{"filename":"jquery.min.js","version":"1.11.0","hash":"b294e973896f8f874e90a8eb1a8908ac790980d034c4c4bdf0fc3d37b8abf682"},{"filename":"jquery.js","version":"1.10.2","hash":"8ade6740a1d3cfedf81e28d9250929341207b23a55f1be90ccc26cf6d98e052a"},{"filename":"jquery.min.js","version":"1.10.2","hash":"89a15e9c40bc6b14809f236ee8cd3ed1ea42393c1f6ca55c7855cd779b3f922e"},{"filename":"jquery.js","version":"1.10.1","hash":"ebaded49db62a60060caa2577f2a4ec1ff68726bc40861bc65d977abeb64fa7d"},{"filename":"jquery.min.js","version":"1.10.1","hash":"8bf150f6b29d6c9337de6c945a8f63c929b203442040688878bc2753fe13e007"},{"filename":"jquery.js","version":"1.10.0","hash":"8aa0f84b5331efcc3cb72c7d504c2bc6ebd861da003d72c33df99ce650d4531d"},{"filename":"jquery.min.js","version":"1.10.0","hash":"1e80de36726582824df3f9a7eb6ecdfe9827fc5a7c69f597b1502ebc13950ecd"},{"filename":"jquery.js","version":"1.9.1","hash":"7bd80d06c01c0340c1b9159b9b4a197db882ca18cbac8e9b9aa025e68f998d40"},{"filename":"jquery.min.js","version":"1.9.1","hash":"c12f6098e641aaca96c60215800f18f5671039aecf812217fab3c0d152f6adb4"},{"filename":"jquery.js","version":"1.9.0","hash":"4d7b01c2f6043bcee83a33d0f627dc6fbc27dc8aeb5bdd5d863e84304b512ef3"},{"filename":"jquery.min.js","version":"1.9.0","hash":"7fa0d5c3f538c76f878e012ac390597faecaabfe6fb9d459b919258e76c5df8e"},{"filename":"jquery.js","version":"1.8.3","hash":"756d7dfac4a35bb57543f677283d6c682e8d704e5350884b27325badd2b3c4a7"},{"filename":"jquery.min.js","version":"1.8.3","hash":"61c6caebd23921741fb5ffe6603f16634fca9840c2bf56ac8201e9264d6daccf"},{"filename":"jquery.js","version":"1.8.2","hash":"ba8f203a9ebbe5771f49bcbe0804079240c7225f4be6ab424769bfbfb35ebc35"},{"filename":"jquery.min.js","version":"1.8.2","hash":"f23d4b309b72743aa8afe1f8c98a25b3ee31246fa572c66d9d8cb1982cae4fbc"},{"filename":"jquery.js","version":"1.8.1","hash":"7614fc75c4fcf6f32f7307f37550440e12adefb9289226acb79020c66faeffea"},{"filename":"jquery.min.js","version":"1.8.1","hash":"a1305347219d673cc973172494248e557ce8eccaf65af995c07c9d7daed4475d"},{"filename":"jquery-1.8.0.js","version":"1.8.0","hash":"04ee795a1a5a908ee339e145ae6c6b394d1dc0d971fd0896e3cb776660adba2e"},{"filename":"jquery-1.8.0.min.js","version":"1.8.0","hash":"d73e2e1bff9c55b85284ff287cb20dc29ad9165ec09091a0597b61199f330805"},{"filename":"jquery.js","version":"1.8.0","hash":"04ee795a1a5a908ee339e145ae6c6b394d1dc0d971fd0896e3cb776660adba2e"},{"filename":"jquery.min.js","version":"1.8.0","hash":"d73e2e1bff9c55b85284ff287cb20dc29ad9165ec09091a0597b61199f330805"},{"filename":"jquery.min.js","version":"1.7.2","hash":"47b68dce8cb6805ad5b3ea4d27af92a241f4e29a5c12a274c852e4346a0500b4"},{"filename":"jquery.min.js","version":"1.7.1","hash":"88171413fc76dda23ab32baa17b11e4fff89141c633ece737852445f1ba6c1bd"},{"filename":"jquery.min.js","version":"1.7","hash":"ff4e4975ef403004f8fe8e59008db7ad47f54b10d84c72eb90e728d1ec9157ce"},{"filename":"jquery.js","version":"1.6.4","hash":"54964f8b580ad795a962fb27066715d3281ae1ad13a28bf8aedd5d8859ebae37"},{"filename":"jquery.min.js","version":"1.6.4","hash":"951d6bae39eb172f57a88bd686f7a921cf060fd21f59648f0d20b6a8f98fc5a5"},{"filename":"jquery.js","version":"1.6.3","hash":"9baa10e1c5630c3dcd9bb46bf00913cc94b3855d58c9459ae9848339c566e97b"},{"filename":"jquery.min.js","version":"1.6.3","hash":"d3f3779f5113da6da957c4d81481146a272c31aefe0d3e4b64414fd686fd9744"},{"filename":"jquery.js","version":"1.6.2","hash":"a57292619d14eb8cbd923bde9f28cf994ac66abc48f7c975b769328ff33bddc9"},{"filename":"jquery.min.js","version":"1.6.2","hash":"fefb084f14120d777c7857ba78603e8531a0778b2e639df7622513c70567afa0"},{"filename":"jquery.js","version":"1.6.1","hash":"0eef76a9583a6c7a1eb764d33fe376bfe1861df79fab82c2c3f5d16183e82016"},{"filename":"jquery.min.js","version":"1.6.1","hash":"c784376960f3163dc760bc019e72e5fed78203745a5510c69992a39d1d8fe776"},{"filename":"jquery.js","version":"1.5.1","hash":"e2ea0a6ca6b984a9405a759d24cf3c51eb3164e5c43e95c3e9a59b316be7b3b9"},{"filename":"jquery.min.js","version":"1.5.1","hash":"764b9e9f3ad386aaa5cdeae9368353994de61c0bede087c8f7e3579cb443de3b"},{"filename":"jquery.js","version":"1.4.4","hash":"b31cd094af7950b3a461dc78161fd2faf01faa9d0ed8c1c072790f83ab26d482"},{"filename":"jquery.min.js","version":"1.4.4","hash":"517364f2d45162fb5037437b5b6cb953d00d9b2b3b79ba87d9fe57ea6ee6070c"},{"filename":"jquery.js","version":"1.4.3","hash":"0e3303a3a0cec95ebc8c3cc3e19fc71c99487faa286b05d01a3eb8cca4d90bc7"},{"filename":"jquery.min.js","version":"1.4.3","hash":"f800b399e5c7a5254fc66bb407117fe38dbde0528780e68c9f7c87d299f8486a"},{"filename":"jquery.js","version":"1.4.2","hash":"95c023c80dfe0d30304c58244878995061f87801a66daa5d6bf4f2512be0e6f9"},{"filename":"jquery.min.js","version":"1.4.2","hash":"e23a2a4e2d7c2b41ebcdd8ffc0679df7140eb7f52e1eebabf827a88182643c59"},{"filename":"jquery.js","version":"1.4.1","hash":"9edc9f813781eca2aad6de78ef85cdbe92ee32bb0a56791be4da0fa7b472c1d8"},{"filename":"jquery.min.js","version":"1.4.1","hash":"2cec78f739fbddfed852cd7934d2530e7cc4c8f14b38673b03ba5fb880ad4cc7"},{"filename":"jquery.js","version":"1.4.0","hash":"882927b9aadb2504b5c6a823bd8c8c516f21dec6e441fe2c8fa228e35951bcc8"},{"filename":"jquery.min.js","version":"1.4.0","hash":"89abaf1e2471b00525b0694048e179c0f39a2674e3bcb34460ea6bc4801882be"},{"filename":"jquery.js","version":"1.3.2","hash":"74537639fa585509395c0d3b9a5601dd1e4ca036961c53dc5ab0e87386aa9be1"},{"filename":"jquery.min.js","version":"1.3.2","hash":"c8370a2d050359e9d505acc411e6f457a49b21360a21e6cbc9229bad3a767899"},{"filename":"jquery.js","version":"1.3.1","hash":"0ae058559b3e65d6cc5674fe3ff01581da5ae62387bb0dfa2923997a52093a06"},{"filename":"jquery.min.js","version":"1.3.1","hash":"17ec1f16efac893b9bd89bba5f13cb1e0bf938bdc9cece6cae3ed77f18fa6fd7"},{"filename":"jquery.js","version":"1.3.0","hash":"a7756f21ff6c558f983d5376072174af546e8d07f8bebe1e6f760b2f4b53012d"},{"filename":"jquery.min.js","version":"1.3.0","hash":"900191a443115d8b48a9d68d3062e8b3d7129727951b8617465b485baf253006"},{"filename":"jquery.js","version":"1.2.6","hash":"3cc5c121471323b25de45fcab48631d4a09c78e76af21c10d747352682605587"},{"filename":"jquery.min.js","version":"1.2.6","hash":"d548530775a6286f49ba66e0715876b4ec5985966b0291c21568fecfc4178e8d"},{"filename":"jquery.js","version":"1.2.3","hash":"d977fc32dd4bdb0479604abf078f1045b0e922666313f2f42cd71ce7835e0061"},{"filename":"jquery.min.js","version":"1.2.3","hash":"f1c4a0a7b5dead231fc9b42f06965a036ab7a2a788768847eb81e1528d6402ad"}]} -}; - -},{}],9:[function(require,module,exports){ -/** -* GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. -* * -* Copyright (C) 2018 Nathan Nichols -* -* This file is part of GNU LibreJS. -* -* GNU LibreJS is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* GNU LibreJS is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with GNU LibreJS. If not, see . -*/ - -const { licenses } = require('./license_definitions.js'); -const { patternUtils } = require('./pattern_utils.js'); - -const licStartLicEndRe = /@licstartThefollowingistheentirelicensenoticefortheJavaScriptcodeinthis(?:page|file)(.*)?@licendTheaboveistheentirelicensenoticefortheJavaScriptcodeinthis(?:page|file)/mi; - - -/** - * stripLicenseToRegexp - * - * Removes all non-alphanumeric characters except for the - * special tokens, and replace the text values that are - * hardcoded in license_definitions.js - * - */ -const stripLicenseToRegexp = function(license) { - for (const frag of license.licenseFragments) { - frag.regex = patternUtils.removeNonalpha(frag.text); - frag.regex = new RegExp( - patternUtils.replaceTokens(frag.regex), ''); - } -}; - -const init = function() { - console.log('initializing regexes'); - for (const key in licenses) { - stripLicenseToRegexp(licenses[key]); - } -} - -module.exports.init = init; - -/** -* -* Takes in the declaration that has been preprocessed and -* tests it against regexes in our table. -*/ -const searchTable = function(strippedComment) { - const stripped = patternUtils.removeNonalpha(strippedComment); - // looking up license - for (const key in licenses) { - const license = licenses[key]; - for (const frag of license.licenseFragments) { - if (frag.regex.test(stripped)) { - return license.licenseName; - } - } - } - console.log('No global license found.'); - return false; - -} - -/** -* Takes the "first comment available on the page" -* returns true for "free" and false for anything else -*/ -const check = function(licenseText) { - if (licenseText === undefined || licenseText === null || licenseText == '') { - // not an inline script - return false; - } - // remove whitespace - const stripped = patternUtils.removeWhitespace(licenseText); - // Search for @licstart/@licend - // This assumes that there isn't anything before the comment - const matches = stripped.match(licStartLicEndRe); - if (matches == null) { - return false; - } - return searchTable(matches[0]); -}; - -module.exports.check = check; - -},{"./license_definitions.js":10,"./pattern_utils.js":14}],10:[function(require,module,exports){ -/** - * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. - * * - * Copyright (C) 2011, 2012, 2013, 2014 Loic J. Duros - * Copyright (C) 2014, 2015 Nik Nyby - * - * This file is part of GNU LibreJS. - * - * GNU LibreJS is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GNU LibreJS is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GNU LibreJS. If not, see . - */ -exports.types = { - SHORT: 'short', - LAZY: 'lazy', - FULL: 'full' -}; - -const type = exports.types; - -/** - * List of all the licenses. - * Currently only short substrings are used with regex. - * - * The licenses are indexed by their "Identifier", which, when possible, - * corresponds to their identifier as specified by SPDX here: - * https://spdx.org/licenses/ - */ -exports.licenses = { - 'AGPL-3.0': { - licenseName: 'GNU AFFERO GENERAL PUBLIC LICENSE version 3', - identifier: 'AGPL-3.0', - canonicalUrl: [ - 'http://www.gnu.org/licenses/agpl-3.0.html', - 'magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt' +},{}],10:[function(require,module,exports){ +module.exports={ + "AGPL-3.0": { + "licenseName": "GNU AFFERO GENERAL PUBLIC LICENSE version 3", + "identifier": "AGPL-3.0", + "canonicalUrl": [ + "http://www.gnu.org/licenses/agpl-3.0.html", + "magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt" ], - - licenseFragments: [{ text: " is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.", type: type.SHORT }] + "licenseFragments": [ + { + "text": " is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.", + "type": "short" + } + ] }, - - 'Apache-2.0': { - licenseName: 'Apache License, Version 2.0', - identifier: 'Apache-2.0', - canonicalUrl: [ - 'http://www.apache.org/licenses/LICENSE-2.0', - 'magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt' + "Apache-2.0": { + "licenseName": "Apache License, Version 2.0", + "identifier": "Apache-2.0", + "canonicalUrl": [ + "http://www.apache.org/licenses/LICENSE-2.0", + "magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt" ], - licenseFragments: [{ text: "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", + "type": "short" + } + ] }, - - 'Artistic-2.0': { - licenseName: "Artistic License 2.0", - identifier: 'Artistic-2.0', - canonicalUrl: [ + "Artistic-2.0": { + "licenseName": "Artistic License 2.0", + "identifier": "Artistic-2.0", + "canonicalUrl": [ "http://www.perlfoundation.org/artistic_license_2_0", "magnet:?xt=urn:btih:54fd2283f9dbdf29466d2df1a98bf8f65cafe314&dn=artistic-2.0.txt" ], - licenseFragments: [] + "licenseFragments": [] }, - - 'BSD-2-Clause': { - licenseName: "BSD 2-Clause License", - identifier: 'BSD-2-Clause', - canonicalUrl: [ - 'http://www.freebsd.org/copyright/freebsd-license.html', - 'magnet:?xt=urn:btih:87f119ba0b429ba17a44b4bffcab33165ebdacc0&dn=freebsd.txt' + "BSD-2-Clause": { + "licenseName": "BSD 2-Clause License", + "identifier": "BSD-2-Clause", + "canonicalUrl": [ + "http://www.freebsd.org/copyright/freebsd-license.html", + "magnet:?xt=urn:btih:87f119ba0b429ba17a44b4bffcab33165ebdacc0&dn=freebsd.txt" ], - licenseFragments: [{ text: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.", + "type": "short" + } + ] }, - - 'BSD-3-Clause': { - licenseName: "BSD 3-Clause License", - identifier: 'BSD-3-Clause', - canonicalUrl: [ - 'http://opensource.org/licenses/BSD-3-Clause', - 'magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt' + "BSD-3-Clause": { + "licenseName": "BSD 3-Clause License", + "identifier": "BSD-3-Clause", + "canonicalUrl": [ + "http://opensource.org/licenses/BSD-3-Clause", + "magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt" ], - licenseFragments: [{ text: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.", + "type": "short" + } + ] }, - - 'BSL-1.0': { - licenseName: 'Boost Software License 1.0', - identifier: 'BSL-1.0', - canonicalUrl: [ - 'http://www.boost.org/LICENSE_1_0.txt', - 'magnet:?xt=urn:btih:89a97c535628232f2f3888c2b7b8ffd4c078cec0&dn=Boost-1.0.txt' + "BSL-1.0": { + "licenseName": "Boost Software License 1.0", + "identifier": "BSL-1.0", + "canonicalUrl": [ + "http://www.boost.org/LICENSE_1_0.txt", + "magnet:?xt=urn:btih:89a97c535628232f2f3888c2b7b8ffd4c078cec0&dn=Boost-1.0.txt" ], - licenseFragments: [{ text: "Boost Software License Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the \"Software\") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Boost Software License Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the \"Software\") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following", + "type": "short" + } + ] }, - - 'CC-BY-1.0': { - licenseName: 'Creative Commons Attribution 1.0 Generic', - identifier: 'CC-BY-1.0', - canonicalUrl: ['https://creativecommons.org/licenses/by/1.0/'], - licenseFragments: [] + "CC-BY-1.0": { + "licenseName": "Creative Commons Attribution 1.0 Generic", + "identifier": "CC-BY-1.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by/1.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-2.0': { - licenseName: 'Creative Commons Attribution 2.0 Generic', - identifier: 'CC-BY-2.0', - canonicalUrl: ['https://creativecommons.org/licenses/by/2.0/'], - licenseFragments: [] + "CC-BY-2.0": { + "licenseName": "Creative Commons Attribution 2.0 Generic", + "identifier": "CC-BY-2.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by/2.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-2.5': { - licenseName: 'Creative Commons Attribution 2.5 Generic', - identifier: 'CC-BY-2.5', - canonicalUrl: ['https://creativecommons.org/licenses/by/2.5/'], - licenseFragments: [] + "CC-BY-2.5": { + "licenseName": "Creative Commons Attribution 2.5 Generic", + "identifier": "CC-BY-2.5", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by/2.5/" + ], + "licenseFragments": [] }, - - 'CC-BY-3.0': { - licenseName: 'Creative Commons Attribution 3.0 Unported', - identifier: 'CC-BY-3.0', - canonicalUrl: ['https://creativecommons.org/licenses/by/3.0/'], - licenseFragments: [] + "CC-BY-3.0": { + "licenseName": "Creative Commons Attribution 3.0 Unported", + "identifier": "CC-BY-3.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by/3.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-4.0': { - licenseName: 'Creative Commons Attribution 4.0 International', - identifier: 'CC-BY-4.0', - canonicalUrl: ['https://creativecommons.org/licenses/by/4.0/'], - licenseFragments: [] + "CC-BY-4.0": { + "licenseName": "Creative Commons Attribution 4.0 International", + "identifier": "CC-BY-4.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by/4.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-SA-1.0': { - licenseName: 'Creative Commons Attribution-ShareAlike 1.0 Generic', - identifier: 'CC-BY-SA-1.0', - canonicalUrl: ['https://creativecommons.org/licenses/by-sa/1.0/'], - licenseFragments: [] + "CC-BY-SA-1.0": { + "licenseName": "Creative Commons Attribution-ShareAlike 1.0 Generic", + "identifier": "CC-BY-SA-1.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by-sa/1.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-SA-2.0': { - licenseName: 'Creative Commons Attribution-ShareAlike 2.0 Generic', - identifier: 'CC-BY-SA-2.0', - canonicalUrl: ['https://creativecommons.org/licenses/by-sa/2.0/'], - licenseFragments: [] + "CC-BY-SA-2.0": { + "licenseName": "Creative Commons Attribution-ShareAlike 2.0 Generic", + "identifier": "CC-BY-SA-2.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by-sa/2.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-SA-2.5': { - licenseName: 'Creative Commons Attribution-ShareAlike 2.5 Generic', - identifier: 'CC-BY-SA-2.5', - canonicalUrl: ['https://creativecommons.org/licenses/by-sa/2.5/'], - licenseFragments: [] + "CC-BY-SA-2.5": { + "licenseName": "Creative Commons Attribution-ShareAlike 2.5 Generic", + "identifier": "CC-BY-SA-2.5", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by-sa/2.5/" + ], + "licenseFragments": [] }, - - 'CC-BY-SA-3.0': { - licenseName: 'Creative Commons Attribution-ShareAlike 3.0 Unported', - identifier: 'CC-BY-SA-3.0', - canonicalUrl: ['https://creativecommons.org/licenses/by-sa/3.0/'], - licenseFragments: [] + "CC-BY-SA-3.0": { + "licenseName": "Creative Commons Attribution-ShareAlike 3.0 Unported", + "identifier": "CC-BY-SA-3.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by-sa/3.0/" + ], + "licenseFragments": [] }, - - 'CC-BY-SA-4.0': { - licenseName: 'Creative Commons Attribution-ShareAlike 4.0 International', - identifier: 'CC-BY-SA-4.0', - canonicalUrl: ['https://creativecommons.org/licenses/by-sa/4.0/'], - licenseFragments: [] + "CC-BY-SA-4.0": { + "licenseName": "Creative Commons Attribution-ShareAlike 4.0 International", + "identifier": "CC-BY-SA-4.0", + "canonicalUrl": [ + "https://creativecommons.org/licenses/by-sa/4.0/" + ], + "licenseFragments": [] }, - - 'CC0-1.0': { - licenseName: 'Creative Commons CC0 1.0 Universal', - identifier: 'CC0-1.0', - canonicalUrl: [ - 'http://creativecommons.org/publicdomain/zero/1.0/legalcode', - 'magnet:?xt=urn:btih:90dc5c0be029de84e523b9b3922520e79e0e6f08&dn=cc0.txt' + "CC0-1.0": { + "licenseName": "Creative Commons CC0 1.0 Universal", + "identifier": "CC0-1.0", + "canonicalUrl": [ + "http://creativecommons.org/publicdomain/zero/1.0/legalcode", + "magnet:?xt=urn:btih:90dc5c0be029de84e523b9b3922520e79e0e6f08&dn=cc0.txt" ], - licenseFragments: [] + "licenseFragments": [] }, - - 'CECILL-2.0': { - licenseName: 'CeCILL Free Software License Agreement v2.0', - identifier: 'CECILL-2.0', - canonicalUrl: [ - 'https://www.cecill.info/licences/Licence_CeCILL_V2-en.txt', - 'magnet:?xt=urn:btih:dda0473d240d7febeac8fa265da27286ead0b1ce&dn=cecill-2.0.txt' + "CECILL-2.0": { + "licenseName": "CeCILL Free Software License Agreement v2.0", + "identifier": "CECILL-2.0", + "canonicalUrl": [ + "https://www.cecill.info/licences/Licence_CeCILL_V2-en.txt", + "magnet:?xt=urn:btih:dda0473d240d7febeac8fa265da27286ead0b1ce&dn=cecill-2.0.txt" ], - licenseFragments: [] + "licenseFragments": [] }, - - 'CPAL-1.0': { - licenseName: 'Common Public Attribution License Version 1.0 (CPAL)', - identifier: 'CPAL-1.0', - canonicalUrl: [ - 'http://opensource.org/licenses/cpal_1.0', - 'magnet:?xt=urn:btih:84143bc45939fc8fa42921d619a95462c2031c5c&dn=cpal-1.0.txt' + "CPAL-1.0": { + "licenseName": "Common Public Attribution License Version 1.0 (CPAL)", + "identifier": "CPAL-1.0", + "canonicalUrl": [ + "http://opensource.org/licenses/cpal_1.0", + "magnet:?xt=urn:btih:84143bc45939fc8fa42921d619a95462c2031c5c&dn=cpal-1.0.txt" ], - licenseFragments: [ + "licenseFragments": [ { - text: 'The contents of this file are subject to the Common Public Attribution License Version 1.0', - type: type.SHORT + "text": "The contents of this file are subject to the Common Public Attribution License Version 1.0", + "type": "short" }, { - text: 'The term "External Deployment" means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.', - type: type.SHORT + "text": "The term \"External Deployment\" means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.", + "type": "short" } ] }, - - 'EPL-1.0': { - licenseName: "Eclipse Public License Version 1.0", - identifier: "EPL-1.0", - canonicalUrl: [ + "EPL-1.0": { + "licenseName": "Eclipse Public License Version 1.0", + "identifier": "EPL-1.0", + "canonicalUrl": [ "http://www.eclipse.org/legal/epl-v10.html", "magnet:?xt=urn:btih:4c6a2ad0018cd461e9b0fc44e1b340d2c1828b22&dn=epl-1.0.txt" ], - licenseFragments: [ + "licenseFragments": [ { - text: "THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (\"AGREEMENT\"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.", - type: type.SHORT + "text": "THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (\"AGREEMENT\"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.", + "type": "short" } ] }, - - 'Expat': { - licenseName: 'Expat License (sometimes called MIT Licensed)', - identifier: 'Expat', - canonicalUrl: [ - 'http://www.jclark.com/xml/copying.txt', - 'magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt' + "Expat": { + "licenseName": "Expat License (sometimes called MIT Licensed)", + "identifier": "Expat", + "canonicalUrl": [ + "http://www.jclark.com/xml/copying.txt", + "magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt" ], - licenseFragments: [{ text: "Copyright Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Copyright Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", + "type": "short" + } + ] }, - - 'FreeBSD': { - licenseName: "FreeBSD License", - identifier: 'FreeBSD', - canonicalUrl: [ - 'http://www.freebsd.org/copyright/freebsd-license.html', - 'magnet:?xt=urn:btih:87f119ba0b429ba17a44b4bffcab33165ebdacc0&dn=freebsd.txt' + "FreeBSD": { + "licenseName": "FreeBSD License", + "identifier": "FreeBSD", + "canonicalUrl": [ + "http://www.freebsd.org/copyright/freebsd-license.html", + "magnet:?xt=urn:btih:87f119ba0b429ba17a44b4bffcab33165ebdacc0&dn=freebsd.txt" ], - licenseFragments: [{ text: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.", + "type": "short" + } + ] }, - - 'GNU-All-Permissive': { - licenseName: 'GNU All-Permissive License', - identifier: 'GNU-All-Permissive', - canonicalUrl: [], - licenseFragments: [{ text: "Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty.", type: type.SHORT }] + "GNU-All-Permissive": { + "licenseName": "GNU All-Permissive License", + "identifier": "GNU-All-Permissive", + "canonicalUrl": [], + "licenseFragments": [ + { + "text": "Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty.", + "type": "short" + } + ] }, - - 'GPL-2.0': { - licenseName: 'GNU General Public License (GPL) version 2', - identifier: 'GPL-2.0', - canonicalUrl: [ - 'http://www.gnu.org/licenses/gpl-2.0.html', - 'magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt' + "GPL-2.0": { + "licenseName": "GNU General Public License (GPL) version 2", + "identifier": "GPL-2.0", + "canonicalUrl": [ + "http://www.gnu.org/licenses/gpl-2.0.html", + "magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt" ], - licenseFragments: [{ text: " is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.", type: type.SHORT }, - { text: "Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later (the \"GPL\"), or the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL.", type: type.SHORT }] + "licenseFragments": [ + { + "text": " is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.", + "type": "short" + }, + { + "text": "Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later (the \"GPL\"), or the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL.", + "type": "short" + } + ] }, - - 'GPL-3.0': { - licenseName: 'GNU General Public License (GPL) version 3', - identifier: 'GPL-3.0', - canonicalUrl: [ - 'http://www.gnu.org/licenses/gpl-3.0.html', - 'magnet:?xt=urn:btih:1f739d935676111cfff4b4693e3816e664797050&dn=gpl-3.0.txt' + "GPL-3.0": { + "licenseName": "GNU General Public License (GPL) version 3", + "identifier": "GPL-3.0", + "canonicalUrl": [ + "http://www.gnu.org/licenses/gpl-3.0.html", + "magnet:?xt=urn:btih:1f739d935676111cfff4b4693e3816e664797050&dn=gpl-3.0.txt" ], - licenseFragments: [ - { text: " is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License (GNU GPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The code is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. As additional permission under GNU GPL version 3 section 7, you may distribute non-source (e.g., minimized or compacted) forms of that code without the copy of the GNU GPL normally required by section 4, provided you include this license notice and a URL through which recipients can access the Corresponding Source.", type: type.SHORT }, - { text: " is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.", type: type.SHORT }] + "licenseFragments": [ + { + "text": " is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License (GNU GPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The code is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. As additional permission under GNU GPL version 3 section 7, you may distribute non-source (e.g., minimized or compacted) forms of that code without the copy of the GNU GPL normally required by section 4, provided you include this license notice and a URL through which recipients can access the Corresponding Source.", + "type": "short" + }, + { + "text": " is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.", + "type": "short" + } + ] }, - - 'ISC': { - licenseName: "The ISC License", - identifier: 'ISC', - canonicalUrl: [ - 'https://www.isc.org/downloads/software-support-policy/isc-license/', - 'magnet:?xt=urn:btih:b8999bbaf509c08d127678643c515b9ab0836bae&dn=ISC.txt' + "ISC": { + "licenseName": "The ISC License", + "identifier": "ISC", + "canonicalUrl": [ + "https://www.isc.org/downloads/software-support-policy/isc-license/", + "magnet:?xt=urn:btih:b8999bbaf509c08d127678643c515b9ab0836bae&dn=ISC.txt" ], - licenseFragments: [{ text: "Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", type: type.SHORT }, - { text: "Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", + "type": "short" + }, + { + "text": "Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", + "type": "short" + } + ] }, - - 'jQueryTools': { - licenseName: "jQuery Tools", - identifier: 'jQueryTools', - canonicalUrl: [], - licenseFragments: [{ - text: 'NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.', - type: type.SHORT - }] + "jQueryTools": { + "licenseName": "jQuery Tools", + "identifier": "jQueryTools", + "canonicalUrl": [], + "licenseFragments": [ + { + "text": "NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.", + "type": "short" + } + ] }, - - 'LGPL-2.1': { - licenseName: 'GNU Lesser General Public License, version 2.1', - identifier: 'LGPL-2.1', - canonicalUrl: [ - 'http://www.gnu.org/licenses/lgpl-2.1.html', - 'magnet:?xt=urn:btih:5de60da917303dbfad4f93fb1b985ced5a89eac2&dn=lgpl-2.1.txt' + "LGPL-2.1": { + "licenseName": "GNU Lesser General Public License, version 2.1", + "identifier": "LGPL-2.1", + "canonicalUrl": [ + "http://www.gnu.org/licenses/lgpl-2.1.html", + "magnet:?xt=urn:btih:5de60da917303dbfad4f93fb1b985ced5a89eac2&dn=lgpl-2.1.txt" ], - licenseFragments: [{ text: " is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.", type: type.SHORT }] + "licenseFragments": [ + { + "text": " is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.", + "type": "short" + } + ] }, - - 'LGPL-3.0': { - licenseName: 'GNU Lesser General Public License, version 3', - identifier: 'LGPL-3.0', - canonicalUrl: [ - 'http://www.gnu.org/licenses/lgpl-3.0.html', - 'magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt' + "LGPL-3.0": { + "licenseName": "GNU Lesser General Public License, version 3", + "identifier": "LGPL-3.0", + "canonicalUrl": [ + "http://www.gnu.org/licenses/lgpl-3.0.html", + "magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt" ], - licenseFragments: [{ text: " is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.", type: type.SHORT }] + "licenseFragments": [ + { + "text": " is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.", + "type": "short" + } + ] }, - - 'MPL-2.0': { - licenseName: 'Mozilla Public License Version 2.0', - identifier: 'MPL-2.0', - canonicalUrl: [ - 'http://www.mozilla.org/MPL/2.0', - 'magnet:?xt=urn:btih:3877d6d54b3accd4bc32f8a48bf32ebc0901502a&dn=mpl-2.0.txt' + "MPL-2.0": { + "licenseName": "Mozilla Public License Version 2.0", + "identifier": "MPL-2.0", + "canonicalUrl": [ + "http://www.mozilla.org/MPL/2.0", + "magnet:?xt=urn:btih:3877d6d54b3accd4bc32f8a48bf32ebc0901502a&dn=mpl-2.0.txt" ], - licenseFragments: [{ text: "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/.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "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/.", + "type": "short" + } + ] }, - - 'PublicDomain': { - licenseName: 'Public Domain', - identifier: 'PublicDomain', - canonicalUrl: [ - 'magnet:?xt=urn:btih:e95b018ef3580986a04669f1b5879592219e2a7a&dn=public-domain.txt' + "PublicDomain": { + "licenseName": "Public Domain", + "identifier": "PublicDomain", + "canonicalUrl": [ + "magnet:?xt=urn:btih:e95b018ef3580986a04669f1b5879592219e2a7a&dn=public-domain.txt" ], - licenseFragments: [] + "licenseFragments": [] }, - - - 'Unlicense': { - licenseName: 'Unlicense', - identifier: 'Unlicense', - canonicalUrl: [ - 'http://unlicense.org/UNLICENSE', - 'magnet:?xt=urn:btih:5ac446d35272cc2e4e85e4325b146d0b7ca8f50c&dn=unlicense.txt' + "Unlicense": { + "licenseName": "Unlicense", + "identifier": "Unlicense", + "canonicalUrl": [ + "http://unlicense.org/UNLICENSE", + "magnet:?xt=urn:btih:5ac446d35272cc2e4e85e4325b146d0b7ca8f50c&dn=unlicense.txt" ], - licenseFragments: [ + "licenseFragments": [ { - text: 'This is free and unencumbered software released into the public domain.', - type: type.SHORT - }, + "text": "This is free and unencumbered software released into the public domain.", + "type": "short" + } ] }, - - 'UPL': { - licenseName: 'Universal Permissive License', - identifier: 'UPL-1.0', - canonicalUrl: [ - 'https://oss.oracle.com/licenses/upl/', - 'magnet:?xt=urn:btih:478974f4d41c3fa84c4befba25f283527fad107d&dn=upl-1.0.txt' + "UPL": { + "licenseName": "Universal Permissive License", + "identifier": "UPL-1.0", + "canonicalUrl": [ + "https://oss.oracle.com/licenses/upl/", + "magnet:?xt=urn:btih:478974f4d41c3fa84c4befba25f283527fad107d&dn=upl-1.0.txt" ], - licenseFragments: [{ - text: "The Universal Permissive License (UPL), Version 1.0", - type: type.SHORT - }] + "licenseFragments": [ + { + "text": "The Universal Permissive License (UPL), Version 1.0", + "type": "short" + } + ] }, - - 'WTFPL': { - licenseName: 'Do What The F*ck You Want To Public License (WTFPL)', - identifier: 'WTFPL', - canonicalUrl: [ - 'http://www.wtfpl.net/txt/copying/', - 'magnet:?xt=urn:btih:723febf9f6185544f57f0660a41489c7d6b4931b&dn=wtfpl.txt' + "WTFPL": { + "licenseName": "Do What The F*ck You Want To Public License (WTFPL)", + "identifier": "WTFPL", + "canonicalUrl": [ + "http://www.wtfpl.net/txt/copying/", + "magnet:?xt=urn:btih:723febf9f6185544f57f0660a41489c7d6b4931b&dn=wtfpl.txt" ], - licenseFragments: [ + "licenseFragments": [ { - text: 'DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE', - type: type.SHORT + "text": "DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE", + "type": "short" }, { - text: '0. You just DO WHAT THE FUCK YOU WANT TO.', - type: type.SHORT + "text": "0. You just DO WHAT THE FUCK YOU WANT TO.", + "type": "short" } ] }, - - 'X11': { - licenseName: 'X11 License', - identifier: 'X11', - canonicalUrl: [ - 'magnet:?xt=urn:btih:5305d91886084f776adcf57509a648432709a7c7&dn=x11.txt' + "X11": { + "licenseName": "X11 License", + "identifier": "X11", + "canonicalUrl": [ + "magnet:?xt=urn:btih:5305d91886084f776adcf57509a648432709a7c7&dn=x11.txt" ], - licenseFragments: [{ text: "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", type: type.SHORT }] + "licenseFragments": [ + { + "text": "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", + "type": "short" + } + ] }, - - 'XFree86-1.1': { - licenseName: "XFree86 1.1 License", - identifier: 'XFree86-1.1', - canonicalUrl: [ - 'http://www.xfree86.org/3.3.6/COPYRIGHT2.html#3', - 'http://www.xfree86.org/current/LICENSE4.html', - 'magnet:?xt=urn:btih:12f2ec9e8de2a3b0002a33d518d6010cc8ab2ae9&dn=xfree86.txt' + "XFree86-1.1": { + "licenseName": "XFree86 1.1 License", + "identifier": "XFree86-1.1", + "canonicalUrl": [ + "http://www.xfree86.org/3.3.6/COPYRIGHT2.html#3", + "http://www.xfree86.org/current/LICENSE4.html", + "magnet:?xt=urn:btih:12f2ec9e8de2a3b0002a33d518d6010cc8ab2ae9&dn=xfree86.txt" ], - licenseFragments: [{ text: "All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution, and in the same place and form as other copyright, license and disclaimer information.\n3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: \"This product includes software developed by The XFree86 Project, Inc (http://www.xfree86.org/) and its contributors\", in the same place and form as other third-party acknowledgments. Alternately, this acknowledgment may appear in the software itself, in the same form and location as other such third-party acknowledgments.4. Except as contained in this notice, the name of The XFree86 Project, Inc shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The XFree86 Project, Inc.", type: type.SHORT } + "licenseFragments": [ + { + "text": "All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution, and in the same place and form as other copyright, license and disclaimer information.\n3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: \"This product includes software developed by The XFree86 Project, Inc (http://www.xfree86.org/) and its contributors\", in the same place and form as other third-party acknowledgments. Alternately, this acknowledgment may appear in the software itself, in the same form and location as other such third-party acknowledgments.4. Except as contained in this notice, the name of The XFree86 Project, Inc shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The XFree86 Project, Inc.", + "type": "short" + } ] }, - - 'Zlib': { - licenseName: 'zlib License', - canonicalUrl: [ - 'https://www.zlib.net/zlib_license.html', - 'https://spdx.org/licenses/Zlib.txt', - 'magnet:?xt=urn:btih:922bd98043fa3daf4f9417e3e8fec8406b1961a3&dn=zlib.txt' + "Zlib": { + "licenseName": "zlib License", + "canonicalUrl": [ + "https://www.zlib.net/zlib_license.html", + "https://spdx.org/licenses/Zlib.txt", + "magnet:?xt=urn:btih:922bd98043fa3daf4f9417e3e8fec8406b1961a3&dn=zlib.txt" ], - identifier: 'Zlib', - licenseFragments: [] + "identifier": "Zlib", + "licenseFragments": [] + } +} + +},{}],11:[function(require,module,exports){ +/** + * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. + * * + * Copyright (C) 2011, 2012, 2013, 2014 Loic J. Duros + * Copyright (C) 2014, 2015 Nik Nyby + * Copyright (C) 2022 Yuchen Pei + * + * This file is part of GNU LibreJS. + * + * GNU LibreJS is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GNU LibreJS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU LibreJS. If not, see . + */ + +exports.patternUtils = { + /** + * removeNonalpha + * + * Remove all nonalphanumeric values, except for + * < and >, since they are what we use for tokens. + * + */ + removeNonalpha: function(str) { + return str.replace(/[^a-z0-9<>@]+/gi, ''); + }, + + removeWhitespace: function(str) { + return str.replace(/\/\//gmi, '').replace(/\*/gmi, '').replace(/\s+/gmi, ''); + }, + + replaceTokens: function(str) { + return str.replace(/<.*?>/gi, '.*?'); }, + + removeJsComments: function(str) { + const ml_comments = /\/\*.*?(\*\/)/g; + const il_comments = /\/\/.*/gm; + return str.replace(ml_comments, '').replace(il_comments, ''); + } }; -},{}],11:[function(require,module,exports){ +},{}],12:[function(require,module,exports){ /** * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript. * * * Copyright (C) 2017, 2018 Nathan Nichols * Copyright (C) 2018 Ruben Rodriguez +* Copyright (C) 2022 Yuchen Pei * * This file is part of GNU LibreJS. * @@ -2069,62 +2523,15 @@ exports.licenses = { * along with GNU LibreJS. If not, see . */ -const acorn = require('acorn'); -const legacy_license_lib = require('./legacy_license_check.js'); -const { ResponseProcessor } = require('./bg/ResponseProcessor'); +const checkLib = require('./common/checks.js'); +const { ResponseProcessor, BLOCKING_RESPONSES } = require('./bg/ResponseProcessor'); const { Storage, ListStore, hash } = require('./common/Storage'); const { ListManager } = require('./bg/ListManager'); const { ExternalLicenses } = require('./bg/ExternalLicenses'); -const { licenses } = require('./license_definitions'); -const { patternUtils } = require('./pattern_utils'); - -console.log('main_background.js'); -/** -* If this is true, it evaluates entire scripts instead of returning as soon as it encounters a violation. -* -* Also, it controls whether or not this part of the code logs to the console. -* -*/ -var DEBUG = false; // debug the JS evaluation -var PRINT_DEBUG = false; // Everything else -var time = Date.now(); - -function dbg_print(a, b) { - if (PRINT_DEBUG == true) { - console.log('Time spent so far: ' + (Date.now() - time) / 1000 + ' seconds'); - if (b === undefined) { - console.log(a); - } else { - console.log(a, b); - } - } -} - -/* - NONTRIVIAL THINGS: - - Fetch - - XMLhttpRequest - - eval() - - ? - JAVASCRIPT CAN BE FOUND IN: - - Event handlers (onclick, onload, onsubmit, etc.) - - - - - WAYS TO DETERMINE PASS/FAIL: - - "// @license [magnet link] [identifier]" then "// @license-end" (may also use /* comments) - - Automatic whitelist: (http://bzr.savannah.gnu.org/lh/librejs/dev/annotate/head:/data/script_libraries/script-libraries.json_ -*/ +const { makeDebugLogger } = require('./common/debug.js'); -// These are objects that it will search for in an initial regex pass over non-free scripts. -var reserved_objects = [ - //"document", - //"window", - 'fetch', - 'XMLHttpRequest', - 'chrome', // only on chrome - 'browser', // only on firefox - 'eval' -]; +const PRINT_DEBUG = false; +const dbgPrint = makeDebugLogger('main_background.js', PRINT_DEBUG, Date.now()); /* * @@ -2138,22 +2545,14 @@ var reserved_objects = [ * with its code to update accordingly * */ -function options_listener(changes, area) { - dbg_print('Items updated in area' + area + ': '); - - var changedItems = Object.keys(changes); - var changed_items = ''; - for (var i = 0; i < changedItems.length; i++) { - var item = changedItems[i]; - changed_items += item + ','; - } - dbg_print(changed_items); - +function optionsListener(changes, area) { + dbgPrint('Items updated in area' + area + ': '); + dbgPrint(Object.keys(changes).join(',')); } +const activeMessagePorts = {}; +const activityReports = {}; -var activeMessagePorts = {}; -var activityReports = {}; async function createReport(initializer) { if (!(initializer && (initializer.url || initializer.tabId))) { throw new Error('createReport() needs an URL or a tabId at least'); @@ -2170,7 +2569,7 @@ async function createReport(initializer) { template.url = url; template.site = ListStore.siteItem(url); template.siteStatus = listManager.getStatus(template.site); - let list = { 'whitelisted': whitelist, 'blacklisted': blacklist }[template.siteStatus]; + const list = { 'whitelisted': whitelist, 'blacklisted': blacklist }[template.siteStatus]; if (list) { template.listedSite = ListManager.siteMatch(template.site, list); } @@ -2183,19 +2582,17 @@ async function createReport(initializer) { * at the moment. */ async function openReportInTab(data) { - let popupURL = await browser.browserAction.getPopup({}); - let tab = await browser.tabs.create({ url: `${popupURL}#fromTab=${data.tabId}` }); + const popupURL = await browser.browserAction.getPopup({}); + const tab = await browser.tabs.create({ url: `${popupURL}#fromTab=${data.tabId}` }); activityReports[tab.id] = await createReport(data); } /** -* * Clears local storage (the persistent data) -* */ -function debug_delete_local() { +function debugDeleteLocal() { browser.storage.local.clear(); - dbg_print('Local storage cleared'); + dbgPrint('Local storage cleared'); } /** @@ -2203,16 +2600,16 @@ function debug_delete_local() { * Prints local storage (the persistent data) as well as the temporary popup object * */ -function debug_print_local() { - function storage_got(items) { +function debugPrintLocal() { + function storageGot(items) { console.log('%c Local storage: ', 'color: red;'); - for (var i in items) { + for (const i in items) { console.log('%c ' + i + ' = ' + items[i], 'color: blue;'); } } console.log('%c Variable \'activityReports\': ', 'color: red;'); console.log(activityReports); - browser.storage.local.get(storage_got); + browser.storage.local.get(storageGot); } /** @@ -2231,86 +2628,84 @@ function debug_print_local() { * */ async function updateReport(tabId, oldReport, updateUI = false) { - let { url } = oldReport; - let newReport = await createReport({ url, tabId }); - for (let property of Object.keys(oldReport)) { - let entries = oldReport[property]; + const { url } = oldReport; + const newReport = await createReport({ url, tabId }); + for (const property of Object.keys(oldReport)) { + const entries = oldReport[property]; if (!Array.isArray(entries)) continue; - let defValue = property === 'accepted' || property === 'blocked' ? property : 'unknown'; - for (let script of entries) { - let status = listManager.getStatus(script[0], defValue); + const defValue = property === 'accepted' || property === 'blocked' ? property : 'unknown'; + for (const script of entries) { + const status = listManager.getStatus(script[0], defValue); if (Array.isArray(newReport[status])) newReport[status].push(script); } } activityReports[tabId] = newReport; if (browser.sessions) browser.sessions.setTabValue(tabId, url, newReport); - dbg_print(newReport); + dbgPrint(newReport); if (updateUI && activeMessagePorts[tabId]) { - dbg_print(`[TABID: ${tabId}] Sending script blocking report directly to browser action.`); + dbgPrint(`[TABID: ${tabId}] Sending script blocking report directly to browser action.`); activeMessagePorts[tabId].postMessage({ show_info: newReport }); } } -/** -* -* This is what you call when a page gets changed to update the info box. -* -* Sends a message to the content script that adds a popup entry for a tab. -* -* The action argument is an object with two properties: one named either -* "accepted","blocked", "whitelisted", "blacklisted" or "unknown", whose value -* is the array [scriptName, reason], and another named "url". Example: -* action = { -* "accepted": ["jquery.js (someHash)","Whitelisted by user"], -* "url": "https://example.com/js/jquery.js" -* } -* -* Returns either "whitelisted, "blacklisted", "blocked", "accepted" or "unknown" -* -* NOTE: This WILL break if you provide inconsistent URLs to it. -* Make sure it will use the right URL when refering to a certain script. -* -*/ +/** Updates the report for tab with tabId with action. + * + * This is what you call when a page gets changed to update the info + * box. + * + * Sends a message to the content script that adds a popup entry for + * a tab. + * + * The action argument is an object with two properties: one named of + * "accepted","blocked", "whitelisted", "blacklisted", whose value is + * the array [scriptName, reason], and another named "url". Example: + * action = + * { + * "accepted": ["jquery.js (someHash)", "Whitelisted by user"], + * "url": "https://example.com/js/jquery.js" + * } + * + * Overrides the action type with the white/blacklist status for + * scriptName, if any. Then add the entry if scriptName is not + * already in the entries associated with the action type. + * + * Returns one of "whitelisted", "blacklisted", "blocked", "accepted" + * or "unknown" + * + * NOTE: This WILL break if you provide inconsistent URLs to it. + * Make sure it will use the right URL when refering to a certain + * script. + * + */ async function addReportEntry(tabId, action) { - let report = activityReports[tabId]; - if (!report) report = activityReports[tabId] = - await createReport({ tabId }); - let type, actionValue; - for (type of ['accepted', 'blocked', 'whitelisted', 'blacklisted']) { - if (type in action) { - actionValue = action[type]; - break; - } - } - if (!actionValue) { - console.debug('Something wrong with action', action); - return ''; - } - // Search unused data for the given entry - function isNew(entries, item) { - for (let e of entries) { - if (e[0] === item) return false; - } - return true; + const actionPair = Object.entries(action).find( + ([k, _]) => ['accepted', 'blocked', 'whitelisted', 'blacklisted'].indexOf(k) != -1); + if (!actionPair) { + console.debug('Wrong action', action); + return 'unknown'; } + const [actionType, actionValue] = actionPair; + const scriptName = actionValue[0]; + const report = activityReports[tabId] || (activityReports[tabId] = await createReport({ tabId })); let entryType; - let scriptName = actionValue[0]; + // Update the report if the scriptName is new for the entryType. try { - entryType = listManager.getStatus(scriptName, type); - let entries = report[entryType]; - if (isNew(entries, scriptName)) { - dbg_print(activityReports); - dbg_print(activityReports[tabId]); - dbg_print(entryType); + entryType = listManager.getStatus(scriptName, actionType); + const entries = report[entryType]; + if (!entries.find(e => e[0] === scriptName)) { + dbgPrint(activityReports); + dbgPrint(activityReports[tabId]); + dbgPrint(entryType); entries.push(actionValue); } } catch (e) { - console.error('action %o, type %s, entryType %s', action, type, entryType, e); + console.error('action %o, type %s, entryType %s', action, actionType, entryType, e); entryType = 'unknown'; } + // Refresh the main panel script list. if (activeMessagePorts[tabId]) { activeMessagePorts[tabId].postMessage({ show_info: report }); } @@ -2321,8 +2716,8 @@ async function addReportEntry(tabId, action) { } -function get_domain(url) { - var domain = url.replace('http://', '').replace('https://', '').split(/[/?#]/)[0]; +function getDomain(url) { + let domain = url.replace('http://', '').replace('https://', '').split(/[/?#]/)[0]; if (url.indexOf('http://') == 0) { domain = 'http://' + domain; } @@ -2335,10 +2730,11 @@ function get_domain(url) { } /** -* -* This is the callback where the content scripts of the browser action will contact the background script. -* -*/ + * + * This is the callback where the content scripts of the browser action + * will contact the background script. + * + */ async function connected(p) { if (p.name === 'contact_finder') { // style the contact finder panel @@ -2350,14 +2746,14 @@ async function connected(p) { }); // Send a message back with the relevant settings - p.postMessage(await browser.storage.local.get(['prefs_subject', 'prefs_body'])); + p.postMessage(await browser.storage.local.get(['pref_subject', 'pref_body'])); return; } p.onMessage.addListener(async function(m) { - var update = false; - var contact_finder = false; + let update = false; + let contactFinder = false; - for (let action of ['whitelist', 'blacklist', 'forget']) { + for (const action of ['whitelist', 'blacklist', 'forget']) { if (m[action]) { let [key] = m[action]; if (m.site) { @@ -2376,433 +2772,162 @@ async function connected(p) { // a debug feature if (m['printlocalstorage'] !== undefined) { console.log('Print local storage'); - debug_print_local(); + debugPrintLocal(); } // invoke_contact_finder if (m['invoke_contact_finder'] !== undefined) { - contact_finder = true; + contactFinder = true; await injectContactFinder(); } // a debug feature (maybe give the user an option to do this?) if (m['deletelocalstorage'] !== undefined) { console.log('Delete local storage'); - debug_delete_local(); + debugDeleteLocal(); } - let tabs = await browser.tabs.query({ active: true, currentWindow: true }); + const tabs = await browser.tabs.query({ active: true, currentWindow: true }); - if (contact_finder) { - let tab = tabs.pop(); - dbg_print(`[TABID:${tab.id}] Injecting contact finder`); - //inject_contact_finder(tabs[0]["id"]); + if (contactFinder) { + const tab = tabs.pop(); + dbgPrint(`[TABID:${tab.id}] Injecting contact finder`); } if (update || m.update && activityReports[m.tabId]) { - let tabId = 'tabId' in m ? m.tabId : tabs.pop().id; - dbg_print(`%c updating tab ${tabId}`, 'color: red;'); + const tabId = 'tabId' in m ? m.tabId : tabs.pop().id; + dbgPrint(`%c updating tab ${tabId}`, 'color: red;'); activeMessagePorts[tabId] = p; await updateReport(tabId, activityReports[tabId], true); } else { - for (let tab of tabs) { + for (const tab of tabs) { if (activityReports[tab.id]) { // If we have some data stored here for this tabID, send it - dbg_print(`[TABID: ${tab.id}] Sending stored data associated with browser action'`); + dbgPrint(`[TABID: ${tab.id}] Sending stored data associated with browser action'`); p.postMessage({ 'show_info': activityReports[tab.id] }); } else { - // create a new entry - let report = activityReports[tab.id] = await createReport({ 'url': tab.url, tabId: tab.id }); - p.postMessage({ show_info: report }); - dbg_print(`[TABID: ${tab.id}] No data found, creating a new entry for this window.`); - } - } - } - }); -} - -/** -* The callback for tab closings. -* -* Delete the info we are storing about this tab if there is any. -* -*/ -function delete_removed_tab_info(tab_id, _) { - dbg_print('[TABID:' + tab_id + ']' + 'Deleting stored info about closed tab'); - if (activityReports[tab_id] !== undefined) { - delete activityReports[tab_id]; - } - if (activeMessagePorts[tab_id] !== undefined) { - delete activeMessagePorts[tab_id]; - } - ExternalLicenses.purgeCache(tab_id); -} - -/** -* Called when the tab gets updated / activated -* -* Here we check if new tab's url matches activityReports[tabId].url, and if -* it doesn't we use the session cached value (if any). -* -*/ - -async function onTabUpdated(tabId, _, tab) { - let [url] = tab.url.split('#'); - let report = activityReports[tabId]; - if (!(report && report.url === url)) { - let cache = browser.sessions && - await browser.sessions.getTabValue(tabId, url) || null; - // on session restore tabIds may change - if (cache && cache.tabId !== tabId) cache.tabId = tabId; - updateBadge(tabId, activityReports[tabId] = cache); - } -} - -async function onTabActivated({ tabId }) { - await onTabUpdated(tabId, {}, await browser.tabs.get(tabId)); -} - -/* *********************************************************************************************** */ - -var fname_data = require('./fname_data.json').fname_data; - -//************************this part can be tested in the HTML file index.html's script test.js**************************** - -function full_evaluate(script) { - if (script === undefined || script == '') { - return [true, 'Harmless null script']; - } - - var amtloops = 0; - - var loopkeys = { 'for': true, 'if': true, 'while': true, 'switch': true }; - var operators = { '||': true, '&&': true, '=': true, '==': true, '++': true, '--': true, '+=': true, '-=': true, '*': true }; - try { - var tokens = acorn.tokenizer(script); - } catch (e) { - console.warn('Tokenizer could not be initiated (probably invalid code)'); - return [false, 'Tokenizer could not be initiated (probably invalid code)']; - } - try { - var toke = tokens.getToken(); - } catch (e) { - console.log(script); - console.log(e); - console.warn('couldn\'t get first token (probably invalid code)'); - console.warn('Continuing evaluation'); - } - - /** - * Given the end of an identifer token, it tests for parentheses - */ - function is_bsn(end) { - var i = 0; - while (script.charAt(end + i).match(/\s/g) !== null) { - i++; - if (i >= script.length - 1) { - return false; - } - } - return script.charAt(end + i) == '['; - } - var defines_functions = false; - while (toke !== undefined && toke.type != acorn.tokTypes.eof) { - if (toke.type.keyword !== undefined) { - //dbg_print("Keyword:"); - //dbg_print(toke); - - // This type of loop detection ignores functional loop alternatives and ternary operators - - if (toke.type.keyword == 'function') { - dbg_print('%c NOTICE: Function declaration.', 'color:green'); - defines_functions = true; - } - - if (loopkeys[toke.type.keyword] !== undefined) { - amtloops++; - if (amtloops > 3) { - dbg_print('%c NONTRIVIAL: Too many loops/conditionals.', 'color:red'); - if (DEBUG == false) { - return [false, 'NONTRIVIAL: Too many loops/conditionals.']; - } - } - } - } else if (toke.value !== undefined && operators[toke.value] !== undefined) { - // It's just an operator. Javascript doesn't have operator overloading so it must be some - // kind of primitive (I.e. a number) - } else if (toke.value !== undefined) { - var status = fname_data[toke.value]; - if (status === true) { // is the identifier banned? - dbg_print('%c NONTRIVIAL: nontrivial token: \'' + toke.value + '\'', 'color:red'); - if (DEBUG == false) { - return [false, 'NONTRIVIAL: nontrivial token: \'' + toke.value + '\'']; - } - } else if (status === false) {// is the identifier not banned? - // Is there bracket suffix notation? - if (is_bsn(toke.end)) { - dbg_print('%c NONTRIVIAL: Bracket suffix notation on variable \'' + toke.value + '\'', 'color:red'); - if (DEBUG == false) { - return [false, '%c NONTRIVIAL: Bracket suffix notation on variable \'' + toke.value + '\'']; - } - } - } else if (status === undefined) {// is the identifier user defined? - // Is there bracket suffix notation? - if (is_bsn(toke.end)) { - dbg_print('%c NONTRIVIAL: Bracket suffix notation on variable \'' + toke.value + '\'', 'color:red'); - if (DEBUG == false) { - return [false, 'NONTRIVIAL: Bracket suffix notation on variable \'' + toke.value + '\'']; - } + // create a new entry + const report = activityReports[tab.id] = await createReport({ 'url': tab.url, tabId: tab.id }); + p.postMessage({ show_info: report }); + dbgPrint(`[TABID: ${tab.id}] No data found, creating a new entry for this window.`); } - } else { - dbg_print('trivial token:' + toke.value); } } - // If not a keyword or an identifier it's some kind of operator, field parenthesis, brackets - try { - toke = tokens.getToken(); - } catch (e) { - dbg_print('Denied script because it cannot be parsed.'); - return [false, 'NONTRIVIAL: Cannot be parsed. This could mean it is a 404 error.']; - } - } - - dbg_print('%cAppears to be trivial.', 'color:green;'); - if (defines_functions === true) - return [true, 'Script appears to be trivial but defines functions.']; - else - return [true, 'Script appears to be trivial.']; + }); } +/** +* Loads the contact finder on the given tab ID. +*/ +async function injectContactFinder(tabId) { + await Promise.all([ + browser.tabs.insertCSS(tabId, { file: '/content/overlay.css', cssOrigin: 'user' }), + browser.tabs.executeScript(tabId, { file: '/content/contactFinder.js' }), + ]); +} -//**************************************************************************************************** /** -* This is the entry point for full code evaluation. -* -* Performs the initial pass on code to see if it needs to be completely parsed -* -* This can only determine if a script is bad, not if it's good +* The callback for tab closings. * -* If it passes the intitial pass, it runs the full pass and returns the result - -* It returns an array of [flag (boolean, false if "bad"), reason (string, human readable report)] +* Delete the info we are storing about this tab if there is any. * */ -function evaluate(script, name) { - function reserved_object_regex(object) { - var arith_operators = '\\+\\-\\*\\/\\%\\='; - return new RegExp('(?:[^\\w\\d]|^|(?:' + arith_operators + '))' + object + '(?:\\s*?(?:[\\;\\,\\.\\(\\[])\\s*?)', 'g'); - } - reserved_object_regex('window'); - const ml_comment = /\/\*([\s\S]+?)\*\//g; - const il_comment = /\/\/.+/gm; - var temp = script.replace(/'.+?'+/gm, '\'string\''); - temp = temp.replace(/".+?"+/gm, '"string"'); - temp = temp.replace(ml_comment, ''); - temp = temp.replace(il_comment, ''); - dbg_print('%c ------evaluation results for ' + name + '------', 'color:white'); - dbg_print('Script accesses reserved objects?'); - var flag = true; - var reason = '' - // This is where individual "passes" are made over the code - for (var i = 0; i < reserved_objects.length; i++) { - var res = reserved_object_regex(reserved_objects[i]).exec(temp); - if (res != null) { - dbg_print('%c fail', 'color:red;'); - flag = false; - reason = 'Script uses a reserved object (' + reserved_objects[i] + ')'; - } - } - if (flag) { - dbg_print('%c pass', 'color:green;'); - } else { - return [flag, reason]; - } - - return full_evaluate(script); -} - - -function validateLicense(matches) { - if (!(Array.isArray(matches) && matches.length >= 4)) { - return [false, 'Malformed or unrecognized license tag.']; +function deleteRemovedTabInfo(tab_id, _) { + dbgPrint('[TABID:' + tab_id + ']' + 'Deleting stored info about closed tab'); + if (activityReports[tab_id] !== undefined) { + delete activityReports[tab_id]; } - - const [all, first] = [matches[0], matches[2].replace('&', '&')]; - - for (const key in licenses) { - // Match by link on first parameter (legacy) - for (const url of licenses[key].canonicalUrl) { - if (first === url || first === url.replace('^http://', 'https://')) { - return [true, `Recognized license: "${licenses[key].licenseName}".`]; - } - } + if (activeMessagePorts[tab_id] !== undefined) { + delete activeMessagePorts[tab_id]; } - return [false, `Unrecognized license tag: "${all}"`]; + ExternalLicenses.purgeCache(tab_id); } - /** +* Called when the tab gets updated / activated * -* Evaluates the content of a script (license, if it is non-trivial) +* Here we check if new tab's url matches activityReports[tabId].url, and if +* it doesn't we use the session cached value (if any). * -* Returns -* [ -* true (accepted) or false (denied), -* edited content, -* reason text -* ] */ -function license_read(scriptSrc, name, external = false) { - - const license = legacy_license_lib.check(scriptSrc); - if (license) { - return [true, scriptSrc, `Licensed under: ${license}`]; - } - if (listManager.builtInHashes.has(hash(scriptSrc))) { - return [true, scriptSrc, 'Common script known to be free software.']; - } - - let editedSrc = ''; - let uneditedSrc = scriptSrc.trim(); - let reason = uneditedSrc ? '' : 'Empty source.'; - let partsDenied = false; - let partsAccepted = false; - - function checkTriviality(s) { - if (!patternUtils.removeJsComments(s).trim()) { - return true; // empty, ignore it - } - const [trivial, message] = external ? - [false, 'External script with no known license'] - : evaluate(s, name); - if (trivial) { - partsAccepted = true; - editedSrc += s; - } else { - partsDenied = true; - if (s.startsWith('javascript:')) - editedSrc += `# LIBREJS BLOCKED: ${message}`; - else - editedSrc += `/*\nLIBREJS BLOCKED: ${message}\n*/`; - } - reason += `\n${message}`; - return trivial; - } - - while (uneditedSrc) { - const openingMatch = /\/[/*]\s*?(@license)\s+(\S+)\s+(\S+).*$/mi.exec(uneditedSrc); - if (!openingMatch) { // no license found, check for triviality - checkTriviality(uneditedSrc); - break; - } - - const openingIndex = openingMatch.index; - if (openingIndex) { - // let's check the triviality of the code before the license tag, if any - checkTriviality(uneditedSrc.substring(0, openingIndex)); - } - // let's check the actual license - uneditedSrc = uneditedSrc.substring(openingIndex); - - const closureMatch = - /\/([*/])\s*@license-end\s*(\*\/)?/mi.exec(uneditedSrc); - if (!closureMatch) { - const msg = 'ERROR: @license with no @license-end'; - return [false, `\n/*\n ${msg} \n*/\n`, msg]; - } - - let closureEndIndex = closureMatch.index + closureMatch[0].length; - const commentEndOffset = uneditedSrc.substring(closureEndIndex).indexOf(closureMatch[1] === '*' ? '*/' : '\n'); - if (commentEndOffset !== -1) { - closureEndIndex += commentEndOffset; - } - - const [licenseOK, message] = validateLicense(openingMatch); - if (licenseOK) { - editedSrc += uneditedSrc.substr(0, closureEndIndex); - partsAccepted = true; - } else { - editedSrc += `\n/*\n${message}\n*/\n`; - partsDenied = true; - } - reason += `\n${message}`; - // trim off everything we just evaluated - uneditedSrc = uneditedSrc.substring(closureEndIndex).trim(); - } - - if (partsDenied) { - if (partsAccepted) { - reason = `Some parts of the script have been disabled (check the source for details).\n^--- ${reason}`; - } - return [false, editedSrc, reason]; +async function onTabUpdated(tabId, _, tab) { + const [url] = tab.url.split('#'); + const report = activityReports[tabId]; + if (!(report && report.url === url)) { + const cache = browser.sessions && + await browser.sessions.getTabValue(tabId, url) || null; + // on session restore tabIds may change + if (cache && cache.tabId !== tabId) cache.tabId = tabId; + updateBadge(tabId, activityReports[tabId] = cache); } +} - return [true, scriptSrc, reason]; +async function onTabActivated({ tabId }) { + await onTabUpdated(tabId, {}, await browser.tabs.get(tabId)); } /* *********************************************************************************************** */ // TODO: Test if this script is being loaded from another domain compared to activityReports[tabid]["url"] /** -* Asynchronous function, returns the final edited script as a string, -* or an array containing it and the index, if the latter !== -1 -*/ -async function get_script(response, url, tabId = -1, whitelisted = false, index = -1) { - function result(scriptSource) { - return index === -1 ? scriptSource : [scriptSource, index]; - } - - - let scriptName = url.split('/').pop(); + * Checks script and updates the report entry accordingly. + * + * Asynchronous function, returns the final edited script as a string, + * or unedited script if passAccWlist is true and the script is + * accepted or whitelisted. + */ +async function checkScriptAndUpdateReport(scriptSrc, url, tabId, whitelisted, isExternal = false, passAccWlist = false) { + const scriptName = url.split('/').pop(); if (whitelisted) { if (tabId !== -1) { - let site = ListManager.siteMatch(url, whitelist); + const site = ListManager.siteMatch(url, whitelist); // Accept without reading script, it was explicitly whitelisted - let reason = site + const reason = site ? `All ${site} whitelisted by user` : 'Address whitelisted by user'; addReportEntry(tabId, { 'whitelisted': [site || url, reason], url }); } - if (response.startsWith('javascript:')) - return result(response); + if (scriptSrc.startsWith('javascript:') || passAccWlist) + return scriptSrc; else - return result(`/* LibreJS: script whitelisted by user preference. */\n${response}`); + return `/* LibreJS: script whitelisted by user preference. */\n${scriptSrc}`; } - let [verdict, editedSource, reason] = license_read(response, scriptName, index === -2); + const [accepted, editedSource, reason] = listManager.builtInHashes.has(hash(scriptSrc)) ? [true, scriptSrc, 'Common script known to be free software.'] : checkLib.checkScriptSource(scriptSrc, scriptName, isExternal); if (tabId < 0) { - return result(verdict ? response : editedSource); + return editedSource; } - let domain = get_domain(url); - let report = activityReports[tabId] || (activityReports[tabId] = await createReport({ tabId })); - updateBadge(tabId, report, !verdict); - let category = await addReportEntry(tabId, { 'url': domain, [verdict ? 'accepted' : 'blocked']: [url, reason] }); - switch (category) { + const domain = getDomain(url); + const report = activityReports[tabId] || (activityReports[tabId] = await createReport({ tabId })); + updateBadge(tabId, report, !accepted); + const actionType = await addReportEntry(tabId, { 'url': domain, [accepted ? 'accepted' : 'blocked']: [url, reason] }); + switch (actionType) { case 'blacklisted': { - editedSource = `/* LibreJS: script ${category} by user. */`; - return result(response.startsWith('javascript:') - ? `javascript:void(${encodeURIComponent(editedSource)})` : editedSource); - } - case 'whitelisted': { - return result(response.startsWith('javascript:') - ? response : `/* LibreJS: script ${category} by user. */\n${response}`); + const edited = `/* LibreJS: script ${actionType} by user. */`; + return scriptSrc.startsWith('javascript:') + ? `javascript:void(${encodeURIComponent(edited)})` : edited; } + case 'whitelisted': + case 'accepted': + { + return (scriptSrc.startsWith('javascript:') || passAccWlist) + ? scriptSrc : `/* LibreJS: script ${actionType} by user. */\n${scriptSrc}`; + } + // blocked default: { - let scriptSource = verdict ? response : editedSource; - return result(response.startsWith('javascript:') - ? (verdict ? scriptSource : `javascript:void(/* ${scriptSource} */)`) - : `/* LibreJS: script ${category}. */\n${scriptSource}` - ); + return scriptSrc.startsWith('javascript:') + ? `javascript:void(/* ${editedSource} */)` + : `/* LibreJS: script ${actionType}. */\n${editedSource}`; } } } - +// Updates the extension icon in the toolbar. function updateBadge(tabId, report = null, forceRed = false) { - let blockedCount = report ? report.blocked.length + report.blacklisted.length : 0; - let [text, color] = blockedCount > 0 || forceRed + const blockedCount = report ? report.blocked.length + report.blacklisted.length : 0; + const [text, color] = blockedCount > 0 || forceRed ? [blockedCount && blockedCount.toString() || '!', 'red'] : ['✓', 'green'] - let { browserAction } = browser; + const { browserAction } = browser; if ('setBadgeText' in browserAction) { browserAction.setBadgeText({ text, tabId }); browserAction.setBadgeBackgroundColor({ color, tabId }); @@ -2812,9 +2937,10 @@ function updateBadge(tabId, report = null, forceRed = false) { } } +// TODO: is this the only way google analytics can show up? function blockGoogleAnalytics(request) { - let { url } = request; - let res = {}; + const { url } = request; + const res = {}; if (url === 'https://www.google-analytics.com/analytics.js' || /^https:\/\/www\.google\.com\/analytics\/[^#]/.test(url) ) { @@ -2824,49 +2950,56 @@ function blockGoogleAnalytics(request) { } async function blockBlacklistedScripts(request) { - let { url, tabId, documentUrl } = request; - url = ListStore.urlItem(url); - let status = listManager.getStatus(url); + const { tabId, documentUrl } = request; + const url = ListStore.urlItem(request.url); + const status = listManager.getStatus(url); if (status !== 'blacklisted') return {}; - let blacklistedSite = ListManager.siteMatch(url, blacklist); + const blacklistedSite = ListManager.siteMatch(url, blacklist); await addReportEntry(tabId, { url: documentUrl, 'blacklisted': [url, /\*/.test(blacklistedSite) ? `User blacklisted ${blacklistedSite}` : 'Blacklisted by user'] }); - return { cancel: true }; + return BLOCKING_RESPONSES.REJECT; } /** -* This listener gets called as soon as we've got all the HTTP headers, can guess -* content type and encoding, and therefore correctly parse HTML documents -* and external script inclusions in search of non-free JavaScript -*/ - -var ResponseHandler = { + * An onHeadersReceived handler. See bg/ResponseProcessor.js for how + * it is used. + * + * This listener gets called as soon as we've got all the HTTP + * headers, can guess content type and encoding, and therefore + * correctly parse HTML documents and external script inclusions in + * search of non-free JavaScript + */ +const ResponseHandler = { /** - * Enforce white/black lists for url/site early (hashes will be handled later) - */ + * Checks black/whitelists and web labels. Returns a + * BlockingResponse (if we can determine) or null (if further work + * is needed). + * + * Enforce white/black lists for url/site early (hashes will be + * handled later) + */ async pre(response) { - let { request } = response; - let { url, type, tabId, frameId, documentUrl } = request; - - let fullUrl = url; - url = ListStore.urlItem(url); - let site = ListStore.siteItem(url); - - let blacklistedSite = ListManager.siteMatch(site, blacklist); - let blacklisted = blacklistedSite || blacklist.contains(url); - let topUrl = type === 'sub_frame' && request.frameAncestors && request.frameAncestors.pop() || documentUrl; + const { request } = response; + const { type, tabId, frameId, documentUrl } = request; + const fullUrl = request.url; + const url = ListStore.urlItem(fullUrl); + const site = ListStore.siteItem(url); + const blacklistedSite = ListManager.siteMatch(site, blacklist); + const blacklisted = blacklistedSite || blacklist.contains(url); + const topUrl = type === 'sub_frame' && request.frameAncestors && request.frameAncestors.pop() || documentUrl; if (blacklisted) { if (type === 'script') { // this shouldn't happen, because we intercept earlier in blockBlacklistedScripts() - return ResponseProcessor.REJECT; + return BLOCKING_RESPONSES.REJECT; } - if (type === 'main_frame') { // we handle the page change here too, since we won't call edit_html() + // we handle the page change here too, since we won't call editHtml() + if (type === 'main_frame') { activityReports[tabId] = await createReport({ url: fullUrl, tabId }); // Go on without parsing the page: it was explicitly blacklisted - let reason = blacklistedSite + const reason = blacklistedSite ? `All ${blacklistedSite} blacklisted by user` : 'Address blacklisted by user'; await addReportEntry(tabId, { 'blacklisted': [blacklistedSite || url, reason], url: fullUrl }); @@ -2876,10 +3009,11 @@ var ResponseHandler = { name: 'Content-security-policy', value: 'script-src \'none\';' }); - return { responseHeaders: request.responseHeaders }; // let's skip the inline script parsing, since we block by CSP + // let's skip the inline script parsing, since we block by CSP + return { responseHeaders: request.responseHeaders }; } else { - let whitelistedSite = ListManager.siteMatch(site, whitelist); - let whitelisted = response.whitelisted = whitelistedSite || whitelist.contains(url); + const whitelistedSite = ListManager.siteMatch(site, whitelist); + const whitelisted = response.whitelisted = whitelistedSite || whitelist.contains(url); if (type === 'script') { if (whitelisted) { // accept the script and stop processing @@ -2887,19 +3021,16 @@ var ResponseHandler = { url: topUrl, 'whitelisted': [url, whitelistedSite ? `User whitelisted ${whitelistedSite}` : 'Whitelisted by user'] }); - return ResponseProcessor.ACCEPT; + return BLOCKING_RESPONSES.ACCEPT; } else { - let scriptInfo = await ExternalLicenses.check({ url: fullUrl, tabId, frameId, documentUrl }); + // Check the web labels + const scriptInfo = await ExternalLicenses.check({ url: fullUrl, tabId, frameId, documentUrl }); if (scriptInfo) { - let verdict, ret; - let msg = scriptInfo.toString(); - if (scriptInfo.free) { - verdict = 'accepted'; - ret = ResponseProcessor.ACCEPT; - } else { - verdict = 'blocked'; - ret = ResponseProcessor.REJECT; - } + const [verdict, ret] = scriptInfo.free ? ['accepted', BLOCKING_RESPONSES.ACCEPT] : ['blocked', BLOCKING_RESPONSES.REJECT]; + const licenseIds = [...scriptInfo.licenses].map(l => l.identifier).sort().join(', '); + const msg = licenseIds + ? `Free license${scriptInfo.licenses.size > 1 ? 's' : ''} (${licenseIds})` + : 'Unknown license(s)'; addReportEntry(tabId, { url, [verdict]: [url, msg] }); return ret; } @@ -2908,28 +3039,26 @@ var ResponseHandler = { } // it's a page (it's too early to report) or an unknown script: // let's keep processing - return ResponseProcessor.CONTINUE; + return null; }, /** * Here we do the heavylifting, analyzing unknown scripts */ async post(response) { - let { type } = response.request; - let handle_it = type === 'script' ? handle_script : handle_html; - return await handle_it(response, response.whitelisted); + const { type } = response.request; + const handler = type === 'script' ? handleScript : handleHtml; + return await handler(response, response.whitelisted); } } /** * Here we handle external script requests */ -async function handle_script(response, whitelisted) { - let { text, request } = response; - let { url, tabId } = request; - url = ListStore.urlItem(url); - let edited = await get_script(text, url, tabId, whitelisted, -2); - return Array.isArray(edited) ? edited[0] : edited; +async function handleScript(response, whitelisted) { + const { text, request } = response; + const { url, tabId } = request; + return await checkScriptAndUpdateReport(text, ListStore.urlItem(url), tabId, whitelisted, isExternal = true, passAccWlist = true); } /** @@ -2939,7 +3068,7 @@ async function handle_script(response, whitelisted) { function doc2HTML(doc) { let s = doc.documentElement.outerHTML; if (doc.doctype) { - let dt = doc.doctype; + const dt = doc.doctype; let sDoctype = ` elements on pages where LibreJS disabled inline scripts (unless -* they have the "data-librejs-nodisplay" attribute). + * Forces displaying any noscript element not having the "data-librejs-nodisplay" attribute on pages. + * returns number of elements forced, mutates doc. */ function forceNoscriptElements(doc) { let shown = 0; // inspired by NoScript's onScriptDisabled.js - for (let noscript of doc.querySelectorAll('noscript:not([data-librejs-nodisplay])')) { - let replacement = forceElement(doc, noscript); + for (const noscript of doc.querySelectorAll('noscript:not([data-librejs-nodisplay])')) { + const replacement = forceElement(doc, noscript); // emulate meta-refresh - let meta = replacement.querySelector('meta[http-equiv="refresh"]'); + const meta = replacement.querySelector('meta[http-equiv="refresh"]'); if (meta) { doc.head.appendChild(meta); } @@ -2985,14 +3113,13 @@ function forceNoscriptElements(doc) { } return shown; } + /** -* Forces displaying any element having the "data-librejs-display" attribute and -*