emailengine-app 2.81.2 → 2.82.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -145,9 +145,8 @@ function jsonForScript(value) {
145
145
  // halves the payload since the operation id is already the key.
146
146
  //
147
147
  // The lookup is keyed on the operation id alone, deliberately ignoring the tag in the old
148
- // hash - tags get renamed (the Chat endpoints now sit under "Deprecated endpoints (Document
149
- // Store)"), which would strand every link that named the old one. The tag table is only a
150
- // second chance for a link whose operation no longer exists but whose group still does.
148
+ // hash - tags get renamed, which would strand every link that named the old one. The tag table
149
+ // is only a second chance for a link whose operation no longer exists but whose group still does.
151
150
  let redirectMapJson;
152
151
 
153
152
  async function getRedirectView(request) {
@@ -65,6 +65,34 @@ function lookupRef(spec, ref) {
65
65
  return (spec.components && spec.components.schemas && spec.components.schemas[name]) || null;
66
66
  }
67
67
 
68
+ // A branch that only lists primitive values of one type, as lib/openapi/joi-schema.js
69
+ // withForeignValues() emits for an allowed value of another type than the schema's own
70
+ function isSentinelBranch(branch) {
71
+ return (
72
+ !!branch &&
73
+ typeof branch === 'object' &&
74
+ Object.keys(branch).length === 2 &&
75
+ ['boolean', 'number', 'string'].includes(branch.type) &&
76
+ Array.isArray(branch.enum) &&
77
+ branch.enum.length > 0
78
+ );
79
+ }
80
+
81
+ // Splits `anyOf: [schema, ...sentinel branches]` into the schema and the sentinel values, or
82
+ // returns null for any other shape (a real alternatives list stays a list of variants)
83
+ function sentinelFold(schema) {
84
+ if (!schema || typeof schema !== 'object' || !Array.isArray(schema.anyOf) || schema.anyOf.length < 2) {
85
+ return null;
86
+ }
87
+
88
+ const [main, ...rest] = schema.anyOf;
89
+ if (isSentinelBranch(main) || !rest.every(isSentinelBranch)) {
90
+ return null;
91
+ }
92
+
93
+ return { main, sentinels: rest.flatMap(branch => branch.enum) };
94
+ }
95
+
68
96
  // Follows a $ref chain to the underlying schema. `refStack` carries the refs already
69
97
  // visited on the current branch; revisiting one means the document is recursive, which
70
98
  // is reported rather than followed.
@@ -87,6 +115,28 @@ function resolve(spec, schema, refStack) {
87
115
  current = target;
88
116
  }
89
117
 
118
+ // The generator publishes `.allow(false)` beside an object or a string as
119
+ // `anyOf: [schema, {type: 'boolean', enum: [false]}]`, which is what a strict validator
120
+ // needs. A reader is better served by the schema itself with the sentinel on its own
121
+ // "also accepts" line, so the pair is folded back into the enum form enumInfo() splits.
122
+ const fold = sentinelFold(current);
123
+ if (fold) {
124
+ const inner = resolve(spec, fold.main, stack);
125
+ if (!inner.schema || typeof inner.schema !== 'object') {
126
+ return inner;
127
+ }
128
+
129
+ const merged = Object.assign({}, inner.schema);
130
+ for (const key of Object.keys(current)) {
131
+ if (key !== 'anyOf') {
132
+ merged[key] = current[key];
133
+ }
134
+ }
135
+ merged.enum = (Array.isArray(inner.schema.enum) ? inner.schema.enum : []).concat(fold.sentinels);
136
+
137
+ return { schema: merged, refStack: inner.refStack };
138
+ }
139
+
90
140
  return { schema: current, refStack: stack };
91
141
  }
92
142
 
@@ -147,9 +197,9 @@ function matchesType(type, value) {
147
197
  // Returns null when the schema is not an enum, so callers can assign both fields in one go.
148
198
  //
149
199
  // The enum is split by whether a value can be an instance of the schema's own type.
150
- // lib/openapi/joi-schema.js emits `.valid()` and `.allow()` into one `enum`, so a joi
151
- // `.allow(false)` lands there too - 35 schemas in the document carry `enum: [false]` beside
152
- // a `string`, `integer` or `object` type. Those are sentinels standing next to the type, not
200
+ // A joi `.allow(false)` beside a `string`, `integer` or `object` type reaches here in the enum:
201
+ // the document publishes it as a separate anyOf branch, which resolve() folds back into the
202
+ // enum for rendering. Those are sentinels standing next to the type, not
153
203
  // its value domain: `false` clears the block on an update payload and means "not available"
154
204
  // on a response. Rendered through the normal "Allowed" row they claimed the only value an
155
205
  // IMAP configuration object accepts is `false`. `alsoAccepts` gets its own line instead.
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ // Which routes an account-bound access token can reach although their path carries no {account}
4
+ // parameter.
5
+ //
6
+ // The api-token strategy checks a bound token's binding against `request.params.account`
7
+ // (workers/api.js), so a route whose path has no such parameter refuses the token with
8
+ // "Unauthorized account" unless it is named here. Three resolutions exist, and the strategy keeps the
9
+ // code for each - this table only says which route gets which:
10
+ //
11
+ // 'query' - the account arrives as a query argument and has to name the token's own account.
12
+ // Omitting it still refuses, so a bound credential cannot enumerate the instance.
13
+ // 'token' - the account is taken from the token rather than from the request, and the handler is
14
+ // held to it through `request.app.enforceAccount`.
15
+ // 'record' - the entity named in the path is checked for membership in the token's account.
16
+ //
17
+ // The MCP tool registry reads the same table to decide which tools are advertised to a bound
18
+ // credential (lib/mcp/tools.js). It used to answer that question from "the route takes an `account`
19
+ // argument", which is a different question: `POST /v1/account`, `POST /v1/authentication/form` and
20
+ // `POST /v1/blocklist/{listId}` all take one in the payload and are refused here, so three tools were
21
+ // offered to a credential whose every call died on the same bare 403, while the template routes that
22
+ // a bound token really can reach were hidden because they name no account at all. One table is what
23
+ // keeps the advertisement and the enforcement from drifting apart again.
24
+ const BOUND_ROUTES = new Map([
25
+ ['get:/v1/templates', 'query'],
26
+ ['get:/v1/tokens', 'query'],
27
+ ['post:/v1/templates/template', 'token'],
28
+ // Matched for every method: the strategy's own case carries no method switch
29
+ ['get:/v1/templates/template/{template}', 'record'],
30
+ ['put:/v1/templates/template/{template}', 'record'],
31
+ ['delete:/v1/templates/template/{template}', 'record']
32
+ ]);
33
+
34
+ /**
35
+ * How a bound token's binding is satisfied on one route, or null when the route has to carry the
36
+ * account in its path.
37
+ *
38
+ * @param {String} method - HTTP method, in any case
39
+ * @param {String} path - the Hapi route path, with its parameter placeholders
40
+ * @returns {String|null} 'query', 'token', 'record', or null
41
+ */
42
+ function boundRouteBinding(method, path) {
43
+ return BOUND_ROUTES.get(`${String(method).toLowerCase()}:${path}`) || null;
44
+ }
45
+
46
+ /**
47
+ * Whether an account-bound token can reach a route at all - either because the path names the
48
+ * account, or because the route is one of the exceptions above.
49
+ *
50
+ * @param {String} method - HTTP method, in any case
51
+ * @param {String} path - the Hapi route path
52
+ * @returns {Boolean}
53
+ */
54
+ function routeAdmitsBoundToken(method, path) {
55
+ return /\{account\}/.test(path) || !!boundRouteBinding(method, path);
56
+ }
57
+
58
+ module.exports = { BOUND_ROUTES, boundRouteBinding, routeAdmitsBoundToken };
@@ -2,7 +2,7 @@
2
2
 
3
3
  const crypto = require('crypto');
4
4
  const { redis } = require('../db');
5
- const { Account, accountExists, authFailureDisabledAt } = require('../account');
5
+ const { Account, accountExists, authFailureDisabledAt, isImapDisabled, isOperatorDisabled } = require('../account');
6
6
  const { formatGmailWatch } = require('../account/account-state');
7
7
  const getSecret = require('../get-secret');
8
8
  const { oauth2Apps, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
@@ -30,10 +30,11 @@ const {
30
30
  shortMailboxesSchema,
31
31
  ACCOUNT_DISPLAY_STATES,
32
32
  apiResponses,
33
- ENUM_DESCRIPTIONS
33
+ ENUM_DESCRIPTIONS,
34
+ apiBoolean
34
35
  } = require('../schemas');
35
36
 
36
- const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE } = require('../consts');
37
+ const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE, OUTLOOK_SYNC_MAX_LOOKBACK } = require('../consts');
37
38
  const BEHAVIOR = require('./behavior-notes');
38
39
  const { IMPACT } = require('./operation-impact');
39
40
  const { FIELD_USAGE } = require('../field-usage');
@@ -158,7 +159,6 @@ async function init(args) {
158
159
  const {
159
160
  server,
160
161
  call,
161
- documentsQueue,
162
162
  oauth2Schema: oauth2SchemaArg,
163
163
  imapSchema: imapSchemaArg,
164
164
  smtpSchema: smtpSchemaArg,
@@ -338,7 +338,7 @@ async function init(args) {
338
338
  logs: Joi.boolean().example(false).description('Store recent logs').default(false),
339
339
 
340
340
  notifyFrom: accountSchemas.notifyFrom.default('now'),
341
- syncFrom: accountSchemas.syncFrom.default(null),
341
+ syncFrom: accountSchemas.syncFrom,
342
342
 
343
343
  proxy: settingsSchema.proxyUrl,
344
344
  smtpEhloName: settingsSchema.smtpEhloName,
@@ -621,13 +621,13 @@ async function init(args) {
621
621
  }),
622
622
 
623
623
  payload: Joi.object({
624
- reconnect: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(false).description('Only reconnect if true')
624
+ reconnect: apiBoolean().default(false).description('Only reconnect if true')
625
625
  }).label('RequestReconnect')
626
626
  },
627
627
 
628
628
  response: {
629
629
  schema: Joi.object({
630
- reconnect: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(false).description('Reconnection status')
630
+ reconnect: apiBoolean().default(false).description('Reconnection status')
631
631
  }).label('RequestReconnectResponse'),
632
632
  failAction: 'log'
633
633
  }
@@ -664,7 +664,8 @@ async function init(args) {
664
664
  name: 'sync_account',
665
665
  title: 'Sync account now',
666
666
  description: "Ask the account's worker to run a sync now instead of waiting for the next scheduled one.",
667
- omit: ['sync'],
667
+ // `since` can announce weeks of mail again, an operator decision rather than an agent's
668
+ omit: ['sync', 'since'],
668
669
  force: { sync: true }
669
670
  },
670
671
  openapi: {
@@ -700,13 +701,22 @@ async function init(args) {
700
701
  }),
701
702
 
702
703
  payload: Joi.object({
703
- sync: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(false).description('Only sync if true')
704
+ sync: apiBoolean().default(false).description('Only sync if true'),
705
+ since: Joi.date()
706
+ .iso()
707
+ .max('now')
708
+ .custom((value, helpers) => (value.getTime() < Date.now() - OUTLOOK_SYNC_MAX_LOOKBACK ? helpers.error('date.lookback') : value))
709
+ .messages({ 'date.lookback': '{{#label}} must be within the last 30 days' })
710
+ .example('2026-10-02T13:00:00.000Z')
711
+ .description(
712
+ 'Outlook (MS Graph) accounts only, ignored for other account types. Look for messages received since this time that were never announced, instead of the usual recovery window of the last few hours. Messages announced before EmailEngine stopped remembering them (about six hours) are announced again with a new messageNew webhook. At most 30 days back.'
713
+ )
704
714
  }).label('RequestSync')
705
715
  },
706
716
 
707
717
  response: {
708
718
  schema: Joi.object({
709
- sync: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(false).description('Sync status')
719
+ sync: apiBoolean().default(false).description('Sync status')
710
720
  }).label('RequestSyncResponse'),
711
721
  failAction: 'log'
712
722
  }
@@ -722,7 +732,6 @@ async function init(args) {
722
732
  let accountObject = new Account({
723
733
  redis,
724
734
  account: request.params.account,
725
- documentsQueue,
726
735
  call,
727
736
  secret: await getSecret(),
728
737
  timeout: request.headers['x-ee-timeout']
@@ -784,9 +793,7 @@ async function init(args) {
784
793
  }),
785
794
 
786
795
  query: Joi.object({
787
- revoke: Joi.boolean()
788
- .truthy('Y', 'true', '1')
789
- .falsy('N', 'false', 0)
796
+ revoke: apiBoolean()
790
797
  .default(false)
791
798
  .description('Revoke the upstream OAuth2 grant at the provider before deleting the account')
792
799
  .meta({ usage: FIELD_USAGE.revokeGrant })
@@ -796,7 +803,7 @@ async function init(args) {
796
803
  response: {
797
804
  schema: Joi.object({
798
805
  account: accountIdSchema.required(),
799
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the account deleted')
806
+ deleted: apiBoolean().default(true).description('Was the account deleted')
800
807
  }).label('DeleteAccountResponse'),
801
808
  failAction: 'log'
802
809
  }
@@ -808,13 +815,12 @@ async function init(args) {
808
815
  method: 'PUT',
809
816
  path: '/v1/account/{account}/flush',
810
817
 
811
- async handler(request, h) {
818
+ async handler(request) {
812
819
  let accountObject = new Account({
813
820
  redis,
814
821
  account: request.params.account,
815
822
  call,
816
823
  secret: await getSecret(),
817
- esClient: await h.getESClient(request.logger),
818
824
  timeout: request.headers['x-ee-timeout']
819
825
  });
820
826
 
@@ -827,7 +833,7 @@ async function init(args) {
827
833
  options: {
828
834
  description: 'Request account flush',
829
835
  notes: [
830
- 'Deletes all email indexes from Redis and ElasticSearch and re-creates the index for that account. You can only run a single flush operation at a time, so you must wait until the previous flush has finished before initiating a new one.',
836
+ 'Deletes all email indexes from Redis and re-creates the index for that account. You can only run a single flush operation at a time, so you must wait until the previous flush has finished before initiating a new one.',
831
837
  BEHAVIOR.SCHEDULED_ON_WORKER
832
838
  ],
833
839
  tags: ['api', 'Account'],
@@ -875,7 +881,7 @@ async function init(args) {
875
881
  }),
876
882
 
877
883
  payload: Joi.object({
878
- flush: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(false).description('Only flush the account if true'),
884
+ flush: apiBoolean().default(false).description('Only flush the account if true'),
879
885
  notifyFrom: accountSchemas.notifyFrom.default('now'),
880
886
  imapIndexer: accountSchemas.imapIndexer,
881
887
  syncFrom: accountSchemas.syncFrom
@@ -884,7 +890,7 @@ async function init(args) {
884
890
 
885
891
  response: {
886
892
  schema: Joi.object({
887
- flush: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(false).description('Flush status')
893
+ flush: apiBoolean().default(false).description('Flush status')
888
894
  }).label('RequestFlushResponse'),
889
895
  failAction: 'log'
890
896
  }
@@ -1080,7 +1086,6 @@ async function init(args) {
1080
1086
  'copy',
1081
1087
  'logs',
1082
1088
  'notifyFrom',
1083
- 'syncFrom',
1084
1089
  'path',
1085
1090
  'subconnections',
1086
1091
  'webhooks',
@@ -1120,7 +1125,7 @@ async function init(args) {
1120
1125
  }
1121
1126
 
1122
1127
  // default null
1123
- for (let key of ['notifyFrom', 'syncFrom', 'lastError', 'smtpStatus']) {
1128
+ for (let key of ['notifyFrom', 'lastError', 'smtpStatus']) {
1124
1129
  result[key] = result[key] || null;
1125
1130
  }
1126
1131
 
@@ -1143,11 +1148,19 @@ async function init(args) {
1143
1148
  }
1144
1149
  } else if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedAccount) {
1145
1150
  result.type = 'delegated';
1146
- } else if (accountData.imap && !accountData.imap.disabled) {
1151
+ } else if (accountData.imap && !isOperatorDisabled(accountData)) {
1152
+ // A parked account is still an IMAP account, only switched off: imap.disabled is
1153
+ // set by the send-only switch AND by the authentication-failure safety net, so
1154
+ // reading it directly answered "sending", sendOnly true for an account whose mail
1155
+ // a client was about to stop reading. The accounts listing and the admin UI have
1156
+ // asked isOperatorDisabled() since the park shipped - send-only is a
1157
+ // configuration, a park is a fault.
1147
1158
  result.type = 'imap';
1148
1159
  } else {
1149
1160
  result.type = 'sending';
1150
- result.sendOnly = true;
1161
+ // The same answer the listing gives: an account with neither IMAP nor SMTP is a
1162
+ // broken configuration rather than a send-only one
1163
+ result.sendOnly = accountObject.isSendOnlyAccount(accountData);
1151
1164
  }
1152
1165
 
1153
1166
  if ((accountData.imap || (oauth2App && (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap'))) && !result.imapIndexer) {
@@ -1174,8 +1187,25 @@ async function init(args) {
1174
1187
  result.counters = accountData.counters;
1175
1188
  }
1176
1189
 
1177
- if (request.query.quota && !result.sendOnly) {
1178
- result.quota = await accountObject.getQuota();
1190
+ // The quota is the one field of this record that is read off the live connection, and
1191
+ // a connection is not something the stored record can predict: getQuota() loads the
1192
+ // account with requireValid, which refuses every state outside connected, connecting
1193
+ // and syncing, and the IMAP client then checks for a usable socket of its own. So an
1194
+ // account that is merely disconnected, backing off after a connect error, parked or
1195
+ // paused answered 503 for the WHOLE account rather than returning it without a quota,
1196
+ // and so did one carrying no IMAP, SMTP or OAuth2 configuration at all. An optional
1197
+ // field must not be able to fail the response that carries it, which is how the
1198
+ // sibling enrichments above are written too.
1199
+ //
1200
+ // The three skips are kept as a short-circuit: they cost nothing, and they keep a
1201
+ // request that could never answer from making a worker round trip and logging a
1202
+ // warning about it. They are not what makes this safe.
1203
+ if (request.query.quota && !result.sendOnly && result.type !== 'sending' && !isImapDisabled(accountData)) {
1204
+ try {
1205
+ result.quota = await accountObject.getQuota();
1206
+ } catch (err) {
1207
+ request.logger.warn({ msg: 'Failed to read account quota', account: request.params.account, err });
1208
+ }
1179
1209
  }
1180
1210
 
1181
1211
  return result;
@@ -1219,12 +1249,7 @@ async function init(args) {
1219
1249
  }),
1220
1250
 
1221
1251
  query: Joi.object({
1222
- quota: Joi.boolean()
1223
- .truthy('Y', 'true', '1')
1224
- .falsy('N', 'false', 0)
1225
- .default(false)
1226
- .description('If true, then include quota information in the response')
1227
- .label('AccountQuota')
1252
+ quota: apiBoolean().default(false).description('If true, then include quota information in the response').label('AccountQuota')
1228
1253
  })
1229
1254
  },
1230
1255
 
@@ -1583,7 +1608,6 @@ async function init(args) {
1583
1608
  name: request.payload.name,
1584
1609
  email: request.payload.email,
1585
1610
  expectedEmail: request.payload.expectedEmail,
1586
- syncFrom: request.payload.syncFrom,
1587
1611
  notifyFrom: request.payload.notifyFrom,
1588
1612
  subconnections: request.payload.subconnections,
1589
1613
  redirectUrl: request.payload.redirectUrl,
@@ -1697,21 +1721,21 @@ async function init(args) {
1697
1721
  delegated: Joi.boolean()
1698
1722
  .empty('')
1699
1723
  .truthy('Y', 'true', '1')
1700
- .falsy('N', 'false', 0)
1724
+ .falsy('N', 'false', '0', 0)
1701
1725
  .default(false)
1702
1726
  .description('If true, configures this account as a shared mailbox. Currently supported by MS365 OAuth2 accounts'),
1703
1727
 
1704
1728
  skipServerSettings: Joi.boolean()
1705
1729
  .empty('')
1706
1730
  .truthy('Y', 'true', '1')
1707
- .falsy('N', 'false', 0)
1731
+ .falsy('N', 'false', '0', 0)
1708
1732
  .default(true)
1709
1733
  .description(
1710
1734
  'If true, the mail server settings step is skipped whenever the IMAP and SMTP settings for the address can both be discovered and verified with the password the user enters. The step is still shown if discovery or verification does not fully succeed. Set to false to always ask the user for the server settings. Applies to the IMAP setup path only.'
1711
1735
  ),
1712
1736
 
1713
- syncFrom: accountSchemas.syncFrom,
1714
1737
  notifyFrom: accountSchemas.notifyFrom,
1738
+ syncFrom: accountSchemas.syncFrom,
1715
1739
 
1716
1740
  subconnections: accountSchemas.subconnections,
1717
1741
 
@@ -1778,7 +1802,11 @@ async function init(args) {
1778
1802
  name: 'get_account_logs',
1779
1803
  title: 'Get account connection log',
1780
1804
  description:
1781
- 'Read the stored connection log of an account: the raw IMAP or provider API trace, which names folders, message ids and subjects. Use it to find out why an account fails to connect or sync. Only kept while logging is enabled for the account or for the whole instance.'
1805
+ 'Read the stored connection log of an account: the raw IMAP or provider API trace, which names folders, message ids and subjects. Use it to find out why an account fails to connect or sync. Only kept while logging is enabled for the account or for the whole instance. A long log is cut to its most recent entries.',
1806
+ // One JSON entry per line, oldest first, so a log over the result cap has to keep
1807
+ // its END - the first 128KB of a connection log says nothing about why the
1808
+ // account is failing now
1809
+ tail: true
1782
1810
  },
1783
1811
  openapi: {
1784
1812
  'x-ee-behavior': [BEHAVIOR.ACCOUNT_LOG_SCOPE],
@@ -19,6 +19,7 @@
19
19
  // NO_LABEL_SET_ON_GMAIL lib/email-client/gmail-client.js, assertLabelSetSupported throw
20
20
  // GMAIL_DELETE_IS_TRASH lib/email-client/gmail-client.js, deleteMessage
21
21
  // UPLOAD_DRAFTS_ONLY_GRAPH lib/email-client/outlook-client.js, uploadMessage
22
+ // UPLOAD_IGNORES_FLAGS_GMAIL lib/email-client/gmail-client.js, uploadMessage payload
22
23
  // NO_QUOTA_ON_API_ACCOUNTS getQuota on both clients
23
24
  // ACCOUNT_LOG_SCOPE lib/email-client/base-client.js, getLogger; workers/imap.js, getAccountLogger
24
25
 
@@ -49,6 +50,9 @@ module.exports = {
49
50
 
50
51
  UPLOAD_DRAFTS_ONLY_GRAPH: 'For MS Graph accounts only drafts can be uploaded, and the draft flag cannot be changed afterwards.',
51
52
 
53
+ UPLOAD_IGNORES_FLAGS_GMAIL:
54
+ 'For Gmail API accounts the flags and internalDate fields are ignored. The message is inserted with the target label only, and its internal date is taken from the Date header of the message itself.',
55
+
52
56
  NO_LABEL_SET_ON_GMAIL:
53
57
  'For Gmail API accounts the entire label set cannot be replaced in one call. Add and remove labels individually instead of using the set operation.',
54
58
 
@@ -8,7 +8,7 @@ const getSecret = require('../get-secret');
8
8
  const { lists } = require('../lists');
9
9
  const { failAction } = require('../tools');
10
10
  const { handleError } = require('./route-helpers');
11
- const { accountIdSchema, blocklistListIdSchema, apiResponses } = require('../schemas');
11
+ const { accountIdSchema, blocklistListIdSchema, apiResponses, apiBoolean } = require('../schemas');
12
12
  const { IMPACT } = require('./operation-impact');
13
13
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
14
14
 
@@ -331,7 +331,7 @@ async function init(args) {
331
331
 
332
332
  response: {
333
333
  schema: Joi.object({
334
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the address removed from the list')
334
+ deleted: apiBoolean().default(true).description('Was the address removed from the list')
335
335
  }).label('DeleteBlocklistResponse'),
336
336
  failAction: 'log'
337
337
  }
@@ -3,7 +3,7 @@
3
3
  const { createBullBoard } = require('@bull-board/api');
4
4
  const { BullMQAdapter } = require('@bull-board/api/bullMQAdapter');
5
5
  const { HapiAdapter } = require('@bull-board/hapi');
6
- const { notifyQueue, submitQueue, documentsQueue } = require('../db');
6
+ const { notifyQueue, submitQueue } = require('../db');
7
7
  const { BULL_BOARD_BASE_PATH } = require('../consts');
8
8
 
9
9
  async function init(args) {
@@ -21,11 +21,6 @@ async function init(args) {
21
21
  queue: submitQueue,
22
22
  prefix: 'Submission Queue - ',
23
23
  description: 'This queue contains emails that are scheduled to be sent.'
24
- },
25
- {
26
- queue: documentsQueue,
27
- prefix: 'Document Queue - ',
28
- description: '(Deprecated) This queue was used for indexing email information in the Document Store'
29
24
  }
30
25
  ];
31
26
  let queueAdapters = queues.map(queue => {
@@ -1,13 +1,10 @@
1
1
  'use strict';
2
2
 
3
- const fs = require('fs');
4
- const { Export } = require('../export');
3
+ const { Export, openExportReadStream } = require('../export');
5
4
  const Boom = require('@hapi/boom');
6
5
  const Joi = require('joi');
7
6
  const { failAction } = require('../tools');
8
7
  const { accountIdSchema, exportRequestSchema, exportStatusSchema, exportListSchema, exportIdSchema, apiResponses } = require('../schemas');
9
- const getSecret = require('../get-secret');
10
- const { createDecryptStream } = require('../stream-encrypt');
11
8
  const { handleError } = require('./route-helpers');
12
9
  const BEHAVIOR = require('./behavior-notes');
13
10
  const { IMPACT } = require('./operation-impact');
@@ -144,27 +141,10 @@ async function init(args) {
144
141
  throw Boom.notFound('Export not found');
145
142
  }
146
143
 
147
- const fileReadStream = fs.createReadStream(fileInfo.filePath);
148
- let stream = fileReadStream;
149
-
150
- stream.on('error', err => {
144
+ const stream = await openExportReadStream(fileInfo, err => {
151
145
  request.logger.error({ msg: 'Export download stream error', exportId, err });
152
146
  });
153
147
 
154
- if (fileInfo.isEncrypted) {
155
- const secret = await getSecret();
156
- if (!secret) {
157
- fileReadStream.destroy();
158
- throw Boom.serverUnavailable('Encryption secret not available for decryption');
159
- }
160
- const decryptStream = await createDecryptStream(secret);
161
- decryptStream.on('error', err => {
162
- request.logger.error({ msg: 'Export decryption error', exportId, err });
163
- fileReadStream.destroy();
164
- });
165
- stream = fileReadStream.pipe(decryptStream);
166
- }
167
-
168
148
  return h
169
149
  .response(stream)
170
150
  .type('application/gzip')
@@ -6,7 +6,7 @@ const { Gateway } = require('../gateway');
6
6
  const getSecret = require('../get-secret');
7
7
  const { failAction } = require('../tools');
8
8
  const { handleError, maskSecrets, MASKED, MASK_NOTE } = require('./route-helpers');
9
- const { apiResponses } = require('../schemas');
9
+ const { apiResponses, apiBoolean, formBoolean } = require('../schemas');
10
10
  const { ENUM_DESCRIPTIONS } = require('../enum-descriptions');
11
11
  const { IMPACT } = require('./operation-impact');
12
12
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
@@ -229,9 +229,7 @@ async function init(args) {
229
229
  .description('Service port number')
230
230
  .label('Port'),
231
231
 
232
- secure: Joi.boolean()
233
- .truthy('Y', 'true', '1', 'on')
234
- .falsy('N', 'false', 0, '')
232
+ secure: formBoolean()
235
233
  .allow(null)
236
234
  .default(false)
237
235
  .example(true)
@@ -270,7 +268,7 @@ async function init(args) {
270
268
  name: 'create_gateway',
271
269
  title: 'Create SMTP gateway',
272
270
  description:
273
- 'Register an SMTP gateway, a relay server messages can be sent through. Needs an id, a name, the host and the port; a password can be written but never read back.'
271
+ 'Register an SMTP gateway, a relay server messages can be sent through. Needs an id (or null to have one generated), a name, the host and the port; a password can be written but never read back.'
274
272
  },
275
273
  openapi: {
276
274
  responses: apiResponses('Returns the registered gateway.', 400, 401, 403, 429, 500)
@@ -292,7 +290,15 @@ async function init(args) {
292
290
  failAction,
293
291
 
294
292
  payload: Joi.object({
295
- gateway: Joi.string().empty('').trim().max(256).default(null).example('sendgun').description('Gateway ID').label('Gateway ID').required(),
293
+ gateway: Joi.string()
294
+ .empty('')
295
+ .trim()
296
+ .max(256)
297
+ .allow(null)
298
+ .example('sendgun')
299
+ .description('Gateway ID. If set to `null`, a unique ID will be generated automatically')
300
+ .label('Gateway ID')
301
+ .required(),
296
302
 
297
303
  name: Joi.string().empty('').max(256).example('John Smith').description('Account Name').label('Gateway Name').required(),
298
304
 
@@ -316,9 +322,7 @@ async function init(args) {
316
322
  .label('Port')
317
323
  .required(),
318
324
 
319
- secure: Joi.boolean()
320
- .truthy('Y', 'true', '1', 'on')
321
- .falsy('N', 'false', 0, '')
325
+ secure: formBoolean()
322
326
  .default(false)
323
327
  .example(true)
324
328
  .description('Should connection use TLS. Usually true for port 465')
@@ -413,12 +417,7 @@ async function init(args) {
413
417
  .description('Service port number')
414
418
  .label('Port'),
415
419
 
416
- secure: Joi.boolean()
417
- .truthy('Y', 'true', '1', 'on')
418
- .falsy('N', 'false', 0, '')
419
- .example(true)
420
- .description('Should connection use TLS. Usually true for port 465')
421
- .label('GatewayUpdateTlsOptions')
420
+ secure: formBoolean().example(true).description('Should connection use TLS. Usually true for port 465').label('GatewayUpdateTlsOptions')
422
421
  }).label('UpdateGateway')
423
422
  },
424
423
 
@@ -487,7 +486,7 @@ async function init(args) {
487
486
  response: {
488
487
  schema: Joi.object({
489
488
  gateway: Joi.string().max(256).required().example('example').description('Gateway ID'),
490
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the gateway deleted')
489
+ deleted: apiBoolean().default(true).description('Was the gateway deleted')
491
490
  }).label('DeleteGatewayResponse'),
492
491
  failAction: 'log'
493
492
  }