@remit/mailbox-service 0.0.15 → 0.0.16

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.
@@ -591,20 +591,23 @@ export class ImapFlowConnection {
591
591
  for await (const msg of fetchIterator) {
592
592
  // imapflow occasionally yields a row with undefined uid or internalDate
593
593
  // on back-to-back FETCH calls (e.g. after a body-fetch on the same UID).
594
- // Skipping the row is safe: the caller asked for a specific UID set and
595
- // will simply not see that entry rather than the whole call crashing.
596
- // See #408 for the investigation.
594
+ // See #408 for the investigation. This is the client library glitching,
595
+ // not the message being malformed, so the row is dropped rather than
596
+ // quarantined recording it as a defective message would advance a
597
+ // cursor past mail that is fine (issue #72).
598
+ //
599
+ // Dropping it is only safe because the caller treats a requested UID
600
+ // with no row as unconsumed and holds its watermark below it. It used
601
+ // to advance regardless, which is how a transient client glitch turned
602
+ // into a message never fetched again.
597
603
  if (msg.uid == null || msg.internalDate == null) {
598
604
  continue;
599
605
  }
600
606
 
601
607
  // Coerce INTERNALDATE without ever throwing: a malformed value must not
602
- // abort the whole fetch batch. `null` only for an absent value (already
603
- // handled by the guard above); a bad value falls back to now.
604
- const internalDate = toInternalDate(msg.internalDate);
605
- if (internalDate === null) {
606
- continue;
607
- }
608
+ // abort the whole fetch batch. A bad value falls back to now; an absent
609
+ // one cannot reach here, having been dropped above.
610
+ const internalDate = toInternalDate(msg.internalDate) ?? new Date();
608
611
 
609
612
  // Parse References header if present
610
613
  const references = await this.parseReferencesHeader(msg.headers);
@@ -840,20 +843,13 @@ export class ImapFlowConnection {
840
843
  }
841
844
  | undefined,
842
845
  ): ImapMessage["envelope"] => {
843
- if (!envelope) {
844
- return {
845
- date: "",
846
- subject: "",
847
- from: [],
848
- sender: [],
849
- replyTo: [],
850
- to: [],
851
- cc: [],
852
- bcc: [],
853
- inReplyTo: "",
854
- messageId: "",
855
- };
856
- }
846
+ // An absent ENVELOPE stays absent. Synthesising an empty one here made
847
+ // every `if (!msg.envelope)` guard downstream unreachable, so a FETCH row
848
+ // that carried no envelope was saved as a row with no sender, no subject
849
+ // and no date, keyed by the `generated:` fallback — indistinguishable
850
+ // from a real message. The field is optional on `ImapMessage` precisely
851
+ // so callers can see the difference (issue #72).
852
+ if (!envelope) return undefined;
857
853
 
858
854
  const convertAddresses = (
859
855
  addrs?: Array<{ name?: string; address?: string }>,
package/src/index.ts CHANGED
@@ -15,6 +15,10 @@ export {
15
15
  type ParsedAttributes,
16
16
  parseImapAttributes,
17
17
  } from "./attribute-mapper.js";
18
+ export {
19
+ BodyParseError,
20
+ parseMessageBody,
21
+ } from "./body-parse.js";
18
22
  export {
19
23
  type BodySyncLogger,
20
24
  BodySyncService,
@@ -22,6 +26,7 @@ export {
22
26
  extractPrimaryFromEmail,
23
27
  type FetchBodyResult,
24
28
  type PlacementConfig,
29
+ type QuarantineConfig,
25
30
  type SyncBodiesResult,
26
31
  toParsedBody,
27
32
  } from "./body-sync.js";
@@ -188,6 +193,16 @@ export {
188
193
  type ResolveExhaustedPlacementMoveResult,
189
194
  resolveExhaustedPlacementMoveFailure,
190
195
  } from "./placement-move-terminal.js";
196
+ export {
197
+ type QuarantineContext,
198
+ QuarantinedUids,
199
+ type QuarantineFailure,
200
+ type QuarantineLogger,
201
+ type QuarantineMessageShape,
202
+ QuarantineService,
203
+ resolveMailboxRole,
204
+ shapeFromMessageData,
205
+ } from "./quarantine.js";
191
206
  export {
192
207
  extractSnippetFromEmail,
193
208
  generateSnippet,
@@ -0,0 +1,407 @@
1
+ /**
2
+ * The ways an enumeration round used to let go of a message without a record of
3
+ * it (issue #72).
4
+ *
5
+ * A row carrying no ENVELOPE was counted as saved and the watermark moved past
6
+ * it; so was a UID the FETCH never returned a row for. Neither is attributable
7
+ * to the message — an absent envelope is indistinguishable from the FETCH row
8
+ * glitching — so neither is quarantined. Both are now failures the watermark
9
+ * must stop below, which is the only treatment that survives a gap in the
10
+ * middle of a batch.
11
+ */
12
+
13
+ import assert from "node:assert/strict";
14
+ import { describe, it } from "node:test";
15
+ import type {
16
+ IAddressRepository,
17
+ IEnvelopeRepository,
18
+ IMailboxRepository,
19
+ IMailboxSpecialUseRepository,
20
+ IMessageRepository,
21
+ IQuarantineRepository,
22
+ IThreadMessageRepository,
23
+ IUnitOfWork,
24
+ MailboxItem,
25
+ QuarantineItem,
26
+ QuarantineUpsertInput,
27
+ UpdateMailboxInput,
28
+ } from "@remit/data-ports";
29
+ import { MailboxCursorState } from "@remit/domain-enums";
30
+ import type { ManagedConnectionFactory } from "./connection-factory.js";
31
+ import { MessageSyncService, selectUidsToSync } from "./message-sync.js";
32
+ import { QuarantineService } from "./quarantine.js";
33
+ import type { IImapConnection, ImapMessage } from "./types.js";
34
+
35
+ const ACCOUNT_ID = "acc-1";
36
+ const ACCOUNT_CONFIG_ID = "cfg-1";
37
+ const MAILBOX_ID = "mbx-1";
38
+ const UID_VALIDITY = 100;
39
+
40
+ const buildMailbox = (over: Partial<MailboxItem> = {}): MailboxItem =>
41
+ ({
42
+ mailboxId: MAILBOX_ID,
43
+ accountId: ACCOUNT_ID,
44
+ fullPath: "INBOX",
45
+ uidValidity: UID_VALIDITY,
46
+ lastSyncUid: 0,
47
+ highWaterMarkUid: 20,
48
+ highestModseq: "0",
49
+ cursorState: MailboxCursorState.normal,
50
+ ...over,
51
+ }) as MailboxItem;
52
+
53
+ const withEnvelope = (uid: number): ImapMessage => ({
54
+ uid,
55
+ seq: uid,
56
+ flags: [],
57
+ internalDate: new Date("2026-01-01T00:00:00Z"),
58
+ size: 42,
59
+ envelope: {
60
+ date: "Thu, 01 Jan 2026 00:00:00 +0000",
61
+ subject: "Hello",
62
+ from: [{ mailbox: "sender", host: "example.com" }],
63
+ sender: [],
64
+ replyTo: [],
65
+ to: [{ mailbox: "me", host: "example.com" }],
66
+ cc: [],
67
+ bcc: [],
68
+ inReplyTo: "",
69
+ messageId: `<${uid}@example.com>`,
70
+ },
71
+ });
72
+
73
+ const withoutEnvelope = (uid: number): ImapMessage => ({
74
+ uid,
75
+ seq: uid,
76
+ flags: [],
77
+ internalDate: new Date("2026-01-01T00:00:00Z"),
78
+ size: 42,
79
+ bodyStructure: { type: "text/plain", encoding: "7bit" },
80
+ });
81
+
82
+ const buildHarness = (options: {
83
+ allUids: number[];
84
+ enumerated: ImapMessage[];
85
+ existing?: QuarantineItem[];
86
+ lastSyncUid?: number;
87
+ highWaterMarkUid?: number;
88
+ /** UIDs the cheap snapshot FETCH returns; defaults to `allUids`. */
89
+ snapshotUids?: number[];
90
+ /** Set to `cursor_invalid` to take the rebuild path. */
91
+ cursorState?: MailboxItem["cursorState"];
92
+ }) => {
93
+ const mailbox = buildMailbox({
94
+ ...(options.lastSyncUid !== undefined
95
+ ? { lastSyncUid: options.lastSyncUid }
96
+ : {}),
97
+ ...(options.highWaterMarkUid !== undefined
98
+ ? { highWaterMarkUid: options.highWaterMarkUid }
99
+ : {}),
100
+ ...(options.cursorState ? { cursorState: options.cursorState } : {}),
101
+ });
102
+ const mailboxUpdates: UpdateMailboxInput[] = [];
103
+ const writes: QuarantineUpsertInput[] = [];
104
+ const fetched: number[][] = [];
105
+
106
+ const connection = {
107
+ openBox: async () => ({ uidvalidity: UID_VALIDITY, uidnext: 99 }),
108
+ getMailboxStatus: async () => ({
109
+ messages: 10,
110
+ recent: 0,
111
+ unseen: 1,
112
+ uidNext: 99,
113
+ uidValidity: UID_VALIDITY,
114
+ highestModseq: "600",
115
+ deletedCount: 0,
116
+ }),
117
+ supportsCondstore: () => false,
118
+ search: async () => options.allUids,
119
+ fetchEnvelopeSnapshots: async () =>
120
+ (options.snapshotUids ?? options.allUids).map((uid) => ({
121
+ uid,
122
+ messageId: `<${uid}@example.com>`,
123
+ internalDate: new Date("2026-01-01T00:00:00Z"),
124
+ })),
125
+ fetchMessages: async (uids: number[]) => {
126
+ fetched.push(uids);
127
+ return options.enumerated.filter((msg) => uids.includes(msg.uid));
128
+ },
129
+ } as unknown as IImapConnection;
130
+
131
+ const mailboxService = {
132
+ get: async () => mailbox,
133
+ update: async (_a: string, _m: string, input: UpdateMailboxInput) => {
134
+ mailboxUpdates.push(input);
135
+ return mailbox;
136
+ },
137
+ } as unknown as IMailboxRepository;
138
+
139
+ const threadMessageService = {
140
+ findByMessageId: async () => null,
141
+ findAllByMessageId: async () => [],
142
+ listByMailbox: async () => ({ items: [], continuationToken: undefined }),
143
+ create: async () => ({ threadMessageId: "tm-1" }),
144
+ update: async () => ({ threadMessageId: "tm-1" }),
145
+ } as unknown as IThreadMessageRepository;
146
+
147
+ const unitOfWork: IUnitOfWork = {
148
+ transaction: (fn) =>
149
+ fn({
150
+ message: {
151
+ upsertWithStatus: async (input: { mailboxId: string }) => ({
152
+ item: { mailboxId: input.mailboxId },
153
+ created: true,
154
+ }),
155
+ updateUid: async () => undefined,
156
+ } as unknown as IMessageRepository,
157
+ envelope: {
158
+ upsertEnvelope: async () => undefined,
159
+ upsertBodyParts: async () => undefined,
160
+ } as unknown as IEnvelopeRepository,
161
+ address: {
162
+ upsertAddress: async () => undefined,
163
+ upsertEnvelopeAddress: async () => undefined,
164
+ } as unknown as IAddressRepository,
165
+ threadMessage: threadMessageService,
166
+ }),
167
+ };
168
+
169
+ const repository = {
170
+ listByAccountConfigId: async () => options.existing ?? [],
171
+ upsert: async (input: QuarantineUpsertInput) => {
172
+ writes.push(input);
173
+ },
174
+ } satisfies IQuarantineRepository;
175
+
176
+ const service = new MessageSyncService(
177
+ {
178
+ getConnection: () => connection,
179
+ close: async () => {},
180
+ } as ManagedConnectionFactory,
181
+ mailboxService,
182
+ {} as IMessageRepository,
183
+ {} as IEnvelopeRepository,
184
+ {} as IAddressRepository,
185
+ threadMessageService,
186
+ { info: () => {}, warn: () => {}, error: () => {} },
187
+ unitOfWork,
188
+ undefined,
189
+ undefined,
190
+ new QuarantineService(
191
+ repository,
192
+ {
193
+ listByMailboxId: async () => [],
194
+ } as unknown as IMailboxSpecialUseRepository,
195
+ "sha-abc",
196
+ { info: () => {}, warn: () => {} },
197
+ ),
198
+ );
199
+
200
+ return { service, mailboxUpdates, writes, fetched };
201
+ };
202
+
203
+ const sync = (service: MessageSyncService) =>
204
+ service.syncMessages(MAILBOX_ID, ACCOUNT_ID, ACCOUNT_CONFIG_ID, 50);
205
+
206
+ describe("a row that carried no ENVELOPE", () => {
207
+ it("is held for retry rather than set aside", async () => {
208
+ const harness = buildHarness({
209
+ allUids: [21],
210
+ enumerated: [withoutEnvelope(21)],
211
+ });
212
+
213
+ await sync(harness.service);
214
+
215
+ // Nothing can tell an envelope-less row apart from the FETCH glitching,
216
+ // and the client is far more often the cause than the message. Recording
217
+ // it would set aside mail that is fine.
218
+ assert.deepEqual(harness.writes, []);
219
+ assert.equal(harness.mailboxUpdates[0]?.highWaterMarkUid, 20);
220
+ });
221
+
222
+ it("keeps the mailbox on enumeration rather than seeding a mod-sequence over it", async () => {
223
+ const harness = buildHarness({
224
+ allUids: [21],
225
+ enumerated: [withoutEnvelope(21)],
226
+ });
227
+
228
+ await sync(harness.service);
229
+
230
+ assert.equal(harness.mailboxUpdates[0]?.highestModseq, undefined);
231
+ });
232
+ });
233
+
234
+ describe("a uid already quarantined", () => {
235
+ it("is not fetched again, but the watermark still passes it", async () => {
236
+ const harness = buildHarness({
237
+ allUids: [21, 22],
238
+ enumerated: [withEnvelope(22)],
239
+ existing: [
240
+ {
241
+ mailboxId: MAILBOX_ID,
242
+ uidValidity: UID_VALIDITY,
243
+ uid: 21,
244
+ } as QuarantineItem,
245
+ ],
246
+ });
247
+
248
+ await sync(harness.service);
249
+
250
+ assert.deepEqual(harness.fetched, [[22]]);
251
+ assert.equal(harness.mailboxUpdates[0]?.highWaterMarkUid, 22);
252
+ });
253
+ });
254
+
255
+ describe("a uid the FETCH returned no row for", () => {
256
+ it("stops the watermark below it when it is the highest of the batch", async () => {
257
+ const harness = buildHarness({
258
+ allUids: [22, 21],
259
+ enumerated: [withEnvelope(21)],
260
+ });
261
+
262
+ await sync(harness.service);
263
+
264
+ assert.equal(harness.mailboxUpdates[0]?.highWaterMarkUid, 21);
265
+ });
266
+
267
+ it("stops the watermark below it when it sits in the middle of the batch", async () => {
268
+ const harness = buildHarness({
269
+ allUids: [23, 22, 21],
270
+ // 22's row is dropped; 23 above it saves fine.
271
+ enumerated: [withEnvelope(23), withEnvelope(21)],
272
+ });
273
+
274
+ await sync(harness.service);
275
+
276
+ // The watermark advances by MAX of what was applied, so absence alone
277
+ // would let 23 carry it straight over the gap and lose 22 for good.
278
+ assert.equal(harness.mailboxUpdates[0]?.highWaterMarkUid, 21);
279
+ });
280
+
281
+ it("stops the backfill floor above a gap, so it stays selectable", async () => {
282
+ const harness = buildHarness({
283
+ allUids: [12, 11, 10],
284
+ enumerated: [withEnvelope(12), withEnvelope(10)],
285
+ lastSyncUid: 20,
286
+ highWaterMarkUid: 20,
287
+ });
288
+
289
+ await sync(harness.service);
290
+
291
+ assert.equal(harness.mailboxUpdates[0]?.lastSyncUid, 12);
292
+ });
293
+
294
+ it("keeps the mailbox on enumeration rather than seeding a mod-sequence over it", async () => {
295
+ const harness = buildHarness({
296
+ allUids: [22, 21],
297
+ enumerated: [withEnvelope(21)],
298
+ });
299
+
300
+ await sync(harness.service);
301
+
302
+ assert.equal(harness.mailboxUpdates[0]?.highestModseq, undefined);
303
+ });
304
+ });
305
+
306
+ /**
307
+ * The cursor rebuild is the third save path, and the one where a lost UID is
308
+ * lost for good: its covered region is computed from the server snapshot
309
+ * rather than from what it applied, and it seeds the mod-sequence and returns
310
+ * the mailbox to `normal` — so the next round takes CHANGEDSINCE, which never
311
+ * enumerates.
312
+ */
313
+ describe("cursor rebuild", () => {
314
+ const rebuild = (over: {
315
+ allUids: number[];
316
+ enumerated: ImapMessage[];
317
+ snapshotUids?: number[];
318
+ }) =>
319
+ buildHarness({
320
+ ...over,
321
+ cursorState: MailboxCursorState.cursor_invalid,
322
+ lastSyncUid: 0,
323
+ highWaterMarkUid: 0,
324
+ });
325
+
326
+ it("holds the watermark below a UID whose row carried no ENVELOPE", async () => {
327
+ const harness = rebuild({
328
+ allUids: [23, 22, 21],
329
+ enumerated: [withEnvelope(23), withoutEnvelope(22), withEnvelope(21)],
330
+ });
331
+
332
+ await sync(harness.service);
333
+
334
+ const final = harness.mailboxUpdates.at(-1);
335
+ assert.equal(final?.highWaterMarkUid, 21);
336
+ });
337
+
338
+ it("holds the watermark below a UID the message FETCH did not return", async () => {
339
+ const harness = rebuild({
340
+ allUids: [23, 22, 21],
341
+ enumerated: [withEnvelope(23), withEnvelope(21)],
342
+ });
343
+
344
+ await sync(harness.service);
345
+
346
+ assert.equal(harness.mailboxUpdates.at(-1)?.highWaterMarkUid, 21);
347
+ });
348
+
349
+ it("holds the watermark below a UID the snapshot FETCH did not return", async () => {
350
+ const harness = rebuild({
351
+ allUids: [23, 22, 21],
352
+ snapshotUids: [23, 21],
353
+ enumerated: [withEnvelope(23), withEnvelope(21)],
354
+ });
355
+
356
+ await sync(harness.service);
357
+
358
+ // This UID never reaches the snapshot, so it is not even a candidate for
359
+ // saving — but the covered region spans it, which is the whole hazard.
360
+ assert.equal(harness.mailboxUpdates.at(-1)?.highWaterMarkUid, 21);
361
+ });
362
+
363
+ it("withholds the mod-sequence seed, so the mailbox stays on enumeration", async () => {
364
+ const harness = rebuild({
365
+ allUids: [23, 22, 21],
366
+ enumerated: [withEnvelope(23), withEnvelope(21)],
367
+ });
368
+
369
+ await sync(harness.service);
370
+
371
+ // Seeding it would flip the mailbox to CHANGEDSINCE, which never
372
+ // enumerates — the UID would never be looked for again.
373
+ assert.equal(harness.mailboxUpdates.at(-1)?.highestModseq, "0");
374
+ });
375
+
376
+ it("leaves the missing UID selectable by the next round", async () => {
377
+ const harness = rebuild({
378
+ allUids: [23, 22, 21],
379
+ enumerated: [withEnvelope(23), withEnvelope(21)],
380
+ });
381
+
382
+ await sync(harness.service);
383
+
384
+ const final = harness.mailboxUpdates.at(-1);
385
+ assert.deepEqual(
386
+ selectUidsToSync(
387
+ [23, 22, 21],
388
+ final?.lastSyncUid ?? 0,
389
+ final?.highWaterMarkUid ?? 0,
390
+ ),
391
+ [23, 22],
392
+ );
393
+ });
394
+
395
+ it("seeds the mod-sequence when every UID was accounted for", async () => {
396
+ const harness = rebuild({
397
+ allUids: [23, 22, 21],
398
+ enumerated: [withEnvelope(23), withEnvelope(22), withEnvelope(21)],
399
+ });
400
+
401
+ await sync(harness.service);
402
+
403
+ const final = harness.mailboxUpdates.at(-1);
404
+ assert.equal(final?.highestModseq, "600");
405
+ assert.equal(final?.highWaterMarkUid, 23);
406
+ });
407
+ });