emailengine-app 2.88.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 (79) hide show
  1. package/.ncurc.js +36 -45
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -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 +77 -11
  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/node-version.js +99 -12
  38. package/lib/oauth/gmail.js +39 -120
  39. package/lib/oauth/http-request.js +195 -0
  40. package/lib/oauth/mail-ru.js +24 -58
  41. package/lib/oauth/outlook.js +37 -137
  42. package/lib/oauth/pubsub/google.js +176 -117
  43. package/lib/oauth2-apps.js +440 -463
  44. package/lib/openapi/build-document.js +10 -10
  45. package/lib/read-env-value.js +1 -1
  46. package/lib/route-descriptors.js +78 -0
  47. package/lib/schemas.js +10 -1
  48. package/lib/sentry-integrations.js +299 -0
  49. package/lib/sentry.js +75 -27
  50. package/lib/settings.js +4 -1
  51. package/lib/sso-routes.js +249 -0
  52. package/lib/sso.js +29 -6
  53. package/lib/tools.js +5 -4
  54. package/lib/ui-routes/account-edit-form.js +198 -0
  55. package/lib/ui-routes/account-page.js +241 -0
  56. package/lib/ui-routes/account-routes.js +12 -318
  57. package/lib/ui-routes/auth-routes.js +10 -10
  58. package/lib/ui-routes/dashboard-routes.js +4 -0
  59. package/lib/ui-view-context.js +328 -0
  60. package/lib/utils/public-suffix.js +22 -101
  61. package/lib/web-safe-html.js +70 -13
  62. package/lib/worker-metrics.js +82 -0
  63. package/list-generate.js +57 -23
  64. package/package.json +34 -33
  65. package/sbom.json +380 -1612
  66. package/scripts/refresh-test-tokens.js +1 -1
  67. package/server.js +351 -707
  68. package/static/css/flyonui.css +1 -1
  69. package/static/css/src/app.tailwind.css +18 -0
  70. package/static/js/ee-client.js +2619 -645
  71. package/static/js/ui.js +12 -2
  72. package/static/licenses.html +1055 -969
  73. package/translations/messages.pot +71 -60
  74. package/views/accounts/browse.hbs +19 -1
  75. package/views/dashboard.hbs +9 -0
  76. package/views/upgrade.hbs +25 -0
  77. package/workers/api.js +20 -451
  78. package/data/public_suffix_list.dat +0 -16597
  79. package/lib/net-tos-guard.js +0 -42
@@ -27,6 +27,7 @@ const Joi = require('joi');
27
27
 
28
28
  const { SchemaConverter, deleteEmptyProperties } = require('./joi-schema');
29
29
  const { pluginOptions } = require('../api-routes/route-metadata');
30
+ const { describeRoutes } = require('../route-descriptors');
30
31
  const { routeGrant } = require('../api-routes/permission-map');
31
32
 
32
33
  // Routes opt into the document by carrying this tag. It is an internal marker rather than a
@@ -85,15 +86,14 @@ class DocumentBuilder {
85
86
  }
86
87
 
87
88
  /**
88
- * Turns one Hapi route into an OpenAPI Operation Object.
89
+ * Turns one route into an OpenAPI Operation Object.
89
90
  *
90
- * @param {Object} route - an entry from server.table()
91
+ * @param {Object} route - a route descriptor (lib/route-descriptors.js)
91
92
  * @returns {Object} { path, method, operation }
92
93
  */
93
94
  buildOperation(route) {
94
- const settings = route.settings;
95
95
  const options = pluginOptions(route);
96
- const validate = settings.validate || {};
96
+ const validate = route.validate;
97
97
 
98
98
  // Non-JSON routes (raw message source, gzip export, event streams) declare the media type
99
99
  // their success response carries
@@ -102,15 +102,15 @@ class DocumentBuilder {
102
102
  // Assembled in one literal because the key order is what gets published, and a document that
103
103
  // reorders itself between builds is a diff for everyone tracking the hosted copy
104
104
  const operation = {
105
- summary: settings.description,
105
+ summary: route.description,
106
106
  operationId: operationId(route.method, route.path),
107
- description: Array.isArray(settings.notes) ? settings.notes.join(NOTES_SEPARATOR) : settings.notes,
107
+ description: Array.isArray(route.notes) ? route.notes.join(NOTES_SEPARATOR) : route.notes,
108
108
  parameters: [
109
109
  ...this.buildParameters(validate.headers, 'header', route.path),
110
110
  ...this.buildParameters(validate.params, 'path', route.path),
111
111
  ...this.buildParameters(validate.query, 'query', route.path)
112
112
  ],
113
- tags: (settings.tags || []).filter(tag => tag !== API_ROUTE_TAG)
113
+ tags: route.tags.filter(tag => tag !== API_ROUTE_TAG)
114
114
  };
115
115
 
116
116
  if (validate.payload) {
@@ -120,7 +120,7 @@ class DocumentBuilder {
120
120
  }
121
121
  }
122
122
 
123
- operation.responses = this.buildResponses(options.responses, settings.response && settings.response.schema, produces);
123
+ operation.responses = this.buildResponses(options.responses, route.responseSchema, produces);
124
124
 
125
125
  assignVendorExtensions(operation, options);
126
126
 
@@ -272,7 +272,7 @@ function sortRoutes(routes) {
272
272
  /**
273
273
  * Builds the OpenAPI document.
274
274
  *
275
- * @param {Array} routes - the Hapi route table (server.table()), unfiltered
275
+ * @param {Array} routes - the route table, unfiltered: hapi's server.table() or route descriptors
276
276
  * @param {Object} options - document-level options, see lib/swagger-options.js
277
277
  * @param {Object} options.info - the Info Object; title and version are required
278
278
  * @param {Array} [options.servers] - Server Objects; omitted from the document when not given
@@ -286,7 +286,7 @@ function buildOpenApiDocument(routes, options) {
286
286
  // Routes marked `plugins.openapi.deprecated` are compatibility aliases: they stay registered
287
287
  // (and keep the `api` tag, which also drives the CSRF skip list) but are left out of the
288
288
  // published document and the reference page, so nothing steers a new integration onto them
289
- for (const route of sortRoutes(routes.filter(route => (route.settings.tags || []).includes(API_ROUTE_TAG) && !pluginOptions(route).deprecated))) {
289
+ for (const route of sortRoutes(describeRoutes(routes).filter(route => route.tags.includes(API_ROUTE_TAG) && !pluginOptions(route).deprecated))) {
290
290
  const { path, method, operation } = builder.buildOperation(route);
291
291
 
292
292
  if (!paths[path]) {
@@ -7,7 +7,7 @@
7
7
  const Fs = require('fs');
8
8
 
9
9
  // Loaded on first use: only the <KEY>_FILE branch logs, and a short-lived process that reads plain
10
- // variables (the Docker health check) should not pay for pino and dotenv. lib/logger.js takes its
10
+ // variables (the Docker health check) should not pay for pino and the .env load. lib/logger.js takes its
11
11
  // constants from lib/logger-consts.js rather than lib/consts.js, so there is no cycle either way.
12
12
  let logger;
13
13
  const getLogger = () => (logger = logger || require('./logger'));
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ // A framework-neutral description of a registered route: everything the OpenAPI document
4
+ // (lib/openapi/), the MCP tool registry (lib/mcp/tools.js) and the permission map
5
+ // (lib/api-routes/permission-map.js) read from a route. They used to read hapi's route objects
6
+ // directly (`route.settings.validate`, `route.settings.plugins`, ...); now they read descriptors, so
7
+ // moving off hapi would mean writing another describeRoute() rather than touching those three.
8
+ // The request-time code (the api-token strategy, deprecations, DBSC, security headers) still reads
9
+ // the live hapi `request.route`; routePlugins() below is the one accessor it shares with them.
10
+ // See the hapi vs Fastify study of the 2026-11 dependency audit.
11
+ //
12
+ // The joi schemas are passed through as they are: they are what both the document and the tool
13
+ // schemas are generated from, and joi is not tied to the framework.
14
+
15
+ const DESCRIPTOR = Symbol('routeDescriptor');
16
+
17
+ /**
18
+ * @typedef {Object} RouteDescriptor
19
+ * @property {string} method - lowercase, as hapi reports it
20
+ * @property {string} path - in hapi's syntax ("/v1/account/{account}")
21
+ * @property {string} [description] - one-line summary
22
+ * @property {string|string[]} [notes] - longer description
23
+ * @property {string[]} tags
24
+ * @property {{headers?: Object, params?: Object, query?: Object, payload?: Object}} validate - joi schemas
25
+ * @property {Object} [responseSchema] - joi schema of the success response
26
+ * @property {Object} plugins - the route's `plugins` blocks (`openapi`, `mcp`, `securityHeaders`, ...)
27
+ */
28
+
29
+ /**
30
+ * Describes one route. A descriptor passed in is returned as it is.
31
+ *
32
+ * @param {Object} route - an entry of hapi's `server.table()`, a live `request.route`, or a descriptor
33
+ * @returns {RouteDescriptor}
34
+ */
35
+ function describeRoute(route) {
36
+ if (route && route[DESCRIPTOR]) {
37
+ return route;
38
+ }
39
+ const settings = (route && route.settings) || {};
40
+ return Object.freeze({
41
+ [DESCRIPTOR]: true,
42
+ method: route && route.method,
43
+ path: route && route.path,
44
+ description: settings.description,
45
+ notes: settings.notes,
46
+ tags: settings.tags || [],
47
+ validate: settings.validate || {},
48
+ responseSchema: settings.response ? settings.response.schema : undefined,
49
+ plugins: settings.plugins || {}
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Describes a whole route table.
55
+ *
56
+ * @param {Array} routes - hapi's `server.table()`
57
+ * @returns {RouteDescriptor[]}
58
+ */
59
+ function describeRoutes(routes) {
60
+ return routes.map(describeRoute);
61
+ }
62
+
63
+ /**
64
+ * The `plugins` blocks of a route, for either a descriptor or a hapi route. The api-token strategy
65
+ * reads them off the live `request.route` on every request, where building a descriptor would be
66
+ * an allocation per request for nothing.
67
+ *
68
+ * @param {Object} route
69
+ * @returns {Object|undefined}
70
+ */
71
+ function routePlugins(route) {
72
+ if (!route) {
73
+ return undefined;
74
+ }
75
+ return route[DESCRIPTOR] ? route.plugins : route.settings && route.settings.plugins;
76
+ }
77
+
78
+ module.exports = { describeRoute, describeRoutes, routePlugins };
package/lib/schemas.js CHANGED
@@ -1197,8 +1197,17 @@ const attachmentSchema = Joi.object({
1197
1197
  encodedSize: Joi.number()
1198
1198
  .integer()
1199
1199
  .example(48)
1200
- .description('Size of the attachment as stored in the email (base64 encoded). The actual decoded file size is approximately 75% of this value.')
1200
+ .description(
1201
+ 'Size of the attachment as the mail server reports it. For IMAP accounts this is the encoded size of the MIME part (for base64 about 4/3 of the file); the Gmail API and MS Graph report the file size. Use `size` for the file size.'
1202
+ )
1201
1203
  .label('AttachmentEncodedSize'),
1204
+ size: Joi.number()
1205
+ .integer()
1206
+ .example(36)
1207
+ .description(
1208
+ 'Size of the attachment file in bytes, as an estimate. For IMAP accounts it is computed from the encoded size, assuming base64 in 76 character lines, and is an upper bound for quoted-printable. MS Graph reports the size of the attachment item, which can be a little larger than the file'
1209
+ )
1210
+ .label('AttachmentSize'),
1202
1211
  embedded: Joi.boolean().example(true).description('Whether the attachment is embedded in the HTML content'),
1203
1212
  inline: Joi.boolean().example(true).description('Whether the attachment should be displayed inline rather than as a download'),
1204
1213
  encodedInMessage: Joi.boolean()
@@ -0,0 +1,299 @@
1
+ 'use strict';
2
+
3
+ // The three event integrations EmailEngine's error reports carry, written for @sentry/core, which
4
+ // ships none of them. They used to come from @sentry/node-core, whose 10.x line had no successor:
5
+ // Sentry 11 moved its Node.js SDK onto packages that pull the FSL-licensed Sentry CLI and a native
6
+ // parser into the tree (see .ncurc.js). Each produces the same event fields as the node-core one it
7
+ // replaces, so reports read the same in Sentry:
8
+ //
9
+ // ContextLines - pre_context / context_line / post_context around each stack frame
10
+ // Context - the app, os, device and culture contexts
11
+ // Modules - name and version of the packages the process has loaded
12
+ //
13
+ // Nothing here runs a command: the operating system is read from files (node-core ran sw_vers on
14
+ // macOS), see "Pure JavaScript only" in CLAUDE.md.
15
+
16
+ const fs = require('node:fs');
17
+ const os = require('node:os');
18
+ const pathlib = require('node:path');
19
+ const { defineIntegration, snipLine } = require('@sentry/core');
20
+ const { LRUCache } = require('./tools');
21
+
22
+ const CONTEXT_LINES = 7;
23
+ // Frames past these are minified or generated code, where a source line is noise
24
+ const MAX_LINENO = 10000;
25
+ const MAX_COLNO = 1000;
26
+ // A source file larger than this is not read for context
27
+ const MAX_SOURCE_SIZE = 2 * 1024 * 1024;
28
+ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
29
+ const MAX_CACHED_FILES = 10;
30
+
31
+ // filename -> lines (index 0 is line 1), or null when the file could not be read
32
+ const sourceCache = new LRUCache(MAX_CACHED_FILES);
33
+
34
+ async function readSourceLines(filename) {
35
+ if (sourceCache.has(filename)) {
36
+ return sourceCache.get(filename);
37
+ }
38
+ let lines = null;
39
+ try {
40
+ let stat = await fs.promises.stat(filename);
41
+ if (stat.isFile() && stat.size <= MAX_SOURCE_SIZE) {
42
+ lines = (await fs.promises.readFile(filename, 'utf8')).split(/\r?\n/);
43
+ }
44
+ } catch {
45
+ // unreadable, e.g. a frame from Node's own internals or a file removed since
46
+ }
47
+ sourceCache.set(filename, lines);
48
+ return lines;
49
+ }
50
+
51
+ function wantsContext(frame) {
52
+ let filename = frame && frame.filename;
53
+ return (
54
+ typeof filename === 'string' &&
55
+ typeof frame.lineno === 'number' &&
56
+ frame.lineno <= MAX_LINENO &&
57
+ !(frame.colno > MAX_COLNO) &&
58
+ !filename.startsWith('node:') &&
59
+ !filename.startsWith('data:') &&
60
+ !/\.min\.[cm]?js$/i.test(filename) &&
61
+ SOURCE_FILE.test(filename)
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Adds the source lines around a frame's line, the way node-core's ContextLines did: up to seven
67
+ * lines before and after, each shortened by snipLine(). A frame whose line is not in the file gets
68
+ * no context at all.
69
+ *
70
+ * @param {Object} frame Sentry stack frame
71
+ * @param {string[]} lines The file's lines
72
+ */
73
+ function addContextToFrame(frame, lines) {
74
+ let index = frame.lineno - 1;
75
+ if (index < 0 || index >= lines.length) {
76
+ return;
77
+ }
78
+ let start = Math.max(0, index - CONTEXT_LINES);
79
+ frame.pre_context = lines.slice(start, index).map(line => snipLine(line, 0));
80
+ frame.context_line = snipLine(lines[index], 0);
81
+ frame.post_context = lines.slice(index + 1, index + 1 + CONTEXT_LINES).map(line => snipLine(line, 0));
82
+ }
83
+
84
+ async function addSourceContext(event) {
85
+ let frames = [];
86
+ for (let exception of (event.exception && event.exception.values) || []) {
87
+ for (let frame of (exception.stacktrace && exception.stacktrace.frames) || []) {
88
+ if (frame.context_line === undefined && wantsContext(frame)) {
89
+ frames.push(frame);
90
+ }
91
+ }
92
+ }
93
+ let files = [...new Set(frames.map(frame => frame.filename))];
94
+ let sources = new Map(await Promise.all(files.map(async filename => [filename, await readSourceLines(filename)])));
95
+ for (let frame of frames) {
96
+ let lines = sources.get(frame.filename);
97
+ if (lines) {
98
+ addContextToFrame(frame, lines);
99
+ }
100
+ }
101
+ return event;
102
+ }
103
+
104
+ const contextLinesIntegration = defineIntegration(() => ({
105
+ name: 'ContextLines',
106
+ processEvent: event => addSourceContext(event)
107
+ }));
108
+
109
+ // Darwin kernel major -> macOS major, used only when SystemVersion.plist cannot be read
110
+ function macosFromKernel(release) {
111
+ let major = Number(String(release).split('.')[0]);
112
+ return major >= 25 ? String(major + 1) : major >= 20 ? String(major - 9) : `10.${major - 4}`;
113
+ }
114
+
115
+ function plistValue(plist, key) {
116
+ let match = plist.match(new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`));
117
+ return match ? match[1] : undefined;
118
+ }
119
+
120
+ function osReleaseValue(content, key) {
121
+ let match = content.match(new RegExp(`^${key}=(.*)$`, 'm'));
122
+ return match ? match[1].trim().replace(/^(["'])(.*)\1$/, '$2') : undefined;
123
+ }
124
+
125
+ /**
126
+ * The `os` context: name, version, kernel_version and (macOS) build.
127
+ *
128
+ * @param {Object} [env] Injected by the tests
129
+ * @returns {Promise<Object>}
130
+ */
131
+ async function getOsContext(env = { platform: process.platform, readFile: fs.promises.readFile, os }) {
132
+ let kernel = env.os.release();
133
+ switch (env.platform) {
134
+ case 'darwin': {
135
+ let context = { kernel_version: kernel, name: 'macOS', version: macosFromKernel(kernel) };
136
+ try {
137
+ let plist = await env.readFile('/System/Library/CoreServices/SystemVersion.plist', 'utf8');
138
+ context.name = plistValue(plist, 'ProductName') || context.name;
139
+ context.version = plistValue(plist, 'ProductVersion') || context.version;
140
+ let build = plistValue(plist, 'ProductBuildVersion');
141
+ if (build) {
142
+ context.build = build;
143
+ }
144
+ } catch {
145
+ // keep what the kernel version says
146
+ }
147
+ return context;
148
+ }
149
+ case 'linux': {
150
+ let context = { kernel_version: kernel, name: 'Linux' };
151
+ try {
152
+ let content = await env.readFile('/etc/os-release', 'utf8');
153
+ context.name = osReleaseValue(content, 'NAME') || context.name;
154
+ let version = osReleaseValue(content, 'VERSION_ID');
155
+ if (version) {
156
+ context.version = version;
157
+ }
158
+ } catch {
159
+ // a container without the file
160
+ }
161
+ return context;
162
+ }
163
+ case 'win32':
164
+ return { name: 'Windows', version: kernel, kernel_version: env.os.version() };
165
+ default:
166
+ return { name: env.platform, version: kernel };
167
+ }
168
+ }
169
+
170
+ function getAppContext() {
171
+ let context = {
172
+ app_start_time: new Date(Date.now() - process.uptime() * 1000).toISOString(),
173
+ app_memory: process.memoryUsage().rss
174
+ };
175
+ if (typeof process.availableMemory === 'function') {
176
+ context.free_memory = process.availableMemory();
177
+ }
178
+ return context;
179
+ }
180
+
181
+ function getDeviceContext() {
182
+ let context = {};
183
+ try {
184
+ context.boot_time = new Date(Date.now() - os.uptime() * 1000).toISOString();
185
+ } catch {
186
+ // not available on every platform
187
+ }
188
+ context.arch = os.arch();
189
+ context.memory_size = os.totalmem();
190
+ context.free_memory = os.freemem();
191
+ let cpus = os.cpus();
192
+ if (cpus && cpus.length) {
193
+ context.processor_count = cpus.length;
194
+ context.cpu_description = cpus[0].model;
195
+ context.processor_frequency = cpus[0].speed;
196
+ }
197
+ return context;
198
+ }
199
+
200
+ function getCultureContext() {
201
+ try {
202
+ let { locale, timeZone } = Intl.DateTimeFormat().resolvedOptions();
203
+ return { locale, timezone: timeZone };
204
+ } catch {
205
+ return undefined;
206
+ }
207
+ }
208
+
209
+ const nodeContextIntegration = defineIntegration(() => {
210
+ // what does not change while the process runs is read once
211
+ let osContext = getOsContext();
212
+ let cultureContext = getCultureContext();
213
+
214
+ return {
215
+ name: 'Context',
216
+ async processEvent(event) {
217
+ let contexts = event.contexts || {};
218
+ event.contexts = {
219
+ ...contexts,
220
+ app: { ...getAppContext(), ...contexts.app },
221
+ os: { ...(await osContext), ...contexts.os },
222
+ device: { ...getDeviceContext(), ...contexts.device },
223
+ ...(cultureContext ? { culture: { ...cultureContext, ...contexts.culture } } : {})
224
+ };
225
+ return event;
226
+ }
227
+ };
228
+ });
229
+
230
+ // The package a loaded file belongs to: the directory right below its last node_modules segment
231
+ // (two levels for a scoped package)
232
+ function packageDirOf(filename) {
233
+ let parts = filename.split(/[\\/]/);
234
+ let index = parts.lastIndexOf('node_modules');
235
+ if (index < 0 || index + 1 >= parts.length - 1) {
236
+ return null;
237
+ }
238
+ let depth = parts[index + 1].startsWith('@') ? 2 : 1;
239
+ return parts.slice(0, index + 1 + depth).join(pathlib.sep);
240
+ }
241
+
242
+ /**
243
+ * Name and version of every package something in the process has loaded, read from the
244
+ * package.json files next to the entries of require.cache, plus the application's own
245
+ * dependency list.
246
+ *
247
+ * @param {string[]} [loaded] Loaded file names, injected by the tests
248
+ * @returns {Object} { [name]: version }
249
+ */
250
+ function collectModules(loaded = Object.keys(require.cache)) {
251
+ let modules = {};
252
+ try {
253
+ let app = require('../package.json');
254
+ Object.assign(modules, app.dependencies);
255
+ } catch {
256
+ // not expected, the package file ships with every build
257
+ }
258
+ let seen = new Set();
259
+ for (let filename of loaded) {
260
+ let dir = packageDirOf(filename);
261
+ if (!dir || seen.has(dir)) {
262
+ continue;
263
+ }
264
+ seen.add(dir);
265
+ try {
266
+ let info = JSON.parse(fs.readFileSync(pathlib.join(dir, 'package.json'), 'utf8'));
267
+ if (info.name && info.version) {
268
+ modules[info.name] = info.version;
269
+ }
270
+ } catch {
271
+ // a directory without a readable package.json
272
+ }
273
+ }
274
+ return modules;
275
+ }
276
+
277
+ const modulesIntegration = defineIntegration(() => {
278
+ let modules;
279
+ return {
280
+ name: 'Modules',
281
+ processEvent(event) {
282
+ // collected on the first event, when the process has loaded what it is going to load
283
+ modules = modules || collectModules();
284
+ event.modules = { ...event.modules, ...modules };
285
+ return event;
286
+ }
287
+ };
288
+ });
289
+
290
+ module.exports = {
291
+ contextLinesIntegration,
292
+ nodeContextIntegration,
293
+ modulesIntegration,
294
+ // exported for the tests
295
+ addContextToFrame,
296
+ getOsContext,
297
+ collectModules,
298
+ packageDirOf
299
+ };
package/lib/sentry.js CHANGED
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const crypto = require('crypto');
4
+ const os = require('os');
5
+ const pathlib = require('path');
4
6
  const packageData = require('../package.json');
5
7
  const logger = require('./logger');
6
8
  const { readEnvValue, httpAgent } = require('./tools');
@@ -30,7 +32,7 @@ const SENTRY_RELEASE = `${packageData.name}@${packageData.version}`;
30
32
  // settings change applies to the next event without a restart. Only the two headers Sentry's
31
33
  // rate limiting reads are handed back.
32
34
  function makeTransport(options) {
33
- const { createTransport } = require('@sentry/node-core/light');
35
+ const { createTransport } = require('@sentry/core');
34
36
 
35
37
  return createTransport(options, async request => {
36
38
  let res = await fetchCmd(options.url, {
@@ -53,39 +55,85 @@ function makeTransport(options) {
53
55
  });
54
56
  }
55
57
 
56
- function startSentry(dsn) {
57
- // require lazily, the SDK loads several hundred modules in every worker thread,
58
- // so only pay that cost when error tracking is actually enabled. The light entry of
59
- // @sentry/node-core is the SDK without the OpenTelemetry setup and the automatic
60
- // instrumentation @sentry/node layers on top - both switched off below anyway - which
61
- // keeps that closure out of the tree and the binary.
62
- if (!Sentry) {
63
- Sentry = require('@sentry/node-core/light');
64
- }
58
+ // The module name Sentry groups a frame under: the path below the last node_modules with dots for
59
+ // slashes, or below the application directory, then the file name without its extension
60
+ // ("@hapi.hapi.lib:server", "lib:tools"). The same rule @sentry/node-core applied.
61
+ function createGetModuleFromFilename(basePath = pathlib.join(__dirname, '..')) {
62
+ const toPosix = value => value.replace(/\\/g, '/');
63
+ const base = toPosix(basePath);
64
+ return filename => {
65
+ if (!filename) {
66
+ return undefined;
67
+ }
68
+ let { dir, name, ext } = pathlib.posix.parse(toPosix(filename));
69
+ let file = decodeURIComponent(['.js', '.mjs', '.cjs'].includes(ext) ? name : name + ext);
70
+ let index = dir.lastIndexOf('/node_modules');
71
+ if (index > -1) {
72
+ return `${dir.slice(index + 14).replace(/\//g, '.')}:${file}`;
73
+ }
74
+ if (dir.startsWith(base)) {
75
+ let moduleName = dir.slice(base.length + 1).replace(/\//g, '.');
76
+ return moduleName ? `${moduleName}:${file}` : file;
77
+ }
78
+ return file;
79
+ };
80
+ }
81
+
82
+ /**
83
+ * The client options EmailEngine starts Sentry with.
84
+ *
85
+ * @param {string} dsn
86
+ * @param {Object} [overrides] Replaces any option, e.g. the transport in the tests
87
+ * @returns {Object}
88
+ */
89
+ function sentryOptions(dsn, overrides) {
90
+ const { createStackParser, eventFiltersIntegration, functionToStringIntegration, linkedErrorsIntegration } = require('@sentry/core');
91
+ const { nodeStackLineParser } = require('@sentry/core/server');
92
+ const { contextLinesIntegration, nodeContextIntegration, modulesIntegration } = require('./sentry-integrations');
65
93
 
66
- Sentry.init({
94
+ return {
67
95
  dsn,
68
96
  release: SENTRY_RELEASE,
97
+ environment: readEnvValue('SENTRY_ENVIRONMENT') || 'production',
69
98
  transport: makeTransport,
70
- // Error capture only: skip the OpenTelemetry setup and the default
71
- // integrations that patch http/fetch/console on hot paths. Sentry's own
72
- // uncaughtException/unhandledRejection integrations are left out on
73
- // purpose - they do not run in worker threads and do not guarantee a
74
- // process exit, so lib/logger.js owns reporting and exiting instead.
75
- skipOpenTelemetrySetup: true,
76
- defaultIntegrations: false,
99
+ stackParser: createStackParser(nodeStackLineParser(createGetModuleFromFilename())),
100
+ platform: 'node',
101
+ runtime: { name: 'node', version: process.version },
102
+ serverName: readEnvValue('SENTRY_NAME') || os.hostname(),
103
+ // Error capture only: no tracing ('static' also keeps ServerRuntimeClient from adding its
104
+ // span streaming integration), and none of the integrations that patch http/fetch/console
105
+ // on hot paths. Sentry's own uncaughtException/unhandledRejection handling is left out on
106
+ // purpose - it does not run in worker threads and does not guarantee a process exit, so
107
+ // lib/logger.js owns reporting and exiting instead.
108
+ traceLifecycle: 'static',
77
109
  integrations: [
78
- Sentry.eventFiltersIntegration(),
79
- Sentry.functionToStringIntegration(),
80
- Sentry.linkedErrorsIntegration(),
81
- Sentry.contextLinesIntegration(),
82
- Sentry.nodeContextIntegration(),
83
- Sentry.modulesIntegration()
110
+ eventFiltersIntegration(),
111
+ functionToStringIntegration(),
112
+ linkedErrorsIntegration(),
113
+ contextLinesIntegration(),
114
+ nodeContextIntegration(),
115
+ modulesIntegration()
84
116
  ],
85
117
  initialScope: {
86
118
  tags: { worker: workerName }
87
- }
88
- });
119
+ },
120
+ ...overrides
121
+ };
122
+ }
123
+
124
+ function startSentry(dsn, overrides) {
125
+ // require lazily, the SDK is a few hundred modules in every worker thread, so only pay that
126
+ // cost when error tracking is actually enabled. EmailEngine builds its client from
127
+ // @sentry/core directly: @sentry/node-core, the light Node.js SDK it used before, has no 11.x,
128
+ // and @sentry/node 11 pulls the FSL-licensed Sentry CLI into the tree (see .ncurc.js).
129
+ if (!Sentry) {
130
+ Sentry = require('@sentry/core');
131
+ }
132
+
133
+ const { ServerRuntimeClient } = require('@sentry/core/server');
134
+ const options = sentryOptions(dsn, overrides);
135
+ Sentry.applySdkMetadata(options, 'node', ['core']);
136
+ Sentry.initAndBind(ServerRuntimeClient, options);
89
137
 
90
138
  logger.notifyError = (err, opts) => {
91
139
  let captureContext = {};
@@ -203,4 +251,4 @@ function initSentry(worker) {
203
251
  setImmediate(checkSettings);
204
252
  }
205
253
 
206
- module.exports = { initSentry, makeTransport, licenseTag, SENTRY_RELEASE };
254
+ module.exports = { initSentry, makeTransport, licenseTag, SENTRY_RELEASE, startSentry, createGetModuleFromFilename };
package/lib/settings.js CHANGED
@@ -462,7 +462,10 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
462
462
 
463
463
  let multi = redis.multi().hset(`${REDIS_PREFIX}settings`, 'license', licenseFile);
464
464
  if (!keepState) {
465
- multi = multi.hdel(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp');
465
+ // A different key starts clean, and is checked online soon rather than when the last
466
+ // check of the key it replaces said: subcheck was stamped by that key's checks, and
467
+ // left in place it would hold off the first check of the new one by up to a day
468
+ multi = multi.hdel(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp', 'subcheck');
466
469
  }
467
470
  await multi
468
471
  .hset(