forked from forwardemail/forwardemail.net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite-server.js
246 lines (208 loc) · 7.2 KB
/
sqlite-server.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
/**
* Copyright (c) Forward Email LLC
* SPDX-License-Identifier: BUSL-1.1
*/
const fs = require('node:fs');
const http = require('node:http');
const https = require('node:https');
const { promisify } = require('node:util');
const Boom = require('@hapi/boom');
const Lock = require('ioredfour');
const MessageHandler = require('wildduck/lib/message-handler');
const auth = require('basic-auth');
const isSANB = require('is-string-and-not-blank');
const ms = require('ms');
const pify = require('pify');
const { WebSocketServer } = require('ws');
const { mkdirp } = require('mkdirp');
const AttachmentStorage = require('#helpers/attachment-storage');
const IMAPNotifier = require('#helpers/imap-notifier');
const Indexer = require('#helpers/indexer');
const config = require('#config');
const createTangerine = require('#helpers/create-tangerine');
const env = require('#config/env');
const i18n = require('#helpers/i18n');
const logger = require('#helpers/logger');
const parsePayload = require('#helpers/parse-payload');
const refreshSession = require('#helpers/refresh-session');
const wspServer = require('#helpers/wsp-server');
const { decrypt } = require('#helpers/encrypt-decrypt');
class SQLite {
constructor(options = {}) {
this.client = options.client;
this.subscriber = options.subscriber;
this.resolver = createTangerine(this.client, logger);
// start server with either http or https
const server =
config.env === 'production'
? https.createServer({
key: fs.readFileSync(env.WEB_SSL_KEY_PATH),
cert: fs.readFileSync(env.WEB_SSL_CERT_PATH),
ca: fs.readFileSync(env.WEB_SSL_CA_PATH),
ecdhCurve: 'auto'
})
: http.createServer();
//
// bind helpers so we can re-use IMAP helper commands
// (mirrored from `imap-server.js`)
//
// override logger
this.logger = logger;
server.logger = logger;
server.loggelf = (...args) => logger.debug(...args);
//
// NOTE: it is using a lock under `wildduck` prefix
// (to override set `this.attachmentStorage.storage.lock = new Lock(...)`)
//
this.attachmentStorage = new AttachmentStorage();
this.indexer = new Indexer({ attachmentStorage: this.attachmentStorage });
// promisified version of prepare message from wildduck message handler
this.prepareMessage = pify(
MessageHandler.prototype.prepareMessage.bind({
indexer: this.indexer,
normalizeSubject: MessageHandler.prototype.normalizeSubject,
generateIndexedHeaders: MessageHandler.prototype.generateIndexedHeaders
})
);
//
// the notifier is utilized in the IMAP connection (see `wildduck/imap-core/lib/imap-connection.js`)
// in order to `getUpdates` and send them over the socket (e.g. `EXIST`, `EXPUNGE`, `FETCH`)
// <https://github.com/nodemailer/wildduck/issues/509>
//
server.notifier = new IMAPNotifier({
publisher: this.client,
subscriber: this.subscriber
});
this.lock = new Lock({
redis: this.client,
namespace: config.imapLockNamespace
});
//
// in test/development listen for locking and releasing
// <https://github.com/nodemailer/ioredfour/blob/0bc1035c34c548b2d3058352c588dc20422cfb96/lib/ioredfour.js#L48-L49>
//
// if (config.env === 'development') {
// this.lock._redisSubscriber.on('message', (channel, message) => {
// logger.debug('lock message received', { channel, message });
// });
// }
// this.wss = new WebSocketServer({ noServer: true, perMessageDeflate: true });
this.wss = new WebSocketServer({
noServer: true,
maxPayload: 0 // disable max payload size
});
this.server = server;
this.refreshSession = refreshSession.bind(this);
this.wsp = wspServer;
function authenticate(request, socket, head, fn) {
try {
const credentials = auth(request);
if (
typeof credentials === 'undefined' ||
typeof credentials.name !== 'string' ||
!credentials.name
)
return fn(
Boom.unauthorized(
i18n.translateError(
'INVALID_API_CREDENTIALS',
i18n.config.defaultLocale
)
)
);
if (!env.API_SECRETS.includes(decrypt(credentials.name)))
return fn(
Boom.unauthorized(
i18n.translateError(
'INVALID_API_TOKEN',
i18n.config.defaultLocale
)
)
);
fn();
} catch (err) {
err.isCodeBug = true;
fn(err);
}
}
function onSocketError(err) {
logger.error(err);
}
this.server.on('upgrade', (request, socket, head) => {
logger.debug('upgrade from %s', request.socket.remoteAddress);
socket.on('error', onSocketError);
authenticate(request, socket, head, (err) => {
if (err) {
socket.write(
`HTTP/1.1 ${err?.output?.statusCode || 401} ${
err?.output?.payload?.error || 'Unauthorized'
}\r\n\r\n`
);
socket.destroy();
return;
}
socket.removeListener('error', onSocketError);
this.wss.handleUpgrade(request, socket, head, (ws) => {
this.wss.emit('connection', ws, request);
});
});
});
this.wss.on('connection', (ws, request) => {
ws.isAlive = true;
logger.debug('connection from %s', request.socket.remoteAddress);
ws.on('error', (err) => logger.error(err, { ws, request }));
ws.on('pong', function () {
// logger.debug('pong from %s', request.socket.remoteAddress);
this.isAlive = true;
});
ws.on('message', function () {
this.isAlive = true;
});
ws.on('message', (data) => {
// TODO: spawn worker thread to parse the payload (?)
parsePayload.call(this, data, ws);
});
});
this.wss.on('close', () => {
clearInterval(this.wsInterval);
});
// bind listen/close to this
this.listen = this.listen.bind(this);
this.close = this.close.bind(this);
}
async listen(port = env.SQLITE_PORT, host = '::', ...args) {
//
// ensure that /tmp dir's exist in each /mnt folder
// (e.g. `/mnt/storage_do_1/tmp`)
//
if (isSANB(env.SQLITE_TMPDIR)) await mkdirp(env.SQLITE_TMPDIR);
this.subscriber.subscribe('sqlite_auth_response');
this.wsInterval = setInterval(() => {
for (const ws of this.wss.clients) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
}
}, ms('35s'));
await promisify(this.server.listen).bind(this.server)(port, host, ...args);
}
async close() {
this.subscriber.unsubscribe('sqlite_auth_response');
clearInterval(this.wsInterval);
// close websocket connections
// if (this.wss && this.wss.clients) {
// for (const ws of this.wss.clients) {
// ws.terminate();
// ws.isAlive = false;
// }
// }
// close server
try {
await promisify(this.wss.close).bind(this.wss)();
} catch (err) {
logger.fatal(err);
}
await promisify(this.server.close).bind(this.server)();
}
}
module.exports = SQLite;