domma-cms 1.28.4 → 1.29.0

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