emailjs 4.0.3 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +215 -247
  2. package/dist/address.d.ts +6 -0
  3. package/dist/address.js +183 -0
  4. package/dist/address.js.map +1 -0
  5. package/dist/address.test.d.ts +1 -0
  6. package/dist/address.test.js +120 -0
  7. package/dist/address.test.js.map +1 -0
  8. package/dist/auth.integration.test.d.ts +1 -0
  9. package/dist/auth.integration.test.js +137 -0
  10. package/dist/auth.integration.test.js.map +1 -0
  11. package/dist/client.d.ts +39 -0
  12. package/dist/client.integration.test.d.ts +1 -0
  13. package/dist/client.integration.test.js +198 -0
  14. package/dist/client.integration.test.js.map +1 -0
  15. package/dist/client.js +202 -0
  16. package/dist/client.js.map +1 -0
  17. package/dist/client.test.d.ts +1 -0
  18. package/dist/client.test.js +293 -0
  19. package/dist/client.test.js.map +1 -0
  20. package/dist/connection.commands.integration.test.d.ts +1 -0
  21. package/dist/connection.commands.integration.test.js +79 -0
  22. package/dist/connection.commands.integration.test.js.map +1 -0
  23. package/dist/connection.d.ts +83 -0
  24. package/dist/connection.errors.integration.test.d.ts +1 -0
  25. package/dist/connection.errors.integration.test.js +186 -0
  26. package/dist/connection.errors.integration.test.js.map +1 -0
  27. package/dist/connection.greylist.integration.test.d.ts +1 -0
  28. package/dist/connection.greylist.integration.test.js +53 -0
  29. package/dist/connection.greylist.integration.test.js.map +1 -0
  30. package/dist/connection.integration.test.d.ts +1 -0
  31. package/dist/connection.integration.test.js +223 -0
  32. package/dist/connection.integration.test.js.map +1 -0
  33. package/dist/connection.js +492 -0
  34. package/dist/connection.js.map +1 -0
  35. package/dist/connection.test.d.ts +1 -0
  36. package/dist/connection.test.js +50 -0
  37. package/dist/connection.test.js.map +1 -0
  38. package/dist/date.d.ts +3 -0
  39. package/dist/date.js +26 -0
  40. package/dist/date.js.map +1 -0
  41. package/dist/date.test.d.ts +1 -0
  42. package/dist/date.test.js +26 -0
  43. package/dist/date.test.js.map +1 -0
  44. package/dist/error.d.ts +20 -0
  45. package/dist/error.js +31 -0
  46. package/dist/error.js.map +1 -0
  47. package/dist/error.test.d.ts +1 -0
  48. package/dist/error.test.js +23 -0
  49. package/dist/error.test.js.map +1 -0
  50. package/dist/index.d.ts +8 -0
  51. package/dist/index.js +9 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/message.d.ts +71 -0
  54. package/dist/message.integration.test.d.ts +1 -0
  55. package/dist/message.integration.test.js +401 -0
  56. package/dist/message.integration.test.js.map +1 -0
  57. package/dist/message.js +456 -0
  58. package/dist/message.js.map +1 -0
  59. package/dist/message.test.d.ts +1 -0
  60. package/dist/message.test.js +258 -0
  61. package/dist/message.test.js.map +1 -0
  62. package/dist/mime.d.ts +2 -0
  63. package/dist/mime.js +145 -0
  64. package/dist/mime.js.map +1 -0
  65. package/dist/mime.test.d.ts +1 -0
  66. package/dist/mime.test.js +76 -0
  67. package/dist/mime.test.js.map +1 -0
  68. package/dist/response.d.ts +6 -0
  69. package/dist/response.js +93 -0
  70. package/dist/response.js.map +1 -0
  71. package/dist/response.test.d.ts +1 -0
  72. package/dist/response.test.js +177 -0
  73. package/dist/response.test.js.map +1 -0
  74. package/package.json +30 -28
  75. package/email.js +0 -2126
  76. package/email.ts +0 -8
  77. package/smtp/address.ts +0 -237
  78. package/smtp/client.ts +0 -365
  79. package/smtp/connection.ts +0 -937
  80. package/smtp/date.ts +0 -51
  81. package/smtp/error.ts +0 -57
  82. package/smtp/message.ts +0 -774
  83. package/smtp/mime.ts +0 -234
  84. package/smtp/response.ts +0 -112
@@ -1,937 +0,0 @@
1
- import { createHmac } from 'crypto';
2
- import { EventEmitter } from 'events';
3
- import { Socket } from 'net';
4
- import { hostname } from 'os';
5
- import { connect, createSecureContext, TLSSocket } from 'tls';
6
- import type { ConnectionOptions } from 'tls';
7
-
8
- import { SMTPError, SMTPErrorStates } from './error.js';
9
- import { SMTPResponseMonitor } from './response.js';
10
-
11
- /**
12
- * @readonly
13
- * @enum
14
- */
15
- export const AUTH_METHODS = {
16
- PLAIN: 'PLAIN',
17
- 'CRAM-MD5': 'CRAM-MD5',
18
- LOGIN: 'LOGIN',
19
- XOAUTH2: 'XOAUTH2',
20
- } as const;
21
-
22
- /**
23
- * @readonly
24
- * @enum
25
- */
26
- export const SMTPState = {
27
- NOTCONNECTED: 0,
28
- CONNECTING: 1,
29
- CONNECTED: 2,
30
- } as const;
31
-
32
- export const DEFAULT_TIMEOUT = 5000 as const;
33
-
34
- const SMTP_PORT = 25 as const;
35
- const SMTP_SSL_PORT = 465 as const;
36
- const SMTP_TLS_PORT = 587 as const;
37
- const CRLF = '\r\n' as const;
38
- const GREYLIST_DELAY = 300 as const;
39
-
40
- let DEBUG: 0 | 1 = 0;
41
-
42
- /**
43
- * @param {...any[]} args the message(s) to log
44
- * @returns {void}
45
- */
46
- const log = (...args: any[]) => {
47
- if (DEBUG === 1) {
48
- args.forEach((d) =>
49
- console.log(
50
- typeof d === 'object'
51
- ? d instanceof Error
52
- ? d.message
53
- : JSON.stringify(d)
54
- : d
55
- )
56
- );
57
- }
58
- };
59
-
60
- /**
61
- * @param {function(...any[]): void} callback the function to call
62
- * @param {...any[]} args the arguments to apply to the function
63
- * @returns {void}
64
- */
65
- const caller = (callback?: (...rest: any[]) => void, ...args: any[]) => {
66
- if (typeof callback === 'function') {
67
- callback(...args);
68
- }
69
- };
70
-
71
- export type SMTPSocketOptions = Omit<
72
- ConnectionOptions,
73
- 'port' | 'host' | 'path' | 'socket' | 'timeout' | 'secureContext'
74
- >;
75
-
76
- export interface SMTPConnectionOptions {
77
- timeout: number | null;
78
- user: string;
79
- password: string;
80
- domain: string;
81
- host: string;
82
- port: number;
83
- ssl: boolean | SMTPSocketOptions;
84
- tls: boolean | SMTPSocketOptions;
85
- authentication: (keyof typeof AUTH_METHODS)[];
86
- logger: (...args: any[]) => void;
87
- }
88
-
89
- export interface ConnectOptions {
90
- ssl?: boolean;
91
- }
92
-
93
- export class SMTPConnection extends EventEmitter {
94
- public readonly user: () => string;
95
- public readonly password: () => string;
96
- public readonly timeout: number = DEFAULT_TIMEOUT;
97
-
98
- protected readonly log = log;
99
- protected readonly authentication: (keyof typeof AUTH_METHODS)[] = [
100
- AUTH_METHODS['CRAM-MD5'],
101
- AUTH_METHODS.LOGIN,
102
- AUTH_METHODS.PLAIN,
103
- AUTH_METHODS.XOAUTH2,
104
- ];
105
-
106
- protected _state: 0 | 1 | 2 = SMTPState.NOTCONNECTED;
107
- protected _secure = false;
108
- protected loggedin = false;
109
-
110
- protected sock: Socket | TLSSocket | null = null;
111
- protected features: { [index: string]: string | boolean } | null = null;
112
- protected monitor: SMTPResponseMonitor | null = null;
113
- protected domain = hostname();
114
- protected host = 'localhost';
115
- protected ssl: boolean | SMTPSocketOptions = false;
116
- protected tls: boolean | SMTPSocketOptions = false;
117
- protected port: number;
118
-
119
- private greylistResponseTracker = new WeakSet<(...rest: any[]) => void>();
120
-
121
- /**
122
- * SMTP class written using python's (2.7) smtplib.py as a base.
123
- *
124
- * To target a Message Transfer Agent (MTA), omit all options.
125
- *
126
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
127
- */
128
- constructor({
129
- timeout,
130
- host,
131
- user,
132
- password,
133
- domain,
134
- port,
135
- ssl,
136
- tls,
137
- logger,
138
- authentication,
139
- }: Partial<SMTPConnectionOptions> = {}) {
140
- super();
141
-
142
- if (Array.isArray(authentication)) {
143
- this.authentication = authentication;
144
- }
145
-
146
- if (typeof timeout === 'number') {
147
- this.timeout = timeout;
148
- }
149
-
150
- if (typeof domain === 'string') {
151
- this.domain = domain;
152
- }
153
-
154
- if (typeof host === 'string') {
155
- this.host = host;
156
- }
157
-
158
- if (
159
- ssl != null &&
160
- (typeof ssl === 'boolean' ||
161
- (typeof ssl === 'object' && Array.isArray(ssl) === false))
162
- ) {
163
- this.ssl = ssl;
164
- }
165
-
166
- if (
167
- tls != null &&
168
- (typeof tls === 'boolean' ||
169
- (typeof tls === 'object' && Array.isArray(tls) === false))
170
- ) {
171
- this.tls = tls;
172
- }
173
-
174
- this.port = port || (ssl ? SMTP_SSL_PORT : tls ? SMTP_TLS_PORT : SMTP_PORT);
175
- this.loggedin = user && password ? false : true;
176
-
177
- if (!user && (password?.length ?? 0) > 0) {
178
- throw new Error('`password` cannot be set without `user`');
179
- }
180
-
181
- // keep these strings hidden when quicky debugging/logging
182
- this.user = () => user as string;
183
- this.password = () => password as string;
184
-
185
- if (typeof logger === 'function') {
186
- this.log = logger;
187
- }
188
- }
189
-
190
- /**
191
- * @public
192
- * @param {0 | 1} level -
193
- * @returns {void}
194
- */
195
- public debug(level: 0 | 1) {
196
- DEBUG = level;
197
- }
198
-
199
- /**
200
- * @public
201
- * @returns {SMTPState} the current state
202
- */
203
- public state() {
204
- return this._state;
205
- }
206
-
207
- /**
208
- * @public
209
- * @returns {boolean} whether or not the instance is authorized
210
- */
211
- public authorized() {
212
- return this.loggedin;
213
- }
214
-
215
- /**
216
- * Establish an SMTP connection.
217
- *
218
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
219
- *
220
- * @public
221
- * @param {function(...any[]): void} callback function to call after response
222
- * @param {number} [port] the port to use for the connection
223
- * @param {string} [host] the hostname to use for the connection
224
- * @param {ConnectOptions} [options={}] the options
225
- * @returns {void}
226
- */
227
- public connect(
228
- callback: (...rest: any[]) => void,
229
- port: number = this.port,
230
- host: string = this.host,
231
- options: ConnectOptions = {}
232
- ) {
233
- this.port = port;
234
- this.host = host;
235
- this.ssl = options.ssl || this.ssl;
236
-
237
- if (this._state !== SMTPState.NOTCONNECTED) {
238
- this.quit(() => this.connect(callback, port, host, options));
239
- }
240
-
241
- /**
242
- * @returns {void}
243
- */
244
- const connected = () => {
245
- this.log(`connected: ${this.host}:${this.port}`);
246
-
247
- if (this.ssl && !this.tls) {
248
- // if key/ca/cert was passed in, check if connection is authorized
249
- if (
250
- typeof this.ssl !== 'boolean' &&
251
- this.sock instanceof TLSSocket &&
252
- !this.sock.authorized
253
- ) {
254
- this.close(true);
255
- caller(
256
- callback,
257
- SMTPError.create(
258
- 'could not establish an ssl connection',
259
- SMTPErrorStates.CONNECTIONAUTH
260
- )
261
- );
262
- } else {
263
- this._secure = true;
264
- }
265
- }
266
- };
267
-
268
- /**
269
- * @param {Error} err err
270
- * @returns {void}
271
- */
272
- const connectedErrBack = (err?: Error) => {
273
- if (!err) {
274
- connected();
275
- } else {
276
- this.close(true);
277
- this.log(err);
278
- caller(
279
- callback,
280
- SMTPError.create(
281
- 'could not connect',
282
- SMTPErrorStates.COULDNOTCONNECT,
283
- err
284
- )
285
- );
286
- }
287
- };
288
-
289
- const response = (
290
- err: Error | null | undefined,
291
- msg: { code: string | number; data: string }
292
- ) => {
293
- if (err) {
294
- if (this._state === SMTPState.NOTCONNECTED && !this.sock) {
295
- return;
296
- }
297
- this.close(true);
298
- caller(callback, err);
299
- } else if (msg.code == '220') {
300
- this.log(msg.data);
301
-
302
- // might happen first, so no need to wait on connected()
303
- this._state = SMTPState.CONNECTED;
304
- caller(callback, null, msg.data);
305
- } else {
306
- this.log(`response (data): ${msg.data}`);
307
- this.quit(() => {
308
- caller(
309
- callback,
310
- SMTPError.create(
311
- 'bad response on connection',
312
- SMTPErrorStates.BADRESPONSE,
313
- err,
314
- msg.data
315
- )
316
- );
317
- });
318
- }
319
- };
320
-
321
- this._state = SMTPState.CONNECTING;
322
- this.log(`connecting: ${this.host}:${this.port}`);
323
-
324
- if (this.ssl) {
325
- this.sock = connect(
326
- this.port,
327
- this.host.trim(),
328
- typeof this.ssl === 'object' ? this.ssl : {},
329
- connected
330
- );
331
- } else {
332
- this.sock = new Socket();
333
- this.sock.connect(this.port, this.host.trim(), connectedErrBack);
334
- }
335
-
336
- this.monitor = new SMTPResponseMonitor(this.sock, this.timeout, () =>
337
- this.close(true)
338
- );
339
- this.sock.once('response', response);
340
- this.sock.once('error', response); // the socket could reset or throw, so let's handle it and let the user know
341
- }
342
-
343
- /**
344
- * @public
345
- * @param {string} str the string to send
346
- * @param {function(...any[]): void} callback function to call after response
347
- * @returns {void}
348
- */
349
- public send(str: string, callback: (...args: any[]) => void) {
350
- if (this.sock != null && this._state === SMTPState.CONNECTED) {
351
- this.log(str);
352
-
353
- this.sock.once('response', (err, msg) => {
354
- if (err) {
355
- caller(callback, err);
356
- } else {
357
- this.log(msg.data);
358
- caller(callback, null, msg);
359
- }
360
- });
361
- if (this.sock.writable) {
362
- this.sock.write(str);
363
- }
364
- } else {
365
- this.close(true);
366
- caller(
367
- callback,
368
- SMTPError.create(
369
- 'no connection has been established',
370
- SMTPErrorStates.NOCONNECTION
371
- )
372
- );
373
- }
374
- }
375
-
376
- /**
377
- * @public
378
- * @param {string} cmd command to issue
379
- * @param {function(...any[]): void} callback function to call after response
380
- * @param {(number[] | number)} [codes=[250]] array codes
381
- * @returns {void}
382
- */
383
- public command(
384
- cmd: string,
385
- callback: (...rest: any[]) => void,
386
- codes: number[] | number = [250]
387
- ) {
388
- const codesArray = Array.isArray(codes)
389
- ? codes
390
- : typeof codes === 'number'
391
- ? [codes]
392
- : [250];
393
-
394
- const response = (
395
- err: Error | null | undefined,
396
- msg: { code: string | number; data: string; message: string }
397
- ) => {
398
- if (err) {
399
- caller(callback, err);
400
- } else {
401
- const code = Number(msg.code);
402
- if (codesArray.indexOf(code) !== -1) {
403
- caller(callback, err, msg.data, msg.message);
404
- } else if (
405
- (code === 450 || code === 451) &&
406
- msg.message.toLowerCase().includes('greylist') &&
407
- this.greylistResponseTracker.has(response) === false
408
- ) {
409
- this.greylistResponseTracker.add(response);
410
- setTimeout(() => {
411
- this.send(cmd + CRLF, response);
412
- }, GREYLIST_DELAY);
413
- } else {
414
- const suffix = msg.message ? `: ${msg.message}` : '';
415
- const errorMessage = `bad response on command '${
416
- cmd.split(' ')[0]
417
- }'${suffix}`;
418
- caller(
419
- callback,
420
- SMTPError.create(
421
- errorMessage,
422
- SMTPErrorStates.BADRESPONSE,
423
- null,
424
- msg.data
425
- )
426
- );
427
- }
428
- }
429
- };
430
-
431
- this.greylistResponseTracker.delete(response);
432
- this.send(cmd + CRLF, response);
433
- }
434
-
435
- /**
436
- * @public
437
- * @description SMTP 'helo' command.
438
- *
439
- * Hostname to send for self command defaults to the FQDN of the local
440
- * host.
441
- *
442
- * As this command was deprecated by rfc2821, it should only be used for compatibility with non-compliant servers.
443
- * @see https://tools.ietf.org/html/rfc2821#appendix-F.3
444
- *
445
- * @param {function(...any[]): void} callback function to call after response
446
- * @param {string} domain the domain to associate with the 'helo' request
447
- * @returns {void}
448
- */
449
- public helo(callback: (...rest: any[]) => void, domain?: string) {
450
- this.command(`helo ${domain || this.domain}`, (err, data) => {
451
- if (err) {
452
- caller(callback, err);
453
- } else {
454
- this.parse_smtp_features(data);
455
- caller(callback, err, data);
456
- }
457
- });
458
- }
459
-
460
- /**
461
- * @public
462
- * @param {function(...any[]): void} callback function to call after response
463
- * @returns {void}
464
- */
465
- public starttls(callback: (...rest: any[]) => void) {
466
- const response = (err: Error, msg: { data: unknown }) => {
467
- if (this.sock == null) {
468
- throw new Error('null socket');
469
- }
470
-
471
- if (err) {
472
- err.message += ' while establishing a starttls session';
473
- caller(callback, err);
474
- } else {
475
- const secureContext = createSecureContext(
476
- typeof this.tls === 'object' ? this.tls : {}
477
- );
478
- const secureSocket = new TLSSocket(this.sock, { secureContext });
479
-
480
- secureSocket.on('error', (err: Error) => {
481
- this.close(true);
482
- caller(callback, err);
483
- });
484
-
485
- this._secure = true;
486
- this.sock = secureSocket;
487
-
488
- new SMTPResponseMonitor(this.sock, this.timeout, () =>
489
- this.close(true)
490
- );
491
- caller(callback, msg.data);
492
- }
493
- };
494
-
495
- this.command('starttls', response, [220]);
496
- }
497
-
498
- /**
499
- * @public
500
- * @param {string} data the string to parse for features
501
- * @returns {void}
502
- */
503
- public parse_smtp_features(data: string) {
504
- // According to RFC1869 some (badly written)
505
- // MTA's will disconnect on an ehlo. Toss an exception if
506
- // that happens -ddm
507
-
508
- data.split('\n').forEach((ext) => {
509
- const parse = ext.match(/^(?:\d+[-=]?)\s*?([^\s]+)(?:\s+(.*)\s*?)?$/);
510
-
511
- // To be able to communicate with as many SMTP servers as possible,
512
- // we have to take the old-style auth advertisement into account,
513
- // because:
514
- // 1) Else our SMTP feature parser gets confused.
515
- // 2) There are some servers that only advertise the auth methods we
516
- // support using the old style.
517
-
518
- if (parse != null && this.features != null) {
519
- // RFC 1869 requires a space between ehlo keyword and parameters.
520
- // It's actually stricter, in that only spaces are allowed between
521
- // parameters, but were not going to check for that here. Note
522
- // that the space isn't present if there are no parameters.
523
- this.features[parse[1].toLowerCase()] = parse[2] || true;
524
- }
525
- });
526
- }
527
-
528
- /**
529
- * @public
530
- * @param {function(...any[]): void} callback function to call after response
531
- * @param {string} domain the domain to associate with the 'ehlo' request
532
- * @returns {void}
533
- */
534
- public ehlo(callback: (...rest: any[]) => void, domain?: string) {
535
- this.features = {};
536
- this.command(`ehlo ${domain || this.domain}`, (err, data) => {
537
- if (err) {
538
- caller(callback, err);
539
- } else {
540
- this.parse_smtp_features(data);
541
-
542
- if (this.tls && !this._secure) {
543
- this.starttls(() => this.ehlo(callback, domain));
544
- } else {
545
- caller(callback, err, data);
546
- }
547
- }
548
- });
549
- }
550
-
551
- /**
552
- * @public
553
- * @param {string} opt the features keyname to check
554
- * @returns {boolean} whether the extension exists
555
- */
556
- public has_extn(opt: string) {
557
- return (this.features ?? {})[opt.toLowerCase()] === undefined;
558
- }
559
-
560
- /**
561
- * @public
562
- * @description SMTP 'help' command, returns text from the server
563
- * @param {function(...any[]): void} callback function to call after response
564
- * @param {string} domain the domain to associate with the 'help' request
565
- * @returns {void}
566
- */
567
- public help(callback: (...rest: any[]) => void, domain: string) {
568
- this.command(domain ? `help ${domain}` : 'help', callback, [211, 214]);
569
- }
570
-
571
- /**
572
- * @public
573
- * @param {function(...any[]): void} callback function to call after response
574
- * @returns {void}
575
- */
576
- public rset(callback: (...rest: any[]) => void) {
577
- this.command('rset', callback);
578
- }
579
-
580
- /**
581
- * @public
582
- * @param {function(...any[]): void} callback function to call after response
583
- * @returns {void}
584
- */
585
- public noop(callback: (...rest: any[]) => void) {
586
- this.send('noop', callback);
587
- }
588
-
589
- /**
590
- * @public
591
- * @param {function(...any[]): void} callback function to call after response
592
- * @param {string} from the sender
593
- * @returns {void}
594
- */
595
- public mail(callback: (...rest: any[]) => void, from: string) {
596
- this.command(`mail FROM:${from}`, callback);
597
- }
598
-
599
- /**
600
- * @public
601
- * @param {function(...any[]): void} callback function to call after response
602
- * @param {string} to the receiver
603
- * @returns {void}
604
- */
605
- public rcpt(callback: (...rest: any[]) => void, to: string) {
606
- this.command(`RCPT TO:${to}`, callback, [250, 251]);
607
- }
608
-
609
- /**
610
- * @public
611
- * @param {function(...any[]): void} callback function to call after response
612
- * @returns {void}
613
- */
614
- public data(callback: (...rest: any[]) => void) {
615
- this.command('data', callback, [354]);
616
- }
617
-
618
- /**
619
- * @public
620
- * @param {function(...any[]): void} callback function to call after response
621
- * @returns {void}
622
- */
623
- public data_end(callback: (...rest: any[]) => void) {
624
- this.command(`${CRLF}.`, callback);
625
- }
626
-
627
- /**
628
- * @public
629
- * @param {string} data the message to send
630
- * @returns {void}
631
- */
632
- public message(data: string) {
633
- this.log(data);
634
- this.sock?.write(data) ?? this.log('no socket to write to');
635
- }
636
-
637
- /**
638
- * @public
639
- * @description SMTP 'verify' command -- checks for address validity.
640
- * @param {string} address the address to validate
641
- * @param {function(...any[]): void} callback function to call after response
642
- * @returns {void}
643
- */
644
- public verify(address: string, callback: (...rest: any[]) => void) {
645
- this.command(`vrfy ${address}`, callback, [250, 251, 252]);
646
- }
647
-
648
- /**
649
- * @public
650
- * @description SMTP 'expn' command -- expands a mailing list.
651
- * @param {string} address the mailing list to expand
652
- * @param {function(...any[]): void} callback function to call after response
653
- * @returns {void}
654
- */
655
- public expn(address: string, callback: (...rest: any[]) => void) {
656
- this.command(`expn ${address}`, callback);
657
- }
658
-
659
- /**
660
- * @public
661
- * @description Calls this.ehlo() and, if an error occurs, this.helo().
662
- *
663
- * If there has been no previous EHLO or HELO command self session, self
664
- * method tries ESMTP EHLO first.
665
- *
666
- * @param {function(...any[]): void} callback function to call after response
667
- * @param {string} [domain] the domain to associate with the command
668
- * @returns {void}
669
- */
670
- public ehlo_or_helo_if_needed(
671
- callback: (...rest: any[]) => void,
672
- domain?: string
673
- ) {
674
- // is this code callable...?
675
- if (!this.features) {
676
- const response = (err: Error, data: unknown) =>
677
- caller(callback, err, data);
678
- this.ehlo((err, data) => {
679
- if (err) {
680
- this.helo(response, domain);
681
- } else {
682
- caller(callback, err, data);
683
- }
684
- }, domain);
685
- }
686
- }
687
-
688
- /**
689
- * @public
690
- *
691
- * Log in on an SMTP server that requires authentication.
692
- *
693
- * If there has been no previous EHLO or HELO command self session, self
694
- * method tries ESMTP EHLO first.
695
- *
696
- * This method will return normally if the authentication was successful.
697
- *
698
- * @param {function(...any[]): void} callback function to call after response
699
- * @param {string} [user] the username to authenticate with
700
- * @param {string} [password] the password for the authentication
701
- * @param {{ method: string, domain: string }} [options] login options
702
- * @returns {void}
703
- */
704
- public login(
705
- callback: (...rest: any[]) => void,
706
- user?: string,
707
- password?: string,
708
- options: { method?: string; domain?: string } = {}
709
- ) {
710
- const login = {
711
- user: user ? () => user : this.user,
712
- password: password ? () => password : this.password,
713
- method: options?.method?.toUpperCase() ?? '',
714
- };
715
-
716
- const domain = options?.domain || this.domain;
717
-
718
- const initiate = (err: Error | null | undefined, data: unknown) => {
719
- if (err) {
720
- caller(callback, err);
721
- return;
722
- }
723
-
724
- let method: keyof typeof AUTH_METHODS | null = null;
725
-
726
- /**
727
- * @param {string} challenge challenge
728
- * @returns {string} base64 cram hash
729
- */
730
- const encodeCramMd5 = (challenge: string) => {
731
- const hmac = createHmac('md5', login.password());
732
- hmac.update(Buffer.from(challenge, 'base64').toString('ascii'));
733
- return Buffer.from(`${login.user()} ${hmac.digest('hex')}`).toString(
734
- 'base64'
735
- );
736
- };
737
-
738
- /**
739
- * @returns {string} base64 login/password
740
- */
741
- const encodePlain = () =>
742
- Buffer.from(`\u0000${login.user()}\u0000${login.password()}`).toString(
743
- 'base64'
744
- );
745
-
746
- /**
747
- * @see https://developers.google.com/gmail/xoauth2_protocol
748
- * @returns {string} base64 xoauth2 auth token
749
- */
750
- const encodeXoauth2 = () =>
751
- Buffer.from(
752
- `user=${login.user()}\u0001auth=Bearer ${login.password()}\u0001\u0001`
753
- ).toString('base64');
754
-
755
- // List of authentication methods we support: from preferred to
756
- // less preferred methods.
757
- if (!method) {
758
- const preferred = this.authentication;
759
- let auth = '';
760
-
761
- if (typeof this.features?.['auth'] === 'string') {
762
- auth = this.features['auth'];
763
- }
764
-
765
- for (let i = 0; i < preferred.length; i++) {
766
- if (auth.includes(preferred[i])) {
767
- method = preferred[i];
768
- break;
769
- }
770
- }
771
- }
772
-
773
- /**
774
- * handle bad responses from command differently
775
- * @param {Error} err err
776
- * @param {unknown} data data
777
- * @returns {void}
778
- */
779
- const failed = (err: Error, data: unknown) => {
780
- this.loggedin = false;
781
- this.close(); // if auth is bad, close the connection, it won't get better by itself
782
-
783
- err.message = err.message.replace(this.password(), 'REDACTED');
784
-
785
- caller(
786
- callback,
787
- SMTPError.create(
788
- 'authorization.failed',
789
- SMTPErrorStates.AUTHFAILED,
790
- err,
791
- data
792
- )
793
- );
794
- };
795
-
796
- /**
797
- * @param {Error} err err
798
- * @param {unknown} data data
799
- * @returns {void}
800
- */
801
- const response = (err: Error | null | undefined, data: unknown) => {
802
- if (err) {
803
- failed(err, data);
804
- } else {
805
- this.loggedin = true;
806
- caller(callback, err, data);
807
- }
808
- };
809
-
810
- /**
811
- * @param {Error} err err
812
- * @param {unknown} data data
813
- * @param {string} msg msg
814
- * @returns {void}
815
- */
816
- const attempt = (
817
- err: Error | null | undefined,
818
- data: unknown,
819
- msg: string
820
- ) => {
821
- if (err) {
822
- failed(err, data);
823
- } else {
824
- if (method === AUTH_METHODS['CRAM-MD5']) {
825
- this.command(encodeCramMd5(msg), response, [235, 503]);
826
- } else if (method === AUTH_METHODS.LOGIN) {
827
- this.command(
828
- Buffer.from(login.password()).toString('base64'),
829
- response,
830
- [235, 503]
831
- );
832
- }
833
- }
834
- };
835
-
836
- /**
837
- * @param {Error} err err
838
- * @param {unknown} data data
839
- * @param {string} msg msg
840
- * @returns {void}
841
- */
842
- const attemptUser = (err: Error, data: unknown) => {
843
- if (err) {
844
- failed(err, data);
845
- } else {
846
- if (method === AUTH_METHODS.LOGIN) {
847
- this.command(
848
- Buffer.from(login.user()).toString('base64'),
849
- attempt,
850
- [334]
851
- );
852
- }
853
- }
854
- };
855
-
856
- switch (method) {
857
- case AUTH_METHODS['CRAM-MD5']:
858
- this.command(`AUTH ${AUTH_METHODS['CRAM-MD5']}`, attempt, [334]);
859
- break;
860
- case AUTH_METHODS.LOGIN:
861
- this.command(`AUTH ${AUTH_METHODS.LOGIN}`, attemptUser, [334]);
862
- break;
863
- case AUTH_METHODS.PLAIN:
864
- this.command(
865
- `AUTH ${AUTH_METHODS.PLAIN} ${encodePlain()}`,
866
- response,
867
- [235, 503]
868
- );
869
- break;
870
- case AUTH_METHODS.XOAUTH2:
871
- this.command(
872
- `AUTH ${AUTH_METHODS.XOAUTH2} ${encodeXoauth2()}`,
873
- response,
874
- [235, 503]
875
- );
876
- break;
877
- default:
878
- caller(
879
- callback,
880
- SMTPError.create(
881
- 'no form of authorization supported',
882
- SMTPErrorStates.AUTHNOTSUPPORTED,
883
- null,
884
- data
885
- )
886
- );
887
- break;
888
- }
889
- };
890
-
891
- this.ehlo_or_helo_if_needed(initiate, domain);
892
- }
893
-
894
- /**
895
- * @public
896
- * @param {boolean} [force=false] whether or not to force destroy the connection
897
- * @returns {void}
898
- */
899
- public close(force = false) {
900
- if (this.sock) {
901
- if (force) {
902
- this.log('smtp connection destroyed!');
903
- this.sock.destroy();
904
- } else {
905
- this.log('smtp connection closed.');
906
- this.sock.end();
907
- }
908
- }
909
-
910
- if (this.monitor) {
911
- this.monitor.stop();
912
- this.monitor = null;
913
- }
914
-
915
- this._state = SMTPState.NOTCONNECTED;
916
- this._secure = false;
917
- this.sock = null;
918
- this.features = null;
919
- this.loggedin = !(this.user() && this.password());
920
- }
921
-
922
- /**
923
- * @public
924
- * @param {function(...any[]): void} [callback] function to call after response
925
- * @returns {void}
926
- */
927
- public quit(callback?: (...rest: any[]) => void) {
928
- this.command(
929
- 'quit',
930
- (err, data) => {
931
- caller(callback, err, data);
932
- this.close();
933
- },
934
- [221, 250]
935
- );
936
- }
937
- }