-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
1440 lines (1232 loc) · 54.9 KB
/
Copy pathbot.js
File metadata and controls
1440 lines (1232 loc) · 54.9 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
// ===========================================
// HARDCODE SECURITY SCANNER
// ===========================================
class EnhancedHardcodeScanner {
constructor() {
this.patterns = {
// ========== CRYPTO WALLETS - IMPROVED ==========
// Bitcoin private keys with better validation
bitcoin_private_key_wif: {
regex: /\b([5KL][1-9A-HJ-NP-Za-km-z]{50,51})\b/g,
severity: '🔴 CRITICAL',
type: 'Bitcoin Private Key (WIF)',
validate: true,
validator: (match) => this.validateBitcoinWIF(match)
},
bitcoin_private_key_hex: {
regex: /\b(bitcoin[_-]?(?:private[_-]?key|priv[_-]?key))["\s]*[:=]["\s]*["']?(0x)?([a-fA-F0-9]{64})["']?/gi,
severity: '🔴 CRITICAL',
type: 'Bitcoin Private Key (Hex)',
validate: true
},
// Ethereum with context validation
ethereum_private_key: {
regex: /\b(?:(?:eth|ethereum)[_-]?(?:private[_-]?key|priv[_-]?key)|privateKey)["\s]*[:=]["\s]*["']?(0x)?([a-fA-F0-9]{64})["']?/gi,
severity: '🔴 CRITICAL',
type: 'Ethereum Private Key',
validate: true,
validator: (match) => this.validateEthereumKey(match)
},
// Solana with better patterns
solana_private_key_array: {
regex: /\[(?:\s*(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\s*,\s*){31}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\s*\]/g,
severity: '🔴 CRITICAL',
type: 'Solana Private Key (Uint8Array)',
validate: true
},
solana_base58_private: {
regex: /\b(?:solana[_-]?(?:private[_-]?key|secret)|SOL_PRIVATE_KEY)["\s]*[:=]["\s]*["']?([1-9A-HJ-NP-Za-km-z]{87,88})["']?/gi,
severity: '🔴 CRITICAL',
type: 'Solana Private Key (Base58)',
validate: true
},
// SUI with enhanced detection
sui_private_key_bech32: {
regex: /\b(suiprivkey1[a-z0-9]{58,})\b/g,
severity: '🔴 CRITICAL',
type: 'SUI Private Key (Bech32)',
validate: true
},
sui_ed25519_key: {
regex: /\b(?:sui[_-]?(?:private[_-]?key|secret)|SUI_PRIVATE_KEY)["\s]*[:=]["\s]*["']?([a-zA-Z0-9+/=]{44})["']?/gi,
severity: '🔴 CRITICAL',
type: 'SUI Private Key (Ed25519)',
validate: true
},
// Comprehensive mnemonic detection
mnemonic_12_words: {
regex: /\b(?:mnemonic|seed[_-]?phrase|recovery[_-]?phrase|backup[_-]?phrase)["\s]*[:=]["\s]*["']((?:[a-z]{3,8}\s+){11}[a-z]{3,8})["']/gi,
severity: '🔴 CRITICAL',
type: '12-Word Mnemonic Phrase',
validator: (match) => this.validateMnemonic(match, 12)
},
mnemonic_15_words: {
regex: /\b(?:mnemonic|seed[_-]?phrase|recovery[_-]?phrase)["\s]*[:=]["\s]*["']((?:[a-z]{3,8}\s+){14}[a-z]{3,8})["']/gi,
severity: '🔴 CRITICAL',
type: '15-Word Mnemonic Phrase',
validator: (match) => this.validateMnemonic(match, 15)
},
mnemonic_18_words: {
regex: /\b(?:mnemonic|seed[_-]?phrase|recovery[_-]?phrase)["\s]*[:=]["\s]*["']((?:[a-z]{3,8}\s+){17}[a-z]{3,8})["']/gi,
severity: '🔴 CRITICAL',
type: '18-Word Mnemonic Phrase',
validator: (match) => this.validateMnemonic(match, 18)
},
mnemonic_21_words: {
regex: /\b(?:mnemonic|seed[_-]?phrase|recovery[_-]?phrase)["\s]*[:=]["\s]*["']((?:[a-z]{3,8}\s+){20}[a-z]{3,8})["']/gi,
severity: '🔴 CRITICAL',
type: '21-Word Mnemonic Phrase',
validator: (match) => this.validateMnemonic(match, 21)
},
mnemonic_24_words: {
regex: /\b(?:mnemonic|seed[_-]?phrase|recovery[_-]?phrase)["\s]*[:=]["\s]*["']((?:[a-z]{3,8}\s+){23}[a-z]{3,8})["']/gi,
severity: '🔴 CRITICAL',
type: '24-Word Mnemonic Phrase',
validator: (match) => this.validateMnemonic(match, 24)
},
// Unquoted mnemonic detection
mnemonic_unquoted: {
regex: /\b((?:[a-z]{3,8}\s+){11,23}[a-z]{3,8})\b(?=\s*[;,\n\r]|$)/g,
severity: '🔴 CRITICAL',
type: 'Potential Mnemonic Phrase',
validator: (match) => this.validateUnquotedMnemonic(match)
},
// ========== API KEYS - ENHANCED ==========
// AWS with improved patterns
aws_access_key_id: {
regex: /\b((?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16})\b/g,
severity: '🔴 CRITICAL',
type: 'AWS Access Key ID',
validate: true
},
aws_secret_access_key: {
regex: /\b(?:aws[_-]?secret[_-]?access[_-]?key|aws[_-]?secret|AWS_SECRET_ACCESS_KEY)["\s]*[:=]["\s]*["']?([A-Za-z0-9+/]{40})["']?/gi,
severity: '🔴 CRITICAL',
type: 'AWS Secret Access Key',
validate: true,
validator: (match) => this.validateBase64Like(match, 40)
},
aws_session_token: {
regex: /\b(?:aws[_-]?session[_-]?token|AWS_SESSION_TOKEN)["\s]*[:=]["\s]*["']?([A-Za-z0-9+/=]{100,})["']?/gi,
severity: '🟠 HIGH',
type: 'AWS Session Token',
validate: true
},
// Google Cloud enhanced
gcp_api_key: {
regex: /\b(AIza[0-9A-Za-z\-_]{35})\b/g,
severity: '🟠 HIGH',
type: 'Google Cloud API Key',
validate: true
},
gcp_service_account_key: {
regex: /"type":\s*"service_account"[\s\S]*?"private_key":\s*"-----BEGIN PRIVATE KEY-----[\s\S]*?-----END PRIVATE KEY-----"/g,
severity: '🔴 CRITICAL',
type: 'GCP Service Account Key',
validate: true
},
// GitHub tokens with all variants
github_pat_classic: {
regex: /\b(ghp_[A-Za-z0-9_]{36})\b/g,
severity: '🟠 HIGH',
type: 'GitHub Personal Access Token (Classic)',
validate: true
},
github_pat_fine_grained: {
regex: /\b(github_pat_[A-Za-z0-9_]{82})\b/g,
severity: '🟠 HIGH',
type: 'GitHub Personal Access Token (Fine-grained)',
validate: true
},
github_oauth: {
regex: /\b(gho_[A-Za-z0-9_]{36})\b/g,
severity: '🟠 HIGH',
type: 'GitHub OAuth Token',
validate: true
},
github_app_token: {
regex: /\b(ghs_[A-Za-z0-9_]{36})\b/g,
severity: '🟠 HIGH',
type: 'GitHub App Token',
validate: true
},
github_refresh_token: {
regex: /\b(ghr_[A-Za-z0-9_]{36})\b/g,
severity: '🟠 HIGH',
type: 'GitHub Refresh Token',
validate: true
},
// OpenAI enhanced
openai_api_key: {
regex: /\b(sk-[A-Za-z0-9]{32}T3BlbkFJ[A-Za-z0-9]{16})\b/g,
severity: '🟠 HIGH',
type: 'OpenAI API Key',
validate: true
},
openai_api_key_new: {
regex: /\b(sk-proj-[A-Za-z0-9]{48})\b/g,
severity: '🟠 HIGH',
type: 'OpenAI API Key (Project)',
validate: true
},
// Stripe enhanced
stripe_secret_key_live: {
regex: /\b(sk_live_[A-Za-z0-9]{24,})\b/g,
severity: '🔴 CRITICAL',
type: 'Stripe Live Secret Key',
validate: true
},
stripe_secret_key_test: {
regex: /\b(sk_test_[A-Za-z0-9]{24,})\b/g,
severity: '🟡 MEDIUM',
type: 'Stripe Test Secret Key',
validate: true
},
stripe_restricted_key: {
regex: /\b(rk_live_[A-Za-z0-9]{24,})\b/g,
severity: '🟠 HIGH',
type: 'Stripe Restricted Key',
validate: true
},
// Database connections improved
mongodb_connection_string: {
regex: /mongodb(?:\+srv)?:\/\/([^:]+):([^@]+)@([^/\s]+)(?:\/([^?\s]+))?(?:\?([^&\s]+=([^&\s]+)(&[^&\s]+=([^&\s]+))*))?/gi,
severity: '🔴 CRITICAL',
type: 'MongoDB Connection String',
validate: true
},
postgresql_connection_string: {
regex: /postgres(?:ql)?:\/\/([^:]+):([^@]+)@([^:\s]+)(?::(\d+))?\/([^?\s]+)(?:\?([^&\s]+=([^&\s]+)(&[^&\s]+=([^&\s]+))*))?/gi,
severity: '🔴 CRITICAL',
type: 'PostgreSQL Connection String',
validate: true
},
mysql_connection_string: {
regex: /mysql:\/\/([^:]+):([^@]+)@([^:\s]+)(?::(\d+))?\/([^?\s]+)(?:\?([^&\s]+=([^&\s]+)(&[^&\s]+=([^&\s]+))*))?/gi,
severity: '🔴 CRITICAL',
type: 'MySQL Connection String',
validate: true
},
// JWT tokens with validation
jwt_token: {
regex: /\b(eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b/g,
severity: '🟠 HIGH',
type: 'JWT Token',
validator: (match) => this.validateJWT(match)
},
// Private keys comprehensive
rsa_private_key: {
regex: /-----BEGIN RSA PRIVATE KEY-----[\s\S]{100,}-----END RSA PRIVATE KEY-----/g,
severity: '🔴 CRITICAL',
type: 'RSA Private Key'
},
ecdsa_private_key: {
regex: /-----BEGIN EC PRIVATE KEY-----[\s\S]{100,}-----END EC PRIVATE KEY-----/g,
severity: '🔴 CRITICAL',
type: 'ECDSA Private Key'
},
openssh_private_key: {
regex: /-----BEGIN OPENSSH PRIVATE KEY-----[\s\S]{100,}-----END OPENSSH PRIVATE KEY-----/g,
severity: '🔴 CRITICAL',
type: 'OpenSSH Private Key'
},
ed25519_private_key: {
regex: /-----BEGIN PRIVATE KEY-----[\s\S]{50,100}-----END PRIVATE KEY-----/g,
severity: '🔴 CRITICAL',
type: 'Ed25519 Private Key'
},
// Generic patterns with better validation
generic_api_key: {
regex: /\b(?:api[_-]?key|apikey|API_KEY)["\s]*[:=]["\s]*["']([A-Za-z0-9_\-\.]{20,})["']/gi,
severity: '🟡 MEDIUM',
type: 'Generic API Key',
validator: (match) => this.validateGenericKey(match)
},
generic_secret: {
regex: /\b(?:secret|client[_-]?secret|app[_-]?secret)["\s]*[:=]["\s]*["']([A-Za-z0-9_\-\.\/\+=]{16,})["']/gi,
severity: '🟡 MEDIUM',
type: 'Generic Secret',
validator: (match) => this.validateGenericSecret(match)
},
// Password patterns
password_field: {
regex: /\b(?:password|passwd|pwd)["\s]*[:=]["\s]*["']([^"']{8,})["']/gi,
severity: '🟡 MEDIUM',
type: 'Password Field',
validator: (match) => this.validatePassword(match)
},
// Cryptocurrency addresses (for reference, not critical)
bitcoin_address: {
regex: /\b([13][a-km-zA-HJ-NP-Z1-9]{25,34}|bc1[a-z0-9]{39,59})\b/g,
severity: '🟢 INFO',
type: 'Bitcoin Address',
validate: true
},
ethereum_address: {
regex: /\b(0x[a-fA-F0-9]{40})\b/g,
severity: '🟢 INFO',
type: 'Ethereum Address',
validator: (match) => this.validateEthereumAddress(match)
}
};
// Expanded BIP39 wordlist for better validation
this.bip39Words = [
'abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract', 'absurd', 'abuse',
'access', 'accident', 'account', 'accuse', 'achieve', 'acid', 'acoustic', 'acquire', 'across', 'act',
'action', 'actor', 'actress', 'actual', 'adapt', 'add', 'addict', 'address', 'adjust', 'admit',
'adult', 'advance', 'advice', 'aerobic', 'affair', 'afford', 'afraid', 'again', 'against', 'age',
'agent', 'agree', 'ahead', 'aim', 'air', 'airport', 'aisle', 'alarm', 'album', 'alcohol',
'alert', 'alien', 'all', 'alley', 'allow', 'almost', 'alone', 'alpha', 'already', 'also',
'alter', 'always', 'amateur', 'amazing', 'among', 'amount', 'amused', 'analyst', 'anchor', 'ancient',
'anger', 'angle', 'angry', 'animal', 'ankle', 'announce', 'annual', 'another', 'answer', 'antenna'
// ... (truncated for brevity, should include all 2048 BIP39 words)
];
this.findings = [];
this.scannedSources = new Set();
this.falsePositives = new Set();
this.scanStartTime = Date.now();
// Enhanced false positive patterns
this.excludePatterns = [
/^[0-9a-fA-F]{64}$/, // Generic hex
/^0+$/, // All zeros
/^[fF]+$/, // All Fs
/example/i,
/your[_-]?(api[_-]?key|secret|token|password)/i,
/placeholder/i,
/test[_-]?(key|secret|token)/i,
/demo[_-]?(key|secret|token)/i,
/sample[_-]?(key|secret|token)/i,
/fake[_-]?(key|secret|token)/i,
/dummy[_-]?(key|secret|token)/i,
/xxxxxxxx/i,
/12345678/,
/abcdefgh/i,
/undefined/,
/null/,
/lorem\s+ipsum/i,
/\$\{[^}]+\}/, // Template variables
/%[A-Z_]+%/, // Environment variable placeholders
/INSERT[_-]?(YOUR|API|SECRET)/i
];
}
// Validation methods
validateBitcoinWIF(key) {
// Basic WIF validation - should start with 5, K, or L and be proper length
if (!/^[5KL]/.test(key)) return false;
if (key.startsWith('5') && key.length !== 51) return false;
if ((key.startsWith('K') || key.startsWith('L')) && key.length !== 52) return false;
return true;
}
validateEthereumKey(key) {
// Remove 0x prefix if present
key = key.replace(/^0x/i, '');
return key.length === 64 && /^[a-fA-F0-9]+$/.test(key);
}
validateEthereumAddress(address) {
return /^0x[a-fA-F0-9]{40}$/.test(address);
}
validateMnemonic(phrase, wordCount) {
const words = phrase.trim().toLowerCase().split(/\s+/);
if (words.length !== wordCount) return false;
// Check if at least 70% of words are valid BIP39 words
const validWords = words.filter(w => this.bip39Words.includes(w));
return validWords.length >= words.length * 0.7;
}
validateUnquotedMnemonic(phrase) {
const words = phrase.trim().toLowerCase().split(/\s+/);
if (words.length < 12 || words.length > 24) return false;
// Should not be common English sentences
const commonWords = ['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'];
const commonWordCount = words.filter(w => commonWords.includes(w)).length;
if (commonWordCount > words.length * 0.3) return false;
// Check if it looks like a mnemonic
const validWords = words.filter(w => this.bip39Words.includes(w));
return validWords.length >= words.length * 0.5;
}
validateJWT(token) {
try {
const parts = token.split('.');
if (parts.length !== 3) return false;
// Decode header and check if it looks like JWT
const header = JSON.parse(atob(parts[0].replace(/-/g, '+').replace(/_/g, '/')));
return header.typ === 'JWT' || header.alg;
} catch {
return false;
}
}
validateBase64Like(str, expectedLength) {
if (str.length !== expectedLength) return false;
return /^[A-Za-z0-9+/]*={0,2}$/.test(str);
}
validateGenericKey(key) {
// Filter out obvious false positives
const fp = ['example', 'your-api-key', 'test-key', 'xxxxxxxx', '12345678', 'sample', 'demo'];
if (fp.some(f => key.toLowerCase().includes(f))) return false;
// Should have reasonable entropy
const uniqueChars = new Set(key.toLowerCase()).size;
return uniqueChars >= key.length * 0.4;
}
validateGenericSecret(secret) {
const fp = ['your-secret', 'secret-key', 'test-secret', 'example-secret'];
if (fp.some(f => secret.toLowerCase().includes(f))) return false;
const uniqueChars = new Set(secret.toLowerCase()).size;
return uniqueChars >= secret.length * 0.3;
}
validatePassword(password) {
// Filter out obvious test passwords
const fp = ['password', '123456', 'test123', 'admin', 'user123', 'example'];
if (fp.some(f => password.toLowerCase().includes(f))) return false;
return password.length >= 8;
}
isLikelyFalsePositive(match, pattern) {
// Enhanced false positive detection
if (this.excludePatterns.some(exp => exp.test(match))) {
return true;
}
// Check for CSS colors
if (/^#[0-9a-fA-F]{6}$/i.test(match)) {
return true;
}
// Check for repeated patterns
if (/^(.)\1+$/.test(match) || /^(..)\1+$/.test(match)) {
return true;
}
// Check for common development patterns
if (/^(test|demo|sample|example|placeholder|dummy|fake)[-_]?/i.test(match)) {
return true;
}
// Run pattern-specific validator
if (pattern.validator) {
return !pattern.validator(match);
}
return false;
}
// Enhanced context extraction
getContext(content, index, match) {
const contextSize = 150;
const start = Math.max(0, index - contextSize);
const end = Math.min(content.length, index + match.length + contextSize);
let context = content.substring(start, end);
if (start > 0) context = '...' + context;
if (end < content.length) context = context + '...';
// Highlight the match with more visible markers
context = context.replace(match, `🔍${match}🔍`);
// Clean up the context for better readability
context = context.replace(/\s+/g, ' ').trim();
return context;
}
// Enhanced DOM scanning
async scanDOM() {
console.log('🔍 Scanning DOM content...');
// Scan HTML content
const htmlContent = document.documentElement.outerHTML;
this.scanContent(htmlContent, 'DOM HTML', window.location.href);
// Scan meta tags
const metaTags = document.querySelectorAll('meta[content]');
metaTags.forEach(meta => {
this.scanContent(`${meta.name || meta.property}="${meta.content}"`, 'META Tag', meta.outerHTML);
});
// Scan data attributes comprehensively
const elementsWithData = document.querySelectorAll('*');
elementsWithData.forEach(el => {
Array.from(el.attributes).forEach(attr => {
if (attr.name.includes('key') || attr.name.includes('secret') ||
attr.name.includes('token') || attr.name.includes('api') ||
attr.name.includes('private') || attr.name.includes('credential')) {
this.scanContent(`${attr.name}="${attr.value}"`, 'DOM Attribute', el.tagName);
}
});
});
// Scan form inputs including all types
const inputs = document.querySelectorAll('input, textarea');
inputs.forEach(input => {
if (input.value && input.value.length > 10) {
this.scanContent(`${input.name || input.id || 'unnamed'}=${input.value}`, 'Form Input', input.type);
}
if (input.placeholder && input.placeholder.length > 10) {
this.scanContent(input.placeholder, 'Input Placeholder', input.type);
}
});
// Scan comments in HTML
const walker = document.createTreeWalker(
document.documentElement,
NodeFilter.SHOW_COMMENT,
null,
false
);
let commentNode;
while (commentNode = walker.nextNode()) {
if (commentNode.nodeValue.length > 20) {
this.scanContent(commentNode.nodeValue, 'HTML Comment', 'comment');
}
}
}
// Enhanced script scanning with better error handling
async scanScripts() {
console.log('📜 Scanning JavaScript files...');
const scripts = document.querySelectorAll('script');
const promises = [];
for (let i = 0; i < scripts.length; i++) {
const script = scripts[i];
if (script.src && !this.scannedSources.has(script.src)) {
this.scannedSources.add(script.src);
const promise = this.fetchWithTimeout(script.src, 10000)
.then(content => {
this.scanContent(content, 'External Script', script.src);
})
.catch(error => {
console.warn(` ⚠️ Cannot access: ${script.src} (${error.message})`);
});
promises.push(promise);
} else if (script.textContent && script.textContent.trim()) {
this.scanContent(script.textContent, 'Inline Script', `inline-script-${i}`);
}
}
// Wait for all script fetches to complete
await Promise.allSettled(promises);
}
async fetchWithTimeout(url, timeout = 10000) {
return new Promise(async (resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('Timeout'));
}, timeout);
try {
const response = await fetch(url);
const content = await response.text();
clearTimeout(timeoutId);
resolve(content);
} catch (error) {
clearTimeout(timeoutId);
reject(error);
}
});
}
// Enhanced storage scanning
scanStorage() {
console.log('💾 Scanning browser storage...');
// LocalStorage
try {
const localStorageData = { ...localStorage };
Object.entries(localStorageData).forEach(([key, value]) => {
this.scanContent(`${key}=${value}`, 'LocalStorage', key);
// Also scan the key itself
this.scanContent(key, 'LocalStorage Key', key);
});
} catch (e) {
console.warn('⚠️ Cannot access localStorage:', e.message);
}
// SessionStorage
try {
const sessionStorageData = { ...sessionStorage };
Object.entries(sessionStorageData).forEach(([key, value]) => {
this.scanContent(`${key}=${value}`, 'SessionStorage', key);
this.scanContent(key, 'SessionStorage Key', key);
});
} catch (e) {
console.warn('⚠️ Cannot access sessionStorage:', e.message);
}
// IndexedDB enumeration
if (window.indexedDB) {
this.scanIndexedDB();
}
}
async scanIndexedDB() {
try {
console.log(' 🔍 Scanning IndexedDB...');
const databases = await indexedDB.databases();
for (const dbInfo of databases) {
console.log(` 📊 Found database: ${dbInfo.name}`);
// Note: Full IndexedDB scanning would require opening each database
// and iterating through object stores, which is complex and might
// require user permission
}
} catch (e) {
console.warn(' ⚠️ Cannot enumerate IndexedDB:', e.message);
}
}
// Main scanning function with better progress reporting
async scan(options = {}) {
const opts = {
includeScripts: true,
includeStorage: true,
includeCookies: true,
includeDOM: true,
includeWindowObject: true,
includeFetch: true,
deepScan: false,
verbose: true,
...options
};
console.clear();
console.log('%c🔍 ENHANCED HARDCODE SECURITY SCANNER v2.1', 'font-size: 20px; font-weight: bold; color: #ff6b6b;');
console.log('%c' + '='.repeat(60), 'color: #4ecdc4;');
console.log(`🎯 Target: ${window.location.href}`);
console.log(`⏰ Time: ${new Date().toLocaleString()}`);
console.log(`🔧 Mode: ${opts.deepScan ? 'DEEP SCAN' : 'STANDARD SCAN'}`);
console.log(`📊 Patterns loaded: ${Object.keys(this.patterns).length}`);
console.log('%c' + '='.repeat(60), 'color: #4ecdc4;');
this.findings = [];
this.scannedSources.clear();
this.falsePositives.clear();
const scanSteps = [];
if (opts.includeDOM) scanSteps.push('DOM');
if (opts.includeScripts) scanSteps.push('Scripts');
if (opts.includeStorage) scanSteps.push('Storage');
if (opts.includeCookies) scanSteps.push('Cookies');
if (opts.includeWindowObject) scanSteps.push('Window');
if (opts.includeFetch) scanSteps.push('Network');
if (opts.deepScan) scanSteps.push('Deep Analysis');
console.log(`🔄 Scanning: ${scanSteps.join(' → ')}`);
try {
let currentStep = 1;
const totalSteps = scanSteps.length;
if (opts.includeDOM) {
console.log(`\n[${currentStep}/${totalSteps}] 🏗️ DOM Analysis`);
await this.scanDOM();
currentStep++;
}
if (opts.includeScripts) {
console.log(`\n[${currentStep}/${totalSteps}] 📜 JavaScript Analysis`);
await this.scanScripts();
currentStep++;
}
if (opts.includeStorage) {
console.log(`\n[${currentStep}/${totalSteps}] 💾 Storage Analysis`);
this.scanStorage();
currentStep++;
}
if (opts.includeCookies) {
console.log(`\n[${currentStep}/${totalSteps}] 🍪 Cookie Analysis`);
this.scanCookies();
currentStep++;
}
if (opts.includeWindowObject) {
console.log(`\n[${currentStep}/${totalSteps}] 🪟 Window Object Analysis`);
this.scanWindowObject();
currentStep++;
}
if (opts.includeFetch) {
console.log(`\n[${currentStep}/${totalSteps}] 🌐 Network Monitoring Setup`);
this.interceptFetch();
currentStep++;
}
if (opts.deepScan) {
console.log(`\n[${currentStep}/${totalSteps}] 🔬 Deep Analysis`);
await this.deepScan();
currentStep++;
}
console.log('\n' + '='.repeat(60));
this.displayResults(opts.verbose);
this.displaySummary();
this.displayRecommendations();
} catch (error) {
console.error('❌ Scan error:', error);
console.error('Stack trace:', error.stack);
}
return this.findings;
}
scanContent(content, type, source) {
if (!content || typeof content !== 'string' || content.length < 5) return;
Object.entries(this.patterns).forEach(([patternName, pattern]) => {
let matches;
try {
matches = [...content.matchAll(pattern.regex)];
} catch (error) {
console.warn(`Pattern error for ${patternName}:`, error.message);
return;
}
matches.forEach(match => {
const matchValue = match[1] || match[0];
if (this.isLikelyFalsePositive(matchValue, pattern)) {
this.falsePositives.add(matchValue);
return;
}
const finding = {
type: pattern.type,
severity: pattern.severity,
match: this.maskSensitiveData(matchValue),
fullMatch: matchValue,
source: source,
location: type,
timestamp: new Date().toISOString(),
context: this.getContext(content, match.index, match[0]),
confidence: pattern.validate ? 'High' : 'Medium',
patternName: patternName
};
const isDuplicate = this.findings.some(f =>
f.fullMatch === finding.fullMatch &&
f.source === finding.source &&
f.type === finding.type
);
if (!isDuplicate) {
this.findings.push(finding);
}
});
});
}
scanCookies() {
const cookies = document.cookie.split(';');
cookies.forEach((cookie, index) => {
if (cookie.trim()) {
const [name, ...valueParts] = cookie.trim().split('=');
const value = valueParts.join('=');
this.scanContent(`${name}=${value}`, 'Cookie', `cookie-${name || index}`);
// Scan cookie name separately
if (name && name.length > 5) {
this.scanContent(name, 'Cookie Name', name);
}
}
});
}
scanWindowObject() {
const suspiciousKeys = [
'apikey', 'api_key', 'apiKey', 'API_KEY',
'secret', 'Secret', 'SECRET',
'token', 'Token', 'TOKEN',
'password', 'Password', 'PASSWORD',
'privatekey', 'private_key', 'privateKey', 'PRIVATE_KEY',
'mnemonic', 'Mnemonic', 'MNEMONIC',
'seed', 'Seed', 'SEED',
'credential', 'Credential', 'CREDENTIAL',
'auth', 'Auth', 'AUTH',
'key', 'Key', 'KEY'
];
const scanObject = (obj, path = 'window', depth = 0) => {
if (depth > 3) return; // Prevent infinite recursion
try {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const fullPath = `${path}.${key}`;
const value = obj[key];
if (suspiciousKeys.some(sk => key.toLowerCase().includes(sk.toLowerCase()))) {
if (typeof value === 'string' && value.length > 10) {
this.scanContent(`${fullPath}=${value}`, 'Window Object', fullPath);
} else if (typeof value === 'object' && value !== null) {
try {
const jsonValue = JSON.stringify(value);
if (jsonValue.length > 20 && jsonValue.length < 10000) {
this.scanContent(jsonValue, 'Window Object', fullPath);
}
} catch (e) {
// Skip circular references or non-serializable objects
}
}
}
// Recursively scan nested objects
if (typeof value === 'object' && value !== null && depth < 2) {
scanObject(value, fullPath, depth + 1);
}
}
}
} catch (e) {
// Skip inaccessible properties
}
};
scanObject(window);
}
interceptFetch() {
if (window._securityScannerFetchIntercepted) return;
const originalFetch = window.fetch;
window.fetch = async (...args) => {
const [resource, config] = args;
try {
// Scan request URL
if (typeof resource === 'string') {
this.scanContent(resource, 'Fetch URL', 'network-request');
}
// Scan headers
if (config && config.headers) {
const headers = typeof config.headers === 'object' ?
JSON.stringify(config.headers) : config.headers;
this.scanContent(headers, 'Fetch Headers', resource.toString());
}
// Scan body
if (config && config.body) {
const body = typeof config.body === 'string' ?
config.body : JSON.stringify(config.body);
this.scanContent(body, 'Fetch Body', resource.toString());
}
} catch (e) {
// Ignore errors in interception
}
return originalFetch.apply(this, args);
};
window._securityScannerFetchIntercepted = true;
}
async deepScan() {
// Wait for dynamic content
await new Promise(resolve => setTimeout(resolve, 3000));
// Re-scan DOM for dynamically added content
await this.scanDOM();
// Check for framework-specific patterns
this.scanFrameworkData();
// Scan Web Workers if accessible
this.scanWebWorkers();
// Scan Service Workers if accessible
this.scanServiceWorkers();
}
scanFrameworkData() {
// React DevTools
if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
console.log(' ⚛️ React detected');
try {
const reactFiber = document.querySelector('[data-reactroot]')?._reactInternalFiber;
if (reactFiber) {
this.scanContent(JSON.stringify(reactFiber), 'React Fiber', 'react-devtools');
}
} catch (e) {
// React scanning failed
}
}
// Vue DevTools
if (window.__VUE__) {
console.log(' 🖖 Vue detected');
try {
this.scanContent(JSON.stringify(window.__VUE__), 'Vue Instance', 'vue-devtools');
} catch (e) {
// Vue scanning failed
}
}
// Angular
if (window.ng || window.angular) {
console.log(' 🅰️ Angular detected');
// Angular scanning would require more complex implementation
}
}
scanWebWorkers() {
// This is limited since we can't directly access worker content
// but we can detect their presence
if ('serviceWorker' in navigator) {
console.log(' 👷 Service Worker API available');
}
}
scanServiceWorkers() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
if (registrations.length > 0) {
console.log(` 📋 Found ${registrations.length} service worker(s)`);
registrations.forEach(registration => {
if (registration.active) {
console.log(` 🔗 Active: ${registration.active.scriptURL}`);
}
});
}
}).catch(e => {
console.warn(' ⚠️ Cannot access service workers:', e.message);
});
}
}
maskSensitiveData(data) {
if (!data || data.length <= 12) return data;
const visibleChars = 6;
const start = data.substring(0, visibleChars);
const end = data.substring(data.length - visibleChars);
const maskedLength = Math.min(data.length - visibleChars * 2, 20);
const masked = '•'.repeat(maskedLength);
return `${start}${masked}${end}`;
}
displayResults(verbose = true) {
console.log('\n%c📊 SCAN RESULTS', 'font-size: 18px; font-weight: bold; color: #4ecdc4;');
console.log('%c' + '='.repeat(50), 'color: #4ecdc4;');
if (this.findings.length === 0) {
console.log('%c✅ No hardcoded secrets detected!', 'color: #2ed573; font-weight: bold; font-size: 16px;');
if (this.falsePositives.size > 0) {
console.log(`%c🔍 Filtered ${this.falsePositives.size} false positives`, 'color: #95a5a6;');
}
return;
}
const grouped = this.findings.reduce((acc, finding) => {
const severity = finding.severity.split(' ')[1];
if (!acc[severity]) acc[severity] = [];
acc[severity].push(finding);
return acc;
}, {});
const severityOrder = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFO'];
severityOrder.forEach(level => {
if (grouped[level]) {
console.log(`\n%c${grouped[level][0].severity} FINDINGS (${grouped[level].length})`,
`color: ${this.getSeverityColor(level)}; font-weight: bold; font-size: 16px;`);
console.log('%c' + '-'.repeat(50), `color: ${this.getSeverityColor(level)};`);