imapkit 5.0.0 → 5.1.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 (74) hide show
  1. package/README.md +51 -29
  2. package/bin/help.txt +3 -2
  3. package/bin/imapkit.js +15 -5
  4. package/dist/browser/imapkit.js +105 -0
  5. package/dist/cjs/commands/handlers/fetch.js +2 -1
  6. package/dist/cjs/commands/handlers/store.js +4 -4
  7. package/dist/cjs/commands/list.js +17 -3
  8. package/dist/cjs/control.d.ts +4 -9
  9. package/dist/cjs/control.js +1 -1
  10. package/dist/cjs/dates.d.ts +9 -1
  11. package/dist/cjs/dates.js +20 -0
  12. package/dist/cjs/envelope.d.ts +1 -1
  13. package/dist/cjs/envelope.js +26 -1
  14. package/dist/cjs/index.d.ts +3 -1
  15. package/dist/cjs/load-plugins.d.ts +3 -1
  16. package/dist/cjs/load-plugins.js +25 -6
  17. package/dist/cjs/memory-socket.d.ts +69 -0
  18. package/dist/cjs/memory-socket.js +187 -0
  19. package/dist/cjs/plugins/binary.js +2 -1
  20. package/dist/cjs/plugins/context-search.js +2 -2
  21. package/dist/cjs/plugins/create-special-use.d.ts +0 -5
  22. package/dist/cjs/plugins/create-special-use.js +11 -1
  23. package/dist/cjs/plugins/idle.js +2 -2
  24. package/dist/cjs/plugins/imap4rev2.js +5 -0
  25. package/dist/cjs/plugins/metadata-server.d.ts +6 -2
  26. package/dist/cjs/plugins/metadata-server.js +3 -1
  27. package/dist/cjs/plugins/metadata.d.ts +5 -1
  28. package/dist/cjs/plugins/metadata.js +3 -0
  29. package/dist/cjs/quirks.d.ts +2 -2
  30. package/dist/cjs/quirks.js +5 -4
  31. package/dist/cjs/rest.d.ts +7 -3
  32. package/dist/cjs/rest.js +11 -5
  33. package/dist/cjs/server.d.ts +67 -3
  34. package/dist/cjs/server.js +241 -93
  35. package/dist/cjs/storage-schema.js +12 -5
  36. package/dist/cjs/store-operations.d.ts +5 -2
  37. package/dist/cjs/store-operations.js +6 -3
  38. package/dist/cjs/types.d.ts +4 -0
  39. package/dist/esm/commands/handlers/fetch.js +2 -1
  40. package/dist/esm/commands/handlers/store.js +4 -4
  41. package/dist/esm/commands/list.js +17 -3
  42. package/dist/esm/control.d.ts +4 -9
  43. package/dist/esm/control.js +1 -1
  44. package/dist/esm/dates.d.ts +9 -1
  45. package/dist/esm/dates.js +20 -1
  46. package/dist/esm/envelope.d.ts +1 -1
  47. package/dist/esm/envelope.js +26 -1
  48. package/dist/esm/index.d.ts +3 -1
  49. package/dist/esm/load-plugins.d.ts +3 -1
  50. package/dist/esm/load-plugins.js +25 -6
  51. package/dist/esm/memory-socket.d.ts +69 -0
  52. package/dist/esm/memory-socket.js +182 -0
  53. package/dist/esm/plugins/binary.js +2 -1
  54. package/dist/esm/plugins/context-search.js +2 -2
  55. package/dist/esm/plugins/create-special-use.d.ts +0 -5
  56. package/dist/esm/plugins/create-special-use.js +8 -1
  57. package/dist/esm/plugins/idle.js +2 -2
  58. package/dist/esm/plugins/imap4rev2.js +5 -0
  59. package/dist/esm/plugins/metadata-server.d.ts +6 -2
  60. package/dist/esm/plugins/metadata-server.js +3 -1
  61. package/dist/esm/plugins/metadata.d.ts +5 -1
  62. package/dist/esm/plugins/metadata.js +3 -0
  63. package/dist/esm/quirks.d.ts +2 -2
  64. package/dist/esm/quirks.js +5 -4
  65. package/dist/esm/rest.d.ts +7 -3
  66. package/dist/esm/rest.js +11 -5
  67. package/dist/esm/server.d.ts +67 -3
  68. package/dist/esm/server.js +243 -95
  69. package/dist/esm/storage-schema.js +12 -5
  70. package/dist/esm/store-operations.d.ts +5 -2
  71. package/dist/esm/store-operations.js +6 -3
  72. package/dist/esm/types.d.ts +4 -0
  73. package/dist/plugin-help.json +3 -2
  74. package/package.json +8 -1
@@ -85,7 +85,8 @@ function getSection(data, query, global) {
85
85
  else if (query.section.length > 1) {
86
86
  throw new Error((key || 'Part number') + ' does not take any arguments');
87
87
  }
88
- // RFC 3501 6.4.5: a part that does not exist is returned as an empty string
88
+ // a part that does not exist is returned as an empty string, like Dovecot does: RFC 3501 and RFC 9051 section
89
+ // 6.4.5 define no error for it, only an empty string for a partial range that starts beyond the end of the text
89
90
  const node = path ? (0, mimeparser_js_1.resolveNode)(data.tree, path, global) : data.tree;
90
91
  if (!node) {
91
92
  return '';
@@ -10,8 +10,8 @@ function setFlags(connection, message, flags) {
10
10
  [].concat(flags).forEach(flag => {
11
11
  flag = (0, flags_js_1.normalizeSystemFlag)(typeof flag === 'string' ? flag : String(flag.value || ''));
12
12
  (0, flags_js_1.checkSystemFlags)(connection.server, flag);
13
- // Ignore if it is not in allowed list and only permament flags are allowed to use
14
- if (mailbox.permanentFlags.indexOf(flag) < 0 && !mailbox.allowPermanentFlags) {
13
+ // a flag that is not in PERMANENTFLAGS is ignored (RFC 3501 section 7.1, RFC 9051 section 7.1)
14
+ if (!connection.server.isPermanentFlag(mailbox, flag)) {
15
15
  return;
16
16
  }
17
17
  if (messageFlags.indexOf(flag) < 0) {
@@ -26,8 +26,8 @@ function addFlags(connection, message, flags) {
26
26
  [].concat(flags).forEach(flag => {
27
27
  flag = (0, flags_js_1.normalizeSystemFlag)(typeof flag === 'string' ? flag : String(flag.value || ''));
28
28
  (0, flags_js_1.checkSystemFlags)(connection.server, flag);
29
- // Ignore if it is not in allowed list and only permament flags are allowed to use
30
- if (mailbox.permanentFlags.indexOf(flag) < 0 && !mailbox.allowPermanentFlags) {
29
+ // a flag that is not in PERMANENTFLAGS is ignored (RFC 3501 section 7.1, RFC 9051 section 7.1)
30
+ if (!connection.server.isPermanentFlag(mailbox, flag)) {
31
31
  return;
32
32
  }
33
33
  if (message.flags.indexOf(flag) < 0) {
@@ -22,8 +22,22 @@ function listCommand(connection, parsed, data, callback) {
22
22
  return callback();
23
23
  }
24
24
  if (!parsed.attributes[1].value) {
25
- // empty reference lists separator only
26
- const namespace = connection.server.storage[parsed.attributes[1].value || connection.server.referenceNamespace];
25
+ // RFC 3501 section 6.3.8: "An empty ("" string) mailbox name argument is a special request to return the
26
+ // hierarchy delimiter and the root name of the name given in the reference. The value returned as the root
27
+ // MAY be the empty string if the reference is non-rooted or is an empty string."
28
+ const server = connection.server;
29
+ const reference = parsed.attributes[0].value || '';
30
+ // the namespace of the reference, the personal one for a reference that is not a valid name
31
+ let key = server.referenceNamespace;
32
+ try {
33
+ key = server.getNamespace(connection.importMailboxName(reference)) || key;
34
+ }
35
+ catch {
36
+ // not a mailbox name, so not in another namespace
37
+ }
38
+ const namespace = key !== false ? server.storage[key] : undefined;
39
+ // the root of a name in another namespace is the prefix of that namespace, like "#news." in the RFC example
40
+ const root = key !== false && key !== server.referenceNamespace ? connection.exportMailboxName(key) : '';
27
41
  if (namespace) {
28
42
  connection.send({
29
43
  tag: '*',
@@ -36,7 +50,7 @@ function listCommand(connection, parsed, data, callback) {
36
50
  }
37
51
  ],
38
52
  namespace.separator,
39
- ''
53
+ root
40
54
  ]
41
55
  }, 'LIST ITEM', parsed, data);
42
56
  }
@@ -4,7 +4,7 @@
4
4
  * unsolicited FETCH, BYE, NOTIFY events, CONDSTORE mod-sequences), with no session as its origin. The API is the
5
5
  * operator: ACL does not apply, but every argument is checked. Mailboxes are addressed by their storage name
6
6
  * (modified UTF-7), messages by mailbox and UID. Methods return plain data and throw an ImapKitError with a `code`:
7
- * NONEXISTENT, ALREADYEXISTS, INVALID, or a RFC 5530 code of a failed mailbox operation (CANNOT, HASCHILDREN ...)
7
+ * NONEXISTENT, ALREADYEXISTS, INVALID, or the response code of a failed mailbox operation (CANNOT, HASCHILDREN ...)
8
8
  */
9
9
  import { ImapKitError } from './store-operations.js';
10
10
  import type { FlagMode, UidValidityOptions } from './store-operations.js';
@@ -22,7 +22,7 @@ interface MailboxInfo {
22
22
  unseen: number;
23
23
  uidnext: number;
24
24
  uidvalidity: number;
25
- /** flags that can be stored, \* when new keywords are allowed */
25
+ /** the flags of the FLAGS response, SELECT adds \* to PERMANENTFLAGS when new keywords are allowed */
26
26
  permanentFlags: string[];
27
27
  /** only with CONDSTORE */
28
28
  highestModseq?: number;
@@ -67,13 +67,8 @@ interface NewMessage {
67
67
  /** a Date or a RFC 3501 date-time string, the current time if not set */
68
68
  internaldate?: Date | string | undefined;
69
69
  }
70
- interface UserOptions {
71
- password?: string | undefined;
72
- xoauth2?: {
73
- accessToken?: string | undefined;
74
- sessionTimeout?: number | undefined;
75
- } | undefined;
76
- }
70
+ /** The credentials of a user, see UserData */
71
+ type UserOptions = Pick<UserData, 'password' | 'xoauth2'>;
77
72
  /** What a REST route handler gets, see src/rest.ts */
78
73
  interface RouteRequest {
79
74
  params: Record<string, string>;
@@ -5,7 +5,7 @@
5
5
  * unsolicited FETCH, BYE, NOTIFY events, CONDSTORE mod-sequences), with no session as its origin. The API is the
6
6
  * operator: ACL does not apply, but every argument is checked. Mailboxes are addressed by their storage name
7
7
  * (modified UTF-7), messages by mailbox and UID. Methods return plain data and throw an ImapKitError with a `code`:
8
- * NONEXISTENT, ALREADYEXISTS, INVALID, or a RFC 5530 code of a failed mailbox operation (CANNOT, HASCHILDREN ...)
8
+ * NONEXISTENT, ALREADYEXISTS, INVALID, or the response code of a failed mailbox operation (CANNOT, HASCHILDREN ...)
9
9
  */
10
10
  var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -36,6 +36,14 @@ declare function isRealDate(day: number | string | undefined, month: number, yea
36
36
  * @return {String|Boolean} the date, or false for an impossible date
37
37
  */
38
38
  declare function dateKey(day: number | string, month: number, year: number | string): string | false;
39
+ /**
40
+ * Checks a date-time string of RFC 3501 section 9, like an INTERNALDATE ("14-Sep-2013 21:22:28 -0300"):
41
+ * date-time = DQUOTE date-day-fixed "-" date-month "-" date-year SP time SP zone DQUOTE
42
+ *
43
+ * @param {String} value Value to check
44
+ * @return {Boolean} true if the value is a date-time string of a real date and time
45
+ */
46
+ declare function isDateTime(value: unknown): boolean;
39
47
  /**
40
48
  * Parses a date-time value of the RFC 3501 section 9 form, like an INTERNALDATE ("14-Sep-2013 21:22:28 -0300").
41
49
  * A value with only the date part is accepted as well, its time fields are left undefined
@@ -61,4 +69,4 @@ declare function parseHeaderDate(header: string | undefined): DateParts | null;
61
69
  * @return {Number} timestamp
62
70
  */
63
71
  declare function toTimestamp(date: DateParts): number;
64
- export { MONTHS, monthIndex, isRealDate, dateKey, parseDateTime, parseHeaderDate, toTimestamp };
72
+ export { MONTHS, monthIndex, isRealDate, isDateTime, dateKey, parseDateTime, parseHeaderDate, toTimestamp };
package/dist/cjs/dates.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MONTHS = void 0;
4
4
  exports.monthIndex = monthIndex;
5
5
  exports.isRealDate = isRealDate;
6
+ exports.isDateTime = isDateTime;
6
7
  exports.dateKey = dateKey;
7
8
  exports.parseDateTime = parseDateTime;
8
9
  exports.parseHeaderDate = parseHeaderDate;
@@ -50,6 +51,25 @@ function dateKey(day, month, year) {
50
51
  }
51
52
  return String(year).padStart(4, '0') + '-' + String(month + 1).padStart(2, '0') + '-' + String(day).padStart(2, '0');
52
53
  }
54
+ /**
55
+ * Checks a date-time string of RFC 3501 section 9, like an INTERNALDATE ("14-Sep-2013 21:22:28 -0300"):
56
+ * date-time = DQUOTE date-day-fixed "-" date-month "-" date-year SP time SP zone DQUOTE
57
+ *
58
+ * @param {String} value Value to check
59
+ * @return {Boolean} true if the value is a date-time string of a real date and time
60
+ */
61
+ function isDateTime(value) {
62
+ if (!value || typeof value !== 'string') {
63
+ return false;
64
+ }
65
+ // month names are case-insensitive like all ABNF strings
66
+ const match = value.match(/^( \d|\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4}) (\d{2}):(\d{2}):(\d{2}) [-+](\d{2})(\d{2})$/i);
67
+ if (!match) {
68
+ return false;
69
+ }
70
+ // the values must also make a real date and time
71
+ return (isRealDate(match[1], monthIndex(match[2]), match[3]) && Number(match[4]) < 24 && Number(match[5]) < 60 && Number(match[6]) < 61 && Number(match[8]) < 60);
72
+ }
53
73
  /**
54
74
  * Parses a date-time value of the RFC 3501 section 9 form, like an INTERNALDATE ("14-Sep-2013 21:22:28 -0300").
55
75
  * A value with only the date part is accepted as well, its time fields are left undefined
@@ -1,7 +1,7 @@
1
1
  import type { ParsedAddress } from './addressparser.js';
2
2
  import type { ParsedHeader } from './mimeparser.js';
3
3
  /** An address of the ENVELOPE (RFC 3501 section 9): name, source route, mailbox and host, all NIL for a group end */
4
- export type EnvelopeAddress = [name: string | null, adl: null, mailbox: string | null, host: string | null];
4
+ export type EnvelopeAddress = [name: string | null, adl: string | null, mailbox: string | null, host: string | null];
5
5
  /** The fields of the ENVELOPE (RFC 3501 section 7.4.2), in order */
6
6
  export type Envelope = [
7
7
  date: string | null,
@@ -3,6 +3,29 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.default = envelope;
5
5
  exports.processAddress = processAddress;
6
+ // RFC 5322 section 4.4: obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS], obs-route = obs-domain-list ":",
7
+ // obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]). A domain-literal can hold a colon
8
+ const OBS_ROUTE = /^[\s,]*(@(?:[^:[]|\[[^\]]*\])*):/;
9
+ /**
10
+ * Splits an obsolete source route from an address: the route goes to addr-adl, the rest is the addr-spec
11
+ * (RFC 9051 section 7.5.2: the at-domain-list is the "source route and obs-route ABNF production from [RFC5322]",
12
+ * the mailbox name the "local-part ABNF production"). The route is sent like Dovecot does, "@a,@b"
13
+ *
14
+ * @param {String} address Address from the angle brackets
15
+ * @return {Array} [route or null, addr-spec]
16
+ */
17
+ function splitRoute(address) {
18
+ const match = address.match(OBS_ROUTE);
19
+ if (!match) {
20
+ return [null, address];
21
+ }
22
+ const route = match[1]
23
+ .split(',')
24
+ .map(domain => domain.trim())
25
+ .filter(domain => domain)
26
+ .join(',');
27
+ return [route, address.substr(match[0].length).trim()];
28
+ }
6
29
  /**
7
30
  * Convert a message object to an ENVELOPE object
8
31
  *
@@ -61,12 +84,14 @@ function processAddress(arr, def) {
61
84
  if (!address) {
62
85
  return;
63
86
  }
87
+ const [route, addrSpec] = splitRoute(address);
88
+ address = addrSpec;
64
89
  const at = address.lastIndexOf('@');
65
90
  const user = at >= 0 ? address.substr(0, at) : address;
66
91
  // RFC 3501 7.4.2 reserves a NIL host for group markers, so an address without a domain gets
67
92
  // the placeholder host that Dovecot uses for the same input
68
93
  const domain = (at >= 0 ? address.substr(at + 1) : '') || 'MISSING_DOMAIN';
69
- result.push([name, null, user || null, domain]);
94
+ result.push([name, route, user || null, domain]);
70
95
  });
71
96
  // env-from = "(" 1*address ")", there is no SP between the addresses (RFC 3501 section 9)
72
97
  Object.defineProperty(result, 'adjacentLists', { value: true });
@@ -6,7 +6,9 @@ export { TAG_REGEX, IMAPServer, IMAPConnection, ImapKitError, quirks, storageSch
6
6
  export type { Attribute, ParsedCommand, IMAPResponse, Notification, Callback, CommandHandler, CommandOptions, Plugin, IMAPError, Message, Mailbox, StorageNamespace, UserData, IMAPServerOptions } from './types.js';
7
7
  export type { ScriptRule, ScriptContext, ScriptEvent, ScriptBytes, ScriptHandle } from './script.js';
8
8
  export type { Quirk } from './quirks.js';
9
- export type { Control, MailboxInfo, MessageInfo, SessionInfo, NewMessage, UserOptions, SessionFilter } from './control.js';
9
+ export type { MemorySocket } from './memory-socket.js';
10
+ export type { Control, MailboxInfo, MessageInfo, SessionInfo, NewMessage, UserOptions, SessionFilter, ControlRoute, RouteRequest } from './control.js';
11
+ export type { FlagMode, UidMode, UidValidityOptions } from './store-operations.js';
10
12
  declare const imapkit: typeof createServer & {
11
13
  TAG_REGEX: RegExp;
12
14
  IMAPServer: typeof IMAPServer;
@@ -15,7 +15,9 @@ declare function listPlugins(): string[];
15
15
  *
16
16
  * @param {Object} server IMAPServer instance
17
17
  * @param {Array|String|Function} plugins List of plugins to load
18
+ * @param {Map} [exclude] Plugins a quirk preset leaves out, plugin name to quirk name
19
+ * @throws {Error} when a loaded plugin requires an excluded one
18
20
  */
19
- declare function loadPlugins(server: IMAPServer, plugins: (string | Plugin)[] | string | Plugin | null | undefined, exclude?: string[]): void;
21
+ declare function loadPlugins(server: IMAPServer, plugins: (string | Plugin)[] | string | Plugin | null | undefined, exclude?: Map<string, string>): void;
20
22
  export default loadPlugins;
21
23
  export { listPlugins };
@@ -49,12 +49,21 @@ function resolvePlugin(name) {
49
49
  *
50
50
  * @param {Object} server IMAPServer instance
51
51
  * @param {Array|String|Function} plugins List of plugins to load
52
+ * @param {Map} [exclude] Plugins a quirk preset leaves out, plugin name to quirk name
53
+ * @throws {Error} when a loaded plugin requires an excluded one
52
54
  */
53
55
  function loadPlugins(server, plugins, exclude) {
54
56
  const loaded = new Set();
55
- // plugins a quirk preset leaves out (no-move), they are not loaded even when listed
56
- const excluded = new Set((exclude || []).map(name => resolvePlugin(name)).flatMap(name => (name ? [index_js_1.plugins[name]] : [])));
57
- const load = (entry) => {
57
+ // plugins a quirk preset leaves out (no-move), they are not loaded even when listed, and the quirk that removes them
58
+ const excluded = new Map();
59
+ (exclude || new Map()).forEach((quirk, name) => {
60
+ const resolved = resolvePlugin(name);
61
+ if (resolved) {
62
+ excluded.set(index_js_1.plugins[resolved], quirk);
63
+ }
64
+ });
65
+ // `requiredBy` names the plugin whose `requires` lists this one
66
+ const load = (entry, requiredBy) => {
58
67
  let plugin = entry;
59
68
  if (typeof plugin === 'string') {
60
69
  const name = resolvePlugin(plugin);
@@ -69,14 +78,24 @@ function loadPlugins(server, plugins, exclude) {
69
78
  if (typeof plugin !== 'function') {
70
79
  throw new TypeError('Invalid plugin, expecting a plugin name or a function');
71
80
  }
72
- if (loaded.has(plugin) || excluded.has(plugin)) {
81
+ const quirk = excluded.get(plugin);
82
+ if (quirk) {
83
+ if (requiredBy) {
84
+ // the plugin can not work without it (IMAP4rev2 folds in MOVE and UIDPLUS, RFC 9051 Appendix E), so
85
+ // advertising it without the required plugin would break its RFC
86
+ throw new Error(requiredBy + ' requires ' + entry + ', which the "' + quirk + '" quirk removes');
87
+ }
88
+ return;
89
+ }
90
+ if (loaded.has(plugin)) {
73
91
  return;
74
92
  }
75
93
  loaded.add(plugin);
76
- [].concat(plugin.requires || []).forEach(load);
94
+ const name = typeof entry === 'string' ? entry.trim() : plugin.name;
95
+ [].concat(plugin.requires || []).forEach(required => load(required, name));
77
96
  plugin(server);
78
97
  };
79
- [].concat(plugins || []).forEach(load);
98
+ [].concat(plugins || []).forEach(entry => load(entry));
80
99
  server.emit('pluginsLoaded');
81
100
  }
82
101
  exports.default = loadPlugins;
@@ -0,0 +1,69 @@
1
+ import { EventEmitter } from 'node:events';
2
+ /**
3
+ * One end of an in-memory connection, see `server.connect()`. It has the parts of `net.Socket` that the server and a
4
+ * client use: `write(data, [encoding], [callback])`, `end()`, `destroy()`, `pause()`, `resume()`, `setEncoding()`,
5
+ * the `data`, `end`, `close` and `error` events, and `encrypted`, which makes the server treat the connection like
6
+ * one over TLS (as `tls.TLSSocket#encrypted` does). Written data reaches the other end on a later event loop turn,
7
+ * one `data` event per write
8
+ */
9
+ export declare class MemorySocket extends EventEmitter {
10
+ /** the other end of the connection */
11
+ peer: MemorySocket | null;
12
+ destroyed: boolean;
13
+ /** true if the connection counts as encrypted (implicit TLS, or after STARTTLS) */
14
+ encrypted: boolean;
15
+ _paused: boolean;
16
+ _ending: boolean;
17
+ _encoding: BufferEncoding | null;
18
+ /** received data that waits while the socket is paused */
19
+ _received: Buffer[];
20
+ constructor();
21
+ /**
22
+ * Sends data to the other end
23
+ *
24
+ * @param data Data to send, a string is encoded with `encoding` (utf8 by default)
25
+ * @param encoding Encoding of a string, or the callback
26
+ * @param callback Called once the other end received the data
27
+ * @return true, there is no backpressure
28
+ */
29
+ write(data: Buffer | Uint8Array | string, encoding?: BufferEncoding | (() => void), callback?: () => void): boolean;
30
+ /**
31
+ * Ends the connection after the data written so far reached the other end, both ends close then
32
+ *
33
+ * @param data Data to send before the end
34
+ */
35
+ end(data?: Buffer | Uint8Array | string): this;
36
+ /**
37
+ * Closes both ends right away, data that did not reach the other end yet is lost
38
+ *
39
+ * @param error Error to emit on this end
40
+ */
41
+ destroy(error?: Error): this;
42
+ /**
43
+ * Closes the connection like a TCP RST: the other end gets an ECONNRESET error (`close: 'reset'` of script rules)
44
+ */
45
+ resetAndDestroy(): this;
46
+ /**
47
+ * STARTTLS without TLS: both ends count as encrypted from now on (`upgradeConnection` in src/server.ts)
48
+ *
49
+ * @param callback Called once the connection counts as encrypted
50
+ */
51
+ startTls(callback: () => void): void;
52
+ pause(): this;
53
+ resume(): this;
54
+ /**
55
+ * Makes the `data` events carry strings instead of Buffers
56
+ *
57
+ * @param encoding Encoding of the strings, e.g. "utf8" or "binary"
58
+ */
59
+ setEncoding(encoding: BufferEncoding): this;
60
+ deliver(chunk: Buffer): void;
61
+ private emitData;
62
+ close(error?: Error): void;
63
+ }
64
+ /**
65
+ * Creates the two ends of an in-memory connection
66
+ *
67
+ * @return `[serverSocket, clientSocket]`
68
+ */
69
+ export declare function createSocketPair(): [MemorySocket, MemorySocket];
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemorySocket = void 0;
4
+ exports.createSocketPair = createSocketPair;
5
+ const node_events_1 = require("node:events");
6
+ /**
7
+ * One end of an in-memory connection, see `server.connect()`. It has the parts of `net.Socket` that the server and a
8
+ * client use: `write(data, [encoding], [callback])`, `end()`, `destroy()`, `pause()`, `resume()`, `setEncoding()`,
9
+ * the `data`, `end`, `close` and `error` events, and `encrypted`, which makes the server treat the connection like
10
+ * one over TLS (as `tls.TLSSocket#encrypted` does). Written data reaches the other end on a later event loop turn,
11
+ * one `data` event per write
12
+ */
13
+ class MemorySocket extends node_events_1.EventEmitter {
14
+ constructor() {
15
+ super();
16
+ this.peer = null;
17
+ this.destroyed = false;
18
+ this.encrypted = false;
19
+ this._paused = false;
20
+ this._ending = false;
21
+ this._encoding = null;
22
+ this._received = [];
23
+ }
24
+ /**
25
+ * Sends data to the other end
26
+ *
27
+ * @param data Data to send, a string is encoded with `encoding` (utf8 by default)
28
+ * @param encoding Encoding of a string, or the callback
29
+ * @param callback Called once the other end received the data
30
+ * @return true, there is no backpressure
31
+ */
32
+ write(data, encoding, callback) {
33
+ if (typeof encoding === 'function') {
34
+ callback = encoding;
35
+ encoding = undefined;
36
+ }
37
+ if (this.destroyed || this._ending) {
38
+ return false;
39
+ }
40
+ // no copy, like a real socket the data is not changed after it was written
41
+ const chunk = typeof data === 'string' ? Buffer.from(data, encoding || 'utf8') : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
42
+ nextTurn(() => {
43
+ this.peer?.deliver(chunk);
44
+ callback?.();
45
+ });
46
+ return true;
47
+ }
48
+ /**
49
+ * Ends the connection after the data written so far reached the other end, both ends close then
50
+ *
51
+ * @param data Data to send before the end
52
+ */
53
+ end(data) {
54
+ if (data !== undefined) {
55
+ this.write(data);
56
+ }
57
+ if (this.destroyed || this._ending) {
58
+ return this;
59
+ }
60
+ this._ending = true;
61
+ // queued after the writes, so the other end gets all data first
62
+ nextTurn(() => {
63
+ const peer = this.peer;
64
+ if (peer && !peer.destroyed) {
65
+ peer.emit('end');
66
+ peer.close();
67
+ }
68
+ this.close();
69
+ });
70
+ return this;
71
+ }
72
+ /**
73
+ * Closes both ends right away, data that did not reach the other end yet is lost
74
+ *
75
+ * @param error Error to emit on this end
76
+ */
77
+ destroy(error) {
78
+ if (this.destroyed) {
79
+ return this;
80
+ }
81
+ const peer = this.peer;
82
+ this.close(error);
83
+ if (peer && !peer.destroyed) {
84
+ peer.close();
85
+ }
86
+ return this;
87
+ }
88
+ /**
89
+ * Closes the connection like a TCP RST: the other end gets an ECONNRESET error (`close: 'reset'` of script rules)
90
+ */
91
+ resetAndDestroy() {
92
+ const peer = this.peer;
93
+ this.destroy();
94
+ if (peer) {
95
+ const error = new Error('read ECONNRESET');
96
+ error.code = 'ECONNRESET';
97
+ nextTurn(() => peer.emit('error', error));
98
+ }
99
+ return this;
100
+ }
101
+ /**
102
+ * STARTTLS without TLS: both ends count as encrypted from now on (`upgradeConnection` in src/server.ts)
103
+ *
104
+ * @param callback Called once the connection counts as encrypted
105
+ */
106
+ startTls(callback) {
107
+ this.encrypted = true;
108
+ if (this.peer) {
109
+ this.peer.encrypted = true;
110
+ }
111
+ callback();
112
+ }
113
+ pause() {
114
+ this._paused = true;
115
+ return this;
116
+ }
117
+ resume() {
118
+ this._paused = false;
119
+ while (this._received.length && !this._paused && !this.destroyed) {
120
+ this.emitData(this._received.shift());
121
+ }
122
+ return this;
123
+ }
124
+ /**
125
+ * Makes the `data` events carry strings instead of Buffers
126
+ *
127
+ * @param encoding Encoding of the strings, e.g. "utf8" or "binary"
128
+ */
129
+ setEncoding(encoding) {
130
+ this._encoding = encoding;
131
+ return this;
132
+ }
133
+ deliver(chunk) {
134
+ if (this.destroyed) {
135
+ return;
136
+ }
137
+ if (this._paused) {
138
+ this._received.push(chunk);
139
+ return;
140
+ }
141
+ this.emitData(chunk);
142
+ }
143
+ emitData(chunk) {
144
+ this.emit('data', this._encoding ? chunk.toString(this._encoding) : chunk);
145
+ }
146
+ close(error) {
147
+ if (this.destroyed) {
148
+ return;
149
+ }
150
+ this.destroyed = true;
151
+ this._received = [];
152
+ nextTurn(() => {
153
+ if (error) {
154
+ this.emit('error', error);
155
+ }
156
+ this.emit('close', !!error);
157
+ });
158
+ }
159
+ }
160
+ exports.MemorySocket = MemorySocket;
161
+ /**
162
+ * Creates the two ends of an in-memory connection
163
+ *
164
+ * @return `[serverSocket, clientSocket]`
165
+ */
166
+ function createSocketPair() {
167
+ const serverSocket = new MemorySocket();
168
+ const clientSocket = new MemorySocket();
169
+ serverSocket.peer = clientSocket;
170
+ clientSocket.peer = serverSocket;
171
+ return [serverSocket, clientSocket];
172
+ }
173
+ // one ordered queue for both ends, so the data and events of a connection keep the order they were sent in
174
+ const queue = [];
175
+ function nextTurn(fn) {
176
+ queue.push(fn);
177
+ if (queue.length === 1) {
178
+ setImmediate(runQueue);
179
+ }
180
+ }
181
+ function runQueue() {
182
+ // what runs now may queue more, that waits for the next turn
183
+ const batch = queue.splice(0, queue.length);
184
+ for (const fn of batch) {
185
+ fn();
186
+ }
187
+ }
@@ -109,7 +109,8 @@ function getDecodedSection(connection, message, query) {
109
109
  }
110
110
  const node = (0, mimeparser_js_1.resolveNode)((0, mimeparser_js_1.getMessageData)(message).tree, section[0].value, connection.messageGlobal);
111
111
  if (!node) {
112
- // like BODY[<section>], a part that does not exist is empty
112
+ // like BODY[<section>], a part that does not exist is empty: RFC 3516 and RFC 9051 section 6.4.5 define no
113
+ // error for it, and BINARY follows the semantics of BODY (RFC 3516 section 4.2)
113
114
  return '';
114
115
  }
115
116
  if (!isLeaf(node, connection.messageGlobal)) {
@@ -252,8 +252,8 @@ function contextSearchPlugin(server) {
252
252
  // knows the current message list, so new matches can be reported after their EXISTS and FETCH responses
253
253
  // (RFC 5267 section 4.3.2). A command that closes the mailbox gets no updates, its tagged response ends them
254
254
  const processNotifications = connection.processNotifications;
255
- connection.processNotifications = function (data) {
256
- processNotifications.call(this, data);
255
+ connection.processNotifications = function (data, beforeCommand) {
256
+ processNotifications.call(this, data, beforeCommand);
257
257
  const command = ((data && data.command) || '').toUpperCase();
258
258
  if (this.searchContexts && this.searchContexts.size && !this.notificationQueue.length && !CLOSING_COMMANDS.has(command)) {
259
259
  checkContexts(this);
@@ -1,7 +1,2 @@
1
1
  import type { IMAPServer } from '../types.js';
2
- /**
3
- * @help Enables CREATE-SPECIAL-USE [RFC6154] capability
4
- * @help Allowed special flags can be set with server
5
- * @help option "special-use"
6
- */
7
2
  export default function createSpecialUsePlugin(server: IMAPServer): void;
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.default = createSpecialUsePlugin;
7
+ const formal_1 = __importDefault(require("imap-handler/lib/formal"));
8
+ const arguments_js_1 = require("../arguments.js");
4
9
  /**
5
10
  * @help Enables CREATE-SPECIAL-USE [RFC6154] capability
6
11
  * @help Allowed special flags can be set with server
7
12
  * @help option "special-use"
8
13
  */
14
+ // use-attr-ext = "\" atom (RFC 6154 section 6), with the ATOM-CHAR of the imap-handler grammar (RFC 3501 section 9)
15
+ const USE_ATTR = new RegExp('^\\\\[' + formal_1.default['ATOM-CHAR']().replace(/[\\\]^-]/g, '\\$&') + ']+$');
9
16
  function createSpecialUsePlugin(server) {
10
17
  // Register capability
11
18
  server.registerCapability('CREATE-SPECIAL-USE');
@@ -34,7 +41,10 @@ function createSpecialUsePlugin(server) {
34
41
  }
35
42
  if (specialUseList) {
36
43
  for (i = 0, len = specialUseList.length; i < len; i++) {
37
- if (['ATOM', 'STRING', 'LITERAL'].indexOf(specialUseList[i].type) < 0) {
44
+ // RFC 6154 section 6: use-attr-ext = "\" atom, so every entry is an atom that starts with a backslash,
45
+ // not NIL, a string, a literal, a number or a list
46
+ const entry = specialUseList[i];
47
+ if (!(0, arguments_js_1.isAtom)(entry) || !USE_ATTR.test(entry.value)) {
38
48
  connection.send({
39
49
  tag: parsed.tag,
40
50
  command: 'BAD',
@@ -23,8 +23,8 @@ function idlePlugin(server) {
23
23
  connection.end();
24
24
  }
25
25
  }, 30 * 60 * 1000);
26
- // An idling client should not keep the process alive
27
- idleTimer.unref();
26
+ // An idling client should not keep the process alive (browsers have no unref)
27
+ idleTimer.unref?.();
28
28
  const clearIdleTimer = () => clearTimeout(idleTimer);
29
29
  const socket = connection.socket;
30
30
  if (socket) {
@@ -128,6 +128,11 @@ function imap4rev2Plugin(server) {
128
128
  }, 'SELECT LIST', parsed, data, mailbox);
129
129
  };
130
130
  server.outputHandlers.push((connection, response, description, parsed, data) => {
131
+ if (description === 'RECENT NOTIFICATION' && isRev2(connection)) {
132
+ // Appendix E item 12: no RECENT response after the EXISTS of new messages either
133
+ response.skipResponse = true;
134
+ return;
135
+ }
131
136
  if (!parsed || !response || !isRev2(connection)) {
132
137
  return;
133
138
  }