emailengine-app 2.84.1 → 2.84.2

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 (93) hide show
  1. package/.dockerignore +6 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +28 -0
  4. package/Dockerfile +2 -2
  5. package/bin/emailengine.js +15 -0
  6. package/data/google-crawlers.json +1 -1
  7. package/docker-compose.yml +1 -1
  8. package/lib/account/own-account-key.js +42 -0
  9. package/lib/account-assignment.js +1 -33
  10. package/lib/account.js +32 -19
  11. package/lib/add-trackers.js +11 -4
  12. package/lib/api-routes/account-routes.js +67 -14
  13. package/lib/api-routes/gateway-routes.js +9 -3
  14. package/lib/api-routes/message-routes.js +7 -1
  15. package/lib/api-routes/mint-bounds.js +11 -0
  16. package/lib/api-routes/route-helpers.js +125 -3
  17. package/lib/api-routes/submit-routes.js +4 -2
  18. package/lib/auth-token.js +23 -10
  19. package/lib/bounce-detect.js +17 -5
  20. package/lib/consts.js +34 -0
  21. package/lib/create-imap-client.js +41 -2
  22. package/lib/email-client/base-client.js +20 -10
  23. package/lib/email-client/gmail-client.js +21 -7
  24. package/lib/email-client/imap/mailbox.js +10 -4
  25. package/lib/email-client/imap/response-metrics.js +75 -0
  26. package/lib/email-client/imap-client.js +5 -2
  27. package/lib/email-client/message-builder.js +7 -2
  28. package/lib/email-client/outlook/graph-api.js +17 -2
  29. package/lib/email-client/outlook-client.js +6 -3
  30. package/lib/email-client/smtp-pool-manager.js +6 -0
  31. package/lib/encrypt.js +9 -0
  32. package/lib/export.js +3 -1
  33. package/lib/get-raw-email.js +4 -2
  34. package/lib/imap-proxy-auth.js +14 -1
  35. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  36. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  37. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  38. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  39. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  40. package/lib/mcp/listen.js +10 -1
  41. package/lib/oauth/external-account-config.js +3 -1
  42. package/lib/oauth/gmail.js +21 -48
  43. package/lib/oauth/mail-ru.js +5 -38
  44. package/lib/oauth/outlook.js +26 -44
  45. package/lib/pbkdf2-phc.js +18 -1
  46. package/lib/privileged-settings.js +6 -3
  47. package/lib/redis-scan-delete.js +15 -1
  48. package/lib/schemas.js +78 -32
  49. package/lib/settings.js +13 -1
  50. package/lib/smtp-auth.js +23 -0
  51. package/lib/tools.js +245 -56
  52. package/lib/ui-routes/account-routes.js +16 -37
  53. package/lib/ui-routes/admin-config-routes.js +10 -38
  54. package/lib/ui-routes/admin-entities-routes.js +22 -24
  55. package/lib/ui-routes/auth-routes.js +47 -24
  56. package/lib/ui-routes/connection-security-form.js +74 -0
  57. package/lib/ui-routes/form-lists.js +46 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  59. package/lib/ui-routes/oauth-config-routes.js +9 -18
  60. package/lib/ui-routes/sign-in-helpers.js +59 -0
  61. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  62. package/lib/utils/map-concurrent.js +36 -0
  63. package/lib/utils/network.js +28 -0
  64. package/lib/utils/provider-id.js +27 -0
  65. package/lib/utils/require-tls.js +33 -0
  66. package/lib/web-safe-html.js +5 -6
  67. package/lib/webhook-penalty.js +75 -0
  68. package/lib/webhook-routing.js +22 -2
  69. package/package.json +21 -21
  70. package/sbom.json +1 -1
  71. package/server.js +25 -14
  72. package/static/js/ace/ace.js +1 -1
  73. package/static/js/ace/mode-handlebars.js +1 -1
  74. package/static/js/ace/mode-html.js +1 -1
  75. package/static/js/ace/mode-javascript.js +1 -1
  76. package/static/js/ace/mode-markdown.js +1 -1
  77. package/static/js/ace/worker-html.js +1 -1
  78. package/static/js/ace/worker-javascript.js +1 -1
  79. package/static/js/ace/worker-json.js +1 -1
  80. package/static/js/ee-client.js +5 -0
  81. package/static/licenses.html +23 -23
  82. package/translations/messages.pot +66 -66
  83. package/views/account/security.hbs +10 -0
  84. package/views/accounts/account.hbs +11 -11
  85. package/views/accounts/edit.hbs +6 -2
  86. package/views/partials/gateway_form.hbs +3 -1
  87. package/workers/api.js +43 -3
  88. package/workers/webhooks.js +39 -3
  89. package/config/test.toml +0 -46
  90. package/install.sh +0 -428
  91. package/setup-production.sh +0 -215
  92. package/systemd/emailengine.service +0 -97
  93. package/systemd/nginx-proxy.conf +0 -77
package/workers/api.js CHANGED
@@ -39,6 +39,7 @@ const {
39
39
  resolveOAuthErrorStatus,
40
40
  constantTimeEqual,
41
41
  verifyServiceSignature,
42
+ SIGNING_PURPOSE,
42
43
  claimFormNonce,
43
44
  releaseFormNonce,
44
45
  setAdminSession,
@@ -505,6 +506,10 @@ const init = async () => {
505
506
 
506
507
  // Base Hapi options shared by both the default and SO_REUSEPORT binding paths
507
508
  const serverOptions = {
509
+ // hapi's default prints every internal request error to stderr; the request error
510
+ // listener below logs them through pino instead
511
+ debug: false,
512
+
508
513
  state: {
509
514
  strictHeader: false
510
515
  },
@@ -843,6 +848,20 @@ const init = async () => {
843
848
 
844
849
  let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
845
850
  if (isValidSessionToken) {
851
+ // The credential was minted for a page inside the admin perimeter, so it is
852
+ // held to that perimeter too. The /v1 path it is presented on is not an admin
853
+ // path, so the request-level check above did not apply.
854
+ if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length && !matchIp(request.app.ip, ADMIN_ACCESS_ADDRESSES)) {
855
+ logger.warn({
856
+ msg: 'Session token presented from outside the admin address list',
857
+ account: request.params.account,
858
+ remoteAddress: request.app.ip,
859
+ method: request.route.method,
860
+ path: request.route.path
861
+ });
862
+ throw Boom.forbidden('Unauthorized address');
863
+ }
864
+
846
865
  // A session token is bound to the account whose page minted it (checked above,
847
866
  // against request.params.account), but it used to reach every api-tagged route
848
867
  // naming that account - it never met the permission model at all. It lives in
@@ -1507,6 +1526,27 @@ const init = async () => {
1507
1526
  // first request, not at registration time
1508
1527
  registerOpenApiRoute(server, openApiOptions);
1509
1528
 
1529
+ // An exception thrown by a handler, an extension or a response schema with failAction
1530
+ // 'error' is answered with a bare 500 and reported on the request's error channel. hapi's
1531
+ // own record of it was an unstructured line on stderr (switched off above), and the API
1532
+ // error path only logs what handlers pass to handleError(), not what escapes them
1533
+ server.events.on({ name: 'request', channels: 'error' }, (request, event, tags) => {
1534
+ if (tags.internal && !tags.implementation) {
1535
+ // a 5xx the code raised on purpose: the API error path (handleError) and the web
1536
+ // error page log those themselves, with the request context they have
1537
+ return;
1538
+ }
1539
+ logger.error({
1540
+ msg: 'Request failed with an internal error',
1541
+ component: 'api',
1542
+ method: request.method,
1543
+ path: request.path,
1544
+ route: request.route && request.route.path,
1545
+ tags: Object.keys(tags || {}),
1546
+ err: event.error
1547
+ });
1548
+ });
1549
+
1510
1550
  server.events.on('response', request => {
1511
1551
  const tags = request.route && request.route.settings && request.route.settings.tags;
1512
1552
  if (!tags || !tags.includes('api')) {
@@ -1725,7 +1765,7 @@ const init = async () => {
1725
1765
  path: '/redirect',
1726
1766
  async handler(request, h) {
1727
1767
  let data = Buffer.from(request.query.data, 'base64url').toString();
1728
- if (!(await verifyServiceSignature(data, request.query.sig))) {
1768
+ if (!(await verifyServiceSignature(data, request.query.sig, SIGNING_PURPOSE.TRACKING))) {
1729
1769
  let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1730
1770
  throw error;
1731
1771
  }
@@ -1795,7 +1835,7 @@ const init = async () => {
1795
1835
  path: '/open.gif',
1796
1836
  async handler(request, h) {
1797
1837
  let data = Buffer.from(request.query.data, 'base64url').toString();
1798
- if (!(await verifyServiceSignature(data, request.query.sig))) {
1838
+ if (!(await verifyServiceSignature(data, request.query.sig, SIGNING_PURPOSE.TRACKING))) {
1799
1839
  let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1800
1840
  throw error;
1801
1841
  }
@@ -1873,7 +1913,7 @@ const init = async () => {
1873
1913
 
1874
1914
  // A false result is a forged/bad signature (permanent -> benign); a THROWN error is a
1875
1915
  // transient failure reading the service secret and is intentionally left to surface as 5xx.
1876
- if (!(await verifyServiceSignature(raw, request.query.sig))) {
1916
+ if (!(await verifyServiceSignature(raw, request.query.sig, SIGNING_PURPOSE.UNSUBSCRIBE))) {
1877
1917
  return 'data validation failed';
1878
1918
  }
1879
1919
 
@@ -20,12 +20,13 @@ const { initSentry } = require('../lib/sentry');
20
20
  initSentry('webhooks');
21
21
 
22
22
  const { redis, queueConf, logBullErrors } = require('../lib/db');
23
- const { Worker, UnrecoverableError } = require('bullmq');
23
+ const { Worker, UnrecoverableError, DelayedError } = require('bullmq');
24
+ const { penaltyKey, penaltyFor } = require('../lib/webhook-penalty');
24
25
  const settings = require('../lib/settings');
25
26
  const { decryptField } = require('../lib/encrypt');
26
27
  const getSecret = require('../lib/get-secret');
27
28
 
28
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MESSAGE_NEW_NOTIFY } = require('../lib/consts');
29
+ const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MESSAGE_NEW_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('../lib/consts');
29
30
 
30
31
  const { fetch: fetchCmd } = require('undici');
31
32
 
@@ -202,7 +203,7 @@ parentPort.on('message', message => {
202
203
 
203
204
  const notifyWorker = new Worker(
204
205
  'notify',
205
- async job => {
206
+ async (job, token) => {
206
207
  // do not process active jobs, use it for debugging only
207
208
  //return new Promise((resolve, reject) => {});
208
209
  let accountKey = getAccountKey(job.data.account);
@@ -293,6 +294,30 @@ const notifyWorker = new Worker(
293
294
  return;
294
295
  }
295
296
 
297
+ // A target whose last attempt ran into the timeout is penalised for a short while, and a
298
+ // delivery to it waits out the penalty in the delayed set instead of costing the queue
299
+ // another full attempt timeout; see lib/webhook-penalty.js. The attempt count is not
300
+ // spent by the wait
301
+ const targetPenaltyKey = penaltyKey(webhooks);
302
+ if (targetPenaltyKey) {
303
+ let remaining = await redis.pttl(targetPenaltyKey);
304
+ if (remaining > 0) {
305
+ logger.debug({
306
+ msg: 'Webhook target is penalised, delaying delivery',
307
+ action: 'webhook',
308
+ queue: job.queue.name,
309
+ code: 'target_penalised',
310
+ job: job.id,
311
+ event: job.name,
312
+ account: job.data.account,
313
+ webhooks: redactUrlCredentials(webhooks),
314
+ delay: remaining
315
+ });
316
+ await job.moveToDelayed(Date.now() + remaining, token);
317
+ throw new DelayedError();
318
+ }
319
+ }
320
+
296
321
  // Only the header lists that travel to this target are loaded; lib/webhook-routing.js
297
322
  // holds the rule and the reasons
298
323
  let levels = headerLevels(target.source);
@@ -513,6 +538,17 @@ const notifyWorker = new Worker(
513
538
  // egress and redirect failures are thrown as UnrecoverableError below, so they are final as well
514
539
  let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
515
540
 
541
+ // A target that held the attempt until it timed out, or refused the connection, is
542
+ // penalised so the next deliveries to it do not each cost the same wait
543
+ let penalty = penaltyFor(err, WEBHOOK_TIMEOUT || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
544
+ if (penalty && targetPenaltyKey) {
545
+ try {
546
+ await redis.set(targetPenaltyKey, '1', 'PX', penalty);
547
+ } catch (penaltyErr) {
548
+ // a missed penalty costs the queue one more timeout, nothing else
549
+ }
550
+ }
551
+
516
552
  // BullMQ keeps only the message of a failure on the job. The code and the HTTP status
517
553
  // are what explain it, so they are recorded the way the submit worker records its own
518
554
  // 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 ""