-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
415 lines (381 loc) · 18.7 KB
/
server.js
File metadata and controls
415 lines (381 loc) · 18.7 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
require('dotenv').config();
const express = require('express');
const fetch = require('node-fetch');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');
const settings = require('./lib/settings');
const app = express();
const PORT = process.env.PORT || 3008;
app.use(express.json());
// ── SEO 模板渲染: 替换 index.html 中的 SEO 占位符 ──
app.get(['/', '/index.html'], (req, res) => {
const htmlPath = path.join(__dirname, 'public', 'index.html');
fs.readFile(htmlPath, 'utf8', (err, html) => {
if (err) return res.status(500).send('Internal Server Error');
const seo = settings.get().seo || {};
const rendered = html
.replace('{{SEO_TITLE}}', seo.title || 'IP 信息查询系统')
.replace('{{SEO_DESC}}', seo.description || '多数据源 IP 地理位置查询系统')
.replace('{{SEO_KEYWORDS}}', seo.keywords || 'IP查询,IP地址,地理位置,GeoIP');
res.set('Content-Type', 'text/html');
res.send(rendered);
});
});
app.use(express.static(path.join(__dirname, 'public')));
// ═══════════════════════════════════════════
// 管理员 Token 存储 (内存)
// ═══════════════════════════════════════════
const adminTokens = new Map(); // token → { createdAt }
const TOKEN_TTL = 24 * 60 * 60 * 1000; // 24h
function cleanExpiredTokens() {
const now = Date.now();
for (const [t, v] of adminTokens) {
if (now - v.createdAt > TOKEN_TTL) adminTokens.delete(t);
}
}
setInterval(cleanExpiredTokens, 60 * 60 * 1000);
function requireAdmin(req, res, next) {
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: true, message: '未授权' });
}
const token = auth.slice(7);
const entry = adminTokens.get(token);
if (!entry || Date.now() - entry.createdAt > TOKEN_TTL) {
adminTokens.delete(token);
return res.status(401).json({ error: true, message: 'Token 已过期' });
}
next();
}
// ═══════════════════════════════════════════
// API Key 轮询器 (动态从 settings 读取)
// ═══════════════════════════════════════════
function getAbuseKeys() {
return settings.get().apiKeys?.abuseipdb || [];
}
function getIplocateKey() {
return settings.get().apiKeys?.iplocate || '';
}
let abuseKeyIndex = 0;
function nextAbuseKey() {
const keys = getAbuseKeys();
if (!keys.length) return '';
const key = keys[abuseKeyIndex % keys.length];
abuseKeyIndex = (abuseKeyIndex + 1) % keys.length;
return key;
}
// ═══════════════════════════════════════════
// 工具函数
// ═══════════════════════════════════════════
function getClientIP(req) {
let ip = (
req.headers['x-real-ip'] ||
req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
req.connection?.remoteAddress ||
req.ip
);
// Strip IPv4-mapped IPv6 prefix
if (ip && ip.startsWith('::ffff:')) {
ip = ip.substring(7);
}
return ip;
}
function isPrivateIP(ip) {
if (!ip) return true;
// Loopback
if (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost') return true;
// Private IPv4 ranges
if (/^10\./.test(ip)) return true;
if (/^172\.(1[6-9]|2\d|3[01])\./.test(ip)) return true;
if (/^192\.168\./.test(ip)) return true;
// Link-local
if (/^169\.254\./.test(ip)) return true;
return false;
}
async function getPublicIP() {
const services = [
'https://api.ipify.org?format=json',
'https://api.myip.com',
];
for (const url of services) {
try {
const res = await fetch(url, { timeout: 5000 });
if (!res.ok) continue;
const data = await res.json();
return data.ip || null;
} catch { continue; }
}
return null;
}
function isValidIP(ip) {
const ipv4 = /^(\d{1,3}\.){3}\d{1,3}$/;
const ipv6 = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/;
if (ipv4.test(ip)) {
return ip.split('.').every(n => parseInt(n) >= 0 && parseInt(n) <= 255);
}
return ipv6.test(ip);
}
// ═══════════════════════════════════════════
// 数据源1: AbuseIPDB
// ═══════════════════════════════════════════
async function fetchAbuseIPDB(ip) {
const apiKey = nextAbuseKey();
if (!apiKey) return { source: 'AbuseIPDB', success: false, error: 'No API key', data: null };
try {
const s = settings.get();
const baseUrl = s.apiEndpoints?.abuseipdb || 'https://api.abuseipdb.com/api/v2/check';
const res = await fetch(`${baseUrl}?ipAddress=${encodeURIComponent(ip)}&verbose`, {
headers: { 'Key': apiKey, 'Accept': 'application/json' }, timeout: 8000
});
if (!res.ok) throw new Error(`AbuseIPDB HTTP ${res.status}`);
const json = await res.json();
const d = json.data || {};
return {
source: 'AbuseIPDB', success: true,
data: {
ip: d.ipAddress || ip, country: d.countryName || null,
country_code: d.countryCode || null, region: null, city: null,
latitude: null, longitude: null, timezone: null, asn: null,
organization: null, isp: d.isp || null,
hostname: d.hostnames?.[0] || null,
is_vpn: null, is_proxy: null, is_tor: d.isTor || null,
is_threat: d.totalReports > 0, continent: null, postal: null,
domain: d.domain || null, usage_type: d.usageType || null,
abuse_score: d.abuseConfidenceScore || 0,
total_reports: d.totalReports || 0,
is_whitelisted: d.isWhitelisted || false,
}
};
} catch (err) {
return { source: 'AbuseIPDB', success: false, error: err.message, data: null };
}
}
// ═══════════════════════════════════════════
// 数据源2: iplocate.io
// ═══════════════════════════════════════════
async function fetchIplocate(ip) {
const key = getIplocateKey();
if (!key) return { source: 'iplocate', success: false, error: 'No API key', data: null };
try {
const s = settings.get();
const baseUrl = s.apiEndpoints?.iplocate || 'https://iplocate.io/api/lookup';
const url = ip
? `${baseUrl}/${encodeURIComponent(ip)}?apikey=${encodeURIComponent(key)}`
: `${baseUrl}?apikey=${encodeURIComponent(key)}`;
const res = await fetch(url, { timeout: 8000 });
if (!res.ok) throw new Error(`iplocate HTTP ${res.status}`);
const d = await res.json();
if (d.error) throw new Error(d.error);
return {
source: 'iplocate', success: true,
data: {
ip: d.ip || ip,
country: d.country || null,
country_code: d.country_code || null,
country_flag: null,
region: d.subdivision || null,
city: d.city || null,
latitude: d.latitude || null,
longitude: d.longitude || null,
timezone: d.time_zone || null,
timezone_abbr: null,
asn: d.asn?.asn || null,
organization: d.asn?.name || null,
connection_type: d.asn?.type || null,
isp: d.company?.name || d.asn?.name || null,
hostname: null,
ip_type: null,
is_vpn: d.privacy?.is_vpn ?? null,
is_proxy: d.privacy?.is_proxy ?? null,
is_tor: d.privacy?.is_tor ?? null,
is_threat: d.privacy?.is_abuser ?? null,
continent: d.continent || null,
continent_code: null,
postal: d.postal_code || null,
domain: d.asn?.domain || null,
usage_type: d.asn?.type || null,
is_hosting: d.privacy?.is_hosting ?? null,
is_anonymous: d.privacy?.is_anonymous ?? null,
company_name: d.company?.name || null,
company_domain: d.company?.domain || null,
hosting_provider: d.hosting?.provider || null,
}
};
} catch (err) {
return { source: 'iplocate', success: false, error: err.message, data: null };
}
}
// ═══════════════════════════════════════════
// Nominatim 反向地理编码
// ═══════════════════════════════════════════
async function reverseGeocode(lat, lon) {
const s = settings.get();
const email = s.apiKeys?.nominatimEmail || '';
const baseUrl = s.apiEndpoints?.nominatim || 'https://nominatim.openstreetmap.org/reverse';
const headers = {
'User-Agent': `IPQuerySystem/1.0 ${email ? '(' + email + ')' : ''}`,
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.5',
};
try {
const url = `${baseUrl}?lat=${lat}&lon=${lon}&format=json&zoom=14&addressdetails=1`;
const res = await fetch(url, { headers, timeout: 8000 });
if (!res.ok) throw new Error(`Nominatim HTTP ${res.status}`);
return await res.json();
} catch (err) {
return { error: err.message };
}
}
// ═══════════════════════════════════════════
// API: 获取访客 IP
// ═══════════════════════════════════════════
app.get('/api/myip', async (req, res) => {
let ip = getClientIP(req);
// 如果是私有/回环地址,尝试通过外部服务获取真实公网 IP
if (isPrivateIP(ip)) {
const publicIP = await getPublicIP();
if (publicIP) ip = publicIP;
}
res.json({ ip });
});
// ═══════════════════════════════════════════
// API: 获取浏览器标识 (User-Agent)
// ═══════════════════════════════════════════
app.get('/api/useragent', (req, res) => {
const ua = req.headers['user-agent'] || '';
res.json({
raw: ua,
parsed: parseUserAgent(ua),
accept_language: req.headers['accept-language'] || '',
});
});
function parseUserAgent(ua) {
const result = { browser: '', version: '', os: '', device: 'Desktop' };
// Browser
if (/Edg\/(\d[\d.]*)/i.test(ua)) { result.browser = 'Microsoft Edge'; result.version = RegExp.$1; }
else if (/OPR\/(\d[\d.]*)/i.test(ua)) { result.browser = 'Opera'; result.version = RegExp.$1; }
else if (/Chrome\/(\d[\d.]*)/i.test(ua)) { result.browser = 'Google Chrome'; result.version = RegExp.$1; }
else if (/Firefox\/(\d[\d.]*)/i.test(ua)) { result.browser = 'Firefox'; result.version = RegExp.$1; }
else if (/Safari\/(\d[\d.]*)/i.test(ua) && /Version\/(\d[\d.]*)/i.test(ua)) { result.browser = 'Safari'; result.version = RegExp.$1; }
else { result.browser = 'Unknown'; }
// OS
if (/Windows NT 10/i.test(ua)) result.os = 'Windows 10/11';
else if (/Windows NT 6\.3/i.test(ua)) result.os = 'Windows 8.1';
else if (/Windows NT 6\.1/i.test(ua)) result.os = 'Windows 7';
else if (/Mac OS X ([\d_]+)/i.test(ua)) result.os = 'macOS ' + RegExp.$1.replace(/_/g, '.');
else if (/Linux/i.test(ua) && /Android ([\d.]+)/i.test(ua)) { result.os = 'Android ' + RegExp.$1; result.device = 'Mobile'; }
else if (/iPhone|iPad/i.test(ua)) { result.os = 'iOS'; result.device = /iPad/i.test(ua) ? 'Tablet' : 'Mobile'; }
else if (/Linux/i.test(ua)) result.os = 'Linux';
else result.os = 'Unknown';
// Device
if (/Mobile|Android|iPhone/i.test(ua)) result.device = 'Mobile';
else if (/iPad|Tablet/i.test(ua)) result.device = 'Tablet';
return result;
}
// ═══════════════════════════════════════════
// API: 查询 IP 信息
// ═══════════════════════════════════════════
app.get('/api/query', async (req, res) => {
const ip = req.query.ip;
if (!ip) return res.status(400).json({ error: true, message: '缺少 ip 参数' });
if (!isValidIP(ip)) return res.status(400).json({ error: true, message: 'IP 地址格式无效' });
try {
const [abuse, iplocate] = await Promise.all([
fetchAbuseIPDB(ip), fetchIplocate(ip),
]);
res.json({ ip, timestamp: new Date().toISOString(), sources: { abuseipdb: abuse, iplocate } });
} catch (err) {
res.status(500).json({ error: true, message: '查询失败: ' + err.message });
}
});
// ═══════════════════════════════════════════
// API: Nominatim 反向地理编码代理
// ═══════════════════════════════════════════
app.get('/api/geocode', async (req, res) => {
const { lat, lon } = req.query;
if (!lat || !lon) return res.status(400).json({ error: true, message: '缺少 lat/lon 参数' });
const data = await reverseGeocode(lat, lon);
res.json(data);
});
// ═══════════════════════════════════════════
// API: 获取 SEO 设置 (公开)
// ═══════════════════════════════════════════
app.get('/api/seo', (req, res) => {
const s = settings.get();
res.json(s.seo || {});
});
// ═══════════════════════════════════════════
// 管理后台: 登录
// ═══════════════════════════════════════════
app.post('/api/admin/login', (req, res) => {
const { password } = req.body;
const s = settings.get();
if (password && password === s.admin?.password) {
const token = crypto.randomBytes(32).toString('hex');
adminTokens.set(token, { createdAt: Date.now() });
return res.json({ success: true, token });
}
res.status(401).json({ error: true, message: '密码错误' });
});
// ═══════════════════════════════════════════
// 管理后台: 获取设置 (需认证)
// ═══════════════════════════════════════════
app.get('/api/admin/settings', requireAdmin, (req, res) => {
const s = settings.get();
// 脱敏返回 — 密码不完整显示
const safe = JSON.parse(JSON.stringify(s));
safe.admin.password = s.admin?.password || '';
res.json(safe);
});
// ═══════════════════════════════════════════
// 管理后台: 更新设置 (需认证)
// ═══════════════════════════════════════════
app.put('/api/admin/settings', requireAdmin, (req, res) => {
try {
const updated = settings.update(req.body);
// 重新加载 key index
abuseKeyIndex = 0;
res.json({ success: true, settings: updated });
} catch (err) {
res.status(500).json({ error: true, message: err.message });
}
});
// ═══════════════════════════════════════════
// 管理后台: 登出
// ═══════════════════════════════════════════
app.post('/api/admin/logout', requireAdmin, (req, res) => {
const token = req.headers.authorization?.slice(7);
if (token) adminTokens.delete(token);
res.json({ success: true });
});
// ═══════════════════════════════════════════
// 页面路由: 管理后台
// ═══════════════════════════════════════════
app.get('/admin', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
// ═══════════════════════════════════════════
// 页面路由: 首页 (动态 SEO 注入)
// ═══════════════════════════════════════════
app.get('/', (req, res) => {
const s = settings.get();
let html = fs.readFileSync(path.join(__dirname, 'public', 'index.html'), 'utf8');
html = html
.replace(/\{\{SEO_TITLE\}\}/g, s.seo?.title || 'IP 信息查询系统')
.replace(/\{\{SEO_DESC\}\}/g, s.seo?.description || '')
.replace(/\{\{SEO_KEYWORDS\}\}/g, s.seo?.keywords || '');
res.type('html').send(html);
});
// ═══════════════════════════════════════════
// 启动
// ═══════════════════════════════════════════
app.listen(PORT, '0.0.0.0', () => {
const s = settings.get();
const abuseCount = s.apiKeys?.abuseipdb?.length || 0;
const hasIplocate = !!s.apiKeys?.iplocate;
console.log(`🚀 IP Query Server running at http://0.0.0.0:${PORT}`);
console.log(` AbuseIPDB keys: ${abuseCount} loaded`);
console.log(` iplocate.io: ${hasIplocate ? '✅ configured' : '❌ not configured'}`);
console.log(` Admin panel: http://0.0.0.0:${PORT}/admin`);
console.log(` Admin password: ${s.admin?.password || 'admin123'}`);
});