emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -55,6 +55,28 @@
55
55
  rel="noopener noreferrer" class="link link-animated">the token log endpoint</a>. Logging starts when enabled and adds a storage write to each authenticated request.</span>
56
56
  </div>
57
57
 
58
+ <div class="grid gap-4 sm:grid-cols-2">
59
+ <div>
60
+ {{> ui/setting-ref name="tokenLogEntries"}}
61
+ {{#> ui/form-field id="settingsTokenLogEntries" label="Requests kept per token" error=errors.tokenLogEntries}}
62
+ <input type="number" min="1" class="input{{#if errors.tokenLogEntries}} is-invalid{{/if}}"
63
+ id="settingsTokenLogEntries" name="tokenLogEntries" value="{{values.tokenLogEntries}}" data-lpignore="true"
64
+ autocomplete="off" />
65
+ <span class="helper-text">A full log of typical entries takes roughly 170KB of Redis per token.</span>
66
+ {{/ui/form-field}}
67
+ </div>
68
+
69
+ <div>
70
+ {{> ui/setting-ref name="tokenLogAge"}}
71
+ {{#> ui/form-field id="settingsTokenLogAge" label="Log retention after last use (days)" error=errors.tokenLogAge}}
72
+ <input type="number" min="0.01" step="any" class="input{{#if errors.tokenLogAge}} is-invalid{{/if}}"
73
+ id="settingsTokenLogAge" name="tokenLogAge" value="{{values.tokenLogAge}}" data-lpignore="true"
74
+ autocomplete="off" />
75
+ <span class="helper-text">A token nobody uses takes its log with it after this long.</span>
76
+ {{/ui/form-field}}
77
+ </div>
78
+ </div>
79
+
58
80
  {{/ui/card}}
59
81
 
60
82
  {{#> ui/card title="Secrets and Encryption" id="secrets" bodyClass="space-y-4"}}
@@ -117,6 +117,50 @@
117
117
  {{/ui/form-field}}
118
118
  </div>
119
119
 
120
+ <div class="grid gap-4 sm:grid-cols-2 mt-4">
121
+ <div>
122
+ {{> ui/setting-ref name="queueKeepFailed"}}
123
+ {{#> ui/form-field id="settingsQueueKeepFailed" label="Failed job limit" error=errors.queueKeepFailed}}
124
+ <input type="number" min="1" class="input{{#if errors.queueKeepFailed}} is-invalid{{/if}}"
125
+ id="settingsQueueKeepFailed" name="queueKeepFailed" value="{{values.queueKeepFailed}}" data-lpignore="true"
126
+ autocomplete="off" />
127
+ <span class="helper-text">Failed jobs retained per queue, at least. A failed job is the only record that a
128
+ delivery was given up on.</span>
129
+ {{/ui/form-field}}
130
+ </div>
131
+
132
+ <div>
133
+ {{> ui/setting-ref name="queueKeepFailedAge"}}
134
+ {{#> ui/form-field id="settingsQueueKeepFailedAge" label="Failed job retention (days)" error=errors.queueKeepFailedAge}}
135
+ <input type="number" min="0.01" step="any" class="input{{#if errors.queueKeepFailedAge}} is-invalid{{/if}}"
136
+ id="settingsQueueKeepFailedAge" name="queueKeepFailedAge" value="{{values.queueKeepFailedAge}}" data-lpignore="true"
137
+ autocomplete="off" />
138
+ <span class="helper-text">How long failed jobs are kept.</span>
139
+ {{/ui/form-field}}
140
+ </div>
141
+
142
+ <div>
143
+ {{> ui/setting-ref name="queueKeepFailedContent"}}
144
+ {{#> ui/form-field id="settingsQueueKeepFailedContent" label="Retryable failed messages" error=errors.queueKeepFailedContent}}
145
+ <input type="number" min="0" class="input{{#if errors.queueKeepFailedContent}} is-invalid{{/if}}"
146
+ id="settingsQueueKeepFailedContent" name="queueKeepFailedContent" value="{{values.queueKeepFailedContent}}" data-lpignore="true"
147
+ autocomplete="off" />
148
+ <span class="helper-text">How many of the most recent failed messages keep their content so they can be
149
+ retried. 0 keeps none.</span>
150
+ {{/ui/form-field}}
151
+ </div>
152
+
153
+ <div>
154
+ {{> ui/setting-ref name="queueKeepFailedContentSize"}}
155
+ {{#> ui/form-field id="settingsQueueKeepFailedContentSize" label="Retryable message content (MB)" error=errors.queueKeepFailedContentSize}}
156
+ <input type="number" min="0" step="any" class="input{{#if errors.queueKeepFailedContentSize}} is-invalid{{/if}}"
157
+ id="settingsQueueKeepFailedContentSize" name="queueKeepFailedContentSize" value="{{values.queueKeepFailedContentSize}}" data-lpignore="true"
158
+ autocomplete="off" />
159
+ <span class="helper-text">Total size of the kept content. 0 keeps none.</span>
160
+ {{/ui/form-field}}
161
+ </div>
162
+ </div>
163
+
120
164
  </div>
121
165
  </div>
122
166
 
@@ -103,6 +103,34 @@ class="mb-1"}}
103
103
  </div>
104
104
  </div>
105
105
 
106
+ {{#> ui/details summary="Delivery Retries" summarySmall="(All webhooks)"
107
+ class="card bg-base-100 shadow-md mb-6" open=values.webhooksDeliveryAttempts}}
108
+
109
+ <p class="mb-4">How a failed webhook delivery is retried. The delay doubles with every attempt. Changes apply to events queued after saving.</p>
110
+
111
+ <div class="grid gap-4 md:grid-cols-2">
112
+ <div>
113
+ {{> ui/setting-ref name="webhooksDeliveryAttempts"}}
114
+ {{#> ui/form-field id="settingsWebhooksDeliveryAttempts" label="Delivery attempts" error=errors.webhooksDeliveryAttempts}}
115
+ <input type="number" min="1" max="100" class="input{{#if errors.webhooksDeliveryAttempts}} is-invalid{{/if}}"
116
+ id="settingsWebhooksDeliveryAttempts" name="webhooksDeliveryAttempts" value="{{values.webhooksDeliveryAttempts}}"
117
+ placeholder="{{defaultWebhookAttempts}}" data-lpignore="true" autocomplete="off" />
118
+ <span class="helper-text">Attempts per event, including the first. Empty uses {{defaultWebhookAttempts}}.</span>
119
+ {{/ui/form-field}}
120
+ </div>
121
+ <div>
122
+ {{> ui/setting-ref name="webhooksRetryDelay"}}
123
+ {{#> ui/form-field id="settingsWebhooksRetryDelay" label="First retry delay (seconds)" error=errors.webhooksRetryDelay}}
124
+ <input type="number" min="1" max="3600" class="input{{#if errors.webhooksRetryDelay}} is-invalid{{/if}}"
125
+ id="settingsWebhooksRetryDelay" name="webhooksRetryDelay" value="{{values.webhooksRetryDelay}}"
126
+ placeholder="{{defaultWebhookRetryDelay}}" data-lpignore="true" autocomplete="off" />
127
+ <span class="helper-text">Wait before the first retry. Empty uses {{defaultWebhookRetryDelay}} seconds.</span>
128
+ {{/ui/form-field}}
129
+ </div>
130
+ </div>
131
+
132
+ {{/ui/details}}
133
+
106
134
  {{#> ui/details summary="Custom Headers" summarySmall="(Default webhook only)"
107
135
  class="card bg-base-100 shadow-md mb-6" open=values.customHeaders}}
108
136
 
@@ -175,6 +203,14 @@ class="mb-1"}}
175
203
  hint="Remove unsafe HTML, convert plain text to HTML when needed, and collapse quoted thread history."}}
176
204
  </div>
177
205
 
206
+ <div>
207
+ {{> ui/setting-ref name="disableThreadCollapse"}}
208
+ {{> ui/checkbox id="settingsDisableThreadCollapse" name="disableThreadCollapse"
209
+ label="Keep quoted thread history expanded" class="text-list" checked=values.disableThreadCollapse
210
+ error=errors.disableThreadCollapse
211
+ hint="Do not fold quoted replies into a collapsed block in web-safe HTML, here and in API responses that ask for it."}}
212
+ </div>
213
+
178
214
  <div>
179
215
  {{> ui/setting-ref name="notifyTextSize"}}
180
216
  {{#> ui/form-field id="settingsNotifyTextSize" label="Content Size Limit" error=errors.notifyTextSize}}
@@ -299,12 +299,15 @@
299
299
 
300
300
  <!-- Footer -->
301
301
  <footer class="bg-base-100 border-base-content/20 border-t py-6 mt-auto">
302
- <div class="text-base-content/60 text-center text-sm">
303
- <a href="{{packageData.homepage}}" target="_blank" rel="noopener noreferrer" class="link link-animated">EmailEngine</a>
304
- v{{packageData.version}}.
305
- <span>&copy; 2020-{{currentYear}}</span>
306
- <a class="link link-animated" href="https://postalsys.com/contact" target="_blank" rel="noopener noreferrer">Postal Systems O&Uuml;</a>.
307
- <a class="link link-animated" href="/admin/legal">License and terms</a>.
302
+ <div class="text-base-content/60 flex flex-col items-center gap-3 px-4 text-sm sm:px-6 lg:flex-row lg:justify-between">
303
+ <p>EmailEngine v{{packageData.version}} &middot; &copy; 2020-{{currentYear}} Postal Systems O&Uuml;</p>
304
+ <nav aria-label="Footer">
305
+ <ul class="flex flex-wrap justify-center gap-x-6 gap-y-2">
306
+ <li><a class="link link-animated inline-flex items-center gap-1.5" href="https://learn.emailengine.app/" target="_blank" rel="noopener noreferrer"><span class="icon-[tabler--book] size-4" aria-hidden="true"></span>Documentation</a></li>
307
+ <li><a class="link link-animated inline-flex items-center gap-1.5" href="https://emailengine.app/support" target="_blank" rel="noopener noreferrer"><span class="icon-[tabler--lifebuoy] size-4" aria-hidden="true"></span>Support</a></li>
308
+ <li><a class="link link-animated inline-flex items-center gap-1.5" href="/admin/legal"><span class="icon-[tabler--gavel] size-4" aria-hidden="true"></span>License and terms</a></li>
309
+ </ul>
310
+ </nav>
308
311
  </div>
309
312
  </footer>
310
313
  <!-- End of Footer -->
package/views/legal.hbs CHANGED
@@ -24,6 +24,14 @@
24
24
 
25
25
  <ul class="divide-base-content/10 border-base-content/10 divide-y border-t">
26
26
 
27
+ <li class="px-6 py-4">
28
+ <a href="https://emailengine.app/support" target="_blank" rel="noopener noreferrer" class="link link-animated">
29
+ <span class="icon-[tabler--arrow-right] size-4 align-text-bottom"></span>
30
+ <strong>Support</strong>
31
+ </a>
32
+ - or email <a href="mailto:support@postalsys.com" class="link link-animated">support@postalsys.com</a>
33
+ </li>
34
+
27
35
  <li class="px-6 py-4">
28
36
  <strong>
29
37
  {{#if licenseInfo.details.key}}
@@ -11,20 +11,24 @@
11
11
  {{#if retention.failedCountFromSetting}}
12
12
  The count follows the completed job history limit in
13
13
  <a href="/admin/config/service#queue_settings" class="link link-animated">General settings</a>, which is above the
14
- floor of {{formatInteger retention.failedCountFloor userLocale}} set with <code>EENGINE_QUEUE_KEEP_FAILED</code>;
14
+ floor of {{formatInteger retention.failedCountFloor userLocale}} set by the failed job limit there or by
15
+ <code>EENGINE_QUEUE_KEEP_FAILED</code>;
15
16
  {{else}}
16
- The count is set with <code>EENGINE_QUEUE_KEEP_FAILED</code>, or by the completed job history limit in
17
- <a href="/admin/config/service#queue_settings" class="link link-animated">General settings</a> when that is higher;
17
+ The count is the failed job limit in
18
+ <a href="/admin/config/service#queue_settings" class="link link-animated">General settings</a> (or
19
+ <code>EENGINE_QUEUE_KEEP_FAILED</code>), or the completed job history limit there when that is higher;
18
20
  {{/if}}
19
- the age with <code>EENGINE_QUEUE_KEEP_FAILED_AGE</code>.
21
+ the age is set there too (or by <code>EENGINE_QUEUE_KEEP_FAILED_AGE</code>).
20
22
  {{#equals queue.name "submit"}}
21
23
  {{#if failedContent.limits.keepsContent}}
22
24
  The content of the {{formatInteger failedContent.limits.maxCount userLocale}} most recent failed messages is kept
23
- so they can be retried, up to {{failedContent.limits.maxBytesLabel}} in total, set with
24
- <code>EENGINE_QUEUE_KEEP_FAILED_CONTENT</code> and <code>EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE</code>.
25
+ so they can be retried, up to {{failedContent.limits.maxBytesLabel}} in total, set in
26
+ <a href="/admin/config/service#queue_settings" class="link link-animated">General settings</a> (or with
27
+ <code>EENGINE_QUEUE_KEEP_FAILED_CONTENT</code> and <code>EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE</code>).
25
28
  {{else}}
26
- The content of a failed message is not kept, so none can be retried from here; set
27
- <code>EENGINE_QUEUE_KEEP_FAILED_CONTENT</code> to keep some.
29
+ The content of a failed message is not kept, so none can be retried from here; raise the retained failed
30
+ message limits in <a href="/admin/config/service#queue_settings" class="link link-animated">General settings</a>
31
+ (or <code>EENGINE_QUEUE_KEEP_FAILED_CONTENT</code>) to keep some.
28
32
  {{/if}}
29
33
  {{/equals}}
30
34
  {{else}}
@@ -1,14 +1,16 @@
1
1
  {{!--
2
2
  ui/env-managed-alert - notice for the settings pages registered through
3
- lib/ui-routes/settings-page.js, naming the form fields whose values the EENGINE_SETTINGS
4
- environment variable re-applies on every boot. A value saved for one of them holds only
5
- until the next restart, and without this the page would show the save succeeding.
6
- Renders nothing when the page has no such field. The inputs stay enabled on purpose -
7
- a disabled control drops out of the POST and would silently strip its value from the
3
+ lib/ui-routes/settings-page.js, naming the form fields whose values come from the environment.
4
+ Two kinds: fields the EENGINE_SETTINGS environment variable re-applies on every boot (a value
5
+ saved for one of them holds only until the next restart), and fields whose own environment
6
+ variable overrides the setting (lib/env-setting-overrides.js: the page shows the variable's
7
+ value and a value typed there is not saved). Without this the page would show the save
8
+ succeeding. Renders nothing when the page has no such field. The inputs stay enabled on
9
+ purpose - a disabled control drops out of the POST and would silently strip its value from the
8
10
  save - so the notice is the whole treatment.
9
11
  {{> ui/env-managed-alert}}
10
- Reads `envManagedKeys` (array of field names) from the page context; registerSettingsPage
11
- sets it on every render of the page.
12
+ Reads `envManagedKeys` (array of field names) and `envOverriddenSettings` (array of
13
+ `{key, env}`) from the page context; registerSettingsPage sets both on every render of the page.
12
14
  --}}
13
15
  {{#if envManagedKeys.length}}
14
16
  {{#> ui/alert-banner variant="info" icon="icon-[tabler--info-circle]" title="Some fields are set by the environment"}}
@@ -17,3 +19,10 @@
17
19
  {{#each envManagedKeys}}<code>{{this}}</code>{{#unless @last}}, {{/unless}}{{/each}}.</div>
18
20
  {{/ui/alert-banner}}
19
21
  {{/if}}
22
+ {{#if envOverriddenSettings.length}}
23
+ {{#> ui/alert-banner variant="info" icon="icon-[tabler--info-circle]" title="Some fields are pinned by environment variables"}}
24
+ <div>These settings are set by their own environment variable, which takes precedence over the saved setting. The
25
+ form shows the environment value, and a value entered for them here is not saved while the variable is set:
26
+ {{#each envOverriddenSettings}}<code>{{key}}</code> (<code>{{env}}</code>){{#unless @last}}, {{/unless}}{{/each}}.</div>
27
+ {{/ui/alert-banner}}
28
+ {{/if}}
package/workers/api.js CHANGED
@@ -89,6 +89,7 @@ const { routeGrant, perRequestSurfaceAdmits, sessionTokenAdmits } = require('../
89
89
  const { mcpOptions } = require('../lib/api-routes/route-metadata');
90
90
 
91
91
  const { redis } = require('../lib/db');
92
+ const { createHealthChecks } = require('../lib/health');
92
93
  const { Account } = require('../lib/account');
93
94
  const settings = require('../lib/settings');
94
95
 
@@ -125,6 +126,9 @@ const {
125
126
 
126
127
  const registerApiRoutes = require('../lib/api-routes');
127
128
  const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
129
+ const { deprecationExt } = require('../lib/deprecations');
130
+ const { errorCodeExt } = require('../lib/api-error-codes');
131
+ const { apiCallDuration } = require('../lib/request-timing');
128
132
  const { registerHandlebarsHelpers } = require('../lib/handlebars-helpers');
129
133
 
130
134
  const {
@@ -237,6 +241,9 @@ const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
237
241
  // the API proxy setting is on, which is the historical behavior; see resolveClientIp().
238
242
  const API_PROXY_ADDRESSES = readEnvList('EENGINE_API_PROXY_ADDRESSES');
239
243
 
244
+ // How long a shutdown waits for requests in flight, just below the main thread's WORKER_DRAIN_TIMEOUT
245
+ const API_DRAIN_TIMEOUT = 6000;
246
+
240
247
  const IMAP_WORKER_COUNT = getWorkerCount(readEnvValue('EENGINE_WORKERS') || (config.workers && config.workers.imap)) || 4;
241
248
 
242
249
  // Max POST body size for message uploads
@@ -391,12 +398,32 @@ async function onCommand(command) {
391
398
  // reconciler is a singleton but the HTTPS listeners are not, and a sibling worker that
392
399
  // kept its old context would go on serving the certificate that was just replaced.
393
400
  return refreshApiTls ? await refreshApiTls() : { updated: false };
401
+ case 'close':
402
+ return await drainApiServer();
394
403
  default:
395
404
  logger.debug({ msg: 'Unhandled command', command });
396
405
  return 999;
397
406
  }
398
407
  }
399
408
 
409
+ /**
410
+ * Stops taking new connections and waits for the requests in flight, so a shutdown no longer cuts
411
+ * them. Readiness turns 503 first, which tells a load balancer to stop sending traffic here. The
412
+ * main thread bounds the whole wait with its own drain timeout, this one is just below it.
413
+ */
414
+ async function drainApiServer() {
415
+ apiDraining = true;
416
+ if (!sessionAuthServer) {
417
+ return true;
418
+ }
419
+ try {
420
+ await sessionAuthServer.stop({ timeout: API_DRAIN_TIMEOUT });
421
+ } catch (err) {
422
+ logger.warn({ msg: 'Failed to stop the API server cleanly', err });
423
+ }
424
+ return true;
425
+ }
426
+
400
427
  function publishChangeEvent(data) {
401
428
  // Nothing to do (and no reason to compute the badge label) when no SSE client is
402
429
  // subscribed - the common case whenever no admin browser has the dashboard open.
@@ -430,7 +457,8 @@ function publishChangeEvent(data) {
430
457
 
431
458
  // The Hapi server, published by init() once the session strategy is registered and the boot-time
432
459
  // default has been decided, so the authData branch of the settings dispatcher below cannot set a
433
- // strategy that does not exist yet or race the boot-time server.auth.default() call
460
+ // strategy that does not exist yet or race the boot-time server.auth.default() call. Also what the
461
+ // shutdown drain stops
434
462
  let sessionAuthServer = null;
435
463
 
436
464
  // Installs a renewed certificate on this worker's own HTTPS listener. Published by init() when the
@@ -1586,11 +1614,19 @@ function registerRequestEvents(server) {
1586
1614
  // only log API calls
1587
1615
  return;
1588
1616
  }
1589
- metrics(logger, 'apiCall', 'inc', {
1590
- method: request.method,
1591
- route: request.route.path,
1592
- statusCode: request.response && request.response.statusCode
1593
- });
1617
+ // One message per request: the latency rides on the call counter's message and the main
1618
+ // thread observes it there, rather than costing a second postMessage on every request
1619
+ try {
1620
+ parentPort.postMessage({
1621
+ cmd: 'metrics',
1622
+ key: 'apiCall',
1623
+ method: 'inc',
1624
+ args: [{ method: request.method, route: request.route.path, statusCode: request.response && request.response.statusCode }],
1625
+ duration: apiCallDuration(request.info)
1626
+ });
1627
+ } catch (err) {
1628
+ logger.error({ msg: 'Failed to post metrics to parent', err });
1629
+ }
1594
1630
  });
1595
1631
  }
1596
1632
 
@@ -1771,32 +1807,64 @@ function registerStaticFilesRoute(server) {
1771
1807
  });
1772
1808
  }
1773
1809
 
1810
+ // Set by the close command: readiness answers 503 from then on while Hapi drains the requests in flight
1811
+ let apiDraining = false;
1812
+
1813
+ const healthChecks = createHealthChecks({
1814
+ call,
1815
+ redis,
1816
+ prefix: REDIS_PREFIX,
1817
+ expectedImapWorkers: IMAP_WORKER_COUNT,
1818
+ isDraining: () => apiDraining
1819
+ });
1820
+
1821
+ /**
1822
+ * Runs a readiness check and turns its failure into a 503 carrying a `code`
1823
+ * @param {Object} request - Hapi request
1824
+ * @returns {Promise<Object>} The check result
1825
+ */
1826
+ async function answerReadiness(request) {
1827
+ // Same rule as the license lookup: a header value the timer would mangle is ignored
1828
+ const { error: timeoutError, value: timeout } = headerTimeoutSchema.validate(request.headers['x-ee-timeout']);
1829
+ try {
1830
+ return await healthChecks.ready(timeoutError ? undefined : timeout);
1831
+ } catch (err) {
1832
+ if (err.statusCode !== 503) {
1833
+ throw err;
1834
+ }
1835
+ const error = Boom.boomify(err, { statusCode: err.statusCode });
1836
+ error.output.payload.code = err.code;
1837
+ throw error;
1838
+ }
1839
+ }
1840
+
1774
1841
  function registerHealthRoute(server) {
1842
+ const options = {
1843
+ auth: false,
1844
+ tags: ['static', 'health']
1845
+ };
1846
+
1847
+ // Kept with its historical meaning (everything needed to serve traffic), for the probes and
1848
+ // smoke tests already pointed at it
1775
1849
  server.route({
1776
1850
  method: 'GET',
1777
1851
  path: '/health',
1778
- async handler(request) {
1779
- const imapWorkerCount = await call({ cmd: 'imapWorkerCount', timeout: request.headers['x-ee-timeout'] });
1780
- if (imapWorkerCount < IMAP_WORKER_COUNT) {
1781
- let error = Boom.boomify(new Error('Not all IMAP workers available'), { statusCode: 500 });
1782
- throw error;
1783
- }
1852
+ handler: answerReadiness,
1853
+ options: Object.assign({ description: 'Health check' }, options)
1854
+ });
1784
1855
 
1785
- let checkKey = `${REDIS_PREFIX}test:${Date.now()}`;
1786
- let expected = crypto.randomBytes(8).toString('hex');
1787
- let res = await redis.multi().set(checkKey, expected).get(checkKey).del(checkKey).exec();
1788
- if (!(res[1] && res[1][1] === expected && res[2] && res[2][1] === 1)) {
1789
- let error = Boom.boomify(new Error('Database check failed'), { statusCode: 500 });
1790
- throw error;
1791
- }
1856
+ server.route({
1857
+ method: 'GET',
1858
+ path: '/health/ready',
1859
+ handler: answerReadiness,
1860
+ options: Object.assign({ description: 'Readiness check' }, options)
1861
+ });
1792
1862
 
1793
- return { success: true };
1794
- },
1795
- options: {
1796
- description: 'Health check',
1797
- auth: false,
1798
- tags: ['static', 'health']
1799
- }
1863
+ server.route({
1864
+ method: 'GET',
1865
+ path: '/health/live',
1866
+ handler: () => healthChecks.live(),
1867
+ options: Object.assign({ description: 'Liveness check' }, options)
1800
1868
  });
1801
1869
  }
1802
1870
 
@@ -2396,9 +2464,11 @@ async function gmailMissingScopesView(flow, r, grantedScopes) {
2396
2464
  missing: missingScopes
2397
2465
  });
2398
2466
 
2399
- // Best-effort revocation of the partial token
2400
- oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2401
- request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2467
+ // Best-effort revocation of the partial token. revokeToken() never throws, it reports
2468
+ oAuth2Client.revokeToken(r.refresh_token || r.access_token).then(revocation => {
2469
+ if (!revocation.revoked) {
2470
+ request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', revocation });
2471
+ }
2402
2472
  });
2403
2473
 
2404
2474
  const retryUrl = await startOAuthRetry(flow, accountData.email);
@@ -2735,14 +2805,13 @@ async function rejectOAuthIdentity(flow, { grantToken, workspaceDomain }, expect
2735
2805
  const { request, h, accountData, oauth2App, oAuth2Client, providerIdentities } = flow;
2736
2806
 
2737
2807
  // The code was already exchanged, so a refused setup leaves us holding a grant we will never
2738
- // use. Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2739
- // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2808
+ // use. Best effort, and the same duck-typing guard Account.findRevocableGrant() uses: only
2809
+ // GmailOauth implements revokeToken, which reports a failure rather than throwing it.
2740
2810
  const revokeUnusedGrant = async failureMessage => {
2741
2811
  if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2742
- try {
2743
- await oAuth2Client.revokeToken(grantToken);
2744
- } catch (err) {
2745
- request.logger.warn({ msg: failureMessage, err });
2812
+ const revocation = await oAuth2Client.revokeToken(grantToken);
2813
+ if (!revocation.revoked) {
2814
+ request.logger.warn({ msg: failureMessage, revocation });
2746
2815
  }
2747
2816
  }
2748
2817
  };
@@ -3296,8 +3365,8 @@ function registerResponseExtensions(server) {
3296
3365
  const wantsJsonError = routeTags.includes('api') || routeTags.includes('external');
3297
3366
 
3298
3367
  if (request.errorInfo && wantsJsonError) {
3299
- // JSON response for API requests
3300
-
3368
+ // JSON response for API requests. A 404 thrown without a code already got NotFound
3369
+ // from errorCodeExt(), registered ahead of this handler
3301
3370
  let res = h.response(request.errorInfo);
3302
3371
  if (error.output.headers) {
3303
3372
  for (let key of Object.keys(error.output.headers)) {
@@ -3322,11 +3391,17 @@ function registerResponseExtensions(server) {
3322
3391
  .code(error.output.statusCode);
3323
3392
  };
3324
3393
 
3394
+ // First: fills in the default code of an error body before preResponse copies it
3395
+ server.ext('onPreResponse', errorCodeExt);
3325
3396
  server.ext('onPreResponse', preResponse);
3326
3397
 
3327
3398
  // After preResponse on purpose: it replaces an error response with the rendered error page
3328
3399
  // or a JSON body, and the headers have to land on whatever is actually sent
3329
3400
  server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
3401
+
3402
+ // Deprecation, Sunset and Link on the routes that declare plugins.deprecation, also after
3403
+ // preResponse for the same reason
3404
+ server.ext('onPreResponse', deprecationExt({ logger }));
3330
3405
  }
3331
3406
 
3332
3407
  function registerTotpExtension(server) {