imapflow 2.2.7 → 2.2.9

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/dist/cjs/tools.js CHANGED
@@ -56,6 +56,7 @@ exports.packMessageRange = packMessageRange;
56
56
  const libmime_1 = __importDefault(require("libmime"));
57
57
  const charsets_js_1 = require("./charsets.js");
58
58
  const imap_handler_js_1 = require("./handler/imap-handler.js");
59
+ const imap_formal_syntax_js_1 = __importDefault(require("./handler/imap-formal-syntax.js"));
59
60
  const node_crypto_1 = require("node:crypto");
60
61
  const jp_decoder_js_1 = require("./jp-decoder.js");
61
62
  const iconv_lite_1 = __importDefault(require("iconv-lite"));
@@ -336,7 +337,8 @@ function buildStatusQueryAttributes(connection, statusQuery) {
336
337
  }
337
338
  break;
338
339
  case 'HIGHESTMODSEQ':
339
- if (connection.capabilities.has('CONDSTORE')) {
340
+ // QRESYNC implies CONDSTORE (RFC 7162 3.2.3)
341
+ if (connection.capabilities.has('CONDSTORE') || connection.capabilities.has('QRESYNC')) {
340
342
  attributes.push({ type: 'ATOM', value: key.toUpperCase() });
341
343
  }
342
344
  break;
@@ -717,24 +719,40 @@ function getColorFlags(color) {
717
719
  * @param untagged - Parsed untagged IMAP response
718
720
  * @param mailbox - Current mailbox state object
719
721
  * @param idHashAlgorithm - Hash for the fallback message id, `md5` unless the client was told otherwise
722
+ * @param connection - Connection the response arrived on, decodes Gmail labels like mailbox names
720
723
  * @returns Formatted message object with properties like seq, uid, flags, envelope, etc.
721
724
  */
722
- async function formatMessageResponse(untagged, mailbox, idHashAlgorithm) {
725
+ async function formatMessageResponse(untagged, mailbox, idHashAlgorithm, connection) {
723
726
  let map = {};
724
727
  // The sequence number indexes into mailbox state, so an unusable one is dropped rather
725
728
  // than coerced to NaN or Infinity
726
729
  map.seq = parseUintValue(untagged.command, exports.MAX_UINT32_DIGITS) || undefined;
727
730
  let key;
731
+ // the <origin> of a partial section ("BODY[2]<1024>"), kept for the value that follows
732
+ let origin = false;
733
+ let partialOrigins;
734
+ let recordOrigin = (sectionKey) => {
735
+ if (origin !== false) {
736
+ if (!partialOrigins) {
737
+ partialOrigins = new Map();
738
+ }
739
+ partialOrigins.set(sectionKey, origin);
740
+ }
741
+ };
728
742
  let attributes = ((untagged.attributes && untagged.attributes[1]) || []);
729
743
  for (let i = 0, len = attributes.length; i < len; i++) {
730
744
  let attribute = attributes[i];
731
745
  if (i % 2 === 0) {
746
+ origin = false;
732
747
  key = (await (0, imap_handler_js_1.compiler)({
733
748
  attributes: [attribute]
734
749
  }))
735
750
  .toString()
736
751
  .toLowerCase()
737
- .replace(/<\d+(\.\d+)?>$/, '');
752
+ .replace(/<(\d+)(\.\d+)?>$/, (match, start) => {
753
+ origin = parseUintValue(start, exports.MAX_UINT32_DIGITS);
754
+ return '';
755
+ });
738
756
  continue;
739
757
  }
740
758
  /* c8 ignore start */ // defensive: key is always a string produced by the compiler above
@@ -779,6 +797,7 @@ async function formatMessageResponse(untagged, mailbox, idHashAlgorithm) {
779
797
  case 'body[]':
780
798
  case 'binary[]':
781
799
  map.source = getBuffer(attribute);
800
+ recordOrigin('');
782
801
  break;
783
802
  case 'uid':
784
803
  // A UID feeds mailbox.uidNext one line below, and from there every range
@@ -825,7 +844,8 @@ async function formatMessageResponse(untagged, mailbox, idHashAlgorithm) {
825
844
  map.threadId = getString(attribute);
826
845
  break;
827
846
  case 'x-gm-labels':
828
- map.labels = new Set(getArray(attribute));
847
+ // labels are mailbox names, modified UTF-7 unless UTF-8 is enabled
848
+ map.labels = new Set(getArray(attribute).map(label => (connection ? decodePath(connection, label) : label)));
829
849
  break;
830
850
  case 'rfc822.size':
831
851
  map.size = getUint(attribute) || 0;
@@ -871,6 +891,7 @@ async function formatMessageResponse(untagged, mailbox, idHashAlgorithm) {
871
891
  map.bodyParts = new Map();
872
892
  }
873
893
  map.bodyParts.set(partKey, value);
894
+ recordOrigin(partKey);
874
895
  if (match[1].toLowerCase() === 'binary') {
875
896
  // The part arrived via FETCH BINARY (RFC 3516, FETCH side folded
876
897
  // into IMAP4rev2), so the server has already removed the
@@ -912,6 +933,10 @@ async function formatMessageResponse(untagged, mailbox, idHashAlgorithm) {
912
933
  .update([path, mailbox.uidValidity?.toString() || '', map.uid.toString()].join(':'))
913
934
  .digest('hex');
914
935
  }
936
+ if (partialOrigins) {
937
+ // non-enumerable, so it stays out of logged and serialized fetch results
938
+ Object.defineProperty(map, 'partialOrigins', { value: partialOrigins, writable: true, configurable: true });
939
+ }
915
940
  if (map.flags) {
916
941
  let flagColor = getFlagColor(map.flags);
917
942
  if (flagColor) {
@@ -1354,14 +1379,22 @@ function formatDateTime(value) {
1354
1379
  let timeStr = date.toISOString().substring(11, 19);
1355
1380
  return `${dateStr} ${timeStr} +0000`;
1356
1381
  }
1382
+ // the memoized ATOM-CHAR set of RFC 9051 section 9
1383
+ const atomChars = imap_formal_syntax_js_1.default['ATOM-CHAR'];
1357
1384
  /**
1358
- * Normalizes a flag string. Returns false for non-settable flags (e.g. \Recent),
1359
- * and capitalizes system flags properly.
1385
+ * Normalizes a flag string. Returns false for non-settable flags (e.g. \Recent) and for
1386
+ * values that are not valid flags (keywords must be atoms), and capitalizes system flags properly.
1360
1387
  *
1361
1388
  * @param flag - Flag string to normalize
1362
1389
  * @returns Normalized flag string, or false if the flag cannot be set
1363
1390
  */
1364
1391
  function formatFlag(flag) {
1392
+ // RFC 9051 section 9: flag-keyword is an atom and flag-extension is "\\" atom, the same check
1393
+ // the compiler uses to decide what it can send unquoted
1394
+ let atom = flag.charAt(0) === '\\' ? flag.slice(1) : flag;
1395
+ if (!atom || imap_formal_syntax_js_1.default.verify(atom, atomChars()) >= 0) {
1396
+ return false;
1397
+ }
1365
1398
  switch (flag.toLowerCase()) {
1366
1399
  case '\\recent':
1367
1400
  // can not set or remove
@@ -499,6 +499,8 @@ export interface FetchQueryObject {
499
499
  /** Include full message in the response, up to maxLength bytes */
500
500
  maxLength?: number | undefined;
501
501
  } | undefined;
502
+ /** Email ID (OBJECTID EMAILID or Gmail X-GM-MSGID) is always requested when the server supports either extension, so this is accepted but changes nothing */
503
+ emailId?: boolean | undefined;
502
504
  /** If true then include thread ID in the response (only if server supports either OBJECTID or X-GM-EXT-1 extensions) */
503
505
  threadId?: boolean | undefined;
504
506
  /** If true then include GMail labels in the response (only if server supports X-GM-EXT-1 extension) */
@@ -653,9 +655,11 @@ export interface DownloadOptions {
653
655
  maxBytes?: number | undefined;
654
656
  /** How large content parts to ask from the server. Defaults to 65536 */
655
657
  chunkSize?: number | undefined;
658
+ /** If true then requests the content with FETCH BINARY when the server supports it (BINARY or IMAP4rev2), so the server removes the transfer encoding */
659
+ binary?: boolean | undefined;
656
660
  }
657
661
  /** Options for downloadMany(): the download() options without `chunkSize`, as the parts come in one FETCH */
658
- export type DownloadManyOptions = Pick<DownloadOptions, 'uid' | 'maxBytes'>;
662
+ export type DownloadManyOptions = Pick<DownloadOptions, 'uid' | 'maxBytes' | 'binary'>;
659
663
  export interface DownloadManyPart {
660
664
  meta: DownloadMeta;
661
665
  content?: Buffer | null | undefined;
@@ -706,6 +710,10 @@ export interface MailboxOpenOptions {
706
710
  readOnly?: boolean | undefined;
707
711
  /** Optional description for mailbox lock tracking */
708
712
  description?: string | undefined;
713
+ /** QRESYNC (RFC 7162): HIGHESTMODSEQ from an earlier session. With `uidValidity` and QRESYNC enabled, changes since then are reported as `flags` and `expunge` events. getMailboxLock() only applies it when it selects the mailbox, not when the mailbox is already open */
714
+ changedSince?: bigint | number | string | undefined;
715
+ /** QRESYNC (RFC 7162): the UIDVALIDITY known from the previous session, required with `changedSince` */
716
+ uidValidity?: bigint | number | string | undefined;
709
717
  }
710
718
  export interface MailboxLockOptions extends MailboxOpenOptions {
711
719
  /**
@@ -63,15 +63,26 @@ async function authOauth(connection, username, accessToken) {
63
63
  // Empty breaker: XOAUTH2 expects an empty response to abort the SASL exchange
64
64
  breaker = '';
65
65
  }
66
+ let encoded = Buffer.from(oauthbearer).toString('base64');
67
+ // Without SASL-IR the payload may not ride on the command line (RFC 4959 section 3): it is
68
+ // sent as the answer to the first, empty continuation request instead
69
+ let payloadPending = !connection.capabilities.has('SASL-IR');
66
70
  let errorResponse = false;
67
71
  try {
68
- let response = await connection.exec('AUTHENTICATE', [
69
- { type: 'ATOM', value: command },
70
- { type: 'ATOM', value: Buffer.from(oauthbearer).toString('base64'), sensitive: true }
71
- ], {
72
+ let attributes = [{ type: 'ATOM', value: command }];
73
+ if (!payloadPending) {
74
+ attributes.push({ type: 'ATOM', value: encoded, sensitive: true });
75
+ }
76
+ let response = await connection.exec('AUTHENTICATE', attributes, {
72
77
  // Server sends a "+" continuation if auth fails, with a base64 JSON error payload.
73
78
  // We decode it for diagnostics, then send the breaker to terminate the exchange.
74
79
  onPlusTag: async (resp) => {
80
+ if (payloadPending) {
81
+ payloadPending = false;
82
+ connection.log.debug({ src: 'c', msg: '(* value hidden *)', comment: `Encoded response for AUTH=${command}`, cid: connection.id });
83
+ connection.write(encoded);
84
+ return;
85
+ }
75
86
  if (resp.attributes && resp.attributes[0] && resp.attributes[0].type === 'TEXT') {
76
87
  try {
77
88
  errorResponse = JSON.parse(Buffer.from(resp.attributes[0].value, 'base64').toString());
@@ -46,6 +46,12 @@ export default async function enable(connection, extensionList) {
46
46
  // extensions enabled by this command (RFC 5161), so a replace would drop
47
47
  // grants from an earlier ENABLE call
48
48
  connection.enabled = new Set([...connection.enabled, ...enabled]);
49
+ if (connection.enabled.has('QRESYNC')) {
50
+ // ENABLE QRESYNC is a CONDSTORE enabling command (RFC 7162 3.2.3), whether or not the
51
+ // server lists CONDSTORE in its ENABLED answer. Apache James advertises only QRESYNC
52
+ // and leaves a lone ENABLE CONDSTORE unanswered, which the RFC allows.
53
+ connection.enabled.add('CONDSTORE');
54
+ }
49
55
  response.next();
50
56
  return connection.enabled;
51
57
  }
@@ -62,13 +62,30 @@ export default async function fetch(connection, range, query, options) {
62
62
  };
63
63
  queryStructure.push(bodyPeek);
64
64
  };
65
- // IMAP fetch macros (ALL, FAST, FULL) and standard data items map directly to IMAP atoms
66
- ['all', 'fast', 'full', 'uid', 'flags', 'bodyStructure', 'envelope', 'internalDate'].forEach(key => {
67
- if (query[key]) {
65
+ // The ALL, FAST and FULL macros may only be sent on their own, never in a list with other
66
+ // items (RFC 3501 section 9), and UID is always in the list, so they are expanded into
67
+ // the items they stand for. FULL is expanded to BODYSTRUCTURE rather than the
68
+ // non-extensible BODY, as documented for the full option.
69
+ let full = !!query.full;
70
+ let all = !!query.all || full;
71
+ let fast = !!query.fast || all;
72
+ let items = {
73
+ flags: query.flags || fast,
74
+ internalDate: query.internalDate || fast,
75
+ size: query.size || fast,
76
+ envelope: query.envelope || all,
77
+ bodyStructure: query.bodyStructure || full
78
+ };
79
+ // standard data items map directly to IMAP atoms
80
+ if (query.uid) {
81
+ queryStructure.push({ type: 'ATOM', value: 'UID' });
82
+ }
83
+ ['flags', 'bodyStructure', 'envelope', 'internalDate'].forEach(key => {
84
+ if (items[key]) {
68
85
  queryStructure.push({ type: 'ATOM', value: key.toUpperCase() });
69
86
  }
70
87
  });
71
- if (query.size) {
88
+ if (items.size) {
72
89
  queryStructure.push({ type: 'ATOM', value: 'RFC822.SIZE' });
73
90
  }
74
91
  // Fetch full message source, optionally with byte range (start/maxLength)
@@ -191,7 +208,7 @@ export default async function fetch(connection, range, query, options) {
191
208
  if (consumerError) {
192
209
  return;
193
210
  }
194
- let formatted = await formatMessageResponse(untagged, mailbox, connection.idHashAlgorithm);
211
+ let formatted = await formatMessageResponse(untagged, mailbox, connection.idHashAlgorithm, connection);
195
212
  if (typeof options.onUntaggedFetch === 'function') {
196
213
  /* c8 ignore next */ // a UID FETCH row without its UID is a non-compliant server, so the seq fallback is not exercised
197
214
  let key = options.uid ? formatted.uid || formatted.seq : formatted.seq;
@@ -1,24 +1,13 @@
1
1
  import type { ImapFlow } from '../imap-flow.js';
2
2
  import type { MailboxObject, MailboxOpenOptions } from '../types.js';
3
- /**
4
- * Options for SELECT/EXAMINE: the public open options plus the QRESYNC resynchronization
5
- * parameters, which are only honored when the QRESYNC extension has been enabled
6
- */
7
- export interface SelectOptions extends MailboxOpenOptions {
8
- /** QRESYNC modseq value to fetch changes since */
9
- changedSince?: bigint | number | string | undefined;
10
- /** QRESYNC UID validity value */
11
- uidValidity?: bigint | number | string | undefined;
12
- }
3
+ /** SELECT/EXAMINE options, the QRESYNC parameters are part of the public mailboxOpen() options */
4
+ export type SelectOptions = MailboxOpenOptions;
13
5
  /**
14
6
  * Selects or examines a mailbox, making it the current mailbox for subsequent operations.
15
7
  *
16
8
  * @param connection - IMAP connection instance
17
9
  * @param path - Mailbox path to select
18
- * @param options - Select options
19
- * @param options.readOnly - If true, use EXAMINE instead of SELECT (read-only access)
20
- * @param options.changedSince - QRESYNC modseq value to fetch changes since
21
- * @param options.uidValidity - QRESYNC UID validity value
10
+ * @param options - Select options, see MailboxOpenOptions
22
11
  * @returns Mailbox info object with path, flags, exists, uidNext, uidValidity, highestModseq, etc., or undefined if preconditions not met
23
12
  * @throws If the SELECT/EXAMINE command fails
24
13
  */
@@ -48,10 +48,7 @@ const VALUED_RESPONSE_CODES = Object.assign(Object.create(null), {
48
48
  *
49
49
  * @param connection - IMAP connection instance
50
50
  * @param path - Mailbox path to select
51
- * @param options - Select options
52
- * @param options.readOnly - If true, use EXAMINE instead of SELECT (read-only access)
53
- * @param options.changedSince - QRESYNC modseq value to fetch changes since
54
- * @param options.uidValidity - QRESYNC UID validity value
51
+ * @param options - Select options, see MailboxOpenOptions
55
52
  * @returns Mailbox info object with path, flags, exists, uidNext, uidValidity, highestModseq, etc., or undefined if preconditions not met
56
53
  * @throws If the SELECT/EXAMINE command fails
57
54
  */
@@ -1,4 +1,4 @@
1
- import { formatFlag, canUseFlag, reportCommandError, getSelectedMailbox } from '../tools.js';
1
+ import { formatFlag, canUseFlag, encodePath, reportCommandError, getSelectedMailbox } from '../tools.js';
2
2
  /**
3
3
  * Updates flags or labels for messages in the selected mailbox.
4
4
  *
@@ -58,7 +58,10 @@ export default async function store(connection, range, flags, options) {
58
58
  const dropped = [];
59
59
  flags = (Array.isArray(flags) ? flags : [].concat(flags || []))
60
60
  .map(flag => {
61
- let formatted = formatFlag(flag);
61
+ // Gmail labels other than the \-prefixed system labels are mailbox names: astrings in
62
+ // the form mailbox names take on the session (modified UTF-7 unless UTF-8 is enabled),
63
+ // not atoms like IMAP keywords
64
+ let formatted = options.useLabels && flag && flag.charAt(0) !== '\\' ? encodePath(connection, flag) : formatFlag(flag);
62
65
  if (!formatted || (!canUseFlag(flagSource, formatted) && operationName !== 'remove')) {
63
66
  dropped.push(flag);
64
67
  return false;
@@ -80,13 +83,10 @@ export default async function store(connection, range, flags, options) {
80
83
  if (!flags.length && !clearAll) {
81
84
  return false;
82
85
  }
83
- let attributes = [
84
- { type: 'SEQUENCE', value: range },
85
- { type: 'ATOM', value: operation },
86
- flags.map(flag => ({ type: 'ATOM', value: flag }))
87
- ];
86
+ let attributes = [{ type: 'SEQUENCE', value: range }];
88
87
  // CONDSTORE (RFC 7162): UNCHANGEDSINCE modifier prevents updating messages whose
89
88
  // mod-sequence is higher than the specified value, avoiding overwriting concurrent changes.
89
+ // The store-modifiers list goes between the sequence set and the item name (section 3.1.3).
90
90
  if (options.unchangedSince && connection.enabled.has('CONDSTORE') && !mailbox.noModseq) {
91
91
  attributes.push([
92
92
  {
@@ -99,6 +99,7 @@ export default async function store(connection, range, flags, options) {
99
99
  }
100
100
  ]);
101
101
  }
102
+ attributes.push({ type: 'ATOM', value: operation }, flags.map(flag => ({ type: 'ATOM', value: flag })));
102
103
  let response;
103
104
  try {
104
105
  response = await connection.exec(options.uid ? 'UID STORE' : 'STORE', attributes);
@@ -12,6 +12,113 @@ import { LimitedPassthrough, normalizeByteLimit } from './limited-passthrough.js
12
12
  // away (a consumer destroying it closes it without a 'drain')
13
13
  const DRAIN_WAIT_EVENTS = ['drain', 'error', 'close'];
14
14
  import { getDecoder, isUnsafeKey } from './tools.js';
15
+ const isEmptySection = (value) => !value?.length;
16
+ /**
17
+ * The section to ask again when exactly one of a part's MIME headers and content came back
18
+ * empty (see refetchDroppedSections()), undefined when both or neither did
19
+ */
20
+ const droppedSection = (mime, content, mimeRequest, contentRequest) => {
21
+ if (isEmptySection(mime) === isEmptySection(content)) {
22
+ return undefined;
23
+ }
24
+ return isEmptySection(content) ? contentRequest : mimeRequest;
25
+ };
26
+ /** Start offset of every partial section among the requests, keyed by section */
27
+ const partialStarts = (requests) => {
28
+ let starts = new Map();
29
+ for (let request of requests) {
30
+ if (typeof request !== 'string') {
31
+ starts.set(request.key, Number(request.start) || 0);
32
+ }
33
+ }
34
+ return starts;
35
+ };
36
+ // How many times a request is repeated after answers that belong to another request
37
+ const MAX_FOREIGN_ANSWERS = 3;
38
+ const requestedUid = (range, options) => options.uid && /^\d+$/.test(String(range)) ? Number(range) : undefined;
39
+ const isForeignAnswer = (response, expected) => {
40
+ if (expected.uid && response.uid && response.uid !== expected.uid) {
41
+ return true;
42
+ }
43
+ for (let [key, start] of expected.origins) {
44
+ let origin = response.partialOrigins && response.partialOrigins.get(key);
45
+ // An answer without the origin is taken as is: some servers leave it out, and some
46
+ // ignore the partial specifier altogether
47
+ if (typeof origin === 'number' && origin !== start) {
48
+ return true;
49
+ }
50
+ }
51
+ return false;
52
+ };
53
+ /**
54
+ * fetchOne() that takes only an answer belonging to the request. Apache James now and then
55
+ * writes the head of a FETCH answer after its tagged OK, so the data of one request shows up
56
+ * within the answer to the next one. Taken at face value it would be the data of that next
57
+ * request, and a download would end without an error but with misplaced bytes. An answer for
58
+ * another UID, or with a partial section that starts at another offset than asked, is dropped
59
+ * and the request repeated.
60
+ */
61
+ async function fetchExpected(client, range, query, options, expected) {
62
+ for (let attempt = 1;; attempt++) {
63
+ let response = await client.fetchOne(range, query, options);
64
+ if (!response || !isForeignAnswer(response, expected)) {
65
+ return response;
66
+ }
67
+ client.log.warn({
68
+ msg: 'Server answered with data of another request, asking again',
69
+ uid: response.uid,
70
+ origins: response.partialOrigins && Object.fromEntries(response.partialOrigins),
71
+ attempt,
72
+ cid: client.id
73
+ });
74
+ if (attempt >= MAX_FOREIGN_ANSWERS) {
75
+ let err = new Error('Server kept answering with data of another request');
76
+ err.code = 'DownloadIncomplete';
77
+ err.cid = client.id;
78
+ throw err;
79
+ }
80
+ }
81
+ }
82
+ /**
83
+ * Apache James (and the servers built on it, Twake Mail among them) answers only the first
84
+ * section it is asked for each MIME part of one FETCH and returns the other one empty:
85
+ * BODY[2.MIME] with BODY[2] yields the headers and a zero-length body, the reverse order loses
86
+ * the headers (FetchGroup.addPartContent() keeps the first descriptor for a part path). Asks the
87
+ * sections that came back empty again, in a FETCH of their own, and merges the answer into
88
+ * `response`. Callers only list a section whose companion did arrive, so a compliant server
89
+ * pays the extra round trip only for a part that really is empty.
90
+ */
91
+ async function refetchDroppedSections(client, response, range, options, sections) {
92
+ if (!sections.length) {
93
+ return;
94
+ }
95
+ client.log.debug({
96
+ msg: 'Server answered a body section empty while its companion section was not, asking it again separately',
97
+ sections: sections.map(section => (typeof section === 'string' ? section : section.key)),
98
+ cid: client.id
99
+ });
100
+ // the UID pins the message even when the first command addressed it by sequence number
101
+ let uid = response.uid;
102
+ let retry = await fetchExpected(client, uid || range, { uid: true, bodyParts: sections }, uid ? { ...options, uid: true } : options, {
103
+ uid,
104
+ origins: partialStarts(sections)
105
+ });
106
+ if (!retry) {
107
+ return;
108
+ }
109
+ if (retry.headers) {
110
+ response.headers = retry.headers;
111
+ }
112
+ for (let [key, value] of retry.bodyParts || []) {
113
+ (response.bodyParts ??= new Map()).set(key, value);
114
+ if (retry.binaryParts && retry.binaryParts.has(key)) {
115
+ (response.binaryParts ??= new Set()).add(key);
116
+ }
117
+ else if (response.binaryParts) {
118
+ response.binaryParts.delete(key);
119
+ }
120
+ }
121
+ }
15
122
  /**
16
123
  * Implements ImapFlow.download(), see its documentation
17
124
  *
@@ -59,6 +166,7 @@ export async function downloadMessage(client, range, part, options) {
59
166
  let getNextPart = async (query) => {
60
167
  query = query || {};
61
168
  let mimeKey;
169
+ let contentRequest;
62
170
  if (!part) {
63
171
  query.source = {
64
172
  start: processed,
@@ -81,13 +189,18 @@ export async function downloadMessage(client, range, part, options) {
81
189
  query.bodyParts.push(mimeKey);
82
190
  }
83
191
  }
84
- query.bodyParts.push({
192
+ contentRequest = {
85
193
  key: part,
86
194
  start: processed,
87
195
  maxLength: chunkSize
88
- });
196
+ };
197
+ query.bodyParts.push(contentRequest);
89
198
  }
90
- let response = await client.fetchOne(range, query, downloadOptions);
199
+ let expected = {
200
+ uid: uid || requestedUid(range, downloadOptions),
201
+ origins: new Map([[part || '', processed]])
202
+ };
203
+ let response = await fetchExpected(client, range, query, downloadOptions, expected);
91
204
  if (!response) {
92
205
  return { response: false, chunk: false };
93
206
  }
@@ -97,6 +210,12 @@ export async function downloadMessage(client, range, part, options) {
97
210
  range = uid;
98
211
  downloadOptions.uid = true;
99
212
  }
213
+ if (mimeKey && contentRequest) {
214
+ let dropped = droppedSection(mimeKey === 'header' ? response.headers : response.bodyParts?.get(mimeKey), response.bodyParts?.get(part), mimeKey, contentRequest);
215
+ if (dropped) {
216
+ await refetchDroppedSections(client, response, range, downloadOptions, [dropped]);
217
+ }
218
+ }
100
219
  let chunk = !part ? response.source : response.bodyParts && response.bodyParts.get(part);
101
220
  if (!chunk) {
102
221
  return {};
@@ -451,16 +570,31 @@ export async function downloadMessageParts(client, range, parts, options) {
451
570
  // again on the answer for servers that ignore the partial specifier
452
571
  let maxBytes = normalizeByteLimit(downloadOptions.maxBytes);
453
572
  let query = { bodyParts: [] };
573
+ let contentRequests = new Map();
454
574
  for (let part of parts) {
455
575
  query.bodyParts.push(part + '.mime');
456
576
  // The partial specifier carries a 32-bit length (RFC 9051 "number"), so a cap beyond
457
577
  // that is applied on the answer alone
458
- query.bodyParts.push(maxBytes > 0xffffffff ? part : { key: part, start: 0, maxLength: maxBytes });
578
+ let contentRequest = maxBytes > 0xffffffff ? part : { key: part, start: 0, maxLength: maxBytes };
579
+ contentRequests.set(part, contentRequest);
580
+ query.bodyParts.push(contentRequest);
459
581
  }
460
- let response = await client.fetchOne(range, query, downloadOptions);
582
+ let response = await fetchExpected(client, range, query, downloadOptions, {
583
+ uid: requestedUid(range, downloadOptions),
584
+ origins: partialStarts(query.bodyParts)
585
+ });
461
586
  if (!response || !response.bodyParts) {
462
587
  return {};
463
588
  }
589
+ let dropped = [];
590
+ for (let [part, contentRequest] of contentRequests) {
591
+ let section = droppedSection(response.bodyParts.get(part + '.mime'), response.bodyParts.get(part), part + '.mime', contentRequest);
592
+ if (section) {
593
+ dropped.push(section);
594
+ }
595
+ }
596
+ // Sections of different parts do not collide, so every dropped one fits in one FETCH
597
+ await refetchDroppedSections(client, response, range, downloadOptions, dropped);
464
598
  let data = {};
465
599
  for (let [part, content] of response.bodyParts) {
466
600
  let keyParts = part.split('.mime');
@@ -122,8 +122,8 @@ export declare class ImapFlow extends EventEmitter {
122
122
  */
123
123
  usable: boolean;
124
124
  /**
125
- * Currently authenticated user or `false` if mailbox is not open
126
- * or `true` if connection was authenticated by PREAUTH
125
+ * `true` once the connection is authenticated (by LOGIN, AUTHENTICATE or a PREAUTH greeting),
126
+ * `false` before that. The user name is in `options.auth.user`
127
127
  */
128
128
  authenticated: string | boolean;
129
129
  /**
@@ -1459,9 +1459,8 @@ export class ImapFlow extends EventEmitter {
1459
1459
  // of the IP - accepting any "localhost" certificate for any IP-hosted
1460
1460
  // server, and rejecting legitimate IP-SAN certificates.
1461
1461
  host: this.host,
1462
- servername: this.servername,
1463
1462
  port: this.port
1464
- }, this.options.tls || {});
1463
+ }, this.tlsServername(), this.options.tls || {});
1465
1464
  this.clearSocketHandlers();
1466
1465
  let settled = false;
1467
1466
  // Single settlement path for the upgrade. Every terminal outcome - handshake
@@ -1851,12 +1850,18 @@ export class ImapFlow extends EventEmitter {
1851
1850
  uids = untagged.attributes[0].value;
1852
1851
  }
1853
1852
  let uidList = expandRange(uids);
1853
+ let earlier = tags.includes('EARLIER');
1854
+ // RFC 7162 section 3.2.10: unlike VANISHED (EARLIER), a plain VANISHED reports messages the
1855
+ // client knows about and decrements the message count like the same number of EXPUNGEs would
1856
+ if (!earlier) {
1857
+ mailbox.exists = Math.max(0, mailbox.exists - uidList.length);
1858
+ }
1854
1859
  for (let uid of uidList) {
1855
1860
  let payload = {
1856
1861
  path: mailbox.path,
1857
1862
  uid,
1858
1863
  vanished: true,
1859
- earlier: tags.includes('EARLIER')
1864
+ earlier
1860
1865
  };
1861
1866
  await this.notifyExpunge(payload);
1862
1867
  }
@@ -1868,7 +1873,7 @@ export class ImapFlow extends EventEmitter {
1868
1873
  // mailbox closed, ignore
1869
1874
  return;
1870
1875
  }
1871
- let message = await formatMessageResponse(untagged, mailbox, this.idHashAlgorithm);
1876
+ let message = await formatMessageResponse(untagged, mailbox, this.idHashAlgorithm, this);
1872
1877
  if (message.flags) {
1873
1878
  let updateEvent = {
1874
1879
  path: mailbox.path,
@@ -1897,6 +1902,12 @@ export class ImapFlow extends EventEmitter {
1897
1902
  }
1898
1903
  return true;
1899
1904
  }
1905
+ // servername for tls.connect(), left out for an IP literal host (this.servername is false then):
1906
+ // Node treats a false value like a missing one, but Bun throws a TypeError for it
1907
+ /** @internal */
1908
+ tlsServername() {
1909
+ return this.servername ? { servername: this.servername } : {};
1910
+ }
1900
1911
  // Normalizes a message range from various input formats into an IMAP-compatible
1901
1912
  // sequence string (e.g., "1:5,7,10:*"). Handles: numbers, "*", {all:true},
1902
1913
  // {uid:value}, search query objects (resolved via SEARCH), and arrays of numbers.
@@ -1939,6 +1950,11 @@ export class ImapFlow extends EventEmitter {
1939
1950
  if (!value) {
1940
1951
  return false;
1941
1952
  }
1953
+ // An empty mailbox has no message numbers: every sequence set, "1:*" included, would get a
1954
+ // BAD (RFC 9051 section 9, seq-number). UID sets may point past the end, so they are sent.
1955
+ if (!options.uid && this.mailbox && !this.mailbox.exists) {
1956
+ return false;
1957
+ }
1942
1958
  return value;
1943
1959
  }
1944
1960
  // The single definition of "the connection is not free". A held or queued mailbox lock, a
@@ -2008,9 +2024,8 @@ export class ImapFlow extends EventEmitter {
2008
2024
  let connector = this.secureConnection ? tls : net;
2009
2025
  let opts = Object.assign({
2010
2026
  host: this.host,
2011
- servername: this.servername,
2012
2027
  port: this.port
2013
- }, this.options.tls || {});
2028
+ }, this.tlsServername(), this.options.tls || {});
2014
2029
  this.untaggedHandlers.OK = (...args) => this.initialOK(...args);
2015
2030
  this.untaggedHandlers.BYE = (...args) => this.serverBye(...args);
2016
2031
  this.untaggedHandlers.PREAUTH = () => this.initialPREAUTH();
@@ -1,3 +1,3 @@
1
1
  export declare const name = "imapflow";
2
- export declare const version = "2.2.7";
2
+ export declare const version = "2.2.9";
3
3
  export declare const homepage = "https://imapflow.com/";
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/build.js from package.json. Do not edit by hand.
2
2
  export const name = "imapflow";
3
- export const version = "2.2.7";
3
+ export const version = "2.2.9";
4
4
  export const homepage = "https://imapflow.com/";
@@ -368,10 +368,13 @@ export const searchCompiler = (connection, query) => {
368
368
  fail('InvalidSearchQuery', `Search value for ${term.toLowerCase()} must be a string`);
369
369
  }
370
370
  let flag = formatFlag(params[term]);
371
- // formatFlag() refuses \Recent, which is not a keyword. Dropping the
372
- // criterion would widen the search, so the query is refused instead
371
+ // formatFlag() refuses \Recent, which is not a keyword, and values that are
372
+ // not atoms. Dropping the criterion would widen the search, so the query is
373
+ // refused instead
373
374
  if (flag === false) {
374
- fail('InvalidSearchQuery', `${params[term]} can not be searched as a keyword, use the "recent" search key instead`);
375
+ fail('InvalidSearchQuery', /^\\recent$/i.test(params[term])
376
+ ? `${params[term]} can not be searched as a keyword, use the "recent" search key instead`
377
+ : `${params[term]} is not a valid keyword`);
375
378
  }
376
379
  // Compiled even when the mailbox does not allow the keyword: the
377
380
  // correct answer is then the empty set, which dropping the