-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathSMTPAuth.ts
71 lines (56 loc) · 1.75 KB
/
SMTPAuth.ts
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
import { SMTPClient } from 'smtp-client';
import { IAuthentication } from '../interfaces/Authentication.js';
import { Logger } from '../logger/Logger.js';
interface ISMTPAuthOptions {
host: string;
port?: number;
useSecureTransport?: boolean;
validHosts?: string[];
}
export class SMTPAuth implements IAuthentication {
private logger = new Logger('SMTPAuth');
private host: string;
private port = 25;
private useSecureTransport = false;
private validHosts?: string[];
constructor(options: ISMTPAuthOptions) {
this.host = options.host;
if (options.port !== undefined) {
this.port = options.port;
}
if (options.useSecureTransport !== undefined) {
this.useSecureTransport = options.useSecureTransport;
}
if (options.validHosts !== undefined) {
this.validHosts = options.validHosts;
}
}
async authenticate(username: string, password: string) {
if (this.validHosts) {
const domain = username.split('@').pop();
if (!domain || !this.validHosts.includes(domain)) {
this.logger.log(`invalid or no domain in username ${username} ${domain}`);
return false;
}
}
const s = new SMTPClient({
host: this.host,
port: this.port,
secure: this.useSecureTransport,
tlsOptions: {
servername: this.host, // SNI (needs to be set for gmail)
},
} as any); // secure is currently not part of type def..but it is available: https://www.npmjs.com/package/smtp-client
let success = false;
try {
await s.connect();
await s.greet({ hostname: 'mx.domain.com' }); // runs EHLO command or HELO as a fallback
await s.authPlain({ username, password }); // authenticates a user
success = true;
s.close(); // runs QUIT command
} catch (err) {
this.logger.error('imap auth failed', err);
}
return success;
}
}