imapflow 1.0.75 → 1.0.79

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # CHANGELOG
2
2
 
3
+ - 1.0.79 - 2021-12-29
4
+
5
+ - Added property `greeting` that contains that first response from the server
6
+
7
+ - 1.0.78 - 2021-11-28
8
+
9
+ - Proxy support. Use configuration options `proxy: "url"` to use proxies
10
+
11
+ - 1.0.77 - 2021-11-25
12
+
13
+ - Testing out proxy connections
14
+ - Add X-GM-RAW support for search (jhi721 #68)
15
+
3
16
  - 1.0.75 - 2021-10-15
4
17
 
5
18
  - Fixed an exception with failing IDLE (ramiroaisen #60)
package/README.md CHANGED
@@ -1,10 +1,14 @@
1
1
  # ImapFlow
2
2
 
3
- _Node.js IMAP Client library built for for [EmailEngine Email API](https://emailengine.app/)._
3
+ ---
4
4
 
5
- The focus for ImapFlow is to provide easy to use API over IMAP. Using ImapFlow does not expect knowledge about specific IMAP details, general understanding is good enough.
5
+ > Managing IMAP connections is cool, but if you are only looking for an easy way to integrate email accounts, then ImapFlow was built for [EmailEngine Email API](https://emailengine.app/). It's a self-hosted software that converts all IMAP accounts to easy-to-use REST interfaces.
6
6
 
7
- IMAP extensions are handled in the background, so for example you can always request `labels` value from a {@link FetchQueryObject|fetch()} call but if the IMAP server does not support `X-GM-EXT1` extension, then `labels` value is not included in the response.
7
+ ---
8
+
9
+ The focus for ImapFlow is to provide easy to use API over IMAP. Using ImapFlow does not expect knowledge about specific IMAP details. A general understanding is good enough.
10
+
11
+ IMAP extensions are handled in the background, so for example, you can always request `labels` value from a {@link FetchQueryObject|fetch()} call, but if the IMAP server does not support `X-GM-EXT1` extension, then `labels` value is not included in the response.
8
12
 
9
13
  ## Source
10
14
 
@@ -24,7 +24,13 @@ module.exports = async connection => {
24
24
  let preCheck = () => {
25
25
  doneRequested = true;
26
26
  if (canEnd && !doneSent) {
27
- connection.log.debug({ src: 'c', msg: `DONE`, comment: `breaking IDLE` });
27
+ connection.log.debug({
28
+ src: 'c',
29
+ msg: `DONE`,
30
+ comment: `breaking IDLE`,
31
+ lockId: connection.currentLockId,
32
+ path: connection.mailbox && connection.mailbox.path
33
+ });
28
34
  connection.write('DONE');
29
35
  doneSent = true;
30
36
 
@@ -43,6 +49,16 @@ module.exports = async connection => {
43
49
  preCheckWaitQueue.push({ resolve, reject });
44
50
  });
45
51
 
52
+ connection.log.trace({
53
+ msg: 'Requesting IDLE break',
54
+ lockId: connection.currentLockId,
55
+ path: connection.mailbox && connection.mailbox.path,
56
+ queued: preCheckWaitQueue.length,
57
+ doneRequested,
58
+ canEnd,
59
+ doneSent
60
+ });
61
+
46
62
  preCheck();
47
63
 
48
64
  return handler;
@@ -50,7 +66,7 @@ module.exports = async connection => {
50
66
 
51
67
  response = await connection.exec('IDLE', false, {
52
68
  onPlusTag: async () => {
53
- connection.log.debug({ msg: `Initiated IDLE, waiting for server input` });
69
+ connection.log.debug({ msg: `Initiated IDLE, waiting for server input`, doneRequested });
54
70
  canEnd = true;
55
71
  if (doneRequested) {
56
72
  preCheck();
@@ -62,7 +78,22 @@ module.exports = async connection => {
62
78
  });
63
79
 
64
80
  // unset before response.next()
65
- connection.preCheck = false;
81
+ if (typeof connection.preCheck === 'function') {
82
+ connection.log.trace({
83
+ msg: 'Clearing pre-check function',
84
+ lockId: connection.currentLockId,
85
+ path: connection.mailbox && connection.mailbox.path,
86
+ queued: preCheckWaitQueue.length,
87
+ doneRequested,
88
+ canEnd,
89
+ doneSent
90
+ });
91
+ connection.preCheck = false;
92
+ while (preCheckWaitQueue.length) {
93
+ let { resolve } = preCheckWaitQueue.shift();
94
+ resolve();
95
+ }
96
+ }
66
97
 
67
98
  response.next();
68
99
  return;
package/lib/imap-flow.js CHANGED
@@ -27,6 +27,8 @@ const libbase64 = require('libbase64');
27
27
  const FlowedDecoder = require('mailsplit/lib/flowed-decoder');
28
28
  const { PassThrough } = require('stream');
29
29
 
30
+ const { proxyConnection } = require('./proxy-connection');
31
+
30
32
  const { comparePaths, updateCapabilities, getFolderTree, formatMessageResponse, getDecoder, packMessageRange, normalizePath } = require('./tools');
31
33
 
32
34
  const imapCommands = require('./imap-commands.js');
@@ -124,6 +126,7 @@ class ImapFlow extends EventEmitter {
124
126
  * @param {Boolean} [options.logRaw=false] If true then log data read from and written to socket encoded in base64
125
127
  * @param {Boolean} [options.emitLogs=false] If `true` then in addition of sending data to logger, ImapFlow emits 'log' events with the same data
126
128
  * @param {Boolean} [options.verifyOnly=false] If `true` then logs out automatically after successful authentication
129
+ * @param {Boolean} [options.proxy] Optional proxy URL. Supports HTTP CONNECT (`http://`, `https://`) and SOCKS (`socks://`, `socks4://`, `socks5://`) proxies
127
130
  */
128
131
  constructor(options) {
129
132
  super();
@@ -805,7 +808,13 @@ class ImapFlow extends EventEmitter {
805
808
  return false;
806
809
  }
807
810
 
808
- async initialOK() {
811
+ async initialOK(message) {
812
+ this.greeting = (message.attributes || [])
813
+ .filter(entry => entry.type === 'TEXT')
814
+ .map(entry => entry.value)
815
+ .filter(entry => entry)
816
+ .join('');
817
+
809
818
  clearTimeout(this.greetingTimeout);
810
819
  this.untaggedHandlers.OK = null;
811
820
  this.untaggedHandlers.PREAUTH = null;
@@ -1054,6 +1063,22 @@ class ImapFlow extends EventEmitter {
1054
1063
  this.untaggedHandlers.EXISTS = (...args) => this.untaggedExists(...args);
1055
1064
  this.untaggedHandlers.EXPUNGE = (...args) => this.untaggedExpunge(...args);
1056
1065
 
1066
+ let socket = false;
1067
+ if (this.options.proxy) {
1068
+ try {
1069
+ socket = await proxyConnection(this.log, this.options.proxy, this.host, this.port);
1070
+ if (!socket) {
1071
+ throw new Error('Failed to setup proxy connection');
1072
+ }
1073
+ } catch (err) {
1074
+ let error = new Error('Failed to setup proxy connection');
1075
+ error.code = err.code || 'ProxyError';
1076
+ error._err = err;
1077
+ this.log.error({ error, cid: this.id });
1078
+ throw error;
1079
+ }
1080
+ }
1081
+
1057
1082
  await new Promise((resolve, reject) => {
1058
1083
  this.connectTimeout = setTimeout(() => {
1059
1084
  let err = new Error('Failed to established connection in required time');
@@ -1063,7 +1088,7 @@ class ImapFlow extends EventEmitter {
1063
1088
  reject(err);
1064
1089
  }, CONNECT_TIMEOUT);
1065
1090
 
1066
- this.socket = connector.connect(opts, () => {
1091
+ let onConnect = () => {
1067
1092
  clearTimeout(this.connectTimeout);
1068
1093
  this.socket.setKeepAlive(true, 5 * 1000);
1069
1094
  this.socket.setTimeout(SOCKET_TIMEOUT);
@@ -1105,7 +1130,23 @@ class ImapFlow extends EventEmitter {
1105
1130
  // executed by initial "* OK"
1106
1131
  this.initialResolve = resolve;
1107
1132
  this.initialReject = reject;
1108
- });
1133
+ };
1134
+
1135
+ if (socket) {
1136
+ // socket is already establised via proxy
1137
+ if (this.secureConnection) {
1138
+ // TLS socket requires a handshake
1139
+ opts.socket = socket;
1140
+ this.socket = connector.connect(opts, onConnect);
1141
+ } else {
1142
+ // cleartext socket is already usable
1143
+ this.socket = socket;
1144
+ setImmediate(onConnect);
1145
+ }
1146
+ } else {
1147
+ this.socket = connector.connect(opts, onConnect);
1148
+ }
1149
+
1109
1150
  this.writeSocket = this.socket;
1110
1151
 
1111
1152
  this.socket.once('error', err => {
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ const httpProxyClient = require('nodemailer/lib/smtp-connection/http-proxy-client');
4
+ const { SocksClient } = require('socks');
5
+ const util = require('util');
6
+ const httpProxyClientAsync = util.promisify(httpProxyClient);
7
+ const dns = require('dns').promises;
8
+ const net = require('net');
9
+
10
+ const proxyConnection = async (logger, connectionUrl, host, port) => {
11
+ let proxyUrl = new URL(connectionUrl);
12
+
13
+ let protocol = proxyUrl.protocol.replace(/:$/, '').toLowerCase();
14
+
15
+ if (!net.isIP(host)) {
16
+ let resolveResult = await dns.resolve(host);
17
+ if (resolveResult && resolveResult.length) {
18
+ host = resolveResult[0];
19
+ }
20
+ }
21
+
22
+ switch (protocol) {
23
+ // Connect using a HTTP CONNECT method
24
+ case 'http':
25
+ case 'https': {
26
+ try {
27
+ let socket = await httpProxyClientAsync(proxyUrl.href, port, host);
28
+ if (socket) {
29
+ if (proxyUrl.password) {
30
+ proxyUrl.password = '(hidden)';
31
+ }
32
+ logger.info({
33
+ msg: 'Established a socket via HTTP proxy',
34
+ proxyUrl: proxyUrl.href,
35
+ port,
36
+ host
37
+ });
38
+ }
39
+ return socket;
40
+ } catch (err) {
41
+ if (proxyUrl.password) {
42
+ proxyUrl.password = '(hidden)';
43
+ }
44
+ logger.error({
45
+ msg: 'Failed to establish a socket via HTTP proxy',
46
+ proxyUrl: proxyUrl.href,
47
+ port,
48
+ host,
49
+ err
50
+ });
51
+ throw err;
52
+ }
53
+ }
54
+
55
+ // SOCKS proxy
56
+ case 'socks':
57
+ case 'socks5':
58
+ case 'socks4':
59
+ case 'socks4a': {
60
+ let proxyType = Number(protocol.replace(/\D/g, '')) || 5;
61
+
62
+ let targetHost = proxyUrl.hostname;
63
+ if (!net.isIP(targetHost)) {
64
+ let resolveResult = await dns.resolve(targetHost);
65
+ if (resolveResult && resolveResult.length) {
66
+ targetHost = resolveResult[0];
67
+ }
68
+ }
69
+
70
+ let connectionOpts = {
71
+ proxy: {
72
+ host: targetHost,
73
+ port: Number(proxyUrl.port) || 1080,
74
+ type: proxyType
75
+ },
76
+ destination: {
77
+ host,
78
+ port
79
+ },
80
+ command: 'connect',
81
+ set_tcp_nodelay: true
82
+ };
83
+
84
+ if (proxyUrl.username || proxyUrl.password) {
85
+ connectionOpts.proxy.userId = proxyUrl.username;
86
+ connectionOpts.proxy.password = proxyUrl.password;
87
+ }
88
+
89
+ try {
90
+ const info = await SocksClient.createConnection(connectionOpts);
91
+ if (info && info.socket) {
92
+ if (proxyUrl.password) {
93
+ proxyUrl.password = '(hidden)';
94
+ }
95
+ logger.info({
96
+ msg: 'Established a socket via SOCKS proxy',
97
+ proxyUrl: proxyUrl.href,
98
+ port,
99
+ host
100
+ });
101
+ }
102
+ return info.socket;
103
+ } catch (err) {
104
+ if (proxyUrl.password) {
105
+ proxyUrl.password = '(hidden)';
106
+ }
107
+ logger.error({
108
+ msg: 'Failed to establish a socket via SOCKS proxy',
109
+ proxyUrl: proxyUrl.href,
110
+ port,
111
+ host,
112
+ err
113
+ });
114
+ throw err;
115
+ }
116
+ }
117
+ }
118
+ };
119
+
120
+ module.exports = { proxyConnection };
@@ -117,6 +117,11 @@ module.exports.searchCompiler = (connection, query) => {
117
117
  setOpt(attributes, 'X-GM-THRID', params[term]);
118
118
  }
119
119
  break;
120
+ case 'GMRAW':
121
+ if (connection.capabilities.has('X-GM-EXT-1')) {
122
+ setOpt(attributes, 'X-GM-RAW', params[term]);
123
+ }
124
+ break;
120
125
 
121
126
  case 'BEFORE':
122
127
  case 'ON':
package/lib/types.d.ts CHANGED
@@ -26,6 +26,7 @@ declare module "imapflow" {
26
26
  * @param [options.logRaw = false] - If true then log data read from and written to socket encoded in base64
27
27
  * @param [options.emitLogs = false] - If `true` then in addition of sending data to logger, ImapFlow emits 'log' events with the same data
28
28
  * @param [options.verifyOnly = false] - If `true` then logs out automatically after successful authentication
29
+ * @param [options.proxy] - Optional proxy URL. Supports HTTP CONNECT (`http://`, `https://`) and SOCKS (`socks://`, `socks4://`, `socks5://`) proxies
29
30
  */
30
31
  class ImapFlow extends EventEmitter {
31
32
  constructor(options: {
@@ -50,6 +51,7 @@ declare module "imapflow" {
50
51
  logRaw?: boolean;
51
52
  emitLogs?: boolean;
52
53
  verifyOnly?: boolean;
54
+ proxy?: boolean;
53
55
  });
54
56
  /**
55
57
  * Current module version as a static class property
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imapflow",
3
- "version": "1.0.75",
3
+ "version": "1.0.79",
4
4
  "description": "IMAP Client for Node",
5
5
  "main": "./lib/imap-flow.js",
6
6
  "scripts": {
@@ -26,19 +26,19 @@
26
26
  },
27
27
  "homepage": "https://imapflow.com/",
28
28
  "devDependencies": {
29
- "@babel/eslint-parser": "7.15.8",
30
- "@babel/eslint-plugin": "7.14.5",
29
+ "@babel/eslint-parser": "7.16.5",
30
+ "@babel/eslint-plugin": "7.16.5",
31
31
  "@babel/plugin-syntax-class-properties": "7.12.13",
32
- "@babel/preset-env": "7.15.8",
33
- "@types/node": "16.11.0",
32
+ "@babel/preset-env": "7.16.5",
33
+ "@types/node": "17.0.5",
34
34
  "braintree-jsdoc-template": "3.3.0",
35
- "eslint": "8.0.1",
35
+ "eslint": "8.5.0",
36
36
  "eslint-config-nodemailer": "1.2.0",
37
37
  "eslint-config-prettier": "8.3.0",
38
38
  "grunt": "1.4.1",
39
39
  "grunt-cli": "1.4.3",
40
40
  "grunt-contrib-nodeunit": "4.0.0",
41
- "grunt-eslint": "23.0.0",
41
+ "grunt-eslint": "24.0.0",
42
42
  "jsdoc": "3.6.7",
43
43
  "tsd-jsdoc": "2.5.0"
44
44
  },
@@ -49,6 +49,8 @@
49
49
  "libmime": "5.0.0",
50
50
  "libqp": "1.1.0",
51
51
  "mailsplit": "5.3.1",
52
- "pino": "7.0.1"
52
+ "nodemailer": "6.7.2",
53
+ "pino": "7.6.2",
54
+ "socks": "2.6.1"
53
55
  }
54
56
  }