@remit/mailbox-service 0.0.112 → 0.0.113
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/account-credentials.d.ts +83 -0
- package/dist/account-credentials.js +104 -0
- package/dist/attribute-mapper.d.ts +36 -0
- package/dist/attribute-mapper.js +119 -0
- package/dist/body-parse.d.ts +28 -0
- package/{src/body-parse.ts → dist/body-parse.js} +18 -26
- package/dist/body-part-mapper.d.ts +92 -0
- package/dist/body-part-mapper.js +301 -0
- package/dist/body-sync-queue.d.ts +59 -0
- package/dist/body-sync-queue.js +56 -0
- package/dist/body-sync-terminal.d.ts +58 -0
- package/dist/body-sync-terminal.js +95 -0
- package/dist/body-sync.d.ts +351 -0
- package/dist/body-sync.js +1204 -0
- package/dist/calendar-parts.d.ts +23 -0
- package/dist/calendar-parts.js +18 -0
- package/dist/classification-backfill.d.ts +91 -0
- package/dist/classification-backfill.js +180 -0
- package/dist/classify-message.d.ts +31 -0
- package/dist/classify-message.js +89 -0
- package/dist/connection-factory.d.ts +54 -0
- package/dist/connection-factory.js +54 -0
- package/dist/connection-test.d.ts +41 -0
- package/dist/connection-test.js +152 -0
- package/dist/external-move.d.ts +94 -0
- package/dist/external-move.js +173 -0
- package/dist/filter-operations.d.ts +42 -0
- package/dist/filter-operations.js +211 -0
- package/dist/filters/filter-config.d.ts +14 -0
- package/dist/filters/filter-config.js +10 -0
- package/{src/filters/list-id.ts → dist/filters/list-id.d.ts} +2 -16
- package/dist/filters/list-id.js +26 -0
- package/dist/filters/match.d.ts +69 -0
- package/dist/filters/match.js +165 -0
- package/dist/filters/pipeline.d.ts +64 -0
- package/dist/filters/pipeline.js +100 -0
- package/{src/flag-push-terminal.ts → dist/flag-push-terminal.d.ts} +16 -72
- package/dist/flag-push-terminal.js +63 -0
- package/dist/flag-push.d.ts +69 -0
- package/dist/flag-push.js +111 -0
- package/dist/flag-queue.d.ts +175 -0
- package/dist/flag-queue.js +291 -0
- package/dist/folder-operations.d.ts +39 -0
- package/dist/folder-operations.js +112 -0
- package/dist/folder-placement.d.ts +13 -0
- package/dist/folder-placement.js +23 -0
- package/dist/heuristics/authenticationResults.d.ts +10 -0
- package/dist/heuristics/authenticationResults.js +187 -0
- package/dist/heuristics/classifyByHeaders.d.ts +82 -0
- package/dist/heuristics/classifyByHeaders.js +365 -0
- package/dist/heuristics/classifyPlacement.d.ts +67 -0
- package/dist/heuristics/classifyPlacement.js +153 -0
- package/dist/heuristics/machineSenders.d.ts +21 -0
- package/{src/heuristics/machineSenders.ts → dist/heuristics/machineSenders.js} +34 -40
- package/dist/heuristics/senderMismatch.d.ts +81 -0
- package/dist/heuristics/senderMismatch.js +192 -0
- package/dist/heuristics/socialDomains.d.ts +14 -0
- package/{src/heuristics/socialDomains.ts → dist/heuristics/socialDomains.js} +9 -9
- package/dist/heuristics/transactionalDomains.d.ts +18 -0
- package/{src/heuristics/transactionalDomains.ts → dist/heuristics/transactionalDomains.js} +8 -8
- package/dist/imapflow-connection.d.ts +377 -0
- package/dist/imapflow-connection.js +1147 -0
- package/dist/index.d.ts +63 -0
- package/dist/index.js +65 -0
- package/dist/list-id-backfill.d.ts +83 -0
- package/dist/list-id-backfill.js +132 -0
- package/dist/mailbox-cursor-rebuild.d.ts +74 -0
- package/dist/mailbox-cursor-rebuild.js +71 -0
- package/{src/mailbox-cursor.ts → dist/mailbox-cursor.d.ts} +20 -98
- package/dist/mailbox-cursor.js +102 -0
- package/dist/mailbox-intent.d.ts +41 -0
- package/{src/mailbox-intent.ts → dist/mailbox-intent.js} +38 -64
- package/dist/mailbox-management.d.ts +240 -0
- package/dist/mailbox-management.js +576 -0
- package/dist/mailbox-presence.d.ts +52 -0
- package/{src/mailbox-presence.ts → dist/mailbox-presence.js} +19 -30
- package/dist/mailbox-queue.d.ts +126 -0
- package/dist/mailbox-queue.js +214 -0
- package/dist/mailbox-sync.d.ts +93 -0
- package/dist/mailbox-sync.js +490 -0
- package/dist/mailbox-upstream.d.ts +38 -0
- package/{src/mailbox-upstream.ts → dist/mailbox-upstream.js} +37 -47
- package/dist/message-category.d.ts +51 -0
- package/{src/message-category.ts → dist/message-category.js} +28 -71
- package/dist/message-move.d.ts +285 -0
- package/dist/message-move.js +858 -0
- package/dist/message-parser.d.ts +14 -0
- package/dist/message-parser.js +17 -0
- package/{src/message-presence.ts → dist/message-presence.d.ts} +1 -13
- package/dist/message-presence.js +29 -0
- package/dist/message-read.d.ts +51 -0
- package/dist/message-read.js +31 -0
- package/dist/message-sync.d.ts +345 -0
- package/dist/message-sync.js +1358 -0
- package/dist/mime-walker.d.ts +102 -0
- package/dist/mime-walker.js +198 -0
- package/dist/organize-job.d.ts +20 -0
- package/dist/organize-job.js +37 -0
- package/dist/outbox-attachment-content.d.ts +37 -0
- package/dist/outbox-attachment-content.js +50 -0
- package/dist/outbox-attachment-filename.d.ts +19 -0
- package/dist/outbox-attachment-filename.js +64 -0
- package/dist/outbox-attachment.d.ts +148 -0
- package/dist/outbox-attachment.js +273 -0
- package/dist/outbox-queue.d.ts +73 -0
- package/dist/outbox-queue.js +284 -0
- package/{src/outbox-status.ts → dist/outbox-status.d.ts} +1 -6
- package/dist/outbox-status.js +18 -0
- package/dist/ownership.d.ts +24 -0
- package/dist/ownership.js +83 -0
- package/dist/placement-move-terminal.d.ts +67 -0
- package/dist/placement-move-terminal.js +88 -0
- package/dist/placement-move.d.ts +83 -0
- package/dist/placement-move.js +216 -0
- package/{src/placement-settled.ts → dist/placement-settled.d.ts} +13 -68
- package/dist/placement-settled.js +75 -0
- package/dist/quarantine.d.ts +95 -0
- package/dist/quarantine.js +131 -0
- package/dist/refusal.d.ts +31 -0
- package/dist/refusal.js +3 -0
- package/{src/restore-source-placement.ts → dist/restore-source-placement.d.ts} +29 -97
- package/dist/restore-source-placement.js +79 -0
- package/dist/search-text-backfill.d.ts +15 -0
- package/dist/search-text-backfill.js +33 -0
- package/dist/snippet.d.ts +61 -0
- package/dist/snippet.js +129 -0
- package/dist/spam-report.d.ts +86 -0
- package/dist/spam-report.js +241 -0
- package/dist/sync-warning.d.ts +21 -0
- package/dist/sync-warning.js +26 -0
- package/dist/sync-watermarks.d.ts +138 -0
- package/dist/sync-watermarks.js +205 -0
- package/dist/test-helpers/fake-imap.d.ts +151 -0
- package/dist/test-helpers/fake-imap.js +508 -0
- package/dist/test-helpers/folder-roles.d.ts +34 -0
- package/dist/test-helpers/folder-roles.js +47 -0
- package/dist/test-helpers/mime-tree-generator.d.ts +82 -0
- package/dist/test-helpers/mime-tree-generator.js +329 -0
- package/dist/test-helpers/test-store.d.ts +69 -0
- package/dist/test-helpers/test-store.js +193 -0
- package/dist/text/normalizer.d.ts +20 -0
- package/dist/text/normalizer.js +102 -0
- package/dist/thread-message-rows.d.ts +69 -0
- package/dist/thread-message-rows.js +40 -0
- package/dist/thread-root.d.ts +7 -0
- package/dist/thread-root.js +25 -0
- package/dist/types.d.ts +343 -0
- package/dist/types.js +19 -0
- package/package.json +86 -88
- package/src/account-credentials.ts +0 -210
- package/src/attribute-mapper.test.ts +0 -104
- package/src/attribute-mapper.ts +0 -148
- package/src/body-parse.test.ts +0 -55
- package/src/body-part-mapper.property.test.ts +0 -354
- package/src/body-part-mapper.ts +0 -410
- package/src/body-sync-queue.test.ts +0 -64
- package/src/body-sync-queue.ts +0 -131
- package/src/body-sync-terminal.test.ts +0 -148
- package/src/body-sync-terminal.ts +0 -174
- package/src/body-sync.test.ts +0 -925
- package/src/body-sync.ts +0 -1891
- package/src/calendar-parts.ts +0 -41
- package/src/classification-backfill.test.ts +0 -285
- package/src/classification-backfill.ts +0 -363
- package/src/classify-message.test.ts +0 -142
- package/src/classify-message.ts +0 -116
- package/src/connection-factory.ts +0 -102
- package/src/connection-test.ts +0 -208
- package/src/credentials.test.ts +0 -181
- package/src/external-move.test.ts +0 -262
- package/src/external-move.ts +0 -285
- package/src/filter-operations.test.ts +0 -319
- package/src/filter-operations.ts +0 -377
- package/src/filter-update.test.ts +0 -313
- package/src/filters/filter-config.test.ts +0 -87
- package/src/filters/filter-config.ts +0 -34
- package/src/filters/list-id.test.ts +0 -50
- package/src/filters/match.test.ts +0 -392
- package/src/filters/match.ts +0 -225
- package/src/filters/pipeline.test.ts +0 -199
- package/src/filters/pipeline.ts +0 -170
- package/src/flag-push.test.ts +0 -112
- package/src/flag-push.ts +0 -198
- package/src/flag-queue.test.ts +0 -197
- package/src/flag-queue.ts +0 -509
- package/src/folder-operations.test.ts +0 -273
- package/src/folder-operations.ts +0 -217
- package/src/folder-placement.ts +0 -56
- package/src/forwarded-message.test.ts +0 -122
- package/src/heuristics/authenticationResults.test.ts +0 -189
- package/src/heuristics/authenticationResults.ts +0 -212
- package/src/heuristics/classifyByHeaders.test.ts +0 -889
- package/src/heuristics/classifyByHeaders.ts +0 -467
- package/src/heuristics/classifyPlacement.test.ts +0 -366
- package/src/heuristics/classifyPlacement.ts +0 -211
- package/src/heuristics/classifyRealMail.test.ts +0 -242
- package/src/heuristics/machineSenders.test.ts +0 -101
- package/src/heuristics/senderMismatch.test.ts +0 -346
- package/src/heuristics/senderMismatch.ts +0 -259
- package/src/imapflow-connect-retry.test.ts +0 -97
- package/src/imapflow-connection.test.ts +0 -503
- package/src/imapflow-connection.ts +0 -1476
- package/src/index.ts +0 -397
- package/src/list-id-backfill.test.ts +0 -207
- package/src/list-id-backfill.ts +0 -274
- package/src/mailbox-cursor-rebuild.test.ts +0 -171
- package/src/mailbox-cursor-rebuild.ts +0 -146
- package/src/mailbox-cursor.test.ts +0 -141
- package/src/mailbox-delete-intent.test.ts +0 -119
- package/src/mailbox-management.test.ts +0 -243
- package/src/mailbox-management.ts +0 -838
- package/src/mailbox-presence.test.ts +0 -74
- package/src/mailbox-queue.ts +0 -397
- package/src/mailbox-rename-intent.test.ts +0 -220
- package/src/mailbox-rename-subtree.test.ts +0 -287
- package/src/mailbox-sync.test.ts +0 -286
- package/src/mailbox-sync.ts +0 -724
- package/src/message-move.test.ts +0 -726
- package/src/message-move.ts +0 -1518
- package/src/message-parser.ts +0 -26
- package/src/message-presence.test.ts +0 -50
- package/src/message-read.ts +0 -87
- package/src/message-save-retry.test.ts +0 -90
- package/src/message-sync-flags.test.ts +0 -167
- package/src/message-sync.test.ts +0 -762
- package/src/message-sync.ts +0 -2133
- package/src/mime-walker.test.ts +0 -311
- package/src/mime-walker.ts +0 -306
- package/src/organize-job.ts +0 -93
- package/src/outbox-attachment-content.test.ts +0 -153
- package/src/outbox-attachment-content.ts +0 -104
- package/src/outbox-attachment-filename.test.ts +0 -132
- package/src/outbox-attachment-filename.ts +0 -76
- package/src/outbox-attachment.test.ts +0 -626
- package/src/outbox-attachment.ts +0 -536
- package/src/outbox-failed-recovery.test.ts +0 -299
- package/src/outbox-queue.test.ts +0 -315
- package/src/outbox-queue.ts +0 -525
- package/src/ownership.ts +0 -140
- package/src/placement-move-terminal.ts +0 -145
- package/src/placement-move.ts +0 -363
- package/src/placement-settled.test.ts +0 -147
- package/src/placement.test.ts +0 -404
- package/src/quarantine.test.ts +0 -133
- package/src/quarantine.ts +0 -229
- package/src/refusal.ts +0 -29
- package/src/snippet.test.ts +0 -213
- package/src/snippet.ts +0 -152
- package/src/spam-report.test.ts +0 -329
- package/src/spam-report.ts +0 -357
- package/src/sync-warning.test.ts +0 -213
- package/src/sync-warning.ts +0 -56
- package/src/sync-watermarks.test.ts +0 -409
- package/src/sync-watermarks.ts +0 -319
- package/src/system-flag-wire-format.test.ts +0 -77
- package/src/test-helpers/fake-imap.ts +0 -690
- package/src/test-helpers/folder-roles.ts +0 -66
- package/src/test-helpers/mime-tree-generator.ts +0 -461
- package/src/test-helpers/test-queue.ts +0 -56
- package/src/test-helpers/test-store.ts +0 -299
- package/src/text/normalizer.test.ts +0 -223
- package/src/text/normalizer.ts +0 -140
- package/src/thread-message-rows.ts +0 -77
- package/src/thread-root.test.ts +0 -29
- package/src/thread-root.ts +0 -51
- package/src/types/mailparser-augment.d.ts +0 -23
- package/src/types/natural-porter-stemmer.d.ts +0 -50
- package/src/types/stopword.d.ts +0 -69
- package/src/types.ts +0 -371
- package/tsconfig.json +0 -8
|
@@ -0,0 +1,1147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ImapFlow-based IMAP connection
|
|
3
|
+
*
|
|
4
|
+
* Modern async/await replacement for the node-imap based ImapConnection.
|
|
5
|
+
* Provides the same interface but uses ImapFlow under the hood.
|
|
6
|
+
*/
|
|
7
|
+
import { Readable } from "node:stream";
|
|
8
|
+
import { ImapFlow } from "imapflow";
|
|
9
|
+
import { simpleParser } from "mailparser";
|
|
10
|
+
import { MailConnectionError } from "./types.js";
|
|
11
|
+
/**
|
|
12
|
+
* Convert an envelope date into an ISO string, tolerating non-Date values.
|
|
13
|
+
*
|
|
14
|
+
* imapflow types `envelope.date` as a Date, but a malformed `Date:` header can
|
|
15
|
+
* leave it as a string or other value at runtime. Returns "" for absent or
|
|
16
|
+
* invalid dates so one bad header never poisons the whole fetch batch.
|
|
17
|
+
*/
|
|
18
|
+
export const toIsoDateString = (value) => {
|
|
19
|
+
if (value instanceof Date) {
|
|
20
|
+
return Number.isNaN(value.getTime()) ? "" : value.toISOString();
|
|
21
|
+
}
|
|
22
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
23
|
+
const date = new Date(value);
|
|
24
|
+
return Number.isNaN(date.getTime()) ? "" : date.toISOString();
|
|
25
|
+
}
|
|
26
|
+
return "";
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Coerce an IMAP INTERNALDATE into a valid `Date`, tolerating malformed input.
|
|
30
|
+
*
|
|
31
|
+
* INTERNALDATE is the server's receive time and is almost always a clean Date.
|
|
32
|
+
* But a broken server (or an unexpected imapflow runtime value) can yield a
|
|
33
|
+
* string that `new Date` cannot parse, or a wholly unexpected type. Either way
|
|
34
|
+
* `getTime()` would be `NaN`, which is the message's date-of-last-resort — it
|
|
35
|
+
* is the fallback `parseHeaderDate` uses and is stored as the message's
|
|
36
|
+
* `internalDate` — so a `NaN` here silently corrupts every downstream date and
|
|
37
|
+
* gets rejected by ElectroDB, permanently failing the message.
|
|
38
|
+
*
|
|
39
|
+
* When the value cannot produce a valid Date we fall back to `now` so the
|
|
40
|
+
* message still syncs with an approximate receive time rather than being
|
|
41
|
+
* dropped. Returns `null` only for a genuinely absent value, which the caller
|
|
42
|
+
* skips (a transient imapflow artifact, see #408 — not bad data).
|
|
43
|
+
*/
|
|
44
|
+
export const toInternalDate = (value) => {
|
|
45
|
+
if (value == null)
|
|
46
|
+
return null;
|
|
47
|
+
if (value instanceof Date) {
|
|
48
|
+
return Number.isNaN(value.getTime()) ? new Date() : value;
|
|
49
|
+
}
|
|
50
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
51
|
+
const date = new Date(value);
|
|
52
|
+
return Number.isNaN(date.getTime()) ? new Date() : date;
|
|
53
|
+
}
|
|
54
|
+
return new Date();
|
|
55
|
+
};
|
|
56
|
+
const FLAG_CRITERIA = {
|
|
57
|
+
ALL: {},
|
|
58
|
+
SEEN: { seen: true },
|
|
59
|
+
UNSEEN: { seen: false },
|
|
60
|
+
FLAGGED: { flagged: true },
|
|
61
|
+
UNFLAGGED: { flagged: false },
|
|
62
|
+
DELETED: { deleted: true },
|
|
63
|
+
UNDELETED: { deleted: false },
|
|
64
|
+
ANSWERED: { answered: true },
|
|
65
|
+
UNANSWERED: { answered: false },
|
|
66
|
+
DRAFT: { draft: true },
|
|
67
|
+
UNDRAFT: { draft: false },
|
|
68
|
+
};
|
|
69
|
+
const VALUE_CRITERIA = {
|
|
70
|
+
UID: "uid",
|
|
71
|
+
FROM: "from",
|
|
72
|
+
TO: "to",
|
|
73
|
+
SUBJECT: "subject",
|
|
74
|
+
SINCE: "since",
|
|
75
|
+
BEFORE: "before",
|
|
76
|
+
};
|
|
77
|
+
const unsupported = (criterion) => new Error(`Unsupported IMAP search criterion ${JSON.stringify(criterion)} — dropping it would widen the query to SEARCH ALL`);
|
|
78
|
+
const applyValueCriterion = (result, header, criterion) => {
|
|
79
|
+
const [key, ...values] = criterion;
|
|
80
|
+
if (typeof key !== "string")
|
|
81
|
+
throw unsupported(criterion);
|
|
82
|
+
if (key.toUpperCase() === "HEADER") {
|
|
83
|
+
const [name, value] = values;
|
|
84
|
+
if (values.length !== 2 || typeof name !== "string") {
|
|
85
|
+
throw unsupported(criterion);
|
|
86
|
+
}
|
|
87
|
+
if (typeof value !== "string" && value !== true) {
|
|
88
|
+
throw unsupported(criterion);
|
|
89
|
+
}
|
|
90
|
+
header.set(name.toLowerCase(), value === true ? "" : value);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const field = VALUE_CRITERIA[key.toUpperCase()];
|
|
94
|
+
if (field === undefined || values.length !== 1)
|
|
95
|
+
throw unsupported(criterion);
|
|
96
|
+
result[field] = values[0];
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Compile node-imap style search criteria into an ImapFlow search object.
|
|
100
|
+
*
|
|
101
|
+
* A criterion this does not understand throws, and so does an empty criteria
|
|
102
|
+
* list. imapflow reads an empty object as `SEARCH ALL`
|
|
103
|
+
* (`imapflow/lib/commands/search.js`), so quietly skipping one turns a narrow
|
|
104
|
+
* probe into "every message in the mailbox" — the reconcile and move paths then
|
|
105
|
+
* act on a stranger's UID (#912). Header names accumulate in a Map so that a
|
|
106
|
+
* name like `__proto__` lands as a query term rather than hitting the
|
|
107
|
+
* prototype setter and vanishing.
|
|
108
|
+
*
|
|
109
|
+
* Values travel as structured tokens, never interpolated into a criterion
|
|
110
|
+
* string, so a quote or a CRLF in a header value cannot alter the query.
|
|
111
|
+
*/
|
|
112
|
+
export const convertSearchCriteria = (criteria) => {
|
|
113
|
+
if (criteria.length === 0) {
|
|
114
|
+
throw new Error("Empty IMAP search criteria list — it would compile to SEARCH ALL");
|
|
115
|
+
}
|
|
116
|
+
const result = {};
|
|
117
|
+
const header = new Map();
|
|
118
|
+
for (const criterion of criteria) {
|
|
119
|
+
if (typeof criterion === "string") {
|
|
120
|
+
const flags = FLAG_CRITERIA[criterion.toUpperCase()];
|
|
121
|
+
if (flags === undefined)
|
|
122
|
+
throw unsupported(criterion);
|
|
123
|
+
Object.assign(result, flags);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (Array.isArray(criterion)) {
|
|
127
|
+
applyValueCriterion(result, header, criterion);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
throw unsupported(criterion);
|
|
131
|
+
}
|
|
132
|
+
if (header.size > 0)
|
|
133
|
+
result.header = Object.fromEntries(header);
|
|
134
|
+
return result;
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* ImapFlow-based IMAP connection
|
|
138
|
+
*
|
|
139
|
+
* Drop-in replacement for ImapConnection using the ImapFlow library.
|
|
140
|
+
* Benefits:
|
|
141
|
+
* - Native async/await API (no callback wrapping)
|
|
142
|
+
* - Built-in envelope parsing that works with mokapi
|
|
143
|
+
* - Proper IDLE support with events
|
|
144
|
+
* - Built-in TypeScript types
|
|
145
|
+
* - Active maintenance
|
|
146
|
+
*/
|
|
147
|
+
export class ImapFlowConnection {
|
|
148
|
+
client = null;
|
|
149
|
+
_state = "disconnected";
|
|
150
|
+
config;
|
|
151
|
+
currentMailbox = null;
|
|
152
|
+
constructor(config) {
|
|
153
|
+
this.config = config;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Current connection state
|
|
157
|
+
*/
|
|
158
|
+
get state() {
|
|
159
|
+
return this._state;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Whether the connection is established and authenticated
|
|
163
|
+
*/
|
|
164
|
+
get isConnected() {
|
|
165
|
+
return this._state === "authenticated";
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Connect to the IMAP server with retry logic.
|
|
169
|
+
*
|
|
170
|
+
* Retries up to 3 times with exponential backoff (1s, 2s, 4s) on connection errors.
|
|
171
|
+
* Authentication errors are not retried.
|
|
172
|
+
*/
|
|
173
|
+
connect = async () => {
|
|
174
|
+
if (this.client) {
|
|
175
|
+
throw new Error("Already connected");
|
|
176
|
+
}
|
|
177
|
+
const maxRetries = 3;
|
|
178
|
+
const baseDelayMs = 1000;
|
|
179
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
180
|
+
try {
|
|
181
|
+
await this.attemptConnect();
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
const classified = classifyImapError(error, `${this.config.host}:${this.config.port}`);
|
|
186
|
+
// Auth errors won't fix themselves on retry — throw immediately.
|
|
187
|
+
if (classified?.kind === "auth") {
|
|
188
|
+
throw classified;
|
|
189
|
+
}
|
|
190
|
+
// Final attempt exhausted: throw the classified error if we have
|
|
191
|
+
// one (network failures), otherwise let the raw error bubble.
|
|
192
|
+
if (attempt === maxRetries) {
|
|
193
|
+
throw classified ?? error;
|
|
194
|
+
}
|
|
195
|
+
// Network and unknown errors fall through to retry-with-backoff.
|
|
196
|
+
// Exponential backoff: 1s, 2s, 4s
|
|
197
|
+
const delay = baseDelayMs * 2 ** (attempt - 1);
|
|
198
|
+
await this.sleep(delay);
|
|
199
|
+
// Reset state for retry
|
|
200
|
+
this.cleanup();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
205
|
+
* Single connection attempt
|
|
206
|
+
*/
|
|
207
|
+
attemptConnect = async () => {
|
|
208
|
+
this._state = "connecting";
|
|
209
|
+
// Determine TLS options
|
|
210
|
+
// When secure is false, STARTTLS may still be used, so we need to handle self-signed certs
|
|
211
|
+
const tlsOptions = this.config.tlsOptions
|
|
212
|
+
? {
|
|
213
|
+
rejectUnauthorized: this.config.tlsOptions.rejectUnauthorized ?? true,
|
|
214
|
+
}
|
|
215
|
+
: !this.config.tls
|
|
216
|
+
? {
|
|
217
|
+
// Allow self-signed certs when TLS is disabled (for STARTTLS)
|
|
218
|
+
rejectUnauthorized: false,
|
|
219
|
+
}
|
|
220
|
+
: undefined;
|
|
221
|
+
const auth = buildImapAuth(this.config.user, this.config.credentials);
|
|
222
|
+
this.client = new ImapFlow({
|
|
223
|
+
host: this.config.host,
|
|
224
|
+
port: this.config.port,
|
|
225
|
+
secure: this.config.tls,
|
|
226
|
+
servername: this.config.tlsOptions?.servername,
|
|
227
|
+
auth,
|
|
228
|
+
tls: tlsOptions,
|
|
229
|
+
// Disable auto IDLE to work around servers that don't handle IDLE correctly
|
|
230
|
+
// This is equivalent to node-imap's forceNoop: true
|
|
231
|
+
disableAutoIdle: true,
|
|
232
|
+
logger: false, // Disable verbose logging
|
|
233
|
+
});
|
|
234
|
+
this.client.on("close", () => {
|
|
235
|
+
this._state = "disconnected";
|
|
236
|
+
this.client = null;
|
|
237
|
+
this.currentMailbox = null;
|
|
238
|
+
});
|
|
239
|
+
this.client.on("error", () => {
|
|
240
|
+
this._state = "error";
|
|
241
|
+
});
|
|
242
|
+
await this.client.connect();
|
|
243
|
+
this._state = "authenticated";
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Cleanup client state for retry
|
|
247
|
+
*/
|
|
248
|
+
cleanup = () => {
|
|
249
|
+
if (this.client) {
|
|
250
|
+
this.client.close();
|
|
251
|
+
this.client = null;
|
|
252
|
+
}
|
|
253
|
+
this._state = "disconnected";
|
|
254
|
+
this.currentMailbox = null;
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* Sleep for a specified duration
|
|
258
|
+
*/
|
|
259
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
260
|
+
/**
|
|
261
|
+
* Disconnect from the IMAP server
|
|
262
|
+
*/
|
|
263
|
+
disconnect = async () => {
|
|
264
|
+
if (!this.client) {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const client = this.client;
|
|
268
|
+
// Use a timeout to avoid hanging on logout
|
|
269
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
270
|
+
setTimeout(() => {
|
|
271
|
+
// Force close if logout doesn't complete
|
|
272
|
+
client.close();
|
|
273
|
+
resolve();
|
|
274
|
+
}, 5000);
|
|
275
|
+
});
|
|
276
|
+
try {
|
|
277
|
+
await Promise.race([client.logout(), timeoutPromise]);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// Ignore errors during disconnect, force close
|
|
281
|
+
client.close();
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
this._state = "disconnected";
|
|
285
|
+
this.client = null;
|
|
286
|
+
this.currentMailbox = null;
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
/**
|
|
290
|
+
* Get IMAP namespaces
|
|
291
|
+
*
|
|
292
|
+
* Note: ImapFlow doesn't expose namespaces directly, so we return
|
|
293
|
+
* the default namespace. The mailbox listing works without explicit
|
|
294
|
+
* namespace handling in ImapFlow.
|
|
295
|
+
*/
|
|
296
|
+
getNamespaces = async () => {
|
|
297
|
+
this.ensureConnected();
|
|
298
|
+
// ImapFlow doesn't expose NAMESPACE info, return defaults
|
|
299
|
+
// This is sufficient as ImapFlow handles namespaces internally
|
|
300
|
+
return {
|
|
301
|
+
personal: [{ prefix: "", delimiter: "/" }],
|
|
302
|
+
other: [],
|
|
303
|
+
shared: [],
|
|
304
|
+
};
|
|
305
|
+
};
|
|
306
|
+
/**
|
|
307
|
+
* List all mailboxes as a flat list, preserving original paths from server.
|
|
308
|
+
* This avoids path corruption from split/join operations.
|
|
309
|
+
*
|
|
310
|
+
* @param nsPrefix - Optional namespace prefix to filter mailboxes
|
|
311
|
+
*/
|
|
312
|
+
listMailboxes = async (nsPrefix) => {
|
|
313
|
+
this.ensureConnected();
|
|
314
|
+
const mailboxes = await this.client?.list();
|
|
315
|
+
if (!mailboxes) {
|
|
316
|
+
return [];
|
|
317
|
+
}
|
|
318
|
+
const result = [];
|
|
319
|
+
for (const mailbox of mailboxes) {
|
|
320
|
+
// Filter by namespace prefix if provided
|
|
321
|
+
if (nsPrefix !== undefined && !mailbox.path.startsWith(nsPrefix)) {
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
// Extract name from path (last component)
|
|
325
|
+
const pathParts = mailbox.path.split(mailbox.delimiter);
|
|
326
|
+
const name = pathParts[pathParts.length - 1] || mailbox.path;
|
|
327
|
+
const parentPath = pathParts.length > 1
|
|
328
|
+
? pathParts.slice(0, -1).join(mailbox.delimiter)
|
|
329
|
+
: null;
|
|
330
|
+
result.push({
|
|
331
|
+
fullPath: mailbox.path, // Use original path from server
|
|
332
|
+
name,
|
|
333
|
+
delimiter: mailbox.delimiter,
|
|
334
|
+
attributes: this.convertFlags(mailbox.flags),
|
|
335
|
+
parentPath,
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
return result;
|
|
339
|
+
};
|
|
340
|
+
/**
|
|
341
|
+
* Convert ImapFlow flags Set to string array
|
|
342
|
+
*/
|
|
343
|
+
convertFlags = (flags) => {
|
|
344
|
+
if (!flags)
|
|
345
|
+
return [];
|
|
346
|
+
return Array.from(flags);
|
|
347
|
+
};
|
|
348
|
+
/**
|
|
349
|
+
* Open a mailbox for reading
|
|
350
|
+
*
|
|
351
|
+
* @param mailboxPath - Full path to the mailbox (e.g., "INBOX", "[Gmail]/Sent")
|
|
352
|
+
* @param readOnly - Whether to open read-only (default: true)
|
|
353
|
+
*/
|
|
354
|
+
openBox = async (mailboxPath, readOnly = true) => {
|
|
355
|
+
this.ensureConnected();
|
|
356
|
+
// Idempotency guard: re-selecting the currently-open mailbox is a no-op
|
|
357
|
+
// SELECT on the wire. `mailbox` exposes the live, already-selected box, so
|
|
358
|
+
// we can return its status without paying for another round-trip — this is
|
|
359
|
+
// what lets a batch issue one SELECT and many fetches on the same box.
|
|
360
|
+
if (this.currentMailbox === mailboxPath && this.client?.mailbox) {
|
|
361
|
+
return this.toBoxStatus(this.client.mailbox, readOnly);
|
|
362
|
+
}
|
|
363
|
+
const mailbox = await this.client?.mailboxOpen(mailboxPath, {
|
|
364
|
+
readOnly,
|
|
365
|
+
});
|
|
366
|
+
if (!mailbox) {
|
|
367
|
+
throw new Error(`Failed to open mailbox: ${mailboxPath}`);
|
|
368
|
+
}
|
|
369
|
+
this.currentMailbox = mailboxPath;
|
|
370
|
+
return this.toBoxStatus(mailbox, readOnly);
|
|
371
|
+
};
|
|
372
|
+
/**
|
|
373
|
+
* Build an ImapBoxStatus from an imapflow MailboxObject.
|
|
374
|
+
*/
|
|
375
|
+
toBoxStatus = (mailbox, readOnly) => {
|
|
376
|
+
const pathParts = mailbox.path.split(mailbox.delimiter);
|
|
377
|
+
const name = pathParts[pathParts.length - 1] || mailbox.path;
|
|
378
|
+
return {
|
|
379
|
+
name,
|
|
380
|
+
readOnly: mailbox.readOnly ?? readOnly,
|
|
381
|
+
uidvalidity: Number(mailbox.uidValidity),
|
|
382
|
+
uidnext: mailbox.uidNext,
|
|
383
|
+
flags: Array.from(mailbox.flags || []),
|
|
384
|
+
permFlags: Array.from(mailbox.permanentFlags || []),
|
|
385
|
+
persistentUIDs: true, // ImapFlow assumes persistent UIDs
|
|
386
|
+
messages: {
|
|
387
|
+
total: mailbox.exists,
|
|
388
|
+
new: 0, // ImapFlow doesn't provide unseen count on open
|
|
389
|
+
},
|
|
390
|
+
newKeywords: mailbox.permanentFlags?.has("\\*") ?? false,
|
|
391
|
+
};
|
|
392
|
+
};
|
|
393
|
+
/**
|
|
394
|
+
* Close the currently open mailbox
|
|
395
|
+
*
|
|
396
|
+
* @param _expunge - Whether to permanently remove deleted messages (not used in ImapFlow)
|
|
397
|
+
*/
|
|
398
|
+
closeBox = async (_expunge = false) => {
|
|
399
|
+
this.ensureConnected();
|
|
400
|
+
if (this.currentMailbox) {
|
|
401
|
+
await this.client?.mailboxClose();
|
|
402
|
+
this.currentMailbox = null;
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
/**
|
|
406
|
+
* Search for messages, answering UIDs.
|
|
407
|
+
*
|
|
408
|
+
* imapflow answers a successful SEARCH with an array — empty when the
|
|
409
|
+
* server matched nothing — and `false` when the command failed or no
|
|
410
|
+
* mailbox was selected. Collapsing the two into `[]` makes a failed SEARCH
|
|
411
|
+
* indistinguishable from an empty mailbox, and every caller here acts on
|
|
412
|
+
* emptiness by deleting something: the cursor rebuild reads it as "every
|
|
413
|
+
* local row is stale", and {@link isMessageGoneFromOpenMailbox} reads it as
|
|
414
|
+
* "this message is gone". A failure therefore throws.
|
|
415
|
+
*/
|
|
416
|
+
search = async (criteria) => {
|
|
417
|
+
this.ensureConnected();
|
|
418
|
+
if (!this.currentMailbox) {
|
|
419
|
+
throw new Error("No mailbox selected");
|
|
420
|
+
}
|
|
421
|
+
const searchQuery = convertSearchCriteria(criteria);
|
|
422
|
+
const result = await this.client?.search(searchQuery, { uid: true });
|
|
423
|
+
if (!Array.isArray(result)) {
|
|
424
|
+
throw new Error(`IMAP SEARCH failed in mailbox ${this.currentMailbox}`);
|
|
425
|
+
}
|
|
426
|
+
return result;
|
|
427
|
+
};
|
|
428
|
+
/**
|
|
429
|
+
* Fetch messages by UID
|
|
430
|
+
*
|
|
431
|
+
* Uses ImapFlow's native envelope parsing which works correctly
|
|
432
|
+
* with all IMAP servers including mokapi.
|
|
433
|
+
*/
|
|
434
|
+
fetchMessages = async (uids) => {
|
|
435
|
+
this.ensureConnected();
|
|
436
|
+
if (uids.length === 0) {
|
|
437
|
+
return [];
|
|
438
|
+
}
|
|
439
|
+
return this.runMessageFetch(uids.join(","), {});
|
|
440
|
+
};
|
|
441
|
+
/**
|
|
442
|
+
* True when this session negotiated CONDSTORE (RFC 7162) and the open
|
|
443
|
+
* mailbox keeps persistent mod-sequences.
|
|
444
|
+
*
|
|
445
|
+
* Both halves matter. `enabled` reflects the ENABLE exchange, not merely
|
|
446
|
+
* the advertised capability, and a server may still answer NOMODSEQ for an
|
|
447
|
+
* individual mailbox — in which case RFC 7162 Section 3.1.2.2 requires it
|
|
448
|
+
* to reject CHANGEDSINCE with a BAD response.
|
|
449
|
+
*/
|
|
450
|
+
supportsCondstore = () => {
|
|
451
|
+
const { client } = this;
|
|
452
|
+
if (!client?.mailbox)
|
|
453
|
+
return false;
|
|
454
|
+
return client.enabled.has("CONDSTORE") && !client.mailbox.noModseq;
|
|
455
|
+
};
|
|
456
|
+
/**
|
|
457
|
+
* FETCH everything in the open mailbox whose MODSEQ is strictly greater
|
|
458
|
+
* than `sinceModseq` — new arrivals and metadata changes to messages
|
|
459
|
+
* already synced, in one pass over the whole UID space.
|
|
460
|
+
*
|
|
461
|
+
* The CONDSTORE guard is load-bearing rather than defensive: imapflow drops
|
|
462
|
+
* the CHANGEDSINCE modifier when the extension is unavailable, so the same
|
|
463
|
+
* call would degrade into a fetch of every message in the mailbox.
|
|
464
|
+
*/
|
|
465
|
+
fetchMessagesChangedSince = async (sinceModseq) => {
|
|
466
|
+
this.ensureConnected();
|
|
467
|
+
if (!this.supportsCondstore()) {
|
|
468
|
+
throw new Error("CHANGEDSINCE requires CONDSTORE on both the session and the open mailbox");
|
|
469
|
+
}
|
|
470
|
+
return this.runMessageFetch("1:*", { changedSince: sinceModseq });
|
|
471
|
+
};
|
|
472
|
+
/**
|
|
473
|
+
* One UID FETCH over `range`, mapped to {@link ImapMessage}. The shared
|
|
474
|
+
* body of {@link fetchMessages} and {@link fetchMessagesChangedSince} —
|
|
475
|
+
* both need identical message shapes and differ only in what they select.
|
|
476
|
+
*/
|
|
477
|
+
runMessageFetch = async (range, options) => {
|
|
478
|
+
const { client } = this;
|
|
479
|
+
if (!client) {
|
|
480
|
+
throw new Error("Not connected to IMAP server");
|
|
481
|
+
}
|
|
482
|
+
if (!this.currentMailbox) {
|
|
483
|
+
throw new Error("No mailbox selected");
|
|
484
|
+
}
|
|
485
|
+
const messages = [];
|
|
486
|
+
const fetchIterator = client.fetch(range, {
|
|
487
|
+
uid: true,
|
|
488
|
+
flags: true,
|
|
489
|
+
envelope: true,
|
|
490
|
+
bodyStructure: true,
|
|
491
|
+
internalDate: true,
|
|
492
|
+
size: true,
|
|
493
|
+
headers: ["references"],
|
|
494
|
+
}, { uid: true, ...options });
|
|
495
|
+
// Connection may have been lost - fetch returns an async iterable
|
|
496
|
+
if (!fetchIterator) {
|
|
497
|
+
throw new Error(`IMAP connection lost while fetching messages: ${range}`);
|
|
498
|
+
}
|
|
499
|
+
for await (const msg of fetchIterator) {
|
|
500
|
+
// imapflow occasionally yields a row with undefined uid or internalDate
|
|
501
|
+
// on back-to-back FETCH calls (e.g. after a body-fetch on the same UID).
|
|
502
|
+
// See #408 for the investigation. This is the client library glitching,
|
|
503
|
+
// not the message being malformed, so the row is dropped rather than
|
|
504
|
+
// quarantined — recording it as a defective message would advance a
|
|
505
|
+
// cursor past mail that is fine (issue #72).
|
|
506
|
+
//
|
|
507
|
+
// Dropping it is only safe because the caller treats a requested UID
|
|
508
|
+
// with no row as unconsumed and holds its watermark below it. It used
|
|
509
|
+
// to advance regardless, which is how a transient client glitch turned
|
|
510
|
+
// into a message never fetched again.
|
|
511
|
+
if (msg.uid == null || msg.internalDate == null) {
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
// Coerce INTERNALDATE without ever throwing: a malformed value must not
|
|
515
|
+
// abort the whole fetch batch. A bad value falls back to now; an absent
|
|
516
|
+
// one cannot reach here, having been dropped above.
|
|
517
|
+
const internalDate = toInternalDate(msg.internalDate) ?? new Date();
|
|
518
|
+
// Parse References header if present
|
|
519
|
+
const references = await this.parseReferencesHeader(msg.headers);
|
|
520
|
+
messages.push({
|
|
521
|
+
uid: msg.uid,
|
|
522
|
+
seq: msg.seq,
|
|
523
|
+
flags: Array.from(msg.flags || []),
|
|
524
|
+
internalDate,
|
|
525
|
+
size: msg.size ?? 0,
|
|
526
|
+
envelope: this.convertEnvelope(msg.envelope),
|
|
527
|
+
references,
|
|
528
|
+
bodyStructure: msg.bodyStructure,
|
|
529
|
+
...(msg.modseq != null ? { modseq: msg.modseq.toString() } : {}),
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
return messages;
|
|
533
|
+
};
|
|
534
|
+
/**
|
|
535
|
+
* Cheap envelope-only FETCH for the UIDVALIDITY cursor rebuild (#1272):
|
|
536
|
+
* UID + Message-ID + INTERNALDATE only — no flags, no BODYSTRUCTURE, no
|
|
537
|
+
* References header, no body. Deliberately lighter than {@link
|
|
538
|
+
* fetchMessages} so a rebuild pass over a large mailbox stays cheap (epic
|
|
539
|
+
* #1281 invariant 6).
|
|
540
|
+
*/
|
|
541
|
+
fetchEnvelopeSnapshots = async (uids) => {
|
|
542
|
+
this.ensureConnected();
|
|
543
|
+
const { client } = this;
|
|
544
|
+
if (!client) {
|
|
545
|
+
throw new Error("Not connected to IMAP server");
|
|
546
|
+
}
|
|
547
|
+
if (!this.currentMailbox) {
|
|
548
|
+
throw new Error("No mailbox selected");
|
|
549
|
+
}
|
|
550
|
+
if (uids.length === 0) {
|
|
551
|
+
return [];
|
|
552
|
+
}
|
|
553
|
+
const uidRange = uids.join(",");
|
|
554
|
+
const fetchIterator = client.fetch(uidRange, { uid: true, envelope: true, internalDate: true }, { uid: true });
|
|
555
|
+
if (!fetchIterator) {
|
|
556
|
+
throw new Error(`IMAP connection lost while fetching envelope snapshots: ${uidRange}`);
|
|
557
|
+
}
|
|
558
|
+
const snapshots = [];
|
|
559
|
+
for await (const msg of fetchIterator) {
|
|
560
|
+
// Same defensive skip as fetchMessages (#408) — an occasional row
|
|
561
|
+
// with no uid/internalDate must not abort the whole batch.
|
|
562
|
+
if (msg.uid == null || msg.internalDate == null) {
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const internalDate = toInternalDate(msg.internalDate);
|
|
566
|
+
if (internalDate === null) {
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
snapshots.push({
|
|
570
|
+
uid: msg.uid,
|
|
571
|
+
messageId: msg.envelope?.messageId ?? "",
|
|
572
|
+
internalDate,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
return snapshots;
|
|
576
|
+
};
|
|
577
|
+
/**
|
|
578
|
+
* Fetch the full message body (RFC822 source) for a single message by UID.
|
|
579
|
+
*
|
|
580
|
+
* @param uid - The UID of the message to fetch
|
|
581
|
+
* @returns The raw message body, or null when the UID FETCH matched no message
|
|
582
|
+
*/
|
|
583
|
+
fetchMessageBody = async (uid) => {
|
|
584
|
+
this.ensureConnected();
|
|
585
|
+
const { client } = this;
|
|
586
|
+
if (!client) {
|
|
587
|
+
throw new Error("Not connected to IMAP server");
|
|
588
|
+
}
|
|
589
|
+
if (!this.currentMailbox) {
|
|
590
|
+
throw new Error("No mailbox selected");
|
|
591
|
+
}
|
|
592
|
+
const result = await client.download(String(uid), undefined, {
|
|
593
|
+
uid: true,
|
|
594
|
+
});
|
|
595
|
+
if (result?.content) {
|
|
596
|
+
const chunks = [];
|
|
597
|
+
for await (const chunk of result.content) {
|
|
598
|
+
chunks.push(chunk);
|
|
599
|
+
}
|
|
600
|
+
return Buffer.concat(chunks);
|
|
601
|
+
}
|
|
602
|
+
if (!client.usable || !client.mailbox) {
|
|
603
|
+
throw new MailConnectionError("network", `IMAP connection lost while downloading message UID ${uid}`);
|
|
604
|
+
}
|
|
605
|
+
return null;
|
|
606
|
+
};
|
|
607
|
+
/**
|
|
608
|
+
* Fetch full message bodies (RFC822 source) for many UIDs in ONE pipelined
|
|
609
|
+
* ranged UID FETCH on a single connection — the desktop-client pattern.
|
|
610
|
+
*
|
|
611
|
+
* Mirrors `fetchMessages`: one comma-joined UID range, one `client.fetch`,
|
|
612
|
+
* one SELECT (the caller opens the box once for the whole batch). Yields
|
|
613
|
+
* `{ uid, source }` as each message arrives so the caller can stream each
|
|
614
|
+
* body straight to storage without buffering the whole batch.
|
|
615
|
+
*
|
|
616
|
+
* `source` is a readable stream over the message bytes — callers must
|
|
617
|
+
* consume it (e.g. pipe to an upload) before requesting the next item.
|
|
618
|
+
*/
|
|
619
|
+
async *fetchMessageBodies(uids) {
|
|
620
|
+
this.ensureConnected();
|
|
621
|
+
const { client } = this;
|
|
622
|
+
if (!client) {
|
|
623
|
+
throw new Error("Not connected to IMAP server");
|
|
624
|
+
}
|
|
625
|
+
if (!this.currentMailbox) {
|
|
626
|
+
throw new Error("No mailbox selected");
|
|
627
|
+
}
|
|
628
|
+
if (uids.length === 0) {
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
const uidRange = uids.join(",");
|
|
632
|
+
const fetchIterator = client.fetch(uidRange, { uid: true, source: true }, { uid: true });
|
|
633
|
+
if (!fetchIterator) {
|
|
634
|
+
throw new MailConnectionError("network", `IMAP connection lost while fetching message bodies: ${uidRange}`);
|
|
635
|
+
}
|
|
636
|
+
try {
|
|
637
|
+
for await (const msg of fetchIterator) {
|
|
638
|
+
// imapflow can yield a row with an undefined uid or no source on
|
|
639
|
+
// back-to-back FETCH calls, and Dovecot answers `source: false` for a
|
|
640
|
+
// message another client expunged; skip it rather than crash the batch
|
|
641
|
+
// — the caller treats any UID it never sees as failed and re-enqueues
|
|
642
|
+
// it. See #408.
|
|
643
|
+
if (msg.uid == null || !msg.source) {
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
yield { uid: msg.uid, source: Readable.from(msg.source) };
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
catch (error) {
|
|
650
|
+
// A mid-stream socket drop surfaces as imapflow's
|
|
651
|
+
// `new Error("Connection closed")` with code `EConnectionClosed` — a
|
|
652
|
+
// string the rest of the code never matches on. Re-throw it as the
|
|
653
|
+
// typed MailConnectionError so the caller's fail-fast path triggers and
|
|
654
|
+
// re-enqueues the not-yet-yielded UIDs instead of failing the record.
|
|
655
|
+
throw (classifyImapError(error, `${this.config.host}:${this.config.port}`) ??
|
|
656
|
+
error);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Parse the References header from IMAP headers buffer.
|
|
661
|
+
* Returns an array of Message-IDs, with the first being the thread root.
|
|
662
|
+
*/
|
|
663
|
+
parseReferencesHeader = async (headers) => {
|
|
664
|
+
if (!headers)
|
|
665
|
+
return undefined;
|
|
666
|
+
// Raw header bytes are untrusted. simpleParser is tolerant but can still
|
|
667
|
+
// throw on sufficiently broken input; a throw here would abort the whole
|
|
668
|
+
// fetch batch. Missing references just means "no thread parent", so on any
|
|
669
|
+
// parse failure treat the message as a thread root rather than crashing.
|
|
670
|
+
const parsed = await simpleParser(headers).catch(() => null);
|
|
671
|
+
if (!parsed?.references)
|
|
672
|
+
return undefined;
|
|
673
|
+
// mailparser returns references as string or array
|
|
674
|
+
if (Array.isArray(parsed.references)) {
|
|
675
|
+
return parsed.references.length > 0 ? parsed.references : undefined;
|
|
676
|
+
}
|
|
677
|
+
// Single reference as string
|
|
678
|
+
return [parsed.references];
|
|
679
|
+
};
|
|
680
|
+
/**
|
|
681
|
+
* Convert ImapFlow envelope to our ImapEnvelope format
|
|
682
|
+
*/
|
|
683
|
+
convertEnvelope = (envelope) => {
|
|
684
|
+
// An absent ENVELOPE stays absent. Synthesising an empty one here made
|
|
685
|
+
// every `if (!msg.envelope)` guard downstream unreachable, so a FETCH row
|
|
686
|
+
// that carried no envelope was saved as a row with no sender, no subject
|
|
687
|
+
// and no date, keyed by the `generated:` fallback — indistinguishable
|
|
688
|
+
// from a real message. The field is optional on `ImapMessage` precisely
|
|
689
|
+
// so callers can see the difference (issue #72).
|
|
690
|
+
if (!envelope)
|
|
691
|
+
return undefined;
|
|
692
|
+
const convertAddresses = (addrs) => {
|
|
693
|
+
if (!addrs)
|
|
694
|
+
return [];
|
|
695
|
+
return addrs
|
|
696
|
+
.filter((a) => a.address)
|
|
697
|
+
.map((a) => {
|
|
698
|
+
const [mailbox, host] = (a.address || "").split("@");
|
|
699
|
+
return {
|
|
700
|
+
name: a.name || undefined,
|
|
701
|
+
mailbox: mailbox || "",
|
|
702
|
+
host: host || "",
|
|
703
|
+
};
|
|
704
|
+
});
|
|
705
|
+
};
|
|
706
|
+
return {
|
|
707
|
+
date: toIsoDateString(envelope.date),
|
|
708
|
+
subject: envelope.subject ?? "",
|
|
709
|
+
from: convertAddresses(envelope.from),
|
|
710
|
+
sender: convertAddresses(envelope.sender),
|
|
711
|
+
replyTo: convertAddresses(envelope.replyTo),
|
|
712
|
+
to: convertAddresses(envelope.to),
|
|
713
|
+
cc: convertAddresses(envelope.cc),
|
|
714
|
+
bcc: convertAddresses(envelope.bcc),
|
|
715
|
+
inReplyTo: envelope.inReplyTo ?? "",
|
|
716
|
+
messageId: envelope.messageId ?? "",
|
|
717
|
+
};
|
|
718
|
+
};
|
|
719
|
+
/**
|
|
720
|
+
* Add flags to messages by UID.
|
|
721
|
+
* Requires mailbox to be open (not read-only).
|
|
722
|
+
*
|
|
723
|
+
* @param uids - Array of message UIDs
|
|
724
|
+
* @param flags - Array of flags to add (e.g., ["\\Seen", "\\Flagged"])
|
|
725
|
+
*/
|
|
726
|
+
addFlags = async (uids, flags) => {
|
|
727
|
+
this.ensureConnected();
|
|
728
|
+
const { client } = this;
|
|
729
|
+
if (!client) {
|
|
730
|
+
throw new Error("Not connected to IMAP server");
|
|
731
|
+
}
|
|
732
|
+
if (!this.currentMailbox) {
|
|
733
|
+
throw new Error("No mailbox selected");
|
|
734
|
+
}
|
|
735
|
+
if (uids.length === 0 || flags.length === 0) {
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const uidRange = uids.join(",");
|
|
739
|
+
await client.messageFlagsAdd(uidRange, flags, { uid: true });
|
|
740
|
+
};
|
|
741
|
+
/**
|
|
742
|
+
* Remove flags from messages by UID.
|
|
743
|
+
* Requires mailbox to be open (not read-only).
|
|
744
|
+
*
|
|
745
|
+
* @param uids - Array of message UIDs
|
|
746
|
+
* @param flags - Array of flags to remove (e.g., ["\\Seen", "\\Flagged"])
|
|
747
|
+
*/
|
|
748
|
+
removeFlags = async (uids, flags) => {
|
|
749
|
+
this.ensureConnected();
|
|
750
|
+
const { client } = this;
|
|
751
|
+
if (!client) {
|
|
752
|
+
throw new Error("Not connected to IMAP server");
|
|
753
|
+
}
|
|
754
|
+
if (!this.currentMailbox) {
|
|
755
|
+
throw new Error("No mailbox selected");
|
|
756
|
+
}
|
|
757
|
+
if (uids.length === 0 || flags.length === 0) {
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
const uidRange = uids.join(",");
|
|
761
|
+
await client.messageFlagsRemove(uidRange, flags, { uid: true });
|
|
762
|
+
};
|
|
763
|
+
/**
|
|
764
|
+
* Replace all flags on messages by UID.
|
|
765
|
+
* Requires mailbox to be open (not read-only).
|
|
766
|
+
*
|
|
767
|
+
* @param uids - Array of message UIDs
|
|
768
|
+
* @param flags - Array of flags to set (replaces all existing flags)
|
|
769
|
+
*/
|
|
770
|
+
setFlags = async (uids, flags) => {
|
|
771
|
+
this.ensureConnected();
|
|
772
|
+
const { client } = this;
|
|
773
|
+
if (!client) {
|
|
774
|
+
throw new Error("Not connected to IMAP server");
|
|
775
|
+
}
|
|
776
|
+
if (!this.currentMailbox) {
|
|
777
|
+
throw new Error("No mailbox selected");
|
|
778
|
+
}
|
|
779
|
+
if (uids.length === 0) {
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
const uidRange = uids.join(",");
|
|
783
|
+
await client.messageFlagsSet(uidRange, flags, { uid: true });
|
|
784
|
+
};
|
|
785
|
+
/**
|
|
786
|
+
* Create a new mailbox.
|
|
787
|
+
*
|
|
788
|
+
* @param path - Full path of the mailbox to create (e.g., "Projects/ClientA")
|
|
789
|
+
* @returns Object with path and whether it was created (false if already exists)
|
|
790
|
+
*/
|
|
791
|
+
createMailbox = async (path) => {
|
|
792
|
+
this.ensureConnected();
|
|
793
|
+
const { client } = this;
|
|
794
|
+
if (!client) {
|
|
795
|
+
throw new Error("Not connected to IMAP server");
|
|
796
|
+
}
|
|
797
|
+
const result = await client.mailboxCreate(path);
|
|
798
|
+
return {
|
|
799
|
+
path: result.path,
|
|
800
|
+
created: result.created ?? true,
|
|
801
|
+
};
|
|
802
|
+
};
|
|
803
|
+
/**
|
|
804
|
+
* Delete a mailbox.
|
|
805
|
+
*
|
|
806
|
+
* @param path - Full path of the mailbox to delete
|
|
807
|
+
* @returns Object with the deleted path
|
|
808
|
+
*/
|
|
809
|
+
deleteMailbox = async (path) => {
|
|
810
|
+
this.ensureConnected();
|
|
811
|
+
const { client } = this;
|
|
812
|
+
if (!client) {
|
|
813
|
+
throw new Error("Not connected to IMAP server");
|
|
814
|
+
}
|
|
815
|
+
// Cannot delete INBOX
|
|
816
|
+
if (path.toUpperCase() === "INBOX") {
|
|
817
|
+
throw new Error("Cannot delete INBOX");
|
|
818
|
+
}
|
|
819
|
+
const result = await client.mailboxDelete(path);
|
|
820
|
+
return { path: result.path };
|
|
821
|
+
};
|
|
822
|
+
/**
|
|
823
|
+
* Rename a mailbox.
|
|
824
|
+
*
|
|
825
|
+
* @param oldPath - Current path of the mailbox
|
|
826
|
+
* @param newPath - New path for the mailbox
|
|
827
|
+
* @returns Object with old and new paths
|
|
828
|
+
*/
|
|
829
|
+
renameMailbox = async (oldPath, newPath) => {
|
|
830
|
+
this.ensureConnected();
|
|
831
|
+
const { client } = this;
|
|
832
|
+
if (!client) {
|
|
833
|
+
throw new Error("Not connected to IMAP server");
|
|
834
|
+
}
|
|
835
|
+
const result = await client.mailboxRename(oldPath, newPath);
|
|
836
|
+
// `mailboxRename` resolves `undefined` when the connection is not
|
|
837
|
+
// AUTHENTICATED or SELECTED — RENAME was never issued. Dereferencing it
|
|
838
|
+
// raised a `TypeError` where the settle now reads the resolved path, and a
|
|
839
|
+
// `TypeError` is not an outcome the rename settle can classify.
|
|
840
|
+
if (!result) {
|
|
841
|
+
throw new Error(`Rename of "${oldPath}" was not issued: the IMAP connection is not ready`);
|
|
842
|
+
}
|
|
843
|
+
return {
|
|
844
|
+
path: result.path,
|
|
845
|
+
newPath: result.newPath,
|
|
846
|
+
};
|
|
847
|
+
};
|
|
848
|
+
/**
|
|
849
|
+
* Subscribe to a mailbox.
|
|
850
|
+
*
|
|
851
|
+
* @param path - Full path of the mailbox to subscribe to
|
|
852
|
+
*/
|
|
853
|
+
subscribeMailbox = async (path) => {
|
|
854
|
+
this.ensureConnected();
|
|
855
|
+
const { client } = this;
|
|
856
|
+
if (!client) {
|
|
857
|
+
throw new Error("Not connected to IMAP server");
|
|
858
|
+
}
|
|
859
|
+
await client.mailboxSubscribe(path);
|
|
860
|
+
};
|
|
861
|
+
/**
|
|
862
|
+
* Unsubscribe from a mailbox.
|
|
863
|
+
*
|
|
864
|
+
* @param path - Full path of the mailbox to unsubscribe from
|
|
865
|
+
*/
|
|
866
|
+
unsubscribeMailbox = async (path) => {
|
|
867
|
+
this.ensureConnected();
|
|
868
|
+
const { client } = this;
|
|
869
|
+
if (!client) {
|
|
870
|
+
throw new Error("Not connected to IMAP server");
|
|
871
|
+
}
|
|
872
|
+
await client.mailboxUnsubscribe(path);
|
|
873
|
+
};
|
|
874
|
+
/**
|
|
875
|
+
* Move messages to another mailbox.
|
|
876
|
+
* Uses ImapFlow's messageMove which wraps UID MOVE command.
|
|
877
|
+
* Returns mapping of source UIDs to destination UIDs from COPYUID response.
|
|
878
|
+
*
|
|
879
|
+
* @param uids - Array of message UIDs to move
|
|
880
|
+
* @param destination - Destination mailbox path
|
|
881
|
+
* @returns Object with destination path, uidValidity, and uidMap
|
|
882
|
+
*/
|
|
883
|
+
moveMessages = async (uids, destination) => {
|
|
884
|
+
this.ensureConnected();
|
|
885
|
+
const { client } = this;
|
|
886
|
+
if (!client) {
|
|
887
|
+
throw new Error("Not connected to IMAP server");
|
|
888
|
+
}
|
|
889
|
+
if (!this.currentMailbox) {
|
|
890
|
+
throw new Error("No mailbox selected");
|
|
891
|
+
}
|
|
892
|
+
if (uids.length === 0) {
|
|
893
|
+
return { destination, uidValidity: 0, uidMap: new Map() };
|
|
894
|
+
}
|
|
895
|
+
const uidRange = uids.join(",");
|
|
896
|
+
const result = await client.messageMove(uidRange, destination, {
|
|
897
|
+
uid: true,
|
|
898
|
+
});
|
|
899
|
+
// messageMove returns false if no messages were moved
|
|
900
|
+
if (result === false) {
|
|
901
|
+
return { destination, uidValidity: 0, uidMap: new Map() };
|
|
902
|
+
}
|
|
903
|
+
return {
|
|
904
|
+
destination: result.destination,
|
|
905
|
+
uidValidity: Number(result.uidValidity ?? 0),
|
|
906
|
+
uidMap: result.uidMap ?? new Map(),
|
|
907
|
+
};
|
|
908
|
+
};
|
|
909
|
+
/**
|
|
910
|
+
* Copy messages to another mailbox.
|
|
911
|
+
* Uses ImapFlow's messageCopy which wraps UID COPY command.
|
|
912
|
+
* Returns mapping of source UIDs to destination UIDs from COPYUID response.
|
|
913
|
+
*
|
|
914
|
+
* @param uids - Array of message UIDs to copy
|
|
915
|
+
* @param destination - Destination mailbox path
|
|
916
|
+
* @returns Object with destination path, uidValidity, and uidMap
|
|
917
|
+
*/
|
|
918
|
+
copyMessages = async (uids, destination) => {
|
|
919
|
+
this.ensureConnected();
|
|
920
|
+
const { client } = this;
|
|
921
|
+
if (!client) {
|
|
922
|
+
throw new Error("Not connected to IMAP server");
|
|
923
|
+
}
|
|
924
|
+
if (!this.currentMailbox) {
|
|
925
|
+
throw new Error("No mailbox selected");
|
|
926
|
+
}
|
|
927
|
+
if (uids.length === 0) {
|
|
928
|
+
return { destination, uidValidity: 0, uidMap: new Map() };
|
|
929
|
+
}
|
|
930
|
+
const uidRange = uids.join(",");
|
|
931
|
+
const result = await client.messageCopy(uidRange, destination, {
|
|
932
|
+
uid: true,
|
|
933
|
+
});
|
|
934
|
+
// messageCopy returns false if no messages were copied
|
|
935
|
+
if (result === false) {
|
|
936
|
+
return { destination, uidValidity: 0, uidMap: new Map() };
|
|
937
|
+
}
|
|
938
|
+
return {
|
|
939
|
+
destination: result.destination,
|
|
940
|
+
uidValidity: Number(result.uidValidity ?? 0),
|
|
941
|
+
uidMap: result.uidMap ?? new Map(),
|
|
942
|
+
};
|
|
943
|
+
};
|
|
944
|
+
/**
|
|
945
|
+
* Permanently delete messages (mark \Deleted + expunge).
|
|
946
|
+
* Uses ImapFlow's messageDelete which wraps STORE +FLAGS.SILENT \Deleted
|
|
947
|
+
* followed by UID EXPUNGE.
|
|
948
|
+
*
|
|
949
|
+
* @param uids - Array of message UIDs to delete
|
|
950
|
+
* @returns Number of messages deleted
|
|
951
|
+
*/
|
|
952
|
+
deleteMessages = async (uids) => {
|
|
953
|
+
this.ensureConnected();
|
|
954
|
+
const { client } = this;
|
|
955
|
+
if (!client) {
|
|
956
|
+
throw new Error("Not connected to IMAP server");
|
|
957
|
+
}
|
|
958
|
+
if (!this.currentMailbox) {
|
|
959
|
+
throw new Error("No mailbox selected");
|
|
960
|
+
}
|
|
961
|
+
if (uids.length === 0) {
|
|
962
|
+
return 0;
|
|
963
|
+
}
|
|
964
|
+
const uidRange = uids.join(",");
|
|
965
|
+
const result = await client.messageDelete(uidRange, { uid: true });
|
|
966
|
+
// messageDelete returns boolean or deleted count
|
|
967
|
+
if (typeof result === "number") {
|
|
968
|
+
return result;
|
|
969
|
+
}
|
|
970
|
+
return result ? uids.length : 0;
|
|
971
|
+
};
|
|
972
|
+
/**
|
|
973
|
+
* Get mailbox status.
|
|
974
|
+
*
|
|
975
|
+
* Message/unseen counts come from the IMAP STATUS command (no SELECT). The
|
|
976
|
+
* \Deleted count is not part of imapflow's typed STATUS query (there is no
|
|
977
|
+
* IMAP4rev2 STATUS=DELETED in the API), so it is derived by selecting the
|
|
978
|
+
* mailbox read-only and running SEARCH \Deleted — a projection re-read from
|
|
979
|
+
* the server, never a locally computed value.
|
|
980
|
+
*
|
|
981
|
+
* @param mailboxPath - Full path to the mailbox
|
|
982
|
+
* @returns Mailbox status including unseen and deleted counts
|
|
983
|
+
*/
|
|
984
|
+
getMailboxStatus = async (mailboxPath) => {
|
|
985
|
+
this.ensureConnected();
|
|
986
|
+
const { client } = this;
|
|
987
|
+
if (!client) {
|
|
988
|
+
throw new Error("Not connected to IMAP server");
|
|
989
|
+
}
|
|
990
|
+
const status = await client.status(mailboxPath, {
|
|
991
|
+
messages: true,
|
|
992
|
+
recent: true,
|
|
993
|
+
unseen: true,
|
|
994
|
+
uidNext: true,
|
|
995
|
+
uidValidity: true,
|
|
996
|
+
highestModseq: true,
|
|
997
|
+
});
|
|
998
|
+
const deletedCount = await this.countDeleted(mailboxPath);
|
|
999
|
+
return {
|
|
1000
|
+
messages: status.messages ?? 0,
|
|
1001
|
+
recent: status.recent ?? 0,
|
|
1002
|
+
unseen: status.unseen ?? 0,
|
|
1003
|
+
uidNext: status.uidNext ?? 0,
|
|
1004
|
+
uidValidity: Number(status.uidValidity ?? 0),
|
|
1005
|
+
highestModseq: (status.highestModseq ?? 0n).toString(),
|
|
1006
|
+
deletedCount,
|
|
1007
|
+
};
|
|
1008
|
+
};
|
|
1009
|
+
/**
|
|
1010
|
+
* Count messages flagged \Deleted but not yet expunged.
|
|
1011
|
+
*
|
|
1012
|
+
* Selects the mailbox read-only (no state change) and counts SEARCH \Deleted
|
|
1013
|
+
* hits. Read-only SELECT is idempotent against an already-open mailbox.
|
|
1014
|
+
*/
|
|
1015
|
+
countDeleted = async (mailboxPath) => {
|
|
1016
|
+
await this.openBox(mailboxPath, true);
|
|
1017
|
+
const deletedUids = await this.search(["DELETED"]);
|
|
1018
|
+
return deletedUids.length;
|
|
1019
|
+
};
|
|
1020
|
+
/**
|
|
1021
|
+
* Append a message to a mailbox.
|
|
1022
|
+
* Used primarily for testing to seed messages.
|
|
1023
|
+
*
|
|
1024
|
+
* @param mailbox - Mailbox path to append to
|
|
1025
|
+
* @param message - RFC 822 message content
|
|
1026
|
+
* @param flags - Optional flags to set on the message
|
|
1027
|
+
* @returns Object with destination path, uidValidity, and uid of the appended message
|
|
1028
|
+
*/
|
|
1029
|
+
append = async (mailbox, message, flags) => {
|
|
1030
|
+
this.ensureConnected();
|
|
1031
|
+
const { client } = this;
|
|
1032
|
+
if (!client) {
|
|
1033
|
+
throw new Error("Not connected to IMAP server");
|
|
1034
|
+
}
|
|
1035
|
+
const result = await client.append(mailbox, message, flags);
|
|
1036
|
+
// append returns false if the message could not be appended
|
|
1037
|
+
if (result === false) {
|
|
1038
|
+
throw new Error(`Failed to append message to ${mailbox}`);
|
|
1039
|
+
}
|
|
1040
|
+
return {
|
|
1041
|
+
destination: result.destination,
|
|
1042
|
+
uidValidity: Number(result.uidValidity ?? 0),
|
|
1043
|
+
uid: result.uid ?? 0,
|
|
1044
|
+
};
|
|
1045
|
+
};
|
|
1046
|
+
/**
|
|
1047
|
+
* Ensure the connection is established
|
|
1048
|
+
*/
|
|
1049
|
+
ensureConnected = () => {
|
|
1050
|
+
if (!this.client || this._state !== "authenticated") {
|
|
1051
|
+
throw new Error("Not connected to IMAP server");
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Create an ImapFlow connection from account data using password credentials.
|
|
1057
|
+
*/
|
|
1058
|
+
export const createImapFlowConnectionFromAccount = (account, password) => {
|
|
1059
|
+
return new ImapFlowConnection({
|
|
1060
|
+
host: account.imapHost,
|
|
1061
|
+
port: account.imapPort,
|
|
1062
|
+
tls: account.imapTls,
|
|
1063
|
+
user: account.username,
|
|
1064
|
+
credentials: { kind: "password", password },
|
|
1065
|
+
});
|
|
1066
|
+
};
|
|
1067
|
+
/**
|
|
1068
|
+
* Create an ImapFlow connection using a credentials union (password or OAuth access token).
|
|
1069
|
+
*/
|
|
1070
|
+
export const createImapFlowConnectionWithCredentials = (account, credentials) => {
|
|
1071
|
+
return new ImapFlowConnection({
|
|
1072
|
+
host: account.imapHost,
|
|
1073
|
+
port: account.imapPort,
|
|
1074
|
+
tls: account.imapTls,
|
|
1075
|
+
user: account.username,
|
|
1076
|
+
credentials,
|
|
1077
|
+
});
|
|
1078
|
+
};
|
|
1079
|
+
/**
|
|
1080
|
+
* Build the imapflow auth object from mail credentials.
|
|
1081
|
+
*
|
|
1082
|
+
* IMPORTANT: never include access-token values in error messages.
|
|
1083
|
+
*/
|
|
1084
|
+
const buildImapAuth = (user, credentials) => {
|
|
1085
|
+
if (credentials.kind === "password") {
|
|
1086
|
+
return { user, pass: credentials.password };
|
|
1087
|
+
}
|
|
1088
|
+
if (credentials.kind === "accessToken") {
|
|
1089
|
+
return { user, accessToken: credentials.accessToken };
|
|
1090
|
+
}
|
|
1091
|
+
// Exhaustiveness check — fails to compile if a new credential kind is added
|
|
1092
|
+
// without handling it here.
|
|
1093
|
+
const _exhaustive = credentials;
|
|
1094
|
+
throw new Error(`Unknown credential kind: ${JSON.stringify(_exhaustive)}`);
|
|
1095
|
+
};
|
|
1096
|
+
/**
|
|
1097
|
+
* The server's own words for the failure: the text of the tagged NO/BAD, which
|
|
1098
|
+
* imapflow hangs off the error as `responseText`. It is the server's side of
|
|
1099
|
+
* the exchange only — never the command we sent, so no credential can ride out
|
|
1100
|
+
* on it. "SmtpClientAuthentication is disabled" and "User is authenticated but
|
|
1101
|
+
* not connected" arrive this way, and neither is fixed by re-authenticating, so
|
|
1102
|
+
* dropping the text leaves the account card telling the user to do the one
|
|
1103
|
+
* thing that cannot help.
|
|
1104
|
+
*/
|
|
1105
|
+
const serverResponseText = (error) => {
|
|
1106
|
+
const text = error.responseText;
|
|
1107
|
+
return typeof text === "string" ? text.trim() : "";
|
|
1108
|
+
};
|
|
1109
|
+
/**
|
|
1110
|
+
* Classify a raw IMAP error into a MailConnectionError, or return null if
|
|
1111
|
+
* the error is not recognisable (let it bubble as-is).
|
|
1112
|
+
*
|
|
1113
|
+
* IMPORTANT: never include access-token values in error messages.
|
|
1114
|
+
*/
|
|
1115
|
+
const classifyImapError = (error, endpoint) => {
|
|
1116
|
+
if (!(error instanceof Error)) {
|
|
1117
|
+
return null;
|
|
1118
|
+
}
|
|
1119
|
+
const msg = error.message;
|
|
1120
|
+
const code = error.code ?? "";
|
|
1121
|
+
// Authentication failures
|
|
1122
|
+
if (msg.includes("Invalid credentials") ||
|
|
1123
|
+
msg.includes("Authentication failed") ||
|
|
1124
|
+
msg.includes("AUTHENTICATIONFAILED") ||
|
|
1125
|
+
msg.includes("AUTHENTICATE") ||
|
|
1126
|
+
error.authenticationFailed === true) {
|
|
1127
|
+
const serverText = serverResponseText(error);
|
|
1128
|
+
return new MailConnectionError("auth", serverText
|
|
1129
|
+
? `IMAP authentication failed: ${serverText}`
|
|
1130
|
+
: "IMAP authentication failed");
|
|
1131
|
+
}
|
|
1132
|
+
// Network-level failures — NEVER include the original message as it may
|
|
1133
|
+
// echo back tokens in some server implementations. The endpoint (host:port)
|
|
1134
|
+
// is safe and makes DNS/connect failures self-describing.
|
|
1135
|
+
if (code === "ECONNREFUSED" ||
|
|
1136
|
+
code === "ETIMEDOUT" ||
|
|
1137
|
+
code === "ENOTFOUND" ||
|
|
1138
|
+
code === "ECONNRESET" ||
|
|
1139
|
+
code === "EHOSTUNREACH" ||
|
|
1140
|
+
// imapflow raises these when the socket is gone mid-command.
|
|
1141
|
+
code === "EConnectionClosed" ||
|
|
1142
|
+
code === "NoConnection") {
|
|
1143
|
+
const where = endpoint ? ` (${endpoint})` : "";
|
|
1144
|
+
return new MailConnectionError("network", `IMAP connection failed: ${code}${where}`);
|
|
1145
|
+
}
|
|
1146
|
+
return null;
|
|
1147
|
+
};
|