@remit/imap-worker 0.0.86 → 0.0.87
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/README.md +3 -1
- package/package.json +10 -2
- package/src/account-check.ts +1 -1
- package/src/body-sync-gate.test.ts +1 -1
- package/src/body-sync-gate.ts +1 -1
- package/src/e2e-processor-shim.ts +6 -21
- package/src/emit.ts +1 -1
- package/src/failure-kind.ts +1 -1
- package/src/handlers/append-sent-message.sqlite.test.ts +176 -0
- package/src/handlers/append-sent-message.ts +3 -24
- package/src/handlers/delete-account-objects.test.ts +1 -1
- package/src/handlers/delete-account-objects.ts +1 -1
- package/src/handlers/empty-trash.sqlite.test.ts +209 -0
- package/src/handlers/empty-trash.ts +3 -24
- package/src/handlers/flag-push.ts +11 -18
- package/src/handlers/mailbox-management.sqlite.test.ts +265 -0
- package/src/handlers/mailbox-management.ts +12 -48
- package/src/handlers/message-copy.sqlite.test.ts +298 -0
- package/src/handlers/message-copy.ts +31 -49
- package/src/handlers/message-delete-terminal.ts +12 -10
- package/src/handlers/message-delete.sqlite.test.ts +291 -0
- package/src/handlers/message-delete.ts +26 -32
- package/src/handlers/message-move-terminal.ts +12 -10
- package/src/handlers/message-move.sqlite.test.ts +271 -0
- package/src/handlers/message-move.test.ts +76 -863
- package/src/handlers/message-move.ts +49 -39
- package/src/handlers/placement-move-push.test.ts +96 -329
- package/src/handlers/placement-move-push.ts +75 -29
- package/src/handlers/placement-push.sqlite.test.ts +298 -0
- package/src/handlers/probe-message-id.sqlite.test.ts +197 -0
- package/src/handlers/probe-message-id.ts +15 -0
- package/src/handlers/sync-mailboxes.test.ts +0 -1
- package/src/handlers/sync-mailboxes.ts +1 -1
- package/src/handlers/sync-message-body.sqlite.test.ts +314 -0
- package/src/handlers/sync-message-body.test.ts +3 -299
- package/src/handlers/sync-message-body.ts +21 -11
- package/src/handlers/sync-messages.sqlite.test.ts +183 -0
- package/src/handlers/sync-messages.ts +27 -33
- package/src/index.ts +5 -3
- package/src/mail-sync-selection.sqlite.test.ts +16 -18
- package/src/poller.ts +5 -4
- package/src/processor.test.ts +1 -1
- package/src/processor.ts +1 -1
- package/src/scheduler/attachment-sweep.sqlite.test.ts +74 -0
- package/src/scheduler/attachment-sweep.ts +1 -1
- package/src/scheduler/{calendar-subscriptions.test.ts → calendar-subscriptions.sqlite.test.ts} +43 -55
- package/src/scheduler/calendar-subscriptions.ts +6 -6
- package/src/scheduler/half-deleted-accounts.sqlite.test.ts +203 -0
- package/src/scheduler/handler.ts +12 -1
- package/src/scheduler/loop.test.ts +2 -0
- package/src/scheduler/run-tick.sqlite.test.ts +192 -0
- package/src/scheduler/run-tick.ts +39 -1
- package/src/scheduler/runner.ts +21 -1
- package/src/scheduler/stranded-placement-redrive.ts +265 -0
- package/src/stranded-placement.sqlite.test.ts +795 -0
- package/src/test-helpers/test-world.ts +398 -0
- package/src/thread-join.sqlite.test.ts +115 -0
- package/src/with-oauth-lifecycle-deps.sqlite.test.ts +138 -14
- package/src/with-oauth-lifecycle.ts +1 -1
- package/src/handlers/append-sent-message.test.ts +0 -529
- package/src/handlers/empty-trash.test.ts +0 -728
- package/src/handlers/flag-push-placement-race.test.ts +0 -385
- package/src/handlers/flag-push.test.ts +0 -325
- package/src/handlers/mailbox-management.test.ts +0 -850
- package/src/handlers/message-copy.test.ts +0 -654
- package/src/handlers/message-delete.test.ts +0 -1869
- package/src/handlers/message-move-terminal.test.ts +0 -412
- package/src/handlers/sync-messages.test.ts +0 -569
- package/src/scheduler/attachment-sweep.test.ts +0 -169
- package/src/scheduler/run-tick.test.ts +0 -478
- package/src/with-oauth-lifecycle.test.ts +0 -318
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
_resetForTest,
|
|
8
|
+
getClient,
|
|
9
|
+
type RemitClient,
|
|
10
|
+
setClient,
|
|
11
|
+
} from "@remit/backend/client";
|
|
12
|
+
import type {
|
|
13
|
+
AccountItem,
|
|
14
|
+
MailboxItem,
|
|
15
|
+
MailboxSpecialUseValue,
|
|
16
|
+
MessageItem,
|
|
17
|
+
OutboxMessageItem,
|
|
18
|
+
} from "@remit/data-ports";
|
|
19
|
+
import {
|
|
20
|
+
AccountAuthType,
|
|
21
|
+
ConnectionState,
|
|
22
|
+
MailboxCursorState,
|
|
23
|
+
} from "@remit/domain-enums";
|
|
24
|
+
import { createShippedSqliteFiles } from "@remit/drizzle-service/test-sqlite";
|
|
25
|
+
import type { Logger } from "@remit/logger";
|
|
26
|
+
import type { ManagedConnectionFactory } from "@remit/mailbox-service";
|
|
27
|
+
import {
|
|
28
|
+
eml,
|
|
29
|
+
FakeImapServer,
|
|
30
|
+
} from "@remit/mailbox-service/test-helpers/fake-imap";
|
|
31
|
+
import {
|
|
32
|
+
captureQueue,
|
|
33
|
+
type QueueCapture,
|
|
34
|
+
} from "@remit/mailbox-service/test-helpers/test-queue";
|
|
35
|
+
import { serializeEncryptedPayload } from "@remit/secrets-service";
|
|
36
|
+
import type { createConnectionScopeWithCredentials } from "../connection-scope.js";
|
|
37
|
+
import { syncMessages } from "../handlers/sync-messages.js";
|
|
38
|
+
|
|
39
|
+
export interface LogLine {
|
|
40
|
+
level: string;
|
|
41
|
+
fields: Record<string, unknown>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const capturingLogger = (lines: LogLine[]): Logger => {
|
|
45
|
+
const at =
|
|
46
|
+
(level: string) =>
|
|
47
|
+
(fields: Record<string, unknown>): void => {
|
|
48
|
+
lines.push({ level, fields });
|
|
49
|
+
};
|
|
50
|
+
const log = {
|
|
51
|
+
info: at("info"),
|
|
52
|
+
warn: at("warn"),
|
|
53
|
+
error: at("error"),
|
|
54
|
+
debug: at("debug"),
|
|
55
|
+
fatal: at("fatal"),
|
|
56
|
+
trace: at("trace"),
|
|
57
|
+
child: () => log,
|
|
58
|
+
} as unknown as Logger;
|
|
59
|
+
return log;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** A message the way a correspondent sends one, naming it by its Message-ID. */
|
|
63
|
+
export const mail = (messageIdHeader: string): Buffer =>
|
|
64
|
+
eml({
|
|
65
|
+
"Message-ID": messageIdHeader,
|
|
66
|
+
From: "Friend <friend@example.com>",
|
|
67
|
+
To: "Person <person@example.com>",
|
|
68
|
+
Date: "Tue, 14 Nov 2023 22:13:20 +0000",
|
|
69
|
+
Subject: "test",
|
|
70
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
export interface FolderOptions {
|
|
74
|
+
specialUse?: MailboxSpecialUseValue;
|
|
75
|
+
uidValidity?: number;
|
|
76
|
+
cursorState?: MailboxItem["cursorState"];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface SeededMessage {
|
|
80
|
+
messageId: string;
|
|
81
|
+
uid: number;
|
|
82
|
+
messageIdHeader: string;
|
|
83
|
+
threadMessageId: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* One SQLite store per test file, over the shipped migrations, composed by the
|
|
88
|
+
* backend's own SQLite composition root over filesystem storage — every
|
|
89
|
+
* repository and service a handler reaches is the one a self-host process
|
|
90
|
+
* runs. Each `world()` is a fresh account on it, with its own in-memory mail
|
|
91
|
+
* server at the IMAP port, and a message reaches the store the way mail does:
|
|
92
|
+
* delivered to the server, then synced.
|
|
93
|
+
*/
|
|
94
|
+
export const openStore = async (): Promise<{
|
|
95
|
+
client: RemitClient;
|
|
96
|
+
world: (accountConfigId?: string) => Promise<World>;
|
|
97
|
+
close: () => void;
|
|
98
|
+
}> => {
|
|
99
|
+
const directory = mkdtempSync(join(tmpdir(), "imap-worker-world-"));
|
|
100
|
+
createShippedSqliteFiles(directory);
|
|
101
|
+
delete process.env.S3_BUCKET_NAME;
|
|
102
|
+
process.env.STORAGE_LOCAL_PATH = join(directory, "storage");
|
|
103
|
+
process.env.BETTER_AUTH_URL = "https://mail.example.com";
|
|
104
|
+
process.env.BETTER_AUTH_SECRET = "a-signing-secret-of-at-least-32-characters";
|
|
105
|
+
_resetForTest();
|
|
106
|
+
const client = await getClient();
|
|
107
|
+
setClient(client);
|
|
108
|
+
return {
|
|
109
|
+
client,
|
|
110
|
+
world: (accountConfigId = `cfg-${randomUUID()}`) =>
|
|
111
|
+
createWorld(client, accountConfigId),
|
|
112
|
+
close: () => {
|
|
113
|
+
_resetForTest();
|
|
114
|
+
rmSync(directory, { recursive: true, force: true });
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export interface World {
|
|
120
|
+
client: RemitClient;
|
|
121
|
+
imap: FakeImapServer;
|
|
122
|
+
account: AccountItem;
|
|
123
|
+
logs: LogLine[];
|
|
124
|
+
log: Logger;
|
|
125
|
+
folder: (path: string, options?: FolderOptions) => Promise<MailboxItem>;
|
|
126
|
+
/** A folder of a second account on this world's account config. */
|
|
127
|
+
siblingFolder: (path: string) => Promise<MailboxItem>;
|
|
128
|
+
message: (
|
|
129
|
+
mailbox: MailboxItem,
|
|
130
|
+
options?: { messageIdHeader?: string },
|
|
131
|
+
) => Promise<SeededMessage>;
|
|
132
|
+
row: (messageId: string) => Promise<MessageItem | undefined>;
|
|
133
|
+
threadRows: (
|
|
134
|
+
messageId: string,
|
|
135
|
+
) => Promise<Array<{ mailboxId: string; uid?: number; isDeleted: boolean }>>;
|
|
136
|
+
queued: () => Array<Record<string, unknown>>;
|
|
137
|
+
refuseSends: (error: Error | undefined) => void;
|
|
138
|
+
queue: QueueCapture;
|
|
139
|
+
draft: (
|
|
140
|
+
attachment?: Buffer,
|
|
141
|
+
) => Promise<{ outbox: OutboxMessageItem; attachmentId?: string }>;
|
|
142
|
+
scope: typeof createConnectionScopeWithCredentials;
|
|
143
|
+
connectionFactory: () => ManagedConnectionFactory;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const createWorld = async (
|
|
147
|
+
client: RemitClient,
|
|
148
|
+
accountConfigId: string,
|
|
149
|
+
): Promise<World> => {
|
|
150
|
+
const queue = captureQueue();
|
|
151
|
+
|
|
152
|
+
const imap = new FakeImapServer();
|
|
153
|
+
const logs: LogLine[] = [];
|
|
154
|
+
const password = await client.secrets.encrypt("app-password");
|
|
155
|
+
const account = await client.account.create({
|
|
156
|
+
accountConfigId,
|
|
157
|
+
username: "person@example.com",
|
|
158
|
+
email: "person@example.com",
|
|
159
|
+
authType: AccountAuthType.Password,
|
|
160
|
+
passwordHash: JSON.stringify(serializeEncryptedPayload(password)),
|
|
161
|
+
imapHost: "imap.example.com",
|
|
162
|
+
imapPort: 993,
|
|
163
|
+
imapTls: true,
|
|
164
|
+
imapStartTls: false,
|
|
165
|
+
isActive: true,
|
|
166
|
+
connectionState: ConnectionState.Authenticated,
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const folder = async (
|
|
170
|
+
path: string,
|
|
171
|
+
options: FolderOptions = {},
|
|
172
|
+
): Promise<MailboxItem> => {
|
|
173
|
+
const uidValidity = options.uidValidity ?? 1;
|
|
174
|
+
imap.addFolder(path, { uidValidity });
|
|
175
|
+
const created = await client.mailbox.create({
|
|
176
|
+
accountId: account.accountId,
|
|
177
|
+
namespacePrefix: "",
|
|
178
|
+
hierarchyDelimiter: "/",
|
|
179
|
+
fullPath: path,
|
|
180
|
+
uidValidity,
|
|
181
|
+
uidNext: 1,
|
|
182
|
+
highestModseq: "0",
|
|
183
|
+
messageCount: 0,
|
|
184
|
+
unseenCount: 0,
|
|
185
|
+
deletedCount: 0,
|
|
186
|
+
totalSize: 0,
|
|
187
|
+
lastSyncUid: 0,
|
|
188
|
+
highWaterMarkUid: 0,
|
|
189
|
+
lastMessageSyncAt: 0,
|
|
190
|
+
syncStatus: "synced",
|
|
191
|
+
});
|
|
192
|
+
if (created.outcome !== "Created") {
|
|
193
|
+
throw new Error(`${path} could not be created: ${created.outcome}`);
|
|
194
|
+
}
|
|
195
|
+
const mailbox = created.mailbox;
|
|
196
|
+
if (options.specialUse) {
|
|
197
|
+
await client.mailboxSpecialUse.create(
|
|
198
|
+
mailbox.mailboxId,
|
|
199
|
+
options.specialUse,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
if (
|
|
203
|
+
options.cursorState &&
|
|
204
|
+
options.cursorState !== MailboxCursorState.normal
|
|
205
|
+
) {
|
|
206
|
+
await client.mailbox.update(account.accountId, mailbox.mailboxId, {
|
|
207
|
+
cursorState: options.cursorState,
|
|
208
|
+
});
|
|
209
|
+
return client.mailbox.get(account.accountId, mailbox.mailboxId);
|
|
210
|
+
}
|
|
211
|
+
return mailbox;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const siblingFolder = async (path: string): Promise<MailboxItem> => {
|
|
215
|
+
const sibling = await client.account.create({
|
|
216
|
+
accountConfigId,
|
|
217
|
+
username: "person-too@example.com",
|
|
218
|
+
email: "person-too@example.com",
|
|
219
|
+
authType: AccountAuthType.Password,
|
|
220
|
+
passwordHash: JSON.stringify(serializeEncryptedPayload(password)),
|
|
221
|
+
imapHost: "imap.example.com",
|
|
222
|
+
imapPort: 993,
|
|
223
|
+
imapTls: true,
|
|
224
|
+
imapStartTls: false,
|
|
225
|
+
isActive: true,
|
|
226
|
+
connectionState: ConnectionState.Authenticated,
|
|
227
|
+
});
|
|
228
|
+
const created = await client.mailbox.create({
|
|
229
|
+
accountId: sibling.accountId,
|
|
230
|
+
namespacePrefix: "",
|
|
231
|
+
hierarchyDelimiter: "/",
|
|
232
|
+
fullPath: path,
|
|
233
|
+
uidValidity: 1,
|
|
234
|
+
uidNext: 1,
|
|
235
|
+
highestModseq: "0",
|
|
236
|
+
messageCount: 0,
|
|
237
|
+
unseenCount: 0,
|
|
238
|
+
deletedCount: 0,
|
|
239
|
+
totalSize: 0,
|
|
240
|
+
lastSyncUid: 0,
|
|
241
|
+
highWaterMarkUid: 0,
|
|
242
|
+
lastMessageSyncAt: 0,
|
|
243
|
+
syncStatus: "synced",
|
|
244
|
+
});
|
|
245
|
+
if (created.outcome !== "Created") {
|
|
246
|
+
throw new Error(`${path} could not be created: ${created.outcome}`);
|
|
247
|
+
}
|
|
248
|
+
return created.mailbox;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const message = async (
|
|
252
|
+
mailbox: MailboxItem,
|
|
253
|
+
options: { messageIdHeader?: string } = {},
|
|
254
|
+
): Promise<SeededMessage> => {
|
|
255
|
+
const messageIdHeader =
|
|
256
|
+
options.messageIdHeader ?? `<${randomUUID()}@example.com>`;
|
|
257
|
+
const uid = imap.deliver(mailbox.fullPath, mail(messageIdHeader));
|
|
258
|
+
const baseline = {
|
|
259
|
+
connections: imap.connections,
|
|
260
|
+
commands: imap.log.length,
|
|
261
|
+
};
|
|
262
|
+
await syncMessages(
|
|
263
|
+
{
|
|
264
|
+
type: "SYNC_MESSAGES",
|
|
265
|
+
eventId: randomUUID(),
|
|
266
|
+
timestamp: Date.now(),
|
|
267
|
+
accountId: account.accountId,
|
|
268
|
+
mailboxId: mailbox.mailboxId,
|
|
269
|
+
},
|
|
270
|
+
capturingLogger([]),
|
|
271
|
+
connectionFactory,
|
|
272
|
+
);
|
|
273
|
+
imap.connections = baseline.connections;
|
|
274
|
+
imap.log.length = baseline.commands;
|
|
275
|
+
const synced = (
|
|
276
|
+
await client.message.listAllByMailbox(mailbox.mailboxId)
|
|
277
|
+
).find((row) => row.uid === uid);
|
|
278
|
+
if (!synced)
|
|
279
|
+
throw new Error(`uid ${uid} in ${mailbox.fullPath} did not sync`);
|
|
280
|
+
const [threadMessage] = await client.threadMessage.findAllByMessageId(
|
|
281
|
+
accountConfigId,
|
|
282
|
+
synced.messageId,
|
|
283
|
+
);
|
|
284
|
+
if (!threadMessage)
|
|
285
|
+
throw new Error(`uid ${uid} synced without a listing row`);
|
|
286
|
+
return {
|
|
287
|
+
messageId: synced.messageId,
|
|
288
|
+
uid,
|
|
289
|
+
messageIdHeader,
|
|
290
|
+
threadMessageId: threadMessage.threadMessageId,
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const row = async (messageId: string): Promise<MessageItem | undefined> =>
|
|
295
|
+
(await client.message.get([messageId]))[0];
|
|
296
|
+
|
|
297
|
+
const threadRows = async (messageId: string) =>
|
|
298
|
+
(
|
|
299
|
+
await client.threadMessage.findAllByMessageId(accountConfigId, messageId)
|
|
300
|
+
).map((tm) => ({
|
|
301
|
+
mailboxId: tm.mailboxId,
|
|
302
|
+
uid: tm.uid,
|
|
303
|
+
isDeleted: tm.isDeleted,
|
|
304
|
+
}));
|
|
305
|
+
|
|
306
|
+
const queued = (): Array<Record<string, unknown>> =>
|
|
307
|
+
queue.sent.map((event) => event.body);
|
|
308
|
+
|
|
309
|
+
const refuseSends = (error: Error | undefined): void => {
|
|
310
|
+
queue.answer(async () => {
|
|
311
|
+
if (error) throw error;
|
|
312
|
+
return {};
|
|
313
|
+
});
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const draft = async (
|
|
317
|
+
attachment?: Buffer,
|
|
318
|
+
): Promise<{ outbox: OutboxMessageItem; attachmentId?: string }> => {
|
|
319
|
+
const outbox = await client.outboxQueue.createDraft({
|
|
320
|
+
accountId: account.accountId,
|
|
321
|
+
accountConfigId,
|
|
322
|
+
fromAddress: "person@example.com",
|
|
323
|
+
fromName: "Person",
|
|
324
|
+
toAddresses: ["friend@example.com"],
|
|
325
|
+
subject: "Quarterly numbers",
|
|
326
|
+
textBody: "See you Thursday.",
|
|
327
|
+
});
|
|
328
|
+
if (!attachment) return { outbox };
|
|
329
|
+
const minted = await client.outboxAttachment.mint({
|
|
330
|
+
accountConfigId,
|
|
331
|
+
outboxMessageId: outbox.outboxMessageId,
|
|
332
|
+
filename: "numbers.csv",
|
|
333
|
+
contentType: "text/csv",
|
|
334
|
+
sizeBytes: attachment.length,
|
|
335
|
+
});
|
|
336
|
+
if (minted.outcome !== "Minted") throw new Error("the upload was refused");
|
|
337
|
+
const attachmentId = minted.reservation.outboxAttachmentId;
|
|
338
|
+
await client.storage.storeOutboxAttachment({
|
|
339
|
+
accountConfigId,
|
|
340
|
+
accountId: account.accountId,
|
|
341
|
+
outboxMessageId: outbox.outboxMessageId,
|
|
342
|
+
outboxAttachmentId: attachmentId,
|
|
343
|
+
content: attachment,
|
|
344
|
+
});
|
|
345
|
+
const completed = await client.outboxAttachment.complete({
|
|
346
|
+
accountConfigId,
|
|
347
|
+
outboxMessageId: outbox.outboxMessageId,
|
|
348
|
+
outboxAttachmentId: attachmentId,
|
|
349
|
+
});
|
|
350
|
+
assert.equal(completed.outcome, "Completed");
|
|
351
|
+
return { outbox, attachmentId };
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
const scope = () => {
|
|
355
|
+
let open: ReturnType<FakeImapServer["connection"]> | undefined;
|
|
356
|
+
return {
|
|
357
|
+
getConnection: async () => {
|
|
358
|
+
open ??= imap.connection();
|
|
359
|
+
return open;
|
|
360
|
+
},
|
|
361
|
+
disconnect: async () => {
|
|
362
|
+
open = undefined;
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
const connectionFactory = (): ManagedConnectionFactory => {
|
|
368
|
+
let open: ReturnType<FakeImapServer["connection"]> | undefined;
|
|
369
|
+
return {
|
|
370
|
+
getConnection: () => {
|
|
371
|
+
open ??= imap.connection();
|
|
372
|
+
return open;
|
|
373
|
+
},
|
|
374
|
+
close: async () => {
|
|
375
|
+
open = undefined;
|
|
376
|
+
},
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
return {
|
|
381
|
+
client,
|
|
382
|
+
imap,
|
|
383
|
+
account,
|
|
384
|
+
logs,
|
|
385
|
+
log: capturingLogger(logs),
|
|
386
|
+
folder,
|
|
387
|
+
siblingFolder,
|
|
388
|
+
message,
|
|
389
|
+
row,
|
|
390
|
+
threadRows,
|
|
391
|
+
queued,
|
|
392
|
+
refuseSends,
|
|
393
|
+
queue,
|
|
394
|
+
draft,
|
|
395
|
+
scope,
|
|
396
|
+
connectionFactory,
|
|
397
|
+
};
|
|
398
|
+
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import type {
|
|
4
|
+
IMailboxRepository,
|
|
5
|
+
IMailboxSpecialUseRepository,
|
|
6
|
+
MailboxItem,
|
|
7
|
+
} from "@remit/data-ports";
|
|
8
|
+
import { deriveThreadId } from "@remit/data-ports/id";
|
|
9
|
+
import {
|
|
10
|
+
AddressRepo,
|
|
11
|
+
DrizzleEnvelopeRepository,
|
|
12
|
+
DrizzleMessageRepository,
|
|
13
|
+
DrizzleThreadMessageRepository,
|
|
14
|
+
SearchIndex,
|
|
15
|
+
SyncWarningRepo,
|
|
16
|
+
} from "@remit/drizzle-service";
|
|
17
|
+
import { createShippedSqliteDb } from "@remit/drizzle-service/test-sqlite";
|
|
18
|
+
import { MessageSyncService, SyncWarningService } from "@remit/mailbox-service";
|
|
19
|
+
import type { ImapMessage } from "@remit/mailbox-service/types";
|
|
20
|
+
|
|
21
|
+
const ACCOUNT = "acct-1";
|
|
22
|
+
const CONFIG = "cfg-1";
|
|
23
|
+
const MAILBOX = { mailboxId: "mbx-1", fullPath: "INBOX" } as MailboxItem;
|
|
24
|
+
const ROLES = {
|
|
25
|
+
junkMailboxId: null,
|
|
26
|
+
trashMailboxId: null,
|
|
27
|
+
configJunkRoles: { junkMailboxIds: [], trashMailboxIds: [] },
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const message = (
|
|
31
|
+
uid: number,
|
|
32
|
+
messageId: string,
|
|
33
|
+
inReplyTo: string,
|
|
34
|
+
references?: string[],
|
|
35
|
+
): ImapMessage =>
|
|
36
|
+
({
|
|
37
|
+
uid,
|
|
38
|
+
seq: uid,
|
|
39
|
+
size: 100,
|
|
40
|
+
internalDate: new Date(uid * 1000),
|
|
41
|
+
flags: [],
|
|
42
|
+
references,
|
|
43
|
+
envelope: {
|
|
44
|
+
date: new Date(uid * 1000).toISOString(),
|
|
45
|
+
messageId,
|
|
46
|
+
subject: `Subject ${uid}`,
|
|
47
|
+
from: [{ name: "Sender", mailbox: "sender", host: "example.com" }],
|
|
48
|
+
sender: [],
|
|
49
|
+
replyTo: [],
|
|
50
|
+
to: [],
|
|
51
|
+
cc: [],
|
|
52
|
+
bcc: [],
|
|
53
|
+
inReplyTo,
|
|
54
|
+
},
|
|
55
|
+
}) as unknown as ImapMessage;
|
|
56
|
+
|
|
57
|
+
const PARENT = message(1, "<p@example.com>", "<a@example.com>", [
|
|
58
|
+
"<a@example.com>",
|
|
59
|
+
]);
|
|
60
|
+
const REPLY = message(2, "<r@example.com>", "<p@example.com>");
|
|
61
|
+
|
|
62
|
+
const syncInOrder = async (
|
|
63
|
+
messages: ImapMessage[],
|
|
64
|
+
): Promise<{ threadIds: (messageId: string) => string[] }> => {
|
|
65
|
+
const { db, sqlite } = createShippedSqliteDb();
|
|
66
|
+
const typed = db as unknown as ConstructorParameters<
|
|
67
|
+
typeof DrizzleMessageRepository
|
|
68
|
+
>[0];
|
|
69
|
+
const service = new MessageSyncService(
|
|
70
|
+
{} as never,
|
|
71
|
+
{} as IMailboxRepository,
|
|
72
|
+
{} as IMailboxSpecialUseRepository,
|
|
73
|
+
new DrizzleMessageRepository(typed, new SearchIndex(typed, typed)),
|
|
74
|
+
new DrizzleEnvelopeRepository(typed),
|
|
75
|
+
new AddressRepo(db as never),
|
|
76
|
+
new DrizzleThreadMessageRepository(db, new SearchIndex(db, db)),
|
|
77
|
+
new SyncWarningService(new SyncWarningRepo(db as never)),
|
|
78
|
+
);
|
|
79
|
+
const save = (
|
|
80
|
+
service as unknown as {
|
|
81
|
+
saveMessage: (...args: unknown[]) => Promise<unknown>;
|
|
82
|
+
}
|
|
83
|
+
).saveMessage.bind(service);
|
|
84
|
+
for (const msg of messages) {
|
|
85
|
+
await save(MAILBOX, ACCOUNT, CONFIG, msg, ROLES, {
|
|
86
|
+
departed: new Set(),
|
|
87
|
+
settled: new Set(),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
threadIds: (messageIdHeader) =>
|
|
92
|
+
(
|
|
93
|
+
sqlite
|
|
94
|
+
.prepare(
|
|
95
|
+
"SELECT thread_id FROM thread_message WHERE message_id_header = ?",
|
|
96
|
+
)
|
|
97
|
+
.all(messageIdHeader) as { thread_id: string }[]
|
|
98
|
+
).map((row) => row.thread_id),
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
describe("a reply naming only its parent, which is itself a reply", () => {
|
|
103
|
+
const rootThread = deriveThreadId(CONFIG, "<a@example.com>");
|
|
104
|
+
|
|
105
|
+
it("joins the root's thread when the parent synced first", async () => {
|
|
106
|
+
const { threadIds } = await syncInOrder([PARENT, REPLY]);
|
|
107
|
+
assert.deepEqual(threadIds("<r@example.com>"), [rootThread]);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("joins the root's thread when it synced before its parent, and stays there on a re-save", async () => {
|
|
111
|
+
const { threadIds } = await syncInOrder([REPLY, PARENT, REPLY]);
|
|
112
|
+
assert.deepEqual(threadIds("<r@example.com>"), [rootThread]);
|
|
113
|
+
assert.deepEqual(threadIds("<p@example.com>"), [rootThread]);
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -14,6 +14,7 @@ import type { AccountItem } from "@remit/data-ports";
|
|
|
14
14
|
import { AccountAuthType, ConnectionState } from "@remit/domain-enums";
|
|
15
15
|
import { AccountRepo } from "@remit/drizzle-service";
|
|
16
16
|
import { createShippedSqliteDb } from "@remit/drizzle-service/test-sqlite";
|
|
17
|
+
import { noopLogger } from "@remit/logger";
|
|
17
18
|
import { RefreshTokenError } from "@remit/mail-oauth-service";
|
|
18
19
|
import { MailConnectionError } from "@remit/mailbox-service/types";
|
|
19
20
|
import type { SecretsService } from "@remit/secrets-service";
|
|
@@ -23,16 +24,6 @@ import {
|
|
|
23
24
|
} from "./with-oauth-lifecycle.js";
|
|
24
25
|
import { buildLifecycleDeps } from "./with-oauth-lifecycle-deps.js";
|
|
25
26
|
|
|
26
|
-
const silentLogger = {
|
|
27
|
-
info: () => {},
|
|
28
|
-
warn: () => {},
|
|
29
|
-
error: () => {},
|
|
30
|
-
debug: () => {},
|
|
31
|
-
trace: () => {},
|
|
32
|
-
fatal: () => {},
|
|
33
|
-
child: () => silentLogger,
|
|
34
|
-
} as never;
|
|
35
|
-
|
|
36
27
|
const secrets = {
|
|
37
28
|
decrypt: async () => "decrypted",
|
|
38
29
|
encrypt: async () => ({}) as never,
|
|
@@ -76,7 +67,7 @@ const account = async (): Promise<AccountItem> =>
|
|
|
76
67
|
before(() => {
|
|
77
68
|
const db = createShippedSqliteDb();
|
|
78
69
|
close = db.close;
|
|
79
|
-
repo = new AccountRepo(db.db);
|
|
70
|
+
repo = new AccountRepo(db.db, db.db);
|
|
80
71
|
});
|
|
81
72
|
|
|
82
73
|
after(() => {
|
|
@@ -87,7 +78,7 @@ describe("the reason an account card reads back", () => {
|
|
|
87
78
|
it("keeps the refusal the mail server gave", async () => {
|
|
88
79
|
const created = await account();
|
|
89
80
|
|
|
90
|
-
await withOAuthLifecycle(deps(), created,
|
|
81
|
+
await withOAuthLifecycle(deps(), created, noopLogger, async () => {
|
|
91
82
|
throw new MailConnectionError("auth", REFUSAL);
|
|
92
83
|
});
|
|
93
84
|
|
|
@@ -107,7 +98,7 @@ describe("the reason an account card reads back", () => {
|
|
|
107
98
|
await withOAuthLifecycle(
|
|
108
99
|
deps(),
|
|
109
100
|
await repo.get(created.accountId),
|
|
110
|
-
|
|
101
|
+
noopLogger,
|
|
111
102
|
async () => {
|
|
112
103
|
throw new RefreshTokenError({
|
|
113
104
|
kind: "reauth-required",
|
|
@@ -128,7 +119,7 @@ describe("the reason an account card reads back", () => {
|
|
|
128
119
|
it("stores a chatty refusal at a length a card can hold", async () => {
|
|
129
120
|
const created = await account();
|
|
130
121
|
|
|
131
|
-
await withOAuthLifecycle(deps(), created,
|
|
122
|
+
await withOAuthLifecycle(deps(), created, noopLogger, async () => {
|
|
132
123
|
throw new MailConnectionError("auth", "x".repeat(4000));
|
|
133
124
|
});
|
|
134
125
|
|
|
@@ -136,3 +127,136 @@ describe("the reason an account card reads back", () => {
|
|
|
136
127
|
assert.equal(stored.lastError?.length, 500);
|
|
137
128
|
});
|
|
138
129
|
});
|
|
130
|
+
|
|
131
|
+
describe("which failures stop the work, and what the account row says after", () => {
|
|
132
|
+
const passwordAccount = (passwordHash?: string): Promise<AccountItem> =>
|
|
133
|
+
repo.create({
|
|
134
|
+
accountConfigId: "cfg-1",
|
|
135
|
+
username: "person@example.com",
|
|
136
|
+
email: "person@example.com",
|
|
137
|
+
authType: AccountAuthType.Password,
|
|
138
|
+
passwordHash,
|
|
139
|
+
imapHost: "imap.example.com",
|
|
140
|
+
imapPort: 993,
|
|
141
|
+
imapTls: true,
|
|
142
|
+
imapStartTls: false,
|
|
143
|
+
isActive: true,
|
|
144
|
+
connectionState: ConnectionState.Authenticated,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("runs nothing for an account that has to sign in again", async () => {
|
|
148
|
+
const created = await account();
|
|
149
|
+
await repo.update(created.accountId, {
|
|
150
|
+
connectionState: ConnectionState.ReauthRequired,
|
|
151
|
+
});
|
|
152
|
+
let worked = false;
|
|
153
|
+
|
|
154
|
+
await withOAuthLifecycle(
|
|
155
|
+
deps(),
|
|
156
|
+
await repo.get(created.accountId),
|
|
157
|
+
noopLogger,
|
|
158
|
+
async () => {
|
|
159
|
+
worked = true;
|
|
160
|
+
},
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
assert.equal(worked, false);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// Issue #1120: a password account with nothing stored can only fail, and a
|
|
167
|
+
// failing batch item fences the account's FIFO group.
|
|
168
|
+
it("acks a password account that stores no password and says the credential is missing", async () => {
|
|
169
|
+
const created = await passwordAccount();
|
|
170
|
+
let worked = false;
|
|
171
|
+
|
|
172
|
+
await withOAuthLifecycle(
|
|
173
|
+
buildLifecycleDeps(secrets, repo),
|
|
174
|
+
created,
|
|
175
|
+
noopLogger,
|
|
176
|
+
async () => {
|
|
177
|
+
worked = true;
|
|
178
|
+
},
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
assert.equal(worked, false);
|
|
182
|
+
assert.equal(
|
|
183
|
+
(await repo.get(created.accountId)).connectionState,
|
|
184
|
+
ConnectionState.CredentialsMissing,
|
|
185
|
+
);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("acks an OAuth account that holds no refresh token and asks for a sign-in", async () => {
|
|
189
|
+
const created = await repo.create({
|
|
190
|
+
accountConfigId: "cfg-1",
|
|
191
|
+
username: "matthijs@example.com",
|
|
192
|
+
email: "matthijs@example.com",
|
|
193
|
+
authType: AccountAuthType.OauthMicrosoft,
|
|
194
|
+
imapHost: "outlook.office365.com",
|
|
195
|
+
imapPort: 993,
|
|
196
|
+
imapTls: true,
|
|
197
|
+
imapStartTls: false,
|
|
198
|
+
isActive: true,
|
|
199
|
+
connectionState: ConnectionState.Authenticated,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
await withOAuthLifecycle(
|
|
203
|
+
buildLifecycleDeps(secrets, repo),
|
|
204
|
+
created,
|
|
205
|
+
noopLogger,
|
|
206
|
+
async () => {},
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
assert.equal(
|
|
210
|
+
(await repo.get(created.accountId)).connectionState,
|
|
211
|
+
ConnectionState.ReauthRequired,
|
|
212
|
+
);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// A password that stopped working is the user's to fix in settings; the
|
|
216
|
+
// state flip is reserved for OAuth, where a sign-in is the fix.
|
|
217
|
+
for (const [name, error] of [
|
|
218
|
+
["a refused password", new MailConnectionError("auth", "auth failed")],
|
|
219
|
+
["a network failure", new MailConnectionError("network", "timeout")],
|
|
220
|
+
["any other error", new Error("boom")],
|
|
221
|
+
] as const) {
|
|
222
|
+
it(`redelivers ${name} on a password account and leaves its state alone`, async () => {
|
|
223
|
+
const created = await passwordAccount('{"ciphertext":"x"}');
|
|
224
|
+
|
|
225
|
+
await assert.rejects(
|
|
226
|
+
withOAuthLifecycle(deps(), created, noopLogger, async () => {
|
|
227
|
+
throw error;
|
|
228
|
+
}),
|
|
229
|
+
error,
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
assert.equal(
|
|
233
|
+
(await repo.get(created.accountId)).connectionState,
|
|
234
|
+
ConnectionState.Authenticated,
|
|
235
|
+
);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
it("redelivers a transient token failure and leaves the state alone", async () => {
|
|
240
|
+
const created = await account();
|
|
241
|
+
|
|
242
|
+
await assert.rejects(
|
|
243
|
+
withOAuthLifecycle(
|
|
244
|
+
{
|
|
245
|
+
...deps(),
|
|
246
|
+
resolveCredentials: async () => {
|
|
247
|
+
throw new RefreshTokenError({ kind: "transient", code: "503" });
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
created,
|
|
251
|
+
noopLogger,
|
|
252
|
+
async () => {},
|
|
253
|
+
),
|
|
254
|
+
/transient/,
|
|
255
|
+
);
|
|
256
|
+
|
|
257
|
+
assert.equal(
|
|
258
|
+
(await repo.get(created.accountId)).connectionState,
|
|
259
|
+
ConnectionState.Authenticated,
|
|
260
|
+
);
|
|
261
|
+
});
|
|
262
|
+
});
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
|
|
29
29
|
import type { AccountItem } from "@remit/data-ports";
|
|
30
30
|
import { AccountAuthType, ConnectionState } from "@remit/domain-enums";
|
|
31
|
-
import type { Logger } from "@remit/logger
|
|
31
|
+
import type { Logger } from "@remit/logger";
|
|
32
32
|
import { RefreshTokenError } from "@remit/mail-oauth-service";
|
|
33
33
|
import {
|
|
34
34
|
type AccountCredentialsDeps,
|