summaryrefslogtreecommitdiffstats
path: root/toolkit/mozapps/extensions/internal/siteperms-addon-utils.sys.mjs
blob: 86853d71681b7a6ad9e7c2ab2a90d2e5a9facd06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

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

export const GATED_PERMISSIONS = ["midi", "midi-sysex"];
export const SITEPERMS_ADDON_PROVIDER_PREF =
  "dom.sitepermsaddon-provider.enabled";
export const SITEPERMS_ADDON_TYPE = "sitepermission";
export const SITEPERMS_ADDON_BLOCKEDLIST_PREF =
  "dom.sitepermsaddon-provider.separatedBlocklistedDomains";

const lazy = {};
XPCOMUtils.defineLazyPreferenceGetter(
  lazy,
  "blocklistedOriginsSet",
  SITEPERMS_ADDON_BLOCKEDLIST_PREF,
  // Default value
  "",
  // onUpdate
  null,
  // transform
  prefValue => new Set(prefValue.split(","))
);

/**
 * @param {string} type
 * @returns {boolean}
 */
export function isGatedPermissionType(type) {
  return GATED_PERMISSIONS.includes(type);
}

/**
 * @param {string} siteOrigin
 * @returns {boolean}
 */
export function isKnownPublicSuffix(siteOrigin) {
  const { host } = new URL(siteOrigin);

  let isPublic = false;
  // getKnownPublicSuffixFromHost throws when passed an IP, in such case, assume
  // this is not a public etld.
  try {
    isPublic = Services.eTLD.getKnownPublicSuffixFromHost(host) == host;
  } catch (e) {}

  return isPublic;
}

/**
 * ⚠️ This should be only used for testing purpose ⚠️
 *
 * @param {Array<String>} permissionTypes
 * @throws if not called from xpcshell test
 */
export function addGatedPermissionTypesForXpcShellTests(permissionTypes) {
  if (!Services.env.exists("XPCSHELL_TEST_PROFILE_DIR")) {
    throw new Error("This should only be called from XPCShell tests");
  }

  GATED_PERMISSIONS.push(...permissionTypes);
}

/**
 * @param {nsIPrincipal} principal
 * @returns {Boolean}
 */
export function isPrincipalInSitePermissionsBlocklist(principal) {
  return lazy.blocklistedOriginsSet.has(principal.baseDomain);
}