forked from eooce/nodejs-argo
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.js
More file actions
546 lines (495 loc) · 19.4 KB
/
index.js
File metadata and controls
546 lines (495 loc) · 19.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
const express = require("express");
const app = express();
const axios = require("axios");
const os = require('os');
const fs = require("fs");
const path = require("path");
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
const { execSync } = require('child_process'); // 只填写UPLOAD_URL将上传节点,同时填写UPLOAD_URL和PROJECT_URL将上传订阅
const UPLOAD_URL = process.env.UPLOAD_URL || ''; // 节点或订阅自动上传地址,需填写部署Merge-sub项目后的首页地址,例如:https://merge.serv00.net
const PROJECT_URL = process.env.PROJECT_URL || ''; // 需要上传订阅或保活时需填写项目分配的url,例如:https://google.com
const AUTO_ACCESS = process.env.AUTO_ACCESS || false; // false关闭自动保活,true开启,需同时填写PROJECT_URL变量
const FILE_PATH = process.env.FILE_PATH || './tmp'; // 运行目录,sub节点文件保存目录
const SUB_PATH = process.env.SUB_PATH || 'sub'; // 订阅路径
const PORT = process.env.SERVER_PORT || process.env.PORT || 3000; // http服务订阅端口
const UUID = process.env.UUID || '9afd1229-b893-40c1-84dd-51e7ce204913'; // 使用哪吒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需填写
const NEZHA_KEY = process.env.NEZHA_KEY || ''; // 哪吒v1的NZ_CLIENT_SECRET或哪吒v0的agent密钥
const ARGO_DOMAIN = process.env.ARGO_DOMAIN || ''; // 固定隧道域名,留空即启用临时隧道
const ARGO_AUTH = process.env.ARGO_AUTH || ''; // 固定隧道密钥json或token,留空即启用临时隧道,json获取地址:https://fscarmen.cloudflare.now.cc
const ARGO_PORT = process.env.ARGO_PORT || 8001; // 固定隧道端口,使用token需在cloudflare后台设置和这里一致
const CFIP = process.env.CFIP || 'www.visa.com.sg'; // 节点优选域名或优选ip
const CFPORT = process.env.CFPORT || 443; // 节点优选域名或优选ip对应的端口
const NAME = process.env.NAME || 'Vls'; // 节点名称
//创建运行文件夹
if (!fs.existsSync(FILE_PATH)) {
fs.mkdirSync(FILE_PATH);
console.log(`${FILE_PATH} is created`);
} else {
console.log(`${FILE_PATH} already exists`);
}
let npmPath = path.join(FILE_PATH, 'npm');
let phpPath = path.join(FILE_PATH, 'php');
let webPath = path.join(FILE_PATH, 'web');
let botPath = path.join(FILE_PATH, 'bot');
let subPath = path.join(FILE_PATH, 'sub.txt');
let listPath = path.join(FILE_PATH, 'list.txt');
let bootLogPath = path.join(FILE_PATH, 'boot.log');
let configPath = path.join(FILE_PATH, 'config.json');
// 如果订阅器上存在历史运行节点则先删除
function deleteNodes() {
try {
if (!UPLOAD_URL) return;
if (!fs.existsSync(subPath)) return;
let fileContent;
try {
fileContent = fs.readFileSync(subPath, 'utf-8');
} catch {
return null;
}
const decoded = Buffer.from(fileContent, 'base64').toString('utf-8');
const nodes = decoded.split('\n').filter(line =>
/(vless|vmess|trojan|hysteria2|tuic):\/\//.test(line)
);
if (nodes.length === 0) return;
return axios.post(`${UPLOAD_URL}/api/delete-nodes`,
JSON.stringify({ nodes }),
{ headers: { 'Content-Type': 'application/json' } }
).catch((error) => {
return null;
});
} catch (err) {
return null;
}
}
//清理历史文件
function cleanupOldFiles() {
const pathsToDelete = ['web', 'bot', 'npm', 'php', 'sub.txt', 'boot.log'];
pathsToDelete.forEach(file => {
const filePath = path.join(FILE_PATH, file);
fs.unlink(filePath, () => {});
});
}
// 根路由
app.get("/", function(req, res) {
res.send("Hello world!");
});
// 生成xr-ay配置文件
const config = {
log: { access: '/dev/null', error: '/dev/null', loglevel: 'none' },
inbounds: [
{ port: ARGO_PORT, protocol: 'vless', settings: { clients: [{ id: UUID, flow: 'xtls-rprx-vision' }], decryption: 'none', fallbacks: [{ dest: 3001 }, { path: "/vless-argo", dest: 3002 }, { path: "/vmess-argo", dest: 3003 }, { path: "/trojan-argo", dest: 3004 }] }, streamSettings: { network: 'tcp' } },
{ port: 3001, listen: "127.0.0.1", protocol: "vless", settings: { clients: [{ id: UUID }], decryption: "none" }, streamSettings: { network: "tcp", security: "none" } },
{ port: 3002, listen: "127.0.0.1", protocol: "vless", settings: { clients: [{ id: UUID, level: 0 }], decryption: "none" }, streamSettings: { network: "ws", security: "none", wsSettings: { path: "/vless-argo" } }, sniffing: { enabled: true, destOverride: ["http", "tls", "quic"], metadataOnly: false } },
{ port: 3003, listen: "127.0.0.1", protocol: "vmess", settings: { clients: [{ id: UUID, alterId: 0 }] }, streamSettings: { network: "ws", wsSettings: { path: "/vmess-argo" } }, sniffing: { enabled: true, destOverride: ["http", "tls", "quic"], metadataOnly: false } },
{ port: 3004, listen: "127.0.0.1", protocol: "trojan", settings: { clients: [{ password: UUID }] }, streamSettings: { network: "ws", security: "none", wsSettings: { path: "/trojan-argo" } }, sniffing: { enabled: true, destOverride: ["http", "tls", "quic"], metadataOnly: false } },
],
dns: { servers: ["https+local://8.8.8.8/dns-query"] },
outbounds: [ { protocol: "freedom", tag: "direct" }, {protocol: "blackhole", tag: "block"} ]
};
fs.writeFileSync(path.join(FILE_PATH, 'config.json'), JSON.stringify(config, null, 2));
// 判断系统架构
function getSystemArchitecture() {
const arch = os.arch();
if (arch === 'arm' || arch === 'arm64' || arch === 'aarch64') {
return 'arm';
} else {
return 'amd';
}
}
// 下载对应系统架构的依赖文件
function downloadFile(fileName, fileUrl, callback) {
const filePath = path.join(FILE_PATH, fileName);
const writer = fs.createWriteStream(filePath);
axios({
method: 'get',
url: fileUrl,
responseType: 'stream',
})
.then(response => {
response.data.pipe(writer);
writer.on('finish', () => {
writer.close();
console.log(`Download ${fileName} successfully`);
callback(null, fileName);
});
writer.on('error', err => {
fs.unlink(filePath, () => { });
const errorMessage = `Download ${fileName} failed: ${err.message}`;
console.error(errorMessage); // 下载失败时输出错误消息
callback(errorMessage);
});
})
.catch(err => {
const errorMessage = `Download ${fileName} failed: ${err.message}`;
console.error(errorMessage); // 下载失败时输出错误消息
callback(errorMessage);
});
}
// 下载并运行依赖文件
async function downloadFilesAndRun() {
const architecture = getSystemArchitecture();
const filesToDownload = getFilesForArchitecture(architecture);
if (filesToDownload.length === 0) {
console.log(`Can't find a file for the current architecture`);
return;
}
const downloadPromises = filesToDownload.map(fileInfo => {
return new Promise((resolve, reject) => {
downloadFile(fileInfo.fileName, fileInfo.fileUrl, (err, fileName) => {
if (err) {
reject(err);
} else {
resolve(fileName);
}
});
});
});
try {
await Promise.all(downloadPromises);
} catch (err) {
console.error('Error downloading files:', err);
return;
}
// 授权和运行
function authorizeFiles(filePaths) {
const newPermissions = 0o775;
filePaths.forEach(relativeFilePath => {
const absoluteFilePath = path.join(FILE_PATH, relativeFilePath);
if (fs.existsSync(absoluteFilePath)) {
fs.chmod(absoluteFilePath, newPermissions, (err) => {
if (err) {
console.error(`Empowerment failed for ${absoluteFilePath}: ${err}`);
} else {
console.log(`Empowerment success for ${absoluteFilePath}: ${newPermissions.toString(8)}`);
}
});
}
});
}
const filesToAuthorize = NEZHA_PORT ? ['./npm', './web', './bot'] : ['./php', './web', './bot'];
authorizeFiles(filesToAuthorize);
//运行ne-zha
if (NEZHA_SERVER && NEZHA_KEY) {
if (!NEZHA_PORT) {
// 检测哪吒是否开启TLS
const port = NEZHA_SERVER.includes(':') ? NEZHA_SERVER.split(':').pop() : '';
const tlsPorts = new Set(['443', '8443', '2096', '2087', '2083', '2053']);
const nezhatls = tlsPorts.has(port) ? 'true' : 'false';
// 生成 config.yaml
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: false
ip_report_period: 1800
report_delay: 1
server: ${NEZHA_SERVER}
skip_connection_count: false
skip_procs_count: false
temperature: false
tls: ${nezhatls}
use_gitee_to_upgrade: false
use_ipv6_country_code: false
uuid: ${UUID}`;
fs.writeFileSync(path.join(FILE_PATH, 'config.yaml'), configYaml);
// 运行 php
const command = `nohup ${FILE_PATH}/php -c "${FILE_PATH}/config.yaml" >/dev/null 2>&1 &`;
try {
await exec(command);
console.log('php is running');
await new Promise((resolve) => setTimeout(resolve, 1000));
} catch (error) {
console.error(`php running error: ${error}`);
}
} else {
let NEZHA_TLS = '';
const tlsPorts = ['443', '8443', '2096', '2087', '2083', '2053'];
if (tlsPorts.includes(NEZHA_PORT)) {
NEZHA_TLS = '--tls';
}
const command = `nohup ${FILE_PATH}/npm -s ${NEZHA_SERVER}:${NEZHA_PORT} -p ${NEZHA_KEY} ${NEZHA_TLS} >/dev/null 2>&1 &`;
try {
await exec(command);
console.log('npm is running');
await new Promise((resolve) => setTimeout(resolve, 1000));
} catch (error) {
console.error(`npm running error: ${error}`);
}
}
} else {
console.log('NEZHA variable is empty,skip running');
}
//运行xr-ay
const command1 = `nohup ${FILE_PATH}/web -c ${FILE_PATH}/config.json >/dev/null 2>&1 &`;
try {
await exec(command1);
console.log('web is running');
await new Promise((resolve) => setTimeout(resolve, 1000));
} catch (error) {
console.error(`web running error: ${error}`);
}
// 运行cloud-fared
if (fs.existsSync(path.join(FILE_PATH, 'bot'))) {
let args;
if (ARGO_AUTH.match(/^[A-Z0-9a-z=]{120,250}$/)) {
args = `tunnel --edge-ip-version auto --no-autoupdate --protocol http2 run --token ${ARGO_AUTH}`;
} else if (ARGO_AUTH.match(/TunnelSecret/)) {
args = `tunnel --edge-ip-version auto --config ${FILE_PATH}/tunnel.yml run`;
} else {
args = `tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile ${FILE_PATH}/boot.log --loglevel info --url http://localhost:${ARGO_PORT}`;
}
try {
await exec(`nohup ${FILE_PATH}/bot ${args} >/dev/null 2>&1 &`);
console.log('bot is running');
await new Promise((resolve) => setTimeout(resolve, 2000));
} catch (error) {
console.error(`Error executing command: ${error}`);
}
}
await new Promise((resolve) => setTimeout(resolve, 5000));
}
//根据系统架构返回对应的url
function getFilesForArchitecture(architecture) {
let baseFiles;
if (architecture === 'arm') {
baseFiles = [
{ fileName: "web", fileUrl: "https://arm64.ssss.nyc.mn/web" },
{ fileName: "bot", fileUrl: "https://arm64.ssss.nyc.mn/2go" }
];
} else {
baseFiles = [
{ fileName: "web", fileUrl: "https://amd64.ssss.nyc.mn/web" },
{ fileName: "bot", fileUrl: "https://amd64.ssss.nyc.mn/2go" }
];
}
if (NEZHA_SERVER && NEZHA_KEY) {
if (NEZHA_PORT) {
const npmUrl = architecture === 'arm'
? "https://arm64.ssss.nyc.mn/agent"
: "https://amd64.ssss.nyc.mn/agent";
baseFiles.unshift({
fileName: "npm",
fileUrl: npmUrl
});
} else {
const phpUrl = architecture === 'arm'
? "https://arm64.ssss.nyc.mn/v1"
: "https://amd64.ssss.nyc.mn/v1";
baseFiles.unshift({
fileName: "php",
fileUrl: phpUrl
});
}
}
return baseFiles;
}
// 获取固定隧道json
function argoType() {
if (!ARGO_AUTH || !ARGO_DOMAIN) {
console.log("ARGO_DOMAIN or ARGO_AUTH variable is empty, use quick tunnels");
return;
}
if (ARGO_AUTH.includes('TunnelSecret')) {
fs.writeFileSync(path.join(FILE_PATH, 'tunnel.json'), ARGO_AUTH);
const tunnelYaml = `
tunnel: ${ARGO_AUTH.split('"')[11]}
credentials-file: ${path.join(FILE_PATH, 'tunnel.json')}
protocol: http2
ingress:
- hostname: ${ARGO_DOMAIN}
service: http://localhost:${ARGO_PORT}
originRequest:
noTLSVerify: true
- service: http_status:404
`;
fs.writeFileSync(path.join(FILE_PATH, 'tunnel.yml'), tunnelYaml);
} else {
console.log("ARGO_AUTH mismatch TunnelSecret,use token connect to tunnel");
}
}
argoType();
// 获取临时隧道domain
async function extractDomains() {
let argoDomain;
if (ARGO_AUTH && ARGO_DOMAIN) {
argoDomain = ARGO_DOMAIN;
console.log('ARGO_DOMAIN:', argoDomain);
await generateLinks(argoDomain);
} else {
try {
const fileContent = fs.readFileSync(path.join(FILE_PATH, 'boot.log'), 'utf-8');
const lines = fileContent.split('\n');
const argoDomains = [];
lines.forEach((line) => {
const domainMatch = line.match(/https?:\/\/([^ ]*trycloudflare\.com)\/?/);
if (domainMatch) {
const domain = domainMatch[1];
argoDomains.push(domain);
}
});
if (argoDomains.length > 0) {
argoDomain = argoDomains[0];
console.log('ArgoDomain:', argoDomain);
await generateLinks(argoDomain);
} else {
console.log('ArgoDomain not found, re-running bot to obtain ArgoDomain');
// 删除 boot.log 文件,等待 2s 重新运行 server 以获取 ArgoDomain
fs.unlinkSync(path.join(FILE_PATH, 'boot.log'));
async function killBotProcess() {
try {
await exec('pkill -f "[b]ot" > /dev/null 2>&1');
} catch (error) {
// 忽略输出
}
}
killBotProcess();
await new Promise((resolve) => setTimeout(resolve, 3000));
const args = `tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile ${FILE_PATH}/boot.log --loglevel info --url http://localhost:${ARGO_PORT}`;
try {
await exec(`nohup ${path.join(FILE_PATH, 'bot')} ${args} >/dev/null 2>&1 &`);
console.log('bot is running.');
await new Promise((resolve) => setTimeout(resolve, 3000));
await extractDomains(); // 重新提取域名
} catch (error) {
console.error(`Error executing command: ${error}`);
}
}
} catch (error) {
console.error('Error reading boot.log:', error);
}
}
// 生成 list 和 sub 信息
async function generateLinks(argoDomain) {
const metaInfo = execSync(
'curl -s https://speed.cloudflare.com/meta | awk -F\\" \'{print $26"-"$18}\' | sed -e \'s/ /_/g\'',
{ encoding: 'utf-8' }
);
const ISP = metaInfo.trim();
return new Promise((resolve) => {
setTimeout(() => {
const VMESS = { v: '2', ps: `${NAME}-${ISP}`, add: CFIP, port: CFPORT, id: UUID, aid: '0', scy: 'none', net: 'ws', type: 'none', host: argoDomain, path: '/vmess-argo?ed=2560', tls: 'tls', sni: argoDomain, alpn: '' };
const subTxt = `
vless://${UUID}@${CFIP}:${CFPORT}?encryption=none&security=tls&sni=${argoDomain}&type=ws&host=${argoDomain}&path=%2Fvless-argo%3Fed%3D2560#${NAME}-${ISP}
vmess://${Buffer.from(JSON.stringify(VMESS)).toString('base64')}
trojan://${UUID}@${CFIP}:${CFPORT}?security=tls&sni=${argoDomain}&type=ws&host=${argoDomain}&path=%2Ftrojan-argo%3Fed%3D2560#${NAME}-${ISP}
`;
// 打印 sub.txt 内容到控制台
console.log(Buffer.from(subTxt).toString('base64'));
fs.writeFileSync(subPath, Buffer.from(subTxt).toString('base64'));
console.log(`${FILE_PATH}/sub.txt saved successfully`);
uplodNodes();
// 将内容进行 base64 编码并写入 SUB_PATH 路由
app.get(`/${SUB_PATH}`, (req, res) => {
const encodedContent = Buffer.from(subTxt).toString('base64');
res.set('Content-Type', 'text/plain; charset=utf-8');
res.send(encodedContent);
});
resolve(subTxt);
}, 2000);
});
}
}
// 自动上传节点或订阅
async function uplodNodes() {
if (UPLOAD_URL && PROJECT_URL) {
const subscriptionUrl = `${PROJECT_URL}/${SUB_PATH}`;
const jsonData = {
subscription: [subscriptionUrl]
};
try {
const response = await axios.post(`${UPLOAD_URL}/api/add-subscriptions`, jsonData, {
headers: {
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log('Subscription uploaded successfully');
} else {
return null;
// console.log('Unknown response status');
}
} catch (error) {
if (error.response) {
if (error.response.status === 400) {
// console.error('Subscription already exists');
}
}
}
} else if (UPLOAD_URL) {
if (!fs.existsSync(listPath)) return;
const content = fs.readFileSync(listPath, 'utf-8');
const nodes = content.split('\n').filter(line => /(vless|vmess|trojan|hysteria2|tuic):\/\//.test(line));
if (nodes.length === 0) return;
const jsonData = JSON.stringify({ nodes });
try {
await axios.post(`${UPLOAD_URL}/api/add-nodes`, jsonData, {
headers: { 'Content-Type': 'application/json' }
});
if (response.status === 200) {
console.log('Subscription uploaded successfully');
} else {
return null;
}
} catch (error) {
return null;
}
} else {
// console.log('Skipping upload nodes');
return;
}
}
// 90s后删除相关文件
function cleanFiles() {
setTimeout(() => {
const filesToDelete = [bootLogPath, configPath, webPath, botPath, phpPath, npmPath];
if (NEZHA_PORT) {
filesToDelete.push(npmPath);
} else if (NEZHA_SERVER && NEZHA_KEY) {
filesToDelete.push(phpPath);
}
exec(`rm -rf ${filesToDelete.join(' ')} >/dev/null 2>&1`, (error) => {
console.clear();
console.log('App is running');
console.log('Thank you for using this script, enjoy!');
});
}, 90000); // 90s
}
cleanFiles();
// 自动访问项目URL
async function AddVisitTask() {
if (!AUTO_ACCESS || !PROJECT_URL) {
console.log("Skipping adding automatic access task");
return;
}
try {
const response = await axios.post('https://oooo.serv00.net/add-url', {
url: PROJECT_URL
}, {
headers: {
'Content-Type': 'application/json'
}
});
// console.log(`${JSON.stringify(response.data)}`);
console.log(`automatic access task added successfully`);
} catch (error) {
console.error(`添加URL失败: ${error.message}`);
}
}
// 回调运行
async function startserver() {
deleteNodes();
cleanupOldFiles();
await downloadFilesAndRun();
await extractDomains();
AddVisitTask();
}
startserver();
app.listen(PORT, () => console.log(`http server is running on port:${PORT}!`));