emailengine-app 2.79.7 → 2.79.9

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 (188) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +37 -0
  5. package/DOCKER_DEPLOYMENT.md +8 -7
  6. package/Dockerfile +35 -11
  7. package/bin/emailengine.js +29 -13
  8. package/config/default.toml +15 -4
  9. package/copy-static-files.sh +23 -5
  10. package/data/google-crawlers.json +7 -1
  11. package/docker-compose.yml +12 -3
  12. package/install.sh +2 -0
  13. package/lib/account.js +26 -1
  14. package/lib/api-routes/account-routes.js +14 -3
  15. package/lib/api-routes/bull-board-routes.js +3 -2
  16. package/lib/api-routes/mailbox-routes.js +4 -1
  17. package/lib/api-routes/message-routes.js +6 -5
  18. package/lib/api-routes/outbox-routes.js +7 -4
  19. package/lib/api-routes/route-helpers.js +8 -0
  20. package/lib/api-routes/settings-routes.js +34 -25
  21. package/lib/api-routes/stats-routes.js +8 -1
  22. package/lib/api-routes/submit-routes.js +2 -1
  23. package/lib/api-routes/template-routes.js +3 -2
  24. package/lib/auth-token.js +73 -2
  25. package/lib/autodetect-imap-settings.js +33 -25
  26. package/lib/bounce-detect.js +45 -0
  27. package/lib/consts.js +13 -2
  28. package/lib/egress-fetch.js +133 -0
  29. package/lib/egress-filter.js +39 -4
  30. package/lib/email-client/base-client.js +274 -24
  31. package/lib/email-client/gmail/gmail-api.js +15 -7
  32. package/lib/email-client/gmail-client.js +121 -64
  33. package/lib/email-client/imap/mailbox.js +18 -59
  34. package/lib/email-client/imap-client.js +53 -29
  35. package/lib/email-client/notification-handler.js +11 -2
  36. package/lib/email-client/outlook/graph-api.js +106 -90
  37. package/lib/email-client/outlook-client.js +222 -106
  38. package/lib/export.js +35 -2
  39. package/lib/generate-text-preview.js +10 -5
  40. package/lib/handlebars-helpers.js +129 -0
  41. package/lib/headers-rewriter.js +1 -1
  42. package/lib/imap-proxy-auth.js +41 -21
  43. package/lib/imapproxy/imap-core/README.md +1 -0
  44. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  45. package/lib/imapproxy/imap-server.js +9 -10
  46. package/lib/llm-pre-process.js +4 -1
  47. package/lib/mcp/json-schema.js +50 -2
  48. package/lib/openapi/index.js +3 -0
  49. package/lib/outbox.js +50 -8
  50. package/lib/pre-process.js +4 -1
  51. package/lib/rate-limit.js +23 -4
  52. package/lib/rewrite-text-nodes.js +12 -1
  53. package/lib/schemas.js +37 -8
  54. package/lib/security-headers.js +396 -0
  55. package/lib/sentry.js +36 -4
  56. package/lib/settings.js +19 -1
  57. package/lib/smtp-auth.js +86 -7
  58. package/lib/sso.js +13 -3
  59. package/lib/submit-progress.js +29 -0
  60. package/lib/templates.js +11 -0
  61. package/lib/tools.js +361 -173
  62. package/lib/ui-routes/account-routes.js +73 -13
  63. package/lib/ui-routes/admin-config-routes.js +7 -21
  64. package/lib/ui-routes/admin-entities-routes.js +42 -12
  65. package/lib/ui-routes/auth-routes.js +87 -28
  66. package/lib/ui-routes/dashboard-routes.js +1 -1
  67. package/lib/ui-routes/export-routes.js +4 -0
  68. package/lib/ui-routes/internals-routes.js +2 -0
  69. package/lib/ui-routes/mcp-consent-routes.js +12 -2
  70. package/lib/ui-routes/network-config-routes.js +6 -5
  71. package/lib/ui-routes/oauth-config-routes.js +12 -1
  72. package/lib/ui-routes/route-helpers.js +65 -14
  73. package/lib/ui-routes/settings-page.js +10 -0
  74. package/lib/ui-routes/smtp-test-routes.js +7 -0
  75. package/lib/ui-routes/suppression-list-routes.js +16 -5
  76. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  77. package/lib/webhook-egress.js +5 -0
  78. package/lib/webhooks.js +14 -2
  79. package/package.json +23 -26
  80. package/sbom.json +1 -1
  81. package/server.js +100 -71
  82. package/static/css/flyonui.css +1 -1
  83. package/static/js/ace/css/ace.css +1462 -0
  84. package/static/js/ace/css/kuroir-1.png +0 -0
  85. package/static/js/ace/css/kuroir-2.png +0 -0
  86. package/static/js/ace/css/main-1.png +0 -0
  87. package/static/js/ace/css/main-10.svg +4 -0
  88. package/static/js/ace/css/main-11.svg +5 -0
  89. package/static/js/ace/css/main-12.svg +4 -0
  90. package/static/js/ace/css/main-13.png +0 -0
  91. package/static/js/ace/css/main-14.png +0 -0
  92. package/static/js/ace/css/main-15.png +0 -0
  93. package/static/js/ace/css/main-16.png +0 -0
  94. package/static/js/ace/css/main-17.png +0 -0
  95. package/static/js/ace/css/main-18.png +0 -0
  96. package/static/js/ace/css/main-19.png +0 -0
  97. package/static/js/ace/css/main-2.png +0 -0
  98. package/static/js/ace/css/main-20.png +0 -0
  99. package/static/js/ace/css/main-21.png +0 -0
  100. package/static/js/ace/css/main-22.png +0 -0
  101. package/static/js/ace/css/main-23.png +0 -0
  102. package/static/js/ace/css/main-24.png +0 -0
  103. package/static/js/ace/css/main-25.svg +1 -0
  104. package/static/js/ace/css/main-26.png +0 -0
  105. package/static/js/ace/css/main-3.png +0 -0
  106. package/static/js/ace/css/main-4.png +0 -0
  107. package/static/js/ace/css/main-5.svg +7 -0
  108. package/static/js/ace/css/main-6.svg +9 -0
  109. package/static/js/ace/css/main-7.svg +7 -0
  110. package/static/js/ace/css/main-8.svg +9 -0
  111. package/static/js/ace/css/main-9.svg +6 -0
  112. package/static/js/ace/css/theme/kuroir.css +78 -0
  113. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  114. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  115. package/static/js/ace/css/theme/xcode.css +106 -0
  116. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  117. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  118. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  119. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  120. package/static/js/ace/css/xcode-1.png +0 -0
  121. package/static/js/ace/css/xcode-2.png +0 -0
  122. package/static/js/ee-client.js +256 -102
  123. package/static/js/public.js +7 -0
  124. package/static/js/ui.js +32 -0
  125. package/static/licenses.html +338 -298
  126. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  127. package/translations/messages.pot +158 -112
  128. package/views/account/passkeys.hbs +8 -0
  129. package/views/account/password.hbs +11 -0
  130. package/views/account/security.hbs +18 -7
  131. package/views/accounts/account.hbs +21 -38
  132. package/views/accounts/browse.hbs +3 -1
  133. package/views/accounts/edit.hbs +1 -1
  134. package/views/accounts/register/imap-server.hbs +11 -3
  135. package/views/config/ai.hbs +3 -1
  136. package/views/config/branding.hbs +4 -2
  137. package/views/config/document-store/chat.hbs +1 -1
  138. package/views/config/document-store/index.hbs +1 -1
  139. package/views/config/email-processing.hbs +2 -0
  140. package/views/config/imap-proxy.hbs +3 -1
  141. package/views/config/license.hbs +1 -1
  142. package/views/config/logging.hbs +3 -1
  143. package/views/config/mcp.hbs +3 -1
  144. package/views/config/network.hbs +16 -16
  145. package/views/config/oauth/app.hbs +4 -4
  146. package/views/config/security.hbs +2 -0
  147. package/views/config/service.hbs +3 -1
  148. package/views/config/smtp.hbs +3 -1
  149. package/views/config/webhooks.hbs +4 -2
  150. package/views/error.hbs +10 -2
  151. package/views/internals/index.hbs +1 -1
  152. package/views/layout/app.hbs +9 -14
  153. package/views/layout/login.hbs +1 -1
  154. package/views/layout/prompt.hbs +1 -1
  155. package/views/layout/public.hbs +1 -1
  156. package/views/legal.hbs +1 -1
  157. package/views/mcp/authorize.hbs +1 -1
  158. package/views/partials/ace_assets.hbs +13 -0
  159. package/views/partials/add_account_modal.hbs +1 -1
  160. package/views/partials/address_list.hbs +4 -4
  161. package/views/partials/filter_editor_js.hbs +3 -3
  162. package/views/partials/gateway_js.hbs +1 -1
  163. package/views/partials/oauth_form.hbs +6 -6
  164. package/views/partials/public_theme_init.hbs +1 -1
  165. package/views/partials/template_form.hbs +2 -2
  166. package/views/partials/test_send.hbs +7 -4
  167. package/views/partials/theme_init.hbs +1 -1
  168. package/views/partials/ui/details.hbs +2 -2
  169. package/views/partials/ui/env-managed-alert.hbs +19 -0
  170. package/views/partials/webhook_form.hbs +1 -1
  171. package/views/partials/webhooks_editor_functions.hbs +1 -1
  172. package/views/reference/redirect.hbs +1 -1
  173. package/views/templates/template.hbs +2 -2
  174. package/views/tokens/new.hbs +1 -1
  175. package/views/unsubscribe.hbs +7 -1
  176. package/views/webhooks/webhook.hbs +2 -2
  177. package/workers/api.js +179 -175
  178. package/workers/export.js +1 -5
  179. package/workers/imap.js +33 -6
  180. package/workers/smtp.js +19 -43
  181. package/workers/submit.js +31 -13
  182. package/workers/webhooks.js +9 -24
  183. package/lib/reconnection-manager.js +0 -106
  184. package/static/front/EmailEngine_logo_horiz.png +0 -0
  185. package/static/front/EmailEngine_logo_vert.png +0 -0
  186. package/static/front/index.html +0 -57
  187. package/static/front/logo.png +0 -0
  188. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
@@ -52,6 +52,10 @@ export class EmailEngineClient {
52
52
  }
53
53
  this.showDarkModeToggle = options.showDarkModeToggle !== false;
54
54
 
55
+ // The nonce a Content-Security-Policy page hands the widget so the <style> element
56
+ // createStyles() appends passes a style-src-elem directive without 'unsafe-inline'
57
+ this.styleNonce = typeof options.styleNonce === 'string' && options.styleNonce ? options.styleNonce : null;
58
+
55
59
  // Get page size from localStorage or options or default
56
60
  const savedPageSize =
57
61
  typeof window !== 'undefined' && window.localStorage ? localStorage.getItem('ee-client-page-size') : null;
@@ -66,23 +70,13 @@ export class EmailEngineClient {
66
70
  this._startKeepAliveTimer();
67
71
  }
68
72
 
69
- async apiRequest(method, endpoint, data = null) {
70
- // Update activity timestamp for keep-alive
73
+ // Resolves the platform fetch (native in browsers and modern Node, node-fetch as
74
+ // an optional fallback on older Node) and normalizes transport failures, so both
75
+ // HTTP entry points - apiRequest and _fetchBlob - fail in the same shape.
76
+ async _fetch(url, options) {
77
+ // Any request counts as activity for the keep-alive timer
71
78
  this._updateActivity();
72
79
 
73
- const url = `${this.apiUrl}${endpoint}`;
74
- const options = {
75
- method: method,
76
- headers: {
77
- 'Content-Type': 'application/json',
78
- ...this._authHeaders()
79
- }
80
- };
81
-
82
- if (data) {
83
- options.body = JSON.stringify(data);
84
- }
85
-
86
80
  let fetchFn = globalThis.fetch;
87
81
  if (!fetchFn) {
88
82
  // Native fetch is missing (older Node.js). Fall back to node-fetch.
@@ -102,26 +96,63 @@ export class EmailEngineClient {
102
96
  );
103
97
  }
104
98
 
105
- const response = await fetchFn(url, options);
106
- if (!response.ok) {
107
- let errorDetails;
108
- try {
109
- errorDetails = await response.json();
110
- } catch (parseError) {
111
- // If JSON parsing fails, fall back to status text
112
- errorDetails = { message: response.statusText };
99
+ try {
100
+ return await fetchFn(url, options);
101
+ } catch (err) {
102
+ // Mark transport level failures - an unreachable server, DNS/TLS
103
+ // problems, a blocked CORS preflight - so callers can tell them apart
104
+ // from an API error that carries a server message.
105
+ const error = new Error(`Could not reach the EmailEngine server at ${this.apiUrl}`);
106
+ error.isNetworkError = true;
107
+ error.cause = err;
108
+ throw error;
109
+ }
110
+ }
111
+
112
+ // Turns a non-ok response into an Error carrying the server's own explanation.
113
+ // EmailEngine answers with Boom payloads - { statusCode, error, message, code,
114
+ // fields } - which _errorMessage() knows how to read.
115
+ async _responseError(response) {
116
+ let details;
117
+ try {
118
+ details = await response.json();
119
+ } catch (parseError) {
120
+ // Not a JSON body - the status line is all there is to go on
121
+ details = { message: response.statusText };
122
+ }
123
+
124
+ const error = new Error(`API request failed: ${response.statusText}`);
125
+ error.statusCode = response.status;
126
+ error.details = details;
127
+ return error;
128
+ }
129
+
130
+ async apiRequest(method, endpoint, data = null) {
131
+ const options = {
132
+ method: method,
133
+ headers: {
134
+ 'Content-Type': 'application/json',
135
+ ...this._authHeaders()
113
136
  }
137
+ };
114
138
 
115
- const error = new Error(`API request failed: ${response.statusText}`);
116
- error.statusCode = response.status;
117
- error.details = errorDetails;
118
- throw error;
139
+ if (data) {
140
+ options.body = JSON.stringify(data);
141
+ }
142
+
143
+ const response = await this._fetch(`${this.apiUrl}${endpoint}`, options);
144
+ if (!response.ok) {
145
+ throw await this._responseError(response);
119
146
  }
120
147
 
121
148
  return await response.json();
122
149
  }
123
150
 
124
151
  async loadFolders() {
152
+ // Reset the pane to its loading state so a retry after a failure does not
153
+ // keep showing the previous error while the new request is in flight.
154
+ this._setPaneHtml('.ee-folder-tree', '<div class="ee-loading">Loading folders...</div>');
155
+
125
156
  try {
126
157
  const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
127
158
  this.folders = data.mailboxes || [];
@@ -132,17 +163,13 @@ export class EmailEngineClient {
132
163
  return this.folders;
133
164
  } catch (error) {
134
165
  console.error('Failed to load folders:', error);
166
+ this._renderPaneError('.ee-folder-tree', 'Folders unavailable', error, () => this._loadInitialView());
135
167
  throw error;
136
168
  }
137
169
  }
138
170
 
139
171
  async loadMessages(path, cursor = null) {
140
- if (this.container) {
141
- const messageList = this.container.querySelector('.ee-message-list');
142
- if (messageList) {
143
- messageList.innerHTML = '<div class="ee-loading">Loading messages...</div>';
144
- }
145
- }
172
+ this._setPaneHtml('.ee-message-list', '<div class="ee-loading">Loading messages...</div>');
146
173
 
147
174
  try {
148
175
  const params = new URLSearchParams({ path: path, pageSize: this.pageSize });
@@ -172,23 +199,15 @@ export class EmailEngineClient {
172
199
  };
173
200
  } catch (error) {
174
201
  console.error('Failed to load messages:', error);
175
- if (this.container) {
176
- const messageList = this.container.querySelector('.ee-message-list');
177
- if (messageList) {
178
- messageList.innerHTML = '<div class="ee-error">Failed to load messages</div>';
179
- }
180
- }
202
+ this._renderPaneError('.ee-message-list', 'Messages unavailable', error, () =>
203
+ this._fireAndForget(this.loadMessages(path, cursor))
204
+ );
181
205
  throw error;
182
206
  }
183
207
  }
184
208
 
185
209
  async loadMessage(messageId) {
186
- if (this.container) {
187
- const viewer = this.container.querySelector('.ee-message-viewer');
188
- if (viewer) {
189
- viewer.innerHTML = '<div class="ee-loading">Loading message...</div>';
190
- }
191
- }
210
+ this._setPaneHtml('.ee-message-viewer', '<div class="ee-loading">Loading message...</div>');
192
211
 
193
212
  try {
194
213
  const params = new URLSearchParams({
@@ -224,12 +243,9 @@ export class EmailEngineClient {
224
243
  return this.currentMessage;
225
244
  } catch (error) {
226
245
  console.error('Failed to load message:', error);
227
- if (this.container) {
228
- const viewer = this.container.querySelector('.ee-message-viewer');
229
- if (viewer) {
230
- viewer.innerHTML = '<div class="ee-error">Failed to load message</div>';
231
- }
232
- }
246
+ this._renderPaneError('.ee-message-viewer', 'Message unavailable', error, () =>
247
+ this._fireAndForget(this.loadMessage(messageId))
248
+ );
233
249
  throw error;
234
250
  }
235
251
  }
@@ -337,8 +353,6 @@ export class EmailEngineClient {
337
353
  return response;
338
354
  } catch (error) {
339
355
  console.error('Failed to send message:', error);
340
- // Try to parse detailed error information
341
- this._parseApiError(error);
342
356
  throw error;
343
357
  }
344
358
  }
@@ -380,7 +394,6 @@ export class EmailEngineClient {
380
394
  return response;
381
395
  } catch (error) {
382
396
  console.error('Failed to save draft:', error);
383
- this._parseApiError(error);
384
397
  throw error;
385
398
  }
386
399
  }
@@ -395,7 +408,6 @@ export class EmailEngineClient {
395
408
  return response;
396
409
  } catch (error) {
397
410
  console.error('Failed to submit draft:', error);
398
- this._parseApiError(error);
399
411
  throw error;
400
412
  }
401
413
  }
@@ -414,23 +426,21 @@ export class EmailEngineClient {
414
426
  return !!(folder && folder.specialUse === '\\Drafts');
415
427
  }
416
428
 
417
- _parseApiError(error) {
418
- try {
419
- // If error has response text, try to parse it
420
- if (error.message && error.message.includes('API request failed:')) {
421
- // This is our custom error from apiRequest, the actual response might have more details
422
- error.isDetailedError = false;
423
- }
424
- } catch (parseError) {
425
- // If parsing fails, just use the original error
426
- console.error('Failed to parse error details:', parseError);
429
+ // Best-effort human readable reason for a failed request. EmailEngine returns
430
+ // Boom style payloads - { statusCode, error, message, code, fields } - so the
431
+ // `message` field usually carries the actual cause, e.g. "Requested account is
432
+ // not yet initialized" when the account has not connected yet.
433
+ _errorMessage(error, fallback = 'Unexpected error') {
434
+ if (!error) {
435
+ return fallback;
427
436
  }
428
- }
429
437
 
430
- _formatSendError(error) {
431
- // If we have detailed error information from the API
432
- if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
433
- const fieldErrors = error.details.fields
438
+ const details = error.details;
439
+ const detailsMessage = details && typeof details.message === 'string' ? details.message : '';
440
+
441
+ // Validation failures list the offending fields
442
+ if (details && Array.isArray(details.fields)) {
443
+ const fieldErrors = details.fields
434
444
  // Keep only entries that carry a usable message string.
435
445
  .filter(field => field && typeof field.message === 'string')
436
446
  // Map technical field names to user-friendly ones. Each replace
@@ -443,18 +453,100 @@ export class EmailEngineClient {
443
453
  .replace(/"text"/g, 'message')
444
454
  );
445
455
 
446
- const mainMessage = error.details.message || 'Failed to send email';
456
+ const mainMessage = detailsMessage || fallback;
447
457
  if (fieldErrors.length > 0) {
448
458
  return `${mainMessage}:\n\n• ${fieldErrors.join('\n• ')}`;
449
459
  }
450
460
  return mainMessage;
451
461
  }
452
462
 
453
- // No field-level details - fall back to the API-provided message, then to a generic one
454
- if (error.details && typeof error.details.message === 'string' && error.details.message) {
455
- return error.details.message;
463
+ if (detailsMessage) {
464
+ return detailsMessage;
465
+ }
466
+
467
+ if (error.statusCode) {
468
+ return `The server responded with status ${error.statusCode}`;
469
+ }
470
+
471
+ return error.message || fallback;
472
+ }
473
+
474
+ _formatSendError(error) {
475
+ return this._errorMessage(error, 'Failed to send email. Please check your input and try again.');
476
+ }
477
+
478
+ // Writes markup into one of the client's panes when the UI exists and is still
479
+ // alive, and hands the pane back so callers can wire up what they rendered.
480
+ _setPaneHtml(selector, html) {
481
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
482
+ return null;
483
+ }
484
+
485
+ const pane = this.container.querySelector(selector);
486
+ if (pane) {
487
+ pane.innerHTML = html;
456
488
  }
457
- return 'Failed to send email. Please check your input and try again.';
489
+ return pane;
490
+ }
491
+
492
+ // Replaces a pane's contents with an error panel explaining why its data is
493
+ // missing, optionally with a Retry button. Without this a failed request
494
+ // leaves the pane stuck on its "Loading..." placeholder forever, with the
495
+ // only trace of the failure in the developer console.
496
+ _renderPaneError(selector, title, error, retry = null) {
497
+ const detail = this._errorMessage(error, '');
498
+ const pane = this._setPaneHtml(
499
+ selector,
500
+ `
501
+ <div class="ee-error">
502
+ <div class="ee-error-title">${this.escapeHtml(title)}</div>
503
+ ${detail ? `<div class="ee-error-detail">${this.escapeHtml(detail)}</div>` : ''}
504
+ ${retry ? '<button type="button" class="ee-button ee-error-retry">Retry</button>' : ''}
505
+ </div>
506
+ `
507
+ );
508
+
509
+ if (pane && retry) {
510
+ const retryButton = pane.querySelector('.ee-error-retry');
511
+ if (retryButton) {
512
+ retryButton.addEventListener('click', () => {
513
+ if (this._destroyed) {
514
+ return;
515
+ }
516
+ // Disable while the request is in flight so an impatient second
517
+ // click can not fan out a duplicate round trip. A failed retry
518
+ // re-renders the panel with a fresh button.
519
+ retryButton.disabled = true;
520
+ retry();
521
+ });
522
+ }
523
+ }
524
+ }
525
+
526
+ // Loads started from a DOM handler render their own error panel, so the user
527
+ // has already been told. Swallow the rejection rather than letting it surface
528
+ // as an unhandled rejection in hosts with a global error reporter.
529
+ _fireAndForget(promise) {
530
+ promise.catch(() => {});
531
+ }
532
+
533
+ // Message actions (flag, delete, move) have no pane of their own to report into:
534
+ // when one fails the message simply stays put, which is indistinguishable from
535
+ // nothing having happened. Say so instead.
536
+ _alertActionFailed(error, fallback) {
537
+ console.error(`${fallback}:`, error);
538
+ return this.alertMethod(this._errorMessage(error, fallback), 'Error', null, 'OK');
539
+ }
540
+
541
+ // The message list before any folder is opened. Shared with createLayout so the
542
+ // pane header markup lives in one place.
543
+ _messageListPlaceholder() {
544
+ return `
545
+ <div class="ee-pane-header">
546
+ <span class="ee-pane-title">Messages</span>
547
+ </div>
548
+ <div class="ee-empty-state">Select a folder</div>
549
+ `;
458
550
  }
459
551
 
460
552
  formatDate(dateStr) {
@@ -508,15 +600,17 @@ export class EmailEngineClient {
508
600
  }
509
601
 
510
602
  // Authenticated GET for binary payloads (attachments, message source).
511
- // apiRequest is not reused here - it always parses the body as JSON.
603
+ // apiRequest is not reused here - it always parses the body as JSON - but the
604
+ // same _fetch/_responseError pair is, so a failed download reports the same
605
+ // reason as any other request.
512
606
  async _fetchBlob(endpoint) {
513
- const response = await fetch(`${this.apiUrl}${endpoint}`, {
607
+ const response = await this._fetch(`${this.apiUrl}${endpoint}`, {
514
608
  headers: this._authHeaders(),
515
609
  credentials: 'include'
516
610
  });
517
611
 
518
612
  if (!response.ok) {
519
- throw new Error(`HTTP error! status: ${response.status}`);
613
+ throw await this._responseError(response);
520
614
  }
521
615
 
522
616
  return response;
@@ -541,7 +635,12 @@ export class EmailEngineClient {
541
635
  this._saveBlob(blob, filename);
542
636
  } catch (error) {
543
637
  console.error('Failed to download attachment:', error);
544
- this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
638
+ this.alertMethod(
639
+ this._errorMessage(error, 'Failed to download attachment. Please try again.'),
640
+ 'Download Error',
641
+ null,
642
+ 'OK'
643
+ );
545
644
  }
546
645
  }
547
646
 
@@ -561,7 +660,12 @@ export class EmailEngineClient {
561
660
  this._saveBlob(blob, filename);
562
661
  } catch (error) {
563
662
  console.error('Failed to download original message:', error);
564
- this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
663
+ this.alertMethod(
664
+ this._errorMessage(error, 'Failed to download original message. Please try again.'),
665
+ 'Download Error',
666
+ null,
667
+ 'OK'
668
+ );
565
669
  }
566
670
  }
567
671
 
@@ -571,6 +675,10 @@ export class EmailEngineClient {
571
675
  }
572
676
 
573
677
  const style = document.createElement('style');
678
+ if (this.styleNonce) {
679
+ // the IDL property, which is what the policy check reads on an element a script inserts
680
+ style.nonce = this.styleNonce;
681
+ }
574
682
  style.textContent = `
575
683
  .ee-client {
576
684
  --ee-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
@@ -926,6 +1034,25 @@ export class EmailEngineClient {
926
1034
  border: 1px solid #fcc;
927
1035
  border-radius: 4px;
928
1036
  margin: 16px;
1037
+ /* Panes can be as narrow as the 200px sidebar and server
1038
+ messages are arbitrary text, so break anywhere rather than
1039
+ letting a long word push the layout wider. */
1040
+ overflow-wrap: anywhere;
1041
+ }
1042
+
1043
+ .ee-error-title {
1044
+ font-weight: 500;
1045
+ }
1046
+
1047
+ .ee-error-detail {
1048
+ margin-top: 6px;
1049
+ font-size: 12px;
1050
+ /* Field level API errors arrive as a newline separated list */
1051
+ white-space: pre-line;
1052
+ }
1053
+
1054
+ .ee-error-retry {
1055
+ margin-top: 10px;
929
1056
  }
930
1057
 
931
1058
  .ee-flag {
@@ -1362,11 +1489,16 @@ export class EmailEngineClient {
1362
1489
  }
1363
1490
 
1364
1491
  .ee-dark-mode .ee-loading,
1365
- .ee-dark-mode .ee-empty-state,
1366
- .ee-dark-mode .ee-error {
1492
+ .ee-dark-mode .ee-empty-state {
1367
1493
  color: #999;
1368
1494
  }
1369
1495
 
1496
+ .ee-dark-mode .ee-error {
1497
+ background: #3a2222;
1498
+ border-color: #5c3030;
1499
+ color: #f0a5a5;
1500
+ }
1501
+
1370
1502
  .ee-dark-mode .ee-pagination {
1371
1503
  background: #252525;
1372
1504
  border-color: #333;
@@ -1560,7 +1692,7 @@ export class EmailEngineClient {
1560
1692
  folderTree.querySelectorAll('.ee-folder-item').forEach(item => {
1561
1693
  item.addEventListener('click', () => {
1562
1694
  const path = item.getAttribute('data-path');
1563
- this.loadMessages(path);
1695
+ this._fireAndForget(this.loadMessages(path));
1564
1696
  });
1565
1697
  });
1566
1698
  }
@@ -1636,19 +1768,19 @@ export class EmailEngineClient {
1636
1768
  messageList.querySelectorAll('.ee-message-item').forEach(item => {
1637
1769
  item.addEventListener('click', () => {
1638
1770
  const messageId = item.getAttribute('data-id');
1639
- this.loadMessage(messageId);
1771
+ this._fireAndForget(this.loadMessage(messageId));
1640
1772
  });
1641
1773
  });
1642
1774
 
1643
1775
  messageList.querySelectorAll('[data-action="prev-page"]').forEach(btn => {
1644
1776
  btn.addEventListener('click', () => {
1645
- this.loadMessages(this.currentFolder, this.prevPageCursor);
1777
+ this._fireAndForget(this.loadMessages(this.currentFolder, this.prevPageCursor));
1646
1778
  });
1647
1779
  });
1648
1780
 
1649
1781
  messageList.querySelectorAll('[data-action="next-page"]').forEach(btn => {
1650
1782
  btn.addEventListener('click', () => {
1651
- this.loadMessages(this.currentFolder, this.nextPageCursor);
1783
+ this._fireAndForget(this.loadMessages(this.currentFolder, this.nextPageCursor));
1652
1784
  });
1653
1785
  });
1654
1786
 
@@ -1660,7 +1792,7 @@ export class EmailEngineClient {
1660
1792
  if (typeof window !== 'undefined' && window.localStorage) {
1661
1793
  localStorage.setItem('ee-client-page-size', this.pageSize.toString());
1662
1794
  }
1663
- this.loadMessages(this.currentFolder);
1795
+ this._fireAndForget(this.loadMessages(this.currentFolder));
1664
1796
  });
1665
1797
  }
1666
1798
  }
@@ -1797,7 +1929,9 @@ export class EmailEngineClient {
1797
1929
 
1798
1930
  viewer.querySelector('[data-action="toggle-read"]').addEventListener('click', () => {
1799
1931
  const currentlyUnseen = msg.unseen;
1800
- this.markAsRead(msg.id, currentlyUnseen);
1932
+ this.markAsRead(msg.id, currentlyUnseen).catch(error =>
1933
+ this._alertActionFailed(error, 'Failed to update the message flags')
1934
+ );
1801
1935
  });
1802
1936
 
1803
1937
  viewer.querySelector('[data-action="delete"]').addEventListener('click', async () => {
@@ -1808,7 +1942,9 @@ export class EmailEngineClient {
1808
1942
  'Delete'
1809
1943
  );
1810
1944
  if (result) {
1811
- this.deleteMessage(msg.id);
1945
+ this.deleteMessage(msg.id).catch(error =>
1946
+ this._alertActionFailed(error, 'Failed to delete the message')
1947
+ );
1812
1948
  }
1813
1949
  });
1814
1950
 
@@ -1819,7 +1955,12 @@ export class EmailEngineClient {
1819
1955
  viewer.querySelector('[data-action="move"]').addEventListener('change', e => {
1820
1956
  const targetPath = e.target.value;
1821
1957
  if (targetPath) {
1822
- this.moveMessage(msg.id, targetPath);
1958
+ this.moveMessage(msg.id, targetPath).catch(error => {
1959
+ // The message did not move, so the select must not keep showing
1960
+ // the target folder as though it had
1961
+ e.target.value = '';
1962
+ this._alertActionFailed(error, 'Failed to move the message');
1963
+ });
1823
1964
  }
1824
1965
  });
1825
1966
 
@@ -1872,16 +2013,9 @@ export class EmailEngineClient {
1872
2013
  <div class="ee-pane-header">
1873
2014
  <span class="ee-pane-title">Folders</span>
1874
2015
  </div>
1875
- <div class="ee-folder-tree">
1876
- <div class="ee-loading">Loading folders...</div>
1877
- </div>
1878
- </div>
1879
- <div class="ee-message-list">
1880
- <div class="ee-pane-header">
1881
- <span class="ee-pane-title">Messages</span>
1882
- </div>
1883
- <div class="ee-empty-state">Select a folder</div>
2016
+ <div class="ee-folder-tree"></div>
1884
2017
  </div>
2018
+ <div class="ee-message-list">${this._messageListPlaceholder()}</div>
1885
2019
  <div class="ee-message-viewer">
1886
2020
  <div class="ee-empty-state">Select a message to view</div>
1887
2021
  </div>
@@ -2182,18 +2316,38 @@ export class EmailEngineClient {
2182
2316
  toggleBtn.addEventListener('click', () => this.toggleDarkMode());
2183
2317
  }
2184
2318
 
2185
- this.loadFolders()
2319
+ this._loadInitialView();
2320
+ }
2321
+
2322
+ // Load the folder list and open the account's inbox. Used on startup and by
2323
+ // the Retry button that loadFolders renders when the request fails; both
2324
+ // failure paths already put an error panel in the UI, so the rejection is
2325
+ // logged and swallowed here rather than surfacing as an unhandled rejection.
2326
+ _loadInitialView() {
2327
+ // Drop whatever a previous attempt left here; loadFolders and loadMessages
2328
+ // paint their own loading states from this point on.
2329
+ this._setPaneHtml('.ee-message-list', this._messageListPlaceholder());
2330
+
2331
+ return this.loadFolders()
2332
+ .catch(error => {
2333
+ // loadFolders reports into the sidebar, but the message list is the
2334
+ // larger pane and would still read "Select a folder" - a folder the
2335
+ // sidebar can no longer offer. Say what happened there too.
2336
+ this._renderPaneError('.ee-message-list', 'Folders unavailable', error, () => this._loadInitialView());
2337
+ throw error;
2338
+ })
2186
2339
  .then(() => {
2187
2340
  const inbox =
2188
2341
  this.folders.find(f => f.specialUse && f.specialUse.includes('\\Inbox')) ||
2189
2342
  this.folders.find(f => f.name.toLowerCase() === 'inbox') ||
2190
2343
  this.folders[0];
2191
2344
  if (inbox) {
2192
- this.loadMessages(inbox.path);
2345
+ return this.loadMessages(inbox.path);
2193
2346
  }
2194
2347
  })
2195
2348
  .catch(error => {
2196
- console.error('Failed to auto-select inbox:', error);
2349
+ // Both loadFolders and loadMessages have already rendered a panel
2350
+ console.error('Failed to load the initial view:', error);
2197
2351
  });
2198
2352
  }
2199
2353
 
@@ -16,6 +16,13 @@
16
16
  // - clicking the backdrop closes the dialog (the dialog element is the
17
17
  // click target only when the click lands outside the dialog panel)
18
18
  document.addEventListener('click', e => {
19
+ // The error page's "Go back" button. A button rather than a javascript: link, which the
20
+ // Content-Security-Policy of the admin surface (where the error page also renders) forbids
21
+ if (e.target.closest('[data-ee-back]')) {
22
+ window.history.back();
23
+ return;
24
+ }
25
+
19
26
  let closeBtn = e.target.closest('[data-modal-close]');
20
27
  if (closeBtn) {
21
28
  let dialog = closeBtn.closest('dialog.ee-modal');
package/static/js/ui.js CHANGED
@@ -719,11 +719,41 @@ window.uiBusyAction = (btn, run) => {
719
719
  // creation and re-applied whenever the admin theme changes. The theme files
720
720
  // must exist under static/js/ace/ - they are copied from ace-builds by
721
721
  // copy-static-files.sh and ship in the pkg binary via the static/**/* asset glob.
722
+ // Their stylesheets are linked by views/partials/ace_assets.hbs, which also puts
723
+ // ACE in strict-CSP mode so it injects none of its own.
722
724
  const uiAceThemes = {
723
725
  editor: { light: 'ace/theme/xcode', dark: 'ace/theme/tomorrow_night' },
724
726
  preview: { light: 'ace/theme/kuroir', dark: 'ace/theme/tomorrow_night_eighties' }
725
727
  };
726
728
 
729
+ // ACE keeps its stylesheets inside its JavaScript and injects them as elements the admin
730
+ // Content-Security-Policy refuses (it accepts a stylesheet only with the request nonce, which
731
+ // ACE cannot set). Strict mode stops the injection and the sheets are linked instead:
732
+ // views/partials/ace_assets.hbs carries them in the markup for the pages that always have an
733
+ // editor, and this adds whatever is missing for the one that loads ACE lazily from script (the
734
+ // try-it panels in static/js/reference.js). Both paths reach ACE through the two helpers below,
735
+ // so this is the one place that has to know. The hrefs come from uiAceThemes, so a theme added
736
+ // there needs no second edit.
737
+ const uiAceEnsureAssets = () => {
738
+ ace.config.set('useStrictCSP', true);
739
+
740
+ let sheets = ['/static/js/ace/css/ace.css'];
741
+ for (let kind of Object.values(uiAceThemes)) {
742
+ for (let theme of Object.values(kind)) {
743
+ sheets.push(`/static/js/ace/css/theme/${theme.split('/').pop()}.css`);
744
+ }
745
+ }
746
+
747
+ for (let href of sheets) {
748
+ if (!document.querySelector(`link[href="${href}"]`)) {
749
+ let link = document.createElement('link');
750
+ link.rel = 'stylesheet';
751
+ link.href = href;
752
+ document.head.appendChild(link);
753
+ }
754
+ }
755
+ };
756
+
727
757
  // container element -> { editor, kind }; also the lookup the .copy-btn
728
758
  // handler uses to read the full session value of a targeted editor
729
759
  const uiAceInstances = new Map();
@@ -744,6 +774,7 @@ const uiAceRegister = (editor, kind) => {
744
774
  // the initial value loaded into the session. Extra ace options pass through
745
775
  // via opts.
746
776
  window.uiAceEditor = (id, mode, value, opts) => {
777
+ uiAceEnsureAssets();
747
778
  const editor = opts ? ace.edit(id, opts) : ace.edit(id);
748
779
  uiAceRegister(editor, 'editor');
749
780
  editor.session.setMode(`ace/mode/${mode}`);
@@ -756,6 +787,7 @@ window.uiAceEditor = (id, mode, value, opts) => {
756
787
  // Read-only preview pane variant: gutter, no print margin or active-line
757
788
  // highlight, with its own theme pair to keep previews visually distinct
758
789
  window.uiAcePreview = (id, mode, opts) => {
790
+ uiAceEnsureAssets();
759
791
  const editor = ace.edit(id, Object.assign({ showGutter: true }, opts));
760
792
  editor.setReadOnly(true);
761
793
  editor.setShowPrintMargin(false);