imapkit 4.3.1 → 5.0.0

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 (93) hide show
  1. package/README.md +167 -51
  2. package/bin/help.txt +17 -3
  3. package/bin/imapkit.js +53 -23
  4. package/dist/cjs/commands/append.js +1 -1
  5. package/dist/cjs/commands/create.js +2 -2
  6. package/dist/cjs/commands/delete.js +2 -14
  7. package/dist/cjs/commands/handlers/flags.d.ts +3 -3
  8. package/dist/cjs/commands/handlers/flags.js +3 -3
  9. package/dist/cjs/commands/handlers/store.js +3 -3
  10. package/dist/cjs/commands/rename.js +6 -46
  11. package/dist/cjs/commands/select.js +1 -0
  12. package/dist/cjs/commands/subscribe.js +7 -8
  13. package/dist/cjs/commands/unsubscribe.js +3 -9
  14. package/dist/cjs/control.d.ts +430 -0
  15. package/dist/cjs/control.js +637 -0
  16. package/dist/cjs/index.d.ts +8 -1
  17. package/dist/cjs/index.js +9 -2
  18. package/dist/cjs/load-plugins.d.ts +1 -1
  19. package/dist/cjs/load-plugins.js +7 -2
  20. package/dist/cjs/plugins/acl.js +109 -42
  21. package/dist/cjs/plugins/condstore.js +7 -0
  22. package/dist/cjs/plugins/index.js +1 -3
  23. package/dist/cjs/plugins/metadata.js +140 -57
  24. package/dist/cjs/plugins/objectid.js +10 -0
  25. package/dist/cjs/plugins/quota.js +50 -2
  26. package/dist/cjs/plugins/savedate.js +1 -1
  27. package/dist/cjs/plugins/special-use.d.ts +0 -8
  28. package/dist/cjs/plugins/special-use.js +23 -0
  29. package/dist/cjs/quirks.d.ts +28 -0
  30. package/dist/cjs/quirks.js +124 -0
  31. package/dist/cjs/random.d.ts +10 -0
  32. package/dist/cjs/random.js +22 -0
  33. package/dist/cjs/rest.d.ts +50 -0
  34. package/dist/cjs/rest.js +561 -0
  35. package/dist/cjs/script.d.ts +33 -4
  36. package/dist/cjs/script.js +64 -4
  37. package/dist/cjs/server.d.ts +147 -8
  38. package/dist/cjs/server.js +398 -144
  39. package/dist/cjs/smtp-listener.d.ts +3 -2
  40. package/dist/cjs/smtp-listener.js +10 -6
  41. package/dist/cjs/storage-schema.d.ts +139 -0
  42. package/dist/cjs/storage-schema.js +215 -0
  43. package/dist/cjs/store-operations.d.ts +168 -0
  44. package/dist/cjs/store-operations.js +422 -0
  45. package/dist/cjs/types.d.ts +22 -1
  46. package/dist/esm/commands/append.js +1 -1
  47. package/dist/esm/commands/create.js +2 -2
  48. package/dist/esm/commands/delete.js +2 -14
  49. package/dist/esm/commands/handlers/flags.d.ts +3 -3
  50. package/dist/esm/commands/handlers/flags.js +3 -3
  51. package/dist/esm/commands/handlers/store.js +3 -3
  52. package/dist/esm/commands/rename.js +6 -46
  53. package/dist/esm/commands/select.js +1 -0
  54. package/dist/esm/commands/subscribe.js +7 -8
  55. package/dist/esm/commands/unsubscribe.js +3 -9
  56. package/dist/esm/control.d.ts +430 -0
  57. package/dist/esm/control.js +630 -0
  58. package/dist/esm/index.d.ts +8 -1
  59. package/dist/esm/index.js +5 -2
  60. package/dist/esm/load-plugins.d.ts +1 -1
  61. package/dist/esm/load-plugins.js +7 -2
  62. package/dist/esm/plugins/acl.js +109 -42
  63. package/dist/esm/plugins/condstore.js +7 -0
  64. package/dist/esm/plugins/index.js +1 -3
  65. package/dist/esm/plugins/metadata.js +140 -57
  66. package/dist/esm/plugins/objectid.js +10 -0
  67. package/dist/esm/plugins/quota.js +50 -2
  68. package/dist/esm/plugins/savedate.js +1 -1
  69. package/dist/esm/plugins/special-use.d.ts +0 -8
  70. package/dist/esm/plugins/special-use.js +23 -0
  71. package/dist/esm/quirks.d.ts +28 -0
  72. package/dist/esm/quirks.js +120 -0
  73. package/dist/esm/random.d.ts +10 -0
  74. package/dist/esm/random.js +19 -0
  75. package/dist/esm/rest.d.ts +50 -0
  76. package/dist/esm/rest.js +553 -0
  77. package/dist/esm/script.d.ts +33 -4
  78. package/dist/esm/script.js +63 -4
  79. package/dist/esm/server.d.ts +147 -8
  80. package/dist/esm/server.js +399 -145
  81. package/dist/esm/smtp-listener.d.ts +3 -2
  82. package/dist/esm/smtp-listener.js +10 -6
  83. package/dist/esm/storage-schema.d.ts +139 -0
  84. package/dist/esm/storage-schema.js +211 -0
  85. package/dist/esm/store-operations.d.ts +168 -0
  86. package/dist/esm/store-operations.js +407 -0
  87. package/dist/esm/types.d.ts +22 -1
  88. package/dist/plugin-help.json +0 -14
  89. package/package.json +11 -3
  90. package/dist/cjs/plugins/xtoybird.d.ts +0 -2
  91. package/dist/cjs/plugins/xtoybird.js +0 -236
  92. package/dist/esm/plugins/xtoybird.d.ts +0 -2
  93. package/dist/esm/plugins/xtoybird.js +0 -218
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Changes of the message store that IMAP commands and the control API share: expunge, flag changes, and the
3
+ * mailbox operations of DELETE, RENAME, SUBSCRIBE and UNSUBSCRIBE. Each one tells the sessions about the change
4
+ * the way another session's command would (EXISTS, EXPUNGE, unsolicited FETCH, BYE, `mailbox` events). The
5
+ * session that caused a change is `server.activeConnection` (null for the control API), the commands keep only
6
+ * what is specific to a session: argument checks, the selected mailbox, read-only state and the responses.
7
+ */
8
+ import { normalizeSystemFlag, checkSystemFlags } from './commands/handlers/flags.js';
9
+ import { seededRandom } from './random.js';
10
+ import { MAX_NUMBER } from './numbers.js';
11
+ /** the XOAUTH2 session timeout of the default user, and of a user the control API adds without one */
12
+ const DEFAULT_SESSION_TIMEOUT = 3600 * 1000;
13
+ /** An error of a failed store operation or control API call, `code` is a RFC 5530 response code or INVALID */
14
+ class ImapKitError extends Error {
15
+ constructor(message, code) {
16
+ super(message);
17
+ this.name = 'ImapKitError';
18
+ this.code = code;
19
+ }
20
+ }
21
+ /**
22
+ * Creates an error for a failed operation, with a RFC 5530 response code
23
+ *
24
+ * @param {String} message Error message
25
+ * @param {String} code Response code, e.g. "NONEXISTENT"
26
+ * @return {Error} Error object
27
+ */
28
+ function storeError(message, code) {
29
+ return new ImapKitError(message, code);
30
+ }
31
+ /**
32
+ * Removes messages from a mailbox and tells the sessions that have it selected with EXPUNGE responses
33
+ * (VANISHED with QRESYNC) and a new EXISTS. The `expunge` event goes out before the notifications
34
+ *
35
+ * @param {Object} server IMAP server
36
+ * @param {Object} mailbox Mailbox of the messages
37
+ * @param {Array|Function} messagesOrFilterFunc Messages to remove, or a function that returns true for them
38
+ * @param {Object} [options] `{ origin, skip, skipExists, highestFirst }`
39
+ * @return {Array} the removed messages
40
+ */
41
+ function expungeMessages(server, mailbox, messagesOrFilterFunc, options = {}) {
42
+ let filterFunc;
43
+ if (Array.isArray(messagesOrFilterFunc)) {
44
+ const messageSet = new Set(messagesOrFilterFunc);
45
+ filterFunc = (message) => messageSet.has(message);
46
+ }
47
+ else {
48
+ filterFunc = messagesOrFilterFunc;
49
+ }
50
+ // sequence numbers of the removed messages, each one as it is after the earlier EXPUNGE responses. From the
51
+ // highest message down, the earlier responses do not change the sequence numbers of the later ones
52
+ const expunged = [];
53
+ const kept = [];
54
+ mailbox.messages.forEach((message, i) => {
55
+ if (filterFunc(message)) {
56
+ message.ghost = true;
57
+ expunged.push({ seq: options.highestFirst ? i + 1 : kept.length + 1, message });
58
+ }
59
+ else {
60
+ kept.push(message);
61
+ }
62
+ });
63
+ if (!expunged.length) {
64
+ return [];
65
+ }
66
+ // old copy is required for those sessions that run FETCH before
67
+ // displaying the EXPUNGE notice
68
+ const mailboxCopy = mailbox.messages.slice();
69
+ // update the list in place, other code might hold a reference to it
70
+ kept.forEach((message, i) => {
71
+ mailbox.messages[i] = message;
72
+ });
73
+ mailbox.messages.length = kept.length;
74
+ const messages = expunged.map(entry => entry.message);
75
+ const origin = options.origin !== undefined ? options.origin : server.activeConnection;
76
+ // lets plugins track the removal (e.g. mod-sequences of CONDSTORE and QRESYNC) before any notification
77
+ server.emit('expunge', mailbox, messages, origin);
78
+ (options.highestFirst ? expunged.slice().reverse() : expunged).forEach(entry => {
79
+ server.notify({
80
+ tag: '*',
81
+ attributes: [
82
+ entry.seq,
83
+ {
84
+ type: 'ATOM',
85
+ value: 'EXPUNGE'
86
+ }
87
+ ],
88
+ // the removed message, for plugins that report it differently (e.g. VANISHED of QRESYNC)
89
+ message: entry.message
90
+ }, mailbox, options.skip);
91
+ });
92
+ server.notify({
93
+ tag: '*',
94
+ attributes: [
95
+ mailbox.messages.length,
96
+ {
97
+ type: 'ATOM',
98
+ value: 'EXISTS'
99
+ }
100
+ ],
101
+ // distribute the old mailbox data with the notification
102
+ mailboxCopy: mailboxCopy
103
+ }, mailbox, options.skip || options.skipExists);
104
+ return messages;
105
+ }
106
+ /**
107
+ * Tells the sessions that have a mailbox selected about changed flags, they get an untagged FETCH with the
108
+ * new flags (RFC 3501 section 5.2)
109
+ *
110
+ * @param {Object} server IMAP server
111
+ * @param {Object} mailbox Mailbox of the messages
112
+ * @param {Array} messages Messages with changed flags
113
+ * @param {Object} [ignoreConnection] A session that is not told, e.g. the one whose STORE changed the flags
114
+ */
115
+ function notifyFlagChanges(server, mailbox, messages, ignoreConnection) {
116
+ if (messages.length) {
117
+ server.notify({ tag: '*', flagUpdate: messages }, mailbox, ignoreConnection);
118
+ }
119
+ }
120
+ /**
121
+ * Checks flags the way STORE does: system flags the server knows (never \Recent), valid keywords, and only
122
+ * permanent flags in a mailbox that does not allow new keywords
123
+ *
124
+ * @param {Object} server IMAP server
125
+ * @param {Object} mailbox Mailbox the flags are for
126
+ * @param {Array} flags Flags to check
127
+ * @param {Boolean} stored true if the flags are stored, so they must be permanent flags of the mailbox
128
+ * @return {Array} the normalized flags without duplicates
129
+ * @throws {Error} INVALID for a flag that can not be used
130
+ */
131
+ function checkFlags(server, mailbox, flags, stored) {
132
+ if (!Array.isArray(flags)) {
133
+ throw storeError('Flags must be an array', 'INVALID');
134
+ }
135
+ const list = [];
136
+ flags.forEach((value) => {
137
+ if (typeof value !== 'string') {
138
+ throw storeError('Flags must be strings', 'INVALID');
139
+ }
140
+ const flag = normalizeSystemFlag(value);
141
+ try {
142
+ checkSystemFlags(server, flag);
143
+ }
144
+ catch (err) {
145
+ throw storeError(err.message, 'INVALID');
146
+ }
147
+ if (stored && mailbox.permanentFlags.indexOf(flag) < 0 && !mailbox.allowPermanentFlags) {
148
+ throw storeError('Flag ' + flag + ' is not a permanent flag of ' + mailbox.path, 'INVALID');
149
+ }
150
+ if (list.indexOf(flag) < 0) {
151
+ list.push(flag);
152
+ }
153
+ });
154
+ return list;
155
+ }
156
+ /**
157
+ * Changes the flags of messages outside of a STORE command. The flags follow the rules of STORE: system flags
158
+ * the server knows (never \Recent), valid keywords, and only permanent flags in a mailbox that does not allow
159
+ * new keywords. Plugins learn about the changed messages from the `flags` event `(mailbox, messages, origin)`
160
+ * before the sessions are told (CONDSTORE gives them new mod-sequences there)
161
+ *
162
+ * @param {Object} server IMAP server
163
+ * @param {Object} mailbox Mailbox of the messages
164
+ * @param {Array} messages Messages to change
165
+ * @param {Array} flags Flags to set, add or remove
166
+ * @param {String} mode "set", "add" or "remove"
167
+ * @return {Array} the messages whose flags changed
168
+ */
169
+ function changeFlags(server, mailbox, messages, flags, mode) {
170
+ if (['set', 'add', 'remove'].indexOf(mode) < 0) {
171
+ throw storeError('Invalid flag mode ' + JSON.stringify(mode) + ', expected set, add or remove', 'INVALID');
172
+ }
173
+ const list = checkFlags(server, mailbox, flags, mode !== 'remove');
174
+ const changed = [];
175
+ messages.forEach(message => {
176
+ const before = message.flags.join(' ');
177
+ if (mode === 'set') {
178
+ message.flags = list.slice();
179
+ }
180
+ else if (mode === 'add') {
181
+ list.forEach(flag => server.ensureFlag(message.flags, flag));
182
+ }
183
+ else {
184
+ list.forEach(flag => server.removeFlag(message.flags, flag));
185
+ }
186
+ server.rememberFlags(mailbox, message.flags);
187
+ if (message.flags.join(' ') !== before) {
188
+ changed.push(message);
189
+ }
190
+ });
191
+ if (changed.length) {
192
+ server.emit('flags', mailbox, changed, server.activeConnection);
193
+ notifyFlagChanges(server, mailbox, changed, null);
194
+ }
195
+ return changed;
196
+ }
197
+ /**
198
+ * Creates a mailbox (CREATE), with any missing superior hierarchy levels
199
+ *
200
+ * @param {Object} server IMAP server
201
+ * @param {String} path Storage name of the mailbox
202
+ * @return {Object} the created mailbox
203
+ * @throws {Error} with a RFC 5530 `code` (ALREADYEXISTS, CANNOT ...)
204
+ */
205
+ function createMailbox(server, path) {
206
+ const existing = new Set(Object.keys(server.folderCache));
207
+ const mailbox = server.createMailbox(path);
208
+ // the superior levels that did not exist are new mailboxes as well, plugins set them up like the target (ACL)
209
+ const created = Object.keys(server.folderCache)
210
+ .filter(name => !existing.has(name))
211
+ .sort((a, b) => a.length - b.length);
212
+ server.mailboxChanged('create', mailbox.path, { created });
213
+ return mailbox;
214
+ }
215
+ /**
216
+ * Deletes a mailbox (DELETE). Other sessions that have it selected are disconnected with an untagged BYE
217
+ * (RFC 2180 section 3.3, RFC 2683 section 3.1.2), as they can not be told about the deletion in any other way
218
+ *
219
+ * @param {Object} server IMAP server
220
+ * @param {String} path Storage name of the mailbox
221
+ * @throws {Error} with a RFC 5530 `code` (NONEXISTENT, CANNOT, HASCHILDREN ...)
222
+ */
223
+ function deleteMailbox(server, path) {
224
+ const mailbox = server.getMailbox(path);
225
+ if (!mailbox) {
226
+ throw storeError('Mailbox does not exist', 'NONEXISTENT');
227
+ }
228
+ server.deleteMailbox(path);
229
+ server.mailboxChanged('delete', mailbox.path, { mailbox });
230
+ byeSelected(server, mailbox, 'Selected mailbox was deleted', 'MAILBOX DELETED');
231
+ }
232
+ /**
233
+ * Disconnects the sessions that have a mailbox selected with an untagged BYE, except the one that made the change
234
+ *
235
+ * @param {Object} server IMAP server
236
+ * @param {Object} mailbox Mailbox
237
+ * @param {String} text Text of the BYE
238
+ * @param {String} description Description for output handlers
239
+ */
240
+ function byeSelected(server, mailbox, text, description) {
241
+ const origin = server.activeConnection;
242
+ server.connections.forEach(connection => {
243
+ if (connection !== origin && connection.selectedMailbox === mailbox) {
244
+ connection.bye(text, description);
245
+ }
246
+ });
247
+ }
248
+ /**
249
+ * Renames a mailbox (RENAME). Renaming INBOX moves its messages to the new mailbox and leaves INBOX
250
+ * empty (RFC 3501 section 6.3.5). Everything that can be checked is checked up front, so that a failed
251
+ * rename never loses the source
252
+ *
253
+ * @param {Object} server IMAP server
254
+ * @param {String} source Storage name of the mailbox
255
+ * @param {String} destination New storage name
256
+ * @return {Object} `{ path, mailbox }`: the new name, and the source mailbox object, which is INBOX itself for
257
+ * a rename of INBOX
258
+ * @throws {Error} with a RFC 5530 `code` (NONEXISTENT, ALREADYEXISTS, CANNOT ...)
259
+ */
260
+ function renameMailbox(server, source, destination) {
261
+ const mailbox = server.getMailbox(source);
262
+ const target = server.getMailbox(destination);
263
+ if (!mailbox || mailbox.flags.indexOf('\\Noselect') >= 0) {
264
+ throw storeError('Mailbox does not exist', 'NONEXISTENT');
265
+ }
266
+ if (target && target.flags.indexOf('\\Noselect') < 0) {
267
+ throw storeError('Mailbox already exists', 'ALREADYEXISTS');
268
+ }
269
+ const separator = server.getSeparator(mailbox);
270
+ if (destination.substr(0, mailbox.path.length + separator.length) === mailbox.path + separator) {
271
+ throw storeError('Can not move a mailbox into itself', 'CANNOT');
272
+ }
273
+ const oldPath = mailbox.path;
274
+ let path;
275
+ if (source.toUpperCase() === 'INBOX') {
276
+ const renamed = server.createMailbox(destination);
277
+ path = renamed.path;
278
+ mailbox.messages.forEach((message) => {
279
+ server.copyMessage(renamed, message);
280
+ });
281
+ expungeMessages(server, mailbox, () => true);
282
+ }
283
+ else {
284
+ server.deleteMailbox(source, true);
285
+ try {
286
+ server.createMailbox(destination, mailbox);
287
+ }
288
+ catch (E) {
289
+ // put the source mailbox back where it was
290
+ server.createMailbox(source, mailbox);
291
+ server.indexFolders();
292
+ throw E;
293
+ }
294
+ server.indexFolders();
295
+ path = mailbox.path;
296
+ }
297
+ server.mailboxChanged('rename', path, { oldPath });
298
+ return { path, mailbox };
299
+ }
300
+ /**
301
+ * Gives a mailbox a new UIDVALIDITY, optionally with new UIDs. A UID never changes during a session (RFC 9051
302
+ * section 2.3.1.1), so the sessions that have the mailbox selected are disconnected with BYE, and the new value
303
+ * is greater than every earlier one, as UIDs that do not persist require. A client that keeps its cached UIDs
304
+ * without checking UIDVALIDITY gets other messages ("shuffle") or none ("offset") for them
305
+ *
306
+ * @param {Object} server IMAP server
307
+ * @param {Object} mailbox Mailbox, not \Noselect
308
+ * @param {Object} [options] `{ uidvalidity, uids, offset, seed }`
309
+ * @return {Object} `{ uidvalidity, uidnext, uids }`, `uids` maps every old UID to its new one
310
+ * @throws {Error} INVALID for a UIDVALIDITY that is not greater, or invalid options
311
+ */
312
+ function resetUidValidity(server, mailbox, options = {}) {
313
+ const mode = options.uids || 'keep';
314
+ if (['keep', 'renumber', 'shuffle', 'offset'].indexOf(mode) < 0) {
315
+ throw storeError('Invalid UID mode ' + JSON.stringify(mode) + ', expected keep, renumber, shuffle or offset', 'INVALID');
316
+ }
317
+ const offset = options.offset === undefined ? 0 : options.offset;
318
+ if (!Number.isSafeInteger(offset) || offset < 0) {
319
+ throw storeError('Offset must be a non-negative integer', 'INVALID');
320
+ }
321
+ let uidvalidity = options.uidvalidity;
322
+ if (uidvalidity === undefined) {
323
+ uidvalidity = Math.max(mailbox.uidvalidity, server.uidvalidityCounter) + 1;
324
+ }
325
+ else if (!Number.isSafeInteger(uidvalidity) || uidvalidity <= mailbox.uidvalidity || uidvalidity > 0xffffffff) {
326
+ // nz-number of RFC 3501 section 9, a 32-bit value
327
+ throw storeError('UIDVALIDITY must be an integer above ' + mailbox.uidvalidity + ' and below 2^32', 'INVALID');
328
+ }
329
+ if (options.seed !== undefined && !Number.isSafeInteger(options.seed)) {
330
+ throw storeError('Seed must be an integer', 'INVALID');
331
+ }
332
+ byeSelected(server, mailbox, 'UIDVALIDITY of the selected mailbox changed', 'UIDVALIDITY CHANGED');
333
+ const messages = mailbox.messages;
334
+ const oldUids = messages.map(message => message.uid);
335
+ let newUids = oldUids;
336
+ if (mode === 'renumber' || mode === 'shuffle') {
337
+ newUids = messages.map((message, i) => i + 1);
338
+ if (mode === 'shuffle') {
339
+ const random = seededRandom(options.seed === undefined ? Math.floor(Math.random() * MAX_NUMBER) : options.seed);
340
+ // Fisher-Yates
341
+ for (let i = newUids.length - 1; i > 0; i--) {
342
+ const j = Math.floor(random() * (i + 1));
343
+ [newUids[i], newUids[j]] = [newUids[j], newUids[i]];
344
+ }
345
+ }
346
+ mailbox.uidnext = messages.length + 1;
347
+ }
348
+ else if (mode === 'offset') {
349
+ const shift = mailbox.uidnext - 1 + offset;
350
+ newUids = oldUids.map(uid => uid + shift);
351
+ mailbox.uidnext += shift;
352
+ }
353
+ messages.forEach((message, i) => {
354
+ message.uid = newUids[i];
355
+ });
356
+ if (mode === 'shuffle') {
357
+ // the other modes keep the UID order
358
+ messages.sort((a, b) => a.uid - b.uid);
359
+ }
360
+ mailbox.uidvalidity = uidvalidity;
361
+ server.uidvalidityCounter = Math.max(server.uidvalidityCounter, uidvalidity);
362
+ return {
363
+ uidvalidity,
364
+ uidnext: mailbox.uidnext,
365
+ uids: oldUids.map((uid, i) => ({ uid, newUid: newUids[i] }))
366
+ };
367
+ }
368
+ /**
369
+ * Subscribes a mailbox (SUBSCRIBE), only an existing mailbox can be subscribed
370
+ *
371
+ * @param {Object} server IMAP server
372
+ * @param {String} path Storage name of the mailbox
373
+ * @return {Boolean} true if the subscription changed
374
+ * @throws {Error} NONEXISTENT for a name that is not a mailbox
375
+ */
376
+ function subscribeMailbox(server, path) {
377
+ const mailbox = server.getMailbox(path);
378
+ if (!mailbox || mailbox.flags.indexOf('\\Noselect') >= 0) {
379
+ throw storeError('Mailbox does not exist', 'NONEXISTENT');
380
+ }
381
+ if (mailbox.subscribed) {
382
+ return false;
383
+ }
384
+ mailbox.subscribed = true;
385
+ server.mailboxChanged('subscribe', mailbox.path);
386
+ return true;
387
+ }
388
+ /**
389
+ * Unsubscribes a name (UNSUBSCRIBE). The subscription list holds names, so a name stays removable after its
390
+ * mailbox is deleted (RFC 3501 section 6.3.6). Removing a name that is not subscribed is not an error
391
+ * (RFC 9051 section 6.3.8)
392
+ *
393
+ * @param {Object} server IMAP server
394
+ * @param {String} path Storage name
395
+ * @return {Boolean} true if the subscription changed
396
+ */
397
+ function unsubscribeMailbox(server, path) {
398
+ if (path.toUpperCase() === 'INBOX') {
399
+ path = 'INBOX';
400
+ }
401
+ if (!server.subscriptions.delete(path)) {
402
+ return false;
403
+ }
404
+ server.mailboxChanged('unsubscribe', path);
405
+ return true;
406
+ }
407
+ export { DEFAULT_SESSION_TIMEOUT, ImapKitError, storeError, expungeMessages, notifyFlagChanges, checkFlags, changeFlags, createMailbox, deleteMailbox, renameMailbox, resetUidValidity, subscribeMailbox, unsubscribeMailbox };
@@ -72,6 +72,8 @@ export interface MailboxChangeEvent {
72
72
  oldPath: string | null;
73
73
  mailbox: Mailbox | null;
74
74
  origin: IMAPConnection | null;
75
+ /** "create": every mailbox the change created, superior hierarchy levels first */
76
+ created?: string[] | undefined;
75
77
  }
76
78
  export type Callback = (err?: any, ...args: any[]) => void;
77
79
  /** Handler of an IMAP command, it must send a tagged response and then call the callback */
@@ -222,6 +224,18 @@ export interface IMAPServerOptions {
222
224
  plugins?: (string | Plugin)[] | string | Plugin | undefined;
223
225
  users?: Record<string, UserData> | undefined;
224
226
  secureConnection?: boolean | undefined;
227
+ /** starts an SMTP server with `server.start()` that appends every received message to INBOX, needs the optional
228
+ * smtp-server package */
229
+ smtp?: {
230
+ port?: number | undefined;
231
+ host?: string | undefined;
232
+ } | undefined;
233
+ /** starts the REST API with `server.start()`, see src/rest.ts. A host other than a loopback address needs a token */
234
+ rest?: {
235
+ port?: number | undefined;
236
+ host?: string | undefined;
237
+ token?: string | undefined;
238
+ } | undefined;
225
239
  credentials?: {
226
240
  key: string | Buffer;
227
241
  cert: string | Buffer;
@@ -232,6 +246,12 @@ export interface IMAPServerOptions {
232
246
  maxLiteralSize?: number | undefined;
233
247
  /** script rules that make the server misbehave on purpose, see src/script.ts and README "Scripted faults" */
234
248
  script?: ScriptRule | ScriptRule[] | undefined;
249
+ /** the current time for the dates the server sets (INTERNALDATE, SAVEDATE): a Date, a timestamp or a function */
250
+ now?: Date | number | (() => Date | number) | undefined;
251
+ /** quirk presets that make the server behave like a known real server, see src/quirks.ts */
252
+ quirks?: string[] | string | undefined;
253
+ /** seed of the random numbers of script rules with `chance`, so that a run can be repeated */
254
+ scriptSeed?: number | undefined;
235
255
  [key: string]: any;
236
256
  }
237
257
  /**
@@ -318,7 +338,8 @@ export type MessageHandler = (server: IMAPServer, message: Message, mailbox: Mai
318
338
  export type MailboxHandler = (server: IMAPServer, mailbox: Mailbox) => void;
319
339
  export type CopyHandler = (server: IMAPServer, source: Message, properties: Record<string, any>, mailbox: Mailbox) => void;
320
340
  export type NotifyFilter = (connection: IMAPConnection, event: NotifyEvent) => boolean;
321
- export type AppendCheck = (connection: IMAPConnection, mailbox: Mailbox, messages: AppendMessage[], options: AppendCheckOptions) => CheckResult | false | null | undefined | void;
341
+ /** `server.appendChecks`, `connection` is null for the control API (`addMessage` with `checks`) */
342
+ export type AppendCheck = (connection: IMAPConnection | null, mailbox: Mailbox, messages: AppendMessage[], options: AppendCheckOptions) => CheckResult | false | null | undefined | void;
322
343
  export type LiteralFilter = (connection: IMAPConnection, command: string, line: string, size: number) => Refusal | false | null | undefined;
323
344
  export type UrlAccessCheck = (connection: IMAPConnection, mailbox: Mailbox, url: any) => {
324
345
  text: string;
@@ -280,19 +280,5 @@
280
280
  "Valid login info:",
281
281
  " Username: testuser",
282
282
  " Access Token: testtoken"
283
- ],
284
- "XTOYBIRD": [
285
- "Custom plugin to allow programmatic control of the server",
286
- "Available commands:",
287
- " XTOYBIRD SERVER dumps server internals",
288
- " XTOYBIRD CONNECTION dumps connection internals",
289
- " XTOYBIRD STORAGE dumps storage as JSON",
290
- " XTOYBIRD USERADD \"username\" \"password\" adds or updates user",
291
- " XTOYBIRD USERDEL \"username\" removes a user",
292
- " XTOYBIRD SHUTDOWN Closes the server after the last client",
293
- " disconnects. New connections are rejected.",
294
- "Commands are only allowed after login, and only for the owner",
295
- "(aclOwner option) when ACL is loaded. A test control plugin,",
296
- "any user it allows can read and change everything"
297
283
  ]
298
284
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imapkit",
3
- "version": "4.3.1",
3
+ "version": "5.0.0",
4
4
  "description": "Scriptable, strictly RFC compliant in-memory IMAP server for testing IMAP clients",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/index.js",
@@ -83,8 +83,7 @@
83
83
  "author": "Postal Systems OÜ",
84
84
  "license": "MIT",
85
85
  "dependencies": {
86
- "imap-handler": "1.4.0",
87
- "smtp-server": "3.19.17"
86
+ "imap-handler": "1.4.0"
88
87
  },
89
88
  "devDependencies": {
90
89
  "@eslint/js": "10.0.1",
@@ -95,11 +94,20 @@
95
94
  "globals": "17.13.0",
96
95
  "imapflow": "2.2.9",
97
96
  "prettier": "3.9.9",
97
+ "smtp-server": "3.19.17",
98
98
  "tsx": "4.23.15",
99
99
  "typescript": "6.0.3",
100
100
  "typescript-eslint": "8.71.1"
101
101
  },
102
102
  "engines": {
103
103
  "node": ">=20.0.0"
104
+ },
105
+ "peerDependencies": {
106
+ "smtp-server": "^3.19.17"
107
+ },
108
+ "peerDependenciesMeta": {
109
+ "smtp-server": {
110
+ "optional": true
111
+ }
104
112
  }
105
113
  }
@@ -1,2 +0,0 @@
1
- import type { IMAPServer } from '../types.js';
2
- export default function xtoybirdPlugin(server: IMAPServer): void;