-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
575 lines (506 loc) · 17.8 KB
/
index.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
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
import { ImapFlow } from "imapflow";
import { uniqueUsernameGenerator } from "unique-username-generator";
import { simpleParser } from "mailparser";
import axios from "axios";
/**
* Represents a client for interacting with a Mail-in-a-Box server.
*/
class MiabClient {
/**
* @param {String} apiUrl URL like https://box.example.com
* @param {String} apiEmail Admin Email Address
* @param {String} apiPassword Admin Password
*/
constructor(apiUrl, apiEmail, apiPassword, debug = false) {
if (!apiUrl || !apiEmail || !apiPassword) throw new Error('The apiUrl, apiEmail and apiPassword must be provided.');
this.apiUrl = apiUrl;
this.apiEmail = apiEmail;
this.apiPassword = apiPassword;
this.apiKey = Buffer.from(apiEmail + ':' + apiPassword).toString('base64');
this.debug = debug;
}
genUsername() {
return uniqueUsernameGenerator({
dictionaries: [[
'anna',
'maria',
'julia',
'sophia',
'emily',
'emma',
'olivia',
'isabella',
'ava',
'mia',
'madison',
'elizabeth',
'abigail',
'hannah',
'addison',
'mike',
'john',
'david',
'james',
'robert',
'michael',
'william',
'joseph',
'charles',
'thomas',
'christopher',
'daniel',
'matthew',
'anthony',
'mark',
'donald',
'steven',
'paul',
'andrew',
'joshua',
'kenneth',
'kevin',
'brian',
'george',
'edward',
], [
'smith',
'johnson',
'williams',
'brown',
'jones',
'miller',
'davis',
'garcia',
'rodriguez',
'wilson',
'martinez',
'anderson',
'taylor',
'thomas',
'hernandez',
'moore',
'martin',
'jackson',
'thompson',
'white',
'lopez',
'lee',
'gonzalez',
'harris',
'clark',
'lewis',
'robinson',
'walker',
'perez',
'hall',
'young',
'allen',
'sanchez',
'wright',
'king',
'scott',
'green',
'baker',
'adams',
'nelson',
'hill',
'ramirez',
'campbell',
'mitchell',
'roberts',
'carter',
'phillips',
'evans',
'turner',
'torres',
'parker',
], [
// aa-zz
...(Array.from({ length: 26 }, (_, i) =>
Array.from({ length: 26 }, (_, j) =>
String.fromCharCode(97 + i) + String.fromCharCode(97 + j)
)
).flat())
],
[
// 0-99
...(
Array.from({ length: 100 }, (_, i) => i)
)
]
],
separator: ''
});
}
generatePassword(length = 12) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
}
async #sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async #request(method, url, data = null) {
/**
* @type {import('axios').AxiosRequestConfig}
*/
const config = {
method: method,
url: url,
headers: {
'Authorization': 'Basic ' + this.apiKey,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 5 * 60 * 1000,
data: data
};
return axios(config);
}
async #get(url) {
return this.#request('get', url);
}
async #post(url, data) {
return this.#request('post', url, data);
}
/**
* Method to create a new mailbox
* @param {String} domain The domain name to create the mailbox on
* @param {String} username The username of the mailbox
* @param {String} password Minimum 8 characters
* @returns
*/
async createMailbox(domain, username = this.genUsername(), password = this.generatePassword()) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/users/add',
`email=${username}@${domain}&password=${password}`
)
const data = response.data.trim();
if (data !== 'mail user added') {
throw new Error(data);
}
return {
success: true,
response: data,
email: username + '@' + domain,
password: password
}
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* Method to delete an existing mailbox
* @param {String} email
* @returns
*/
async deleteMailbox(email) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/users/delete',
`email=${email}`
)
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* @typedef {import('mailparser').ParsedMail} ParsedMail
*/
/**
* Method to get all emails from a mailbox
* @param {String} email
* @param {String} password
* @returns {Promise<{success: Boolean, response: ParsedMail[]>}
*/
async getEmails(email, password) {
try {
/**
* @type {ImapFlow}
*/
const client = new ImapFlow({
host: new URL(this.apiUrl).host,
port: 993,
secure: true,
auth: {
user: email,
pass: password
},
logger: false,
maxIdleTime: 60000
});
await client.connect();
const mailbox = await client.mailboxOpen('INBOX');
if (mailbox.exists === 0) {
await client.logout();
return { success: true, response: [] };
}
const messagesFunc = client.fetch('1:*', { source: true });
const messages = [];
for await (const msg of messagesFunc) {
const parsed = await simpleParser(msg.source);
messages.push(parsed);
}
await client.logout();
return { success: true, response: messages };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
#isRegex(str) {
try {
new RegExp(str);
return true;
} catch (error) {
return false;
}
}
/**
* Method to filter emails
* @param {ParsedMail[]} emails
* @param {Object} options - The filtering options.
* @param {String[] | RegExp[]} options.regex - The regex patterns to match.
* @param {String} options.from - The sender's email address.
* @param {String} options.subject - The email subject.
* @returns {ParsedMail[]}
*/
filterEmails(emails, options = {}) {
let { regex = [], from = '', subject = '' } = options;
if (regex.length === 0 && from === '' && subject === '') {
throw new Error('At least one option must be specified. All options cannot be default values.');
}
if (!Array.isArray(regex)) {
console.error('The regex option must be an array. Trying to experimentally convert it to an array.');
if (this.#isRegex(regex) || typeof regex === 'string') {
regex = [regex];
} else {
throw new Error('The regex option must be an array and either a valid string or regex. Failed to experimentally convert it to an array.');
}
}
return emails.filter(email => {
// Check if the email matches the regex patterns.
const regexMatch = Array.isArray(regex) ? regex.some(r => {
if (this.#isRegex(r)) {
const regex = new RegExp(r);
return regex.test(email.textAsHtml) || regex.test(email.text);
} else {
return email.textAsHtml.includes(r) || email.text.includes(r);
}
}) : true;
// Check if the email is from the specified sender.
const fromMatch = from ? email.from.text.includes(from) : true;
// Check if the email has the specified subject.
const subjectMatch = subject ? email.subject.includes(subject) : true;
return regexMatch && fromMatch && subjectMatch;
});
}
/**
* Method to wait for an specific email
* @param {Object} options - The options for the waitForEmail method.
* @param {String} options.email - The email address.
* @param {String} options.password - The email password.
* @param {String} options.from - The sender's email address.
* @param {String} options.subject - The email subject.
* @param {String[] | RegExp[]} options.regex - The regex patterns to match.
* @param {Number} options.timeout - The timeout in milliseconds.
* @param {Number} options.interval - The interval in milliseconds.
* @returns {Promise<{success: Boolean, response: ParsedMail} | {success: Boolean, response: String}>}
* @throws {Error} - On error
*/
async waitForEmail(options) {
const { from, subject, regex, timeout = 5 * 60 * 1000, interval = 3000 } = options;
const { email, password } = options;
if (!email || !password) {
return { success: false, response: 'The email and password must be provided.' };
}
if (!from && !subject && !regex) {
return { success: false, response: 'At least one filtering of the options must be provided.' };
}
const start = Date.now();
let emails = [];
while (Date.now() - start < timeout) {
emails = (await this.getEmails(email, password)).response;
const filteredEmails = this.filterEmails(emails, { from, subject, regex });
this.debug && console.log('Filtered Emails:', filteredEmails);
if (filteredEmails.length > 0) {
return { success: true, response: filteredEmails[0] };
}
this.debug && console.log('Email not found within the timeout. Waiting...');
await this.#sleep(interval);
}
return { success: false, response: 'Email not found within the timeout.' }
}
/**
* Method to get the email address of the admin
* @returns {String}
*/
getEmail() {
return this.apiEmail;
}
/**
* Method to get the password of the admin
* @returns {String}
*/
getPassword() {
return this.apiPassword;
}
/**
* Method to change the email address of the admin
*/
setEmail(email) {
this.apiEmail = email;
this.apiKey = Buffer.from(email + ':' + this.apiPassword).toString('base64');
}
/**
* Method to change the password of the admin
*/
setPassword(password) {
this.apiPassword = password;
this.apiKey = Buffer.from(this.apiEmail + ':' + password).toString('base64');
}
/**
* Method used to make a mail user an admin
* @param {String} email
* @returns {Promise<{success: Boolean, response: String}>}
*/
async makeAdmin(email) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/users/privileges/add',
`email=${email}&privilege=admin`
)
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* Method used to remove admin privileges from a mail user
* @param {String} email
* @returns {Promise<{success: Boolean, response: String}>}
*/
async removeAdmin(email) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/users/privileges/remove',
`email=${email}`
)
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* @typedef {Object} User
* @property {String} email
* @property {privileges: String[]} privileges
* @property {String} status
*/
/**
* @typedef {Object} Mailbox
* @property {String} domain
* @property {User[]} users
*/
/**
* Method to get all mailboxes
* @returns {Promise<{success: Boolean, response: Mailbox[], emails: String[]}>}
*/
async getMailboxes() {
try {
const response = await this.#get(this.apiUrl + '/admin/mail/users?format=json');
if (Array.isArray(response.data)) {
const emails = response.data.map(mailbox => mailbox.users.map(user => user.email)).flat();
return { success: true, response: response.data, emails: emails };
} else {
return { success: false, response: response.data };
}
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* Method to get all mail aliases
* @returns {Promise<{success: Boolean, response: Object[]}>}
*/
async getMailAliases() {
try {
const response = await this.#get(this.apiUrl + '/admin/mail/aliases?format=json');
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* Method to add a new mail alias
* @param {String} address Email address
* @param {String} forwardsTo Email address to forward to
* @returns {Promise<{success: Boolean, response: String}>}
*/
async addMailAlias(address, forwardsTo) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/aliases/add',
`address=${address}&forwards_to=${forwardsTo}`);
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* Method to remove a mail alias
* @param {String} address
* @returns {Promise<{success: Boolean, response: String}>}
*/
async removeMailAlias(address) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/aliases/remove',
`address=${address}`);
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* Method to set the password of a mailbox
* @param {String} email
* @param {String} password
* @returns {Promise<{success: Boolean, response: String}>}
*/
async updatePassword(email, password = this.generatePassword(12)) {
try {
const response = await this.#post(this.apiUrl + '/admin/mail/users/password',
`email=${email}&password=${password}`);
return { success: true, response: response.data, email: email, password: password };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
* @typedef {Object} WebDomain
* @property {String} custom_root The custom root directory for the web domain
* @property {String} domain The domain name
* @property {String} root The root directory for the web domain
* @property {String[]} ssl_certificate The SSL certificate for the web domain
* @property {String} static_enabled
*/
/**
* Method to get the web domains
* @returns {Promise<{success: Boolean, response: WebDomain[], domains: String[]}>}
*/
async getWebDomains() {
try {
const response = await this.#get(this.apiUrl + '/admin/web/domains',);
return { success: true, response: response.data, domains: response.data.map(domain => domain.domain) };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
/**
*
* @returns {Promise<{success: Boolean, response: String}>}
*/
async getVersion() {
try {
const response = await this.#get(this.apiUrl + '/admin/system/version');
return { success: true, response: response.data };
} catch (error) {
return { success: false, response: error?.response?.data || error };
}
}
}
export default MiabClient;