emailengine-app 2.89.0 → 2.90.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 (72) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +60 -0
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/oauth/gmail.js +39 -120
  38. package/lib/oauth/http-request.js +195 -0
  39. package/lib/oauth/mail-ru.js +24 -58
  40. package/lib/oauth/outlook.js +37 -137
  41. package/lib/oauth/pubsub/google.js +176 -117
  42. package/lib/oauth2-apps.js +440 -463
  43. package/lib/openapi/build-document.js +10 -10
  44. package/lib/read-env-value.js +1 -1
  45. package/lib/route-descriptors.js +78 -0
  46. package/lib/schemas.js +10 -1
  47. package/lib/sentry-integrations.js +299 -0
  48. package/lib/sentry.js +75 -27
  49. package/lib/sso-routes.js +249 -0
  50. package/lib/sso.js +29 -6
  51. package/lib/ui-routes/account-edit-form.js +198 -0
  52. package/lib/ui-routes/account-page.js +241 -0
  53. package/lib/ui-routes/account-routes.js +12 -318
  54. package/lib/ui-routes/auth-routes.js +10 -10
  55. package/lib/ui-view-context.js +328 -0
  56. package/lib/utils/public-suffix.js +22 -101
  57. package/lib/web-safe-html.js +20 -7
  58. package/lib/worker-metrics.js +82 -0
  59. package/list-generate.js +2 -5
  60. package/package.json +23 -19
  61. package/sbom.json +267 -908
  62. package/scripts/refresh-test-tokens.js +1 -1
  63. package/server.js +320 -676
  64. package/static/css/flyonui.css +1 -1
  65. package/static/css/src/app.tailwind.css +18 -0
  66. package/static/js/ee-client.js +2619 -645
  67. package/static/js/ui.js +12 -2
  68. package/static/licenses.html +219 -737
  69. package/translations/messages.pot +64 -53
  70. package/views/accounts/browse.hbs +19 -1
  71. package/workers/api.js +20 -451
  72. package/data/public_suffix_list.dat +0 -16698
package/.ncurc.js CHANGED
@@ -23,7 +23,7 @@ module.exports = {
23
23
  target: name =>
24
24
  ['pino', '@playwright/test'].includes(name)
25
25
  ? 'patch'
26
- : ['gettext-parser', 'marked', '@sentry/node-core', 'he', 'iconv-lite'].includes(name)
26
+ : ['gettext-parser', 'marked', 'he', 'iconv-lite', '@hapi/boom'].includes(name)
27
27
  ? 'minor'
28
28
  : 'latest'
29
29
  // pino - held on 10.3.x. 10.4.0 took PR #2294, which makes lib/caller.js prefer
@@ -44,22 +44,33 @@ module.exports = {
44
44
  // times out with "Received: undefined" while the page snapshot shows the button).
45
45
  // Same spec passes in 3.8 s on 1.63.0; nothing in the 1.64 release notes covers
46
46
  // it. Lift once a 1.64.x or later passes that spec unchanged.
47
- // gettext-parser - 8.x is ESM-only
47
+ // gettext-parser - 8.x and later are ESM-only (10.0.0 is type:module with no require condition). It is a
48
+ // devDependency only (gettext-extract.js and test/gettext-pot-order-test.js), so pkg is not
49
+ // the constraint: the unit tier runs under `npm run test:cjs` (require(esm) disabled), where
50
+ // an ESM-only gettext-parser fails to load.
48
51
  // marked - 16.x dropped the CommonJS build (ESM-only, needs require(esm)); 15.x is the last
49
52
  // require()-compatible line, verified in a yao/pkg node24 build.
50
53
  // Permanent: an ESM-only release cannot be bundled by pkg, whatever the Node floor.
51
54
  // iconv-lite - 1.0 (alpha since 2026-10) moves to ES modules, relying on require(esm). Held on 0.x;
52
55
  // libmime, imapflow and mailparser carry the same cap. The ES module move keeps it out of
53
56
  // the pkg bundle.
57
+ // @hapi/boom - 11.0.0-rc.0 (dist-tag next, 2026-08) is type:module with only an ESM export (boom PR #309,
58
+ // "convert module to ESM") and engines node>=22. Without this cap `npm run update` would move
59
+ // to it the day 11.0.0 reaches latest, and the pkg binary would fail while dev and tests pass on
60
+ // require(esm). The hapi org did the same to bourne, formula, pinpoint and tlds in 2026 and has
61
+ // ESM-only rcs of hoek 12 and topo 7, so a hapi 22 will likely follow: add every direct
62
+ // @hapi/* dependency here the day it publishes an ESM-only major. hapi 21 itself still depends
63
+ // on boom ^10, hoek ^11 and topo ^6.
54
64
  // he - 2.x is ESM-only (exports only src/he.mjs). 1.2.0 is the last CommonJS release. mailparser,
55
65
  // which reaches EmailEngine through the same require, rejects 2.x for the same reason.
56
66
  // Permanent for the same pkg reason as marked.
57
- // @sentry/node-core - held on the 10.x line for the reason @sentry/node (which it replaced, through its
58
- // `light` entry) was held there: @sentry/node 11.x depends on @sentry/bundler-plugins,
59
- // which pulls the 16 MB Sentry CLI (package `sentry`, licensed FSL-1.1-Apache-2.0, not an
60
- // OSI license) into the runtime tree and the pkg bundle. The node-core line is versioned in
61
- // step with @sentry/node, so lift this only once an 11.x of node-core exists and has been
62
- // checked against that.
67
+ //
68
+ // Sentry: EmailEngine builds its client from @sentry/core (lib/sentry.js, with its own context-lines, context and
69
+ // modules integrations in lib/sentry-integrations.js) and must not depend on @sentry/node or @sentry/node-core.
70
+ // @sentry/node 11.x depends on @sentry/bundler-plugins, which pulls the 16 MB Sentry CLI (package `sentry`,
71
+ // licensed FSL-1.1-Apache-2.0, not an OSI license) and the native oxc-parser into the runtime tree and the pkg
72
+ // bundle, and @sentry/node-core, the light SDK used until 2026-11, ended at 10.x. @sentry/core depends only on
73
+ // @sentry/conventions; check that it still does on every major.
63
74
  //
64
75
  // ical.js was capped at 1.x here as "2.x is ESM-only", which was never true: every 2.x ships a CommonJS
65
76
  // build behind exports.require. Moved to 2.x on 2026-09-28; it is also what resolves a DTSTART against
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.89.0"
2
+ ".": "2.90.0"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.90.0](https://github.com/postalsys/emailengine/compare/v2.89.0...v2.90.0) (2026-11-20)
4
+
5
+
6
+ ### Features
7
+
8
+ * write inline reply and forward headers in the language of the locale ([454a6dd](https://github.com/postalsys/emailengine/commit/454a6ddc23f9de95f326e8ba55e3e8e0cb67b9a0))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * anchor the AWS WorkMail MX pattern ([1cc357e](https://github.com/postalsys/emailengine/commit/1cc357e58f8678a60a4aeff5a9b5c773126646df))
14
+ * connect a Gmail account whose profile carries no history ID ([c7cb645](https://github.com/postalsys/emailengine/commit/c7cb64595c8f868a9c2ea4c6196a501a13f5803b))
15
+ * fetch listed Gmail messages ten at a time, not eleven ([ac2e0d3](https://github.com/postalsys/emailengine/commit/ac2e0d31447bf73b1c7a7ed0425bb7b9706b1f9c))
16
+ * give a reply or forward a text part when it has no text of its own ([86522b7](https://github.com/postalsys/emailengine/commit/86522b7a3c4547ad72fc8accc5f6266f6353e9d3))
17
+ * keep account counter names off Object.prototype ([35d62b0](https://github.com/postalsys/emailengine/commit/35d62b0ee10a3206ee128d941cb0b719f68cf8d0))
18
+ * keep an unsaved message in the message browser when its save question is dismissed ([aace267](https://github.com/postalsys/emailengine/commit/aace267ddd763b7647ce92b72b48b4a8bd7e285a))
19
+ * keep complaint recipients collected before the feedback report ([09b5e84](https://github.com/postalsys/emailengine/commit/09b5e848b51a8ebb24f2ca584f0466ddcfa0110c))
20
+ * leave an account field holding undefined out of the stored hash ([9e96857](https://github.com/postalsys/emailengine/commit/9e968579b165c7462f0c3fb547ed1fd0e011f03f))
21
+ * leave optional packages out of the Docker image ([6d00ea1](https://github.com/postalsys/emailengine/commit/6d00ea121364872da597bf07bda2f064ca83c1e1))
22
+ * link straight to a message in the admin message browser ([9d881a6](https://github.com/postalsys/emailengine/commit/9d881a6706aae3bc002eeb6295bfa932cd20f7ea))
23
+ * load .env with Node's own parser instead of dotenv ([23fd4ad](https://github.com/postalsys/emailengine/commit/23fd4adf0396690557de837b8a2e609f0285de1e))
24
+ * load the passkey library on the first passkey request ([2f4280b](https://github.com/postalsys/emailengine/commit/2f4280b4f09eb084ca1d81f6e6519b55a1a543a3))
25
+ * look up registrable domains through tldts ([942bd43](https://github.com/postalsys/emailengine/commit/942bd4368dc5c59ea99d8a880f518403df014e05))
26
+ * mark a forwarded message $Forwarded only, and even when it was answered ([c52084a](https://github.com/postalsys/emailengine/commit/c52084a86966661bca74f48a5c9cf447d8b7ca99))
27
+ * move the Prometheus metrics to @prometheus-io/client ([a2c6f63](https://github.com/postalsys/emailengine/commit/a2c6f63c75c2c3a12bcca62e29fbe932990b74d1))
28
+ * plain-text quotes, web-safe font and attachment file size ([779082e](https://github.com/postalsys/emailengine/commit/779082ee6735b475f26fdfcacc52af7a5028ef2a))
29
+ * quote a plain-text original in the HTML part of a reply or forward ([2f6a02a](https://github.com/postalsys/emailengine/commit/2f6a02a9f8074ac2070025f03cd2715da48bcd7f))
30
+ * raise the Outlook client secret flag when no secret is configured ([6667e8d](https://github.com/postalsys/emailengine/commit/6667e8dea9b42a836b32929606f1e5da29f4479a))
31
+ * refuse a missing API token with a 401 instead of a TypeError ([140d88d](https://github.com/postalsys/emailengine/commit/140d88de63c5e7243a46c535c9035072f4561088))
32
+ * register the OIDC sign-in route at boot, before discovery succeeds ([a81ee0b](https://github.com/postalsys/emailengine/commit/a81ee0bed1419941ae824718fd316104f5dcc637))
33
+ * report the file size of attachments ([79386b3](https://github.com/postalsys/emailengine/commit/79386b39355f3cb023dc5f591460fabb97e68f89))
34
+ * resolve @hapi/bell to the root joi 18 ([0b77d15](https://github.com/postalsys/emailengine/commit/0b77d154ee8471f8d665f917b9eec65634a861db))
35
+ * return the usual shape from the IMAP attachment list without a body structure ([caaaba9](https://github.com/postalsys/emailengine/commit/caaaba9f7d8c4f588239bc76a5e84f71b6175611))
36
+ * send error reports through @sentry/core 11 ([b6531e5](https://github.com/postalsys/emailengine/commit/b6531e52445a059a6f70b44b83887b28015f960d))
37
+ * stop an untouched account edit save from reconnecting IMAP ([65ee163](https://github.com/postalsys/emailengine/commit/65ee1639a91ed4ad7a4e57059b0227ddba4f70fa))
38
+ * stop re-downloading an API message that came back without content ([ba5e272](https://github.com/postalsys/emailengine/commit/ba5e2721db068abe5345ce3a49b7d67d3f3b99e7))
39
+ * stop storing account objects as '[object Object]' ([324c803](https://github.com/postalsys/emailengine/commit/324c8035c1343c0cf904b8feb40efd7dbd451643))
40
+ * treat an uppercase GET as a GET when placing an Outlook request payload ([7a55420](https://github.com/postalsys/emailengine/commit/7a55420c93c075048b061b8a98550fce8a32a4ac))
41
+ * update dependencies ([d116dbc](https://github.com/postalsys/emailengine/commit/d116dbc09112f170133c22608fd8b880eb78247d))
42
+ * update dependencies ([aa47701](https://github.com/postalsys/emailengine/commit/aa47701d5cd9dbe3a0b78effaf4499cab93d0548))
43
+ * update dependencies ([2bf0f1b](https://github.com/postalsys/emailengine/commit/2bf0f1b6542dac24e291db973de6f663159de52d))
44
+ * update dependencies ([a61a043](https://github.com/postalsys/emailengine/commit/a61a043b8d6b36c21abeebe3cc304b188fba6cd4))
45
+ * web-safe HTML of plain-text mail no longer fixes the font ([484c601](https://github.com/postalsys/emailengine/commit/484c6016c6ac10094dde44af3989fef4a4a8ef22))
46
+
3
47
  ## [2.89.0](https://github.com/postalsys/emailengine/compare/v2.88.0...v2.89.0) (2026-11-15)
4
48
 
5
49
 
package/Dockerfile CHANGED
@@ -33,7 +33,11 @@ WORKDIR /emailengine
33
33
  # the lockfile actually changes.
34
34
  COPY package.json package.json
35
35
  COPY package-lock.json package-lock.json
36
- RUN npm ci --omit=dev
36
+ # --omit=optional, as the binary build does: the only optional runtime packages are msgpackr-extract
37
+ # (a native addon with an install script that MSGPACKR_NATIVE_ACCELERATION_DISABLED below keeps
38
+ # unused anyway, plus its six platform prebuilds), handlebars' precompiler (uglify-js) and a
39
+ # types package. None of them is loaded at runtime.
40
+ RUN npm ci --omit=dev --omit=optional
37
41
 
38
42
  # Copy app folders
39
43
  COPY bin bin
@@ -6,7 +6,7 @@
6
6
 
7
7
  // Resolve `.env` and `config/` against the application root, in the same order as server.js
8
8
  process.chdir(require('path').join(__dirname, '..'));
9
- require('dotenv').config({ quiet: true });
9
+ require('../lib/load-env').loadEnvFile();
10
10
 
11
11
  const config = require('@zone-eu/wild-config');
12
12
  const { probeTarget, probe } = require('../lib/health-probe');
@@ -93,14 +93,6 @@ fetch_json() {
93
93
  fetch_json data/google-crawlers.json wget -q -O - https://developers.google.com/static/crawling/ipranges/special-crawlers.json
94
94
  node -e 'console.log("Google crawlers updated: "+require("./data/google-crawlers.json").creationTime);'
95
95
 
96
- # The Public Suffix List, read by lib/utils/public-suffix.js. Kept verbatim (it is MPL-2.0 and carries
97
- # its own licence header), and only accepted when both sections arrived whole: a truncated list would
98
- # not fail to parse, it would just quietly know fewer suffixes. Nor is a list older than the one
99
- # already here: the site's CDN has served a copy two days behind the one committed the same morning,
100
- # and the refresh replaced the newer list with it. Exit code 3 keeps the current copy without a warning
101
- fetch_checked data/public_suffix_list.dat 'const fs=require("fs");const t=fs.readFileSync(process.argv[1],"utf8");for(const m of ["===BEGIN ICANN DOMAINS===","===END ICANN DOMAINS===","===BEGIN PRIVATE DOMAINS===","===END PRIVATE DOMAINS==="])if(!t.includes(m))throw new Error("missing "+m);const v=x=>((x.match(/^\/\/ VERSION: (\S+)/m)||[])[1]||"");let old="";try{old=v(fs.readFileSync(process.argv[2],"utf8"))}catch(e){}if(old&&v(t)<old){console.error("Public Suffix List: the download ("+(v(t)||"no version")+") is older than the copy here ("+old+"), keeping it");process.exit(3)}' wget -q -O - https://publicsuffix.org/list/public_suffix_list.dat
102
- grep -m1 '^// VERSION:' data/public_suffix_list.dat || true
103
-
104
96
  # The SBOM shipped in the binary and served at /sbom.json, generated from the installed tree by npm
105
97
  # (SPDX 2.3). Runtime dependencies only: dev tooling never reaches an instance. It used to come
106
98
  # from GitHub's dependency graph (gh sbom), which only knows a lockfile once it has been pushed, so
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-11-13T15:46:09.000000",
2
+ "creationTime": "2026-11-19T15:46:09.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/encrypt.js CHANGED
@@ -1,9 +1,6 @@
1
1
  'use strict';
2
2
 
3
- if (!process.env.EE_ENV_LOADED) {
4
- require('dotenv').config({ quiet: true });
5
- process.env.EE_ENV_LOADED = 'true';
6
- }
3
+ require('./lib/load-env').loadEnvOnce();
7
4
 
8
5
  try {
9
6
  process.chdir(__dirname);
@@ -0,0 +1,396 @@
1
+ 'use strict';
2
+
3
+ // The account hash codec: how Account.serializeAccountData() stores a field in Redis and how
4
+ // Account.unserializeAccountData() reads it back, for every field that is not kept as the plain
5
+ // string it is stored as. Both look the field up here and fall back to the plain string.
6
+ //
7
+ // Every entry is called as (accountObject, key, accountData, result), decoders with skipDecrypt as
8
+ // a fifth argument, and writes into `result` itself, or writes nothing when the field stores or
9
+ // reads as nothing. Writing in place rather than returning a value keeps the output keys in the
10
+ // order of the input keys, which the webhookErrorFlag reset in encodeWebhooks() depends on. An
11
+ // encoder is never called for a field holding undefined: serializeAccountData() skips it.
12
+
13
+ const { encrypt, parseEncryptedData } = require('../encrypt');
14
+
15
+ // Subkeys of the connection objects that hold dates
16
+ const CONNECTION_DATE_KEYS = ['created', 'expires', 'generated'];
17
+
18
+ // Credentials inside a connection object, looked up in its `auth` first (imap, smtp) and then
19
+ // beside it (the OAuth2 tokens)
20
+ const CONNECTION_SECRET_KEYS = ['pass', 'accessToken', 'refreshToken'];
21
+
22
+ function isValidDateObject(value) {
23
+ return value && typeof value === 'object' && typeof value.toISOString === 'function' && value.toString() !== 'Invalid Date';
24
+ }
25
+
26
+ function isStringable(value) {
27
+ return typeof value !== 'undefined' && value !== null && typeof value.toString === 'function';
28
+ }
29
+
30
+ /**
31
+ * Parses a stored JSON value. A value that does not parse is logged and, like a stored `null`,
32
+ * reads as undefined: the field is then left out of the account.
33
+ */
34
+ function parseStoredJson(accountObject, key, stored, ownerAccount) {
35
+ let value;
36
+ try {
37
+ value = JSON.parse(stored);
38
+ } catch (err) {
39
+ accountObject.logUnserializeFailure('Failed to parse input from Redis', key, stored, ownerAccount, err);
40
+ return undefined;
41
+ }
42
+ return value === null ? undefined : value;
43
+ }
44
+
45
+ // Sets the parsed stored JSON value as the field, unless it is null or does not parse. Returns the
46
+ // value, so a decoder can go on to convert parts of it in place
47
+ function setStoredJson(accountObject, key, stored, accountData, result) {
48
+ const value = parseStoredJson(accountObject, key, stored, accountData.account);
49
+ if (value !== undefined) {
50
+ result[key] = value;
51
+ }
52
+ return value;
53
+ }
54
+
55
+ function logStringifyFailure(accountObject, key, err) {
56
+ accountObject.logger.error({ msg: 'Failed to stringify input for Redis', key, account: accountObject.account, err });
57
+ }
58
+
59
+ function decodeDate(accountObject, key, accountData, result) {
60
+ const stored = accountData[key];
61
+ if (!stored) {
62
+ return;
63
+ }
64
+ if (stored === 'null') {
65
+ result[key] = null;
66
+ return;
67
+ }
68
+ const date = new Date(stored);
69
+ if (date.toString() !== 'Invalid Date') {
70
+ result[key] = date;
71
+ }
72
+ }
73
+
74
+ function decodeBool(accountObject, key, accountData, result) {
75
+ const stored = accountData[key];
76
+ if (stored && stored !== 'null') {
77
+ result[key] = stored === 'true';
78
+ }
79
+ }
80
+
81
+ // '' is the cleared marker written by encodeClearable() - report it as unset
82
+ function decodeNonEmpty(accountObject, key, accountData, result) {
83
+ if (accountData[key]) {
84
+ result[key] = accountData[key];
85
+ }
86
+ }
87
+
88
+ function decodePath(accountObject, key, accountData, result) {
89
+ const stored = accountData[key];
90
+ if (!stored || !stored.length) {
91
+ return;
92
+ }
93
+ if (stored.length > 1 && (/^"|"$/.test(stored) || /^\[|\]$/.test(stored))) {
94
+ // seems like JSON array or string
95
+ setStoredJson(accountObject, key, stored, accountData, result);
96
+ } else {
97
+ // regular string
98
+ result[key] = stored;
99
+ }
100
+ }
101
+
102
+ function decodeEncrypted(accountObject, key, accountData, result, skipDecrypt) {
103
+ const value = skipDecrypt ? accountData[key] : accountObject.decryptAccountField(key, accountData[key], accountData.account);
104
+ if (typeof value !== 'undefined') {
105
+ result[key] = value;
106
+ }
107
+ }
108
+
109
+ function decodeCustomHeaders(accountObject, key, accountData, result, skipDecrypt) {
110
+ let stored = accountData[key];
111
+ if (skipDecrypt) {
112
+ if (accountObject.secret && parseEncryptedData(stored).format !== 'cleartext') {
113
+ // not read by any caller that skips decryption
114
+ return;
115
+ }
116
+ } else {
117
+ stored = accountObject.decryptAccountField(key, stored, accountData.account);
118
+ if (typeof stored === 'undefined') {
119
+ return;
120
+ }
121
+ }
122
+ setStoredJson(accountObject, key, stored, accountData, result);
123
+ }
124
+
125
+ function decodeJson(accountObject, key, accountData, result) {
126
+ setStoredJson(accountObject, key, accountData[key], accountData, result);
127
+ }
128
+
129
+ function decodeOutlookSubscription(accountObject, key, accountData, result) {
130
+ const value = setStoredJson(accountObject, key, accountData[key], accountData, result);
131
+ if (value === undefined) {
132
+ return;
133
+ }
134
+ if (value.expirationDateTime) {
135
+ let expirationDateTime = new Date(value.expirationDateTime);
136
+ if (expirationDateTime.toString() === 'Invalid Date') {
137
+ expirationDateTime = null;
138
+ }
139
+ value.expirationDateTime = expirationDateTime;
140
+ }
141
+ }
142
+
143
+ // Connection settings and stored states: date subkeys become Date objects, null subkeys are dropped
144
+ function decodeConnectionJson(accountObject, key, accountData, result) {
145
+ const value = setStoredJson(accountObject, key, accountData[key], accountData, result);
146
+ if (value === undefined) {
147
+ return;
148
+ }
149
+ for (const subKey of CONNECTION_DATE_KEYS) {
150
+ if (value[subKey]) {
151
+ const dateVal = /^[0-9]+$/.test(value[subKey]) ? Number(value[subKey]) : value[subKey];
152
+ const date = new Date(dateVal);
153
+ if (date.toString() !== 'Invalid Date') {
154
+ value[subKey] = date;
155
+ }
156
+ }
157
+ }
158
+ for (const subKey of Object.keys(value)) {
159
+ if (value[subKey] === null) {
160
+ delete value[subKey];
161
+ }
162
+ }
163
+ }
164
+
165
+ function decodeNumber(accountObject, key, accountData, result) {
166
+ result[key] = Number(accountData[key]) || 0;
167
+ }
168
+
169
+ // The fallback for a field with no decoder: the stored string as it is
170
+ function decodePlain(accountObject, key, accountData, result) {
171
+ result[key] = accountData[key];
172
+ }
173
+
174
+ const FIELD_DECODERS = new Map([
175
+ ['notifyFrom', decodeDate],
176
+ ['lastWatch', decodeDate],
177
+ ['copy', decodeBool],
178
+ ['logs', decodeBool],
179
+ ['expectedEmail', decodeNonEmpty],
180
+ ['path', decodePath],
181
+ ['webhooks', decodeEncrypted],
182
+ ['proxy', decodeEncrypted],
183
+ ['webhooksCustomHeaders', decodeCustomHeaders],
184
+ ['subconnections', decodeJson],
185
+ ['watchResponse', decodeJson],
186
+ ['watchFailure', decodeJson],
187
+ ['outlookSubscription', decodeOutlookSubscription],
188
+ ['imap', decodeConnectionJson],
189
+ ['smtp', decodeConnectionJson],
190
+ ['imapServerInfo', decodeConnectionJson],
191
+ ['smtpServerEhlo', decodeConnectionJson],
192
+ ['oauth2', decodeConnectionJson],
193
+ ['lastErrorState', decodeConnectionJson],
194
+ ['syncError', decodeConnectionJson],
195
+ ['smtpStatus', decodeConnectionJson],
196
+ ['webhookErrorFlag', decodeConnectionJson],
197
+ ['connections', decodeNumber],
198
+ ['listRegistry', decodeNumber],
199
+ ['runIndex', decodeNumber]
200
+ ]);
201
+
202
+ function encodeDate(accountObject, key, accountData, result) {
203
+ const value = accountData[key];
204
+ if (value === 'now') {
205
+ result[key] = new Date().toISOString();
206
+ } else if (isValidDateObject(value)) {
207
+ result[key] = value.toISOString();
208
+ } else if (typeof value === 'string') {
209
+ const date = new Date(value);
210
+ if (date.toString() !== 'Invalid Date') {
211
+ result[key] = date.toISOString();
212
+ }
213
+ } else if (value === null) {
214
+ result[key] = 'null';
215
+ }
216
+ }
217
+
218
+ function encodePath(accountObject, key, accountData, result) {
219
+ const value = accountData[key];
220
+ if (value === null || value === '*' || (Array.isArray(value) && (value.length === 0 || (value.length === 1 && value[0] === '*')))) {
221
+ result[key] = '';
222
+ return;
223
+ }
224
+ try {
225
+ result[key] = JSON.stringify(value);
226
+ } catch (err) {
227
+ logStringifyFailure(accountObject, key, err);
228
+ }
229
+ }
230
+
231
+ function encodeCustomHeaders(accountObject, key, accountData, result) {
232
+ try {
233
+ result[key] = accountObject.encryptAccountField(key, JSON.stringify(accountData[key]));
234
+ } catch (err) {
235
+ logStringifyFailure(accountObject, key, err);
236
+ }
237
+ }
238
+
239
+ function encodeProxy(accountObject, key, accountData, result) {
240
+ if (isStringable(accountData[key])) {
241
+ result[key] = accountObject.encryptAccountField(key, accountData[key].toString());
242
+ }
243
+ }
244
+
245
+ function encodeWebhooks(accountObject, key, accountData, result) {
246
+ if (!isStringable(accountData[key])) {
247
+ return;
248
+ }
249
+ const value = accountData[key].toString();
250
+ if (!value) {
251
+ // clear potential error flag
252
+ result.webhookErrorFlag = '{}';
253
+ }
254
+ result[key] = accountObject.encryptAccountField(key, value);
255
+ }
256
+
257
+ function encodeJson(accountObject, key, accountData, result) {
258
+ try {
259
+ result[key] = JSON.stringify(accountData[key]);
260
+ } catch (err) {
261
+ logStringifyFailure(accountObject, key, err);
262
+ }
263
+ }
264
+
265
+ // Stored state the sync clients write as JSON themselves. A string given here is that JSON already
266
+ // and is kept as it is; anything else is encoded, so it reads back as the object it was rather than
267
+ // as '[object Object]'
268
+ function encodeStoredJson(accountObject, key, accountData, result) {
269
+ if (typeof accountData[key] === 'string') {
270
+ result[key] = accountData[key];
271
+ return;
272
+ }
273
+ encodeJson(accountObject, key, accountData, result);
274
+ }
275
+
276
+ function encodeOutlookSubscription(accountObject, key, accountData, result) {
277
+ try {
278
+ const objValue = Object.assign({}, accountData[key]);
279
+
280
+ if (typeof objValue.expirationDateTime === 'number' || typeof objValue.expirationDateTime === 'string') {
281
+ objValue.expirationDateTime = new Date(objValue.expirationDateTime);
282
+ }
283
+
284
+ if (isValidDateObject(objValue.expirationDateTime)) {
285
+ objValue.expirationDateTime = objValue.expirationDateTime.toISOString();
286
+ } else if (objValue.expirationDateTime) {
287
+ objValue.expirationDateTime = null;
288
+ }
289
+
290
+ result[key] = JSON.stringify(objValue);
291
+ } catch (err) {
292
+ logStringifyFailure(accountObject, key, err);
293
+ }
294
+ }
295
+
296
+ // Encrypts the credentials of a connection object copy in place; a value that does not encrypt is
297
+ // logged under its own name and stored as it is
298
+ function encryptConnectionSecrets(accountObject, connectData) {
299
+ for (const field of CONNECTION_SECRET_KEYS) {
300
+ let holder;
301
+ if (field in connectData.auth) {
302
+ holder = connectData.auth;
303
+ } else if (field in connectData) {
304
+ holder = connectData;
305
+ } else {
306
+ continue;
307
+ }
308
+ try {
309
+ holder[field] = encrypt(holder[field], accountObject.secret);
310
+ } catch (err) {
311
+ accountObject.logger.error({ msg: 'Failed to encrypt value', key: field, account: accountObject.account, err });
312
+ }
313
+ }
314
+ }
315
+
316
+ function encodeConnectionJson(accountObject, key, accountData, result) {
317
+ try {
318
+ // make a deep copy for manipulation
319
+ const connectData = JSON.parse(JSON.stringify(accountData[key]));
320
+
321
+ // if possible encrypt passwords
322
+ if (accountObject.secret && connectData.auth) {
323
+ encryptConnectionSecrets(accountObject, connectData);
324
+ }
325
+
326
+ for (const subKey of CONNECTION_DATE_KEYS) {
327
+ const date = accountData[key][subKey];
328
+ if (date && typeof date === 'object' && date.toString() !== 'Invalid Date') {
329
+ connectData[subKey] = date.toISOString();
330
+ }
331
+ }
332
+
333
+ result[key] = JSON.stringify(connectData);
334
+ } catch (err) {
335
+ logStringifyFailure(accountObject, key, err);
336
+ }
337
+ }
338
+
339
+ function encodeBool(accountObject, key, accountData, result) {
340
+ if (typeof accountData[key] === 'boolean') {
341
+ result[key] = accountData[key].toString();
342
+ } else if (accountData[key] === null) {
343
+ result[key] = '';
344
+ }
345
+ }
346
+
347
+ // Clearable, so it cannot ride the plain string fallback: that drops nulls, and hmset only ever
348
+ // adds keys, which would leave an identity pin settable but never removable. Follows the same
349
+ // convention as `copy` - null serializes to the empty marker and decodeNonEmpty() treats it as
350
+ // unset - rather than adding a per-field delete to persistUpdate.
351
+ function encodeClearable(accountObject, key, accountData, result) {
352
+ if (typeof accountData[key] === 'string' || accountData[key] === null) {
353
+ result[key] = accountData[key] || '';
354
+ }
355
+ }
356
+
357
+ const FIELD_ENCODERS = new Map([
358
+ ['notifyFrom', encodeDate],
359
+ ['lastWatch', encodeDate],
360
+ ['path', encodePath],
361
+ ['webhooksCustomHeaders', encodeCustomHeaders],
362
+ ['proxy', encodeProxy],
363
+ ['subconnections', encodeJson],
364
+ ['watchResponse', encodeJson],
365
+ ['watchFailure', encodeJson],
366
+ ['outlookSubscription', encodeOutlookSubscription],
367
+ ['imap', encodeConnectionJson],
368
+ ['smtp', encodeConnectionJson],
369
+ ['oauth2', encodeConnectionJson],
370
+ ['imapServerInfo', encodeStoredJson],
371
+ ['smtpServerEhlo', encodeStoredJson],
372
+ ['lastErrorState', encodeStoredJson],
373
+ ['syncError', encodeStoredJson],
374
+ ['smtpStatus', encodeStoredJson],
375
+ ['webhookErrorFlag', encodeStoredJson],
376
+ ['webhooks', encodeWebhooks],
377
+ ['copy', encodeBool],
378
+ ['logs', encodeBool],
379
+ ['expectedEmail', encodeClearable]
380
+ ]);
381
+
382
+ // The plain string fallback for a field with no encoder: null and undefined are not stored, and
383
+ // neither is an object with no string form of its own, which would be stored as '[object Object]'
384
+ function encodePlain(accountObject, key, accountData, result) {
385
+ const value = accountData[key];
386
+ if (!isStringable(value)) {
387
+ return;
388
+ }
389
+ if (value.toString === Object.prototype.toString) {
390
+ logStringifyFailure(accountObject, key, new TypeError('An object has no plain string form'));
391
+ return;
392
+ }
393
+ result[key] = value.toString();
394
+ }
395
+
396
+ module.exports = { FIELD_DECODERS, FIELD_ENCODERS, decodePlain, encodePlain };