emailengine-app 2.84.1 → 2.85.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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
package/workers/export.js CHANGED
@@ -125,7 +125,7 @@ async function notify(account, event, data) {
125
125
  data
126
126
  };
127
127
 
128
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
128
+ await Webhooks.enqueue(event, payload);
129
129
  }
130
130
 
131
131
  // Returns a throttled callback that extends both the BullMQ job lock and the export's Redis key
package/workers/submit.js CHANGED
@@ -116,7 +116,7 @@ async function notify(account, event, data) {
116
116
  payload.data = data;
117
117
  }
118
118
 
119
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
119
+ await Webhooks.enqueue(event, payload);
120
120
  }
121
121
 
122
122
  const smtpLogger = {};
@@ -14,18 +14,27 @@ const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, red
14
14
  const { sendWebhookRequest, isUnrecoverableWebhookError } = require('../lib/webhook-request');
15
15
  const { willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
16
16
  const { validateWebhookTarget } = require('../lib/webhook-egress');
17
- const { resolveTargetUrl, isDeliverableRoute, eventAllowed, headerLevels, deliveryCustomHeaders, isRouteMappingMissing } = require('../lib/webhook-routing');
17
+ const {
18
+ resolveTargetUrl,
19
+ isDeliverableRoute,
20
+ eventAllowed,
21
+ defaultRouteTakes,
22
+ headerLevels,
23
+ deliveryCustomHeaders,
24
+ isRouteMappingMissing
25
+ } = require('../lib/webhook-routing');
18
26
 
19
27
  const { initSentry } = require('../lib/sentry');
20
28
  initSentry('webhooks');
21
29
 
22
30
  const { redis, queueConf, logBullErrors } = require('../lib/db');
23
- const { Worker, UnrecoverableError } = require('bullmq');
31
+ const { Worker, UnrecoverableError, DelayedError } = require('bullmq');
32
+ const { penaltyKey, penaltyFor } = require('../lib/webhook-penalty');
24
33
  const settings = require('../lib/settings');
25
34
  const { decryptField } = require('../lib/encrypt');
26
35
  const getSecret = require('../lib/get-secret');
27
36
 
28
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MESSAGE_NEW_NOTIFY } = require('../lib/consts');
37
+ const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('../lib/consts');
29
38
 
30
39
  const { fetch: fetchCmd } = require('undici');
31
40
 
@@ -202,7 +211,7 @@ parentPort.on('message', message => {
202
211
 
203
212
  const notifyWorker = new Worker(
204
213
  'notify',
205
- async job => {
214
+ async (job, token) => {
206
215
  // do not process active jobs, use it for debugging only
207
216
  //return new Promise((resolve, reject) => {});
208
217
  let accountKey = getAccountKey(job.data.account);
@@ -293,6 +302,30 @@ const notifyWorker = new Worker(
293
302
  return;
294
303
  }
295
304
 
305
+ // A target whose last attempt ran into the timeout is penalised for a short while, and a
306
+ // delivery to it waits out the penalty in the delayed set instead of costing the queue
307
+ // another full attempt timeout; see lib/webhook-penalty.js. The attempt count is not
308
+ // spent by the wait
309
+ const targetPenaltyKey = penaltyKey(webhooks);
310
+ if (targetPenaltyKey) {
311
+ let remaining = await redis.pttl(targetPenaltyKey);
312
+ if (remaining > 0) {
313
+ logger.debug({
314
+ msg: 'Webhook target is penalised, delaying delivery',
315
+ action: 'webhook',
316
+ queue: job.queue.name,
317
+ code: 'target_penalised',
318
+ job: job.id,
319
+ event: job.name,
320
+ account: job.data.account,
321
+ webhooks: redactUrlCredentials(webhooks),
322
+ delay: remaining
323
+ });
324
+ await job.moveToDelayed(Date.now() + remaining, token);
325
+ throw new DelayedError();
326
+ }
327
+ }
328
+
296
329
  // Only the header lists that travel to this target are loaded; lib/webhook-routing.js
297
330
  // holds the rule and the reasons
298
331
  let levels = headerLevels(target.source);
@@ -318,14 +351,15 @@ const notifyWorker = new Worker(
318
351
  }
319
352
 
320
353
  if (!customRoute) {
321
- // custom routes have their own mappings
322
- let webhookEvents = (await settings.get('webhookEvents')) || [];
323
- if (!eventAllowed(webhookEvents, job.name)) {
354
+ // custom routes have their own mappings; the default route follows webhookEvents and
355
+ // inboxNewOnly, by the same rule pushToQueue() applied before queueing
356
+ let { webhookEvents, inboxNewOnly } = await settings.getMulti('webhookEvents', 'inboxNewOnly');
357
+ if (!defaultRouteTakes(job.name, job.data, { webhookEvents, inboxNewOnly })) {
324
358
  logger.trace({
325
- msg: 'Webhook event not in whitelist',
359
+ msg: 'Webhook event not taken by the default route',
326
360
  action: 'webhook',
327
361
  queue: job.queue.name,
328
- code: 'event_not_whitelisted',
362
+ code: eventAllowed(webhookEvents, job.name) ? 'inbox_new_only' : 'event_not_whitelisted',
329
363
  job: job.id,
330
364
  event: job.name,
331
365
  account: job.data.account,
@@ -333,31 +367,6 @@ const notifyWorker = new Worker(
333
367
  });
334
368
  return;
335
369
  }
336
-
337
- switch (job.data.event) {
338
- case MESSAGE_NEW_NOTIFY: {
339
- // check if we need to send this event or not
340
- let isInbox = false;
341
- if (
342
- (job.data.account && job.data.path === 'INBOX') ||
343
- job.data.specialUse === '\\Inbox' ||
344
- (job.data.data && job.data.data.messageSpecialUse === '\\Inbox') ||
345
- (job.data.data && job.data.data.labels && job.data.data.labels.includes('\\Inbox'))
346
- ) {
347
- isInbox = true;
348
- }
349
-
350
- if (!isInbox) {
351
- const inboxNewOnly = (await settings.get('inboxNewOnly')) || false;
352
- if (inboxNewOnly) {
353
- // ignore this message
354
- return;
355
- }
356
- }
357
-
358
- break;
359
- }
360
- }
361
370
  }
362
371
 
363
372
  // only log some of the properties for webhooks, not full contents
@@ -513,6 +522,17 @@ const notifyWorker = new Worker(
513
522
  // egress and redirect failures are thrown as UnrecoverableError below, so they are final as well
514
523
  let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
515
524
 
525
+ // A target that held the attempt until it timed out, or refused the connection, is
526
+ // penalised so the next deliveries to it do not each cost the same wait
527
+ let penalty = penaltyFor(err, WEBHOOK_TIMEOUT || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
528
+ if (penalty && targetPenaltyKey) {
529
+ try {
530
+ await redis.set(targetPenaltyKey, '1', 'PX', penalty);
531
+ } catch (penaltyErr) {
532
+ // a missed penalty costs the queue one more timeout, nothing else
533
+ }
534
+ }
535
+
516
536
  // BullMQ keeps only the message of a failure on the job. The code and the HTTP status
517
537
  // are what explain it, so they are recorded the way the submit worker records its own
518
538
  // delivery errors, for the queue browser to read back
package/config/test.toml DELETED
@@ -1,46 +0,0 @@
1
-
2
-
3
- # JSON formatted settings
4
- settings = '''
5
- {
6
- "webhooksEnabled": true,
7
- "webhooks": "http://127.0.0.1:7078/webhooks",
8
- "webhookEvents": ["*"],
9
- "webhooksCustomHeaders": [
10
- {
11
- "key": "Custom-Header",
12
- "value": "Custom-Value"
13
- }
14
- ],
15
- "serviceUrl": "http://127.0.0.1:7077",
16
- "ignoreMailCertErrors": true,
17
- "serviceSecret": "a cat",
18
- "sentryEnabled": false
19
- }
20
- '''
21
-
22
- # static access token
23
- # 2aa97ad0456d6624a55d30780aa2ff61bfb7edc6fa00935b40814b271e718660
24
- preparedToken = "hKJpZNlAZWEzODczZjkyMzRmYjNiOGI3MDAwNDMzNzMxMzhjNzMwYzU2ZmQyZjdmYTI3ZGJjZGM2MWQ0YzljMmIyZGY4ZKdjcmVhdGVk1_-UiOcAZ2lLVqZzY29wZXORoSqrZGVzY3JpcHRpb26qdGVzdCB0b2tlbg"
25
-
26
-
27
- [service]
28
- secret = "secret cat"
29
-
30
- [workers]
31
- imap = 1
32
-
33
- [log]
34
- raw = true
35
-
36
- [dbs]
37
- # redis connection
38
- redis = "redis://127.0.0.1:6379/13"
39
-
40
- [api]
41
- host = "0.0.0.0"
42
- port = 7077
43
-
44
-
45
- [webhooksServer]
46
- port = 7078
package/install.sh DELETED
@@ -1,428 +0,0 @@
1
- #!/bin/bash
2
-
3
- set -e
4
-
5
- DOMAIN_NAME=$1
6
- VERSION=$2
7
-
8
- # Strip 'v' prefix if present in version
9
- if [ -n "$VERSION" ] && [ "$VERSION" != "latest" ]; then
10
- VERSION="${VERSION#v}"
11
- fi
12
-
13
- # Default to latest if no version specified
14
- if [ -z "$VERSION" ] || [ "$VERSION" = "latest" ]; then
15
- APP_URL="https://github.com/postalsys/emailengine/releases/latest/download/emailengine.tar.gz"
16
- else
17
- APP_URL="https://github.com/postalsys/emailengine/releases/download/v${VERSION}/emailengine.tar.gz"
18
- fi
19
-
20
- IS_UPGRADE=false
21
-
22
- show_info () {
23
- echo "Usage: $0 <domain-name> [version]"
24
- echo "Where"
25
- echo " <domain-name> is the domain name for EmailEngine, eg. \"example.com\""
26
- echo " [version] is the optional version to install (default: latest)"
27
- echo " eg. \"2.55.4\" or \"v2.55.4\" will install v2.55.4"
28
- }
29
-
30
- if [[ $EUID -ne 0 ]]; then
31
- echo "This script must be run as root" 1>&2
32
- show_info
33
- exit 1
34
- fi
35
-
36
- if [ "$DOMAIN_NAME" = "help" ]; then
37
- show_info
38
- exit
39
- fi
40
-
41
- if [ "$DOMAIN_NAME" = "-h" ]; then
42
- show_info
43
- exit
44
- fi
45
-
46
- # Check for existing installation
47
- if systemctl is-active emailengine >/dev/null 2>&1; then
48
- # Get current version
49
- CURRENT_VERSION=$(/opt/emailengine -v 2>/dev/null | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | sed 's/^v//' || echo "unknown")
50
-
51
- # Get target version
52
- if [ -z "$VERSION" ] || [ "$VERSION" = "latest" ]; then
53
- TARGET_VERSION=$(curl -sL https://github.com/postalsys/emailengine/releases/latest/download/version.txt 2>/dev/null || echo "latest")
54
- VERSION_DISPLAY="latest ($TARGET_VERSION)"
55
- else
56
- TARGET_VERSION="$VERSION"
57
- VERSION_DISPLAY="$VERSION"
58
- fi
59
-
60
- echo "EmailEngine is already installed and running."
61
- echo " Current version: $CURRENT_VERSION"
62
- echo " Target version: $VERSION_DISPLAY"
63
- echo
64
- read -p "Do you want to proceed with the upgrade/change? (y/N): " -n 1 -r
65
- echo
66
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
67
- echo "Installation cancelled."
68
- exit 0
69
- fi
70
- IS_UPGRADE=true
71
- echo "Proceeding with upgrade/version change..."
72
- echo
73
- else
74
- echo
75
- echo "NB! This install script works on public-facing servers, do not run it on local instances."
76
- echo "The installer tries to provision an HTTPS certificate, and the process will fail if the server
77
- is inaccessible from the public web.
78
- "
79
- read -n 1 -s -r -p "Press any key to continue..."
80
- echo "
81
- "
82
- fi
83
-
84
- if ! [ -x $(command -v curl) ]; then
85
- apt-get update
86
- apt-get install curl -q -y
87
- echo ""
88
- fi
89
-
90
- if [[ -z $DOMAIN_NAME ]]; then
91
- # For upgrades, try to extract existing domain from Caddyfile
92
- if [ "$IS_UPGRADE" = true ] && [ -f /etc/caddy/Caddyfile ]; then
93
- EXISTING_DOMAIN=$(grep -E '^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9] \{' /etc/caddy/Caddyfile 2>/dev/null | head -1 | cut -d' ' -f1 || echo "")
94
- if [ -n "$EXISTING_DOMAIN" ]; then
95
- DOMAIN_NAME="$EXISTING_DOMAIN"
96
- echo "Using existing domain: $DOMAIN_NAME"
97
- fi
98
- fi
99
-
100
- # Only prompt for domain if not found (new installation or upgrade without existing domain)
101
- if [ -z "$DOMAIN_NAME" ]; then
102
- echo "Enter the domain name for your new EmailEngine installation."
103
- echo "(ex. example.com or test.example.com)"
104
- echo "Leave empty to autogenerate a domain name."
105
-
106
- while [ -z "$DOMAIN_NAME" ]
107
- do
108
- #echo -en "\n"
109
- read -p "Domain/Subdomain name: " DOMAIN_NAME
110
-
111
- if [ -z "$DOMAIN_NAME" ]
112
- then
113
- DOMAIN_NAME=$(curl --silent --fail -XPOST "https://api.nodemailer.com/autoassign" -H "Content-Type: application/json" -d '{
114
- "prefix": "engine",
115
- "version": "1",
116
- "requestor": "install"
117
- }')
118
- fi
119
- done
120
- fi
121
- fi
122
-
123
- echo "Using the domain name \"${DOMAIN_NAME}\" for this installation."
124
-
125
- # Validate domain format
126
- if ! echo "$DOMAIN_NAME" | grep -qE '^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$'; then
127
- echo "Error: Invalid domain name format: $DOMAIN_NAME"
128
- exit 1
129
- fi
130
-
131
- # Prepare Caddy
132
- apt install -y debian-keyring debian-archive-keyring apt-transport-https
133
-
134
- # Only add Caddy repository if not already configured
135
- if [ ! -f /usr/share/keyrings/caddy-stable-archive-keyring.gpg ]; then
136
- curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
137
- fi
138
-
139
- if [ ! -f /etc/apt/sources.list.d/caddy-stable.list ]; then
140
- curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
141
- fi
142
-
143
- # Install Redis and Caddy and required tools
144
- apt-get update
145
- apt-get install redis-server caddy wget openssl -q -y
146
-
147
- # Generate secure credentials
148
- REDIS_PASSWORD=$(openssl rand -hex 32)
149
- EENGINE_SECRET=$(openssl rand -hex 32)
150
-
151
- # Configure Redis for production use (skip if upgrading)
152
- if [ "$IS_UPGRADE" = false ]; then
153
- systemctl stop redis-server
154
-
155
- # Backup original Redis config
156
- cp /etc/redis/redis.conf /etc/redis/redis.conf.backup
157
-
158
- # Configure Redis with authentication and production settings
159
- cat >> /etc/redis/redis.conf <<EOF
160
-
161
- # EmailEngine production configuration
162
- requirepass $REDIS_PASSWORD
163
- maxmemory-policy noeviction
164
- save 900 1
165
- save 300 10
166
- save 60 10000
167
- stop-writes-on-bgsave-error yes
168
- rdbcompression yes
169
- rdbchecksum yes
170
- EOF
171
- else
172
- # For upgrades, read existing Redis password from service file
173
- REDIS_PASSWORD=$(systemctl show -p Environment emailengine | grep EENGINE_REDIS | sed 's/.*redis:\/\/:\([^@]*\)@.*/\1/')
174
- EENGINE_SECRET=$(systemctl show -p Environment emailengine | grep EENGINE_SECRET | cut -d'=' -f3 | cut -d'"' -f1)
175
- echo "Using existing Redis configuration"
176
- fi
177
-
178
- # Start Redis with new configuration
179
- systemctl start redis-server || { echo "Failed to start Redis server"; exit 1; }
180
- systemctl enable redis-server
181
-
182
- # Verify Redis connectivity
183
- redis-cli -a "$REDIS_PASSWORD" ping > /dev/null 2>&1 || { echo "Redis connection failed"; exit 1; }
184
- echo "Redis server started and verified successfully"
185
-
186
- # Just in case the installation does not start Caddy already
187
- systemctl enable caddy
188
- systemctl start caddy || { echo "Failed to start Caddy"; exit 1; }
189
-
190
- # Download and extract EmailEngine executable
191
- TMPDIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'ee')
192
- cd $TMPDIR
193
- if ! [ -x $(command -v wget) ]; then
194
- if ! [ -x $(command -v curl) ]; then
195
- echo "Can not download application"
196
- exit 1
197
- else
198
- curl "$APP_URL" -L -o emailengine.tar.gz
199
- fi
200
- else
201
- # use wget do download EmailEngine
202
- wget "$APP_URL"
203
- fi
204
-
205
- tar xzf emailengine.tar.gz
206
- rm -rf emailengine.tar.gz
207
- mv emailengine /opt
208
- chmod +x /opt/emailengine
209
-
210
- rm -rf $TMPDIR
211
-
212
- # Create dedicated user for EmailEngine
213
- if ! id -u emailengine >/dev/null 2>&1; then
214
- useradd -r -s /bin/false -d /opt/emailengine -m emailengine
215
- fi
216
-
217
- # Set proper ownership
218
- chown emailengine:emailengine /opt/emailengine
219
-
220
- # Create unit file for EmailEngine (skip if upgrading)
221
- if [ "$IS_UPGRADE" = false ]; then
222
- echo "[Unit]
223
- Description=EmailEngine
224
- After=redis-server
225
-
226
- [Service]
227
- # Configure environment variables
228
- Environment=\"EENGINE_REDIS=redis://:${REDIS_PASSWORD}@127.0.0.1:6379/8\"
229
- Environment=\"EENGINE_PORT=3000\"
230
- Environment=\"EENGINE_SECRET=${EENGINE_SECRET}\"
231
- Environment=\"EENGINE_API_PROXY=true\"
232
- # Caddy on this host is the only proxy allowed to set X-Forwarded-For
233
- Environment=\"EENGINE_API_PROXY_ADDRESSES=127.0.0.1,::1\"
234
- Environment=\"EENGINE_WORKERS=8\"
235
- Environment=\"EENGINE_LOG_LEVEL=info\"
236
- # Triggers install script specific upgrade instructions
237
- Environment=\"EENGINE_INSTALL_SCRIPT=true\"
238
-
239
- # Folder where EmailEngine executable is located
240
- WorkingDirectory=/opt
241
-
242
- # EmailEngine runs as dedicated user
243
- User=emailengine
244
- Group=emailengine
245
-
246
- # Run the EmailEngine executable
247
- ExecStart=/opt/emailengine
248
-
249
- Type=simple
250
- Restart=always
251
-
252
- SyslogIdentifier=emailengine
253
-
254
- [Install]
255
- WantedBy=multi-user.target" > /etc/systemd/system/emailengine.service
256
- fi
257
-
258
- systemctl daemon-reload
259
- systemctl enable emailengine
260
- systemctl restart emailengine || { echo "Failed to start EmailEngine service"; exit 1; }
261
-
262
- # Log installation details
263
- echo "$(date): EmailEngine ${VERSION:-latest} installed/upgraded for $DOMAIN_NAME" >> /var/log/emailengine-install.log
264
-
265
- # Check if domain exists in Caddyfile
266
- DOMAIN_EXISTS_IN_CADDY=false
267
- if [ -f /etc/caddy/Caddyfile ]; then
268
- if grep -q "^${DOMAIN_NAME} {" /etc/caddy/Caddyfile 2>/dev/null; then
269
- DOMAIN_EXISTS_IN_CADDY=true
270
- fi
271
- fi
272
-
273
- # Create or update Caddyfile only if needed
274
- if [ "$IS_UPGRADE" = false ] || [ ! -f /etc/caddy/Caddyfile ] || [ "$DOMAIN_EXISTS_IN_CADDY" = false ]; then
275
- if [ "$DOMAIN_EXISTS_IN_CADDY" = false ] && [ -f /etc/caddy/Caddyfile ]; then
276
- echo "Domain ${DOMAIN_NAME} not found in Caddy configuration, adding it..."
277
- # Backup existing Caddyfile
278
- cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.backup.$(date +%Y%m%d%H%M%S)
279
- fi
280
-
281
- echo "
282
- :80 {
283
- redir https://${DOMAIN_NAME}{uri}
284
- }
285
-
286
- ${DOMAIN_NAME} {
287
- reverse_proxy localhost:3000 {
288
- header_up X-Real-IP {remote_host}
289
- }
290
-
291
- header {
292
- Strict-Transport-Security \"max-age=31536000; includeSubDomains\"
293
- X-Frame-Options \"SAMEORIGIN\"
294
- X-Content-Type-Options \"nosniff\"
295
- X-XSS-Protection \"1; mode=block\"
296
- Referrer-Policy \"strict-origin-when-cross-origin\"
297
- }
298
-
299
- # Request size limit for email operations
300
- request_body {
301
- max_size 100MB
302
- }
303
- }" > /etc/caddy/Caddyfile
304
-
305
- # Validate Caddy configuration
306
- caddy validate --config /etc/caddy/Caddyfile || { echo "Invalid Caddy configuration"; exit 1; }
307
- echo "Caddy configuration validated successfully"
308
- else
309
- echo "Domain ${DOMAIN_NAME} already configured in Caddy, keeping existing configuration"
310
- fi
311
-
312
- # Create upgrade script
313
- cat > '/opt/upgrade-emailengine.sh' <<'EOL'
314
- #!/bin/bash
315
-
316
- set -e
317
-
318
- if [[ $EUID -ne 0 ]]; then
319
- echo "This script must be run as root" 1>&2
320
- exit 1
321
- fi
322
-
323
- OLD_VERSION=`/opt/emailengine -v | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | sed 's/^v//'`
324
-
325
- TMPDIR=$(mktemp -d -t ci-XXXXXXXXXX)
326
-
327
- cd "$TMPDIR"
328
- wget https://github.com/postalsys/emailengine/releases/latest/download/emailengine.tar.gz
329
- tar xzf emailengine.tar.gz
330
- rm -rf emailengine.tar.gz
331
-
332
- NEW_VERSION=`./emailengine -v | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | sed 's/^v//'`
333
-
334
- if [ "$OLD_VERSION" = "$NEW_VERSION" ]; then
335
- rm -rf "$TMPDIR"
336
- echo "Nothing to upgrade, already running $NEW_VERSION"
337
- else
338
- mv emailengine /opt
339
- rm -rf "$TMPDIR"
340
- chmod +x /opt/emailengine
341
- chown emailengine:emailengine /opt/emailengine
342
- systemctl restart emailengine
343
-
344
- echo "Upgraded EmailEngine"
345
- echo " - was: $OLD_VERSION"
346
- echo " - now: $NEW_VERSION"
347
- fi
348
- EOL
349
- chmod +x /opt/upgrade-emailengine.sh
350
-
351
-
352
- systemctl reload caddy || { echo "Failed to reload Caddy"; exit 1; }
353
-
354
- printf "Waiting for the web server to start up.."
355
- MAX_WAIT=60
356
- ELAPSED=0
357
- until $(curl --output /dev/null --silent --fail https://${DOMAIN_NAME}/) || [ $ELAPSED -ge $MAX_WAIT ]; do
358
- printf '.'
359
- sleep 2
360
- ELAPSED=$((ELAPSED + 2))
361
- done
362
- echo "."
363
-
364
- if [ $ELAPSED -ge $MAX_WAIT ]; then
365
- echo "Warning: Web server did not respond within $MAX_WAIT seconds"
366
- echo "Please check the service status manually"
367
- fi
368
-
369
- # Save credentials to a secure file (skip if upgrading)
370
- if [ "$IS_UPGRADE" = false ]; then
371
- cat > /root/emailengine-credentials.txt <<EOF
372
- ===========================================
373
- EmailEngine Installation Credentials
374
- ===========================================
375
-
376
- Domain: https://${DOMAIN_NAME}/
377
-
378
- Redis Password: ${REDIS_PASSWORD}
379
- Encryption Secret: ${EENGINE_SECRET}
380
-
381
- IMPORTANT: Save these credentials securely!
382
- They cannot be recovered if lost.
383
-
384
- Systemd service: emailengine
385
- Service user: emailengine
386
- Redis database: 8
387
-
388
- Commands:
389
- Status: systemctl status emailengine
390
- Logs: journalctl -u emailengine -f
391
- Restart: systemctl restart emailengine
392
- Upgrade: /opt/upgrade-emailengine.sh
393
-
394
- Monitoring:
395
- Redis memory: redis-cli -a '${REDIS_PASSWORD}' INFO memory
396
- Service health: curl http://localhost:3000/health
397
- ===========================================
398
- EOF
399
-
400
- chmod 600 /root/emailengine-credentials.txt
401
- fi
402
-
403
- echo ""
404
- echo "========================================="
405
- if [ "$IS_UPGRADE" = true ]; then
406
- echo "Upgrade/Version change complete!"
407
- else
408
- echo "Installation complete!"
409
- fi
410
- echo "========================================="
411
- echo ""
412
- echo "Access your EmailEngine installation at:"
413
- echo " https://${DOMAIN_NAME}/"
414
- echo ""
415
- if [ "$IS_UPGRADE" = false ]; then
416
- echo "IMPORTANT: Credentials have been saved to:"
417
- echo " /root/emailengine-credentials.txt"
418
- echo ""
419
- echo "This file contains your Redis password and encryption secret."
420
- echo "Store these credentials securely - they cannot be recovered!"
421
- fi
422
- echo ""
423
- echo "To upgrade EmailEngine in the future:"
424
- echo " /opt/upgrade-emailengine.sh"
425
- echo ""
426
- echo "To monitor Redis memory usage:"
427
- echo " redis-cli -a 'YOUR_REDIS_PASSWORD' INFO memory"
428
- echo ""