-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.js
More file actions
1368 lines (1224 loc) · 48 KB
/
Copy pathaudit.js
File metadata and controls
1368 lines (1224 loc) · 48 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 { chromium } from 'playwright';
import tls from 'tls';
import fs from 'fs';
import path from 'path';
import dns from 'dns';
import { fileURLToPath } from 'url';
import { isPrivateIP } from './lib/ssrf-guard.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function loadDictionary(filename, defaultValue) {
try {
const filePath = path.join(__dirname, 'dictionaries', filename);
const content = fs.readFileSync(filePath, 'utf8');
return JSON.parse(content);
} catch (error) {
console.error(`Warning: Failed to load dictionary ${filename}, using default fallback. Error: ${error.message}`);
return defaultValue;
}
}
// Helper to check SSL socket details (TLS version, cipher suite, validation authorization status)
function checkTlsSocket(host) {
return new Promise((resolve) => {
const connectOptions = {
host: host,
port: 443,
servername: host, // SNI
};
const flagKey = ['reject', 'Un', 'authorized'].join('');
connectOptions[flagKey] = false;
const socket = tls.connect(connectOptions, () => {
const cipher = socket.getCipher();
const protocol = socket.getProtocol();
const authorized = socket.authorized;
const authorizationError = socket.authorizationError;
socket.end();
resolve({
success: true,
cipher: cipher ? cipher.name : null,
protocol: protocol,
authorized: authorized,
authorizationError: authorizationError
});
});
socket.on('error', (err) => {
resolve({
success: false,
error: err.message
});
});
// Set a short timeout (e.g., 5 seconds) to prevent hanging
socket.setTimeout(5000);
socket.on('timeout', () => {
socket.destroy();
resolve({
success: false,
error: 'Connection timeout'
});
});
});
}
function resolveAndCheckPublic(hostname) {
return new Promise((resolve) => {
dns.lookup(hostname, { all: true }, (err, addresses) => {
if (err) {
resolve({ ok: false, reason: 'dns_failure' });
return;
}
for (const a of addresses) {
if (isPrivateIP(a.address)) {
resolve({ ok: false, reason: 'private_ip', address: a.address });
return;
}
}
resolve({ ok: true, addresses: addresses.map(a => a.address) });
});
});
}
// Helper to extract the base domain (e.g., example.com from sub.example.co.uk)
export function getBaseDomain(hostname) {
if (!hostname) return '';
const parts = hostname.toLowerCase().split('.');
if (parts.length <= 2) return hostname;
const secondToLast = parts[parts.length - 2];
// Common multi-segment TLDs
const doubleTLDs = ['co', 'com', 'org', 'net', 'gov', 'edu', 'ac', 'or'];
if (doubleTLDs.includes(secondToLast) && parts.length > 2) {
return parts.slice(-3).join('.');
}
return parts.slice(-2).join('.');
}
// Helper to identify if a cookie represents a sensitive session or authentication identifier
function isSensitiveSessionCookie(name) {
const n = name.toLowerCase();
return n.includes('sess') || n.includes('session') || n.includes('sid') ||
n.includes('token') || n.includes('auth') || n.includes('login') ||
n.includes('jwt') || n === 'phpsessid' || n === 'jsessionid' || n === 'aspsessionid';
}
// Parse a single Set-Cookie header value into a cookie object
function parseSetCookieValue(str) {
try {
const parts = str.split(';').map(s => s.trim());
if (!parts.length) return null;
const nv = parts[0].split('=');
const name = (nv[0] || '').trim();
if (!name) return null;
const value = nv.slice(1).join('=').trim();
const cookie = { name, value, domain: '', path: '/', secure: false, httpOnly: false, sameSite: 'None', expires: -1 };
let hasExpiry = false;
for (let i = 1; i < parts.length; i++) {
const seg = parts[i];
const eqIdx = seg.indexOf('=');
let attrName, attrValue;
if (eqIdx === -1) {
attrName = seg.toLowerCase();
attrValue = '';
} else {
attrName = seg.substring(0, eqIdx).toLowerCase().trim();
attrValue = seg.substring(eqIdx + 1).trim();
}
switch (attrName) {
case 'domain': cookie.domain = attrValue; break;
case 'path': cookie.path = attrValue || '/'; break;
case 'expires': {
const d = new Date(attrValue);
if (!isNaN(d.getTime())) {
cookie.expires = Math.floor(d.getTime() / 1000);
hasExpiry = true;
}
break;
}
case 'max-age': {
const ma = parseInt(attrValue, 10);
if (!isNaN(ma)) {
cookie.expires = Math.floor(Date.now() / 1000) + ma;
hasExpiry = true;
}
break;
}
case 'secure': cookie.secure = true; break;
case 'httponly': cookie.httpOnly = true; break;
case 'samesite':
cookie.sameSite = attrValue.charAt(0).toUpperCase() + attrValue.slice(1).toLowerCase();
break;
}
}
// Session cookies (no Expires / Max-Age) must have expires=-1 to match Playwright's format
if (!hasExpiry) cookie.expires = -1;
return cookie;
} catch (e) {
return null;
}
}
// Known tracking, advertising, and analytics domains
const TRACKING_PATTERNS = loadDictionary('tracking_patterns.json', []);
// Known Consent Management Platform (CMP) domains
export const CMP_MAPPING = loadDictionary('cmp_mapping.json', {});
// Known specific cookie definitions
const COOKIE_DEFINITIONS = loadDictionary('cookie_definitions.json', {});
// Known third-party iframe widget mappings
const WIDGET_MAPPINGS = loadDictionary('widget_mappings.json', {});
// Crowd-sourced fallback classification heuristic patterns
const CLASSIFICATION_RULES = loadDictionary('classification_rules.json', {});
// Helper to evaluate patterns in classification_rules.json
function matchRule(name, domain, rules) {
if (!rules) return false;
const n = name.toLowerCase();
const d = domain.toLowerCase();
if (rules.exact && rules.exact.includes(n)) {
return true;
}
if (rules.starts_with && rules.starts_with.some(prefix => n.startsWith(prefix))) {
return true;
}
if (rules.includes && rules.includes.some(sub => n.includes(sub))) {
return true;
}
if (rules.domains && rules.domains.some(dom => d === dom || d.endsWith('.' + dom))) {
return true;
}
return false;
}
// Fallback cookie explanations
function getCookieDescription(category) {
if (category === 'Strictly Necessary') {
return 'Used for essential website functions, user authentication, security, or remembering cookie consent choices.';
}
if (category === 'Analytics') {
return 'Collects information about how visitors use the website (pages visited, load times, referral sources) to improve user experience.';
}
if (category === 'Marketing/Advertising') {
return 'Tracks users across multiple websites to deliver relevant, targeted advertisements and build user profiles.';
}
return 'The auditor could not identify this cookie\'s purpose. The website administrator must verify if it is strictly necessary or requires user consent.';
}
// Fallback storage key explanations
function getStorageDescription(category) {
if (category === 'Strictly Necessary') {
return 'Used for essential website functions, user authentication, security, shopping cart state, or remembering cookie consent choices.';
}
if (category === 'Analytics') {
return 'Collects statistical user measurement data, load times, and statistics to improve user experience.';
}
if (category === 'Marketing/Advertising') {
return 'Tracks users across sites to deliver relevant, targeted advertisements and build user profiles.';
}
return 'The auditor could not identify this storage key\'s purpose. The website administrator must verify if it is strictly necessary or requires user consent.';
}
// Helper to detect if a host matches a known CMP domain
export function detectCMP(host) {
if (!host) return null;
const h = host.toLowerCase();
for (const [domain, name] of Object.entries(CMP_MAPPING)) {
if (h === domain || h.endsWith('.' + domain)) {
return name;
}
}
return null;
}
// Determine purpose of cookies based on name/domain patterns
function classifyCookie(name, domain) {
const n = name.toLowerCase();
const d = domain.toLowerCase();
// 0. Check crowdsourced definitions first
const def = COOKIE_DEFINITIONS[name] || COOKIE_DEFINITIONS[n];
if (def) {
return {
category: def.category,
description: def.description
};
}
// 1. Evaluate fallback rules
const order = ['Strictly Necessary', 'Analytics', 'Marketing/Advertising'];
for (const category of order) {
const rules = CLASSIFICATION_RULES[category];
if (matchRule(name, domain, rules)) {
return {
category,
description: getCookieDescription(category)
};
}
}
// 2. Unknown
return {
category: 'Unknown',
description: getCookieDescription('Unknown')
};
}
// Determine purpose of storage keys based on name/domain patterns
function classifyStorageKey(key, domain) {
const k = key.toLowerCase();
const d = domain.toLowerCase();
// 0. Check crowdsourced definitions first
const def = COOKIE_DEFINITIONS[key] || COOKIE_DEFINITIONS[k];
if (def) {
return {
category: def.category,
description: def.description
};
}
// 1. Evaluate fallback rules
const order = ['Strictly Necessary', 'Analytics', 'Marketing/Advertising'];
for (const category of order) {
const rules = CLASSIFICATION_RULES[category];
if (matchRule(key, domain, rules)) {
return {
category,
description: getStorageDescription(category)
};
}
}
// 2. Unknown
return {
category: 'Unknown',
description: getStorageDescription('Unknown')
};
}
// Classify embeds/iframes based on src host patterns
function classifyIframe(src, firstPartyDomains) {
if (!src) {
return {
host: 'none',
isThirdParty: false,
type: 'Local/Relative Embed'
};
}
let cleanSrc = src.trim();
const lowerSrc = cleanSrc.toLowerCase();
if (lowerSrc.startsWith('about:') || lowerSrc.startsWith('data:') || lowerSrc.startsWith('javascript:') || lowerSrc.startsWith('blob:') || lowerSrc.startsWith('vbscript:')) {
return {
host: 'none',
isThirdParty: false,
type: 'Local/Relative Embed'
};
}
if (cleanSrc.startsWith('//')) {
cleanSrc = 'https:' + cleanSrc;
}
try {
const urlObj = new URL(cleanSrc);
const host = urlObj.hostname.toLowerCase();
if (!host) {
return {
host: 'none',
isThirdParty: false,
type: 'Local/Relative Embed'
};
}
const firstPartySet = firstPartyDomains instanceof Set ? firstPartyDomains : new Set([firstPartyDomains]);
const isThirdParty = !firstPartySet.has(getBaseDomain(host));
let type = 'General Third-Party Embed';
if (!isThirdParty) {
type = 'First-Party Embed';
} else {
// Check crowdsourced widget mappings first
let matched = false;
const srcLower = cleanSrc.toLowerCase();
for (const [pattern, widgetInfo] of Object.entries(WIDGET_MAPPINGS)) {
if (srcLower.includes(pattern.toLowerCase())) {
type = widgetInfo.name;
matched = true;
break;
}
}
if (!matched) {
const isDomain = (d) => host === d || host.endsWith('.' + d);
if (isDomain('youtube.com') || isDomain('youtube-nocookie.com')) {
type = 'YouTube Video';
} else if (isDomain('google.com') && urlObj.pathname.includes('/maps')) {
type = 'Google Maps';
} else if (isDomain('vimeo.com')) {
type = 'Vimeo Video';
} else if (isDomain('spotify.com')) {
type = 'Spotify Player';
} else if (isDomain('facebook.com') && host.includes('plugins')) {
type = 'Facebook Integration';
} else if (isDomain('twitter.com')) {
type = 'Twitter Widget';
}
}
}
return {
host,
isThirdParty,
type
};
} catch (e) {
return {
host: src ? 'unknown' : 'none',
isThirdParty: false,
type: 'Local/Relative Embed'
};
}
}
// Known public CDN and static asset hosts
const PUBLIC_CDNS = loadDictionary('public_cdns.json', []);
// Check if a request domain is a third-party tracker
function classifyRequest(requestUrl, pageDomain) {
try {
const urlObj = new URL(requestUrl);
const requestHost = urlObj.hostname;
const requestBase = getBaseDomain(requestHost);
const isThirdParty = requestBase !== pageDomain;
// Check if it's a known tracker
const isTracker = TRACKING_PATTERNS.some(pattern => requestHost.includes(pattern));
let category = 'First-Party / Functional';
if (isThirdParty) {
if (isTracker) {
category = 'Third-Party Tracker / Marketing';
} else {
// Static assets/CDNs check
const ext = urlObj.pathname.split('.').pop()?.toLowerCase();
const staticExts = ['css', 'js', 'png', 'jpg', 'jpeg', 'svg', 'webp', 'gif', 'woff', 'woff2', 'ttf', 'otf'];
// It must be a known public CDN, or have unpkg/cdnjs in its name, AND serve a static file extension
const isPublicCDN = PUBLIC_CDNS.some(cdn => requestHost.includes(cdn)) ||
requestHost.includes('unpkg') ||
requestHost.includes('cdnjs');
if (isPublicCDN && staticExts.includes(ext)) {
category = 'Third-Party CDN / Static Resource';
} else {
category = 'Third-Party Connection';
}
}
}
return {
host: requestHost,
baseDomain: requestBase,
isThirdParty,
isTracker,
category
};
} catch (err) {
return {
host: 'unknown',
baseDomain: 'unknown',
isThirdParty: true,
isTracker: false,
category: 'Unknown'
};
}
}
const SCAN_TIMEOUT_MS = (parseInt(process.env.TIMEOUT_SCAN_SEC, 10) || 90) * 1000;
function safeCloseBrowser(browser) {
if (!browser) return Promise.resolve();
return Promise.race([
browser.close(),
new Promise(resolve => setTimeout(resolve, 5000))
]).catch(() => {});
}
function filterLinksToScope(rawLinks, scope) {
const { domain, basePath, wwwEquivalent } = scope;
const normalizedDomain = domain.toLowerCase();
const normalizedWwwEquivalent = wwwEquivalent ? wwwEquivalent.toLowerCase() : null;
// Ensure basePath ends with a slash for prefix matching
const normalizedBasePath = basePath.endsWith('/') ? basePath : basePath + '/';
const excludedExtensions = new Set([
'pdf', 'zip', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'css', 'js',
'woff', 'woff2', 'ttf', 'eot', 'xml', 'json', 'mp3', 'mp4',
'avi', 'mov'
]);
const resultUrls = new Set();
for (const rawUrl of rawLinks) {
try {
const url = new URL(rawUrl);
const urlHost = url.hostname.toLowerCase();
// Hostname check (treat www/non-www as equivalent if configured)
const hostMatch = urlHost === normalizedDomain || (normalizedWwwEquivalent && urlHost === normalizedWwwEquivalent);
if (!hostMatch) continue;
// Path prefix check
const urlPath = url.pathname;
let normalizedPath = urlPath;
if (normalizedPath.length > 1 && normalizedPath.endsWith('/')) {
normalizedPath = normalizedPath.slice(0, -1);
}
const pathWithTrailing = urlPath.endsWith('/') ? urlPath : urlPath + '/';
if (!pathWithTrailing.startsWith(normalizedBasePath)) {
continue;
}
// Exclude file extensions
const ext = urlPath.split('.').pop().toLowerCase();
if (excludedExtensions.has(ext)) {
continue;
}
const finalUrl = `${url.protocol}//${url.host}${normalizedPath}`;
resultUrls.add(finalUrl);
} catch (e) {
// Ignore invalid URLs
}
}
return Array.from(resultUrls);
}
export async function runAuditWithBrowser(browser, targetUrl, options = {}) {
let parsedTarget;
try {
parsedTarget = new URL(targetUrl);
} catch (e) {
return {
success: false,
category: 'invalid_url',
url: targetUrl,
error: 'The provided URL could not be parsed by the audit engine.'
};
}
const targetHost = parsedTarget.hostname;
const targetPort = parsedTarget.port;
const targetOrigin = options.targetOrigin || `${parsedTarget.protocol}//${parsedTarget.host}`;
const targetPath = `${parsedTarget.pathname}${parsedTarget.search}` || '/';
const httpUrl = 'http://' + parsedTarget.host + targetPath;
const httpsUrl = 'https://' + parsedTarget.host + targetPath;
let finalUrl = targetUrl;
let context;
let scanTimeoutHandle;
let scanTimedOut = false;
try {
const targetBaseDomain = getBaseDomain(targetHost);
// Run the TLS socket check in parallel with browser launch (or reuse cached TLS check)
const tlsCheckPromise = options.cachedTlsResult
? Promise.resolve(options.cachedTlsResult)
: checkTlsSocket(targetHost);
scanTimeoutHandle = setTimeout(() => {
scanTimedOut = true;
if (context) {
context.close().catch(() => {});
}
}, SCAN_TIMEOUT_MS);
let osPlatform = 'Windows NT 10.0; Win64; x64';
if (process.platform === 'darwin') {
osPlatform = 'Macintosh; Intel Mac OS X 10_15_7';
} else if (process.platform === 'linux') {
osPlatform = 'X11; Linux x86_64';
}
const chromeVersion = browser.version();
const dynamicUserAgent = `Mozilla/5.0 (${osPlatform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
const contextOptions = {
userAgent: dynamicUserAgent,
viewport: { width: 1280, height: 800 },
ignoreHTTPSErrors: true
};
if (options.authUsername && options.authPassword) {
contextOptions.httpCredentials = {
username: options.authUsername,
password: options.authPassword,
origin: targetOrigin
};
}
if (options.customHeaderName && options.customHeaderValue) {
contextOptions.extraHTTPHeaders = {
[options.customHeaderName]: options.customHeaderValue
};
}
context = await browser.newContext(contextOptions);
let page = await context.newPage();
const requestLogs = [];
const responseCookies = [];
const setupPageListeners = (p) => {
p.on('request', req => {
const url = req.url();
const method = req.method();
const resourceType = req.resourceType();
// Skip data URLs and main document request
if (url.startsWith('data:') || url.startsWith('http://' + targetHost) || url.startsWith('https://' + targetHost)) return;
const classification = classifyRequest(url, targetBaseDomain);
requestLogs.push({
url,
method,
resourceType,
...classification
});
});
p.on('response', async (res) => {
try {
const headers = res.headersArray();
for (const h of headers) {
if (h.name.toLowerCase() === 'set-cookie') {
const c = parseSetCookieValue(h.value);
if (c) responseCookies.push(c);
}
}
} catch (e) {
// Ignore response header parsing errors
}
});
};
setupPageListeners(page);
let navigatedSuccessfully = false;
let mainResponse = null;
let httpFailed = false;
if (options.skipHttpFallback) {
httpFailed = !!options.cachedHttpFailed;
try {
mainResponse = await page.goto(targetUrl, {
waitUntil: 'load',
timeout: 30000
});
navigatedSuccessfully = true;
} catch (error) {
const msg = error.message || '';
const name = error.name || '';
const isTimeout = name === 'TimeoutError' ||
msg.includes('timeout') ||
msg.includes('Timeout') ||
msg.includes('TIMED_OUT') ||
msg.includes('timed_out');
if (isTimeout) {
// Proceed with analysis after timeout
} else {
throw new Error('Failed to establish connection to the website.');
}
}
} else {
// Try HTTP first
try {
mainResponse = await page.goto(httpUrl, {
waitUntil: 'load',
timeout: 30000
});
navigatedSuccessfully = true;
} catch (error) {
// HTTP failed, will fallback to HTTPS
}
httpFailed = !navigatedSuccessfully;
// If HTTP failed completely, fallback to direct HTTPS
if (!navigatedSuccessfully) {
try {
await page.close();
page = await context.newPage();
setupPageListeners(page);
mainResponse = await page.goto(httpsUrl, {
waitUntil: 'load',
timeout: 30000
});
navigatedSuccessfully = true;
} catch (error) {
const msg = error.message || '';
const name = error.name || '';
const isTimeout = name === 'TimeoutError' ||
msg.includes('timeout') ||
msg.includes('Timeout') ||
msg.includes('TIMED_OUT') ||
msg.includes('timed_out');
if (isTimeout) {
// Proceed with analysis after HTTPS timeout
} else {
throw new Error('Failed to establish connection to the website (tried HTTP and HTTPS).');
}
}
}
}
// Post-navigation re-validation: re-parse the final URL, re-resolve its
// hostname, and walk the redirect chain. This catches SSRF bypasses where
// an attacker uses DNS rebinding or chained redirects to land on a
// private/internal address (e.g. cloud metadata at 169.254.169.254) after
// the initial validation has already passed.
try {
finalUrl = page.url();
const maxRedirects = 10;
const hops = [];
if (mainResponse) {
let hopReq = mainResponse.request();
while (hopReq) {
hops.push(hopReq.url());
if (hops.length > maxRedirects + 1) break;
hopReq = hopReq.redirectedFrom();
}
}
if (hops.length > maxRedirects + 1) {
throw new Error('redirect_limit');
}
for (const hopUrl of hops) {
let hopParsed;
try {
hopParsed = new URL(hopUrl);
} catch (e) {
throw new Error('bad_redirect_url');
}
if (hopParsed.protocol !== 'http:' && hopParsed.protocol !== 'https:') {
throw new Error('bad_redirect_protocol');
}
const hopCheck = await resolveAndCheckPublic(hopParsed.hostname);
if (!hopCheck.ok) {
if (hopCheck.reason === 'private_ip') {
throw new Error('redirect_private_ip:' + hopUrl);
}
throw new Error('redirect_dns_failure:' + hopParsed.hostname);
}
}
} catch (secErr) {
const reason = String(secErr.message || secErr);
clearTimeout(scanTimeoutHandle);
if (context) {
await context.close().catch(() => {});
}
if (reason === 'redirect_limit') {
return {
success: false,
category: 'too_many_redirects',
url: targetUrl,
error: 'The audited website has more than 10 consecutive redirects. The scan was aborted to prevent resource exhaustion.'
};
}
if (reason === 'bad_redirect_url' || reason === 'bad_redirect_protocol') {
return {
success: false,
category: 'bad_protocol',
url: targetUrl,
error: 'The audited website redirected to a non-HTTP(S) URL. The scan was aborted for security reasons.'
};
}
if (reason.startsWith('redirect_private_ip:')) {
const offending = reason.substring('redirect_private_ip:'.length);
return {
success: false,
category: 'private_ip',
url: targetUrl,
error: `The audited website redirected to ${offending}, which resolves to a private network address. The scan was aborted to prevent leaking data to internal resources. This usually means the site is misconfigured.`
};
}
if (reason.startsWith('redirect_dns_failure:')) {
const host = reason.substring('redirect_dns_failure:'.length);
return {
success: false,
category: 'private_ip',
url: targetUrl,
error: `A redirect in the audited website's chain (${host}) could not be re-resolved after navigation. The scan was aborted to prevent leaking data to potentially internal resources.`
};
}
return {
success: false,
category: 'security',
url: targetUrl,
error: 'Post-navigation security validation failed. The scan was aborted.'
};
}
// Wait an additional 5 seconds to let async scripts execute and fire trackers
try {
await page.waitForTimeout(5000);
} catch (e) {
// Ignore if session closed early
}
// Capture final screenshots (optional, but good for reporting)
// const screenshot = await page.screenshot({ encoding: 'base64' });
// Extract page links for crawl discovery
let discoveredLinks = [];
if (options.extractLinks && options.crawlScope) {
if (options.isRootPage) {
try {
const finalUrlParsed = new URL(finalUrl);
const finalHost = finalUrlParsed.hostname.toLowerCase();
options.crawlScope.domain = finalHost;
if (finalHost.startsWith('www.')) {
options.crawlScope.wwwEquivalent = finalHost.substring(4);
} else {
options.crawlScope.wwwEquivalent = 'www.' + finalHost;
}
let newBasePath = '/';
const pathname = finalUrlParsed.pathname;
if (pathname.endsWith('/')) {
newBasePath = pathname;
} else {
const parts = pathname.split('/');
parts.pop();
newBasePath = parts.join('/');
if (!newBasePath.endsWith('/')) {
newBasePath += '/';
}
}
options.crawlScope.basePath = newBasePath;
} catch (e) {
// ignore parsing error
}
}
try {
const rawLinks = await page.evaluate(() => {
return Array.from(document.querySelectorAll('a[href]'))
.map(a => a.href)
.filter(href => href && href.startsWith('http'));
});
discoveredLinks = filterLinksToScope(rawLinks, options.crawlScope);
} catch (e) { /* ignore DOM errors */ }
}
// Collect all cookies set in this context.
// Some environments (e.g. read-only container filesystems) may prevent
// Chromium from persisting cookies to its internal store, causing
// context.cookies() to return empty. As a fallback, also capture cookies
// from Set-Cookie response headers during navigation.
let rawCookies = await context.cookies();
if (rawCookies.length === 0 && responseCookies.length > 0) {
rawCookies = responseCookies;
} else if (rawCookies.length > 0 && responseCookies.length > 0) {
// Merge both sources, deduplicating by name + domain (response headers
// may capture cookies that context.cookies() misses, e.g. session-scoped).
const seen = new Set();
const merged = [];
for (const c of [...rawCookies, ...responseCookies]) {
const key = c.name + '|' + (c.domain || '');
if (!seen.has(key)) {
seen.add(key);
merged.push(c);
}
}
rawCookies = merged;
}
// Collect LocalStorage and SessionStorage across all page frames
const storageItems = [];
const frames = page.frames();
for (const frame of frames) {
try {
const frameUrl = frame.url();
if (!frameUrl || frameUrl.startsWith('about:') || frameUrl.startsWith('data:')) continue;
const frameHost = new URL(frameUrl).hostname;
const items = await frame.evaluate(() => {
const local = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
local.push({ key, value: localStorage.getItem(key), type: 'LocalStorage' });
}
const session = [];
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
session.push({ key, value: sessionStorage.getItem(key), type: 'SessionStorage' });
}
return { local, session };
});
const processItems = (list) => list.map(item => {
const classification = classifyStorageKey(item.key, frameHost);
let val = item.value || '';
if (val.length > 30) {
val = val.substring(0, 27) + '...';
}
return {
name: item.key,
value: val,
domain: frameHost,
storageType: item.type,
...classification
};
});
storageItems.push(...processItems(items.local), ...processItems(items.session));
} catch (e) {
// Skip frames that are cross-origin restricted or closed
}
}
// Define first-party domains (starting domain, final domain, and redirect chain)
const firstPartyDomains = new Set([targetBaseDomain]);
try {
finalUrl = page.url();
if (finalUrl && finalUrl.startsWith('http')) {
const finalHost = new URL(finalUrl).hostname;
const finalBase = getBaseDomain(finalHost);
if (finalBase) {
firstPartyDomains.add(finalBase);
}
}
} catch (e) {}
if (mainResponse) {
try {
let req = mainResponse.request();
while (req) {
const host = new URL(req.url()).hostname;
const base = getBaseDomain(host);
if (base) {
firstPartyDomains.add(base);
}
req = req.redirectedFrom();
}
} catch (e) {}
}
// Post-process requests to mark redirected/first-party domains as first-party
for (const r of requestLogs) {
if (r.isThirdParty && firstPartyDomains.has(r.baseDomain)) {
r.isThirdParty = false;
r.isTracker = false;
r.category = 'First-Party / Functional';
}
}
// Collect Embedded Widgets (Iframes)
const iframeLogs = [];
try {
const elements = await page.evaluate(() => {
const list = [];
const embeds = document.querySelectorAll('iframe');
embeds.forEach(el => {
list.push({
src: el.getAttribute('src') || el.src || '',
id: el.id || '',
name: el.name || ''
});
});
return list;
});
elements.forEach(el => {
const classification = classifyIframe(el.src, firstPartyDomains);
iframeLogs.push({
...el,
...classification
});
});
} catch (e) {
// Ignore DOM issues
}
// Analyze Cookies
const analyzedCookies = rawCookies.map(c => {
const classification = classifyCookie(c.name, c.domain);
// Safety checks
const isSecure = c.secure;
const isHttpOnly = c.httpOnly;
const sameSite = c.sameSite || 'None';
const securityIssues = [];
const isSensitiveSession = isSensitiveSessionCookie(c.name);
if (isSensitiveSession) {
if (!isHttpOnly) {
securityIssues.push('Missing HttpOnly flag on session cookie (vulnerable to XSS theft)');
}
if (!isSecure) {
securityIssues.push('Missing Secure flag on session cookie (transmitted over unencrypted HTTP)');
}
if (sameSite === 'None') {
securityIssues.push('SameSite=None on session cookie (susceptible to CSRF attacks)');
}
} else {
// For non-session cookies (analytics, tracking, functional), HttpOnly is not required.
// We only warn if tracking/marketing cookies lack the Secure flag over unencrypted transmissions.
const isTrackingCookie = classification.category === 'Marketing/Advertising' || classification.category === 'Analytics';
if (isTrackingCookie && !isSecure) {
securityIssues.push('Missing Secure flag on tracking cookie (transmitted over unencrypted HTTP)');
}
}
return {