-
Notifications
You must be signed in to change notification settings - Fork 9.9k
Expand file tree
/
Copy pathindex.js
More file actions
498 lines (455 loc) · 15.6 KB
/
index.js
File metadata and controls
498 lines (455 loc) · 15.6 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
#!/usr/bin/env node
const os = require('os');
const http = require('http');
const fs = require('fs');
const axios = require('axios');
const net = require('net');
const path = require('path');
const crypto = require('crypto');
const { Buffer } = require('buffer');
const { exec, execSync } = require('child_process');
const { WebSocket, createWebSocketStream } = require('ws');
const UUID = process.env.UUID || '5efabea4-f6d4-91fd-b8f0-17e004c89c60'; // 运行哪吒v1,在不同的平台需要改UUID,否则会被覆盖
const NEZHA_SERVER = process.env.NEZHA_SERVER || ''; // 哪吒v1填写形式:nz.abc.com:8008 哪吒v0填写形式:nz.abc.com
const NEZHA_PORT = process.env.NEZHA_PORT || ''; // 哪吒v1没有此变量,v0的agent端口为{443,8443,2096,2087,2083,2053}其中之一时开启tls
const NEZHA_KEY = process.env.NEZHA_KEY || ''; // v1的NZ_CLIENT_SECRET或v0的agent端口
const DOMAIN = process.env.DOMAIN || 'your-domain.com'; // 填写项目域名或已反代的域名,不带前缀,建议填已反代的域名
const AUTO_ACCESS = process.env.AUTO_ACCESS || false; // 是否开启自动访问保活,false为关闭,true为开启,需同时填写DOMAIN变量
const WSPATH = process.env.WSPATH || UUID.slice(0, 8); // 节点路径,默认获取uuid前8位
const SUB_PATH = process.env.SUB_PATH || 'sub'; // 获取节点的订阅路径
const NAME = process.env.NAME || ''; // 节点名称
const PORT = process.env.PORT || 3000; // http和ws服务端口
let uuid = UUID.replace(/-/g, ""), CurrentDomain = DOMAIN, Tls = 'tls', CurrentPort = 443, ISP = '';
const DNS_SERVERS = ['8.8.4.4', '1.1.1.1'];
const BLOCKED_DOMAINS = [
'speedtest.net', 'fast.com', 'speedtest.cn', 'speed.cloudflare.com', 'speedof.me',
'testmy.net', 'bandwidth.place', 'speed.io', 'librespeed.org', 'speedcheck.org'
];
// block speedtest domains
function isBlockedDomain(host) {
if (!host) return false;
const hostLower = host.toLowerCase();
return BLOCKED_DOMAINS.some(blocked => {
return hostLower === blocked || hostLower.endsWith('.' + blocked);
});
}
async function getisp() {
try {
const res = await axios.get('https://api.ip.sb/geoip', { headers: { 'User-Agent': 'Mozilla/5.0', timeout: 3000 }});
const data = res.data;
ISP = `${data.country_code}-${data.isp}`.replace(/ /g, '_');
} catch (e) {
try {
const res2 = await axios.get('http://ip-api.com/json', { headers: { 'User-Agent': 'Mozilla/5.0', timeout: 3000 }});
const data2 = res2.data;
ISP = `${data2.countryCode}-${data2.org}`.replace(/ /g, '_');
} catch (e2) {
ISP = 'Unknown';
}
}
}
async function getip() {
if (!DOMAIN || DOMAIN === 'your-domain.com') {
try {
const res = await axios.get('https://api-ipv4.ip.sb/ip', { timeout: 5000 });
const ip = res.data.trim();
CurrentDomain = ip, Tls = 'none', CurrentPort = PORT;
} catch (e) {
console.error('Failed to get IP', e.message);
CurrentDomain = 'cahnge-your-domain.com', Tls = 'tls', CurrentPort = 443;
}
} else {
CurrentDomain = DOMAIN, Tls = 'tls', CurrentPort = 443;
}
}
// http route
const httpServer = http.createServer(async (req, res) => {
if (req.url === '/') {
const filePath = path.join(__dirname, 'index.html');
fs.readFile(filePath, 'utf8', (err, content) => {
if (err) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Hello world!');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
});
return;
} else if (req.url === `/${SUB_PATH}`) {
await getisp();await getip();
const namePart = NAME ? `${NAME}-${ISP}` : ISP;
const tlsParam = Tls === 'tls' ? 'tls' : 'none';
const ssTlsParam = Tls === 'tls' ? 'tls;' : '';
const vlsURL = `vless://${UUID}@${CurrentDomain}:${CurrentPort}?encryption=none&security=${tlsParam}&sni=${CurrentDomain}&fp=chrome&type=ws&host=${CurrentDomain}&path=%2F${WSPATH}#${namePart}`;
const troURL = `trojan://${UUID}@${CurrentDomain}:${CurrentPort}?security=${tlsParam}&sni=${CurrentDomain}&fp=chrome&type=ws&host=${CurrentDomain}&path=%2F${WSPATH}#${namePart}`;
const ssMethodPassword = Buffer.from(`none:${UUID}`).toString('base64');
const ssURL = `ss://${ssMethodPassword}@${CurrentDomain}:${CurrentPort}?plugin=v2ray-plugin;mode%3Dwebsocket;host%3D${CurrentDomain};path%3D%2F${WSPATH};${ssTlsParam}sni%3D${CurrentDomain};skip-cert-verify%3Dtrue;mux%3D0#${namePart}`;
const subscription = vlsURL + '\n' + troURL + '\n' + ssURL;
const base64Content = Buffer.from(subscription).toString('base64');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(base64Content + '\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found\n');
}
});
// Custom DNS
function resolveHost(host) {
return new Promise((resolve, reject) => {
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]?)$/.test(host)) {
resolve(host);
return;
}
let attempts = 0;
function tryNextDNS() {
if (attempts >= DNS_SERVERS.length) {
reject(new Error(`Failed to resolve ${host} with all DNS servers`));
return;
}
const dnsServer = DNS_SERVERS[attempts];
attempts++;
const dnsQuery = `https://dns.google/resolve?name=${encodeURIComponent(host)}&type=A`;
axios.get(dnsQuery, {
timeout: 5000,
headers: {
'Accept': 'application/dns-json'
}
})
.then(response => {
const data = response.data;
if (data.Status === 0 && data.Answer && data.Answer.length > 0) {
const ip = data.Answer.find(record => record.type === 1);
if (ip) {
resolve(ip.data);
return;
}
}
tryNextDNS();
})
.catch(error => {
tryNextDNS();
});
}
tryNextDNS();
});
}
// VLE-SS处理
function handleVlsConnection(ws, msg) {
const [VERSION] = msg;
const id = msg.slice(1, 17);
if (!id.every((v, i) => v == parseInt(uuid.substr(i * 2, 2), 16))) return false;
let i = msg.slice(17, 18).readUInt8() + 19;
const port = msg.slice(i, i += 2).readUInt16BE(0);
const ATYP = msg.slice(i, i += 1).readUInt8();
const host = ATYP == 1 ? msg.slice(i, i += 4).join('.') :
(ATYP == 2 ? new TextDecoder().decode(msg.slice(i + 1, i += 1 + msg.slice(i, i + 1).readUInt8())) :
(ATYP == 3 ? msg.slice(i, i += 16).reduce((s, b, i, a) => (i % 2 ? s.concat(a.slice(i - 1, i + 1)) : s), []).map(b => b.readUInt16BE(0).toString(16)).join(':') : ''));
if (isBlockedDomain(host)) {
ws.close();
return false;
}
ws.send(new Uint8Array([VERSION, 0]));
const duplex = createWebSocketStream(ws);
resolveHost(host)
.then(resolvedIP => {
net.connect({ host: resolvedIP, port }, function () {
this.write(msg.slice(i));
duplex.on('error', () => { }).pipe(this).on('error', () => { }).pipe(duplex);
}).on('error', () => { });
})
.catch(error => {
net.connect({ host, port }, function () {
this.write(msg.slice(i));
duplex.on('error', () => { }).pipe(this).on('error', () => { }).pipe(duplex);
}).on('error', () => { });
});
return true;
}
// Tro-jan处理
function handleTrojConnection(ws, msg) {
try {
if (msg.length < 58) return false;
const receivedPasswordHash = msg.slice(0, 56).toString();
const possiblePasswords = [UUID];
let matchedPassword = null;
for (const pwd of possiblePasswords) {
const hash = crypto.createHash('sha224').update(pwd).digest('hex');
if (hash === receivedPasswordHash) {
matchedPassword = pwd;
break;
}
}
if (!matchedPassword) return false;
let offset = 56;
if (msg[offset] === 0x0d && msg[offset + 1] === 0x0a) {
offset += 2;
}
const cmd = msg[offset];
if (cmd !== 0x01) return false;
offset += 1;
const atyp = msg[offset];
offset += 1;
let host, port;
if (atyp === 0x01) {
host = msg.slice(offset, offset + 4).join('.');
offset += 4;
} else if (atyp === 0x03) {
const hostLen = msg[offset];
offset += 1;
host = msg.slice(offset, offset + hostLen).toString();
offset += hostLen;
} else if (atyp === 0x04) {
host = msg.slice(offset, offset + 16).reduce((s, b, i, a) =>
(i % 2 ? s.concat(a.slice(i - 1, i + 1)) : s), [])
.map(b => b.readUInt16BE(0).toString(16)).join(':');
offset += 16;
} else {
return false;
}
port = msg.readUInt16BE(offset);
offset += 2;
if (offset < msg.length && msg[offset] === 0x0d && msg[offset + 1] === 0x0a) {
offset += 2;
}
if (isBlockedDomain(host)) {
ws.close();
return false;
}
const duplex = createWebSocketStream(ws);
resolveHost(host)
.then(resolvedIP => {
net.connect({ host: resolvedIP, port }, function () {
if (offset < msg.length) {
this.write(msg.slice(offset));
}
duplex.on('error', () => { }).pipe(this).on('error', () => { }).pipe(duplex);
}).on('error', () => { });
})
.catch(error => {
net.connect({ host, port }, function () {
if (offset < msg.length) {
this.write(msg.slice(offset));
}
duplex.on('error', () => { }).pipe(this).on('error', () => { }).pipe(duplex);
}).on('error', () => { });
});
return true;
} catch (error) {
return false;
}
}
// Ss处理
function handleSsConnection(ws, msg) {
try {
let offset = 0;
const atyp = msg[offset];
offset += 1;
let host, port;
if (atyp === 0x01) {
host = msg.slice(offset, offset + 4).join('.');
offset += 4;
} else if (atyp === 0x03) {
const hostLen = msg[offset];
offset += 1;
host = msg.slice(offset, offset + hostLen).toString();
offset += hostLen;
} else if (atyp === 0x04) {
host = msg.slice(offset, offset + 16).reduce((s, b, i, a) =>
(i % 2 ? s.concat(a.slice(i - 1, i + 1)) : s), [])
.map(b => b.readUInt16BE(0).toString(16)).join(':');
offset += 16;
} else {
return false;
}
port = msg.readUInt16BE(offset);
offset += 2;
if (isBlockedDomain(host)) {
ws.close();
return false;
}
const duplex = createWebSocketStream(ws);
resolveHost(host)
.then(resolvedIP => {
net.connect({ host: resolvedIP, port }, function () {
if (offset < msg.length) {
this.write(msg.slice(offset));
}
duplex.on('error', () => { }).pipe(this).on('error', () => { }).pipe(duplex);
}).on('error', () => { });
})
.catch(error => {
net.connect({ host, port }, function () {
if (offset < msg.length) {
this.write(msg.slice(offset));
}
duplex.on('error', () => { }).pipe(this).on('error', () => { }).pipe(duplex);
}).on('error', () => { });
});
return true;
} catch (error) {
return false;
}
}
// Ws handler
const wss = new WebSocket.Server({ server: httpServer });
wss.on('connection', (ws, req) => {
const url = req.url || '';
const expectedPath = `/${WSPATH}`;
if (!url.startsWith(expectedPath)) {
ws.close();
return;
}
ws.once('message', msg => {
// VLE-SS (version byte 0 + 16 bytes UUID)
if (msg.length > 17 && msg[0] === 0) {
const id = msg.slice(1, 17);
const isVless = id.every((v, i) => v == parseInt(uuid.substr(i * 2, 2), 16));
if (isVless) {
if (!handleVlsConnection(ws, msg)) {
ws.close();
}
return;
}
}
// tro-jan (56 bytes SHA224 hash)
if (msg.length >= 58) {
if (handleTrojConnection(ws, msg)) {
return;
}
}
// SS (ATYP开头: 0x01, 0x03, 0x04)
if (msg.length > 0 && (msg[0] === 0x01 || msg[0] === 0x03 || msg[0] === 0x04)) {
if (handleSsConnection(ws, msg)) {
return;
}
}
ws.close();
}).on('error', () => { });
});
const getDownloadUrl = () => {
const arch = os.arch();
if (arch === 'arm' || arch === 'arm64' || arch === 'aarch64') {
if (!NEZHA_PORT) {
return 'https://arm64.ssss.nyc.mn/v1';
} else {
return 'https://arm64.ssss.nyc.mn/agent';
}
} else {
if (!NEZHA_PORT) {
return 'https://amd64.ssss.nyc.mn/v1';
} else {
return 'https://amd64.ssss.nyc.mn/agent';
}
}
};
const downloadFile = async () => {
if (!NEZHA_SERVER && !NEZHA_KEY) return;
try {
const url = getDownloadUrl();
const response = await axios({
method: 'get',
url: url,
responseType: 'stream'
});
const writer = fs.createWriteStream('npm');
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', () => {
console.log('npm download successfully');
exec('chmod +x npm', (err) => {
if (err) reject(err);
resolve();
});
});
writer.on('error', reject);
});
} catch (err) {
throw err;
}
};
const runnz = async () => {
try {
const status = execSync('ps aux | grep -v "grep" | grep "./[n]pm"', { encoding: 'utf-8' });
if (status.trim() !== '') {
console.log('npm is already running, skip running...');
return;
}
} catch (e) {
// 进程不存在时继续运行nezha
}
await downloadFile();
let command = '';
let tlsPorts = ['443', '8443', '2096', '2087', '2083', '2053'];
if (NEZHA_SERVER && NEZHA_PORT && NEZHA_KEY) {
const NEZHA_TLS = tlsPorts.includes(NEZHA_PORT) ? '--tls' : '';
command = `setsid nohup ./npm -s ${NEZHA_SERVER}:${NEZHA_PORT} -p ${NEZHA_KEY} ${NEZHA_TLS} --disable-auto-update --report-delay 4 --skip-conn --skip-procs >/dev/null 2>&1 &`;
} else if (NEZHA_SERVER && NEZHA_KEY) {
if (!NEZHA_PORT) {
const port = NEZHA_SERVER.includes(':') ? NEZHA_SERVER.split(':').pop() : '';
const NZ_TLS = tlsPorts.includes(port) ? 'true' : 'false';
const configYaml = `client_secret: ${NEZHA_KEY}
debug: false
disable_auto_update: true
disable_command_execute: false
disable_force_update: true
disable_nat: false
disable_send_query: false
gpu: false
insecure_tls: true
ip_report_period: 1800
report_delay: 4
server: ${NEZHA_SERVER}
skip_connection_count: true
skip_procs_count: true
temperature: false
tls: ${NZ_TLS}
use_gitee_to_upgrade: false
use_ipv6_country_code: false
uuid: ${UUID}`;
fs.writeFileSync('config.yaml', configYaml);
}
command = `setsid nohup ./npm -c config.yaml >/dev/null 2>&1 &`;
} else {
// console.log('NEZHA variable is empty, skip running');
return;
}
try {
exec(command, { shell: '/bin/bash' }, (err) => {
if (err) console.error('npm running error:', err);
else console.log('npm is running');
});
} catch (error) {
console.error(`error: ${error}`);
}
};
async function addAccessTask() {
if (!AUTO_ACCESS) return;
if (!DOMAIN) {
return;
}
const fullURL = `https://${DOMAIN}/${SUB_PATH}`;
try {
const res = await axios.post("https://oooo.serv00.net/add-url", {
url: fullURL
}, {
headers: {
'Content-Type': 'application/json'
}
});
console.log('Automatic Access Task added successfully');
} catch (error) {
// console.error('Error adding Task:', error.message);
}
}
const delFiles = () => {
['npm', 'config.yaml'].forEach(file => fs.unlink(file, () => { }));
};
httpServer.listen(PORT, () => {
runnz();
setTimeout(() => {
delFiles();
}, 180000);
addAccessTask();
console.log(`Server is running on port ${PORT}`);
});