@metamask-previews/phishing-controller 12.0.0-preview-04657153 → 12.0.1-preview-6ea311ff
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -2
- package/dist/PhishingController.js +2 -2
- package/dist/PhishingController.mjs +1 -1
- package/dist/PhishingDetector.js +2 -2
- package/dist/PhishingDetector.mjs +1 -1
- package/dist/{chunk-F7CZ3O4X.mjs → chunk-I3U4U3MW.mjs} +20 -4
- package/dist/chunk-I3U4U3MW.mjs.map +1 -0
- package/dist/{chunk-XZNT2KYX.js → chunk-ZAOBCAQT.js} +21 -5
- package/dist/chunk-ZAOBCAQT.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/PhishingController.d.ts.map +1 -1
- package/dist/types/utils.d.ts +7 -0
- package/dist/types/utils.d.ts.map +1 -1
- package/dist/utils.js +4 -2
- package/dist/utils.mjs +3 -1
- package/package.json +3 -3
- package/dist/chunk-F7CZ3O4X.mjs.map +0 -1
- package/dist/chunk-XZNT2KYX.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [12.0.1]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Add `getHostnameFromUrl` utility function to standardize hostname extraction from URLs ([#4645](https://github.com/MetaMask/core/pull/4645))
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Update `test`, `isBlockedRequest`, and `bypass` methods to use the hostname for allowlist checks instead of the full origin ([#4645](https://github.com/MetaMask/core/pull/4645))
|
|
19
|
+
- The previous approach of using the full origin had limitations in dealing with subdomains or variations in the URL structure, which could lead to inconsistent results or false negatives.
|
|
20
|
+
|
|
10
21
|
## [12.0.0]
|
|
11
22
|
|
|
12
23
|
### Added
|
|
@@ -87,7 +98,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
87
98
|
- Changed Stalelist and hotlist update intervals ([#4202](https://github.com/MetaMask/core/pull/4202))
|
|
88
99
|
- Updated the Stalelist update interval to 30 days and the hotlist update interval to 5 mins
|
|
89
100
|
- Bump `@metamask/controller-utils` version to `~9.1.0` ([#4153](https://github.com/MetaMask/core/pull/4153))
|
|
90
|
-
- Bump TypeScript version to `~4.9.5` ([#4084](https://github.com/MetaMask/core
|
|
101
|
+
- Bump TypeScript version to `~4.9.5` ([#4084](https://github.com/MetaMask/core/pull/4084))
|
|
91
102
|
- Bump `@metamask/base-controller` to `^5.0.2`
|
|
92
103
|
|
|
93
104
|
## [9.0.1]
|
|
@@ -251,7 +262,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
251
262
|
|
|
252
263
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
253
264
|
|
|
254
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/phishing-controller@12.0.
|
|
265
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/phishing-controller@12.0.1...HEAD
|
|
266
|
+
[12.0.1]: https://github.com/MetaMask/core/compare/@metamask/phishing-controller@12.0.0...@metamask/phishing-controller@12.0.1
|
|
255
267
|
[12.0.0]: https://github.com/MetaMask/core/compare/@metamask/phishing-controller@11.0.0...@metamask/phishing-controller@12.0.0
|
|
256
268
|
[11.0.0]: https://github.com/MetaMask/core/compare/@metamask/phishing-controller@10.1.1...@metamask/phishing-controller@11.0.0
|
|
257
269
|
[10.1.1]: https://github.com/MetaMask/core/compare/@metamask/phishing-controller@10.1.0...@metamask/phishing-controller@10.1.1
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
|
|
18
|
-
var
|
|
18
|
+
var _chunkZAOBCAQTjs = require('./chunk-ZAOBCAQT.js');
|
|
19
19
|
require('./chunk-5NDIXQG5.js');
|
|
20
20
|
require('./chunk-Z4BLTVTB.js');
|
|
21
21
|
|
|
@@ -35,5 +35,5 @@ require('./chunk-Z4BLTVTB.js');
|
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
|
|
38
|
-
exports.C2_DOMAIN_BLOCKLIST_ENDPOINT =
|
|
38
|
+
exports.C2_DOMAIN_BLOCKLIST_ENDPOINT = _chunkZAOBCAQTjs.C2_DOMAIN_BLOCKLIST_ENDPOINT; exports.C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = _chunkZAOBCAQTjs.C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL; exports.C2_DOMAIN_BLOCKLIST_URL = _chunkZAOBCAQTjs.C2_DOMAIN_BLOCKLIST_URL; exports.CLIENT_SIDE_DETECION_BASE_URL = _chunkZAOBCAQTjs.CLIENT_SIDE_DETECION_BASE_URL; exports.HOTLIST_REFRESH_INTERVAL = _chunkZAOBCAQTjs.HOTLIST_REFRESH_INTERVAL; exports.ListKeys = _chunkZAOBCAQTjs.ListKeys; exports.ListNames = _chunkZAOBCAQTjs.ListNames; exports.METAMASK_HOTLIST_DIFF_FILE = _chunkZAOBCAQTjs.METAMASK_HOTLIST_DIFF_FILE; exports.METAMASK_HOTLIST_DIFF_URL = _chunkZAOBCAQTjs.METAMASK_HOTLIST_DIFF_URL; exports.METAMASK_STALELIST_FILE = _chunkZAOBCAQTjs.METAMASK_STALELIST_FILE; exports.METAMASK_STALELIST_URL = _chunkZAOBCAQTjs.METAMASK_STALELIST_URL; exports.PHISHING_CONFIG_BASE_URL = _chunkZAOBCAQTjs.PHISHING_CONFIG_BASE_URL; exports.PhishingController = _chunkZAOBCAQTjs.PhishingController; exports.STALELIST_REFRESH_INTERVAL = _chunkZAOBCAQTjs.STALELIST_REFRESH_INTERVAL; exports.default = _chunkZAOBCAQTjs.PhishingController_default; exports.phishingListKeyNameMap = _chunkZAOBCAQTjs.phishingListKeyNameMap;
|
|
39
39
|
//# sourceMappingURL=PhishingController.js.map
|
package/dist/PhishingDetector.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkZAOBCAQTjs = require('./chunk-ZAOBCAQT.js');
|
|
4
4
|
require('./chunk-5NDIXQG5.js');
|
|
5
5
|
require('./chunk-Z4BLTVTB.js');
|
|
6
6
|
|
|
7
7
|
|
|
8
|
-
exports.PhishingDetector =
|
|
8
|
+
exports.PhishingDetector = _chunkZAOBCAQTjs.PhishingDetector;
|
|
9
9
|
//# sourceMappingURL=PhishingDetector.js.map
|
|
@@ -417,7 +417,8 @@ var PhishingController = class extends BaseController {
|
|
|
417
417
|
*/
|
|
418
418
|
test(origin) {
|
|
419
419
|
const punycodeOrigin = toASCII(origin);
|
|
420
|
-
|
|
420
|
+
const hostname = getHostnameFromUrl(punycodeOrigin);
|
|
421
|
+
if (this.state.whitelist.includes(hostname || punycodeOrigin)) {
|
|
421
422
|
return { result: false, type: "all" /* All */ };
|
|
422
423
|
}
|
|
423
424
|
return __privateGet(this, _detector).check(punycodeOrigin);
|
|
@@ -434,6 +435,10 @@ var PhishingController = class extends BaseController {
|
|
|
434
435
|
*/
|
|
435
436
|
isBlockedRequest(origin) {
|
|
436
437
|
const punycodeOrigin = toASCII(origin);
|
|
438
|
+
const hostname = getHostnameFromUrl(punycodeOrigin);
|
|
439
|
+
if (this.state.whitelist.includes(hostname || punycodeOrigin)) {
|
|
440
|
+
return { result: false, type: "all" /* All */ };
|
|
441
|
+
}
|
|
437
442
|
return __privateGet(this, _detector).isMaliciousC2Domain(punycodeOrigin);
|
|
438
443
|
}
|
|
439
444
|
/**
|
|
@@ -443,12 +448,13 @@ var PhishingController = class extends BaseController {
|
|
|
443
448
|
*/
|
|
444
449
|
bypass(origin) {
|
|
445
450
|
const punycodeOrigin = toASCII(origin);
|
|
451
|
+
const hostname = getHostnameFromUrl(punycodeOrigin);
|
|
446
452
|
const { whitelist } = this.state;
|
|
447
|
-
if (whitelist.includes(punycodeOrigin)) {
|
|
453
|
+
if (whitelist.includes(hostname || punycodeOrigin)) {
|
|
448
454
|
return;
|
|
449
455
|
}
|
|
450
456
|
this.update((draftState) => {
|
|
451
|
-
draftState.whitelist.push(punycodeOrigin);
|
|
457
|
+
draftState.whitelist.push(hostname || punycodeOrigin);
|
|
452
458
|
});
|
|
453
459
|
}
|
|
454
460
|
/**
|
|
@@ -761,6 +767,15 @@ var sha256Hash = (hostname) => {
|
|
|
761
767
|
const hashBuffer = sha256(new TextEncoder().encode(hostname.toLowerCase()));
|
|
762
768
|
return bytesToHex(hashBuffer);
|
|
763
769
|
};
|
|
770
|
+
var getHostnameFromUrl = (url) => {
|
|
771
|
+
let hostname;
|
|
772
|
+
try {
|
|
773
|
+
hostname = new URL(url).hostname;
|
|
774
|
+
} catch (error) {
|
|
775
|
+
return null;
|
|
776
|
+
}
|
|
777
|
+
return hostname;
|
|
778
|
+
};
|
|
764
779
|
|
|
765
780
|
export {
|
|
766
781
|
fetchTimeNow,
|
|
@@ -775,6 +790,7 @@ export {
|
|
|
775
790
|
domainPartsToFuzzyForm,
|
|
776
791
|
matchPartsAgainstList,
|
|
777
792
|
sha256Hash,
|
|
793
|
+
getHostnameFromUrl,
|
|
778
794
|
PhishingDetector,
|
|
779
795
|
PHISHING_CONFIG_BASE_URL,
|
|
780
796
|
METAMASK_STALELIST_FILE,
|
|
@@ -793,4 +809,4 @@ export {
|
|
|
793
809
|
PhishingController,
|
|
794
810
|
PhishingController_default
|
|
795
811
|
};
|
|
796
|
-
//# sourceMappingURL=chunk-
|
|
812
|
+
//# sourceMappingURL=chunk-I3U4U3MW.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/PhishingController.ts","../src/PhishingDetector.ts"],"sourcesContent":["import { bytesToHex } from '@noble/hashes/utils';\nimport { sha256 } from 'ethereum-cryptography/sha256';\n\nimport type { Hotlist, PhishingListState } from './PhishingController';\nimport { ListKeys, phishingListKeyNameMap } from './PhishingController';\nimport type {\n PhishingDetectorList,\n PhishingDetectorConfiguration,\n} from './PhishingDetector';\n\nconst DEFAULT_TOLERANCE = 3;\n\n/**\n * Fetches current epoch time in seconds.\n *\n * @returns the Date.now() time in seconds instead of miliseconds. backend files rely on timestamps in seconds since epoch.\n */\nexport const fetchTimeNow = (): number => Math.round(Date.now() / 1000);\n\n/**\n * Rounds a Unix timestamp down to the nearest minute.\n *\n * @param unixTimestamp - The Unix timestamp to be rounded.\n * @returns The rounded Unix timestamp.\n */\nexport function roundToNearestMinute(unixTimestamp: number): number {\n return Math.floor(unixTimestamp / 60) * 60;\n}\n\n/**\n * Split a string into two pieces, using the first period as the delimiter.\n *\n * @param stringToSplit - The string to split.\n * @returns An array of length two containing the beginning and end of the string.\n */\nconst splitStringByPeriod = <Start extends string, End extends string>(\n stringToSplit: `${Start}.${End}`,\n): [Start, End] => {\n const periodIndex = stringToSplit.indexOf('.');\n return [\n stringToSplit.slice(0, periodIndex) as Start,\n stringToSplit.slice(periodIndex + 1) as End,\n ];\n};\n\n/**\n * Determines which diffs are applicable to the listState, then applies those diffs.\n *\n * @param listState - the stalelist or the existing liststate that diffs will be applied to.\n * @param hotlistDiffs - the diffs to apply to the listState if valid.\n * @param listKey - the key associated with the input/output phishing list state.\n * @param recentlyAddedC2Domains - list of hashed C2 domains to add to the local c2 domain blocklist\n * @param recentlyRemovedC2Domains - list of hashed C2 domains to remove from the local c2 domain blocklist\n * @returns the new list state\n */\nexport const applyDiffs = (\n listState: PhishingListState,\n hotlistDiffs: Hotlist,\n listKey: ListKeys,\n recentlyAddedC2Domains: string[] = [],\n recentlyRemovedC2Domains: string[] = [],\n): PhishingListState => {\n // filter to remove diffs that were added before the lastUpdate time.\n // filter to remove diffs that aren't applicable to the specified list (by listKey).\n const diffsToApply = hotlistDiffs.filter(\n ({ timestamp, targetList }) =>\n timestamp > listState.lastUpdated &&\n splitStringByPeriod(targetList)[0] === listKey,\n );\n\n // the reason behind using latestDiffTimestamp as the lastUpdated time\n // is so that we can benefit server-side from memoization due to end client's\n // `GET /v1/diffSince/:timestamp` requests lining up with\n // our periodic updates (which create diffs at specific timestamps).\n let latestDiffTimestamp = listState.lastUpdated;\n\n const listSets = {\n allowlist: new Set(listState.allowlist),\n blocklist: new Set(listState.blocklist),\n fuzzylist: new Set(listState.fuzzylist),\n c2DomainBlocklist: new Set(listState.c2DomainBlocklist),\n };\n for (const { isRemoval, targetList, url, timestamp } of diffsToApply) {\n const targetListType = splitStringByPeriod(targetList)[1];\n if (timestamp > latestDiffTimestamp) {\n latestDiffTimestamp = timestamp;\n }\n if (isRemoval) {\n listSets[targetListType].delete(url);\n } else {\n listSets[targetListType].add(url);\n }\n }\n\n if (listKey === ListKeys.EthPhishingDetectConfig) {\n for (const hash of recentlyAddedC2Domains) {\n listSets.c2DomainBlocklist.add(hash);\n }\n for (const hash of recentlyRemovedC2Domains) {\n listSets.c2DomainBlocklist.delete(hash);\n }\n }\n\n return {\n c2DomainBlocklist: Array.from(listSets.c2DomainBlocklist),\n allowlist: Array.from(listSets.allowlist),\n blocklist: Array.from(listSets.blocklist),\n fuzzylist: Array.from(listSets.fuzzylist),\n version: listState.version,\n name: phishingListKeyNameMap[listKey],\n tolerance: listState.tolerance,\n lastUpdated: latestDiffTimestamp,\n };\n};\n\n/**\n * Validates the configuration object for the phishing detector.\n *\n * @param config - the configuration object to validate.\n * @throws an error if the configuration is invalid.\n */\nexport function validateConfig(\n config: unknown,\n): asserts config is PhishingListState {\n if (config === null || typeof config !== 'object') {\n throw new Error('Invalid config');\n }\n\n if ('tolerance' in config && !('fuzzylist' in config)) {\n throw new Error('Fuzzylist tolerance provided without fuzzylist');\n }\n\n if (\n 'name' in config &&\n (typeof config.name !== 'string' || config.name === '')\n ) {\n throw new Error(\"Invalid config parameter: 'name'\");\n }\n\n if (\n 'version' in config &&\n (!['number', 'string'].includes(typeof config.version) ||\n config.version === '')\n ) {\n throw new Error(\"Invalid config parameter: 'version'\");\n }\n}\n\n/**\n * Converts a domain string to a list of domain parts.\n *\n * @param domain - the domain string to convert.\n * @returns the list of domain parts.\n */\nexport const domainToParts = (domain: string) => {\n try {\n return domain.split('.').reverse();\n } catch (e) {\n throw new Error(JSON.stringify(domain));\n }\n};\n\n/**\n * Converts a list of domain strings to a list of domain parts.\n *\n * @param list - the list of domain strings to convert.\n * @returns the list of domain parts.\n */\nexport const processDomainList = (list: string[]) => {\n return list.map(domainToParts);\n};\n\n/**\n * Gets the default phishing detector configuration.\n *\n * @param override - the optional override for the configuration.\n * @param override.allowlist - the optional allowlist to override.\n * @param override.blocklist - the optional blocklist to override.\n * @param override.c2DomainBlocklist - the optional c2DomainBlocklist to override.\n * @param override.fuzzylist - the optional fuzzylist to override.\n * @param override.tolerance - the optional tolerance to override.\n * @returns the default phishing detector configuration.\n */\nexport const getDefaultPhishingDetectorConfig = ({\n allowlist = [],\n blocklist = [],\n fuzzylist = [],\n tolerance = DEFAULT_TOLERANCE,\n}: {\n allowlist?: string[];\n blocklist?: string[];\n c2DomainBlocklist?: string[];\n fuzzylist?: string[];\n tolerance?: number;\n}): PhishingDetectorConfiguration => ({\n allowlist: processDomainList(allowlist),\n blocklist: processDomainList(blocklist),\n fuzzylist: processDomainList(fuzzylist),\n tolerance,\n});\n\n/**\n * Processes the configurations for the phishing detector.\n *\n * @param configs - the configurations to process.\n * @returns the processed configurations.\n */\nexport const processConfigs = (configs: PhishingDetectorList[] = []) => {\n return configs.map((config: PhishingDetectorList) => {\n validateConfig(config);\n return { ...config, ...getDefaultPhishingDetectorConfig(config) };\n });\n};\n\n/**\n * Converts a list of domain parts to a domain string.\n *\n * @param domainParts - the list of domain parts.\n * @returns the domain string.\n */\nexport const domainPartsToDomain = (domainParts: string[]) => {\n return domainParts.slice().reverse().join('.');\n};\n\n/**\n * Converts a list of domain parts to a fuzzy form.\n *\n * @param domainParts - the list of domain parts.\n * @returns the fuzzy form of the domain.\n */\nexport const domainPartsToFuzzyForm = (domainParts: string[]) => {\n return domainParts.slice(1).reverse().join('.');\n};\n\n/**\n * Matches the target parts, ignoring extra subdomains on source.\n *\n * @param source - the source domain parts.\n * @param list - the list of domain parts to match against.\n * @returns the parts for the first found matching entry.\n */\nexport const matchPartsAgainstList = (source: string[], list: string[][]) => {\n return list.find((target) => {\n // target domain has more parts than source, fail\n if (target.length > source.length) {\n return false;\n }\n // source matches target or (is deeper subdomain)\n return target.every((part, index) => source[index] === part);\n });\n};\n\n/**\n * Generate the SHA-256 hash of a hostname.\n *\n * @param hostname - The hostname to hash.\n * @returns The SHA-256 hash of the hostname.\n */\nexport const sha256Hash = (hostname: string): string => {\n const hashBuffer = sha256(new TextEncoder().encode(hostname.toLowerCase()));\n return bytesToHex(hashBuffer);\n};\n\n/**\n * Extracts the hostname from a URL.\n *\n * @param url - The URL to extract the hostname from.\n * @returns The hostname extracted from the URL, or null if the URL is invalid.\n */\nexport const getHostnameFromUrl = (url: string): string | null => {\n let hostname;\n try {\n hostname = new URL(url).hostname;\n } catch (error) {\n return null;\n }\n return hostname;\n};\n","import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport { toASCII } from 'punycode/';\n\nimport { PhishingDetector } from './PhishingDetector';\nimport {\n PhishingDetectorResultType,\n type PhishingDetectorResult,\n} from './types';\nimport {\n applyDiffs,\n fetchTimeNow,\n getHostnameFromUrl,\n roundToNearestMinute,\n} from './utils';\n\nexport const PHISHING_CONFIG_BASE_URL =\n 'https://phishing-detection.api.cx.metamask.io';\nexport const METAMASK_STALELIST_FILE = '/v1/stalelist';\nexport const METAMASK_HOTLIST_DIFF_FILE = '/v1/diffsSince';\n\nexport const CLIENT_SIDE_DETECION_BASE_URL =\n 'https://client-side-detection.api.cx.metamask.io';\nexport const C2_DOMAIN_BLOCKLIST_ENDPOINT = '/v1/request-blocklist';\n\nexport const C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = 15 * 60; // 15 mins in seconds\nexport const HOTLIST_REFRESH_INTERVAL = 5 * 60; // 5 mins in seconds\nexport const STALELIST_REFRESH_INTERVAL = 30 * 24 * 60 * 60; // 30 days in seconds\n\nexport const METAMASK_STALELIST_URL = `${PHISHING_CONFIG_BASE_URL}${METAMASK_STALELIST_FILE}`;\nexport const METAMASK_HOTLIST_DIFF_URL = `${PHISHING_CONFIG_BASE_URL}${METAMASK_HOTLIST_DIFF_FILE}`;\nexport const C2_DOMAIN_BLOCKLIST_URL = `${CLIENT_SIDE_DETECION_BASE_URL}${C2_DOMAIN_BLOCKLIST_ENDPOINT}`;\n\n/**\n * @type ListTypes\n *\n * Type outlining the types of lists provided by aggregating different source lists\n */\nexport type ListTypes =\n | 'fuzzylist'\n | 'blocklist'\n | 'allowlist'\n | 'c2DomainBlocklist';\n\n/**\n * @type EthPhishingResponse\n *\n * Configuration response from the eth-phishing-detect package\n * consisting of approved and unapproved website origins\n * @property blacklist - List of unapproved origins\n * @property fuzzylist - List of fuzzy-matched unapproved origins\n * @property tolerance - Fuzzy match tolerance level\n * @property version - Version number of this configuration\n * @property whitelist - List of approved origins\n */\nexport type EthPhishingResponse = {\n blacklist: string[];\n fuzzylist: string[];\n tolerance: number;\n version: number;\n whitelist: string[];\n};\n\n/**\n * @type C2DomainBlocklistResponse\n *\n * Response for blocklist update requests\n * @property recentlyAdded - List of c2 domains recently added to the blocklist\n * @property recentlyRemoved - List of c2 domains recently removed from the blocklist\n * @property lastFetchedAt - Timestamp of the last fetch request\n */\nexport type C2DomainBlocklistResponse = {\n recentlyAdded: string[];\n recentlyRemoved: string[];\n lastFetchedAt: string;\n};\n\n/**\n * @type PhishingStalelist\n *\n * type defining expected type of the stalelist.json file.\n * @property eth_phishing_detect_config - Stale list sourced from eth-phishing-detect's config.json.\n * @property tolerance - Fuzzy match tolerance level\n * @property lastUpdated - Timestamp of last update.\n * @property version - Stalelist data structure iteration.\n */\nexport type PhishingStalelist = {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n eth_phishing_detect_config: Record<ListTypes, string[]>;\n tolerance: number;\n version: number;\n lastUpdated: number;\n};\n\n/**\n * @type PhishingListState\n *\n * type defining the persisted list state. This is the persisted state that is updated frequently with `this.maybeUpdateState()`.\n * @property allowlist - List of approved origins (legacy naming \"whitelist\")\n * @property blocklist - List of unapproved origins (legacy naming \"blacklist\")\n * @property c2DomainBlocklist - List of hashed hostnames that C2 requests are blocked against.\n * @property fuzzylist - List of fuzzy-matched unapproved origins\n * @property tolerance - Fuzzy match tolerance level\n * @property lastUpdated - Timestamp of last update.\n * @property version - Version of the phishing list state.\n * @property name - Name of the list. Used for attribution.\n */\nexport type PhishingListState = {\n allowlist: string[];\n blocklist: string[];\n c2DomainBlocklist: string[];\n fuzzylist: string[];\n tolerance: number;\n version: number;\n lastUpdated: number;\n name: ListNames;\n};\n\n/**\n * @type HotlistDiff\n *\n * type defining the expected type of the diffs in hotlist.json file.\n * @property url - Url of the diff entry.\n * @property timestamp - Timestamp at which the diff was identified.\n * @property targetList - The list name where the diff was identified.\n * @property isRemoval - Was the diff identified a removal type.\n */\nexport type HotlistDiff = {\n url: string;\n timestamp: number;\n targetList: `${ListKeys}.${ListTypes}`;\n isRemoval?: boolean;\n};\n\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type DataResultWrapper<T> = {\n data: T;\n};\n\n/**\n * @type Hotlist\n *\n * Type defining expected hotlist.json file.\n * @property url - Url of the diff entry.\n * @property timestamp - Timestamp at which the diff was identified.\n * @property targetList - The list name where the diff was identified.\n * @property isRemoval - Was the diff identified a removal type.\n */\nexport type Hotlist = HotlistDiff[];\n\n/**\n * Enum containing upstream data provider source list keys.\n * These are the keys denoting lists consumed by the upstream data provider.\n */\nexport enum ListKeys {\n EthPhishingDetectConfig = 'eth_phishing_detect_config',\n}\n\n/**\n * Enum containing downstream client attribution names.\n */\nexport enum ListNames {\n MetaMask = 'MetaMask',\n}\n\n/**\n * Maps from downstream client attribution name\n * to list key sourced from upstream data provider.\n */\nconst phishingListNameKeyMap = {\n [ListNames.MetaMask]: ListKeys.EthPhishingDetectConfig,\n};\n\n/**\n * Maps from list key sourced from upstream data\n * provider to downstream client attribution name.\n */\nexport const phishingListKeyNameMap = {\n [ListKeys.EthPhishingDetectConfig]: ListNames.MetaMask,\n};\n\nconst controllerName = 'PhishingController';\n\nconst metadata = {\n phishingLists: { persist: true, anonymous: false },\n whitelist: { persist: true, anonymous: false },\n hotlistLastFetched: { persist: true, anonymous: false },\n stalelistLastFetched: { persist: true, anonymous: false },\n c2DomainBlocklistLastFetched: { persist: true, anonymous: false },\n};\n\n/**\n * Get a default empty state for the controller.\n * @returns The default empty state.\n */\nconst getDefaultState = (): PhishingControllerState => {\n return {\n phishingLists: [],\n whitelist: [],\n hotlistLastFetched: 0,\n stalelistLastFetched: 0,\n c2DomainBlocklistLastFetched: 0,\n };\n};\n\n/**\n * @type PhishingControllerState\n *\n * Phishing controller state\n * @property phishing - eth-phishing-detect configuration\n * @property whitelist - array of temporarily-approved origins\n */\nexport type PhishingControllerState = {\n phishingLists: PhishingListState[];\n whitelist: string[];\n hotlistLastFetched: number;\n stalelistLastFetched: number;\n c2DomainBlocklistLastFetched: number;\n};\n\n/**\n * @type PhishingControllerOptions\n *\n * Phishing controller options\n * @property stalelistRefreshInterval - Polling interval used to fetch stale list.\n * @property hotlistRefreshInterval - Polling interval used to fetch hotlist diff list.\n * @property c2DomainBlocklistRefreshInterval - Polling interval used to fetch c2 domain blocklist.\n */\nexport type PhishingControllerOptions = {\n stalelistRefreshInterval?: number;\n hotlistRefreshInterval?: number;\n c2DomainBlocklistRefreshInterval?: number;\n messenger: PhishingControllerMessenger;\n state?: Partial<PhishingControllerState>;\n};\n\nexport type MaybeUpdateState = {\n type: `${typeof controllerName}:maybeUpdateState`;\n handler: PhishingController['maybeUpdateState'];\n};\n\nexport type TestOrigin = {\n type: `${typeof controllerName}:testOrigin`;\n handler: PhishingController['test'];\n};\n\nexport type PhishingControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n PhishingControllerState\n>;\n\nexport type PhishingControllerActions =\n | PhishingControllerGetStateAction\n | MaybeUpdateState\n | TestOrigin;\n\nexport type PhishingControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n PhishingControllerState\n>;\n\nexport type PhishingControllerEvents = PhishingControllerStateChangeEvent;\n\nexport type PhishingControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n PhishingControllerActions,\n PhishingControllerEvents,\n never,\n never\n>;\n\n/**\n * Controller that manages community-maintained lists of approved and unapproved website origins.\n */\nexport class PhishingController extends BaseController<\n typeof controllerName,\n PhishingControllerState,\n PhishingControllerMessenger\n> {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #detector: any;\n\n #stalelistRefreshInterval: number;\n\n #hotlistRefreshInterval: number;\n\n #c2DomainBlocklistRefreshInterval: number;\n\n #inProgressHotlistUpdate?: Promise<void>;\n\n #inProgressStalelistUpdate?: Promise<void>;\n\n #isProgressC2DomainBlocklistUpdate?: Promise<void>;\n\n /**\n * Construct a Phishing Controller.\n *\n * @param config - Initial options used to configure this controller.\n * @param config.stalelistRefreshInterval - Polling interval used to fetch stale list.\n * @param config.hotlistRefreshInterval - Polling interval used to fetch hotlist diff list.\n * @param config.c2DomainBlocklistRefreshInterval - Polling interval used to fetch c2 domain blocklist.\n * @param config.messenger - The controller restricted messenger.\n * @param config.state - Initial state to set on this controller.\n */\n constructor({\n stalelistRefreshInterval = STALELIST_REFRESH_INTERVAL,\n hotlistRefreshInterval = HOTLIST_REFRESH_INTERVAL,\n c2DomainBlocklistRefreshInterval = C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL,\n messenger,\n state = {},\n }: PhishingControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultState(),\n ...state,\n },\n });\n\n this.#stalelistRefreshInterval = stalelistRefreshInterval;\n this.#hotlistRefreshInterval = hotlistRefreshInterval;\n this.#c2DomainBlocklistRefreshInterval = c2DomainBlocklistRefreshInterval;\n this.#registerMessageHandlers();\n\n this.updatePhishingDetector();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:maybeUpdateState` as const,\n this.maybeUpdateState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:testOrigin` as const,\n this.test.bind(this),\n );\n }\n\n /**\n * Updates this.detector with an instance of PhishingDetector using the current state.\n */\n updatePhishingDetector() {\n this.#detector = new PhishingDetector(this.state.phishingLists);\n }\n\n /**\n * Set the interval at which the stale phishing list will be refetched.\n * Fetching will only occur on the next call to test/bypass.\n * For immediate update to the phishing list, call {@link updateStalelist} directly.\n *\n * @param interval - the new interval, in ms.\n */\n setStalelistRefreshInterval(interval: number) {\n this.#stalelistRefreshInterval = interval;\n }\n\n /**\n * Set the interval at which the hot list will be refetched.\n * Fetching will only occur on the next call to test/bypass.\n * For immediate update to the phishing list, call {@link updateHotlist} directly.\n *\n * @param interval - the new interval, in ms.\n */\n setHotlistRefreshInterval(interval: number) {\n this.#hotlistRefreshInterval = interval;\n }\n\n /**\n * Set the interval at which the C2 domain blocklist will be refetched.\n * Fetching will only occur on the next call to test/bypass.\n * For immediate update to the phishing list, call {@link updateHotlist} directly.\n *\n * @param interval - the new interval, in ms.\n */\n setC2DomainBlocklistRefreshInterval(interval: number) {\n this.#c2DomainBlocklistRefreshInterval = interval;\n }\n\n /**\n * Determine if an update to the stalelist configuration is needed.\n *\n * @returns Whether an update is needed\n */\n isStalelistOutOfDate() {\n return (\n fetchTimeNow() - this.state.stalelistLastFetched >=\n this.#stalelistRefreshInterval\n );\n }\n\n /**\n * Determine if an update to the hotlist configuration is needed.\n *\n * @returns Whether an update is needed\n */\n isHotlistOutOfDate() {\n return (\n fetchTimeNow() - this.state.hotlistLastFetched >=\n this.#hotlistRefreshInterval\n );\n }\n\n /**\n * Determine if an update to the C2 domain blocklist is needed.\n *\n * @returns Whether an update is needed\n */\n isC2DomainBlocklistOutOfDate() {\n return (\n fetchTimeNow() - this.state.c2DomainBlocklistLastFetched >=\n this.#c2DomainBlocklistRefreshInterval\n );\n }\n\n /**\n * Conditionally update the phishing configuration.\n *\n * If the stalelist configuration is out of date, this function will call `updateStalelist`\n * to update the configuration. This will automatically grab the hotlist,\n * so it isn't necessary to continue on to download the hotlist and the c2 domain blocklist.\n *\n */\n async maybeUpdateState() {\n const staleListOutOfDate = this.isStalelistOutOfDate();\n if (staleListOutOfDate) {\n await this.updateStalelist();\n return;\n }\n const hotlistOutOfDate = this.isHotlistOutOfDate();\n if (hotlistOutOfDate) {\n await this.updateHotlist();\n }\n const c2DomainBlocklistOutOfDate = this.isC2DomainBlocklistOutOfDate();\n if (c2DomainBlocklistOutOfDate) {\n await this.updateC2DomainBlocklist();\n }\n }\n\n /**\n * Determines if a given origin is unapproved.\n *\n * It is strongly recommended that you call {@link maybeUpdateState} before calling this,\n * to check whether the phishing configuration is up-to-date. It will be updated if necessary\n * by calling {@link updateStalelist} or {@link updateHotlist}.\n *\n * @param origin - Domain origin of a website.\n * @returns Whether the origin is an unapproved origin.\n */\n test(origin: string): PhishingDetectorResult {\n const punycodeOrigin = toASCII(origin);\n const hostname = getHostnameFromUrl(punycodeOrigin);\n if (this.state.whitelist.includes(hostname || punycodeOrigin)) {\n return { result: false, type: PhishingDetectorResultType.All }; // Same as whitelisted match returned by detector.check(...).\n }\n return this.#detector.check(punycodeOrigin);\n }\n\n /**\n * Checks if a request URL's domain is blocked against the request blocklist.\n *\n * This method is used to determine if a specific request URL is associated with a malicious\n * command and control (C2) domain. The URL's hostname is hashed and checked against a configured\n * blocklist of known malicious domains.\n *\n * @param origin - The full request URL to be checked.\n * @returns An object indicating whether the URL's domain is blocked and relevant metadata.\n */\n isBlockedRequest(origin: string): PhishingDetectorResult {\n const punycodeOrigin = toASCII(origin);\n const hostname = getHostnameFromUrl(punycodeOrigin);\n if (this.state.whitelist.includes(hostname || punycodeOrigin)) {\n return { result: false, type: PhishingDetectorResultType.All }; // Same as whitelisted match returned by detector.check(...).\n }\n return this.#detector.isMaliciousC2Domain(punycodeOrigin);\n }\n\n /**\n * Temporarily marks a given origin as approved.\n *\n * @param origin - The origin to mark as approved.\n */\n bypass(origin: string) {\n const punycodeOrigin = toASCII(origin);\n const hostname = getHostnameFromUrl(punycodeOrigin);\n const { whitelist } = this.state;\n if (whitelist.includes(hostname || punycodeOrigin)) {\n return;\n }\n this.update((draftState) => {\n draftState.whitelist.push(hostname || punycodeOrigin);\n });\n }\n\n /**\n * Update the C2 domain blocklist.\n *\n * If an update is in progress, no additional update will be made. Instead this will wait until\n * the in-progress update has finished.\n */\n async updateC2DomainBlocklist() {\n if (this.#isProgressC2DomainBlocklistUpdate) {\n await this.#isProgressC2DomainBlocklistUpdate;\n return;\n }\n\n try {\n this.#isProgressC2DomainBlocklistUpdate = this.#updateC2DomainBlocklist();\n await this.#isProgressC2DomainBlocklistUpdate;\n } finally {\n this.#isProgressC2DomainBlocklistUpdate = undefined;\n }\n }\n\n /**\n * Update the hotlist.\n *\n * If an update is in progress, no additional update will be made. Instead this will wait until\n * the in-progress update has finished.\n */\n async updateHotlist() {\n if (this.#inProgressHotlistUpdate) {\n await this.#inProgressHotlistUpdate;\n return;\n }\n\n try {\n this.#inProgressHotlistUpdate = this.#updateHotlist();\n await this.#inProgressHotlistUpdate;\n } finally {\n this.#inProgressHotlistUpdate = undefined;\n }\n }\n\n /**\n * Update the stalelist.\n *\n * If an update is in progress, no additional update will be made. Instead this will wait until\n * the in-progress update has finished.\n */\n async updateStalelist() {\n if (this.#inProgressStalelistUpdate) {\n await this.#inProgressStalelistUpdate;\n return;\n }\n\n try {\n this.#inProgressStalelistUpdate = this.#updateStalelist();\n await this.#inProgressStalelistUpdate;\n } finally {\n this.#inProgressStalelistUpdate = undefined;\n }\n }\n\n /**\n * Update the stalelist configuration.\n *\n * This should only be called from the `updateStalelist` function, which is a wrapper around\n * this function that prevents redundant configuration updates.\n */\n async #updateStalelist() {\n let stalelistResponse: DataResultWrapper<PhishingStalelist> | null = null;\n let hotlistDiffsResponse: DataResultWrapper<Hotlist> | null = null;\n let c2DomainBlocklistResponse: C2DomainBlocklistResponse | null = null;\n try {\n const stalelistPromise = this.#queryConfig<\n DataResultWrapper<PhishingStalelist>\n >(METAMASK_STALELIST_URL);\n\n const c2DomainBlocklistPromise =\n this.#queryConfig<C2DomainBlocklistResponse>(C2_DOMAIN_BLOCKLIST_URL);\n\n [stalelistResponse, c2DomainBlocklistResponse] = await Promise.all([\n stalelistPromise,\n c2DomainBlocklistPromise,\n ]);\n // Fetching hotlist diffs relies on having a lastUpdated timestamp to do `GET /v1/diffsSince/:timestamp`,\n // so it doesn't make sense to call if there is not a timestamp to begin with.\n if (stalelistResponse?.data && stalelistResponse.data.lastUpdated > 0) {\n hotlistDiffsResponse = await this.#queryConfig<\n DataResultWrapper<Hotlist>\n >(`${METAMASK_HOTLIST_DIFF_URL}/${stalelistResponse.data.lastUpdated}`);\n }\n } finally {\n // Set `stalelistLastFetched` and `hotlistLastFetched` even for failed requests to prevent server\n // from being overwhelmed with traffic after a network disruption.\n const timeNow = fetchTimeNow();\n this.update((draftState) => {\n draftState.stalelistLastFetched = timeNow;\n draftState.hotlistLastFetched = timeNow;\n draftState.c2DomainBlocklistLastFetched = timeNow;\n });\n }\n\n if (!stalelistResponse || !hotlistDiffsResponse) {\n return;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { eth_phishing_detect_config, ...partialState } =\n stalelistResponse.data;\n\n const metamaskListState: PhishingListState = {\n ...eth_phishing_detect_config,\n ...partialState,\n c2DomainBlocklist: c2DomainBlocklistResponse\n ? c2DomainBlocklistResponse.recentlyAdded\n : [],\n name: phishingListKeyNameMap.eth_phishing_detect_config,\n };\n\n const newMetaMaskListState: PhishingListState = applyDiffs(\n metamaskListState,\n hotlistDiffsResponse.data,\n ListKeys.EthPhishingDetectConfig,\n );\n\n this.update((draftState) => {\n draftState.phishingLists = [newMetaMaskListState];\n });\n this.updatePhishingDetector();\n }\n\n /**\n * Update the stalelist configuration.\n *\n * This should only be called from the `updateStalelist` function, which is a wrapper around\n * this function that prevents redundant configuration updates.\n */\n async #updateHotlist() {\n const lastDiffTimestamp = Math.max(\n ...this.state.phishingLists.map(({ lastUpdated }) => lastUpdated),\n );\n let hotlistResponse: DataResultWrapper<Hotlist> | null;\n\n try {\n hotlistResponse = await this.#queryConfig<DataResultWrapper<Hotlist>>(\n `${METAMASK_HOTLIST_DIFF_URL}/${lastDiffTimestamp}`,\n );\n } finally {\n // Set `hotlistLastFetched` even for failed requests to prevent server from being overwhelmed with\n // traffic after a network disruption.\n this.update((draftState) => {\n draftState.hotlistLastFetched = fetchTimeNow();\n });\n }\n\n if (!hotlistResponse?.data) {\n return;\n }\n const hotlist = hotlistResponse.data;\n const newPhishingLists = this.state.phishingLists.map((phishingList) => {\n const updatedList = applyDiffs(\n phishingList,\n hotlist,\n phishingListNameKeyMap[phishingList.name],\n [],\n [],\n );\n\n return updatedList;\n });\n\n this.update((draftState) => {\n draftState.phishingLists = newPhishingLists;\n });\n this.updatePhishingDetector();\n }\n\n /**\n * Update the C2 domain blocklist.\n *\n * This should only be called from the `updateC2DomainBlocklist` function, which is a wrapper around\n * this function that prevents redundant configuration updates.\n */\n async #updateC2DomainBlocklist() {\n let c2DomainBlocklistResponse: C2DomainBlocklistResponse | null = null;\n\n try {\n c2DomainBlocklistResponse =\n await this.#queryConfig<C2DomainBlocklistResponse>(\n `${C2_DOMAIN_BLOCKLIST_URL}?timestamp=${roundToNearestMinute(\n this.state.c2DomainBlocklistLastFetched,\n )}`,\n );\n } finally {\n // Set `c2DomainBlocklistLastFetched` even for failed requests to prevent server from being overwhelmed with\n // traffic after a network disruption.\n this.update((draftState) => {\n draftState.c2DomainBlocklistLastFetched = fetchTimeNow();\n });\n }\n\n if (!c2DomainBlocklistResponse) {\n return;\n }\n\n const recentlyAddedC2Domains = c2DomainBlocklistResponse.recentlyAdded;\n const recentlyRemovedC2Domains = c2DomainBlocklistResponse.recentlyRemoved;\n\n const newPhishingLists = this.state.phishingLists.map((phishingList) => {\n const updatedList = applyDiffs(\n phishingList,\n [],\n phishingListNameKeyMap[phishingList.name],\n recentlyAddedC2Domains,\n recentlyRemovedC2Domains,\n );\n\n return updatedList;\n });\n\n this.update((draftState) => {\n draftState.phishingLists = newPhishingLists;\n });\n this.updatePhishingDetector();\n }\n\n async #queryConfig<ResponseType>(\n input: RequestInfo,\n ): Promise<ResponseType | null> {\n const response = await safelyExecute(\n () => fetch(input, { cache: 'no-cache' }),\n true,\n );\n\n switch (response?.status) {\n case 200: {\n return await response.json();\n }\n\n default: {\n return null;\n }\n }\n }\n}\n\nexport default PhishingController;\n\nexport type { PhishingDetectorResult };\n","import { distance } from 'fastest-levenshtein';\n\nimport {\n PhishingDetectorResultType,\n type PhishingDetectorResult,\n} from './types';\nimport {\n domainPartsToDomain,\n domainPartsToFuzzyForm,\n domainToParts,\n getDefaultPhishingDetectorConfig,\n matchPartsAgainstList,\n processConfigs,\n sha256Hash,\n} from './utils';\n\nexport type LegacyPhishingDetectorList = {\n whitelist?: string[];\n blacklist?: string[];\n c2DomainBlocklist?: string[];\n} & FuzzyTolerance;\n\nexport type PhishingDetectorList = {\n allowlist?: string[];\n blocklist?: string[];\n c2DomainBlocklist?: string[];\n name?: string;\n version?: string | number;\n tolerance?: number;\n} & FuzzyTolerance;\n\nexport type FuzzyTolerance =\n | {\n tolerance?: number;\n fuzzylist: string[];\n }\n | {\n tolerance?: never;\n fuzzylist?: never;\n };\n\nexport type PhishingDetectorOptions =\n | LegacyPhishingDetectorList\n | PhishingDetectorList[];\n\nexport type PhishingDetectorConfiguration = {\n name?: string;\n version?: number | string;\n allowlist: string[][];\n blocklist: string[][];\n c2DomainBlocklist?: string[];\n fuzzylist: string[][];\n tolerance: number;\n};\n\nexport class PhishingDetector {\n #configs: PhishingDetectorConfiguration[];\n\n #legacyConfig: boolean;\n\n /**\n * Construct a phishing detector, which can check whether origins are known\n * to be malicious or similar to common phishing targets.\n *\n * A list of configurations is accepted. Each origin checked is processed\n * using each configuration in sequence, so the order defines which\n * configurations take precedence.\n *\n * @param opts - Phishing detection options\n */\n constructor(opts: PhishingDetectorOptions) {\n // recommended configuration\n if (Array.isArray(opts)) {\n this.#configs = processConfigs(opts);\n this.#legacyConfig = false;\n // legacy configuration\n } else {\n this.#configs = [\n getDefaultPhishingDetectorConfig({\n allowlist: opts.whitelist,\n blocklist: opts.blacklist,\n c2DomainBlocklist: opts.c2DomainBlocklist,\n fuzzylist: opts.fuzzylist,\n tolerance: opts.tolerance,\n }),\n ];\n this.#legacyConfig = true;\n }\n }\n\n /**\n * Check if a url is known to be malicious or similar to a common phishing\n * target. This will check the hostname and IPFS CID that is sometimes\n * located in the path.\n *\n * @param url - The url to check.\n * @returns The result of the check.\n */\n check(url: string): PhishingDetectorResult {\n const result = this.#check(url);\n\n if (this.#legacyConfig) {\n let legacyType = result.type;\n if (legacyType === PhishingDetectorResultType.Allowlist) {\n legacyType = PhishingDetectorResultType.Whitelist;\n } else if (legacyType === PhishingDetectorResultType.Blocklist) {\n legacyType = PhishingDetectorResultType.Blacklist;\n }\n return {\n match: result.match,\n result: result.result,\n type: legacyType,\n };\n }\n return result;\n }\n\n #check(url: string): PhishingDetectorResult {\n const ipfsCidMatch = url.match(ipfsCidRegex());\n\n // Check for IPFS CID related blocklist entries\n if (ipfsCidMatch !== null) {\n // there is a cID string somewhere\n // Determine if any of the entries are ipfs cids\n // Depending on the gateway, the CID is in the path OR a subdomain, so we do a regex match on it all\n const cID = ipfsCidMatch[0];\n for (const { blocklist, name, version } of this.#configs) {\n const blocklistMatch = blocklist\n .filter((entries) => entries.length === 1)\n .find((entries) => {\n return entries[0] === cID;\n });\n if (blocklistMatch) {\n return {\n name,\n match: cID,\n result: true,\n type: PhishingDetectorResultType.Blocklist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n }\n\n let domain;\n try {\n domain = new URL(url).hostname;\n } catch (error) {\n return {\n result: false,\n type: PhishingDetectorResultType.All,\n };\n }\n\n const fqdn = domain.endsWith('.') ? domain.slice(0, -1) : domain;\n\n const source = domainToParts(fqdn);\n\n for (const { allowlist, name, version } of this.#configs) {\n // if source matches allowlist hostname (or subdomain thereof), PASS\n const allowlistMatch = matchPartsAgainstList(source, allowlist);\n if (allowlistMatch) {\n const match = domainPartsToDomain(allowlistMatch);\n return {\n match,\n name,\n result: false,\n type: PhishingDetectorResultType.Allowlist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n\n for (const { blocklist, fuzzylist, name, tolerance, version } of this\n .#configs) {\n // if source matches blocklist hostname (or subdomain thereof), FAIL\n const blocklistMatch = matchPartsAgainstList(source, blocklist);\n if (blocklistMatch) {\n const match = domainPartsToDomain(blocklistMatch);\n return {\n match,\n name,\n result: true,\n type: PhishingDetectorResultType.Blocklist,\n version: version === undefined ? version : String(version),\n };\n }\n\n if (tolerance > 0) {\n // check if near-match of whitelist domain, FAIL\n let fuzzyForm = domainPartsToFuzzyForm(source);\n // strip www\n fuzzyForm = fuzzyForm.replace(/^www\\./u, '');\n // check against fuzzylist\n const levenshteinMatched = fuzzylist.find((targetParts) => {\n const fuzzyTarget = domainPartsToFuzzyForm(targetParts);\n const dist = distance(fuzzyForm, fuzzyTarget);\n return dist <= tolerance;\n });\n if (levenshteinMatched) {\n const match = domainPartsToDomain(levenshteinMatched);\n return {\n name,\n match,\n result: true,\n type: PhishingDetectorResultType.Fuzzy,\n version: version === undefined ? version : String(version),\n };\n }\n }\n }\n\n // matched nothing, PASS\n return { result: false, type: PhishingDetectorResultType.All };\n }\n\n /**\n * Checks if a URL is blocked against the hashed request blocklist.\n * This is done by hashing the URL's hostname and checking it against the hashed request blocklist.\n *\n *\n * @param urlString - The URL to check.\n * @returns An object indicating if the URL is blocked and relevant metadata.\n */\n isMaliciousC2Domain(urlString: string): PhishingDetectorResult {\n let hostname;\n try {\n hostname = new URL(urlString).hostname;\n } catch (error) {\n return {\n result: false,\n type: PhishingDetectorResultType.C2DomainBlocklist,\n };\n }\n\n const fqdn = hostname.endsWith('.') ? hostname.slice(0, -1) : hostname;\n\n const source = domainToParts(fqdn);\n\n for (const { allowlist, name, version } of this.#configs) {\n // if source matches allowlist hostname (or subdomain thereof), PASS\n const allowlistMatch = matchPartsAgainstList(source, allowlist);\n if (allowlistMatch) {\n const match = domainPartsToDomain(allowlistMatch);\n return {\n match,\n name,\n result: false,\n type: PhishingDetectorResultType.Allowlist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n\n for (const { c2DomainBlocklist, name, version } of this.#configs) {\n const hash = sha256Hash(hostname.toLowerCase());\n const blocked = c2DomainBlocklist?.includes(hash) ?? false;\n\n if (blocked) {\n return {\n name,\n result: true,\n type: PhishingDetectorResultType.C2DomainBlocklist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n // did not match, PASS\n return {\n result: false,\n type: PhishingDetectorResultType.C2DomainBlocklist,\n };\n }\n}\n\n/**\n * Runs a regex match to determine if a string is a IPFS CID\n * @returns Regex string for IPFS CID\n */\nfunction ipfsCidRegex() {\n // regex from https://stackoverflow.com/a/67176726\n const reg =\n 'Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,}';\n return new RegExp(reg, 'u');\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,cAAc;;;ACIvB,SAAS,sBAAsB;AAC/B,SAAS,qBAAqB;AAC9B,SAAS,eAAe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,EAAE;AAAA,EAC1B,SAAS,OAAO;AACd,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["ListKeys","ListNames"]}
|
|
@@ -417,7 +417,8 @@ var PhishingController = class extends _basecontroller.BaseController {
|
|
|
417
417
|
*/
|
|
418
418
|
test(origin) {
|
|
419
419
|
const punycodeOrigin = _.toASCII.call(void 0, origin);
|
|
420
|
-
|
|
420
|
+
const hostname = getHostnameFromUrl(punycodeOrigin);
|
|
421
|
+
if (this.state.whitelist.includes(hostname || punycodeOrigin)) {
|
|
421
422
|
return { result: false, type: "all" /* All */ };
|
|
422
423
|
}
|
|
423
424
|
return _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _detector).check(punycodeOrigin);
|
|
@@ -434,6 +435,10 @@ var PhishingController = class extends _basecontroller.BaseController {
|
|
|
434
435
|
*/
|
|
435
436
|
isBlockedRequest(origin) {
|
|
436
437
|
const punycodeOrigin = _.toASCII.call(void 0, origin);
|
|
438
|
+
const hostname = getHostnameFromUrl(punycodeOrigin);
|
|
439
|
+
if (this.state.whitelist.includes(hostname || punycodeOrigin)) {
|
|
440
|
+
return { result: false, type: "all" /* All */ };
|
|
441
|
+
}
|
|
437
442
|
return _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _detector).isMaliciousC2Domain(punycodeOrigin);
|
|
438
443
|
}
|
|
439
444
|
/**
|
|
@@ -443,12 +448,13 @@ var PhishingController = class extends _basecontroller.BaseController {
|
|
|
443
448
|
*/
|
|
444
449
|
bypass(origin) {
|
|
445
450
|
const punycodeOrigin = _.toASCII.call(void 0, origin);
|
|
451
|
+
const hostname = getHostnameFromUrl(punycodeOrigin);
|
|
446
452
|
const { whitelist } = this.state;
|
|
447
|
-
if (whitelist.includes(punycodeOrigin)) {
|
|
453
|
+
if (whitelist.includes(hostname || punycodeOrigin)) {
|
|
448
454
|
return;
|
|
449
455
|
}
|
|
450
456
|
this.update((draftState) => {
|
|
451
|
-
draftState.whitelist.push(punycodeOrigin);
|
|
457
|
+
draftState.whitelist.push(hostname || punycodeOrigin);
|
|
452
458
|
});
|
|
453
459
|
}
|
|
454
460
|
/**
|
|
@@ -761,6 +767,16 @@ var sha256Hash = (hostname) => {
|
|
|
761
767
|
const hashBuffer = _sha256.sha256.call(void 0, new TextEncoder().encode(hostname.toLowerCase()));
|
|
762
768
|
return _utils.bytesToHex.call(void 0, hashBuffer);
|
|
763
769
|
};
|
|
770
|
+
var getHostnameFromUrl = (url) => {
|
|
771
|
+
let hostname;
|
|
772
|
+
try {
|
|
773
|
+
hostname = new URL(url).hostname;
|
|
774
|
+
} catch (error) {
|
|
775
|
+
return null;
|
|
776
|
+
}
|
|
777
|
+
return hostname;
|
|
778
|
+
};
|
|
779
|
+
|
|
764
780
|
|
|
765
781
|
|
|
766
782
|
|
|
@@ -792,5 +808,5 @@ var sha256Hash = (hostname) => {
|
|
|
792
808
|
|
|
793
809
|
|
|
794
810
|
|
|
795
|
-
exports.fetchTimeNow = fetchTimeNow; exports.roundToNearestMinute = roundToNearestMinute; exports.applyDiffs = applyDiffs; exports.validateConfig = validateConfig; exports.domainToParts = domainToParts; exports.processDomainList = processDomainList; exports.getDefaultPhishingDetectorConfig = getDefaultPhishingDetectorConfig; exports.processConfigs = processConfigs; exports.domainPartsToDomain = domainPartsToDomain; exports.domainPartsToFuzzyForm = domainPartsToFuzzyForm; exports.matchPartsAgainstList = matchPartsAgainstList; exports.sha256Hash = sha256Hash; exports.PhishingDetector = PhishingDetector; exports.PHISHING_CONFIG_BASE_URL = PHISHING_CONFIG_BASE_URL; exports.METAMASK_STALELIST_FILE = METAMASK_STALELIST_FILE; exports.METAMASK_HOTLIST_DIFF_FILE = METAMASK_HOTLIST_DIFF_FILE; exports.CLIENT_SIDE_DETECION_BASE_URL = CLIENT_SIDE_DETECION_BASE_URL; exports.C2_DOMAIN_BLOCKLIST_ENDPOINT = C2_DOMAIN_BLOCKLIST_ENDPOINT; exports.C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL; exports.HOTLIST_REFRESH_INTERVAL = HOTLIST_REFRESH_INTERVAL; exports.STALELIST_REFRESH_INTERVAL = STALELIST_REFRESH_INTERVAL; exports.METAMASK_STALELIST_URL = METAMASK_STALELIST_URL; exports.METAMASK_HOTLIST_DIFF_URL = METAMASK_HOTLIST_DIFF_URL; exports.C2_DOMAIN_BLOCKLIST_URL = C2_DOMAIN_BLOCKLIST_URL; exports.ListKeys = ListKeys; exports.ListNames = ListNames; exports.phishingListKeyNameMap = phishingListKeyNameMap; exports.PhishingController = PhishingController; exports.PhishingController_default = PhishingController_default;
|
|
796
|
-
//# sourceMappingURL=chunk-
|
|
811
|
+
exports.fetchTimeNow = fetchTimeNow; exports.roundToNearestMinute = roundToNearestMinute; exports.applyDiffs = applyDiffs; exports.validateConfig = validateConfig; exports.domainToParts = domainToParts; exports.processDomainList = processDomainList; exports.getDefaultPhishingDetectorConfig = getDefaultPhishingDetectorConfig; exports.processConfigs = processConfigs; exports.domainPartsToDomain = domainPartsToDomain; exports.domainPartsToFuzzyForm = domainPartsToFuzzyForm; exports.matchPartsAgainstList = matchPartsAgainstList; exports.sha256Hash = sha256Hash; exports.getHostnameFromUrl = getHostnameFromUrl; exports.PhishingDetector = PhishingDetector; exports.PHISHING_CONFIG_BASE_URL = PHISHING_CONFIG_BASE_URL; exports.METAMASK_STALELIST_FILE = METAMASK_STALELIST_FILE; exports.METAMASK_HOTLIST_DIFF_FILE = METAMASK_HOTLIST_DIFF_FILE; exports.CLIENT_SIDE_DETECION_BASE_URL = CLIENT_SIDE_DETECION_BASE_URL; exports.C2_DOMAIN_BLOCKLIST_ENDPOINT = C2_DOMAIN_BLOCKLIST_ENDPOINT; exports.C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL; exports.HOTLIST_REFRESH_INTERVAL = HOTLIST_REFRESH_INTERVAL; exports.STALELIST_REFRESH_INTERVAL = STALELIST_REFRESH_INTERVAL; exports.METAMASK_STALELIST_URL = METAMASK_STALELIST_URL; exports.METAMASK_HOTLIST_DIFF_URL = METAMASK_HOTLIST_DIFF_URL; exports.C2_DOMAIN_BLOCKLIST_URL = C2_DOMAIN_BLOCKLIST_URL; exports.ListKeys = ListKeys; exports.ListNames = ListNames; exports.phishingListKeyNameMap = phishingListKeyNameMap; exports.PhishingController = PhishingController; exports.PhishingController_default = PhishingController_default;
|
|
812
|
+
//# sourceMappingURL=chunk-ZAOBCAQT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/PhishingController.ts","../src/PhishingDetector.ts"],"names":["ListKeys","ListNames"],"mappings":";;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,cAAc;;;ACIvB,SAAS,sBAAsB;AAC/B,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACPxB,SAAS,gBAAgB;AAAzB;AAuDO,IAAM,mBAAN,MAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAe5B,YAAY,MAA+B;AA+C3C;AA7DA;AAEA;AAcE,QAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,yBAAK,UAAW,eAAe,IAAI;AACnC,yBAAK,eAAgB;AAAA,IAEvB,OAAO;AACL,yBAAK,UAAW;AAAA,QACd,iCAAiC;AAAA,UAC/B,WAAW,KAAK;AAAA,UAChB,WAAW,KAAK;AAAA,UAChB,mBAAmB,KAAK;AAAA,UACxB,WAAW,KAAK;AAAA,UAChB,WAAW,KAAK;AAAA,QAClB,CAAC;AAAA,MACH;AACA,yBAAK,eAAgB;AAAA,IACvB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,KAAqC;AACzC,UAAM,SAAS,sBAAK,kBAAL,WAAY;AAE3B,QAAI,mBAAK,gBAAe;AACtB,UAAI,aAAa,OAAO;AACxB,U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AQO,IAAM,yBAAyB,CAAC,gBAA0B;AAC/D,SAAO,YAAY,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,GAAG;AAChD;AASO,IAAM,wBAAwB,CAAC,QAAkB,SAAqB;AAC3E,SAAO,KAAK,KAAK,CAAC,WAAW;AAE3B,QAAI,OAAO,SAAS,OAAO,QAAQ;AACjC,aAAO;AAAA,IACT;AAEA,WAAO,OAAO,MAAM,CAAC,MAAM,UAAU,OAAO,KAAK,MAAM,IAAI;AAAA,EAC7D,CAAC;AACH;AAQO,IAAM,aAAa,CAAC,aAA6B;AACtD,QAAM,aAAa,OAAO,IAAI,YAAY,EAAE,OAAO,SAAS,YAAY,CAAC,CAAC;AAC1E,SAAO,WAAW,UAAU;AAC9B;AAQO,IAAM,qBAAqB,CAAC,QAA+B;AAChE,MAAI;AACJ,MAAI;AACF,eAAW,IAAI,IAAI,GAAG,EAAE;AAAA,EAC1B,SAAS,OAAO;AACd,WAAO;AAAA,EACT;AACA,SAAO;AACT","sourcesContent":["import { bytesToHex } from '@noble/hashes/utils';\nimport { sha256 } from 'ethereum-cryptography/sha256';\n\nimport type { Hotlist, PhishingListState } from './PhishingController';\nimport { ListKeys, phishingListKeyNameMap } from './PhishingController';\nimport type {\n PhishingDetectorList,\n PhishingDetectorConfiguration,\n} from './PhishingDetector';\n\nconst DEFAULT_TOLERANCE = 3;\n\n/**\n * Fetches current epoch time in seconds.\n *\n * @returns the Date.now() time in seconds instead of miliseconds. backend files rely on timestamps in seconds since epoch.\n */\nexport const fetchTimeNow = (): number => Math.round(Date.now() / 1000);\n\n/**\n * Rounds a Unix timestamp down to the nearest minute.\n *\n * @param unixTimestamp - The Unix timestamp to be rounded.\n * @returns The rounded Unix timestamp.\n */\nexport function roundToNearestMinute(unixTimestamp: number): number {\n return Math.floor(unixTimestamp / 60) * 60;\n}\n\n/**\n * Split a string into two pieces, using the first period as the delimiter.\n *\n * @param stringToSplit - The string to split.\n * @returns An array of length two containing the beginning and end of the string.\n */\nconst splitStringByPeriod = <Start extends string, End extends string>(\n stringToSplit: `${Start}.${End}`,\n): [Start, End] => {\n const periodIndex = stringToSplit.indexOf('.');\n return [\n stringToSplit.slice(0, periodIndex) as Start,\n stringToSplit.slice(periodIndex + 1) as End,\n ];\n};\n\n/**\n * Determines which diffs are applicable to the listState, then applies those diffs.\n *\n * @param listState - the stalelist or the existing liststate that diffs will be applied to.\n * @param hotlistDiffs - the diffs to apply to the listState if valid.\n * @param listKey - the key associated with the input/output phishing list state.\n * @param recentlyAddedC2Domains - list of hashed C2 domains to add to the local c2 domain blocklist\n * @param recentlyRemovedC2Domains - list of hashed C2 domains to remove from the local c2 domain blocklist\n * @returns the new list state\n */\nexport const applyDiffs = (\n listState: PhishingListState,\n hotlistDiffs: Hotlist,\n listKey: ListKeys,\n recentlyAddedC2Domains: string[] = [],\n recentlyRemovedC2Domains: string[] = [],\n): PhishingListState => {\n // filter to remove diffs that were added before the lastUpdate time.\n // filter to remove diffs that aren't applicable to the specified list (by listKey).\n const diffsToApply = hotlistDiffs.filter(\n ({ timestamp, targetList }) =>\n timestamp > listState.lastUpdated &&\n splitStringByPeriod(targetList)[0] === listKey,\n );\n\n // the reason behind using latestDiffTimestamp as the lastUpdated time\n // is so that we can benefit server-side from memoization due to end client's\n // `GET /v1/diffSince/:timestamp` requests lining up with\n // our periodic updates (which create diffs at specific timestamps).\n let latestDiffTimestamp = listState.lastUpdated;\n\n const listSets = {\n allowlist: new Set(listState.allowlist),\n blocklist: new Set(listState.blocklist),\n fuzzylist: new Set(listState.fuzzylist),\n c2DomainBlocklist: new Set(listState.c2DomainBlocklist),\n };\n for (const { isRemoval, targetList, url, timestamp } of diffsToApply) {\n const targetListType = splitStringByPeriod(targetList)[1];\n if (timestamp > latestDiffTimestamp) {\n latestDiffTimestamp = timestamp;\n }\n if (isRemoval) {\n listSets[targetListType].delete(url);\n } else {\n listSets[targetListType].add(url);\n }\n }\n\n if (listKey === ListKeys.EthPhishingDetectConfig) {\n for (const hash of recentlyAddedC2Domains) {\n listSets.c2DomainBlocklist.add(hash);\n }\n for (const hash of recentlyRemovedC2Domains) {\n listSets.c2DomainBlocklist.delete(hash);\n }\n }\n\n return {\n c2DomainBlocklist: Array.from(listSets.c2DomainBlocklist),\n allowlist: Array.from(listSets.allowlist),\n blocklist: Array.from(listSets.blocklist),\n fuzzylist: Array.from(listSets.fuzzylist),\n version: listState.version,\n name: phishingListKeyNameMap[listKey],\n tolerance: listState.tolerance,\n lastUpdated: latestDiffTimestamp,\n };\n};\n\n/**\n * Validates the configuration object for the phishing detector.\n *\n * @param config - the configuration object to validate.\n * @throws an error if the configuration is invalid.\n */\nexport function validateConfig(\n config: unknown,\n): asserts config is PhishingListState {\n if (config === null || typeof config !== 'object') {\n throw new Error('Invalid config');\n }\n\n if ('tolerance' in config && !('fuzzylist' in config)) {\n throw new Error('Fuzzylist tolerance provided without fuzzylist');\n }\n\n if (\n 'name' in config &&\n (typeof config.name !== 'string' || config.name === '')\n ) {\n throw new Error(\"Invalid config parameter: 'name'\");\n }\n\n if (\n 'version' in config &&\n (!['number', 'string'].includes(typeof config.version) ||\n config.version === '')\n ) {\n throw new Error(\"Invalid config parameter: 'version'\");\n }\n}\n\n/**\n * Converts a domain string to a list of domain parts.\n *\n * @param domain - the domain string to convert.\n * @returns the list of domain parts.\n */\nexport const domainToParts = (domain: string) => {\n try {\n return domain.split('.').reverse();\n } catch (e) {\n throw new Error(JSON.stringify(domain));\n }\n};\n\n/**\n * Converts a list of domain strings to a list of domain parts.\n *\n * @param list - the list of domain strings to convert.\n * @returns the list of domain parts.\n */\nexport const processDomainList = (list: string[]) => {\n return list.map(domainToParts);\n};\n\n/**\n * Gets the default phishing detector configuration.\n *\n * @param override - the optional override for the configuration.\n * @param override.allowlist - the optional allowlist to override.\n * @param override.blocklist - the optional blocklist to override.\n * @param override.c2DomainBlocklist - the optional c2DomainBlocklist to override.\n * @param override.fuzzylist - the optional fuzzylist to override.\n * @param override.tolerance - the optional tolerance to override.\n * @returns the default phishing detector configuration.\n */\nexport const getDefaultPhishingDetectorConfig = ({\n allowlist = [],\n blocklist = [],\n fuzzylist = [],\n tolerance = DEFAULT_TOLERANCE,\n}: {\n allowlist?: string[];\n blocklist?: string[];\n c2DomainBlocklist?: string[];\n fuzzylist?: string[];\n tolerance?: number;\n}): PhishingDetectorConfiguration => ({\n allowlist: processDomainList(allowlist),\n blocklist: processDomainList(blocklist),\n fuzzylist: processDomainList(fuzzylist),\n tolerance,\n});\n\n/**\n * Processes the configurations for the phishing detector.\n *\n * @param configs - the configurations to process.\n * @returns the processed configurations.\n */\nexport const processConfigs = (configs: PhishingDetectorList[] = []) => {\n return configs.map((config: PhishingDetectorList) => {\n validateConfig(config);\n return { ...config, ...getDefaultPhishingDetectorConfig(config) };\n });\n};\n\n/**\n * Converts a list of domain parts to a domain string.\n *\n * @param domainParts - the list of domain parts.\n * @returns the domain string.\n */\nexport const domainPartsToDomain = (domainParts: string[]) => {\n return domainParts.slice().reverse().join('.');\n};\n\n/**\n * Converts a list of domain parts to a fuzzy form.\n *\n * @param domainParts - the list of domain parts.\n * @returns the fuzzy form of the domain.\n */\nexport const domainPartsToFuzzyForm = (domainParts: string[]) => {\n return domainParts.slice(1).reverse().join('.');\n};\n\n/**\n * Matches the target parts, ignoring extra subdomains on source.\n *\n * @param source - the source domain parts.\n * @param list - the list of domain parts to match against.\n * @returns the parts for the first found matching entry.\n */\nexport const matchPartsAgainstList = (source: string[], list: string[][]) => {\n return list.find((target) => {\n // target domain has more parts than source, fail\n if (target.length > source.length) {\n return false;\n }\n // source matches target or (is deeper subdomain)\n return target.every((part, index) => source[index] === part);\n });\n};\n\n/**\n * Generate the SHA-256 hash of a hostname.\n *\n * @param hostname - The hostname to hash.\n * @returns The SHA-256 hash of the hostname.\n */\nexport const sha256Hash = (hostname: string): string => {\n const hashBuffer = sha256(new TextEncoder().encode(hostname.toLowerCase()));\n return bytesToHex(hashBuffer);\n};\n\n/**\n * Extracts the hostname from a URL.\n *\n * @param url - The URL to extract the hostname from.\n * @returns The hostname extracted from the URL, or null if the URL is invalid.\n */\nexport const getHostnameFromUrl = (url: string): string | null => {\n let hostname;\n try {\n hostname = new URL(url).hostname;\n } catch (error) {\n return null;\n }\n return hostname;\n};\n","import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport { toASCII } from 'punycode/';\n\nimport { PhishingDetector } from './PhishingDetector';\nimport {\n PhishingDetectorResultType,\n type PhishingDetectorResult,\n} from './types';\nimport {\n applyDiffs,\n fetchTimeNow,\n getHostnameFromUrl,\n roundToNearestMinute,\n} from './utils';\n\nexport const PHISHING_CONFIG_BASE_URL =\n 'https://phishing-detection.api.cx.metamask.io';\nexport const METAMASK_STALELIST_FILE = '/v1/stalelist';\nexport const METAMASK_HOTLIST_DIFF_FILE = '/v1/diffsSince';\n\nexport const CLIENT_SIDE_DETECION_BASE_URL =\n 'https://client-side-detection.api.cx.metamask.io';\nexport const C2_DOMAIN_BLOCKLIST_ENDPOINT = '/v1/request-blocklist';\n\nexport const C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = 15 * 60; // 15 mins in seconds\nexport const HOTLIST_REFRESH_INTERVAL = 5 * 60; // 5 mins in seconds\nexport const STALELIST_REFRESH_INTERVAL = 30 * 24 * 60 * 60; // 30 days in seconds\n\nexport const METAMASK_STALELIST_URL = `${PHISHING_CONFIG_BASE_URL}${METAMASK_STALELIST_FILE}`;\nexport const METAMASK_HOTLIST_DIFF_URL = `${PHISHING_CONFIG_BASE_URL}${METAMASK_HOTLIST_DIFF_FILE}`;\nexport const C2_DOMAIN_BLOCKLIST_URL = `${CLIENT_SIDE_DETECION_BASE_URL}${C2_DOMAIN_BLOCKLIST_ENDPOINT}`;\n\n/**\n * @type ListTypes\n *\n * Type outlining the types of lists provided by aggregating different source lists\n */\nexport type ListTypes =\n | 'fuzzylist'\n | 'blocklist'\n | 'allowlist'\n | 'c2DomainBlocklist';\n\n/**\n * @type EthPhishingResponse\n *\n * Configuration response from the eth-phishing-detect package\n * consisting of approved and unapproved website origins\n * @property blacklist - List of unapproved origins\n * @property fuzzylist - List of fuzzy-matched unapproved origins\n * @property tolerance - Fuzzy match tolerance level\n * @property version - Version number of this configuration\n * @property whitelist - List of approved origins\n */\nexport type EthPhishingResponse = {\n blacklist: string[];\n fuzzylist: string[];\n tolerance: number;\n version: number;\n whitelist: string[];\n};\n\n/**\n * @type C2DomainBlocklistResponse\n *\n * Response for blocklist update requests\n * @property recentlyAdded - List of c2 domains recently added to the blocklist\n * @property recentlyRemoved - List of c2 domains recently removed from the blocklist\n * @property lastFetchedAt - Timestamp of the last fetch request\n */\nexport type C2DomainBlocklistResponse = {\n recentlyAdded: string[];\n recentlyRemoved: string[];\n lastFetchedAt: string;\n};\n\n/**\n * @type PhishingStalelist\n *\n * type defining expected type of the stalelist.json file.\n * @property eth_phishing_detect_config - Stale list sourced from eth-phishing-detect's config.json.\n * @property tolerance - Fuzzy match tolerance level\n * @property lastUpdated - Timestamp of last update.\n * @property version - Stalelist data structure iteration.\n */\nexport type PhishingStalelist = {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n eth_phishing_detect_config: Record<ListTypes, string[]>;\n tolerance: number;\n version: number;\n lastUpdated: number;\n};\n\n/**\n * @type PhishingListState\n *\n * type defining the persisted list state. This is the persisted state that is updated frequently with `this.maybeUpdateState()`.\n * @property allowlist - List of approved origins (legacy naming \"whitelist\")\n * @property blocklist - List of unapproved origins (legacy naming \"blacklist\")\n * @property c2DomainBlocklist - List of hashed hostnames that C2 requests are blocked against.\n * @property fuzzylist - List of fuzzy-matched unapproved origins\n * @property tolerance - Fuzzy match tolerance level\n * @property lastUpdated - Timestamp of last update.\n * @property version - Version of the phishing list state.\n * @property name - Name of the list. Used for attribution.\n */\nexport type PhishingListState = {\n allowlist: string[];\n blocklist: string[];\n c2DomainBlocklist: string[];\n fuzzylist: string[];\n tolerance: number;\n version: number;\n lastUpdated: number;\n name: ListNames;\n};\n\n/**\n * @type HotlistDiff\n *\n * type defining the expected type of the diffs in hotlist.json file.\n * @property url - Url of the diff entry.\n * @property timestamp - Timestamp at which the diff was identified.\n * @property targetList - The list name where the diff was identified.\n * @property isRemoval - Was the diff identified a removal type.\n */\nexport type HotlistDiff = {\n url: string;\n timestamp: number;\n targetList: `${ListKeys}.${ListTypes}`;\n isRemoval?: boolean;\n};\n\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type DataResultWrapper<T> = {\n data: T;\n};\n\n/**\n * @type Hotlist\n *\n * Type defining expected hotlist.json file.\n * @property url - Url of the diff entry.\n * @property timestamp - Timestamp at which the diff was identified.\n * @property targetList - The list name where the diff was identified.\n * @property isRemoval - Was the diff identified a removal type.\n */\nexport type Hotlist = HotlistDiff[];\n\n/**\n * Enum containing upstream data provider source list keys.\n * These are the keys denoting lists consumed by the upstream data provider.\n */\nexport enum ListKeys {\n EthPhishingDetectConfig = 'eth_phishing_detect_config',\n}\n\n/**\n * Enum containing downstream client attribution names.\n */\nexport enum ListNames {\n MetaMask = 'MetaMask',\n}\n\n/**\n * Maps from downstream client attribution name\n * to list key sourced from upstream data provider.\n */\nconst phishingListNameKeyMap = {\n [ListNames.MetaMask]: ListKeys.EthPhishingDetectConfig,\n};\n\n/**\n * Maps from list key sourced from upstream data\n * provider to downstream client attribution name.\n */\nexport const phishingListKeyNameMap = {\n [ListKeys.EthPhishingDetectConfig]: ListNames.MetaMask,\n};\n\nconst controllerName = 'PhishingController';\n\nconst metadata = {\n phishingLists: { persist: true, anonymous: false },\n whitelist: { persist: true, anonymous: false },\n hotlistLastFetched: { persist: true, anonymous: false },\n stalelistLastFetched: { persist: true, anonymous: false },\n c2DomainBlocklistLastFetched: { persist: true, anonymous: false },\n};\n\n/**\n * Get a default empty state for the controller.\n * @returns The default empty state.\n */\nconst getDefaultState = (): PhishingControllerState => {\n return {\n phishingLists: [],\n whitelist: [],\n hotlistLastFetched: 0,\n stalelistLastFetched: 0,\n c2DomainBlocklistLastFetched: 0,\n };\n};\n\n/**\n * @type PhishingControllerState\n *\n * Phishing controller state\n * @property phishing - eth-phishing-detect configuration\n * @property whitelist - array of temporarily-approved origins\n */\nexport type PhishingControllerState = {\n phishingLists: PhishingListState[];\n whitelist: string[];\n hotlistLastFetched: number;\n stalelistLastFetched: number;\n c2DomainBlocklistLastFetched: number;\n};\n\n/**\n * @type PhishingControllerOptions\n *\n * Phishing controller options\n * @property stalelistRefreshInterval - Polling interval used to fetch stale list.\n * @property hotlistRefreshInterval - Polling interval used to fetch hotlist diff list.\n * @property c2DomainBlocklistRefreshInterval - Polling interval used to fetch c2 domain blocklist.\n */\nexport type PhishingControllerOptions = {\n stalelistRefreshInterval?: number;\n hotlistRefreshInterval?: number;\n c2DomainBlocklistRefreshInterval?: number;\n messenger: PhishingControllerMessenger;\n state?: Partial<PhishingControllerState>;\n};\n\nexport type MaybeUpdateState = {\n type: `${typeof controllerName}:maybeUpdateState`;\n handler: PhishingController['maybeUpdateState'];\n};\n\nexport type TestOrigin = {\n type: `${typeof controllerName}:testOrigin`;\n handler: PhishingController['test'];\n};\n\nexport type PhishingControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n PhishingControllerState\n>;\n\nexport type PhishingControllerActions =\n | PhishingControllerGetStateAction\n | MaybeUpdateState\n | TestOrigin;\n\nexport type PhishingControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n PhishingControllerState\n>;\n\nexport type PhishingControllerEvents = PhishingControllerStateChangeEvent;\n\nexport type PhishingControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n PhishingControllerActions,\n PhishingControllerEvents,\n never,\n never\n>;\n\n/**\n * Controller that manages community-maintained lists of approved and unapproved website origins.\n */\nexport class PhishingController extends BaseController<\n typeof controllerName,\n PhishingControllerState,\n PhishingControllerMessenger\n> {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #detector: any;\n\n #stalelistRefreshInterval: number;\n\n #hotlistRefreshInterval: number;\n\n #c2DomainBlocklistRefreshInterval: number;\n\n #inProgressHotlistUpdate?: Promise<void>;\n\n #inProgressStalelistUpdate?: Promise<void>;\n\n #isProgressC2DomainBlocklistUpdate?: Promise<void>;\n\n /**\n * Construct a Phishing Controller.\n *\n * @param config - Initial options used to configure this controller.\n * @param config.stalelistRefreshInterval - Polling interval used to fetch stale list.\n * @param config.hotlistRefreshInterval - Polling interval used to fetch hotlist diff list.\n * @param config.c2DomainBlocklistRefreshInterval - Polling interval used to fetch c2 domain blocklist.\n * @param config.messenger - The controller restricted messenger.\n * @param config.state - Initial state to set on this controller.\n */\n constructor({\n stalelistRefreshInterval = STALELIST_REFRESH_INTERVAL,\n hotlistRefreshInterval = HOTLIST_REFRESH_INTERVAL,\n c2DomainBlocklistRefreshInterval = C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL,\n messenger,\n state = {},\n }: PhishingControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultState(),\n ...state,\n },\n });\n\n this.#stalelistRefreshInterval = stalelistRefreshInterval;\n this.#hotlistRefreshInterval = hotlistRefreshInterval;\n this.#c2DomainBlocklistRefreshInterval = c2DomainBlocklistRefreshInterval;\n this.#registerMessageHandlers();\n\n this.updatePhishingDetector();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:maybeUpdateState` as const,\n this.maybeUpdateState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:testOrigin` as const,\n this.test.bind(this),\n );\n }\n\n /**\n * Updates this.detector with an instance of PhishingDetector using the current state.\n */\n updatePhishingDetector() {\n this.#detector = new PhishingDetector(this.state.phishingLists);\n }\n\n /**\n * Set the interval at which the stale phishing list will be refetched.\n * Fetching will only occur on the next call to test/bypass.\n * For immediate update to the phishing list, call {@link updateStalelist} directly.\n *\n * @param interval - the new interval, in ms.\n */\n setStalelistRefreshInterval(interval: number) {\n this.#stalelistRefreshInterval = interval;\n }\n\n /**\n * Set the interval at which the hot list will be refetched.\n * Fetching will only occur on the next call to test/bypass.\n * For immediate update to the phishing list, call {@link updateHotlist} directly.\n *\n * @param interval - the new interval, in ms.\n */\n setHotlistRefreshInterval(interval: number) {\n this.#hotlistRefreshInterval = interval;\n }\n\n /**\n * Set the interval at which the C2 domain blocklist will be refetched.\n * Fetching will only occur on the next call to test/bypass.\n * For immediate update to the phishing list, call {@link updateHotlist} directly.\n *\n * @param interval - the new interval, in ms.\n */\n setC2DomainBlocklistRefreshInterval(interval: number) {\n this.#c2DomainBlocklistRefreshInterval = interval;\n }\n\n /**\n * Determine if an update to the stalelist configuration is needed.\n *\n * @returns Whether an update is needed\n */\n isStalelistOutOfDate() {\n return (\n fetchTimeNow() - this.state.stalelistLastFetched >=\n this.#stalelistRefreshInterval\n );\n }\n\n /**\n * Determine if an update to the hotlist configuration is needed.\n *\n * @returns Whether an update is needed\n */\n isHotlistOutOfDate() {\n return (\n fetchTimeNow() - this.state.hotlistLastFetched >=\n this.#hotlistRefreshInterval\n );\n }\n\n /**\n * Determine if an update to the C2 domain blocklist is needed.\n *\n * @returns Whether an update is needed\n */\n isC2DomainBlocklistOutOfDate() {\n return (\n fetchTimeNow() - this.state.c2DomainBlocklistLastFetched >=\n this.#c2DomainBlocklistRefreshInterval\n );\n }\n\n /**\n * Conditionally update the phishing configuration.\n *\n * If the stalelist configuration is out of date, this function will call `updateStalelist`\n * to update the configuration. This will automatically grab the hotlist,\n * so it isn't necessary to continue on to download the hotlist and the c2 domain blocklist.\n *\n */\n async maybeUpdateState() {\n const staleListOutOfDate = this.isStalelistOutOfDate();\n if (staleListOutOfDate) {\n await this.updateStalelist();\n return;\n }\n const hotlistOutOfDate = this.isHotlistOutOfDate();\n if (hotlistOutOfDate) {\n await this.updateHotlist();\n }\n const c2DomainBlocklistOutOfDate = this.isC2DomainBlocklistOutOfDate();\n if (c2DomainBlocklistOutOfDate) {\n await this.updateC2DomainBlocklist();\n }\n }\n\n /**\n * Determines if a given origin is unapproved.\n *\n * It is strongly recommended that you call {@link maybeUpdateState} before calling this,\n * to check whether the phishing configuration is up-to-date. It will be updated if necessary\n * by calling {@link updateStalelist} or {@link updateHotlist}.\n *\n * @param origin - Domain origin of a website.\n * @returns Whether the origin is an unapproved origin.\n */\n test(origin: string): PhishingDetectorResult {\n const punycodeOrigin = toASCII(origin);\n const hostname = getHostnameFromUrl(punycodeOrigin);\n if (this.state.whitelist.includes(hostname || punycodeOrigin)) {\n return { result: false, type: PhishingDetectorResultType.All }; // Same as whitelisted match returned by detector.check(...).\n }\n return this.#detector.check(punycodeOrigin);\n }\n\n /**\n * Checks if a request URL's domain is blocked against the request blocklist.\n *\n * This method is used to determine if a specific request URL is associated with a malicious\n * command and control (C2) domain. The URL's hostname is hashed and checked against a configured\n * blocklist of known malicious domains.\n *\n * @param origin - The full request URL to be checked.\n * @returns An object indicating whether the URL's domain is blocked and relevant metadata.\n */\n isBlockedRequest(origin: string): PhishingDetectorResult {\n const punycodeOrigin = toASCII(origin);\n const hostname = getHostnameFromUrl(punycodeOrigin);\n if (this.state.whitelist.includes(hostname || punycodeOrigin)) {\n return { result: false, type: PhishingDetectorResultType.All }; // Same as whitelisted match returned by detector.check(...).\n }\n return this.#detector.isMaliciousC2Domain(punycodeOrigin);\n }\n\n /**\n * Temporarily marks a given origin as approved.\n *\n * @param origin - The origin to mark as approved.\n */\n bypass(origin: string) {\n const punycodeOrigin = toASCII(origin);\n const hostname = getHostnameFromUrl(punycodeOrigin);\n const { whitelist } = this.state;\n if (whitelist.includes(hostname || punycodeOrigin)) {\n return;\n }\n this.update((draftState) => {\n draftState.whitelist.push(hostname || punycodeOrigin);\n });\n }\n\n /**\n * Update the C2 domain blocklist.\n *\n * If an update is in progress, no additional update will be made. Instead this will wait until\n * the in-progress update has finished.\n */\n async updateC2DomainBlocklist() {\n if (this.#isProgressC2DomainBlocklistUpdate) {\n await this.#isProgressC2DomainBlocklistUpdate;\n return;\n }\n\n try {\n this.#isProgressC2DomainBlocklistUpdate = this.#updateC2DomainBlocklist();\n await this.#isProgressC2DomainBlocklistUpdate;\n } finally {\n this.#isProgressC2DomainBlocklistUpdate = undefined;\n }\n }\n\n /**\n * Update the hotlist.\n *\n * If an update is in progress, no additional update will be made. Instead this will wait until\n * the in-progress update has finished.\n */\n async updateHotlist() {\n if (this.#inProgressHotlistUpdate) {\n await this.#inProgressHotlistUpdate;\n return;\n }\n\n try {\n this.#inProgressHotlistUpdate = this.#updateHotlist();\n await this.#inProgressHotlistUpdate;\n } finally {\n this.#inProgressHotlistUpdate = undefined;\n }\n }\n\n /**\n * Update the stalelist.\n *\n * If an update is in progress, no additional update will be made. Instead this will wait until\n * the in-progress update has finished.\n */\n async updateStalelist() {\n if (this.#inProgressStalelistUpdate) {\n await this.#inProgressStalelistUpdate;\n return;\n }\n\n try {\n this.#inProgressStalelistUpdate = this.#updateStalelist();\n await this.#inProgressStalelistUpdate;\n } finally {\n this.#inProgressStalelistUpdate = undefined;\n }\n }\n\n /**\n * Update the stalelist configuration.\n *\n * This should only be called from the `updateStalelist` function, which is a wrapper around\n * this function that prevents redundant configuration updates.\n */\n async #updateStalelist() {\n let stalelistResponse: DataResultWrapper<PhishingStalelist> | null = null;\n let hotlistDiffsResponse: DataResultWrapper<Hotlist> | null = null;\n let c2DomainBlocklistResponse: C2DomainBlocklistResponse | null = null;\n try {\n const stalelistPromise = this.#queryConfig<\n DataResultWrapper<PhishingStalelist>\n >(METAMASK_STALELIST_URL);\n\n const c2DomainBlocklistPromise =\n this.#queryConfig<C2DomainBlocklistResponse>(C2_DOMAIN_BLOCKLIST_URL);\n\n [stalelistResponse, c2DomainBlocklistResponse] = await Promise.all([\n stalelistPromise,\n c2DomainBlocklistPromise,\n ]);\n // Fetching hotlist diffs relies on having a lastUpdated timestamp to do `GET /v1/diffsSince/:timestamp`,\n // so it doesn't make sense to call if there is not a timestamp to begin with.\n if (stalelistResponse?.data && stalelistResponse.data.lastUpdated > 0) {\n hotlistDiffsResponse = await this.#queryConfig<\n DataResultWrapper<Hotlist>\n >(`${METAMASK_HOTLIST_DIFF_URL}/${stalelistResponse.data.lastUpdated}`);\n }\n } finally {\n // Set `stalelistLastFetched` and `hotlistLastFetched` even for failed requests to prevent server\n // from being overwhelmed with traffic after a network disruption.\n const timeNow = fetchTimeNow();\n this.update((draftState) => {\n draftState.stalelistLastFetched = timeNow;\n draftState.hotlistLastFetched = timeNow;\n draftState.c2DomainBlocklistLastFetched = timeNow;\n });\n }\n\n if (!stalelistResponse || !hotlistDiffsResponse) {\n return;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { eth_phishing_detect_config, ...partialState } =\n stalelistResponse.data;\n\n const metamaskListState: PhishingListState = {\n ...eth_phishing_detect_config,\n ...partialState,\n c2DomainBlocklist: c2DomainBlocklistResponse\n ? c2DomainBlocklistResponse.recentlyAdded\n : [],\n name: phishingListKeyNameMap.eth_phishing_detect_config,\n };\n\n const newMetaMaskListState: PhishingListState = applyDiffs(\n metamaskListState,\n hotlistDiffsResponse.data,\n ListKeys.EthPhishingDetectConfig,\n );\n\n this.update((draftState) => {\n draftState.phishingLists = [newMetaMaskListState];\n });\n this.updatePhishingDetector();\n }\n\n /**\n * Update the stalelist configuration.\n *\n * This should only be called from the `updateStalelist` function, which is a wrapper around\n * this function that prevents redundant configuration updates.\n */\n async #updateHotlist() {\n const lastDiffTimestamp = Math.max(\n ...this.state.phishingLists.map(({ lastUpdated }) => lastUpdated),\n );\n let hotlistResponse: DataResultWrapper<Hotlist> | null;\n\n try {\n hotlistResponse = await this.#queryConfig<DataResultWrapper<Hotlist>>(\n `${METAMASK_HOTLIST_DIFF_URL}/${lastDiffTimestamp}`,\n );\n } finally {\n // Set `hotlistLastFetched` even for failed requests to prevent server from being overwhelmed with\n // traffic after a network disruption.\n this.update((draftState) => {\n draftState.hotlistLastFetched = fetchTimeNow();\n });\n }\n\n if (!hotlistResponse?.data) {\n return;\n }\n const hotlist = hotlistResponse.data;\n const newPhishingLists = this.state.phishingLists.map((phishingList) => {\n const updatedList = applyDiffs(\n phishingList,\n hotlist,\n phishingListNameKeyMap[phishingList.name],\n [],\n [],\n );\n\n return updatedList;\n });\n\n this.update((draftState) => {\n draftState.phishingLists = newPhishingLists;\n });\n this.updatePhishingDetector();\n }\n\n /**\n * Update the C2 domain blocklist.\n *\n * This should only be called from the `updateC2DomainBlocklist` function, which is a wrapper around\n * this function that prevents redundant configuration updates.\n */\n async #updateC2DomainBlocklist() {\n let c2DomainBlocklistResponse: C2DomainBlocklistResponse | null = null;\n\n try {\n c2DomainBlocklistResponse =\n await this.#queryConfig<C2DomainBlocklistResponse>(\n `${C2_DOMAIN_BLOCKLIST_URL}?timestamp=${roundToNearestMinute(\n this.state.c2DomainBlocklistLastFetched,\n )}`,\n );\n } finally {\n // Set `c2DomainBlocklistLastFetched` even for failed requests to prevent server from being overwhelmed with\n // traffic after a network disruption.\n this.update((draftState) => {\n draftState.c2DomainBlocklistLastFetched = fetchTimeNow();\n });\n }\n\n if (!c2DomainBlocklistResponse) {\n return;\n }\n\n const recentlyAddedC2Domains = c2DomainBlocklistResponse.recentlyAdded;\n const recentlyRemovedC2Domains = c2DomainBlocklistResponse.recentlyRemoved;\n\n const newPhishingLists = this.state.phishingLists.map((phishingList) => {\n const updatedList = applyDiffs(\n phishingList,\n [],\n phishingListNameKeyMap[phishingList.name],\n recentlyAddedC2Domains,\n recentlyRemovedC2Domains,\n );\n\n return updatedList;\n });\n\n this.update((draftState) => {\n draftState.phishingLists = newPhishingLists;\n });\n this.updatePhishingDetector();\n }\n\n async #queryConfig<ResponseType>(\n input: RequestInfo,\n ): Promise<ResponseType | null> {\n const response = await safelyExecute(\n () => fetch(input, { cache: 'no-cache' }),\n true,\n );\n\n switch (response?.status) {\n case 200: {\n return await response.json();\n }\n\n default: {\n return null;\n }\n }\n }\n}\n\nexport default PhishingController;\n\nexport type { PhishingDetectorResult };\n","import { distance } from 'fastest-levenshtein';\n\nimport {\n PhishingDetectorResultType,\n type PhishingDetectorResult,\n} from './types';\nimport {\n domainPartsToDomain,\n domainPartsToFuzzyForm,\n domainToParts,\n getDefaultPhishingDetectorConfig,\n matchPartsAgainstList,\n processConfigs,\n sha256Hash,\n} from './utils';\n\nexport type LegacyPhishingDetectorList = {\n whitelist?: string[];\n blacklist?: string[];\n c2DomainBlocklist?: string[];\n} & FuzzyTolerance;\n\nexport type PhishingDetectorList = {\n allowlist?: string[];\n blocklist?: string[];\n c2DomainBlocklist?: string[];\n name?: string;\n version?: string | number;\n tolerance?: number;\n} & FuzzyTolerance;\n\nexport type FuzzyTolerance =\n | {\n tolerance?: number;\n fuzzylist: string[];\n }\n | {\n tolerance?: never;\n fuzzylist?: never;\n };\n\nexport type PhishingDetectorOptions =\n | LegacyPhishingDetectorList\n | PhishingDetectorList[];\n\nexport type PhishingDetectorConfiguration = {\n name?: string;\n version?: number | string;\n allowlist: string[][];\n blocklist: string[][];\n c2DomainBlocklist?: string[];\n fuzzylist: string[][];\n tolerance: number;\n};\n\nexport class PhishingDetector {\n #configs: PhishingDetectorConfiguration[];\n\n #legacyConfig: boolean;\n\n /**\n * Construct a phishing detector, which can check whether origins are known\n * to be malicious or similar to common phishing targets.\n *\n * A list of configurations is accepted. Each origin checked is processed\n * using each configuration in sequence, so the order defines which\n * configurations take precedence.\n *\n * @param opts - Phishing detection options\n */\n constructor(opts: PhishingDetectorOptions) {\n // recommended configuration\n if (Array.isArray(opts)) {\n this.#configs = processConfigs(opts);\n this.#legacyConfig = false;\n // legacy configuration\n } else {\n this.#configs = [\n getDefaultPhishingDetectorConfig({\n allowlist: opts.whitelist,\n blocklist: opts.blacklist,\n c2DomainBlocklist: opts.c2DomainBlocklist,\n fuzzylist: opts.fuzzylist,\n tolerance: opts.tolerance,\n }),\n ];\n this.#legacyConfig = true;\n }\n }\n\n /**\n * Check if a url is known to be malicious or similar to a common phishing\n * target. This will check the hostname and IPFS CID that is sometimes\n * located in the path.\n *\n * @param url - The url to check.\n * @returns The result of the check.\n */\n check(url: string): PhishingDetectorResult {\n const result = this.#check(url);\n\n if (this.#legacyConfig) {\n let legacyType = result.type;\n if (legacyType === PhishingDetectorResultType.Allowlist) {\n legacyType = PhishingDetectorResultType.Whitelist;\n } else if (legacyType === PhishingDetectorResultType.Blocklist) {\n legacyType = PhishingDetectorResultType.Blacklist;\n }\n return {\n match: result.match,\n result: result.result,\n type: legacyType,\n };\n }\n return result;\n }\n\n #check(url: string): PhishingDetectorResult {\n const ipfsCidMatch = url.match(ipfsCidRegex());\n\n // Check for IPFS CID related blocklist entries\n if (ipfsCidMatch !== null) {\n // there is a cID string somewhere\n // Determine if any of the entries are ipfs cids\n // Depending on the gateway, the CID is in the path OR a subdomain, so we do a regex match on it all\n const cID = ipfsCidMatch[0];\n for (const { blocklist, name, version } of this.#configs) {\n const blocklistMatch = blocklist\n .filter((entries) => entries.length === 1)\n .find((entries) => {\n return entries[0] === cID;\n });\n if (blocklistMatch) {\n return {\n name,\n match: cID,\n result: true,\n type: PhishingDetectorResultType.Blocklist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n }\n\n let domain;\n try {\n domain = new URL(url).hostname;\n } catch (error) {\n return {\n result: false,\n type: PhishingDetectorResultType.All,\n };\n }\n\n const fqdn = domain.endsWith('.') ? domain.slice(0, -1) : domain;\n\n const source = domainToParts(fqdn);\n\n for (const { allowlist, name, version } of this.#configs) {\n // if source matches allowlist hostname (or subdomain thereof), PASS\n const allowlistMatch = matchPartsAgainstList(source, allowlist);\n if (allowlistMatch) {\n const match = domainPartsToDomain(allowlistMatch);\n return {\n match,\n name,\n result: false,\n type: PhishingDetectorResultType.Allowlist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n\n for (const { blocklist, fuzzylist, name, tolerance, version } of this\n .#configs) {\n // if source matches blocklist hostname (or subdomain thereof), FAIL\n const blocklistMatch = matchPartsAgainstList(source, blocklist);\n if (blocklistMatch) {\n const match = domainPartsToDomain(blocklistMatch);\n return {\n match,\n name,\n result: true,\n type: PhishingDetectorResultType.Blocklist,\n version: version === undefined ? version : String(version),\n };\n }\n\n if (tolerance > 0) {\n // check if near-match of whitelist domain, FAIL\n let fuzzyForm = domainPartsToFuzzyForm(source);\n // strip www\n fuzzyForm = fuzzyForm.replace(/^www\\./u, '');\n // check against fuzzylist\n const levenshteinMatched = fuzzylist.find((targetParts) => {\n const fuzzyTarget = domainPartsToFuzzyForm(targetParts);\n const dist = distance(fuzzyForm, fuzzyTarget);\n return dist <= tolerance;\n });\n if (levenshteinMatched) {\n const match = domainPartsToDomain(levenshteinMatched);\n return {\n name,\n match,\n result: true,\n type: PhishingDetectorResultType.Fuzzy,\n version: version === undefined ? version : String(version),\n };\n }\n }\n }\n\n // matched nothing, PASS\n return { result: false, type: PhishingDetectorResultType.All };\n }\n\n /**\n * Checks if a URL is blocked against the hashed request blocklist.\n * This is done by hashing the URL's hostname and checking it against the hashed request blocklist.\n *\n *\n * @param urlString - The URL to check.\n * @returns An object indicating if the URL is blocked and relevant metadata.\n */\n isMaliciousC2Domain(urlString: string): PhishingDetectorResult {\n let hostname;\n try {\n hostname = new URL(urlString).hostname;\n } catch (error) {\n return {\n result: false,\n type: PhishingDetectorResultType.C2DomainBlocklist,\n };\n }\n\n const fqdn = hostname.endsWith('.') ? hostname.slice(0, -1) : hostname;\n\n const source = domainToParts(fqdn);\n\n for (const { allowlist, name, version } of this.#configs) {\n // if source matches allowlist hostname (or subdomain thereof), PASS\n const allowlistMatch = matchPartsAgainstList(source, allowlist);\n if (allowlistMatch) {\n const match = domainPartsToDomain(allowlistMatch);\n return {\n match,\n name,\n result: false,\n type: PhishingDetectorResultType.Allowlist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n\n for (const { c2DomainBlocklist, name, version } of this.#configs) {\n const hash = sha256Hash(hostname.toLowerCase());\n const blocked = c2DomainBlocklist?.includes(hash) ?? false;\n\n if (blocked) {\n return {\n name,\n result: true,\n type: PhishingDetectorResultType.C2DomainBlocklist,\n version: version === undefined ? version : String(version),\n };\n }\n }\n // did not match, PASS\n return {\n result: false,\n type: PhishingDetectorResultType.C2DomainBlocklist,\n };\n }\n}\n\n/**\n * Runs a regex match to determine if a string is a IPFS CID\n * @returns Regex string for IPFS CID\n */\nfunction ipfsCidRegex() {\n // regex from https://stackoverflow.com/a/67176726\n const reg =\n 'Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,}';\n return new RegExp(reg, 'u');\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
var
|
|
17
|
+
var _chunkZAOBCAQTjs = require('./chunk-ZAOBCAQT.js');
|
|
18
18
|
require('./chunk-5NDIXQG5.js');
|
|
19
19
|
require('./chunk-Z4BLTVTB.js');
|
|
20
20
|
|
|
@@ -33,5 +33,5 @@ require('./chunk-Z4BLTVTB.js');
|
|
|
33
33
|
|
|
34
34
|
|
|
35
35
|
|
|
36
|
-
exports.C2_DOMAIN_BLOCKLIST_ENDPOINT =
|
|
36
|
+
exports.C2_DOMAIN_BLOCKLIST_ENDPOINT = _chunkZAOBCAQTjs.C2_DOMAIN_BLOCKLIST_ENDPOINT; exports.C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = _chunkZAOBCAQTjs.C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL; exports.C2_DOMAIN_BLOCKLIST_URL = _chunkZAOBCAQTjs.C2_DOMAIN_BLOCKLIST_URL; exports.CLIENT_SIDE_DETECION_BASE_URL = _chunkZAOBCAQTjs.CLIENT_SIDE_DETECION_BASE_URL; exports.HOTLIST_REFRESH_INTERVAL = _chunkZAOBCAQTjs.HOTLIST_REFRESH_INTERVAL; exports.ListKeys = _chunkZAOBCAQTjs.ListKeys; exports.ListNames = _chunkZAOBCAQTjs.ListNames; exports.METAMASK_HOTLIST_DIFF_FILE = _chunkZAOBCAQTjs.METAMASK_HOTLIST_DIFF_FILE; exports.METAMASK_HOTLIST_DIFF_URL = _chunkZAOBCAQTjs.METAMASK_HOTLIST_DIFF_URL; exports.METAMASK_STALELIST_FILE = _chunkZAOBCAQTjs.METAMASK_STALELIST_FILE; exports.METAMASK_STALELIST_URL = _chunkZAOBCAQTjs.METAMASK_STALELIST_URL; exports.PHISHING_CONFIG_BASE_URL = _chunkZAOBCAQTjs.PHISHING_CONFIG_BASE_URL; exports.PhishingController = _chunkZAOBCAQTjs.PhishingController; exports.STALELIST_REFRESH_INTERVAL = _chunkZAOBCAQTjs.STALELIST_REFRESH_INTERVAL; exports.phishingListKeyNameMap = _chunkZAOBCAQTjs.phishingListKeyNameMap;
|
|
37
37
|
//# sourceMappingURL=index.js.map
|
package/dist/index.mjs
CHANGED