-
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathPhishingController.ts
More file actions
1728 lines (1546 loc) · 51.5 KB
/
PhishingController.ts
File metadata and controls
1728 lines (1546 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BaseController } from '@metamask/base-controller';
import type {
StateMetadata,
ControllerGetStateAction,
ControllerStateChangeEvent,
} from '@metamask/base-controller';
import {
safelyExecute,
safelyExecuteWithTimeout,
} from '@metamask/controller-utils';
import type { Messenger } from '@metamask/messenger';
import type {
TransactionControllerStateChangeEvent,
TransactionMeta,
} from '@metamask/transaction-controller';
import type { Patch } from 'immer';
import { toASCII } from 'punycode/punycode.js';
import { CacheManager } from './CacheManager';
import type { CacheEntry } from './CacheManager';
import { convertListToTrie, insertToTrie, matchedPathPrefix } from './PathTrie';
import type { PathTrie } from './PathTrie';
import { PhishingDetector } from './PhishingDetector';
import {
PhishingDetectorResultType,
RecommendedAction,
AddressScanResultType,
} from './types';
import type {
PhishingDetectorResult,
PhishingDetectionScanResult,
TokenScanCacheData,
BulkTokenScanResponse,
BulkTokenScanRequest,
TokenScanApiResponse,
AddressScanCacheData,
AddressScanResult,
ApprovalsResponse,
} from './types';
import {
applyDiffs,
fetchTimeNow,
getHostnameFromUrl,
roundToNearestMinute,
getHostnameFromWebUrl,
buildCacheKey,
splitCacheHits,
resolveChainName,
getPathnameFromUrl,
} from './utils';
export const PHISHING_CONFIG_BASE_URL =
'https://phishing-detection.api.cx.metamask.io';
export const METAMASK_STALELIST_FILE = '/v1/stalelist';
export const METAMASK_HOTLIST_DIFF_FILE = '/v2/diffsSince';
export const CLIENT_SIDE_DETECION_BASE_URL =
'https://client-side-detection.api.cx.metamask.io';
export const C2_DOMAIN_BLOCKLIST_ENDPOINT = '/v1/request-blocklist';
export const PHISHING_DETECTION_BASE_URL =
'https://dapp-scanning.api.cx.metamask.io';
export const PHISHING_DETECTION_SCAN_ENDPOINT = 'v2/scan';
export const PHISHING_DETECTION_BULK_SCAN_ENDPOINT = 'bulk-scan';
export const SECURITY_ALERTS_BASE_URL = 'http://localhost:3000';
export const TOKEN_BULK_SCANNING_ENDPOINT = '/token/scan-bulk';
export const ADDRESS_SCAN_ENDPOINT = '/address/evm/scan';
export const APPROVALS_ENDPOINT = '/address/evm/approvals';
// Cache configuration defaults
export const DEFAULT_URL_SCAN_CACHE_TTL = 15 * 60; // 15 minutes in seconds
export const DEFAULT_URL_SCAN_CACHE_MAX_SIZE = 250;
export const DEFAULT_TOKEN_SCAN_CACHE_TTL = 15 * 60; // 15 minutes in seconds
export const DEFAULT_TOKEN_SCAN_CACHE_MAX_SIZE = 1000;
export const DEFAULT_ADDRESS_SCAN_CACHE_TTL = 15 * 60; // 15 minutes in seconds
export const DEFAULT_ADDRESS_SCAN_CACHE_MAX_SIZE = 1000;
export const C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL = 5 * 60; // 5 mins in seconds
export const HOTLIST_REFRESH_INTERVAL = 5 * 60; // 5 mins in seconds
export const STALELIST_REFRESH_INTERVAL = 30 * 24 * 60 * 60; // 30 days in seconds
export const METAMASK_STALELIST_URL = `${PHISHING_CONFIG_BASE_URL}${METAMASK_STALELIST_FILE}`;
export const METAMASK_HOTLIST_DIFF_URL = `${PHISHING_CONFIG_BASE_URL}${METAMASK_HOTLIST_DIFF_FILE}`;
export const C2_DOMAIN_BLOCKLIST_URL = `${CLIENT_SIDE_DETECION_BASE_URL}${C2_DOMAIN_BLOCKLIST_ENDPOINT}`;
/**
* @type ListTypes
*
* Type outlining the types of lists provided by aggregating different source lists
*/
export type ListTypes =
| 'fuzzylist'
| 'blocklist'
| 'blocklistPaths'
| 'allowlist'
| 'c2DomainBlocklist';
/**
* @type EthPhishingResponse
*
* Configuration response from the eth-phishing-detect package
* consisting of approved and unapproved website origins
*
* @property blacklist - List of unapproved origins
* @property fuzzylist - List of fuzzy-matched unapproved origins
* @property tolerance - Fuzzy match tolerance level
* @property version - Version number of this configuration
* @property whitelist - List of approved origins
*/
export type EthPhishingResponse = {
blacklist: string[];
fuzzylist: string[];
tolerance: number;
version: number;
whitelist: string[];
};
/**
* @type C2DomainBlocklistResponse
*
* Response for blocklist update requests
*
* @property recentlyAdded - List of c2 domains recently added to the blocklist
* @property recentlyRemoved - List of c2 domains recently removed from the blocklist
* @property lastFetchedAt - Timestamp of the last fetch request
*/
export type C2DomainBlocklistResponse = {
recentlyAdded: string[];
recentlyRemoved: string[];
lastFetchedAt: string;
};
/**
* PhishingStalelist defines the expected type of the stalelist from the API.
*
* allowlist - List of approved origins.
* blocklist - List of unapproved origins (hostname-only entries).
* blocklistPaths - Trie of unapproved origins with paths (hostname + path entries).
* fuzzylist - List of fuzzy-matched unapproved origins.
* tolerance - Fuzzy match tolerance level
* lastUpdated - Timestamp of last update.
* version - Stalelist data structure iteration.
*/
export type PhishingStalelist = {
allowlist: string[];
blocklist: string[];
blocklistPaths: string[];
fuzzylist: string[];
tolerance: number;
version: number;
lastUpdated: number;
};
/**
* @type PhishingListState
*
* type defining the persisted list state. This is the persisted state that is updated frequently with `this.maybeUpdateState()`.
*
* @property allowlist - List of approved origins (legacy naming "whitelist")
* @property blocklist - List of unapproved origins (legacy naming "blacklist")
* @property blocklistPaths - Trie of unapproved origins with paths (hostname + path, no query params).
* @property c2DomainBlocklist - List of hashed hostnames that C2 requests are blocked against.
* @property fuzzylist - List of fuzzy-matched unapproved origins
* @property tolerance - Fuzzy match tolerance level
* @property lastUpdated - Timestamp of last update.
* @property version - Version of the phishing list state.
* @property name - Name of the list. Used for attribution.
*/
export type PhishingListState = {
allowlist: string[];
blocklist: string[];
blocklistPaths: PathTrie;
c2DomainBlocklist: string[];
fuzzylist: string[];
tolerance: number;
version: number;
lastUpdated: number;
name: ListNames;
};
/**
* @type HotlistDiff
*
* type defining the expected type of the diffs in hotlist.json file.
*
* @property url - Url of the diff entry.
* @property timestamp - Timestamp at which the diff was identified.
* @property targetList - The list name where the diff was identified.
* @property isRemoval - Was the diff identified a removal type.
*/
export type HotlistDiff = {
url: string;
timestamp: number;
targetList: `${ListKeys}.${ListTypes}`;
isRemoval?: boolean;
};
export type DataResultWrapper<T> = {
data: T;
};
/**
* @type Hotlist
*
* Type defining expected hotlist.json file.
*
* @property url - Url of the diff entry.
* @property timestamp - Timestamp at which the diff was identified.
* @property targetList - The list name where the diff was identified.
* @property isRemoval - Was the diff identified a removal type.
*/
export type Hotlist = HotlistDiff[];
/**
* Enum containing upstream data provider source list keys.
* These are the keys denoting lists consumed by the upstream data provider.
*/
export enum ListKeys {
EthPhishingDetectConfig = 'eth_phishing_detect_config',
}
/**
* Enum containing downstream client attribution names.
*/
export enum ListNames {
MetaMask = 'MetaMask',
}
/**
* Maps from downstream client attribution name
* to list key sourced from upstream data provider.
*/
const phishingListNameKeyMap = {
[ListNames.MetaMask]: ListKeys.EthPhishingDetectConfig,
};
/**
* Maps from list key sourced from upstream data
* provider to downstream client attribution name.
*/
export const phishingListKeyNameMap = {
[ListKeys.EthPhishingDetectConfig]: ListNames.MetaMask,
};
const controllerName = 'PhishingController';
const metadata: StateMetadata<PhishingControllerState> = {
phishingLists: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
whitelist: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
whitelistPaths: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
hotlistLastFetched: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
stalelistLastFetched: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
c2DomainBlocklistLastFetched: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
urlScanCache: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
tokenScanCache: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
addressScanCache: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
};
/**
* Get a default empty state for the controller.
*
* @returns The default empty state.
*/
const getDefaultState = (): PhishingControllerState => {
return {
phishingLists: [],
whitelist: [],
whitelistPaths: {},
hotlistLastFetched: 0,
stalelistLastFetched: 0,
c2DomainBlocklistLastFetched: 0,
urlScanCache: {},
tokenScanCache: {},
addressScanCache: {},
};
};
/**
* @type PhishingControllerState
*
* Phishing controller state
* phishingLists - array of phishing lists
* whitelist - origins that bypass the phishing detector
* whitelistPaths - origins with paths that bypass the phishing detector
* hotlistLastFetched - timestamp of the last hotlist fetch
* stalelistLastFetched - timestamp of the last stalelist fetch
* c2DomainBlocklistLastFetched - timestamp of the last c2 domain blocklist fetch
* urlScanCache - cache of URL scan results
* tokenScanCache - cache of token scan results
* addressScanCache - cache of address scan results
*/
export type PhishingControllerState = {
phishingLists: PhishingListState[];
whitelist: string[];
whitelistPaths: PathTrie;
hotlistLastFetched: number;
stalelistLastFetched: number;
c2DomainBlocklistLastFetched: number;
urlScanCache: Record<string, CacheEntry<PhishingDetectionScanResult>>;
tokenScanCache: Record<string, CacheEntry<TokenScanCacheData>>;
addressScanCache: Record<string, CacheEntry<AddressScanCacheData>>;
};
/**
* PhishingControllerOptions
*
* Phishing controller options
* stalelistRefreshInterval - Polling interval used to fetch stale list.
* hotlistRefreshInterval - Polling interval used to fetch hotlist diff list.
* c2DomainBlocklistRefreshInterval - Polling interval used to fetch c2 domain blocklist.
* urlScanCacheTTL - Time to live in seconds for cached scan results.
* urlScanCacheMaxSize - Maximum number of entries in the scan cache.
* tokenScanCacheTTL - Time to live in seconds for cached token scan results.
* tokenScanCacheMaxSize - Maximum number of entries in the token scan cache.
* addressScanCacheTTL - Time to live in seconds for cached address scan results.
* addressScanCacheMaxSize - Maximum number of entries in the address scan cache.
*/
export type PhishingControllerOptions = {
stalelistRefreshInterval?: number;
hotlistRefreshInterval?: number;
c2DomainBlocklistRefreshInterval?: number;
urlScanCacheTTL?: number;
urlScanCacheMaxSize?: number;
tokenScanCacheTTL?: number;
tokenScanCacheMaxSize?: number;
addressScanCacheTTL?: number;
addressScanCacheMaxSize?: number;
messenger: PhishingControllerMessenger;
state?: Partial<PhishingControllerState>;
};
export type MaybeUpdateState = {
type: `${typeof controllerName}:maybeUpdateState`;
handler: PhishingController['maybeUpdateState'];
};
export type TestOrigin = {
type: `${typeof controllerName}:testOrigin`;
handler: PhishingController['test'];
};
export type PhishingControllerBulkScanUrlsAction = {
type: `${typeof controllerName}:bulkScanUrls`;
handler: PhishingController['bulkScanUrls'];
};
export type PhishingControllerBulkScanTokensAction = {
type: `${typeof controllerName}:bulkScanTokens`;
handler: PhishingController['bulkScanTokens'];
};
export type PhishingControllerScanAddressAction = {
type: `${typeof controllerName}:scanAddress`;
handler: PhishingController['scanAddress'];
};
export type PhishingControllerGetApprovalsAction = {
type: `${typeof controllerName}:getApprovals`;
handler: PhishingController['getApprovals'];
};
export type PhishingControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
PhishingControllerState
>;
export type PhishingControllerActions =
| PhishingControllerGetStateAction
| MaybeUpdateState
| TestOrigin
| PhishingControllerBulkScanUrlsAction
| PhishingControllerBulkScanTokensAction
| PhishingControllerScanAddressAction
| PhishingControllerGetApprovalsAction;
export type PhishingControllerStateChangeEvent = ControllerStateChangeEvent<
typeof controllerName,
PhishingControllerState
>;
export type PhishingControllerEvents = PhishingControllerStateChangeEvent;
/**
* The external actions available to the PhishingController.
*/
type AllowedActions = never;
/**
* The external events available to the PhishingController.
*/
export type AllowedEvents = TransactionControllerStateChangeEvent;
export type PhishingControllerMessenger = Messenger<
typeof controllerName,
PhishingControllerActions | AllowedActions,
PhishingControllerEvents | AllowedEvents
>;
/**
* BulkPhishingDetectionScanResponse
*
* Response for bulk phishing detection scan requests
* results - Record of domain names and their corresponding phishing detection scan results
*
* errors - Record of domain names and their corresponding errors
*/
export type BulkPhishingDetectionScanResponse = {
results: Record<string, PhishingDetectionScanResult>;
errors: Record<string, string[]>;
};
/**
* Controller that manages community-maintained lists of approved and unapproved website origins.
*/
export class PhishingController extends BaseController<
typeof controllerName,
PhishingControllerState,
PhishingControllerMessenger
> {
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
#detector: any;
#stalelistRefreshInterval: number;
#hotlistRefreshInterval: number;
#c2DomainBlocklistRefreshInterval: number;
readonly #urlScanCache: CacheManager<PhishingDetectionScanResult>;
readonly #tokenScanCache: CacheManager<TokenScanCacheData>;
readonly #addressScanCache: CacheManager<AddressScanCacheData>;
#inProgressHotlistUpdate?: Promise<void>;
#inProgressStalelistUpdate?: Promise<void>;
#isProgressC2DomainBlocklistUpdate?: Promise<void>;
readonly #transactionControllerStateChangeHandler: (
state: { transactions: TransactionMeta[] },
patches: Patch[],
) => void;
/**
* Construct a Phishing Controller.
*
* @param config - Initial options used to configure this controller.
* @param config.stalelistRefreshInterval - Polling interval used to fetch stale list.
* @param config.hotlistRefreshInterval - Polling interval used to fetch hotlist diff list.
* @param config.c2DomainBlocklistRefreshInterval - Polling interval used to fetch c2 domain blocklist.
* @param config.urlScanCacheTTL - Time to live in seconds for cached scan results.
* @param config.urlScanCacheMaxSize - Maximum number of entries in the scan cache.
* @param config.tokenScanCacheTTL - Time to live in seconds for cached token scan results.
* @param config.tokenScanCacheMaxSize - Maximum number of entries in the token scan cache.
* @param config.addressScanCacheTTL - Time to live in seconds for cached address scan results.
* @param config.addressScanCacheMaxSize - Maximum number of entries in the address scan cache.
* @param config.messenger - The controller restricted messenger.
* @param config.state - Initial state to set on this controller.
*/
constructor({
stalelistRefreshInterval = STALELIST_REFRESH_INTERVAL,
hotlistRefreshInterval = HOTLIST_REFRESH_INTERVAL,
c2DomainBlocklistRefreshInterval = C2_DOMAIN_BLOCKLIST_REFRESH_INTERVAL,
urlScanCacheTTL = DEFAULT_URL_SCAN_CACHE_TTL,
urlScanCacheMaxSize = DEFAULT_URL_SCAN_CACHE_MAX_SIZE,
tokenScanCacheTTL = DEFAULT_TOKEN_SCAN_CACHE_TTL,
tokenScanCacheMaxSize = DEFAULT_TOKEN_SCAN_CACHE_MAX_SIZE,
addressScanCacheTTL = DEFAULT_ADDRESS_SCAN_CACHE_TTL,
addressScanCacheMaxSize = DEFAULT_ADDRESS_SCAN_CACHE_MAX_SIZE,
messenger,
state = {},
}: PhishingControllerOptions) {
super({
name: controllerName,
metadata,
messenger,
state: {
...getDefaultState(),
...state,
},
});
this.#stalelistRefreshInterval = stalelistRefreshInterval;
this.#hotlistRefreshInterval = hotlistRefreshInterval;
this.#c2DomainBlocklistRefreshInterval = c2DomainBlocklistRefreshInterval;
this.#transactionControllerStateChangeHandler =
this.#onTransactionControllerStateChange.bind(this);
this.#urlScanCache = new CacheManager<PhishingDetectionScanResult>({
cacheTTL: urlScanCacheTTL,
maxCacheSize: urlScanCacheMaxSize,
initialCache: this.state.urlScanCache,
updateState: (cache) => {
this.update((draftState) => {
draftState.urlScanCache = cache;
});
},
});
this.#tokenScanCache = new CacheManager<TokenScanCacheData>({
cacheTTL: tokenScanCacheTTL,
maxCacheSize: tokenScanCacheMaxSize,
initialCache: this.state.tokenScanCache,
updateState: (cache) => {
this.update((draftState) => {
draftState.tokenScanCache = cache;
});
},
});
this.#addressScanCache = new CacheManager<AddressScanCacheData>({
cacheTTL: addressScanCacheTTL,
maxCacheSize: addressScanCacheMaxSize,
initialCache: this.state.addressScanCache,
updateState: (cache) => {
this.update((draftState) => {
draftState.addressScanCache = cache;
});
},
});
this.#registerMessageHandlers();
this.updatePhishingDetector();
this.#subscribeToTransactionControllerStateChange();
}
#subscribeToTransactionControllerStateChange() {
this.messenger.subscribe(
'TransactionController:stateChange',
this.#transactionControllerStateChangeHandler,
);
}
/**
* Constructor helper for registering this controller's messaging system
* actions.
*/
#registerMessageHandlers(): void {
this.messenger.registerActionHandler(
`${controllerName}:maybeUpdateState` as const,
this.maybeUpdateState.bind(this),
);
this.messenger.registerActionHandler(
`${controllerName}:testOrigin` as const,
this.test.bind(this),
);
this.messenger.registerActionHandler(
`${controllerName}:bulkScanUrls` as const,
this.bulkScanUrls.bind(this),
);
this.messenger.registerActionHandler(
`${controllerName}:bulkScanTokens` as const,
this.bulkScanTokens.bind(this),
);
this.messenger.registerActionHandler(
`${controllerName}:scanAddress` as const,
this.scanAddress.bind(this),
);
this.messenger.registerActionHandler(
`${controllerName}:getApprovals` as const,
this.getApprovals.bind(this),
);
}
/**
* Checks if a patch represents a transaction-level change or nested transaction property change
*
* @param patch - Immer patch to check
* @returns True if patch affects a transaction or its nested properties
*/
#isTransactionPatch(patch: Patch): boolean {
const { path } = patch;
return (
path.length === 2 &&
path[0] === 'transactions' &&
typeof path[1] === 'number'
);
}
/**
* Checks if a patch represents a simulation data change
*
* @param patch - Immer patch to check
* @returns True if patch represents a simulation data change
*/
#isSimulationDataPatch(patch: Patch): boolean {
const { path } = patch;
return (
path.length === 3 &&
path[0] === 'transactions' &&
typeof path[1] === 'number' &&
path[2] === 'simulationData'
);
}
/**
* Handle transaction controller state changes using Immer patches
* Extracts token addresses from simulation data and groups them by chain for bulk scanning
*
* @param _state - The current transaction controller state
* @param _state.transactions - Array of transaction metadata
* @param patches - Array of Immer patches only for transaction-level changes
*/
#onTransactionControllerStateChange(
_state: { transactions: TransactionMeta[] },
patches: Patch[],
) {
try {
const tokensByChain = new Map<string, Set<string>>();
for (const patch of patches) {
if (patch.op === 'remove') {
continue;
}
// Handle transaction-level patches (includes simulation data updates)
if (this.#isTransactionPatch(patch)) {
const transaction = patch.value as TransactionMeta;
this.#getTokensFromTransaction(transaction, tokensByChain);
} else if (this.#isSimulationDataPatch(patch)) {
const transactionIndex = patch.path[1] as number;
const transaction = _state.transactions?.[transactionIndex];
this.#getTokensFromTransaction(transaction, tokensByChain);
}
}
this.#scanTokensByChain(tokensByChain);
} catch (error) {
console.error('Error processing transaction state change:', error);
}
}
/**
* Collect token addresses from a transaction and group them by chain
*
* @param transaction - Transaction metadata to extract tokens from
* @param tokensByChain - Map to collect tokens grouped by chainId
*/
#getTokensFromTransaction(
transaction: TransactionMeta,
tokensByChain: Map<string, Set<string>>,
) {
// extract token addresses from simulation data
const tokenAddresses = transaction.simulationData?.tokenBalanceChanges?.map(
(tokenChange) => tokenChange.address.toLowerCase(),
);
// add token addresses to the map by chainId
if (tokenAddresses && tokenAddresses.length > 0 && transaction.chainId) {
const chainId = transaction.chainId.toLowerCase();
if (!tokensByChain.has(chainId)) {
tokensByChain.set(chainId, new Set());
}
const chainTokens = tokensByChain.get(chainId);
if (chainTokens) {
for (const address of tokenAddresses) {
chainTokens.add(address);
}
}
}
}
/**
* Scan tokens grouped by chain ID
*
* @param tokensByChain - Map of chainId to token addresses
*/
#scanTokensByChain(tokensByChain: Map<string, Set<string>>) {
for (const [chainId, tokenSet] of tokensByChain) {
if (tokenSet.size > 0) {
const tokens = Array.from(tokenSet);
this.bulkScanTokens({
chainId,
tokens,
}).catch((error) =>
console.error(`Error scanning tokens for chain ${chainId}:`, error),
);
}
}
}
/**
* Updates this.detector with an instance of PhishingDetector using the current state.
*/
updatePhishingDetector() {
this.#detector = new PhishingDetector(this.state.phishingLists);
}
/**
* Set the interval at which the stale phishing list will be refetched.
* Fetching will only occur on the next call to test/bypass.
* For immediate update to the phishing list, call {@link updateStalelist} directly.
*
* @param interval - the new interval, in ms.
*/
setStalelistRefreshInterval(interval: number) {
this.#stalelistRefreshInterval = interval;
}
/**
* Set the interval at which the hot list will be refetched.
* Fetching will only occur on the next call to test/bypass.
* For immediate update to the phishing list, call {@link updateHotlist} directly.
*
* @param interval - the new interval, in ms.
*/
setHotlistRefreshInterval(interval: number) {
this.#hotlistRefreshInterval = interval;
}
/**
* Set the interval at which the C2 domain blocklist will be refetched.
* Fetching will only occur on the next call to test/bypass.
* For immediate update to the phishing list, call {@link updateHotlist} directly.
*
* @param interval - the new interval, in ms.
*/
setC2DomainBlocklistRefreshInterval(interval: number) {
this.#c2DomainBlocklistRefreshInterval = interval;
}
/**
* Set the time-to-live for URL scan cache entries.
*
* @param ttl - The TTL in seconds.
*/
setUrlScanCacheTTL(ttl: number) {
this.#urlScanCache.setTTL(ttl);
}
/**
* Set the maximum number of entries in the URL scan cache.
*
* @param maxSize - The maximum cache size.
*/
setUrlScanCacheMaxSize(maxSize: number) {
this.#urlScanCache.setMaxSize(maxSize);
}
/**
* Clear the URL scan cache.
*/
clearUrlScanCache() {
this.#urlScanCache.clear();
}
/**
* Determine if an update to the stalelist configuration is needed.
*
* @returns Whether an update is needed
*/
isStalelistOutOfDate() {
return (
fetchTimeNow() - this.state.stalelistLastFetched >=
this.#stalelistRefreshInterval
);
}
/**
* Determine if an update to the hotlist configuration is needed.
*
* @returns Whether an update is needed
*/
isHotlistOutOfDate() {
return (
fetchTimeNow() - this.state.hotlistLastFetched >=
this.#hotlistRefreshInterval
);
}
/**
* Determine if an update to the C2 domain blocklist is needed.
*
* @returns Whether an update is needed
*/
isC2DomainBlocklistOutOfDate() {
return (
fetchTimeNow() - this.state.c2DomainBlocklistLastFetched >=
this.#c2DomainBlocklistRefreshInterval
);
}
/**
* Conditionally update the phishing configuration.
*
* If the stalelist configuration is out of date, this function will call `updateStalelist`
* to update the configuration. This will automatically grab the hotlist,
* so it isn't necessary to continue on to download the hotlist and the c2 domain blocklist.
*
*/
async maybeUpdateState() {
const staleListOutOfDate = this.isStalelistOutOfDate();
if (staleListOutOfDate) {
await this.updateStalelist();
return;
}
const hotlistOutOfDate = this.isHotlistOutOfDate();
if (hotlistOutOfDate) {
await this.updateHotlist();
}
const c2DomainBlocklistOutOfDate = this.isC2DomainBlocklistOutOfDate();
if (c2DomainBlocklistOutOfDate) {
await this.updateC2DomainBlocklist();
}
}
/**
* Determines if a given origin is unapproved.
*
* It is strongly recommended that you call {@link maybeUpdateState} before calling this,
* to check whether the phishing configuration is up-to-date. It will be updated if necessary
* by calling {@link updateStalelist} or {@link updateHotlist}.
*
* @param origin - Domain origin of a website.
* @returns Whether the origin is an unapproved origin.
*/
test(origin: string): PhishingDetectorResult {
const punycodeOrigin = toASCII(origin);
const hostname = getHostnameFromUrl(punycodeOrigin);
const hostnameWithPaths = hostname + getPathnameFromUrl(origin);
if (matchedPathPrefix(hostnameWithPaths, this.state.whitelistPaths)) {
return { result: false, type: PhishingDetectorResultType.All };
}
if (this.state.whitelist.includes(hostname || punycodeOrigin)) {
return { result: false, type: PhishingDetectorResultType.All }; // Same as whitelisted match returned by detector.check(...).
}
return this.#detector.check(punycodeOrigin);
}
/**
* Checks if a request URL's domain is blocked against the request blocklist.
*
* This method is used to determine if a specific request URL is associated with a malicious
* command and control (C2) domain. The URL's hostname is hashed and checked against a configured
* blocklist of known malicious domains.
*
* @param origin - The full request URL to be checked.
* @returns An object indicating whether the URL's domain is blocked and relevant metadata.
*/
isBlockedRequest(origin: string): PhishingDetectorResult {
const punycodeOrigin = toASCII(origin);
const hostname = getHostnameFromUrl(punycodeOrigin);
if (this.state.whitelist.includes(hostname || punycodeOrigin)) {
return { result: false, type: PhishingDetectorResultType.All }; // Same as whitelisted match returned by detector.check(...).
}
return this.#detector.isMaliciousC2Domain(punycodeOrigin);
}
/**
* Temporarily marks a given origin as approved.
*
* @param origin - The origin to mark as approved.
*/
bypass(origin: string) {
const punycodeOrigin = toASCII(origin);
const hostname = getHostnameFromUrl(punycodeOrigin);
const hostnameWithPaths = hostname + getPathnameFromUrl(origin);
const { whitelist, whitelistPaths } = this.state;
const whitelistPath = matchedPathPrefix(hostnameWithPaths, whitelistPaths);
if (whitelist.includes(hostname || punycodeOrigin) || whitelistPath) {
return;
}
// If the origin was blocked by a path, then we only want to add it to the whitelistPaths since
// other paths with the same hostname may not be blocked.
const blockingPath = this.#detector.blockingPath(origin);
if (blockingPath) {
this.update((draftState) => {
insertToTrie(blockingPath, draftState.whitelistPaths);
});
return;
}
this.update((draftState) => {
draftState.whitelist.push(hostname || punycodeOrigin);
});
}
/**
* Update the C2 domain blocklist.
*
* If an update is in progress, no additional update will be made. Instead this will wait until
* the in-progress update has finished.
*/
async updateC2DomainBlocklist() {
if (this.#isProgressC2DomainBlocklistUpdate) {
await this.#isProgressC2DomainBlocklistUpdate;
return;
}
try {
this.#isProgressC2DomainBlocklistUpdate = this.#updateC2DomainBlocklist();
await this.#isProgressC2DomainBlocklistUpdate;
} finally {
this.#isProgressC2DomainBlocklistUpdate = undefined;
}
}
/**
* Update the hotlist.
*
* If an update is in progress, no additional update will be made. Instead this will wait until
* the in-progress update has finished.
*/
async updateHotlist() {
if (this.#inProgressHotlistUpdate) {
await this.#inProgressHotlistUpdate;
return;
}
try {
this.#inProgressHotlistUpdate = this.#updateHotlist();
await this.#inProgressHotlistUpdate;
} finally {
this.#inProgressHotlistUpdate = undefined;
}
}
/**
* Update the stalelist.
*
* If an update is in progress, no additional update will be made. Instead this will wait until
* the in-progress update has finished.
*/
async updateStalelist() {
if (this.#inProgressStalelistUpdate) {
await this.#inProgressStalelistUpdate;
return;
}
try {
this.#inProgressStalelistUpdate = this.#updateStalelist();
await this.#inProgressStalelistUpdate;
} finally {
this.#inProgressStalelistUpdate = undefined;
}
}
/**
* Scan a URL for phishing. It will only scan the hostname of the URL. It also only supports
* web URLs.
*
* @param url - The URL to scan.