@postalsys/ee-client 1.7.1 → 1.8.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 (4) hide show
  1. package/README.md +12 -11
  2. package/index.d.ts +2 -0
  3. package/index.js +149 -66
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -115,17 +115,18 @@ EmailEngine can also mint short-lived, session-bound tokens whose value starts w
115
115
  new EmailEngineClient(options);
116
116
  ```
117
117
 
118
- | Option | Type | Default | Description |
119
- | -------------------- | ------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
- | `account` | `string` | (required) | EmailEngine account identifier. |
121
- | `apiUrl` | `string` | `http://127.0.0.1:3000` | Base URL of your EmailEngine instance. |
122
- | `accessToken` | `string` | - | Bearer token for API authentication. |
123
- | `container` | `HTMLElement` | - | DOM element to render the webmail UI into. Omit for API-only use. |
124
- | `pageSize` | `number` | `20` | Messages per page. A saved value in `localStorage` takes precedence. |
125
- | `confirmMethod` | `function` | browser `confirm()` | Custom confirm dialog, `(message, title, cancelText, okText)`. May be sync or async; returns a boolean. |
126
- | `alertMethod` | `function` | browser `alert()` | Custom alert dialog, `(message, title, cancelText, okText)` where `cancelText` is `null`. |
127
- | `darkMode` | `boolean` | stored preference | Initial dark mode. Overrides the preference stored by the builtin toggle. |
128
- | `showDarkModeToggle` | `boolean` | `true` | Render the builtin dark mode toggle. Set `false` when the host application drives the mode through `client.setDarkMode(enabled)` (for example in sync with its own theme switch). |
118
+ | Option | Type | Default | Description |
119
+ | -------------------- | ------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
+ | `account` | `string` | (required) | EmailEngine account identifier. |
121
+ | `apiUrl` | `string` | `http://127.0.0.1:3000` | Base URL of your EmailEngine instance. |
122
+ | `accessToken` | `string` | - | Bearer token for API authentication. |
123
+ | `container` | `HTMLElement` | - | DOM element to render the webmail UI into. Omit for API-only use. |
124
+ | `pageSize` | `number` | `20` | Messages per page. A saved value in `localStorage` takes precedence. |
125
+ | `confirmMethod` | `function` | browser `confirm()` | Custom confirm dialog, `(message, title, cancelText, okText)`. May be sync or async; returns a boolean. |
126
+ | `alertMethod` | `function` | browser `alert()` | Custom alert dialog, `(message, title, cancelText, okText)` where `cancelText` is `null`. |
127
+ | `darkMode` | `boolean` | stored preference | Initial dark mode. Overrides the preference stored by the builtin toggle. |
128
+ | `showDarkModeToggle` | `boolean` | `true` | Render the builtin dark mode toggle. Set `false` when the host application drives the mode through `client.setDarkMode(enabled)` (for example in sync with its own theme switch). |
129
+ | `styleNonce` | `string` | none | Nonce set on the `<style>` elements the widget creates (its own stylesheet and the one inside the message body's shadow root). Pass the page's Content-Security-Policy nonce when `style-src-elem` allows no inline stylesheet without one. |
129
130
 
130
131
  UI rendering, the compose modal, and dark mode only activate when a `container` is supplied. In a non-browser environment the UI is skipped and the instance behaves as a plain API client.
131
132
 
package/index.d.ts CHANGED
@@ -105,6 +105,8 @@ export interface EmailEngineClientOptions {
105
105
  darkMode?: boolean;
106
106
  /** Render the builtin dark mode toggle button (default true); set false when the host drives the mode through setDarkMode() */
107
107
  showDarkModeToggle?: boolean;
108
+ /** CSP nonce set on the <style> element the widget appends, for a host page whose style-src-elem requires one */
109
+ styleNonce?: string;
108
110
  }
109
111
 
110
112
  export declare class EmailEngineClient {
package/index.js CHANGED
@@ -1,3 +1,65 @@
1
+ // Stylesheet inside the message body's shadow root (see _renderMessageBody). Host rules do not
2
+ // reach in, so this carries everything the body needs: a reset on the host, the image cap, and
3
+ // the folded-thread control. Custom properties still inherit through the boundary, which is how
4
+ // the font and the dark mode colours arrive from .ee-client / .ee-dark-mode.
5
+ const MESSAGE_BODY_STYLES = `
6
+ :host {
7
+ all: initial;
8
+ display: block;
9
+ color: inherit;
10
+ font-family: var(--ee-font, sans-serif);
11
+ font-size: 14px;
12
+ line-height: 1.6;
13
+ overflow-wrap: break-word;
14
+ }
15
+
16
+ *,
17
+ *::before,
18
+ *::after {
19
+ box-sizing: border-box;
20
+ }
21
+
22
+ img {
23
+ max-width: 100%;
24
+ height: auto;
25
+ }
26
+
27
+ /* Quoted thread history, folded away by EmailEngine - see _labelCollapsedThreads() */
28
+ .ee-collapsed-thread {
29
+ margin-top: 12px;
30
+ }
31
+
32
+ .ee-collapsed-thread-toggle {
33
+ display: inline-block;
34
+ padding: 4px 10px;
35
+ border: 1px solid var(--ee-toggle-border, #ddd);
36
+ border-radius: 4px;
37
+ background: var(--ee-toggle-bg, white);
38
+ color: var(--ee-toggle-color, inherit);
39
+ cursor: pointer;
40
+ /* The message brings its own fonts along; the control keeps the client's */
41
+ font-family: var(--ee-font, sans-serif);
42
+ font-size: 12px;
43
+ line-height: 1;
44
+ user-select: none;
45
+ list-style: none;
46
+ }
47
+
48
+ .ee-collapsed-thread-toggle:hover {
49
+ background: var(--ee-toggle-hover-bg, #f0f0f0);
50
+ border-color: var(--ee-toggle-hover-border, #ddd);
51
+ }
52
+
53
+ /* Same, for Safari before it supported list-style on a summary */
54
+ .ee-collapsed-thread-toggle::-webkit-details-marker {
55
+ display: none;
56
+ }
57
+
58
+ .ee-collapsed-thread[open] > .ee-collapsed-thread-toggle {
59
+ margin-bottom: 12px;
60
+ }
61
+ `;
62
+
1
63
  export class EmailEngineClient {
2
64
  constructor(options = {}) {
3
65
  this.apiUrl = options.apiUrl || 'http://127.0.0.1:3000';
@@ -52,6 +114,10 @@ export class EmailEngineClient {
52
114
  }
53
115
  this.showDarkModeToggle = options.showDarkModeToggle !== false;
54
116
 
117
+ // The nonce a Content-Security-Policy page hands the widget so the <style> element
118
+ // createStyles() appends passes a style-src-elem directive without 'unsafe-inline'
119
+ this.styleNonce = typeof options.styleNonce === 'string' && options.styleNonce ? options.styleNonce : null;
120
+
55
121
  // Get page size from localStorage or options or default
56
122
  const savedPageSize =
57
123
  typeof window !== 'undefined' && window.localStorage ? localStorage.getItem('ee-client-page-size') : null;
@@ -144,13 +210,27 @@ export class EmailEngineClient {
144
210
  return await response.json();
145
211
  }
146
212
 
213
+ // Base path for this account's endpoints. The id is a path segment, so characters such as
214
+ // '#', '?', '/' or '%' in it must be encoded or they cut or redirect the request.
215
+ _accountPath() {
216
+ return `/v1/account/${encodeURIComponent(this.account)}`;
217
+ }
218
+
219
+ _messagePath(messageId, suffix = '') {
220
+ return `${this._accountPath()}/message/${encodeURIComponent(messageId)}${suffix}`;
221
+ }
222
+
223
+ _attachmentPath(attachmentId) {
224
+ return `${this._accountPath()}/attachment/${encodeURIComponent(attachmentId)}`;
225
+ }
226
+
147
227
  async loadFolders() {
148
228
  // Reset the pane to its loading state so a retry after a failure does not
149
229
  // keep showing the previous error while the new request is in flight.
150
230
  this._setPaneHtml('.ee-folder-tree', '<div class="ee-loading">Loading folders...</div>');
151
231
 
152
232
  try {
153
- const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
233
+ const data = await this.apiRequest('GET', `${this._accountPath()}/mailboxes`);
154
234
  this.folders = data.mailboxes || [];
155
235
  this._folderTreeCache = null;
156
236
  if (this.container) {
@@ -173,7 +253,7 @@ export class EmailEngineClient {
173
253
  params.set('cursor', cursor);
174
254
  }
175
255
 
176
- const data = await this.apiRequest('GET', `/v1/account/${this.account}/messages?${params}`);
256
+ const data = await this.apiRequest('GET', `${this._accountPath()}/messages?${params}`);
177
257
  this.messages = data.messages || [];
178
258
  this.currentFolder = path;
179
259
  this.nextPageCursor = data.nextPageCursor || null;
@@ -210,7 +290,7 @@ export class EmailEngineClient {
210
290
  webSafeHtml: true,
211
291
  markAsSeen: true
212
292
  });
213
- const data = await this.apiRequest('GET', `/v1/account/${this.account}/message/${messageId}?${params}`);
293
+ const data = await this.apiRequest('GET', this._messagePath(messageId, `?${params}`));
214
294
  this.currentMessage = data;
215
295
 
216
296
  this.currentMessage.unseen = false;
@@ -250,7 +330,7 @@ export class EmailEngineClient {
250
330
  try {
251
331
  const flagUpdate = seen ? { flags: { add: ['\\Seen'] } } : { flags: { delete: ['\\Seen'] } };
252
332
 
253
- await this.apiRequest('PUT', `/v1/account/${this.account}/message/${messageId}`, flagUpdate);
333
+ await this.apiRequest('PUT', this._messagePath(messageId), flagUpdate);
254
334
 
255
335
  const msg = this.messages.find(m => m.id === messageId);
256
336
  if (msg) {
@@ -276,7 +356,7 @@ export class EmailEngineClient {
276
356
 
277
357
  async deleteMessage(messageId) {
278
358
  try {
279
- await this.apiRequest('DELETE', `/v1/account/${this.account}/message/${messageId}`);
359
+ await this.apiRequest('DELETE', this._messagePath(messageId));
280
360
 
281
361
  this.messages = this.messages.filter(m => m.id !== messageId);
282
362
  if (this.container) {
@@ -299,7 +379,7 @@ export class EmailEngineClient {
299
379
 
300
380
  async moveMessage(messageId, targetPath) {
301
381
  try {
302
- await this.apiRequest('PUT', `/v1/account/${this.account}/message/${messageId}/move`, {
382
+ await this.apiRequest('PUT', this._messagePath(messageId, '/move'), {
303
383
  path: targetPath
304
384
  });
305
385
 
@@ -332,7 +412,7 @@ export class EmailEngineClient {
332
412
  // of the instance; used as the From identity of saved drafts.
333
413
  async _getAccountInfo() {
334
414
  if (!this._accountInfo) {
335
- this._accountInfo = await this.apiRequest('GET', `/v1/account/${this.account}`);
415
+ this._accountInfo = await this.apiRequest('GET', this._accountPath());
336
416
  }
337
417
  return this._accountInfo;
338
418
  }
@@ -345,7 +425,7 @@ export class EmailEngineClient {
345
425
  text: text
346
426
  };
347
427
 
348
- const response = await this.apiRequest('POST', `/v1/account/${this.account}/submit`, messageData);
428
+ const response = await this.apiRequest('POST', `${this._accountPath()}/submit`, messageData);
349
429
  return response;
350
430
  } catch (error) {
351
431
  console.error('Failed to send message:', error);
@@ -386,7 +466,7 @@ export class EmailEngineClient {
386
466
  // Non-fatal: the draft is saved without a From header
387
467
  }
388
468
 
389
- const response = await this.apiRequest('POST', `/v1/account/${this.account}/message`, messageData);
469
+ const response = await this.apiRequest('POST', `${this._accountPath()}/message`, messageData);
390
470
  return response;
391
471
  } catch (error) {
392
472
  console.error('Failed to save draft:', error);
@@ -396,11 +476,7 @@ export class EmailEngineClient {
396
476
 
397
477
  async submitDraft(messageId, options = null) {
398
478
  try {
399
- const response = await this.apiRequest(
400
- 'POST',
401
- `/v1/account/${this.account}/message/${messageId}/submit`,
402
- options
403
- );
479
+ const response = await this.apiRequest('POST', this._messagePath(messageId, '/submit'), options);
404
480
  return response;
405
481
  } catch (error) {
406
482
  console.error('Failed to submit draft:', error);
@@ -614,7 +690,7 @@ export class EmailEngineClient {
614
690
 
615
691
  async downloadAttachment(attachmentId, suggestedFilename = null) {
616
692
  try {
617
- const response = await this._fetchBlob(`/v1/account/${this.account}/attachment/${attachmentId}`);
693
+ const response = await this._fetchBlob(this._attachmentPath(attachmentId));
618
694
 
619
695
  // Get filename from Content-Disposition header if available
620
696
  const contentDisposition = response.headers.get('content-disposition');
@@ -642,7 +718,7 @@ export class EmailEngineClient {
642
718
 
643
719
  async downloadOriginalMessage(messageId, subject = null) {
644
720
  try {
645
- const response = await this._fetchBlob(`/v1/account/${this.account}/message/${messageId}/source`);
721
+ const response = await this._fetchBlob(this._messagePath(messageId, '/source'));
646
722
 
647
723
  // Get the email data
648
724
  const blob = await response.blob();
@@ -665,13 +741,24 @@ export class EmailEngineClient {
665
741
  }
666
742
  }
667
743
 
744
+ // A <style> element carrying styleNonce, for the widget stylesheet and the message body's
745
+ // shadow root alike: a stylesheet inside a shadow root is checked against style-src-elem too.
746
+ _createStyle(css) {
747
+ const style = document.createElement('style');
748
+ if (this.styleNonce) {
749
+ // the IDL property, which is what the policy check reads on an element a script inserts
750
+ style.nonce = this.styleNonce;
751
+ }
752
+ style.textContent = css;
753
+ return style;
754
+ }
755
+
668
756
  createStyles() {
669
757
  if (typeof document === 'undefined') {
670
758
  return;
671
759
  }
672
760
 
673
- const style = document.createElement('style');
674
- style.textContent = `
761
+ const style = this._createStyle(`
675
762
  .ee-client {
676
763
  --ee-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
677
764
  display: flex;
@@ -871,8 +958,7 @@ export class EmailEngineClient {
871
958
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
872
959
  }
873
960
 
874
- .ee-button,
875
- .ee-collapsed-thread-toggle {
961
+ .ee-button {
876
962
  padding: 4px 10px;
877
963
  border: 1px solid #ddd;
878
964
  background: white;
@@ -889,8 +975,7 @@ export class EmailEngineClient {
889
975
  height: 24px;
890
976
  }
891
977
 
892
- .ee-button:hover:not(:disabled),
893
- .ee-collapsed-thread-toggle:hover {
978
+ .ee-button:hover:not(:disabled) {
894
979
  background: #f0f0f0;
895
980
  }
896
981
 
@@ -924,38 +1009,6 @@ export class EmailEngineClient {
924
1009
  font-weight: 500;
925
1010
  }
926
1011
 
927
- .ee-message-body {
928
- line-height: 1.6;
929
- }
930
-
931
- .ee-message-body img {
932
- max-width: 100%;
933
- height: auto;
934
- }
935
-
936
- /* Quoted thread history, folded away by EmailEngine - see _labelCollapsedThreads() */
937
- .ee-collapsed-thread {
938
- margin-top: 12px;
939
- }
940
-
941
- .ee-collapsed-thread-toggle {
942
- display: inline-block;
943
- height: auto;
944
- /* The message brings its own fonts along; the control keeps the client's */
945
- font-family: var(--ee-font);
946
- user-select: none;
947
- list-style: none;
948
- }
949
-
950
- /* Same, for Safari before it supported list-style on a summary */
951
- .ee-collapsed-thread-toggle::-webkit-details-marker {
952
- display: none;
953
- }
954
-
955
- .ee-collapsed-thread[open] > .ee-collapsed-thread-toggle {
956
- margin-bottom: 12px;
957
- }
958
-
959
1012
  .ee-attachments {
960
1013
  margin-top: 16px;
961
1014
  padding-top: 16px;
@@ -1428,6 +1481,15 @@ export class EmailEngineClient {
1428
1481
  color: #e0e0e0;
1429
1482
  }
1430
1483
 
1484
+ /* Read inside the message body's shadow root, where .ee-dark-mode selectors cannot reach */
1485
+ .ee-dark-mode {
1486
+ --ee-toggle-bg: #333;
1487
+ --ee-toggle-border: #444;
1488
+ --ee-toggle-color: #e0e0e0;
1489
+ --ee-toggle-hover-bg: #444;
1490
+ --ee-toggle-hover-border: #555;
1491
+ }
1492
+
1431
1493
  .ee-dark-mode .ee-message-viewer {
1432
1494
  background: #1a1a1a;
1433
1495
  }
@@ -1437,15 +1499,13 @@ export class EmailEngineClient {
1437
1499
  border-color: #333;
1438
1500
  }
1439
1501
 
1440
- .ee-dark-mode .ee-button,
1441
- .ee-dark-mode .ee-collapsed-thread-toggle {
1502
+ .ee-dark-mode .ee-button {
1442
1503
  background: #333;
1443
1504
  border-color: #444;
1444
1505
  color: #e0e0e0;
1445
1506
  }
1446
1507
 
1447
- .ee-dark-mode .ee-button:hover,
1448
- .ee-dark-mode .ee-collapsed-thread-toggle:hover {
1508
+ .ee-dark-mode .ee-button:hover {
1449
1509
  background: #444;
1450
1510
  border-color: #555;
1451
1511
  }
@@ -1556,7 +1616,7 @@ export class EmailEngineClient {
1556
1616
  background: #66b2ff;
1557
1617
  color: #1a1a1a;
1558
1618
  }
1559
- `;
1619
+ `);
1560
1620
  document.head.appendChild(style);
1561
1621
  this._styleElement = style;
1562
1622
  }
@@ -1853,9 +1913,7 @@ export class EmailEngineClient {
1853
1913
  ${this.escapeHtml(msg.subject || '(no subject)')}
1854
1914
  </div>
1855
1915
  </div>
1856
- <div class="ee-message-body">
1857
- ${msg.text && msg.text.html ? msg.text.html : msg.text && msg.text.plain ? `<pre>${this.escapeHtml(msg.text.plain)}</pre>` : ''}
1858
- </div>
1916
+ <div class="ee-message-body"></div>
1859
1917
  ${
1860
1918
  msg.attachments && msg.attachments.length > 0
1861
1919
  ? `
@@ -1882,7 +1940,8 @@ export class EmailEngineClient {
1882
1940
  `;
1883
1941
  viewer.innerHTML = html;
1884
1942
 
1885
- this._labelCollapsedThreads(viewer);
1943
+ const bodyRoot = this._renderMessageBody(viewer.querySelector('.ee-message-body'), msg);
1944
+ this._labelCollapsedThreads(bodyRoot);
1886
1945
 
1887
1946
  const sendDraftButton = viewer.querySelector('[data-action="send-draft"]');
1888
1947
  if (sendDraftButton) {
@@ -1968,6 +2027,30 @@ export class EmailEngineClient {
1968
2027
  // Message content scrolling is now handled in loadMessage method
1969
2028
  }
1970
2029
 
2030
+ // The message body goes into a shadow root on its container. Sanitised message HTML still
2031
+ // carries class and id attributes, and in the host document those would pick up the host's
2032
+ // own stylesheet (a utility class like "fixed inset-0" could cover the whole page) or collide
2033
+ // with its ids. Inside the shadow root no host selector matches, while the message's inline
2034
+ // style attributes keep working. The host element is the same .ee-message-body as before, so
2035
+ // sizing and scrolling of the viewer are unchanged.
2036
+ _renderMessageBody(host, msg) {
2037
+ const root = host.attachShadow({ mode: 'open' });
2038
+ const style = this._createStyle(MESSAGE_BODY_STYLES);
2039
+
2040
+ const content = document.createElement('div');
2041
+ content.className = 'ee-message-body-content';
2042
+ if (msg.text && msg.text.html) {
2043
+ content.innerHTML = msg.text.html;
2044
+ } else if (msg.text && msg.text.plain) {
2045
+ const pre = document.createElement('pre');
2046
+ pre.textContent = msg.text.plain;
2047
+ content.appendChild(pre);
2048
+ }
2049
+
2050
+ root.replaceChildren(style, content);
2051
+ return root;
2052
+ }
2053
+
1971
2054
  // EmailEngine's web-safe HTML folds quoted thread history (reply history, forwarded content,
1972
2055
  // disclaimers) into a <details class="ee-collapsed-thread"> whose <summary> it leaves empty on
1973
2056
  // purpose, for the renderer to label. The fold is closed until the reader opens it.
@@ -1975,8 +2058,8 @@ export class EmailEngineClient {
1975
2058
  // A sender can put the same markup in their own HTML - it survives sanitization - so every
1976
2059
  // match is relabelled rather than trusted, and the control always reads as one of these two
1977
2060
  // labels instead of whatever text came with the message.
1978
- _labelCollapsedThreads(viewer) {
1979
- viewer.querySelectorAll('details.ee-collapsed-thread > summary.ee-collapsed-thread-toggle').forEach(toggle => {
2061
+ _labelCollapsedThreads(root) {
2062
+ root.querySelectorAll('details.ee-collapsed-thread > summary.ee-collapsed-thread-toggle').forEach(toggle => {
1980
2063
  const details = toggle.parentElement;
1981
2064
  const applyLabel = () => {
1982
2065
  toggle.textContent = details.open ? 'Hide quoted text' : 'Show quoted text';
@@ -2373,7 +2456,7 @@ export class EmailEngineClient {
2373
2456
  async _keepTokenAlive() {
2374
2457
  try {
2375
2458
  // Ping account endpoint to keep token alive
2376
- await this.apiRequest('GET', `/v1/account/${this.account}`);
2459
+ await this.apiRequest('GET', this._accountPath());
2377
2460
  console.debug('Keep-alive ping sent for sess_ token');
2378
2461
  } catch (error) {
2379
2462
  console.warn('Keep-alive ping failed:', error.message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/ee-client",
3
- "version": "1.7.1",
3
+ "version": "1.8.1",
4
4
  "description": "EmailEngine client library for browser and Node.js applications",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "eslint": "^8.57.1",
46
- "prettier": "^3.9.6"
46
+ "prettier": "^3.9.9"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "node-fetch": "^3.0.0"