@crawlith/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/analysis/analyze.d.ts +70 -0
- package/dist/analysis/analyze.js +436 -0
- package/dist/analysis/content.d.ts +12 -0
- package/dist/analysis/content.js +33 -0
- package/dist/analysis/images.d.ts +6 -0
- package/dist/analysis/images.js +18 -0
- package/dist/analysis/links.d.ts +7 -0
- package/dist/analysis/links.js +30 -0
- package/dist/analysis/scoring.d.ts +9 -0
- package/dist/analysis/scoring.js +42 -0
- package/dist/analysis/seo.d.ts +15 -0
- package/dist/analysis/seo.js +64 -0
- package/dist/analysis/structuredData.d.ts +6 -0
- package/dist/analysis/structuredData.js +51 -0
- package/dist/audit/dns.d.ts +2 -0
- package/dist/audit/dns.js +42 -0
- package/dist/audit/headers.d.ts +2 -0
- package/dist/audit/headers.js +95 -0
- package/dist/audit/index.d.ts +2 -0
- package/dist/audit/index.js +50 -0
- package/dist/audit/scoring.d.ts +14 -0
- package/dist/audit/scoring.js +214 -0
- package/dist/audit/transport.d.ts +6 -0
- package/dist/audit/transport.js +207 -0
- package/dist/audit/types.d.ts +88 -0
- package/dist/audit/types.js +1 -0
- package/dist/core/network/proxyAdapter.d.ts +6 -0
- package/dist/core/network/proxyAdapter.js +19 -0
- package/dist/core/network/rateLimiter.d.ts +6 -0
- package/dist/core/network/rateLimiter.js +31 -0
- package/dist/core/network/redirectController.d.ts +13 -0
- package/dist/core/network/redirectController.js +41 -0
- package/dist/core/network/responseLimiter.d.ts +4 -0
- package/dist/core/network/responseLimiter.js +26 -0
- package/dist/core/network/retryPolicy.d.ts +10 -0
- package/dist/core/network/retryPolicy.js +41 -0
- package/dist/core/scope/domainFilter.d.ts +11 -0
- package/dist/core/scope/domainFilter.js +40 -0
- package/dist/core/scope/scopeManager.d.ts +14 -0
- package/dist/core/scope/scopeManager.js +39 -0
- package/dist/core/scope/subdomainPolicy.d.ts +6 -0
- package/dist/core/scope/subdomainPolicy.js +35 -0
- package/dist/core/security/ipGuard.d.ts +11 -0
- package/dist/core/security/ipGuard.js +84 -0
- package/dist/crawler/crawl.d.ts +22 -0
- package/dist/crawler/crawl.js +336 -0
- package/dist/crawler/extract.d.ts +5 -0
- package/dist/crawler/extract.js +33 -0
- package/dist/crawler/fetcher.d.ts +40 -0
- package/dist/crawler/fetcher.js +161 -0
- package/dist/crawler/metricsRunner.d.ts +1 -0
- package/dist/crawler/metricsRunner.js +108 -0
- package/dist/crawler/normalize.d.ts +7 -0
- package/dist/crawler/normalize.js +88 -0
- package/dist/crawler/parser.d.ts +22 -0
- package/dist/crawler/parser.js +158 -0
- package/dist/crawler/sitemap.d.ts +8 -0
- package/dist/crawler/sitemap.js +70 -0
- package/dist/crawler/trap.d.ts +24 -0
- package/dist/crawler/trap.js +78 -0
- package/dist/db/graphLoader.d.ts +2 -0
- package/dist/db/graphLoader.js +96 -0
- package/dist/db/index.d.ts +4 -0
- package/dist/db/index.js +61 -0
- package/dist/db/repositories/EdgeRepository.d.ts +16 -0
- package/dist/db/repositories/EdgeRepository.js +17 -0
- package/dist/db/repositories/MetricsRepository.d.ts +26 -0
- package/dist/db/repositories/MetricsRepository.js +27 -0
- package/dist/db/repositories/PageRepository.d.ts +47 -0
- package/dist/db/repositories/PageRepository.js +93 -0
- package/dist/db/repositories/SiteRepository.d.ts +15 -0
- package/dist/db/repositories/SiteRepository.js +22 -0
- package/dist/db/repositories/SnapshotRepository.d.ts +22 -0
- package/dist/db/repositories/SnapshotRepository.js +55 -0
- package/dist/db/schema.d.ts +2 -0
- package/dist/db/schema.js +169 -0
- package/dist/diff/compare.d.ts +26 -0
- package/dist/diff/compare.js +64 -0
- package/dist/graph/cluster.d.ts +6 -0
- package/dist/graph/cluster.js +173 -0
- package/dist/graph/duplicate.d.ts +10 -0
- package/dist/graph/duplicate.js +251 -0
- package/dist/graph/graph.d.ts +103 -0
- package/dist/graph/graph.js +106 -0
- package/dist/graph/metrics.d.ts +29 -0
- package/dist/graph/metrics.js +74 -0
- package/dist/graph/pagerank.d.ts +12 -0
- package/dist/graph/pagerank.js +102 -0
- package/dist/graph/simhash.d.ts +17 -0
- package/dist/graph/simhash.js +56 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +30 -0
- package/dist/lock/hashKey.d.ts +1 -0
- package/dist/lock/hashKey.js +44 -0
- package/dist/lock/lockManager.d.ts +7 -0
- package/dist/lock/lockManager.js +112 -0
- package/dist/lock/pidCheck.d.ts +1 -0
- package/dist/lock/pidCheck.js +14 -0
- package/dist/report/html.d.ts +2 -0
- package/dist/report/html.js +223 -0
- package/dist/report/sitegraphExport.d.ts +3 -0
- package/dist/report/sitegraphExport.js +52 -0
- package/dist/report/sitegraph_template.d.ts +1 -0
- package/dist/report/sitegraph_template.js +630 -0
- package/dist/scoring/hits.d.ts +9 -0
- package/dist/scoring/hits.js +111 -0
- package/dist/scoring/orphanSeverity.d.ts +39 -0
- package/dist/scoring/orphanSeverity.js +125 -0
- package/dist/utils/version.d.ts +2 -0
- package/dist/utils/version.js +15 -0
- package/package.json +33 -0
- package/src/analysis/analyze.ts +548 -0
- package/src/analysis/content.ts +62 -0
- package/src/analysis/images.ts +28 -0
- package/src/analysis/links.ts +41 -0
- package/src/analysis/scoring.ts +59 -0
- package/src/analysis/seo.ts +82 -0
- package/src/analysis/structuredData.ts +62 -0
- package/src/audit/dns.ts +49 -0
- package/src/audit/headers.ts +98 -0
- package/src/audit/index.ts +66 -0
- package/src/audit/scoring.ts +232 -0
- package/src/audit/transport.ts +258 -0
- package/src/audit/types.ts +102 -0
- package/src/core/network/proxyAdapter.ts +21 -0
- package/src/core/network/rateLimiter.ts +39 -0
- package/src/core/network/redirectController.ts +47 -0
- package/src/core/network/responseLimiter.ts +34 -0
- package/src/core/network/retryPolicy.ts +57 -0
- package/src/core/scope/domainFilter.ts +45 -0
- package/src/core/scope/scopeManager.ts +52 -0
- package/src/core/scope/subdomainPolicy.ts +39 -0
- package/src/core/security/ipGuard.ts +92 -0
- package/src/crawler/crawl.ts +382 -0
- package/src/crawler/extract.ts +34 -0
- package/src/crawler/fetcher.ts +233 -0
- package/src/crawler/metricsRunner.ts +124 -0
- package/src/crawler/normalize.ts +108 -0
- package/src/crawler/parser.ts +190 -0
- package/src/crawler/sitemap.ts +73 -0
- package/src/crawler/trap.ts +96 -0
- package/src/db/graphLoader.ts +105 -0
- package/src/db/index.ts +70 -0
- package/src/db/repositories/EdgeRepository.ts +29 -0
- package/src/db/repositories/MetricsRepository.ts +49 -0
- package/src/db/repositories/PageRepository.ts +128 -0
- package/src/db/repositories/SiteRepository.ts +32 -0
- package/src/db/repositories/SnapshotRepository.ts +74 -0
- package/src/db/schema.ts +177 -0
- package/src/diff/compare.ts +84 -0
- package/src/graph/cluster.ts +192 -0
- package/src/graph/duplicate.ts +286 -0
- package/src/graph/graph.ts +172 -0
- package/src/graph/metrics.ts +110 -0
- package/src/graph/pagerank.ts +125 -0
- package/src/graph/simhash.ts +61 -0
- package/src/index.ts +30 -0
- package/src/lock/hashKey.ts +51 -0
- package/src/lock/lockManager.ts +124 -0
- package/src/lock/pidCheck.ts +13 -0
- package/src/report/html.ts +227 -0
- package/src/report/sitegraphExport.ts +58 -0
- package/src/report/sitegraph_template.ts +630 -0
- package/src/scoring/hits.ts +131 -0
- package/src/scoring/orphanSeverity.ts +176 -0
- package/src/utils/version.ts +18 -0
- package/tests/__snapshots__/orphanSeverity.test.ts.snap +49 -0
- package/tests/analysis.unit.test.ts +98 -0
- package/tests/analyze.integration.test.ts +98 -0
- package/tests/audit/dns.test.ts +31 -0
- package/tests/audit/headers.test.ts +45 -0
- package/tests/audit/scoring.test.ts +133 -0
- package/tests/audit/security.test.ts +12 -0
- package/tests/audit/transport.test.ts +112 -0
- package/tests/clustering.test.ts +118 -0
- package/tests/crawler.test.ts +358 -0
- package/tests/db.test.ts +159 -0
- package/tests/diff.test.ts +67 -0
- package/tests/duplicate.test.ts +110 -0
- package/tests/fetcher.test.ts +106 -0
- package/tests/fetcher_safety.test.ts +85 -0
- package/tests/fixtures/analyze-crawl.json +26 -0
- package/tests/hits.test.ts +134 -0
- package/tests/html_report.test.ts +58 -0
- package/tests/lock/lockManager.test.ts +138 -0
- package/tests/metrics.test.ts +196 -0
- package/tests/normalize.test.ts +101 -0
- package/tests/orphanSeverity.test.ts +160 -0
- package/tests/pagerank.test.ts +98 -0
- package/tests/parser.test.ts +117 -0
- package/tests/proxy_safety.test.ts +57 -0
- package/tests/redirect_safety.test.ts +73 -0
- package/tests/safety.test.ts +114 -0
- package/tests/scope.test.ts +66 -0
- package/tests/scoring.test.ts +59 -0
- package/tests/sitemap.test.ts +88 -0
- package/tests/soft404.test.ts +41 -0
- package/tests/trap.test.ts +39 -0
- package/tests/visualization_data.test.ts +46 -0
- package/tsconfig.json +11 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Metrics } from '../graph/metrics.js';
|
|
2
|
+
import type { PageAnalysis } from './analyze.js';
|
|
3
|
+
|
|
4
|
+
export interface SiteScore {
|
|
5
|
+
seoHealthScore: number;
|
|
6
|
+
authorityEntropyOrphanScore: number;
|
|
7
|
+
overallScore: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function scorePageSeo(page: PageAnalysis): number {
|
|
11
|
+
const titleMeta = (scoreTextStatus(page.title.status) + scoreTextStatus(page.metaDescription.status)) / 2;
|
|
12
|
+
const h1 = page.h1.status === 'ok' ? 100 : page.h1.status === 'warning' ? 60 : 10;
|
|
13
|
+
const wordQuality = Math.min(100, (page.content.wordCount / 600) * 100) * 0.7 + Math.min(100, page.content.textHtmlRatio * 500) * 0.3;
|
|
14
|
+
const thin = 100 - page.thinScore;
|
|
15
|
+
const imageDen = Math.max(1, page.images.totalImages);
|
|
16
|
+
const imageAlt = Math.max(0, 100 - ((page.images.missingAlt + page.images.emptyAlt) / imageDen) * 100);
|
|
17
|
+
const structured = page.structuredData.present ? (page.structuredData.valid ? 100 : 40) : 30;
|
|
18
|
+
const linkBalance = Math.max(0, 100 - Math.abs(page.links.externalRatio - 0.3) * 200);
|
|
19
|
+
|
|
20
|
+
const score =
|
|
21
|
+
titleMeta * 0.15 +
|
|
22
|
+
h1 * 0.1 +
|
|
23
|
+
wordQuality * 0.2 +
|
|
24
|
+
thin * 0.2 +
|
|
25
|
+
imageAlt * 0.1 +
|
|
26
|
+
structured * 0.1 +
|
|
27
|
+
linkBalance * 0.15;
|
|
28
|
+
|
|
29
|
+
return Number(Math.max(0, Math.min(100, score)).toFixed(2));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function scoreTextStatus(status: PageAnalysis['title']['status']): number {
|
|
33
|
+
switch (status) {
|
|
34
|
+
case 'ok': return 100;
|
|
35
|
+
case 'duplicate': return 45;
|
|
36
|
+
case 'too_short': return 60;
|
|
37
|
+
case 'too_long': return 60;
|
|
38
|
+
case 'missing': return 0;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function aggregateSiteScore(metrics: Metrics, pages: PageAnalysis[]): SiteScore {
|
|
43
|
+
const seoHealthScore = pages.length === 0 ? 0 : pages.reduce((acc, page) => acc + page.seoScore, 0) / pages.length;
|
|
44
|
+
|
|
45
|
+
const avgAuthority = metrics.topAuthorityPages.length === 0
|
|
46
|
+
? 0
|
|
47
|
+
: metrics.topAuthorityPages.reduce((acc, item) => acc + item.authority, 0) / metrics.topAuthorityPages.length;
|
|
48
|
+
const entropyScore = Math.max(0, 100 - Math.abs(metrics.structuralEntropy - 2) * 25);
|
|
49
|
+
const orphanPenalty = metrics.totalPages === 0 ? 0 : (metrics.orphanPages.length / metrics.totalPages) * 100;
|
|
50
|
+
const authorityEntropyOrphanScore = Math.max(0, Math.min(100, (avgAuthority * 100 * 0.4) + (entropyScore * 0.35) + ((100 - orphanPenalty) * 0.25)));
|
|
51
|
+
|
|
52
|
+
const overallScore = Number((seoHealthScore * 0.7 + authorityEntropyOrphanScore * 0.3).toFixed(2));
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
seoHealthScore: Number(seoHealthScore.toFixed(2)),
|
|
56
|
+
authorityEntropyOrphanScore: Number(authorityEntropyOrphanScore.toFixed(2)),
|
|
57
|
+
overallScore
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { load } from 'cheerio';
|
|
2
|
+
|
|
3
|
+
export type SeoStatus = 'ok' | 'missing' | 'too_short' | 'too_long' | 'duplicate';
|
|
4
|
+
|
|
5
|
+
export interface TextFieldAnalysis {
|
|
6
|
+
value: string | null;
|
|
7
|
+
length: number;
|
|
8
|
+
status: SeoStatus;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface H1Analysis {
|
|
12
|
+
count: number;
|
|
13
|
+
status: 'ok' | 'critical' | 'warning';
|
|
14
|
+
matchesTitle: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function normalizedText(value: string | null): string {
|
|
18
|
+
return (value ?? '').trim().toLowerCase();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function analyzeTitle(html: string): TextFieldAnalysis {
|
|
22
|
+
const $ = load(html);
|
|
23
|
+
const title = $('title').first().text().trim();
|
|
24
|
+
if (!title) {
|
|
25
|
+
return { value: null, length: 0, status: 'missing' };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (title.length < 50) return { value: title, length: title.length, status: 'too_short' };
|
|
29
|
+
if (title.length > 60) return { value: title, length: title.length, status: 'too_long' };
|
|
30
|
+
return { value: title, length: title.length, status: 'ok' };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function analyzeMetaDescription(html: string): TextFieldAnalysis {
|
|
34
|
+
const $ = load(html);
|
|
35
|
+
const raw = $('meta[name="description"]').attr('content');
|
|
36
|
+
if (raw === undefined) {
|
|
37
|
+
return { value: null, length: 0, status: 'missing' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const description = raw.trim();
|
|
41
|
+
if (!description) {
|
|
42
|
+
return { value: '', length: 0, status: 'missing' };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (description.length < 140) return { value: description, length: description.length, status: 'too_short' };
|
|
46
|
+
if (description.length > 160) return { value: description, length: description.length, status: 'too_long' };
|
|
47
|
+
return { value: description, length: description.length, status: 'ok' };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function applyDuplicateStatuses<T extends TextFieldAnalysis>(fields: T[]): T[] {
|
|
51
|
+
const counts = new Map<string, number>();
|
|
52
|
+
for (const field of fields) {
|
|
53
|
+
const key = normalizedText(field.value);
|
|
54
|
+
if (!key) continue;
|
|
55
|
+
counts.set(key, (counts.get(key) || 0) + 1);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return fields.map((field) => {
|
|
59
|
+
const key = normalizedText(field.value);
|
|
60
|
+
if (!key) return field;
|
|
61
|
+
if ((counts.get(key) || 0) > 1) {
|
|
62
|
+
return { ...field, status: 'duplicate' };
|
|
63
|
+
}
|
|
64
|
+
return field;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function analyzeH1(html: string, titleValue: string | null): H1Analysis {
|
|
69
|
+
const $ = load(html);
|
|
70
|
+
const h1Values = $('h1').toArray().map((el) => $(el).text().trim()).filter(Boolean);
|
|
71
|
+
const count = h1Values.length;
|
|
72
|
+
const first = h1Values[0] || null;
|
|
73
|
+
const matchesTitle = Boolean(first && titleValue && normalizedText(first) === normalizedText(titleValue));
|
|
74
|
+
|
|
75
|
+
if (count === 0) {
|
|
76
|
+
return { count, status: 'critical', matchesTitle };
|
|
77
|
+
}
|
|
78
|
+
if (count > 1) {
|
|
79
|
+
return { count, status: 'warning', matchesTitle };
|
|
80
|
+
}
|
|
81
|
+
return { count, status: 'ok', matchesTitle };
|
|
82
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { load } from 'cheerio';
|
|
2
|
+
|
|
3
|
+
export interface StructuredDataResult {
|
|
4
|
+
present: boolean;
|
|
5
|
+
types: string[];
|
|
6
|
+
valid: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function analyzeStructuredData(html: string): StructuredDataResult {
|
|
10
|
+
const $ = load(html);
|
|
11
|
+
const scripts = $('script[type="application/ld+json"]').toArray();
|
|
12
|
+
if (scripts.length === 0) {
|
|
13
|
+
return { present: false, types: [], valid: false };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const types = new Set<string>();
|
|
17
|
+
let valid = true;
|
|
18
|
+
|
|
19
|
+
for (const script of scripts) {
|
|
20
|
+
const raw = $(script).text().trim();
|
|
21
|
+
if (!raw) {
|
|
22
|
+
valid = false;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
const parsed = JSON.parse(raw);
|
|
28
|
+
extractTypes(parsed, types);
|
|
29
|
+
} catch {
|
|
30
|
+
valid = false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
present: true,
|
|
36
|
+
valid,
|
|
37
|
+
types: Array.from(types)
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function extractTypes(input: unknown, types: Set<string>): void {
|
|
42
|
+
if (Array.isArray(input)) {
|
|
43
|
+
input.forEach((item) => extractTypes(item, types));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (!input || typeof input !== 'object') return;
|
|
48
|
+
|
|
49
|
+
const maybeType = (input as Record<string, unknown>)['@type'];
|
|
50
|
+
if (typeof maybeType === 'string') {
|
|
51
|
+
types.add(maybeType);
|
|
52
|
+
} else if (Array.isArray(maybeType)) {
|
|
53
|
+
for (const item of maybeType) {
|
|
54
|
+
if (typeof item === 'string') types.add(item);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const graph = (input as Record<string, unknown>)['@graph'];
|
|
59
|
+
if (Array.isArray(graph)) {
|
|
60
|
+
graph.forEach((item) => extractTypes(item, types));
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/audit/dns.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import dns from 'node:dns/promises';
|
|
2
|
+
import { DnsDiagnostics } from './types.js';
|
|
3
|
+
|
|
4
|
+
export async function resolveDns(hostname: string): Promise<DnsDiagnostics> {
|
|
5
|
+
const start = performance.now();
|
|
6
|
+
|
|
7
|
+
const result: DnsDiagnostics = {
|
|
8
|
+
a: [],
|
|
9
|
+
aaaa: [],
|
|
10
|
+
cname: [],
|
|
11
|
+
reverse: [],
|
|
12
|
+
ipCount: 0,
|
|
13
|
+
ipv6Support: false,
|
|
14
|
+
resolutionTime: 0
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
// We run these in parallel
|
|
19
|
+
const [a, aaaa, cname] = await Promise.all([
|
|
20
|
+
dns.resolve4(hostname).catch(() => [] as string[]),
|
|
21
|
+
dns.resolve6(hostname).catch(() => [] as string[]),
|
|
22
|
+
dns.resolveCname(hostname).catch(() => [] as string[])
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
result.a = a;
|
|
26
|
+
result.aaaa = aaaa;
|
|
27
|
+
result.cname = cname;
|
|
28
|
+
result.ipCount = a.length + aaaa.length;
|
|
29
|
+
result.ipv6Support = aaaa.length > 0;
|
|
30
|
+
|
|
31
|
+
// Try reverse lookup on first IP if available
|
|
32
|
+
const ipToReverse = a.length > 0 ? a[0] : (aaaa.length > 0 ? aaaa[0] : null);
|
|
33
|
+
|
|
34
|
+
if (ipToReverse) {
|
|
35
|
+
try {
|
|
36
|
+
result.reverse = await dns.reverse(ipToReverse);
|
|
37
|
+
} catch {
|
|
38
|
+
// Reverse lookup failed, ignore
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
} catch (_error) {
|
|
43
|
+
// DNS resolution failed entirely or other error
|
|
44
|
+
// We return empty result but with time measured
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
result.resolutionTime = performance.now() - start;
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { SecurityHeadersResult, HeaderStatus } from './types.js';
|
|
2
|
+
|
|
3
|
+
export function analyzeHeaders(headers: Record<string, string | string[] | undefined>): SecurityHeadersResult {
|
|
4
|
+
const normalized: Record<string, string> = {};
|
|
5
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
6
|
+
if (typeof value === 'string') {
|
|
7
|
+
normalized[key.toLowerCase()] = value;
|
|
8
|
+
} else if (Array.isArray(value)) {
|
|
9
|
+
normalized[key.toLowerCase()] = value.join(', ');
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const result: SecurityHeadersResult = {
|
|
14
|
+
strictTransportSecurity: checkHSTS(normalized['strict-transport-security']),
|
|
15
|
+
contentSecurityPolicy: checkCSP(normalized['content-security-policy']),
|
|
16
|
+
xFrameOptions: checkXFrameOptions(normalized['x-frame-options']),
|
|
17
|
+
xContentTypeOptions: checkXContentTypeOptions(normalized['x-content-type-options']),
|
|
18
|
+
referrerPolicy: checkReferrerPolicy(normalized['referrer-policy']),
|
|
19
|
+
permissionsPolicy: checkPermissionsPolicy(normalized['permissions-policy']),
|
|
20
|
+
details: normalized,
|
|
21
|
+
score: 0
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Calculate internal score (0-100) based on presence and validity
|
|
25
|
+
let score = 0;
|
|
26
|
+
const weights = {
|
|
27
|
+
hsts: 30,
|
|
28
|
+
csp: 25,
|
|
29
|
+
xframe: 15,
|
|
30
|
+
xcontent: 15,
|
|
31
|
+
referrer: 10,
|
|
32
|
+
permissions: 5
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
if (result.strictTransportSecurity.valid) score += weights.hsts;
|
|
36
|
+
if (result.contentSecurityPolicy.valid) score += weights.csp;
|
|
37
|
+
if (result.xFrameOptions.valid) score += weights.xframe;
|
|
38
|
+
if (result.xContentTypeOptions.valid) score += weights.xcontent;
|
|
39
|
+
if (result.referrerPolicy.valid) score += weights.referrer;
|
|
40
|
+
if (result.permissionsPolicy.valid) score += weights.permissions;
|
|
41
|
+
|
|
42
|
+
result.score = score;
|
|
43
|
+
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function checkHSTS(value: string | undefined): HeaderStatus {
|
|
48
|
+
if (!value) return { present: false, value: null, valid: false, issues: ['Missing HSTS header'] };
|
|
49
|
+
|
|
50
|
+
const valid = value.includes('max-age=');
|
|
51
|
+
const issues: string[] = [];
|
|
52
|
+
if (!valid) issues.push('Missing max-age directive');
|
|
53
|
+
if (!value.includes('includeSubDomains')) issues.push('Missing includeSubDomains');
|
|
54
|
+
|
|
55
|
+
return { present: true, value, valid, issues };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function checkCSP(value: string | undefined): HeaderStatus {
|
|
59
|
+
if (!value) return { present: false, value: null, valid: false, issues: ['Missing CSP header'] };
|
|
60
|
+
|
|
61
|
+
// Basic check: non-empty
|
|
62
|
+
return { present: true, value, valid: value.length > 0, issues: [] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function checkXFrameOptions(value: string | undefined): HeaderStatus {
|
|
66
|
+
if (!value) return { present: false, value: null, valid: false, issues: ['Missing X-Frame-Options'] };
|
|
67
|
+
|
|
68
|
+
const upper = value.toUpperCase();
|
|
69
|
+
const valid = upper === 'DENY' || upper === 'SAMEORIGIN';
|
|
70
|
+
return {
|
|
71
|
+
present: true,
|
|
72
|
+
value,
|
|
73
|
+
valid,
|
|
74
|
+
issues: valid ? [] : [`Invalid value: ${value}`]
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function checkXContentTypeOptions(value: string | undefined): HeaderStatus {
|
|
79
|
+
if (!value) return { present: false, value: null, valid: false, issues: ['Missing X-Content-Type-Options'] };
|
|
80
|
+
|
|
81
|
+
const valid = value.toLowerCase() === 'nosniff';
|
|
82
|
+
return {
|
|
83
|
+
present: true,
|
|
84
|
+
value,
|
|
85
|
+
valid,
|
|
86
|
+
issues: valid ? [] : [`Invalid value: ${value}`]
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function checkReferrerPolicy(value: string | undefined): HeaderStatus {
|
|
91
|
+
if (!value) return { present: false, value: null, valid: false, issues: ['Missing Referrer-Policy'] };
|
|
92
|
+
return { present: true, value, valid: true, issues: [] };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function checkPermissionsPolicy(value: string | undefined): HeaderStatus {
|
|
96
|
+
if (!value) return { present: false, value: null, valid: false, issues: ['Missing Permissions-Policy'] };
|
|
97
|
+
return { present: true, value, valid: true, issues: [] };
|
|
98
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { resolveDns } from './dns.js';
|
|
2
|
+
import { analyzeTransport } from './transport.js';
|
|
3
|
+
import { analyzeHeaders } from './headers.js';
|
|
4
|
+
import { calculateScore } from './scoring.js';
|
|
5
|
+
import { AuditResult, AuditOptions } from './types.js';
|
|
6
|
+
import { URL } from 'node:url';
|
|
7
|
+
import { IPGuard } from '../core/security/ipGuard.js';
|
|
8
|
+
|
|
9
|
+
export async function auditUrl(urlStr: string, options: AuditOptions = {}): Promise<AuditResult> {
|
|
10
|
+
const timeout = options.timeout || 10000;
|
|
11
|
+
|
|
12
|
+
// 1. Basic URL validation
|
|
13
|
+
let url: URL;
|
|
14
|
+
try {
|
|
15
|
+
url = new URL(urlStr);
|
|
16
|
+
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
17
|
+
throw new Error('Only HTTP and HTTPS protocols are supported');
|
|
18
|
+
}
|
|
19
|
+
} catch (error: any) {
|
|
20
|
+
throw new Error(`Invalid URL: ${error.message}`, { cause: error });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// 2. SSRF Guard
|
|
24
|
+
const isSafe = await IPGuard.validateHost(url.hostname);
|
|
25
|
+
if (!isSafe) {
|
|
26
|
+
throw new Error('Access to internal or private infrastructure is prohibited');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// 3. Parallelize DNS and Transport
|
|
30
|
+
// We handle transport errors differently as they are fatal for the audit (e.g. connection refused)
|
|
31
|
+
// DNS errors might return partial results but usually if transport works, DNS worked (unless transport used IP)
|
|
32
|
+
|
|
33
|
+
const dnsPromise = resolveDns(url.hostname);
|
|
34
|
+
const transportPromise = analyzeTransport(urlStr, timeout);
|
|
35
|
+
|
|
36
|
+
const [dnsResult, transportResult] = await Promise.all([
|
|
37
|
+
dnsPromise,
|
|
38
|
+
transportPromise
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
// 3. Analyze Headers
|
|
42
|
+
const headersResult = analyzeHeaders(transportResult.transport.headers);
|
|
43
|
+
|
|
44
|
+
// 4. Calculate Score
|
|
45
|
+
const scoringResult = calculateScore(
|
|
46
|
+
transportResult.transport,
|
|
47
|
+
dnsResult,
|
|
48
|
+
headersResult,
|
|
49
|
+
transportResult.performance,
|
|
50
|
+
transportResult.issues
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
// 5. Build Result
|
|
54
|
+
const result: AuditResult = {
|
|
55
|
+
url: urlStr,
|
|
56
|
+
transport: transportResult.transport,
|
|
57
|
+
securityHeaders: headersResult,
|
|
58
|
+
dns: dnsResult,
|
|
59
|
+
performance: transportResult.performance,
|
|
60
|
+
score: scoringResult.score,
|
|
61
|
+
grade: scoringResult.grade,
|
|
62
|
+
issues: scoringResult.issues
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/* eslint-disable no-useless-assignment */
|
|
2
|
+
import { TransportDiagnostics, DnsDiagnostics, SecurityHeadersResult, PerformanceMetrics, AuditIssue } from './types.js';
|
|
3
|
+
|
|
4
|
+
interface CategoryScores {
|
|
5
|
+
transport: number;
|
|
6
|
+
security: number;
|
|
7
|
+
performance: number;
|
|
8
|
+
infrastructure: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function calculateScore(
|
|
12
|
+
transport: TransportDiagnostics,
|
|
13
|
+
dns: DnsDiagnostics,
|
|
14
|
+
headers: SecurityHeadersResult,
|
|
15
|
+
performance: PerformanceMetrics,
|
|
16
|
+
existingIssues: AuditIssue[]
|
|
17
|
+
): { score: number; grade: 'A' | 'B' | 'C' | 'D' | 'F'; issues: AuditIssue[]; categoryScores: CategoryScores } {
|
|
18
|
+
|
|
19
|
+
const issues: AuditIssue[] = [...existingIssues];
|
|
20
|
+
let transportScore = 0; // Max 30
|
|
21
|
+
let securityScore = 0; // Max 20
|
|
22
|
+
let performanceScore = 0; // Max 30
|
|
23
|
+
let infrastructureScore = 0; // Max 20
|
|
24
|
+
|
|
25
|
+
// 1. Transport Security (30 pts)
|
|
26
|
+
// TLS Version
|
|
27
|
+
if (transport.tlsVersion) {
|
|
28
|
+
const version = parseFloat(transport.tlsVersion.replace('v', '').replace('TLS', '').trim());
|
|
29
|
+
if (version >= 1.2) {
|
|
30
|
+
transportScore += 15;
|
|
31
|
+
} else {
|
|
32
|
+
issues.push({
|
|
33
|
+
id: 'tls-old',
|
|
34
|
+
severity: 'severe',
|
|
35
|
+
category: 'tls',
|
|
36
|
+
message: `Deprecated TLS version: ${transport.tlsVersion}`,
|
|
37
|
+
scorePenalty: 15
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
} else if (transport.certificate) {
|
|
41
|
+
// HTTPS but no version detected? Unlikely.
|
|
42
|
+
} else {
|
|
43
|
+
// HTTP only?
|
|
44
|
+
issues.push({
|
|
45
|
+
id: 'no-https',
|
|
46
|
+
severity: 'critical',
|
|
47
|
+
category: 'tls',
|
|
48
|
+
message: 'Site is not using HTTPS',
|
|
49
|
+
scorePenalty: 30
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Certificate
|
|
54
|
+
if (transport.certificate) {
|
|
55
|
+
if (transport.certificate.isValidChain && !transport.certificate.isSelfSigned) {
|
|
56
|
+
transportScore += 15;
|
|
57
|
+
} else {
|
|
58
|
+
// Already caught in transport.ts, but let's ensure score reflects it
|
|
59
|
+
// If issues has cert-invalid, we don't add points.
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (transport.certificate.daysUntilExpiry < 30 && transport.certificate.daysUntilExpiry >= 0) {
|
|
63
|
+
issues.push({
|
|
64
|
+
id: 'cert-expiring-soon',
|
|
65
|
+
severity: 'moderate',
|
|
66
|
+
category: 'tls',
|
|
67
|
+
message: `Certificate expires in ${transport.certificate.daysUntilExpiry} days`,
|
|
68
|
+
scorePenalty: 5
|
|
69
|
+
});
|
|
70
|
+
// Penalty applied to transport score logic implicitly by not reaching max,
|
|
71
|
+
// but here we are adding up points.
|
|
72
|
+
// Let's deduct from the 15 points we might have given.
|
|
73
|
+
transportScore -= 5;
|
|
74
|
+
} else if (transport.certificate.daysUntilExpiry < 0) {
|
|
75
|
+
issues.push({
|
|
76
|
+
id: 'cert-expired',
|
|
77
|
+
severity: 'critical',
|
|
78
|
+
category: 'tls',
|
|
79
|
+
message: `Certificate expired on ${transport.certificate.validTo}`,
|
|
80
|
+
scorePenalty: 30
|
|
81
|
+
});
|
|
82
|
+
transportScore = 0; // Reset transport score
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 2. Response Security (Headers) (20 pts)
|
|
87
|
+
// headers.score is 0-100. Map to 0-20.
|
|
88
|
+
securityScore = (headers.score / 100) * 20;
|
|
89
|
+
|
|
90
|
+
// Add issues for missing critical headers
|
|
91
|
+
if (!headers.strictTransportSecurity.present) {
|
|
92
|
+
issues.push({
|
|
93
|
+
id: 'hsts-missing',
|
|
94
|
+
severity: 'moderate',
|
|
95
|
+
category: 'headers',
|
|
96
|
+
message: 'Missing Strict-Transport-Security header',
|
|
97
|
+
scorePenalty: 5
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
if (!headers.contentSecurityPolicy.present) {
|
|
101
|
+
issues.push({
|
|
102
|
+
id: 'csp-missing',
|
|
103
|
+
severity: 'moderate',
|
|
104
|
+
category: 'headers',
|
|
105
|
+
message: 'Missing Content-Security-Policy header',
|
|
106
|
+
scorePenalty: 5
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// 3. Performance (30 pts)
|
|
111
|
+
// HTTP/2 (5 pts)
|
|
112
|
+
if (transport.alpnProtocol === 'h2' || transport.httpVersion === '2.0') {
|
|
113
|
+
performanceScore += 5;
|
|
114
|
+
} else {
|
|
115
|
+
issues.push({
|
|
116
|
+
id: 'no-h2',
|
|
117
|
+
severity: 'minor',
|
|
118
|
+
category: 'performance',
|
|
119
|
+
message: 'HTTP/2 not supported',
|
|
120
|
+
scorePenalty: 5
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Compression (5 pts)
|
|
125
|
+
if (transport.compression.length > 0) {
|
|
126
|
+
performanceScore += 5;
|
|
127
|
+
} else {
|
|
128
|
+
issues.push({
|
|
129
|
+
id: 'no-compression',
|
|
130
|
+
severity: 'moderate',
|
|
131
|
+
category: 'performance',
|
|
132
|
+
message: 'No compression enabled (gzip/br)',
|
|
133
|
+
scorePenalty: 5
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// TTFB (10 pts)
|
|
138
|
+
if (performance.ttfb < 800) {
|
|
139
|
+
performanceScore += 10;
|
|
140
|
+
} else {
|
|
141
|
+
issues.push({
|
|
142
|
+
id: 'slow-ttfb',
|
|
143
|
+
severity: 'moderate',
|
|
144
|
+
category: 'performance',
|
|
145
|
+
message: `Slow TTFB: ${performance.ttfb.toFixed(0)}ms`,
|
|
146
|
+
scorePenalty: 10
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Redirects (5 pts)
|
|
151
|
+
if (transport.redirectCount <= 3) {
|
|
152
|
+
performanceScore += 5;
|
|
153
|
+
} else {
|
|
154
|
+
issues.push({
|
|
155
|
+
id: 'too-many-redirects',
|
|
156
|
+
severity: 'moderate',
|
|
157
|
+
category: 'performance',
|
|
158
|
+
message: `Too many redirects: ${transport.redirectCount}`,
|
|
159
|
+
scorePenalty: 5
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// HTML Size (5 pts)
|
|
164
|
+
if (performance.htmlSize < 1024 * 1024) { // 1MB
|
|
165
|
+
performanceScore += 5;
|
|
166
|
+
} else {
|
|
167
|
+
issues.push({
|
|
168
|
+
id: 'large-html',
|
|
169
|
+
severity: 'minor',
|
|
170
|
+
category: 'performance',
|
|
171
|
+
message: `HTML size > 1MB: ${(performance.htmlSize / 1024 / 1024).toFixed(2)}MB`,
|
|
172
|
+
scorePenalty: 5
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 4. Infrastructure (20 pts)
|
|
177
|
+
// IPv6 (10 pts)
|
|
178
|
+
if (dns.ipv6Support) {
|
|
179
|
+
infrastructureScore += 10;
|
|
180
|
+
} else {
|
|
181
|
+
issues.push({
|
|
182
|
+
id: 'no-ipv6',
|
|
183
|
+
severity: 'minor',
|
|
184
|
+
category: 'dns',
|
|
185
|
+
message: 'No IPv6 DNS records found',
|
|
186
|
+
scorePenalty: 5
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Redundancy (10 pts)
|
|
191
|
+
if (dns.ipCount > 1) {
|
|
192
|
+
infrastructureScore += 10;
|
|
193
|
+
} else {
|
|
194
|
+
issues.push({
|
|
195
|
+
id: 'single-ip',
|
|
196
|
+
severity: 'minor',
|
|
197
|
+
category: 'dns',
|
|
198
|
+
message: 'Single IP address detected (no redundancy)',
|
|
199
|
+
scorePenalty: 5
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let totalScore = transportScore + securityScore + performanceScore + infrastructureScore;
|
|
204
|
+
|
|
205
|
+
// Critical Overrides
|
|
206
|
+
const criticalIssues = issues.filter(i => i.severity === 'critical');
|
|
207
|
+
if (criticalIssues.length > 0) {
|
|
208
|
+
totalScore = Math.min(totalScore, 39); // Cap at F (<40)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const grade = getGrade(totalScore);
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
score: Math.round(totalScore),
|
|
215
|
+
grade,
|
|
216
|
+
issues,
|
|
217
|
+
categoryScores: {
|
|
218
|
+
transport: transportScore,
|
|
219
|
+
security: securityScore,
|
|
220
|
+
performance: performanceScore,
|
|
221
|
+
infrastructure: infrastructureScore
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function getGrade(score: number): 'A' | 'B' | 'C' | 'D' | 'F' {
|
|
227
|
+
if (score >= 90) return 'A';
|
|
228
|
+
if (score >= 75) return 'B';
|
|
229
|
+
if (score >= 60) return 'C';
|
|
230
|
+
if (score >= 40) return 'D';
|
|
231
|
+
return 'F';
|
|
232
|
+
}
|