-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (155 loc) · 5.32 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
const Imap = require('imap');
const { simpleParser } = require('mailparser');
const WaitGroup = require('waitgroup');
/**
* Generic interface to process emails from GMail using IMAP filters & body regex parsing.
* Once messages are processed, they are marked as read and moved to a designated folder
*
* Calls `parseFunc` to turn emails into objects and `insertCallback` on successful parsing.
* Example settings object:
* {
* username: '[email protected]',
* password: 'password123',
* keepEmail: true, // optional. If true, the emails will not be moved upon succesful processing
* targetDomain: 'example.com', // the domain you should be receiving these emails from. This is used to verify certificates
* outputFolder: 'myEmails',
* imapFilters: [
* ['FROM', '@mydomain.com'],
* ['SUBJECT', 'Daily Mail']
* ],
* }
*/
class GmailProcessor {
constructor(settings, parseFunc, insertCallback) {
this.imap = new Imap({
user: settings.username,
password: settings.password,
host: 'imap.gmail.com',
port: 993,
tls: true,
tlsOptions: { rejectUnauthorized: false }
});
this.settings = settings;
this.parseFunc = parseFunc;
this.insertCallback = insertCallback;
}
async moveMsgOutOfInbox(uid) {
await this.imap.move(uid, this.settings.outputFolder, err => {
if (err) {
throw err;
}
this.imap.end();
})
await this.imap.addFlags(uid, ['\\Seen'], err => {
if (err) {
throw err;
}
});
}
verifyEmailSignature(headerLines) {
// verify the signature of the sender
let foundDKIM = false;
let foundDMARC = false;
let foundSPF = false;
for (let i = 0; i < headerLines.length; i++) {
const { key, line } = headerLines[i];
if (key === "arc-authentication-results" || key === "authentication-results") {
// only trust google's certs
if (!line.includes("Authentication-Results: mx.google.com;")) {
continue;
}
if (line.includes(`dkim=pass header.i=@${this.settings.targetDomain}`)) {
foundDKIM = true;
}
if (line.includes("dmarc=pass") && line.includes(`header.from=${this.settings.targetDomain}`)) {
foundDMARC = true;
}
if (line.includes("spf=pass")) {
foundSPF = true;
}
}
if (foundDKIM && foundDMARC && foundSPF) {
break;
}
}
return foundDKIM && foundDMARC;
}
processIMAPSearchResults(searchErr, results) {
if (searchErr) {
throw searchErr;
}
let f;
try {
f = this.imap.fetch(results, { bodies: '' });
} catch (err) {
if (err.message != "Nothing to fetch") {
throw err;
}
}
// if there are no results, return
if (!f) {
this.imap.end();
return;
}
let wg = new WaitGroup();
f.on('message', msg => {
wg.add();
let stream;
let uid;
msg.on('body', stream_in => {
stream = stream_in;
});
msg.once('attributes', attrs => {
uid = attrs.uid;
});
msg.once('end', () => {
// we only move the email out of the inbox if we parse
// it succesfully (both as an email and a transaction)
simpleParser(stream, async (err, parsed) => {
if (!this.verifyEmailSignature(parsed.headerLines)) {
console.log("WARNING: SPOOFED EMAIL: ");
console.log(parsed);
}
const { txn, parseErr } = this.parseFunc(parsed);
if (!parseErr) {
let err = false;
try {
await this.insertCallback(txn);
} catch (e) {
console.log(e);
err = true;
}
if (!err && !this.settings.keepEmail) {
await this.moveMsgOutOfInbox(uid);
}
}
wg.done();
});
});
});
f.once('error', ex => {
return Promise.reject(ex);
});
f.once('end', () => {
wg.wait(() => this.imap.end());
});
}
run(callback) {
this.imap.once('ready', () => {
this.imap.openBox('INBOX', false, () => {
this.imap.search(
this.settings.imapFilters,
(err, results) => this.processIMAPSearchResults(err, results)
);
});
});
this.imap.once('error', err => {
throw err;
});
this.imap.connect();
this.imap.once('end', () => {
callback();
})
}
}
module.exports = GmailProcessor;