emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -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,11 +7,25 @@
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'));
14
14
 
15
+ // lib/logger.js reads its configuration (EENGINE_LOG_LEVEL, EENGINE_LOG_REDACT_HEADERS) once, when
16
+ // it loads, and the first record this module writes is what loads it. So while resolveEnvFiles()
17
+ // runs, records are held here and written only after every file has been read: otherwise a file
18
+ // listed before EENGINE_LOG_LEVEL_FILE would build the logger at the default level.
19
+ let heldRecords = null;
20
+
21
+ function log(level, entry) {
22
+ if (heldRecords) {
23
+ heldRecords.push({ level, entry });
24
+ return;
25
+ }
26
+ getLogger()[level](entry);
27
+ }
28
+
15
29
  // The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
16
30
  // function. Those copies stripped a single trailing newline and nothing else, so for a file carrying
17
31
  // any other surrounding whitespace the value they produced is not the value this helper produces.
@@ -67,14 +81,14 @@ function readEnvValue(key) {
67
81
  // the operator needs to find it, and the value is what the warning exists to protect.
68
82
  const legacyValue = contents.replace(/\r?\n$/, '');
69
83
  if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
70
- getLogger().warn({
84
+ log('warn', {
71
85
  msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
72
86
  key,
73
87
  file
74
88
  });
75
89
  }
76
90
 
77
- getLogger().trace({ msg: 'Loaded environment value from file', key, file });
91
+ log('trace', { msg: 'Loaded environment value from file', key, file });
78
92
  return value;
79
93
  }
80
94
  }
@@ -97,10 +111,20 @@ function hasEnvValue(key) {
97
111
  * @throws {Error} code `EnvFileUnreadable` for the first file that can not be read
98
112
  */
99
113
  function resolveEnvFiles() {
100
- for (const name of Object.keys(process.env)) {
101
- const match = /^(EENGINE_[A-Z0-9_]+|REDIS_URL)_FILE$/.exec(name);
102
- if (match) {
103
- readEnvValue(match[1]);
114
+ heldRecords = [];
115
+ try {
116
+ for (const name of Object.keys(process.env)) {
117
+ const match = /^(EENGINE_[A-Z0-9_]+|REDIS_URL)_FILE$/.exec(name);
118
+ if (match) {
119
+ readEnvValue(match[1]);
120
+ }
121
+ }
122
+ } finally {
123
+ // Also when a file can not be read: the records of the files that were read still matter
124
+ const records = heldRecords;
125
+ heldRecords = null;
126
+ for (const { level, entry } of records) {
127
+ log(level, entry);
104
128
  }
105
129
  }
106
130
  }
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ // Dashboard warnings about the kind of Redis server EmailEngine is connected to, derived from INFO.
4
+ // Pure, so the decisions can be tested without a Redis in each configuration.
5
+ //
6
+ // Redis Cluster is refused outright: EmailEngine's queues and Lua scripts touch keys in different hash
7
+ // slots, which a cluster rejects with CROSSSLOT, and a cluster refuses SELECT for any database but 0.
8
+ // That also covers Amazon MemoryDB and ElastiCache with cluster mode or the durability option, which
9
+ // always run as a cluster.
10
+ //
11
+ // Amazon ElastiCache without cluster mode works, but a node that has no replica does not reload its
12
+ // snapshot when AWS replaces it: the new node starts empty and every account is gone until someone
13
+ // restores a backup by hand. A primary with a connected replica fails over instead and keeps its data,
14
+ // so only the replica-less setup is flagged. Multi-AZ failover itself is not visible in INFO.
15
+
16
+ /**
17
+ * Warning about a Redis Cluster backend
18
+ * @param {Object} redisInfo - Parsed INFO output
19
+ * @returns {Object|null} Warning entry, or null
20
+ */
21
+ function clusterWarning(redisInfo) {
22
+ if (!(Number(redisInfo.cluster_enabled) > 0)) {
23
+ return null;
24
+ }
25
+
26
+ return {
27
+ key: 'cluster',
28
+ color: 'danger',
29
+ title: 'Redis compatibility warning',
30
+ details: ['EmailEngine is incompatible with a Redis Cluster setup.', 'Please switch to a standard Redis primary instance.']
31
+ };
32
+ }
33
+
34
+ /**
35
+ * Warning about an Amazon ElastiCache primary that has no replica to fail over to
36
+ * @param {Object} redisInfo - Parsed INFO output
37
+ * @returns {Object|null} Warning entry, or null
38
+ */
39
+ function elastiCacheWarning(redisInfo) {
40
+ if (!/Amazon ElastiCache/i.test(redisInfo.os || '') || Number(redisInfo.cluster_enabled) > 0) {
41
+ // not ElastiCache, or a cluster, which clusterWarning() already refuses
42
+ return null;
43
+ }
44
+
45
+ if (redisInfo.role !== 'master' || Number(redisInfo.connected_slaves) > 0) {
46
+ return null;
47
+ }
48
+
49
+ return {
50
+ key: 'elasticache',
51
+ color: 'danger',
52
+ title: 'Amazon ElastiCache without a replica',
53
+ details: [
54
+ 'This ElastiCache node has no replica. When AWS replaces a node without one, the new node starts empty, and EmailEngine loses every account until a backup is restored by hand.',
55
+ 'Add at least one replica and enable Multi-AZ automatic failover, or switch to a standard Redis instance with persistence enabled.'
56
+ ]
57
+ };
58
+ }
59
+
60
+ /**
61
+ * All backend warnings for the dashboard, in display order
62
+ * @param {Object} redisInfo - Parsed INFO output
63
+ * @returns {Object[]} Warning entries
64
+ */
65
+ function redisBackendWarnings(redisInfo) {
66
+ redisInfo = redisInfo || {};
67
+ return [elastiCacheWarning(redisInfo), clusterWarning(redisInfo)].filter(Boolean);
68
+ }
69
+
70
+ module.exports = { redisBackendWarnings };
@@ -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
+ };