imapflow 2.2.5 → 2.2.7

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/CHANGELOG.md +17 -0
  2. package/dist/cjs/commands/append.js +10 -3
  3. package/dist/cjs/commands/authenticate.js +27 -18
  4. package/dist/cjs/commands/close.d.ts +12 -1
  5. package/dist/cjs/commands/close.js +4 -2
  6. package/dist/cjs/commands/copyuid-parser.js +16 -2
  7. package/dist/cjs/commands/delete.js +2 -1
  8. package/dist/cjs/commands/esearch-parser.js +8 -2
  9. package/dist/cjs/commands/fetch.js +35 -9
  10. package/dist/cjs/commands/id.js +8 -1
  11. package/dist/cjs/commands/idle.js +15 -5
  12. package/dist/cjs/commands/list.js +10 -1
  13. package/dist/cjs/commands/login.js +5 -1
  14. package/dist/cjs/commands/logout.js +7 -0
  15. package/dist/cjs/commands/namespace.js +7 -3
  16. package/dist/cjs/commands/quota.js +3 -1
  17. package/dist/cjs/commands/rename.js +2 -1
  18. package/dist/cjs/commands/select.js +5 -0
  19. package/dist/cjs/commands/status.js +6 -1
  20. package/dist/cjs/commands/store.d.ts +1 -1
  21. package/dist/cjs/commands/store.js +1 -2
  22. package/dist/cjs/download.js +82 -91
  23. package/dist/cjs/handler/imap-compiler.js +45 -29
  24. package/dist/cjs/handler/limits.d.ts +11 -0
  25. package/dist/cjs/handler/limits.js +16 -1
  26. package/dist/cjs/handler/parser-instance.d.ts +10 -0
  27. package/dist/cjs/handler/parser-instance.js +25 -10
  28. package/dist/cjs/handler/token-parser.js +162 -78
  29. package/dist/cjs/imap-flow.js +235 -89
  30. package/dist/cjs/package-info.d.ts +1 -1
  31. package/dist/cjs/package-info.js +1 -1
  32. package/dist/cjs/proxy-connection.js +7 -7
  33. package/dist/cjs/search-compiler.js +37 -16
  34. package/dist/cjs/special-use.js +10 -5
  35. package/dist/cjs/tools.d.ts +10 -1
  36. package/dist/cjs/tools.js +30 -3
  37. package/dist/cjs/types.d.ts +19 -4
  38. package/dist/esm/commands/append.js +11 -4
  39. package/dist/esm/commands/authenticate.js +28 -19
  40. package/dist/esm/commands/close.d.ts +12 -1
  41. package/dist/esm/commands/close.js +5 -3
  42. package/dist/esm/commands/copyuid-parser.js +16 -2
  43. package/dist/esm/commands/delete.js +2 -1
  44. package/dist/esm/commands/esearch-parser.js +8 -2
  45. package/dist/esm/commands/fetch.js +35 -9
  46. package/dist/esm/commands/id.js +9 -2
  47. package/dist/esm/commands/idle.js +16 -6
  48. package/dist/esm/commands/list.js +10 -1
  49. package/dist/esm/commands/login.js +6 -2
  50. package/dist/esm/commands/logout.js +7 -0
  51. package/dist/esm/commands/namespace.js +7 -3
  52. package/dist/esm/commands/quota.js +3 -1
  53. package/dist/esm/commands/rename.js +2 -1
  54. package/dist/esm/commands/select.js +5 -0
  55. package/dist/esm/commands/status.js +7 -2
  56. package/dist/esm/commands/store.d.ts +1 -1
  57. package/dist/esm/commands/store.js +1 -2
  58. package/dist/esm/download.js +82 -91
  59. package/dist/esm/handler/imap-compiler.js +45 -29
  60. package/dist/esm/handler/limits.d.ts +11 -0
  61. package/dist/esm/handler/limits.js +14 -0
  62. package/dist/esm/handler/parser-instance.d.ts +10 -0
  63. package/dist/esm/handler/parser-instance.js +25 -10
  64. package/dist/esm/handler/token-parser.js +163 -79
  65. package/dist/esm/imap-flow.js +235 -89
  66. package/dist/esm/package-info.d.ts +1 -1
  67. package/dist/esm/package-info.js +1 -1
  68. package/dist/esm/proxy-connection.js +7 -7
  69. package/dist/esm/search-compiler.js +37 -16
  70. package/dist/esm/special-use.js +10 -5
  71. package/dist/esm/tools.d.ts +10 -1
  72. package/dist/esm/tools.js +29 -3
  73. package/dist/esm/types.d.ts +19 -4
  74. package/package.json +3 -2
@@ -50,17 +50,12 @@ let toSequenceValue = (value) => [].concat(value).join(',');
50
50
  let toSearchValue = (value) => UNICODE_PATTERN.test(value) && !value.includes('\0') ? { type: 'LITERAL', value: Buffer.from(value) } : { type: 'ATOM', value };
51
51
  /**
52
52
  * Adds a search option with its value(s) to the attributes array.
53
- * Handles NOT operations and array values.
54
53
  *
55
54
  * @param attributes - Array to append the attribute to
56
55
  * @param term - The search term (e.g., 'FROM', 'SUBJECT')
57
- * @param value - The value for the search term (string, array, or falsy for NOT)
56
+ * @param value - The value for the search term (string or array)
58
57
  */
59
58
  let setOpt = (attributes, term, value) => {
60
- // Handle NOT operations for false or null values
61
- if (value === false || value === null) {
62
- attributes.push({ type: 'ATOM', value: 'NOT' });
63
- }
64
59
  attributes.push({ type: 'ATOM', value: term.toUpperCase() });
65
60
  // Handle array values (e.g. HEADER name/value pairs)
66
61
  if (Array.isArray(value)) {
@@ -250,6 +245,11 @@ export const searchCompiler = (connection, query) => {
250
245
  break;
251
246
  // Email ID support (OBJECTID or Gmail extension)
252
247
  case 'EMAILID':
248
+ // A falsy value means no criterion, as for the text fields. It used to
249
+ // compile into NOT EMAILID "false", which matched every message
250
+ if (!params[term]) {
251
+ break;
252
+ }
253
253
  if (connection.capabilities.has('OBJECTID')) {
254
254
  setOpt(attributes, 'EMAILID', params[term]);
255
255
  }
@@ -257,7 +257,7 @@ export const searchCompiler = (connection, query) => {
257
257
  // Fallback to Gmail message ID
258
258
  setOpt(attributes, 'X-GM-MSGID', params[term]);
259
259
  }
260
- else if (params[term]) {
260
+ else {
261
261
  // Dropping the criterion would widen the search to every message
262
262
  // matching the rest of the query, which a delete or move acts on
263
263
  fail('MissingServerExtension', 'Server does not support OBJECTID or X-GM-EXT-1 extension required for EMAILID');
@@ -265,6 +265,11 @@ export const searchCompiler = (connection, query) => {
265
265
  break;
266
266
  // Thread ID support (OBJECTID or Gmail extension)
267
267
  case 'THREADID':
268
+ // A falsy value means no criterion, as for the text fields. It used to
269
+ // compile into NOT THREADID "false", which matched every message
270
+ if (!params[term]) {
271
+ break;
272
+ }
268
273
  if (connection.capabilities.has('OBJECTID')) {
269
274
  setOpt(attributes, 'THREADID', params[term]);
270
275
  }
@@ -272,7 +277,7 @@ export const searchCompiler = (connection, query) => {
272
277
  // Fallback to Gmail thread ID
273
278
  setOpt(attributes, 'X-GM-THRID', params[term]);
274
279
  }
275
- else if (params[term]) {
280
+ else {
276
281
  // Dropping the criterion would widen the search to every message
277
282
  // matching the rest of the query, which a delete or move acts on
278
283
  fail('MissingServerExtension', 'Server does not support OBJECTID or X-GM-EXT-1 extension required for THREADID');
@@ -335,11 +340,11 @@ export const searchCompiler = (connection, query) => {
335
340
  if (!value) {
336
341
  break;
337
342
  }
338
- // Use WITHIN extension for better timezone handling if available
339
- if (connection.capabilities.has('WITHIN')) {
340
- // Convert to seconds ago from now
341
- const now = Date.now();
342
- const withinSeconds = Math.round(Math.max(0, now - value.getTime()) / 1000);
343
+ // Use WITHIN extension for better timezone handling if available.
344
+ // The interval is an nz-number (RFC 5032), so a date that is not in the
345
+ // past (OLDER 0 would be answered with BAD) takes the date path instead
346
+ const withinSeconds = Math.round((Date.now() - value.getTime()) / 1000);
347
+ if (connection.capabilities.has('WITHIN') && withinSeconds >= 1) {
343
348
  const withinKeyword = term.toUpperCase() === 'BEFORE' ? 'OLDER' : 'YOUNGER';
344
349
  setOpt(attributes, withinKeyword, withinSeconds.toString());
345
350
  break;
@@ -359,7 +364,15 @@ export const searchCompiler = (connection, query) => {
359
364
  case 'KEYWORD':
360
365
  case 'UNKEYWORD':
361
366
  {
367
+ if (typeof params[term] !== 'string') {
368
+ fail('InvalidSearchQuery', `Search value for ${term.toLowerCase()} must be a string`);
369
+ }
362
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
373
+ if (flag === false) {
374
+ fail('InvalidSearchQuery', `${params[term]} can not be searched as a keyword, use the "recent" search key instead`);
375
+ }
363
376
  // Compiled even when the mailbox does not allow the keyword: the
364
377
  // correct answer is then the empty set, which dropping the
365
378
  // criterion would turn into every message matching the rest
@@ -386,8 +399,12 @@ export const searchCompiler = (connection, query) => {
386
399
  }
387
400
  break;
388
401
  // NOT operator
402
+ // A falsy operand means no NOT clause (`not: cond && {...}`). Any other one goes
403
+ // through walkOperand(), which refuses a value that is not a query object or
404
+ // compiles to nothing: dropping it would turn the filter into a search that
405
+ // matches everything
389
406
  case 'NOT':
390
- if (params[term] && typeof params[term] === 'object') {
407
+ if (params[term]) {
391
408
  attributes.push({ type: 'ATOM', value: 'NOT' });
392
409
  walkOperand('NOT', params[term]);
393
410
  }
@@ -400,8 +417,8 @@ export const searchCompiler = (connection, query) => {
400
417
  }
401
418
  // Single element - just process it directly
402
419
  if (params[term].length === 1) {
403
- if (typeof params[term][0] === 'object' && params[term][0]) {
404
- walk(params[term][0]);
420
+ if (params[term][0]) {
421
+ walkOperand('OR', params[term][0]);
405
422
  }
406
423
  break;
407
424
  }
@@ -453,6 +470,10 @@ export const searchCompiler = (connection, query) => {
453
470
  walkOrTree(genOrTree(params[term]));
454
471
  }
455
472
  break;
473
+ default:
474
+ // An unknown key is refused: dropping it silently widened the search (a
475
+ // query of only unknown keys matched every message)
476
+ fail('InvalidSearchQuery', `Unknown search key "${term}"`);
456
477
  }
457
478
  });
458
479
  };
@@ -74,6 +74,7 @@ const TOKEN_SPLIT = /[\s\-_/.,()[\]]+/;
74
74
  // we fall back to matching folder names against these lists of known
75
75
  // translations in various languages (including non-Latin scripts).
76
76
  export const flags = ['\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash'];
77
+ const LOWERCASE_FLAGS = flags.map(flag => flag.toLowerCase());
77
78
  export const names = {
78
79
  '\\Sent': [
79
80
  'aika',
@@ -860,9 +861,10 @@ for (let flag of Object.keys(names)) {
860
861
  }
861
862
  }
862
863
  // Fold a folder name into the form the name tables are stored in.
863
- // Remove U+200E (LEFT-TO-RIGHT MARK) which some mail clients (especially for
864
- // RTL languages like Arabic, Hebrew) insert into folder names for display purposes.
865
- // These invisible marks would otherwise prevent exact string matching.
864
+ // Remove U+200E and U+200F (LEFT-TO-RIGHT and RIGHT-TO-LEFT MARK) which some mail clients
865
+ // (especially for RTL languages like Arabic, Hebrew) insert into folder names for display
866
+ // purposes. These invisible marks would otherwise prevent exact string matching. U+200B
867
+ // (ZERO WIDTH SPACE) is kept, Khmer names in the tables use it as their word separator.
866
868
  // Normalize with NFKC last: the same folder name can arrive in different but
867
869
  // equivalent forms depending on the client that created it, and matching is exact.
868
870
  // NFKC rather than NFC because the compatibility folding is what maps halfwidth
@@ -871,7 +873,7 @@ for (let flag of Object.keys(names)) {
871
873
  function normalizeName(name) {
872
874
  return name
873
875
  .toLowerCase()
874
- .replace(/\u200e/g, '')
876
+ .replace(/[\u200e\u200f]/g, '')
875
877
  .trim()
876
878
  .normalize('NFKC');
877
879
  }
@@ -880,7 +882,10 @@ export const specialUse = (hasSpecialUseExtension, folder) => {
880
882
  // Extension-provided flags take precedence over name-based detection because they
881
883
  // are authoritative - the server explicitly marks the folder's role.
882
884
  if (hasSpecialUseExtension) {
883
- const flag = flags.find(flag => folder.flags.has(flag));
885
+ // Flags are atoms and compare case-insensitively (RFC 9051 section 9)
886
+ const listed = new Set();
887
+ folder.flags.forEach(flag => listed.add(flag.toLowerCase()));
888
+ const flag = flags.find((flag, i) => listed.has(LOWERCASE_FLAGS[i]));
884
889
  if (flag) {
885
890
  return { flag, source: 'extension' };
886
891
  }
@@ -119,6 +119,14 @@ export declare function unrefTimer<T extends NodeJS.Timeout | null | undefined>(
119
119
  * @param err - The error to log
120
120
  */
121
121
  export declare function logConnectionError(connection: ImapFlow, msg: string, err: ImapFlowError | null | undefined): void;
122
+ /**
123
+ * Whether a command failed because the server answered it with a tagged NO or BAD, as opposed
124
+ * to a lost connection, a timeout or a local failure that says nothing about the server's answer.
125
+ *
126
+ * @param err - The error the command failed with
127
+ * @returns True for a tagged NO or BAD
128
+ */
129
+ export declare function isServerRefusal(err: ImapFlowError | null | undefined): boolean;
122
130
  /**
123
131
  * Checks whether IMAP4rev2 semantics are active for the connection: either the
124
132
  * client enabled IMAP4rev2 explicitly, or the server is rev2-only (advertises
@@ -407,7 +415,8 @@ export declare function isUnsafeKey(key: unknown): boolean;
407
415
  /**
408
416
  * Reads a parsed attribute list of atoms or strings (a flag list, a capability list) into
409
417
  * an array of strings. Any element can be a parsed NIL, and the list itself can be NIL,
410
- * so both levels are guarded here rather than at each call site.
418
+ * so both levels are guarded here rather than at each call site. A literal (a Gmail label
419
+ * the server could not send quoted) arrives as a Buffer and is decoded as UTF-8.
411
420
  *
412
421
  * @param list - Parsed attribute list from a response.
413
422
  * @returns The string values, in order, with unusable entries dropped.
package/dist/esm/tools.js CHANGED
@@ -211,6 +211,16 @@ export function logConnectionError(connection, msg, err) {
211
211
  let routine = !!err && CONNECTION_GONE_CODES.has(err.code) && !err.reason;
212
212
  connection.log[routine ? 'debug' : 'warn']({ msg, err, cid: connection.id });
213
213
  }
214
+ /**
215
+ * Whether a command failed because the server answered it with a tagged NO or BAD, as opposed
216
+ * to a lost connection, a timeout or a local failure that says nothing about the server's answer.
217
+ *
218
+ * @param err - The error the command failed with
219
+ * @returns True for a tagged NO or BAD
220
+ */
221
+ export function isServerRefusal(err) {
222
+ return !!err && (err.responseStatus === 'NO' || err.responseStatus === 'BAD');
223
+ }
214
224
  /**
215
225
  * Checks whether IMAP4rev2 semantics are active for the connection: either the
216
226
  * client enabled IMAP4rev2 explicitly, or the server is rev2-only (advertises
@@ -538,7 +548,12 @@ export function getFolderTree(folders) {
538
548
  }
539
549
  return node;
540
550
  };
541
- for (let folder of folders) {
551
+ // Parents are inserted before their children, as getTreeNode() can only descend into nodes
552
+ // that already exist. LIST gives no ordering guarantee, and the LIST command sorts special-use
553
+ // mailboxes first, which put a child such as "[Gmail]/Sent Mail" ahead of "[Gmail]" and left
554
+ // it at the root. The sort is stable, so siblings keep their listing order
555
+ let byDepth = [...folders].sort((a, b) => (a.parent ? a.parent.length : 0) - (b.parent ? b.parent.length : 0));
556
+ for (let folder of byDepth) {
542
557
  let parent = getTreeNode(folder.parent);
543
558
  // see if entry already exists
544
559
  let existing = parent.folders && parent.folders.find(existing => existing.name === folder.name);
@@ -1357,7 +1372,8 @@ export function isUnsafeKey(key) {
1357
1372
  /**
1358
1373
  * Reads a parsed attribute list of atoms or strings (a flag list, a capability list) into
1359
1374
  * an array of strings. Any element can be a parsed NIL, and the list itself can be NIL,
1360
- * so both levels are guarded here rather than at each call site.
1375
+ * so both levels are guarded here rather than at each call site. A literal (a Gmail label
1376
+ * the server could not send quoted) arrives as a Buffer and is decoded as UTF-8.
1361
1377
  *
1362
1378
  * @param list - Parsed attribute list from a response.
1363
1379
  * @returns The string values, in order, with unusable entries dropped.
@@ -1366,7 +1382,17 @@ export function getStringList(list) {
1366
1382
  if (!Array.isArray(list)) {
1367
1383
  return [];
1368
1384
  }
1369
- return list.map(entry => (entry && typeof entry.value === 'string' ? entry.value : false)).filter(entry => entry);
1385
+ let strings = [];
1386
+ for (let entry of list) {
1387
+ let value = entry && entry.value;
1388
+ if (Buffer.isBuffer(value)) {
1389
+ value = value.toString();
1390
+ }
1391
+ if (value && typeof value === 'string') {
1392
+ strings.push(value);
1393
+ }
1394
+ }
1395
+ return strings;
1370
1396
  }
1371
1397
  /**
1372
1398
  * Parses an untrusted decimal value from a server response into a BigInt.
@@ -155,7 +155,15 @@ export interface ImapFlowOptions {
155
155
  * 30 minutes. Set to 0 or false to disable.
156
156
  */
157
157
  maxLockHoldTime?: number | false | undefined;
158
- /** If true, uses TLS. If false, uses cleartext. If not set, upgrades to TLS if available */
158
+ /**
159
+ * STARTTLS policy for a connection that was not opened with `secure: true`. If true, the
160
+ * connection must upgrade to TLS, and connecting fails when the server does not offer
161
+ * STARTTLS. If false, the connection stays in cleartext. If not set, the connection upgrades
162
+ * when the server offers STARTTLS and otherwise continues in cleartext with a warning logged:
163
+ * the capability list that decides this was itself received in cleartext, so an attacker on
164
+ * the path can strip it. Set `doSTARTTLS: true` whenever the credentials must never cross the
165
+ * wire unencrypted.
166
+ */
159
167
  doSTARTTLS?: boolean | undefined;
160
168
  /** Custom instance ID string for logs */
161
169
  id?: string | undefined;
@@ -646,8 +654,8 @@ export interface DownloadOptions {
646
654
  /** How large content parts to ask from the server. Defaults to 65536 */
647
655
  chunkSize?: number | undefined;
648
656
  }
649
- /** Options for downloadMany(), the same shape as the download() options */
650
- export type DownloadManyOptions = DownloadOptions;
657
+ /** Options for downloadMany(): the download() options without `chunkSize`, as the parts come in one FETCH */
658
+ export type DownloadManyOptions = Pick<DownloadOptions, 'uid' | 'maxBytes'>;
651
659
  export interface DownloadManyPart {
652
660
  meta: DownloadMeta;
653
661
  content?: Buffer | null | undefined;
@@ -769,6 +777,13 @@ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
769
777
  */
770
778
  export type InternalLogger = {
771
779
  [level in LogLevel]: (obj: any) => void;
780
+ } & {
781
+ /**
782
+ * Whether an entry logged at this level reaches anyone (the logger, or a 'log' event
783
+ * listener). Set on the logger the connection builds; a logger assigned from outside may
784
+ * lack it, and every level then counts as enabled
785
+ */
786
+ isLevelEnabled?: ((level: LogLevel) => boolean) | undefined;
772
787
  };
773
788
  export interface LogEvent {
774
789
  /** Log level */
@@ -802,7 +817,7 @@ export interface ESearchResult {
802
817
  partial?: {
803
818
  /** The requested range, e.g. "1:100" */
804
819
  range: string;
805
- /** Matching UIDs in that range as compact sequence-set */
820
+ /** Matching UIDs in that range as compact sequence-set, an empty string when the range lies past the end of the results */
806
821
  messages: string;
807
822
  } | undefined;
808
823
  /** Highest mod-sequence of the matching messages (RFC 7162, present when the search used a modseq criterion on a CONDSTORE session) */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imapflow",
3
- "version": "2.2.5",
3
+ "version": "2.2.7",
4
4
  "description": "IMAP Client for Node",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/imap-flow.js",
@@ -45,6 +45,7 @@
45
45
  "pretest:workers": "npm run build",
46
46
  "test:workers": "node --import tsx --test test/cloudflare/cloudflare-test.ts",
47
47
  "test:rev2": "bash test/integration/run-rev2-tests.sh",
48
+ "test:mutation": "node scripts/mutation-test.js",
48
49
  "format": "prettier --write \"**/*.{js,cjs,ts,json,md,yml,yaml}\"",
49
50
  "format:check": "prettier --check \"**/*.{js,cjs,ts,json,md,yml,yaml}\"",
50
51
  "lint": "npm run typecheck && eslint .",
@@ -77,7 +78,7 @@
77
78
  "tsx": "4.23.15",
78
79
  "types-node-legacy": "npm:@types/node@20.0.0",
79
80
  "typescript": "6.0.3",
80
- "typescript-eslint": "8.71.0",
81
+ "typescript-eslint": "8.71.1",
81
82
  "wrangler": "4.147.0"
82
83
  },
83
84
  "dependencies": {