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
@@ -25,17 +25,18 @@
25
25
  * @module _lib/mail/accounts
26
26
  */
27
27
  import {randomUUID} from 'node:crypto';
28
- import fs from 'node:fs/promises';
29
28
  import path from 'node:path';
30
29
  import {fileURLToPath} from 'node:url';
31
30
 
32
31
  import {normaliseIdentity, normaliseIdentityList, findIdentity} from '../admin/mail/identity.js';
33
- import {normaliseRuleGroups, normaliseRules, rulesInEffect} from '../admin/mail/rules.js';
32
+ import {normaliseRules} from '../admin/mail/rules.js';
34
33
  import {normaliseUndoSeconds} from '../admin/mail/scheduling.js';
35
34
  import {normaliseVacation} from '../admin/mail/vacation.js';
36
35
  import {normaliseTemplates} from '../admin/mail/templates.js';
37
36
  import {sanitiseSignature} from './render.js';
38
37
  import {MailKeyError, open, seal} from './secretbox.js';
38
+ import {createAccountFileStore} from './accountFileStore.js';
39
+ import {createAccountRepository} from './accountRepository.js';
39
40
 
40
41
  /**
41
42
  * A mailbox signed in with Microsoft or Google whose sign-in no longer works.
@@ -45,159 +46,25 @@ import {MailKeyError, open, seal} from './secretbox.js';
45
46
  * here, with nothing to learn. `statusCode` makes a route that lets it escape
46
47
  * answer 409 with the sentence rather than a 500.
47
48
  */
48
- export class OAuthReconnectError extends MailKeyError {
49
- constructor(message = 'This mailbox\'s sign-in has expired or was withdrawn. Reconnect it under Mail Settings > Mailboxes.') {
50
- super(message);
51
- this.name = 'OAuthReconnectError';
52
- this.needsReconnect = true;
53
- this.statusCode = 409;
54
- }
55
- }
56
-
57
- /**
58
- * Is this mailbox signed in with a provider (OAuth2) rather than a password?
59
- *
60
- * @param {object|null} account
61
- * @returns {boolean}
62
- */
63
- export function isOAuth(account) {
64
- return account?.auth === 'oauth' && !!account.oauth;
65
- }
49
+ export {OAuthReconnectError, isOAuth, needsReconnect} from './oauthAccounts.js';
50
+ import {createOAuthAccounts, isOAuth, needsReconnect, OAuthReconnectError} from './oauthAccounts.js';
66
51
 
67
- /**
68
- * Does this mailbox need its owner to sign in again?
69
- *
70
- * @param {object|null} account
71
- * @returns {boolean}
72
- */
73
- export function needsReconnect(account) {
74
- return isOAuth(account) && account.oauth.status !== 'ok';
75
- }
76
-
77
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
78
-
79
- /**
80
- * Where mail state lives. Overridable so tests can point at a temp directory:
81
- * without that they would have to operate on the real store, and a test that
82
- * cleans up after itself would delete live mailbox credentials.
83
- */
84
- const DATA_DIR = process.env.DOMMA_MAIL_DATA_DIR || path.join(__dirname, '..', 'data');
85
- // `plugins/<name>/data` is the ONLY path bin/update.js preserves across an
86
- // engine update - it deletes and replaces the rest of the directory. A
87
- // nested `_lib/mail/data` would be wiped on every upgrade, taking every
88
- // saved mailbox with it.
89
- const STORE_FILE = path.join(DATA_DIR, 'mail-accounts.json');
90
-
91
- /** Where the store lived while this code belonged to the mail-reader plugin. */
92
- const LEGACY_STORE_FILE = path.join(__dirname, '..', '..', 'mail-reader', 'data', 'accounts.json');
93
-
94
- /**
95
- * Bring a stored record up to the current shape.
96
- *
97
- * The first release kept one account per user, keyed by the user id itself.
98
- * Those records have no `userId` and their `id` is the owner - carry them
99
- * forward rather than stranding anyone's saved mailbox.
100
- *
101
- * @param {object} record
102
- * @returns {object}
103
- */
104
- function normalise(record) {
105
- if (record.userId) return record;
106
- return {...record, userId: record.id, id: randomUUID()};
107
- }
108
-
109
- /**
110
- * Take over the store from the old mail-reader-owned location, once.
111
- *
112
- * Returns the records so the caller can carry on, or null when there is
113
- * nothing to adopt. The old file is left where it is: an engine update
114
- * preserves it, and leaving it costs nothing while deleting it would throw
115
- * away the only copy if this went wrong.
116
- *
117
- * @returns {Promise<object[]|null>}
118
- */
119
- async function adoptLegacyStore() {
120
- let legacy;
121
- try {
122
- legacy = JSON.parse(await fs.readFile(LEGACY_STORE_FILE, 'utf8'));
123
- } catch {
124
- return null;
125
- }
126
- if (!Array.isArray(legacy) || !legacy.length) return null;
127
-
128
- const records = legacy.map(normalise);
129
- await writeAll(records);
130
- return records;
131
- }
132
-
133
- /**
134
- * Read every stored account, migrating any legacy records as a side effect.
135
- *
136
- * The migration is WRITTEN BACK, not just applied in memory. Normalising on
137
- * every read without persisting would hand a legacy record a fresh `id` each
138
- * time it was read, so it could never be selected twice or deleted at all -
139
- * an upgraded user would be left with a ghost mailbox they could not remove.
140
- *
141
- * @returns {Promise<object[]>}
142
- */
143
- async function readAll() {
144
- let parsed;
145
- try {
146
- parsed = JSON.parse(await fs.readFile(STORE_FILE, 'utf8'));
147
- } catch {
148
- parsed = await adoptLegacyStore();
149
- if (!parsed) return [];
150
- }
151
- if (!Array.isArray(parsed)) return [];
152
-
153
- const normalised = parsed.map(normalise);
154
- // normalise() returns the same reference when nothing changed.
155
- if (normalised.some((record, i) => record !== parsed[i])) {
156
- await writeAll(normalised);
157
- }
158
- return normalised;
159
- }
160
-
161
- /**
162
- * Atomically write the store with owner-only permissions.
163
- *
164
- * The temp file is created 0600 rather than chmod-ed after the fact, so the
165
- * sealed passwords are never briefly readable by other local users.
166
- *
167
- * @param {object[]} accounts
168
- * @returns {Promise<void>}
169
- */
170
- async function writeAll(accounts) {
171
- await fs.mkdir(path.dirname(STORE_FILE), {recursive: true});
172
- // A name of its own per write: two writers sharing one `.tmp` could rename
173
- // each other's half-written file into place.
174
- const tmp = `${STORE_FILE}.${process.pid}.${randomUUID()}.tmp`;
175
- await fs.writeFile(tmp, JSON.stringify(accounts, null, 2) + '\n', {encoding: 'utf8', mode: 0o600});
176
- await fs.rename(tmp, STORE_FILE);
177
- }
178
-
179
- /** The tail of the one queue every read-modify-write of the store waits in. */
180
- let storeQueue = Promise.resolve();
181
-
182
- /**
183
- * Run a read-modify-write of the store with nothing else writing meanwhile.
184
- *
185
- * Every exported function that reads the store and writes it back goes
186
- * through here. Without it a token renewal and, say, a rules save that
187
- * overlap each write back the copy they read, and one of them is lost -
188
- * the renewal's rotated refresh token included, which is a lost sign-in.
189
- * Single process (as the pool is); never nest - a locked function must not
190
- * call another one.
191
- *
192
- * @template T
193
- * @param {() => Promise<T>} fn
194
- * @returns {Promise<T>}
195
- */
196
- function withStoreLock(fn) {
197
- const run = storeQueue.then(fn);
198
- storeQueue = run.catch(() => {});
199
- return run;
200
- }
52
+ // Shared persistence and lifecycle; edition-specific mailbox settings remain here.
53
+ const directory = path.dirname(fileURLToPath(import.meta.url));
54
+ const mailStore = createAccountFileStore({
55
+ dataDir: process.env.DOMMA_MAIL_DATA_DIR || path.join(directory, '..', 'data'),
56
+ legacyStoreFile: path.join(directory, '..', '..', 'mail-reader', 'data', 'accounts.json')
57
+ });
58
+ const {readAll, writeAll, withStoreLock} = mailStore;
59
+ const oauthAccounts = createOAuthAccounts({store: mailStore, secrets: {seal, open}, refresherFor: refresher});
60
+ export const {saveOAuthAccount, updateOAuth} = oauthAccounts;
61
+ const {oauthToPublic} = oauthAccounts;
62
+ const baseAccounts = createAccountRepository({
63
+ store: mailStore,
64
+ secrets: {seal, open},
65
+ isOAuth,
66
+ oauthConnection: oauthAccounts.oauthConnection
67
+ });
201
68
 
202
69
  /**
203
70
  * Strip everything the browser must never see.
@@ -229,18 +96,6 @@ export function toPublic(account) {
229
96
  * @param {object} oauth
230
97
  * @returns {object}
231
98
  */
232
- function oauthToPublic(oauth) {
233
- return {
234
- provider: oauth.provider,
235
- clientId: oauth.clientId,
236
- tenant: oauth.tenant ?? null,
237
- status: oauth.status ?? 'reconnect',
238
- error: oauth.error ?? null,
239
- connectedAt: oauth.connectedAt ?? null,
240
- refreshedAt: oauth.refreshedAt ?? null,
241
- hasClientSecret: typeof oauth.clientSecretSealed === 'string' && oauth.clientSecretSealed.length > 0
242
- };
243
- }
244
99
 
245
100
  /**
246
101
  * Create a mailbox signed in with a provider, or move an existing one onto
@@ -257,114 +112,6 @@ function oauthToPublic(oauth) {
257
112
  * scope: string, imap: object, smtp: object}} f
258
113
  * @returns {Promise<object|null>} the stored record, or null if not theirs
259
114
  */
260
- export async function saveOAuthAccount(userId, accountId, f) {
261
- return withStoreLock(async () => {
262
- const all = await readAll();
263
- const now = new Date().toISOString();
264
- const previous = accountId ? all.find(a => a.id === accountId && a.userId === userId) : null;
265
- const oauth = {
266
- // A new sign-in is a new generation: a renewal that started under the
267
- // old one must not write its tokens over this (see updateOAuth).
268
- gen: (Number(previous?.oauth?.gen) || 0) + 1,
269
- provider: f.provider,
270
- clientId: f.clientId,
271
- tenant: f.tenant ?? null,
272
- clientSecretSealed: seal(f.clientSecret),
273
- refreshTokenSealed: seal(f.refreshToken),
274
- accessTokenSealed: seal(f.accessToken),
275
- expiresAt: f.expiresAt,
276
- scope: f.scope ?? '',
277
- status: 'ok',
278
- error: null,
279
- connectedAt: now,
280
- refreshedAt: now
281
- };
282
- const fields = {
283
- auth: 'oauth',
284
- host: f.imap.host,
285
- port: f.imap.port,
286
- secure: f.imap.secure,
287
- username: f.username,
288
- oauth
289
- };
290
-
291
- if (accountId) {
292
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
293
- if (index === -1) return null;
294
- const {passwordSealed, ...existing} = all[index];
295
- const keepSmtp = existing.smtp ?? {};
296
- all[index] = {
297
- ...existing,
298
- ...fields,
299
- label: f.label || existing.label,
300
- smtp: {
301
- ...keepSmtp,
302
- host: f.smtp.host, port: f.smtp.port, secure: f.smtp.secure,
303
- username: f.username, passwordSealed: null,
304
- from: keepSmtp.from || f.username,
305
- sentFolder: keepSmtp.sentFolder ?? null
306
- },
307
- updatedAt: now
308
- };
309
- await writeAll(all);
310
- return all[index];
311
- }
312
-
313
- const record = {
314
- id: randomUUID(),
315
- userId,
316
- label: f.label || f.username,
317
- ...fields,
318
- smtp: {host: f.smtp.host, port: f.smtp.port, secure: f.smtp.secure, username: f.username,
319
- passwordSealed: null, from: f.username, sentFolder: null},
320
- createdAt: now,
321
- updatedAt: now
322
- };
323
- all.push(record);
324
- await writeAll(all);
325
- return record;
326
- });
327
- }
328
-
329
- /**
330
- * Change part of a mailbox's stored sign-in: a renewed token, a rotated
331
- * refresh token, "needs reconnecting", or a disconnect.
332
- *
333
- * Does NOT touch `updatedAt`: that stamp means "the person changed the
334
- * settings", and the free reader's unread badge keys its failure back-off on
335
- * it - an hourly token renewal would otherwise reset the back-off every hour.
336
- *
337
- * `expectGen`: apply only if the stored sign-in is still that generation.
338
- * `requireOk`: apply only if it is still working. `bumpGen`: this patch IS a
339
- * new state (Disconnect) that older in-flight work must not overwrite.
340
- * Returns null when the patch was dropped (or the mailbox is gone).
341
- *
342
- * @param {string} userId
343
- * @param {string} accountId
344
- * @param {object} patch
345
- * @param {{expectGen?: number, requireOk?: boolean, bumpGen?: boolean}} [options]
346
- * @returns {Promise<object|null>}
347
- */
348
- export async function updateOAuth(userId, accountId, patch, {expectGen, requireOk = false, bumpGen = false} = {}) {
349
- return withStoreLock(async () => {
350
- const all = await readAll();
351
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
352
- if (index === -1 || !all[index].oauth) return null;
353
- const current = all[index].oauth;
354
- // The sign-in this patch was worked out against is no longer the stored
355
- // one (a Reconnect or Disconnect happened meanwhile): drop it rather than
356
- // undo the newer state.
357
- if (expectGen !== undefined && (Number(current.gen) || 0) !== expectGen) return null;
358
- // A renewal only ever lands on a working sign-in, never revives a dead one.
359
- if (requireOk && current.status !== 'ok') return null;
360
- const next = {...current, ...patch};
361
- if (bumpGen) next.gen = (Number(current.gen) || 0) + 1;
362
- all[index] = {...all[index], oauth: next};
363
- await writeAll(all);
364
- return all[index];
365
- });
366
- }
367
-
368
115
  /**
369
116
  * The renewal hook a connection carries. Imported lazily: oauth.js imports
370
117
  * this module, and a static import back would be a cycle.
@@ -384,16 +131,6 @@ function refresher(account) {
384
131
  * @param {object} account
385
132
  * @returns {{accessToken: string, expiresAt: number}}
386
133
  */
387
- function storedAccess(account) {
388
- if (needsReconnect(account)) throw new OAuthReconnectError(account.oauth.error || undefined);
389
- let accessToken = '';
390
- try {
391
- accessToken = account.oauth.accessTokenSealed ? open(account.oauth.accessTokenSealed) : '';
392
- } catch {
393
- // Unreadable (the key moved): treat as expired, the refresh decides.
394
- }
395
- return {accessToken, expiresAt: accessToken ? Number(account.oauth.expiresAt) || 0 : 0};
396
- }
397
134
 
398
135
  /**
399
136
  * Store the outgoing server for a mailbox.
@@ -409,118 +146,6 @@ function storedAccess(account) {
409
146
  * password: string, from: string, sentFolder: string|null}} smtp
410
147
  * @returns {Promise<object|null>}
411
148
  */
412
- export async function setSmtp(userId, accountId, smtp) {
413
- return withStoreLock(async () => {
414
- const all = await readAll();
415
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
416
- if (index === -1) return null;
417
-
418
- const existing = all[index].smtp ?? {};
419
- all[index] = {
420
- ...all[index],
421
- smtp: {
422
- host: smtp.host,
423
- port: smtp.port,
424
- secure: smtp.secure,
425
- username: smtp.username,
426
- passwordSealed: smtp.password
427
- ? seal(smtp.password)
428
- : (existing.passwordSealed ?? null),
429
- from: smtp.from,
430
- sentFolder: smtp.sentFolder ?? null
431
- },
432
- updatedAt: new Date().toISOString()
433
- };
434
- await writeAll(all);
435
- return all[index];
436
- });
437
- }
438
-
439
- /**
440
- * Build a nodemailer transport config for a mailbox.
441
- *
442
- * Falls back to the IMAP credentials when the outgoing server has none of its
443
- * own, which is the common case.
444
- *
445
- * `identityId` chooses which of the mailbox's identities is sending. Absent,
446
- * it is the default one - which is what every message sent before aliases
447
- * existed did, and what most messages still do.
448
- *
449
- * @param {object} account
450
- * @param {string|null} [identityId]
451
- * @returns {{transport: object, from: string}|null}
452
- */
453
- export function toSmtpConnection(account, identityId = null) {
454
- const smtp = account?.smtp;
455
- if (!smtp?.host) return null;
456
-
457
- let auth;
458
- if (isOAuth(account)) {
459
- const {accessToken, expiresAt} = storedAccess(account);
460
- const renew = refresher(account);
461
- auth = {
462
- type: 'OAuth2',
463
- user: smtp.username || account.username,
464
- accessToken,
465
- // 0 = unknown: nodemailer then asks provisionCallback straight away.
466
- ...(expiresAt ? {expires: expiresAt - 60_000} : {}),
467
- // nodemailer calls this when the token has expired (renew=false)
468
- // and once more after a refused AUTH XOAUTH2 (renew=true) - which
469
- // is exactly "refresh on an auth failure, once".
470
- provisionCallback: (user, renewNow, callback) => {
471
- // Both branches guarded, and a final catch: a throw inside
472
- // nodemailer's callback must never become an unhandled rejection.
473
- renew(Boolean(renewNow))
474
- .then(r => callback(null, r.accessToken, r.expiresAt), err => callback(err))
475
- .catch(() => {});
476
- }
477
- };
478
- } else {
479
- const pass = smtp.passwordSealed
480
- ? open(smtp.passwordSealed)
481
- : open(account.passwordSealed);
482
- auth = {user: smtp.username || account.username, pass};
483
- }
484
-
485
- const identity = findIdentity(normaliseIdentityList(account), identityId);
486
- const mailboxAddress = smtp.from || account.username;
487
-
488
- return {
489
- transport: {
490
- host: smtp.host,
491
- port: smtp.port,
492
- secure: smtp.secure !== false,
493
- auth
494
- },
495
- // Still the bare address, as it always was. The display name travels
496
- // beside it rather than folded into it, because the two go to
497
- // different places: the name belongs in the From header and must stay
498
- // out of the SMTP envelope.
499
- //
500
- // An alias replaces it outright: sending AS sales@ means the From and
501
- // the envelope both say sales@, or the alias fails DMARC alignment
502
- // and lands in spam at a good many receivers.
503
- from: identity?.address || mailboxAddress,
504
- fromName: identity?.displayName ?? '',
505
- replyTo: identity?.replyTo ?? '',
506
- identity: identity ?? null,
507
- sentFolder: smtp.sentFolder ?? null
508
- };
509
- }
510
-
511
- /**
512
- * The outgoing settings, without the password.
513
- *
514
- * @param {object} account
515
- * @returns {object|null}
516
- */
517
- export function smtpToPublic(account) {
518
- const smtp = account?.smtp;
519
- if (!smtp) return null;
520
- const {passwordSealed, ...rest} = smtp;
521
- return {...rest, hasPassword: typeof passwordSealed === 'string' && passwordSealed.length > 0};
522
- }
523
-
524
149
  /**
525
150
  * What this mailbox signs its mail with.
526
151
  *
@@ -565,27 +190,6 @@ export function identitiesToPublic(account) {
565
190
  * @param {object[]} identities
566
191
  * @returns {Promise<object|null>}
567
192
  */
568
- export async function setIdentities(userId, accountId, identities) {
569
- return withStoreLock(async () => {
570
- const all = await readAll();
571
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
572
- if (index === -1) return null;
573
-
574
- const cleaned = (Array.isArray(identities) ? identities : []).map(entry => ({
575
- ...entry,
576
- signatureHtml: sanitiseSignature(entry?.signatureHtml ?? '')
577
- }));
578
-
579
- const {identity, ...rest} = all[index];
580
- all[index] = {
581
- ...rest,
582
- identities: normaliseIdentityList({identities: cleaned}),
583
- updatedAt: new Date().toISOString()
584
- };
585
- await writeAll(all);
586
- return all[index];
587
- });
588
- }
589
193
 
590
194
  /**
591
195
  * The canned responses this mailbox holds.
@@ -608,26 +212,6 @@ export function templatesToPublic(account) {
608
212
  * @param {object[]} templates
609
213
  * @returns {Promise<object|null>}
610
214
  */
611
- export async function setTemplates(userId, accountId, templates) {
612
- return withStoreLock(async () => {
613
- const all = await readAll();
614
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
615
- if (index === -1) return null;
616
-
617
- const cleaned = (Array.isArray(templates) ? templates : []).map(entry => ({
618
- ...entry,
619
- bodyHtml: sanitiseSignature(entry?.bodyHtml ?? '')
620
- }));
621
-
622
- all[index] = {
623
- ...all[index],
624
- templates: normaliseTemplates({templates: cleaned}),
625
- updatedAt: new Date().toISOString()
626
- };
627
- await writeAll(all);
628
- return all[index];
629
- });
630
- }
631
215
 
632
216
  /**
633
217
  * The filing rules this mailbox runs, in order.
@@ -635,29 +219,7 @@ export async function setTemplates(userId, accountId, templates) {
635
219
  * @param {object|null} account
636
220
  * @returns {object[]}
637
221
  */
638
- export function rulesToPublic(account) {
639
- return normaliseRules(account);
640
- }
641
-
642
- /**
643
- * The groups this mailbox's rules are sorted into, in order.
644
- *
645
- * @param {object|null} account
646
- * @returns {{name: string, enabled: boolean}[]}
647
- */
648
- export function ruleGroupsToPublic(account) {
649
- return normaliseRuleGroups({ruleGroups: account?.ruleGroups, rules: normaliseRules(account)});
650
- }
651
222
 
652
- /**
653
- * The rules a sync pass runs: switched on, and not in a switched-off group.
654
- *
655
- * @param {object|null} account
656
- * @returns {object[]}
657
- */
658
- export function rulesToRun(account) {
659
- return rulesInEffect(normaliseRules(account), ruleGroupsToPublic(account));
660
- }
661
223
 
662
224
  /**
663
225
  * Store the filing rules for a mailbox.
@@ -673,26 +235,6 @@ export function rulesToRun(account) {
673
235
  * @param {object[]} rules
674
236
  * @returns {Promise<object|null>}
675
237
  */
676
- export async function setRules(userId, accountId, rules, groups = undefined) {
677
- return withStoreLock(async () => {
678
- const all = await readAll();
679
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
680
- if (index === -1) return null;
681
-
682
- const saved = normaliseRules({rules});
683
- all[index] = {
684
- ...all[index],
685
- rules: saved,
686
- // Only when given: a caller that knows nothing of groups (an older
687
- // screen) keeps the stored ones.
688
- ...(Array.isArray(groups) ? {ruleGroups: normaliseRuleGroups({ruleGroups: groups, rules: saved})} : {}),
689
- rulesFrom: all[index].rulesFrom ?? new Date().toISOString(),
690
- updatedAt: new Date().toISOString()
691
- };
692
- await writeAll(all);
693
- return all[index];
694
- });
695
- }
696
238
 
697
239
  /**
698
240
  * Which folders rules are applied to.
@@ -703,10 +245,6 @@ export async function setRules(userId, accountId, rules, groups = undefined) {
703
245
  * @param {object|null} account
704
246
  * @returns {string[]}
705
247
  */
706
- export function ruleFolders(account) {
707
- const chosen = Array.isArray(account?.ruleFolders) ? account.ruleFolders : null;
708
- return (chosen && chosen.length) ? chosen : ['INBOX'];
709
- }
710
248
 
711
249
  /**
712
250
  * How long this mailbox holds a message after Send, in seconds.
@@ -714,9 +252,7 @@ export function ruleFolders(account) {
714
252
  * @param {object|null} account
715
253
  * @returns {number}
716
254
  */
717
- export function undoSendSeconds(account) {
718
- return normaliseUndoSeconds(account?.undoSendSeconds);
719
- }
255
+
720
256
 
721
257
  /**
722
258
  * Set the sending behaviour that is neither the server nor the identity:
@@ -727,86 +263,7 @@ export function undoSendSeconds(account) {
727
263
  * @param {{undoSendSeconds?: number, snoozeFolder?: string, ruleFolders?: string[]}} options
728
264
  * @returns {Promise<object|null>}
729
265
  */
730
- export async function setSendingOptions(userId, accountId, options) {
731
- return withStoreLock(async () => {
732
- const all = await readAll();
733
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
734
- if (index === -1) return null;
735
-
736
- const folders = Array.isArray(options?.ruleFolders)
737
- ? [...new Set(options.ruleFolders.filter(f => typeof f === 'string' && f.trim()))]
738
- : null;
739
-
740
- all[index] = {
741
- ...all[index],
742
- undoSendSeconds: normaliseUndoSeconds(options?.undoSendSeconds),
743
- snoozeFolder: String(options?.snoozeFolder ?? '').trim() || null,
744
- ...(folders ? {ruleFolders: folders} : {}),
745
- updatedAt: new Date().toISOString()
746
- };
747
- await writeAll(all);
748
- return all[index];
749
- });
750
- }
751
-
752
- /**
753
- * How a new message from this mailbox starts out, and two rules about where
754
- * and how it leaves.
755
- *
756
- * All off by default, which is what every message sent before these existed
757
- * did. The receipts, signing and encryption are only where the compose
758
- * window's ticks START - each message can still change them. The other two
759
- * are the mailbox's rules and apply to every message:
760
- * `repliesInSourceFolder` files the copy of a reply beside the message it
761
- * answers instead of in Sent, and `requireSecureDelivery` refuses to send
762
- * unless the outgoing server promises TLS all the way (REQUIRETLS, RFC 8689).
763
- */
764
- export const COMPOSE_DEFAULTS = Object.freeze({
765
- readReceipt: false,
766
- deliveryReceipt: false,
767
- sign: false,
768
- encrypt: false,
769
- repliesInSourceFolder: false,
770
- requireSecureDelivery: false
771
- });
772
266
 
773
- /**
774
- * This mailbox's compose options, every key present.
775
- *
776
- * @param {object|null} account
777
- * @returns {typeof COMPOSE_DEFAULTS}
778
- */
779
- export function composeOptions(account) {
780
- const stored = account?.compose && typeof account.compose === 'object' ? account.compose : {};
781
- return Object.fromEntries(Object.keys(COMPOSE_DEFAULTS)
782
- .map(key => [key, stored[key] === true]));
783
- }
784
-
785
- /**
786
- * Store the compose options. Only the known switches, only as booleans; a key
787
- * left out keeps its stored value, so a screen that knows half of them cannot
788
- * switch the other half off.
789
- *
790
- * @param {string} userId
791
- * @param {string} accountId
792
- * @param {object} options
793
- * @returns {Promise<object|null>}
794
- */
795
- export async function setComposeOptions(userId, accountId, options) {
796
- return withStoreLock(async () => {
797
- const all = await readAll();
798
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
799
- if (index === -1) return null;
800
-
801
- const next = composeOptions(all[index]);
802
- for (const key of Object.keys(COMPOSE_DEFAULTS)) {
803
- if (typeof options?.[key] === 'boolean') next[key] = options[key];
804
- }
805
- all[index] = {...all[index], compose: next, updatedAt: new Date().toISOString()};
806
- await writeAll(all);
807
- return all[index];
808
- });
809
- }
810
267
 
811
268
  /**
812
269
  * Every address this mailbox sends as.
@@ -819,16 +276,7 @@ export async function setComposeOptions(userId, accountId, options) {
819
276
  * @param {object|null} account
820
277
  * @returns {string[]}
821
278
  */
822
- export function sendingAddresses(account) {
823
- const addresses = new Set();
824
- if (account?.username) addresses.add(String(account.username).trim().toLowerCase());
825
- const from = account?.smtp?.from;
826
- if (from) addresses.add(String(from).replace(/^.*<|>.*$/g, '').trim().toLowerCase());
827
- for (const identity of normaliseIdentityList(account)) {
828
- if (identity.address) addresses.add(identity.address.toLowerCase());
829
- }
830
- return [...addresses].filter(Boolean);
831
- }
279
+
832
280
 
833
281
  /**
834
282
  * The away message this mailbox is configured with.
@@ -836,9 +284,7 @@ export function sendingAddresses(account) {
836
284
  * @param {object|null} account
837
285
  * @returns {object}
838
286
  */
839
- export function vacationToPublic(account) {
840
- return normaliseVacation(account);
841
- }
287
+
842
288
 
843
289
  /**
844
290
  * Store the away message.
@@ -853,26 +299,7 @@ export function vacationToPublic(account) {
853
299
  * @param {object} vacation
854
300
  * @returns {Promise<object|null>}
855
301
  */
856
- export async function setVacation(userId, accountId, vacation) {
857
- return withStoreLock(async () => {
858
- const all = await readAll();
859
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
860
- if (index === -1) return null;
861
302
 
862
- all[index] = {
863
- ...all[index],
864
- vacation: normaliseVacation({
865
- vacation: {
866
- ...vacation,
867
- bodyHtml: sanitiseSignature(vacation?.bodyHtml ?? '')
868
- }
869
- }),
870
- updatedAt: new Date().toISOString()
871
- };
872
- await writeAll(all);
873
- return all[index];
874
- });
875
- }
876
303
 
877
304
  /** The folder snoozed mail waits in, for a mailbox that has not chosen one. */
878
305
  export const DEFAULT_SNOOZE_FOLDER = 'Snoozed';
@@ -883,9 +310,7 @@ export const DEFAULT_SNOOZE_FOLDER = 'Snoozed';
883
310
  * @param {object|null} account
884
311
  * @returns {string}
885
312
  */
886
- export function snoozeFolder(account) {
887
- return String(account?.snoozeFolder ?? '').trim() || DEFAULT_SNOOZE_FOLDER;
888
- }
313
+
889
314
 
890
315
  /**
891
316
  * Store the sending identity for a mailbox.
@@ -942,88 +367,6 @@ export async function setIdentity(userId, accountId, identity) {
942
367
  * @param {string} address
943
368
  * @returns {Promise<object|null>}
944
369
  */
945
- export async function trustImageSender(userId, accountId, address) {
946
- return withStoreLock(async () => {
947
- const clean = String(address ?? '').trim().toLowerCase();
948
- if (!clean) return null;
949
-
950
- const all = await readAll();
951
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
952
- if (index === -1) return null;
953
-
954
- const current = Array.isArray(all[index].imageSenders) ? all[index].imageSenders : [];
955
- if (current.includes(clean)) return all[index];
956
-
957
- all[index] = {...all[index], imageSenders: [...current, clean], updatedAt: new Date().toISOString()};
958
- await writeAll(all);
959
- return all[index];
960
- });
961
- }
962
-
963
- /**
964
- * Stop trusting a sender's images.
965
- *
966
- * @param {string} userId
967
- * @param {string} accountId
968
- * @param {string} address
969
- * @returns {Promise<object|null>}
970
- */
971
- export async function untrustImageSender(userId, accountId, address) {
972
- return withStoreLock(async () => {
973
- const clean = String(address ?? '').trim().toLowerCase();
974
- const all = await readAll();
975
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
976
- if (index === -1) return null;
977
-
978
- const current = Array.isArray(all[index].imageSenders) ? all[index].imageSenders : [];
979
- all[index] = {
980
- ...all[index],
981
- imageSenders: current.filter(a => a !== clean),
982
- updatedAt: new Date().toISOString()
983
- };
984
- await writeAll(all);
985
- return all[index];
986
- });
987
- }
988
-
989
- /**
990
- * Turn the whole remembering feature on or off for a mailbox.
991
- *
992
- * Off means the button is never offered and any existing list is ignored
993
- * without being thrown away - turning it back on should not mean rebuilding
994
- * a list someone curated.
995
- *
996
- * @param {string} userId
997
- * @param {string} accountId
998
- * @param {boolean} enabled
999
- * @returns {Promise<object|null>}
1000
- */
1001
- export async function setRememberImageSenders(userId, accountId, enabled) {
1002
- return withStoreLock(async () => {
1003
- const all = await readAll();
1004
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
1005
- if (index === -1) return null;
1006
-
1007
- all[index] = {...all[index], rememberImageSenders: !!enabled, updatedAt: new Date().toISOString()};
1008
- await writeAll(all);
1009
- return all[index];
1010
- });
1011
- }
1012
-
1013
- /**
1014
- * Should this message's remote images load without being asked?
1015
- *
1016
- * @param {object} account
1017
- * @param {Array<{address?: string}>} from
1018
- * @returns {boolean}
1019
- */
1020
- export function sendersImagesTrusted(account, from) {
1021
- if (account?.rememberImageSenders === false) return false;
1022
- const trusted = Array.isArray(account?.imageSenders) ? account.imageSenders : [];
1023
- if (!trusted.length) return false;
1024
- return (from ?? []).some(entry => trusted.includes(String(entry?.address ?? '').trim().toLowerCase()));
1025
- }
1026
-
1027
370
  /**
1028
371
  * Poll intervals a mailbox may be set to, in minutes.
1029
372
  *
@@ -1031,7 +374,7 @@ export function sendersImagesTrusted(account, from) {
1031
374
  * spend the day being rate-limited by their mail server, and the difference
1032
375
  * between 11 and 12 minutes is not worth a decision.
1033
376
  */
1034
- export const POLL_INTERVALS = [3, 5, 10, 15];
377
+ export {POLL_INTERVALS} from './accountRepository.js';
1035
378
 
1036
379
  /**
1037
380
  * Set how often a mailbox is polled.
@@ -1045,21 +388,6 @@ export const POLL_INTERVALS = [3, 5, 10, 15];
1045
388
  * @param {number|null} minutes
1046
389
  * @returns {Promise<{ok: true, account: object} | {ok: false, error: string}>}
1047
390
  */
1048
- export async function setPollInterval(userId, accountId, minutes) {
1049
- return withStoreLock(async () => {
1050
- if (minutes !== null && !POLL_INTERVALS.includes(minutes)) {
1051
- return {ok: false, error: `Poll interval must be one of ${POLL_INTERVALS.join(', ')} minutes.`};
1052
- }
1053
-
1054
- const all = await readAll();
1055
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
1056
- if (index === -1) return {ok: false, error: 'That mailbox does not exist.'};
1057
-
1058
- all[index] = {...all[index], pollIntervalMinutes: minutes, updatedAt: new Date().toISOString()};
1059
- await writeAll(all);
1060
- return {ok: true, account: all[index]};
1061
- });
1062
- }
1063
391
 
1064
392
  /**
1065
393
  * Every stored mailbox, for every user.
@@ -1069,9 +397,6 @@ export async function setPollInterval(userId, accountId, minutes) {
1069
397
  *
1070
398
  * @returns {Promise<object[]>}
1071
399
  */
1072
- export async function listAllAccounts() {
1073
- return readAll();
1074
- }
1075
400
 
1076
401
  /**
1077
402
  * Choose which folders to keep mirrored.
@@ -1085,268 +410,69 @@ export async function listAllAccounts() {
1085
410
  * @param {string[]|null} folders - explicit paths, or null to go back to the default
1086
411
  * @returns {Promise<object|null>} the stored record, or null if not theirs
1087
412
  */
1088
- export async function setSyncFolders(userId, accountId, folders) {
1089
- return withStoreLock(async () => {
1090
- const all = await readAll();
1091
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
1092
- if (index === -1) return null;
1093
-
1094
- const value = folders === null
1095
- ? null
1096
- : [...new Set(folders.filter(f => typeof f === 'string' && f.trim()))];
1097
-
1098
- all[index] = {...all[index], syncFolders: value, updatedAt: new Date().toISOString()};
1099
- await writeAll(all);
1100
- return all[index];
1101
- });
1102
- }
1103
413
 
1104
414
  /**
1105
- * Validate and normalise submitted account fields.
415
+ * How a new message from this mailbox starts out, and two rules about where
416
+ * and how it leaves.
1106
417
  *
1107
- * @param {object} input
1108
- * @param {object|null} existing
1109
- * @returns {{ok: true, value: object} | {ok: false, error: string}}
418
+ * All off by default, which is what every message sent before these existed
419
+ * did. The receipts, signing and encryption are only where the compose
420
+ * window's ticks START - each message can still change them. The other two
421
+ * are the mailbox's rules and apply to every message:
422
+ * `repliesInSourceFolder` files the copy of a reply beside the message it
423
+ * answers instead of in Sent, and `requireSecureDelivery` refuses to send
424
+ * unless the outgoing server promises TLS all the way (REQUIRETLS, RFC 8689).
1110
425
  */
1111
- export function validate(input, existing) {
1112
- const host = String(input.host ?? '').trim();
1113
- const username = String(input.username ?? '').trim();
1114
- const label = String(input.label ?? '').trim();
1115
- const port = Number(input.port ?? (input.secure === false ? 143 : 993));
1116
- const secure = input.secure !== false;
1117
- const password = typeof input.password === 'string' ? input.password : '';
1118
-
1119
- // A signed-in mailbox keeps its provider's servers and address: only the
1120
- // name is the person's to change here. A sign-in is changed by Reconnect.
1121
- if (isOAuth(existing)) {
1122
- return {ok: true, value: {
1123
- label: label || existing.label, host: existing.host, port: existing.port,
1124
- secure: existing.secure, username: existing.username, password: '', oauth: true
1125
- }};
1126
- }
1127
-
1128
- if (!host) return {ok: false, error: 'A mail server hostname is required.'};
1129
- if (!username) return {ok: false, error: 'A username is required.'};
1130
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
1131
- return {ok: false, error: 'Port must be a whole number between 1 and 65535.'};
1132
- }
1133
- if (!password && !existing?.passwordSealed) {
1134
- return {ok: false, error: 'A password is required.'};
1135
- }
1136
-
1137
- return {
1138
- ok: true,
1139
- value: {
1140
- label: label || host,
1141
- host,
1142
- port,
1143
- secure,
1144
- username,
1145
- // An empty password on update means "keep the one you have" - the
1146
- // admin form never round-trips the stored password, so a blank
1147
- // field is the normal case when editing the hostname.
1148
- password
1149
- }
1150
- };
1151
- }
426
+ export const COMPOSE_DEFAULTS = Object.freeze({
427
+ readReceipt: false,
428
+ deliveryReceipt: false,
429
+ sign: false,
430
+ encrypt: false,
431
+ repliesInSourceFolder: false,
432
+ requireSecureDelivery: false
433
+ });
1152
434
 
1153
435
  /**
1154
- * Every mailbox belonging to one user: the default first, then oldest first.
436
+ * This mailbox's compose options, every key present.
1155
437
  *
1156
- * @param {string} userId
1157
- * @returns {Promise<object[]>}
438
+ * @param {object|null} account
439
+ * @returns {typeof COMPOSE_DEFAULTS}
1158
440
  */
1159
- export async function listAccounts(userId) {
1160
- const all = await readAll();
1161
- return all
1162
- .filter(a => a.userId === userId)
1163
- .sort((a, b) => (b.isDefault === true) - (a.isDefault === true)
1164
- || String(a.createdAt).localeCompare(String(b.createdAt)));
441
+ export function composeOptions(account) {
442
+ const stored = account?.compose && typeof account.compose === 'object' ? account.compose : {};
443
+ return Object.fromEntries(Object.keys(COMPOSE_DEFAULTS)
444
+ .map(key => [key, stored[key] === true]));
1165
445
  }
1166
446
 
1167
447
  /**
1168
- * Make one mailbox this user's default, or clear the default.
1169
- *
1170
- * At most one per user, so setting it takes it off every other mailbox they
1171
- * own. The default is listed first and is the one the reader opens with.
448
+ * Store the compose options. Only the known switches, only as booleans; a key
449
+ * left out keeps its stored value, so a screen that knows half of them cannot
450
+ * switch the other half off.
1172
451
  *
1173
452
  * @param {string} userId
1174
453
  * @param {string} accountId
1175
- * @param {boolean} isDefault - false clears it from this mailbox only
1176
- * @returns {Promise<object|null>} the stored record, or null if not theirs
454
+ * @param {object} options
455
+ * @returns {Promise<object|null>}
1177
456
  */
1178
- export async function setDefaultAccount(userId, accountId, isDefault) {
457
+ export async function setComposeOptions(userId, accountId, options) {
1179
458
  return withStoreLock(async () => {
1180
459
  const all = await readAll();
1181
460
  const index = all.findIndex(a => a.id === accountId && a.userId === userId);
1182
461
  if (index === -1) return null;
1183
462
 
1184
- const now = new Date().toISOString();
1185
- for (let i = 0; i < all.length; i++) {
1186
- if (all[i].userId !== userId) continue;
1187
- const want = i === index ? !!isDefault : (isDefault ? false : all[i].isDefault === true);
1188
- if ((all[i].isDefault === true) !== want) all[i] = {...all[i], isDefault: want, updatedAt: now};
463
+ const next = composeOptions(all[index]);
464
+ for (const key of Object.keys(COMPOSE_DEFAULTS)) {
465
+ if (typeof options?.[key] === 'boolean') next[key] = options[key];
1189
466
  }
467
+ all[index] = {...all[index], compose: next, updatedAt: new Date().toISOString()};
1190
468
  await writeAll(all);
1191
469
  return all[index];
1192
470
  });
1193
471
  }
1194
472
 
1195
- /**
1196
- * One mailbox, but only if this user owns it.
1197
- *
1198
- * Takes both ids on purpose: there is no way to ask for an account without
1199
- * saying who is asking.
1200
- *
1201
- * @param {string} userId
1202
- * @param {string} accountId
1203
- * @returns {Promise<object|null>}
1204
- */
1205
- export async function getAccount(userId, accountId) {
1206
- const all = await readAll();
1207
- return all.find(a => a.id === accountId && a.userId === userId) ?? null;
1208
- }
1209
-
1210
- /**
1211
- * Create a mailbox, or update one this user owns.
1212
- *
1213
- * @param {string} userId
1214
- * @param {string|null} accountId - null to create
1215
- * @param {object} fields - output of validate()
1216
- * @returns {Promise<object|null>} the stored record, or null if not theirs
1217
- */
1218
- export async function saveAccount(userId, accountId, fields) {
1219
- return withStoreLock(async () => {
1220
- const all = await readAll();
1221
- const now = new Date().toISOString();
1222
-
1223
- if (accountId) {
1224
- const index = all.findIndex(a => a.id === accountId && a.userId === userId);
1225
- if (index === -1) return null;
1226
- const existing = all[index];
1227
- if (isOAuth(existing)) {
1228
- all[index] = {...existing, label: fields.label, updatedAt: now};
1229
- await writeAll(all);
1230
- return all[index];
1231
- }
1232
- all[index] = {
1233
- ...existing,
1234
- label: fields.label,
1235
- host: fields.host,
1236
- port: fields.port,
1237
- secure: fields.secure,
1238
- username: fields.username,
1239
- passwordSealed: fields.password ? seal(fields.password) : existing.passwordSealed,
1240
- updatedAt: now
1241
- };
1242
- await writeAll(all);
1243
- return all[index];
1244
- }
1245
-
1246
- const record = {
1247
- id: randomUUID(),
1248
- userId,
1249
- label: fields.label,
1250
- host: fields.host,
1251
- port: fields.port,
1252
- secure: fields.secure,
1253
- username: fields.username,
1254
- passwordSealed: seal(fields.password),
1255
- createdAt: now,
1256
- updatedAt: now
1257
- };
1258
- all.push(record);
1259
- await writeAll(all);
1260
- return record;
1261
- });
1262
- }
1263
-
1264
- /**
1265
- * Remove a mailbox this user owns.
1266
- *
1267
- * @param {string} userId
1268
- * @param {string} accountId
1269
- * @returns {Promise<boolean>} true when something was removed
1270
- */
1271
- export async function deleteAccount(userId, accountId) {
1272
- return withStoreLock(async () => {
1273
- const all = await readAll();
1274
- const next = all.filter(a => !(a.id === accountId && a.userId === userId));
1275
- if (next.length === all.length) return false;
1276
- await writeAll(next);
1277
- return true;
1278
- });
1279
- }
1280
-
1281
- /**
1282
- * Forget every mailbox belonging to one user.
1283
- *
1284
- * Called when a CMS user is deleted. Their stored passwords have no owner
1285
- * left and must not outlive the account.
1286
- *
1287
- * @param {string} userId
1288
- * @returns {Promise<number>} how many were removed
1289
- */
1290
- export async function deleteAccountsForUser(userId) {
1291
- return withStoreLock(async () => {
1292
- const all = await readAll();
1293
- const next = all.filter(a => a.userId !== userId);
1294
- const removed = all.length - next.length;
1295
- if (removed) await writeAll(next);
1296
- return removed;
1297
- });
1298
- }
1299
-
1300
- /**
1301
- * Drop mailboxes whose owner no longer exists.
1302
- *
1303
- * The `user:deleted` hook covers the normal case, but only while a plugin
1304
- * using this core is loaded to hear it - a user deleted while the Mail Reader
1305
- * was disabled would otherwise leave credentials behind for good. This sweeps
1306
- * those up on the next start, so the hook is the fast path rather than the
1307
- * only one.
1308
- *
1309
- * @param {Set<string>|string[]} existingUserIds
1310
- * @returns {Promise<number>} how many were removed
1311
- */
1312
- export async function pruneOrphans(existingUserIds) {
1313
- return withStoreLock(async () => {
1314
- const live = existingUserIds instanceof Set ? existingUserIds : new Set(existingUserIds);
1315
- const all = await readAll();
1316
- const next = all.filter(a => live.has(a.userId));
1317
- const removed = all.length - next.length;
1318
- if (removed) await writeAll(next);
1319
- return removed;
1320
- });
1321
- }
1322
-
1323
- /**
1324
- * Build an ImapFlow-shaped connection config.
1325
- *
1326
- * Throws MailKeyError (from secretbox) if the stored password cannot be
1327
- * opened - callers surface that message directly, it is written for humans.
1328
- *
1329
- * @param {object} account
1330
- * @returns {{host: string, port: number, secure: boolean, auth: {user: string, pass: string}}}
1331
- */
1332
- export function toConnection(account) {
1333
- if (isOAuth(account)) {
1334
- const {accessToken, expiresAt} = storedAccess(account);
1335
- return {
1336
- host: account.host,
1337
- port: account.port,
1338
- secure: account.secure,
1339
- auth: {user: account.username, accessToken},
1340
- // Read by the pool (imapPool.js): renew under a minute before
1341
- // expiry, and once after a refused login. ImapFlow never sees them.
1342
- expiresAt,
1343
- refresh: refresher(account)
1344
- };
1345
- }
1346
- return {
1347
- host: account.host,
1348
- port: account.port,
1349
- secure: account.secure,
1350
- auth: {user: account.username, pass: open(account.passwordSealed)}
1351
- };
1352
- }
473
+ /** Account lifecycle is authored in domma-mail/packages/core/src/mail/accountRepository.js. */
474
+ export const {
475
+ sieveToPublic, setSieve, vacationToPublic, sendingAddresses, setVacation, snoozeFolder, undoSendSeconds, setSendingOptions, rulesToPublic, ruleGroupsToPublic, rulesToRun, ruleFolders, setRules, rewriteFolderPaths, setIdentities, setTemplates, listAllAccounts, setPollInterval, setSyncFolders, validate, listAccounts, setDefaultAccount, getAccount, saveAccount,
476
+ deleteAccount, deleteAccountsForUser, pruneOrphans, toConnection,
477
+ setSmtp, toSmtpConnection, smtpToPublic, trustImageSender, untrustImageSender, setRememberImageSenders, sendersImagesTrusted
478
+ } = baseAccounts;