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
@@ -0,0 +1,10 @@
1
+ /** Serialize mode changes with sync so an in-flight pass cannot run stale CMS rules. */
2
+ const queues = new Map();
3
+
4
+ export async function withMailAutomation(accountId, action) {
5
+ const previous = queues.get(accountId) ?? Promise.resolve();
6
+ const run = previous.catch(() => {}).then(action);
7
+ queues.set(accountId, run);
8
+ try { return await run; }
9
+ finally { if (queues.get(accountId) === run) queues.delete(accountId); }
10
+ }
@@ -0,0 +1,36 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/bodyTokenProvider.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ import {createHmac, timingSafeEqual} from 'node:crypto';
4
+
5
+ const DOMAIN = 'domma-mail-body-v1';
6
+ const TTL_MS = 120_000;
7
+
8
+ /** Narrow iframe grants, using this mail instance's key rather than its login key. */
9
+ export function createBodyTokens({resolveKeySource, now = Date.now} = {}) {
10
+ if (typeof resolveKeySource !== 'function') throw new Error('A mail key provider is required.');
11
+ function signature(body) {
12
+ const {secret} = resolveKeySource();
13
+ return createHmac('sha256', DOMAIN + ':' + secret).update(body).digest('base64url');
14
+ }
15
+ function sign(grant) {
16
+ const payload = {u: grant.userId, a: grant.accountId, f: grant.folder, m: grant.uid, i: grant.images ? 1 : 0, e: now() + TTL_MS};
17
+ const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
18
+ return `${body}.${signature(body)}`;
19
+ }
20
+ function verify(token) {
21
+ if (typeof token !== 'string' || token.length > 8192) return null;
22
+ const parts = token.split('.');
23
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
24
+ const [body, provided] = parts;
25
+ const actual = Buffer.from(provided);
26
+ const expected = Buffer.from(signature(body));
27
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return null;
28
+ let payload;
29
+ try { payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')); }
30
+ catch { return null; }
31
+ if (!Number.isFinite(payload?.e) || now() >= payload.e || typeof payload.u !== 'string' || !payload.u
32
+ || typeof payload.a !== 'string' || !payload.a || !Number.isSafeInteger(payload.m) || payload.m < 1) return null;
33
+ return {userId: payload.u, accountId: payload.a, folder: typeof payload.f === 'string' ? payload.f : 'INBOX', uid: payload.m, images: payload.i === 1};
34
+ }
35
+ return {sign, verify};
36
+ }
@@ -1,101 +1,7 @@
1
- /**
2
- * Short-lived tokens authorising one message body fetch.
3
- *
4
- * ## Why this exists
5
- *
6
- * A message renders inside an iframe. The obvious way to fill that iframe is
7
- * `srcdoc`, and that is what the reader did first - but a `srcdoc` document
8
- * **inherits the embedding page's Content-Security-Policy**, and the admin is
9
- * served with `img-src 'self' data: blob:`. The consequence was that "Load
10
- * images" could flip the `src` to the real URL and the browser would then
11
- * refuse to fetch it, silently, with no request ever made. The feature could
12
- * not work, however correct the server was.
13
- *
14
- * A document loaded over the network carries its own CSP instead of
15
- * inheriting, so the body is served from a real route. That route cannot read
16
- * an Authorization header - an `<iframe src>` sends none - so the URL carries
17
- * a signed token that says exactly which message, for which user, and for how
18
- * long. Same shape as the CMS's own preview links.
19
- *
20
- * The token is deliberately narrow: it names one mailbox, one folder and one
21
- * message, it expires in minutes, and it grants nothing else.
22
- *
23
- * @module _lib/mail/bodyTokens
24
- */
25
- import {createHmac, timingSafeEqual} from 'node:crypto';
26
-
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/bodyTokens.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /** CMS compatibility entry point for the existing iframe grant API. */
27
4
  import {resolveKeySource} from './secretbox.js';
5
+ import {createBodyTokens} from './bodyTokenProvider.js';
28
6
 
29
- /** Domain separation, so this key can never collide with the sealing key. */
30
- const DOMAIN = 'domma-mail-body-v1';
31
-
32
- /** How long a token stays valid. Long enough to load a page, short enough not to matter. */
33
- const TTL_MS = 120_000;
34
-
35
- /**
36
- * Sign a payload.
37
- *
38
- * @param {string} body - base64url payload
39
- * @returns {string} base64url signature
40
- */
41
- function signature(body) {
42
- const {secret} = resolveKeySource();
43
- return createHmac('sha256', DOMAIN + ':' + secret).update(body).digest('base64url');
44
- }
45
-
46
- /**
47
- * Mint a token authorising one message body fetch.
48
- *
49
- * @param {{userId: string, accountId: string, folder: string, uid: number, images: boolean}} grant
50
- * @returns {string}
51
- */
52
- export function sign(grant) {
53
- const payload = {
54
- u: grant.userId,
55
- a: grant.accountId,
56
- f: grant.folder,
57
- m: grant.uid,
58
- i: grant.images ? 1 : 0,
59
- e: Date.now() + TTL_MS
60
- };
61
- const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
62
- return `${body}.${signature(body)}`;
63
- }
64
-
65
- /**
66
- * Check a token and return what it authorises.
67
- *
68
- * @param {string} token
69
- * @returns {{userId: string, accountId: string, folder: string, uid: number, images: boolean}|null}
70
- */
71
- export function verify(token) {
72
- if (typeof token !== 'string' || !token.includes('.')) return null;
73
-
74
- const [body, provided] = token.split('.');
75
- if (!body || !provided) return null;
76
-
77
- const expected = signature(body);
78
- // Compare in constant time, and only when the lengths already match -
79
- // timingSafeEqual throws on a length mismatch.
80
- const a = Buffer.from(provided);
81
- const b = Buffer.from(expected);
82
- if (a.length !== b.length || !timingSafeEqual(a, b)) return null;
83
-
84
- let payload;
85
- try {
86
- payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
87
- } catch {
88
- return null;
89
- }
90
-
91
- if (typeof payload?.e !== 'number' || Date.now() > payload.e) return null;
92
- if (!payload.u || !payload.a || typeof payload.m !== 'number') return null;
93
-
94
- return {
95
- userId: payload.u,
96
- accountId: payload.a,
97
- folder: typeof payload.f === 'string' ? payload.f : 'INBOX',
98
- uid: payload.m,
99
- images: payload.i === 1
100
- };
101
- }
7
+ export const {sign, verify} = createBodyTokens({resolveKeySource});
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/compose.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Turning a message into a reply, and a reply into something sendable.
3
5
  *
@@ -36,12 +38,12 @@ export function replyRecipients(message) {
36
38
  * client then has to file.
37
39
  *
38
40
  * @param {object} message
39
- * @param {string} self - the address replying
41
+ * @param {string|string[]} self - the mailbox and alias addresses replying
40
42
  * @returns {{to: object[], cc: object[]}}
41
43
  */
42
44
  export function replyAllRecipients(message, self) {
43
- const mine = String(self ?? '').trim().toLowerCase();
44
- const notMine = list => (list ?? []).filter(a => String(a.address ?? '').toLowerCase() !== mine);
45
+ const mine = new Set((Array.isArray(self) ? self : [self]).map(address => String(address ?? '').trim().toLowerCase()));
46
+ const notMine = list => (list ?? []).filter(a => !mine.has(String(a.address ?? '').toLowerCase()));
45
47
 
46
48
  const to = replyRecipients(message);
47
49
  const seen = new Set(to.map(a => String(a.address ?? '').toLowerCase()));
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/defaults.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Reading defaults, shared by every edition.
3
5
  *
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/envelope.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * The shape the mirror holds one message in.
3
5
  *
@@ -37,7 +39,7 @@ export const ENVELOPE_QUERY = {
37
39
  // per message later: the responder runs over new mail on every poll,
38
40
  // and a second round trip per message to read three headers would be
39
41
  // the most expensive part of the feature.
40
- 'auto-submitted', 'precedence', 'return-path'
42
+ 'auto-submitted', 'precedence', 'return-path', 'list-unsubscribe', 'list-post', 'list-help', 'x-auto-response-suppress'
41
43
  ]
42
44
  };
43
45
 
@@ -0,0 +1,83 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/folderActions.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /** Whole-folder operations use a snapshot of UIDs, never the visible page or a moving '*'. */
4
+ import {moveBulk, setFlagsBulk} from './write.js';
5
+
6
+ const ACTIONS = new Set(['markRead', 'markUnread', 'clear', 'emptyTrash']);
7
+ const fail = (message, statusCode = 409) => Object.assign(new Error(message), {statusCode, folderActionError: true});
8
+
9
+ export async function actOnFolder({pool, store, account, poolKey, connection, path, action, confirmed = false}) {
10
+ if (typeof path !== 'string' || !path || path.length > 1024 || /[\x00-\x1f\x7f]/.test(path)
11
+ || !ACTIONS.has(action)) throw fail('Choose a folder and a supported folder action.', 400);
12
+ const destructive = action === 'clear' || action === 'emptyTrash';
13
+ if (destructive && confirmed !== true) throw fail('Confirm the folder contents action first.', 400);
14
+ const boxes = await pool.withClient(poolKey, connection, client => client.list());
15
+ const folder = boxes.find(box => box.path === path);
16
+ if (!folder) throw fail('That folder does not exist.', 404);
17
+ if (folder.flags?.has('\\Noselect')) throw fail('This folder cannot hold messages.');
18
+ const trash = boxes.find(box => box.specialUse === '\\Trash');
19
+ if (destructive && ['\\All', '\\Flagged'].includes(folder.specialUse)) {
20
+ throw fail('Clear a regular folder instead of a combined message view.');
21
+ }
22
+ if (action === 'clear' && (!trash || trash.path === path)) {
23
+ throw fail(trash ? 'Use Empty Trash to permanently delete messages from Trash.' : 'This mailbox has no Trash folder, so its contents cannot be cleared safely.');
24
+ }
25
+ if (action === 'emptyTrash' && folder.specialUse !== '\\Trash') throw fail('Only Trash can be emptied permanently.');
26
+
27
+ const snapshot = await pool.withMailbox(poolKey, connection, path, async client => {
28
+ if (destructive && !client.capabilities?.has('UIDPLUS')
29
+ && (action === 'emptyTrash' || !client.capabilities?.has('MOVE'))) {
30
+ throw fail('This server cannot safely remove only the selected folder contents.');
31
+ }
32
+ const query = action === 'markRead' ? {seen: false} : action === 'markUnread' ? {seen: true} : {all: true};
33
+ const uids = await client.search(query, {uid: true});
34
+ if (!Array.isArray(uids)) throw fail('The server could not list the folder contents.', 502);
35
+ return {uids, validity: String(client.mailbox.uidValidity)};
36
+ });
37
+ let processed = 0;
38
+ // Bulk helpers open their own mailbox locks. Recheck UIDVALIDITY inside
39
+ // every lock so a recreated folder cannot reuse captured UIDs for new mail.
40
+ const guardedPool = {
41
+ withClient: pool.withClient.bind(pool),
42
+ withMailbox: (key, conn, folderPath, fn, options) => pool.withMailbox(key, conn, folderPath, client => {
43
+ if (folderPath === path && String(client.mailbox.uidValidity) !== snapshot.validity) {
44
+ throw fail('The folder changed on the server. Refresh it before trying again.');
45
+ }
46
+ const checked = new Proxy(client, {get(target, property) {
47
+ const value = Reflect.get(target, property, target);
48
+ if (typeof value !== 'function') return value;
49
+ if (!['messageMove', 'messageFlagsAdd', 'messageFlagsRemove', 'messageDelete'].includes(property)) return value.bind(target);
50
+ return async (...args) => {
51
+ if (property === 'messageMove' && !target.capabilities?.has('MOVE') && !target.capabilities?.has('UIDPLUS')) throw fail('This server cannot safely move only the folder contents.');
52
+ if (property === 'messageDelete' && !target.capabilities?.has('UIDPLUS')) throw fail('This server cannot safely remove only the folder contents.');
53
+ const result = await value.apply(target, args);
54
+ if (result === false) throw fail('The mail server refused the folder action.', 502);
55
+ return result;
56
+ };
57
+ }});
58
+ return fn(checked);
59
+ }, options)
60
+ };
61
+ try {
62
+ for (let at = 0; at < snapshot.uids.length; at += 500) {
63
+ const uids = snapshot.uids.slice(at, at + 500);
64
+ const set = uids.join(',');
65
+ const deps = {pool: guardedPool, store, account, poolKey, connection, folder: path, uids, set};
66
+ if (action === 'clear') await moveBulk({...deps, destination: trash.path});
67
+ else if (action === 'emptyTrash') {
68
+ await guardedPool.withMailbox(poolKey, connection, path,
69
+ client => client.messageDelete({uid: set}, {uid: true}), {writable: true});
70
+ if (store) await store.removeMessages(account.id, path, uids);
71
+ } else {
72
+ await setFlagsBulk({...deps, add: action === 'markRead' ? ['\\Seen'] : [], remove: action === 'markUnread' ? ['\\Seen'] : []});
73
+ }
74
+ processed += uids.length;
75
+ }
76
+ } catch (err) {
77
+ err.processedMessages = processed;
78
+ err.requestedMessages = snapshot.uids.length;
79
+ err.message += ` ${processed} of ${snapshot.uids.length} messages processed. Refresh the folder to check its current contents.`;
80
+ throw err;
81
+ }
82
+ return {path, action, processed, movedTo: action === 'clear' ? trash.path : null, permanent: action === 'emptyTrash'};
83
+ }
@@ -0,0 +1,109 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/folderRuntime.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /** Portable folder operations. Hosts supply ownership, serialization and metadata updates. */
4
+ import {validateFolderName, buildFolderPath, renameTarget, canModifyFolder, descendantsOf, moveTarget, resolveSubscriptions} from './folders.js';
5
+
6
+ const fail = (message, statusCode = 409) => Object.assign(new Error(message), {statusCode, publicFolderError: true});
7
+ const validPath = path => typeof path === 'string' && path.length > 0 && path.length <= 1024 && !/[\x00-\x1f\x7f]/.test(path);
8
+ const checked = result => {if (result === false) throw fail('The mail server refused the folder change.', 502); return result;};
9
+ const requirePath = path => {if (!validPath(path)) throw fail('Choose a valid folder path.', 400);};
10
+ const find = (boxes, path) => {requirePath(path); const box = boxes.find(item => item.path === path); if (!box) throw fail('That folder does not exist.', 404); return box;};
11
+ const delimiterOf = box => box?.delimiter ?? '';
12
+ const allowed = (box, action) => {const result = canModifyFolder(box, {action}); if (!result.ok) throw fail(result.error);};
13
+ const nameCheck = (name, delimiter) => {
14
+ if (typeof name !== 'string') throw fail('A folder needs a name.', 400);
15
+ const result = validateFolderName(name, delimiter);
16
+ if (!result.ok) throw fail(result.error, 400);
17
+ };
18
+ async function changed(result, afterChange) {
19
+ try { await afterChange?.(result); }
20
+ catch { result.metadataPending = true; }
21
+ return result;
22
+ }
23
+
24
+ export async function createFolder({pool, poolKey, connection, name, parent = '', beforeChange, afterChange}) {
25
+ return pool.withClient(poolKey, connection, async client => {
26
+ const boxes = await client.list();
27
+ if (typeof parent !== 'string' || (parent && !validPath(parent))) throw fail('Choose a valid parent folder.', 400);
28
+ const parentBox = parent ? find(boxes, parent) : null;
29
+ const delimiter = delimiterOf(parentBox ?? boxes[0]);
30
+ if (parent && !delimiter) throw fail('This mailbox does not support nested folders.', 400);
31
+ nameCheck(name, delimiter);
32
+ const path = buildFolderPath(parent, name, delimiter);
33
+ requirePath(path);
34
+ if (boxes.some(box => box.path === path)) throw fail('A folder with that path already exists.');
35
+ await beforeChange?.([{from: null, to: path}]);
36
+ checked(await client.mailboxCreate(path));
37
+ let subscribed = true;
38
+ try {subscribed = (await client.mailboxSubscribe(path)) !== false;} catch {subscribed = false;}
39
+ return changed({created: true, path, subscribed, changes: [{from: null, to: path}]}, afterChange);
40
+ });
41
+ }
42
+
43
+ export async function renameFolder({pool, poolKey, connection, path, name, parent, moving = false, beforeChange, afterChange}) {
44
+ return pool.withClient(poolKey, connection, async client => {
45
+ const boxes = await client.list();
46
+ const folder = find(boxes, path), delimiter = delimiterOf(folder);
47
+ const children = descendantsOf(path, boxes, delimiter);
48
+ for (const item of [folder, ...children.map(child => find(boxes, child))]) allowed(item, moving ? 'move' : 'rename');
49
+ let target;
50
+ if (moving) {
51
+ const result = moveTarget(folder, parent, boxes, delimiter);
52
+ if (!result.ok) throw fail(result.error, result.status);
53
+ target = result.path;
54
+ } else {
55
+ nameCheck(name, delimiter);
56
+ target = renameTarget(path, name.trim(), delimiter);
57
+ }
58
+ requirePath(target);
59
+ if (path === target) return {renamed: false, path, changes: []};
60
+ const changes = [path, ...children].map(from => ({from, to: target + from.slice(path.length)}));
61
+ const old = new Set(changes.map(item => item.from));
62
+ for (const item of changes) {
63
+ requirePath(item.to);
64
+ if (boxes.some(box => box.path === item.to && !old.has(box.path))) throw fail('A folder with that destination already exists.');
65
+ }
66
+ await beforeChange?.(changes);
67
+ checked(await client.mailboxRename(path, target));
68
+ return changed({renamed: true, from: path, path: target, changes}, afterChange);
69
+ });
70
+ }
71
+
72
+ export async function deleteFolder({pool, poolKey, connection, path, confirmed = false, beforeChange, afterChange}) {
73
+ return pool.withClient(poolKey, connection, async client => {
74
+ const boxes = await client.list();
75
+ const folder = find(boxes, path);
76
+ const children = descendantsOf(path, boxes, delimiterOf(folder));
77
+ for (const item of [folder, ...children.map(child => find(boxes, child))]) allowed(item, 'delete');
78
+ if (confirmed !== true) throw fail('Confirm permanent deletion of the folder and its contents first.', 400);
79
+ await beforeChange?.([...children, path].map(from => ({from, to: null})));
80
+ const removed = [];
81
+ let metadataPending = false;
82
+ try {
83
+ for (const gone of [...children, path]) {
84
+ checked(await client.mailboxDelete(gone));
85
+ removed.push(gone);
86
+ const result = await changed({changes: [{from: gone, to: null}]}, afterChange);
87
+ metadataPending ||= result.metadataPending === true;
88
+ }
89
+ } catch (error) {
90
+ error.removedFolders = removed;
91
+ throw error;
92
+ }
93
+ return {deleted: true, path, alsoDeleted: children, changes: removed.map(from => ({from, to: null})), ...(metadataPending ? {metadataPending} : {})};
94
+ });
95
+ }
96
+
97
+ export async function subscribeFolder({pool, poolKey, connection, path, subscribed}) {
98
+ if (typeof subscribed !== 'boolean') throw fail('Choose whether to show this folder.', 400);
99
+ return pool.withClient(poolKey, connection, async client => {
100
+ find(await client.list(), path);
101
+ if (!subscribed && path.toUpperCase() === 'INBOX') throw fail('The Inbox cannot be hidden.');
102
+ checked(await (subscribed ? client.mailboxSubscribe(path) : client.mailboxUnsubscribe(path)));
103
+ const visible = resolveSubscriptions(await client.list());
104
+ if (!visible.has(path)) throw fail('The folder disappeared while changing its subscription.');
105
+ const actual = visible.get(path) !== false;
106
+ if (actual !== subscribed) throw fail('The server did not apply the folder subscription.');
107
+ return {path, subscribed: actual};
108
+ });
109
+ }
@@ -1,3 +1,6 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/mail/folders.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ import {resolveSubscriptions} from './subscriptions.js';
1
4
  /**
2
5
  * Creating, renaming and deleting mailboxes.
3
6
  *
@@ -181,15 +184,7 @@ export function descendantsOf(path, folders, delimiter) {
181
184
  * @param {{path: string, subscribed?: boolean}[]} boxes
182
185
  * @returns {Map<string, boolean>} path -> visible
183
186
  */
184
- export function resolveSubscriptions(boxes) {
185
- const list = boxes ?? [];
186
- const serverAnswers = list.some(box => box.subscribed === true);
187
- const out = new Map();
188
- for (const box of list) {
189
- out.set(box.path, serverAnswers ? box.subscribed === true : true);
190
- }
191
- return out;
192
- }
187
+ export {resolveSubscriptions};
193
188
 
194
189
  /** Validate a folder move before sending an IMAP rename. */
195
190
  export function moveTarget(folder, parent, folders, delimiter) {