Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
1174 lines (1004 loc) · 47.4 KB
/
Copy pathserver.ts
File metadata and controls
1174 lines (1004 loc) · 47.4 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 express from 'express';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { URL } from 'url';
import { GoogleGenAI } from '@google/genai';
import https from 'https';
// Initialize Gemini
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
}
}
});
// Resolve Vertex AI redirect links to actual URLs
function resolveRedirect(url: string): Promise<string> {
return new Promise((resolve) => {
if (!url.includes('vertexaisearch')) {
return resolve(url);
}
const req = https.get(url, (res) => {
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
resolve(res.headers.location);
} else {
resolve(url);
}
res.resume(); // Consume data to free memory
}).on('error', () => resolve(url));
req.end();
});
}
async function generateContentWithFallback(aiInstance: GoogleGenAI, params: any) {
const modelsToTry = [
'gemini-2.5-flash',
'gemini-2.0-flash',
'gemini-1.5-pro',
'gemini-1.5-flash-8b'
];
let lastError;
for (const model of modelsToTry) {
try {
const result = await aiInstance.models.generateContent({
...params,
model: model
});
return result;
} catch (err: any) {
console.error(`Model ${model} failed in fallback wrapper:`, err.message);
lastError = err;
}
}
throw lastError || new Error('All fallback models failed.');
}
function sanitizeAndDecodeUrl(rawHref: string): string {
if (!rawHref) return '';
let str = String(rawHref).trim();
for (let pass = 0; pass < 10; pass++) {
if (!str.includes('&') && !str.includes('&#')) break;
const prev = str;
str = str
.replace(/"/gi, '"')
.replace(/�*34;/g, '"')
.replace(/'/gi, "'")
.replace(/�*39;/g, "'")
.replace(/</gi, '<')
.replace(/�*60;/g, '<')
.replace(/>/gi, '>')
.replace(/�*62;/g, '>')
.replace(/&/gi, '&');
if (str === prev) break;
}
try {
str = str.replace(/%22/gi, '"').replace(/%27/gi, "'").replace(/%7B/gi, '{').replace(/%7D/gi, '}');
} catch (e) {}
const match = str.match(/^([^"'\s<>{}\[\]\\]+)/);
if (match) str = match[1];
const cutIndices = [
str.indexOf('",'),
str.indexOf('"{'),
str.indexOf('"}'),
str.indexOf(',"'),
str.indexOf('"')
].filter(idx => idx !== -1);
if (cutIndices.length > 0) {
const minCut = Math.min(...cutIndices);
str = str.substring(0, minCut);
}
str = str.replace(/[,;:\\)\]\}&?]+$/, '');
return str.trim();
}
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// Chat Endpoint
app.post('/api/chat', async (req, res) => {
try {
const { history, message, context, deepResearch, expertMode } = req.body;
let systemInstruction = "You are an advanced Web Intelligence and Data Analysis assistant. You provide authentic answers with citations and sources. If the user asks for a list of links, ALWAYS output them in a code block at the very end of your response. While you specialize in analyzing the provided context payload, you are ALSO fully capable of general research, coding, and providing external knowledge. Do not artificially limit your capabilities.";
if (deepResearch) {
systemInstruction += "\n\nDEEP RESEARCH MODE: You have access to Google Search. When asked about 'Antigravity' or 'Google Antigravity', know that this refers to Google's agentic AI framework (often used in AI Studio / Project IDX). Ensure your search queries are highly specific so you don't return results about physical gravity or unrelated Android remote control tutorials. ALWAYS cite your sources using [1], [2] format inline.";
}
if (expertMode) {
systemInstruction += "\n\nEXPERT MODE ACTIVE: Focus specifically on CLI tools, Developer documentation, technical API references, and code logic. Prioritize advanced developer-focused sources over general consumer content or introductory tutorials.";
}
if (context) {
systemInstruction += `\n\nContext for this session (crawled data, URLs, etc.):\n${context}`;
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Intent Extraction Pre-processing (Chain-of-Thought)
if (deepResearch) {
try {
const intentCheck = await generateContentWithFallback(ai, {
contents: [{ role: 'user', parts: [{ text: `Analyze this user request and determine its intent category: "Technical/CLI Guide", "General Research", or "Tool Usage". Request: "${message}"\nOutput ONLY the category name.` }] }]
});
const category = intentCheck.text?.trim() || "General Research";
systemInstruction += `\n\n[SYSTEM DIRECTIVE - CHAIN OF THOUGHT INTENT PRE-EXTRACTION] This user request has been categorized as: ${category}. Ensure your search queries and synthesized response heavily align with this category type to avoid irrelevant results.`;
} catch (e) {
console.error("Intent extraction failed, continuing without it.", e);
}
}
const contents = [];
if (history && history.length > 0) {
for (const msg of history) {
contents.push({ role: msg.role === 'user' ? 'user' : 'model', parts: [{ text: msg.text }] });
}
}
contents.push({ role: 'user', parts: [{ text: message }] });
const modelsToTry = deepResearch ? ["gemini-2.5-flash", "gemini-2.0-flash"] : ["gemini-2.5-flash", "gemini-2.0-flash", "gemini-1.5-pro", "gemini-1.5-flash-8b"];
const tools = deepResearch ? [{ googleSearch: {} }] : undefined;
let success = false;
let lastError: any = null;
for (const modelToUse of modelsToTry) {
try {
const responseStream = await ai.models.generateContentStream({
model: modelToUse,
contents,
config: {
systemInstruction,
temperature: deepResearch ? 0.4 : 0.7,
maxOutputTokens: 8192,
tools: tools as any // Use tools if deepResearch is true
}
});
let hasStarted = false;
res.write(`data: ${JSON.stringify({ type: 'model_used', model: modelToUse, tokens: Math.round(contents.map(c => JSON.stringify(c)).join('').length / 4) })}\n\n`);
let groundingMappingSent = false;
for await (const chunk of responseStream) {
hasStarted = true;
// Handle grounding chunks if present and we haven't sent them yet
const groundingChunks = chunk.candidates?.[0]?.groundingMetadata?.groundingChunks;
if (groundingChunks && groundingChunks.length > 0 && !groundingMappingSent) {
groundingMappingSent = true;
// Resolve all URLs asynchronously without blocking the stream
Promise.all(groundingChunks.map(async (gc, index) => {
if (gc.web?.uri) {
const realUrl = await resolveRedirect(gc.web.uri);
return { index, vertexUrl: gc.web.uri, realUrl, title: gc.web.title };
}
return null;
})).then(resolved => {
const validResolved = resolved.filter(Boolean);
if (validResolved.length > 0) {
res.write(`data: ${JSON.stringify({ type: 'grounding_mapping', mappings: validResolved })}\n\n`);
}
}).catch(err => console.error('Failed to resolve grounding URLs:', err));
}
if (chunk.text) {
res.write(`data: ${JSON.stringify({ text: chunk.text })}\n\n`);
}
}
res.write(`data: ${JSON.stringify({ done: true })}\n\n`);
success = true;
break; // Exit retry loop on success
} catch (e: any) {
lastError = e;
console.error(`Model ${modelToUse} failed:`, e.message);
}
}
if (!success) {
res.write(`data: ${JSON.stringify({ error: lastError?.message || 'All models failed due to rate limits or errors.' })}\n\n`);
}
res.end();
} catch (e: any) {
res.write(`data: ${JSON.stringify({ error: e.message })}\n\n`);
res.end();
}
});
app.get('/api/subdomains', async (req, res) => {
const domain = req.query.domain as string;
if (!domain) return res.status(400).json({ error: 'Domain is required' });
try {
const subdomains = new Set<string>();
// Try crt.sh first
try {
const crtShUrl = `https://crt.sh/?q=%25.${domain}&output=json`;
const response = await axios.get(crtShUrl, { timeout: 10000 });
if (response.data && Array.isArray(response.data)) {
response.data.forEach((entry: any) => {
if (entry.name_value) {
const names = entry.name_value.split('\n');
names.forEach((name: string) => {
name = name.trim().toLowerCase();
if (!name.startsWith('*') && name.endsWith(domain)) {
subdomains.add(name);
}
});
}
});
}
} catch (crtErr: any) {
console.error('crt.sh failed, trying fallback:', crtErr.message);
// Fallback to HackerTarget API
try {
const htUrl = `https://api.hackertarget.com/hostsearch/?q=${domain}`;
const htRes = await axios.get(htUrl, { timeout: 10000 });
if (htRes.data && typeof htRes.data === 'string') {
const lines = htRes.data.split('\n');
lines.forEach(line => {
const parts = line.split(',');
if (parts.length > 0 && parts[0].endsWith(domain)) {
subdomains.add(parts[0].trim().toLowerCase());
}
});
}
} catch(htErr: any) {
console.error('HackerTarget failed too:', htErr.message);
}
}
return res.json({ subdomains: Array.from(subdomains) });
} catch (error: any) {
console.error('Subdomain discovery error:', error.message);
return res.status(500).json({ error: 'Failed to discover subdomains' });
}
});
// SSE endpoint for crawling
app.get('/api/crawl', async (req, res) => {
const targetUrl = req.query.url as string;
const mode = req.query.mode as 'single' | 'subdir' | 'domain';
const maxPages = parseInt(req.query.maxPages as string) || 50;
const maxDepth = parseInt(req.query.maxDepth as string) || 3;
const maxBreadth = parseInt(req.query.maxBreadth as string) || 1000;
const extractAll = req.query.extractAll === 'true';
const fuzzPaths = req.query.fuzzPaths === 'true';
const subdomainOnly = req.query.subdomainOnly !== 'false'; // true by default
const fileTypesRaw = (req.query.fileTypes as string) || '';
const fileTypesList = fileTypesRaw.split(',').map(ext => ext.trim().toLowerCase()).filter(Boolean);
const includePatternsRaw = (req.query.includePatterns as string) || '';
const includePatternsList = includePatternsRaw.split(',').map(p => p.trim()).filter(Boolean).map(p => new RegExp(p, 'i'));
const excludePatternsRaw = (req.query.excludePatterns as string) || '';
const excludePatternsList = excludePatternsRaw.split(',').map(p => p.trim()).filter(Boolean).map(p => new RegExp(p, 'i'));
const excludeExtensionsRaw = (req.query.excludeExtensions as string) || '';
const excludeExtensionsList = excludeExtensionsRaw.split(',').map(ext => ext.trim().toLowerCase()).filter(Boolean);
const excludePathsRaw = (req.query.excludePaths as string) || '';
const excludePathsList = excludePathsRaw.split(',').map(p => p.trim()).filter(Boolean);
const keywordFiltersRaw = (req.query.keywordFilters as string) || '';
const keywordFiltersList = keywordFiltersRaw.split(',').map(k => k.trim().toLowerCase()).filter(Boolean);
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
if (!targetUrl) {
res.write(`data: ${JSON.stringify({ error: 'URL is required' })}\n\n`);
return res.end();
}
try {
const parsedStartUrl = new URL(targetUrl);
const startDomain = parsedStartUrl.hostname;
const baseDomain = startDomain.startsWith('www.') ? startDomain.slice(4) : startDomain;
const startPath = parsedStartUrl.pathname;
// Ensure startDomain is treated correctly for subdomain filtering
// If startDomain is app.mpghs.com, and subdomainOnly is false,
// it should theoretically allow www.mpghs.com, mpghs.com etc.
// We will match if it ends with the base domain, but for simplicity we'll just check if it ends with startDomain if not subdomainOnly
const visited = new Set<string>();
const toVisit = [{ url: targetUrl, depth: 0 }];
const foundLinks = new Set<string>();
let pagesCrawled = 0;
let errorsCount = 0;
let isClientConnected = true;
req.on('close', () => {
isClientConnected = false;
});
const heartbeat = setInterval(() => {
if (isClientConnected) {
res.write(':\n\n'); // SSE comment for keep-alive
}
}, 15000);
const sendEvent = (type: string, data: any) => {
if (!isClientConnected) return;
res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
};
const processHref = (href: string, currentUrl: string, source: string, currentDepth: number) => {
if (!href) return;
href = sanitizeAndDecodeUrl(href);
href = href.split('#')[0]; // Remove hash
if (!href) return;
try {
const resolvedUrl = new URL(href, currentUrl);
const normalizedUrl = resolvedUrl.toString();
let isExcluded = false;
if (includePatternsList.length > 0) {
if (!includePatternsList.some(p => p.test(normalizedUrl))) isExcluded = true;
}
if (!isExcluded && excludePatternsList.length > 0) {
if (excludePatternsList.some(p => p.test(normalizedUrl))) isExcluded = true;
}
if (!isExcluded && excludePathsList.length > 0) {
if (excludePathsList.some(p => resolvedUrl.pathname.includes(p))) isExcluded = true;
}
const ext = resolvedUrl.pathname.split('.').pop()?.toLowerCase() || '';
if (!isExcluded && excludeExtensionsList.length > 0) {
if (ext && excludeExtensionsList.includes(ext)) isExcluded = true;
}
if (isExcluded) return;
if (!foundLinks.has(normalizedUrl)) {
let isValid = false;
if (mode === 'single') {
isValid = true;
} else if (mode === 'subdir') {
if (resolvedUrl.hostname === startDomain && resolvedUrl.pathname.startsWith(startPath)) {
isValid = true;
}
} else if (mode === 'domain') {
if (subdomainOnly) {
if (resolvedUrl.hostname === startDomain) isValid = true;
} else {
if (resolvedUrl.hostname === baseDomain || resolvedUrl.hostname.endsWith('.' + baseDomain)) {
isValid = true;
}
}
}
// Apply fileType filter if provided
if (fileTypesList.length > 0) {
if (!ext || !fileTypesList.includes(ext)) {
isValid = false;
}
}
if (isValid) {
foundLinks.add(normalizedUrl);
if (keywordFiltersList.length === 0) {
sendEvent('link', { url: normalizedUrl, source });
}
}
// Decide if we should queue it for visiting
const skipExtensions = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'css', 'js', 'woff', 'woff2', 'ttf', 'ico', 'pdf', 'docx', 'zip', 'mp3', 'mp4'];
if (mode !== 'single' && !visited.has(normalizedUrl) && (!ext || !skipExtensions.includes(ext)) && currentDepth < maxDepth) {
let canCrawl = false;
if (mode === 'subdir' && resolvedUrl.hostname === startDomain && resolvedUrl.pathname.startsWith(startPath)) canCrawl = true;
if (mode === 'domain') {
if (subdomainOnly && resolvedUrl.hostname === startDomain) canCrawl = true;
else if (!subdomainOnly && (resolvedUrl.hostname === baseDomain || resolvedUrl.hostname.endsWith('.' + baseDomain))) canCrawl = true;
}
if (canCrawl && !toVisit.some(item => item.url === normalizedUrl)) {
toVisit.push({ url: normalizedUrl, depth: currentDepth + 1 });
}
}
}
} catch (err) {
// Invalid URL, ignore
}
};
// Check sitemap if domain mode
if (mode === 'domain') {
try {
sendEvent('status', { message: 'Checking robots.txt & sitemap.xml...', log: 'Starting robots/sitemap phase' });
const robotsUrl = new URL('/robots.txt', targetUrl).toString();
const robotsRes = await axios.get(robotsUrl, { timeout: 5000 }).catch(() => null);
let sitemapUrl = new URL('/sitemap.xml', targetUrl).toString();
if (robotsRes && robotsRes.data) {
const sitemapMatch = robotsRes.data.match(/Sitemap:\s*(.+)/i);
if (sitemapMatch) {
sitemapUrl = sitemapMatch[1].trim();
}
if (extractAll) {
const pathRegex = /(?:Allow|Disallow):\s*(\/[^\s]*)/gi;
let match;
while ((match = pathRegex.exec(robotsRes.data)) !== null) {
processHref(match[1], targetUrl, 'robots.txt', 0);
}
}
}
const sitemapRes = await axios.get(sitemapUrl, { timeout: 5000 }).catch(() => null);
if (sitemapRes && sitemapRes.data) {
const $sitemap = cheerio.load(sitemapRes.data, { xmlMode: true });
$sitemap('loc').each((_, el) => {
const loc = $sitemap(el).text();
processHref(loc, targetUrl, 'sitemap', 0);
});
sendEvent('status', { message: `Found ${foundLinks.size} links from sitemap.`, log: 'Sitemap processed successfully' });
}
} catch (e: any) {
errorsCount++;
sendEvent('status', { log: `Sitemap error: ${e.message}` });
}
// Fuzz common paths
if (fuzzPaths) {
const commonPaths = [
'/wp-admin/', '/wp-json/', '/wp-json/wp/v2/', '/wp-json/oembed/1.0/',
'/wp-login.php', '/wp-content/uploads/', '/api/', '/api/v1/',
'/.env', '/.git/config', '/admin', '/dashboard', '/backup'
];
for (const p of commonPaths) {
processHref(p, targetUrl, 'fuzzing_guess', 0);
}
}
}
while (toVisit.length > 0 && pagesCrawled < maxPages && isClientConnected) {
const { url: currentUrl, depth: currentDepth } = toVisit.shift()!;
if (visited.has(currentUrl)) continue;
visited.add(currentUrl);
pagesCrawled++;
sendEvent('status', {
message: `Crawling (${pagesCrawled}/${maxPages}): ${currentUrl}`,
stats: { pagesCrawled, totalLinks: foundLinks.size, errors: errorsCount }
});
try {
const response = await axios.get(currentUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
},
timeout: 8000,
maxRedirects: 5,
validateStatus: () => true
});
const contentTypeRaw = response.headers['content-type'] || '';
const contentType = Array.isArray(contentTypeRaw) ? contentTypeRaw.join(' ') : String(contentTypeRaw);
if (contentType.includes('text/html') || contentType.includes('application/json') || contentType.includes('text/xml') || contentType.includes('application/xml')) {
if (contentType.includes('text/html')) {
let htmlData = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
if (keywordFiltersList.length > 0) {
const pageText = htmlData.toLowerCase();
const hasKeyword = keywordFiltersList.some(kw => pageText.includes(kw));
if (hasKeyword) {
sendEvent('link', { url: currentUrl, source: 'keyword_match' });
}
}
const $ = cheerio.load(htmlData);
let processedLinksCount = 0;
const elements = $('a, link, form, script, img, iframe').toArray();
for (const el of elements) {
if (processedLinksCount >= maxBreadth) {
sendEvent('status', { log: `Reached max breadth (${maxBreadth}) for ${currentUrl}` });
break;
}
const href = $(el).attr('href') || $(el).attr('action') || $(el).attr('src');
if (href) {
processHref(href, currentUrl, el.tagName, currentDepth);
processedLinksCount++;
}
}
} else if (contentType.includes('text/xml') || contentType.includes('application/xml')) {
let xmlData = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
const $sitemap = cheerio.load(xmlData, { xmlMode: true });
$sitemap('loc, link').each((_, el) => {
const loc = $sitemap(el).text();
if (loc) processHref(loc, currentUrl, 'sitemap_xml', currentDepth);
});
}
if (extractAll) {
let rawText = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
rawText = rawText.replace(/\\\//g, '/');
let processedRegexCount = 0;
const domainRegex = new RegExp(`https?://${startDomain.replace(/\./g, '\\.')}[^\\s"'<>\`\\[\\]]+`, 'gi');
const absMatches = rawText.match(domainRegex) || [];
for (const match of absMatches) {
if (processedRegexCount >= maxBreadth) break;
processHref(match, currentUrl, 'deep_regex', currentDepth);
processedRegexCount++;
}
const relRegex = /["'](\/[a-zA-Z0-9_/-][^"'\s<>\`]*?)["']/g;
let relMatch;
while ((relMatch = relRegex.exec(rawText)) !== null) {
if (processedRegexCount >= maxBreadth) break;
processHref(relMatch[1], currentUrl, 'deep_regex', currentDepth);
processedRegexCount++;
}
}
}
} catch (error: any) {
errorsCount++;
sendEvent('status', { log: `Failed to fetch ${currentUrl}: ${error.message}` });
}
if (mode === 'single') break;
}
if (pagesCrawled >= maxPages) {
sendEvent('status', { log: `Crawl stopped: Reached max pages limit (${maxPages}).` });
} else if (toVisit.length === 0 && mode !== 'single') {
sendEvent('status', { log: `Crawl finished: Exhausted all links within depth limit (${maxDepth}).` });
}
sendEvent('done', { total: foundLinks.size, pagesCrawled, errors: errorsCount });
clearInterval(heartbeat);
setTimeout(() => res.end(), 250);
} catch (error: any) {
res.write(`data: ${JSON.stringify({ type: 'error', message: error.message })}\n\n`);
res.end();
}
});
// SSE endpoint for AI Smart Crawler
app.get('/api/smart-crawl', async (req, res) => {
const targetUrl = req.query.url as string;
const instruction = req.query.instruction as string;
const maxPages = parseInt(req.query.maxPages as string) || 20;
const maxDepth = parseInt(req.query.maxDepth as string) || 2;
const includePatternsRaw = (req.query.includePatterns as string) || '';
const includePatternsList = includePatternsRaw.split(',').map(p => p.trim()).filter(Boolean).map(p => new RegExp(p, 'i'));
const excludePatternsRaw = (req.query.excludePatterns as string) || '';
const excludePatternsList = excludePatternsRaw.split(',').map(p => p.trim()).filter(Boolean).map(p => new RegExp(p, 'i'));
const includeDomainsRaw = (req.query.includeDomains as string) || '';
const includeDomainsList = includeDomainsRaw.split(',').map(p => p.trim().toLowerCase()).filter(Boolean);
const excludeExtensionsRaw = (req.query.excludeExtensions as string) || '';
const excludeExtensionsList = excludeExtensionsRaw.split(',').map(ext => ext.trim().toLowerCase()).filter(Boolean);
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
if (!targetUrl || !instruction) {
res.write(`data: ${JSON.stringify({ error: 'URL and Instruction are required' })}\n\n`);
return res.end();
}
try {
const parsedStartUrl = new URL(targetUrl);
const startDomain = parsedStartUrl.hostname;
const visited = new Set<string>();
const toVisit = [{ url: targetUrl, depth: 0 }];
const foundLinks = new Set<string>([targetUrl]);
let pagesCrawled = 0;
let errorsCount = 0;
let isClientConnected = true;
req.on('close', () => {
isClientConnected = false;
});
const heartbeat = setInterval(() => {
if (isClientConnected) {
res.write(':\n\n');
}
}, 15000);
const sendEvent = (type: string, data: any) => {
if (!isClientConnected) return;
res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
};
// Always emit the start URL
sendEvent('link', { url: targetUrl, source: 'seed' });
while (toVisit.length > 0 && pagesCrawled < maxPages) {
if (!isClientConnected) break;
const { url: currentUrl, depth: currentDepth } = toVisit.shift()!;
if (visited.has(currentUrl)) continue;
visited.add(currentUrl);
pagesCrawled++;
sendEvent('status', {
message: `Crawling (${pagesCrawled}/${maxPages}): ${currentUrl}`,
stats: { pagesCrawled, totalLinks: foundLinks.size, errors: errorsCount }
});
try {
const response = await axios.get(currentUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
},
timeout: 8000,
maxRedirects: 5,
validateStatus: () => true
});
const contentType = String(response.headers['content-type'] || '');
if (!contentType.includes('text/html')) continue;
let htmlData = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
const $ = cheerio.load(htmlData);
let pageLinks = new Set<string>();
$('a').each((_, el) => {
let href = $(el).attr('href');
if (href && !href.startsWith('javascript:') && !href.startsWith('mailto:')) {
try {
href = sanitizeAndDecodeUrl(href);
if (!href) return;
const resolvedUrl = new URL(href, currentUrl);
const normalizedUrl = resolvedUrl.toString().split('#')[0];
let allowed = false;
if (includeDomainsList.length > 0) {
allowed = includeDomainsList.some(d => resolvedUrl.hostname === d || resolvedUrl.hostname.endsWith(`.${d}`));
} else {
allowed = resolvedUrl.hostname === startDomain || resolvedUrl.hostname.endsWith(`.${startDomain}`);
}
if (allowed) {
if (includePatternsList.length > 0 && !includePatternsList.some(p => p.test(normalizedUrl))) {
allowed = false;
}
if (excludePatternsList.length > 0 && excludePatternsList.some(p => p.test(normalizedUrl))) {
allowed = false;
}
if (excludeExtensionsList.length > 0) {
const ext = normalizedUrl.split('.').pop()?.toLowerCase() || '';
if (excludeExtensionsList.includes(ext)) {
allowed = false;
}
}
}
if (allowed) {
pageLinks.add(normalizedUrl);
}
} catch(e) {}
}
});
const uniqueLinks = Array.from(pageLinks).filter(link => !visited.has(link) && !foundLinks.has(link));
if (uniqueLinks.length > 0) {
sendEvent('status', { log: `Analyzing ${uniqueLinks.length} links with AI...` });
// Chunk links if there are too many (limit to 150 to save tokens/time)
const linksToAnalyze = uniqueLinks.slice(0, 150);
const prompt = `
You are an intelligent URL filter.
The user's instruction is: "${instruction}"
Current context page: ${currentUrl}
Here is a list of discovered URLs:
${linksToAnalyze.map((l, i) => `${i+1}. ${l}`).join('\n')}
Based ONLY on the URL paths, slugs, and domain names, filter this list and return ONLY the URLs that are highly relevant to the user's instruction.
Return your answer as a valid JSON array of strings. Example: ["https://example.com/about", "https://example.com/contact"]
If none are relevant, return an empty array [].
Do NOT include any markdown formatting, backticks, or explanation. Just the raw JSON array.
`;
try {
let text: string | null = null;
try {
const aiResult = await generateContentWithFallback(ai, {
contents: prompt,
config: {
temperature: 0.1,
responseMimeType: "application/json"
}
});
if (aiResult.text) {
text = aiResult.text;
}
} catch (fallbackErr: any) {
sendEvent('status', { log: `AI filtering failed, falling back to all extracted URLs.` });
}
let filteredUrls: string[] = [];
if (text === null) {
filteredUrls = linksToAnalyze;
} else {
try {
let cleaned = text.replace(/```json\s*/gi, '').replace(/```\s*/g, '').trim();
const firstBracket = cleaned.indexOf('[');
const lastBracket = cleaned.lastIndexOf(']');
if (firstBracket !== -1 && lastBracket !== -1 && lastBracket > firstBracket) {
cleaned = cleaned.substring(firstBracket, lastBracket + 1);
}
filteredUrls = JSON.parse(cleaned);
if (!Array.isArray(filteredUrls)) filteredUrls = linksToAnalyze;
} catch(e) {
filteredUrls = linksToAnalyze;
}
}
if (Array.isArray(filteredUrls)) {
for (const furl of filteredUrls) {
if (!foundLinks.has(furl) && typeof furl === 'string' && furl.startsWith('http')) {
foundLinks.add(furl);
sendEvent('link', { url: furl, source: 'ai_filtered' });
if (currentDepth < maxDepth) {
toVisit.push({ url: furl, depth: currentDepth + 1 });
}
}
}
sendEvent('status', { log: `AI approved ${filteredUrls.length} relevant links.` });
}
} catch(e: any) {
sendEvent('status', { log: `AI filtering error: ${e.message}` });
}
}
} catch (error: any) {
errorsCount++;
sendEvent('status', { log: `Failed to fetch ${currentUrl}: ${error.message}` });
}
}
sendEvent('status', { log: `Smart crawl finished. Analyzed ${pagesCrawled} pages.` });
// Generate AI Summary/Guide
if (foundLinks.size > 0) {
sendEvent('status', { log: `Generating AI guide based on found links...` });
try {
const linksArray = Array.from(foundLinks);
const summaryPrompt = `
The user asked for: "${instruction}"
You have crawled the website and found the following relevant links:
${linksArray.map((l, i) => `${i + 1}. ${l}`).join('\n')}
Based on the user's instruction and these links, write a helpful guideline, suggestion, or tutorial.
IMPORTANT:
- You MUST reference the links in your response using their serial numbers (e.g., [1], [2]).
- Explain when and how to use the information from these links.
- Keep the response professional, well-structured, and easy to read.
- DO NOT list the links again at the end; the system will append the "Source References" section automatically.
`;
const summaryResult = await generateContentWithFallback(ai, {
contents: summaryPrompt,
});
sendEvent('summary', { text: summaryResult.text });
sendEvent('status', { log: `AI guide generated successfully.` });
} catch (e: any) {
sendEvent('status', { log: `Failed to generate AI guide: ${e.message}` });
}
}
sendEvent('done', { total: foundLinks.size, pagesCrawled, errors: errorsCount });
clearInterval(heartbeat);
setTimeout(() => res.end(), 250);
} catch (error: any) {
res.write(`data: ${JSON.stringify({ type: 'error', message: error.message })}\n\n`);
res.end();
}
});
// POST endpoint for one-shot AI filtering of a list of URLs
app.post('/api/smart-filter', async (req, res) => {
const { urls, instruction } = req.body;
if (!Array.isArray(urls) || urls.length === 0) {
return res.status(400).json({ error: 'Array of URLs is required' });
}
if (!instruction) {
return res.status(400).json({ error: 'Instruction is required' });
}
try {
const prompt = `You are a URL filtering AI.
The user has provided a list of URLs and a specific instruction on what they are looking for.
Your task is to analyze the URLs (their paths, domains, and structure) and select ONLY the ones that match the instruction.
User Instruction: "${instruction}"
URLs to analyze:
${urls.map((u, i) => `[${i}] ${u}`).join('\n')}
Return ONLY a valid JSON array of the matching URL strings.
If none are relevant, return an empty array [].
Do NOT include any markdown formatting, backticks, or explanation. Just the raw JSON array.`;
let text: string | null = null;
try {
const aiResult = await generateContentWithFallback(ai, {
contents: prompt,
config: {
temperature: 0.1,
responseMimeType: "application/json"
}
});
if (aiResult.text) {
text = aiResult.text;
}
} catch (fallbackErr: any) {
console.error(`AI filtering failed:`, fallbackErr.message);
}
let filteredUrls: string[] = [];
if (text === null) {
res.json({ urls: urls });
} else {
try {
let cleaned = text.replace(/```json\s*/gi, '').replace(/```\s*/g, '').trim();
const firstBracket = cleaned.indexOf('[');
const lastBracket = cleaned.lastIndexOf(']');
if (firstBracket !== -1 && lastBracket !== -1 && lastBracket > firstBracket) {
cleaned = cleaned.substring(firstBracket, lastBracket + 1);
}
filteredUrls = JSON.parse(cleaned);
res.json({ urls: filteredUrls });
} catch (e) {
res.json({ urls: urls });
}
}
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// SSE endpoint for bulk fetching content from URLs
app.post('/api/fetch-bulk', async (req, res) => {
const { urls, customHeaders = {} } = req.body;
if (!Array.isArray(urls) || urls.length === 0) {
return res.status(400).json({ error: 'Array of URLs is required' });
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
let isClientConnected = true;
res.on('close', () => {
isClientConnected = false;
});
const sendEvent = (type: string, data: any) => {
if (!isClientConnected) return;
res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
};
let processedCount = 0;
const maxConcurrency = 5;
// A helper to process a single URL
const fetchUrl = async (url: string) => {
if (!isClientConnected) return;
try {
const response = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml,application/json,text/plain;q=0.9,*/*;q=0.8',
...customHeaders
},
timeout: 10000,
maxRedirects: 5,
validateStatus: () => true // Allow handling 401/403/404 manually
});
const status = response.status;
if (status === 401 || status === 403) {
sendEvent('auth_required', { url, status });
return;
}
if (status >= 400) {
sendEvent('error', { url, error: `Status ${status}`, success: false });
return;
}
// Determine content type
const rawContentType = response.headers['content-type'] || '';
const contentTypeHeader = Array.isArray(rawContentType) ? rawContentType.join(' ') : String(rawContentType);
let category = 'Unknown';
if (contentTypeHeader.includes('application/json')) category = 'JSON';
else if (contentTypeHeader.includes('text/html') || contentTypeHeader.includes('application/xhtml+xml')) category = 'HTML';
else if (contentTypeHeader.includes('text/css')) category = 'CSS';
else if (contentTypeHeader.includes('application/javascript') || contentTypeHeader.includes('text/javascript')) category = 'JS';
else if (contentTypeHeader.includes('text/xml') || contentTypeHeader.includes('application/xml')) category = 'XML';
else if (contentTypeHeader.includes('text/plain')) category = 'Text';
else category = 'Other';
let content = '';
let isUseless = false;
let uselessReason = '';
if (category === 'JSON') {
const data = response.data;
content = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
if (!data || (typeof data === 'object' && Object.keys(data).length === 0)) {
isUseless = true;
uselessReason = 'Empty JSON';
} else if (data.code === 'rest_no_route' || data.code === 'rest_forbidden' || data.code === 'rest_invalid_param') {
isUseless = true;
uselessReason = 'Error Message JSON';
} else if (data.namespace && data.routes) {
isUseless = true;
uselessReason = 'API Schema/Routes';
}
} else if (category === 'HTML') {
const $ = cheerio.load(response.data);
$('script, style, nav, footer, iframe, noscript').remove();
content = $('body').text().replace(/\s+/g, ' ').trim();
if (!content) content = $.text().replace(/\s+/g, ' ').trim(); // fallback
} else {
// Plain text or XML or others
content = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
}
if (isUseless) {
sendEvent('ignored', { url, reason: uselessReason });
} else if (content && content.length > 0) {
sendEvent('content', { url, content, category, success: true });
} else {