domma-cms 1.28.4 → 1.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/admin/js/lib/contacts-arrange.js +1 -1
  3. package/docs/DommaFeatures.md +15 -9
  4. package/docs/plugin-development.md +1 -1
  5. package/package.json +4 -1
  6. package/plugins/_lib/admin/mail/body-menu.js +2 -0
  7. package/plugins/_lib/admin/mail/cms-host.js +22 -0
  8. package/plugins/_lib/admin/mail/compose-window.js +1027 -1021
  9. package/plugins/_lib/admin/mail/contacts.js +10 -8
  10. package/plugins/_lib/admin/mail/diagnostics-section.js +2 -0
  11. package/plugins/_lib/admin/mail/drag-drop.js +46 -0
  12. package/plugins/_lib/admin/mail/folder-tree.js +2 -0
  13. package/plugins/_lib/admin/mail/font-controls.js +6 -4
  14. package/plugins/_lib/admin/mail/fonts.js +1 -1
  15. package/plugins/_lib/admin/mail/host-context.js +87 -0
  16. package/plugins/_lib/admin/mail/identity.js +2 -0
  17. package/plugins/_lib/admin/mail/image-senders-section.js +2 -0
  18. package/plugins/_lib/admin/mail/keyboard.js +2 -0
  19. package/plugins/_lib/admin/mail/mail.css +1 -1
  20. package/plugins/_lib/admin/mail/mail.html +4 -0
  21. package/plugins/_lib/admin/mail/message-actions.js +2 -0
  22. package/plugins/_lib/admin/mail/oauth-panel.js +2 -0
  23. package/plugins/_lib/admin/mail/panes.js +2 -0
  24. package/plugins/_lib/admin/mail/reader-kit.js +2 -0
  25. package/plugins/_lib/admin/mail/reader-runtime.js +6534 -0
  26. package/plugins/_lib/admin/mail/reader-view.js +9 -6380
  27. package/plugins/_lib/admin/mail/resizable.js +2 -0
  28. package/plugins/_lib/admin/mail/restore-spam.js +13 -0
  29. package/plugins/_lib/admin/mail/rules.js +14 -0
  30. package/plugins/_lib/admin/mail/scheduling.js +4 -1
  31. package/plugins/_lib/admin/mail/section-kit.js +4 -1
  32. package/plugins/_lib/admin/mail/security-note.js +2 -0
  33. package/plugins/_lib/admin/mail/settings-section.js +11 -10
  34. package/plugins/_lib/admin/mail/templates.js +5 -2
  35. package/plugins/_lib/admin/mail/threads.js +2 -0
  36. package/plugins/_lib/admin/mail/vacation.js +16 -2
  37. package/plugins/_lib/admin/mail/when-closed.js +24 -2
  38. package/plugins/_lib/admin/ui/dates.js +2 -0
  39. package/plugins/_lib/admin/ui/resizable.js +7 -5
  40. package/plugins/_lib/contacts/mailContact.js +69 -0
  41. package/plugins/_lib/contacts/model.js +199 -0
  42. package/plugins/_lib/domma-mail-contacts.lock.json +10 -0
  43. package/plugins/_lib/domma-mail.lock.json +85 -0
  44. package/plugins/_lib/mail/accountFileStore.js +66 -0
  45. package/plugins/_lib/mail/accountRepository.js +617 -0
  46. package/plugins/_lib/mail/accountRoutes.js +130 -0
  47. package/plugins/_lib/mail/accounts.js +66 -940
  48. package/plugins/_lib/mail/automationLock.js +10 -0
  49. package/plugins/_lib/mail/bodyTokenProvider.js +36 -0
  50. package/plugins/_lib/mail/bodyTokens.js +5 -99
  51. package/plugins/_lib/mail/compose.js +5 -3
  52. package/plugins/_lib/mail/defaults.js +2 -0
  53. package/plugins/_lib/mail/envelope.js +3 -1
  54. package/plugins/_lib/mail/folderActions.js +83 -0
  55. package/plugins/_lib/mail/folderRuntime.js +109 -0
  56. package/plugins/_lib/mail/folders.js +4 -9
  57. package/plugins/_lib/mail/imapPool.js +11 -389
  58. package/plugins/_lib/mail/imapPoolRuntime.js +396 -0
  59. package/plugins/_lib/mail/mbox.js +2 -0
  60. package/plugins/_lib/mail/message-action.js +2 -0
  61. package/plugins/_lib/mail/messageSecurity.js +4 -111
  62. package/plugins/_lib/mail/messageSecurityProvider.js +116 -0
  63. package/plugins/_lib/mail/networkAddresses.js +77 -0
  64. package/plugins/_lib/mail/networkPolicy.js +62 -0
  65. package/plugins/_lib/mail/oauth.js +3 -451
  66. package/plugins/_lib/mail/oauthAccounts.js +178 -0
  67. package/plugins/_lib/mail/oauthRouteRuntime.js +282 -0
  68. package/plugins/_lib/mail/oauthRoutes.js +7 -289
  69. package/plugins/_lib/mail/oauthRuntime.js +456 -0
  70. package/plugins/_lib/mail/pollSchedule.js +2 -0
  71. package/plugins/_lib/mail/poller.js +4 -136
  72. package/plugins/_lib/mail/pollerRuntime.js +150 -0
  73. package/plugins/_lib/mail/priority.js +2 -0
  74. package/plugins/_lib/mail/publicMailbox.js +27 -0
  75. package/plugins/_lib/mail/readRoutes.js +14 -827
  76. package/plugins/_lib/mail/readRuntime.js +701 -0
  77. package/plugins/_lib/mail/render.js +2 -0
  78. package/plugins/_lib/mail/ruleRunner.js +27 -10
  79. package/plugins/_lib/mail/scheduler.js +11 -279
  80. package/plugins/_lib/mail/schedulerRuntime.js +259 -0
  81. package/plugins/_lib/mail/secretProvider.js +112 -0
  82. package/plugins/_lib/mail/secretbox.js +12 -225
  83. package/plugins/_lib/mail/send.js +21 -537
  84. package/plugins/_lib/mail/sieve.js +211 -0
  85. package/plugins/_lib/mail/sieveHost.js +24 -0
  86. package/plugins/_lib/mail/smtpService.js +553 -0
  87. package/plugins/_lib/mail/snoozeRuntime.js +60 -0
  88. package/plugins/_lib/mail/store.js +122 -64
  89. package/plugins/_lib/mail/subscriptions.js +11 -0
  90. package/plugins/_lib/mail/sync.js +64 -290
  91. package/plugins/_lib/mail/syncPlan.js +2 -0
  92. package/plugins/_lib/mail/syncRuntime.js +255 -0
  93. package/plugins/_lib/mail/syncSelection.js +2 -0
  94. package/plugins/_lib/mail/unreadBadge.js +2 -0
  95. package/plugins/_lib/mail/unsubscribe.js +2 -0
  96. package/plugins/_lib/mail/vacationRunner.js +3 -116
  97. package/plugins/_lib/mail/vacationRuntime.js +70 -0
  98. package/plugins/_lib/mail/write.js +44 -13
  99. package/server/routes/api/contacts.js +2 -196
  100. package/server/routes/api/forms.js +8 -1
  101. package/server/services/viewerSession.js +1 -1
@@ -0,0 +1,553 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/smtpService.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /**
4
+ * Sending, and keeping a copy where the rest of your clients will find it.
5
+ *
6
+ * The message is built once, as raw RFC822, and that same buffer is both sent
7
+ * and appended to Sent. Building it twice - once for the transport and once
8
+ * for the copy - is how a Sent folder ends up holding something subtly unlike
9
+ * what the recipient received.
10
+ *
11
+ * @module _lib/mail/send
12
+ */
13
+ import {createRequire} from 'node:module';
14
+
15
+ import nodemailer from 'nodemailer';
16
+
17
+ import {bareAddress, formatFrom} from '../admin/mail/identity.js';
18
+ import {describeError} from './imapPoolRuntime.js';
19
+ import {normalisePriority, priorityHeaders} from './priority.js';
20
+ import {composeFlagsHeader, COMPOSE_HEADER, normaliseMessageSource, recordMessageAction, SOURCE_HEADER} from './message-action.js';
21
+
22
+ export function createSmtpService({pinMailHost, composeOptions = () => ({}), messageSecurity, createTransport = options => nodemailer.createTransport(options)} = {}) {
23
+ if (typeof pinMailHost !== 'function' || !messageSecurity) throw new Error('SMTP requires a host policy and a message security provider.');
24
+ const {protectRaw, protectDraftRaw} = messageSecurity;
25
+ // MailComposer is not on nodemailer's public export, but it is the piece that
26
+ // turns a message object into the bytes that go on the wire - which is what a
27
+ // faithful Sent copy needs.
28
+ const MailComposer = createRequire(import.meta.url)('nodemailer/lib/mail-composer');
29
+
30
+ /**
31
+ * Turn an address list into what nodemailer expects.
32
+ *
33
+ * @param {Array<{name?: string, address?: string}>|string|undefined} list
34
+ * @returns {object[]}
35
+ */
36
+ function addresses(list) {
37
+ if (!list) return [];
38
+ if (typeof list === 'string') {
39
+ return list.split(',').map(part => ({address: part.trim()})).filter(a => a.address);
40
+ }
41
+ return list
42
+ .map(entry => (typeof entry === 'string' ? {address: entry.trim()} : entry))
43
+ .filter(entry => entry?.address);
44
+ }
45
+
46
+ /**
47
+ * Check a draft is worth trying to send.
48
+ *
49
+ * @param {object} draft
50
+ * @returns {{ok: true} | {ok: false, error: string}}
51
+ */
52
+ function validateDraft(draft, {maxAttachmentBytes = 20_000_000} = {}) {
53
+ const to = addresses(draft?.to);
54
+ const cc = addresses(draft?.cc);
55
+ const bcc = addresses(draft?.bcc);
56
+
57
+ if (!to.length && !cc.length && !bcc.length) {
58
+ return {ok: false, error: 'A message needs at least one recipient.'};
59
+ }
60
+
61
+ const bad = [...to, ...cc, ...bcc]
62
+ .map(a => a.address)
63
+ .filter(address => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address));
64
+ if (bad.length) {
65
+ return {ok: false, error: `Not a valid address: ${bad.join(', ')}`};
66
+ }
67
+
68
+ if (!String(draft?.body ?? '').trim() && !String(draft?.subject ?? '').trim()) {
69
+ return {ok: false, error: 'A message needs a subject or a body.'};
70
+ }
71
+
72
+ const attachments = draft?.attachments ?? [];
73
+ if (!Array.isArray(attachments)) {
74
+ return {ok: false, error: 'Attachments must be a list.'};
75
+ }
76
+
77
+ let total = 0;
78
+ for (const file of attachments) {
79
+ if (!file?.filename || typeof file.content !== 'string') {
80
+ return {ok: false, error: 'Every attachment needs a filename and its content.'};
81
+ }
82
+ // Base64 length maps to bytes without decoding it first, which means
83
+ // an oversized payload is refused before it is turned into memory.
84
+ total += Math.floor(file.content.length * 3 / 4);
85
+ }
86
+
87
+ if (total > maxAttachmentBytes) {
88
+ const mb = n => `${(n / 1_000_000).toFixed(1)}MB`;
89
+ return {
90
+ ok: false,
91
+ error: `Attachments total ${mb(total)}, over the ${mb(maxAttachmentBytes)} limit. Most providers refuse around 25MB, so this is better refused here than bounced later.`
92
+ };
93
+ }
94
+
95
+ return {ok: true, attachmentBytes: total};
96
+ }
97
+
98
+ /**
99
+ * Build the raw bytes of a message.
100
+ *
101
+ * `from` is the header value, display name and all. The envelope address is
102
+ * the caller's business, not this function's - see `sendMessage`.
103
+ *
104
+ * @param {object} draft
105
+ * @param {string} from
106
+ * @param {{replyTo?: string, readReceiptTo?: string, headers?: object, keepBcc?: boolean}} [options]
107
+ * @returns {Promise<Buffer>}
108
+ */
109
+ function buildRaw(draft, from, {replyTo = '', readReceiptTo = '', headers = {}, keepBcc = false} = {}) {
110
+ const composer = new MailComposer({
111
+ from,
112
+ // Only when the mailbox asks for one. An absent Reply-To means
113
+ // "answer the From address", which is what every client already does -
114
+ // setting it to the From address says the same thing in a header that
115
+ // some mailing lists then rewrite.
116
+ ...(replyTo ? {replyTo} : {}),
117
+ to: addresses(draft.to),
118
+ cc: addresses(draft.cc),
119
+ bcc: addresses(draft.bcc),
120
+ subject: draft.subject ?? '',
121
+ // Set by the caller for a QUEUED send, so that a retry after a
122
+ // failure carries the same id as the attempt before it.
123
+ //
124
+ // The claim in the store makes a send exactly-once up to the moment
125
+ // the message leaves; it cannot make SMTP exactly-once. A connection
126
+ // dropped between the terminating dot and the 250 looks identical to
127
+ // a message that was never accepted, and the only honest options are
128
+ // to risk losing it or to risk sending it twice. This takes the
129
+ // second and makes the duplicate detectable: both copies carry one
130
+ // Message-ID, which is what every receiver deduplicates on.
131
+ ...(draft.messageId ? {messageId: draft.messageId} : {}),
132
+ text: draft.body ?? '',
133
+ // Both parts when there is formatting, so the message is
134
+ // multipart/alternative: clients that render HTML get it, and those
135
+ // that do not - and anyone reading in a terminal - still get something
136
+ // written for them rather than a wall of tags.
137
+ ...(String(draft.html ?? '').trim() ? {html: draft.html} : {}),
138
+ // Threading. Present only for a reply - a forward deliberately carries
139
+ // neither, so it does not file itself into a conversation its new
140
+ // recipient has never seen.
141
+ ...(draft.inReplyTo ? {inReplyTo: draft.inReplyTo} : {}),
142
+ ...(draft.references?.length ? {references: draft.references} : {}),
143
+ // All three priority headers, or none. A recipient's client reads
144
+ // whichever one it knows, and setting only one is how a message looks
145
+ // urgent in Outlook and ordinary everywhere else. Normal sends none:
146
+ // the absence of the header IS normal.
147
+ headers: {
148
+ ...priorityHeaders(normalisePriority(draft.priority)),
149
+ // Both spellings when a receipt is wanted. `Disposition-Notification-To`
150
+ // is the standard one (RFC 8098) and `Return-Receipt-To` is what
151
+ // older clients read; sending one and not the other is how a
152
+ // receipt request works in half the world. A receipt is a request,
153
+ // not a mechanism - every client is free to ignore it, and many
154
+ // do, which is worth knowing before relying on one.
155
+ ...(readReceiptTo
156
+ ? {
157
+ 'Disposition-Notification-To': readReceiptTo,
158
+ 'Return-Receipt-To': readReceiptTo
159
+ }
160
+ : {}),
161
+ // Anything the caller must put on the wire itself. Today that is
162
+ // the away message announcing itself as automatic, which is what
163
+ // stops the responder at the far end answering it back.
164
+ ...headers
165
+ },
166
+ attachments: (draft.attachments ?? []).map(file => ({
167
+ filename: file.filename,
168
+ content: Buffer.from(file.content, 'base64'),
169
+ contentType: file.contentType
170
+ }))
171
+ });
172
+
173
+ return new Promise((resolve, reject) => {
174
+ const compiled = composer.compile();
175
+ compiled.keepBcc = keepBcc;
176
+ compiled.build((err, message) => (err ? reject(err) : resolve(message)));
177
+ });
178
+ }
179
+
180
+ /**
181
+ * Thrown to skip filing a copy, rather than checked around the whole block.
182
+ *
183
+ * The filing is already wrapped in a try/catch that treats any failure as
184
+ * "delivered but not filed", which is exactly the outcome wanted here - so
185
+ * the cheapest correct way in is through the same door.
186
+ */
187
+ class SkipFiling extends Error {}
188
+
189
+ /**
190
+ * Send a draft, and file a copy.
191
+ *
192
+ * The copy is best effort. A message that was delivered but could not be
193
+ * filed is still delivered, and failing the send at that point would invite
194
+ * someone to send it a second time.
195
+ *
196
+ * @param {{smtp: object, draft: object, pool: object, poolKey: string,
197
+ * connection: object, sentFolder: string|null}} options
198
+ * @returns {Promise<{messageId: string, accepted: string[], rejected: string[], filedTo: string|null, fileError: string|null}>}
199
+ */
200
+ async function sendMessage({
201
+ smtp, draft, pool, poolKey, connection, sentFolder = null, allowInsecureTLS = false,
202
+ replaces = null, draftsFolder = null, headers = {}, fileCopy = true, account = null, store = null
203
+ }) {
204
+ const options = composeOptions(account);
205
+
206
+ // The header carries the display name; the envelope never can. They are
207
+ // built from the same stored address so they cannot name two different
208
+ // mailboxes, but they are not the same string.
209
+ const built = await buildRaw(draft, formatFrom(smtp.from, smtp.fromName), {
210
+ replyTo: smtp.replyTo,
211
+ // Asked for per message, addressed to wherever replies would go -
212
+ // which is the Reply-To when there is one and the From otherwise.
213
+ // A receipt sent to an address the sender does not read is a receipt
214
+ // nobody sees.
215
+ readReceiptTo: draft.readReceipt
216
+ ? (smtp.replyTo || bareAddress(smtp.from))
217
+ : '',
218
+ headers
219
+ });
220
+
221
+ // Signed and/or encrypted when the message asks - after it is built and
222
+ // before it is sent, so what is sent and what is filed are one buffer, as
223
+ // ever. Encrypted, the copy in Sent is encrypted too (to the sender as
224
+ // well as the recipients), which is the point: a copy readable by anyone
225
+ // with the mailbox password would undo it.
226
+ const raw = await protectRaw({raw: built, draft, account, userId: account?.userId ?? null});
227
+
228
+ // The same setting that governs incoming TLS governs outgoing: a site
229
+ // running its own mail server with a self-signed certificate has the same
230
+ // problem in both directions, and two switches for one decision is how
231
+ // one of them ends up wrong.
232
+ // The mail server's own words never leave as the error (they say what
233
+ // listens on a port): describeError's plain text, the detail in the log.
234
+ let transport;
235
+ let info;
236
+ let attempted = false;
237
+ try {
238
+ transport = createTransport({
239
+ ...await pinnedTransport(smtp.transport, pool?.mailHostOptions),
240
+ // Secure delivery starts with this hop: STARTTLS or nothing.
241
+ ...(options.requireSecureDelivery ? {requireTLS: true} : {}),
242
+ tls: {rejectUnauthorized: !allowInsecureTLS}
243
+ });
244
+ attempted = true;
245
+ info = await transport.sendMail({
246
+ envelope: {
247
+ // Bare, always. A display name here is not decoration the server
248
+ // ignores - it is a MAIL FROM the server rejects, and `smtp.from`
249
+ // is a free-text field somebody may well have typed a name into.
250
+ from: bareAddress(smtp.from),
251
+ to: [...addresses(draft.to), ...addresses(draft.cc), ...addresses(draft.bcc)]
252
+ .map(a => a.address)
253
+ },
254
+ ...deliveryOptions(draft, options),
255
+ raw
256
+ });
257
+ } catch (err) {
258
+ const plain = plainSendError(err, {...smtp.transport, requireTLS: options.requireSecureDelivery});
259
+ const refused = Number(err.responseCode) >= 400 && Number(err.responseCode) < 600;
260
+ const beforeData = typeof err.command === 'string' && /^(CONN|EHLO|HELO|STARTTLS|AUTH|MAIL FROM|RCPT TO)/i.test(err.command);
261
+ plain.retryable = !attempted || refused || beforeData;
262
+ plain.deliveryUnknown = !plain.retryable;
263
+ throw plain;
264
+ } finally {
265
+ transport?.close();
266
+ }
267
+
268
+ const messageAction = await recordMessageAction({
269
+ source: draft.sourceMessage, account, pool, poolKey, connection, store
270
+ });
271
+
272
+ let filedTo = null;
273
+ let fileError = null;
274
+ try {
275
+ // An away message deliberately does not file. One holiday can produce
276
+ // a hundred of them, and a Sent folder that is mostly "Out of office"
277
+ // is a Sent folder nobody can find anything in - the responder keeps
278
+ // its own log instead.
279
+ if (!fileCopy) throw new SkipFiling();
280
+ const destination = await filingFolder({
281
+ pool, poolKey, connection, sentFolder,
282
+ source: options.repliesInSourceFolder && account ? draft.sourceMessage : null,
283
+ accountId: account?.id ?? null
284
+ });
285
+ if (destination) {
286
+ await pool.withClient(poolKey, connection,
287
+ client => client.append(destination, raw, ['\\Seen']));
288
+ filedTo = destination;
289
+ }
290
+ } catch (err) {
291
+ if (!(err instanceof SkipFiling)) fileError = err.message;
292
+ }
293
+
294
+ // Only once it has actually gone. A draft cleared before the send would
295
+ // be a draft lost to a rejected recipient, and the text only existed
296
+ // there.
297
+ const draftRemoved = replaces ? await discardDraft({
298
+ pool, poolKey, connection, uid: replaces, draftsFolder
299
+ }) : false;
300
+
301
+ return {
302
+ messageId: info.messageId,
303
+ accepted: info.accepted ?? [],
304
+ rejected: info.rejected ?? [],
305
+ filedTo,
306
+ fileError,
307
+ draftRemoved,
308
+ messageAction
309
+ };
310
+ }
311
+
312
+ /**
313
+ * The SMTP extras a message asks for: a delivery status notification (DSN,
314
+ * RFC 3461) when it wants a delivery receipt, and REQUIRETLS (RFC 8689) when
315
+ * the mailbox requires secure delivery.
316
+ *
317
+ * A delivery receipt is the outgoing server's to give: one that does not offer
318
+ * DSN sends the message without asking, which is the most a client can do.
319
+ * REQUIRETLS is the opposite - asked for, it must be honoured, and a server
320
+ * that cannot is refused before the message leaves (EREQUIRETLS).
321
+ *
322
+ * @param {object} draft
323
+ * @param {{requireSecureDelivery?: boolean}} options
324
+ * @returns {object}
325
+ */
326
+ function deliveryOptions(draft, options = {}) {
327
+ return {
328
+ // Headers, not the whole message, come back with the report: the
329
+ // sender has the message already, and a full copy doubles the mail.
330
+ ...(draft?.deliveryReceipt === true
331
+ ? {dsn: {ret: 'HDRS', notify: ['SUCCESS', 'FAILURE', 'DELAY']}}
332
+ : {}),
333
+ ...(options.requireSecureDelivery === true ? {requireTLSExtensionEnabled: true} : {})
334
+ };
335
+ }
336
+
337
+ /**
338
+ * Where the copy of a sent message is filed.
339
+ *
340
+ * Sent, normally. A reply goes beside the message it answers when the mailbox
341
+ * says so - the folder it was replied from, so a conversation filed under a
342
+ * project keeps both halves there. Never into Trash, Junk or Drafts (a reply
343
+ * written from the bin is not meant to live in it), nor into a folder that
344
+ * has gone, nor for another mailbox's message: those fall back to Sent.
345
+ *
346
+ * @param {{folders: Array<{path: string, specialUse?: string}>, sentFolder?: string|null,
347
+ * source?: object|null, accountId?: string|null}} input
348
+ * @returns {string|null}
349
+ */
350
+ function chooseFilingFolder({folders = [], sentFolder = null, source = null, accountId = null}) {
351
+ const sent = sentFolder ?? folders.find(box => box.specialUse === '\\Sent')?.path ?? null;
352
+ const from = normaliseMessageSource(source);
353
+ if (!from || from.action !== 'reply' || !accountId || from.accountId !== accountId) return sent;
354
+ const box = folders.find(entry => entry.path === from.folder);
355
+ if (!box || ['\\Trash', '\\Junk', '\\Drafts'].includes(box.specialUse)) return sent;
356
+ return box.path;
357
+ }
358
+
359
+ /**
360
+ * The folder list, then `chooseFilingFolder`. Skips the listing when there is
361
+ * nothing to choose: Sent is already known and this is not a reply to file
362
+ * elsewhere.
363
+ *
364
+ * @returns {Promise<string|null>}
365
+ */
366
+ async function filingFolder({pool, poolKey, connection, sentFolder, source, accountId}) {
367
+ if (sentFolder && !source) return sentFolder;
368
+ const folders = await pool.withClient(poolKey, connection, client => client.list());
369
+ return chooseFilingFolder({folders, sentFolder, source, accountId});
370
+ }
371
+
372
+ /**
373
+ * Take a superseded draft out of the Drafts folder.
374
+ *
375
+ * Expunged rather than moved to Trash, which is the one place this codebase
376
+ * departs from "deleting means Trash": the draft has just been sent, so the
377
+ * message still exists in Sent, and putting a copy of it in the bin as well
378
+ * leaves someone three copies of one email to reason about.
379
+ *
380
+ * Best-effort. A leftover draft is untidy; a send reported as failed because
381
+ * the tidying did is worse.
382
+ *
383
+ * @param {{pool: object, poolKey: string, connection: object, uid: number,
384
+ * draftsFolder?: string|null}} options
385
+ * @returns {Promise<boolean>}
386
+ */
387
+ async function discardDraft({pool, poolKey, connection, uid, draftsFolder = null}) {
388
+ try {
389
+ const destination = draftsFolder
390
+ ?? await findSpecialFolder(pool, poolKey, connection, '\\Drafts');
391
+ if (!destination) return false;
392
+
393
+ await pool.withMailbox(poolKey, connection, destination, async (client) => {
394
+ await client.messageFlagsAdd({uid: String(uid)}, ['\\Deleted'], {uid: true});
395
+ await client.messageDelete({uid: String(uid)}, {uid: true});
396
+ }, {writable: true});
397
+ return true;
398
+ } catch {
399
+ return false;
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Save a draft to the Drafts folder.
405
+ *
406
+ * Built with the same code that builds a sendable message, so what is stored
407
+ * is what would have gone out. Saved with `\\Draft` so other clients treat it
408
+ * as editable rather than as received mail.
409
+ *
410
+ * A previous version is replaced rather than accumulated: editing a draft four
411
+ * times should leave one draft, not four. The old copy is removed only after
412
+ * the new one is stored, so an interruption loses nothing.
413
+ *
414
+ * @param {{draft: object, from: string, replyTo?: string, pool: object, poolKey: string,
415
+ * connection: object, draftsFolder?: string|null, replaces?: number|null}} options
416
+ * @returns {Promise<{savedTo: string, uid: number|null, replaced: number|null}>}
417
+ */
418
+ async function saveDraft({
419
+ draft, from, replyTo = '', pool, poolKey, connection, draftsFolder = null, replaces = null, account = null
420
+ }) {
421
+ // Written into the draft, not applied when it is eventually sent: a draft
422
+ // opened on the phone should show the same headers it will go out with.
423
+ const source = normaliseMessageSource(draft.sourceMessage);
424
+ const flags = composeFlagsHeader(draft);
425
+ const raw = await buildRaw(draft, from, {
426
+ keepBcc: true,
427
+ replyTo,
428
+ readReceiptTo: draft.readReceipt ? (replyTo || bareAddress(from)) : '',
429
+ // Private draft metadata: it is omitted from SMTP and the Sent copy.
430
+ headers: {
431
+ ...(source ? {[SOURCE_HEADER]: Buffer.from(JSON.stringify(source)).toString('base64url')} : {}),
432
+ ...(flags ? {[COMPOSE_HEADER]: flags} : {})
433
+ }
434
+ });
435
+
436
+ const destination = draftsFolder ?? await findSpecialFolder(pool, poolKey, connection, '\\Drafts');
437
+ if (!destination) {
438
+ throw new Error('This server has no Drafts folder to save into.');
439
+ }
440
+
441
+ // A message that is to be encrypted is not left readable in Drafts: it
442
+ // is encrypted to the sender alone, and opened again when reopened.
443
+ const stored = await protectDraftRaw({raw, draft, account, userId: account?.userId ?? null});
444
+
445
+ const appended = await pool.withClient(poolKey, connection,
446
+ client => client.append(destination, stored, ['\\Draft', '\\Seen']));
447
+
448
+ // Only now is the previous version expendable.
449
+ let replaced = null;
450
+ if (replaces) {
451
+ try {
452
+ await pool.withMailbox(poolKey, connection, destination, async (client) => {
453
+ await client.messageFlagsAdd({uid: String(replaces)}, ['\\Deleted'], {uid: true});
454
+ await client.messageDelete({uid: String(replaces)}, {uid: true});
455
+ }, {writable: true});
456
+ replaced = replaces;
457
+ } catch {
458
+ // The new draft is saved; a leftover old one is untidy, not broken.
459
+ }
460
+ }
461
+
462
+ return {savedTo: destination, uid: appended?.uid ?? null, replaced};
463
+ }
464
+
465
+ /**
466
+ * Find a folder by its SPECIAL-USE attribute.
467
+ *
468
+ * @param {object} pool
469
+ * @param {string} poolKey
470
+ * @param {object} connection
471
+ * @param {string} use
472
+ * @returns {Promise<string|null>}
473
+ */
474
+ async function findSpecialFolder(pool, poolKey, connection, use) {
475
+ const boxes = await pool.withClient(poolKey, connection, client => client.list());
476
+ return boxes.find(box => box.specialUse === use)?.path ?? null;
477
+ }
478
+
479
+ /**
480
+ * A send failure as plain words. Our own errors (a refused host, a mailbox that
481
+ * needs signing in again) pass as they are; anything from the server or the
482
+ * library becomes describeError()'s text, keeping `code` so a caller can still
483
+ * tell an authentication failure from the rest.
484
+ *
485
+ * @param {Error} err
486
+ * @param {object} transportConfig
487
+ * @returns {Error}
488
+ */
489
+ function plainSendError(err, transportConfig = {}) {
490
+ if (!err || err.needsReconnect || err.mailHostRefused || err.name === 'MailKeyError') return err;
491
+ // Asked for, and the outgoing server could not promise it - said in words,
492
+ // because "not sent" is the right answer and the reason is the useful part.
493
+ // A certificate problem is NOT this - it keeps describeError's own words.
494
+ if (err.code === 'EREQUIRETLS'
495
+ || (err.code === 'ETLS' && transportConfig.requireTLS && /upgrading connection with STARTTLS/i.test(err.message ?? ''))) {
496
+ const plain = new Error('Not sent: this mailbox requires secure delivery, and its outgoing server '
497
+ + 'cannot promise it (it does not offer REQUIRETLS over an encrypted connection). '
498
+ + 'Switch "Require secure delivery" off in Settings > Composing to send it normally.');
499
+ plain.code = 'EREQUIRETLS';
500
+ return plain;
501
+ }
502
+ const plain = new Error(describeError(err, transportConfig));
503
+ if (err.code) plain.code = err.code;
504
+ if (err.responseCode) plain.responseCode = err.responseCode;
505
+ if (err.retryable !== undefined) plain.retryable = err.retryable;
506
+ if (err.deliveryUnknown !== undefined) plain.deliveryUnknown = err.deliveryUnknown;
507
+ return plain;
508
+ }
509
+
510
+ /**
511
+ * A mailbox's transport settings with the host checked and pinned: connect to
512
+ * the address hostGuard.js checked, keep the name for TLS. Throws when the
513
+ * host or port is refused, or the name does not resolve.
514
+ *
515
+ * @param {object} transportConfig - {host, port, ...}
516
+ * @param {{allowPrivate?: boolean}} [guard] - the plugin's allowPrivateMailHosts, when the caller has it
517
+ * @returns {Promise<object>}
518
+ */
519
+ async function pinnedTransport(transportConfig, guard = {}) {
520
+ const port = Number(transportConfig.port) || (transportConfig.secure ? 465 : 587);
521
+ const {address, servername} = await pinMailHost(transportConfig.host, port, {kind: 'smtp', ...(guard || {})});
522
+ return {...transportConfig, port, host: address, ...(servername && {servername})};
523
+ }
524
+
525
+ /**
526
+ * Try the outgoing server without sending anything.
527
+ *
528
+ * @param {object} transportConfig
529
+ * @returns {Promise<{ok: boolean, error?: string}>}
530
+ */
531
+ async function verifySmtp(transportConfig, allowInsecureTLS = false, guard = undefined) {
532
+ let pinned;
533
+ try {
534
+ pinned = await pinnedTransport(transportConfig, guard);
535
+ } catch (err) {
536
+ return {ok: false, error: describeError(err, transportConfig)};
537
+ }
538
+ const transport = createTransport({
539
+ ...pinned,
540
+ connectionTimeout: 10_000,
541
+ tls: {rejectUnauthorized: !allowInsecureTLS}
542
+ });
543
+ try {
544
+ await transport.verify();
545
+ return {ok: true};
546
+ } catch (err) {
547
+ return {ok: false, error: describeError(err, transportConfig)};
548
+ } finally {
549
+ transport.close();
550
+ }
551
+ }
552
+ return {validateDraft, sendMessage, deliveryOptions, chooseFilingFolder, discardDraft, saveDraft, plainSendError, pinnedTransport, verifySmtp};
553
+ }
@@ -0,0 +1,60 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/snoozeRuntime.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ import {safeWritePool, moveMessage} from './write.js';
4
+
5
+ const attention = message => Object.assign(new Error(message), {snoozeAttention: true});
6
+ export const validSnoozePath = value => typeof value === 'string' && value.length > 0 && value.length <= 500 && !/[\x00-\x1f\x7f]/.test(value);
7
+ const validity = client => String(client.mailbox?.uidValidity ?? '');
8
+ const messageId = message => String(message?.envelope?.messageId ?? '').trim();
9
+ const validUid = uid => Number.isSafeInteger(Number(uid)) && Number(uid) > 0 && Number(uid) <= 0xffffffff;
10
+
11
+ /** Resolve only a recorded UID in its generation or a unique Message-ID. */
12
+ export async function locateSnoozed(client, reference) {
13
+ const uidValidity = validity(client);
14
+ if (!uidValidity) throw attention('The server did not identify this folder. Check the message manually.');
15
+ if (reference.uidValidity && uidValidity !== String(reference.uidValidity)) throw attention('The snooze folder was recreated. Check the message manually.');
16
+ let uid = reference.uid;
17
+ if (!validUid(uid) || !reference.uidValidity) {
18
+ if (!reference.messageId) throw attention('This older snooze has no reliable message reference. Check the message manually.');
19
+ const found = await client.search({header: {'message-id': reference.messageId}}, {uid: true});
20
+ const matches = [...new Set((found ?? []).map(Number))].filter(value => validUid(value) && value >= (reference.searchFromUid ?? 1));
21
+ if (matches.length !== 1) throw attention('The snoozed message could not be identified uniquely. Check the message manually.');
22
+ uid = matches[0];
23
+ }
24
+ const fetched = await client.fetchOne(Number(uid), {envelope: true, flags: true}, {uid: true});
25
+ if (!fetched || Number(fetched.uid) !== Number(uid) || (reference.messageId && messageId(fetched) !== reference.messageId)) throw attention('The recorded message is no longer in its folder. Check it manually.');
26
+ return {uid: Number(uid), uidValidity, messageId: messageId(fetched), fetched};
27
+ }
28
+
29
+ /** Verify the reference again inside every mailbox lock that can write. */
30
+ export function referencedPool(pool, reference, beforeMove = () => {}) {
31
+ const guarded = safeWritePool(pool);
32
+ return {withClient: guarded.withClient, withMailbox(key, connection, path, action, options) {
33
+ return guarded.withMailbox(key, connection, path, async (client, mailbox) => {
34
+ if (path !== reference.folder) throw attention('The message folder changed. Refresh before trying again.');
35
+ await locateSnoozed(client, reference);
36
+ const checked = new Proxy(client, {get(target, name) {
37
+ if (name === 'messageMove') return async (...args) => {beforeMove(); return target.messageMove(...args);};
38
+ const value = target[name]; return typeof value === 'function' ? value.bind(target) : value;
39
+ }});
40
+ return action(checked, mailbox);
41
+ }, options);
42
+ }};
43
+ }
44
+
45
+ /** Public IMAP half of waking a snooze, derived from the CMS scheduler. */
46
+ export async function wakeSnoozedMessage({pool, account, poolKey, connection, item, beforeMove}) {
47
+ if (!validSnoozePath(item.folder) || !validSnoozePath(item.returnTo) || item.folder === item.returnTo) throw attention('The snooze or return folder needs attention.');
48
+ const folders = await pool.withClient(poolKey, connection, client => client.list());
49
+ for (const path of [item.folder, item.returnTo]) if (!folders.some(box => box.path === path && !box.flags?.has('\\Noselect'))) throw attention('The snooze or return folder is missing. Check the message manually.');
50
+ if (item.returnUidValidity) await pool.withMailbox(poolKey, connection, item.returnTo, client => {
51
+ if (validity(client) !== String(item.returnUidValidity)) throw attention('The return folder was recreated. Choose where to move the message manually.');
52
+ });
53
+ const reference = await pool.withMailbox(poolKey, connection, item.folder, client => locateSnoozed(client, item));
54
+ const checked = referencedPool(pool, {...reference, folder: item.folder}, beforeMove);
55
+ await checked.withMailbox(poolKey, connection, item.folder, async client => {
56
+ if (!client.capabilities?.has('MOVE') && !client.capabilities?.has('UIDPLUS')) throw attention('This server cannot move only the snoozed message safely.');
57
+ if (await client.messageFlagsRemove({uid: String(reference.uid)}, ['\\Seen'], {uid: true}) === false) throw new Error('The server refused to mark the snoozed message unread.');
58
+ }, {writable: true});
59
+ return moveMessage({pool: checked, store: null, account, poolKey, connection, folder: item.folder, uid: reference.uid, destination: item.returnTo});
60
+ }