-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathserver.js
More file actions
579 lines (512 loc) · 22.1 KB
/
server.js
File metadata and controls
579 lines (512 loc) · 22.1 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const path = require('path');
const whois = require('node-whois');
const util = require('util');
const { getCorsOptions, originValidationMiddleware } = require('./scripts/cors');
const { generatePWAManifest } = require('./scripts/pwa-manifest-generator');
const app = express();
const PORT = process.env.PORT || 3000;
const SITE_TITLE = process.env.SITE_TITLE || 'DumbWhois';
const PUBLIC_DIR = path.join(__dirname, 'public');
const ASSETS_DIR = path.join(PUBLIC_DIR, 'assets');
// Convert whois.lookup to Promise
const lookupPromise = util.promisify(whois.lookup);
// Trust proxy - required for secure cookies behind a reverse proxy
app.set('trust proxy', 1);
// CORS setup
const corsOptions = getCorsOptions();
app.use(cors(corsOptions));
app.use(express.json());
app.use(originValidationMiddleware);
generatePWAManifest(SITE_TITLE);
app.use(express.static('public'));
// Helper function to detect query type
function detectQueryType(query) {
// Clean up the query - remove brackets if present
const cleanQuery = query.replace(/^\[|\]$/g, '');
// ASN pattern (AS followed by numbers)
if (/^(AS|as)?\d+$/i.test(cleanQuery)) {
return 'asn';
}
// IPv6 pattern (with optional CIDR)
if (/^(?:(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(?:\/\d{1,3})?$/.test(cleanQuery)) {
return 'ip';
}
// IPv4 pattern (with optional CIDR)
if (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/\d{1,2})?$/.test(cleanQuery)) {
return 'ip';
}
// Domain pattern (anything with a dot that's not an IP)
if (cleanQuery.includes('.')) {
return 'whois';
}
return 'unknown';
}
// Helper function to parse WHOIS data
async function parseWhoisData(data, domain) {
// Split into lines and create key-value pairs
const result = {
domainName: domain,
registrar: '',
creationDate: '',
expirationDate: '',
lastUpdated: '',
status: [],
nameservers: [],
ipAddresses: {
v4: [],
v6: []
},
raw: data
};
// Get both IPv4 and IPv6 addresses from DNS lookup
try {
const dns = require('dns').promises;
const [ipv4Addresses, ipv6Addresses] = await Promise.all([
dns.resolve4(domain).catch(() => []),
dns.resolve6(domain).catch(() => [])
]);
result.ipAddresses.v4 = ipv4Addresses;
result.ipAddresses.v6 = ipv6Addresses;
} catch (e) {
// If DNS lookup fails, keep arrays empty
}
// Regular expressions for IP addresses
const ipv4Regex = /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g;
const ipv6Regex = /(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])/g;
// First try to find IPs in specific fields that might contain them
const lines = data.split('\n');
for (const line of lines) {
const trimmedLine = line.trim().toLowerCase();
if (trimmedLine.includes('ip address') ||
trimmedLine.includes('a record') ||
trimmedLine.includes('aaaa record') ||
trimmedLine.includes('addresses') ||
trimmedLine.includes('host') ||
trimmedLine.includes('dns')) {
const ipv4InLine = line.match(ipv4Regex);
const ipv6InLine = line.match(ipv6Regex);
if (ipv4InLine) result.ipAddresses.v4.push(...ipv4InLine);
if (ipv6InLine) result.ipAddresses.v6.push(...ipv6InLine);
}
}
// Remove duplicates
result.ipAddresses.v4 = [...new Set(result.ipAddresses.v4)];
result.ipAddresses.v6 = [...new Set(result.ipAddresses.v6)];
// Special handling for .eu domains
if (domain.toLowerCase().endsWith('.eu')) {
const lines = data.split('\n');
let currentSection = '';
for (const line of lines) {
const trimmedLine = line.trim();
// Skip empty lines and comment lines
if (!trimmedLine || trimmedLine.startsWith('%')) continue;
// Check for section headers
if (trimmedLine.endsWith(':')) {
currentSection = trimmedLine.slice(0, -1).toLowerCase();
continue;
}
// Handle indented lines (section content)
if (line.startsWith(' ')) {
const [key, ...values] = line.trim().split(':').map(s => s.trim());
const value = values.join(':').trim();
switch (currentSection) {
case 'registrar':
if (key === 'Name') {
result.registrar = value;
}
break;
case 'name servers':
if (!key.includes(':') && key !== 'Please visit www.eurid.eu for more info.') {
result.nameservers.push(key);
}
break;
case 'technical':
if (key === 'Organisation' && !result.registrar) {
result.registrar = value;
}
break;
}
} else if (line.includes(':')) {
const [key, ...values] = line.split(':').map(s => s.trim());
const value = values.join(':').trim();
if (key === 'Domain') {
result.domainName = value;
}
}
}
// Add default status for .eu domains if none found
if (result.status.length === 0) {
result.status.push('registered');
}
} else {
// Original parsing logic for non-.eu domains
const lines = data.split('\n');
for (const line of lines) {
const [key, ...values] = line.split(':').map(s => s.trim());
const value = values.join(':').trim();
if (!key || !value) continue;
const keyLower = key.toLowerCase();
// Registrar information
if (keyLower.includes('registrar')) {
result.registrar = value;
}
// Creation date
else if (keyLower.includes('creation') || keyLower.includes('created') ||
keyLower.includes('registered')) {
result.creationDate = value;
}
// Expiration date
else if (keyLower.includes('expir')) {
result.expirationDate = value;
}
// Last updated
else if (keyLower.includes('updated') || keyLower.includes('modified')) {
result.lastUpdated = value;
}
// Status
else if (keyLower.includes('status')) {
const statuses = value.split(/[,;]/).map(s => s.trim());
result.status.push(...statuses);
}
// Nameservers
else if (keyLower.includes('name server') || keyLower.includes('nameserver')) {
const ns = value.split(/[\s,;]+/)[0];
if (ns && !result.nameservers.includes(ns)) {
result.nameservers.push(ns);
}
}
}
}
return result;
}
// IP lookup services with fallbacks
const ipLookupServices = [
{
name: 'ipapi.co',
url: (ip) => `https://ipapi.co/${ip}/json/`,
transform: (data) => ({
...data,
source: 'ipapi.co'
})
},
{
name: 'ip-api.com',
url: (ip) => `http://ip-api.com/json/${ip}`,
transform: (data) => ({
ip: data.query,
version: data.query.includes(':') ? 'IPv6' : 'IPv4',
city: data.city,
region: data.regionName,
region_code: data.region,
country_code: data.countryCode,
country_name: data.country,
postal: data.zip,
latitude: data.lat,
longitude: data.lon,
timezone: data.timezone,
org: data.org || data.isp,
asn: data.as,
source: 'ip-api.com'
})
},
{
name: 'ipwho.is',
url: (ip) => `https://ipwho.is/${ip}`,
transform: (data) => ({
ip: data.ip,
version: data.type,
city: data.city,
region: data.region,
region_code: data.region_code,
country_code: data.country_code,
country_name: data.country,
postal: data.postal,
latitude: data.latitude,
longitude: data.longitude,
timezone: data.timezone.id,
org: data.connection.org,
asn: data.connection.asn,
source: 'ipwho.is'
})
}
];
// Helper function to fetch ASN data from RIPEstat and PeeringDB
async function fetchASNData(asnNumber) {
// RIPEstat whois endpoint provides comprehensive ASN information
// Works for all RIRs: ARIN, RIPE, APNIC, LACNIC, AFRINIC
const whoisUrl = `https://stat.ripe.net/data/whois/data.json?resource=AS${asnNumber}`;
const overviewUrl = `https://stat.ripe.net/data/as-overview/data.json?resource=AS${asnNumber}`;
const peeringDbUrl = `https://www.peeringdb.com/api/net?asn=${asnNumber}`;
// Fetch all endpoints in parallel (PeeringDB is optional, don't fail if unavailable)
const [whoisResponse, overviewResponse, peeringDbResponse] = await Promise.all([
axios.get(whoisUrl),
axios.get(overviewUrl),
axios.get(peeringDbUrl).catch(() => ({ data: { data: [] } }))
]);
const whoisData = whoisResponse.data;
const overviewData = overviewResponse.data;
const peeringDbData = peeringDbResponse.data?.data?.[0] || {};
// Parse WHOIS records to extract relevant fields
const records = whoisData.data?.records || [];
const flatRecords = records.flat();
// Helper to find value by key in WHOIS records (case-insensitive)
const findValue = (key) => {
const record = flatRecords.find(r => r.key?.toLowerCase() === key.toLowerCase());
return record?.value || '';
};
// Helper to find all values by key (case-insensitive)
const findAllValues = (key) => {
return flatRecords
.filter(r => r.key?.toLowerCase() === key.toLowerCase())
.map(r => r.value)
.filter(Boolean);
};
// Determine RIR from source field or authority
const source = findValue('source') || whoisData.data?.authorities?.[0] || '';
const isARIN = source.toUpperCase() === 'ARIN';
// Extract holder info from overview (format: "NAME - Description, CC")
const holder = overviewData.data?.holder || '';
const holderParts = holder.split(' - ');
const name = holderParts[0] || findValue('as-name') || findValue('ASName') || findValue('aut-num');
// Try to extract country code from holder or WHOIS
let countryCode = findValue('country');
if (!countryCode && holder) {
// Try to extract from holder string (e.g., "CLOUDFLARENET - Cloudflare, Inc., US")
const ccMatch = holder.match(/,\s*([A-Z]{2})$/);
if (ccMatch) countryCode = ccMatch[1];
}
// Extract description - ARIN uses OrgName, RIPE uses descr
const descriptions = findAllValues('descr');
const orgName = findValue('OrgName');
const description = descriptions[0] || orgName || (holderParts.length > 1 ? holderParts.slice(1).join(' - ') : '');
// Extract email contacts - handle both RIPE and ARIN formats
let emailContacts = findAllValues('e-mail');
if (emailContacts.length === 0) {
// ARIN format: OrgTechEmail, OrgNOCEmail
const techEmail = findAllValues('OrgTechEmail');
const nocEmail = findAllValues('OrgNOCEmail');
emailContacts = [...new Set([...techEmail, ...nocEmail])];
}
// Fallback to contact handles if no emails found
if (emailContacts.length === 0) {
const techC = findAllValues('tech-c');
const adminC = findAllValues('admin-c');
emailContacts = [...techC, ...adminC];
}
// Extract abuse contacts - handle both RIPE and ARIN formats
let abuseContacts = findAllValues('abuse-mailbox');
if (abuseContacts.length === 0) {
// ARIN format: OrgAbuseEmail
abuseContacts = findAllValues('OrgAbuseEmail');
}
if (abuseContacts.length === 0) {
abuseContacts = findAllValues('abuse-c');
}
// Extract address - handle both RIPE and ARIN formats
const remarks = findAllValues('remarks');
let ownerAddress = findAllValues('address');
if (ownerAddress.length === 0 && isARIN) {
// ARIN uses separate fields: Address, City, StateProv, PostalCode, Country
const streetAddr = findValue('Address');
const city = findValue('City');
const state = findValue('StateProv');
const postal = findValue('PostalCode');
const addrCountry = findValue('Country');
const addrParts = [streetAddr];
if (city || state || postal) {
addrParts.push([city, state, postal].filter(Boolean).join(', '));
}
if (addrCountry) addrParts.push(addrCountry);
ownerAddress = addrParts.filter(Boolean);
}
if (ownerAddress.length === 0) {
ownerAddress = remarks.filter(r => !r.includes('http'));
}
const rirMap = {
'RIPE': 'RIPE NCC',
'ARIN': 'ARIN',
'APNIC': 'APNIC',
'LACNIC': 'LACNIC',
'AFRINIC': 'AFRINIC',
'RADB': 'RADB'
};
const rirName = rirMap[source.toUpperCase()] || source || 'Unknown';
// Extract dates - handle both RIPE and ARIN formats
// ARIN uses RegDate, RIPE uses created
const created = findValue('created') || findValue('RegDate') || findValue('reg-date');
const lastModified = findValue('last-modified') || findValue('Updated') || findValue('changed');
// Extract website - prefer PeeringDB, fallback to WHOIS remarks
const website = peeringDbData.website || remarks.find(r => r.includes('http')) || '';
// Build response in BGPView-compatible format
return {
data: {
asn: parseInt(asnNumber),
name: name,
description_short: description,
country_code: countryCode,
website: website,
email_contacts: emailContacts,
abuse_contacts: abuseContacts.length > 0 ? abuseContacts : emailContacts,
owner_address: ownerAddress,
rir_allocation: {
rir_name: rirName,
date_allocated: created
},
traffic_ratio: peeringDbData.info_ratio || null, // From PeeringDB
date_updated: lastModified
}
};
}
// Helper function to try IP lookup services in sequence
async function tryIpLookup(ip) {
// Remove brackets and CIDR notation for the lookup
const cleanIp = ip.replace(/^\[|\]$/g, '').replace(/\/\d+$/, '');
let lastError = null;
for (const service of ipLookupServices) {
try {
console.log(`Trying IP lookup with ${service.name}...`);
const response = await axios.get(service.url(cleanIp));
// Check if the service returned an error
if (response.data.error) {
throw new Error(response.data.message || 'Service returned error');
}
// Transform the data to our standard format
return service.transform(response.data);
} catch (error) {
console.log(`${service.name} lookup failed:`, error.message);
lastError = error;
// Continue to next service
continue;
}
}
// If we get here, all services failed
throw lastError;
}
// Universal lookup endpoint
app.get('/api/lookup/:query', async (req, res) => {
const query = req.params.query;
const queryType = detectQueryType(query);
try {
let response;
switch (queryType) {
case 'whois':
// Set specific options for WHOIS query
const options = {
follow: 3, // Follow up to 3 redirects
timeout: 10000, // 10 second timeout
};
// Add specific server for .eu domains
if (query.toLowerCase().endsWith('.eu')) {
options.server = 'whois.eu';
}
const whoisData = await lookupPromise(query, options);
const parsedData = await parseWhoisData(whoisData, query);
response = {
data: {
ldhName: parsedData.domainName,
handle: query,
status: parsedData.status,
ipAddresses: parsedData.ipAddresses,
events: [
{
eventAction: 'registration',
eventDate: parsedData.creationDate
},
{
eventAction: 'expiration',
eventDate: parsedData.expirationDate
},
{
eventAction: 'lastChanged',
eventDate: parsedData.lastUpdated
}
],
nameservers: parsedData.nameservers.map(ns => ({ ldhName: ns })),
entities: [{
roles: ['registrar'],
vcardArray: [
"vcard",
[
["version", {}, "text", "4.0"],
["fn", {}, "text", parsedData.registrar],
["email", {}, "text", ""]
]
]
}]
}
};
break;
case 'ip':
const ipData = await tryIpLookup(query);
response = { data: ipData };
break;
case 'asn':
// Remove 'AS' prefix if present
const asnNumber = query.replace(/^(AS|as)/i, '');
const asnData = await fetchASNData(asnNumber);
response = { data: asnData };
break;
default:
return res.status(400).json({
error: 'Invalid input',
message: 'Please enter a valid domain name, IP address, or ASN number'
});
}
res.json({ type: queryType, data: response.data });
} catch (error) {
console.error('Error details:', error);
if (error.response) {
if (error.response.status === 429) {
res.status(429).json({
error: 'Rate limit exceeded',
message: 'All IP lookup services are currently rate limited. Please try again later.'
});
} else if (error.response.status === 404) {
res.status(404).json({ error: `${queryType.toUpperCase()} not found` });
} else {
res.status(error.response.status).json({
error: `Error fetching ${queryType.toUpperCase()} data`,
message: error.response.data?.message || error.message
});
}
} else {
res.status(500).json({
error: `Error fetching ${queryType.toUpperCase()} data`,
message: error.message
});
}
}
});
// Serve the pwa/asset manifest
app.get('/asset-manifest.json', (req, res) => {
// generated in pwa-manifest-generator and fetched from service-worker.js
res.sendFile(path.join(ASSETS_DIR, 'asset-manifest.json'));
});
app.get('/manifest.json', (req, res) => {
res.sendFile(path.join(ASSETS_DIR, 'manifest.json'));
});
app.get('/config', (req, res) => {
res.json({
siteTitle: SITE_TITLE
});
});
app.get('/managers/toast', (req, res) => {
res.sendFile(path.join(PUBLIC_DIR, 'managers', 'toast.js'));
});
app.get('/health', (_req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Server is running on: http://localhost:${PORT}`);
});