-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.js
404 lines (374 loc) · 12.5 KB
/
core.js
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
const fetch = require('node-fetch');
const dotenv = require('dotenv');
const nodemailer = require('nodemailer');
const winston = require('winston');
const { exec } = require('child_process');
const fs = require('fs');
dotenv.config();
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console({ format: winston.format.simple() })
]
});
let transporter;
if (process.env.HOST && process.env.SENDER && process.env.SPASS) {
transporter = nodemailer.createTransport({
host: process.env.HOST,
port: 465,
secure: true,
auth: {
user: process.env.SENDER,
pass: process.env.SPASS,
},
});
}
let message = [];
async function fetchWithRetry(url, options, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(res => setTimeout(res, 1000 * (i + 1))); // Exponential backoff
}
}
}
async function grabDomainNames() {
try {
const data = await fetchWithRetry(`https://${process.env.PLESKURL}/api/v2/domains`, {
method: "GET",
headers: {
'X-API-Key': process.env.PLESKKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
return data.map(domain => domain.name);
} catch (error) {
logger.error('Error fetching domain names from Plesk:', error);
return [];
}
}
let domainInfo = [];
async function grabCloudflareDomains() {
let domains = [];
try {
let page = 1;
let totalPages = 1;
while (page <= totalPages) {
const data = await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones?match=all&account.id=${process.env.CLOUDACCOUNTID}&page=${page}`, {
method: 'GET',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
totalPages = data.result_info.total_pages;
domainInfo.push(...data.result);
domains.push(...data.result.map(domain => domain.name));
page++;
}
} catch (error) {
logger.error('Error fetching domain names from Cloudflare:', error);
}
return domains;
}
async function filterDomains() {
const [cloudflareDomains, pleskDomains] = await Promise.all([grabCloudflareDomains(), grabDomainNames()]);
return cloudflareDomains.filter(domain => pleskDomains.includes(domain));
}
async function getDNSRecords(domains) {
const records = await Promise.all(domains.map(async domain => {
try {
const data = await fetchWithRetry(`https://${process.env.PLESKURL}/api/v2/cli/dns/call`, {
method: 'POST',
headers: {
'X-API-Key': process.env.PLESKKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ "params": ["--info", domain] }),
});
return data.stdout.split("\n").filter(record => record.includes("_acme-challenge")).map(record => record.split(' '));
} catch (error) {
logger.error(`Error fetching DNS records for domain ${domain}:`, error);
return [];
}
}));
return records.flat();
}
async function mergeDNS(records) {
const results = await Promise.all(records.map(async record => {
const zone = record[4];
try {
const data = await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records?type=TXT&name=_acme-challenge.${record[5]}`, {
method: 'GET',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
if (!data.result[0]) {
record.push("create");
} else {
record.push(data.result[0].id);
record.push(data.result[0].content);
}
} catch (error) {
logger.error('Error checking DNS records on Cloudflare:', error);
}
return record;
}));
return results;
}
async function updateDNSRecord(record) {
const zone = record[4];
const dnsData = {
type: record[1],
name: record[0],
content: record[3],
ttl: 1,
};
try {
if (record[6] === 'create') {
await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records`, {
method: 'POST',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
},
body: JSON.stringify(dnsData),
});
} else if (record[3] !== record[7]) {
await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records/${record[6]}`, {
method: 'PUT',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
},
body: JSON.stringify(dnsData),
});
} else {
logger.info("No update needed for this record");
}
} catch (error) {
logger.error('Error updating DNS record on Cloudflare:', error);
}
}
async function renewSSLCertificates(domains) {
for (const domain of domains) {
try {
exec(`certbot renew --domain ${domain}`, (error, stdout, stderr) => {
if (error) {
logger.error(`Error renewing SSL certificate for ${domain}: ${error.message}`);
return;
}
if (stderr) {
logger.warn(`Stderr output for ${domain}: ${stderr}`);
}
logger.info(`SSL certificate renewed for ${domain}: ${stdout}`);
// Update DNS records on Cloudflare if necessary
updateDNSRecord(domain);
});
} catch (error) {
logger.error(`Error during SSL certificate renewal for ${domain}:`, error);
}
}
}
async function cleanupDNSRecords() {
const activeDomains = await grabDomainNames();
const cloudflareDomains = await grabCloudflareDomains();
const inactiveDomains = cloudflareDomains.filter(domain => !activeDomains.includes(domain));
for (const domain of inactiveDomains) {
try {
const zone = domainInfo.find(info => info.name === domain).id;
const records = await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records`, {
method: 'GET',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
for (const record of records.result) {
// Check if the record was created by this script
if (record.metadata && record.metadata.autoGenerated) {
await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records/${record.id}`, {
method: 'DELETE',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
logger.info(`Deleted DNS record ${record.name} for inactive domain ${domain}`);
}
}
} catch (error) {
logger.error(`Error cleaning up DNS records for ${domain}:`, error);
}
}
}
async function monitorDomainHealth() {
const domains = await grabDomainNames();
for (const domain of domains) {
try {
const response = await fetch(`http://${domain}`, { method: 'HEAD' });
if (!response.ok) {
throw new Error(`Domain health check failed for ${domain}`);
}
logger.info(`Domain ${domain} is healthy`);
} catch (error) {
logger.error(`Domain health check error for ${domain}: ${error.message}`);
sendAlertEmail(domain, error.message);
}
}
}
async function sendAlertEmail(domain, message) {
if (!transporter) {
logger.warn('Email settings not configured. Skipping email.');
return;
}
try {
await transporter.sendMail({
from: `"DNSBOT" <${process.env.SENDER}>`,
to: process.env.EMAIL,
subject: `Alert: Issue detected with domain ${domain}`,
text: message,
});
logger.info(`Alert email sent for domain ${domain}`);
} catch (error) {
logger.error('Error sending alert email:', error);
}
}
async function manageRedirectionAndDDoSProtection() {
const domains = await grabDomainNames();
for (const domain of domains) {
try {
// Set redirection settings
await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${domainInfo.find(info => info.name === domain).id}/settings/redirects`, {
method: 'PATCH',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ status: 'enabled' }),
});
// Enable DDoS protection
await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${domainInfo.find(info => info.name === domain).id}/settings/ddos_protection`, {
method: 'PATCH',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ status: 'enabled' }),
});
logger.info(`Redirection and DDoS protection settings updated for ${domain}`);
} catch (error) {
logger.error(`Error updating settings for ${domain}:`, error);
}
}
}
async function backupDNSConfigurations() {
const domains = await grabCloudflareDomains();
const backups = {};
for (const domain of domains) {
try {
const zone = domainInfo.find(info => info.name === domain).id;
const records = await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records`, {
method: 'GET',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
backups[domain] = records.result;
} catch (error) {
logger.error(`Error backing up DNS records for ${domain}:`, error);
}
}
fs.writeFileSync('dns_backup.json', JSON.stringify(backups, null, 2));
logger.info('DNS configurations backed up');
}
async function restoreDNSConfigurations() {
const backups = JSON.parse(fs.readFileSync('dns_backup.json'));
for (const domain in backups) {
const zone = domainInfo.find(info => info.name === domain).id;
for (const record of backups[domain]) {
try {
await fetchWithRetry(`https://api.cloudflare.com/client/v4/zones/${zone}/dns_records`, {
method: 'POST',
headers: {
'X-Auth-Email': process.env.CLOUDEMAIL,
'X-Auth-Key': process.env.CLOUDKEY,
'Content-Type': 'application/json',
},
body: JSON.stringify(record),
});
} catch (error) {
logger.error(`Error restoring DNS record for ${domain}:`, error);
}
}
logger.info(`DNS configurations restored for ${domain}`);
}
}
async function updateDNS() {
const domains = await filterDomains();
const records = await getDNSRecords(domains);
const mergedRecords = await mergeDNS(records);
await Promise.all(mergedRecords.map(updateDNSRecord));
message.push(mergedRecords);
await sendEmail(`DNS updates ${new Date()}`, message.join("\n"));
}
async function sendEmail(subject, text) {
if (!transporter) {
logger.warn('Email settings not configured. Skipping email.');
return;
}
try {
const info = await transporter.sendMail({
from: `"DNSBOT" <${process.env.SENDER}>`,
to: process.env.EMAIL,
subject: subject,
text: text,
});
logger.info("Message sent:", info.messageId);
} catch (error) {
logger.error('Error sending email:', error);
}
}
module.exports = {
fetchWithRetry,
grabDomainNames,
grabCloudflareDomains,
filterDomains,
getDNSRecords,
mergeDNS,
updateDNSRecord,
renewSSLCertificates,
cleanupDNSRecords,
monitorDomainHealth,
manageRedirectionAndDDoSProtection,
backupDNSConfigurations,
restoreDNSConfigurations,
updateDNS,
sendEmail,
};