domma-cms 1.28.3 → 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 (99) hide show
  1. package/CHANGELOG.md +9 -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/games/plays.js +15 -3
  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
@@ -1,117 +1,4 @@
1
- /**
2
- * Sending the away message.
3
- *
4
- * The decision - and every reason not to - is `_lib/admin/mail/vacation.js`,
5
- * which is pure. This is the half that talks to SMTP, and it is deliberately
6
- * thin: an auto-responder's bugs are decisions, not transport, and a decision
7
- * that lives behind a mail server is a decision nobody can test.
8
- *
9
- * ## The two halves of not causing a loop
10
- *
11
- * `shouldAutoReply` refuses to answer anything that announced itself as
12
- * automatic. `autoReplyHeaders` makes OUR reply announce itself the same way,
13
- * so the responder at the far end refuses it in turn. Either half alone
14
- * leaves a loop that only stops when somebody notices.
15
- *
16
- * @module _lib/mail/vacationRunner
17
- */
18
- import {
19
- autoReplyHeaders,
20
- isActive,
21
- normaliseVacation,
22
- replySubject,
23
- shouldAutoReply
24
- } from '../admin/mail/vacation.js';
25
- import {textToHtml} from '../admin/mail/identity.js';
1
+ /** CMS transport adapter for the shared away responder. */
26
2
  import {sendMessage} from './send.js';
27
-
28
- /**
29
- * How many away messages may go out in one sync pass.
30
- *
31
- * A ceiling on the blast radius of a mistake. If something has gone wrong -
32
- * a guard that does not hold, a folder full of mail that suddenly looks new -
33
- * the damage is bounded at ten messages rather than at the size of the
34
- * mailbox, and the next pass will do ten more only if it is still right to.
35
- */
36
- const MAX_PER_PASS = 10;
37
-
38
- /**
39
- * Answer whatever has just arrived and deserves an answer.
40
- *
41
- * Must be called with NO mailbox lock held - it sends, which opens its own
42
- * connections. Failures are collected rather than thrown: one message that
43
- * could not be answered must not stop the rest, and it must certainly not
44
- * fail the sync pass it is riding on.
45
- *
46
- * @param {{pool: object, store: object, account: object, poolKey: string,
47
- * connection: object, smtp: object, messages: object[],
48
- * config: object, addresses: string[], now?: Date}} deps
49
- * @returns {Promise<{considered: number, replied: number, skipped: object[], errors: string[]}>}
50
- */
51
- export async function runVacation({
52
- pool, store, account, poolKey, connection, smtp, messages, config, addresses, now = new Date()
53
- }) {
54
- const report = {considered: messages?.length ?? 0, replied: 0, skipped: [], errors: []};
55
-
56
- const vacation = normaliseVacation(account);
57
- if (!isActive(vacation, now)) return report;
58
- // Nothing to send it with. Reported rather than silent: a mailbox with an
59
- // away message switched on and no outgoing server is a mailbox whose
60
- // owner believes people are being answered.
61
- if (!smtp) {
62
- report.errors.push('No outgoing server is configured, so nothing could be answered.');
63
- return report;
64
- }
65
-
66
- for (const message of messages ?? []) {
67
- if (report.replied >= MAX_PER_PASS) break;
68
-
69
- const sender = (message.from ?? [])[0]?.address ?? '';
70
- const lastRepliedAt = sender ? await store.lastAutoReply(account.id, sender) : null;
71
-
72
- const verdict = shouldAutoReply({message, vacation, addresses, lastRepliedAt, now});
73
- if (!verdict.reply) {
74
- report.skipped.push({uid: message.uid, reason: verdict.reason});
75
- continue;
76
- }
77
-
78
- try {
79
- await sendMessage({
80
- smtp,
81
- draft: {
82
- to: [{name: (message.from ?? [])[0]?.name ?? '', address: sender}],
83
- subject: replySubject(vacation, message.subject),
84
- body: vacation.bodyText,
85
- html: vacation.bodyHtml || textToHtml(vacation.bodyText),
86
- // Threaded onto what they sent, so the answer arrives
87
- // under their own message rather than as a new one.
88
- inReplyTo: message.messageId ?? null,
89
- references: message.messageId ? [message.messageId] : []
90
- },
91
- pool,
92
- poolKey,
93
- connection,
94
- allowInsecureTLS: config.allowInsecureTLS === true,
95
- // The half that protects everybody else.
96
- headers: autoReplyHeaders(),
97
- // Not filed. One holiday produces a hundred of these, and a
98
- // Sent folder that is mostly "Out of office" is one nobody can
99
- // find anything in - the reply log is the audit trail instead.
100
- fileCopy: false,
101
- // So the mailbox's rules about leaving (secure delivery) apply
102
- // to its away message too.
103
- account
104
- });
105
-
106
- // Recorded AFTER it has gone. The other order would mean a send
107
- // that failed still counted as "already told", and that person
108
- // would never hear anything.
109
- await store.noteAutoReply(account.id, sender, now);
110
- report.replied += 1;
111
- } catch (err) {
112
- report.errors.push(`${sender}: ${err.message}`);
113
- }
114
- }
115
-
116
- return report;
117
- }
3
+ import {createVacationRunner} from './vacationRuntime.js';
4
+ export const runVacation = createVacationRunner({sendMessage});
@@ -0,0 +1,70 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/vacationRuntime.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ import {randomUUID} from 'node:crypto';
4
+ import {autoReplyHeaders, isActive, normaliseVacation, replySubject, shouldAutoReply, replyHistory} from '../admin/mail/vacation.js';
5
+ import {textToHtml} from '../admin/mail/identity.js';
6
+ import {ENVELOPE_QUERY, toRecord} from './envelope.js';
7
+
8
+ /** Public CMS responder, with explicit transport and durable sender claims. */
9
+ export function createVacationRunner({sendMessage, isKnownSender = async () => false}) {
10
+ return async function runVacation({pool, store, account, poolKey, connection, smtp, messages, config = {}, addresses,
11
+ now = new Date(), budget = {remaining: 10}, folder, uidValidity, isStopping = () => false}) {
12
+ const report = {considered: 0, replied: 0, attempted: 0, skipped: [], errors: []};
13
+ const vacation = normaliseVacation(account), epoch = account.vacationEpoch ?? 'legacy';
14
+ if (!isActive(vacation, now) || account.sieve?.filtering === true) return report;
15
+ if (!smtp) {report.errors.push('No outgoing server is configured, so nothing could be answered.'); return report;}
16
+ if (folder) {
17
+ if (!budget.incomingFolders) {
18
+ let boxes;
19
+ try {boxes = await pool.withClient(poolKey, connection, client => client.list());}
20
+ catch {report.errors.push('Incoming folders could not be checked. No automatic reply was attempted.'); return report;}
21
+ budget.incomingFolders = new Set(boxes.filter(box => !box.flags?.has('\\Noselect')
22
+ && !['\\Sent', '\\Drafts', '\\Trash', '\\Junk', '\\Archive', '\\All', '\\Flagged'].includes(box.specialUse)
23
+ && box.path !== (account.snoozeFolder || 'Snoozed')).map(box => box.path));
24
+ }
25
+ if (!budget.incomingFolders.has(folder)) {report.errors.push('Away replies only run in incoming folders.'); return report;}
26
+ }
27
+ for (const stored of messages ?? []) {
28
+ if (budget.remaining <= 0 || isStopping()) break;
29
+ report.considered++;
30
+ let message = stored;
31
+ try {
32
+ if (folder) message = await pool.withMailbox(poolKey, connection, folder, async client => {
33
+ if (String(client.mailbox?.uidValidity) !== String(uidValidity)) return null;
34
+ const fetched = await client.fetchOne(stored.uid, ENVELOPE_QUERY, {uid: true});
35
+ if (!fetched?.headers || Number(fetched.uid) !== stored.uid) return null;
36
+ const live = toRecord(fetched);
37
+ return stored.messageId && live.messageId !== stored.messageId ? null : live;
38
+ });
39
+ if (!message) {report.skipped.push({uid: stored.uid, reason: 'The message changed or its safety headers could not be read.'}); continue;}
40
+ const sender = String(message.from?.[0]?.address ?? '').trim().toLowerCase();
41
+ const previous = sender ? await store.getAutoReply(account.id, sender, epoch) : null;
42
+ const history = replyHistory(previous, vacation, now);
43
+ const verdict = history.blocked ? {reply: false, reason: history.reason} : shouldAutoReply({message, vacation, addresses,
44
+ lastRepliedAt: history.lastRepliedAt, knownSender: vacation.knownSendersOnly ? await isKnownSender(account, sender) : false, now});
45
+ if (!verdict.reply) {report.skipped.push({uid: stored.uid, reason: verdict.reason}); continue;}
46
+ const claim = await store.claimAutoReply(account.id, sender, {epoch, now, intervalDays: vacation.intervalDays});
47
+ if (!claim) {report.skipped.push({uid: stored.uid, reason: 'A reply to this sender was already claimed.'}); continue;}
48
+ budget.remaining--; report.attempted++;
49
+ try {
50
+ const incomingId = typeof message.messageId === 'string' && !/[\r\n]/.test(message.messageId) ? message.messageId.slice(0, 1000) : null;
51
+ await sendMessage({smtp, account, store: null, draft: {
52
+ to: [{address: sender}], subject: replySubject(vacation, String(message.subject ?? '').slice(0, 500)),
53
+ body: vacation.bodyText, html: vacation.bodyHtml || textToHtml(vacation.bodyText),
54
+ messageId: `<${randomUUID()}@${String(smtp.from).split('@')[1]?.replace(/[^a-zA-Z0-9.-]/g, '') || 'localhost'}>`, inReplyTo: incomingId, references: incomingId ? [incomingId] : []
55
+ }, pool, poolKey, connection, allowInsecureTLS: config.allowInsecureTLS === true, headers: autoReplyHeaders(), fileCopy: false});
56
+ } catch (error) {
57
+ await store.finishAutoReply(claim, {status: error.deliveryUnknown === true || error.retryable !== true ? 'unknown' : 'failed',
58
+ error: 'The automatic reply could not be confirmed. Check with the sender before sending another copy.'});
59
+ report.errors.push('An automatic reply could not be confirmed. It will not be retried automatically.');
60
+ continue;
61
+ }
62
+ // DB failure here must leave an unconfirmed claim, never a retry.
63
+ await store.finishAutoReply(claim, {status: 'sent', error: null}); report.replied++;
64
+ } catch {
65
+ report.errors.push('An automatic reply could not be recorded. Check recent attempts before trying manually.');
66
+ }
67
+ }
68
+ return report;
69
+ };
70
+ }
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/write.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Changing mail, rather than reading it.
3
5
  *
@@ -14,6 +16,35 @@
14
16
  */
15
17
  import {ENVELOPE_QUERY, toRecord} from './envelope.js';
16
18
 
19
+ /** Refuse IMAP fallbacks that could expunge mail outside the selected UID set. */
20
+ export function safeWritePool(pool) {
21
+ return {
22
+ withClient: pool.withClient.bind(pool),
23
+ withMailbox(key, connection, path, action, options) {
24
+ return pool.withMailbox(key, connection, path, (client, mailbox) => {
25
+ const guarded = new Proxy(client, {get(target, property) {
26
+ const value = Reflect.get(target, property, target);
27
+ if (typeof value !== 'function') return value;
28
+ return (...args) => {
29
+ let message;
30
+ if (property === 'messageMove' && !target.capabilities?.has('MOVE') && !target.capabilities?.has('UIDPLUS')) message = 'This server cannot safely move only the selected messages.';
31
+ if ((property === 'messageDelete' || (property === 'messageFlagsAdd' && args[1]?.includes('\\Deleted'))) && !target.capabilities?.has('UIDPLUS')) message = 'This server cannot permanently delete only the selected messages safely.';
32
+ if (message) throw Object.assign(new Error(message), {statusCode: 409, publicMailError: true});
33
+ return value.apply(target, args);
34
+ };
35
+ }});
36
+ return action(guarded, mailbox);
37
+ }, options);
38
+ }
39
+ };
40
+ }
41
+
42
+ /** A refused IMAP command must never be reported as a completed change. */
43
+ function commandResult(result, action) {
44
+ if (result === false) throw Object.assign(new Error(`The mail server refused the ${action}.`), {statusCode: 502});
45
+ return result;
46
+ }
47
+
17
48
  /** Flags a caller may set. Anything else is refused rather than passed through. */
18
49
  export const WRITABLE_FLAGS = new Set(['\\Seen', '\\Flagged', '\\Answered', '\\Draft']);
19
50
 
@@ -47,8 +78,8 @@ export async function setMessageFlags({
47
78
  pool, store, account, poolKey, connection, folder, uid, add = [], remove = []
48
79
  }) {
49
80
  const flags = await pool.withMailbox(poolKey, connection, folder, async (client) => {
50
- if (add.length) await client.messageFlagsAdd({uid: String(uid)}, add, {uid: true});
51
- if (remove.length) await client.messageFlagsRemove({uid: String(uid)}, remove, {uid: true});
81
+ if (add.length) commandResult(await client.messageFlagsAdd({uid: String(uid)}, add, {uid: true}), 'message change');
82
+ if (remove.length) commandResult(await client.messageFlagsRemove({uid: String(uid)}, remove, {uid: true}), 'message change');
52
83
 
53
84
  // Read back rather than assume: another client may have changed
54
85
  // something in between, and the mirror should hold what is true on the
@@ -122,7 +153,7 @@ export async function moveMessage({
122
153
  pool, store, account, poolKey, connection, folder, uid, destination
123
154
  }) {
124
155
  const result = await pool.withMailbox(poolKey, connection, folder, async (client) => {
125
- return client.messageMove({uid: String(uid)}, destination, {uid: true});
156
+ return commandResult(await client.messageMove({uid: String(uid)}, destination, {uid: true}), 'move');
126
157
  }, {writable: true});
127
158
 
128
159
  if (store) {
@@ -183,8 +214,8 @@ export async function deleteMessage({
183
214
 
184
215
  // No Trash, or already there: this is the irreversible path.
185
216
  await pool.withMailbox(poolKey, connection, folder, async (client) => {
186
- await client.messageFlagsAdd({uid: String(uid)}, ['\\Deleted'], {uid: true});
187
- await client.messageDelete({uid: String(uid)}, {uid: true});
217
+ commandResult(await client.messageFlagsAdd({uid: String(uid)}, ['\\Deleted'], {uid: true}), 'message change');
218
+ commandResult(await client.messageDelete({uid: String(uid)}, {uid: true}), 'message change');
188
219
  }, {writable: true});
189
220
 
190
221
  if (store) await store.removeMessages(account.id, folder, [uid]);
@@ -221,8 +252,8 @@ export async function setFlagsBulk({
221
252
  pool, store, account, poolKey, connection, folder, uids, set, add = [], remove = []
222
253
  }) {
223
254
  const updated = await pool.withMailbox(poolKey, connection, folder, async (client) => {
224
- if (add.length) await client.messageFlagsAdd({uid: set}, add, {uid: true});
225
- if (remove.length) await client.messageFlagsRemove({uid: set}, remove, {uid: true});
255
+ if (add.length) commandResult(await client.messageFlagsAdd({uid: set}, add, {uid: true}), 'message change');
256
+ if (remove.length) commandResult(await client.messageFlagsRemove({uid: set}, remove, {uid: true}), 'message change');
226
257
 
227
258
  // Read back what the server now holds, for the same reason the single
228
259
  // version does: another client may have changed something, and the
@@ -248,7 +279,7 @@ export async function moveBulk({
248
279
  pool, store, account, poolKey, connection, folder, uids, set, destination
249
280
  }) {
250
281
  const result = await pool.withMailbox(poolKey, connection, folder, async (client) => {
251
- return client.messageMove({uid: set}, destination, {uid: true});
282
+ return commandResult(await client.messageMove({uid: set}, destination, {uid: true}), 'move');
252
283
  }, {writable: true});
253
284
 
254
285
  if (store) await store.removeMessages(account.id, folder, uids);
@@ -290,8 +321,8 @@ export async function deleteBulk({
290
321
  }
291
322
 
292
323
  await pool.withMailbox(poolKey, connection, folder, async (client) => {
293
- await client.messageFlagsAdd({uid: set}, ['\\Deleted'], {uid: true});
294
- await client.messageDelete({uid: set}, {uid: true});
324
+ commandResult(await client.messageFlagsAdd({uid: set}, ['\\Deleted'], {uid: true}), 'message change');
325
+ commandResult(await client.messageDelete({uid: set}, {uid: true}), 'message change');
295
326
  }, {writable: true});
296
327
 
297
328
  if (store) await store.removeMessages(account.id, folder, uids);
@@ -371,8 +402,8 @@ export async function findJunkFolder(pool, poolKey, connection) {
371
402
  async function applyJunkKeywords({pool, poolKey, connection, folder, set, add, remove}) {
372
403
  try {
373
404
  const rows = await pool.withMailbox(poolKey, connection, folder, async (client) => {
374
- if (add.length) await client.messageFlagsAdd({uid: set}, add, {uid: true});
375
- if (remove.length) await client.messageFlagsRemove({uid: set}, remove, {uid: true});
405
+ if (add.length) commandResult(await client.messageFlagsAdd({uid: set}, add, {uid: true}), 'message change');
406
+ if (remove.length) commandResult(await client.messageFlagsRemove({uid: set}, remove, {uid: true}), 'message change');
376
407
 
377
408
  // Read back rather than assume, exactly as setMessageFlags does:
378
409
  // a server may have refused the keyword, and the caller has to be
@@ -487,7 +518,7 @@ export async function emptyTrash({pool, store, account, poolKey, connection, fol
487
518
  if (!Number.isSafeInteger(count) || count < 0 || !Number.isSafeInteger(lastUid) || lastUid < 1) {
488
519
  throw new Error('The Trash message count could not be verified. Refresh and try again.');
489
520
  }
490
- const result = await client.messageDelete({uid: `1:${lastUid}`}, {uid: true});
521
+ const result = commandResult(await client.messageDelete({uid: `1:${lastUid}`}, {uid: true}), 'message change');
491
522
  if (result === false) throw new Error('The server refused to empty Trash.');
492
523
  return count;
493
524
  }, {writable: true});
@@ -62,178 +62,8 @@ function defaultHoldsManageGroups(request) {
62
62
  const CONTACTS_SLUG = 'contacts-contacts';
63
63
  const GROUPS_SLUG = 'contacts-groups';
64
64
 
65
- /**
66
- * The fields a contact carries beyond a name and a phone number.
67
- *
68
- * Kept as one list so the create, update and import paths cannot drift apart -
69
- * they each used to spell the field set out by hand, which is how a field gets
70
- * added to two of the three and quietly dropped by the other.
71
- */
72
- const TEXT_FIELDS = [
73
- 'name', 'email', 'phone', 'notes',
74
- 'company', 'jobTitle', 'website',
75
- 'vatNumber', 'companyNumber', 'reference', 'billingEmail', 'currency',
76
- 'accountName', 'bankName', 'sortCode', 'accountNumber', 'iban', 'bic'
77
- ];
78
-
79
- /** Repeatable lists, each a array of small objects. */
80
- const LIST_FIELDS = ['addresses', 'emails', 'phones'];
81
-
82
- /** Parse a value that may have been stored as JSON text by an import or the API. */
83
- function toArray(value) {
84
- if (Array.isArray(value)) return value;
85
- if (typeof value === 'string' && value.trim()) {
86
- try {
87
- const parsed = JSON.parse(value);
88
- return Array.isArray(parsed) ? parsed : [];
89
- } catch {
90
- return [];
91
- }
92
- }
93
- return [];
94
- }
95
-
96
- const str = (v) => (typeof v === 'string' ? v.trim() : (v === undefined || v === null ? '' : String(v)));
97
-
98
- /**
99
- * One address, with every part named.
100
- *
101
- * Stored as parts rather than a blob because an invoice, a letter and a
102
- * delivery note each want them arranged differently - and because a postcode
103
- * you cannot read out separately is not much use for anything.
104
- */
105
- function cleanAddress(raw) {
106
- return {
107
- label: str(raw?.label) || 'Address',
108
- line1: str(raw?.line1),
109
- line2: str(raw?.line2),
110
- city: str(raw?.city),
111
- region: str(raw?.region),
112
- postcode: str(raw?.postcode),
113
- country: str(raw?.country),
114
- isBilling: raw?.isBilling === true || raw?.isBilling === 'true'
115
- };
116
- }
117
-
118
- function cleanEmail(raw) {
119
- return { label: str(raw?.label) || 'Email', address: str(raw?.address) };
120
- }
121
-
122
- function cleanPhone(raw) {
123
- return { label: str(raw?.label) || 'Phone', number: str(raw?.number) };
124
- }
125
-
126
- const CLEANERS = { addresses: cleanAddress, emails: cleanEmail, phones: cleanPhone };
127
-
128
- /** Coerce a repeatable list, dropping rows with nothing in them. */
129
- function cleanList(field, value) {
130
- const clean = CLEANERS[field];
131
- return toArray(value)
132
- .map(clean)
133
- .filter((row) => Object.entries(row).some(([k, v]) => k !== 'label' && v !== '' && v !== false));
134
- }
135
-
136
- /**
137
- * An address as an invoice prints it: one line per part, blanks omitted.
138
- *
139
- * @param {object} address
140
- * @returns {string}
141
- */
142
- export function formatAddress(address) {
143
- if (!address) return '';
144
- return [address.line1, address.line2, address.city, address.region, address.postcode, address.country]
145
- .map(str)
146
- .filter(Boolean)
147
- .join('\n');
148
- }
149
-
150
- /**
151
- * The address to bill to: the one marked for billing, else the first.
152
- *
153
- * @param {object[]} addresses
154
- * @returns {object|null}
155
- */
156
- export function billingAddress(addresses) {
157
- const list = toArray(addresses);
158
- return list.find((a) => a?.isBilling) ?? list[0] ?? null;
159
- }
160
-
161
- /**
162
- * A contact projected into the shape the Invoice plugin's receivers use.
163
- *
164
- * This is the join between the two plugins: the field names are Invoice's, not
165
- * Contacts', so the caller can post it straight at `/api/plugins/invoice/receivers`.
166
- *
167
- * @param {object} contact as returned by toContact()
168
- * @returns {object}
169
- */
170
- export function toBillingProfile(contact) {
171
- const address = billingAddress(contact.addresses);
172
- return {
173
- name: contact.name,
174
- company: contact.company,
175
- // The billing address wins over the personal one, which is the whole
176
- // point of having both - invoices go to accounts, not to a mobile.
177
- email: contact.billingEmail || contact.email,
178
- phone: contact.phone,
179
- address: formatAddress(address),
180
- vatNumber: contact.vatNumber,
181
- reference: contact.reference,
182
- // An issuer prints these so the invoice can be paid; a receiver simply
183
- // has none, and an empty string is what the Invoice plugin stores anyway.
184
- bankDetails: formatBankDetails(contact)
185
- };
186
- }
187
-
188
- /**
189
- * Bank details as an invoice prints them: label and value, one per line,
190
- * blanks omitted. Sort code and account number ride together on one line
191
- * because that is how anyone reads them off a page.
192
- *
193
- * @param {object} contact
194
- * @returns {string}
195
- */
196
- export function formatBankDetails(contact) {
197
- const lines = [];
198
- if (contact.accountName) lines.push(contact.accountName);
199
- if (contact.bankName) lines.push(contact.bankName);
200
-
201
- const sort = str(contact.sortCode);
202
- const acct = str(contact.accountNumber);
203
- if (sort && acct) lines.push(`Sort ${sort} Acc ${acct}`);
204
- else if (sort) lines.push(`Sort ${sort}`);
205
- else if (acct) lines.push(`Acc ${acct}`);
206
-
207
- if (contact.iban) lines.push(`IBAN ${str(contact.iban)}`);
208
- if (contact.bic) lines.push(`BIC ${str(contact.bic)}`);
209
- return lines.join('\n');
210
- }
211
-
212
- /** Map a collection entry to the shape the admin view expects. */
213
- function toContact(entry) {
214
- let groups = entry.data.groups;
215
- if (typeof groups === 'string') {
216
- try {
217
- groups = JSON.parse(groups);
218
- } catch {
219
- groups = [];
220
- }
221
- }
222
- const contact = {
223
- id: entry.id,
224
- groups: Array.isArray(groups) ? groups : [],
225
- favourite: entry.data.favourite === true || entry.data.favourite === 'true',
226
- paymentTerms: entry.data.paymentTerms === '' || entry.data.paymentTerms === undefined || entry.data.paymentTerms === null
227
- ? null
228
- : Number(entry.data.paymentTerms),
229
- userId: entry.data.userId ?? null,
230
- createdAt: entry.meta.createdAt,
231
- updatedAt: entry.meta.updatedAt
232
- };
233
- for (const field of TEXT_FIELDS) contact[field] = entry.data[field] ?? '';
234
- for (const field of LIST_FIELDS) contact[field] = toArray(entry.data[field]);
235
- return contact;
236
- }
65
+ import {TEXT_FIELDS, LIST_FIELDS, cleanList, toContact, buildContact, toBillingProfile} from '../../../plugins/_lib/contacts/model.js';
66
+ export {formatAddress, billingAddress, toBillingProfile, formatBankDetails} from '../../../plugins/_lib/contacts/model.js';
237
67
 
238
68
  function toGroupName(entry) {
239
69
  return entry.data.name ?? '';
@@ -316,30 +146,6 @@ export async function contactsRoutes(fastify, opts = {}) {
316
146
 
317
147
  const NOT_YOURS = 'Only the person who created this group, or someone allowed to manage every group, can rename or delete it.';
318
148
 
319
- /**
320
- * Build the stored shape from whatever a caller sent.
321
- *
322
- * Used by create AND import so the two cannot drift - a field added to one
323
- * and forgotten in the other is the bug this exists to prevent.
324
- *
325
- * @param {object} raw
326
- * @param {string|null} uid
327
- * @returns {object}
328
- */
329
- function buildContact(raw, uid) {
330
- const data = {
331
- groups: Array.isArray(raw.groups) ? raw.groups : [],
332
- favourite: raw.favourite === true || raw.favourite === 'true',
333
- paymentTerms: raw.paymentTerms === '' || raw.paymentTerms === undefined || raw.paymentTerms === null
334
- ? ''
335
- : (Number(raw.paymentTerms) || 0),
336
- userId: uid ?? null
337
- };
338
- for (const field of TEXT_FIELDS) data[field] = str(raw[field]);
339
- for (const field of LIST_FIELDS) data[field] = cleanList(field, raw[field]);
340
- return data;
341
- }
342
-
343
149
  // -------------------------------------------------------------------------
344
150
  // Contacts CRUD
345
151
  // -------------------------------------------------------------------------